content stringlengths 42 6.51k |
|---|
def read_metadata_filters(meta_filts):
"""Create dictionaries of metadata filters from a list.
Args:
meta_filts: list of filters in the format 'key=values' or
'key!=values' with a comma separated list of values
Returns:
tuple of 2 dicts where each key is any of ['taxid', '... |
def calculate_sum(list_of_nums):
"""Calculates the sum of a list of numbers."""
total = 0
for num in list_of_nums:
total += num
return total |
def is_float(string: str = '') -> bool:
"""Return True if the input string can be a float number
Args:
string (str, optional): input string. Defaults to ''.
Returns:
bool: return True if the input string can be converted to float
"""
try:
float(string)
return True
... |
def cube(x):
"""
Cube.
"""
return pow(x, 3) |
def split_filename(filename):
"""Returns the basename and extension of a given filename.
The basename and extension are distinguished using the rightmost dot (.).
For example, "a.file.name.ext" the basename is equivalent to "a.file.name"
and the extension is equivalent to "ext". If there is no dot in t... |
def _approx_beams(beams, precis=5):
"""Return beams with scores rounded."""
return [tuple(list(b[:-1]) + [round(b[-1], precis)]) for b in beams] |
def canConstruct_v4(ransomNote: str, magazine: str) -> bool:
"""I like this solution most."""
return not any(ransomNote.count(letter) > magazine.count(letter) for letter in set(ransomNote)) |
def deduplicate(constraints):
"""
Return a new ``constraints`` list with exact duplicated constraints removed.
"""
seen = set()
unique = []
for c in constraints:
if c not in seen:
unique.append(c)
seen.add(c)
return unique |
def extend_columns(sentences, columns):
"""Extend column to list of sentences
Args:
sentences (list):
Sentences is a list of sentences.
Sentence is a list of token information.
Token information is in format: [token, feature_1, ..., feature_n, tag_label]
columns (list): Same... |
def either(predicate1, predicate2, value):
"""A function wrapping calls to the two functions in an || operation,
returning the result of the first function if it is truth-y and the result
of the second function otherwise. Note that this is short-circuited,
meaning that the second function will not be in... |
def num_trees(n):
"""
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
:param n: int
:return: int
"""
res = [0] * (n + 1)
res[0] = 1
for i in range(1, n + 1):
for j in range(i):
res[i] += res[j] * res[i - 1 - j]
return r... |
def get_next_event_index(read_buffer, last_event_index, last_event_id, max_cursor):
"""
try to get the index of the end of the event
if found return the index and 0 to indicate it is found
if not found return the index of the last item parsed and the last event id
:param sub: byte array to parse
... |
def id_topography_modifiers(fixture_value):
"""Used to see whether scaled or detrended in test output.
"""
use_scale, use_detrend = fixture_value
s = ""
if not use_scale:
s += "no"
s += "scale-"
if not use_detrend:
s += "no"
s += "detrend"
return s |
def second_index(text: str, symbol: str):
"""
returns the second index of a symbol in a given text
"""
res = [i for i,x in enumerate(text) if x==symbol ]
if len(res) >= 2:
return res[1]
return None
# try:
# return text.index(symbol,text.index(symbol)+1)
# except Va... |
def parser_tuple(string):
"""
Returns a pair of string from a string of comma separate elements.
:param string: str
:return: pair
"""
string = string.replace("(", "")
string = string.replace(")", "")
strings = string.split(",")
return int(strings[0]), int(strings[1]) |
def parse_integer(input, metadata):
"""Parse integer value.
Args:
input: Any input value that can be cast as a number.
Returns:
integer (int): Integer equivalent of input.
Raises:
ValueError: Invalid integer.
"""
if float(input).is_integer():
return int(input)
... |
def splitBy(s, fn):
"""functional style"""
lst, t = [], s
while t:
h, t = fn(t)
lst.append(h)
return lst |
def validate_3octets(value):
"""
Validate 3-octets string.
:param value:
:return:
"""
is_valid = False
try:
is_valid = int(value, base=16) >= 0 and len(value) == 6
except ValueError:
is_valid = False
except TypeError:
is_valid = False
return is_valid |
def floyd_warshall2(weight):
"""All pairs shortest paths by Floyd-Warshall.
An improved implementation by Pascal-Ortiz
:param weight: edge weight matrix
:modifies: weight matrix to contain distances in graph
:returns: True if there are negative cycles
:complexity: :math:`O(|V|^3)`
"""
f... |
def get_category_tuples(categories):
"""
Return the hierarchical tuples representation of the given categories.
"""
def get_sub_category_tuples(sub_categories, records, record):
"""
Update records with sub_caregories' hierarhical tuples.
"""
if sub_categories:
... |
def count_functions(signature, functions):
"""Function counting occurrences of a given functional symbol within the scope of a functional signature.
Arguments:
signature - list of functional symbols (expressed as strings),
functions - list of all available functional symbols (also as strings).
... |
def checkio(lines_list):
"""Return the quantity of squares"""
#small squares
count = 0
for each in lines_list:
each.sort()
for i in range(1,12):
if [i,i+1] in lines_list and [i,i+4] in lines_list and [i+4,i+5] in lines_list and [i+1,i+5] in lines_list:
count += 1
... |
def escape(s):
"""python3-ldap doesn't include this for some reason."""
s = s.replace('\\', r'\\5C')
s = s.replace('*', r'\\2A')
s = s.replace('(', r'\\28')
s = s.replace(')', r'\\29')
s = s.replace('\0', r'\\00')
return s |
def ij2I(i, j):
"""
Convert matrix indices to Voigt notation
"""
if i == 0 and j == 0:
return 0
if i == 1 and j == 1:
return 1
if i == 2 and j == 2:
return 2
if (i == 1 and j == 2) or (i == 2 and j == 1):
return 3
if (i == 0 and j == 2) or (i == 2 and j ==... |
def compute_DC(net_dict, w_ext):
""" Computes DC input if no Poisson input is provided to the microcircuit.
Parameters
----------
net_dict
Parameters of the microcircuit.
w_ext
Weight of external connections.
Returns
-------
DC
DC input, which compensates lackin... |
def remove_adjacent_duplicates(name):
""" Remove adjacent duplicate codes."""
j = 1
while j < len(name):
if name[j] == name[j - 1]:
name = name[:j] + name[j + 1:]
else:
j += 1
return name |
def intTryParse(value):
"""A function that check to see if the value can be convert to integer value or not"""
try:
return int(value), True
except ValueError:
return value, False |
def fid_to_filter_ztf(fid: int):
"""
Convert a fid to a filter name.
In the alert data from Fink, the fid corresponds to the 3 different filters used by the ZTF telescope.
Parameters
----------
fid : int
id of a filter in an alert
Returns
----------
filter : str... |
def Unify(l):
"""Removes duplicate elements from l, keeping the first element."""
seen = {}
return [seen.setdefault(e, e) for e in l if e not in seen] |
def remove_eol(s):
"""Removes trailing '\n' if there is one"""
return s[0:len(s) - 1] if s[len(s) - 1] == '\n' else s |
def processargs(argv):
"""Usage: processargs(argv), where argv is a list() of arguments, example,
sys.argv.
processargs() goes through argv and returns a dictionary that specifies
whether the associated flag was passed."""
output = {"weekly": None, "verbose": None,
"bootstrap": None, "... |
def validate_cipher_suite_id(cipher_suite_id):
"""Validates that a CipherSuite conforms to the proper format.
Args:
cipher_suite_id (int): CipherSuite id.
Returns:
(int): The original CipherSuite id.
"""
if not isinstance(cipher_suite_id, int):
raise TypeError("CipherSuite... |
def convert_f2c(f_in):
"""Convert the value in temp_data from Fahrenheit to Celsius
and store the result in out_data."""
return (f_in - 32) * 5 / 9 |
def _GetTagValue(tags, key, default=None, as_type=None):
"""Get the value of the first occurrence of a tag with a given key."""
if as_type is None:
as_type = lambda x: x
return next((as_type(t['value']) for t in tags if t['key'] == key), default) |
def inv(a, n):
"""
Invert a number n.
Args:
a: write your description
n: write your description
"""
if a == 0:
return 0
lm, hm = 1, 0
low, high = a % n, n
while low > 1:
r = high // low
nm, new = hm - lm * r, high - low * r
lm, low, hm, hi... |
def z2a(z):
"""
redshift to scale factor
"""
return 1./(1.+z) |
def triangle(nth):
"""
Providing n'th triangle number.
:param nth: index for n'th triangle
:returns: n'th triangle number
see http://en.wikipedia.org/wiki/Triangular_number
>>> triangle(3)
6
>>> triangle(4)
10
"""
return (nth * (nth + 1)) // 2 |
def memvname(funcname):
"""
:param funcname:
:return:
"""
return funcname + "_memver" |
def Dic_Sort_Value_by_Key_Seq(indic,keylist):
"""
Return a list of dic values, with their sequence as provided in keylist
"""
outlist=[]
for key in keylist:
outlist.append(indic[key])
return outlist |
def iou(intersection, data_mag, query_mag):
"""Finds the IOU for two bloom filters.
Args:
intersection: The intersection of the two genes.
data_mag: The magnitude of the gene being compared to.
query_mag: The magnitude of the gene being searched for.
Returns:
The IOU for th... |
def status_code(chain_name, on_failed_configuration) -> int:
"""returns the status code to be matched based on the current run"""
if chain_name == "successful_chain":
return 200
return on_failed_configuration.get("error_status_code", 503) |
def strip_chrom(chrom):
"""
Remove Chr or chr from the chromosome id
:param chrom: String
:return: String
"""
if 'chr' in chrom.lower():
return chrom[3:]
else:
return chrom |
def get_record_time(time, num_tweets):
"""
time to predict 1 record only
"""
svm_time_record = time / num_tweets
return svm_time_record |
def int_to_bytes(x: int) -> bytes:
""" Convert int to bytes """
return x.to_bytes(4, byteorder='big') |
def normal_approx_interval(p_hat, n, z=1.96):
""" approximating the distribution of error about a binomially-distributed observation, {\hat {p)), with a normal distribution
z = 1.96 --> alpha =0.05
z = 1 --> std
https://www.wikiwand.com/en/Binomial_proportion_confidence_interval"""
return z*((p_hat*... |
def getTASA(ChargeSA):
"""The calculation of total hydrophobic surface area
-->TASA
"""
res = 0.0
for i in ChargeSA:
if abs(float(i[1])) < 0.2:
res = res + i[2]
return res |
def non_zero(dy, dx):
"""Make sure slope is slightly non-zero"""
if dx == 0:
return 0.00001
return max(0.00001, dy / dx) |
def qadd(quat1, quat2):
"""quaternion addition
:param quat1: first quaternion
:param quat2: second quaternion
:return: sum of the two quaternions; q_out = quat1 + quat2
"""
return [q1+q2 for q1, q2 in zip(quat1, quat2)] |
def mib_to_gib(value):
"""
Returns value in Gib.
"""
return float(float(value) / 1024.0) |
def check_cn_match(sv_list, cn_increase, cn_decrease, final_cn):
"""
Check that the CNV combination produces the right final copy number.
"""
if sv_list == []:
return False
initial_cn = 2
for sv in sv_list:
if sv in cn_increase:
initial_cn += 1
if sv in cn_dec... |
def tick_diff(t1, t2):
"""
Returns the microsecond difference between two ticks.
t1:= the earlier tick
t2:= the later tick
...
print(picod.tick_diff(4294967272, 12))
[#36#]
...
The correct result is returned even if tick has wrapped around.
"""
tDiff = t2 - t1
if tDiff < 0:
... |
def _WrapUnaryOp(op_fn, inner, ctx, item):
"""Wrapper for unary operator functions.
"""
return op_fn(inner(ctx, item)) |
def escapeName(name):
"""Escape a name such that it is safe to use for files and anchors."""
escape = '_'
xs = []
for c in name:
if c.isalpha() or c in ['-']:
xs.append(c)
else:
xs += [escape, str(ord(c))]
return ''.join(xs) |
def parse_query(orig_query):
"""Divide query into command name and search query.
Args:
orig_query ([str]): The original query.
Returns:
(str, str): Command name and search query.
Some assumptions are made about the original query:
* If only one element in the orig query and the elem... |
def group_type_object_factory(group_type_name):
"""Cook up a fake group type """
group_type = {
'name': group_type_name
}
return group_type |
def scrub_list(alist):
"""
Take a comma-separate list, split on the commas, and scrub out any leading
or trailing whitespace for each element.
"""
return [p.strip() for p in alist.split(',')] |
def indirect(deps):
""" Return the set of indirect and direct dependencies """
return {(a, b) for a, b, c in deps} |
def find_between_r(s, first, last):
"""Description of find_between_r (s, first, last)
:param s: A string
:param first: Beginning delimiter for substring
:param last: Ending delimiter for substring
:type s: string
:type first: string
:type last: string
:return: Substring contained betwee... |
def sorted_for_ner(crf_classes):
"""
Return labels sorted in a default order suitable for NER tasks:
>>> sorted_for_ner(['B-ORG', 'B-PER', 'O', 'I-PER'])
['O', 'B-ORG', 'B-PER', 'I-PER']
"""
def key(cls):
if len(cls) > 2 and cls[1] == '-':
# group names like B-ORG and I-ORG ... |
def bin_stats(arr) -> str:
"""Return a string basic statistics for a binary array of either {0,1} or {True,False}"""
n = len(arr)
k = sum(arr)
p = 100. * k / n if n != 0 else 0.
return f"{k}/{n} ({p:.2f}%)" |
def create_random_forest_param_grid(num_estimators, max_depths,
min_samples_leaves, num_workers=1):
"""
Returns a parameter grid for a random forest
:param num_estimators: list
:param max_depths: list
:param min_samples_leaves: list
:param num_workers: int
... |
def convert_practitioner_fhir_to_form(pract_res, user):
"""Converts a Practitioner Resource into Values for Form"""
data = {}
data['user'] = user
data['first_name']= pract_res['name'][0]['given'][0]
data['last_name']= pract_res['name'][0]['family'][0]
data['npi']= pract_res['identifier'][0]['val... |
def strip_2tuple_from_dict(dict):
"""
Strips the first value of the tuple out of a dictionary
{key: (first, second)} => {key: second}
"""
new_dict = {}
for key, (first, second) in dict.items():
new_dict[key] = second
return new_dict |
def remove_redundancies(levels):
"""
There are repeats in the output from get_levels(). We
want only the earliest occurrence (after it's reversed)
"""
seen = []
final = []
for line in levels:
new_line = []
for item in line:
if item not in seen:
see... |
def is_empty(s):
"""Check if input string or iterable is empty.
:param s: String or iterable to check.
:return: True if input is empty.
"""
if s:
return False
else:
return True |
def get_common_movies(first_actor_credits, second_actor_credits):
"""
Takes two arrays of actor credits, first_actor_credits and second_actor_credits
Returns an array of movies that are common to both actors
"""
common_movies = []
for first_movie in first_actor_credits:
for second_movie in second_actor_... |
def match_end(names):
"""
"""
if len(names) == 1:
if names[0]=="END":
return 1
return 0 |
def weightsNormalizer(destinations):
"""Normalizes each vertex's out-going weight sum to one."""
destinations = list(destinations)
newDestinations = []
sum = 0
for destination, weight in destinations:
sum += weight
for destination, weight in destinations:
newDestinations.appen... |
def dateIsBefore(year1, month1, day1, year2, month2, day2):
"""Returns True if year1, month1, and day1 is before
year2, month2 and day2. Otherwise returns False
"""
if year1 < year2:
return True
if year1 == year2:
if month1 < month2:
return True
if month1 == m... |
def equality(iterable: list) -> bool:
"""
Check equality of ALL elements in an interable.
>>> equality([1, 2, 3, 4])
False
>>> equality([2, 2, 2, 2])
True
>>> equality([1, 2, 3, 2, 1])
False
"""
return len(set(iterable)) in (0, 1) |
def ishl7(line):
"""Determines whether a *line* looks like an HL7 message.
This method only does a cursory check and does not fully
validate the message.
:rtype: bool
"""
# Prevent issues if the line is empty
return line and line.strip()[:3] == "MSH" and line.count("MSH") == 1 |
def play(start_num):
"""You choose number N. Tom and Jerry will play the game alternatively and
each of them would subtract a number n [n< N] such that N%n=0. The game
is repeated turn by turn until the one,who now cannot make a further
move looses the game. The game begins with Tom playing fi... |
def f(x):
"""
((1-x**(ELEMENT_BOUND + 1)) / (1-x))**SIZE
"""
y = 1/(1-x)
return y |
def hexencode(rgb):
"""Transform an RGB tuple to a hex string (html color)"""
r=int(rgb[0])
g=int(rgb[1])
b=int(rgb[2])
return '#%02x%02x%02x' % (r,g,b) |
def get_rf_checksum(rf_base):
"""
Get the two checksum digits by subtracting modulo 97 of RF base from 98
"""
remainder = int(rf_base) % 97
digits = 98 - remainder
if digits < 10:
return '0' + str(digits)
return str(digits) |
def up(state):
"""move blank space up on the board and return new state."""
new_state = state[:]
index = new_state.index(0)
if index not in [0, 1, 2]:
temp = new_state[index - 3]
new_state[index - 3] = new_state[index]
new_state[index] = temp
return new_state
else:
... |
def clean_dict_values(d, v_list):
"""Returns a NEW dictionary cleaned from values provided in a list"""
return {k:v for k,v in d.items() if v not in v_list} |
def sqrt(x: float, epsilon: float = 1e-6) -> float:
"""
Square root
"""
a = 0
b = x
r = x
xp = r*r
while abs(x-xp) > epsilon:
r = (a+b)/2
xp = r*r
if xp < x:
a = r
else:
b = r
return r |
def create_moves(x, y):
"""Create all valid moves from (x, y)"""
a, b = x, y
moves = []
for c in range(max(x, y)):
if min(a, b) == 0:
if a >= b:
moves.append((c, b))
if b >= a:
moves.append((a, c))
elif (max(a, b) - c) % min(a, b) =... |
def get_header(data):
"""Collect column names from every data set."""
header = set()
for datum in data:
header.update(datum.keys())
return list(header) |
def ParamFromSearchParam(searchParam):
"""Get a parameter from a search parameter
>>> ParamFromSearchParam('R1 =')
'R1'
"""
return searchParam[:-2] |
def _to_space_separated_string(l):
"""
Converts a container to a space-separated string.
INPUT:
- ``l`` -- anything iterable.
OUTPUT:
String.
EXAMPLES::
sage: import sage.geometry.polyhedron.misc as P
sage: P._to_space_separated_string([2,3])
'2 3'
"""
s... |
def strip_url(domain, www=None):
"""
receive a URL Field and remove leading http:// or https://
optionally remove www.
:param url: eg. http://www.medyear.com
:param www remove the prefix passed = "www."
:return:
"""
u = str(domain)
u = u.lower()
check_for_http = "http://"
ch... |
def debug_path(path, map, passable_values):
"""
Path debugging function
"""
if len(path) == 0:
return True
for pos in path:
x, y, z = pos[0], pos[1], pos[2]
# checking if there is some issue with my head
if z + 2 > len(map):
print(f'My head is sticking out... |
def fizzbuzztree(tree):
"""
Transform the node values of the tree to fizzbuzz results.
"""
if not tree:
return tree
def _walk(node):
if node is None:
return
_walk(node.right)
_walk(node.left)
if node.value % 3 == 0:
if node.value % 5 ... |
def check_description(sig_info, error):
"""
Check description
:param sig_info: content of sig-info.yaml
:param error: error count
:return: error
"""
if 'description' not in sig_info.keys():
print('ERROR! description is a required field')
error += 1
else:
print('Ch... |
def inverse_exner(theta,p):
"""convert potential temperature to temperature"""
rcp=287.04/1004.0
t= theta/(1000.0/p)**rcp
return t |
def generate_bucket_arn_from_name(bucket_name):
"""
the bucket arn that we require for setting a policy on an SQS queue can be
derived directly from the bucket name, meaning we do not need to make
any calls to AWS to obtain this if we already have the bucket name.
>>> generate_bucket_arn_from_name(... |
def make_string(seq):
"""
Don't throw an exception when given an out of range character.
"""
string = ''
for c in seq:
# Screen out non-printing characters
try:
if 32 <= c and c < 256:
string += chr(c)
except TypeError:
pass
# I... |
def compoundInterest(amount_borrowed, years_borrowed, interest_rate_percent):
"""assumes amount_borrowed in an int, representing the amoutn fo money borrowed
assumes year+borrowed is an int, representing the years the amount was borrowed for
assumes interest_rate_percent is a number, representing the intere... |
def IsInt(v) -> bool:
"""
Check if the parameter can be int.
v: Variable to check.
SUCCESS Returns ``True``.
FAILURE Returns ``False``.
"""
try:
int(v)
return True
except Exception as ex:
print(ex)
return False |
def ConvertToNW(location):
"""
takes a location as a signed long, lat string and converts to NSEW string
"""
long, lat = map(float, location.split(",") )
if not -180 <= long <= 180:
raise "Longitude out of range"
if not -90 <= lat <= 90:
raise "latitude out of range"
... |
def read_portal(lines, x, y):
"""x,y is a potential portal spot."""
for (a,b) in [[(-2, 0), (-1, 0)], [(1,0), (2,0)], [(0, -2), (0, -1)], [(0, 1), (0, 2)]]:
try:
if lines[y][x] != '.':
return False
ac = lines[y + a[1]][x + a[0]]
bc = lines[y + b[1]][x ... |
def fmt_time(s, minimal=True):
"""
Args:
s: time in seconds (float for fractional)
minimal: Flag, if true, only return strings for times > 0, leave rest outs
Returns: String formatted 99h 59min 59.9s, where elements < 1 are left out optionally.
"""
ms = s - int(s)
s = int(s)
... |
def proto_check(proto):
"""Checks if protocol is TCP or UDP
Parameters
----------
proto: int
The protocol number in the FCN/CN message
Returns
-------
The protocol name if TCP/UDP else returns nothing
"""
# Check for TCP
if proto == 6:
return 'tcp'
# Ch... |
def check_validity(board, insertion, location):
"""
Iterates through the board to check if a certain insertion is valid at the current location
Parameters:
board (2D list): Contains the board going to be solved.
insertion (int) : Contains the number being inserted to the empty node
... |
def magnitude(u):
"""returns the magnitude (length) of vector u"""
return (u[0]**2 + u[1]**2 + u[2]**2)**0.5 |
def get_links(rlinks):
"""
returns list of titles/urls from query/parse links response
"""
if rlinks is None:
return
links = []
for item in rlinks:
if 'url' in item:
links.append(item['url'])
if 'title' in item and 'ns' in item:
if item['ns'] == 0:... |
def _partition_list(items, split_on):
"""
Partition a list of items.
Works similarly to str.partition
Args:
items:
split_on callable:
Should return a boolean. Each item will be passed to
this callable in succession, and partitions will be
created any... |
def echo(s):
"""
Test function
Parameters
----------
s : string
string to return (echo)
Returns
-------
s : string
Examples
--------
>>>echo('This was a triumph!')
This was a triumph!'
"""
print(s)
return s |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.