content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import logging
def get_gp_kwargs(gp_config):
"""Extract keyword argument parameters for the Gaussian process layer."""
covmat_momentum = gp_config.get('covmat_momentum', 0.999)
# Extracts model parameter.
logging.info('gp_config.covmat_momentum = %s', covmat_momentum)
covmat_momentum = None if covmat_momen... | 4909d8b5231bbae20ae17e1cdc1ae17b0ad6714f | 22,302 |
def canon(raw_attr_name: str) -> str:
"""
Canonicalize input attribute name for indy proofs and credential offers.
Args:
raw_attr_name: raw attribute name
Returns:
canonicalized attribute name
"""
if raw_attr_name: # do not dereference None, and "" is already canonical
... | 71858810bc3a65864f4df3c8a2d9c714c12b3692 | 22,305 |
def TOC_schmoker1979(rho_b, A=157.0, B=58.1):
"""
Schmoker (1979) method of TOC caluculation from bulk density to estimate
TOC in devonian shales.
bulk density units: g/cc
"""
TOC = (A / rho_b) - B
return TOC | 530e86cbd3ba1629549c0d5fcc6b0263397d3fa2 | 22,308 |
def get_dtype(table,name):
""" get the dtype of a field in a table (recarray)
given its name
"""
return table.dtype.fields[name][0].descr[0][1] | 6d63ab0f80b955124ccc94363a860c345c1f92b5 | 22,311 |
def internal(fn):
"""
Decorator which does not affect functionality but it is used as marker
which tells that this object is not interesting for users and it is only used internally
"""
return fn | fa9a31962a4f45f7794ec42fc4f2507c52c4535a | 22,312 |
import click
def _cb_shape(ctx, param, value):
"""
Click callback to validate `--shape`.
Returns
-------
tuple
(height, width)
"""
for v in value:
if not v >= 1:
raise click.BadParameter('values must be >= 1')
return value | 5d978379ab21239dec12340347266cab7f0d14f2 | 22,313 |
from typing import Set
def get_subclasses(cls) -> Set:
"""Returns the subclasses of the specified class, recursively."""
return set(cls.__subclasses__()).union(
[s for c in cls.__subclasses__() for s in get_subclasses(c)]) | 2247d1e0ae33904d2019591cd939702fdf4cc26a | 22,319 |
def safe_module_name(n):
"""Returns a module name which should not conflict with any other symbol."""
if n:
return "_mod_" + n.replace(".", "_")
return n | 2c12f48a97a983f69fa39b3b94eb642157d212bf | 22,320 |
def staff_check(user):
"""A method that checks if a user is a memeber of staff and returns true.
It is used by the @user_passes_test() decorator to lock away views that should
only be accessed by staff memebers.
Returns:
Bool: The boolean indicating if a user is a staff memeber or not.
""... | e5832ceb205c31c9d6ff3bdacfaf5c7f6135c024 | 22,323 |
def compute_source_marker(line, column, expression, size):
"""Computes source marker location string.
>>> def test(l, c, e, s):
... s, marker = compute_source_marker(l, c, e, s)
... out = s + '\\n' + marker
...
... # Replace dot with middle-dot to work around doctest ellipsis
..... | dcfd8bc74a83f3b2c7431a2a97c16c58c1b84742 | 22,325 |
def _get_value_for_key(lines, key):
"""Given list of |lines| with colon separated key value pairs,
return the value of |key|."""
for line in lines:
parts = line.split(':')
if parts[0].strip() == key:
return parts[1].strip()
return None | e08bad43f5b095632ef217a4ef7c8a6344d5d32f | 22,326 |
from typing import Optional
def prompt_yes_no(question: str, default: Optional[bool] = None) -> bool:
"""
Prompts the user a yes/no question and returns their choice.
"""
if default is True:
prompt = "[Y/n]"
elif default is False:
prompt = "[y/N]"
else:
prompt = "[y/n]... | d66ac36e51795f5b63fd0ddf482ae9e1529bc02a | 22,333 |
def first(iterable, condition=lambda x: True):
"""Return the first item in the `iterable` that satisfies the `condition`.
If the condition is not given, returns the first item of the iterable.
Raises `StopIteration` if no item satisfying the condition is found.
Parameters
----------
iterable ... | b031650e39a1acf5185a6760622c2197e34b21e1 | 22,334 |
def get_persistence(simplexTree, max_dimension):
"""Calculate the persistent homology of the abstract simplicial complex,
filtering by positive values and dimensions.
:param simplexTree: a simplcial complex, as returned by `build_local_complex`
:type simplexTree: simplexTree
:param max_dimension: ma... | 2b55afcc0503f55b8f08903c1164898abc675308 | 22,336 |
def find_modules(nn_module, type):
"""
Find and return modules of the input `type`
"""
return [module for module in nn_module.modules() if isinstance(module, type)] | d580e570843b7504ab91291fc3a173480c63f376 | 22,337 |
def how_many_can_list(num_market_listings: int, number_to_sell: int, num_in_inventory: int) -> int:
"""
How many items I can actually list on market to have number_to_sell on sale
:param num_market_listings: Number of own listing on market.
:param number_to_sell: Max number on sale
:param num_in_inv... | 29a9844448ebd68710920b83378025ad9ffd74a3 | 22,338 |
def predict_xlogvar_from_epslogvar(*, eps_logvar, logsnr):
"""Scale Var[eps] by (1+exp(-logsnr)) / (1+exp(logsnr)) = exp(-logsnr)."""
return eps_logvar - logsnr | 9f6e6e6d49ff2d6f7622d59439961a298d262693 | 22,343 |
import math
def dcg_trec(r, k=None):
"""The `trec_eval` version of DCG
:param r: results
:param k: cut-off
:return: sum rel_i / log(i + 2)
"""
result = sum([rel / math.log(rank + 2, 2) for rank, rel in enumerate(r[:k])])
return result | 5223776ddfe0a42eaf826cb72f69d1c91ec2f094 | 22,344 |
def qubo_to_ising(Q, offset=0.0):
"""Convert a QUBO problem to an Ising problem.
Map a quadratic unconstrained binary optimization (QUBO) problem :math:`x' Q x`
defined over binary variables (0 or 1 values), where the linear term is contained along
the diagonal of Q, to an Ising model defined on spin... | d2df1b581612ab7f93aaf762915d62583a9df148 | 22,359 |
def find_indices(lst, element):
""" Returns the indices for all occurrences of 'element' in 'lst'.
Args:
lst (list): List to search.
element: Element to find.
Returns:
list: List of indices or values
"""
result = []
offset = -1
while True:
try:
... | 59df6c2dd7a4c8fd43895210503f7ae03d83618b | 22,360 |
def get_paths(cursor):
"""Get the currently watched paths."""
sql = "select path from games"
cursor.execute(sql)
paths = [row[0] for row in cursor.fetchall()]
return paths | 1e3cd541970583bfc452b46bf9c5e635bf5555f4 | 22,363 |
import math
def angle(pos_x, pos_y):
""" Angle in degrees of 2D point """
angle_rad = math.atan(abs(pos_y/pos_x))
angle_degree = math.degrees(angle_rad)
return angle_degree | 9d3b83c3bcb2415af50f5bad7268dd9a72542530 | 22,366 |
def _split_storage_url(storage_object_url):
""" Returns a list containing the bucket id and the object id. """
return storage_object_url.split("/")[2:] | 8506d5071c3061cd73fc0e8ece09279ef39c377a | 22,367 |
def encipher(message: str, cipher_map: dict) -> str:
"""
Enciphers a message given a cipher map.
:param message: Message to encipher
:param cipher_map: Cipher map
:return: enciphered string
>>> encipher('Hello World!!', create_cipher_map('Goodbye!!'))
'CYJJM VMQJB!!'
"""
return "".jo... | 57053d93841dcc3982e18664a1a3ef6d85766788 | 22,370 |
def get_struct_instance_field_type(obj, field_name):
"""
:param obj: A ctypes struct instance
:param field_name: A name of a field in the struct
:return: The declared type of the field
"""
for field in obj._fields_:
current_field_name = field[0]
if current_field_name == field_n... | 255e088d9f36db652d0cbb4f1c21846b35a9d748 | 22,371 |
def capitalize_words(words):
"""Capitalize the words of an input string."""
capitalized = []
for word in words.split(' '):
capitalized.append(word.lower().capitalize())
return ' '.join(capitalized) | bd1e65c82e3abef987825354211c3ab09f12a46a | 22,373 |
def is_gzipped(text):
"""Check that we have gzipped content"""
return text[:2] == b"\x1f\x8b" | 01c1fef598661cc1a1ad8a707b4d5e439dcc8d79 | 22,374 |
def parse_slice_idx_to_str(slice_idx):
"""
Parse the slice index to a three digit string for saving and reading the
2D .npy files generated by io.preprocess.Preprocessor.
Naming convention: {type of slice}_{case}_{slice_idx}
* adding 0s to slice_idx until it reaches 3 digits,
* so sortin... | 2cc1fd4a0e4147ad1fdafe362f932f6fc7fb5d0e | 22,375 |
def bounded_binary_search(generator, length, target, lower_bound, upper_bound):
"""
efficient binary search for a <target> value within bounds [<lower_bound>, <upper_bound>]
- converges to a locally optimal result within the bounds
- instead of indexing an iterable, lazy evaluate a functor for performan... | fd6af8a45130415dec063b2f4cb6884de5c7a8d5 | 22,381 |
from typing import List
from typing import Dict
def can_construct(target_str: str, word_bank: List, memo: Dict = {}) -> bool:
"""
:param target_str: target string
:param word_bank: List of words
:param memo: memoization i.e. hash map to store intermediate computation results
:return: Boolean value... | 00df007b49239277e3ce8768ea9d019c0bcd03f3 | 22,388 |
def mb_to_hgt(Psta, mslp=1013.25): # METERS
"""Convert millibars to expected altitude, in meters."""
return (1-(Psta/mslp)**0.190284)*44307.69396 | dbe2df667e54f80031f162f6d3e9aeb9fcee15f4 | 22,392 |
def _pad_name(name, pad_num=13, quotes=True):
""" Pads a string so that they all line up when stacked."""
l_name = len(name)
if l_name < pad_num:
pad = pad_num - l_name
if quotes:
pad_str = "'{name}'{sep:<{pad}}"
else:
pad_str = "{name}{sep:<{pad}}"
pa... | 5863e78d87a87d063181bcceb2d6d382208f4af4 | 22,393 |
def convertgoogle(ui):
"""function to convert user information returned by google auth service in expected format:
returns this format:
e.g.:{'name':'John Smith','id': '12345', 'email': 'js@example.com','provider','google',...}
"""
myui = {'name':ui['name'],'given_name':ui['given_name'],'family_na... | 96d74c39cfa641fcd3f4961518046b3c0b506284 | 22,395 |
def dataset_was_harvested(package):
"""Return True if package was harvested by a harvester,
False if not."""
return bool(len(package.harvest_objects) > 0) | 5fcd8647b520c2687d06fd1ba6b2ba9f1540da8a | 22,396 |
from pathlib import Path
def recurse_checker(file_path: Path, recursive_flag: bool, recursive_dot_flag: bool) -> bool:
"""
:param file_path: file to be checked.
:param recursive_flag: whether to recursively refactor directories.
:param recursive_dot_flag: whether to recursively refactor dot directorie... | 4b5edcf4d361f6fa27ccf9120bb9f15b16d381d0 | 22,397 |
def default_prompt(prompt, default=None):
"""
Prompt the user for input. If they press enter, return the default.
:param str prompt: Prompt to display to user (do not include default value)
:param str default: Default return value
:return: Value entered or default
:rtype: str or None
"""
... | 59282cb61a25b16dc7ca84553acd28f575350092 | 22,399 |
def bits_to_base(x):
"""convert integer representation of two bits to correct base"""
if x == 0:
return 'T'
elif x == 1:
return 'C'
elif x == 2:
return 'A'
elif x == 3:
return 'G'
else:
raise ValueError('Only integers 0-3 are valid inputs') | e1a9b8894e0591a51058747dc88cf9225c8d053c | 22,401 |
def get_script_sub_ses_and_task_from_cmd(cmd_parts):
"""
:param cmd_parts: List of string parts of complete command calling pipeline
:return: Dictionary mapping each of several pipeline .py script flags
to the index of its value in split_cmd
"""
flags_to_find = ['-subject', '-ses', '-t... | 8caee8ebbb930208f1c6d73e99f5788fc21034af | 22,403 |
import math
def diff_payments(P, n, i):
"""Finding the differentiated payment using:
P = credit principal
n = number of payments (months)
i = nominal (monthly) interest rate (float, not a percentage)
Returns formatted string
A differentiated payment schedule is where part of the payment reduc... | b0eb64645c894d649b350c44e32084cbd11dc766 | 22,407 |
def string2array(value):
""" covert a long string format into a list
:param value: a string that can be split by ","
:type value: str
:return: the array of flaoting numbers from a sring
:rtype: [float,float,....]
"""
value = value.replace("[", "").replace("]", "")
value = value.split(... | 4a301e42b535be64a34f4fbfe20ee81c6b214cc9 | 22,411 |
def is_eligible_file( filename ):
""" Based on the file name, decide whether the file is likely to contain image data """
eligible = False
if ( filename.endswith( '.png' ) or filename.endswith( '.jpg' ) ):
eligible = True
return eligible | 75988428ce9078f8de1f95c97dba4f2e77bdbe3b | 22,412 |
def parse_mltag(mltag):
"""
Convert 255 discrete integer code into mod score 0-1, return as a generator.
This is NOT designed to handle interleaved Ml format for multiple mod types!
:param mltag: The Ml tag obtained for the read with('Ml:B:C,204,89,26'). (str)
:return: Generator of floats, probabi... | 8f775a80717c366ffe00b33a53c924c02f7dc844 | 22,413 |
def collect(gen):
"""Turn the output of a generator into a string we can compare."""
return "\n".join(list(gen)) + "\n" | 9081bc65519d222a355e5adee855e3d22aa75122 | 22,415 |
import time
def to_epoch(cmk_ts):
"""Parse Check_MK's timestamp into epoch time"""
return int(time.mktime(time.strptime(cmk_ts, '%Y-%m-%d %H:%M:%S'))) | 87f11ddffc6fbab3e833d4a39529c94bfca3a6ef | 22,425 |
def truncate_string_to_length(string: str, length: int) -> str:
""" Truncate a string to make sure its length not exceeding a given length. """
if len(string) <= length:
return string
half_length = int(0.5 * length) - 1
head = string[:half_length]
tail = string[-half_length:]
return f"{... | 67e5d1bbe7cd7aa6421fff647c6842af19faabc4 | 22,426 |
import struct
import socket
import ipaddress
def parse_ipv4_address(ipv4_hex):
"""
Convert /proc IPv4 hex address into standard IPv4 notation.
:param ipv4_hex: IPv4 string in hex format
:return: IPv4Address object
"""
ipv4 = int(ipv4_hex, 16)
# pack IPv4 address in system native b... | 007ae07c91df8484ae304fc2218c751e341bbede | 22,428 |
def revcomp(seq):
"""
Convert sequence to reverse complementary
"""
trantab = str.maketrans("ATCG", "TAGC")
return seq.translate(trantab)[::-1] | c5420fdca7e2c85d78a2346d352a6ac4993378da | 22,436 |
def find_perimeter(height: int, width: int) -> int:
"""Find the perimeter of a rectangle."""
return (height + width) * 2 | 75913101034c873743aefb53540d5c0884d162f1 | 22,441 |
def bin_to_dec( clist , c , tot=0 ):
"""Implements ordinary binary to integer conversion if tot=0
and HEADLESS binary to integer if tot=1
clist is a list of bits; read c of them and turn into an integer.
The bits that are read from the list are popped from it, i.e., deleted
Regular binary to decima... | 9aec0835251c52a00ad439e4ba72a7a01ced5196 | 22,442 |
def osr_proj4(input_osr):
"""Return the PROJ4 code of an osr.SpatialReference
Args:
input_osr (:class:`osr.SpatialReference`): OSR Spatial reference
of the input projection/GCS
Returns:
str: Proj4 string of the projection or GCS
"""
return input_osr.ExportToProj4() | 12dd419ebbeb20c48fc795eabf57cd1f64a459a9 | 22,451 |
def otu_name(tax):
"""
Determine a simple Genus-species identifier for an OTU, if possible.
If OTU is not identified to the species level, name it as
Unclassified (familly/genus/etc...).
:type tax: list
:param tax: QIIME-style taxonomy identifiers, e.g.
["k__Bacteria", u"p__Fir... | 1badcad0d023616d72c4276bc6b5bd55b4e5073b | 22,453 |
def split(a, n):
""" Splits an input list into n equal chunks; this works even if modulo > 0.
:param a: list of arbitrary length
:param n: number of groups to split into
:return: generator of chunks
"""
k, m = int(len(a) / n), len(a) % n
return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m... | 832bb9fa9e2dfcae2cee6cb65703aa2a7f35ab7f | 22,456 |
def unprefix(path, prefix):
"""Remove the prefix from path. Append '/' if an empty string results."""
if not path.startswith(prefix):
raise Exception('Not prefixed.')
if prefix != '/':
path = path[len(prefix):]
if not path:
path = '/'
return path | afb4b008e23a62cc1ac0e71196fd131d736d8498 | 22,461 |
def _gen_key_value(size: int) -> bytes:
"""Returns a fixed key_value of a given size."""
return bytes(i for i in range(size)) | 84a5bc5370df0f70994f753ababb40b9e3357458 | 22,463 |
def alternate_capitalization(s):
"""
Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown
below. Index 0 will be considered even.
:param s: a string value.
:return: a list of strings with the first string starting with capitalization alterna... | 89a10d51cc87b306c4f29e2d87baab39c6dbeb2f | 22,465 |
def _inner_join(xA_df, xB_df):
"""
Simple innner join on "interaction_id"
"""
xA_xB_map = xA_df.merge(xB_df, on="interaction_id", how="inner", suffixes=('_A', '_B'))
return xA_xB_map | 79fe471a0644eba9fd0111284e70058e935c148d | 22,471 |
def FairShareTax(c00100, MARS, ptax_was, setax, ptax_amc,
FST_AGI_trt, FST_AGI_thd_lo, FST_AGI_thd_hi,
fstax, iitax, combined, surtax):
"""
Computes Fair Share Tax, or "Buffet Rule", types of reforms.
Taxpayer Characteristics
------------------------
c00100 : AGI
... | 13ad589d6e1cd3dc98a5ef696d811ce41b23b311 | 22,474 |
def word_count_dict_to_tuples(counts, decrease=True):
"""
Given a dictionary of word counts (mapping words to counts of their
frequencies), convert this into an ordered list of tuples (word,
count). The list is ordered by decreasing count, unless increase is
True.
"""
return sorted(list(coun... | b8abfff7b74d2e1b2724bfbe29d1823f6682bd64 | 22,478 |
def _as_mu_args(
mu=None,
omega=None,
tau=None,
# _default={},
**kwargs):
"""
utility function to convert model arguments to kernel arguments.
This renames omega and mu, and *deletes* tau.
"""
kwargs = dict(**kwargs)
# kwargs.setdefault(**_default)
if ... | eebe8933d9157c8fc9e61fbfd325f3864547aa36 | 22,481 |
from typing import List
from typing import Tuple
from typing import Optional
def get_additional_data_lengths(source_pre: List[List[str]],
source_nxt: List[List[str]],
target_pre: List[List[str]],
target_nxt: List[List[str]... | 789ba560074efa0c41f0f26bf71518a8e200cf24 | 22,483 |
def _get_axis(snapshot_data, column, axis_type):
"""Return column of data from snapshot data of the axis type passed.
Parameters
----------
snapshot_data : numpy.ndarray
The data read in holding the axis data of the log.
column : int
The column of the desired data in snapshot_data
... | 5bf7b947d0f593a485f6d5b3a4612717b171b87d | 22,485 |
def calc_fixed_bn(func, in_data, **kwargs):
"""[FixedBatchNormalization](https://docs.chainer.org/en/v4.3.0/reference/generated/chainer.functions.fixed_batch_normalization.html)
Test-mode batch normalization.
It consists of normalization part (using $\mu$ and $\sigma$) and
bias part ($\\gamma$ and $\\b... | 8f20d0210effb07989a35b6b439d3144b0fe6790 | 22,492 |
def count_truthy(items):
"""
Count non None values viz, but includes 0
----
examples:
1) count_truthy([1, 2, None, 'a']) -> 3
2) count_truthy([1, 2, 0, 'a']) -> 4
----
:param items: list
:return: int
"""
counter = 0
for item in items:
if item is not None:
... | 670c97294bae6a75fe3f0949814e52454470df11 | 22,494 |
def int_to_chain(i,base=62):
"""
int_to_chain(int,int) -> str
Converts a positive integer to a chain ID. Chain IDs include uppercase
characters, numbers, and optionally lowercase letters.
i = a positive integer to convert
base = the alphabet size to include. Typically 36 or 62.
"""
if i ... | aa4a96d67ec8b809ec6e01916e9a54369580a897 | 22,495 |
def to_applescript(num):
"""
Convert a Python number to a format that can be passed to Applescript.
A number doesn't need coerced to print to stdout, but it's best to be
thorough and explicit.
"""
return str(num) | 7d4fe31e276267668078cedc0b5fa6c5f97dc035 | 22,504 |
import random
def sample(population, k, seed=42):
"""Return a list of k elements sampled from population. Set random.seed with seed."""
if k is None or k > len(population):
return population
random.seed(len(population) * k * seed)
return random.sample(population, k) | 0f087c675e87fef721426229f570e95ae84b10bc | 22,507 |
def convertBinaryToDecimal(num: str) -> int:
"""
Converts a binary string to a decimal number
"""
multiplier: int = 1
decimalNum: int = 0
for c in reversed(num):
decimalNum += (int(c) * multiplier)
multiplier *= 2
return decimalNum | 6ae6ee26f8f66347284c4db4a6a0e76dd88f749f | 22,512 |
import mimetypes
def get_content_type(filename):
"""
Uses mimetype's guess functionality to take a shot at guessing the provided filename's mimetype.
:param str filename: name of the file, should include extension
:return: the guessed value or `application/octet-stream` by default
:rtype: str
... | 7bc7c33763157ba3104de854dde9106d93db0205 | 22,514 |
def acceptance_probability(previousConfigCost, newConfigurationCost, NumberOfSteps):
"""
e = previous config
e' = new config
T = NumberOfSteps
* Implementation of P(e, e', T).
* The probability of making a transition from the current state s
* to a candidate state ... | ea56f38830f00115e567fc426961e6eafe42695e | 22,522 |
def multiple_split(source_string, separators, split_by = '\n'):
"""
This function allows the user to split a string by using different
separators.
Note: This version is faster than using the (s)re.split method (I tested it
with timeit).
Parameters:
* source_string: string to be splitted
* separators:... | 0310d60a225fe156f86d6c0b4ce02781773750de | 22,526 |
def base36decode(base36_string):
"""Converts base36 string into integer."""
return int(base36_string, 36) | 66da9d391705cd0748e0e7c0ea5c69be2366ed4e | 22,527 |
def get_topic_data(topics_with_summaries):
"""
This function takes in a list of ranked topic objects
and returns a dictionary of the data.
Keys are document object and values are list of tuples of (sent, set of nouns)
for each sent in the doc. {doc_obj: [(sent_index, sent_noun_set)]... | b0abf8ba28bc4359c2453050cb1a24340ac21158 | 22,529 |
def decode(symbol_list, bit_count):
""" Decodes the value encoded on the end of a list of symbols.
Each symbol is a bit in the binary representation of the value, with more significant
bits at the end of the list.
- `symbol_list` - the list of symbols to decode from.
- `bit_count` -... | f7cbfe783b32db099713d357fc6a20a7deff7e9f | 22,530 |
import requests
import json
def make_post_request(url, payload, headers=None):
"""Wrapper for requests.post"""
return requests.post(url, data=json.dumps(payload), headers=headers) | 3d02fe19bfd8c3c80d0f181679b563d4d2429a6a | 22,533 |
def make_scoped_name(*args):
""" Convert a series of strings into a single string
representing joined by points. This convertion represents
Pythons scope convention.i.e. pkg.subpkg.module
Args:
*ags: list of string. The strings will
joined in FIFO order.
Returns:
str: stri... | 39895772eb6d4cb8b0c63b54f8f2cfd4c83964c9 | 22,537 |
def AND(p: bool, q: bool) -> bool:
"""
Conjunction operator used in propositional logic
"""
return bool(p and q) | 5e166eff3b1b998490fd5ed1c9e6e034de1efea0 | 22,538 |
def array_to_string(array, delimiter=" ", format="{}", precision=None):
"""
Converts a numeric array into the string format in mujoco.
Examples:
[0, 1, 2] => "0 1 2"
"""
if precision is not None and format == "{}":
return delimiter.join([format.format(round(x, precision)) for x in a... | 8b308b41d5b6f82d58a8b9a4afd529fc7cbf7408 | 22,546 |
import json
def json_roundtrip(data: dict) -> dict:
"""Input `data` is returned after JSON dump/load round trip."""
return json.loads(json.dumps(data)) | 2e15814d1e975f5f3e845196365de5b521e60cd8 | 22,548 |
def is_apple_os(os_):
"""returns True if OS is Apple one (Macos, iOS, watchOS or tvOS"""
return str(os_) in ['Macos', 'iOS', 'watchOS', 'tvOS'] | 77b85f8e4fec837c5009fff3d8e8446c9f1d0d58 | 22,550 |
def getTZLookup(tzfname='cities15000.txt'):
"""Returns a mapping from gps locations to time-zone names.
The `tzfname` file is read to map gps locations to timezone names.
This is from: http://download.geonames.org/export/dump/cities15000.zip
Returns a list of `((lat, lon), timezone)` pairs.
"""
... | 3dcb3b297be72eb55c2d75ffc0bf269e27775232 | 22,553 |
def format_with_default_value(handle_missing_key, s, d):
"""Formats a string with handling of missing keys from the dict.
Calls s.format(**d) while handling missing keys by calling
handle_missing_key to get the appropriate values for the missing keys.
Args:
handle_issing_key: A function that t... | 957b851dcacfc98c5bcdb5f1c76850014f8262f5 | 22,559 |
def sum_combinations(numbers):
"""Add all combinations of the given numbers, of at least one number"""
combinations = [0]
for element in numbers:
new_combinations = list(combinations)
for element2 in combinations:
new_combinations.append(element + element2)
combinations =... | 193f3c7285f70f13435e971844288cb6faeb1d98 | 22,565 |
import json
def load_json(filepath):
"""
Load a json file
Inputs
filepath: string, path to file
Outputs
data: dictionary, json key, value pairs
Example
path = "~/git/msc-data/unity/roboRacingLeague/log/logs_Sat_Nov_14_12_36_16_2020/record_11640.json"
js = load_json(path)
... | bca35e8e10da33ac599a8895e8495fb5eec829e0 | 22,566 |
from math import log
def idf(term, corpus):
"""
computes inverse document frequency. IDF is defined as the
logarithm of the total number of documents in the corpus over the
number of documents containing the search term:
log(all documents/documents containing the search term)
Note that if *no... | 15ca03e272a0e535500f38e3bb73bab342e42390 | 22,569 |
def two_oldest_ages(ages):
"""Return two distinct oldest ages as tuple (second-oldest, oldest)..
>>> two_oldest_ages([1, 2, 10, 8])
(8, 10)
>>> two_oldest_ages([6, 1, 9, 10, 4])
(9, 10)
Even if more than one person has the same oldest age, this should return
two *distinct*... | 38944082fdf1ca44ff1813b9570dcb0377f40960 | 22,578 |
def replace_pad(l, new_symbol='-'):
"""<pad> refers to epsilon in CTC replace with another symbol for readability"""
new_l = []
for x in l:
if x == "<pad>":
new_l.append(new_symbol)
else:
new_l.append(x)
return new_l | 94671a5d035a4ce2fae1f26e65c52ad55e4dba6c | 22,579 |
def getLemma(line):
"""
retreves the second word in a line in the coha corpus, or nothing if
given an empty line
"""
if line == "":
return ""
s = line.split("\t")
return s[1] | 34c51925d6a9d3908bf8b3114256e50ae3712467 | 22,581 |
import re
def _regex_search(pattern: str, string: str, group: int):
"""Shortcut method to search a string for a given pattern.
:param str pattern:
A regular expression pattern.
:param str string:
A target string to search.
:param int group:
Index of group to return.
:retur... | c703ac3eed3cbb981586b5a950f071c8535f32a5 | 22,583 |
import json
def jsonString(obj, pretty=False):
"""Creates a json object, if pretty is specifed as True proper
formatting is added
Args as data:
obj: object that needs to be converted to a json object
pretty: Boolean specifying whether json object has to be formatted
Returns:
JS... | 7fb621029ee509240dfd46bc641dcde34c87170c | 22,584 |
import struct
def read_plain_int96(fo):
"""Reads a 96-bit int using the plain encoding"""
tup = struct.unpack("<qi", fo.read(12))
return tup[0] << 32 | tup[1] | 39d924fe211a17192b4b3158340d40b3f28948d1 | 22,587 |
def computeAirProperties(T, p, pInhPa=False):
""" Calculates air density in kg/m3 and viscosity in m2/s given pressure
in mmHg and temperature in deg C. Can also specify pressure in hPa with the flag."""
mmHgTohPa = 1.3332239
if pInhPa:
p = p/mmHgTohPa
# from engineering toolbox:
# ... | 645db891cc775bbd1702a8ee437a2fa1fe9b62a3 | 22,590 |
def readonly(label, value):
"""Return HTML markup for a readonly display like a form input."""
return {"label": label, "value": value} | c153ae42b074dea68101ca2e3abce03d1ed6c552 | 22,596 |
def course_str(course):
"""Format course as a string."""
return (
f"[{course['pk']}] {course['name']} "
f"{course['semester']} {course['year']}"
) | a9b1d6663ab18da220eceedc3c2319f9da80a08c | 22,599 |
import functools
def loss_function_for_data(loss_function, X):
""" Get a loss function for a fixed dataset
Parameters
----------
loss_function : function
The loss function to use. The data parameter for the function must
be `X`
X : coo_matrix
coo_matrix of data to apply l... | 782d050ed313146d9cdae38b7e63ed9dd287e3cc | 22,600 |
def time_duration_formatter(x):
"""Format time duration in seconds
"""
mm, ss = divmod(x, 60)
hh, mm = divmod(mm, 60)
dd, hh = divmod(hh, 24)
res = ''
if dd:
res += '%dd ' % dd
if dd or hh:
res += '%dh ' % hh
if dd or hh or mm:
res += '%dm ' % mm
res += '... | a0b28b2dd6cd81cb297b2b1dbbc184ff1be896b8 | 22,611 |
def get_keys_from_post(request, *args):
"""Get a tuple of given keys from request.POST object."""
return tuple(request.POST[arg] for arg in args) | f504a784849470405dbb6022bc0b7ce877caceda | 22,612 |
async def some_async_function(value):
"""A demo async function. Does not do any actual I/O."""
return value | 9324669acd9955095e12c28acc09cf0b7d68d767 | 22,613 |
import json
import hashlib
def compute_caching_hash(d):
"""Generate a hash from a dictionary to use as a cache file name
This is intended to be used for experiments cache files
"""
string = json.dumps(d, sort_keys=True, ensure_ascii=True)
h = hashlib.sha1()
h.update(string.encode('utf8'))... | 140a68c2f349fb5f3db6d48a24c16cc22a215bb0 | 22,614 |
def slopeFromVector(v):
"""
Return the slope of a vector from a QVector2D object.
"""
if v.x() == 0.0:
return v.y()
return v.y() / v.x() | 26d33063f84b889ee80868758eb7d15d9abf7dae | 22,615 |
def validation(model, val_fn, datagen, mb_size=16):
""" Validation routine for speech-models
Params:
model (keras.model): Constructed keras model
val_fn (theano.function): A theano function that calculates the cost
over a validation set
datagen (DataGenerator)
mb_size... | 14b1465ec9934f95b96f2f019cc83a42e8c25cc7 | 22,620 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.