content stringlengths 42 6.51k |
|---|
def remove_model_class_name_field(fields):
"""
When reconstituting the models, they dont know how to deal with this
extra field we added. We need to get rid of it.
"""
del fields['model_class_name']
return fields |
def xor(bytearray_0, bytearray_1):
"""Exclusive ORs (XOR) the values of two bytearrays.
Parameters
----------
bytearray_0 : bytearray
bytearray_1 : bytearray
Returns
-------
output : bytearray
XOR value of two bytearrays
"""
length = min(len(bytearray_0), len(bytearray... |
def case_insensitive(x):
"""creating a function for interchanging key and value"""
return x.lower() |
def semver(major_component, minor_component, patch_component):
"""Construct an SemVer-format version number.
Args:
major_component (int): The major component of the version number.
minor_component (int): The minor component of the version number.
patch_component (int): The patch compone... |
def read_nodes(data):
"""Reads the input data as nodes"""
nodes = []
for line in data.splitlines():
words = line.split(" -> ")
first_index = words[0].index("(") + 1
second_index = words[0].index(")")
children = None
if len(words) > 1: # Has children
child... |
def distribute_tasks(n, memlim):
"""Util function for distribute tasks in matrix computation in order to
save memory or to parallelize computations.
Parameters
----------
n: int
the number of rows.
memlim: int
the limit of rows we are able to compute at the same time.
Retur... |
def n_to_c(n_dict):
""" Calculates concentrations (c) from normalized peak areas (n)
"""
n_tot = 0
for element in n_dict:
n_tot += n_dict[element]
return {element: n_dict[element]/n_tot for element in n_dict} |
def check_img_ext(filename):
"""Check that file upload is an allowable image filetype"""
allowed_image_ext = ['PNG', 'JPG', 'JPEG', 'GIF']
if not '.' in filename:
return False
ext = filename.split('.')[-1]
if ext.upper() in allowed_image_ext:
return True
else:
return... |
def dice(data, axis, i, like_shape=None):
"""like_shape means you want to embed the plane in larger plane of zeros
in the position bbox
"""
if data==None:
return None
if axis==0:
plane = data[i,:,:]
elif axis==1:
plane = data[:,i,:]
elif axis==2:
pl... |
def get_inheritance_map(classes):
"""Return a dict where values are strict subclasses of the key."""
return {scls: [p for p in classes if p != scls and p.issubclass(scls)]
for scls in classes} |
def arrayManipulation(n, queries):
"""
Args:
n (int): len of zero arr.
queries (list): 2d list with queries
Returns:
int: max element"""
arr = [0] * (n + 1)
# increase first el by query amount and decrease last of query amount
for i in queries:
arr[i[0] - 1] += i... |
def percents(x,y):
""" What percentage of x is y? """
one_percent = x/100
result = y / one_percent
return result |
def map_ores_code_to_int(code):
"""
Takes a 1-2 letter code from OREs and turns in into an int
ORES Score map
Stub - 0
Start - 1
C - 2
B - 3
GA - 4
FA - 5
"""
return {
'Stub': 0,
'Start': 1,
'C': 2,
'B': 3,
'GA': 4,
'FA': 5,
... |
def parse_vertex(text):
"""Parse text chunk specifying single vertex.
Possible formats:
* vertex index
* vertex index / texture index
* vertex index / texture index / normal index
* vertex index / / normal index
"""
v = 0
t = 0
n = 0
chunks = text.split("/")
v = int(chunks[0])
if len(c... |
def shareFavLangCost(criterion, frRow, exRow):
"""Returns 0 if the two share a favorite language, else 1"""
fluentQ = criterion['fluentQ']
learningQ = criterion['learningQ']
favT = criterion['favTable']
favQ = criterion['favQ']
frLangs = [set(frRow[fluentQ].split(',')),
set(frRow... |
def _get_acl_from_row(row):
"""
Given a row from the manifest, return the field representing file's expected acls.
Args:
row (dict): column_name:row_value
Returns:
List[str]: acls for the indexd record
"""
return [item for item in row.get("acl", "").strip().split(" ") if item] |
def purge_dup(names):
"""temporary way of making sure values are unique"""
unique_names = {k: [] for k in names}
for k in names.keys():
hash = set()
for v in names[k]:
if v['name'] not in hash:
hash.add(v['name'])
unique_names[k].append(v)
retu... |
def _is_literal(s):
"""
>>> _is_literal("http://example.org/bar")
False
>>> _is_literal('"my text"')
True
>>> _is_literal('"my text"@en-gb')
True
>>> _is_literal('"42"^^http://www.w3.org/2001/XMLSchema#integer')
True
>>> _is_literal('?var')
False
"""
return s.sta... |
def null_data_cleaner(original_data: dict, data: dict) -> dict:
""" this is to remove all null parameters from data that are added during option flow """
for key in data.keys():
if data[key] == "null":
original_data[key] = ""
else:
original_data[key]=data[key]
... |
def hack_ncbi_fasta_name(pipe_name):
"""Turn 'gi|445210138|gb|CP003959.1|' into 'CP003959.1' etc.
For use with NCBI provided FASTA and GenBank files to ensure
contig names match up.
Or Prokka's *.fna and *.gbk files, turning 'gnl|Prokka|contig000001'
into 'contig000001'
"""
if pip... |
def quick_sort(vals):
"""Return sorted list as copy."""
if len(vals) <= 1:
return vals[:]
axis = vals[0]
left = []
right = []
for val in vals[1:]:
if val <= axis:
left.append(val)
else:
right.append(val)
return quick_sort(left) + [axis] + qu... |
def merge_bbox(bbox1, bbox2):
"""Merge two pdf blocks' bounding boxes."""
return (
min(bbox1[0], bbox2[0]), # x0
min(bbox1[1], bbox2[1]), # y0
max(bbox1[2], bbox2[2]), # x1
max(bbox1[3], bbox2[3]), # y1
) |
def get_user_names(L):
"""
for each line in twitter data
slice out username
if its not in username list add it
:param L - list of twitter data:
:return user_names - list of user names:
"""
user_names = list()
for item in L:
user_name = item[0]
if user_name... |
def obfuscate_API_key(API_key):
"""
Return a mostly obfuscated version of the API Key
:param API_key: input string
:return: str
"""
if API_key is not None:
return (len(API_key)-8)*'*'+API_key[-8:] |
def gcd_euclid(a, b):
"""
10) 15 (1
10
--------
5) 10 (2
10
--------
0
GCD = 5
"""
if b == 0:
return a
else:
return gcd_euclid(b, a % b) |
def readbuffer(data):
"""
Reads an arbitary data objects and returns the byte representation
:param data:
:type data:
:return:
:rtype:
"""
if not data:
return b''
if str(type(data)) == "<type 'buffer'>":
return str(data)
elif str(type(data)) == "<class 'memoryview... |
def _format(_string, format_s='{}', style = None):
"""Add color formatting to string for printing in a terminal."""
styles = {
'green' : '\033[37m\033[42m',
'yellow' : '\033[37m\033[43m',
'red' : '\033[37m\033[41m',
None : ''
}
if not ... |
def parse_field_configured(obj, config):
"""
Parses an object to a Telegram Type based on the configuration given
:param obj: The object to parse
:param config: The configuration:
- is array?
- is array in array?
- type of the class to be loaded to
:return: the parsed object
... |
def rows_to_columns(matrix):
#hammer
"""Takes a two dimensional array and returns an new one where rows in the
first become columns in the second."""
num_rows = len(matrix)
num_cols = len(matrix[0])
data = []
for i in range(0, num_cols):
data.append([matrix[j][i] for j in range(0, num_r... |
def get_scene_index(glTF, name):
"""
Return the scene index in the glTF array.
"""
if glTF.get('scenes') is None:
return -1
index = 0
for scene in glTF['scenes']:
if scene['name'] == name:
return index
index += 1
return -1 |
def valid_content_type(content_type):
"""returns if content type is what we are looking for"""
return "text/html" in content_type |
def content_by_name_substring(content, name):
"""
:type content: dict
:param content: The python dict form of the content that has been returned from a query to KairosDB
:type name: string
:param name: This is the string that will be used to match, as a lowercase substring, the things that we want ... |
def divide_channels(old_pixel: tuple, denominator: int) -> tuple:
"""Return a new pixel that has colour channels set to the quotient from dividing the
corresponding colour channel in old_pixel by denominator.
* Assumed that denominators are positive integers.
>>> example_pixel = (100, 12, 155)
>>>... |
def shift(char: str, key: int) -> str:
"""Shift the character by the given key."""
if char == "-":
return " "
else:
return chr(97 + (ord(char) - 97 + key % 26) % 26) |
def get_complement(sequence):
"""Get the complement of `sequence`.
Returns a string with the complementary sequence of `sequence`.
If `sequence` is empty, an empty string is returned.
"""
#Convert all rna_sequence to upper case:
sequence=sequence.upper()
# Conver RNA sequence into a list
... |
def usd(value):
""" Format value as USD """
return f"${value:,.2f}" |
def gauss_sum(n):
"""Calculate sum(x for x in range(1, n+1)) by formula."""
return n * (n + 1) // 2 |
def find_end_paren(function_code: str, start: int):
"""
Find the end location given a starting parenthesis location
:param function_code:
:param start:
:return:
"""
parentheses = []
for i, character in enumerate(function_code[start:]):
if character == "(":
parentheses... |
def _get_level(path):
"""Determine the number of sub directories `path` is contained in
Args:
path (string): The target path
Returns:
int: The directory depth of `path`
"""
normalized = path
# This for loop ensures there are no double `//` substrings.
# A for loop is used ... |
def inverted_index_add(inverted, doc_id, doc_index):
"""
create a WORD LEVEL DOCUMENT UNSPECIFIC Inverted-Index
{word:{doc_id:[locations]}}
"""
for word, locations in doc_index.items():
indices = inverted.setdefault(word, {})
indices[doc_id] = locations
return inverted |
def updatemany_data_handler(args):
""" Handler to override the api action taken for updatemany """
_, path, data = args
return "PATCH", path, data |
def hash_str(f):
"""
Return sha256 of input string
"""
import hashlib
return hashlib.sha256(str(f).encode()).hexdigest() |
def y_from_m_b_x(m, b, x):
"""
get y from y=mx+b
:param m: slope (m)
:param b: b
:param x: x
:return: y from y=mx+b
"""
return m * x + b |
def _CheckBarcode(barcode):
"""Check weather the UPC-A barcode was decoded correctly.
This function calculates the check digit of the provided barcode and compares
it to the check digit that was decoded.
Args:
barcode(string): The barcode (12-digit).
Return:
(bool): True if the barcode was decoded c... |
def make_query(columns, filter):
"""
columns is a string from args.columns
filter is a string from args.filter
this will build the main query using input from columns and filter
"""
if columns is not None:
# the user only wants to report a subset of the columns
query = "SELECT " ... |
def convert_seconds(seconds: float) -> str:
"""
Convert time in seconds to days:hours:minutes:seconds.milliseconds
with leading 0s removed.
Parameters
----------
seconds : float
Number of seconds to be converted.
Returns
-------
str
Converted time.
... |
def lookup(index, event_ref_list):
"""
Get the unserialized event_ref in an list of them and return it.
"""
if index < 0:
return None
else:
count = 0
for event_ref in event_ref_list:
(private, note_list, attribute_list, ref, role) = event_ref
if index ... |
def analytic_convolution_gaussian(mu1,covar1,mu2,covar2):
"""
The analytic vconvolution of two Gaussians is simply the sum of the two mean vectors
and the two convariance matrixes
--- INPUT ---
mu1 The mean of the first gaussian
covar1 The covariance matrix of of the first gaussian... |
def _query(data, predicate=None, key=None, reverse=False):
"""Query data and return results as a list of items.
Args:
data: list of lists or list of tuples
predicate: custom function for filtering results.
key: custom comparison key function for sorting results.
Set to get_i... |
def service_fully_started(dut, service):
"""
@summary: Check whether the specified service is fully started on DUT. According to the SONiC design, the last
instruction in service starting script is to run "docker wait <service_name>". This function take advantage
of this design to check whether ... |
def getCustomOutMsg(errMsg=None, errCode=None, msg=None, exitCode=None):
""" Create custom return dictionary """
newOut = {}
if errMsg:
newOut['error_description'] = errMsg
if errCode:
newOut['error'] = errCode
if msg:
newOut['msg'] = msg
if exitCode:
newOut['exit... |
def create_ordering_payload(order=None):
"""Creates a payload for the given order
:param order: The order, defaults to None
:type order: dict, optional
:raises ValueError: If the order is not a dictionnary
:return: The created payload
:rtype: dict
"""
payload = {}
if not order:
... |
def extract_value(obj, key):
"""Pull all values of specified key from nested JSON."""
arr = []
def extract(obj, arr, key):
"""Recursively search for values of key in JSON tree."""
if isinstance(obj, dict):
for k, v in obj.items():
if k == key:
... |
def _escape_key(string):
"""
The '_type' and '_meta' keys are reserved.
Prefix with an additional '_' if they occur.
"""
if string.startswith("_") and string.lstrip("_") in ("type", "meta"):
return "_" + string
return string |
def ERR_CHANNELISFULL(sender, receipient, message):
""" Error Code 471 """
return "ERROR from <" + sender + ">: " + message |
def list_reduce(fn, lst, dftl):
"""Implementation of list_reduce."""
res = dftl
i = 0
while i < len(lst):
res = fn(res, lst[i])
i = i + 1
return res |
def fmt(x, pos):
"""
Format color bar labels
"""
if abs(x) > 1e4 or (abs(x) < 1e-2 and abs(x) > 0):
a, b = f"{x:.2e}".split("e")
b = int(b)
return fr"${a} \cdot 10^{{{b}}}$"
elif abs(x) > 1e2 or (float(abs(x))).is_integer():
return fr"${int(x):d}$"
elif abs(x) > ... |
def get(seq, ind, defVal=None):
"""Return seq[ind] if available, else defVal"""
try:
return seq[ind]
except LookupError:
return defVal |
def ascii_hex_to_byte(ascii_bytes):
"""
Returns integer value, which is encoded as hexadecimal in first
two characters (ascii bytes) of input; assumes *ascii_bytes* is a
string or array of characters.
Raises ValueError if there was a problem parsing the hex value.
"""
assert len(ascii_byte... |
def at_least(actual_value, expected_value):
"""Assert that actual_value is at least expected_value."""
result = actual_value >= expected_value
if result:
return result
else:
raise AssertionError(
"{!r} is LESS than {!r}".format(actual_value, expected_value)
) |
def any(p, xs):
"""
any :: (a -> Bool) -> [a] -> Bool
Applied to a predicate and a list, any determines if any element of the
list satisfies the predicate. For the result to be False, the list must be
finite; True, however, results from a True value for the predicate applied
to an element at a ... |
def binpow(x: int, n: int, m: int) -> int:
"""Return x**n % m."""
ans = 1
while n:
if n & 1: ans = ans * x % m
x = x * x % m
n >>= 1
return ans |
def reshape_images(image_list=None):
"""
:param image_list: A list of images to reshape for plotting
:return: Images that can be plotted with show_images
"""
if image_list is None:
raise ValueError("Please provide a list of images to reshape.")
final_list = [img[:, :, 0] if len(img.sh... |
def quoteIfNeeded(txt, quoteChar='"'):
"""
quoteIfNeededtxt)
surrounds txt with quotes if txt includes spaces or the quote char
"""
if isinstance(txt, bytes):
txt=txt.decode()
if txt.find(quoteChar) or txt.find(' '):
return "%s%s%s" % (quoteChar, txt.replace(quoteChar, "\\%s" % quoteChar), quoteC... |
def create_batches(graphs, batch_size):
"""
Creating batches of graph locations.
:param graphs: List of training graphs.
:param batch_size: Size of batches.
:return batches: List of lists with paths to graphs.
"""
batches = [graphs[i:i + batch_size] for i in range(0, len(graphs), batch_size)... |
def initialize_scale_config_details(node_classes, param_key, param_value):
""" Initialize scale cluster config details.
:args: node_class (list), param_key (string), param_value (string)
"""
scale_config = {}
scale_config['scale_config'], scale_config['scale_cluster_config'] = [], {}
for each_no... |
def get_operand_string(mean, std_dev):
"""
Method to get operand string for Fsl Maths
Parameters
----------
mean : string
path to img containing mean
std_dev : string
path to img containing standard deviation
Returns
------
op_string : string
operand... |
def E_c(contact_dist, margin, constant, missing_weight=1):
"""
Contact energy function
:param contact_dist: dictionary of geom id and its distance from the target
:param margin: maximum distance between geom and target detected
:param constant: constant dist we ideally want the geoms to "invade" t... |
def compare_with_lt(x, y):
"""
Comparator function that promises only to use the `<` binary operator
(not `>`, `<=`, etc.)
See also: `functools.cmp_to_key` if you plan to use this with `sorted`.
"""
if x < y:
return -1
elif y < x:
return 1
else:
return 0 |
def imlistidx(filelist, idx_in_filename):
"""Return index in list of filename containing index number"""
return [i for (i, item) in enumerate(filelist)
if (item.find('%d' % idx_in_filename) > 0)] |
def parse_config(config, value):
"""Parse config for string interpolation"""
config["tmp_value"] = value
return config["tmp_value"] |
def get_valid_uuids(uuids: list, full_paths: list, valid_full_paths: list) -> list:
"""Returns valid uuids."""
return [uuid for uuid, full_path in zip(uuids, full_paths) if full_path in valid_full_paths] |
def filter_blobnames_for_prefix(candidates, prefix, sep):
"""Given a iterator of candidate blob names, return a set of
2-tuples indicating each match:
(<sub-name>, <is-partial-match>)
where,
<sub-name> is the import component after the prefix
<is-partial-match> is a boolean indicat... |
def _sprite_has_rectangular_region(sprite):
"""
A replacement function for the ugly compound in sprite_in_view
"""
return (
hasattr(sprite, "width")
and hasattr(sprite, "height")
and hasattr(sprite, "left")
and hasattr(sprite, "right")
and hasattr(sprite, "top")
... |
def mod_inverse(a, n):
"""Return the inverse of a mod n.
n must be prime.
>>> mod_inverse(42, 2017)
1969
"""
b = n
if abs(b) == 0:
return (1, 0, a)
x1, x2, y1, y2 = 0, 1, 1, 0
while abs(b) > 0:
q, r = divmod(a, b)
#print("q : " + str(q) + " r : " + str(r));
x = x2 - q * x1
y = y2 - q * y1
a, b,... |
def pad4(length):
"""
>>> pad4(9)
3
>>> pad4(20)
0
:param length:
:return:
"""
return -(length % -4) |
def new_game(n):
"""
Inicializa la matrix en blanco (4x4) lista de listas
"""
matrix = []
for i in range(n):
matrix.append([0] * n)
return matrix |
def ll4(x,b,c,d,e):
"""Dose-response function - LM equation, LL.4 function (4-parameter sigmoidal function).
- b: hill slope
- c: min response
- d: max response
- e: EC50"""
import numpy as np
import warnings
warnings.filterwarnings('ignore')
return(c+(d-c)/(1+np.exp(b*(np.log(x)... |
def qcVector(vectint, records):
"""
Given a set of vector interval and a genome to correct remove the
sequence of the genomes overlapping with the vector intervals, if
the overlap occurs less than 100nts away from the contig ends
Args: vectint list of intervals
genome genome sequence file
... |
def note_and_bend(mycents, middle_note=60):
"""Take a cent value and return a MIDI note and bend.
Scale to '0 cents = middle-C' if middle_c=True.
"""
note, remain = divmod(mycents + 50, 100.0)
note = int(note + middle_note)
bend = 8192 + int(round((remain - 50) * 40.96))
return note, bend |
def str_or_NONE(value):
"""If the `value` is `None` returns a "NONE"",
otherwise returns `str(value)`
"""
if value is None:
return 'NONE'
return str(value) |
def format_box_wider2tfrecord(x, y, w, h, real_h, real_w):
"""
wider to tf_record record the rate of min point and width/height
:param x:
:param y:
:param w:
:param h:
:param real_h:
:param real_w:
:return:
"""
print('orig: ', x, y, w, h, real_h, real_w)
x_ = x / real_w
... |
def precond_is_classifier(iterable=None, program=None):
"""Ensure that a program can do classification."""
if program.__class__.__name__ in ['SGDClassifier',
'LogisticRegression']:
return True
else:
return False |
def set_runtime_build(runtime_build: bool) -> bool:
"""
When runtime_build is True, csrc will be built at runtime.
Default is False.
"""
if not isinstance(runtime_build, bool):
raise TypeError("runtime_build must be bool")
global _runtime_build
_runtime_build = runtime_build
retu... |
def pad_to_multiple_of(n, mult):
"""
pads n to a multiple of mult
"""
extra = n % mult
if extra > 0:
n = n + mult - extra
return n |
def ArrowCurve(type=1, a=1.0, b=0.5):
"""
ArrowCurve( type=1, a=1.0, b=0.5, c=1.0 )
Create arrow curve
Parameters:
type - select type, Arrow1, Arrow2
(type=int)
a - a scaling parameter
(type=float)
b - b scaling parameter
(type=float)
Ret... |
def cardLuhnChecksumIsValid(card_number):
""" checks to make sure that the card passes a luhn mod-10 checksum """
sum = 0
num_digits = len(card_number)
oddeven = num_digits & 1
for count in range(num_digits):
digit = int(card_number[count])
if not (( count & 1 ) ^ oddeven):
... |
def kwargs_to_variable_assignment(kwargs: dict, value_representation=repr,
assignment_operator: str = ' = ',
statement_separator: str = '\n',
statement_per_line: bool = False) -> str:
"""
Convert a dictionary i... |
def version2tuple(ver: str) -> tuple:
"""Convert version to numeric tuple"""
import re
if re.match(r"\d+\.\d+\.\d+$", ver) is None:
raise ValueError(r"Version must be well formed: \d+\.\d+\.\d+")
return tuple([int(val) for val in ver.split(".")]) |
def has_two_stage_cooling(cool_stage):
"""Determines if the cooling stage has two-stage capability
Parameters
----------
cool_stage : str
The name of the cooling stage
Returns
-------
boolean
"""
if cool_stage == "two_speed" or cool_stage == "two_stage":
return Tru... |
def _strip_declaration(contents: str):
""" Strips declaration from the file if there - lxml doesn't like it."""
return str.replace(contents,r'<?xml version="1.0" encoding="utf-8"?>','').strip() |
def format_error(worker_id, message):
"""Formats an error message with the provided worker ID."""
return f"Worker {worker_id}: {message}" |
def reverse_match_odds(match, odds):
"""
Reverse match opponents and odds (away - home -> home - away)
"""
match = " - ".join(reversed(match.split(" - ")))
odds.reverse()
return match, odds |
def merge_raw_data(commits, lines_of_code):
"""
Creates a list of the files sorted primarily by the number of changes
and secondly by the number of lines of code.
:param commits: a dict of file names and the number of commits
:param lines_of_code: a dict of file names and the number of lines of cod... |
def handle(string: str) -> str:
"""
>>> handle('https://github.com/user/repo')
'user/repo'
>>> handle('user/repo')
'user/repo'
>>> handle('')
''
"""
splt = string.split("/")
return "/".join(splt[-2:] if len(splt) >= 2 else splt) |
def quote_path(path):
"""
Surrounds the path in quotes.
:param path:
:return: string
"""
return '"' + path.strip('"') + '"' |
def canonise(i, j):
""" Return canonical intervals of the input interval.
Args:
i (int): left endpoint of input interval (inclusive).
j (int): right endpoint of input interval (inclusive).
Returns:
List of canonical intervals. Each interval is of the form (start,end)
where ... |
def wrap_function_agg(function, args):
"""
Wrap function for the objective function in the BHHH.
"""
ncalls = [0]
if function is None:
return ncalls, None
def function_wrapper(*wrapper_args):
ncalls[0] += 1
return function(*(wrapper_args + args)).sum()
return ncall... |
def _prod(lst):
"""
.. todo::
WRITEME
"""
p = 1
for l in lst:
p *= l
return p |
def get_skeleton_mapIdx(numparts):
"""
Calculate the mapsIdx for each limb from the skeleton.
Input:
skeleton: list of part connection
Output:
list of ids for x and y for part
"""
connections_num = numparts
mapIdx = list()
for i in range(connections_num):
ma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.