content stringlengths 42 6.51k |
|---|
def kernchecker_dict(splitkerns, platforms):
"""
Prepare results dictionary.
:param splitkerns: Split kernel branches.
:type splitkerns: list(str)
:param platforms: List of platform dicts.
:type platforms: list(dict)
"""
kerndict = {x: [] for x in platforms}
for kernel in splitkern... |
def multiplyIsOverflow(a, b):
"""
Function to check whether there is
overflow in a * b or not. It returns
true if there is overflow.
Returns
-------
True if overflow else False.
"""
# Check if either of them is zero
if a == 0 or b == 0:
return False
result = a *... |
def ValidateAtMostOneSelected(*args):
"""Validates that at most one of the argument flags is selected.
Returns:
True if more than 1 flag was selected, False if 1 or 0 were selected.
"""
count = 0
for arg in args:
if arg:
count += 1
return count > 1 |
def is_valid_identifier(string):
"""Check if the string is a valid project/package name.
.. note::
Valid characters for ``projectName`` are::
* uppercase and lowercase letters A through Z
* underscore '_'
* the digits 0 through 9 except for the first character
... |
def all_instances_of(iterable: list, kind: type) -> bool:
"""Returns true is all elements of the given list are instances of [kind]"""
return all(isinstance(x, kind) for x in iterable) |
def level_10(num):
"""Return the next number in the 'see-and-say' sequence, given a number.
The next number in the sequence is found by saying the count of each digit,
in order, in the current number.
"""
# ensure the input is a number as a string
num_as_str = str(num)
cou... |
def float_div(num1, num2):
"""Floating point division, even for ints: float(num1)/num2."""
return float(num1)/num2 |
def triple(n):
""" (number) -> number
Returns triple a given number.
>>> triple(9)
27
>>> triple(-5)
-15
>>> triple(1.1)
3.3
"""
one = n * 3
return (one) |
def first_line(text, keep_empty=False, default=None):
"""First line in 'data', if any
Args:
text (str | list | None): Text to examine
keep_empty (bool): When False skip empty lines (+ strip spaces/newlines), when True don't filter (strip newlines only)
default (str | None): Default to r... |
def avg(l):
"""
Returns the average between list elements
"""
return sum(l) / float(len(l)) |
def find(predicate, iterable):
"""Find the first matching item in a list, or None if not found.
This is as a more-usable alternative to filter(), in that it does
not raise an exception if the item is not found.
Args:
predicate: A function taking one argument: an item from the iterable.
ite... |
def _get_package_dict1(reqs: str) -> dict:
"""Helper to parse requirements str into a dict of
(package, version) k, v pairs
"""
return dict(line.split("==") for line in reqs.strip().splitlines()) |
def sanitize_id(id):
"""Removes unallowed chars from an ID.
Ids may only contain a-z, A-Z, 0-9, - and must have one character.
Args:
id: the ID to be sanitized.
Returns:
A sanitized ID.
"""
return id.replace(':', '-') |
def is_int(value):
"""
Return true if the input can be converted to an int.
"""
if value is None:
return False
try:
int(value)
return True
except ValueError:
return False |
def signum(number):
"""Self-explanatory."""
if(number < 0): return -1
elif(number > 0): return 1
else: return 0 |
def tuple_compare_lt(left, right):
"""Compare two 'TupleOf' instances by comparing their individual elements."""
for i in range(min(len(left), len(right))):
if left[i] > right[i]:
return False
if left[i] < right[i]:
return True
return len(left) < len(right) |
def element_wise_list_summation(list_1, list_2):
"""
Element-wise summation of two lists of the same length.
"""
return [value_1 + value_2 for value_1, value_2 in zip(list_1, list_2)] |
def convert_iob_to_iobes(iob_tags):
"""Converts a sequence of IOB tags into IOBES tags."""
iobes_tags = []
# check each tag and its following one. A None object is appended
# to the end of the list
for tag, next_tag in zip(iob_tags, iob_tags[1:] + [None]):
if tag == 'O':
io... |
def diff_1(arrA, arrB):
"""
Runtime: O(n^2)
"""
results = []
## iterate over arrA and look if its elements don't belong to arrB
for x in arrA:
if x not in arrB:
results.append(x)
## repeat the same for arrB
for x in arrB:
if x not in arrA:
result... |
def toggle_manual_match_form(method):
""" Hide/show field based on other values """
# This one is for manually picking years.
# 1=override (manual match). 0= auto match
# Test
if method == 1:
return "visible"
return "hidden" |
def find_preferred_mag(mags, prefmaglist=[]):
"""
Given a seq of mag dicts, return the id of the preferred one
Note
----
Returns the preferred of the last of any given type, so multiple 'mw'
magnitudes will return the last one. If using reverse-sorted time
magnitudes, (like the Database... |
def bin2dec(n):
"""Convert a binary number to decimal.
Args:
n (str): The string representation of a binary number to convert.
Returns:
int: The result decimal number if n is valid.
"""
return int(n, 2) |
def not_between(a, b):
"""Evaluates a not between b[0] and b[1]"""
if not isinstance(b, list):
raise TypeError('other value must be a list of length 2')
result = b[0] <= a <= b[1]
return False if result else True |
def _to_db_dict(namespace_id, resource_type_id, model_dict):
"""transform a model dict to a metadef_namespace_resource_type dict"""
db_dict = {'namespace_id': namespace_id,
'resource_type_id': resource_type_id,
'properties_target': model_dict['properties_target'],
'p... |
def remove_enclosing_new_line(text):
""" Return a copy of the string *text* with leading and trailing newline removed.
"""
i_min = 1 if text[1] == '\n' else 0
i_max = -1 if text[-1] == '\n' else None
return text[i_min:i_max] |
def count_value(value, values):
"""
Count the number of appearances
Parameters :
-----------
value : int
Cluster label
values : ndarray of shape (n_samples, )
Sample labels
Return :
-------
count : int
Number of ... |
def istril(*index):
"""Return whether and index is in the lower triangle of an array."""
return index[0] <= index[1] |
def _validate_actions(base_actions, inbound_actions, require_all_actions=True):
"""
Check that the inbound actions matches against the base actions
"""
if base_actions:
if len(inbound_actions) == 0 or (
len(base_actions) == 1 and base_actions[0] == ""
):
valid_act... |
def type_arg_size(type_):
""" Given a type object, return the size """
if type_ in ["void"]:
return 0
if type_ in ["int", "float"]:
return 4
if type_ in ["long", "double"]:
return 8
return type_._arg_size_() |
def get_y_indicator_variable_index(i, j, m, n):
"""
Map the i,j indices to the sequential indicator variable index
for the y_{ij} variable.
This is basically the (2-dimensional) 'array equation' (as per
row-major arrays in C for example).
Note that for MiniSat+, the variables are juist indexed... |
def insertTiming(dictOfDF_norm):
"""
Parameters
----------
dictOfDF_norm : dictionary of DataFrames
Contains single sweep data with normalized float32 values
Returns
-------
dictOfDF_norm : dictionary of DataFrames
Contains single sweep data with normalized float32 values
... |
def get_unlabled_last_index(
num_unlabeled_samples,
len_dataset,
len_class):
"""
For example, for CIFAR100 we have len_dataset 10000 for test data.
The number of samples per class is 1000.
If we want 9000 unlabeled samples then the ratio_unlabeled is 9/10.
The number of sampl... |
def createOneRow(width):
""" returns one row of zeros of width "width"...
You might use this in your createBoard(width, height) function """
row = []
# print "width is", width
for _ in range(width):
row += [0]
return row |
def blocks_list_to_strings_list(blocks_list: list, curr_text: list) -> list:
""" Convert blocks list to len of blocks strings """
strings_len_list = []
for block in blocks_list:
# Append size of block in string
strings_len_list.append(len(' '.join(map(str, curr_text[block.a:block.a + block... |
def compute_depths(roots, vertices, edges):
"""The 'depth' of a vertex is its minimal distance from any root."""
depths = {}
curdepth = 0
for v in roots:
depths[v] = 0
pending = list(roots)
while pending:
curdepth += 1
prev_generation = pending
pending = []
... |
def get_b2aset(a2bset):
"""Given gene2gos, return go2genes. Given go2genes, return gene2gos."""
b2aset = {}
for a_item, bset in a2bset.items():
for b_item in bset:
if b_item in b2aset:
b2aset[b_item].add(a_item)
else:
b2aset[b_item] = set([a_it... |
def _assign_if_not_none(obj, param, value):
"""A method to quickly assign a value if it is not none to either a dictionary or an object."""
if value:
if isinstance(obj, dict):
obj[param] = value
else:
setattr(obj, param, value)
return True
return False |
def is_prime(num):
"""
Checks if a number is prime
"""
prime_counter = 1
for x in range(1, num):
if num % x == 0:
prime_counter += 1
if prime_counter > 2:
return False
return True |
def plural_of (noun) :
"""Returns the plural from of the (english) `noun`.
>>> print (plural_of ("house"))
houses
>>> print (plural_of ("address"))
addresses
>>> print (plural_of ("enemy"))
enemies
"""
result = noun
if result.endswith ("s") :
result += "es"
elif res... |
def is_repo_image(image):
"""
Checks whether the given image has a name, i.e. is a repository image. This does not imply that it is
assigned to an external repository.
:param image: Image structure from the Docker Remote API.
:type image: dict
:return: ``False`` if the only image name and tag i... |
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
"""
... |
def _get_loop_type_direct(asm_str):
"""decode loop type"""
if asm_str.startswith('*'):
return False
elif asm_str.startswith('#'):
return True
else:
raise SyntaxError('Syntax error in loop notation') |
def nova_except_format(logical_line):
"""Check for 'except:'.
nova HACKING guide recommends not using except:
Do not write "except:", use "except Exception:" at the very least
N201
"""
if logical_line.startswith("except:"):
return 6, "NOVA N201: no 'except:' at least use 'except Excepti... |
def _calc_cr(r_jp, r_j, r_jm, vel):
"""
Calculates cr value used in superbee advection scheme
"""
eps = 1e-20 # prevent division by 0
if abs(r_j) < eps:
fac = eps
else:
fac = r_j
if vel > 0:
return r_jm / fac
else:
return r_jp / fac |
def ringIsClockwise(ringToTest):
"""
determine if polygon ring coordinates are clockwise. clockwise signifies
outer ring, counter-clockwise an inner ring or hole.
"""
total = 0
i = 0
rLength = len(ringToTest)
pt1 = ringToTest[i]
pt2 = None
for i in range(0, rLength - 1):
... |
def optional_string(value):
"""Raise an exception if a value isn't a string, or None."""
if not isinstance(value, (str, type(None))):
raise ValueError("Expected a string value or None, received %s." % value) # pragma: no cover
return value |
def broadcast(item, length, allowed_types, name="item"):
"""Broadcast item to given length.
Parameters
----------
item : object
Object to broadcast
length : int
Length to broadcast to
allowed_types : list
List of allowed types
name : str, optional
Name of ite... |
def print_and_count_remaining(target_numbers:list, enable_print:bool, answer_number:str) -> int:
"""
print and count remaining.
"""
remaing_count = 0
is_left_answer = False
if enable_print:
print("----+-----")
for i, item in enumerate(target_numbers):
remaing_count += 1
... |
def get_labels05():
"""
Return the labels with ID 05.
"""
return [
"A",
"B",
"C",
"D",
"E",
] |
def is_sitemap(content):
"""Check a string to see if its content is a sitemap or siteindex.
Attributes: content (string)
"""
if 'http://www.sitemaps.org/schemas/sitemap/' in content or '<sitemapindex' in content:
return True
return False |
def local_radius(x, y):
"""Returns radius of the circle going through a point given it's local coordinates."""
if x != 0:
return (x**2 + y**2) / abs(2 * x)
else:
return y**2 |
def validateTokens(tokens):
"""
Make sure there is at least one token longer than one character
@param tokens: the tokens to inspect
@type tokens: iterable of utf-8 encoded strings
@return: True if tokens are valid, False otherwise
@rtype: boolean
"""
for token in tokens:
if le... |
def parse_from(parses):
"""
parse the from status, then converting them into cypher
:param parses: sql parse
:return: string cypher
"""
tables = {}
if "from" not in parses.keys():
print("no from status")
return None
command = "MATCH "
if type(parses["from"]) is list:... |
def type_to_python(typename, size=None):
"""type_to_python(typename: str, size: str) -> str
Transforms a Declarations.yaml type name into a Python type specification
as used for type hints.
"""
typename = typename.replace(' ', '') # normalize spaces, e.g., 'Generator *'
# Disambiguate explici... |
def __collatz_recursivo(numero: int, pasos: list) -> list:
"""Calcula recursivamente la conjetura de Collatz, devuelve los pasos realizados"""
pasos.append(numero)
if numero == 1:
return pasos
if numero % 2 == 0:
return __collatz_recursivo(numero // 2, pasos)
return __collatz_recurs... |
def as_dict(original_names, names):
"""Map slugs to original names {slug-name: orig-name, ...}"""
return dict(zip(names, original_names)) |
def _is_nonempty_observation(obs):
"""Check if an observation has no tokens in it."""
return len(obs.get('text_vec', [])) > 0 |
def tally(word, values):
"""
Takes a string and a dictionary of scrabble letter vlaues
Returns the same of each char's value in the string
"""
return sum([values[x] for x in word]) |
def totalBrought(guests: dict, item: str) -> int:
"""Total brought
Totals given item from given guest dictionary and returns result.
Args:
guests: Dictionary with guest's names and what they are bringing.
item: Specific item in guest dictionary that is to be totaled.
Returns:
... |
def fall(vfz):
"""Compute the fall damage inflicted given final vertical speed on touch.
Return the untruncated damage corresponding to touch-ground vertical speed
*vfz*. Only positive *vfz* values are meaningful.
"""
return max(0.0, 25 * (vfz - 580) / 111) |
def _tn2tstdn_par(mu, sigma, a, b):
"""
Convert `a` and `b` of a truncated normal distribution to a truncated standard normal distribution.
Parameters
----------
mu : float
Mean.
sigma : float
Standard deviation.
a : float
Minimum.
b : float
... |
def search_escape(url):
"""Escape URLs such that preexisting { and } are handled properly.
Will obviously trash a properly-formatted qutebrowser URL.
"""
return url.replace('{', '{{').replace('}', '}}') |
def get_findings(patrowl_api, asset_id):
"""
Get asset findings
"""
try:
return patrowl_api.get_asset_findings_by_id(asset_id)
except:
pass
return list() |
def to_mass_fraction(molar_ratio, massfrac_denominator, numerator_mass, denominator_mass):
"""
Converts per-mass concentrations to molar elemental ratios.
Be careful with units.
Parameters
----------
molar_ratio : float or array-like
The molar ratio of elements.
massfrac_de... |
def quick_sort(list_values):
"""
Given a list, sort it using quick sort algorithm.
Working of quick sort: Take the last element as pivot,...
Partition the array around the pivot, and recursively sort the two sub-lists.
If the list contains one value, return the array.
"""
if len(list_values... |
def is_null_str(value):
"""
Indicate if a string is None or 'None' or 'N/A'
:param value: A string value
:return: True if a string is None or 'None' or 'N/A'
"""
return not value or value == str(None) or value == 'N/A' |
def lerp(a, b, t):
"""
linear interpolation.
"""
return a + (b - a) * t |
def _chomp_element(base, index, value):
"""Implementation of perl = and chomp on an array element"""
if value is None:
value = ''
base[index] = value.rstrip("\n")
return len(value) - len(base[index]) |
def _get_freq(name):
"""
Check if name read contains counts (_xNumber)
"""
try:
counts = int(name.split("_x")[1])
except:
return 0
return counts |
def get_repository_components_for_installation( encoded_tsr_id, encoded_tsr_ids, repo_info_dicts, tool_panel_section_keys ):
"""
The received encoded_tsr_ids, repo_info_dicts, and tool_panel_section_keys are 3 lists that contain associated elements at each location in
the list. This method will return the ... |
def no_duplicates(file, attribute="Name"):
"""Assert whether or not dict has duplicated Names.
`attribute` can be another attribute name like "$id".
Args:
file (str or dict): Path of the json file or dict containing umi objects groups
attribute (str): Attribute to search for duplicates in ... |
def scale_chi(chi, L, nu, gamma):
"""
Scales the susceptibility chi according to finite size scaling.
:param chi: List of values chi to be scaled.
:param L: System size.
:param nu: Critical exponent.
:param gamma: Critical exponent.
:return list: Scaled probabilites.
"""
re... |
def escape_windows_cmd_string(s):
"""Returns a string that is usable by the Windows cmd.exe.
The escaping is based on details here and emperical testing:
http://www.robvanderwoude.com/escapechars.php
"""
for c in '()%!^<>&|"':
s = s.replace(c, '^' + c)
s = s.replace('/?', '/.')
retur... |
def partition(region) -> str:
"""Return partition, such as aws, aws-cn, for use in tests."""
region_partition_amp = {
"us-gov-west-1": "aws-us-gov",
"cn-north-1": "aws-cn",
"cn-northwest-1": "aws-cn",
}
return region_partition_amp.get(region, "aws") |
def compare_motif_cterm(peptide, motif):
"""C-term position specific motif match."""
for i in range(len(motif)):
if peptide[-(i+1)]!=motif[-(i+1)] and motif[-(i+1)]!='x':
return 0
return 1 |
def grade_display(actual, max_grade):
"""
Nicely formats the grades for display to the user
"""
def formatter(value):
if round(value, 8) == round(value,0):
return '%0.0f' % value
else:
return '%0.1f' % value
if actual is not None:
return '%s/%s' % (fo... |
def sort_json_object(obj):
""" Example
# Check if there are any changes
if not sort_json_object(data) == sort_json_object(old_data):
# There are changes
else:
# There are no changes
:param obj: The json object to sort
"""
if isinstance(obj, dict):
... |
def get_er_frequences(er_data, total_number_of_transcripts):
"""Determine ER frequencies"""
for er in er_data:
ex_num = len(er_data[er].ex_ids)
tx_num = len(er_data[er].tx_ids)
er_data[er].ex_num = ex_num
er_data[er].tx_num = tx_num
er_data[er].gene_tx_num = total_number_... |
def is_generator(iterable):
"""
Check if an iterable is a generator.
Args:
iterable: Iterable.
Returns:
boolean
"""
return hasattr(iterable, '__iter__') and not hasattr(iterable, '__len__') |
def transform_req_limit(req, limit, default_req, default_limit):
""" return reqest, limit, this ensure that req <= limit """
if req is None and limit is None:
return default_req, default_limit
elif req is None:
return limit, limit
elif limit is None:
return req, req
else:
... |
def json_replace_date(json_input):
"""Replace date values in json by dummy to enable meaningful comparison"""
for item in json_input['snapshots']:
if item['date']:
item['date'] = 'removed_date'
return json_input |
def triple_step_iterative(nb_of_steps):
"""
The most naive implementation, using 3 variables corresponding
to the 3 previous states, we calculate the next and update them
continuously until we've looped up to nb_of_steps.
"""
a, b, c = 0, 0, 1
for step in range(nb_of_steps):
temp_var... |
def lerp(a, b, x):
"""Linear interpolation function."""
return a + x * (b - a) |
def get_cardinal_direction(direction: int) -> str:
"""
Returns the cardinal direction (NSEW) for a degree direction
Wind Direction - Cheat Sheet:
(360) -- 011/012 -- 033/034 -- (045) -- 056/057 -- 078/079 -- (090)
(090) -- 101/102 -- 123/124 -- (135) -- 146/147 -- 168/169 -- (180)
... |
def dict_to_rank_order(vote_dict):
"""
Convert a vote of the form {candidate: rank, ...} (1 best, 2 second-best, etc.)
to [{set of candidates 1}, {set of candidates 2, ...}] (best first)
:param vote_dict: vote as dictionary
:return: vote as ranked list of tied sets
"""
inverse_dict = ... |
def get_icd9_descript_path(data_dir):
"""Get path of icd9 description file."""
return '{}/{}'.format(data_dir, 'phewas_codes.txt') |
def blend_union(da, db, r):
""" Blend union of the distances da, db with blend radius r. """
e = max(r - abs(da - db), 0)
return min(da, db) - e * e * 0.25 / r |
def get_int(entry):
"""
This function ...
:param entry:
:return:
"""
try: return int(entry)
except ValueError:
value = entry.split(" / ")[0].rstrip()
return int(value) |
def fatorial(n , show= False):
"""
<<<Calcula o fatorual de um numero>>
:param n: ' Numero a ser fatorado'
:param show: 'Chave (OPCIONAL) para fazer print do calculo
:return: 'Retorno da fatorial
"""
f = 1
for c in range(n, 0, -1):
f *= c
if show:
print(f'{c}'... |
def extract_name_value(data: dict) -> tuple:
"""Extract name and value from a simple item, take first dictionary if it is a list."""
item = data.get("SimpleItem", {})
if isinstance(item, list):
item = item[0]
return (item.get("@Name", ""), item.get("@Value", "")) |
def normalizeKerningValue(value):
"""
Normalizes kerning value.
* **value** must be an :ref:`type-int-float`.
* Returned value is the same type as input value.
"""
if not isinstance(value, (int, float)):
raise TypeError("Kerning value must be a int or a float, not %s."
... |
def _write_instance(entity, value, sep = '&'):
"""Helper function to write the search string.
Helps to write the search string, can handle lists and values.
The different entities have to be known and can be found out with the documentation.
Parameters
----------
entity : string
The n... |
def str_format(format_string, *args, **kwargs):
"""
Use python's advanced string formatting to convert the format string and arguments.
References
----------
https://www.python.org/dev/peps/pep-3101/
"""
return format_string.format(*args, **kwargs) |
def count_zero(data):
"""helper function's helper function to count zeros in data."""
count = 0
for ticker in data:
if ticker == 0:
count += 1
return count |
def parse_sqlplus_arg(database):
"""Parses an sqlplus connection string (user/passwd@host) unpacking the user, password and host.
:param database: sqlplus-like connection string
:return: (?user, ?password, ?host)
:raises: ValueError
when database is not of the form <user>/<?password>@<host>
... |
def not_all_alpha(r):
"""
:param r: (str) User's input
:return: (bool) Whether user's input are all letters and no punctuation marks
"""
a = 0
for ch in [r[0], r[2], r[4], r[6]]:
if not ch.isalpha():
a += 1
if a > 0:
return True |
def error_quantifier(x, full_correct_value=1, full_deletion_value=0,
full_substitution_value=0.6, correct_seg_value=1,
substitution_seg_value=0.6, epenthesis_penalty=-0.3):
"""
Generates a float value quantifying phonological error patterns
generated by error_... |
def _decoding_base_info(encoded_info):
"""
Decode base info
Args:
encoded_info(list or dict): encoded base info
"""
if isinstance(encoded_info, dict):
return encoded_info
base_info = dict()
for item in encoded_info:
base_info[item['symbol']] = item['base']
return... |
def mb_Mw_Lin_DiGiacomo2015(MagSize, MagError):
"""
Linear
"""
if MagSize >= 4.0 and MagSize <= 6.5:
M = 1.38 * MagSize - 1.79
E = MagError
else:
M = None
E = None
return (M, E) |
def _afunc(m, n):
"""
A(m,n) e.g. A(365,1)
"""
res = 1
for i in range(n):
res *= (m - i)
return res |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.