content stringlengths 42 6.51k |
|---|
def levenshtein(a, b):
"""
Calculate the Levenshtein distance between `a` and `b`.
Args:
a (str): Original word.
b (str): Decoded word.
Returns:
float: Levenshtein distance.
"""
n, m = len(a), len(b)
if n > m:
# Make sure n <= m, to use O(min(n,m)) space
... |
def ext_from_method(method):
"""
Returns an appropriate file extension for a given model serialization method.
Parameters
----------
method : str
The return value of `method` from ``serialize_model()``.
Returns
-------
str or None
Filename extension without the leading ... |
def scalar(typename):
"""
Returns unbounded scalar type from ROS2 message data type
Like "uint8" from "uint8[]", or "string" from "string<=10[<=5]".
Returns type unchanged if not a collection or bounded type.
"""
if "[" in typename: typename = typename[:typename.index("[")]
if "<=" in type... |
def sometrue(*args, **kwargs):
"""
Check whether some values are true.
Refer to `any` for full documentation.
See Also
--------
any : equivalent function; see for details.
"""
return any(*args, **kwargs) |
def autodec(fwhm):
"""
Automatically calculates the appropriate decimal place to track based on a full-width-at-half-maximum
:param fwhm: full-width-at-half-maximum
:return: decimal power
:rtype: int
"""
shift = fwhm
n = 0
while shift < 1.:
n += 1
shift = fwhm * 10 *... |
def solve(t):
"""
receive the input part of the testing data and
determine the output
"""
# declare and initialise variables
current = 0
highest = 0
grid = [[]]
# iterate over the input and find the 3x3 grid with the highest sum
for i in range(len(t)-2):
for j i... |
def wang_sun(XYZ, t, a=0.2, b=-0.01, c=1, d=-0.4, e=-1, dz=-1):
"""
The Wang-Sun Attractor.
x0 = (0.1,0.1,0.1)
"""
x, y, z = XYZ
x_dt = a * x + c * y * z
y_dt = b * x + d * y - x * z
z_dt = e * z + dz * x * y
return x_dt, y_dt, z_dt |
def int_to_bcd(integer):
"""Converts a two-digit, non-negative integer (0-99) to a one-byte
binary coded decimal.
:param: the integer value as a Python `int`.
:returns: the 1-byte binary-coded decimal as a Python `int`.
"""
assert(0 <= integer and integer <= 99)
ones = integer % 10
tens... |
def to_float(seq):
"""
Takes an arguement seq, tries to convert each value to a float and returns the result. If a value cannot be
converted to a float, it is replaced by 'nan'.
Parameters
----------
seq : array-like
The input object.
Returns
-------
subseq : array_like
... |
def _construct_key(previous_key, separator, new_key):
"""
Returns the new_key if no previous key exists, otherwise concatenates previous key, separator, and new_key
:param previous_key:
:param separator:
:param new_key:
:return: a string if previous_key exists and simply passes through the new_k... |
def task_dict_to_list(iterator, total_parts, partition_num):
"""
Convert a dictionary to a list to be used as partitions later.
:param iterator:
:param total_parts:
:param partition_num:
:return:
"""
ret = list()
sorted_keys = sorted(iterator.keys())
total = len(sorted_keys)
... |
def gamma_from_alpha(alpha):
"""
Adiabatic index from spectral index, Sedov-Taylor expansion.
Parameters
----------
alpha : spectral index
"""
gamma = (4./5)*(2.*alpha + 1.)
return gamma |
def parse_ingredients(raw_ingredients):
"""Parse individual ingredients from ingredients form data."""
ingredients = []
for ingredient in raw_ingredients.split("\r\n"):
if ingredient:
ingredients.append(ingredient)
return ingredients |
def _lenient_lowercase(lst):
"""Lowercase elements of a list.
If an element is not a string, pass it through untouched.
"""
lowered = []
for value in lst:
try:
lowered.append(value.lower())
except AttributeError:
lowered.append(value)
return lowered |
def _image_name_from_key(agent_key: str) -> str:
"""Generate docker image name from an agent key.
Args:
agent_key: agent key in the form agent/organization/name.
Returns:
image_name: image name in the form : agent_organization_name.
"""
return agent_key.replace('/', '_').lower() |
def handle_negations(tweet_tokens, lexicon_scores):
"""
Handling of negations occuring in tweets -> shifts meaning of words
-> if a negation was found the polarity of the following words will change
Parameters
----------
tweet_tokens : List
list of tweet tokens that were already prepocessed (... |
def convert_tags(tags) -> list:
"""
Convert list entries after fetching it from the database.
This function takes a serialized list entry for tags and deserializes it
to return a Python list.
"""
result = [tag.decode('utf-8') for tag in tags.split(b'|')]
if result is None:
return []... |
def _apply_constraint_killers(constraints):
"""Filter out constraints that have a killer."""
killers, real_constraints = set(), []
for constr in constraints:
if "kill" in constr and len(constr) == 1:
killers.add(constr["kill"])
else:
real_constraints.append(constr)
... |
def getParameters(methods):
"""
:param methods:
:return:
"""
"""
data = [] #
for key,val in self.iteritems():
calls = int(10*random())#val._calls
fails = int(10*random())#val._fails
means = 10*random()#val._means
if val._ref is not No... |
def context_from_mentions(mentions):
"""Returns IDs of medical concepts that are present."""
return [m['id'] for m in mentions if m['choice_id'] == 'present'] |
def _adjacency_adjust(adjacency, adjust, is_directed):
"""Takes an adjacency list and returns a (possibly) modified
adjacency list.
"""
for v, adj in adjacency.items():
for properties in adj.values():
if properties.get('edge_type') is None:
properties['edge_type'] = ... |
def set_default(d, v=None):
"""Set variable default value.
Args:
d: default value.
v: current value.
Args:
d if v is None.
"""
if type(None) == type(v):
return d
return v |
def vector_subtract(v, w):
"""subtrai elementos correspondentes"""
return [v_i - w_i
for v_i, w_i in zip(v, w)] |
def ascii_digits(string):
"""
Convert string to digits based on ASCII codes.
>>> ascii_digits('a') # same as ord('a')
97
>>> ascii_digits('ab')
9798
>>> ascii_digits('abc')
979899
:type string: str
:rtype: int
"""
return int(''.join([str(ord(c)) for c in string])) |
def hints(s):
"""return the hints for this command"""
if s == 'hello':
# string, color, bold
return (' World', 35, False)
return None |
def diviseLignes(prog):
""" Divise une chaine de caracteres par ligne, retourne un tableau ou chaque element est une ligne de prog """
liste = []
ligne = ""
i = 0
while i < len(prog):
if prog[i] == '\n': # Si on rencontre un saut de ligne.
# if ligne != "": # Et si cett... |
def get_item(dictionary, key):
"""
Very simple template filter to be able to easily get an item from 'dictionnary' using given 'key'
Usage:
{{ mydict|get_item:'foo' }}
"""
return dictionary.get(key) |
def explode_dep_versions(s):
"""
Take an RDEPENDS style string of format:
"DEPEND1 (optional version) DEPEND2 (optional version) ..."
and return a dictonary of dependencies and versions.
"""
r = {}
l = s.split()
lastdep = None
lastver = ""
inversion = False
for i in l:
... |
def a_function(my_arg, another):
"""
This is the brief description of my function.
This is a more complete example of my function. It can include doctest,
code blocks or any other reST structure.
>>> a_function(10, [MyClass('a'), MyClass('b')])
20
:param int my_arg: The first argument of ... |
def bad_input (input):
"""
Validates if it's a valid input
"""
return (input is None) or len(input) < 1 |
def string_as_bool_or_none(string):
"""
Returns True, None or False based on the argument:
True if passed True, 'True', 'Yes', or 'On'
None if passed None or 'None'
False otherwise
Note: string comparison is case-insensitive so lowecase versions of those
function equivalently.
... |
def pure_list(comma_list):
"""
Transform a list with items that can be comma-separated strings, into
a pure list where the comma-separated strings become multiple items.
"""
pure_items = []
for comma_item in comma_list:
for item in comma_item.split(','):
pure_items.append(ite... |
def stress(f_normal,A):
"""variables:
sigma=stress
f_normal=force
a=area"""
sigma = f_normal/A
return sigma |
def remove_missingalt(line):
"""Remove lines that are missing an alternative allele.
During cleanup of extra alleles, bcftools has an issue in complicated cases
with duplicate alleles and will end up stripping all alternative alleles.
This removes those lines to avoid issues downstream.
"""
if ... |
def sort_by(tuple_like):
"""
https://stackoverflow.com/questions/24579202/
? scaling issues
"""
return (-tuple_like[1], tuple_like[0]) |
def clean_url(url):
"""
Reformat a URL with all querystrings stripped
:param url: The URL
:return: A clean URL
"""
return url[:url.find('?')] |
def is_numeric(literal):
"""Return whether a literal can be parsed as a numeric value"""
castings = [int, float, complex,
lambda s: int(s,2), #binary
lambda s: int(s,8), #octal
lambda s: int(s,16)] #hex
for cast in castings:
try:
cast(literal)
return... |
def pl_true_int_repr(clause, model={}):
"""Lightweight version of pl_true.
Argument clause represents the set of args of an Or clause. This is used
inside dpll, it is not meant to be used directly.
>>> pl_true_int_repr({1, 2}, {1: False})
>>> pl_true_int_repr({1, 2}, {1: False, 2: False})
Fals... |
def sign(x):
"""Returns 1 if the argument is positive, -1 else"""
return (x>=0)*2-1 |
def fnv1a_64(data):
"""
Hashes a string using 64bit fnv1a: http://isthe.com/chongo/tech/comp/fnv/
"""
r = 0xcbf29ce484222325
mh = 2 ** 64
for i in data:
r = r ^ ord(i)
r = (r * 0x100000001b3) % mh
return r |
def remove_leading_zeros(numeric_string):
"""
>>> remove_leading_zeros("0033")
'33'
"""
ret_val = numeric_string.lstrip("0")
return ret_val |
def _fix_tups(x):
"""Return x[0] if x is a single element tuple, else return x."""
if isinstance(x, tuple) and len(x) == 1:
return x[0]
return x |
def given_power(n, ef_power):
"""
Calculate and return the value of given power using given values of the params
How to Use:
Give arguments for efficiency and ef_power parameters
*USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE
IT'LL BE HARD TO UNDERSTAND AND USE.'
Parameters:
... |
def middle(items: list):
"""Return middle item in list."""
length = len(items) // 2
return items[length] |
def condense_meeting_times(times):
"""
This takes a list of times and returns an organized list with all
overlapping times ommited.
parameters:
list of (start_time, end_time) tuples
return:
list of tuples
"""
# Let python sort, most effeciently. This yields an easy
# wa... |
def mrs_function(x):
""" Return mapped mRS value.
:param x: the index of answer from the form, eg. first option of select has index 1 etc.
:type x: int
:returns: the converted mRS score
:rtype: int
"""
x = float(x)
if (x == 1):
x = x - 1
else:
x = x - 2
r... |
def chash(cycles):
"""
Hash a cycle, useful for comparing sets of cycles.
This checks the sorted set of each of the nodes in the cycle. This
is *not* a perfect check, but it's useful so that we can create a set
of these hashes, and check that they all match.
It's not perfect, since D -> A -> B... |
def make_quick_reply_item(action,
url=None,
image_resource_id=None,
i18n_thumbnail_image_urls=None,
i18n_image_resource_ids=None):
"""
Create quick reply message item.
reference
- `Common Mes... |
def Get_IOState_downstream(topo, end_TM):#{{{
"""
Get inside/outside state for the loop after the current TM helix
Input:
topo topology sequence of the protein
end_TM sequence position at the end of the TM helix
(begin_TM, end_TM) defines the location of the T... |
def test_divisibleby(value, num):
"""Check if a variable is divisible by a number."""
return value % num == 0 |
def is_dict(s):
"""
Returns True if the given object has dict type or False otherwise
:param s: object
:return: bool
"""
from collections import OrderedDict
return type(s) in [dict, OrderedDict] |
def get_broken_limbs(life):
"""Returns list of broken limbs."""
_broken = []
for limb in life['body']:
if life['body'][limb]['broken']:
_broken.append(limb)
return _broken |
def replace_vars(var, rhs):
"""Replace the variables on the right hand side of the equation
>>> d = {'a': 23.3}
>>> replace_vars(d, "12 + a * 2")
'12 + 23.3 * 2'
"""
rhs = rhs.split()
for i, x in enumerate(rhs):
if x in var:
rhs[i] = str(var[x])
return " ".join(rhs) |
def remove_list_format(l):
"""Removes brackets, and quotes"""
return str(l).replace("'", '')[1:-1] |
def obj_box_coord_centroid_to_upleft_butright(coord, to_int=False):
"""Convert one coordinate [x_center, y_center, w, h] to [x1, y1, x2, y2] in up-left and botton-right format.
Parameters
------------
coord : list of 4 int/float
One coordinate.
to_int : boolean
Whether to convert ou... |
def judgeFace1(FaceID, FaceDB, CurvatureDB, Threshold = 0):
"""Check whether a face satisfies the zero-order criterion
If all three vertexes of a face have negative curvature, return True. O/w, False.
Input
======
FaceID: integer
the ID of a face, indexing from 0
Face... |
def liangbarsky(left, top, right, bottom, x1, y1, x2, y2):
"""Clips a line to a rectangular area.
This implements the Liang-Barsky line clipping algorithm. ``left``,
``top``, ``right`` and ``bottom`` define the bounds of the clipping area,
by which the line from ``(x1, y1)`` to ``(x2, y2)`` will be cli... |
def min_number_in_rotated_array(r_nums):
"""
:param r_nums:rotated arrat
:return: min number
"""
if not r_nums:
return None
left = 0
right = len(r_nums)-1
while left < right:
mid = (left + right) // 2
if r_nums[mid] == r_nums[right] == r_nums[left]:
ri... |
def tohex(value):
"""Return repr in hex"""
try:
value = int(value)
except TypeError:
return "Unrecognized Number"
return "%x" % value |
def threshold_phased_variant_counts(counts_dict, min_count):
"""
Choose set of phased variants by keeping any variants with associated
counts greater than or equal the given threshold.
Parameters
----------
counts_dict : variant -> int dict
min_count : int
Returns
-------
set ... |
def _bump_release(release, bump_type):
"""Return a bumped release tuple consisting of 3 numbers."""
major, minor, patch = release
if bump_type == "patch":
patch += 1
elif bump_type == "minor":
minor += 1
patch = 0
elif bump_type == "major":
major += 1
minor =... |
def is_subset_dict(dict_to_test, master_dict):
"""
Checks if a dictionary is a subset of another dictionary
Args:
dict_to_test (dict): The subset dictionary
master_dict (dict): The dictionary to test against
Returns:
bool: Whether or not the first dictionary is a subset of the s... |
def replace_multiple(main_string, to_be_replaced, new_string):
"""replace extra elements in a text string"""
for elem in to_be_replaced :
if elem in main_string :
main_string = main_string.replace(elem, new_string)
return main_string |
def overlap(span, spans):
"""Determine whether span overlaps with anything in spans."""
return any(
start <= span[0] < end or start < span[1] <= end
for start, end in spans
) |
def _merge_dicts(*dict_args):
"""Merge the given dictionaries into single dict.
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
From http://stackoverflow.com/a/26853961/1706640
"""
result = {}
for dictionary in dict_arg... |
def limit(value, min_val, max_val):
"""Return a value clipped to the range [min_val, max_val]."""
return max(min_val, min(value, max_val)) |
def link_cmd(path, link):
"""Returns link creation command."""
return ['ln', '-sf', path, link] |
def copy_dict(source, dest):
"""
Populates a destination dictionary with the values from the source
:param source: source dict to read from
:param dest: destination dict to write to
:returns: dest
:rtype: dict
"""
for name, value in source.items():
dest[name] = value
retur... |
def my_tuple(a: int, b: float, c: complex):
"""
>>> my_tuple.cmd("10 14.1 5-2j")
(10, 14.1, (5-2j))
>>> my_tuple.cmd(["14j 13j 10"])
Traceback (most recent call last):
...
SystemExit: 2
"""
return (a, b, c) |
def get_firstday_of_month(date):
"""''
date format = "YYYY-MM-DD"
"""
year, month, day = date.split("-")
year, month, day = int(year), int(month), int(day)
days = "01"
if int(month) < 10:
month = "0" + str(int(month))
arr = (year, month, days)
return "-".join("%s" % i for i... |
def add_prefix(key):
"""Dummy key_function for testing index code."""
return "id_" + key |
def string_reverser(our_string):
"""
Reverse the input string
Args:
our_string(string): String to be reversed
Returns:
string: The reversed string
"""
# New empty string for us to build on
new_string = ""
# Iterate over old string
for i in range(len(our_string)):
... |
def tag_empty_items(list):
"""
Replace empty strings in list by strings of integers starting with 1.
Replaces empty string items in the input list by strings of subsequent
integers starting with '1'. This allows addressing items before and
after what are originally empty strings easily using the in... |
def select_dataset(features, parameters, methods, processing_codes, owners, aggregation_statistics, frequency_intervals, utc_offsets, datasets):
"""
"""
dataset = [d for d in datasets if (d['feature'] == features) and (d['parameter'] == parameters) and (d['method'] == methods) and (d['owner'] == owners) an... |
def get_skin_name(object_name=""):
"""
creates a new skin cluster name from the object provided.
:param object_name: <str> object name to get the name frOpenMaya.
:return: <str> new skin name.
"""
return object_name + '_Skin' |
def splitPoints(clusterA, clusterB, Z):
"""
Splits points in the original cluster
between the old and the new clusters
clusterA - new
clusterB - old
"""
if len(clusterB) == 1:
return None
index = None
maxDiff, idx = 0, 0
for i in clusterB:
sumdistT... |
def WorldFromEyeMatrixFromFace(face_name):
"""Creates world-from-eye matrix for the given face of a cube map.
Args:
face_name: Name of the face. Must be one of 'front', 'back', 'left',
'right', 'bottom', 'top'.
Returns:
The world-from-eye matrix for the given face as a list in row-major order.
... |
def readonly_safe_field_as_table_row(field_label, field_value):
"""See readonly_field_as_table_row().
"""
return {'field_label': field_label,
'field_value': field_value} |
def lmax_modes(lmax):
"""Compute all (l, m) pairs with 2<=l<=lmax"""
return [(l, m) for l in range(2, lmax + 1) for m in range(-l, l + 1)] |
def convert_special_value(value):
"""Convert to special value."""
if value == "NULL":
return None
elif value == "EMPTY":
return ""
else:
return value |
def mulf(*vars):
"""ggd
>>> mulf(1, 2)
2
>>> mulf(1,2,3,4)
24
"""
v = 1
for i in vars:
v *= i
return v |
def parse_params(param_str):
"""
Convert a string of the form name='value', ... into a dictionary. Leading
and trailing spaces are stripped, as are line-feed, carriage-return, tab,
single-quote and double-quote characters.
"""
params = {}
for param in param_str.split(','):
dirty = p... |
def filter_by_ids(original_list, ids_to_filter):
"""Filter a list of dicts by IDs using an id key on each dict."""
if not ids_to_filter:
return original_list
return [i for i in original_list if i['id'] in ids_to_filter] |
def auto_type(string):
"""
Try and convert a string to an integer or float
"""
try:
return int(string)
except:
try:
return float(string)
except:
return string |
def get_str(obj, field, length):
"""
Obtain the str value,
:param obj:
:param length:
:return:
"""
value = obj.get(field)
if value is not None:
value = str(value)[:length]
return value |
def validarCNum(pnum, pcan):
"""
Funcion: Valida si el dato ingresado es un numero con len segun lo pedido
Entradas: `pnum`(str) y `pcan`(int) valor a analizar
Salida: Booleano True/False segun las especificaciones
"""
try:
pnum = abs(int(pnum))
if len(str(pnum)) == pcan:
... |
def pos_obs_from_sig(read_sig):
"""
Returns a list of position, observation pairs described in the read
signature string.
"""
def pos_obs(var):
""" Splits var into a int position and a string base. """
pos, obs = var.split(':')
return int(pos), obs
return [pos_obs(var) fo... |
def is_int(s):
"""
Short helper for duration conversion.
"""
try:
int(s)
except (ValueError, TypeError):
return False
else:
return True |
def remove_suffix(text, suffix):
"""
Remove the suffix from the text if it exists.
>>> remove_suffix('name.git', '.git')
'name'
>>> remove_suffix('something special', 'sample')
'something special'
"""
rest, suffix, null = text.partition(suffix)
return rest |
def spec_str(spec):
"""
Change a spec to the json object format used in mongo.
eg. Print dict in python gives: {'a':'b'}
mongo shell would do {a:'b'}
Mongo shell can handle both formats but it looks more like the
official docs to keep to their standard.
:param spec: Dictionary. A... |
def prep_sub_id(sub_id_input):
"""Processes subscription ID
Args:
sub_id_input: raw subscription id
Returns:
Processed subscription id
"""
if not isinstance(sub_id_input, str):
return ""
if len(sub_id_input) == 0:
return ""
return "{" + sub_id_input.strip... |
def calculate_elo(R1, R2, S, k=32):
"""
Args:
R1 (float): current rating of the first song
R2 (float): current rating of the second song
S (int): 1 for a win, 0 for a loss
k (float): decides how much the elo rating fluctuates
Returns:
float: the newly calculated el... |
def make_item_description(description, numerator, denominator):
"""
Makes an item description giving a number and a percentage based on the
given numerator and denominator.
"""
return "<b>{} ({:.0%})</b> {}\n".format(
numerator, numerator / denominator, description) |
def contains_lua_calls(item):
"""Check if a node contains any Lua API calls"""
if 'lua_' in item['tokens']:
return True
if 'luaL_' in item['tokens']:
return True
if 'LuaSkin' in item['tokens']:
return True
return False |
def create_code(traits):
"""Assign bits to list of traits.
"""
if not traits:
return {}
result = {}
code = 1
for trait in traits:
result[trait] = code
code = code << 1
return result |
def get_caselessly(dictionary, sought):
"""Find the sought key in the given dictionary regardless of case
>>> things = {'Fred' : 9}
>>> print(get_caselessly(things, 'fred'))
9
"""
try:
return dictionary[sought]
except KeyError:
caseless_keys = {k.lower(): k for k in dictiona... |
def rands(n):
"""Generates a random alphanumeric string of length *n*"""
from random import Random
import string
return ''.join(Random().sample(string.ascii_letters + string.digits, n)) |
def _dot_one(version):
"""Returns the version with an appended '.1-signed' on it."""
return u'{0}.1-signed'.format(version) |
def _DecompressLines(line_ranges): # pragma: no cover.
"""Decompress the lines data to a flat format.
For example:
[
{
"count": 1,
"first": 165, // inclusive
"last": 166 // inclusive
}
]
After decompressing, it becomes:
[
{
"line": 165,
"count": 1
},
{
... |
def _get_lemma_names(sub_synset, use_definitions=False):
"""Get lemma names."""
results = []
if sub_synset():
for v in sub_synset():
if hasattr(v.lemma_names, '__call__'):
results += v.lemma_names()
else:
results += v.lemma_names
if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.