content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
from typing import Any
def copy_with_str_subst(x: Any, substitutions: Any) -> Any:
"""Deep-copy a structure, carrying out string substitutions on any strings
Args:
x (object): structure to be copied
substitutions (object): substitutions to be made - passed into the
string '%' operator
Returns:
copy of x
"""
if isinstance(x, str):
return x % substitutions
if isinstance(x, dict):
return {k: copy_with_str_subst(v, substitutions) for (k, v) in x.items()}
if isinstance(x, (list, tuple)):
return [copy_with_str_subst(y, substitutions) for y in x]
# assume it's uninterested and can be shallow-copied.
return x | 2aefd8902b2ca56d9c7a2e81dbd52c52a731a14e | 266,645 |
def channel_reshape(x, channel_shape):
""" (B, *, H, W) to (B, custom, H, W) """
return x.reshape((x.shape[0],) + channel_shape + x.shape[-2:]) | 7d08dc4fc20686f9797a1e36ddaedbf9ef990a0c | 45,369 |
import re
def strip_advanced(s: str) -> str:
"""Remove newlines and multiple whitespaces."""
return re.sub(r'\s{2,}', ' ', s.replace('\n', ' ')) | 66456fd4357e55ec7cba4b2bec69c572d242287e | 221,987 |
def set_conn_string(server, db_name, username, password):
"""
Sets connection string to SSAS database,
in this case designed for Azure Analysis Services
"""
conn_string = (
"Provider=MSOLAP;Data Source={};Initial Catalog={};User ID={};"
"Password={};Persist Security Info=True;Impersonation Level=Impersonate".format(
server, db_name, username, password
)
)
return conn_string | 9b7d63a0ef97eb4012163550ed0548c5e531fe39 | 670,833 |
def dominant_flip_flopping(W):
"""Determine if a unique walk matrix demonstrates dominant flip-flopping.
Dominant flip-flopping is defined as:
For every class C[i], there exists a walk length L[x], such that C[i] has
more closed walks of length L[x] than all other classes combined.
Dominant flip-flopping implies all-subset flip-flopping.
Parameters
----------
W : Numpy Matrix
Unique walk matrix as returned by `walk_classes`
Returns
-------
boolean
True if dominant flip-flopping holds for `W`
"""
# Work with an ndarray representation of W
w = W.getA()
# Get the number of rows and columns in W
num_rows, num_cols = w.shape
# Generate the column-wise sum of w
# This amounts to a 1darray where each item
# is the sum of all walks of a length k for
# all classes
sums = w.sum(0)
# Iterate over all classes
for cls in range(0, num_rows):
# Whether this class dominates any k-walk
is_dominant = False
# Iterate over all walks
for walk in range(0, num_cols):
# Check to see if is dominant
# Sums includes the number of walks for the class
# so it must be removed before checking that it
# dominates the remainder
if w[cls][walk] > sums[walk] - w[cls][walk]:
is_dominant = True
break
# Return false immediately if this class does
# not dominate a k-walk
if not is_dominant:
return False
# Return true as default
return True | 40e4092e23af578008370ef55cc983a0c243f89d | 334,189 |
def export_to_pascal(ibs, *args, **kwargs):
"""Alias for export_to_xml"""
return ibs.export_to_xml(*args, **kwargs) | b7fd4d3c68e09f5665dd658c42fc297341fb0b1e | 665,522 |
def get_typecode(dtype):
"""Get the IDL typecode for a given dtype"""
if dtype.name[:5] == "bytes":
return "1"
if dtype.name == "int16":
return "2"
if dtype.name == "int32":
return "3"
if dtype.name == "float32":
return "4"
if dtype.name == "float64":
return "5"
if dtype.name[:3] == "str":
return dtype.name[3:]
raise ValueError("Don't recognise the datatype") | 29e13fd122d6983b9bbc196216cf29487544e1b8 | 240,959 |
import re
def parse_num(s):
"""Parse data size information into a float number.
Here are some examples of conversions:
199.2k means 203981 bytes
1GB means 1073741824 bytes
2.1 tb means 2199023255552 bytes
"""
g = re.match(r'([-+\d.e]+)\s*(\w*)', str(s))
if not g:
raise ValueError("can't parse %r as a number" % s)
(val, unit) = g.groups()
num = float(val)
unit = unit.lower()
if unit in ['t', 'tb']:
mult = 1024*1024*1024*1024
elif unit in ['g', 'gb']:
mult = 1024*1024*1024
elif unit in ['m', 'mb']:
mult = 1024*1024
elif unit in ['k', 'kb']:
mult = 1024
elif unit in ['', 'b']:
mult = 1
else:
raise ValueError("invalid unit %r in number %r" % (unit, s))
return int(num*mult) | 721cc52cdf543bcaf3ff77d8059a7bfe6cb6d892 | 36,433 |
import re
def extract_target_sdk_version_apk(badging):
"""Extract targetSdkVersion tags from the manifest of an APK."""
pattern = re.compile("^targetSdkVersion?:'(.*)'$", re.MULTILINE)
for match in re.finditer(pattern, badging):
return match.group(1)
raise RuntimeError('cannot find targetSdkVersion in the manifest') | da1d8c9a1d5ee23c4dda9710b872784286072dde | 517,768 |
def _is_vowel(phone):
"""Check whether a phoneme from the CMU dictionary represents a vowel."""
return any(c.isdigit() for c in phone) | 17bc16b73ec45e37d255728c8ea1ad38f80dad1f | 346,361 |
def bucket_size(bucket):
"""
Returns the total number of bytes in a bucket.
"""
return sum(key.size for key in bucket.get_all_keys()) | 83701d79eb54ff01e21814d3d107c06a798e2ef4 | 110,876 |
from typing import Tuple
def find_element(atom_symbol: str) -> Tuple[int, int]:
"""Returns the indices of the element component of a SMILES atom symbol.
That is, if atom_symbol[i:j] is the element substring of the SMILES atom,
then (i, j) is returned. For example:
* _find_element('b') = (0, 1).
* _find_element('B') = (0, 1).
* _find_element('[13C]') = (3, 4).
* _find_element('[nH+]') = (1, 2).
:param atom_symbol: a SMILES atom.
:return: a tuple of the indices of the element substring of
``atom_symbol``.
"""
if atom_symbol[0] != '[':
return 0, len(atom_symbol)
i = 1
while atom_symbol[i].isdigit(): # skip isotope number
i += 1
if atom_symbol[i + 1].isalpha() and atom_symbol[i + 1] != 'H':
return i, i + 2
else:
return i, i + 1 | 2694d5de2a9ac41f25f55139eb3169c68f2f2125 | 57,794 |
def calc_duration(audio, rate):
"""Calculates the length of the audio in seconds.
params:
audio: A numpy ndarray, which has 1 dimension and values within
-1.0 to 1.0 (inclusive)
rate: An integer, which is the rate at which samples are taken
return: A float
"""
return audio.size / rate | 34384c04a4f49bc3730b96696fdbd78621be57b5 | 459,692 |
def get_tag_value(tags, key):
"""Get a specific Tag value from a list of Tags"""
for tag in tags:
if tag['Key'] == key:
return tag['Value']
else:
raise KeyError | bb7a0a6e7dc928575cda84ce8c41065cd89efd09 | 492,416 |
import math
def distance(p1, p2):
"""Return the euclidean distance between (x1,y1) and (x2, y2)"""
x1,y1 = p1
x2,y2 = p2
return math.hypot(x1-x2, y1-y2) | 945213446cb78d7e35466ea7e0caa91ad699f8c1 | 322,935 |
def split(windows, num):
"""Split an iterable of windows into `num` sublists of (roughly) equal
length. Return a list of these sublists."""
if num == 1:
return [windows]
windows = windows if isinstance(windows, list) else list(windows)
length = len(windows) // num
return [windows[i*length:(i+1)*length] for i in range(num)] | 66180dfe34e5a345754c19e9fc5afd3369bacc5c | 250,319 |
def observe_rate(rate, redshift):
"""Returns observable burst rate (per day) from given local rate
"""
return rate / redshift | 13be6db3b3db0763a73be2b8381acb98f6f0ad54 | 679,033 |
def _get_energy(simulation, positions):
"""Given an OpenMM simulation and position, return its energy"""
simulation.context.setPositions(positions)
state = simulation.context.getState(getEnergy=True, getPositions=True)
energy = state.getPotentialEnergy()
return energy | 5179d54a4271bc5033115088ede50db5a532092c | 484,192 |
def is_a_number(string):
"""Takes a string and returns a boolean indicating whether it can be
converted to a float.
"""
try:
float(string)
return True
except ValueError:
return False | 92c20a803c1608140ca21f16e1a05cf0503cf994 | 290,525 |
def query_df(data, col_name, col_value):
"""
Create a new subset of a given DataFrame() by querying it.
Parameters:
- data: The base DataFrame().
- col_name: The name of the column.
- col_vale: The values to match in that column.
Returns:
A DataFrame() object.
"""
return data.query(f'{col_name} == "{col_value}"') | f75290e09c887a312e07fa62015fcdf0c19d5803 | 598,419 |
def add_to_dict_key(prefix: str, dct: dict) -> dict:
""" add a prefix to every dict key """
return {'%s/%s' % (prefix, k): v for k, v in dct.items()} | 9be01ed608744c60963b3f0b29e4bf841776648f | 501,399 |
from typing import Callable
def filter_keys(d: dict, predicate: Callable) -> dict:
"""
Returns new subset dict of d where keys pass predicate fn
>>> filter_keys({'Lisa': 8, 'Marge': 36}, lambda x: len(x) > 4)
{'Marge': 36}
"""
return {k: v for k, v in d.items() if predicate(k)} | 1bb282effd08bd103d479b442f1cd24b8b368e6a | 483,208 |
def al_cuadrado(x):
"""Función que eleva un número al cuadrado."""
y = x ** 2
return y | cbc2707c63d4a7c76f55d1e8ab1312e94eca8eb1 | 283,781 |
def is_str(target: str) -> bool:
"""Check target is str."""
if not isinstance(target, str):
return False
return True | e7d4449a0aac92b6c6f40c8aeca708b756cf3d94 | 219,941 |
def format_authors(paper):
"""
format_authors formats list of author fields to strings
:param paper: dict of paper meta data
:type paper: dict
:return: string format of authors
:rtype: str
"""
authors = paper["authors"]
if len(authors) > 2:
author = authors[0]["name"].split(" ")[-1] + " et al."
elif len(authors) == 2:
author = (
authors[0]["name"].split(" ")[-1]
+ " & "
+ authors[-1]["name"].split(" ")[-1]
)
else:
author = authors[0]["name"].split(" ")[-1]
year = f', {paper["year"]}'
return author + year | 31a32e3460fb11e348577caa2e32b3d9ee079cc0 | 430,508 |
def sbr(data, weights):
"""Stolen Base Runs (SBR)
SBR = runSB * SB + runCS * CS
:param data: DataFrame or Series of player, team, or league totals
:param weights: DataFrame or Series of linear weights
:returns: Series of SBR values
"""
return weights["lw_sb"] * data["sb"] + weights["lw_cs"] * data["cs"] | f577dfa2955802a7cb7177f06f508d7902cbc60d | 633,003 |
def objScale(obj,factor):
"""
Object scaling function, gets obj and scale factor, returns an array of the scaled size
"""
oldSize = obj.get_size()
newSize = []
for i in oldSize:
newSize.append(int(i/float(factor)))
return newSize | 3104fc4e126299400a5a119fff0d8bc9d3ea32f7 | 9,061 |
def text_ends(text, pattern, case_sensitive=True):
"""
Checks whether the text (also known as `text`) contains the text specified for `pattern` at the end.
The no-data value None is passed through and therefore gets propagated.
Parameters
----------
text : str
Text in which to find something at the end.
pattern : str
Text to find at the end of `text`.
case_sensitive : bool, optional
Case sensitive comparison can be disabled by setting this parameter to False (default is True).
Returns
-------
bool :
True if `text` ends with `pattern`, False otherwise.
"""
if text is None:
return None
if case_sensitive:
return text.endswith(pattern)
else:
return text.lower().endswith(pattern.lower()) | e1b821f1c1769e0658d251c521680246884d728b | 574,305 |
def _transform_headers(httpx_reponse):
"""
Some headers can appear multiple times, like "Set-Cookie".
Therefore transform to every header key to list of values.
"""
out = {}
for key, var in httpx_reponse.headers.raw:
decoded_key = key.decode("utf-8")
out.setdefault(decoded_key, [])
out[decoded_key].append(var.decode("utf-8"))
return out | 583f2cef73415317341e65325e1ff35647ae42b9 | 235,697 |
def suggest_parameters_DRE_NMNIST(trial,
list_lr, list_bs, list_opt,
list_wd, list_multLam, list_order):
""" Suggest hyperparameters.
Args:
trial: A trial object for optuna optimization.
list_lr: A list of floats. Candidates of learning rates.
list_bs: A list of ints. Candidates of batch sizes.
list_opt: A list of strings. Candidates of optimizers.
list_wd: A list of floats. weight decay
list_multLam: A list of floats. Prefactor of the second term of BARR.
list_order: A list of integers. Order of SPRT-TANDEM.
Returns:
learning_rate: A float.
batch_size: An int.
name_optimizer: A string.
weight_decay: A float.
param_multLam: A float.
order_sprt: An int.
"""
# load yaml interprrets, e.g., 1e-2 as a string...
for iter_idx in range(len(list_lr)):
list_lr[iter_idx] = float(list_lr[iter_idx])
learning_rate = trial.suggest_categorical('learning_rate', list_lr)
batch_size = trial.suggest_categorical('batch_size', list_bs)
name_optimizer = trial.suggest_categorical('optimizer', list_opt)
weight_decay = trial.suggest_categorical('weight_decay', list_wd)
param_multLam = trial.suggest_categorical('param_multLam', list_multLam)
order_sprt = trial.suggest_categorical('order_sprt', list_order)
return learning_rate, batch_size, name_optimizer,\
weight_decay, param_multLam, order_sprt | 627855f5fe8fd15d43cc7c8ca3da22b704b5907e | 704,119 |
import unicodedata
def deaccent(text):
"""
Remove accentuation from the given string. Input text is either a unicode string or utf8 encoded bytestring.
Return input string with accents removed, as unicode.
Kindly borrowed from https://github.com/RaRe-Technologies/gensim/blob/develop/gensim/utils.py
by Radim Rehurek and Petr Sojka
>>> deaccent("Šéf chomutovských komunistů dostal poštou bílý prášek")
'Sef chomutovskych komunistu dostal postou bily prasek'
"""
if not isinstance(text, str):
# assume utf8 for byte strings, use default (strict) error handling
text = text.decode('utf8')
norm = unicodedata.normalize("NFD", text)
result = ''.join(ch for ch in norm if unicodedata.category(ch) != 'Mn')
return unicodedata.normalize("NFC", result) | 01b36ed9c6e618d442fd67f89aac0cdc30f6a6d2 | 336,326 |
import getpass
def _set_shells(options):
"""Set password, shell and extra prompts for the username.
Args:
options dictionary with username, jump_user and extra_prompts keys.
Returns:
options dictionary with shell_prompts and passwd_prompts keys
"""
shells = [
"mysql\\>",
"ftp\\>",
"telnet\\>",
"\\[root\\@.*\\]\\#",
"root\\@.*\\:\\~\\#",
]
password_shells = ["(yes/no)\\\?", "assword:"]
if not options["username"]:
options["username"] = getpass.getuser()
shells.append("\\[{0}@.*\\]\\$".format(options["username"]))
shells.append("{0}@.*:~\\$".format(options["username"]))
password_shells.append("{0}@.*assword\\:".format(options["username"]))
password_shells.append("{0}\\:".format(options["username"]))
if options["jump_user"]:
shells.append("\\[{0}@.*\\]\\$".format(options["jump_user"]))
shells.append("{0}@.*:~\\$".format(options["jump_user"]))
password_shells.append("{0}@.*assword:".format(options["jump_user"]))
password_shells.append("{0}:".format(options["jump_user"]))
options["shell_prompts"] = shells
options["passwd_prompts"] = password_shells
if not isinstance(options["extra_prompts"], (list, tuple)):
options["extra_prompts"] = [options["extra_prompts"]]
return options | f839646d52e2b43656a049d22866fd6fd201222d | 355,614 |
def input_parameter_name(name, var_pos):
"""Generate parameter name for using as template input parameter names
in Argo YAML. For example, the parameter name "message" in the
container template print-message in
https://github.com/argoproj/argo/tree/master/examples#output-parameters.
"""
return "para-%s-%s" % (name, var_pos) | 40a3d29274b141294e4b9cae83ddb84ae8e44188 | 42,270 |
def format_timedelta(days: int = 0, hours: int = 0, minutes: int = 0,
seconds: int = 0) -> str:
"""Returns a simplified string representation of the given timedelta."""
s = '' if days == 0 else f'{days:d}d'
if hours > 0:
if len(s) > 0:
s += ' '
s += f'{hours:d}h'
if minutes > 0:
if len(s) > 0:
s += ' '
s += f'{minutes:d}min'
if seconds > 0 or len(s) == 0:
if len(s) > 0:
s += ' '
s += f'{seconds:d}sec'
return s | 6414e2be5a01f178d6515ab6f21ea7c5ab4d5004 | 703,402 |
def build_database_url(ensembl_database):
""" Build the correct URL based on the database required
GRCh37 databases are on port 3337, all other databases are on port 3306
"""
port = 3337 if str(ensembl_database).endswith('37') else 3306
return 'mysql+mysqldb://[email protected]:{}/{}'\
.format(port, ensembl_database) | f33b6c4c18b8bf5ab7c8320e6b38c6f4cc9c41ac | 270,899 |
import pathlib
import json
def get_json_fixture_file(filename):
"""
Return JSON fixture from local file
"""
path = pathlib.Path(__file__).parent.parent / f"fixtures/{filename}"
content = pathlib.Path(path).read_text('UTF-8')
return json.loads(content) | a0973b51dd752996c1c2e526ee79cceb234849fa | 379,462 |
def _reduce_xyfp(x, y):
"""
Rescale FP xy coordinates
"""
a = 420.0 #mm
return x/a, y/a | 018c1a7dbd25590fd8bbb61238870cd4c3a00b03 | 134,385 |
import hashlib
def md5_hash(string):
""" Calculates the MD5 sum of a string
"""
m = hashlib.md5()
m.update(string.encode('utf-8'))
return m.hexdigest() | cf89d1c83e3fa1382c2f883627a774bfc51475e1 | 39,996 |
def formolIndex (NaOH_volume, NaOH_molarity, NaOH_fc, grams_of_honey):
"""
Function to calculate the formol index in honey
"""
number_of_NaOH_mols = NaOH_volume * NaOH_molarity * NaOH_fc
volume = number_of_NaOH_mols / NaOH_molarity
formol_index = (volume * 1000) / grams_of_honey
return formol_index | 5c6d72cd1500a61adef21f263010bee1cdec4914 | 410,125 |
def is_float(s):
"""
test if string parameter is valid float value
:param s: string to test
:return: boolean
"""
try:
float(s)
return True
except ValueError:
return False | 4d8074ffcfc0346d2d097ebbcf5b19c793632c28 | 516,467 |
def apply_aliases(seq_dict, aliases):
"""Aliases is a mapping from sequence to replacement sequence. We can use
an alias if the target is a key in the dictionary. Furthermore, if the
source is a key in the dictionary, we can delete it. This updates the
dictionary and returns the usable aliases."""
usable_aliases = {}
for k, v in aliases.items():
if v in seq_dict:
usable_aliases[k] = v
if k in seq_dict:
del seq_dict[k]
return usable_aliases | 54f7bf8e1af653427450cbdb8cee6314359b8db0 | 168,547 |
def get_lineup_number(players: list[dict], prompt: str) -> int:
"""Get the player by lineup number and confirm it is a valid lineup number."""
while True:
try:
number: int = int(input(prompt))
except ValueError:
print("Invalid integer. Please try again.")
continue
if number < 1 or number > len(players):
print("Invalid player number. " +
"Please try again.")
else:
break
return number | 508aabde982d310f52fca8cf80892edb7586db17 | 119,655 |
def merge(h1, h2):
"""
Returns a new dictionary containing the key-value pairs of ``h1`` combined with the key-value pairs of ``h2``.
Duplicate keys from ``h2`` overwrite keys from ``h1``.
:param h1: A python dict
:param h2: A python dict
:return: A new python dict containing the merged key-value pairs
"""
ret = {}
ret.update(h1)
ret.update(h2)
return ret | a7d55808d5ee4e9652779276daa061db993c3587 | 141,923 |
def get_in_shape(in_data):
"""Get shapes of input datas.
Parameters
----------
in_data: Tensor
input datas.
Returns
-------
list of shape
The shapes of input datas.
"""
return [d.shape for d in in_data] | ae54409d425189c33fe9fe1bdb0487cc854f9510 | 25,579 |
def extract_jasmine_summary(line):
"""
Example SUCCESS karma summary line:
PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 SUCCESS (0.205 secs / 0.001 secs)
Exmaple FAIL karma summary line:
PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.21 secs / 0.001 secs)
"""
# get totals
totals = line.split(' Executed ')[1].split(' ')
executed_tests, total_tests = int(totals[0]), int(totals[2])
# get failed
if 'SUCCESS' in line:
failed_tests = 0
else:
failed_tests = int(totals[3][1:])
return {
'total_tests': total_tests,
'executed_tests': executed_tests,
'failed_tests': failed_tests,
'passed_tests': executed_tests - failed_tests
} | f795ff015555cc3a2bd2d27527ae505a6dde9231 | 396 |
def set_recomputation_options(opts,
allow_recompute=True,
allow_stateful_recompute=None): # pylint: disable=unused-argument
"""Set re-computation options.
Args:
allow_recompute: Whether or not to re-compute instructions during training.
If this is enabled then we will attempt to pattern match
instructions/pipeline stages in the forward pass and recompute them in the
backward pass to avoid having to preserve activations which increase the
maximum memory liveness. Enabling this option can reduce memory usage at
the expense of extra computation. Any stateful operations cannot be
recomputed.
allow_stateful_recompute: Deprecated.
Returns:
The IpuOptions configuration protobuf.
"""
opts.speed_size_config.allow_recompute = allow_recompute
return opts | d0e4a6fbaf23401f5e5bba2ec9759627880529fc | 668,146 |
def chk_keys(keys, src_list):
"""Check the keys are included in the src_list
:param keys: the keys need to check
:param src_list: the source list
"""
for key in keys:
if key not in src_list:
return False
return True | 48706a1f39c06cf79b107ca67eb0a5c5e202fe08 | 678,492 |
def _get_first_non_empty_item(items):
"""
:param items: anything that is iterable
:return: first non empty value
In this filter the following values are considered non empty:
- None
- any empty sequence, for example, '', (), [].
- any empty mapping, for example, {}.
Note: to guarantee the returned element is actually the first non empty element in the iterable,
'items' must be a data structure that preserves order, ie tuple, list etc.
If order is not important, this can be reused to return `one of` the elements which is non empty.
This filter will treat zero of any numeric type for example, 0, 0.0, 0j and boolean 'False'
as a valid item since they are naturally 'falsy' in Python but not empty.
Note: Booleans are a subtype of integers. Zero of any numeric type 'is not False' but 'equals False'.
Reference: https://docs.python.org/release/3.4.2/library/stdtypes.html?highlight=boolean#boolean-values
"""
for item in items:
if item or item is False or item == 0:
return item
raise Exception('No valid items provided.') | 7880bef2183fa70cd8a24d61d48b18a28499d368 | 566,790 |
import codecs
def _open_file_with_cache(filename):
"""
Reads the input file and returns the result as a string.
This caches opened files to ensure that the audit functionality
doesn't unnecessarily re-open the same file.
"""
try:
with codecs.open(filename, encoding='utf-8') as f:
return f.read()
except (OSError, IOError):
return None | 099f35fde7b7fd813734fb79e024638a394ac15e | 189,577 |
import re
def validate_account_to_dashed(account):
"""
Validates the the provided string is in valid AdWords account format and converts it to dashed format.
:param str account: AdWords Account
:rtype: str
:return: Dashed format
"""
account = str(account).strip()
if re.match("[0-9]{3}-[0-9]{3}-[0-9]{4}", account):
return account
if re.match("^[0-9]{10}$", account):
return '-'.join([str(account)[0:3], str(account)[3:6], str(account)[6:]])
raise ValueError("Invalid account format provided: {}".format(account)) | 30eae40d2b205aeebc99cfc38864893d2fe6e7b8 | 40,815 |
from typing import Dict
def wrap_multiple_str(wrapping_string: str):
"""Wrap multiple values in a wrapping string by passing a dict where the keys are the parameters in the wrapping string and the values are the desired values.
>>> wrap_multiple_str("hello {first} {second}")({ "first": "happy", "second": "world" })
'hello happy world'
"""
def inner(x: Dict[str, str]) -> str:
return wrapping_string.format(**x)
return inner | 87a5bb85a7ca7586f1c7fa4d66f3c29b0809debe | 268,321 |
def set_list_of_lists(list_of_lists):
"""
Removes duplicated nested lists of a given list of lists, i.e. the set() equivalent for lists of lists
:param list_of_lists: A list of lists to take the set() of
:return: A set() equivalent to the given list of lists
"""
return [list(item) for item in set(tuple(nested_list ) for nested_list in list_of_lists)] | bb297a9c99a84c4dd68a0e4a62d3d9cee50d535b | 273,790 |
def rev_comp(item):
"""
Retuns the base on the opposite strand
"""
if item == 'A':
return 'T'
elif item == 'G':
return 'C'
elif item == 'T':
return 'A'
elif item == 'C':
return 'T'
else:
return 'N' | e38e1482b5682c6147ee6db6cdd92276d695c985 | 489,754 |
def str_to_list(data):
"""
Converts a string delimited by \n and \t to a list of lists.
:param data:
:type data: str
:return:
:rtype: List[List[str]]
"""
if isinstance(data, list):
return data
data = data.replace("'", '')
try:
if data[-1] == '\n':
data = data[:-1]
except IndexError:
return
tmp = data.split('\n')
result = []
for tmp_ in tmp:
result.append(tmp_.split('\t'))
return result | 17b2fda7b45041c101110b2405d3001798c8b258 | 403,595 |
import math
def truncate_floor(number, decimals):
"""Truncates decimals to floor based on given parameter
Arguments:
number {float} -- number to truncate
decimals {int} -- number of decimals
Returns:
float -- truncated number
"""
return math.floor(number * 10 ** decimals) / 10 ** decimals | 3f172b9947635662b59f2c5f31abb2cc13e31882 | 669,921 |
def b2i_le(value: bytes) -> int:
"""Converts a sequence of bytes (in little-endian order) to a single integer."""
value_int = sum(b * 2 ** (i * 8) for i, b in enumerate(value))
return value_int | 282dc9ef38681572c287f447cf4026b1b97c5c31 | 275,115 |
def create_lookup_tables(unique_words):
""" Create lookup tables for word_to_id and id_to_word
Args:
unique_words: dictionary of words in training set
Return:
word_to_id: dict with words as keys and corresponding ids as values
id_to_word: dict with ids as keys and corresponding words as values
"""
word_to_id = {} # word->id lookup
id_to_word = {} # id->word lookup
for index, word in enumerate(sorted(list(unique_words))):
word_to_id[word] = index + 1
id_to_word[index + 1] = word
return word_to_id, id_to_word | 44a99e615c5be147039a2c030e8a45a8c01080b2 | 647,636 |
def _remap(station: dict, i: int):
"""Remaps a channel number to one based on the DVR index
"""
if station['channel'].isdigit():
new_channel = str(int(station['channel']) + 100 * i)
else:
new_channel = str(float(station['channel']) + 100 * i)
return (new_channel, station['callSign'].replace(station['channel'], new_channel)) | 418160cd190299d11944d0fc0d9e74015fd339f2 | 555,689 |
def rotate(pattern, k):
""" Return a left circular rotation of the given pattern by k."""
if not type(k) == int:
raise TypeError("Second argument must be an integer")
n = len(pattern)
k = k % n
return pattern[k:n] + pattern[0:k] | 65ab067a02067ef26e300bd620407e71e63b2f95 | 525,652 |
def human_time(s):
"""Convert floating-point seconds into human-readable time"""
if s < 60.0: return "%.3f" % s
m = int(s) / 60
if m < 60: return "%d:%06.3f" % (m, s % 60)
return "%d:%02d:%06.3f" % (m // 60, m % 60, s % 60) | 5ab95271223ab65d44fce3c09e4f77e51e9be342 | 638,729 |
def get_motion_type(motion_detection_config):
"""Set default type if it is missing."""
if not motion_detection_config.get("type"):
motion_detection_config["type"] = "background_subtractor"
return motion_detection_config | b87f46f10f49a93f10aa0a7efcf530420ff1cef6 | 474,441 |
def get_system_columns(columns):
"""Filters leaderboard columns to get the system column names.
Args:
columns(iterable): Iterable of leaderboard column names.
Returns:
list: A list of channel system names.
"""
excluded_prefices = ['channel_', 'parameter_', 'property_']
return [col for col in columns if not any([col.startswith(prefix) for
prefix in excluded_prefices])] | 024dcdcd9c6327d3ac28a3b1c67bf7daa4953b99 | 647,222 |
def get_embedded(result_object, link_relation):
"""
Given a result_object (returned by a previous API call), return
the embedded object for link_relation. The returned object can be
treated as a result object in its own right.
'result_object' a JSON object returned by a previous API call.
The link relation of the embedded object must have been specified
when the result_object was originally requested. May not be None.
'link_relation' the link relation for which href is required. May
not be None.
Returns None if the embedded object does not exist.
"""
# Argument error checking.
assert result_object is not None
assert link_relation is not None
result = None
embedded_object = result_object.get('_embedded')
if embedded_object:
result = embedded_object.get(link_relation)
return result | a41bb87a1c8a55c7e0be966032fbf959d69bda6e | 674,878 |
def clip(value_before_switch, value_after_switch, t_switch, t):
"""
logical function of time. Changes value at threshold time t_switch.
"""
if t <= t_switch:
return value_before_switch
else:
return value_after_switch | 103a5aede1c1d0589e0acfc9ef058e011813f789 | 34,835 |
def take(src, idx):
"""Generate a list containing the elements of src of which the index is contained in idx
Parameters
----------
src: list (size: n)
Source iterable from which elements must be taken
idx: iterable (subtype: int, range: [0, n[, size: m)
Indexes iterable
Returns
-------
list: list
The list of taken elements
"""
return [src[i] for i in idx] | 4cfa42f8d4d5ec605633014823b27d2bdc4dd5ff | 499,498 |
def n_interactions(nplayers, repetitions):
"""
The number of interactions between n players
Parameters
----------
nplayers : integer
The number of players in the tournament.
repetitions : integer
The number of repetitions in the tournament.
Returns
-------
integer
The number of interactions between players excluding self-interactions.
"""
return repetitions * (nplayers - 1) | 639d4bd535adba4db9117905ba6da66dfea51df6 | 205,601 |
def format_single_query(query):
"""
Formats the query parameters from a single query.
Parameters
----------
query : str
MongoDB-stype query.
Returns
-------
str
Query parameters.
"""
return f'?where={query}' | b2b7a30fa34a9ac2a2f41a10d018e69567ab923a | 408,642 |
from datetime import datetime
def unix_epoch_to_datetime(ux_epoch):
"""Convert number of seconds since 1970-01-01 to `datetime.datetime`
object.
"""
return datetime.utcfromtimestamp(ux_epoch) | 13edceec1631a2a3db06dad215380f609693f441 | 698,133 |
from typing import Union
import logging
def _level_to_int(level: Union[str, int]) -> int:
"""Convert a log level in str or int into an int.
Args:
level: Can be a string or int
Returns:
level as int.
"""
if not isinstance(level, int):
level = logging.getLevelName(level.upper())
# In rare cases it might be false, but it shouldn't generally happen.
if not isinstance(level, int):
raise ValueError(f"Unknown level {level!r}.")
return level | 296529cb2160d94310da8a83d993e1e85fd4c354 | 596,434 |
def format_component_descriptor(name, version):
"""
Return a properly formatted component 'descriptor' in the format
<name>-<version>
"""
return '{0}-{1}'.format(name, version) | 2edb92f20179ae587614cc3c9ca8198c9a4c240e | 707,804 |
def get_foot_trajectory(data, header, foot):
"""Get the trajectory of the foot translations."""
tx = header.index(foot + "_tx")
ty = header.index(foot + "_ty")
tz = header.index(foot + "_tz")
return data[:, [tx, ty, tz]] | 4da8b4e947f3e3af6d7e39a11bdac7ad91a1715b | 258,167 |
def parse_tree_to_sql_where(parse_tree):
"""
Walks a parse tree of a filter expression and generates a Postgres WHERE
clause from it
"""
def next_element():
if len(parse_tree) > 0:
return parse_tree.pop(0)
where_clause = '('
cur = next_element()
while cur:
if isinstance(cur, str):
where_clause += str(cur)
if len(parse_tree) > 0:
where_clause += ' '
else:
if 'token_type' in cur and cur['token_type'] in ('fieldname', 'value'):
if cur['token_type'] == 'fieldname':
where_clause += 'data->>\'' + str(cur[0]) + '\''
else:
where_clause += str(cur[0])
if len(parse_tree) > 0:
where_clause += ' '
else:
where_clause += parse_tree_to_sql_where(cur)
if len(parse_tree) > 0:
where_clause += ' '
cur = next_element()
where_clause += ')'
return where_clause | de1ded97a876c7174037965160eed21c8530a10b | 401,836 |
def clean_state(state: str) -> str:
"""
Republica Virtual API returns a different state value when searching
for a district address. (i.e. "RO - Distrito" for 76840-000).
So let's clean it!
"""
return state.split(" ")[0].strip() | 8f6987ade1ea4cedc3d33593cd8077268a84d00e | 541,763 |
def read_def_file(def_file):
"""Read variables defined in def file."""
ret = {}
f = open(def_file, 'r')
for line_ in f:
if line_.startswith("#"):
continue
line = line_.rstrip()
if len(line) == 0:
continue
if "=" not in line:
continue
var_and_val = line.split("=")
var = var_and_val[0]
val = var_and_val[1].split()[0]
ret[var] = val
f.close()
return ret | 3999378bca9ad4cdccaa480a50635ad567473c66 | 693,905 |
def surfaceTension(T, sTP):
"""
surfaceTension(T, sTP)
surfaceTension (dyne/cm) = A*(1-T/critT)^n
Parameters
T, temperature in Kelvin
sTP, A=sTP[0], critT=sTP[1], n=sTP[2]
A and n are regression coefficients, critT: critical temperature
Returns
surface tension in dyne/cm at T
"""
return sTP[0]*(1-T/sTP[1])**sTP[2] | 24980f54d9bd4760da44d3c453ac422f916917cc | 472,539 |
def merge_histos ( h1 , h2 ) :
"""Simple ``merger'' for historgams"""
if not h1 : return h2
h1.Add ( h2 )
return h1 | a0196a91a275ceca8689b3f70c4197ab674ed37a | 509,771 |
def make_adjlist(vertices, edges):
"""
Args:
vertices (List(int)): vertices of the graph
edges (List(tuple(int, int))): edges of the graph
Returns:
dict(int, List(int)): Adjacency list of thr graph
"""
adjlist = dict(zip(vertices, [[] for vertex in vertices]))
for u, v in edges:
adjlist[u].append(v)
return adjlist | ceb461666e0a8084a80d81aeda08a5a154d2cc56 | 448,554 |
import unicodedata
def is_latin(text):
"""
Function to evaluate whether a piece of text is all Latin characters, numbers or punctuation.
Can be used to test whether a search phrase is suitable for parsing as a fulltext query, or whether it
should be treated as an "icontains" or similarly language independent query filter.
"""
return all(
[
(
"LATIN" in unicodedata.name(x)
or unicodedata.category(x).startswith("P")
or unicodedata.category(x).startswith("N")
or unicodedata.category(x).startswith("Z")
)
for x in text
]
) | e804ffd688a8713e1e4362ac7fbb868a6dbff45c | 131,759 |
def change_eigen_param(self, param_name, new_value):
"""
Used to change a param in eigen params area.
Parameters
----------
param_name : str
name of parameter to change
new_value : ?
the new value to the parameter
Returns
-------
True if successful
"""
if param_name in self.eigen_params:
self.eigen_params[param_name] = new_value
self.global_params["need_recalc_eigen_params"] = True
# self.save_new_param_json()
return True
else:
return False | 2dc9d97fe154ce6c3a6ccee9c93fe03e9c139d3b | 574,366 |
def _pixel_addr(x, y):
"""Translate an x,y coordinate to a pixel index."""
if x > 8:
x = x - 8
y = 6 - (y + 8)
else:
x = 8 - x
return x * 16 + y | 71a718943663cd1e7f3026f1b51ef6c112a3e59a | 204,029 |
def try_lower(string):
# Ask for, forgiveness seems faster, perhaps better :-)
"""Converts string to lower case
Args:
string(str): ascii string
Returns:
converted string
"""
try:
return string.lower()
except Exception:
return string | 7b48401d4aaf4ae5a99b3a2d9ee5869c07726156 | 630,906 |
def compareNoteGroupings(noteGroupingA, noteGroupingB):
"""
Takes in two note groupings, noteGroupingA and noteGroupingB. Returns True
if both groupings have identical contents. False otherwise.
"""
if len(noteGroupingA) == len(noteGroupingB):
for (elementA, elementB) in zip(noteGroupingA, noteGroupingB):
if elementA != elementB:
return False
return True
return False | 3e48d0bab407e7327b7be20a327434dc1371f575 | 566,046 |
from typing import Dict
from typing import Any
def abi_input_signature(input_abi: Dict[str, Any]) -> str:
"""
Stringifies a function ABI input object according to the ABI specification:
https://docs.soliditylang.org/en/v0.5.3/abi-spec.html
"""
input_type = input_abi["type"]
if input_type.startswith("tuple"):
component_types = [
abi_input_signature(component) for component in input_abi["components"]
]
input_type = f"({','.join(component_types)}){input_type[len('tuple'):]}"
return input_type | e2ed8b9587066b1edcbd3563c8c45ceb64dc1442 | 645,699 |
import math
def get_current_pose(measurement):
"""Obtains current x,y,yaw pose from the client measurements
Obtains the current x,y, and yaw pose from the client measurements.
Args:
measurement: The CARLA client measurements (from read_data())
Returns: (x, y, yaw)
x: X position in meters
y: Y position in meters
yaw: Yaw position in radians
"""
x = measurement.player_measurements.transform.location.x
y = measurement.player_measurements.transform.location.y
yaw = math.radians(measurement.player_measurements.transform.rotation.yaw)
return (x, y, yaw) | 42c5ba8a79de5ee9e46a7b72e62e0b63a4ec4c66 | 242,123 |
import torch
def create_simple_image(size, batch=1):
"""
returns a simple target image with two and a seeds mask
"""
sizex, sizey = size
target = torch.zeros(batch, 1, sizex, sizey).long()
target[:, :, :, sizey//2:] = 1
seeds = torch.zeros(batch, sizex, sizey).long()
seeds[:, 3 * sizex//4, 5] = 1
seeds[:, sizex//4, sizey - 5] = 2
return seeds, target | d05cf2febe9e7f4fbc94288521696f9c1cae5745 | 500,654 |
def dotget(root, path: str, default=None) -> object:
""" Access an item in the root field via a dot path.
Arguments:
- root: Object to access via dot path.
- path: Every dot path should be relative to the state property.
- default: Default value if path doesn't exist.
Returns: Value. If path does not exist default is returned.
"""
parts = path.split('.')
for part in parts:
try:
if type(root) is list:
root = root[int(part)]
else:
root = root[part]
except KeyError:
return default
return root | 2fa846bf0cc9c4da7927968d0b208f4381470e0c | 347,992 |
def beta_mean(alpha, beta):
"""Calculate the mean of a beta distribution.
https://en.wikipedia.org/wiki/Beta_distribution
:param alpha: first parameter of the beta distribution
:type alpha: float
:param beta: second parameter of the beta distribution
:type beta: float
:return: mean of the beta distribution
:rtype: float
"""
return alpha / (alpha + beta) | 2d730b5693dba71b07347d7564fed26d0182af7b | 346,657 |
from pathlib import Path
import re
def matches_filepath_pattern(filepath: Path, pattern: str) -> bool:
"""
Check if filepath matches pattern
Parameters
----------
filepath
The filepath to check
pattern
The pattern to search
Returns
-------
rc
A boolean indicating whether the pattern has been found in the filepath
"""
assert isinstance(filepath, Path) # noqa
result = re.search(pattern, str(filepath))
return True if result is not None else False | dbec77f7302d3ad319a0220ef1f29c14ca093486 | 368,347 |
def get_all_names(obj):
"""
Should return all possible names for object, for example real name of user or food, nick...
:param obj: user or food
:return: list of strings
"""
res = list()
if "name" in dir(obj):
if obj.name is not None:
res.append(obj.name)
if "nick" in dir(obj):
if obj.nick is not None:
res.append(obj.nick)
return res | b6b0a879a3d15919813785e70157e1a8f209c654 | 510,233 |
def JtoBTU(eJ):
"""
Convertie l'energie en Joules vers Btu
Conversion: 1 Btu = 1055 Joules
:param eJ: Energie [J]
:return eBTU: Energie [btu]
"""
eBTU = eJ / 1055
return eBTU | c0720b9ed82715415b6233f09c17411e996be6ae | 184,865 |
import errno
def _maybe_read_file(path):
"""Read a file, or return `None` on ENOENT specifically."""
try:
with open(path) as infile:
return infile.read()
except OSError as e:
if e.errno == errno.ENOENT:
return None
raise | 40a6b89eeb4acb9ef3bb5244ba54a86d8ec64efc | 148,391 |
def validated_slot_value(slot):
"""return a value for a slot that's been validated."""
if slot is not None:
for resolution in slot['resolutions']['resolutionsPerAuthority']:
if 'values' in resolution:
return resolution['values'][0]['value']['name']
return None | edef74d5eedb5f15579992c8762114439f399577 | 425,867 |
def count_lines(fasta_file):
"""
Counts number of lines in a fasta file
:param (str) filename: FASTA file
:return (int): number of lines in file
"""
return sum(1 for line in open(fasta_file)) | db3eeff277cbd7291c265ad9a21bb07645b9a24d | 327,156 |
def get_org_name(organisation):
"""Get short name for organisation (--> org.)."""
if organisation.endswith("organisation") or organisation.endswith("organization"):
return organisation[:-9] + "."
else:
return organisation | 7471100d5eba7b12fda080a7c74440d1976baffa | 477,812 |
def get_years(ncfiles, sep='-'):
"""
Retrieve a list of years from a list of netCDF filenames.
Parameters
----------
ncfiles : list
List of filenames from which years will be extracted.
sep : TYPE, optional
Separator. The default is '-'.
Returns
-------
years : set
List of years.
"""
years = set([str(f).split(sep)[-1][:4] for f in ncfiles])
return years | 101424ab4d0d6958097dae63c7afced1dc676b75 | 495,922 |
import glob
def get_image_paths(dataset='cars'):
"""
Loads image paths for selected dataset.
:param dataset: Dataset that should be loaded. ['cars', 'notcars']
:return: Path list
"""
path_list = []
if dataset == 'cars':
print('Loading data set for \'cars\'...')
# GTI
path = 'data/vehicles/GTI*/*.png'
paths = glob.glob(path)
print(path)
print('\t{} elements'.format(len(paths)))
path_list += paths
# KITTI
path = 'data/vehicles/KITTI*/*.png'
paths = glob.glob(path)
print(path)
print('\t{} elements'.format(len(paths)))
path_list += paths
elif dataset == 'notcars':
print('Loading data set for \'notcars\'...')
# GTI
path = 'data/non-vehicles/GTI*/*.png'
paths = glob.glob(path)
print(path)
print('\t{} elements'.format(len(paths)))
path_list += paths
# Udacity data
path = 'data/non-vehicles/Extras/*.png'
paths = glob.glob(path)
print(path)
print('\t{} elements'.format(len(paths)))
path_list += paths
# Manually extracted data
path = 'data/non-vehicles/Extracted/*.png'
paths = glob.glob(path)
print(path)
print('\t{} elements'.format(len(paths)))
path_list += paths
else:
raise Exception('There are only two possible choices for c: \'cars\' and \'notcars\'')
return path_list | e644fa7a8d83b5bf27375b9558f317ff0ed9e2c8 | 92,089 |
def is_event_match_for_list(event, field, value_list):
"""Return if <field> in "event" match any one of the value
in "value_list" or not.
Args:
event: event to test. This event need to have <field>.
field: field to match.
value_list: a list of value to match.
Returns:
True if <field> in "event" match one of the value in "value_list".
False otherwise.
"""
try:
value_in_event = event['data'][field]
except KeyError:
return False
for value in value_list:
if value_in_event == value:
return True
return False | 3e6e14391d04a566933be829fcbd8d0fd089e98b | 174,465 |
def writeContactPoint(cp):
"""Writes a contact point to text 'x1 x2 x3 n1 n2 n3 kFriction'"""
return ' '.join([str(v) for v in cp.x+cp.n+[cp.kFriction]]) | 49f54e04c29d87acb662d81da385ca409e7bd959 | 519,320 |
def calculate_residuals(fit_function,a,xdata,ydata):
"""Given the fit function, a parameter vector, xdata, and ydata returns the residuals as [x_data,y_data]"""
output_x=xdata
output_y=[fit_function(a,x)-ydata[index] for index,x in enumerate(xdata)]
return [output_x,output_y] | 1996a0782baa3e95a97d34324b22584a852179a8 | 244,033 |
def string_to_int(value):
"""Converts a string to an integer
Args:
value(str): string to convert
Return:
The integer representation of the nummber. Fractions are truncated. Invalid values return None
"""
ival = None
try:
ival = float(value)
ival = int(ival)
except Exception:
pass
return ival | d9b251be776d721d25ec35bf7fa558e4e3b68f00 | 660,904 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.