content stringlengths 42 6.51k |
|---|
def stash_tree_on_id_to_paths(tree_on_id):
"""Gets paths to nodes in a tree-on-id data-structure.
See stash_tree_on_id function.
"""
paths = {}
def inner(t, pid):
for k, v in t.items():
paths[k] = paths.get(pid, []) + [k]
children = v['children']
if chil... |
def fixed_anchor_init(dim: int):
"""
Fixed anchors sizes for 2d and 3d
Args:
dim: number of dimensions
Returns:
dict: fixed params
"""
anchor_plan = {"stride": 1, "aspect_ratios": (0.5, 1, 2)}
if dim == 2:
anchor_plan["sizes"] = (32, 64, 128, 256)
else:
... |
def rightSideView(root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root==None:
return []
ans=[root.val]
left=ans+rightSideView(root.left)
right=ans+rightSideView(root.right)
print('\nleft:', left)
print('right:', right)
... |
def output_validator(language, options):
"""Options validator for codemirror code blocks."""
okay = True
return okay |
def seperate_kw(uns_kw):
"""Separate the keywords and return a list."""
sep_kw = []
# Check if -> is present in the name
if '->' not in uns_kw:
sep_kw.append(uns_kw)
else:
while '->' in uns_kw:
pos = uns_kw.find("->")
sep_kw.append(uns_kw[:pos])
u... |
def remove_single_char_word(text: str) -> str:
"""
Remove single character word from text
Example: I am in a a home for two years => am in home for two years
Args:
text (str): text
Returns:
(str): text with single char removed
"""
words = text.split()
filter_word... |
def check_for_ticket_price_error(price):
"""
Returns any error message if the ticket's price is not between 10 and 100 else if
there is no errors it returns false.
:param price: the ticket's price as a string
:return: false if no error, else returns the error as a string message
"""
if floa... |
def str_to_bool(boolstring):
"""
Translate a string into a real boolean value.
:param boolstring:
Any string. But original intention was the usage of the strings "False" and "True".
:return:
Returns True for the string "True" and False for the string "False".
Returns True for any nonempty st... |
def _find_end(tokens):
"""
Find index of closing parenthesis. Based on function from Rhomboid at
https://gist.github.com/Rhomboid/5994999.
Parameters
----------
tokens : list of str
List of strings representing molecular formula.
Return
------
idx : int
Index of clo... |
def best_linking (linking, el2kbid):
"""
return a subset of the linking consisting of only the highest confidence link for each element in el2kbid
"""
new_linking = dict()
for m in el2kbid.keys():
links = el2kbid[m]
kb_id, conf = links[0] # highest confidence kb_id
i... |
def remove_empty_values(_dict):
"""Removes Nonetype dict values"""
return {k: v for k, v in list(_dict.items()) if v is not None} |
def task_payload(now):
"""Return an example valid task payload, with all possible parameters."""
return {
'title': 'Eat donuts',
'list_id': 1,
'due_date': str(now),
'priority': 2,
'completed': False,
} |
def descrFromDoc(obj):
"""
Generate an appropriate description from docstring of the given object
"""
if obj.__doc__ is None:
return None
lines = obj.__doc__.split("\n")
descr = None
try:
if lines[0] != "" and not lines[0].isspace():
descr = lines[0].lstrip()
... |
def conf_to_str(conf, delimiter='\n'):
"""Represent a configuration dict as a string"""
parts = []
for k, v in sorted(conf.items()):
v = ','.join(v) if isinstance(v, list) else str(v)
part = '{}={}'.format(k, v)
parts.append(part)
return delimiter.join(parts) |
def lam(x, lam0, alpha=4.0):
"""Return classic alpha model lambda value(s) for input value(s)."""
return lam0 * ( 1.0 - x**alpha ) |
def compare_nested_dict(modify_setting_payload, existing_setting_payload):
"""compare existing and requested setting values of identity pool in case of modify operations
if both are same return True"""
for key, val in modify_setting_payload.items():
if existing_setting_payload.get(key) is None:
... |
def cross_prod(a,b):
"""
Compute the cross product of two 3 vectors
"""
c0 = a[1]*b[2] - b[1]*a[2]
c1 = b[0]*a[2] - a[0]*b[2]
c2 = a[0]*b[1] - b[0]*a[1]
return c0, c1, c2 |
def isOverlap1D(box1, box2):
"""Check if two 1D boxes overlap.
Reference: https://stackoverflow.com/a/20925869/12646778
Arguments:
box1, box2: format: (xmin, xmax)
Returns:
res: bool, True for overlapping, False for not
"""
xmin1, xmax1 = box1
xmin2, xmax2 = box2
return x... |
def tuples_to_mock_class(wrapper_class_name, functions):
"""Generates a mock class as a string from the parsed result of headers."""
def to_mock_method(return_type, name, arguments):
"""Generates the mock method from a parsed API information."""
arguments_string = ','.join([' '.join(x) for x in arguments])... |
def compute_out_degrees(digraph):
""" dict -> dict
Takes a directed graph represented as a dictionary, and returns a dictionary
in which the keys are the nodes and the values are the nodes' outdegree
value.
"""
out_degrees = {}
for node in digraph:
out_degrees[node] = len(digraph[nod... |
def format_duration(seconds):
"""Format a duration as ``[hours:]minutes:seconds``.
Parameters
----------
seconds : int
Duration in seconds.
Returns
-------
str
"""
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
if hours > 0:
ret... |
def count_l(a):
"""assumes a in a string
returns an int, representing the number of words in a with an "l"
treats sequences of characters seperated by a space as a word
"""
word_list = a.split()
l_count = 0
for word in word_list:
if "l" in word:
l_count += 1
return l_... |
def randseg(start, stop, seglen):
"""Returns a random segment of length seglen between start and stop.
Raises ValueError if the segment is not long enough.
"""
from random import uniform
if stop-start < seglen: raise ValueError
a = uniform(start, stop-seglen)
b = a+seglen
return ... |
def encode_address(address: int) -> bytes:
"""Encodes an HDLC address as a one-terminated LSB varint."""
result = bytearray()
while True:
result += bytes([(address & 0x7f) << 1])
address >>= 7
if address == 0:
break
result[-1] |= 0x1
return result |
def trivial_batch_collator(batch):
"""
"""
collated_list = []
for img in batch:
collated_list.extend(img['image_list'])
return collated_list |
def parityOf( n ):
"""
parityOf - determine if the number of bits is odd or even
Args:
n: the number to be tested.
Returns:
o - if the number has even bits.
1 - if the number has odd bits.
"""
parity = 0
while( n ):
parity ^= (n&1)
n >>= 1
return ... |
def round_filters(filters, d_mult, divisor=8, min_depth=None):
""" Calculate and round number of filters based on depth multiplier. """
if not d_mult:
return filters
filters = [f*d_mult for f in filters]
min_depth = min_depth or divisor
new_filters = [max(min_depth, int(f + divisor... |
def word_count(document, search_term):
""" Count how many times search_term appears in document. """
words = document.split()
answer = 0
for word in words:
if word == search_term:
answer += 1
return answer |
def circleInfo(r):
""" Return (circumference, area) of a circle of radius r """
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a) |
def clean_topics(topics):
"""
Sort and remove list duplicates.
"""
topics = list(dict.fromkeys(topics))
topics.sort()
# after sort, collapse overlapping topic levels to reduce size
_topics = []
high_topic = ""
for i, topic in enumerate(topics):
add = True
if i > 0 and... |
def _to_string(val):
"""
Converts a given float (`val`) of mass, metallicity, or alpha
enhancement to a string (`my_str`) formatted for the model filename.
For example, a metallicity [M/H] = -0.5 corresponds to the string
"-050", and the mass 1.32 corresponds to the string "132".
"""
if va... |
def analytical_pulse_duration(q):
"""
Estimate analytical_pulse_duration from electron bunch charge
:param q: electron bunch charge [nC]
:return t: Duration of pulse [s]
"""
t = (q*1e3)/9.8
return t*1e-15 |
def parse_args_cli(args=None):
"""Parse arguments parsed to the function and return parsed argparse object.
:param args: An array of string arguments, much like sys.argv passes
:type args: [strings]
:returns: Parsed argument object
:rtype: argparse
"""
from sys import stdout, stderr, stdin
import argpa... |
def fib_rec(n: int) -> int:
"""Computes the n-th Fibonacci number.
Args:
n: The number of which Fibonacci sequence to be computed.
Returns:
The n-th number of the Fibonacci sequence.
"""
if n <= 1: return n
else: return fib_rec(n-1) + fib_rec(n-2) |
def location_to_hex(location):
"""convert location to hex for display"""
ret = "%08X" % int(location)
return ret |
def _MetadataMessageToDict(metadata_message):
"""Converts a Metadata message to a dict."""
res = {}
if metadata_message:
for item in metadata_message.items:
res[item.key] = item.value
return res |
def __process_case_list(list_input, list_output):
"""
Process a case list and raise an exception in case of duplicate
entries.
"""
duplicate = ""
for item in list_input:
if item == None or item == "":
continue
elif item.lower() in list_output:
dup... |
def hamming_distance(pattern, motiv):
"""
Calculates the hamming distance
between its two parameters
"""
if len(pattern) != len(motiv):
return -1
hamming_distance = 0
for i in range(len(motiv)):
if pattern[i] != motiv[i]:
hamming_distance += 1
return ha... |
def get_smallest_entry(visited, distance):
""" Returns the position of the unvisited node with the smallest
distance. Returns None if no options are left. """
smallest = None
smallest_entry = None
for i in range(0, len(visited)):
if not visited[i] and distance[i] is not None:
if... |
def compute_in_degrees(digraph):
"""
Makes a directed graph digraph (represented as a dictionary)
and computes the in-degrees for the nodes in the graph
"""
nodes = digraph.keys()
counts = {x:0 for x in nodes}
for key in digraph.keys():
values = digraph[key]
for value in valu... |
def bindingType(b):
"""
Function returns the type of a variable binding. Commonly 'uri' or 'literal'.
"""
type = b['type']
if type == "typed-literal" and b['datatype'] == "http://www.w3.org/2001/XMLSchema#string":
type = 'literal'
return type |
def check_blanks(plaintext: list, ciphertext: list) -> int:
"""Check if the ciphertext can fit in plaintext.
Compare the number of blank lines in **plaintext** to the number of lines
in **ciphertext**. If they aren't a match, returns the number of extra
blank lines needed.
Args:
plaintext ... |
def check_index(index: str, values: list, messages: list) -> bool:
"""Checks that min-max values are a two-items list.
Parameters
----------
index : str
Numeric indicator.
values : list
Metadata variables in criteria.
messages : list
Message to print in case of error.
... |
def lcat(L1,L2):
"""In : L1 (language : a set),
L2 (language : a set).
Out: L1 concat L2 (language : a set).
Example:
L1 = {'ab', 'bc'}
L2 = {'11', 'ab', '22'}
lcat(L1,L2) -> {'abab', 'bc22', 'ab11', 'ab22', 'bcab', 'bc11'}
"""
return {x+y for x in L1 for y i... |
def rect2lines(bbox):
"""
Given a bounding box, convert it into a path of points
Parameters
----------
bbox : list or numpy array [x1 y1 x2 y2]
Bounding box defined as top left and bottom right points
of the box
Returns
-------
point_list : list
List of five points defining a path to draw the bounding
bo... |
def single_number(nums):
"""
Find single number in given array
:param nums: given array
:type nums: list[int]
:return: single number
:rtype: int
"""
result = 0
if len(nums) != 0:
for number in nums:
result = result ^ number
return result |
def pyimpl_invert_permutation(perm):
"""Implement `invert_permutation`."""
return tuple(perm.index(i) for i in range(len(perm))) |
def anglicize1to19(n):
"""
Returns the English equiv of n.
Parameter: the integer to anglicize
Precondition: n in 1..19
"""
if n == 1:
return 'one'
elif n == 2:
return 'two'
elif n == 3:
return 'three'
elif n == 4:
return 'four'
elif n == 5:
... |
def reduce_weights(x, k):
"""
Divide x by k if x is not None
"""
if x is not None:
return x/k
else:
return None |
def sanitize_filename(name, extension='pdf', **kwargs):
"""
Removes whitespace and replaces with '_'. Also ensures proper extension is appended.
:param name: Name to sanitize
:param kwargs: Dict of characters to replace; e.g., {':': '%'} will replace all occurrences of ':' with '%'. Dict items will b... |
def get_env_init_command(package):
"""Get command line arguments for getting emulator env. info.
:type package: str
:param package: The package to get environment info for.
:rtype: tuple
:returns: The arguments to be used, in a tuple.
"""
return ('gcloud', 'beta', 'emulators', package, 'en... |
def make_new_formula(formula, lit, lit_val):
"""
Updates a CNF formula with the consequences of setting lit to lit_val.
Parameters:
formula: list of clauses [ [(x, Bool)] ]
lit: string
lit_val: True or False
Returns a modified CNF formula.
"""
new_formula = []
f... |
def preprocessor(text, pipeline):
"""
preprocess the text as per the given pipeline
pipeline is a list of functions that process an input text and outputs text
(e.g., lemmatizing, removing punctuations etc.),
"""
if len(pipeline)==0:
return text
else:
return prep... |
def list_and_add(a, b):
"""
Coerce to lists and concatenate.
Args:
a: A thing.
b: A thing.
Returns:
List. All the things.
"""
if not isinstance(b, list):
b = [b]
if not isinstance(a, list):
a = [a]
return a + b |
def _get_price_data(price, item):
"""Get a specific data from HS price.
:param price: Hardware Server price.
:param string item: Hardware Server price data.
"""
result = '-'
if item in price:
result = price[item]
return result |
def find_correct_weight(program_weights, program, correction):
"""Return new weight for node."""
return program_weights[program] + correction |
def _encrypt(msg) -> str:
""" Function Name: encrypt
Description: Encrypt a message that is going to be sent
Parameters: str msg: The message that is to be encrypted
Return Value: str - The Encrypted message
"""
return "".join([ chr(ord(x)+3) for x in msg ]) |
def enrich(alert, rules):
"""Determine if an alert meets an enrichment rule
:param alert: The alert to test
:param rules: An array of enrichment rules to test against
:returns: Alert - The enriched Alert object
"""
for enrichment in rules:
updates = enrichment(alert)
if not upda... |
def enforce_list(var):
""" Runs the list() constructor on the var parameter.
"""
try:
return list(var) # iterable
except TypeError:
return [var] |
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
l... |
def verify(url):
"""
To check whether `url` belongs to YouTube, if yes returns True
else False
"""
if "www.youtube.com" in url or "youtu.be" in url:
return True
return False |
def normalize(lines: str) -> str:
""" Remove trailing whitespace from each line,
keeping all line breaks except the last."""
return '\n'.join(line.rstrip() for line in lines.strip().splitlines()) |
def process(data, passed_data, value, module, split, count):
"""Iterates recursively through the data to find only modules
that are searched for
Arguments:
:param data: (dict) module that is searched
:param passed_data: (list) data that contain value searched
... |
def xor(data, key):
"""
Performing XOR encryption on the provided data with the specified key.
"""
return bytearray([ a ^ ord(key) for a in data]) |
def remove_duplicates(from_list):
"""
The function list() will convert an item to a list.
The function set() will convert an item to a set.
A set is similar to a list, but all values must be unique.
Converting a list to a set removes all duplicate values.
We then convert... |
def join(seq, string="", func=None):
"""Create a list from sequence.
*string* is appended to each element but the last.
*func* is applied to every element before appending *string*.
"""
if func is None:
func = lambda x: x
return [func(x) + string for x in seq[:-1]] + [func(seq[-1])] |
def choose_package(file_type, file_name):
"""Choose analysis package due to file type and file extension.
@param file_type: file type.
@return: package or None.
"""
if not file_type:
return None
file_name = file_name.lower()
if "Mach-O" in file_type:
return "macho"
elif... |
def bisect_left(arr, x):
"""Binary search array to find (left-most) x."""
lo, hi = 0, len(arr) # detail 1: len(arr) vs len(arr) - 1
while lo < hi: # detail 2: lo < hi vs lo <= hi
mid = lo + hi >> 1 # detail 3: lo + hi >> 1 vs lo + hi + 1 >> 1
if arr[mid] < x: lo = m... |
def _as_dict(options_list):
"""Builds a disctionary from a list of key,value option pairs"""
return {key: value for key, value in options_list} |
def password_is_complex(password, min_len=12):
"""
Check that the specified string meets standard password complexity
requirements.
:param str password: The password to validate.
:param int min_len: The mininum length the password should be.
:return: Whether the strings appears to be complex or not.
:rtype: bool... |
def ERR_NICKCOLLISION(sender, receipient, message):
""" Error Code 436 """
return "ERROR from <" + sender + ">: " + message |
def set_srate(srate=44100.0):
"""Sets the default sampling rate."""
global _srate
_srate = srate
return _srate |
def _invert_dict(original):
"""
Produce a dictionary with the keys and values
inverted, relative to the dict passed in.
Args:
original dict: The dict like object to invert
Returns:
dict
"""
return {value: key for key, value in original.items()} |
def cleanup_Keyword(keyword):
"""
remove stuff after '{'
remove '.' at last keyword
remove last ',' in string
"ATP-binding{ECO:0000256|HAMAP-Rule:MF_00175,","Chaperone{ECO:0000256|HAMAP-Rule:MF_00175,","Completeproteome{ECO:0000313|Proteomes:UP000005019}","ECO:0000256|SAAS:SAAS00645729}","ECO:000025... |
def byte_to_bits(b):
"""Wandelt Byte (Int 0-255) in ein Array mit 8 True/False-Werten um. Achtung, das niederwertige Bit ist links
"""
bits = [False,False,False,False,False,False,False,False]
i=7
while b>0:
while b>=2**i:
bits[i]=True
b=b-2**i
break
else:
i=i-1
return bits |
def _intersection(A,B):
"""
A simple function to find an intersection between two arrays.
@type A: List
@param A: First List
@type B: List
@param B: Second List
@rtype: List
@return: List of Intersections
"""
intersection = []
for i in A:
if i in B:
... |
def _sort_keys_by_values(p):
"""Returns a sorted list of keys of p sorted by values of p."""
return sorted((pn for pn in p if p[pn]), key=lambda pn: p[pn]) |
def inorder(root):
"""Inorder depth-first traverse a binary tree."""
ans = []
node, stack = root, []
while node or stack:
if node: # go-left
stack.append(node)
node = node.left
else:
node = stack.pop() # go-back
ans.append(node.val)
... |
def liste_vers_paires(l):
"""
Passer d'une structure en list(list(str)) ) list([str, str])
:param l:
:return:
"""
res = []
for i in l:
taille_i = len(i)
for j in range(taille_i-1):
for k in range(j+1, taille_i):
res.append([i[j], i[k]])
return ... |
def jaccard(exonmap1, exonmap2):
""" get jaccard between exon map
1.3 and 2.4
jaccard = 2/4 = 0.5
"""
union_sum = 0
intersection_sum = 0
dct1 = dict()
for se in exonmap1:
s, e = se.split(".")
for i in range(int(s), int(e) + 1):
if not i in dct1.keys()... |
def range_subset(range1, range2):
"""Whether range1 is a subset of range2."""
if not range1:
return True # empty range is subset of anything
if not range2:
return False # non-empty range can't be subset of empty range
if len(range1) > 1 and range1.step % range2.step:
return Fal... |
def get_dci_configs(n_samples, val_per_factor, mode):
""" Get SAP configs, See Generic function description on top of file for more details
Extra args : continuous (bool) : defines the mode of the evaluated metric"""
gin_config_files = ["./disentanglement_lib/config/benchmark/metric_configs/dci.gin"]
... |
def generate_output(shortest_path, starting_node, ending_node):
"""
Generates the message to the user detailing the result of the
breadth first search to find the shortest path.
"""
if shortest_path < 0:
output_message = "Nodes {} and {} are not connected.".format(starting_node, end... |
def dependencies(thing):
"""Dependencies which must be sampled before this value."""
return getattr(thing, '_dependencies', ()) |
def legal_notice(caption="WRF", text="Modified with Windows Registry Fixer"):
"""Nota Legal Antes do Logon
DESCRIPTION
Use estes campos para criar uma caixa de dialogo que sera mostrada para
todos os usuarios antes de se logarem no sistema. Isto e util quando voce
quer avisar ao usuari... |
def x0_mult(guess, slip):
"""
Compute x0_mult element-wise
:param guess: guess (np.array) [odds]
:param slip: slip (np.array) [odds]
:return: np.array
"""
return slip*(1.0+guess)/(1.0+slip) |
def get_efpk_score(protein_length, average_read_length, length_cutoff, insert_size=None):
"""Calculates EFPK score of a single hit (effective FPK)
Note: For very short proteins (<<90 aa) and very short reads, effective gene
length may be negative. In such cases, this function assumes effective
gene len... |
def build_user(first, last, **user_info):
#The double star tells python to make an empty dictionary
#so we can mix-and-match data types (e.g., string and int)
"""Build a dictionary containing user information"""
user_info['first'] = first
user_info['last'] = last
return user_info |
def getTimes(from_, to, incr=1.0, frommid=1):
"""Returns a list of "times" in the given range and incr.
If frommid=1, then returns in increasing distance from midpoint.
Examples:
>>> getTimes(-5, 5, 1)
[0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5]
>>> getTimes(-5, 5, 1, 0)
[-5, -4, -3, -2, -... |
def NormalizeTextualFormat(user_specified_format):
"""Translates the format name specified in a flag into internal form.
For example, 'newline-delimited-json' is translated into the form expected
in job configurations, 'NEWLINE_DELIMITED_JSON'.
Args:
user_specified_format: the flag value, or None
Retur... |
def build_regex_string(groups, separator='\s+'):
"""
Create a regular expression string from a list of group name and pattern tuples.
:param groups: list of tuples (group name, pattern) - if group name is None, no group is created
:param separator: (optional) separator between items - default: whitesp... |
def generate_host_dict(info, params):
"""
Generate ansible host dict
Args:
info(dict): info of a host
params(dict): params of the requests
Returns:
dict: dict of ansible host
"""
ansible_input_json_host = {'ansible_host': info['public_ip'],
... |
def _make_programmable_tuple(cls, data_values):
"""Makes a programmable tuple object
This function will actually make a programmable tuple object of the given
class according to the sequence of values for the fields. It is the
function that is actually used to make the object during the
initializat... |
def get_cmt(cmt_dict, loc):
"""Returns the clock region of an input location."""
for k, v in cmt_dict.items():
for (x, y) in v['vpr_loc']:
if x == loc[0] and y == loc[1]:
return v['clock_region']
return None |
def dict_to_string(dict):
"""
Custom conversion method for dict to string.
This adds a bullet point and line break to the dict.
:param dict: A dict used to store metadata.
:type dict: dict
:return: The dict as a string with added * for seperation
:rtype: str
"""
str = ""
for ke... |
def dict_reverse(dictionary):
"""
Reverse a dictionary. If values are not unique, only one will be used. Which one is not specified
Args:
dictionary (dict): dict to reverse
Returns:
reversed (dict): reversed dictionary
"""
return {v: k for k, v in dictionary.items()} |
def tag_group(tag_group, tag):
"""Select a tag group and a tag."""
payload = {"group": tag_group, "tag": tag}
return payload |
def is_x12_data(input_data: str) -> bool:
"""
Returns True if the input data appears to be a X12 message.
:param input_data: Input data to evaluate
:return: True if the input data is a x12 message, otherwise False
"""
return input_data.startswith("ISA") if input_data else False |
def fizz_buzz_four( start, end ):
"""
Fizz buzz showing compact if-elif-else form,
and precalculatio of boolean values.
"""
result = [] # initalising a list to hold our result
for i in range(start, end+1):
fizz = (i % 3 == 0)
buzz = (i % 5 == 0)
if fizz and buzz: result... |
def AICc(k, L, n):
"""Computes the corrected Akaike Information Criterion.
Keyword arguments:
L -- log likelihood value of given distribution.
k -- number of fitted parameters.
n -- number of observations.
"""
AICc = 2 * k - 2 * L + 2 * k * (k + 1) / (n - k - 1)
return AICc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.