content
stringlengths 42
6.51k
|
---|
def getClues(guess, secretNum):
"""Returns a string with the pico, fermi, bagels clues for a guess
and secret number pair."""
if guess == secretNum:
return 'You got it!'
clues = []
for i in range(len(guess)):
if guess[i] == secretNum[i]:
# A correct digit is in the correct place.
clues.append('Fermi')
elif guess[i] in secretNum:
# A correct digit is in the incorrect place.
clues.append('Pico')
if len(clues) == 0:
return 'Bagels' # There are no correct digits at all.
else:
# Sort the clues into alphabetical order so their original order
# doesn't give information away.
clues.sort()
# Make a single string from the list of string clues.
return ' '.join(clues)
|
def convert_bytes(num):
"""Convert bytes to MB.... GB... etc."""
for x in ["bytes", "KB", "MB", "GB", "TB"]:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0
|
def partition(array, pivot):
"""Selection partition."""
i = -1
j = 0
while j < len(array) - 1:
if array[j] == pivot:
array[-1], array[j] = array[j], array[-1]
continue
elif array[j] < pivot:
i += 1
array[i], array[j] = array[j], array[i]
j += 1
array[-1], array[i + 1] = array[i + 1], array[-1]
return i + 1
|
def getEditDistance(str1, str2):
"""Return the edit distance between two strings.
>>> getEditDistance("abc", "abcd")
1
>>> getEditDistance("abc", "aacd")
2
If one of the strings is empty, it will return the length of the other string
>>> getEditDistance("abc", "")
3
The order of strings is not important, it will return the same output when strings are swapped.
>>> getEditDistance("rice", "raise")
2
>>> getEditDistance("raise", "rice")
2
"""
# if one of the strings is empty, the edit distance equals to the length of the other string
# as all we need to do is insert all the characters from one string to other
if len(str1)==0:
return len(str2)
if len(str2)==0:
return len(str1)
# neither one is empty
# we will use wagner-fischer algorithm
# matrix is one character bigger for each string, because we will start from 0
# matrix[y+1][x+1] will hold the Levenshtein distance between first y chars of str1
# and the first x chars of str2
matrix = [ [i for k in range(len(str2)+1)] for i in range(len(str1)+1)]
# we want to start by putting the numbers 0 to length of the string in the first column and row
for i in range(len(str2)+1):
matrix[0][i]=i
# as the difference between any string and an empty string is the length of that string,
# we start from 0 (no difference between two empty strings) and go up to its length
for i in range(len(str2)):
# now that we completed the first row and column of our matrix,
# proceed to process the rest
for j in range(len(str1)):
if str2[i] == str1[j]:
matrix[j+1][i+1] = matrix[j][i] # no difference in this character, edit distance will equal to previous
else:
# this char is different, get the lowest edit distance to acquire the previous string and add one
matrix[j+1][i+1] = min(matrix[j][i+1]+1,matrix[j+1][i]+1,matrix[j][i]+1)
# as stated earlier, matrix[y+1][x+1] will hold the Levenshtein distance between first y chars of str1
# and the first x chars of str2. So the latest cell will hold the final edit distance
return matrix[-1][-1]
|
def tc_to_int(value):
""" Convert an 8-bit word of 2's complement into an int. """
# Python has interpreted the value as an unsigned int.
assert 0 <= value <= 0xFF
sign = (value & (1 << 7))
if sign != 0:
value -= (1 << 8)
return value
|
def to_css_length(l):
"""
Return the standard length string of css.
It's compatible with number values in old versions.
:param l: source css length.
:return: A string.
"""
if isinstance(l, (int, float)):
return '{}px'.format(l)
else:
return l
|
def get_prefixed(field_dict, prefix):
"""
The inverse of add_prefix.
Returns all prefixed elements of a dict with the prefices stripped.
"""
prefix_len = len(prefix) + 1
return {
k[prefix_len:]: v
for k, v in field_dict.items()
if k.startswith(prefix)
}
|
def serialize_tipo_participacion(tipo_participacion):
"""
$ref: #/components/schemas/tipoParticipacion
"""
if tipo_participacion:
return {
"clave": tipo_participacion.codigo,
"valor": tipo_participacion.tipo_persona
}
return{"clave": "OTRO","valor": "No aplica"}
|
def solve_dependencies(dependencies, all_members=None):
"""Solve a dependency graph.
Parameters
----------
dependencies : dict
For each key, the value is an iterable indicating its dependencies.
all_members : iterable, optional
List of all keys in the graph.
Useful to guarantee that all keys will be in the result even
if they are disconnected from the graph.
(Default value: empty)
Returns
-------
list of sets
Each set contains tasks that depend only on the tasks
in the previous set in the list.
"""
d = dict((key, set(value)) for key, value in dependencies.items())
if all_members:
d.update({key: set() for key in all_members if key not in d})
r = []
while d:
# values not in keys (items without dep)
t = set(i for v in d.values() for i in v) - set(d.keys())
# and keys without value (items without dep)
t.update(k for k, v in d.items() if not v)
# can be done right away
r.append(t)
# and cleaned up
d = dict(((k, v - t) for k, v in d.items() if v))
return r
|
def bb(s):
"""
Use a stack to keep track of the brackets, yo!
Runtime: O(n)
"""
brackets = []
matching = {")":"(", "]":"[", "}":"{"}
for p in s:
if p in matching.values():
brackets.append(p)
else:
try:
top = brackets[-1]
if top == matching[p]:
brackets.pop()
except:
return False
return not brackets
|
def is_prefixed_with(string, prefix):
"""
Checks if the given string is prefixed with prefix
Parameters:
-----------------------------------
string: str
An input word / sub-word
prefix: str
A prefix to check in the word / sub-word
Returns:
-----------------------------------
bool : True if prefix, else False
"""
return string.find(prefix) == 0
|
def convert_string_list(string_list):
"""
Converts a list of strings (e.g. ["3", "5", "6"]) to a list of integers.
In: list of strings
Out: list of integers
"""
int_list = []
for string in string_list:
int_list.append(int(string))
return int_list
|
def make_comment_body(comment_text):
"""Build body of the add issue comment request"""
return {
"body": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
"text": comment_text,
"type": "text"
}
]
}
]
}
}
|
def is_occupied(index_i, index_j, tile_arrangement):
"""
Determines whether the tile at (`index_i`, `index_j`) is occupied.
Args:
index_i (int):
Row index.
index_j (int):
Column index.
tile_arrangement (List[List[str]]):
Arrangement of the tiles as a 2D grid.
Returns:
bool:
Whether or not the tile is occupied.
"""
# Validate inputs
if not (0 <= index_i <= len(tile_arrangement) - 1):
raise IndexError
if not (0 <= index_j <= len(tile_arrangement[0]) - 1):
raise IndexError
# Check occupancy
if tile_arrangement[index_i][index_j] == "#":
return True
else:
return False
|
def _all_done(fs, download_results):
"""
Checks if all futures are ready or done
"""
if download_results:
return all([f.done for f in fs])
else:
return all([f.success or f.done for f in fs])
|
def coalesce(*args):
""":yaql:coalesce
Returns the first predicate which evaluates to non-null value. Returns null
if no arguments are provided or if all of them are null.
:signature: coalesce([args])
:arg [args]: input arguments
:argType [args]: chain of any types
:returnType: any
.. code::
yaql> coalesce(null)
null
yaql> coalesce(null, [1, 2, 3][0], "abc")
1
yaql> coalesce(null, false, 1)
false
"""
for f in args:
res = f()
if res is not None:
return res
return None
|
def _create_network_specification(fc_layers):
"""Creates a tensorforce network specification based on the layer specification given in self.model_config"""
result= []
layer_sizes = fc_layers
for layer_size in layer_sizes:
result.append(dict(type='dense', size=layer_size, activation='relu'))
return result
|
def get_ncor(gold_chunks, guess_chunks):
"""Calculate the number of correctly overlapping chunks in the two sets.
:param gold_chunks:
:param guess_chunks:
:return:
"""
return set(x for x in list(set(gold_chunks) & set(guess_chunks)))
|
def _get_lengthunit_scaling(length_unit):
"""MNE expects distance in m, return required scaling."""
scalings = {'m': 1, 'cm': 100, 'mm': 1000}
if length_unit in scalings:
return scalings[length_unit]
else:
raise RuntimeError(f'The length unit {length_unit} is not supported '
'by MNE. Please report this error as a GitHub '
'issue to inform the developers.')
|
def _read_octal_mode_option(name, value, default):
"""
Read an integer or list of integer configuration option.
Args:
name (str): Name of option
value (str): Value of option from the configuration file or on the CLI. Its value can be any of:
- 'yes', 'y', 'true' (case-insensitive)
The maximum mode value is then set to self.DEFAULT_MAX_MODE
- a single octal or decimal integer
The maximum mode value is then set to that integer value
- a comma-separated list of integers (octal or decimal)
The allowed mode values are then those found in the list
- anything else will count as a falseful value
default (int,list): Default value for option if set to one of
('y', 'yes', 'true') in the configuration file or on the CLI
Returns:
A single integer or a (possibly empty) list of integers
Raises:
ValueError: if the value of the option is not valid
"""
def _str_to_int(arg):
try:
return int(arg, 8)
except ValueError:
return int(arg)
value = value.lower()
modes = [mode.strip() for mode in value.split(',')]
if len(modes) > 1:
# Lists of allowed modes
try:
allowed_modes = [_str_to_int(mode) for mode in modes if mode]
except ValueError as error:
raise ValueError(f'Unable to convert {modes} elements to integers!') from error
else:
if not allowed_modes:
raise ValueError(f'Calculated empty value for `{name}`!')
return allowed_modes
elif modes and modes[0]:
# Single values (ie. max allowed value for mode)
try:
return _str_to_int(value)
except ValueError as error:
if value in ('y', 'yes', 'true'):
return default
if value in ('n', 'no', 'false'):
return None
raise ValueError(f'Invalid value for `{name}`: {value}!') from error
else:
raise ValueError(f'Invalid value for `{name}`: {value}!')
|
def parse_packageset(packageset):
"""
Get "input" or "output" packages and their repositories from each PES event.
:return: A dictionary with packages in format {<pkg_name>: <repository>}
"""
return {p['name']: p['repository'].lower() for p in packageset.get('package', [])}
|
def _shorthand_from_matrix(matrix):
"""Convert from transformation matrix to PDF shorthand."""
a, b = matrix[0][0], matrix[0][1]
c, d = matrix[1][0], matrix[1][1]
e, f = matrix[2][0], matrix[2][1]
return tuple(map(float, (a, b, c, d, e, f)))
|
def shrink(a, diff=1.1, mode='g'):
"""
l - linear progression
g - geom progression
"""
res = [0]
prev = a[0]
for i, x in enumerate(a):
if prev != 0:
if mode == 'g':
if x >= prev and abs(x / prev) < diff:
continue
if x < prev and abs(prev / x) < diff:
continue
else:
if abs(x - prev) < diff * prev:
continue
res.append(i)
prev = x
return res
|
def do_not_inspect(v):
"""Returns True if this value should not be inspected due to potential bugs."""
# https://github.com/Microsoft/python-language-server/issues/740
# https://github.com/cython/cython/issues/1470
if type(v).__name__ != "fused_cython_function":
return False
# If a fused function has __defaults__, then attempting to access
# __kwdefaults__ will fail if generated before cython 0.29.6.
return bool(getattr(v, "__defaults__", False))
|
def is_number(s):
"""Returns True if the argument can be made a float."""
try:
float(s)
return True
except:
return False
|
def scale_tors_pot(spc_mod_dct_i, to_scale):
""" determine if we need to scale the potential
"""
onedhr_model = bool('1dhr' in spc_mod_dct_i['tors']['mod'])
return bool(onedhr_model and to_scale)
|
def pickChromosomes(selection='A'):
"""
Selects the chromosomes you want to overlap.
:param selection: A(autosomes), AS (Auto+Sex), or ASM (Auto+Sex+M)
:return: chrList
"""
chrList = [
'1', '2', '3', '4', '5',
'6', '7', '8', '9', '10',
'11', '12', '13', '14', '15',
'16', '17', '18', '19', '20',
'21', '22'
]
if selection == "AS":
chrList.append("x")
chrList.append("y")
if selection == "ASM":
chrList.append("x")
chrList.append("y")
chrList.append("m")
return chrList
|
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
|
def plotSpheres(ax,spheres,style='surface'):
"""
Takes array of Sphere objects ands plots them on a 3D axis
Parameters
----------
ax : matplotlib.Axes.axes instance
The 3D axes instance to plot the sphere onto
sphere : list of Sphere instances
List of Spheres to plot
style : str
Can either specify style as "surface" or "wireframe"
Defaults to "surface"
Returns
-------
children : list of mpl_toolkits.mplot3d.art3d.Poly3DCollection objects
"""
children = []
if style=='surface':
for sphere in spheres:
artist=ax.plot_surface(sphere.x,sphere.y,sphere.z,color=sphere.color,
alpha=sphere.alpha,label=sphere.label)
#put in some code to fix error described by
#https://stackoverflow.com/questions/55531760/is-there-a-way-to-label-multiple-3d-surfaces-in-matplotlib/55534939
artist._facecolors2d = artist._facecolor3d
artist._edgecolors2d = artist._edgecolor3d
#add artist to list of children to return
children.append(artist)
return children
elif style=='wireframe':
for sphere in spheres:
artist=ax.plot_wireframe(sphere.x,sphere.y,sphere.z,color=sphere.color,
alpha=sphere.alpha,label=sphere.label)
#put in some code to fix error described by
#https://stackoverflow.com/questions/55531760/is-there-a-way-to-label-multiple-3d-surfaces-in-matplotlib/55534939
artist._facecolors2d = artist._facecolor3d
artist._edgecolors2d = artist._edgecolor3d
#add artist to list of children to return
children.append(artist)
return children
else:
print("WARNING: invalid style for plotSpheres(), valid styles are\
'surface' or 'wireframe'")
return None
|
def view3d_find(areas, return_area=False):
""" Discovers a viewport manually for operations that require it (such as loopcutting) """
for area in areas:
if area.type == 'VIEW_3D':
v3d = area.spaces[0]
rv3d = v3d.region_3d
for region in area.regions:
if region.type == 'WINDOW':
if return_area: return region, rv3d, v3d, area
return region, rv3d, v3d
return None, None
|
def _split(y, start, end, n):
"""
Recursively find split points to resolve the convex hull.
Returns a list of split points between start and end.
"""
if (end-start <= 1): # special case - segment has only one data point in it
return [start,end]
if n > 100: # escape for max recursion [ reports and stops weird crashes occasionally ]
print("Error - recursion depth exceeded for segment", start, " - ", end )
print("Problematic Y values:", y[start:end])
print("All Y values:", y)
assert False
# compute gradient
dy = (y[end] - y[start]) / (end - start)
# find max of trend-removed deltas
midx = 0
mv = 0 # set 0 here as we want to ignore negative deltas
for i in range(start, end + 1):
delta = y[i] - (y[start] + dy * (i - start)) # deviation from trend
if delta > mv:
mv = delta
midx = i
if mv <= 1e-10: # we need a tolerance to avoid floating point errors
return [start, end] # this is a complete segment!
else:
return _split(y, start, midx, n+1)[:-1] + _split(y, midx, end, n+1)
|
def safe_stringify(value):
"""
Converts incoming value to a unicode string. Convert bytes by decoding,
anything else has __str__ called.
Strings are checked to avoid duplications
"""
if isinstance(value, str):
return value
if isinstance(value, bytes):
return value.decode("utf-8")
return str(value)
|
def sort_by_message(results):
"""Sort `results` by the message_id of the error messages."""
return sorted(results, key=lambda r: r['message_id'])
|
def write_feed_source(left, center, right, max_width):
"""
Generates a graphviz digraph source description using HTML-like labels with the specified styling
:param left: A string
:param center: A string
:param right: A string
:param max_width: A float specifying the maximum width to draw the digraph in inches
:return: A graphviz digraph source
"""
feed_string = 'digraph {{\n\tgraph [rankdir=LR size={}];'.format(max_width)
feed_string += '\n\tnode [fontsize=12 width=0.35 shape=plaintext];'
feed_string += '\n\tfeed [label=< <table border="0" cellborder="1" cellspacing="0" cellpadding="8"><tr>'
feed_string += '<td>{}</td>'.format(left)
feed_string += '<td width="16">{}</td>'.format(center)
feed_string += '<td>{}</td>'.format(right)
feed_string += '</tr></table>>];\n}'
return feed_string
|
def get_allocated_size(tw_vectors):
"""
:param tw_vectors: See
``allmydata.interfaces.TestAndWriteVectorsForShares``.
:return int: The largest position ``tw_vectors`` writes in any share.
"""
return max(
list(
max(offset + len(s) for (offset, s) in data)
for (sharenum, (test, data, new_length))
in tw_vectors.items()
if data
),
)
|
def compile_ingredients(dishes):
"""
:param dishes: list of dish ingredient sets
:return: set
This function should return a `set` of all ingredients from all listed dishes.
"""
compiled = set()
for dish in dishes:
compiled = compiled | dish
return compiled
|
def scale_and_trim_boxes(boxes, image_width, image_height):
"""
Take care of scaling and trimming the boxes output from model, into something actual image can handle.
:param boxes: Raw boxes output from tflite interpreter.
:param image_width: Width of actual image.
:param image_height: Height of actual image.
:return: Scaled and trimmed boxes of coordinates.
"""
# Just pure magic to handle the scaling.
# Model's coordinates is not aligned well with the cv2 image handling coordinates.
# After many trials, this is the correct version, just use this and don't question.
scaled_boxes = []
max_dimension = max(image_width, image_height)
for box in boxes:
x_min = max(0, int(box[1] * max_dimension))
y_min = max(0, int(box[0] * max_dimension))
x_max = min(image_width, int(box[3] * max_dimension))
y_max = min(image_height, int(box[2] * max_dimension))
scaled_boxes.append([x_min, y_min, x_max, y_max])
return scaled_boxes
|
def get_column(data, column_index):
"""
Gets a column of data from the given data.
:param data: The data from the CSV file.
:param column_index: The column to copy.
:return: The column of data (as a list).
"""
return [row[column_index] for row in data]
|
def plus(ref):
"""Return the pathname of the KOS root directory."""
res = ref+ref
return res
|
def calc_angular_radius(km):
"""calculate the angular radius for a given distance in kilometers"""
earth_radius = 6371.0 # in km
return km / earth_radius
|
def rgba_to_htmlcolors(colors):
"""
:param colors: a 1d list of length 20 floats in range [0, 1].
return a 1d list of 5 html colors of the format "#RRGGBBAA".
"""
hexcolors = [("{:02x}".format(int(255 * x))).upper() for x in colors]
return ["#{}{}{}{}".format(*hexcolors[4*i: 4*i+4]) for i in range(5)]
|
def v1_tail(sequence, n):
"""Return the last n items of given sequence.
This works for non-lists but it doesn't when the given n is 0. This is
because sequence[-0:] is the same thing as sequence[0:] and that will
return the entire sequence (which is likely not 0 items)
"""
return list(sequence[-n:])
|
def get_single_comment_response(status_code):
"""Helper to return a single comment with status_code."""
if status_code == 304:
return (b'', 304, {'content-type': 'application/json'})
return (b'{"user": {"login": "miketaylr","avatar_url": "https://avatars1.githubusercontent.com/u/67283?v=4"},"created_at": "2016-07-28T14:41:43Z","body_html": "<p>test</p>"}', # noqa
status_code, {'content-type': 'application/json'})
|
def left(i:int):
"""
Return the Left child element's index of the request element
Keyword Arguments
i:int: index of requested element
Return
int: Left child's index of requested element
"""
return (i * 2) + 1
|
def mu2G(mu, E):
"""compute shear modulus from poisson ratio mu and Youngs modulus E
"""
return E/(2*(1+mu))
|
def line_count_file(file_path, flags=None):
""" Counts lines for given file in file_name """
try:
count = 0
with open(file_path) as current_file:
for line in current_file:
if line.strip() == "" and flags != None and \
"--noempty" in flags:
continue
count += 1
return count
except IOError:
return -1
|
def get_applied_thresholds_text(threshs_d: dict) -> tuple:
"""
Parameters
----------
threshs_d : dict
Thresholds configs
Returns
-------
names : list
Name for the threshold
thresh_sam : int
Samples threshold
thresh_feat : int
Features threshold
"""
names = []
if 'names' in threshs_d:
names = threshs_d['names']
thresh_sam = 0
if 'samples' in threshs_d:
thresh_sam = threshs_d['samples']
thresh_feat = 0
if 'features' in threshs_d:
thresh_feat = threshs_d['features']
return names, thresh_sam, thresh_feat
|
def binary_search(L, v):
""" (list, object) -> int
Precondition: L is sorted from smallest to largest, and
all the items in L can be compared to v.
Return the index of the first occurrence of v in L, or
return -1 if v is not in L.
>>> binary_search([2, 3, 5, 7], 2)
0
>>> binary_search([2, 3, 5, 5], 5)
2
>>> binary_search([2, 3, 5, 7], 8)
-1
"""
b = 0
e = len(L) - 1
while b <= e:
m = (b + e) // 2
if L[m] < v:
b = m + 1
else:
e = m - 1
if b == len(L) or L[b] != v:
return -1
else:
return b
|
def lon_to_0360(lon):
"""Convert longitude(s) to be within [0, 360).
The Eastern hemisphere corresponds to 0 <= lon + (n*360) < 180, and the
Western Hemisphere corresponds to 180 <= lon + (n*360) < 360, where 'n' is
any integer (positive, negative, or zero).
Parameters
----------
lon : scalar or sequence of scalars
One or more longitude values to be converted to lie in the [0, 360)
range
Returns
-------
If ``lon`` is a scalar, then a scalar of the same type in the range [0,
360). If ``lon`` is array-like, then an array-like of the same type
with each element a scalar in the range [0, 360).
"""
quotient = lon // 360
return lon - quotient*360
|
def get_all_strings(obj):
"""Returns all strings in obj
Parameters
----------
obj : string, tuple, list, or dict
Object (leaves must be strings, regardless of type)
Returns
-------
set
All strings in obj leaves.
"""
ret = set()
if type(obj) in [str, bytes]:
ret.add(obj)
elif type(obj) in [tuple, list, dict]:
if type(obj) == dict:
obj = obj.values()
k = [get_all_strings(x) for x in obj]
k = [x for x in k if x]
for x in k:
ret = ret.union(x)
return set([x for x in ret if x])
|
def _find_size(sysval, vecval):
"""Utility function to find the size of a system parameter
If both parameters are not None, they must be consistent.
"""
if hasattr(vecval, '__len__'):
if sysval is not None and sysval != len(vecval):
raise ValueError("Inconsistend information to determine size "
"of system component")
return len(vecval)
# None or 0, which is a valid value for "a (sysval, ) vector of zeros".
if not vecval:
return 0 if sysval is None else sysval
elif sysval == 1:
# (1, scalar) is also a valid combination from legacy code
return 1
raise ValueError("Can't determine size of system component.")
|
def doesnotcontain(pointlist, needle):
"""Returns true if no point in point list has same coords as needle"""
for point in pointlist:
if point.is_point(needle):
return False
return True
|
def format_match_string(marked_chr_list):
"""
Formats list of marked characters as a string.
"""
chr_list = []
mark_prev = False
for chr, mark in marked_chr_list:
if mark != mark_prev:
chr_list.append('(' if mark else ')')
chr_list.append(chr)
mark_prev = mark
if mark_prev:
chr_list.append(')')
return ''.join(chr_list)
|
def poly(x, *coefs):
"""
f(x) = a * x + b * x**2 + c * x**3 + ...
*args = (x, a, b)
"""
if len(coefs) == 0:
raise Exception(
"you've not provided any coefficients")
result = x * 0
for power, c in enumerate(coefs):
result += c * (x**(power + 1))
return result
print(args)
|
def offset(edge_list: list) -> list:
"""offset edge ordering
Args:
edge_list (list): list of tuples defining edges
Returns:
new_l: offset list of tuples defining edges
"""
new_l = [(edge[0] - 1, edge[1] - 1, edge[-1])
for edge in edge_list]
return new_l
|
def flatten_list(node):
"""
List of expressions may be nested in groups of 32 and 1024
items. flatten that out and return the list
"""
flat_elems = []
for elem in node:
if elem == 'expr1024':
for subelem in elem:
assert subelem == 'expr32'
for subsubelem in subelem:
flat_elems.append(subsubelem)
elif elem == 'expr32':
for subelem in elem:
assert subelem == 'expr'
flat_elems.append(subelem)
else:
flat_elems.append(elem)
pass
pass
return flat_elems
|
def example4(S):
"""Return the sum of the prefix sums of sequence S."""
n = len(S)
prefix = 0
total = 0
for j in range(n):
prefix += S[j]
total += prefix
return total
|
def make_url_path_regex(*path):
"""Get a regex of the form ^/foo/bar/baz/?$ for a path (foo, bar, baz)."""
path = [x.strip("/") for x in path if x] # Filter out falsy components.
return r"^/%s/?$" % "/".join(path)
|
def autolinks_simple(url):
"""
it automatically converts the url to link,
image, video or audio tag
"""
u_url=url.lower()
if '@' in url and not '://' in url:
return '<a href="mailto:%s">%s</a>' % (url, url)
elif u_url.endswith(('.jpg','.jpeg','.gif','.png')):
return '<img src="%s" controls />' % url
elif u_url.endswith(('.mp4','.mpeg','.mov','.ogv')):
return '<video src="%s" controls></video>' % url
elif u_url.endswith(('.mp3','.wav','.ogg')):
return '<audio src="%s" controls></audio>' % url
return '<a href="%s">%s</a>' % (url,url)
|
def remove_whitespace(x):
"""
Helper function to remove any blank space from a string
x: a string
"""
try:
# Remove spaces inside of the string
x = "".join(x.split())
except:
pass
return x
|
def update_deep(dictionary: dict, path_update: dict) -> dict:
"""
Update the main metadata dictionary with the new dictionary.
"""
k = list(path_update.keys())[0]
v = list(path_update.values())[0]
if k not in dictionary.keys():
dictionary[k] = v
else:
key_next = list(path_update[k].keys())[0]
if key_next in dictionary[k].keys():
dictionary[k] = update_deep(dictionary.get(k, {}), v)
else:
dictionary[k].update(v)
return dictionary
|
def IsRegional(location):
"""Returns True if the location string is a GCP region."""
return len(location.split('-')) == 2
|
def string_to_list(s):
"""Splits the input string by whitespace, returning a list of non-whitespace components
Parameters
----------
s : string
String to split
Returns
-------
list
Non-whitespace string chunks
"""
return list(filter(lambda x: x, s.strip().split(' ')))
|
def generate_discord_markdown_string(lines):
"""
Wraps a list of message into a discord markdown block
:param [str] lines:
:return: The wrapped string
:rtype: str
"""
output = ["```markdown"] + lines + ["```"]
return "\n".join(output)
|
def sum_of_integers_in_inclusive_range(a: int, b: int) -> int:
"""
Returns the sum of all integers in the range ``[a, b]``, i.e. from ``a`` to
``b`` inclusive.
See
- https://math.stackexchange.com/questions/1842152/finding-the-sum-of-numbers-between-any-two-given-numbers
""" # noqa
return int((b - a + 1) * (a + b) / 2)
|
def _translate(num_time):
"""Translate number time to str time"""
minutes, remain_time = num_time // 60, num_time % 60
str_minute, str_second = map(str, (round(minutes), round(remain_time, 2)))
str_second = (str_second.split('.')[0].rjust(2, '0'), str_second.split('.')[1].ljust(2, '0'))
str_time = str_minute.rjust(2, '0') + f':{str_second[0]}.{str_second[1]}'
return str_time
|
def strip_entry_value(entry_value):
"""Strip white space from a string or list of strings
:param entry_value: value to strip spaces from
:return: value minus the leading and trailing spaces
"""
if isinstance(entry_value, list):
new_list = []
for value in entry_value:
new_list.append(value.strip())
return ' '.join(new_list)
if isinstance(entry_value, str):
return entry_value.strip()
|
def update_harmony_memory(considered_harmony, considered_fitness,harmony_memory):
"""
Update the harmony memory if necessary with the given harmony. If the given harmony is better than the worst
harmony in memory, replace it. This function doesn't allow duplicate harmonies in memory.
"""
if (considered_harmony, considered_fitness) not in harmony_memory:
worst_index = None
worst_fitness = float('+inf')
for i, (harmony, fitness) in enumerate(harmony_memory):
if fitness < worst_fitness:
worst_index = i
worst_fitness = fitness
if considered_fitness > worst_fitness:
harmony_memory[worst_index] = (considered_harmony, considered_fitness)
return harmony_memory
|
def UdJH_to_F0F2F4(Ud,JH):
"""
Given :math:`U_d` and :math:`J_H`, return :math:`F_0`, :math:`F_2` and :math:`F_4`.
Parameters
----------
Ud : float
Coulomb interaction :math:`U_d`.
JH : float
Hund's coupling :math:`J_H`.
Returns
-------
F0 : float
Slater integral :math:`F_0`.
F2 : float
Slater integral :math:`F_2`.
F4 : float
Slater integral :math:`F_4`.
"""
F0=Ud
F2=14/1.625 * JH
F4=0.625*F2
return F0, F2, F4
|
def is_unique_with_no_extra_space(s: str) -> bool:
"""
Time: O(n log n)
Space: O(1)
"""
if len(s) == 1:
return True
s = "".join(sorted(s))
for char in s:
begin = 0
end = len(s) - 1
while begin < end:
middle = begin + (end - begin) // 2
if s[middle] == char:
if middle >= 1 and s[middle - 1] == char:
return False
if middle <= len(s) - 2 and s[middle + 1] == char:
return False
break
elif s[middle] > char:
begin = middle + 1
else:
end = middle - 1
return True
|
def _letter_map(word):
"""Creates a map of letter use in a word.
Args:
word: a string to create a letter map from
Returns:
a dictionary of {letter: integer count of letter in word}
"""
lmap = {}
for letter in word:
try:
lmap[letter] += 1
except KeyError:
lmap[letter] = 1
return lmap
|
def get_item_properties(item, fields, mixed_case_fields=None, formatters=None):
"""Return a tuple containing the item properties.
:param item: a single item resource (e.g. Server, Project, etc)
:param fields: tuple of strings with the desired field names
:param mixed_case_fields: tuple of field names to preserve case
:param formatters: dictionary mapping field names to callables
to format the values
"""
if mixed_case_fields is None:
mixed_case_fields = []
if formatters is None:
formatters = {}
row = []
for field in fields:
if field in mixed_case_fields:
field_name = field.replace(' ', '_')
else:
field_name = field.lower().replace(' ', '_')
data = getattr(item, field_name, '')
if field in formatters and data is not None:
row.append(formatters[field](data))
else:
row.append(data)
return tuple(row)
|
def cut_string(s, length=100):
"""Truncates a string for a given length.
:param s: string to truncate
:param length: amount of characters to truncate to
:return: string containing given length of characters
"""
if 0 <= length < len(s):
return "%s..." % s[:length]
return s
|
def handle_name(name):
""" To remove the list of characters invalid in name of file"""
name = name.replace(":", "")
name = name.replace("#", "")
name = name.replace("<", "")
name = name.replace(">", "")
name = name.replace("$", "")
name = name.replace("+", "")
name = name.replace("!", "")
name = name.replace(":", "")
name = name.replace("`", "")
name = name.replace("&", "")
name = name.replace("'", "")
name = name.replace("\"", "")
name = name.replace("|", "")
name = name.replace("*", "")
name = name.replace(":", "")
name = name.replace("/", "")
name = name.replace("\\", "")
name = name.replace("@", "")
name = name.replace("=", "")
name = name.replace("{", "")
name = name.replace("}", "")
name = name.replace("?", "")
name = name.replace("%", "")
return name
|
def _best_straight_from_sorted_distinct_values(sorted_distinct_values):
"""
:param sorted_distinct_values: ([int])
:return: (int) best straight or 0 if none
"""
if len(set(sorted_distinct_values)) != len(sorted_distinct_values):
raise Exception(
f'Input to _best_straight_from_sorted_distinct_values '
f'must be a sorted list of distinct values'
)
if len(sorted_distinct_values) == 5:
max_value = max(sorted_distinct_values)
is_straight = (
# we make a straight if there are 5 distinct values
len(sorted_distinct_values) == 5 and
# and the top value minus the bottom value is equal to 4
max_value - min(sorted_distinct_values) == 4
)
return max_value if is_straight else 0
elif len(sorted_distinct_values) == 6:
return max(
# recursively call for ace-low straights
_best_straight_from_sorted_distinct_values(sorted_distinct_values[:-1]),
# recursively call for ace-high straights
_best_straight_from_sorted_distinct_values(sorted_distinct_values[1:])
)
# otherwise, there's no straight
return 0
|
def translation(x,N,sign_ptr,args):
""" works for all system sizes N. """
shift = args[0] # translate state by shift sites
period = N # periodicity/cyclicity of translation
xmax = args[1]
#
l = (shift+period)%period
x1 = (x >> (period - l))
x2 = ((x << l) & xmax)
#
return (x2 | x1)
|
def profile_photo(request):
"""Social template context processors"""
context_extras = {}
if hasattr(request, 'facebook'):
context_extras = {
'social': {
'profile_photo': request.facebook.profile_url()
}
}
return context_extras
|
def sort_preserve_order(sequence):
"""Return a set with the original order of elements preserved.
credit: https://www.peterbe.com/plog/uniqifiers-benchmark
"""
seen = set() # Create an empty set
seen_add = seen.add # Resolve once instead of per-iteration
return [x for x in sequence if not (x in seen or seen_add(x))]
|
def format_pars_listing(pars):
"""Returns a formated list of pars.
Args:
pars (list): A list of PAR objects.
Returns:
The formated list as string
"""
import re
import math
out = ""
i = 1
for p in pars:
# Shorten to 30 chars max, remove linebreaks
name = re.sub(r'[\n\r]', ' ',
p.name[:28] + '..'
if len(p.name) > 30
else p.name)
obj_name = re.sub(r'[\n\r]', ' ',
p.object_name[:28] + '..'
if len(p.object_name) > 30
else p.object_name)
time_cr = f"{p.time_created:%Y-%m-%d %H:%M}" \
if p.time_created is not None else ""
time_ex = f"{p.time_expires:%Y-%m-%d %H:%M}" \
if p.time_expires is not None else ""
out += (f"{i:>4} {name:30} {obj_name:30} {time_cr:16} {time_ex:16}\n")
i += 1
return out
|
def cns_dist_restraint(resid_i, atom_i, resid_j, atom_j,
dist, lower, upper, weight=None,
comment=None):
"""
Create a CNS distance restraint string
Parameters
----------
resid_i : int
Index of first residue
atom_i : str
Name of selected atom in first residue
resid_j : int
Index of second residue
atom_j : str
Name of selected atom in second residue
dist : float
Restrain distance between residues to this value
lower : float
Lower bound delta on distance
upper : float
Upper bound delta on distance
weight : float, optional (default: None)
Weight for distance restraint
comment : str, optional (default: None)
Print comment at the end of restraint line
Returns
-------
r : str
Distance restraint
"""
if weight is not None:
weight_str = "weight {} ".format(weight)
else:
weight_str = ""
if comment is not None:
comment_str = "! {}".format(comment)
else:
comment_str = ""
r = (
"assign (resid {} and name {}) (resid {} and name {}) "
"{} {} {} {}{}".format(
resid_i, atom_i, resid_j, atom_j, dist, lower, upper,
weight_str, comment_str
)
)
return r
|
def plugins_to_dict(string: str) -> dict:
"""Convers a plugins string into a dictionary."""
try:
mod, plugins = string.split(': ')
except ValueError: # No plugins.
return {}
return {mod: plugins.split('; ')}
|
def product_3x3_vector3(matrix,vector):
"""mulipli le vector 3 par une matrice care de 3"""
x = matrix[0][0]*vector[0] + matrix[1][0]*vector[1] + matrix[2][0]*vector[2]
y = matrix[0][1]*vector[0] + matrix[1][1]*vector[1] + matrix[2][1]*vector[2]
z = matrix[0][2]*vector[0] + matrix[1][2]*vector[1] + matrix[2][2]*vector[2]
return [x,y,z]
|
def rpc_encode(obj):
"""
Encode an object into RPC-safe form.
"""
try:
return obj.rpc_encode()
except AttributeError:
return obj
|
def unparse_address(scheme, loc):
"""
Undo parse_address().
"""
return '%s://%s' % (scheme, loc)
|
def generate_ordered_map_to_left_right_unique_partial_old(d_j, left, right, left_to_right, invalid):
"""
Returns:
[0]: how many positions forward i moved
[1]: how many positions forward j moved
[2]: how many elements were written
"""
i = 0
j = 0
unmapped = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
left_to_right[i] = invalid
i += 1
unmapped += 1
elif left[i] > right[j]:
j += 1
else:
left_to_right[i] = j + d_j
if i+1 >= len(left) or left[i+1] != left[i]:
j += 1
i += 1
# if j+1 < len(right) and right[j+1] != right[j]:
# i += 1
# j += 1
return i, j, unmapped
|
def bbox_vert_aligned_center(box1, box2):
"""
Returns true if the center of both boxes is within 5 pts
"""
if not (box1 and box2):
return False
return abs(((box1.right + box1.left) / 2.0) - ((box2.right + box2.left) / 2.0)) <= 5
|
def reverse_iter(lst):
"""Returns the reverse of the given list.
>>> reverse_iter([1, 2, 3, 4])
[4, 3, 2, 1]
"""
reverse = []
for item in lst:
reverse.insert(0, item)
return reverse
|
def bounding_box_to_offsets(bbox, transform):
"""Calculating boxboundary offsets for each segment"""
col1 = int((bbox[0] - transform[0]) / transform[1])
col2 = int((bbox[1] - transform[0]) / transform[1]) + 1
row1 = int((bbox[3] - transform[3]) / transform[5])
row2 = int((bbox[2] - transform[3]) / transform[5]) + 1
return [row1, row2, col1, col2]
|
def create_yaml_file_objects(bam_paths):
"""
Turn a list of paths into a list of cwl-compatible and ruamel-compatible file objects.
Additionally, sort the files in lexicographical order.
:param bam_names: file basenames
:param folder: file folder
:return:
"""
return [{"class": "File", "path": b} for b in bam_paths]
|
def RPL_ENDOFNAMES(sender, receipient, message):
""" Reply Code 366 """
return "<" + sender + ">: " + message
|
def boolean_to_integer(boolean):
"""
Convert boolean representations of TRUE/FALSE to an integer value.
:param bool boolean: the boolean to convert.
:return: _result
:rtype: int
"""
_result = 0
if boolean:
_result = 1
return _result
|
def disjoint2(A, B, C):
"""O(n**2)"""
for a in A:
for b in B:
if a == b:
for c in C:
if a == c:
return False
return True
|
def getCenter(coords):
"""Returns the center of the given set of 2d coords as a 2-ple."""
xs = [c for i, c in enumerate(coords) if i % 2 == 0]
ys = [c for i, c in enumerate(coords) if i % 2 == 1]
cx = sum(xs)/float(len(xs))
cy = sum(ys)/float(len(ys))
return (cx, cy)
|
def merge_two_dicts(x, y):
"""Given two dicts, merge them into a new dict as a shallow copy. http://stackoverflow.com/a/26853961/2153744"""
if not isinstance(x, dict):
x = dict()
elif not isinstance(y, dict):
y = dict()
z = x.copy()
z.update(y)
return z
|
def calc_parity(state):
"""
Takes in a state and returns its parity (even = 0 , odd = 1)
:param state:
:type state: str
:return: parity of state
:rtype: int
"""
bit_sum = 0
for bit in state:
if int(bit) not in [0,1]:
raise ValueError('state {} not allowed'.format(state))
bit_sum += int(bit)
parity = bit_sum % 2
return parity
|
def rectContains(rect, point):
"""Check if a point is inside a rectangle.
Parameters
----------
rect : tuple
Points of the rectangle edges.
point : tuple
List of points.
Returns
-------
bool
Return true if the points are inside rectangle else return false.
"""
if point[0] < rect[0]:
return False
elif point[1] < rect[1]:
return False
elif point[0] > rect[0] + rect[2]:
return False
elif point[1] > rect[1] + rect[3]:
return False
return True
|
def GeneralizedLorentz1D(x, x_0=1., fwhm=1., value=1., power_coeff=1.):
"""
Generalized Lorentzian function,
implemented using astropy.modeling.models custom model
Parameters
----------
x: numpy.ndarray
non-zero frequencies
x_0 : float
peak central frequency
fwhm : float
FWHM of the peak (gamma)
value : float
peak value at x=x0
power_coeff : float
power coefficient [n]
Returns
-------
model: astropy.modeling.Model
generalized Lorentzian psd model
"""
assert power_coeff > 0., "The power coefficient should be greater than zero."
return value * (fwhm / 2)**power_coeff * 1./(abs(x - x_0)**power_coeff + (fwhm / 2)**power_coeff)
|
def flatten_dict(dct, key_string=""):
"""
Expects a dictionary where all keys are strings. Returns a list of tuples containing the key vaue pair where the
keys are merged with a dot in between.
"""
result = []
for key in dct:
updated_key_string = key_string + key + "."
if isinstance(dct[key], dict):
result += flatten_dict(dct[key], updated_key_string)
else:
result.append((updated_key_string[:-1], dct[key]))
return result
|
def _map(value, in_min, in_max, out_min, out_max):
"""From scale value to calc val"""
return (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
|
def any_conversations_specified(args):
"""
Returns true if any conversations were specified on the command line
"""
return args.public_channels is not None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.