content stringlengths 42 6.51k |
|---|
def anagram(word):
"""Returns random words from a file
Parameters
----------
word : str
Word in which we will return all permutations of
Raises
------
TypeError
If no no or 1 parameter was given...requires two keyword parameters path and ammount
"""
if len(word) <= 1:
return word
else:
tmp = []
for perm in anagram(word[1:]):
for i in range(len(word)):
tmp.append(perm[:i] + word[0:1] + perm[i:])
return tmp |
def fragment_positions(fragment):
"""Get the fragmnent position."""
return (
len(fragment),
[aln.chromosome for aln in fragment],
[aln.position for aln in fragment],
[aln.flag for aln in fragment]) |
def guard(f, *args, **kwargs):
"""
Run a function.
Return (is_error, result), where ``is_error`` is a boolean indicating whether
it raised an exception. In that case, ``result`` will be an exception.
"""
try:
return (False, f(*args, **kwargs))
except Exception as e:
return (True, e) |
def egcd(a, b):
"""
Given a, and b, calculates the egcd and returns the x and y values
>>> egcd(9, 6)
(1, -1)
>>> egcd(51, 0)
(1, 0)
>>> egcd(1,0)
(1, 0)
"""
if b == 0:
return (1, 0)
else:
q = a // b
r = a % b
(s, t) = egcd(b, r)
return (t, s - q * t) |
def _get_fields(attrs, field_class, pop=False):
"""
Get fields from a class.
:param attrs: Mapping of class attributes
:param type field_class: Base field class
:param bool pop: Remove matching fields
"""
fields = [
(field_name, field_value)
for field_name, field_value in attrs.items()
if issubclass(field_value, field_class) or
isinstance(field_value, field_class)
]
if pop:
for field_name, _ in fields:
del attrs[field_name]
return fields |
def make_geotransform(x_len, y_len, origin):
"""
Build an array of affine transformation coefficients.
Parameters:
x_len (int or float): The length of a pixel along the x axis.
Generally, this will be a positive value.
y_len (int of float): The length of a pixel along the y axis.
Generally (in North-up rasters), this will be a negative value.
origin (tuple of ints or floats): The origin of the raster, a
2-element tuple.
Returns:
A 6-element list with this structure:
::
[
Origin along x-axis,
Length of a pixel along the x axis,
0.0, (this is the standard in north-up projections)
Origin along y-axis,
Length of a pixel along the y axis,
0.0 (this is the standard in north-up projections)
]
"""
return [origin[0], x_len, 0, origin[1], 0, y_len] |
def divide_by(value, arg):
"""
Returns the result of the division of value with arg.
"""
result = 0
try:
result = value / arg
except:
# error in division
pass
return result |
def selectionSort(array: list = [10, 9, 8, 7 ,6 , 5 ,4 ,3, 2, 1], wasChange: bool = False) -> list:
"""This method will sort a number array.
Args:
array (list, optional): unordered number array. Defaults to [10, 9, 8, 7, 6, 5, 4, 3, 2, 1].
wasChange (bool, optional): This conditional is to indicate that the cycle does not repeat itself unnecessarily more times. Defaults to False.
Returns:
list: sorted array.
"""
for i in range(len(array)):
wasChange = False
idxDes: int = i
for j in range(i+1, len(array)):
if array[idxDes] > array[j]:
wasChange = True
idxDes = j
if wasChange == False:
break
array[i], array[idxDes] = array[idxDes], array[i]
return array |
def _makequalifiers(qualifiers, indent):
"""Return a MOF fragment for a NocaseDict of qualifiers."""
if len(qualifiers) == 0:
return ''
return '[%s]' % ',\n '.ljust(indent + 2). \
join([q.tomof(indent) for q in sorted(qualifiers.values())]) |
def rectintersection(r1, r2):
"""Returns the rect corresponding to the intersection between two rects.
Returns `None` if non-overlapping.
"""
if r1[0] > r2[2] or r1[2] < r2[0] or r1[1] > r2[3] or r1[3] < r2[1]: return None
ret = [max(r1[0], r2[0]), max(r1[1], r2[1]), min(r1[2], r2[2]), min(r1[3], r2[3])]
return ret |
def gettype(var):
"""Return the type of var
Parameters:
----------
var: any type
Type to be tested
Returns:
-------
type: type
Type of var
Examples:
--------
>>> gettype(3)
<type 'int'>
>>> gettype(None)
<type 'int'>
>>> gettype([1,2,3])
<type 'list'>
>>> gettype('Hello World')
<type 'str'>
"""
if var is None:return int
else:return type(var) |
def naics_filter(opps):
"""Filter out opps without desired naics
Arguments:
opps {list} -- a list of sam opportunity api results
naics {list} -- a list of naics to filter with
Returns:
[list] -- a subset of results with matching naics
"""
naics = ('334111', '334118', '3343', '33451', '334516', '334614',
'5112', '518', '54169', '54121', '5415', '54169', '61142')
filtered_opps = []
for opp in opps:
#naics_array = opp.get('data',{}).get('naics')
naics_array = opp.get('naics',{})
if not naics_array:
continue
nested_naics_codes = [c for c in [d.get('code',[]) for d in naics_array]]
#opp_naics = [i for sublist in nested_naics_codes for i in sublist]
opp_naics = [i for i in nested_naics_codes ]
for c in opp_naics:
if any(c.startswith(n) for n in naics):
filtered_opps.append(opp)
break
return filtered_opps |
def _capped_double_heads(num_heads, cap=16):
"""Calculate the number of heads for the attention layers with more heads.
The number of heads will be twice the normal amount (num_heads), until it
reaches |cap| heads.
Args:
num_heads: the num_heads hparam for the model.
cap: the maximum number of heads |num_heads| will be doubled to.
Returns:
The number of heads for the attention layers that have more heads.
"""
return max(min(num_heads * 2, cap), num_heads) |
def from_time_str(time_str):
"""Parses the number of seconds from the given time string in
[[HH:]MM:]SS[.XXX] format.
Examples::
"00.0" => 0.0
"01:00.0" => 60.0
"01:05.0" => 65.0
"16700:52:03.0" => 60123123.0
Args:
time_str: a time string in "HH:MM:SS.XXX" format
Returns:
the number of seconds
"""
return sum(
float(n) * m
for n, m in zip(reversed(time_str.split(":")), (1, 60, 3600))
) |
def _run_arrays(inner_fn, slice, arrays_dict, **kwargs):
"""
Assumes that the lengths of the value arrays are all the same.
"""
# SETUP the re-usable kwargs with parameters and arrays and then poke values one row at a time
res = []
for row_i in range(slice[0], slice[1]):
for field_i, (key, array) in enumerate(arrays_dict.items()):
kwargs[key] = array[row_i]
val = inner_fn(**kwargs)
if isinstance(val, tuple):
res += [val]
else:
res += [(val,)]
return res |
def get_shell(orb):
"""Get the angular quantum numbers for a GTO
according to its respective shell"""
if "s" in orb:
return (0, 0, 0)
if "px" in orb:
return (1, 0, 0)
if "py" in orb:
return (0, 1, 0)
if "pz" in orb:
return (0, 0, 1)
return None |
def listify(item):
""" Ensure that the input is a list or tuple.
Parameters
----------
item: object or list or tuple
the input data.
Returns
-------
out: list
the liftify input data.
"""
if isinstance(item, list) or isinstance(item, tuple):
return item
else:
return [item] |
def roc(counts):
"""Function computing TPR and FPR.
Output arguments:
=================
tpr : float
True positive rate
fpr : float
False positive rate
"""
tp, fp, tn, fn = counts
return float(tp) / (tp+fn), float(fp) / (fp+tn) |
def derivative2_centered_h1(target, y):
"""
Implements the taylor centered approach to calculate the second derivative.
:param target: the position to be derived, must be len(y)-1 > target > 0
:param y: an array with the values
:return: the centered second derivative of target
"""
if len(y) - 1 <= target <= 0:
raise(ValueError("Invalid target, array size {}, given {}".format(len(y), target)))
return (y[target + 1] - 2*y[target] + y[target - 1])/4 |
def compass_angle(data: list, angles: tuple = (0.0, 360.0)) -> list:
"""
Filter out images that do not lie within compass angle range
:param data: The data to be filtered
:type data: list
:param angles: The compass angle range to filter through
:type angle: tuple of floats
:return: A feature list
:rtype: list
"""
if len(angles) != 2:
raise ValueError("Angles must be a tuple of length 2")
if angles[0] > angles[1]:
raise ValueError("First angle must be less than second angle")
if angles[0] < 0.0 or angles[1] > 360.0:
raise ValueError("Angles must be between 0 and 360")
return [
feature
for feature in data
if angles[0] <= feature["properties"]["compass_angle"] <= angles[1]
] |
def _or_optional_event(env, event, optional_event):
"""If the optional_event is None, the event is returned. Otherwise the event and optional_event are combined
through an any_of event, thus returning an event that will trigger if either of these events triggers.
Used by single_run_process to combine an event used to wait for a reservation to become available with its
optional stop_reservation_waiting_event."""
if optional_event is None:
return event
return env.any_of(events=[event, optional_event]) |
def gcd(m, n):
"""
Euclid's Algorithm
"""
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
return n |
def is_shutdown_test(item):
"""Return `True` if the item is a launch test."""
return getattr(item, '_launch_pytest_is_shutdown', False) |
def canConstruct_v6(ransomNote: str, magazine: str) -> bool:
"""
This solution, I picked from the problem discussion page.
Contributed by user 'siwal'.
I liked the intuitive and straight forward approach:
1) Take the next letter from the note.
2) If the required record is not found in a magazine, we can not compose the given note.
2a) Stop pointless.
3) Otherwise, cut out the letter and advance. The magazines now have one more cutout and one less letter.
4) Repeat 1 to 3 until note is complete.
5) Success!
Nice! Easy to understand!
"""
for letter in ransomNote:
if letter not in magazine:
return False
else:
magazine = magazine.replace(letter, '', 1)
return True |
def _lc_list(lst):
"""
Return a lower-cased list from the input list.
"""
result = []
for value in lst:
result.append(value.lower())
return result |
def group_iam_policies_by_targets(policies):
""" Groups the collection of IAM actions by target. """
policies_by_targets = {}
for policy in policies:
target = policy['properties']['resource']
if not target in policies_by_targets:
policies_by_targets[target] = []
policies_by_targets[target].append(policy)
return policies_by_targets |
def isurl(url: str) -> bool:
"""Check *url* is URL or not."""
if url and '://' in url:
return True
else:
return False |
def getBPDifferenceDistance(stack1, stack2):
"""
Based on the not identical amount of base pairs within both structure stacks
"""
d = 0
for i in stack1.keys():
# check base pairs in stack 1
if i < stack1[i] and stack1[i] != stack2[i]:
d += 1
# check base pairs in stack 2
for i in stack2.keys():
if i < stack2[i] and stack1[i] != stack2[i]:
d += 1
return d |
def get_template_from_path(path: str) -> str:
"""Convert a normal path back to its template representation."""
# replace all path parts with the template tags
path = path.replace("\\", "/")
return path |
def get_riming_class_name_dict(method='Praz2017'):
"""
Get riming class ID from riming name
according to a given hydrometeor classif method
Input:
method: hydro class method. Default Praz2017 based on
https://amt.copernicus.org/articles/10/1335/2017/
"""
if method == 'Praz2017':
dict = {
'undefined':0,
'unrimed':1,
'rimed':2,
'densely_rimed':3,
'graupel-like':4,
'graupel':5
}
else:
raise ValueError("Riming class dictionary not available for method {}.".format(method))
return dict |
def attrsearch(o, attr_substr):
"""
Return a list of any attributes of object o that have the string
attr_substr in the name of the attribute.
>>> attrsearch(dict(), 'key')
['fromkeys', 'has_key', 'iterkeys', 'keys', 'viewkeys']
>>> attrsearch(object(), 'vermicious knid')
[]
"""
return [a for a in dir(o) if attr_substr.lower() in a.lower()] |
def IonSeriesUsed(IonSeries):
"""
01 - A series
02 - placeholder (was A - NH3 series in older versions of Mascot)
03 - A++ series
04 - B series
05 - placeholder (was B - NH3 series in older versions of Mascot)
06 - B++ series
07 - Y series
08 - placeholder (was Y - NH3 series in older versions of Mascot)
09 - Y++ series
10 - C series
11 - C++ series
12 - X series
13 - X++ series
14 - Z series
15 - Z++ series
16 - Z+H series
17 - Z+H++ series
18 - Z+2H series
19 - Z+2H++ series
"""
b1_sig = False
b2_sig = False
y1_sig = False
y2_sig = False
if IonSeries[3] == '2':
b1_sig = True
if IonSeries[5] == '2':
b2_sig = True
if IonSeries[6] == '2':
y1_sig = True
if IonSeries[8] == '2':
y2_sig = True
return {'y': {1: y1_sig, 2: y2_sig}, 'b': {1: b1_sig, 2: b2_sig}} |
def jsonKeys2str(x):
"""Some of the yamls have integer keys, which json converts to string.
in the future if there are keys that are strings that are intended to be left
as strings this may break"""
if isinstance(x, dict):
return {(int(k) if k.isdigit() else k):v for k, v in x.items()}
return x |
def lowest_cost_action(ic, dc, sc, im, dm, sm, cost):
"""Given the following values, choose the action (insertion, deletion,
or substitution), that results in the lowest cost (ties are broken using
the 'match' score). This is used within the dynamic programming algorithm.
* ic - insertion cost
* dc - deletion cost
* sc - substitution cost
* im - insertion match (score)
* dm - deletion match (score)
* sm - substitution match (score)
"""
best_action = None
best_match_count = -1
min_cost = min(ic, dc, sc)
if min_cost == sc and cost == 0:
best_action = 'equal'
best_match_count = sm
elif min_cost == sc and cost == 1:
best_action = 'replace'
best_match_count = sm
elif min_cost == ic and im > best_match_count:
best_action = 'insert'
best_match_count = im
elif min_cost == dc and dm > best_match_count:
best_action = 'delete'
best_match_count = dm
return best_action |
def trace_overall_index(batch_idx, test_time_indices):
"""
Given
batch_idx: the particular program this all corresponds to
test_time_indices: list of which (tests, timestep) to select
Returns (trace_idxs, time_idxs)
trace_idxs: the indices int the traces to be returned
time_idxs: the indices into which timesteps should be returned
"""
# this assumes 5 tests exactly
assert all(test < 5 for test, _ in test_time_indices)
return [batch_idx * 5 + test for test, _ in test_time_indices], [time for _, time in test_time_indices] |
def itemmap(func, d, factory=dict):
""" Apply function to items of dictionary
>>> accountids = {"Alice": 10, "Bob": 20}
>>> itemmap(reversed, accountids) # doctest: +SKIP
{10: "Alice", 20: "Bob"}
See Also:
keymap
valmap
"""
rv = factory()
rv.update(map(func, d.items()))
return rv |
def get_grades(n_students):
"""Prompt the user to input the grades for n students.
Args:
n_students: int. Number of grades to input.
Returns: a list of floating point values
"""
grade_list = []
# Get the inputs from the user
for _ in range(n_students):
grade_list.append(int(input("Enter a number: ")))
return grade_list |
def ambientT(y, T0 = 20):
"""
y - in mmm
output in degC
"""
return T0 + y * (3/100) |
def unionranges(rangeslist):
"""Return the union of some closed intervals
>>> unionranges([])
[]
>>> unionranges([(1, 100)])
[(1, 100)]
>>> unionranges([(1, 100), (1, 100)])
[(1, 100)]
>>> unionranges([(1, 100), (2, 100)])
[(1, 100)]
>>> unionranges([(1, 99), (1, 100)])
[(1, 100)]
>>> unionranges([(1, 100), (40, 60)])
[(1, 100)]
>>> unionranges([(1, 49), (50, 100)])
[(1, 100)]
>>> unionranges([(1, 48), (50, 100)])
[(1, 48), (50, 100)]
>>> unionranges([(1, 2), (3, 4), (5, 6)])
[(1, 6)]
"""
rangeslist = sorted(set(rangeslist))
unioned = []
if rangeslist:
unioned, rangeslist = [rangeslist[0]], rangeslist[1:]
for a, b in rangeslist:
c, d = unioned[-1]
if a > d + 1:
unioned.append((a, b))
else:
unioned[-1] = (c, max(b, d))
return unioned |
def is_link(test_string):
"""check if the string is a web link
Args:
test_string (str): input string
Returns:
bool: if string is an http link
"""
return test_string.startswith('http') |
def increment_list_by_index(list_to_increment, index_to_increment, increment_value):
"""
very simple but general method to increment the odes by a specified value
:param list_to_increment: list
the list to be incremented, expected to be the list of ODEs
:param index_to_increment: int
the index of the list that needs to be incremented
:param increment_value: float
the value to increment the list by
:return: list
the list after incrementing
"""
list_to_increment[index_to_increment] += increment_value
return list_to_increment |
def make_divisible(
value: int or float,
divisor: int = 8,
round_bias: float = 0.9):
"""
__version__ = 1.0
__date__ = Mar 7, 2022
"""
round_value = max(divisor, int(value + divisor / 2) // divisor * divisor)
assert 0 < round_bias < 1
if round_value < round_bias * value:
round_value += divisor
return round_value |
def tp_rate(TP, pos):
"""
Gets true positive rate.
:param TP: Number of true positives
:type TP: `int`
:param pos: Number of positive labels
:type pos: `int`
:return: true positive rate
:rtype: `float`
"""
if pos == 0:
return 0
else:
return TP / pos |
def xor_text(text, xor_key, **kwargs):
"""
# uses xor to encrypt/decrypt some text given a xor_key
>>> text = "Hello, World!"
>>> xor_key = "secret"
>>> encrypted = xor_text(text, xor_key)
>>> encrypted
';\x00\x0f\x1e\nXS2\x0c\x00\t\x10R'
>>> decrypted = xor_text(encrypted, xor_key)
>>> print decrypted
Hello, World!
# warning, this is simple to break:
>>> codebreak = xor_text(" ", xor_key)
>>> print codebreak
SECRET
# copied from https://stackoverflow.com/a/2612877/1561176
:param text: the text to xor
:param xor_key: the xor key to use
:param kwargs:
:return:
"""
# we must multiply the key so that it will extend over the whole text
xor_key_multiplier = int(len(text) / len(xor_key)) + 1
return ''.join(chr(ord(s) ^ ord(c)) for s, c in zip(text, xor_key * xor_key_multiplier)) |
def _is_close(d1, d2, atolerance=0, rtolerance=0):
"""Determines whether two adjacency matrices are within
a provided tolerance.
Parameters
----------
d1 : dict
Adjacency dictionary
d2 : dict
Adjacency dictionary
atolerance : float
Some scalar tolerance value to determine closeness
rtolerance : float
A scalar tolerance value that will be some proportion
of ``d2``'s value
Returns
-------
closeness : bool
If all of the nodes within ``d1`` and ``d2`` are within
a predefined tolerance, they are considered "close" and
this method will return True. Otherwise, this method will
return False.
"""
# Pre-condition: d1 and d2 have the same keys at each level if they
# are dictionaries.
if not isinstance(d1, dict) and not isinstance(d2, dict):
return abs(d1 - d2) <= atolerance + rtolerance * abs(d2)
return all(all(_is_close(d1[u][v], d2[u][v]) for v in d1[u]) for u in d1) |
def avg(tup):
"""
Returns average of all of the elements in the tuple.
Remember that the average of a tuple is the sum of all of the elements in the
tuple divided by the number of elements in the tuple.
Examples:
avg((1.0, 2.0, 3.0)) returns 2.0
avg((1.0, 1.0, 3.0, 5.0)) returns 2.5
Parameter tup: the tuple to check
Precondition: tup is a tuple of numbers (int or float)
"""
assert type(tup) == tuple
result = 0.0
for index in tup:
if len(tup) == 0:
return result
elif len(tup) == 1:
result = float(tup[0])
elif len(tup) > 1:
result = sum(tup[:]) / float(len(tup))
else:
result = 'nil'
return result
# pass |
def get_result(response):
"""
Get the desired result from an API response.
:param response: Requests API response object
"""
try:
payload = response.json()
except AttributeError:
payload = response
if 'results' in payload:
return payload['results']
# Or just return the payload... (next-gen)
return payload |
def seq_join(seq, val):
"""
Flatten input sequence of lists into a single list. Insert separator
value if not None.
@param[in] seq sequence of lists
@param[in] val separator value, will be put between sub-sequences in the
resulting list if not None.
@returns resulting flattened list
"""
res = []
for item in seq[:-1]:
res.extend(item)
if val is not None:
res.append(val)
res.extend(seq[-1])
return res |
def mask_alternatives(alternatives):
"""
:param alternatives: Extra security alternatives collected from user
:type alternatives: dict
:return: Masked extra security alternatives
:rtype: dict
"""
if alternatives:
# Phone numbers
masked_phone_numbers = []
for phone_number in alternatives.get('phone_numbers', []):
masked_number = '{}{}'.format('X' * (len(phone_number) - 2), phone_number[len(phone_number) - 2 :])
masked_phone_numbers.append(masked_number)
alternatives['phone_numbers'] = masked_phone_numbers
return alternatives |
def funky_sum(a, b, mix):
"""
Returns a mixture between a and b.
If mix is 0, returns a. If mix is 1, returns b. Otherwise returns a linear
interpolation between them. If mix is outside the range of 0 and 1, it is
capped at those numbers.
"""
if mix < 0:
return a
elif mix > 1:
return b
else:
return (1 - mix) * a + mix * b |
def _get_next_key(key, length):
"""Returns reverse(reverse(key, len) + 1, len), where reverse(key, len) is the
bit-wise reversal of the length least significant bits of key"""
step = 1 << (length - 1)
while key & step:
step >>= 1
return (key & (step - 1)) + step |
def contains_timezone(format_string: str) -> bool:
"""
Give an strftime style format string, check if it contains a %Z or %z timezone
format directive.
:param format_string: The format string to check.
:return: True if it does contain a timezone directive. False otherwise.
"""
is_format_char = False # if the current character is after a "%"
for character in format_string:
if is_format_char:
if character == "z" or character == "Z":
return True
else:
is_format_char = False
else:
if character == "%":
is_format_char = True
return False |
def any2utf8(text, errors='strict', encoding='utf8'):
"""Convert a unicode or bytes string in the given encoding into a utf8 bytestring.
Parameters
----------
text : str
Input text.
errors : str, optional
Error handling behaviour if `text` is a bytestring.
encoding : str, optional
Encoding of `text` if it is a bytestring.
Returns
-------
str
Bytestring in utf8.
"""
if isinstance(text, str):
return text.encode('utf8')
# do bytestring -> unicode -> utf8 full circle, to ensure valid utf8
return str(text, encoding, errors=errors).encode('utf8') |
def map_into_range(low, high, raw_value):
"""
Map an input function into an output value, clamping such that the magnitude of the output is at most 1.0
:param low:
The value in the input range corresponding to zero.
:param high:
The value in the input range corresponding to 1.0 or -1.0, depending on whether this is higher or lower than the
low value respectively.
:param raw_value:
An input value
:return:
Mapped output value
"""
value = float(raw_value)
if low < high:
if value < low:
return 0
elif value > high:
return 1.0
elif low > high:
if value > low:
return 0
elif value < high:
return -1.0
return (value - low) / abs(high - low) |
def twos_complement(val, bits):
"""Retuns the 2-complemented value of val assuming bits word width"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set
val = val - (2 ** bits) # compute negative value
return val |
def _need_loop(v):
"""
if a variable should loop to concat string
:param v: any variable
:return: Boolean
"""
return isinstance(v, list) or isinstance(v, dict) or isinstance(v, tuple) |
def adder(x, y):
"""Adds two numbers together.
>>> adder(1, 1)
2
>>> adder(-1, 1)
0
"""
return x + y + 1 |
def embed_root(html_string: str) -> str:
"""
Embed the root of the workspace in the html string.
"""
root_string = "`http://${window.HOST}:${window.PORT}`"
replace_string = "''"
html_string = html_string.replace(root_string, replace_string)
wssr_string = "`ws://${window.HOST}:${window.PORT}`"
replace_string = "`ws://${window.location.host}`"
html_string = html_string.replace(wssr_string, replace_string)
return html_string |
def reverse(text: str) -> str:
"""Return the reverse of a given string."""
return text[::-1] |
def strip_api(server_url):
"""
Strips "api/" from the end of ``server_url``, if present
>>> strip_api('https://play.dhis2.org/demo/api/')
'https://play.dhis2.org/demo/'
"""
if server_url.rstrip('/').endswith('api'):
i = len(server_url.rstrip('/')) - 3
return server_url[:i]
return server_url |
def parse_connection(connection_string):
"""Parse a connection string.
The connection string must be of the form
proto:address:port,proto:address:port,...
The parsing logic here must be identical to the one at
https://github.com/openvswitch/ovs/blob/master/python/ovs/db/idl.py#L162
for remote connections.
:param connection_string: The ovsdb-server connection string
:type connection_string: string
"""
return [c.strip() for c in connection_string.split(',')] |
def add(a, b):
"""
Adds stuff
"""
return a + b; |
def clean(query: str) -> str:
""" cleans strings from new lines and wrapping whitespaces"""
return query.replace('"', '""').replace("\r\n", " ").replace("\n", " ").strip() |
def getColourStats(colourData):
"""getColourStats.
Args:
colourData:
"""
import numpy as n
x = n.array(colourData)[:,0]
y = n.array(colourData)[:,1]
meanColour = y.mean()
# We can rewrite the line equation as y = Ap, where A = [[x 1]]
# and p = [[m], [c]]. Now use lstsq to solve for p
A = n.vstack([x, n.ones(len(x))]).T
# In this case the gradient is the colour evolution
gradient, intercept = n.linalg.lstsq(A, y)[0]
return meanColour, gradient |
def filter_records_by_victory(records: list) -> list:
"""Filter out records for a specific character"""
specific_records = []
for record in records:
if record["event"]["victory"]:
specific_records.append(record)
return specific_records |
def collect_specific_bytes(bytes_object, start_position, width, relative_to=0):
"""
Collects specific bytes within a bytes object.
:param bytes_object: an opened bytes object
:param start_position: the position to start to read at
:param width: how far to read from the start position
:param relative_to: position relative to 0 -> start of file/object, 1 -> current position of seek head,
2 -> end of file/object
:return: the bytes starting at position
"""
# navigate to byte position
content = bytes_object[start_position: start_position + width]
return {"content": content, "new_position": start_position + width} |
def sub_template(template,template_tag,substitution):
"""
make a substitution for a template_tag in a template
"""
template = template.replace(template_tag,substitution)
return template |
def _is_unique_msg(dialect, msg):
"""
easier unit testing this way
"""
if dialect == 'postgresql':
if 'duplicate key value violates unique constraint' in msg:
return True
elif dialect == 'mssql':
if 'Cannot insert duplicate key' in msg:
return True
elif dialect == 'sqlite':
if 'is not unique' in msg or 'are not unique' in msg:
return True
else:
raise ValueError('is_unique_exc() does not yet support dialect: %s' % dialect)
return False |
def _guess_variables(polynomial, *args):
"""
Return the polynomial variables
INPUT:
- ``polynomial`` -- a polynomial.
- ``*args`` -- the variables. If none are specified, all variables
in ``polynomial`` are returned. If a list or tuple is passed,
the content is returned. If multiple arguments are passed, they
are returned.
OUTPUT:
A tuple of variables in the parent ring of the polynoimal.
EXAMPLES::
sage: from sage.rings.invariant_theory import _guess_variables
sage: R.<x,y> = QQ[]
sage: _guess_variables(x^2+y^2)
(x, y)
sage: _guess_variables(x^2+y^2, x)
(x,)
sage: _guess_variables(x^2+y^2, x,y)
(x, y)
sage: _guess_variables(x^2+y^2, [x,y])
(x, y)
"""
if len(args)==0 or (len(args)==1 and args[0] is None):
return polynomial.variables()
elif len(args) == 1 and isinstance(args[0], (tuple, list)):
return tuple(args[0])
else:
return tuple(args) |
def flatten(iterables, start_with=None):
"""Takes a list of lists ``iterables`` and returns a list containing elements of every list.
If ``start_with`` is not ``None``, the result will start with ``start_with`` items, exactly as
if ``start_with`` would be the first item of lists.
"""
result = []
if start_with:
result.extend(start_with)
for iterable in iterables:
result.extend(iterable)
return result |
def choosecat(str, classnames):
""" Gets a string and tries to match its category with an int. """
for i, id in enumerate(classnames):
if id in str:
return i
return None |
def irpf(base, porcentaje=12.5,prorrateado=False):
"""
irpf (sueldo,porcentaje, prorrateado=boolean)
"""
if prorrateado:
cantidad_prorateada = base/6
if type(base)==float and type(porcentaje)==float:
return (base/100) * porcentaje
else:
return None |
def float_dist(id1, id2):
"""
Compute distance between two identities for NumPyDB.
Assumption: id1 and id2 are real numbers (but always sent
as strings).
This function is typically used when time values are
used as identifiers.
"""
return abs(float(id1) - float(id2)) |
def triangle_shape(height):
"""Print a pyramid made of "x"
Args:
height (int): The height of the pyramid
Returns:
str: a string representing the pyramid, made with the character "x"
"""
pyramid = ""
if height == 0:
return pyramid
for i in range(height):
pyramid += (
(height - i - 1) * " " + (2 * i + 1) * "x" + (height - i - 1) * " " + "\n"
)
return pyramid[:-1] |
def isShiftCharacter(character):
"""Returns True if the key character is uppercase or shifted."""
return character.isupper() or character in '~!@#$%^&*()_+{}|:"<>?' |
def dict_to_tuple(dictionary):
"""
>>> dict_to_tuple({'id':[1,2,3,4],'testing':1,'bla':'three'})
[('testing', 1), ('bla', 'three'), ('id', 1), ('id', 2), ('id', 3), ('id', 4)]
>>>
"""
return_list = []
for key, value in dictionary.items():
if isinstance(value, list):
for entry in value:
return_list.append((key, entry))
else:
return_list.append((key, value))
return return_list |
def find_outbound_connections(l, node_index, node_value):
"""Returns a list indicating the destination nodes of outbound edges
Helper function for constructing a graph showing which integers in list l
are divisors of integers in l with a larger index.
Args:
l: The list of integers that contain potential nodes in graph
node_index: The index of the current node in l
node_value: The value of the current node in l
Returns:
list of integers representing the destination node indices for edges
outbound from the node represented by node_index and node_value.
"""
outbound_connections = []
for destination_index, destination_value in enumerate(l):
if destination_index > node_index:
# avoids processing items out of order
# outbound connections must be to later elements in list
if destination_value % node_value == 0:
outbound_connections.append(str(destination_index))
return outbound_connections |
def updateComboGroupLazy(player, comboGroup):
"""Computes the final combo group based on combo state start and end, using
the lazy startegy.
Lazy:
include any combo from start state that remains in end state"""
newComboGroup = []
for combo in comboGroup:
orientation = combo.orientation()
if orientation == 'h': comboTest = player.grid.comboHorizontalAround(*combo[0])
elif orientation == 'v': comboTest = player.grid.comboVerticalAround(*combo[0])
else: raise NotImplemented
if combo == comboTest:
newComboGroup.append(combo)
return newComboGroup |
def _create_creds_dict(creds_str):
""" Takes the credentials str and converts it to a dict
Parameters
----------
creds_str : str
credentials string with the below format where the user has inserted their values:
'host=my_hostname dbname=my_dbname user=my_user password=my_password port=1234'
Returns
-------
dict
credentials in dict form
"""
creds_dict = {}
for param in creds_str.split(' '):
split_param = param.split('=')
creds_dict[split_param[0]] = split_param[1]
return creds_dict |
def create_word_weight_dictionary(post):
"""
This function creates a word weight dictionary whose keys are
word names and the values are word weights.
:param post: A dict, the Post dictionary from an HTTP Request
:return: A dict, containing word names and associated word weights
"""
word_dict = dict()
for key, value in post.items():
if key.startswith('word_'):
word_dict[key[5:]] = value
return word_dict |
def converttabs(text, spaces=4):
"""
Convert all the tabs to a specific amount of spaces
:type text: string
:param text: The text to convert tabs to spaces on
:type spaces: integer
:param spaces: The amount of spaces to replace tabs to.
"""
return text.replace('\t', ' ' * spaces) |
def exponential_decay(step, rate, decay_steps, start_step=0):
"""A standard exponential decay, scaling the learning rate by :obj:`rate`
every :obj:`decay_steps` steps.
"""
return rate ** (max(step - start_step + decay_steps, 0) // decay_steps) |
def stats(d_raw_materials, f_total_money_collected):
"""
Show machine statistics
Params:
d_raw_materials: dict
f_money_collected: float
Returns:
str
"""
cm_stats = 'sugar {0} tablespoons remaining\n'.format(d_raw_materials['sugar'])
cm_stats += 'butter {0} teaspoons remaining\n'.format(d_raw_materials['butter'])
cm_stats += 'dark chocolate {0} tablespoons remaining\n'.format(d_raw_materials['dark chocolate'])
cm_stats += 'mint chocolate {0} tablespoons remaining\n'.format(d_raw_materials['mint chocolate'])
cm_stats += 'milk chocolate {0} tablespoons remaining\n'.format(d_raw_materials['milk chocolate'])
cm_stats += 'light corn syrup {0} teaspoons remaining\n'.format(d_raw_materials['light corn syrup'])
cm_stats += 'sweetened condensed milk {0} teaspoons remaining\n'.format(d_raw_materials[
'sweetened condensed milk'])
cm_stats += 'vanilla extract {0} teaspoons remaining\n'.format(d_raw_materials['vanilla extract'])
cm_stats += 'Reese\'s Pieces {0} tablespoons remaining\n'.format(d_raw_materials['Reese\'s Pieces'])
cm_stats += 'Total Money Collected: ${0:.2f}\n'.format(f_total_money_collected)
return cm_stats |
def gassmann_sat2dry(Ksat, Kmin, Kfl, phi):
"""
Gassman substitution from Saturated moduli to dry rock moduli
"""
a = Ksat*(phi*Kmin/Kfl + 1.0 - phi) - Kmin
b = phi*Kmin/Kfl + Ksat/Kmin - 1.0 - phi
Kdry = a/b
return Kdry |
def contains_dir(hdfs_dirs, sub_folder):
"""
Support for Lambda Function to check if a HDFS subfolder is contained by the HDFS directory
"""
if sub_folder in hdfs_dirs:
return True
else:
# Debug
# print('{}, {}'.format(sub_folder, hdfs_dirs))
pass
return False |
def AUC_calc(item, TPR):
"""
Calculate Area under the ROC/PR curve for each class (AUC/AUPR).
:param item: True negative rate (TNR) or Positive predictive value (PPV)
:type item: float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR: float
:return: AUC/AUPR as float
"""
try:
return (item + TPR) / 2
except TypeError:
return "None" |
def is_job_active(jobststus):
"""
Check if jobstatus is one of the active
:param jobststus: str
:return: True or False
"""
end_status_list = ['finished', 'failed', 'cancelled', 'closed']
if jobststus in end_status_list:
return False
return True |
def insertionSort(data):
""" Implementation of the insertion sort algorithm in ascending order """
for unsortedIndex in range(len(data)):
unsortedData = data[unsortedIndex]
sortedIndex = unsortedIndex
while sortedIndex > 0 and unsortedData < data[sortedIndex-1]:
data[sortedIndex] = data[sortedIndex-1]
sortedIndex -= 1
data[sortedIndex] = unsortedData
return data |
def _fix2comp(num):
"""
Convert from two's complement to negative.
"""
assert 0 <= num < 2**32
if num & 2**31:
return num - 2**32
else:
return num |
def construct_headers(token):
"""Construct headers for the REST API call."""
headers = {'Authorization': 'Bearer ' + token}
return headers |
def collatz(x):
"""
Generates the next term of the Collatz sequence, given the previous term x
"""
if x % 2 == 0:
return(x//2)
else:
return(3*x + 1) |
def get_intervals(l):
"""For list of lists, gets the cumulative products of the lengths"""
intervals = len(l) * [0]
# Initalize with 1
intervals[0] = 1
for k in range(1, len(l)):
intervals[k] = (len(l[k]) + 1) * intervals[k-1]
return intervals |
def get_name_and_version(filename):
"""Guess name and version of a package given its ``filename``."""
idx = filename.rfind('.tar.gz')
if idx == -1:
idx = filename.rfind('.zip')
if idx == -1:
idx = filename.rfind('.tar.bz2')
if idx == -1:
idx = filename.rfind('.')
name, version = filename[:idx].rsplit('-', 1)
return {'name': name, 'version': version} |
def pad(size, value):
"""Adds up to size bytes to value to make value mod size == 0"""
return (value + size - 1)/size*size |
def generate_kmers(kmerlen):
"""make a full list of k-mers
Arguments:
kmerlen -- integer, length of k-mer
Return:
a list of the full set of k-mers
"""
nts = ['A', 'C', 'G', 'T']
kmers = []
kmers.append('')
l = 0
while l < kmerlen:
imers = []
for imer in kmers:
for nt in nts:
imers.append(imer+nt)
kmers = imers
l += 1
return kmers |
def chunk_string(string, length):
""" This function splits a string of text to equal chunks of text/ string
with equal length.
Args:
string: accepts a string of any length as a parameter.
length: accepts a integer as a parameter.
Returns:
The function returns a python list with each value of the list having
equal length
"""
return [string[0+i:length+i] for i in range(0, len(string), length)] |
def _shape_equal(shape1, shape2):
"""
Check if shape of stream are compatible.
More or less shape1==shape2 but deal with:
* shape can be list or tupple
* shape can have one dim with -1
"""
shape1 = list(shape1)
shape2 = list(shape2)
if len(shape1) != len(shape2):
return False
for i in range(len(shape1)):
if shape1[i]==-1 or shape2[i]==-1:
continue
if shape1[i]!=shape2[i]:
return False
return True |
def move_coordinates(geo, idx1, idx2):
""" move the atom at position idx1 to idx2, shifting all other atoms
"""
# Get the coordinates at idx1 that are to be moved
geo = [list(x) for x in geo]
moving_coords = geo[idx1]
# move the coordinates to idx2
geo.remove(moving_coords)
geo.insert(idx2, moving_coords)
geo_move = tuple(tuple(x) for x in geo)
return geo_move |
def list_of_dict_to_dict(list_of_dict, key):
"""
Converts a list of dicts to a dict of dicts based on the key provided.
Also removes the key from the nested dicts.
converts [{key: v1, k2:v12, k3:v13}, {key:v2, k2: v22, k3:v23}, ... ]
to {v1: {k2: v12, k3:v13}, v2:{k2:v22, k3:v23}, ...}
Args:
list_of_dict: eg: [{k1: v1, k2:v12, k3:v13}, {k1:v2, k2: v22, k3:v23}, ... ]
Returns:
dict_of_dict: eg: {v1: {k2: v12, k3:v13}, v2:{k2:v22, k3:v23}, ...}
"""
dict_of_dict = {}
for item in list_of_dict: # item will be the nested dict
value = item[key] # This will be the "key" in dict_of_dict
item.pop(key) # removes key from the nested dict
dict_of_dict[value] = item # adds item to the new dict
return dict_of_dict |
def is_digit(key_name):
"""Check if a key is a digit."""
return len(key_name) == 1 and key_name.isnumeric() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.