content stringlengths 42 6.51k |
|---|
def to_bytes(key: str, encoding: str = 'utf-8'):
"""
crypto lib expect 'bytes' keys, convert 'str' keys to 'bytes'
"""
return key.encode(encoding) |
def perfect_score(student_info):
"""
:param student_info: list of [<student name>, <score>] lists
:return: first `[<student name>, 100]` or `[]` if no student score of 100 is found.
"""
for info in student_info:
if info[1] == 100:
return info
return [] |
def _can_be_quoted(loan_amount, lent_amounts):
"""
Checks if the borrower can obtain a quote. To this aim, the loan amount should be less than or
equal to the total amounts given by lenders.
:param loan_amount: the requested loan amount
:param lent_amounts: the sum of the amounts given by lenders
... |
def one_hot_encoding(x, allowable_set, encode_unknown=False):
"""One hot encoding of the element x with respect to the allowable set.
If encode unknown is true, and x is not in the allowable set,
then x is added to the allowable set.
Args:
:param x (elem) : [the element to encode]
:param... |
def countSegments(s):
"""
:type s: str
:rtype: int
"""
return len(s.split()) |
def get_decades(start_year, end_year):
"""Get a list of decades to process (usually only 1)
Args:
start_year (int) : Start year.
end_year (int) : End year.
Returns:
list : List of decades to process.
"""
# Convert to decades
start_decade = start_year // 10
end_... |
def is_every_n_steps(interval, current_step, skip_zero=False):
"""
Convenient function to check whether current_step is at the interval.
Returns True if current_step % interval == 0 and asserts a few corner cases (e.g., interval <= 0)
Args:
interval (int): target interval
current_s... |
def linearSearch(searchList, target):
"""
Returns index position of the target if found else return None.
"""
for i in range(0, len(searchList)):
if searchList[i] == target:
return i
return None
# The above is a linear runtime algorithm: O(n) - sequentially goes through th... |
def get_filenames_from_urls(urls):
""" Returns a list of filenames from a list of urls"""
return [url.split("/")[-1] for url in urls] |
def pct(numerator, denominator, precision=None):
"""Makes into a percent, avoiding division by zero"""
if numerator > 0 and denominator > 0:
value = (100.0 * numerator) / denominator
else:
value = 0.0
if precision is not None:
value = round(value, precision)
return value |
def NoTestRunnerFiles(path, dent, is_dir):
"""Filter function that can be passed to FindCFiles or FindHeaderFiles in
order to exclude test runner files."""
# NOTE(martinkr): This prevents .h/.cc files in src/ssl/test/runner, which
# are in their own subpackage, from being included in boringssl/BUILD files.
re... |
def normalize(string : str) -> str:
"""Removes all extra fluff from a text to get the barebone content"""
return string.replace(",", "").replace("members", "").replace("member", "").strip() |
def jsonify(form):
"""Cast WTForm to JSON object.
"""
return {
'form': [
{
'id': field.id,
'label': str(field.label),
'html': str(field),
'description': str(field.description)
}
for field in form
... |
def temperature_to_state(temperature, undefined_temperature):
"""Convert temperature to a state."""
return temperature if temperature > undefined_temperature else None |
def two_sum(nu, t):
"""
Looking for the target between two numbers in 'the list'
:param nu: list numbers []
:param t: target or goal
:return: key:value, and iteration if find result (target - each number) and the iteration it ended up.
if no result is found,it'll return -1
"""
d = dict()... |
def edges_from_path(path):
"""
Converts the list of path nodes into a list of path edges
----------
path: list of path nodes
Returns
-------
path of edge: list of path edges
"""
return list(zip(path,path[1:])) |
def average_list(lst):
"""averages a list"""
return sum(lst)/len(lst) |
def parse_values(string, prefix):
"""Parse the value name pairs output by rndc.
Parse the lines output by rndc with a value and name that are separated by
a space character. Spaces are removed from the, it is converted to lower
case, and prefixed with the prefix variable before becoming the key to the
... |
def maxsum(sequence):
"""Return maximum sum."""
maxsofar, maxendinghere = 0, 0
for x in sequence:
# invariant: ``maxendinghere`` and ``maxsofar`` are accurate for ``x[0..i-1]``
maxendinghere = max(maxendinghere + x, 0)
maxsofar = max(maxsofar, maxendinghere)
return maxs... |
def ERR_NORECIPIENT(sender, receipient, message):
""" Error Code 411 """
return "ERROR from <" + sender + ">: " + message |
def get_plant_status(num):
""""Return a number so that the appropriate image can be called"""
if num < -0.5:
return 1
elif num < 0:
return 2
elif num < 0.5:
return 3
elif num < 1:
return 4 |
def is_punkt(token):
"""
Return if token consists of only punctuation and whitespace
Args:
token: single token
Returns:
Boolean
Raises:
None
Examples:
>>> is_punkt(" ")
True
>>> is_punkt(", ,")
True
>>> is_punkt("?!!")
True
... |
def l3_interface_group_id(ne_id):
"""
L3 Interface Group Id
"""
return 0x50000000 + (ne_id & 0x0fffffff) |
def error_compatibility_score(h1_output_labels, h2_output_labels, expected_labels):
"""
The fraction of instances labeled incorrectly by h1 and h2
out of the total number of instances labeled incorrectly by h1.
Args:
h1_output_labels: A list of the labels outputted by the model h1.
h2_o... |
def _get_inverted_node_graph(node_graph, node_to_ignore):
"""Get the graph {node_id: nodes that depend on this one}
Also this graph does not contain the nodes to ignore
"""
inverted = dict()
for node, dependencies in node_graph.items():
if node not in node_to_ignore:
for dependen... |
def kmer_create(string,k):
""" Disassemble to k-mer. """
return [string[i:k+i] for i in range(len(string)-k+1)] |
def nt2aa(ntseq):
"""Translate a nucleotide sequence into an amino acid sequence.
Parameters
----------
ntseq : str
Nucleotide sequence composed of A, C, G, or T (uppercase or lowercase)
Returns
-------
aaseq : str
Amino acid sequence
Example
--------
>>> nt2aa... |
def join(directory, path):
"""Compute the relative data path prefix from the data_path attribute.
Args:
directory: The relative directory to compute path from
path: The path to append to the directory
Returns:
The relative data path prefix from the data_path attribute
"""
if not ... |
def convert_pascal_bbox_to_coco(xmin, ymin, xmax, ymax):
"""
pascal: top-left-x, top-left-y, x-bottom-right, y-bottom-right
coco: top-left-x, top-left-y, width and height
"""
return [xmin, ymin, xmax - xmin, ymax - ymin] |
def exp(x, n):
"""Computes x raised to the power of n.
>>> exp(2, 3)
8
>>> exp(3, 2)
9
"""
if n == 0:
return 1
else:
return x * exp(x, n - 1) |
def url(base_url: str, region: str) -> str:
"""Returns a regionalized URL based on the default and the given region."""
if region != "us":
base_url = base_url.replace("https://", f"https://{region}-")
return base_url |
def square_pyramidal_numbers(n):
"""[Square Pyramidal Numbers - A000330](https://oeis.org/A000330)
Arguments:
n (Integer): Index of the sequence
Returns:
Integer: Value of this sequence at the specified index
"""
return n * (n + 1) * (2 * n + 1) / 6 |
def normal_dt(x, a, b):
"""
normal trend of transit time
Parameters
----------
x : 1-d ndarray
depth to convert
"""
return a - b * x |
def _quote(text):
"""
Quote the given string so ``_split_quoted`` will not split it up.
:param unicode text: The string to quote:
:return: A unicode string representing ``text`` as protected from
splitting.
"""
return (
'"' +
text.replace("\\", "\\\\").replace('"', '\\"... |
def filter_regex(names, regex):
"""
Return a tuple of strings that match the regular expression pattern.
"""
return tuple(name for name in names
if regex.search(name) is not None) |
def _name(ref):
"""Return the username or email of a reference."""
return ref.get('username', ref.get('email')) |
def mmgray(f):
"""Convert a binary image into a gray-scale image."""
return [255 if item == 1 else 0 for item in f] |
def gf_add_ground(f, a, p, K):
"""
Compute ``f + a`` where ``f`` in ``GF(p)[x]`` and ``a`` in ``GF(p)``.
**Examples**
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.galoistools import gf_add_ground
>>> gf_add_ground([3, 2, 4], 2, 5, ZZ)
[3, 2, 1]
"""
if not f:
... |
def str_join(*members):
"""join_memebers(member1, ...) takes an orbitrary number of
arguments of type 'str'and concatinates them with using the '.' separator"""
return ".".join(members) |
def sort_allAPI(allAPI):
"""Design Note:
A dictionary with the key:value pair id:name is needed for this to work because these are sorting commerceprices data from the API, and only returns the following:
{'id': 79423, 'whitelisted': False, 'buys': {'quantity': 13684, 'unit_price': 114}, 'sells': {'quanti... |
def set_test_mode(user_id, prefix='', rconn=None):
"""Set this user with test mode.
Return True on success, False on failure"""
if user_id is None:
return False
if rconn is None:
return False
try:
result = rconn.set(prefix+'test_mode', user_id, ex=3600, nx=True) # expires... |
def joinPath(modname, relativePath):
"""Adjust a module name by a '/'-separated, relative or absolute path"""
module = modname.split('.')
for p in relativePath.split('/'):
if p=='..':
module.pop()
elif not p:
module = []
elif p!='.':
module.appen... |
def sorted_committees(committees):
"""
sorts a list of committees, ensures that committees are sets
"""
return sorted([set(committee) for committee in committees], key=str) |
def bc(temp):
"""
Calculate Bolometric Correction Using the Teff from the previous equation.
This correction is for main sequence stars of the Teff range given above.
"""
return (-1.007203E1 + temp * 4.347330E-3 - temp**2 * 6.159563E-7
+ temp**3 * 2.851201E-11) |
def iscurried(f):
"""Return whether f is a curried function."""
return hasattr(f, "_is_curried_function") |
def fibonacci(n):
"""Fibonacci series
0, 1, 1, 2, 3, 5, 8, 13, ...
"""
if n <= 1:
return n
a = 0
b = 1
c = 1
for i in range(2, n):
a = b
b = c
c = a + b
return c |
def leaf_fanouts(conn_graph_facts):
"""
@summary: Fixture for getting the list of leaf fanout switches
@param conn_graph_facts: Topology connectivity information
@return: Return the list of leaf fanout switches
"""
leaf_fanouts = []
conn_facts = conn_graph_facts['device_conn']
""" f... |
def parse_orcid(text):
""" parse OI field
"""
if not text or str(text) == 'nan':
return []
state = 'NAME' # NAME | ORCID
name = ''
orcid = ''
results = []
for c in text:
if state == 'NAME':
if c == '/':
state = 'ORCID'
continu... |
def child_is_flat(children, level=1):
"""
Check if all children in section is in same level.
children - list of section children.
level - integer, current level of depth.
Returns True if all children in the same level, False otherwise.
"""
return all(
len(child) <= level + 1 or child... |
def hard_piecewise(x, f, g):
"""
This function harshly glues together f and g at the origin.
@param x: independent variable
@param f: dominant function when x < 0
@param g: dominant function when 0 < x
"""
#FIXME: the comparison does not currently vectorize,
# not that I really expected ... |
def get_smallest_best_parameters(group):
"""Sets defaults based on the smallest values of all known entries. The average might be better for performance but
some parameters might not be supported on other devices."""
# Counts the number of devices in this group
assert len(group) > 0
# Find the sma... |
def strip_word(string):
"""
This function strips the words of any surrounding spaces or quotation marks from an input string,
but does not replace any single quotes inside words (e.g. "isn't")
"""
return string.strip().strip("'").strip('"') |
def retag_from_strings(string_tag) :
"""
Returns only the final node tag
"""
valure = string_tag.rfind('+')
if valure!= -1 :
tag_recal =string_tag [valure+1:]
else :
tag_recal = string_tag
return tag_recal |
def reverse_byte(byte):
"""
Fast way to reverse a byte on 64-bit platforms.
"""
#return (byte * 0x0202020202L & 0x010884422010L) % 1023
return(byte * 0x0202020202 & 0x010884422010) % 1023 |
def extract_name(in_line: str) -> str:
"""
Extracts the name from the type construct. Information that is not needed will be removed
such as the stereotype.
"""
types = {'package', 'class', 'abstract', 'interface',
'enum', 'abstract class', 'entity'}
process_type: str = ''
for i... |
def flip_mat_pat(snps):
"""Take a dictionary of SNPs and flip all mat and pat sites.
Note: This changes the original dictionary and does not make a copy.
"""
for chr, poss in snps.items():
for pos, snp in poss.items():
mat = snp.mat
pat = snp.pat
snp.mat = pa... |
def wrap_bits_left(binary, amount):
"""Move the characters of the binary string to the left. Bits will
be wrapped. E.g. shift_bits('1011', 1) -> '0111'.
"""
return ''.join([binary[(place + amount) % len(binary)]
for place in range(len(binary))]) |
def is_sorted(items):
"""Checks whether the list is sorted or not"""
return all(items[i] <= items[i + 1] for i in range(len(items) - 1)) |
def newick_semicolon_check(tree_str):
"""
This function will check the last character of
the tree in newick form and ensure that is ends in ";".
"""
if list(tree_str)[-1] != ";":
tree_str += ';'
return tree_str
else:
return tree_str |
def rebound_starting_vals(bounds, starting_vals):
"""
Takes the user's starting guess for a resonator fit parameter and makes sure it's within the bounds for the fit
If not, it adjusts the guess to be the closest in-bounds value
Returns a new list of guess parameters, which should be the list actually s... |
def force_list(value):
"""
Coerce the input value to a list.
If `value` is `None`, return an empty list. If it is a single value, create
a new list with that element on index 0.
:param value: Input value to coerce.
:return: Value as list.
:rtype: list
"""
if value is None:
... |
def _col_name(c):
"""Convert a zero-based index into an Excel column name."""
if c < 26:
return chr(65+c)
elif c < 26*27:
return chr(64+c//26) + chr(65+c%26)
else:
raise Exception("Too many products") |
def days_in_frequency_target(target: int) -> int:
"""
Returns number in a frequence period.
e.g. in Mallard, frequence period may be 12, 6,
18, etc to represent the numbner of months between
inspections - ideally. We are simply converting
that to days.
"""
return int((target / 12) * 365) |
def escape(term):
"""
escapes a term for use in ADQL
"""
return str(term).replace("'", "''") |
def get_var_list(func):
"""
get variable names of func, exclude "self" if there is
"""
func_code = func.__code__
var_list = func_code.co_varnames[:func_code.co_argcount]
var_list = [var for var in var_list if var != 'self']
return var_list |
def extract_bounds(line):
"""
@@ -1,4 +1,4 @@
"""
args = line.split("@@")
line = args[1]
a, b = line.strip().split(" ")
sa, ea = a.split(",")
sb, eb = b.split(",")
bnds = (sa[1:], ea, sb, eb)
a, b, c, d = [int(x) for x in bnds]
print(line)
return a, b, c, d
# retu... |
def remove_white_space(txt_list):
"""
Remove unwanted white space and replaced them with single white space
params:
-------
txt_list list(): of str() that contains the text to clean
:return:
--------
txt_list list(): of str() transformed
"""
return [" ".join(txt.split()... |
def zstrip(chars):
"""Strip all data following the first zero in the string"""
if '\0' in chars:
return chars[:chars.index("\0")]
return chars |
def get_class_id(cls_names, classes):
"""
Get list of UIDs matching input class names
:param cls_names:
:param classes:
:return:
"""
cls_uids = []
for cls_name in cls_names:
lower_name = cls_name.lower()
matches = [
uid for uid, info in classes.items()
... |
def sanitize_pg(pg_def):
"""
sanitize the processGroup section from parameterContext references, does a
recursive cleanup of the processGroups if multiple levels are found.
"""
if "parameterContextName" in pg_def:
pg_def.pop("parameterContextName")
if "processGroups" not in pg_def or... |
def reflected_name(constant_name):
"""Returns the name to use for the matching constant name in blink code.
Given an all-uppercase 'CONSTANT_NAME', returns a camel-case
'kConstantName'.
"""
# Check for SHOUTY_CASE constants
if constant_name.upper() != constant_name:
return constant_name... |
def _convert_schedule_to_task_rng(schedule):
"""Convert the schedule to dict{task: starting time range}"""
task_start_rng = dict()
for record in schedule:
# parse schedule entry
task = record[4]
t_start = record[5] # process start time
task_start_rng[task] = (t_start, t_s... |
def gcd(a, b):
"""Calculate the Greatest Common Divisor of (a, b). """
while b != 0:
a, b = b, a % b
return a |
def bio_tags(off, entity_info):
"""
Creates list with BIO tags in a sentence.
Parameters:
-----------
xml_sent: sentence in xml format
Returns:
--------
list of BIO tags
"""
for (span, e_type) in entity_info :
e_start, e_end = span[0], span[1]
if off[0] == e_... |
def colorize(msg, color):
"""
Wrap a message in ANSI color codes.
"""
return '\033[1;{0}m{1}\033[1;m'.format(color, msg) |
def reconstruct_text(text_list):
""" We split the text into a list of words, reconstruct that
text back from the list. """
return ''.join(text_list) |
def merge_st(S1, S2):
"""Merge two sorted Python Lists S1 and S2 into properly sized list S"""
i = j = 0
S = S1+S2
while i+j < len(S):
if j == len(S2) or (i < len(S1) and S1[i] < S2[j]):
S[i+j] = S1[i]
i = i+1
else:
S[i+j] = S2[j]
j = j+1
... |
def get_index2word(word2idx):
"""
:param word2idx: dictionary of word to index
:return: reverse order of input dictionary
"""
idx2word = dict([(idx, word) for word, idx in word2idx.items()])
return idx2word |
def prune_satisfied_clauses(clauses, variables):
"""Remove any clause that is already satisfied (i.e. is True) from the
given clause set.
Parameters
----------
clauses: seq
Sequence of clauses
variables: dict
variable name -> bool mapping
Returns
-------
clauses: se... |
def _get_document_type(abs_path: str) -> str:
"""
The data is downloaded such that the lowest subdirectory is the name of the document type.
i.e.) In the path /hcs-na-v2/new-mat/bunge/han53-2005.shu, the document type is "bunge"
"""
return abs_path.split('/')[-2] |
def parse_response(resp):
"""split the response up by commas"""
response_list = resp[0].split(',')
return response_list |
def write_variant(number):
"""Convert an integer to a protobuf variant binary buffer."""
if number < 128:
return bytes([number])
return bytes([(number & 0x7F) | 0x80]) + write_variant(number >> 7) |
def sig_cmp(u, v, order):
"""
Compare two signatures by extending the term order to K[X]^n.
u < v iff
- the index of v is greater than the index of u
or
- the index of v is equal to the index of u and u[0] < v[0] w.r.t. order
u > v otherwise
"""
if u[1] > v[1]:
retu... |
def word_list_to_long(val_list, big_endian=True):
"""Word list (16 bits int) to long list (32 bits int)
By default word_list_to_long() use big endian order. For use little endian, set
big_endian param to False.
:param val_list: list of 16 bits int value
:type val_list: list
:... |
def response_plain_context_ga(output, attributes, continuesession):
""" create a simple json plain text response """
return {
"payload": {
'google': {
"expectUserResponse": continuesession,
"richResponse": {
"items": [
{
... |
def ipv4_int(ipv4_str):
"""Returns an integer corresponding to the given ipV4 address."""
parts = ipv4_str.split('.')
if len(parts) != 4:
raise Exception('Incorrect IPv4 address format: %s' % ipv4_str)
addr_int = 0
for part in parts:
part_int = 0
try:
part_int = ... |
def convert_box(x1, y1, width, height, img_width, img_height):
"""
Convert from x1, y1, representing the center of the box and its width and
height to the top left and bottom right coordinates.
:param x1: the x coordinate for the center of the bounding box
:param y1: the y coordinate for the center... |
def get_host(environ):
"""Return the real host for the given WSGI environment. This takes care
of the `X-Forwarded-Host` header.
:param environ: the WSGI environment to get the host of.
"""
scheme = environ.get('wsgi.url_scheme')
if 'HTTP_X_FORWARDED_HOST' in environ:
result = environ[... |
def bool_to_private_text(private_bool):
""" If is_name_private returns false, return 'public', if true return 'public' """
if private_bool:
return "Private"
return "Public" |
def rayTracingResultsFileName(
site, telescopeModelName, sourceDistance, zenithAngle, label
):
"""
Ray tracing results file name.
Parameters
----------
site: str
South or North.
telescopeModelName: str
LST-1, MST-FlashCam, ...
sourceDistance: float
Source distanc... |
def writesLabelsToJsonFile(labels):
"""Convert labels dict to the form that's expected"""
tmpLabels = dict(labels)
for label in labels:
tmpLabels[label] = list(labels[label])
return tmpLabels |
def usage():
"""Print Usage Statement.
Print the usage statement for running slack.py standalone.
Returns:
msg (str): usage statement
Example:
>>> import slack
>>> msg = stream.usage()
>>> msg
'stream.py usage:\n$ python slack.py "<YOUR_SLACK_WEB_API_TOKEN>"'
... |
def get_neighbors(x2y, y2x):
"""Get all neighboring graph elements of the same type.
Parameters
----------
x2y : list or dict
Element type1 to element type2 crosswalk.
y2x : list or dict
Element type2 to element type1 crosswalk.
Returns
-------
x2x : dict
Elemen... |
def rgb_to_hex(rgb):
"""
Convert RGB tuple to hex.
Parameters
----------
rgb : tuple[int]
An RGB tuple.
Returns
-------
str
A hex color string.
"""
return f"#{rgb[0]:x}{rgb[1]:x}{rgb[2]:x}".upper() |
def str2float(value: str):
""" Change a string into a floating point number, or a None """
if value == 'None':
return None
return float(value) |
def m_shape(A):
"""
Determines the shape of matrix A.
"""
rows = len(A)
columns = len(A[0]) if A else 0
return rows, columns |
def lemma1(N, p):
"""return a value for prime p which is the sum of int(n/p^i) for all i
where int(n/p^i) <= n"""
v = 1
i = 1
tosum = []
_N = float(N)
while v >= 1:
v = int(_N / float(p ** i))
if v < 1:
break
tosum.append(v)
i += 1
return sum... |
def _isFloat(argstr):
""" Returns True if and only if the given string represents a float. """
try:
float(argstr)
return True
except ValueError:
return False |
def lr1(step: int, base_lr: float) -> float:
"""Medium aggression lr scheduler."""
lr = base_lr
_lr = lr * 0.975 ** (step // 20)
return max(_lr, lr * 1e-3) |
def listOfGetCommands(glist):
""" Returns a list of vclient command line options,
readily compiled for the readVclientData method.
"""
clist = []
clist.append('-c')
clist.append(','.join(glist))
return clist |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.