content
stringlengths 42
6.51k
|
---|
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# Create a hash table (Python dictionary)
htbl = {}
for i, num in enumerate(nums):
t = target - num
if t in htbl.keys():
return [htbl[t], i]
else:
htbl[num] = i
return None
|
def get_row_indices(center: int, length: int, neighbor_range: int):
"""
I do not recommend using, unless you know what to do...
This function takes the center location x and generates the
list of numbers that are within the neighbor_range with the
limitation of the length (cannot extend past the length or
go below 0). Examples:
1. center: 1, length: 2, neighbor_range: 1 results in a
list of [0, 1, 2]
2. center: 1, length: 1, neighbor_range: 1 results in a
list of [0, 1]
3. center: 1, length: 4, neighbor_range: 2 results in a
list of [0, 1, 2, 3]
:param center: int; the center location to get the neighbor_range above and below
:param length: int; the maximum value allowed (the minimum value allowed is 0)
:param neighbor_range: int; The maximum number above and below the center value to
return in resulting list
:return: list; numbers in range of x-neighbor_range: x+neighbor_range, with limitations
of length being the max allowed number in range and 0 being the minimum.
"""
return [x for x in range(max(0, center-neighbor_range), min(length, center+1+neighbor_range))]
|
def checkNotNull(params):
"""
Check if arguments are non Null
Arguments:
params {array}
"""
for value in params:
if value == None:
return False
return True
|
def scale_to_sum_one(vector):
"""Scales the items in the vector, so that their sum is 1"""
total = sum(vector)
if total == 0:
return vector
return [v/total for v in vector]
|
def pick_equipment(categories, cur_pick):
"""Pick one item from each of categories."""
if not categories:
return [cur_pick]
items = categories[0]
picks = []
for item in items:
next_picks = pick_equipment(categories[1:], cur_pick + item)
picks.extend(next_picks)
return picks
|
def get_link_text_from_selector(selector):
"""
A basic method to get the link text from a link text selector.
"""
if selector.startswith('link='):
return selector.split('link=')[1]
elif selector.startswith('link_text='):
return selector.split('link_text=')[1]
return selector
|
def _extract_defines_from_option_list(lst):
"""Extracts preprocessor defines from a list of -D strings."""
defines = []
for item in lst:
if item.startswith('-D'):
defines.append(item[2:])
return defines
|
def pad_b64(encoded):
"""Append = or == to the b64 string."""
if len(encoded) % 4 == 0:
pass
elif len(encoded) % 4 == 3:
encoded += "="
elif len(encoded) % 4 == 2:
encoded += "=="
return encoded
|
def interval_condition(value, inf, sup, dist):
"""Checks if value belongs to the interval [inf - dist, sup + dist].
"""
return inf - dist < value < sup + dist
|
def mock_event(player: dict) -> dict:
"""
Fixture to create an AWS Lambda event dict
:param player: Input character; see above
:return: Mock event dict
"""
return {
"body": {
"Player": player,
"playerId": "player_hash",
"action": "attack",
"enhanced": False,
}
}
|
def box_size_calculate(r):
""" Calculates 1D size of bounding box
Args:
r:
A list containing the 2 co-ordinates of image [(x1, y1), (x2, y2)]
Returns:
length and width of box
"""
length = r[2] - r[0]
width = r[3] - r[1]
return length, width
|
def discount_admin_cost(cost, timestep, global_parameters):
"""
Discount admin cost based on return period.
192,744 = 23,773 / (1 + 0.05) ** (0:9)
Parameters
----------
cost : float
Annual admin network running cost.
timestep : int
Time period (year) to discount against.
global_parameters : dict
All global model parameters.
Returns
-------
discounted_cost : float
The discounted admin cost over the desired time period.
"""
discount_rate = global_parameters['discount_rate'] / 100
discounted_cost = cost / (1 + discount_rate) ** timestep
return discounted_cost
|
def rotate_char(c, n):
"""Rotate a single character n places in the alphabet
n is an integer
"""
# alpha_number and new_alpha_number will represent the
# place in the alphabet (as distinct from the ASCII code)
# So alpha_number('a')==0
# alpha_base is the ASCII code for the first letter of the
# alphabet (different for upper and lower case)
if c.islower():
alpha_base = ord('a')
elif c.isupper():
alpha_base = ord('A')
else:
# Don't rotate character if it's not a letter
return c
# Position in alphabet, starting with a=0
alpha_number = ord(c) - alpha_base
# New position in alphabet after shifting
# The % 26 at the end is for modulo 26, so if we shift it
# past z (or a to the left) it'll wrap around
new_alpha_number = (alpha_number + n) % 26
# Add the new position in the alphabet to the base ASCII code for
# 'a' or 'A' to get the new ASCII code, and use chr() to convert
# that code back to a letter
return chr(alpha_base + new_alpha_number)
|
def snake_to_camel(snake):
"""convert snake_case to camelCase"""
components = snake.split("_")
return components[0] + "".join([comp.title() for comp in components[1:]])
|
def lr_lambda(epoch, base=0.99, exponent=0.05):
"""Multiplier used for learning rate scheduling.
Parameters
----------
epoch: int
base: float
exponent: float
Returns
-------
multiplier: float
"""
return base ** (exponent * epoch)
|
def _default_caltab_filename(stnid, rcumode):
"""Get default filename of a LOFAR station calibration table.
"""
caltabfilename = 'CalTable_'+stnid[2:]+'_mode'+rcumode+'.dat'
return caltabfilename
|
def num_edges(ugraph):
"""
compute total number of edges for a undirected graph
:param ugraph:
:return:
"""
total_edges = 0
for edges in ugraph.values():
total_edges += len(edges)
return total_edges / 2
|
def tknzr_exp_name(exp_name: str) -> str:
"""Tokenizer experiment name."""
return f'{exp_name}-tokenizer'
|
def dh_validate_public(public, q, p):
"""See RFC 2631 section 2.1.5."""
return 1 == pow(public, q, p)
|
def _format_samples_counts(samples, expression):
"""Return a dictionary of samples counts"""
if isinstance(samples, list):
if len(samples) != len(expression):
raise ValueError("samples %s has different length than expression %s" % (samples,
expression))
else:
samples = [samples]
expression = [expression]
return dict(zip(samples, expression))
|
def get_job_class(job):
"""Returns job class."""
if '_class' in job:
if job['_class'] == 'com.cloudbees.hudson.plugins.folder.Folder':
return 'folder'
if 'DFG-' in job['name']:
return 'DFG'
elif 'util' in job['name']:
return 'utility'
|
def ctype(v, t):
"""Convert "v" to type "t"
>>> ctype('10', int)
10
>>> ctype('10', list)
['1', '0']
>>> ctype(10, list)
10
>>> ctype('10a', float)
'10a'
:param tp.Any v:
:param tp.TypeVar t:
:return tp.Any:
"""
try:
return t(v) or v
except (ValueError, TypeError):
return v
|
def file_type(file_name):
"""
Returns the file type from a complete file name
If the file doesn't have a file type, return "file"
"""
if "." not in file_name:
return "file"
return file_name.split(".")[-1]
|
def get_product(temp):
"""returns the product and types of items depending on the temperature value"""
product = ""
items = list()
if temp < 19:
product = "moisturizer"
items = ["Aloe", "Almond"]
elif temp > 34:
product = "sunscreen"
items = ["SPF-30", "SPF-50"]
return product, items
|
def vect3_add(v1, v2):
"""
Adds two 3d vectors.
v1, v2 (3-tuple): 3d vectors
return (3-tuple): 3d vector
"""
return (v1[0]+v2[0], v1[1]+v2[1], v1[2]+v2[2])
|
def take_step(solutions, step):
"""
Takes a step for each solution.
"""
return [solution + [step] for solution in solutions]
|
def merge_sort(list):
"""Merge sort, duh?
:param list: List of things to sort
:return: Cool sorted list
"""
if len(list) > 1:
middle = len(list) // 2
left = merge_sort(list[:middle]) # Sort left partition
right = merge_sort(list[middle:]) # Sort right partition
list = []
# As long as we have stuff to sort, we run this routine
while len(left) > 0 and len(right) > 0:
if left[0] < right[0]:
list.append(left[0])
left.pop(0)
else:
list.append(right[0])
right.pop(0)
# Merge left partition items to list
for item in left:
list.append(item)
# and then the right
for item in right:
list.append(item)
return list
|
def p64b(x):
"""Packs an integer into a 8-byte string (big endian)"""
import struct
return struct.pack('>Q', x & 0xffffffffffffffff)
|
def paging_modes(yaml_string, isa):
"""
This function reads the YAML entry specifying the valid
paging modses supported by the SATP CSR and returns the mode(s)
for the framework to generate tests
"""
split_string = yaml_string.split(' ')
values = (split_string[-1][1:-1]).split(',')
valid_list = [int(i) for i in values]
valid_modes = []
if 'RV64' in isa:
if 8 in valid_list:
valid_modes.append('sv39')
if 9 in valid_list:
valid_modes.append('sv48')
if 10 in valid_list:
valid_modes.append('sv57')
else:
if 1 in valid_list:
valid_modes.append('sv32')
return valid_modes
|
def first(values):
"""
Get the first value in the list of values as a string.
"""
if isinstance(values, (str, bytes)):
return values
value = values[0]
if isinstance(value, str):
return values[0]
return str(value)
|
def conv_outsize(in_size, kernel_size, padding, stride):
"""
Computes the size of output image after the convolution defined by the input arguments
"""
out_size = (in_size - kernel_size + (2 * padding)) // stride
out_size += 1
return out_size
|
def levenshtein_distance(str1, str2):
"""
Return the minimum number of character deletions,
insertions and/or substitutions between two strings.
:param str1: first string
:param str2: second string
:type str1: string
:type str2: string
:returns: levenshtein distance between the two strings
:rtype: int
"""
cols, rows = len(str1), len(str2)
matrix = [[0 for col in range(cols + 1)] for row in range(rows + 1)]
# Distances from empty string
for col in range(1, cols + 1):
matrix[0][col] = col
for row in range(1, rows + 1):
matrix[row][0] = row
for row in range(1, rows + 1):
for col in range(1, cols + 1):
cost = 0 if str1[col - 1] == str2[row - 1] else 1
matrix[row][col] = min(
matrix[row][col - 1] + 1, # deletion
matrix[row - 1][col] + 1, # insertion
matrix[row - 1][col - 1] + cost) # substitution
return matrix[rows][cols]
|
def sample_length(min_length, max_length, rng):
"""
Computes a sequence length based on the minimal and maximal sequence size.
Parameters
----------
max_length : maximal sequence length (t_max)
min_length : minimal sequence length
Returns
-------
A random number from the max/min interval
"""
length = min_length
if max_length > min_length:
length = min_length + rng.randint(max_length - min_length)
return length
|
def resolve_boolean_value(val: str):
""" Resolve a string which represents a boolean value
Args:
val: The value
Returns:
True, False or None
"""
val = val.upper()
if val == "TRUE":
return True
elif val == "FALSE":
return False
else:
return None
|
def get_gender(x):
""" returns the int value for the ordinal value class
:param x: a value that is either 'crew', 'first', 'second', or 'third'
:return: returns 3 if 'crew', 2 if first, etc.
"""
if x == 'Male':
return 1
else:
return 0
|
def generate_previous_list(next_list):
"""
Generate the expected list of previous values given a list of next values.
Lags the next list, holds the last valid number, and adds None to the
front. e.g.
[0,1,2,None,None,None] -> [None, 0,1,2,2,2]
"""
# Add none and lag the list
previous_list = [None] + next_list[:-1]
# Hold the last valid number by replacing None with last valid number
idx_last_valid = 1
for i in range(1, len(previous_list)):
if previous_list[i] is None:
previous_list[i] = previous_list[idx_last_valid]
else:
idx_last_valid = i
assert len(next_list) == len(previous_list)
return previous_list
|
def is_subdir(path, directory):
"""
Returns true if *path* in a subdirectory of *directory*.
Both paths must be absolute.
"""
from os.path import normpath, normcase
path = normpath(normcase(path))
directory = normpath(normcase(directory))
return path.startswith(directory)
|
def information_gain_proxy(
impurity_left, impurity_right, w_samples_left, w_samples_right,
):
"""Computes a proxy of the information gain (improvement in impurity) using the
equation
- n_v0 * impurity_v0 - n_v1 * impurity_v1
where:
* n_v0, n_v1 are the weighted number of samples in the left and right nodes
* impurity_v0, impurity_v1 are the impurities of the left and right nodes
It is used in order to find the best split faster, by removing constant terms from
the formula used in the information_gain function.
Parameters
----------
impurity_left : float
Impurity of the left node
impurity_right : float
Impurity of the right node
w_samples_left : float
Weighted number of samples in the left node
w_samples_right : float
Weighted number of samples in the roght node
Returns
-------
output : float
Proxy of the information gain after splitting the parent into left
and child nodes
"""
return -w_samples_left * impurity_left - w_samples_right * impurity_right
|
def remove_carriage_ret(lst):
"""
Remove carriage return - \r from a list
"""
return list(map(lambda el: el.replace('\r',''), lst))
|
def first_diff_pos(a, b):
"""
find the pos of first char that doesn't match
"""
for i, c in enumerate(a):
if i >= len(b):
return i # return if reached end of b
if b[i] != a[i]:
return i # we have come to the first diff
return len(a)
|
def angle_offset(base, angle):
"""
Given a base bearing and a second bearing, return the offset in degrees.
Positive offsets are clockwise/to the right, negative offsets are
counter-clockwise/to the left.
"""
# rotate the angle towards 0 by base
offset = angle - base
if offset <= -180:
# bring it back into the (-180, 180] range
return 360 + offset
if offset > 180:
return offset - 360
return offset
|
def describe_interval(secs):
"""
Return a string describing the supplied number of seconds in human-readable
time, e.g. "107 hours, 42 minutes".
"""
if secs <= 0:
return 'no time at all'
hours = secs // 3600
minutes = (secs - (hours * 3600)) // 60
parts = []
if hours > 0:
if hours == 1:
parts.append('1 hour')
else:
parts.append('%d hours' % hours)
if minutes > 0:
if minutes == 1:
parts.append('1 minute')
else:
parts.append('%d minutes' % minutes)
if not (hours or minutes):
parts.append('less than a minute')
return ', '.join(parts)
|
def level_put_response_ok(devid, level):
"""Return level change response json."""
return '{"id": "' + devid + '", "level": "' + str(level) + '"}'
|
def py_bool(data):
""" return python boolean """
return data == "true"
|
def tld(s):
""" Parse the TLD of a domain name.
:param s: String to parse.
"""
if s.endswith('.'):
return s[s.rfind('.', 0, -1)+1:-1]
return s[s.rfind('.')+1:]
|
def sequence_frame_number(scene_frame, mode, start, duration, offset):
""" Get sequence frame number from sequence settings and current scene frame """
frame = scene_frame - start + 1
if mode == 'CLIP':
if frame < 1 or frame > duration:
return None
elif mode == 'EXTEND':
frame = min(max(frame, 1), duration)
elif mode == 'REPEAT':
frame %= duration
if frame < 0:
frame += duration
if frame == 0:
frame = duration
else: # mode == 'PING_PONG'
pingpong_duration = duration * 2 - 2
frame %= pingpong_duration
if frame < 0:
frame += pingpong_duration
if frame == 0:
frame = pingpong_duration
if frame > duration:
frame = duration * 2 - frame
frame += offset
return frame
|
def remove_duplicates(a):
"""
Remove Duplicates from an Array
>>> sorted(remove_duplicates("hello"))
['e', 'h', 'l', 'o']
>>> remove_duplicates([1,2,3,1,2,4])
[1, 2, 3, 4]
"""
return list(set(a))
|
def b_to_mb(b: int):
"""Convert bytes to MB."""
return round(float(b) / (1024 ** 2), 2)
|
def is_discord_file(obj):
"""Returns true if the given object is a discord File object."""
return (obj.__class__.__name__) == "File"
|
def create_vector(p1, p2):
"""Contruct a vector going from p1 to p2.
p1, p2 - python list wth coordinates [x,y,z].
Return a list [x,y,z] for the coordinates of vector
"""
return list(map((lambda x,y: x-y), p2, p1))
|
def formata_valor(value):
"""
Formata um valor em R$
"""
return "R$ {}".format(value)
|
def remove_a_key(d: dict, remove_key: str) -> dict:
"""
Removes a key passed in as `remove_key` from a dictionary `d`.
Reference: https://stackoverflow.com/questions/58938576/remove-key-and-its-value-in-nested-dictionary-using-python
"""
if isinstance(d, dict):
for key in list(d.keys()):
if key == remove_key:
del d[key]
else:
remove_a_key(d[key], remove_key)
return d
|
def startEnd(length, start, end):
"""Helper function to normalize the start and end of an array by counting from the end of the array (just like Python).
:type length: non-negative integer
:param length: length of the array in question
:type start: integer
:param start: starting index to interpret
:type end: integer
:param end: ending index to interpret
:rtype: (non-negative integer, non-negative integer)
:return: (normalized starting index, normalized ending index)
"""
if start >= 0:
normStart = start
else:
normStart = length + start
if normStart < 0:
normStart = 0
if normStart > length:
normStart = length
if end >= 0:
normEnd = end
else:
normEnd = length + end
if normEnd < 0:
normEnd = 0
if normEnd > length:
normEnd = length
if normEnd < normStart:
normEnd = normStart
return normStart, normEnd
|
def conv_C2F(c):
"""Convert Celsius to Fahrenheit"""
return c*1.8+32.0
|
def splitter(items, separator, convert_type):
"""
Split the string of items into a list of items.
:param items: A string of joined items.
:param separator: The separator used for separation.
:param convert_type: The type the item should be converted into after separation.
:return: A list of items.
"""
return [convert_type(x) for x in items.split(separator)]
|
def clean_outcomert(row):
"""
Intended for use with DataFrame.apply()
Returns an array with 'outcomert' converted from milliseconds to seconds if the 'study' variable is '3'
"""
if int(row['study']) >= 3:
return float(row['outcomert'] * .001)
else:
return row['outcomert']
|
def apply_inverse_rot_to_vec(rot, vec):
"""Multiply the inverse of a rotation matrix by a vector."""
# Inverse rotation is just transpose
return [rot[0][0] * vec[0] + rot[1][0] * vec[1] + rot[2][0] * vec[2],
rot[0][1] * vec[0] + rot[1][1] * vec[1] + rot[2][1] * vec[2],
rot[0][2] * vec[0] + rot[1][2] * vec[1] + rot[2][2] * vec[2]]
|
def vec2dict(vector):
"""
Input:
vector: a list or (1d) numpy array
Returns:
a dict with {idx:value} for all values of the vector
"""
return {i: val for i, val in enumerate(vector)}
|
def _to_int(x):
"""Converts a completion and error code as it is listed in 32-bit notation
in the VPP-4.3.2 specification to the actual integer value.
"""
if x > 0x7FFFFFFF:
return int(x - 0x100000000)
else:
return int(x)
|
def isint(s):
"""checks if a string is a number"""
try:
return int(s)
except ValueError:
return False
|
def argn(*args):
"""Returs the last argument. Helpful in making lambdas do more than one thing."""
return args[-1]
|
def temp_to_orig_section(temp_sec):
"""
Change a temp section into its original.
If it is its original it will return what was given.
:param temp_sec: temporary section created by 'create_temp_batch'
:return: orig section
"""
section = temp_sec
if temp_sec.startswith(('1', '2', '3', '4', '5', '6', '7', '8', '9')) and '~|~' in temp_sec:
# This is a temp section
section = temp_sec.split('~|~', 1)[1]
return section
|
def merge_dicts(*dicts, deleted_keys=[]):
"""Return a new dict from a list of dicts by repeated calls to update(). Keys in later
dicts will override those in earlier ones. *deleted_keys* is a list of keys which should be
deleted from the resulting dict.
"""
rv = {}
for d in dicts:
rv.update(d)
for k in deleted_keys:
del rv[k]
return rv
|
def merge_and_count_split_inv(B, C):
"""
>>> merge_and_count_split_inv([1, 3, 5], [2, 4, 6])
([1, 2, 3, 4, 5, 6], 3)
>>> merge_and_count_split_inv([1, 3, 5], [2, 4, 6, 7])
([1, 2, 3, 4, 5, 6, 7], 3)
>>> merge_and_count_split_inv([1, 3, 5, 6], [2, 4, 7])
([1, 2, 3, 4, 5, 6, 7], 5)
>>> merge_and_count_split_inv([1], [2])
([1, 2], 0)
>>> merge_and_count_split_inv([2], [1])
([1, 2], 1)
:param B:
:param C:
:return:
"""
merged = []
inv_counter = 0
item_b = None
item_c = None
while (B or C or item_b or item_c):
if not item_b and B:
item_b = B.pop(0)
if not item_c and C:
item_c = C.pop(0)
if item_b and item_c:
if item_b <= item_c:
merged.append(item_b)
item_b = None
else:
merged.append(item_c)
if item_b:
inv_counter += 1 + len(B)
item_c = None
else:
if item_b:
merged.append(item_b)
item_b = None
if item_c:
merged.append(item_c)
item_c = None
return merged, inv_counter
|
def info ():
"""
Check server status
"""
# Build response
return {
"success": True,
"message": "Aquila X is running healthy"
}, 200
|
def sanitize_validation(validators):
"""sanitize validation in the form xn-yn z"""
joined_bounds, letter = validators.split()
lower_bound, upper_bound = map(int, joined_bounds.split("-"))
return lower_bound, upper_bound, letter
|
def print_fortran_indexed(base, indices):
"""Print indexed objects according to the Fortran syntax.
By default, the multi-dimensional array format will be used.
"""
return base + (
'' if len(indices) == 0 else '({})'.format(', '.join(
i.index for i in indices
))
)
|
def R10_assembly(FMzul, Apmin, PG):
"""
R10 Determining the surface pressure Pmax
(Sec 5.5.4)
Assembly state
"""
# Assembly state
PMmax = min(FMzul / Apmin, PG) # (R10/1)
# Alternative safety verification
Sp = PG / PMmax # (R10/4)
#if Sp > 1.0 : print('Sp > {} --> PASS'.format(Sp))
#else: print('Sp < {} --> FAIL'.format(Sp))
#
return PMmax
#
|
def compute_n_steps(control_timestep, physics_timestep, tolerance=1e-8):
"""Returns the number of physics timesteps in a single control timestep.
Args:
control_timestep: Control time-step, should be an integer multiple of the
physics timestep.
physics_timestep: The time-step of the physics simulation.
tolerance: Optional tolerance value for checking if `physics_timestep`
divides `control_timestep`.
Returns:
The number of physics timesteps in a single control timestep.
Raises:
ValueError: If `control_timestep` is smaller than `physics_timestep` or if
`control_timestep` is not an integer multiple of `physics_timestep`.
"""
if control_timestep < physics_timestep:
raise ValueError(
'Control timestep ({}) cannot be smaller than physics timestep ({}).'.
format(control_timestep, physics_timestep))
if abs((control_timestep / physics_timestep - round(
control_timestep / physics_timestep))) > tolerance:
raise ValueError(
'Control timestep ({}) must be an integer multiple of physics timestep '
'({})'.format(control_timestep, physics_timestep))
return int(round(control_timestep / physics_timestep))
|
def byte_lengths(n_bytes, n_partitions):
"""Calculates evenly distributed byte reads for given file size.
Args:
n_bytes: int - total file size in bytes
n_partitions: int - number of file partitions
Returns:
iterable of ints
"""
chunk_size = n_bytes // n_partitions
byte_reads = [chunk_size] * n_partitions
for ix in range(n_bytes % n_partitions):
byte_reads[ix] += 1
return tuple(byte_reads)
|
def callback(fname, fcontents):
"""
The callback to apply to the file contents that we from HDFS.
Just prints the name of the file.
"""
print("Fname:", fname)
return fname, fcontents
|
def check_step_file(filename, steplist):
"""Checks file for existing data, returns number of runs left
Parameters
----------
filename : str
Name of file with data
steplist : list of int
List of different numbers of steps
Returns
-------
runs : dict
Dictionary with number of runs left for each step
"""
#checks file for existing data
#and returns number of runs left to do
#for each # of does in steplist
runs = {}
for step in steplist:
runs[step] = 0
if not 'cuda' in filename:
raise Exception(filename)
try:
with open(filename, 'r') as file:
lines = [line.strip() for line in file.readlines()]
for line in lines:
try:
vals = line.split(',')
if len(vals) == 2:
vals = [float(v) for v in vals]
runs[vals[0]] += 1
except:
pass
return runs
except:
return runs
|
def next_p2(num):
""" If num isn't a power of 2, will return the next higher power of two """
rval = 1
while (rval < num):
rval <<= 1
return rval
|
def major_version(v):
"""
Return the major version for the given version string.
"""
return v.split('.')[0]
|
def del_special(S):
"""
Replace verbatim white space lien endings and tabs (\\n, \\r, \\t) that
may exist as-is as literals in the extracted string by a space.
"""
return S.replace('\\r', ' ').replace('\\n', ' ').replace('\\t', ' ')
|
def dec_to_sex(dec, delimiter=':'):
"""Convert dec in decimal degrees to sexigesimal"""
if (dec >= 0):
hemisphere = '+'
else:
# Unicode minus sign - should be treated as non-breaking by browsers
hemisphere = '-'
dec *= -1
dec_deg = int(dec)
dec_mm = int((dec - dec_deg) * 60)
dec_ss = int(((dec - dec_deg) * 60 - dec_mm) * 60)
dec_f = int(((((dec - dec_deg) * 60 - dec_mm) * 60) - dec_ss) * 10)
return (hemisphere + '%02d' % dec_deg + delimiter + '%02d' % dec_mm + delimiter + '%02d' % dec_ss + '.' + '%01d' % dec_f)
|
def num_trace_events(data):
"""Returns the total number of traces captured
"""
return len(data["traceEvents"])
|
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
|
def get_bruised_limbs(life):
"""Returns list of bruised limbs."""
_bruised = []
for limb in life['body']:
if life['body'][limb]['bruised']:
_bruised.append(limb)
return _bruised
|
def get_sum_metrics(predictions, metrics = None):
""" Create a new object each time the function is called, by using a default arg to signal that no argument was provided
Do not use metrics = [] as it does not Create a new list each time the function is called instead it append to the list
generated at the first call """
if metrics is None:
metrics = []
for i in range(3):
""" this bug is due the late binding closure """
metrics.append(lambda x, i=i: x + i)
sum_metrics = 0
for metric in metrics:
sum_metrics += metric(predictions)
metrics = []
return sum_metrics
|
def ends_with_punctuation(value):
"""Does this end in punctuation? Use to decide if more is needed."""
last_char = value.strip()[-1]
return last_char in "?.!"
|
def get_grid_size(grid):
"""Return grid edge size."""
if not grid:
return 0
pos = grid.find('\n')
if pos < 0:
return 1
return pos
|
def remove_the_last_person(queue: list) -> str:
"""
:param queue: list - names in the queue.
:return: str - name that has been removed from the end of the queue.
"""
return queue.pop()
|
def is_chinese(target_str):
""" determine whether the word is Chinese
Args:
target_str (str): target string
"""
for ch in target_str:
if '\u4e00' <= ch <= '\u9fff':
return True
return False
|
def sort_bed_by_bamfile(bamfile, regions):
"""Orders a set of BED regions, such that processing matches
(as far as possible) the layout of the BAM file. This may be
used to ensure that extraction of regions occurs (close to)
linearly."""
if not regions:
return
references = bamfile.references
indices = dict(zip(references, range(len(references))))
def _by_bam_layout(region):
return (indices[region.contig], region.start, region.end)
regions.sort(key=_by_bam_layout)
|
def _get_name(data):
"""
Returns 'firstname lastname' or 'name'
"""
try:
return '{} {}'.format(data['properties']['first_name'],
data['properties']['last_name'])
except KeyError:
return data['properties'].get('name', '')
|
def remove_thousand_separator(int_as_str: str) -> str:
"""Removes thousand separator from a number stored as string."""
return int_as_str.replace(",", "")
|
def sched_prio(resources, time_in_queue=0):
"""
Weight the priority to prefer smaller resource requests.
As a task stays longer in the queue, increase priority.
Best priority is 0, worse increases to infinity.
Args:
resources (dict): resources dict
time_in_queue (float): the time this task has spent in the queue
Returns:
float: priority
"""
return max(0, sum(resources.values()) - time_in_queue/600)
|
def revert_datetime_to_long_string(dt):
"""
Turns a date/time into a long string as needed by midas code.
"""
return str(dt).replace("-", "").replace(" ", "").replace("T", "").replace(":", "")
|
def json_pointer(jsonpointer: str) -> str:
"""Replace escape characters in JSON pointer."""
return jsonpointer.replace("~0", "~").replace("~1", "/")
|
def get_current_state(state_vector):
""" Get the current state corresponding to the state probability vector.
:param state_vector: The state PMF vector.
:type state_vector: list(int)
:return: The current state.
:rtype: int,>=0
"""
return state_vector.index(1)
|
def check(wants, has):
"""
Check if a desired scope ``wants`` is part of an available scope ``has``.
Returns ``False`` if not, return ``True`` if yes.
:example:
If a list of scopes such as
::
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
SCOPES = (
(READ, 'read'),
(WRITE, 'write'),
(READ_WRITE, 'read+write'),
)
is defined, we can check if a given scope is part of another:
::
>>> from provider import scope
>>> scope.check(READ, READ)
True
>>> scope.check(WRITE, READ)
False
>>> scope.check(WRITE, WRITE)
True
>>> scope.check(READ, WRITE)
False
>>> scope.check(READ, READ_WRITE)
True
>>> scope.check(WRITE, READ_WRITE)
True
"""
if wants & has == 0:
return False
if wants & has < wants:
return False
return True
|
def get_contacts(contacts):
"""
Reformarts mvnx contacts
:param contacts:
:return: Contacts for all the four parts of a foot in the required dictionary format
"""
LeftFoot_Toe = []
RightFoot_Toe = []
LeftFoot_Heel = []
RightFoot_Heel = []
for i in range(len(contacts)):
LeftFoot_Heel.append(contacts[i]['LeftFoot_Heel'][0])
RightFoot_Heel.append(contacts[i]['RightFoot_Heel'][0])
LeftFoot_Toe.append(contacts[i]['LeftFoot_Toe'][0])
RightFoot_Toe.append(contacts[i]['RightFoot_Toe'][0])
new_dict = {
'left_heel':LeftFoot_Heel,
'left_toe': LeftFoot_Toe,
'right_toe':RightFoot_Toe,
'right_heel':RightFoot_Heel
}
return new_dict
|
def avoir_ind_courant(ligne):
"""
renvoie le nombre de case remplie dans la ligne motif
"""
ind_courant = 0
for case in ligne:
if case !="":
ind_courant+=1
return ind_courant
|
def get_node_map(node_set):
"""
Maps every node to an ID.
:param node_set: set of all nodes to be mapped.
:return: dict of original node index as key and the mapped ID as value.
"""
nodes = list(node_set)
nodes.sort()
node_id_map = {}
for i, n in enumerate(nodes):
node_id_map[n] = i
return node_id_map
|
def dict_popper(dicty, pop_target):
"""[pop pop_targets from dict dicty, cool names yeah?]
Args:
dicty ([dict]): [dict to pop keys]
pop_target ([list]): [list with keys to pop]
Returns:
[type]: [description]
"""
for item in dicty:
for col in pop_target:
item.pop(col, None)
for k, v in item.items():
if v == "nan":
item[k] = False
return dicty
|
def polynomial_3_integral(x0, x1, a, b, c, d):
"""Integral of polynomial order 3 where f(x) = a + b * x + c * x**2 + d * x**3.
"""
return a * (x1 - x0) \
+ b * (x1**2 - x0**2) / 2.0 \
+ c * (x1**3 - x0**3) / 3.0 \
+ d * (x1**4 - x0**4) / 4.0
|
def quick_sort_v2(li):
"""([list of int], int, int) => [list of int]
Quick sort: works by selecting a 'pivot' element from the array
and partitioning the other elements into two sub-arrays, according
to whether they are less than or greater than the pivot. The
sub-arrays are then sorted recursively.
This version will use the Hoare partition scheme, where the pivot
is calculated in the middle instead of at the end of the list.
"l" (for low) is the first element of the list "li", and "h" is the
last (for high).
"""
def partition(lst, low, high):
""" ([list of int], int, int) => int
Partitions the list "lst" so that every element greater than an
arbitrarily selected pivot (the element at index high) ends up
on the right of the pivot index, and every element smaller ends
up on the left.
Note: high is excluded.
"""
# pivot is middle item of the bracket [low, high)
pivot = lst[(high + low) // 2]
# counter for index of item to swap
i = low
j = high - 1
# the only exit condition is when i and j meet
while True:
# find a lst[i] out of place
while lst[i] < pivot:
i += 1
# find a lst[j] out of place
while lst[j] > pivot:
j -= 1
# go until i and j meet
if i >= j:
return j
# swap the out of place elements
lst[i], lst[j] = lst[j], lst[i]
def sorter(li, l, h):
""" ([list of int], int, int) => [list of int]
Driver for the recursive sort function.
"""
if l < h:
p = partition(li, l, h)
# sort the partition to the left
sorter(li, l, p)
# sort the partition to the right
sorter(li, p + 1, h)
return li
return sorter(li, 0, len(li))
|
def normalize_idp(idp):
"""
Normalizes the IDP definitions so that the outputs are consistent with the
parameters
- "enabled" (parameter) == "is_enabled" (SDK)
- "name" (parameter) == "id" (SDK)
"""
if idp is None:
return None
_idp = idp.to_dict()
_idp['enabled'] = idp['is_enabled']
_idp['name'] = idp['id']
return _idp
|
def _https(base_uri, *extra):
"""Combine URL components into an https URL"""
parts = [str(e) for e in extra]
str_parts = ''.join(parts)
str_base = str(base_uri)
if str_base.startswith("https://"):
return "{0}{1}".format(str_base, str_parts)
elif str_base.startswith("http://"):
return "{0}{1}".format(str_base.replace("http:","https:", 1), str_parts)
else:
return "https://{0}{1}".format(str_base, str_parts)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.