content
stringlengths 42
6.51k
|
---|
def lookup_key_path(job, obj, path):
"""
Get the item at the given path of keys by repeated [] lookups in obj.
Work around https://github.com/BD2KGenomics/toil/issues/2214
"""
for key in path:
obj = obj[key]
return obj
|
def normalize_option_name(name):
"""Use '-' as default instead of '_' for option as it is easier to type."""
if name.startswith("--"):
name = name.replace("_", "-")
return name
|
def transform_misses(record):
"""Format the missed datasets record we got from the database to adhere to the response schema."""
response = {}
response["datasetId"] = dict(record).get("stableId")
response["internalId"] = dict(record).get("datasetId")
response["exists"] = False
# response["datasetId"] = ''
response["variantCount"] = 0
response["callCount"] = 0
response["sampleCount"] = 0
response["frequency"] = 0
response["numVariants"] = 0
response["info"] = {"access_type": dict(record).get("accessType")}
return response
|
def sort_imgs(image_list, subject_id, EVAL_TIMES):
"""
Function to extract and group the corresponding images in a list of all images
with names like: Step_30_aligned_reference.jpg
Input:
image_list: Contains all filenames of the images as string
subject_id: id of the respective subject.
Output:
step_pairs: dictionary with all found image pairs corresponding to one step
e.g. {30: [Step_30_aligned_stick.jpg, Step_30_aligned_reference.jpg]}
"""
step_pairs = dict()
for step in EVAL_TIMES:
step_images = []
if step == 120:
try:
step_images.append(next(img for img in image_list if (
img[5:8] == str(step) and img[-13:-4] == "reference")))
step_images.append(next(img for img in image_list if (
img[5:8] == str(step) and img[-9:-4] == "stick")))
step_pairs[step] = step_images
# step_pairs.append(step_images)
except:
print("At least one image not found for: {}.".format(subject_id))
else:
try:
step_images.append(next(img for img in image_list if (
img[5:7] == str(step) and img[-13:-4] == "reference")))
step_images.append(next(img for img in image_list if (
img[5:7] == str(step) and img[-9:-4] == "stick")))
step_pairs[step] = step_images
except:
print("At least one image not found for: {}.".format(subject_id))
return step_pairs
|
def parse_related_content_Descriptor(data,i,length,end):
"""\
parse_related_content_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
Parses a descriptor that identifies that the elementary stream it is part of delivers a
'related content' subtable. The returned dict is:
{ "type" : "related_content" }
(Defined in ETSI TS 102 323 specification)
"""
return { "type" : "related_content" }
|
def splice(alists, recycle = True):
"""
Accepts a list of nonempty lists or indexable objects in
argument alists (each element list may not be of the same
length) and a keyword argument recycle which
if true will reuse elements in lists of shorter length.
Any error will result in an empty list to be returned.
"""
try:
nlists = len(alists)
lens = [len(alist) for alist in alists]
if not recycle:
totlen = sum(lens)
else:
totlen = max(lens) * nlists
pos = [0] * nlists
R = [None] * totlen
i, j = 0, 0
while i < totlen:
if pos[j] < lens[j]:
R[i] = alists[j][pos[j]]
i += 1
pos[j] = pos[j] + 1
if recycle and pos[j] >= lens[j]:
pos[j] = 0
j = (j + 1) % nlists
return R
except:
return []
|
def signed_leb128_decode(data) -> int:
"""Read variable length encoded 128 bits signed integer.
.. doctest::
>>> from ppci.utils.leb128 import signed_leb128_decode
>>> signed_leb128_decode(iter(bytes([0x9b, 0xf1, 0x59])))
-624485
"""
result = 0
shift = 0
while True:
byte = next(data)
result |= (byte & 0x7F) << shift
shift += 7
# Detect last byte:
if byte & 0x80 == 0:
break
if byte & 0x40:
# We have sign bit set!
mask = (1 << shift) - 1
result = result ^ mask
result = -result - 1
return result
|
def get_span_labels(sentence_tags, inv_label_mapping=None):
"""Go from token-level labels to list of entities (start, end, class)."""
if inv_label_mapping:
sentence_tags = [inv_label_mapping[i] for i in sentence_tags]
span_labels = []
last = 'O'
start = -1
for i, tag in enumerate(sentence_tags):
pos, _ = (None, 'O') if tag == 'O' else tag.split('-')
if (pos == 'S' or pos == 'B' or tag == 'O') and last != 'O':
span_labels.append((start, i - 1, last.split('-')[-1]))
if pos == 'B' or pos == 'S' or last == 'O':
start = i
last = tag
if sentence_tags[-1] != 'O':
span_labels.append((start, len(sentence_tags) - 1,
sentence_tags[-1].split('-')[-1]))
return span_labels
|
def getmembers(_object, _predicate):
"""This is an implementation of inspect.getmembers, as in some versions
of python it may be buggy.
See issue at http://bugs.python.org/issue1785"""
# This should be:
# return inspect.getmembers(_object, _predicate)
# ... and it is re-implemented as:
observers = []
for key in dir(_object):
try: m = getattr(_object, key)
except AttributeError: continue
if _predicate(m): observers.append((key, m))
pass
return observers
|
def safe_str(obj, newline='\\n'):
"""This function eliminates newlines and replaces them with the explicit character newline string
passed. Defaults to the showing '\n' explicitly"""
return str(obj).replace('\n', newline)
|
def seq(*sequence):
"""Runs a series of parsers in sequence optionally storing results in a returned dictionary.
For example:
seq(whitespace, ('phone', digits), whitespace, ('name', remaining))
"""
results = {}
for p in sequence:
if callable(p):
p()
continue
k, v = p
results[k] = v()
return results
|
def inv_transform_vertex(x, phi):
"""
Given a vertex id x and a set of partial isomorphisms phi.
Returns the inverse transformed vertex id
"""
for _phi in phi:
if _phi[1] == x:
return _phi[0]
raise Exception('Could not find inverse transformation')
|
def _is_equal_position(first: tuple, second: tuple, position):
"""Whether both position are equal in the given tuples."""
if len(first) > position:
if len(second) > position:
return first[position] == second[position]
return first[position] is None
if len(second) > position:
return second[position] is None
return True
|
def get_resources(name, config):
"""Retrieve resources for a program, pulling from multiple config sources.
"""
return config.get("resources", {}).get(name, {})
|
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
index_map = {}
for i in range(len(nums)):
num = nums[i]
pair = target - num
if pair in index_map:
return [index_map[pair], i]
index_map[num] = i
return None
|
def valid_number(num, default=None, name='integer value', lbound=None, ubound=None):
"""Given a user-provided number, return a valid int, or raise."""
if not num and num != 0:
assert default is not None, "%s must be provided" % name
num = default
try:
num = int(num)
except (TypeError, ValueError) as e:
raise AssertionError(str(e))
if lbound is not None and ubound is not None:
assert lbound <= num and num <= ubound, "%s = %d outside valid range [%d:%d]" % (name, num, lbound, ubound)
return num
|
def multiply_1(factor: int):
"""
Example where input argument has specified variable annotation.
This example is showing how to cast variable. And assert in order to check for any error at the early stage.
:param factor:
:return: results: int
"""
# This will print a data type of this variable e.g. int, float, string.
print(type(factor))
# Casting variable into another data type (Casting is when you convert a variable value from one type to another.)
factor_var = int(factor)
# Check if data type is what we expect to be.
assert type(factor_var) == int
# Return function can return a single variable as well as execute function.
# Return causes the function to stop executing and hand a value back to whatever called it.return causes the
# function to stop executing and hand a value back to whatever called it."
return int(factor_var * 23.233223)
|
def gon2dec(gon):
"""
Converts Gradians to Decimal Degrees
:param gon: Gradians
:type gon: float
:return: Decimal Degrees
:rtype: float
"""
return 9/10 * gon
|
def set_document_cookie_disabled(disabled: bool) -> dict:
"""
Parameters
----------
disabled: bool
Whether document.coookie API should be disabled.
**Experimental**
"""
return {
"method": "Emulation.setDocumentCookieDisabled",
"params": {"disabled": disabled},
}
|
def env_matches(env_name, factor):
"""Determine if an env name matches the given factor.
The env name is split into its component factors, and matches if the given
factor is present in the component factors. Partial matches are not valid.
>>> env_matches('py37-django21', 'py37')
True
>>> env_matches('py37-django21', 'py3')
False
The given factor may also consist of multiple dash-delimited factors, of
which all must be present in the env name.
>>> env_matches('py37-django21-redis', 'py37-redis')
True
Args:
env_name: The tox test env name.
factor: The env factor to match against.
Returns:
Whether the name matches the given factor(s).
"""
env_factors = env_name.split('-')
factors = factor.split('-')
return set(factors).issubset(set(env_factors))
|
def ms_len(data):
"""Implementation of `len`."""
return data.__len__()
|
def is_list_of_strings(lst) -> bool:
"""
Verifies that given parameter is a list of strings
:param lst: list
:return: True if parameter is list of strings
"""
if lst and isinstance(lst, list):
return all(isinstance(elem, str) for elem in lst)
else:
return False
|
def keep_last_and_only(authors_str):
"""
This function is dedicated to parse authors, it removes all the "and" but the last and and replace them with ", "
:param str: string with authors
:return: string with authors with only one "and"
"""
last_author = authors_str.split(" and ")[-1]
without_and = authors_str.replace(" and ", ", ")
str_ok = without_and.replace(", " + last_author, " and " + last_author)
return str_ok
|
def evaluate_query(r, query):
"""
>>> r = {"id": "123", "info": {"name": "bla"}}
>>> evaluate_query(r, {"id": "123"})
True
>>> evaluate_query(r, {"info.name": "bla"})
True
>>> evaluate_query(r, {"info.name": "foo"})
False
"""
if len(query) > 1:
return all([evaluate_query(r, {k: v}) for k, v in query.items()])
key = next(iter(query.keys()))
value = next(iter(query.values()))
if '.' in key:
root = key.split('.')[0]
previous = '.'.join(key.split('.')[1:])
if root not in r:
return False
return evaluate_query(r[root], {previous: value})
try:
return r[key] == value
except KeyError:
return False
|
def generate_repo_name(repo_name):
""" This function for converting general string to github_repo_format_string.
Args:
:param repo_name: repository name.
Returns:
repo_name (str): Return a string as github repository correct format.
"""
return repo_name.replace(" ", "-") # Replace all spaces in name with '-'
|
def dictmax(d):
""" returns key with maximum value in dictionary """
return max(d.keys(), key = lambda x: d[x])
|
def value_to_dni(confidence_value):
"""
This method will transform an integer value into the DNI scale string
representation.
The scale for this confidence representation is the following:
.. list-table:: STIX Confidence to DNI Scale
:header-rows: 1
* - Range of Values
- DNI Scale
* - 0-9
- Almost No Chance / Remote
* - 10-19
- Very Unlikely / Highly Improbable
* - 20-39
- Unlikely / Improbable
* - 40-59
- Roughly Even Chance / Roughly Even Odds
* - 60-79
- Likely / Probable
* - 80-89
- Very Likely / Highly Probable
* - 90-100
- Almost Certain / Nearly Certain
Args:
confidence_value (int): An integer value between 0 and 100.
Returns:
str: A string corresponding to the DNI scale.
Raises:
ValueError: If `confidence_value` is out of bounds.
"""
if 9 >= confidence_value >= 0:
return 'Almost No Chance / Remote'
elif 19 >= confidence_value >= 10:
return 'Very Unlikely / Highly Improbable'
elif 39 >= confidence_value >= 20:
return 'Unlikely / Improbable'
elif 59 >= confidence_value >= 40:
return 'Roughly Even Chance / Roughly Even Odds'
elif 79 >= confidence_value >= 60:
return 'Likely / Probable'
elif 89 >= confidence_value >= 80:
return 'Very Likely / Highly Probable'
elif 100 >= confidence_value >= 90:
return 'Almost Certain / Nearly Certain'
else:
raise ValueError("Range of values out of bounds: %s" % confidence_value)
|
def _format_epilog(commands):
"""Create a epilog string for the specified commands.
Args:
commands: Sequence of (func, name, description)
Returns:
str: Formatted list of commands and their descriptions
"""
lines = []
lines.append("Commands:")
for command in commands:
# Note: desc may be None or wrapped lines
name = command[1]
desc = command[2] or " "
for index, item in enumerate(desc.splitlines()):
item = item.strip()
if index == 0:
line = " %-16s%s" % (name, item)
else:
line = " " * 18 + item
lines.append(line)
return '\r\n'.join(lines)
|
def hill_equation(val, diss_cf, hill_cf):
"""
Hill equation
:param val: input value
:param diss_cf: dissociation coefficient
:param hill_cf: Hill coefficient
:return: Hill equation for input *val*
"""
if val == 0:
return 0
else:
return 1 / (1 + (diss_cf / val) ** hill_cf)
|
def combine_batch_pair(summary_a, summary_b):
"""Combines two batches into one.
:param summary_a: list, of first batch
:param summary_b: list, of second batch
:return: list: PartialSummary, combined data of first and second batch in single list
"""
summary = summary_a # Set first list as base
for friend in summary_b:
if friend not in summary: # If person is not in the base, add it to the base
summary[friend] = summary_b[friend]
else:
summary[friend].add_new_data(
summary_b[friend].speed,
summary_b[friend].distance,
summary_b[friend].transport
)
return summary
|
def _config_path_to_class_and_name(path):
"""
Local helper function that takes a pettingzoo config path and returns it in
the service_class/service_name format expected in this module
"""
path = path.split(".")[0]
parts = path.split("/")
if len(parts) >= 2:
service_class = parts[-2]
service_name = parts[-1]
return service_class, service_name
else:
raise Exception("Config path cannot be parsed: %s" % path)
|
def decode_string(s):
"""
:type s: str
:rtype: str
"""
stack = []; cur_num = 0; cur_string = ''
for c in s:
if c == '[':
stack.append((cur_string, cur_num))
cur_string = ''
cur_num = 0
elif c == ']':
prev_string, num = stack.pop()
cur_string = prev_string + num * cur_string
elif c.isdigit():
cur_num = cur_num*10 + int(c)
else:
cur_string += c
return cur_string
|
def jaccard_score(list1, list2):
"""
Jaccard similarity score
The Jaccard coefficient measures similarity between finite sample sets, and
is defined as the size of the intersection divided by the size of the union
of the sample sets
https://en.wikipedia.org/wiki/Jaccard_index
:param input_gene_list:
:param background_gene_list:
:return:
"""
N = len(set(list1).intersection(list2))
D = len(set(list1).union(list2))
if D == 0:
return 0
else:
return 1.0*N/D
|
def get_full_name(taxid, names_map, ranks_map):
"""
Generate full taxonomic lineage from a taxid
Args:
taxid (str): taxid
names_map (dict[str:str]): the taxonomic names for each taxid node
ranks_map (dict[str:str]): the parent node for each taxid
Returns:
taxonomy (str): full taxonomic lineage string
"""
taxid_lineage = list()
while True:
taxid_lineage.append(taxid)
if taxid not in ranks_map:
break
new_taxid = ranks_map[taxid]
if taxid == new_taxid:
break
else:
taxid = new_taxid
names_lineage = list()
for taxid in taxid_lineage:
name = names_map[taxid]
names_lineage.append(name)
taxonomy = ";".join(reversed(names_lineage))
return taxonomy
|
def adoc_with_preview_command(event=None, verbose=True):
"""Run the adoc command, then show the result in the browser."""
c = event and event.get('c')
if not c:
return None
return c.markupCommands.adoc_command(event, preview=True, verbose=verbose)
|
def _get_jinja_error_slug(tb_data):
"""
Return the line number where the template error was found
"""
try:
return [
x
for x in tb_data
if x[2] in ("top-level template code", "template", "<module>")
][-1]
except IndexError:
pass
|
def one_hot_encode(input_field, output_field, options, function_name, field_prefix=""):
"""
Generates lua lines that One-Hot encodes a field from its possible options
:param input_field: original censys field
:param output_field: flattened version of censys field
:param options: array of the possible values the input field can have
:param function_name: the lua function that will encode the field
:param field_prefix: an optional string to be concatenated at the end of original field
:return:
"""
lines = []
for option in options:
key = option
if type(option) == str:
key = f'"{option}"'
lines.append(
f'event["{output_field}_{field_prefix}{option}"] = {function_name}(event["{input_field}"])[{key}]'
)
return lines
|
def no_embed_link(url: str) -> str:
"""Makes link in discord message display without embedded website preview"""
return f"<{url}>"
|
def poly_func(X):
"""This polynomial was chosen because all of its zeroes (-2, 4, 8) lie in
the x-range we're looking at, so it is quite wiggly"""
return X**3 - 10*X**2 + 8*X + 64
|
def _strip_state_dict_prefix(state_dict, prefix='module.'):
"""Removes the name prefix in checkpoint.
Basically, when the model is deployed in parallel, the prefix `module.` will
be added to the saved checkpoint. This function is used to remove the
prefix, which is friendly to checkpoint loading.
Args:
state_dict: The state dict where the variable names are processed.
prefix: The prefix to remove. (default: `module.`)
"""
if not all(key.startswith(prefix) for key in state_dict.keys()):
return state_dict
stripped_state_dict = dict()
for key in state_dict:
stripped_state_dict[key.replace(prefix, '')] = state_dict[key]
return stripped_state_dict
|
def escaped(val):
""" escapes a string to allow injecting it into a json conf """
val = val.replace('\\', '/')
val = val.replace('"', '\"')
return val
|
def celsius_to_fahr(temp):
"""
Convert Celsius to Fahrenheit.
Parameters
----------
temp : int or double
The temperature in Celsius.
Returns
-------
double
The temperature in Fahrenheit.
Examples
--------
>>> from convertempPy import convertempPy as tmp
>>> tmp.celsius_to_fahr(0)
32
"""
return temp * 9 / 5 + 32
|
def is_chinese_char(uchar):
""" Whether is a chinese character.
Args:
uchar: A utf-8 char.
Returns: True/False.
"""
if uchar >= u'\u3400' and uchar <= u'\u4db5': # CJK Unified Ideographs Extension A, release 3.0
return True
elif uchar >= u'\u4e00' and uchar <= u'\u9fa5': # CJK Unified Ideographs, release 1.1
return True
elif uchar >= u'\u9fa6' and uchar <= u'\u9fbb': # CJK Unified Ideographs, release 4.1
return True
elif uchar >= u'\uf900' and uchar <= u'\ufa2d': # CJK Compatibility Ideographs, release 1.1
return True
elif uchar >= u'\ufa30' and uchar <= u'\ufa6a': # CJK Compatibility Ideographs, release 3.2
return True
elif uchar >= u'\ufa70' and uchar <= u'\ufad9': # CJK Compatibility Ideographs, release 4.1
return True
elif uchar >= u'\u20000' and uchar <= u'\u2a6d6': # CJK Unified Ideographs Extension B, release 3.1
return True
elif uchar >= u'\u2f800' and uchar <= u'\u2fa1d': # CJK Compatibility Supplement, release 3.1
return True
elif uchar >= u'\uff00' and uchar <= u'\uffef': # Full width ASCII, full width of English punctuation, half width Katakana, half wide half width kana, Korean alphabet
return True
elif uchar >= u'\u2e80' and uchar <= u'\u2eff': # CJK Radicals Supplement
return True
elif uchar >= u'\u3000' and uchar <= u'\u303f': # CJK punctuation mark
return True
elif uchar >= u'\u31c0' and uchar <= u'\u31ef': # CJK stroke
return True
elif uchar >= u'\u2f00' and uchar <= u'\u2fdf': # Kangxi Radicals
return True
elif uchar >= u'\u2ff0' and uchar <= u'\u2fff': # Chinese character structure
return True
elif uchar >= u'\u3100' and uchar <= u'\u312f': # Phonetic symbols
return True
elif uchar >= u'\u31a0' and uchar <= u'\u31bf': # Phonetic symbols (Taiwanese and Hakka expansion)
return True
elif uchar >= u'\ufe10' and uchar <= u'\ufe1f':
return True
elif uchar >= u'\ufe30' and uchar <= u'\ufe4f':
return True
elif uchar >= u'\u2600' and uchar <= u'\u26ff':
return True
elif uchar >= u'\u2700' and uchar <= u'\u27bf':
return True
elif uchar >= u'\u3200' and uchar <= u'\u32ff':
return True
elif uchar >= u'\u3300' and uchar <= u'\u33ff':
return True
else:
return False
|
def list_element(title, subtitle=None, image_url=None, buttons=None, default_action=None):
"""
Creates a dict to use with send_list
:param title: Element title
:param subtitle: Element subtitle (optional)
:param image_url: Element image URL (optional)
:param buttons: List of button_postback to show under the element (optional)
:param default_action: Action generated by button_url (optional)
:return: dict
"""
payload = {
"title": title,
"image_url": image_url,
"subtitle": subtitle,
"default_action": default_action,
"buttons": buttons
}
if not subtitle:
payload.pop('subtitle')
if not image_url:
payload.pop('image_url')
if not buttons:
payload.pop('buttons')
if not default_action:
payload.pop('default_action')
return payload
|
def sample_lines(lines, n):
"""Draw a sample of n lines from filename, largely evenly."""
if len(lines) <= n:
return "".join(lines)
else:
m = len(lines)
return "".join([lines[x * m // n + m // (2 * n)] for x in range(n)])
|
def is_valid_json(ext):
""" Checks if is a valid JSON file """
formats = ['json']
return ext in formats
|
def format_duration(seconds: float) -> str:
"""
Formats time in seconds as (Dd)HH:MM:SS (time.stfrtime() is not useful for formatting durations).
:param seconds: Number of seconds to format
:return: Given number of seconds as (Dd)HH:MM:SS
"""
x = '-' if seconds < 0 else ''
m, s = divmod(abs(seconds), 60)
h, m = divmod(int(m), 60)
d, h = divmod(h, 24)
x = f'{x}{d}d' if d > 0 else x
return f'{x}{h:02d}:{m:02d}:{s:02d}' if isinstance(s, int) else f'{x}{h:02d}:{m:02d}:{s:05.2f}'
|
def result_has_error(results):
"""
Check the results list for any possible error and return a tuple which
contains the status and error message. If the record contains a Plural
attribute, multiple API calls may be performed for a single record.
Args:
results: List of API responses
Returns:
error_stat: Boolean to check if the expected 'stat' index exists in
response
error_result: Boolean for the status of the API call
error_msg: Error message String
"""
for result in results:
if 'stat' not in result:
return True, False, "Unexpected API response"
elif result['stat'] == "error":
return False, True, result['error_description']
return False, False, ""
|
def bottom_up_cut_rod(price, length):
""" bottom up implementation of cut rod memoized algorithm """
incomelst = [float("-Inf") for _ in range(length + 1)]
# set zero income for zero length
incomelst[0] = 0
for j in range(1, length + 1):
income = float("-Inf")
for i in range(j):
income = max(income, price[i] + incomelst[j - i - 1])
# set income for current length
incomelst[j] = income
# income for whole rod
return incomelst[length]
|
def get_vxlan_ip(n):
"""
Returns an IP address in the range
192.168.0.0 - 192.168.255.255
without using X.0 or X.255
"""
quot, rem = divmod(n, 254)
ip_addr = "192.168.%s.%s" % (quot + 1, rem + 1)
return ip_addr
|
def startdate(acquired):
"""Returns the startdate from an acquired date string
Args:
acquired (str): / separated date range in iso8601 format
Returns:
str: Start date
"""
return acquired.split('/')[0]
|
def find_bucket_key(s3_path):
"""
This is a helper function that given an s3 path such that the path is of
the form: bucket/key
It will return the bucket and the key represented by the s3 path
"""
s3_components = s3_path.split('/')
bucket = s3_components[0]
s3_key = ""
if len(s3_components) > 1:
s3_key = '/'.join(s3_components[1:])
if bucket.endswith('.s3.amazonaws.com'):
bucket = bucket.split('.')[0]
return bucket, s3_key
|
def check_type(var_type, value):
"""
Check that the type of value is the Python equivalent of var_type or a list
of it
@param var_type (string) Type of val (INTEGER, REAL, LOGICAL, STRING)
@param val (int/boolean/float/string/list) Value to check
@return The value in (int, float, boolean, string)
"""
res = True
if var_type in ['LOGIQUE', 'LOGICAL']:
py_type = bool
elif var_type in ['ENTIER', 'INTEGER']:
py_type = int
elif var_type in ['REEL', 'REAL']:
py_type = float
else:
py_type = str
# If only one value returning the value itself not the list
if isinstance(value, list):
for val in value:
res = res and isinstance(val, py_type)
else:
res = isinstance(value, py_type)
return res
|
def snapshot_state_counts_nondeterministic(shots):
"""Snapshot Statevector test circuits reference counts."""
targets = []
# Snapshot |000> + i|111>
targets.append({'0x0': shots/2,
'0x7': shots/2})
# Snapshot |+++>
targets.append({'0x0': shots/8,
'0x1': shots/8,
'0x2': shots/8,
'0x3': shots/8,
'0x4': shots/8,
'0x5': shots/8,
'0x6': shots/8,
'0x7': shots/8})
return targets
|
def pretty_describe(object, nestedness=0, indent=2):
"""Nice YAML-like text version of given dict/object
Maintains dict ordering
"""
if not isinstance(object, dict):
return str(object)
sep = '\n{}'.format(" " * nestedness * indent)
out = sep.join(('{}: {}'.format(k, pretty_describe(v, nestedness + 1))
for k, v in object.items()))
if nestedness > 0 and out:
return '{sep}{out}'.format(sep=sep, format=format)
return out
|
def is_linux(conf):
"""
`is_linux` returns true if we are building for linux
FIXME: we should probably test a waf-based variant or configuration variable
rather than sys.platform...
"""
import sys
return 'linux' in sys.platform.lower()
|
def bootstrap_level(level: str) -> str:
"""Maps logging levels to bootstrap levels. Defaults to light.
Arguments:
level: The logging level.
"""
return {
"DEBUG": "secondary",
"INFO": "info",
"WARNING": "warning",
"ERROR": "danger",
}.get(level.upper(), "light")
|
def create_hover_text(node_attributes, only_use=set()):
"""
create string of node attributes
:param dict node_attributes: a dict such as:
{'attr': {'pos': None,
'lemma': 'demonstratie',
'mw': False,
'rbn_type': None,
'rbn_feature_set': None}
}
:param set only_use: if set is not empty, only these attributes will be used.
:rtype: str
:return: string representation, every attribute key on new line
"""
info = []
for key, value in node_attributes['attr'].items():
if only_use:
if key in only_use:
info.append(f'{key}: {value}')
else:
info.append(f'{key}: {value}')
return '\n'.join(info)
|
def count_in_str(pattern, str):
"""counts the number of times the pattern appears in the string
for example:
count_in_str("a", "abcaabc") returns 3
count_in_str("ab", "abcaabc") return 2"""
c = 0
sp = len(pattern)
while len(str) >= sp:
slice = str[:sp]
if pattern == slice:
c += 1
str = str[1:]
return c
|
def reformat_dict_f(dic, mapping):
"""
switch keys with key values (unique identifier)
"""
return {k: dic[v] for k, v in mapping.items()}
|
def damerau_levenshtein_distance(word1: str, word2: str) -> int:
"""Calculates the distance between two words."""
inf = len(word1) + len(word2)
table = [[inf for _ in range(len(word1) + 2)] for _ in range(len(word2) + 2)]
for i in range(1, len(word1) + 2):
table[1][i] = i - 1
for i in range(1, len(word2) + 2):
table[i][1] = i - 1
da = {}
for col, c1 in enumerate(word1, 2):
last_row = 0
for row, c2 in enumerate(word2, 2):
last_col = da.get(c2, 0)
addition = table[row - 1][col] + 1
deletion = table[row][col - 1] + 1
substitution = table[row - 1][col - 1] + (0 if c1 == c2 else 1)
transposition = (
table[last_row - 1][last_col - 1]
+ (col - last_col - 1)
+ (row - last_row - 1)
+ 1
)
table[row][col] = min(addition, deletion, substitution, transposition)
if c1 == c2:
last_row = row
da[c1] = col
return table[len(word2) + 1][len(word1) + 1]
|
def solution(A):
"""
DINAKAR
Idea is xor of two same numbers produces 0
x = 3 (011) and y = 3 (011) is 000
at the end single numbers left in xor variable.
:return:
"""
xor = 0
for item in A:
xor ^= item
return xor
|
def prune_none_and_empty(d):
"""
Remove keys that have either null values, empty strings or empty arrays
See: https://stackoverflow.com/a/27974027/5472444
"""
if not isinstance(d, (dict, list)):
return d
if isinstance(d, list):
return [v for v in [prune_none_and_empty(v) for v in d] if v]
return {k: v for k, v in ((k, prune_none_and_empty(v)) for k, v in d.items()) if v}
|
def __uglify(text: str) -> str:
"""
csv and json format output contain this non human readable header string:
no CamelCase and no space.
"""
return text.lower().replace(' ', '_')
|
def parent_index(i):
"""Vrati index rodice prvku na pozici 'i'.
Pokud neexistuje, vrati None.
"""
return (i - 1) // 2 if i > 0 else None
|
def create_lzh (archive, compression, cmd, verbosity, interactive, filenames):
"""Create a LZH archive."""
opts = 'a'
if verbosity > 1:
opts += 'v'
cmdlist = [cmd, opts, archive]
cmdlist.extend(filenames)
return cmdlist
|
def transaction_type_5():
"""Transaction of type "ipfs"
"""
data = {
'data': {},
'serialised': ''
}
return data
|
def _client_type(app_id):
"""
Determine whether the given ID is a bundle ID or a
a path to a command
"""
return "1" if app_id[0] == "/" else "0"
|
def newton(f,seed,itern=10,rounding=3,diff_tol=0.1,sol_tol=1E-10):
"""
The function newton has several parameters all of them has been talked about a bit below:
1. f: It is the function/equation to be solevd, the user of the package must define this
function before calling the solver package "newton".
2. seed: It is the initial estimation of the value of root for the equation. It can be set at any
value, but user should be aware of the complexities that can arise because of the
problems of discontinuous nature of function. Hence, this value should be set with an intelligent
guess or some amount of ground work
3. itern: Sets the number of iteration the loop in the function newton should run if the
convergence has not been reached upto defined solution tolerance, default value of 1E-10.
4.rounding: It is the rounding of number of signficant digits the solution and numbers generated
in function are reduced to for printing, default value is 3 decimal places.
5. diff_tol: It is the forward difference value used in estimation of derivaive of the function
in the neighborhood of the seed value, default value is 0.1. It can be easily made smaller to
achieve convergence quicker.
6. sol_tol: This parameter checks if the seed value in each iteration is changing more than
this threshold value or not. If the chnage in seed values is smaller than this value, the loop
in the package exits and the prompt that convergence has been achieved is printed. Hence,
changing this values is essential to achieve more precise convergence.
"""
soln=[] # empty list to save the seed values for comparison to check if they are chnaging in each iteration
print(30*"*","Newton's method convergence visualization",30*"*")
print("f(n)","n",sep="\t")
print(20*"*")
for i in range(1,itern):
seed = seed - (f(seed)*(diff_tol))/(f(seed+diff_tol)-f(seed)) # execution fo the newton's method
soln.append(seed)
# to check if the convergence upto a certain tolerance is acheived
if (len(soln)>2) and ((soln[-2]-soln[-1])<(sol_tol)):
print("Convergene of solution achieved! after",i,"iterations! at seed value of:",round(seed,rounding))
break
print(round(f(seed),rounding),round(seed,rounding),sep="\t") # serves for pretty printing
return seed
|
def normalize_text(text):
"""tidy up string"""
return text.replace('\n', '')
|
def String_to_Tips(string):
"""
given a .newick subtree as a string, return a list of the tips
args
string: should be a .newick string eg "((A,B),((C,D),E))"
returns
overall_tiplist: a list that looks like ["A", "B", "C", "D", "E"]
str_to_tips: a dict of all subclades to their tiplists. {"((A,B),((C,D),E))":["A", "B", "C", "D", "E"],
(A,B):[A,B] ...etc}
"""
depth = 0
depth_to_index = {}
index = 0
str_to_tips = {}
list_of_strings = []
overall_tiplist = []
for item in string:
if item == "(":
depth += 1
depth_to_index[depth] = index
if item == ")":
list_of_strings.append(string[depth_to_index[depth]:index+1])
depth -= 1
index += 1
#print(list_of_strings)
for item in list_of_strings:
tiplist = []
item2 = item.replace("(", "")
item2 = item2.replace(")", "")
items2 = item2.split(",")
#print(items)
for tip in items2:
tipsplits = tip.split(":")
tip = tipsplits[0]
tiplist.append(tip)
if tip not in overall_tiplist:
overall_tiplist.append(tip)
str_to_tips[item] = tiplist
#print(str_to_tips)
#add single tips str mapping to singletip in list.
#for item in overall_tiplist:
# str_to_tips[item] = [item]
return str_to_tips, overall_tiplist
|
def restart_omiserver(run_command):
"""
Restart omiserver as needed (it crashes sometimes, and doesn't restart automatically yet)
:param run_command: External command execution function (e.g., RunGetOutput)
:rtype: int, str
:return: 2-tuple of the process exit code and the resulting output string (run_command's return values)
"""
return run_command('/opt/omi/bin/service_control restart')
|
def regex_matches_to_indexed_words(matches):
"""Transforms tokensregex and semgrex matches to indexed words.
:param matches: unprocessed regex matches
:return: flat array of indexed words
"""
words = [dict(v, **dict([('sentence', i)]))
for i, s in enumerate(matches['sentences'])
for k, v in s.items() if k != 'length']
return words
|
def get_url_without_trailing_slash(value):
"""
Function which strips a trailing slash from the provided url if one is present.
:param value: URL to format.
:type value: ``str``
:rtype: ``str``
"""
result = value[:-1] if value.endswith("/") else value
return result
|
def middleware(resolver, obj, info, **kwargs):
"""
example middleware
"""
return resolver(obj, info, **kwargs)
|
def find_char_groups(s):
"""
Find character groups
"""
pos = 0
groups = []
escaped = False
found = False
first = None
for c in s:
if c == "\\":
escaped = not escaped
elif escaped:
escaped = False
elif c == "[" and not found:
found = True
first = pos
elif c == "]" and found:
groups.append((first, pos))
pos += 1
return groups
|
def properties(obj):
"""
Returns a dictionary with one entry per attribute of the given object. The key being the
attribute name and the value being the attribute value. Attributes starting in two
underscores will be ignored. This function is an alternative to vars() which only returns
instance variables, not properties. Note that methods are returned as well but the value in
the dictionary is the method, not the return value of the method.
>>> class Foo():
... def __init__(self):
... self.var = 1
... @property
... def prop(self):
... return self.var + 1
... def meth(self):
... return self.var + 2
>>> foo = Foo()
>>> properties(foo) == {'var': 1, 'prop': 2, 'meth': foo.meth}
True
Note how the entry for prop is not a bound method (i.e. the getter) but a the return value of
that getter.
"""
return dict((attr, getattr(obj, attr)) for attr in dir(obj) if not attr.startswith('__'))
|
def decimal_to_base2(dec):
"""Convert decimal number to binary number by iteration.
Time complexity: O(d/2).
Space complexity: O(d/2).
"""
# Push remainders into stack.
rem_stack = []
while dec > 0:
dec, rem = divmod(dec, 2)
rem_stack.append(rem)
# Pop remainders and concat them into binary number string.
bin_num = ''
while rem_stack:
bin_num += str(rem_stack.pop())
return bin_num
|
def show_size(n) -> str:
"""
Returns the size ``n`` in human readable form, i.e. as bytes, KB, MB, GB, ...
:return: human readable size
"""
_n = n
if _n < 1024:
return "{} bytes".format(_n)
for dim in ['KB', 'MB', 'GB', 'TB', 'PB']:
_n = _n / 1024.0
if _n < 1024:
return "{:.3f} {}".format(_n, dim)
return "{} bytes".format(n)
|
def chunk(mylist, chunksize):
"""
Args:
mylist: array
chunksize: int
Returns:
list of chunks of an array len chunksize (last chunk is less)
"""
N = len(mylist)
chunks = list(range(0, N, chunksize)) + [N]
return [mylist[i:j] for i, j in zip(chunks[:-1], chunks[1:])]
|
def cleanup_favorite(favorite):
"""Given a dictionary of a favorite item, return a str."""
return str(favorite["post"])
|
def _pad_sequences(sequences, pad_tok, max_length):
"""
Args:
sequences: a generator of list or tuple
pad_tok: the char to pad with
Returns:
a list of list where each sublist has same length
"""
sequence_padded, sequence_length = [], []
for seq in sequences:
seq = list(seq)
seq_ = seq[:max_length] + [pad_tok] * max(max_length - len(seq), 0)
sequence_padded.append(seq_)
sequence_length.append(min(len(seq), max_length))
return sequence_padded, sequence_length
|
def get_shifted_product(first_list: list, second_list: list) -> list:
"""
Returns a list of the product of each element in the first list
with each element in the second list shifted by one index.
"""
shifted_second_list = second_list[1:]
return [a * b for a, b in zip(first_list, shifted_second_list)]
|
def get_result_from_input_values(input, result):
"""Check test conditions in scenario results input.
Check whether the input parameters of a behave scenario results record from
testapi match the input parameters of the latest test. In other words,
check that the test results from testapi come from a test done under the
same conditions (frame size, flow count, rate, ...)
Args:
input: input dict of a results dict of a behave scenario from testapi
result: dict of nfvbench params used during the last test
Returns:
True if test conditions match, else False.
"""
# Select required keys (other keys can be not set or unconsistent between scenarios)
required_keys = ['duration_sec', 'frame_sizes', 'flow_count', 'rate']
if 'user_label' in result:
required_keys.append('user_label')
if 'flavor_type' in result:
required_keys.append('flavor_type')
subset_input = dict((k, input[k]) for k in required_keys if k in input)
subset_result = dict((k, result[k]) for k in required_keys if k in result)
return subset_input == subset_result
|
def check_not_finished_board(board: list):
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5',\
'*?????*', '*?????*', '*2*1***'])
False
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*543215', \
'*35214*', '*41532*', '*2*1***'])
True
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*5?3215',\
'*35214*', '*41532*', '*2*1***'])
False
"""
all_signs = ''.join(board)
if '?' in list(all_signs):
return False
else:
return True
|
def ilen(iterator):
"""
Counts the number of elements in an iterator, consuming it and making it
unavailable for any other purpose.
"""
return sum(1 for _ in iterator)
|
def rewardListToString(s):
"""[Turns a List of Reward Objects into a comma seperated strings]
Arguments:
s {[list of rewards]} -- [list of rewards]
Returns:
[String] -- [string of comma seperated reward names]
"""
# initialize an empty string
str1 = ""
reward_list = []
# traverse in the string
for ele in s:
reward_list.append(ele.name)
str1 = ", ".join(reward_list)
# return string
return str1
|
def argument(*name_or_flags, **kwargs):
"""Helper function to satisfy argparse.ArgumentParser.add_argument()'s
input argument syntax"""
return (list(name_or_flags), kwargs)
|
def get_gear_ratio(g: int, gear_ratios: dict):
"""get gear ratio
Args:
g (int): gear
gear_ratios (dict): mapping of gear to gear ratio
Returns:
[float]: gear ratio
"""
return gear_ratios[g]['ratio']
|
def _kamb_radius(n, sigma):
"""Radius of kernel for Kamb-style smoothing."""
a = sigma**2 / (float(n) + sigma**2)
return (1 - a)
|
def _embedded_checkpoint_frames(prefixed_frame_dict):
"""prefixed_frame_dict should be a dict of base64-encoded files, with prefix"""
template = ' checkpoint_frames[{0}] = "{1}"\n'
return "\n" + "".join(template.format(i, frame_data.replace('\n', '\\\n'))
for i, frame_data in prefixed_frame_dict.items())
|
def newton(f, f_prime, x0, tol):
"""
Find the root of f(x) = 0 using the Newton-Raphson method recursively.
Parameters
----------
f - function
f_prime - derivative of f
x0 - starting value
tol - tolerance
Returns
-------
root of f(x)
"""
if abs(f(x0)) < tol:
return x0
else:
x1 = x0 - (f(x0)/f_prime(x0))
print("x0 = ", x0, "f(x0) = ", f(x0), "f'(x0) =", f_prime(x0), "x1 = ", x1)
return newton(f, f_prime, x1, tol)
|
def get_str2id(strings_array):
"""Returns map from string to index in array. """
str2id = {}
for i in range(len(strings_array)):
str2id[strings_array[i]] = i
return str2id
|
def pluralize(input):
"""Readwise pluralize"""
if input == 1:
return ''
else:
return 's'
|
def has_prefix(sub_s, dic):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
if sub_s == None:
return True
for word in dic:
if word.startswith(sub_s):
return True
return False
|
def map_labels(labels, mapping):
"""Map labels to new labels defined by mapping."""
return [mapping.get(l, l) for l in labels]
|
def uuid_from_obj(obj):
"""Try to get uuid from an object.
Args:
obj (Object): The object possibly containing uuid.
Returns:
Object: obj.uuid if it exists; otherwise, obj
"""
if hasattr(obj, "uuid"):
return obj.uuid
return obj
|
def getMoshDamage(n):
""" Amount of damage from a mosh with N players on stage """
if n > 6 or n < 1:
raise Exception("Invalid n={}".format(n))
return [5,10,20,40,64,100][n-1]
|
def to_hectar(x, resx, resy):
"""convert a pixel number into a surface in hectar using the provided resolution (res in meters)"""
return x * resx * resy / 10000
|
def _trim_dollar(value):
"""Trim dollar character if present."""
return value[1:] if value.startswith("$") else value
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.