content stringlengths 42 6.51k |
|---|
def handles_url(url):
"""
Does this driver handle this kind of URL?
"""
return url.startswith("dht+udp://") |
def sign(x):
"""Retuns 1 if x > 0 else -1. > instead of >= so that sign(False) returns -1"""
return 1 if x > 0 else -1 |
def remainder(val: str) -> str:
""" Return unpaired chars, else empty string """
expected = {')': '(', '}': '{', ']': '[', '>': '<'}
opened = []
for char in list(val):
if char in '({[<':
opened.append(char)
elif char in ')}]>':
if opened and opened[-1] == expecte... |
def parseMalformedBamHeader(headerDict):
"""
Parses the (probably) intended values out of the specified
BAM header dictionary, which is incompletely parsed by pysam.
This is caused by some tools incorrectly using spaces instead
of tabs as a seperator.
"""
headerString = " ".join(
"{}... |
def __check_rule(s_index, part_size, part_index):
"""
CV.
"""
return s_index / part_size == part_index |
def _remove_anonymous_asset_paths(layer, path, identifiers):
"""Remove any anonymous identifier that is/will be merged into a USD stage."""
if path in identifiers:
# If `path` is one of the anonymous layers, setting to an empty
# string will force USD to treat the Asset Path as if it were
... |
def decrypt(ciphertext, key):
"""Dccrypt a ciphertext using key.
This method will return the plaintext as a list of bytes.
"""
plaintext = []
key_length = len(key)
for i in range(len(ciphertext)):
p = ciphertext[i]
k = ord(key[i % key_length])
c = (p - k) % 256
pl... |
def is_prime(number: int) -> bool:
"""Return whether the specified number is a prime number."""
if number <= 1:
return False
for num in range(1, number):
if number % num == 0 and number != num and num != 1:
return False
return True |
def compress_name(champion_name):
"""To ensure champion names can be searched for and compared,
the names need to be reduced.
The process is to remove any characters not in the alphabet
(apostrophe, space, etc) and then convert everything to lowercase.
Note that reversing this is non-trivial, ther... |
def is_valid_position(password: str) -> bool:
"""
Check if given password is valid.
Example: '1-3 b: cdefg' is invalid: neither position 1 nor position 3 contains b.
:type password: str
:rtype: bool
"""
import re
first_index, second_index, letter, pwd = re.split(': |-| ',password)
r... |
def serialize_key(key: str) -> bytes:
"""Serializes a key for use as BigTable row key."""
return key.encode("utf-8") |
def append_dict(dic_a:dict, dic_b:dict):
"""On the fly add/change a key of a dict and return a new dict, without changing the original dict
Requires Python 3.5 or higher.
In Python 3.9 that can be substituted by
dic_a | dic_b
Args:
dic_a (dict): [description]
dic_b (dict): [de... |
def collect_named_entities(tokens):
"""
Creates a list of Entity named-tuples, storing the entity type and the start and end
offsets of the entity.
:param tokens: a list of tags
:return: a list of Entity named-tuples
"""
named_entities = []
start_offset = None
end_offset =... |
def with_tau_m(tau_m, prms):
""" convert back from dimnesionless units """
p = dict(prms)
p["tau_m"] = tau_m
p["rin_e"] = prms["rin_e"] / tau_m
p["tr"] = prms["tr"] * tau_m
p["df"] = prms["df"] / tau_m
p["dt"] = prms["dt"] * tau_m
p["f_c"] = prms["f_c"] / tau_m
p["f_max"] = prms["f_m... |
def accumulator_value(rules):
"""Accumulate value until infinite loop starts."""
counter = 0
pos = 0
visited_pos = []
while pos not in visited_pos:
rule = rules[pos]
visited_pos.append(pos)
if rule[0] == 'acc':
counter += rule[1]
pos += 1
elif ... |
def valid_version(version):
"""Return true if the **version** has the format 'x.x.x' with integers `x`"""
try:
numbers = [int(part) for part in version.split('.')]
except ValueError:
return False
if len(numbers) == 3:
return True
else:
return False |
def freqs2probs(freqs):
"""Converts the given frequencies (list of numeric values) into probabilities.
This just normalizes them to have sum = 1"""
freqs = list(freqs)
total = float(sum(freqs))
return [f/total for f in freqs] |
def format_decimal(num: float, decimal_places: int):
"""Formats float as a string with number of decimal places."""
return format(num, '.' + str(decimal_places) + 'f') |
def get_minidump_keys(crash_info):
"""Get minidump_keys."""
# This is a new crash, so add its minidump to blobstore first and get the
# blob key information.
if crash_info:
return crash_info.store_minidump()
return '' |
def appname_basename(appname):
"""Returns the base name of the app instance without instance id."""
basename, _taskid = appname.split('#')
return basename |
def type_aware_equals(expected, actual):
"""
Use the type of expected to convert actual before comparing.
"""
if type(expected) == int:
try:
return expected == int(actual)
except:
return False
elif type(expected) == float:
try:
return expec... |
def exp_lr_scheduler(optimizer, epoch, lr_decay=0.1, lr_decay_epoch=7):
"""Decay learning rate by a factor of lr_decay every lr_decay_epoch epochs"""
if epoch % lr_decay_epoch:
return optimizer
for param_group in optimizer.param_groups:
param_group['lr'] *= lr_decay
return op... |
def downloadable_version(url):
"""Strip the version out of the git manual download url."""
# example: https://github.com/.../v2.14.1.windows.1/Git-2.14.1-64-bit.exe
return url.split('/')[-2][1:] |
def _complete(states):
"""Returns as per Task.complete depending on whether ALL elements of the given list are at least that state
Priority is "none", "skipped", "revealed", "complete"; this returns the lowest priority complete value that any
list entry has.
"""
toReturn = "complete"
for st... |
def get_protein_score(average_coverage, coverage):
"""Returns relative coverage
Args:
average_coverage (float): average read coverage in the sample
coverage (float): read coverage of contig
"""
try:
result = coverage / average_coverage
except ZeroDivisionError:
resu... |
def sma_calc(candle_list, period_qty):
"""
Calculate the SMA 20 period.
"""
period_sum = 0.0
for candle in candle_list:
period_sum += candle["close"]
result = period_sum / period_qty
return result |
def permutations(l):
""" Generate the permutations of l using recursion. """
if not l:
return [[]]
result = []
for i in range(len(l)):
item = l.pop(i)
temp_result = permutations(l)
l.insert(i,item)
for res in temp_result:
res.append(item)
result.extend(temp_result)
return result |
def _test_categories(line):
"""Returns a tuple indicating whether the line contained categories, the
value of category 1, and the value of category 2."""
if line.lower().startswith('categories : '):
category1 = line[16:48].strip()
category2 = line[48:].strip()
return True, categor... |
def subtract_params(param_list_left: list, param_list_right: list):
"""Subtract two lists of parameters
:param param_list_left: list of numpy arrays
:param param_list_right: list of numpy arrays
:return: list of numpy arrays
"""
return [x - y for x, y in zip(param_list_left, param_list_right)] |
def get_scop_labels_from_string(scop_label):
"""
In [23]: label
Out[23]: 'a.1.1.1'
In [24]: get_scop_labels_from_string(label)
Out[24]: ('a', 'a.1', 'a.1.1', 'a.1.1.1')
"""
class_, fold, superfam, fam = scop_label.split('.')
fold = '.'.join([class_, fold])
superfam = '.'.join([fold,... |
def str_to_int(text):
"""Convert strnig with unit to int. e.g. "30 GB" --> 30."""
return int(''.join(c for c in text if c.isdigit())) |
def get_tuples(l, n=2):
"""Yield successive n-sized chunks from l."""
return [l[i:i + n] for i in range(0, len(l), n)] |
def arglist_to_dict(arglist):
"""Convert a list of arguments like ['arg1=val1', 'arg2=val2', ...] to a
dict
"""
return dict(x.split('=', 1) for x in arglist) |
def get2dgridsize(sz, tpb = (8, 8)):
"""Return CUDA grid size for 2d arrays.
:param sz: input array size
:param tpb: (optional) threads per block
"""
bpg0 = (sz[0] + (tpb[0] - 1)) // tpb[0]
bpg1 = (sz[1] + (tpb[1] - 1)) // tpb[1]
return (bpg0, bpg1), tpb |
def human_readable_list(elements, separator=', ', last_separator=' y ', cap_style='title'):
"""
:param elements: list of elements to be stringyfied
:param separator: join string between two list elements
:param last_separator: join string between the two last list elements
:param type: title (all wo... |
def tags_fromlist(python_list: list) -> str:
"""Format python list into a set of tags in HTML
Args:
python_list (list): python list to format
Returns:
str: Tag formatted list in HTML
"""
strr = ''
for tag in python_list:
strr += f"<button type='button' class='btn btn-ou... |
def doubleLetter(word, dictionaryTree):
"""Cut the words in the dictionaryTree(stored in a BST) down to only entries with the same double letter"""
splitWord = str.split(word)
letterList = []
double = ""
# Check if the word has a double letter
for letter in splitWord:
if letter in letter... |
def get_digit_c(number, digit):
""" Given a number, returns the digit in the specified position, does not accept out of range digits """
return int(str(number)[-digit]) |
def is_perfect_class(confusion_matrix, k):
"""Check if class k is perfectly predicted."""
errors = sum(confusion_matrix[k]) - confusion_matrix[k][k]
for i in range(len(confusion_matrix)):
if i == k:
continue
errors += confusion_matrix[i][k]
return errors == 0 |
def count_symbol_frequency( text ):
""" Count the frequency of symbol occurances in a body of text.
"""
frequencies = dict()
for ch in text:
if ch in frequencies:
frequencies[ch] += 1
else:
frequencies[ch] = 1
return frequencies |
def groupOptPanelPlugins(mainControl, typeDict, guiParent=None):
"""
Returns dictionary {pluginTypeName: (pluginObject, pluginTypeName,
humanReadableName, addOptPanel)}
addOptPanel: additional options GUI panel and is always None if
guiParent is None
typeDict -- dictionary ... |
def _container_config(container):
"""Get container configuration"""
config = {}
if container:
for port_map in container.ports.values():
for port in port_map:
config["host"] = port["HostIp"]
config["port"] = port["HostPort"]
return config |
def generate_uri(host, port, path):
"""
Generates URI string for connection.
Arguments
---------
host: Host string
port: Port string/number
path: Path string without a starting '/'
Returns
-------
A valid URI string.
"""
return "ws://{host}:{port}/{path... |
def get_machine_value(sensitive_machines, address):
"""
Get the value of machine at given address
"""
for m in sensitive_machines:
if m[0] == address[0] and m[1] == address[1]:
return float(m[2])
return 0.0 |
def path_does_not_exist(row):
"""
Check whether any paths exist between the source and target. We know there
isn't a path if the row has a zero path count, or has a zero dwpc if the path
count isn't present in the row
"""
if "path_count" in row:
return row["path_count"] == 0
return r... |
def ip_diff(ip1, ip2):
"""Return ip2 - ip1
ip1/ip2 should like [*,*,*,*]"""
diff = 0
for i in range(4):
diff = 256 * diff + ip2[i] - ip1[i]
return diff |
def _get_exec_name(cfg):
"""Helper function to process_function. """
filename = cfg['xcpp']['filename']
root = cfg['xcpp']['root']
libdir = cfg['python']['lib']
if libdir[0] == '/':
base = libdir
else:
base = '%s/%s' % (root, libdir)
out_fname = '%s/%s_pylib.so' % (base, file... |
def get_lock_key(object_id):
"""Determines the key to use for locking the ``TimeSlot``"""
return 'locked-%s' % object_id |
def stats(r):
"""returns the median, average, standard deviation, min and max of a sequence"""
tot = sum(r)
avg = tot/len(r)
sdsq = sum([(i-avg)**2 for i in r])
s = list(r)
s.sort()
return s[len(s)//2], avg, (sdsq/(len(r)-1 or 1))**.5, min(r), max(r) |
def format_value(value):
"""
When scraping indexable content from the search API, we joined
organisation and topic titles with pipes. Since we are combining
all the columns together here we need to make sure these get treated as
separate words.
"""
return value.replace('|', ' ') |
def time_format_converter(time_str):
"""Accepts 12-hour format time string and converts it into 24-hour strings"""
if time_str[-2:] == "AM" or time_str[-2:] == "PM":
if time_str[1] == ":":
time_str = "0" + time_str
if time_str[0:2] == "12" and time_str[-2:] == "AM":
ret... |
def repr_type_and_name(thing):
"""Print thing's type [and name]"""
s = "<" + type(thing).__name__ + '>'
if hasattr(thing,'name'):
s += ': ' + thing.name
return s |
def imageurl(value): # Only one argument.
"""Converts a string into all lowercase"""
value.split(" ")
return value.lower() |
def get_json(nifti_path):
"""
Get associated JSON of input file
"""
return nifti_path.replace(".nii.gz", ".json").replace(".nii", ".json") |
def display(computer, name, value):
"""Compute the ``display`` property.
See http://www.w3.org/TR/CSS21/visuren.html#dis-pos-flo
"""
float_ = computer['specified']['float']
position = computer['specified']['position']
if position in ('absolute', 'fixed') or float_ != 'none' or \
co... |
def value_for_dsd_ref(kind, args, kwargs):
"""Maybe replace a string 'value_for' in *kwargs* with a DSD reference."""
try:
dsd = kwargs.pop("dsd")
descriptor = getattr(dsd, kind + "s")
kwargs["value_for"] = descriptor.get(kwargs["value_for"])
except KeyError:
pass
... |
def coord_for(n, a=0, b=1):
"""Function that takes 3 parameters or arguments, listed above, and returns a list of the interval division coordinates."""
a=float(a)
b=float(b)
coords = []
inc = (b-a)/ n
for x in range(n+1):
coords.append(a+inc*x)
return coords |
def dot(a, b):
"""Dot product of vectors a and b."""
return a[0]*b[0] + a[1]*b[1] + a[2]*b[2] |
def tokensMatch(expectedTokens, receivedTokens, ignoreErrorOrder):
"""Test whether the test has passed or failed
If the ignoreErrorOrder flag is set to true we don't test the relative
positions of parse errors and non parse errors
"""
if not ignoreErrorOrder:
return expectedTokens == re... |
def make_wget(urls):
"""Download multiple URLs with `wget`
Parameters
----------
urls : list
A list of URLs to download from
"""
return 'wget -c {}'.format(' '.join(urls)) |
def xmltodict_ensure_list(value, key):
"""Make sure response is a list
xmltodict doesn't know schema's so doesn't know
something should be a list or not.
"""
if value is None:
return []
value = value[key]
if isinstance(value, list):
return value
return [value] |
def exact_value_scoring(values_list1, values_list2, values1, values2):
"""
pass this two lists of values from a pair of facets and it will
give a score for exact value matches
"""
if len(values_list1) > 0 and len(values_list2) > 0:
total_attributes = len(values_list1) + len(values_list2)
matching_attributes =... |
def log_compress(env_image):
"""
Log compression of envelope detected US image
:param env_image: numpy array of envelope detected
US data
:return: numpy array of log compressed US image
"""
import sys
import numpy as np
import logging
img_type = type(env_image).__module__
... |
def validateLabel(value):
"""
Validate label for spatial database.
"""
if 0 == len(value):
raise ValueError("Descriptive label for spatial database not specified.")
return value |
def bug11569(debugger, args, result, dict):
"""
http://llvm.org/bugs/show_bug.cgi?id=11569
LLDBSwigPythonCallCommand crashes when a command script returns an object.
"""
return ["return", "a", "non-string", "should", "not", "crash", "LLDB"] |
def xy_to_id(x: int, y: int, nelx: int, nely: int, order: str = "F") -> int:
"""
Map from 2D indices of a node to the flattened 1D index.
The number of elements is (nelx x nely), and the number of nodes is
(nelx + 1) x (nely + 1).
Parameters
----------
x:
The x-coordinate of the no... |
def match_nodes(nodes1, nodes2, excluded=[]):
"""
:param nodes1: A list of Nodes from the DMRS to be matched, sorted by span_pred_key.
:param nodes2: A list of Nodes from the DMRS against which we match, sorted by span_pred_key.
:param excluded: A list of nodeids which should not be used for matching.
... |
def getPointOnLine(x1, y1, x2, y2, n):
"""Returns the (x, y) tuple of the point that has progressed a proportion
n along the line defined by the two x, y coordinates.
Args:
x1 (int, float): The x coordinate of the line's start point.
y1 (int, float): The y coordinate of the line's start point.
... |
def maf_bubble(lst):
""" Sorts a list using a bubblesort algorithm """
for p in range(len(lst)-1, 0, -1):
for i in range(p):
if lst[i] > lst[i + 1]:
t = lst[i]
lst[i] = lst[i + 1]
lst[i + 1] = t
return lst |
def dequote(name):
""" dequote if need be """
if name[0] == '"' and name[-1] == '"':
return name[1:-1]
return name |
def parse_bucket_id(bucket_id):
"""Returns a (project_id, bucket_name) tuple."""
parts = bucket_id.split('/', 1)
assert len(parts) == 2
return tuple(parts) |
def flatten(lis: list) -> list:
"""
Given a list, possibly nested to any level, return it flattened.
From: http://code.activestate.com/recipes/578948-flattening-an-arbitrarily-nested-list-in-python/
"""
new_lis = []
for item in lis:
if isinstance(item, list):
new_lis.extend(f... |
def force_unicode(text) -> str:
""" Encodes a string as UTF-8 if it isn't already """
try: return str(text, 'utf-8')
except TypeError: return text |
def sign(num):
""":yaql:sign
Returns 1 if num > 0; 0 if num = 0; -1 if num < 0.
:signature: sign(num)
:arg num: input value
:argType num: number
:returnType: integer (-1, 0 or 1)
.. code::
yaql> sign(2)
1
"""
if num > 0:
return 1
elif num < 0:
... |
def binary_array_to_number(arr):
"""Returns decimal from the contactanation of the given binary list"""
return int(''.join([str(x) for x in arr]),2) |
def matches(open_symbol: str, close_symbol: str) -> bool:
"""Checks if the opening and closing sybols match"""
symbol_close_map = {"(": ")", "[": "]", "{": "}"}
return close_symbol == symbol_close_map.get(open_symbol) |
def FilterEmptyLinesAndComments(text):
"""Filters empty lines and comments from a line-based string.
Whitespace is also removed from the beginning and end of all lines.
@type text: string
@param text: Input string
@rtype: list
"""
return [line for line in map(lambda s: s.strip(), text.splitlines())
... |
def ksf_cast(value, arg):
"""
Checks to see if the value is a simple cast of the arg
and vice-versa
"""
# untaint will simplify the casting... not in pypyt!
v = value
a = arg
a_type = type(a)
v_type = type(v)
if v_type == a_type:
return v == a
try:
casted_v = ... |
def _pattern_has_uppercase(pattern):
""" Check whether the given regex pattern has uppercase letters to match
"""
# Somewhat rough - check for uppercase chars not following an escape
# char (which may mean valid regex flags like \A or \B)
skipnext = False
for c in pattern:
if skipnext:
... |
def is_lookup_in_users_path(lookup_file_path):
"""
Determine if the lookup is within the user's path as opposed to being within the apps path.
"""
if "etc/users/" in lookup_file_path:
return True
else:
return False |
def asciidec(val):
"""
Convert an integer to ascii, i.e. a list of integers in base 256.
Examples:
- asciidec(434591) = 6 * 256**2 + 161 * 256**1 + 159 * 256**0
- asciidec(797373) = 12 * 256**2 + 42 * 256**1 + 189 * 256**0
"""
word = []
while val > 0:
word.append(val % 256)
... |
def shape_to_HW(shape):
""" Convert from WH => HW
"""
if len(shape) != 2:
return shape # Not WH, return as is
return [shape[1], 1, 1, shape[0]] |
def get_account_ids_from_match(*matches: dict):
"""From an initial list of matches, find all account ids."""
account_ids = []
for match in matches:
for participant in match['participantIdentities']:
account_ids.append(participant['player']['accountId'])
return list(set(account_ids... |
def long2ip(ip):
"""Converts an integer representation of an IP address to string."""
from socket import inet_ntoa
from struct import pack
return inet_ntoa(pack('!L', ip)) |
def filter_even(input):
"""
[5, 6, 7] -> [6]
:return:
"""
return list(filter(
lambda i: i % 2 == 0,
input
)) |
def is_comment(line):
"""
Check if a line consists only of whitespace and
(optionally) a comment.
"""
line = line.strip()
return line == '' or line.startswith('#') |
def readFile(path):
"""Read data from a file.
@param path: The path of the file to read.
@type path: string
@return: The data read from the file.
@rtype: string
"""
f = open(path, "rb")
try:
return f.read()
finally:
f.close() |
def day_spent(records):
"""Return the total time spent for given day"""
return sum([int(record['time']) for record in records]) |
def _extract_path(srcs):
"""Takes the first label in srcs and returns its target name.
Args:
srcs: a collection of build labels of the form "//package/name:target"
Returns:
The first element's target (i.e.- the part after the ":"), else None if empty.
"""
for s in srcs:
toks =... |
def expand_data_indicies(label_indices, data_per_label=1):
"""
when data_per_label > 1, gives the corresponding data indicies for the data
indicies
"""
import numpy as np
expanded_indicies = [
label_indices * data_per_label + count for count in range(data_per_label)
]
data_indic... |
def compute_f1score(precision, recall):
""" Function to compute F1 Score"""
if precision * recall == 0:
return 0
return float(2 * precision * recall) / float(precision + recall) |
def validate_tls_security_policy(tls_security_policy):
"""
Validate TLS Security Policy for ElasticsearchDomain
Property: DomainEndpointOptions.TLSSecurityPolicy
"""
VALID_TLS_SECURITY_POLICIES = (
"Policy-Min-TLS-1-0-2019-07",
"Policy-Min-TLS-1-2-2019-07",
)
if tls_securit... |
def generate_permulations(param_list):
"""
param_list is a list(types of parameter) of list(possible parameter values)
returns a list(all permulation) of list(parameter value) in same order
as in param_list
"""
permu = []
def recurse(param_type_index, current_param_value, param_list):
... |
def product(factors):
"""Return the product of all numbers in the given list."""
prod = 1
for f in factors:
prod *= f
return prod |
def non_negative(start, idx1, idx2, symbol):
"""
Returns SMT constrains about constants being non-negative
"""
result = ""
for i in range(start, idx1):
for j in range(idx2):
const_name = symbol + str(i) + "_" + str(j)
result += "(>= " + const_name + " 0)\n"
... |
def get_good_dim(dim):
"""
This function calculates the dimension supported by opencl library (i.e. is multiplier of 2, 3, or 5) and is closest to the given starting dimension.
If the dimension is not supported the function adds 1 and verifies the new dimension. It iterates until it finds supported value.
... |
def retrieve_captions(data_list):
"""
Reads the captions from a list and returns them
Args:
data_list (list<dict>): List of image metadata
Returns:
merged_captions (list<str>): List of captions from the dataset
"""
caption_list = []
for data in data_list... |
def _min_or_none(itr):
"""
Return the lowest value in itr, or None if itr is empty.
In python 3, this is just min(itr, default=None)
"""
try:
return min(itr)
except ValueError:
return None |
def node_dict(node):
"""Convert a node object to a result dict"""
if node:
return {
'node_id': node.id,
'workers': ", ".join(node.workers),
'disks': ", ".join(node.disks),
'ram': node.memory,
'load_average' : node.load_average,
}
el... |
def parse_tab_list_view(lines, key='Name', sep=":"):
"""
:param lines:
:param key:
:return: list of dictionaries
"""
res = list()
temp = dict()
if isinstance(lines, str):
lines = lines.splitlines()
for line in lines:
if not line:
continue
sep_pos ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.