content stringlengths 42 6.51k |
|---|
def needs_update(targ_capacity, curr_capacity, num_up_to_date):
"""Return whether there are more batch updates to do.
Inputs are the target size for the group, the current size of the group,
and the number of members that already have the latest definition.
"""
return not (num_up_to_date >= curr_ca... |
def integer_to_digit(integer):
"""
Converts an integer into the corresponding hexadecimal digit.
The integer given should be between 0 and 15 and return a string.
:param integer: *(int)*
:return: the hexadecimal digit representing the integer
:rctype: *str*
:UC: 0 <= integer < 16
:Examp... |
def gcd(a, b):
""" compute gcd a and b"""
if a == 0:
return b
if b == 0:
return a
return gcd(b, a % b) |
def getfrom(key, mapping):
"""
Gets value from mapping or None (reversed arguments).
Example (need to convert the year's value to int first)::
{{ d.0|get:year|add:0|getfrom:choices.turnover }}
"""
return mapping.get(key) |
def files_with_extension(path: str,extension: str):
"""
Gives a list of the files in the given directory that have the given extension
Parameters
----------
path: str
The full path to the folder where the files are stored
extension: str
The extension of the files
Re... |
def set_api_url(value):
""" Sets the url that the API uses, in case you're using a self-hosted
version of Dashku
Keyword arguments:
value -- The API url. In the module, this is http://dashku.com by default
"""
global api_url
api_url = value
return api_url |
def decode_bytes(s, encoding='utf-8', errors='replace'):
"""Decodes bytes to str, str to unicode."""
return s.decode(encoding, errors=errors) if isinstance(s, bytes) else s |
def is_power(a, b):
"""
documentation for is_power(a, b)
"""
if b == 0:
if a == 0: # 0^x = 0 (x != 0)
return True
else: # 0^0 is undefined
return False
if a == 1: # case for b^0, b != 0
return True
elif b == 1: # if omitted gives infinite recur... |
def parse_plot_args(*args, **options):
"""Parse the args the same way plt.plot does."""
x = None
y = None
style = None
if len(args) == 1:
y = args[0]
elif len(args) == 2:
if isinstance(args[1], str):
y, style = args
else:
x, y = args
elif len(... |
def sort_map_by_value(dictionary):
"""
Sorts Map by value. Map values must implement Comparable.
:param dictionary: Map to sort
:return: Sorted map
"""
return sorted(dictionary, key=dictionary.get) |
def convert_string(x):
"""
Convert the string to lower case and strip all non [z-z0-9-_] characters
:param str x: the string to convert
:return: the converted string
:rtype: str
"""
# we define the things to keep this way, just for clarity and in case we want to add other things.
wanted ... |
def translate_crops(crop_tuples, translate_tuple):
"""Translate crop tuples to be over the image are, i.e. left top at (0,0)."""
crop_tuples_translated = []
for crop_tuple in crop_tuples:
crop_tuples_translated.append(
(crop_tuple[0] - translate_tuple[0],
crop_tuple[1] - tra... |
def gardner_shale(Vp, A=1.66, B=0.261):
"""
Vp in km/sec
"""
Rho = A*Vp**B
return Rho |
def can_shift_a_to_get_b(a: str, b: str) -> bool:
"""
O(n*n) & O(1)
"""
len_a = len(a)
len_b = len(b)
if len_a != len_b:
return False
start_index = 0
while start_index < len_a:
if a[start_index] == b[0] and a[start_index:] + a[:start_index] == b:
return Tru... |
def pair_min(pair1, pair2):
"""Given two pairs, returns the one that is pointwise lesser in its first two elements.
Fails if neither is lesser."""
if pair1[0] <= pair2[0] and pair1[1] <= pair2[1]:
return pair1
if pair1[0] >= pair2[0] and pair1[1] >= pair2[1]:
return pair2
raise Exception... |
def _get_volume(time_in_seconds: float) -> int:
"""
Returns the volume containing the indicated time point.
"""
return int((time_in_seconds - time_in_seconds % 2) / 2) |
def resolve_wrappers(f):
"""Get the underlying function behind any level of function wrappers."""
return resolve_wrappers(f.__wrapped__) if hasattr(f, "__wrapped__") else f |
def _merge_dicts(a, b, path=None):
"""
Merges b into a.
From: https://stackoverflow.com/a/7205107/13086629
"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
_merge_dicts(a[key], b[key], ... |
def replace_serial(rdata, serial):
"""Replace serial value in given rdata."""
rdatas = rdata.split(" ")
# `mname_and_rname` contains such 'one.dns.id. two.dns.id.'
# `ttls` contains such '10800 3600 604800 38400'
mname_and_rname = " ".join(rdatas[0:2])
ttls = " ".join(rdatas[3:])
return f"... |
def do_not_do_anything_here_either(do_nothing=False):
"""
do not do anything here either
:param do_nothing: should I do something ?
:type do_nothing: boolean
:rtype: bool
>>> result = do_not_do_anything_here_either(True)
>>> print(result)
"""
if do_nothing:
print("I'm slee... |
def plot_line(x1, y1, x2, y2):
"""Brensenham line drawing algorithm.
Return a list of points(tuples) along the line.
"""
dx = x2 - x1
dy = y2 - y1
if dy < 0:
dy = -dy
stepy = -1
else:
stepy = 1
if dx < 0:
dx = -dx
stepx = -1
else:
step... |
def get_old_swap(mod_line):
"""Function to return the old module name in the case of a swap.
:param str mod_line: String provided by the user in the config.
:return str mod_old: Name of module to be swapped out.
"""
return mod_line[:mod_line.find('->')-1] |
def _compound_factors(prime_factors):
"""Return a set of all compound factors, given the list of prime factors."""
compound = set()
for position, factor in enumerate(prime_factors):
compound.add(factor)
remaining = _compound_factors(prime_factors[position+1:])
for value in remaining... |
def _descriptorDocstring(name, nbin, bins):
""" Create a docstring for the descriptor name """
if nbin == 0:
interval = "-inf < x < {0:.2f}".format(bins[nbin])
elif nbin < len(bins):
interval = " {0:.2f} <= x < {1:.2f}".format(bins[nbin - 1], bins[nbin])
else:
interval = " {0:.2f} <= x < inf".form... |
def count_odd(left: int, right: int) -> int:
"""Counts the number of odd numbers.
left,right
Interval boundaries.
"""
n_odd = (right - left) // 2
if right % 2 != 0 or left % 2 != 0:
n_odd += 1
return n_odd |
def truncate_right(number):
"""Truncate a number to the right"""
truncated = str(number)[:-1]
if truncated:
return int(truncated) |
def bbox_iou(a, b):
"""Calculate the Intersection of Unions (IoUs) between bounding boxes.
IoU is calculated as a ratio of area of the intersection
and area of the union.
Args:
a: (list of 4 numbers) [x1,y1,x2,y2]
b: (list of 4 numbers) [x1,y1,x2,y2]
Returns:
iou: the value ... |
def parse_number(value):
"""Quick'n dirty. """
return value.replace(" ", "") |
def syncFn1(n):
"""sync fucntion"""
print(f"start:fn({n})")
print(f"finish:fn{n}")
return f"finish:fn{n}" |
def check_module_lines(lines, module):
"""
Check if a normalized module name appears in the given lines
:param lines: The lines to check
:param module: A module name - e.g. "xt_set" or "ip6_tables"
:return: True if the module appears. False otherwise
"""
full_module = "/%s.ko" % module
r... |
def count_outer_bags(rules, start_color):
"""Count outer bags."""
relevant_rules = []
colors_current = [start_color]
count_previous = -1
while len(relevant_rules) != count_previous:
count_previous = len(relevant_rules)
colors_next = []
for rule in rules:
for color... |
def _MasterUpgradeMessage(name, server_conf, cluster, new_version):
"""Returns the prompt message during a master upgrade.
Args:
name: str, the name of the cluster being upgraded.
server_conf: the server config object.
cluster: the cluster object.
new_version: str, the name of the new version, if g... |
def upstream_cert_hostname(superdomain):
"""
Hostname of the upstream certificate sent to be validated by APIcast
May be overwritten to configure different test cases
"""
return "*." + superdomain.split(".", 1)[1] |
def make_string(attr_dict, create=False):
"""
Create a string from the to_uml_json_<operation> method to aid the
remove_duplicates method.
Parameters
----------
attr_dict : dict
Dictionary output from the Vertex and DiEdge ReporterMixins.
create : Bool
Flag to change keys.
... |
def _concat_date(cmd):
"""Concatonate date to end of command with some spaces"""
return 'echo "`%s` `date -u`"' % cmd |
def filter_inPriceBorders(itineraries, minPrice, maxPrice):
"""
filter the input itineraries and select itineraries with price from minPrice to maxPrice
:param itineraries: input itineraries
:param minPrice: minimum price for itinerary
:param maxPrice: maximum price for itinerary
:return: tiner... |
def astIsFloat(token):
"""
Check if type of ast node is float/double
"""
if not token:
return False
if token.str == '.':
return astIsFloat(token.astOperand2)
if token.str in '+-*/%':
return astIsFloat(token.astOperand1) or astIsFloat(token.astOperand2)
if not token.v... |
def is_true(boolstring: str):
""" Converts an environment variables to a Python boolean. """
if boolstring.lower() in ('true', '1'):
return True
return False |
def is_hashable(obj):
"""Return True if obj is hashable, else return False."""
try:
hash(obj)
return True
except:
return False |
def second_none(f, s):
""" returns f+s if s is not None. None otherwise. """
if s is not None:
return u"{0} {1}".format(f, s)
else:
return None |
def gene_list_intersect(gmt_genes, dataset_genes):
"""return the intersection between the current gene list HGNC symbols and
the columns in the dataset. return a second list, `missing` for any genes
that are missing.
"""
intersect = [x for x in gmt_genes if x in dataset_genes]
missing = [x for x... |
def getTitles(docs):
"""
retrieving titles for all documents
"""
documentData = []
for d in docs:
temp = {}
temp['id'] = d['_id']
#temp[]
if 'title' in d['_source'].keys():
temp['title'] = d['_source']['title']
elif 'html_title' in d['_source'].keys():
temp['title'] = d['_source']['html_title']
e... |
def get_description(*, content: str) -> str:
"""Getting description from the content of the file."""
try:
description = content.split("description:")[1].split("\n")[0].strip()
except IndexError:
description = "No description"
return description |
def keys_from_hash(hexdigest):
"""
Return a cache keys triple for a hash hexdigest string.
NOTE: since we use the first character and next two characters as directories, we
create at most 16 dir at the first level and 16 dir at the second level for each
first level directory for a maximum total of ... |
def bytes_to_str(num, suffix='B'):
"""
Convert number to a human readable string with decimal prefix.
:param float num: Value in given unit.
:param str suffix: Unit suffix. Defaults to 'B'.
:returns: Human readable string with decimal prefixes.
:rtype: str
"""
for unit in ('', 'K', 'M',... |
def flatten(l: list) -> list:
"""Flatten an arbitrary list-of-lists into one flat list."""
return [item for sublist in l for item in sublist] |
def get_chain_missing_res(missing_residues, chainID):
"""
Function that returns a list of missing residues from a given chain identifier/letter.
"""
result = [residue for residue in missing_residues if residue["chain"] == chainID]
return result |
def parse_recvd_data(data):
""" Break up raw received data into messages, delimited by null byte """
parts = data.split(b'\0')
msgs = parts[:-1]
rest = parts[-1]
return msgs, rest |
def xgcd(b, n):
"""
Compute the extended GCD of two integers b and n.
Return d, u, v such that d = u * b + v * n, and d is the GCD of b, n.
"""
x0, x1, y0, y1 = 1, 0, 0, 1
while n != 0:
q, b, n = b // n, n, b % n
x0, x1 = x1, x0 - q * x1
y0, y1 = y1, y0 - q * y1
... |
def parse_size(s):
"""
Parses a size specification. Valid specifications are:
123: bytes
123k: kilobytes
123m: megabytes
123g: gigabytes
"""
if not s:
return None
mult = None
if s[-1].lower() == "k":
mult = 1024**1
elif s[-... |
def get_version(json_data):
"""Returns the schema version for this data object
:returns: version as a string
"""
return json_data.get('schema_version', '1') |
def custom(K_0, D_0, L_S, D_S):
"""
Defines the material properties for a custom nonlinear material.
Args:
K_0(float) : Bulk modulus of the material in Pascal for SAENO Simulation (see [Steinwachs,2015])
D_0(float) : Buckling coefficient of the fibers for SAENO Simulation (see [Steinwac... |
def RPL_TRACEUSER(sender, receipient, message):
""" Reply Code 205 """
return "<" + sender + ">: " + message |
def untag_sentence(tagged_sentence):
"""Get back the original text of a sentence."""
leading_tags = set(
['(', '$', '``']) # don't need a space after, but do before
following_tags = set([')', ',', '.', ':', "''", 'POS']
) # need a space after, but not before
sentence =... |
def errCheck(response):
""" Checks errors in response from Anki connect and returns appropriate message
Parameters:
response (JSON): URL where media is located
Returns:
False if no error.
Error message string otherwise.
"""
if len(response) != 2:
return'response h... |
def get_duplicates_in_list(seq):
"""
Returns all duplicates items in given list or tuple
:param seq: list or tuple
:return: list
"""
seen = set()
duplicates = list()
for obj in seq:
if obj in seen:
duplicates.append(obj)
seen.add(obj)
return duplicates |
def parse_cell(cell, rules):
""" Applies the rules to the bunch of text describing a cell.
@param string cell
A network / cell from iwlist scan.
@param dictionary rules
A dictionary of parse rules.
@return dictionary
parsed networks. """
parsed_cell = {}
for key in rules... |
def laplace_noise_parameter(k, num_attributes, num_tuples, epsilon):
"""The noises injected into conditional distributions. PrivBayes Algorithm 1."""
return 2 * (num_attributes - k) / (num_tuples * epsilon) |
def convert_genotypes(genotypes):
""" Converts list of genotypes as string to genotypes as integers """
convertions = {'AA': 0, 'AG': 1, 'GG': 2}
assert set(genotypes) <= set(convertions.keys())
result = []
for genotype in genotypes:
result.append(convertions[genotype])
return result |
def max_elems(iterable, key=None):
"""Find the elements in 'iterable' corresponding to the maximum values w.r.t. 'key'."""
iterator = iter(iterable)
try:
elem = next(iterator)
except StopIteration:
raise ValueError("argument iterable must be non-empty")
max_elems = [elem]
max_key... |
def find_missed_hsp_ranges(complete_ranges,
final_proximate_ranges,
leftover_proximate_ranges):
"""Testable function to test for problems.
"""
missed_hsps = False
for r in complete_ranges:
total_prox = final_proximate_ranges + leftover_proximate_ranges
... |
def calculate_packet_loss_values(dropped_packets_rate, total_packets_rate):
""" Calculate the packet loss (percentage)
Args:
dropped_packets_rate (float): The rate of dropped packets (packets/sec)
total_packets_rate (float): The rate of total packets (packets/sec)
Returns:
float: T... |
def xunicode(s):
"""If ``s`` is None return empty string
.. deprecated::
Use :func:`xstr` instead.
:param s: string
:return: s or an empty string if s in None
:rtype: str
"""
return '' if s is None else str(s) |
def check_tie(board):
"""
[['O', '-', 'O'],
['O', 'X', '-'],
['-', 'X', 'X']]
"""
empty_cells = board.count('-')
tie = (empty_cells == 0)
return tie |
def powmod(a, b, m):
""" Returns the power a**b % m """
# a^(2b) = (a^b)^2
# a^(2b+1) = a * (a^b)^2
if b==0:
return 1
return ((a if b%2==1 else 1) * powmod(a, b//2, m)**2) % m |
def gpsfix2str(fix: int) -> str:
"""
Convert GPS fix integer to descriptive string.
:param int fix: GPS fix type (0-5)
:return: GPS fix type as string
:rtype: str
"""
if fix == 5:
fixs = "TIME ONLY"
elif fix == 4:
fixs = "GPS + DR"
elif fix == 3:
fixs = "3D... |
def GetMediaComponents(media_str, media_dict, mixAttr, mix):
"""
Args:
media_str: (str) Media name
media_dict: (d)
media (str) -> list<compound_l>
where compound_l list<compound (str), concentration (str), units (str)>
e.g. [Ammonium chloride, 0.25, g... |
def icons(icon_type):
"""A tag to return the correct Bulma icon class given an input type"""
icons = {
'text':'user',
'email':'envelope',
'password':'lock',
}
return icons[icon_type] |
def rangeStr(st, i,j):
"""
Generate a list of labels st+str(k) for k in range(i,j)
"""
return [ st+str(x) for x in range(i,j)] |
def _is_valid_put_block_header(header_name):
"""
:return: True if the specified header name is a valid header for the Put Block operation, False
otherwise. For a list of valid headers, see
https://docs.microsoft.com/en-us/rest/api/storageservices/put-block#request-headers and
... |
def get_bgpvrf_differences(current_dict, old_dict):
"""Compare 2 BGP VPN
- added elements (route_targets, import_targets or export_targets)
- removed elements (route_targets, import_targets or export_targets)
- changed values for keys in both dictionaries (network_id,
route_targets, import_targe... |
def SanityCheckManifestServices(manifest):
"""Ensures any given service name appears only once within a manifest."""
known_services = set()
def has_no_dupes(root):
if "name" in root:
name = root["name"]
if name in known_services:
raise ValueError(
"Duplicate manifest entry foun... |
def prefixKeys(data, prefix, separator):
"""Prefix dictionary keys
:param data: dictionary of data
:param prefix: value to prefix keys with
:param separator: character between prefix and original key name
:returns: prefixed - dictionary with updated key names
"""
prefixed = {}
if type(d... |
def solution(n):
"""
Determines the maximal 'binary gap' in an integer
:param n: a positive integer (between 1 and 2147483647)
:return: a count of the longest sequence of zeros in the binary representation of the integer
"""
bin_limit = 2147483647
if not isinstance(n, int):
... |
def compute_edit_distance(word1: str, word2: str) -> int:
"""Returns the Levenshtein (edit) distance between two words
The edit distance is the minimum number of operations required to convert
word1 to word2.
Based on the observation that word transformation can be achieved via three
distinct char... |
def uniquify(seq):
"""Return unique values in a list in the original order. See: \
http://www.peterbe.com/plog/uniqifiers-benchmark
Args:
seq (list): original list.
Returns:
list: list without duplicates preserving original order.
"""
seen = set()
seen_add = seen.add
... |
def prediction_index_in_set(prediction_index, category_set):
"""Returns True if the prediction index is in the set"""
for x in category_set:
if prediction_index == int(x):
return True
return False |
def _build_debt_string(debt):
"""Build a nice string to represent the debt."""
if not debt:
return "-"
# convert tuples to nice string format (only first 3, the used ones)
debt_nicer = ["{}-{:02d}".format(*d) for d in debt[:3]]
exceeding = "" if len(debt) <= 3 else ", ..."
result = "{} ... |
def remove_chars(text, chars):
"""
remove chars from text
"""
for char in chars:
text = text.replace(char, '')
return text |
def ExtractLogId(log_resource):
"""Extracts only the log id and restore original slashes.
Args:
log_resource: The full log uri e.g projects/my-projects/logs/my-log.
Returns:
A log id that can be used in other commands.
"""
log_id = log_resource.split('/logs/', 1)[1]
return log_id.replace('%2F', '/... |
def normalize(val):
""" Normalize a string so that it can be used as an attribute
to a Python object """
if val.find('-') != -1:
val = val.replace('-','_')
return val |
def get_grid_size(grid):
"""Get size of grid and grid's row."""
return len(grid), len(grid[0]) |
def prod(A, B):
""" Returns the matrix product of two matrices using lists
"""
# Check if dimenstions are compatible
if len(A[0]) != len(B):
raise ValueError("Dimensions do not match.")
product = []
# iterate through rows of A
for i in range(len(A)):
# new row for final pro... |
def get_boolean(val, default=False):
"""
Given a value, check if if corresponds to True or False.
Python's bool() does not behave as expected for strings so we
have a helper function here
"""
if val is None:
return default
return val in ['True', 'true', '1'] |
def binary_tree(levels = 3):
"""
Input :
* levels : default = 3, number of levels for a binary tree
Returns :
* list of binary leafs and ancestors
"""
binary = '01'
L = len(binary)
tree = []
# iterate in the number total lea... |
def get_error_correction_factor(type_id: int) -> float:
"""Retrieve the error code correction factor (piECC).
:param type_id: the error correction type identifier.
:return: _pi_ecc; the value of piECC.
:rtype: float
:raise: KeyError if passed an unknown type_id.
"""
return {1: 1.0, 2: 0.72,... |
def parse_single_query(data, query_type):
"""
Parses the data returned by `send_query`
.. warning::
Like `send_query`, the logic here depends on the specific structure
of the query (e.g. it must be an issue or PR query, and must have a
total count).
"""
try:
total_count = data['data'][... |
def get_bounds(sparse_voxel):
"""
Voxel should either be a schematic, a list of ((x, y, z), (block_id, ?)) objects
or a list of coordinates.
Returns a list of inclusive bounds.
"""
if len(sparse_voxel) == 0:
return [0, 0, 0, 0, 0, 0]
# A schematic
if len(sparse_voxel[0]) == 2 an... |
def Radio2NormOption_Y_Variable(argument):
"""Dictionary for switching the normalisation options in the radio box"""
switcher = {
0: 'Raman_Intensity',
1: 'Vec_Norm_Intensity',
2: 'std_var_Norm_Intensity',
3: 'Zero_to_One_Intensity'
}
return switcher.get(argument, 'k-') |
def _is_bit_flag(n):
"""
Verifies if the input number is a bit flag (i.e., an integer number that is
an integer power of 2).
Parameters
----------
n : int
A positive integer number. Non-positive integers are considered not to
be "flags".
Returns
-------
bool
... |
def reindent(s,indent):
""" reindent s assuming s has already some indent """
nindent=len(indent)
nleading=len(s)-len(s.lstrip())
if nleading<nindent:
return indent+s
else:
return indent+s[nindent:] |
def _empty_str_to_none(v: object) -> object:
"""
Reusable Pydantic validator that converts empty strings to ``None``.
"""
if isinstance(v, str):
if not v.strip():
v = None
return v |
def list_diff(subscribers, owners):
"""Returns list B - A."""
owner_ids = [x.key().id() for x in owners]
return [x for x in subscribers if not x.key().id() in owner_ids] |
def is_terminated(lines):
"""Determine if assert is terminated, from .cpp/.h source lines as text."""
code_block = " ".join(lines)
return ';' in code_block or code_block.count('(') - code_block.count(')') <= 0 |
def smith_gassmann(kstar, k0, kfl2, phi):
"""
Applies the Gassmann equation.
Returns Ksat2.
"""
a = (1 - kstar/k0)**2.0
b = phi/kfl2 + (1-phi)/k0 - (kstar/k0**2.0)
ksat2 = kstar + (a/b)
return ksat2 |
def rebuildList(svgfile, searchFor, toRemove = []):
"""
Rebuild list takes the current text file, the searchFor list and an option toRemove.
toRemove just stores line numbers of any lines we need to remove.
The subroutine goes line by line through the text file passed to it (in a list)
Then for each... |
def linsum(n: int) -> int:
"""Return the sum of the integers from 1 to n."""
return n * ( n + 1) // 2 |
def reflection(n1: float, n2: float) -> float:
"""Returns power reflection at the interface
of two refractive index materials.
Args:
n1: Refractive index of material 1.
n2: Refractive index of material 2.
Returns:
float: The percentage of reflected power.
"""
r = abs((n... |
def checksum(data):
"""
Calculate the 16 bit checksum for data
Described in http://www.faqs.org/rfcs/rfc1071.html as the "the 16-bit 1's complement sum is computed over the octets
concerned, and the 1's complement of this sum is placed in the
checksum field"
"""
total = 0
# ... |
def bgr_skin(b, g, r):
"""Rule for skin pixel segmentation based on the paper 'RGB-H-CbCr Skin Colour Model for Human Face Detection'"""
e1 = bool((r > 95) and (g > 40) and (b > 20) and ((max(r, max(g, b)) - min(r, min(g, b))) > 15) and (
abs(int(r) - int(g)) > 15) and (r > g) and (r > b))
e2 =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.