content stringlengths 42 6.51k |
|---|
def trim_garbage(text: str) -> int:
"""
Strip all characters from the end of string until ']' is reached.
:param text: Text string.
:return: Return position of a character following ']' or zero in case of a null string.
"""
l = len(text)-1
while l:
if text[l] == "]":
... |
def lmp_Kc(link_key):
"""
Derive Kc from link key
"""
Kc = b''
return Kc |
def expandElementRightOnly(_element, _preserve=True): #
"""
_element = (string) to expand
THis one only expands the element one base pair 3'
returns
(list) of expanded elements
"""
dir = {0 : "a",
1 : "c",
2 : "g",
3 : "t"}
if _preserve:
lib = ... |
def convert_string_to_none_or_int(string):
"""Converts string to None or int.
Args:
string: str, string to convert.
Returns:
None or int conversion of string.
"""
return None if string.lower() == "none" else int(string) |
def ParseDupHit(text):#{{{
"""
Parse a duplication hit
e.g.
1-575(nTM=2) 2-571(nTM=2)
"""
li = []
strs = text.split()
for ss in strs:
strs1 = ss.rstrip(')').split('(nTM=') # ['35-345', '7']
li1 = [int(x) for x in strs1[0].split('-')]
li1.append(int(strs1[1])) #... |
def parse_int_ranges_from_number_string(input_string):
"""Parses integers from number string
:param input_string
"""
# Assign helper variable
parsed_input = []
# Construct a list of integers from given number string,range
for cell in input_string.split(','):
if '-' in cell:
... |
def _merge_extra_options(needs_info, needs_kwargs, needs_extra_options):
"""Add any extra options introduced via options_ext to needs_info"""
extra_keys = set(needs_kwargs.keys()).difference(set(needs_info.keys()))
for key in needs_extra_options:
if key in extra_keys:
needs_info[key] = ... |
def list_get(list_obj, index, default=None):
"""Like ``.get`` for list object.
Args:
list_obj (list): list to look up an index in
index (int): index position to look up
default (Optional[object]): default return value. Defaults to None.
Returns:
object: any object found at ... |
def test(expected, actual, epsilon=0):
""" Takes expected and actual values. If they are different by
more than epsilon, then print a fail string. Otherwise, print a pass string.
>>> test(2, 2)
PASS: Got 2
>>> test(2, 2.001, epsilon=.01)
PASS: Got 2.001
>>> test(2, 3)
FAIL: Expected 2... |
def ensure_boolean(val):
"""Coerce a string value to a boolean value"""
if not isinstance(val, str):
return val
return val and val.lower() not in ("false", "no", "0") |
def commas(num):
"""
Format positive integer-like `num`
for display with commas between digit groupings: "xxx,yyy,zzz".
"""
digits = str(num)
assert(digits.isdigit())
result = ''
while digits:
digits, last3 = digits[:-3], digits[-3:]
result = (last3 + ',' + result) if res... |
def findNumber(arr, k):
"""
Check if number is in a list.
:param arr: list to verify
:param k: element to look for
:return: YES, if k is in arr. NO, otherwise.
"""
return 'YES' if k in arr else 'NO' |
def build_us_details(details):
"""Build test data for a member of Congress."""
return {
'name': {
'last': details[0],
'first': details[1],
'full name': f'{details[0]} {details[1]}',
},
'terms': [
{
'party': details[2],
... |
def parse_boolean(s):
"""Takes a string and returns the equivalent as a boolean value."""
s = s.strip().lower()
if s in ('yes', 'true', 'on', '1'):
return True
elif s in ('no', 'false', 'off', '0', 'none'):
return False
else:
raise ValueError('Invalid boolean value %r' % s) |
def shift_box_right(box, width_step):
"""Shift box for image cropping one width_step to the right."""
box_list = list(box)
box_list[0] += width_step
box_list[2] += width_step
return tuple(box_list) |
def is_belong_train_set(fname):
"""
Args:
fname: string, file name without dir path
Returns:
boolean
"""
topic_num_in_test_set = ['3', '45']
if fname.split('_')[0] in topic_num_in_test_set:
return False
else:
return True |
def _split_uri(uri):
"""
Get slash-delimited parts of a ConceptNet URI.
Args:
uri (str)
Returns:
List[str]
"""
uri = uri.lstrip("/")
if not uri:
return []
return uri.split("/") |
def sort_by_similarity(word_pairs):
"""
Given a list of word pair instances, returns a list of the instances sorted
in decreasing order of similarity.
"""
return sorted(word_pairs, key=lambda pair: pair.similarity, reverse=True) |
def read_file(file_str):
""" Return file lines for a file """
file_obj = open(file_str, "r")
file_lines = file_obj.readlines()
return file_lines |
def button_to_string(button, idx=0):
"""Create a string representation of a button."""
return "{idx}: {title} ({val})".format(
idx=idx + 1, title=button['title'], val=button['payload']) |
def find_in_list(list_one, list_two):
"""
Function to find an element from list_one that is in list_two
and returns it. Returns None if nothing is found.
Function taken from A3
Inputs:
list, list
Outputs:
string or None
"""
for element in list_one:
if ele... |
def is_xml_article_set(filename: str) -> bool:
"""
Check if input file is pubmed xml compressed archive from name.
Arguments:
filename {str} -- the name of the file
Returns:
bool -- true if file is compressed pubmed article set
"""
if filename.endswith('.xml.gz'):
retur... |
def subtract(value, arg):
"""
Similar to |add:"-5" but what if 5 is a variable?
{% with limit = 5 %}
+ {{mymodel.objects.count|subtract:limit}} items
{% endwith %}
"""
return int(value) - int(arg) |
def sdfSetMolBlock(mol, molblock):
"""
sdfSetMolBlock() sets the MOL block of molecule mol to molblock
"""
mol["molblock"] = molblock
return mol |
def isTuple( obj ):
"""
Returns a boolean whether or not 'obj' is of type 'tuple'.
"""
return isinstance( obj, tuple ) |
def msg_to_str(msg, ignore_fields=''):
"""
Convert ParlAI message dict to string.
:param msg:
dict to convert into a string.
:param ignore_fields:
(default '') comma-separated field names to not include in the string
even if they're in the msg dict.
"""
def filter(txt):... |
def is_string_nonwhite(val):
"""Return (bool) whether val contains anything besides whitespace.
"""
return bool(val.strip()) |
def tags2set(tags):
"""Parse a ``tags`` argument into a set - leave if already one.
"""
if isinstance(tags, set):
return tags
elif tags is None:
return set()
elif isinstance(tags, str):
return {tags}
else:
return set(tags) |
def makeiter(obj):
"""
Makes everything iterable.
Args:
obj (any): Object to turn iterable.
Returns:
iterable (iterable): An iterable object.
"""
return obj if hasattr(obj, '__iter__') else [obj] |
def indexate(points):
"""
Create an array of unique points and indexes into this array.
Arguments:
points: A sequence of 3-tuples
Returns:
An array of indices and a sequence of unique 3-tuples.
"""
pd = {}
indices = tuple(pd.setdefault(tuple(p), len(pd)) for p in points)
... |
def _build_endpoint_url(hostname, port=None, is_secure=True):
"""Normalize the formats from boto2 and boto3. """
# If the scheme is not in the hostname, check if is_secure is set to set http or https as the scheme
if not hostname.startswith("http://") and not hostname.startswith("https://"):
hostna... |
def utility_Binary(grade): # pylint: disable=invalid-name
"""
Binary utility function, that converts any grades into binary utility.
Args:
grade (float): grade value.
Returns:
float: utility score for the grade
"""
return 1 if grade > 0 else 0 |
def is_unique(digit, cell, grid):
"""
Checks if a given digit is unique across its row, column and subgrid.
Arguments:
digit {number} -- The digit to check for
cell {tuple} -- The (x, y) coordinates of the digit on the grid
grid {number matrix} -- The matrix to check the digit a... |
def flatten(given_list):
"""
Utility function to flatten list of list to a single list
Args:
given_list: list of list
Returns:
flatted list
"""
return [item for sublist in given_list for item in sublist] |
def latexify(string_item):
"""Recursive function to turn a string, or sympy.latex to a
latex equation.
Args:
string_item (str): string we want to make into an equation
Returns:
equation_item (str): a latex-able equation.
"""
if isinstance(string_item, list):
return "\n"... |
def check_intensifiers(text, INTENSIFIER_MAP):
"""
Utility function to check intensifiers of an emotion
:param text: text chunk with the emotion term
:return: boolean value and booster value for intensifiers
"""
# BOOSTER_MAP = {"B_INCR": 2,
# "B_DECR": 0.5}
intensity_word... |
def matrix_compose_4x4(rotation, translation):
"""
Compose a 4x4 matrix using rotations and translation.
:param rotation: 3x3 matrix (list of list)
:param translation: list
:return:
"""
r = range(4)
m = [[0 for _ in r] for _ in r]
three = range(3)
for i in three:
for j in... |
def map_option(v, f):
"""
Applies the function f to the value if it is not None
:param v: A value that maybe None
:param f: A function that takes a single argument to apply to v
:return: The result of applying f to v; None if v is None
"""
if v:
return f(v)
else:
return N... |
def sortArrayByParityII(A):
"""
:type A: List[int]
:rtype: List[int]
"""
B=[0]*len(A)
even = 0
odd = 1
for i in A:
if i % 2 == 0:
B[even] = i
even += 2
else:
B[odd] = i
odd += 2
return B |
def base(p, comp):
"""
Create a base for p variables, comp being the array of the complementary variables
"""
ret = []
for l in range(p):
ret.append((len(comp) + 1) * [0.0])
for i in range(len(comp)):
ret[comp[i]][i+1] = 1.0
return ret |
def in_punctuation(category):
"""Category for code points that are punctuation characters.
Args:
category (str): Unicode general category.
Returns:
bool: True if `category` in set.
"""
return category in {'Pc', 'Pd', 'Ps', 'Pe', 'Pi', 'Pf', 'Po'} |
def parse_int(value):
""" Convert string to int
:param value: string value
:return: int value if the parameter can be converted to str, otherwise None
"""
try:
return int(value)
except (ValueError, TypeError):
return None |
def final_temp(t_i, p_f, p_i, gamma):
"""
Computes the final temperature of adiabatic expansion
:param t_i: initial temperature (K)
:param p_f: total final pressure
:param p_i: total initial pressure
:param gamma: heat capacity ratio ("adiabaattivakio")
:return: final temperature (K)
"""... |
def nested_getattr(obj, attr):
"""getattr implementation supporting nested attributes."""
attributes = attr.split('.')
for i in attributes:
if obj is None:
break
try:
obj = getattr(obj, i)
except AttributeError:
raise
return obj |
def intersection(surface, rect):
""" Remove zone of out of bound from ROI
Params:
surface: image bounds is rect representation (top left coordinates and width and height)
rect: region of interest is also has rect representation
Return:
Modified ROI with correct bounds
"""
l_x = max(sur... |
def convert2relative(bbox,darknet_height,darknet_width):
"""
YOLO format use relative coordinates for annotation
"""
x, y, w, h = bbox
_height = darknet_height
_width = darknet_width
return x/_width, y/_height, w/_width, h/_height |
def get_bin_list(n, nmax):
"""
return a list of digits of the binary representation of n
nmax is the maximum theoretical value of n, used to add 0 at the front of the list if necessary
"""
if n == 0:
return [0 for _ in range(len(bin(nmax))-3)]
n = bin(n)
digits = []
for i in rang... |
def seq(start, stop, step=1):
"""Equivalent to matlab [start:step:stop]"""
n = int(round((stop - start) / float(step)))
if n > 1:
return([start + step * i for i in range(n + 1)])
else:
return([]) |
def lower(s):
"""lower(s) -> string
Return a copy of the string s converted to lowercase.
"""
return s.lower() |
def GetItemByPartialName(list, name):
""" Returns the first item in the list
that has the provided name"""
for item in list :
if name.upper() in item.Name.upper():
return item |
def parse_history(raw_history):
""" Parse smoldyn output from `molcount` command.
Returns
-------
{Species: timeseries}
"""
keys = raw_history[0].split()
history = {key: [] for key in keys}
for line in raw_history[1:]:
for k, v in zip(keys, line.split()):
history[k]... |
def Teq(L, a, albedo=0., emissivity=1., beta=1.):
""" compute the instantaneous equilibrium temperature of a planet at orbital
distance r.
See equation 3 in Kaltenegger+2011.
Parameters
----------
L : float
stellar luminosity [L_sol]
a : float
semi-major axis [au]
a... |
def filter_ag(ag):
"""
Removes unnecessary fields from a user dict to allow for clean logs.
Params:
- ag (dict) : a dictionary of the custom fields of a user on AN.
Returns:
- (dict) : the same dict, but only with the: 'rep_name',
'Municipality', 'AG_name... |
def sec_to_samples(n_sec, sr):
"""Return number of samples required to cover duration in seconds."""
return int(n_sec*sr) |
def choose_robots(exclude_bimanual=False):
"""
Prints out robot options, and returns the requested robot. Restricts options to single-armed robots if
@exclude_bimanual is set to True (False by default)
Args:
exclude_bimanual (bool): If set, excludes bimanual robots from the robot options
R... |
def accuracy_metric(actual, predicted):
"""
Calculate accuracy percentage
"""
correct = 0
for i in range(len(actual)):
if actual[i] == predicted[i]:
correct += 1
return correct / float(len(actual)) * 100.0 |
def n_bonacci(N, n):
"""
Computes the n-bonacci number for the given input
Parameters
----------
N : int
the sequence number
n : int
the number to compute the series from
Returns
-------
int
the n-bonacci number for the given input
"""
if n <= 1:
... |
def fake_site_name(name, default=None):
"""
Method for getting site name for a fake site.
"""
if name == 'SITE_NAME':
return 'openedx.localhost'
else:
return default |
def ip_num_to_string(ip):
"""Convert 32-bit integer to dotted IPv4 address."""
return ".".join(map(lambda n: str(ip >> n & 0xFF), [24, 16, 8, 0])) |
def cluster_profile_platform(cluster_profile):
"""Translate from steps.cluster_profile to workflow.as slugs."""
if cluster_profile == 'azure4':
return 'azure'
if cluster_profile == 'packet':
return 'metal'
return cluster_profile |
def find_array_start_position(big_array, small_array):
"""
Find the starting index of a sub_array inside of a larger array
Returns -1 if the small_array is not contrained within the larger array
Arguments:
big_array (arr) : the larger array to search through
small... |
def square_matrix(square):
"""
This function will calculate the value x
(i.e blurred pixel value) for each 3*3 blur image.
"""
tot_sum = 0
# Calculate sum of all teh pixels in a 3*3 matrix
for i in range(3):
for j in range(3):
tot_sum += square[i][j]
return tot_sum/... |
def generate_net_file_name(file_prefix, net_number):
""" Generate file name and suffix for net-file (.pth). """
return f"{file_prefix}-net{net_number}.pth" |
def find_max_item_support(pattern, supports):
"""
Returns support of item with maximum support among items in pattern.
pattern: List. list of items in pattern.
supports: Dict. item -> count dict
"""
max_support = -1
for item in pattern:
max_support = max(max_support, supports[item... |
def pytest_make_parametrize_id(config, val, argname):
"""
Prettify output for parametrized tests
"""
if isinstance(val, dict):
return '{}({})'.format(
argname, ', '.join('{}={}'.format(k, v) for k, v in val.items())
) |
def derive_aggregation(dim_cols, agg_col, agg):
"""Produces consistent aggregation spec from optional column specification.
This utility provides some consistency to the flexible inputs that can be provided
to charts, such as not specifying dimensions to aggregate on, not specifying an
aggregation, and... |
def divide_exactly(input_x, input_y):
"""
divide_exactly
:param input_x:
:param input_y:
:return:
"""
if input_x % input_y != 0:
raise ValueError("Not divisible")
return input_x // input_y |
def any_isinstance(items, cls):
"""`True` if any item is of type `cls`."""
return any(isinstance(item, cls) for item in items) |
def get_bigrams(text_split):
"""
Returns a list of bigrams
"""
bigrams = [[text_split[i], text_split[i+1]]
for i in range(len(text_split)-1)]
return bigrams |
def _n(value):
"""
Convert between an empty string and a None
This function is translates django's empty elements, which are stored
as empty strings into pyxb empty elements, which are stored as None.
"""
return None if value == '' else value |
def peak_index_in_mountain_array(a):
"""
Find peak index of mountain in given array
:param a: list of numbers
:type a: list[int]
:return: peak index of
:rtype: int
"""
# basic case
if len(a) < 3:
return 0
# find peak index
left, right = 1, len(a) - 1
while left ... |
def valid_gameweek(gameweek):
"""Returns True if the gameweek is valid.
:param gameweek: The gameweek.
:type gameweek: int or string
:raises ValueError: if gameweek is not a number between 1 and 38
"""
gameweek = int(gameweek)
if (gameweek < 1) or (gameweek > 38):
raise ValueError("... |
def _limited_string(value: str, max_size: int = 40):
"""
Provide limited string size, typically for reporting original value
in case of error (and for better identification of error location
based on presenting part of original value)
"""
return (
value
if (value is None) or (len... |
def standard_deviation(numbers):
"""Return standard deviation."""
numbers = list(numbers)
if not numbers:
return 0
mean = sum(numbers) / len(numbers)
return (sum((n - mean) ** 2 for n in numbers) /
len(numbers)) ** .5 |
def _GetSuspectedCLsWithOnlyCLInfo(suspected_cls):
"""Removes failures and top_score from suspected_cls.
Makes sure suspected_cls from heuristic or try_job have the same format.
"""
simplified_suspected_cls = []
for cl in suspected_cls:
simplified_cl = {
'repo_name': cl['repo_name'],
'rev... |
def deconvertVariableName(variable):
"""Convert ``mixedCase`` to ``SERPENT_CASE``"""
out = ""
for char in variable:
if char.isupper():
out += '_' + char
continue
out += char.upper()
return out |
def CTL_CODE(DeviceType, Function, Method, Access):
"""Calculate a DeviceIoControl code just like in the driver's C code"""
return (((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method)) |
def search_products(database, query, new_database=None):
"""
Description
----
Search in the provided dictionary for a specific query. It
specifically searches in the 'summary' key which can be found in
equities, etfs and funds.
Input
----
database (dictionary)
A dictionary t... |
def message(s) -> str:
"""Function to convert OPTIONS description to present tense"""
if s == 'Exit program': return 'Shutting down'
return s.replace('Prepare', 'Preparing').replace('Process', 'Processing') |
def interval_to_milliseconds(interval):
"""Convert a Binance interval string to milliseconds
:param interval: Binance interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w
:type interval: str
:return:
None if unit not one of m, h, d or w
None if string not in ... |
def is_group(keyword):
"""Check if group keyword
Args:
Profiles keyword
Returns:
True if group keyword
"""
return bool(keyword[0] == 'G') |
def append_query_parameter(query_parameters):
"""
Unnecessary due to requests library. This showcases a basic method for adding on the query
parameters in general.
Takes in a dictionary of query parameters and outputs a query string
:param query_parameters: dictionary of query parameters
:retur... |
def gpio_alias(name):
"""
GPIO alias definition.
"""
return ("alias", name) |
def _mangle_token(token):
"""Slaughter a token for public exposure"""
_tl = len(token)//2
return "{}{}".format('*' * (_tl), token[_tl+1:]) |
def HLCharConst(s):
""" Returns the numeric equivalent of a 4-character string (OSType in classic Mac OS).
Used for file types, creator codes, and magic numbers. """
if len(s) != 4:
return 0
return 0 + (ord(s[0]) << 24) + (ord(s[1]) << 16) + (ord(s[2]) << 8) + ord(s[3]) |
def values(dictionary: dict) -> tuple:
"""Return a tuple of values in a dictionary."""
return tuple(dictionary.values()) |
def stringify(li,delimiter):
""" Converts list entries to strings and joins with delimiter."""
string_list = map(str,li)
return delimiter.join(string_list) |
def add_lower(line):
"""Returns if the upper case string is different from the lower case line
Param:
line (unicode)
Returns:
False if they are the same
Lowered string if they are not
"""
line_lower = line.lower()
if line != line_lower:
return line_lower
else... |
def checkProjectDirOption(projectDirOption):
"""
function to set the default value for projectDirOption
Args:
projectDirOption: relative path to the location of the project
directory, or None
Returns: relative path to the location of the project directory
... |
def valid_field(name: str) -> bool:
"""Is it a valid field name for a structured dtype?"""
return (name.isascii() and
all(ord(letter) > 31 and ord(letter) != 127 for letter in name)) |
def line(display=False):
"""To make easy separations while printing in console"""
if display == True:
return print("____________________________________________________________\n") |
def filter_rows(input_str):
"""
Filter matching rows, i.e. strings containing <row> XML elements.
:param input_str: row possibly containing a <row> XML element (could also contain their root element, e.g. <post>)
:return: boolean indicating whether XML element is a <row>
"""
return input_str.lst... |
def percentage(value, precision=2):
"""Convert `float` to #.##% notation as `str`.
A value of 1 = `"100.00%"`; 0.5 = `"50.00%"`"""
return f"{value:.{precision}%}" |
def validate_file_and_rtn_filter_list(filename):
""" Function to validate file exists and generate a list of keywords"""
if filename is None:
return []
with open(filename, "r") as file:
kw_list = file.read()
kw_list = kw_list.strip().split()
if kw_list:
return kw_... |
def intersection_box(box_a, box_b):
"""
Calculates the intersection box from two bounding boxes with the format ((x_min, x_max), (y_min, y_max)).
Source code mainly taken from:
https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/
`box_a`: the first box
`box_... |
def rotate(string, n):
"""Rotate characters in a string.
Expects string and n (int) for number of characters to move.
"""
length = len(string)
if n == length:
return string
elif n > 0:
return string[-(length-n):] + string[:n]
else:
return string[n:] + string[:... |
def parse_service_id(service_id):
"""
**Parse the the serviceID string**
Parses only the serviceID portion of the service ID string
:param service_id: Full device type string
:return: Parsed service ID
:rtype: str
"""
return service_id.split(':')[3:][0] |
def return_rate(start, end, periods):
"""
"""
return (end / start) ** (1 / periods) - 1 |
def _all_dicts(T):
""" Return a list of all __dict__ for a type, or object.
Args:
T: the type, or object, to determine the __dicts__ for.
Returns:
The list of __dict__ references, including those in base classes.
"""
if not isinstance(T, type):
T = type(T)
dicts = []
... |
def transformation_expand_english_contractions(text):
"""
:param text: the text to run the transformation on
:type text: str
:return: the transformed text
:type return: str
"""
# This list certainly is not complete. However, it covers some of the most common cases.
contractions = [
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.