content stringlengths 42 6.51k |
|---|
def str2list(src_str):
"""convert the str to shape list
Args:
src_str: for example '1,2,3,4'
Returns:
ret: list, for example [1,2,3,4]
"""
ret = []
s_list = src_str.split(',')
ret = [int(i) for i in s_list]
return ret |
def _pad_sequence_fix(attr, kernel_dim=None):
"""Changing onnx's pads sequence to match with mxnet's pad_width
mxnet: (x1_begin, x1_end, ... , xn_begin, xn_end)
onnx: (x1_begin, x2_begin, ... , xn_end, xn_end)"""
new_attr = ()
if len(attr) % 2 == 0:
for index in range(int(len(attr) / 2)):
... |
def rgba_to_bgra(red, green, blue, alpha=1.0):
"""Reorders channels, it is necessary for pycairo-pygame compatibility"""
return (blue, green, red, alpha) |
def strtobool(val) -> bool:
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = str(val).lower()
if val... |
def calculate_accuracy(TP, TN, FP, FN):
"""
Calculates the prediction accuracy of the supplied reference and test data
Input:
ref: Numpy boolean array of the reference data, of size [n_samples, ]
test: Numpy boolean array of the test data, of size [n_samples, ]
Output:
... |
def Lte(field, value):
"""
A criterion used to search for a field less or equal than a certain value. For example
* search for TLP <= 2
* search for customFields.cvss <= 4.5
* search for date <= now
Arguments:
field (value): field name
value (Any): field value
Returns:
... |
def custom_field_values_to_string(custom_field_values, queryset=False):
"""
Args:
tags: [{"name": "Demo"}, ...] OR
[models.Tag] (if queryset=True)
Returns:
['<tag.name', ...]
"""
if queryset:
new_custom_field_values = [i.value for i in custom_field_values]... |
def Nxxyy2yolo(xmin, xmax, ymin, ymax):
"""convert normalised xxyy OID format to yolo format"""
ratio_cx = (xmin + xmax)/2
ratio_cy = (ymin + ymax)/2
ratio_bw = xmax - xmin
ratio_bh = ymax - ymin
return (ratio_cx, ratio_cy, ratio_bw, ratio_bh) |
def flatten_args_references(image_specs):
"""Resolve all default-args in each image spec to a concrete dict.
Turns this:
example-image:
arg-defaults:
- MY_ARG: ARG_VALUE
another-example:
arg-defaults:
- ANOTHER_ARG: ANOTHER_VALUE
- example_image
Into this:
exam... |
def format_asset_path(game_reference):
"""
This function removes the extra characters if a game reference is pasted in.
:param str game_reference: The game reference copied to the clipboard from the unreal asset.
:return str: The formatted game folder path.
"""
if game_reference[-1] == "'":
... |
def add_00_str(number: int):
"""add 0 to the beginning to the string if integer is less than 10"""
if number < 10:
# add a zero
n_str = '00' + str(number)
elif number < 100:
n_str = '0' + str(number)
else:
n_str = str(number)
return n_str |
def gallons2liters(gallons):
"""Convert gallons to liters"""
liters = gallons * 3.785
return liters |
def xgcd(a: int, b: int) -> list:
"""
Algoritmo de Euclides Estendido, para encontrar o inverso multiplicativo modular.
a - numero
b - numero
"""
if b == 0:
return [1, 0, a]
else:
x, y, d = xgcd(b, a % b)
return [y, x - (a // b) * y, d] |
def _extract_span(item):
"""Extract span from `step_func`."""
return getattr(item, "_datadog_span", None) |
def is_tuple(value):
"""
Checks if `value` is a tuple.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is a tuple.
Example:
>>> is_tuple(())
True
>>> is_tuple({})
False
>>> is_tuple([])
False
.. versionadded... |
def is_done(floors, elevator):
"""Check if done."""
if elevator != 3:
return False
if not floors[0] and not floors[1] and not floors[2] and floors[3]:
return True
return False |
def int_parameter(level, maxval, parameter_max=10):
"""Helper function to scale `val` between 0 and maxval.
source: https://github.com/tensorflow/models/blob/903194c51d4798df25334dd5ccecc2604974efd9/research/autoaugment/augmentation_transforms.py
Args:
level: Level of the operation that will be between [0, ... |
def clamp(val, min_=0.0, max_=1.0):
""" Clamp a value between an upper and lower bound. """
return min_ if val < min_ else max_ if val > max_ else val |
def sql_writer_insert(table_name, *args):
"""Generate a custom SQL insert statement"""
header_list = []
s_list = []
for value in args:
header_list.append(value)
s_list.append('%s')
# Convert
header_list = ','.join(map(str, header_list))
s_list = ','.join(map(str, s_list))
... |
def split_family(family):
"""Takes a family such as 'C3H1' and splits it into subfamilies such as 'C3'
and 'H1'."""
subfamilies, subfamily = [], ""
for char in family:
if char.isalpha() and subfamily:
subfamilies.append([subfamily[0], int(subfamily[1:])])
subfamily = ""
... |
def msb_32(val) -> int:
"""Returns the MSB of a 32 bit value."""
return (val & 0x80000000)>>31 |
def get_index_from_pos_ch_t(pos, ch, t, meta_data, parse_from_single_pos_file=False):
"""
function to calculate the ND2Reader index of a particular frame.
The function get_frame_2D does (afaik) not
work for non-convocal data. A translation of position, channel,
and time frame into the one-dimensiona... |
def list_flat(l):
"""
convert 2-layer list to 1-layer (flatern list)
"""
return [item for sublist in l for item in sublist] |
def generate_all_directions(length, root=True):
"""Generates all possible directions for movement in length-dimentional
space.
Includes the diagonal points. Usually is less efficient than
generate_nondiagonal_directions
"""
if length < 1:
return [[]]
else:
a = generate_a... |
def _convert_attribute_type(value):
"""Convert pyidcom datatypes to the python datatypes used to set the parameter.
While this removes some functionality, this aligns with the principle
of `dbdicom` to remove DICOM-native langauge from the API.
"""
if value.__class__.__name__ == 'PersonName':... |
def merge(*objects):
""" Merge simple python objects, which only consist of
strings, integers, bools, lists and dicts
"""
mode = type(objects[0])
if not all(type(obj) is mode for obj in objects):
raise ValueError("Cannot merge mixed typed objects")
if len(objects) == 1:
return ob... |
def remove_comments(s):
"""
Examples
--------
>>> code = '''
... # comment 1
... # comment 2
... echo foo
... '''
>>> remove_comments(code)
'echo foo'
"""
return "\n".join(l for l in s.strip().split("\n") if not l.strip().startswith("#")) |
def get_difference(string_1, string_2):
"""
Count every different between two strings
:param string_1:
:param string_2:
:return:
"""
return sum(ele_x != ele_y for ele_x, ele_y in zip(string_1, string_2)) |
def identity(target):
"""Returns a dictionary with the values equal to the keys.
"""
result = ((i, i) for i in target)
return dict(result) |
def TSKVolumeGetBytesPerSector(tsk_volume):
"""Retrieves the number of bytes per sector from a TSK volume object.
Args:
tsk_volume: a TSK volume object (instance of pytsk3.Volume_Info).
Returns:
The number of bytes per sector or 512 by default.
"""
# Note that because pytsk3.Volume_Info does not exp... |
def differentiation_alg(func, b, integral, eps=1e-12):
"""
Numerical differentiation at point by calculating deriviative at a point and halving step size
:param func:
:param b:
:param eps:
:return:
"""
h = 0.01
# First step
def calc_deriv():
return (func(b + h / 2, int... |
def to_unicode(sorb, allow_eval=False):
"""Ensure that strings are unicode (UTF-8 encoded).
Evaluate bytes literals that are sometimes accidentally created by str(b'whatever')
>>> to_unicode(b'whatever')
'whatever'
>>> to_unicode(b'b"whatever"')
"b'whatever'"
>>> '"{}"'.format(b'whatever')... |
def _is_reserved_keyword(name: str) -> bool:
""" Returns bool of whether the uppercased name is reserved in Redshift
NOTE: This is backwards to expected by name (if _is_reserved_keyword , its fine)
"""
reserved = "AES128 AES256 ALL ALLOWOVERWRITE ANALYSE ANALYZE AND ANY ARRAY AS ASC AUTHORIZATION BACKUP... |
def initialize_P(nS, nA):
"""Initializes a uniformly random model of the environment with 0 rewards.
Parameters
----------
nS: int
Number of states
nA: int
Number of actions
Returns
-------
P: np.array of shape [nS x nA x nS x 4] where items are tuples representing tran... |
def check_in_turn_repetition(pred, is_cn=False):
"""Check the in-turn repetition.
Calcuate tri-gram repetition.
Args:
pred: Words or tokens or token_ids.
is_cn: Chinese version repetition detection. If true, calcuate repetition on characters.
Returns:
Whether the in-turn repet... |
def factors(n):
"""
Returns all factors of n
"""
import functools
return list(functools.reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1)
if n % i == 0))) |
def policy_threshold(threshold, belief, loc):
"""
chooses whether to switch side based on whether the belief
on the current site drops below the threshold
Args:
threshold (float): the threshold of belief on the current site,
when the belief is lower than the threshold, switch si... |
def charbuffer_encode( obj, errors='strict'):
"""None
"""
res = str(obj)
res = ''.join(res)
return res, len(res) |
def cumul(d):
""" Cumulates the values in list """
c = 0
for val, count in enumerate(d):
d[val] = count + c
c += count
return d |
def class_names_from_index(classes, category_index):
"""
:param classes: a list of detected classes e.g. [1, 1]
:param category_index: the category index dict e.g. {1: {'id': 1, 'name': 'car'}, 2: {'id': 2, 'name': 'pedestrian'}}
:return: a dict of {class_id:class_name} e.g. {1:'car'}
"""
return... |
def column_names(wide):
"""
Column names for geographic header file
"""
if wide is True:
return ['Summary Level', 'Geographic Component', 'State FIPS', 'Place FIPS', 'County FIPS', 'Tract', 'Zip', 'Block Group', 'Block', 'Name', 'Latitude', 'Longitude', 'Land Area', 'Water Area', 'Population', '... |
def get_close_entity_mentions(pred_indices, possible_ents, threshold):
"""
Get entities up to a distance threshold from pred_indices
:param pred_indices: the predicate indices
:param possible_ents: the argument mention candidates
:param threshold: the distance to the predicate under which compo... |
def selection_sort(arr):
""" Sorts an array by repeatedly finding the minimum element (considering
ascending order) from unsorted part and putting it at the beginning.
This implementation is an in-place sort.
"""
for j in range(0, len(arr)-1):
min_idx = j
for i in range(j+1, ... |
def overlaps_position(start, end, positions, positions_negative):
"""Checks if the interval [start, end] overlaps with any of the positive sample positions. Also check, wehther they overlap with an already existing negative sample"""
for pstart, pend in positions:
if end >= pstart and start <= pend:
... |
def byte_to_megabyte(byte):
"""
Convert byte value to megabyte
"""
return (byte / 1048576) |
def Merge(dict1, dict2):
"""
Appends two dicts and returns a dict.
"""
res = {**dict1, **dict2}
return res |
def find_faces_at_vertices(faces, npoints):
"""
For each vertex, find all faces containing this vertex.
Note: faces do not have to be triangles.
Parameters
----------
faces : list of lists of three integers
the integers for each face are indices to vertices, starting from zero
npoin... |
def turn_into_list(object):
"""Returns a list containing the object passed.
If a list is passed to this function, this function will not create a
nested list, it will instead just return the list itself."""
if isinstance(object, list):
return object
else:
return [object] |
def is_int(target):
"""
"""
try:
a = float(target)
b = int(a)
except ValueError:
return False
else:
return a == b |
def initial_fragment(string, words=20):
"""Get the first `words` words from `string`, joining any linebreaks."""
return " ".join(string.split()[:words]) |
def disjoint_bounds(bounds1, bounds2):
"""Compare two bounds and determine if they are disjoint.
Parameters
----------
bounds1: 4-tuple
rasterio bounds tuple (xmin, ymin, xmax, ymax)
bounds2: 4-tuple
rasterio bounds tuple
Returns
-------
boolean
``True`` if bounds a... |
def key_by_license_plate_month(element):
"""
here we will construct a multi ((keys), (values)) tuple row
we're preparing to aggregate by license plate and month and we would aggregated fields:
count(1), sum(total), sum(cornsilk), sum(slate_gray), sum(navajo_white), mean(total)
multi-aggregation on... |
def get_quarter(dx: int, dy: int) -> int:
"""check in which quarter a point
is located relatively to another.
"""
if dx > 0:
if dy > 0:
return 1
return 4
elif dy > 0:
return 2
return 3 |
def findLast(arr, a):
"""
To understand the advantage of `l + 1 < r`, consider edge case [2, 2].
If using `l < r` as condition, it leads to infinite loop (convince yourself).
Can combine two conditions: `arr[m] <= a`
"""
if not arr: return -1
l, r = 0, len(arr) - 1
while l + 1 < r:
m = (r - l) // ... |
def iter_first_value(iterable, default=None):
""" Get first 'random' value of an iterable or default value. """
for x in iterable:
if hasattr(iterable, "values"):
return iterable[x]
else:
return x
return default |
def set_case(u=0.1, D=0.5, gamma=0.1, rho=1, dx=0.2, phiA=1, phiB=0):
"""
Set variable/parameter for specific Case
args:
u: velocity (m/s) (default=0.1)
L: length (m) (default=1)
rho: density (kg/m3) (default=1)
gamma: gamma (kg/(m.s)) (default=0.1)
nodes: nodes ... |
def merge(line):
"""
Helper function that merges a single row or column in 2048
"""
# replace with your code
result_final = []
result = []
for dummy_count in range(len(line)):
result.append(0)
result_final.append(0)
index = 0
for dummy_ele in line:
if dummy_e... |
def pos(dot, at):
"""Create a human-readable position of a PFA element in a JSON file."""
if at is None or at == "":
return "at {0}".format("" if (dot == "") else "PFA field \"" + dot + "\"")
else:
return "at {0}{1}".format(at, "" if (dot == "") else " (PFA field \"" + dot + "\")") |
def check_codeblock(block, lang="python"):
"""
Cleans the found codeblock and checks if the proglang is correct.
Returns an empty string if the codeblock is deemed invalid.
Arguments:
block: the code block to analyse
lang: if not None, the language that is assigned to the codeblock
... |
def _sigmoid_prime(A):
""" calculate dAdZ
:param A:
:return: dAdZ
"""
return A * (1 - A) |
def is_palindrome(n):
"""
Returns true/false if a number (or string) is a palindrome
"""
string = str(n)
reversed_string = str(n)[::-1]
length = len(string)
for position in range(length):
if string[position] != reversed_string[position]:
return False
return Tr... |
def fib(n: int) -> int:
"""Calculate Fibonacci Number."""
ret = 1
if n == 0:
return 0
if n < 2:
return ret
ret = fib(n - 1) + fib(n - 2)
return ret |
def type_of_exception(exception_object):
"""Get the type of an exception object as a string or None"""
if isinstance(exception_object, Exception):
return str(exception_object.__class__.__name__) |
def check_if_staged_recipe(container: dict) -> bool:
"""
Check whether container pertains to a staged recipe.
Such a "staged container" fulfills two conditions:
- no top level key in container contains "modifiers" in its name
- a stage should map to a dict that has at least one key with
"modif... |
def pad(value):
"""
Add one space padding around value if value is valid.
Args:
value (string): Value
Returns:
string: Value with padding if value was valid else one space
"""
return " %s " % value if value else " " |
def jenkins_api_query_job_statuses(jenkins_url):
"""Construct API query to Jenkins (CI)."""
return "{url}/api/json?tree=jobs[name,color]".format(url=jenkins_url) |
def get_errfile(outfile):
"""Get the stderr file name given the stdout file name"""
i = outfile.rfind(".out")
left = outfile[0:i]
right = ""
if i + 5 < len(outfile):
right = outfile[i + 4 :]
errfile = left + ".err" + right
return errfile |
def encodeParameterValue(value):
"""
RFC6868 parameter encoding.
"""
# Test for encoded characters first as encoding is expensive and it is better to
# avoid doing it if it is not required (which is the common case)
encode = False
for c in "\r\n\"^":
if c in value:
encod... |
def date_format(date: str) -> dict:
"""Formating the date for dict structure
Example:
>>> date = date_format("Mai 15, 2015")
>>> print(date)
Output:
{
"month": "Mai",
"day": "15",
"year": "2015",
"full_date":... |
def get_mid(low, high):
"""returns the int occurring at the midpoint of the ints low and high
"""
return low + high // 2 |
def remove_variables(variables):
"""Removes low-level variables from the input.
Removing low-level parameters (e.g., initial convolution layer) from training
usually leads to higher training speed and slightly better testing accuracy.
The intuition is that the low-level architecture (e.g., ResNet-50) is able t... |
def convert_data_to_list(data):
"""
:param data: "," separated string
:return: returns a list of values
"""
temp = (list(map(lambda x: x.strip(), data['Value'].split(','))) if data['IsArray'] == 1 else data['Value'])
return temp |
def e_sudeste(arg):
"""
e_sudeste: direcao --> logico
e_sudeste(arg) tem o valor verdadeiro se arg for o elemento 'SE' e falso
caso contrario.
"""
return arg == 'SE' |
def key2param(key):
"""Converts key names into parameter names.
For example, converting "max-results" -> "max_results"
Args:
key: string, the method key name.
Returns:
A safe method name based on the key name.
"""
result = []
key = list(key)
if not key[0].isalpha():
result.append('x')
f... |
def problem_25(digits=1000):
"""
index of first fibonacci term with >=1000 digits
"""
# compute fib terms as we go and also keep running sum, so one pass
f_1 = 0
f_2 = 1
# tracks index of f_2
n = 1
even_sum = 0
limit = 10 ** (digits - 1)
while f_2 < limit:
# shift pre... |
def transpose(xss):
"""
Transpose a list of lists. Each element in the input list of lists is
considered to be a column. The list of rows is returned.
The nested lists are assumed to all be of the same length. If they are not,
the shortest list will be used as the number of output rows and other ro... |
def exc_message(exc):
"""Get an exception message."""
message = getattr(exc, 'message', None)
return message or str(exc) |
def latex_safe_url(s):
"""Makes a string that is a URL latex safe."""
return s.replace("#", r"\#") |
def parse_file(input_file):
""" takes all text from ym database file and returns a list of lists with
NPs which is easy to use
input_file: ym database txt file
"""
all_lines = input_file.split('\n')
all_info_list = []
for line in all_lines:
line = line.split('\t')
in... |
def mangle(cls, name):
"""Applies Python name mangling using the provided class and name."""
return "_" + cls.__name__ + "__" + name |
def rotate_list(arr,k):
""" First idea: jump between adrresses by k as many times as num of elements and overwrite values with ones from previous address.
O(2) space and O(n) time
"""
# Length of array.
arl = len(arr)
# Edge cases I & II: k=0 or empty list
if arl < 2 or k == 0:
prin... |
def convert_coord(es_coord):
"""gen coords for kml"""
coord = []
for point in es_coord:
coord.append((str(point[0]), str(point[1])))
return coord |
def mark_list(line: str) -> list:
""""Given a string, return a list of index positions where a character/non blank space exists.
>>> mark_list(" a b c")
[1, 3, 5]
"""
marks = []
for idx, car in enumerate(list(line)):
if car != " ":
marks.append(idx)
return marks |
def num_to_binary(n, N):
"""Returns the binary representation of n
Args:
n (int): The number to be represented in binary
N (int): The number of digits of the rapresentation
Returns:
bool: The binary representation of n
es: num_to_binary(5,4) = 0101
"""
Nbits=2**N
i... |
def lv0_consts(key=None):
"""
defines consts used while reading Sciamachy level 0 data
"""
consts = {}
consts['mph_size'] = 1247
consts['num_aux_bcp'] = 16
consts['num_aux_pmtc_frame'] = 5
consts['num_pmd_packets'] = 200
consts['channel_pixels'] = 1024
if key is None:
re... |
def ternary_search(func, low, high, precision, max_iterations):
"""
Returns tha maxima of the function `func` given the range
`low` - `high` within the specified `precision` stopping
after `max_iterations`.
Returns -1 if the precision could not be achieved withing `max_iterations`
"""
maxima... |
def generate_missing_location_msg(filepath, errors):
"""Generate error message for missing location LookupError."""
msg = (
"Unused step implementation"
if filepath.endswith(".py")
else "Step implementation not found"
)
if len(errors) == 1:
msg += ". Also registered an e... |
def get_bc(eduidx, edu_dict, token_dict, bcvocab, nprefix=5):
""" Get brown cluster features for tokens
:type eduidx: int
:param eduidx: index of one EDU
:type edu_dict: dict
:param edu_dict: All EDUs in one dict
:type token_dict: dict of Token (data structure)
:param token_dict: all toke... |
def gray(graylevel):
"""Returns a xterm256 color index that represents the specified gray level.
The argument should be an integer in the range [0, 25]."""
if graylevel < 0 or graylevel > 25:
raise ValueError("Value out of range")
if graylevel == 0:
return 0
elif graylevel == 25:
... |
def F0F2F4_to_UdJH(F0, F2, F4):
"""
Given :math:`F_0`, :math:`F_2` and :math:`F_4`, return :math:`U_d` and :math:`J_H`.
Parameters
----------
F0 : float
Slater integral :math:`F_0`.
F2 : float
Slater integral :math:`F_2`.
F4 : float
Slater integral :math:`F_4`.
... |
def serialize_file_list(files: list, active_item_index: int = -1):
"""Returns a serialized file list, which JRiver requires in some API calls.
These are a not documented further, but form a string of comma seperated values.
These are, in order:
[0] The value '2', stating a serialization version. Only 2 ... |
def cal_supports(freq, n_rows):
"""
calculate supports
Parameters
----------
freq : int
frequate of itemset.
n_rows : int
number of rows.
Returns
-------
supports of itemset.
"""
if n_rows == 0:
raise ValueError("The rows supposed not to be zero")
... |
def average_word(word_list):
"""
Picks the most frequent character of each word.
Takes list of words
"""
result = ''
#Going through each character position
word_length = len(word_list[0]['text'])
for position in range(word_length):
#How many times each character apears ... |
def pop_with_default(a_dict, key, default=None):
"""
Pop a key from a dict and return its value or a default value.
:Args:
a_dict
Dictionary to look for `key` in
key
Key to look for in `a_dict`
default
Default value to return if `key` is not pre... |
def mean(xs):
"""Returns the mean of the given list of numbers"""
return sum(xs) / len(xs) |
def get_between(txt:str, open_char:str="'", close_char:str="'", start:int=1 ):
"""Parse all content in supplied text that appears between the open and close characters, exclusively.
If txt is empty, or open_char is not found, returns ('', -1, -1). If the close_char is never found,
returns the txt from the... |
def _get_change_ratio_from_change_frac(change_frac, inc_or_dec):
""" Gets the change ratio from the change fraction, i.e. 1 +/- change_frac depending
on inc_or_dec. """
if inc_or_dec.lower() == 'increase':
return 1 + abs(change_frac)
elif inc_or_dec.lower() == 'decrease':
return 1 - abs(change_frac)... |
def get_idx_from_sent(sent, word_idx_map):
"""
Transforms sentence into a list of indices. Pad with zeroes.
"""
x = []
words = sent.split()
for word in words:
if word in word_idx_map:
x.append(word_idx_map[word])
else:
x.append(1)
return x |
def countSegments(s):
"""
:type s: str
:rtype: int
"""
count=0
for i in range(len(s)):
if s[i] != " " and (i==0 or s[i-1]==" "):
count+=1
return count |
def _source_from_detector(parameter, z):
"""Return the source-frame parameter given samples for the detector-frame parameter
and the redshift
"""
return parameter / (1. + z) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.