content stringlengths 42 6.51k |
|---|
def unshift_token(text):
"""Remove a token from the front of a string.
:param str text:
:returns: {'text': str, 'separator': str, 'remainder': str}
"""
if len(text) == 0:
return {'text': text, 'separator': '', 'remainder': ''}
token = ''
for i in range(0, len(text)):
char =... |
def _convert_bytes(content):
"""
TypeError: str() takes at most 1 argument (2 given) # python2
"""
try:
return str(content, "utf-8")
except TypeError:
return str(content) |
def date_name_converter(date):
"""Convert date strings like "DD-MonthName3Letters-YY" to "MM-DD-YY" """
for month_num, month in enumerate(
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
'Nov', 'Dec']):
num_str = str(month_num + 1)
if len(num_str) == 1:
... |
def uses_only(word, letters):
"""return true if word only use a set letters"""
letters = letters.lower()
for letter in word:
if letter.lower() not in letters:
return False
return True |
def unravel_index(index, shape):
""" Analog of numpy.unravel_index. """
out = []
for dim in reversed(shape):
out.append(index % dim)
index = index // dim
return tuple(reversed(out)) |
def duck_type_collection(specimen, default=None):
"""Given an instance or class, guess if it is or is acting as one of
the basic collection types: list, set and dict. If the __emulates__
property is present, return that preferentially.
"""
if hasattr(specimen, '__emulates__'):
# canonicali... |
def getVals( assembliesList, key ):
""" returns a list of values given a key and the list of assemblies.
"""
v = []
for a in assembliesList:
v.append( a.valuesDict[ key ] )
return v |
def _urls(repository, commit, mirrors):
"""Compute the urls from which an archive of the provided GitHub
repository and commit may be downloaded.
Args:
repository: GitHub repository name in the form organization/project.
commit: git revision for which the archive should be downloaded.
... |
def find_least_most( lol, index ):
"""
- finds the number of the min, and the max of a column from a list of lists
- returns ( m_count, b_count )
"""
column = []
for line in lol:
if "diagnosis" in line:
continue
column.append( line.split(",")[ index ] )
return( column.count( "M" ), column.count( "B" ) ) |
def _pictLstToDict(lst):
"""Convert picture from list to dictionary."""
return {i:lst[i] for i in range(len(lst))} |
def parse_filters(filter_list):
"""[will remove = from list items and return just the filter that we can work with]
Args:
filter_list ([list]): [filter list that we need to extract filters from]
Returns:
[List]: [the new filter list after we extract it]
"""
if filter_list:
... |
def _get_payload(instream, identifier):
"""Find the identifier and get the part between {curly brackets}."""
for line in instream:
if '//' in line:
line, _ = line.split('//', 1)
line = line.strip(' \r\n')
# for this to work the declaration must be at the start of the line
... |
def encode_complex(obj):
"""Convert a complex number object into a list containing the real and imaginary values."""
return [obj.real, obj.imag] |
def params_schedule_fn_interval(outside_info):
"""
outside_information (dict):
progress (float in [0, 1] interval) a number that indicate progress
"""
assert outside_info != {} and "progress" in outside_info, \
"if this happens during initialization, please add initial_info to env_params... |
def is_prime_v1(n):
"""Return 'True' if 'n' is a prime number. False otherwise"""
if n == 1:
return False # 1 is not a prime number
for d in range(2, n):
if n % d == 0:
return False
return True |
def calculate_total(books):
"""
Returns the minimum cost of books for any conceivable shopping cart
"""
# We store the discounted price of occurences of each type
d = {
0: 0,
1: 800,
2: 1520,
3: 2160,
4: 2560,
5: 3000
}
total_cost = 0
tota... |
def _get_id_from_api_filter_link(filter_link):
"""Get the id from an api filter link.
Expects the id to come after the "/service/apifilter/" part of the link.
Example filter_link: '/admin/service/apifilter/12345/'
Example return: '12345'
:return: the api filter id
:rtype: str
"""
link_... |
def Builder(*_args, **_kw):
"""Fake Builder"""
return ["fake"] |
def shape(data):
"""
Given a nested list or a numpy array,
return the shape.
"""
if hasattr(data, "shape"):
return list(data.shape)
else:
try:
length = len(data)
return [length] + shape(data[0])
except TypeError:
return [] |
def get_filtered_filename(filename, filename_key):
"""
Return the 'filtered filename' (according to `filename_key`)
in the following format:
`filename`__`filename_key`__.ext
"""
try:
image_name, ext = filename.rsplit('.', 1)
except ValueError:
image_name = filename
ex... |
def EscapeDelimiters(s):
"""
Changes "" into "\" and "|" into "\|" in the input string.
:param `s`: the string to be analyzed.
:note: This is an internal functions which is used for saving perspectives.
"""
result = s.replace(";", "\\")
result = result.replace("|", "|\\")
return resu... |
def is_unique(s):
"""Check if the list s has no duplicate."""
return len(s) == len(set(s)) |
def sentence_id(json_sentence):
"""
Return the unique if of a sentence.
"""
return '_'.join([
str(json_sentence['did']),
str(json_sentence['pid']),
str(json_sentence['sid'])
]) |
def fmt_usd(my_price):
"""
Converts a numeric value to US dollar-formatted string, for printing and display purposes.
Param: my_price (int or float) like 4000.444444
Returns: $4,000.44
"""
return f"${my_price:,.2f}" |
def allowednewrequirements(repo):
"""Obtain requirements that can be added to a repository during upgrade.
This is used to disallow proposed requirements from being added when
they weren't present before.
We use a list of allowed requirement additions instead of a list of known
bad additions becau... |
def str2bool(string):
"""
converts a string into a bool
"""
if string == True:
return True
if string == False or string[:1].lower() == 'f' or string[:1].lower() == 'n':
return False
else:
return True |
def _aggregate(k, oldValue, newValue, summary):
"""
Apply to numeric values, aummarize the diffence
:param k:
:param oldValue:
:param newValue:
:param summary:
:return:
"""
try:
num1 = float(oldValue)
num2 = float(newValue)
if k in summary:
summary... |
def _get_set_name(test_data):
"""Get the set_name from test_data
Return the value of 'set_name' key if present in the data
If set_name it is not present in data, return the value of the first key.
If there's no data, leave set_name as ''
"""
set_name = ''
if 'set_name' in test_data:
... |
def set_true_for_empty_dict(d):
"""
Recursively set value of empty dicts from a dictionary.
For some of entity G Suite API return {} (blank dictionary) which indicates some actions on resource.
Eg. Here, new or upload indicates resource is newly created or uploaded on the server.
{
"new": {}, /... |
def _is_none(s: str) -> bool:
"""Check if a value is a text None."""
if s == 'None':
return True
return False |
def format_isbn_list(isbn_list, isbn_version):
"""
Formats the list for on-wiki publication
"""
text = ""
if len(isbn_list):
isbn_list = sorted(isbn_list)
text += u'== Wrong {}s ==\n'.format(isbn_version)
for t in isbn_list:
text += u'# {{{{Q|{}}}}}: {}\n'.format... |
def compute_indentation(props):
"""
Compute the indentation in inches from the properties of a paragraph style.
"""
res = 0
for k, v in props.items():
if k in ['margin-left', 'text-indent']:
try:
res += float(v.replace('in', ''))
except:
... |
def num_bytes_to_struct_char(n: int):
"""
Given number of bytes, return the struct char that can hold those bytes.
For example,
2 = H
4 = I
"""
if n > 8:
return None
if n > 4:
return "Q"
if n > 2:
return "I"
if n > 1:
return "H"
if n =... |
def spend_utxo(utxo: str) -> dict:
"""
Get spend UTXO action.
:param utxo: Bytom utxo id.
:type utxo: str
:returns: dict -- Bytom spend utxo action.
>>> from pybytom.transaction.actions import spend_utxo
>>> spend_utxo("169a45be47583f7240115c9059cd0d03e4d4fab70a41536cf298d6f261c0a1ac")
... |
def fact(number):
"""
Calculating the factorial of a number
"""
result = 1
for number in range(1, number + 1):
result *= number
return result |
def unique_list(non_unique_list):
"""
Return list with unique subset of provided list, maintaining list order.
Source: https://stackoverflow.com/a/480227/1069467
"""
seen = set()
return [x for x in non_unique_list if not (x in seen or seen.add(x))] |
def sort_tuple_lists_by_timestamp(norm_lists):
"""
"""
get_timestamp = lambda pair: pair[0]
for k, norm_list in norm_lists.items():
norm_lists[k] = sorted(norm_list, key=get_timestamp)
return norm_lists |
def search_for_pod_info(details, operator_id):
"""
Get operator pod info, such as: name, status and message error (if failed).
Parameters
----------
details : dict
Workflow manifest from pipeline runtime.
operator_id : str
Returns
-------
dict
Pod informations.
... |
def cut_prefix(s, prefix):
"""Cuts prefix from given string if it's present."""
return s[len(prefix):] if s.startswith(prefix) else s |
def aggregate_initial_architecture(hparams):
"""Helper function to aggregate initial architecture into an array hparam."""
output = hparams.copy()
initial_architecture_size = len(
[hp for hp in hparams.keys() if hp.startswith("initial_architecture")])
output["initial_architecture"] = [
hparams["init... |
def prob_zipf_distrib(q, t, m, alpha):
"""
Probability that a block pattern of q + t blocks contains another block
pattern of q blocks, assuming that all blocks are i.i.d. according to a
zipf distribution with decay parameter alpha. Parameter m represents the
total number of blocks.
"""
#pro... |
def c_string_literal(env, string):
"""
Escapes string and adds quotes.
"""
# Warning: Order Matters! Replace '\\' first!
e = [("\\", "\\\\"), ("\'", "\\\'"), ("\"", "\\\""), ("\t", "\\t"), ("\n", "\\n"), ("\f", ""), ("\r", "")]
for r in e:
string = string.replace(r[0], r[1])
return "\"" + string + "\"" |
def _split_list_by_function(l, func):
"""For each item in l, if func(l) is truthy, func(l) will be added to l1.
Otherwise, l will be added to l2.
"""
l1 = []
l2 = []
for item in l:
res = func(item)
if res:
l1.append(res)
else:
l2.append(item)
r... |
def format_sec(sec):
"""
format a time
Parameters
----------
sec : float
time in seconds
Returns
-------
string :
formatted time in days, hours, minutes and seconds
"""
m, s = divmod(sec, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
if d:
... |
def convert_str_facet_to_list(facet):
"""
"""
#| - convert_str_facet_to_list
if type(facet) == str:
assert len(facet) == 3, "Facet string must be only 3 in lenght, otherwise I'm not sure how to process"
# [facet[0], facet[1], facet[2], ]
facet_list = []
for str_i in fa... |
def sn2numZ3(scenario: list) -> str:
"""
Convert scenario number to str (zero padding of 3)
Parameters
----------
scenario: list
use only index 0
0: number, 1: items (order and recipe), 2:judge
Returns
----------
str
str of scenario number (ze... |
def heaviside(x, bias=0):
"""
Heaviside function Theta(x - bias)
returns 1 if x >= bias else 0
:param x:
:param bias:
:return:
"""
indicator = 1 if x >= bias else 0
return indicator |
def make_matrix(num_rows, num_cols, entry_fn):
"""returns a num_rows x num_cols matrix
whose (i,j)th entry is entry_fn(i, j)"""
return [[entry_fn(i, j) # given i, create a list
for j in range(num_cols)] # [entry_fn(i, 0), ...]
for i in range(num_rows)] |
def object_to_dict(xmp):
"""
Extracts all XMP data from a given XMPMeta instance organizing it into a
standard Python dictionary.
"""
dxmp = dict()
if not xmp:
return {}
for item in xmp:
if item[-1]['IS_SCHEMA']:
dxmp[item[0]] = []
else:
dxmp... |
def absolute_value(num: int):
"""
This function returns the absoluate value of the provided number
"""
if num >= 0:
return num
return -num |
def time_recommendation(move_num, seconds_per_move=5, time_limit=15*60,
decay_factor=0.98):
"""
Given current move number and "desired" seconds per move,
return how much time should actually be used. To be used specifically
for CGOS time controls, which are absolute 15 minute time.
Th... |
def _check_user_data_match(cmd_ud, user_data):
"""Check if the command user_data matches the input user_data."""
if cmd_ud is None:
return True
if not user_data and not cmd_ud:
return True
if user_data and not cmd_ud:
return False
if cmd_ud and not user_data:
return F... |
def detuplelize(item):
"""If item is a tuple, return first element, otherwise the item itself.
The tuple syntax is used to implement prejoins, so we have to hide from
the user the fact that more than a single object are being selected at
once.
"""
if type(item) is tuple:
return item[0]
... |
def IsListlike(arg):
"""
This function just tests to check if the object acts like a list
"""
from six import string_types
if isinstance(arg, string_types):
return False
try:
_ = [x for x in arg]
return True
except TypeError: # catch when for loop fails
retu... |
def alignment_zeros(data_len) -> bytearray:
"""Return array of 0s to align to 4."""
alignment = (4 - data_len % 4) % 4
return bytearray(alignment) |
def calculate_score(set_of_tags_1, set_of_tags_2):
"""
:param set_of_tags_1: collection of unique strings
:param set_of_tags_2: same as above
:return: score based on hashcode scoring
"""
one_and_two = len(set_of_tags_1.intersection(set_of_tags_2))
one_not_two = len(set_of_tags_1.difference(s... |
def format_time(hour: int, minute: int) -> str:
"""Turns hours and minutes to a string with the format 'HH:MM'. Assumes 24h clock"""
return f"{str(hour).rjust(2, '0')}:{str(minute).rjust(2, '0')}" |
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
# local variables
zero_shift = []
number_merge = []
result = []
blank = 0
cache = 0
# initializing blank list
for idx in range(len(line)):
number_merge.append(0)
# shift... |
def _touch(high, low, level, open, close):
"""
was the given level touched
:param high:
:param low:
:param level:
:return:
"""
if high > level and low < level:
if open >= close:
return -1
else:
return 1
else:
return 0 |
def skip_add(n):
""" Takes a number x and returns x + x-2 + x-4 + x-6 + ... + 0.
>>> skip_add(5) # 5 + 3 + 1 + 0
9
>>> skip_add(10) # 10 + 8 + 6 + 4 + 2 + 0
30
"""
if n ==0:
return 0
if n ==1:
return 1
else:
return n + skip_add(n-2) |
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.type(
"""
import re
import unicodedata
from six import text_type
value = text_type(value)
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignor... |
def radial_blur(blur_width=1.0, blur_height=1.0, sample_num_x=4, sample_num_y=4, center_area=0.0):
"""
Blur filter.
distance = distance apart each sample is
percentage = amount of blurring to apply
sample_num_x = number of samples to apply on the X axis
sample_num_y = number of samples to apply... |
def is_gif(data: bytes) -> bool:
"""
Check if the given data is a GIF.
Parameters:
data (bytes): The data to check.
Returns:
True if the data is a GIF, False otherwise.
"""
return data[:6] in (b"GIF87a", b"GIF89a") |
def is_number(value):
"""
Determine whether a value is a number or not
>>> is_number(5)
True
>>> is_number("1")
True
"""
try:
int(value)
return True
except ValueError:
return False |
def get_columns(filters):
"""return columns based on filters"""
columns = [
{
"fieldname":"item",
"fieldtype":"Link",
"label":"Item",
"options":"Item",
"width":250
},
{
"fieldname":"open_qty",
"fieldtype":"Float",
"label":"Op... |
def pack_layers(i, hiddens, o):
"""Create the full NN topology from input size, hidden layers, and output."""
layers = []
layers.append(i)
for h in hiddens:
layers.append(h)
layers.append(o)
return layers |
def _get_package_uri_props(package_uri):
"""
Gets the properties of a debian package from its URI.
"""
uri_filename = package_uri.rsplit("/", 1)[1]
uri_basename = uri_filename.rsplit(".", 1)[0]
uri_name, uri_version, uri_arch = uri_basename.split("_")
return uri_filename, uri_name, uri_versi... |
def is_numeric(value):
"""Test if a value is numeric."""
return type(value) in (float, int) |
def complement_base(base):
"""Returns the Watson-Crick complement of a base."""
# Convert to lovercase
base = base.lower()
if base == 'a':
return 'T'
elif base == 't':
return 'A'
elif base == 'g':
return 'C'
else:
return 'G' |
def quadrant_update(quadrant_dict, current_angle):
"""
Args:
quadrant_dict:
current_angle:
Returns:
"""
if current_angle > 360:
raise ValueError('You have left the circle, my fiend.')
quadrant = 1
while not (current_angle >= quadrant_dict[quadrant][0] and
... |
def _bytes_from_hexstring(hexstr: str) -> bytes:
"""Convert a hex string to a bytes array"""
return bytes(bytearray.fromhex(hexstr)) |
def decay_across_unit_interval(v, p, d):
""" Generalized decay function over unit interval.
Returns: initial value rescaled based on decay factor
Parameters:
v: Starting value
p: Percent completed must be in a unit interval [0,1]
... |
def get_unique_pairs(es):
""" Query to directly get matching pairs of PS nodes.
Args:
es (Elasticsearch object): Current elasticsearch connection object.
Returns:
dict: An double aggregation of sources and corresponding destinations.
"""
query = {
"query": ... |
def ValidateParameter_PRODRES(query_para):#{{{
"""Validate the input parameters for PRODRES
query_para is a dictionary
"""
is_valid = True
if not 'errinfo' in query_para:
query_para['errinfo'] = ""
if query_para['pfamscan_evalue'] != "" and query_para['pfamscan_bitscore'] != "":
... |
def to_bytes(url):
"""to_bytes(u"URL") --> 'URL'."""
# Most URL schemes require ASCII. If that changes, the conversion
# can be relaxed.
# XXX get rid of to_bytes()
if isinstance(url, str):
try:
url = url.encode("ASCII").decode()
except UnicodeError:
raise Uni... |
def jobs_as_dict(raw_jobs):
"""Construct a dictionary with job name as key and job status as value."""
return dict((job["name"], job["color"]) for job in raw_jobs if "color" in job) |
def get_page_key(page_url):
"""
Get the page key.
Used to prepend a unique key to internal anchorlinks,
so when we combine all pages into one, we don't get conflicting (duplicate) URLs
Works the same when use_directory_urls is set to true or false in docums.yml
Examples
get_page_key('... |
def test_response(resp):
""" some abstract collections raise ValueErrors. Ignore these """
try:
return float(resp) # will evaluate as false if float == 0.0
except ValueError:
return False |
def get_ep_size_tuple(packages):
"""return a list of (ep, size) of the packages"""
return list(set([ (ep, packages[0]["size"]) for ep, packages in packages.items()])) |
def increasing(digits):
""" True if the digits are increasing. """
for i in range(5):
if int(digits[i]) > int(digits[i+1]):
return False
return True |
def convtransp_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1):
"""
SOURCE: https://discuss.pytorch.org/t/utility-function-for-calculating-the-shape-of-a-conv-output/11173/6
Utility function for computing output size of convTransposes given the input size and the convT layer parameters.
A... |
def filter_keys(dct, keys) -> dict:
"""Return filtered dict by given keys"""
return {key: value for key, value in dct.items() if key in keys} |
def check_column(col, sep=":"):
"""Convert input column string to list of columns
:param col: input string
:param sep: default ":"
:return: list of columns
"""
if isinstance(col, str):
col = col.split(sep)
elif not isinstance(col, list):
raise TypeError(f'Columns "{col}" nee... |
def re(rm,rf,beta):
"""Returns cost of equity using CAPM formula."""
return rf + beta*(rm-rf) |
def liquidDensity(T, lDP):
"""
liquidDensity(T, lDP)
liquidDensity (kg/m^3) = A*B^-(1-T/critT)^n*1000.0
Parameters
T, temperature in Kelvin
lDP, A=lDP[0], B=lDP[1], n=lDP[2], critT=lDP[3]
A, B, and n are regression coefficients, critT: critical temperature
Returns
... |
def get_query_string(query_map):
"""Return the query string given a map of key-value pairs."""
if query_map:
query = []
for (name, values) in query_map.items():
for value in values:
query.append(name + "=" + value)
return "&".join(query)
return None |
def _string_label_to_class_id_postprocessor(
string_label, label_classes, default=-1, **unused_kwargs):
"""Returns index of string_label in label_classes or default if not found."""
if string_label in label_classes:
return label_classes.index(string_label)
else:
return default |
def ListTrueOnly(adict):
"""Return a list of strings for which their values were True in the dict.
Args:
adict: The original dictionary, with string keys and boolean values.
Returns:
A list of strings for which the boolean values were True in the dictionary.
"""
return [x for x in adict if adict[x]] |
def whether_prefix(coords):
"""Determine whether gene IDs should be prefixed with nucleotide IDs.
Parameters
----------
coords : dict
Gene coordinates table.
Returns
-------
bool
Whether gene IDs should be prefixed.
See Also
--------
read_gene_coords
Notes... |
def list_objects(s3_resource, bucket, prefix, suffix=None):
"""
Get list of keys in an S3 bucket, filtering by prefix and suffix. Function
developed by Kaixi Zhang as part of AWS_S3 class and adapted slightly here.
This function retrieves all matching objects, and is not subject to the 1000
item lim... |
def get_key(udict, key, missing_value=""):
"""Return a key:value pair as dict
"""
cdict = dict(udict)
return {key: cdict.pop(key, missing_value)} |
def page_number2image_name(number, string="image", padding_size=4):
"""
Utility function to format a number with a padding of size n.
:param number: the number to format (int)
:param string: the prefix to prepend (str)
:param padding_size: the desired lenght of the resulting string (int)
:retur... |
def safefloat(value):
"""safely converts value to float or none"""
try:
return float(value)
except ValueError:
return None |
def truncate(text, width=50):
"""
Truncates text to the provided width. Adds a '..' at the end if truncated.
:param text:
:param width:
:return: truncated text if necessary else the same text
"""
return (text[:width] + '..') if len(text) > width else text |
def get_human_readable_size(sizeinbytes):
"""generate human-readable size representation like du command"""
sizeinbytes = abs(sizeinbytes)
output_fmt = '{0}'
for unit in ['bytes', 'K', 'M', 'G', 'T', 'P']:
if sizeinbytes < 1024.0:
return output_fmt.format(sizeinbytes, unit)
o... |
def get_region(reg_str):
"""Transform a string of the form X-Y into a region"""
spl = reg_str.split('-')
if spl[0] == '' and spl[1] == '':
# Fully open region
reg = [0, float('inf')]
elif spl[0] == '':
# Open beginning
reg = [0, int(spl[1])]
elif spl[1] == '':
... |
def masked_by_quotechar(S, quotechar, escapechar, test_char):
"""Test if a character is always masked by quote characters
>>> masked_by_quotechar('A"B&C"A', '"', '', '&')
True
>>> masked_by_quotechar('A"B&C"A&A', '"', '', '&')
False
>>> masked_by_quotechar('A|"B&C"A', '"', '|', '&')
False
... |
def board_rows(board, rows, cols):
""" Returns a list of row of the given board.
"""
return [''.join(board[row * cols:(row + 1) * cols]) for row in range(rows)] |
def is_rev_dir(dir_i):
"""
"""
#| - is_rev_dir
# print("dir_i:", dir_i)
out_dict = dict()
assert dir_i is not None, "dir_i is None"
is_rev_dir_i = False
rev_num = None
if dir_i[0] == "_":
dir_split = dir_i.split("_")
if len(dir_split) == 2:
if dir_spli... |
def getSQM(header={}):
"""
:param header:
:return:
"""
sqm = max(float(header.get('SQM', 0)),
float(header.get('SKY-QLTY', 0)),
float(header.get('MPSAS', 0)),
)
return sqm |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.