content stringlengths 42 6.51k |
|---|
def num_ids_from_args(arg_ranges):
"""Return the number of argument combinations (and thus the number of corresponding ids)"""
from functools import reduce
import operator
return reduce(operator.mul, [len(r) for r in arg_ranges], 1) |
def _validate_name(name):
"""Pre-flight ``Bucket`` name validation.
:type name: str or :data:`NoneType`
:param name: Proposed bucket name.
:rtype: str or :data:`NoneType`
:returns: ``name`` if valid.
"""
if name is None:
return
# The first and last characters must be alphanume... |
def get_full_item_name(iteminfo: dict, csgo_english: dict) -> str:
"""
Function which adds data to the skin info retrieved from GC
:param iteminfo: item info dict.
:type csgo_english: csgo_english vdf parsed
:rtype: str
"""
name = ''
# Default items have the "unique" quality
if item... |
def levenshtein(a,b):
"""Calculates the Levenshtein distance between *strings* a and b.
from http://hetland.org/coding/python/levenshtein.py
"""
n, m = len(a), len(b)
if n > m:
# Make sure n <= m, to use O(min(n,m)) space
a,b = b,a
n,m = m,n
current = range(n+1... |
def get_corner_coord(vhpos):
"""Convert textbox corner coordinate from str to float"""
if (vhpos is None) or (vhpos == 'right') or (vhpos == 'top'):
return 0.9
else:
return 0.1 |
def str_to_bool(s):
"""
Translates string representing boolean value into boolean value
"""
if s == 'True':
return True
elif s == 'False':
return False
else:
raise ValueError |
def Fastaline(x, **kwargs):
"""Convert a sequence to FASTA format(60 per line)"""
res = ''
while len(x) != 0:
res += ''.join(x[:60]) + '\n'
x = x[60:]
return res |
def _normalize_integer_rgb(value: int) -> int:
"""
Internal normalization function for clipping integer values into
the permitted range (0-255, inclusive).
"""
return 0 if value < 0 else 255 if value > 255 else value |
def event_log_formatter(events):
"""Return the events in log format."""
event_log = []
log_format = ("%(event_time)s "
"[%(rsrc_name)s]: %(rsrc_status)s %(rsrc_status_reason)s")
for event in events:
event_time = getattr(event, 'event_time', '')
log = log_format % {
... |
def mergeLists(lst1, lst2):
"""asssumes lst1 and lst2 are lists
returns a list of tuples of the elementsts of lst1 and lst2"""
return list(zip(lst1, lst2)) |
def joblib_log_level(level: str) -> int:
"""
Convert python log level to joblib int verbosity.
"""
if level == 'INFO':
return 0
else:
return 60 |
def snake_to_darwin_case(text: str) -> str:
"""Convert snake_case to Darwin_Case."""
return "_".join(map(str.capitalize, text.split("_"))) |
def get_output_filename(dest_dir, class_name):
"""Creates the output filename.
Args:
dataset_dir: The dataset directory where the dataset is stored.
split_name: The name of the train/test split.
Returns:
An absolute file path.
"""
return '%s/ON3D_%s.tfrecord' % (dest_dir, class_nam... |
def hits_boat(
direction,
position,
boat_size,
board_matrix,
):
"""
:param direction:
:param position:
:param boat_size:
:param board_matrix:
:return:
"""
if direction == 'UP':
first_square = position['y']
for currentY in range(first_square + 1 - boa... |
def round_down(rounded, divider):
"""Round down an integer to a multiple of divider."""
return int(rounded) // divider * divider |
def make_netloc(data):
"""Make the `netloc` portion of a url from a `dict` of values.
If `netloc` is found in the `dict`, it is returned; otherwise, the `netloc`
is `[{username}[:{password}]@]{hostname}[:{port}]`. If `hostname` is not
found, `host` is used instead.
If neither `netloc`, `hostname`,... |
def create_label_column(row) -> str:
"""
Helper function to generate a new column which will be used
to label the choropleth maps. Function used to label missing data
(otherwise they will show up on the map as "-1 SEK").
Parameters
----------
row :
Returns
-------
str
C... |
def sat(x, xmin, xmax):
"""!
Saturates the input value in the given interval
@param x: value to saturate
@param xmin: minimum value of the interval
@param xmax: maximum value of the interval
@return: saturated value
"""
if x > xmax:
return xmax
if x < xmin:
return xmi... |
def is_directive(headers, data):
"""
checks if a part (of multi-part body) looks like a directive
directives have application/json content-type and key 'directive' in the top-level JSON payload object
:param headers: dict of Part headers (from network, bytes key/values)
:param data: dict part conte... |
def data_by_class(data):
"""
Organize `data` by class.
Parameters
----------
data : list of dicts
Each dict contains the key `symbol_id` which is the class label.
Returns
-------
dbc : dict
mapping class labels to lists of dicts
"""
dbc = {}
for item in data... |
def _consolidate_elemental_array_(elemental_array):
"""
Accounts for non-empirical chemical formulas by taking in the compositional array generated by _create_compositional_array_() and returning a consolidated array of dictionaries with no repeating elements
:param elemental_array: an elemental array gene... |
def get_rnn_hidden_state(h):
"""Returns h_t transparently regardless of RNN type."""
return h if not isinstance(h, tuple) else h[0] |
def attack(suffix_bits, suffix):
"""
Returns a number s for which s^3 ends with the provided suffix.
:param suffix_bits: the amount of bits in the suffix
:param suffix: the suffix
:return: the number s
"""
assert suffix % 2 == 1, "Target suffix must be odd"
s = 1
for i in range(suff... |
def string_in_file(file, str_to_check, repetitions=1):
"""Check if a string is present in a file.
You can also provide the number of times that string is repeated.
:param file: File where the string is searched
:type file: str
:param str_to_check: String to search
:type str_to_check: str
:... |
def has_module(module_name, members=[]):
"""Returns whether or not a given module can be imported."""
try:
mod = __import__(module_name, fromlist=members)
except ImportError:
return False
for member in members:
if not hasattr(mod, member):
return False
return Tr... |
def same_ratio(img_ratio, monitor_ratio, file):
"""
:param img_ratio: Float
:param monitor_ratio: Float
:param file: Str
:return: Bool
"""
percent = img_ratio / monitor_ratio
diff = int(abs(percent - 1) * 100)
if percent > 1:
print("Image is " + str(diff) + "% too wide for sc... |
def _globtest(globpattern, namelist):
""" Filter names in 'namelist', returning those which match 'globpattern'.
"""
import re
pattern = globpattern.replace(".", r"\.") # mask dots
pattern = pattern.replace("*", r".*") # change glob sequence
pattern = pattern.replace("?", r".") ... |
def factorial(n):
""" returns the factorial of n """
if n < 0:
return None
if n == 0:
return 1
if n < 2:
return 1
return n * factorial(n-1) |
def convert_fiscal_quarter_to_fiscal_period(fiscal_quarter):
""" Returns None if fiscal_quarter is invalid or not a number. """
return {1: 3, 2: 6, 3: 9, 4: 12}.get(fiscal_quarter) |
def convert_extension(filename, extensions=('yaml', 'yml',)):
"""
Convert YeT extension in filename to .tex
:param filename: string of file name. validity not checked.
:param extensions: tuple of extensions (without dot) to treat as YeT
"""
# change YAML extension to .tex
if '.' in filename... |
def belong(candidates,checklist):
"""Check whether a list of items appear in a given list of options.
Returns a list of 1 and 0, one for each candidate given."""
return [x in checklist for x in candidates] |
def collect_swift_version(copts):
"""Returns the value of the `-swift-version` argument, if found.
Args:
copts: The list of copts to be scanned.
Returns:
The value of the `-swift-version` argument, or None if it was not found
in the copt list.
"""
# Note that the argument ... |
def validate1(s, a):
"""validate1(s, a): list comprehension with a.index"""
try:
[a.index(x) for x in s]
return True
except:
return False |
def is_simple_passphrase(phrase):
"""
Checks whether a phrase contains no repeated words.
>>> is_simple_passphrase(["aa", "bb", "cc", "dd", "ee"])
True
>>> is_simple_passphrase(["aa", "bb", "cc", "dd", "aa"])
False
>>> is_simple_passphrase(["aa", "bb", "cc", "dd", "aaa"])
True
"""
... |
def R10_yield(FMTab, Apmin, PG):
"""
R10 Determining the surface pressure Pmax
(Sec 5.5.4)
For the maximum surface pressure with yield
or angle controlled tightening techniques.
"""
#
Pmax = 1.40 * (FMTab / Apmin) # (R10/3)
# Alternative safety verification
Sp = P... |
def initial_global_jql(quarter_string, bad_board=False):
"""
Helper function to return the initial global JQL query.
:param String quarter_string: Quarter string to use
:param Bool bad_board: Are we creating the JQL for the bad board
:return: Initial JQL
:rtype: String
"""
if bad_board:... |
def remove_multiple_elements_from_list(a_list, indices_to_be_removed):
"""
remove list elements according to a list of indices to be removed from that list
:param a_list: list
list to be processed
:param indices_to_be_removed: list
list of the elements that are no longer needed
"""
... |
def inverse(sequence):
"""
Calculate the inverse of a DNA sequence.
@param sequence: a DNA sequence expressed as an upper-case string.
@return inverse as an upper-case string.
"""
# Reverse string using approach recommended on StackOverflow
# http://stackoverflow.com/questions/931092/rever... |
def multiply (m1, m2):
"""
Multiply two matrices.
"""
m1r = len (m1)
m1c = len (m1[0])
m2r = len (m2)
m2c = len (m2[0])
rr = m1r
rc = m2c
assert m1c == m2r, "Matrix multiplication not defined. Invalid dimensions."
newRows = []
for i in range (0, rr):
newRow... |
def spin_words(sentence):
"""Spin words greater than five char long in a string.
preserving white spaces
"""
temp = []
spl = sentence.split()
for char in spl:
if len(char) >= 5:
spin = char[::-1]
temp.append(spin)
else:
temp.append(char)
o... |
def subtract(value, arg):
"""subtracts arg from value"""
return int(value) - int(arg) |
def rreplace(s: str, old: str, new: str, occurrence: int) -> str:
"""
Reverse replace.
:param s: Original string.
:param old: The character to be replaced.
:param new: The character that will replace `old`.
:param occurrence: The number of occurrences of `old` that should be replaced with `new`... |
def instruction_list_to_easm(instruction_list: list) -> str:
"""Convert a list of instructions into an easm op code string.
:param instruction_list:
:return:
"""
result = ""
for instruction in instruction_list:
result += "{} {}".format(instruction["address"], instruction["opcode"])
... |
def step(x):
""" A neighbor of x is either 2*x or x+3"""
return [x+3, 2*x] |
def get_fragment(text, startend):
"""Return substring from a text based on start and end substrings delimited by ::."""
startend = startend.split("::")
if startend[0] not in text or startend[1] not in text:
return
start_idx = text.index(startend[0])
end_idx = text.index(startend[1])
... |
def get_integer(bool_var):
"""Returns string value for the bool variable."""
if bool_var:
return "1"
else:
return "0" |
def get_sorted_start_activities_list(start_activities):
"""
Gets sorted start attributes list
Parameters
----------
start_activities
Dictionary of start attributes associated with their count
Returns
----------
listact
Sorted start attributes list
"""
li... |
def applianceLogsDirName(config):
"""
Returns the name of the directory containing the appliance log files.
"""
return config['converter.appliance_logs_dir'] |
def find_used_entities_in_string(query, columns, tables):
"""Heuristically finds schema entities included in a SQL query."""
used_columns = set()
used_tables = set()
nopunct_query = query.replace('.', ' ').replace('(', ' ').replace(')', ' ')
for token in nopunct_query.split(' '):
if token.lower() in col... |
def get_source_url_output(function_name):
""" Generates the Cloud Function output with a link to the source archive.
"""
return {
'name': 'sourceArchiveUrl',
'value': '$(ref.{}.sourceArchiveUrl)'.format(function_name)
} |
def get_schema(dictionary, parameters=False, delimiter="_"):
"""Get a schema of the config of the dictionary"""
global_definition = ""
def get_key_schema(dl, definition=None):
definition = "" if definition is None else definition
if isinstance(dl, dict):
for key in sorted(dl.key... |
def cumulative_gain(rank_list):
"""Calculate the cumulative gain based on the rank list and return a list."""
cumulative_set = []
cumulative_set.append(rank_list[0])
for i in range(1, len(rank_list)):
cg = cumulative_set[i-1] + rank_list[i]
cumulative_set.append(cg)
return cumulative... |
def create_incident_field_context(incident):
"""Parses the 'incident_fields' entry of the incident and returns it
Args:
incident (dict): The incident to parse
Returns:
list. The parsed incident fields list
"""
incident_field_values = dict()
for incident_field in incident.get('i... |
def get_timeout(gross_time, start, end, precision, split_range):
"""
A way to generate varying timeouts based on ranges
:param gross_time: Some integer between start and end
:param start: the start value of the range
:param end: the end value of the range
:param precision: the precision to use t... |
def _convert_to_float(frac_str):
"""Converts a string into a float"""
try:
return float(frac_str)
except ValueError:
num, denom = frac_str.split('/')
try:
leading, num = num.split(' ')
whole = float(leading)
except ValueError:
whole = 0
... |
def get_2nd_ck_line_from_line( line ):
"""
A check line may contain more than 1 check.
Here we get only the info(line aka string) from the 2nd check.
"""
splited = line.split()
ck2 = splited[4:]
ck2 = ' '.join(ck2) # bc next functions expect lines to be strings
# print('ck2 == ... |
def index_by_iterable(obj, iterable):
"""
Index the given object iteratively with values from the given iterable.
:param obj: the object to index.
:param iterable: The iterable to get keys from.
:return: The value resulting after all the indexing.
"""
item = obj
for i in iterable:
... |
def row_str(dflen: int) -> str:
"""String wrapper for the million of rows in a dataframe
Args:
dflen (int): the length of a dataframe
Returns:
str: rows in millions
"""
return str(round(dflen / 1000000, 1)) + "M rows" |
def factorial(n: int) -> str:
"""factorial function that returns the answer in a string.
This so sqlite can save the large integers.
"""
if n < 2:
return "1"
else:
return str(n*int(factorial(n-1))) |
def get_hex(input_list):
"""
Convert a list of bytes into hex string
"""
o = ""
for i in input_list:
o += "%02X"%ord(i)
return o |
def get_neighboring_ap_ids(current_ap_location,
neighboring_aps,
location_to_ap_lookup):
"""
Helper method to remove current ap from neighboring aps and return
list of neighboring ap ids
"""
neighboring_ap_ids = []
if isinstance(current_ap_lo... |
def three_way_partition(seq, left, right):
"""
Three-way-partisions a sequence.
Partitions a sequence of values consisting of three distinct different
types of elements such that the resulting sequence is sorted.
Loop invariants:
1. All values to the left of i are of type 'left'
2. All values to the right of ... |
def delistify(x):
""" A basic slug version of a given parameter list. """
if isinstance(x, list):
x = [e.replace("'", "") for e in x]
return '-'.join(sorted(x))
return x |
def classify(tree, input):
"""classify the input using the given decision tree"""
# if this is a leaf, return it
if tree in [True, False]:
return tree
# find correct subtree
attribute, subtree_dict = tree
subtree_key = input.get(attribute)
if subtree_key not in subtree_dict:
... |
def t_iso(M):
""" Isolation disruption timescale (2-body evaporation)"""
return 17. * (M / 2E5) |
def xgcd(a, b):
"""
Performs the extended Euclidean algorithm
Returns the gcd, coefficient of a, and coefficient of b
"""
x, old_x = 0, 1
y, old_y = 1, 0
while (b != 0):
quotient = a // b
a, b = b, a - quotient * b
old_x, x = x, old_x - quotient * x
old_y, y ... |
def unique_elements(array):
"""Return a list of unique elements of an array."""
unique = []
for x in array:
if x not in unique:
unique.append(x)
return unique |
def is_namedtuple_cls(cls):
"""Test if an object is a namedtuple or a torch.return_types.* quasi-namedtuple"""
try:
if issubclass(cls, tuple):
bases = getattr(cls, "__bases__", []) or [None]
module = getattr(cls, "__module__", None)
return module == "torch.return_type... |
def fromhex(n):
""" hexadecimal to integer """
return int(n, base=16) |
def get_date_print_format(date_filter):
"""
Utility for returning the date format for a given date filter in human readable format
@param date filter : the given date filter
@return the date format for a given filter
"""
vals = {"day": "[YYYY-MM-DD]", "hour": "[YYYY-MM-DD : HH]"}
return val... |
def string_contains_numeric_value(s):
"""Returns true if the string is convertible to float."""
try:
float(s)
return True
except ValueError:
return False |
def factorial(n):
"""Return the factorial of n, an exact integer >= 0.
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(30)
265252859812191058636308480000000
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0
Factoria... |
def get_relative_path_from_module_source(module_source: str) -> str:
"""Get a directory path from module, relative to root of repository.
E.g. zenml.core.step will return zenml/core/step.
Args:
module_source: A module e.g. zenml.core.step
"""
return module_source.replace(".", "/") |
def quotePosix(args):
"""
Given a list of command line arguments, quote them so they can be can be
printed on POSIX
"""
def q(x):
if " " in x:
return "'" + x + "'"
else:
return x
return [q(x) for x in args] |
def parse_unknown_params(params):
"""Purpose of this function is to parse multiple `--metadata.{field}=value` arguments.
:arg:params: tuple of unknown params
"""
structured_params = dict()
for param in params:
param = param.strip('--')
key, value = param.split('=')
if key in... |
def find(n: int) -> int:
"""
This function return the sum of all multiples of 3 and 5.
"""
return sum([i for i in range(2, n + 1) if not i % 3 or not i % 5]) |
def _prepare_labels(labels, label_map):
"""
Converts an array of labels into an array of label_ids
Arguments:
labels (arr) : array of the names of labels
label_map (dict) : key - name of label, value - label-id
Returns:
(arr) : array of the n... |
def glob_all(folder: str, filt: str) -> list:
"""Recursive glob"""
import os
import fnmatch
matches = []
for root, dirnames, filenames in os.walk(folder, followlinks=True):
for filename in fnmatch.filter(filenames, filt):
matches.append(os.path.join(root, filename))
return ma... |
def survival_score(timeSurvived, duration, winPlace):
"""
survival_score = 80% * survival time score + 20% * win place score
: type timeSurvived: int -- participant time survived
: type duration: int -- match duration time
: type winPlace: int
: rtype survival_score: int
"""
survival = (timeSurvived / durat... |
def quote(s):
"""Removes the quotes from a string."""
return s.strip('"\'') |
def float_format(number):
"""Format a float to a precision of 3, without zeroes or dots"""
return ("%.3f" % number).rstrip('0').rstrip('.') |
def param_string_to_kwargs_dict(multiline_param_string):
""" From a multiline parameter string of the form:
parameter
value
Return a kwargs dictionary
E.g.
param_string = \"\"\"base_margin_initialize:
True
colsample_bylevel:
1.0
colsample_bytree:
0.5\"\"\"
... |
def visible_onerow(array):
"""
:return visible number in one row.
"""
out_temp = 1
len_t=len(array)
for i in range(len_t - 1):
for j in range(i+1,len_t):
if array[i] < array[j]:
break
else:
pass
else :
out_temp... |
def _extr_parameter(cmd):
"""Extra parameter for parameterized gate in HiQASM cmd."""
return [float(i) for i in cmd.split(' ')[-1].split(',')] |
def exact_dp4(a_v, b_v):
""" Exact version (formal) of 4D dot-product
:param a_v: left-hand-side vector
:type a_v: list(SollyaObject)
:param b_v: right-hand-side vector
:type b_v: list(SollyaObject)
:return: exact 4D dot-product
:rtype: SollyaObject (value or express... |
def calculate_adjoint_source_raw(py, nproc, misfit_windows_directory, stations_path, raw_sync_directory, sync_directory,
data_directory, output_directory, body_band, surface_band):
"""
At the first step, we should calculate the adjoint source for all the events.
"""
scri... |
def str2bool(v: str) -> bool:
"""This function converts the input parameter into a boolean
Args:
v (*): input argument
Returns:
True: if the input argument is 'yes', 'true', 't', 'y', '1'
False: if the input argument is 'no', 'false', 'f', 'n', '0'
Raises:
ValueError: if ... |
def outlook_days_of_week(event_data):
"""
Converts gathered event data to Outlook-API consumable weekday string
params:
event_data: dictionary containing event data specific to an outlook calendar occurrence
returns:
weekday_list: list containing days of the week for the calend... |
def getFileExt(fileName):
"""returns the fileextension of a given file name"""
lastDot = fileName.rindex('.')
return fileName[lastDot:] |
def format_proxy(proxy_config, auth=True):
"""Convert a Mopidy proxy config to the commonly used proxy string format.
Outputs ``scheme://host:port``, ``scheme://user:pass@host:port`` or
:class:`None` depending on the proxy config provided.
You can also opt out of getting the basic auth by setting ``au... |
def double_eights(n):
"""Return true if n has two eights in a row.
>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(2882)
True
>>> double_eights(880088)
True
>>> double_eights(12345)
False
>>> double_eights(80808080)
False
"""
temp = 0
... |
def matrix_divided(matrix, div):
""" divides matrix by input divisor"""
if div == 0:
raise ZeroDivisionError('division by zero')
if not isinstance(div, (int, float)):
raise TypeError('div must be a number')
new = []
rowlen = len(matrix[0])
for row in matrix:
sub = []
... |
def identidade_matriz(N):
"""Cria matriz quadrada identidade"""
MI = []
for l in range(N):
linha = []
for c in range(N):
if l == c:
valor = 1
else:
valor = 0
linha.append(valor)
MI.append(linha)
return MI |
def xor(bytes_1, bytes_2):
"""XOR two bytearrays of the same length."""
l1 = len(bytes_1)
l2 = len(bytes_2)
assert l1 == l2
result = bytearray(l1)
for i in range(l1):
result[i] = bytes_1[i] ^ bytes_2[i]
return result |
def get_second_smallest(values):
"""
returns the second lowest value in a list of numbers
Args:
values: a list of floats
Returns:
the second lowst number in values
"""
smallest, second_smallest = float("inf"), float("inf")
for value in values:
if value <= smalle... |
def unpack_args(args):
"""
unpacks args
Used by jsonifiers
"""
if isinstance(args, tuple):
return args
else:
return (args, {}) |
def remove_comments(line):
"""remove # comments from given line """
i = line.find("#")
if i >= 0:
line = line[:i]
return line.strip() |
def format_vertex(body): # pragma: no cover
"""Format vertex data.
:param body: Input body.
:type body: dict
:return: Formatted body.
:rtype: dict
"""
vertex = body['vertex']
if '_oldRev' in vertex:
vertex['_old_rev'] = vertex.pop('_oldRev')
if 'new' in body or 'old' in bo... |
def is_comment(line, comments):
"""
A utility method to tell if the provided line is
a comment or not
Parameters
----------
str line: The line string in a file
list comments: A list of potential comment keywords
"""
return line.lstrip(' ')[0] in comments |
def greatest_product_subarray(arr:list, subarray_len:int):
""" returns the subarray having the greatest product in the array and the greatest product
Args:
arr (list): list of integers
subarray_len (int): length of subarray
Returns:
(list,int): subarray,max product
"""
if s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.