content
stringlengths 42
6.51k
|
|---|
def compare_not_none(this, other):
"""Oldschool (python 2.x) cmp.
if this < other return -1
if this = other return 0
if this > other return 1
"""
if len(this) != len(other):
return -1 if len(this) < len(other) else 1
for i in range(len(this)):
this_item, other_item = this[i], other[i]
if this_item != other_item:
return -1 if this_item < other_item else 1
else:
return 0
|
def sec2frames(time_in_seconds, winlength, winstep):
""" turn time in seconds into time in frames"""
time_in_frames = (time_in_seconds - winlength/2)/winstep
time_in_frames = int(round(time_in_frames))
if time_in_frames < 0:
time_in_frames = 0
return time_in_frames
|
def _grid_to_commands(grid_dict):
"""Translate a dictionary of parameter values into a list of commands.
The entire set of possible combinations is generated.
Args:
grid_dict: A dictionary of argument names to lists, where each list
contains possible values for this argument.
Returns:
A list of dictionaries. Each key is an argument name that maps onto a
single value.
"""
# We build a list of dictionaries with key value pairs.
commands = []
# We need track of the index within each value array.
gkeys = list(grid_dict.keys())
indices = [0] * len(gkeys)
stopping_criteria = False
while not stopping_criteria:
cmd = dict()
for i, k in enumerate(gkeys):
v = grid_dict[k][indices[i]]
cmd[k] = v
commands.append(cmd)
for i in range(len(indices)-1,-1,-1):
indices[i] = (indices[i] + 1) % len(grid_dict[gkeys[i]])
if indices[i] == 0 and i == 0:
stopping_criteria = True
elif indices[i] != 0:
break
return commands
|
def selectionSort(array: list):
"""
Best : O(n^2) Time | O(1) Space
Average : O(n^2) Time | O(1) Space
Worst : O(n^2) Time | O(1) Space
"""
n: int = len(array)
for currentIdx in range(n - 1):
smallestIdx = currentIdx
for i in range(currentIdx + 1, n):
if array[smallestIdx] > array[i]:
smallestIdx = i
array[currentIdx], array[smallestIdx] = array[smallestIdx], array[currentIdx]
return array
|
def split_category(category: str):
"""
Split category string into category and sub-category. The category and sub-category
are separated by a colon (":"). However, not all categories have sub-categories. This
method handles both cases.
Args:
category (str): Category[:sub-category] String, e.g. "PROPERTY:VEHICLE", "PEOPLE"
Returns:
(category, sub_category)
"""
try:
(main_cat, sub_cat) = category.split(":", 2)
except ValueError:
(main_cat, sub_cat) = (category, None)
if main_cat:
main_cat = '/' + main_cat
if sub_cat:
sub_cat = '/' + sub_cat
return (main_cat, sub_cat)
|
def _tuple_from_ver(version_string):
"""
:param version_string:
A unicode dotted version string
:return:
A tuple of integers
"""
return tuple(map(int, version_string.split('.')))
|
def split(x, divider):
"""Split a string.
Parameters
----------
x : any
A str object to be split. Anything else is returned as is.
divider : str
Divider string.
"""
if isinstance(x, str):
return x.split(divider)
return x
|
def _histc(x, edges):
"""
Histogram without plot
>>> x = xrange(0, 100)
>>> edges = range(0, 110, 10)
>>> _histc(x, edges)
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
:param x: set of seq
:param edges: histogram edges
:return: histogram count
"""
i = 0
ks = []
while i < len(edges)-1:
ks.append(len([j for j in x if j >= edges[i] and j < edges[i+1]]))
i+=1
return ks
|
def create_codes_and_names_of_A_matrix(db):
"""
Create a dictionary a tuple (activity name, reference product,
unit, location) as key, and its code as value.
:return: a dictionary to map indices to activities
:rtype: dict
"""
return {
(i["name"], i["reference product"], i["unit"], i["location"],): i["code"]
for i in db
}
|
def parrot(voltage, state='a stiff', action='voom', parrot_type='Norwegian Blue'):
"""Example of multi-argument function
This function accepts one required argument (voltage) and three optional arguments
(state, action, and type).
"""
message = 'This parrot wouldn\'t ' + action + ' '
message += 'if you put ' + str(voltage) + ' volts through it. '
message += 'Lovely plumage, the ' + parrot_type + '. '
message += 'It\'s ' + state + '!'
return message
|
def replay(i):
"""
Input: {
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
return {'return':1, 'error':'TBD'}
# TBD - take params from remote/local experiment and pre-set ...
# Run locally, i.e. do not share stats unless requested ...
# i['action']='crowdsource'
# i['module_uoa']=cfg['module_deps']['experiment.bench.caffe']
return ck.access(i)
|
def round_key(matrix, key_block):
"""
This function is used for both AES encryption and AES decryption.
The function will divide the matrix into four 4 bytes blocks (each column as a block), and perform XOR operation
between block and key which contained in the key_block. At last, create and return the new matrix based on the
XOR operation results.
:param matrix: A 4x4 matrix which composed by 4 lists. The lists only accept numeric objects
:param key_block: A list which contain four 4 byte keys.
:return: A new matrix which be changed follow the AddRoundKey rule. The format of this matrix is same as the input
matrix.
"""
new_matrix = matrix.copy()
position_tag = 0
for key in key_block:
column_value = 0
for row in matrix:
column_value = (column_value << 8) + row[position_tag]
encrypted_column_value = column_value ^ key
hexed_key = hex(encrypted_column_value)[2:].zfill(8)
position_tag2 = 0
for round_num in range(3):
new_matrix[position_tag2][position_tag] = eval('0x' + hexed_key[:2])
hexed_key = hexed_key[(-len(hexed_key)) + 2:]
position_tag2 += 1
new_matrix[position_tag2][position_tag] = eval('0x' + hexed_key[:2])
position_tag += 1
return new_matrix
|
def _merge_dicts(*args):
"""
Shallow copy and merge dicts together, giving precedence to last in.
"""
ret = dict()
for arg in args:
ret.update(arg)
return ret
|
def summary_to_entries(summary):
"""
"Height": 140,
"Width": 59.3,
"marked_graph": [1],
"marked_text": [1],
"n_chars": 2936,
"n_pages": 1,
"name": "-patente-de-invencion-1445369-1.pdf",
"page_texts"
"""
name = summary['path']
page_texts = summary['page_texts']
marked_text = summary['marked_text']
marked_graph = summary['marked_graph']
pages = sorted(set(marked_text) - set(marked_graph))
entries = [(name, p, page_texts[p - 1]) for p in pages]
return entries
|
def filter_dictionary(function, dictionary, by="keys"):
"""Filter a dictionary by conditions on keys or values.
Args:
function (callable): Function that takes one argument and returns True or False.
dictionary (dict): Dictionary to be filtered.
Returns:
dict: Filtered dictionary
Examples:
>>> filter_dictionary(lambda x: "bla" in x, {"bla": 1, "blubb": 2})
{'bla': 1}
>>> filter_dictionary(lambda x: x <= 1, {"bla": 1, "blubb": 2}, by="values")
{'bla': 1}
"""
if by == "keys":
keys_to_keep = set(filter(function, dictionary))
out = {key: val for key, val in dictionary.items() if key in keys_to_keep}
elif by == "values":
out = {}
for key, val in dictionary.items():
if function(val):
out[key] = val
else:
raise ValueError(f"by must be 'keys' or 'values', not {by}")
return out
|
def sort(xs):
"""Returns a list containing the same elements as xs, but in sorted order."""
xs.sort()
return xs
|
def J_p(Ep, norm=1.0, alpha=2.0):
"""
Defines the particle distribution of the protons as a power law.
Parameters
----------
- Ep = E_proton (GeV)
- alpha = slope
- norm = the normalization (at 1 GeV) in units of cm^-3 GeV-1
Outputs
--------
- The particle distribution in units of 1/GeV/cm^-3
"""
return norm*(Ep/1.0)**(-alpha)
|
def kareler_toplami(sayi):
""" Bir sayinin kareler toplami zincirinin hangi sayida
sonlandigini ozyinelemeli bulur.
"""
if sayi in [0, 1, 89]:
return sayi
else:
yeni_toplam = sum([int(i)**2 for i in str(sayi)])
return kareler_toplami(yeni_toplam)
|
def halton_seq(prime, index=1):
""" Low discrepancy halton sequence with a given prime """
r, f, i = 0.0, 1.0, index
while i > 0:
f /= prime
r += f * (i % prime)
i = int(i / float(prime))
return r
|
def is_main_process(local_rank):
"""
Whether or not the current process is the local process, based on `xm.get_ordinal()` (for TPUs) first, then on
`local_rank`.
"""
return local_rank in [-1, 0]
|
def trunc_bytes_at(
msg: bytes, delim: bytes = b"{", start: int = 1, occurrence: int = 1
):
"""Truncates bytes starting from a given point at nth occurrence of a
delimiter."""
return delim.join(msg[start:].split(delim, occurrence)[:occurrence])
|
def correct_flask_vol(flask_vol, t=20.0, glass="borosilicate"):
"""
Correct flask volume for changes from thermal expansion of glass.
Parameters
----------
flask_vol : array-like
Flask volumes at standard temperature (20C)
t : float, optional
New temperature to calculate volume
glass : str, optional
Type of glass ("borosilicate" or "soft)
Returns
-------
corrected_vol : array-like
Flask volumes are new temperature
Notes
-----
Flask volume equation from 2007 Best Practices for Ocean CO2 Measurements,
SOP 13 - Gravimetric calibration of volume contained using water
"""
alpha = { # thermal expansion coefficient
"borosilicate": 1.0e-5,
"soft": 2.5e-3,
}
if glass not in alpha.keys():
raise KeyError(f"Glass type not found, must be one of {list(alpha.keys())}")
standard_t = 20.0
corrected_vol = flask_vol * (1.0 + alpha[glass] * (t - standard_t))
return corrected_vol
|
def command_add(date, start_time, end_time, title, calendar):
"""
(str, int, int, str, dict) -> boolean
Add title to the list at calendar[date]
Create date if it was not there
Adds the date if start_time is less or equal to the end_time
date: A string date formatted as "YYYY-MM-DD"
start_time: An integer from 0-23 representing the start time
end_time: An integer from 0-23 representing the start time
title: A string describing the event
calendar: The calendar database
return: boolean of whether the even was successfully added
>>> calendar = {}
>>> command_add("2018-02-28", 11, 12, "Python class", calendar)
True
>>> calendar == {"2018-02-28": [{"start": 11, "end": 12, "title": "Python class"}]}
True
>>> command_add("2018-03-11", 14, 16, "CSCA08 test 2", calendar)
True
>>> calendar == {"2018-03-11": [{"start": 14, "end": 16, "title": "CSCA08 test 2"}], \
"2018-02-28": [{"start": 11, "end": 12, "title": "Python class"}]}
True
>>> command_add("2018-03-11", 10, 9, "go out with friends after test", calendar)
False
>>> calendar == {"2018-03-11": [{"start": 14, "end": 16, "title": "CSCA08 test 2"}], \
"2018-02-28": [{"start": 11, "end": 12, "title": "Python class"}]}
True
>>> command_add("2018-03-13", 13, 13, "Have fun", calendar)
True
>>> calendar == {"2018-03-13": [{"start": 13, "end": 13, "title": "Have fun"}], \
"2018-03-11": [{"start": 14, "end": 16, "title": "CSCA08 test 2"}], \
"2018-02-28": [{"start": 11, "end": 12, "title": "Python class"}]}
True
"""
# YOUR CODE GOES HERE
if start_time <= end_time:
for dates in calendar.keys():
if dates == date:
newevent = {"start": start_time, "end": end_time, "title": title}
calendar[dates].append(newevent)
return True
calendar[date] = []
newevent = {"start": start_time, "end": end_time, "title": title}
calendar[date].append(newevent)
return True
return False
|
def stringify_list(ls):
""" string conversion of all elements in a list,
e.g. stringify_list([1,'2',u'3']) -> ['1', '2', u'3']
Mostly a support function for some other things here.
"""
if type(ls) is list:
return list('%s'%s for s in ls)
else: # tuple. Or something you shouldn't have handed in without specific expectation.
return tuple('%s'%s for s in ls)
|
def charScore(c):
"""return character score for a character. 'A'=1,'B'=2, etc"""
return ord(c) - ord('A') + 1
|
def as_int(n):
"""
Convert the argument to a builtin integer.
The return value is guaranteed to be equal to the input. ValueError is
raised if the input has a non-integral value.
Examples
========
>>> from sympy.core.compatibility import as_int
>>> from sympy import sqrt
>>> 3.0
3.0
>>> as_int(3.0) # convert to int and test for equality
3
>>> int(sqrt(10))
3
>>> as_int(sqrt(10))
Traceback (most recent call last):
...
ValueError: ... is not an integer
"""
try:
result = int(n)
if result != n:
raise TypeError
except TypeError:
raise ValueError('%s is not an integer' % n)
return result
|
def decode_binary_rle(data):
"""
decodes binary rle to integer list rle
"""
m = len(data)
cnts = [0] * m
h = 0
p = 0
while p < m:
x = 0
k = 0
more = 1
while more > 0:
c = ord(data[p]) - 48
x |= (c & 0x1F) << 5 * k
more = c & 0x20
p = p + 1
k = k + 1
if more == 0 and (c & 0x10) != 0:
x |= -1 << 5 * k
if h > 2:
x += cnts[h - 2]
cnts[h] = x
h += 1
return cnts[0:h]
|
def postfixe(arbre):
"""Fonction qui retourne le parcours prefixe de l'arbre
sous la forme d'une liste
"""
liste = []
if arbre != None:
liste += postfixe(arbre.get_ag())
liste += postfixe(arbre.get_ad())
liste.append(arbre.get_val())
return liste
|
def sanatize(input):
"""
Convert input command line arguments into format contained by documents.
"""
return input.upper()
|
def fahrenheit_to_rankine(fahrenheit: float, ndigits: int = 2) -> float:
"""
Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
>>> fahrenheit_to_rankine(273.354, 3)
733.024
>>> fahrenheit_to_rankine(273.354, 0)
733.0
>>> fahrenheit_to_rankine(0)
459.67
>>> fahrenheit_to_rankine(20.0)
479.67
>>> fahrenheit_to_rankine(40.0)
499.67
>>> fahrenheit_to_rankine(60)
519.67
>>> fahrenheit_to_rankine(80)
539.67
>>> fahrenheit_to_rankine("100")
559.67
>>> fahrenheit_to_rankine("fahrenheit")
Traceback (most recent call last):
...
ValueError: could not convert string to float: 'fahrenheit'
"""
return round(float(fahrenheit) + 459.67, ndigits)
|
def is_in(el, list):
"""Decides whether an element is
in a list of elements.
Arguments:
- `el`: an expression
- `a list of expressions`:
"""
for e in list:
if el.equals(e):
return True
return False
|
def parse_exif_val(val):
"""
Sometimes EXIF values are stored in a fraction as a string.
This will return the value as a decimal.
"""
nums = val.split('/')
if len(nums) == 1:
return float(nums[0])
return float(nums[0]) / float(nums[1])
|
def is_suspension(melody, position, cantus_firmus):
"""
Returns true if the note in the melody at the specified position is part of
a correctly formed suspension (dissonance resolving by step onto a
consonance)
"""
current_note = melody[position]
resolution_note = melody[position + 1]
cantus_firmus_note = cantus_firmus[position + 1]
suspension_interval = current_note - cantus_firmus_note
resolution_interval = resolution_note - cantus_firmus_note
if suspension_interval == 3 and resolution_interval == 2:
return True
if suspension_interval == 6 and resolution_interval == 5:
return True
return False
|
def valid_generalisation(new_norm, input_norm, ruleset_norm):
""" Check if it is useful to generalise the match on this rule
If we do not include all matches of the original rule in the new
rule, then the new rule will match more packets than the old. If
that extra packet-space matched has the same forwarding then this
is useful and could reduce the ruleset. Otherwise, it is not
worth exploring.
This checks both actions and match.
new_norm: The new, more general, rule normalised
input_norm: The input rule normalised
norm: The input ruleset normalised
return: True, if the generalisations is applicable to
the extra packet space.
For example consider:
Table 1 Table 2
IP1 -> Set(Out:1) Goto:2 TCP:80 -> [clear_actions]
* -> Goto:2 * -> []
When compressed to a single table
IP1, TCP:80 -> []
IP1 -> [Out:1]
TCP:80 -> []
* -> []
When installing in a reversed order pipeline:
Table 1 Table 2
TCP:80 -> [] IP1 -> [Out:1]
* -> Goto:2 * -> []
The rule IP1, TCP:80 won't be installed because IP1 is not matched.
Instead we collect the partial paths and compare against the action
of all.
"""
# Forwarding must be the same for the input rule's packet-space
if new_norm.intersection(input_norm) != input_norm:
return False
# Either: 1) Require all newly matched packets have the same forwarding
# in for the ruleset as a whole.
#if new_norm.intersection(ruleset_norm) != new_norm:
# return False
# Or 2) Check that at least some of newly matched packets have this same
# forwarding.
if new_norm.intersection(ruleset_norm) != input_norm.intersection(ruleset_norm):
return True
return False
|
def get_list_of_active_skills(utterances):
"""
Extract list of active skills names
Args:
utterances: utterances, the first one is user's reply
Returns:
list of string skill names
"""
result = []
for uttr in utterances:
if "active_skill" in uttr:
result.append(uttr["active_skill"])
return result
|
def matrixReshape(nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
A = [x for row in nums for x in row]
return [A[i*c:(i+1)*c] for i in range(r)] if c * r == len(A) else nums
|
def compose(d1, d2):
"""Compose two homomorphisms given by dicts."""
res = dict()
for key, value in d1.items():
if value in d2.keys():
res[key] = d2[value]
return res
|
def set_import_style(style, origin="unknown", version="unknown"):
""" Let EDIF determine an nuances for more accurate conversion """
if origin == "unknown":
style['views_as_components'] = False
elif origin == "OrCAD Capture":
style['views_as_components'] = True
return style
|
def meets_criteria(value):
"""Determine if a number meets the criteria
>>> meets_criteria(111111)
True
>>> meets_criteria(223450)
False
>>> meets_criteria(123789)
False
"""
digits = [int(d) for d in str(value)]
if len(digits) != 6:
return False
# No repeats.
if len(set(digits)) == len(digits):
return False
adjacent_same = False
prev = -1
for d in digits:
if d == prev:
adjacent_same = True
if d < prev:
return False
# On to the next iteration.
prev = d
return adjacent_same
|
def add_uic_ref(shape, properties, fid, zoom):
"""
If the feature has a valid uic_ref tag (7 integers), then move it
to its properties.
"""
tags = properties.get('tags')
if not tags:
return shape, properties, fid
uic_ref = tags.get('uic_ref')
if not uic_ref:
return shape, properties, fid
uic_ref = uic_ref.strip()
if len(uic_ref) != 7:
return shape, properties, fid
try:
uic_ref_int = int(uic_ref)
except ValueError:
return shape, properties, fid
else:
properties['uic_ref'] = uic_ref_int
return shape, properties, fid
|
def convert_strips_to_bytes_list(playcloud_strips):
"""Extract the data bytes from alist of playcloud strips"""
return [strip.data for strip in playcloud_strips]
|
def parse_data(data):
"""Takes a dictionary of keys and produces a single byte array,
ready to be encrypted.
:param data: Dictionary of (blockchain) private keys
:type data: ``dict``
:returns: Binary blob of encoded keys
:rtype: ``bytes``
"""
text = ""
tickers = ["BCH", "tBCH", "ETH"]
for tic in tickers:
if tic in data.keys():
add_key = tic.ljust(8, " ") + data[tic]
# Adding 8 for the length value itself
text = text + str(len(add_key) + 8).rjust(8, "0") + add_key
return bytes(text, "utf-8")
|
def _isfloat(x):
"""
returns True if x is a float,
returns False otherwise
"""
try:
float(x)
except:
return False
return True
|
def count_unique_word(x, sep=None):
""" Extract number of unique words in a string """
try:
return len(set(str(x).split(sep)))
except Exception as e:
print(f"Exception raised:\n{e}")
return 0
|
def b128_varint_decode(value: bytes, pos = 0):
"""
Reads the weird format of VarInt present in src/serialize.h of bitcoin core
and being used for storing data in the leveldb.
This is not the VARINT format described for general bitcoin serialization
use.
"""
n = 0
while True:
data = value[pos]
pos += 1
n = (n << 7) | (data & 0x7f) # 1111111
if data & 0x80 == 0: # each byte is greater than or equal to 0x80 except at the end
return (n, pos)
n += 1
|
def sentencify(sentence):
"""Ensures a capital letter at the beginning and a full stop at the end of a given sentence."""
sentence = list(sentence)
sentence[0] = sentence[0].upper()
if sentence[-1] != ".":
sentence.append(".")
sentence = "".join(sentence)
return sentence
|
def parsePreprocessorLine( line ):
""" Experimental """
parts = line.split( '"' )
fileName = parts[1]
noFileLine = line.replace( '"' + fileName + '"', '' )
parts = noFileLine.split()
lineNum = int( parts[1] )
flags = []
index = 2
while index < len( parts ):
flags.append( int( parts[index] ) )
index += 1
return lineNum, fileName, flags
|
def changeTubleToListOfDects(data, columns):
""" this function take the tuble returned by database and tranform it to list of dicts.
the keys of the dects is the table columns."""
result = []
columns = str(columns).split()
loop = len(columns)
for row in data:
d = {}
for i in range(loop):
d[str(columns[i])] = row[i]
result.append(d)
return result
|
def mock_any(cls):
"""Returns Any class to use in mock."""
class Any(cls):
"""Any class used for mocks."""
def __eq__(self, other):
return True
return Any()
|
def truncate(s, l):
"""
Truncates the string `s` to length `l`
"""
if l is None or len(s) <= l:
return s
return (s[:l-3] + '...') if l >= 3 else ''
|
def intersperse(lis, value):
"""Put value between each existing item in list.
Parameters
----------
lis : list
List to intersperse.
value : object
Value to insert.
Returns
-------
list
interspersed list
"""
out = [value] * (len(lis) * 2 - 1)
out[0::2] = lis
return out
|
def mult(k, v):
"""
Returns the vector result of multipling scalar k with vector v
"""
return tuple(k*e for e in v)
|
def IsStringInt(string_to_check):
"""Checks whether or not the given string can be converted to a integer.
Args:
string_to_check: Input string to check if it can be converted to an int.
Returns:
True if the string can be converted to an int.
"""
try:
int(string_to_check)
return True
except ValueError:
return False
|
def copy_location(new_node, old_node):
"""Copy the source location hint (`lineno` and `col_offset`) from the
old to the new node if possible and return the new one.
"""
new_attributes = getattr(new_node, '_attributes', ()) or ()
old_attributes = getattr(old_node, '_attributes', ()) or ()
for attr in 'lineno', 'col_offset':
if attr in old_attributes and attr in new_attributes \
and hasattr(old_node, attr):
setattr(new_node, attr, getattr(old_node, attr))
return new_node
|
def get_note(dist=0):
""" Compute the note based on the distance measurements, get percentages of each scale and compare """
# Config
# you can play with these settings
#scale = [-1, -5, 60, 60, -5 ,62, 62, -5, 64, 64, -5, 67, 67, -5, 69, 69, -5, 72, -5, -1]
#distances = [38, 29, 28, 24, 21, 21, 19, 17, 16, 13, 12, 11, 9, 7, 6, 5, 3, 2, 1, 0]
'''scale = [-1, -5, 60, -5 , 62, -5, 64, -5, 67, -5, 69, -5, 72, -5, -1]
distances = [40, 35, 24, 21, 19, 17, 13, 10, 9, 7, 5, 4, 2, .5, 0]'''
scale = [-1, -5, 60, -5 , 67, -5, 69, -5, 72, -5, -1]
distances = [40, 35, 21, 18, 16, 9, 6, 4, 2, .5, 0]
for index in range(len(distances)):
if dist>distances[index]:
return int(scale[index])
|
def maybe_tuple(value):
"""Return `value` as a tuple. If it is already a tuple, return it
unchanged. Otherwise return a 1-element tuple containing `value`."""
if isinstance(value, tuple):
return value
return (value,)
|
def TCn(x, ystress=1.0, eta_bg=0.1, gammadot_crit=0.1,n=0.5):
"""Three component model
Note:
.. math::
\sigma=\sigma_y+\sigma_y\cdot(\dot\gamma/\dot\gamma_c)^n+\eta_{bg}\cdot\dot\gamma
Args:
ystress: yield stress [Pa]
eta_bg : Background viscosity [Pa s]
gammadot_crit : Critical shear rate [1/s]
n: Shear thinning exponent
Returns:
stress : Shear Stress, [Pa]
"""
return ystress + ystress * (x / gammadot_crit) ** n + eta_bg * x
|
def filterObjInfo(objInfo):
"""
filter out noisy object info
Args:
objInfo (struct): object information
"""
# filter params
keep_id = [2, 5] # kept id
keep_class = [1, 2, 3, 4, 5, 6, 7, 8] # kept class
min_obj_area = 400 # minimal kept object (pixel^2) #zzh
# consecutive_visible_frame = 10
# disappear_times = 4
for k in list(objInfo.keys()):
if k not in keep_id or objInfo[k]['class'] not in keep_class:
del(objInfo[k])
return objInfo
|
def kwargs_to_flags(valid_flags, arguments):
""" Takes an iterable containing a list of valid flags and a flattened
kwargs dict containing the flag values received by the function.
The key for each dict entry should be the name of a valid flag for the
command being run, with any hypnens in the flag name replaced with
underscores (e.g. end-time -> end_time). Its corresponding value
should be a string, True (if that flag is included by itself),
or None/False to indicate the flag should be excluded.
Returns a stringified version of kwargs for use with CLI commands. """
flag_string = ''
for flag in arguments.keys():
val = arguments[flag]
if val is not None:
if flag in valid_flags:
tmp = ' --%s' % flag.replace('_', '-')
if type(val) == str:
flag_string += '%s "%s"' % (tmp, val)
elif type(val) == bool:
flag_string += tmp if val else ''
else:
raise TypeError('Invalid value for flag %s, expected \
type \'str\' or \'bool\' and got type \
\'%s\'' % (flag, type(val).__name__))
else:
raise NameError('Invalid flag with name %s' % flag)
return flag_string
|
def get_mod_mappings(mappings):
"""
Returns a dict of all known modification mappings.
Parameters
----------
mappings: collections.abc.Iterable[vermouth.map_parser.Mapping]
All known mappings.
Returns
-------
dict[tuple[str], vermouth.map_parser.Mapping]
All mappings that describe a modification mapping.
"""
out = {}
for mapping in mappings:
if mapping.type == 'modification':
out[mapping.names] = mapping
return out
|
def rotate(string, n):
"""Rotate characters in a string. Expects string and n (int) for
number of characters to move.
"""
return string[n:] + string[:n]
|
def is_external_plugin(appname):
"""
Returns true when the given app is an external plugin.
Implementation note: does a simple check on the name to see if it's
prefixed with "kolibri_". If so, we think it's a plugin.
"""
return not appname.startswith("kolibri.")
|
def status_to_dict(status_str):
"""
Helper that converts the semicolon delimited status values to
a dict
"""
status = {}
params = [param.strip() for param in status_str.split(";") if param.strip()]
for param in params:
(key, val) = param.split(":")
status[key] = val
return status
|
def bounds_to_offset(bounds):
"""Defines a transfer function offset given a transfer function.
"""
mi, ma = bounds
return mi
|
def insert_before(src: str, sub: str, data) -> str:
"""
>>> insert_before("long_filename.mha", ".mha", "_newfile")
long_filename_newfile.mha
"""
i = src.find(sub)
return f"{src[:i]}{data}{src[i:]}"
|
def eh_posicao_unidade (m, p):
"""Esta funcao indica se a posicao p do mapa p se encontra ocupada por uma unidade"""
return p in (m["ex1"], m["ex2"])
|
def flip_dict(dict, unique_items=False, force_list_values=False):
"""Swap keys and values in a dictionary
Parameters
----------
dict: dictionary
dictionary object to flip
unique_items: bool
whether to assume that all items in dict are unique, potential speedup but repeated items will be lost
force_list_values: bool
whether to force all items in the result to be lists or to let unique items have unwrapped values. Doesn't apply if unique_items is true.
"""
if unique_items:
return {v: k for k, v in dict.items()}
elif force_list_values:
new_dict = {}
for k, v in dict.items():
if v not in new_dict:
new_dict[v] = []
new_dict[v].append(k)
return new_dict
else:
new_dict = {}
for k, v in dict.items():
if v in new_dict:
if isinstance(new_dict[v], list):
new_dict[v].append(k)
else:
new_dict[v] = [new_dict[v], k]
else:
new_dict[v] = k
return new_dict
|
def is_reset(command: str) -> bool:
"""Test whether a command is a reset command
Parameters
----------
command : str
The command to test
Returns
----------
answer : bool
Whether the command is a reset command
"""
if "reset" in command:
return True
if command == "r":
return True
if command == "r\n":
return True
return False
|
def createFolderUrl(foldersIn):
"""
Takes a list of folders separated by '|' and returns the proper url
"""
folderUrl = ""
d = foldersIn.split("|")
for folder in d:
folderUrl += "job/" + folder + "/"
return folderUrl
|
def to_selector(labels):
"""
Transfer Labels to selector.
"""
parts = []
for key in labels.keys():
parts.append("{0}={1}".format(key, labels[key]))
return ",".join(parts)
|
def stream_output(output: dict):
"""
Transform a stream output into a human readable str
:param output:
:return:
"""
return "".join(output["text"])
|
def precision(x, p):
"""
Returns a string representation of `x` formatted with precision `p`.
Based on the webkit javascript implementation taken
`from here <https://code.google.com/p/webkit-mirror/source/browse/JavaScriptCore/kjs/number_object.cpp>`_,
and implemented by `randlet <https://github.com/randlet/to-precision>`_.
"""
import math
x = float(x)
if x == 0.0:
return "0." + "0" * (p - 1)
out = []
if x < 0:
out.append("-")
x = -x
e = int(math.log10(x))
tens = math.pow(10, e - p + 1)
n = math.floor(x / tens)
if n < math.pow(10, p - 1):
e = e - 1
tens = math.pow(10, e - p + 1)
n = math.floor(x / tens)
if abs((n + 1.0) * tens - x) <= abs(n * tens - x):
n = n + 1
if n >= math.pow(10, p):
n = n / 10.0
e = e + 1
m = "%.*g" % (p, n)
if e < -2 or e >= p:
out.append(m[0])
if p > 1:
out.append(".")
out.extend(m[1:p])
out.append("e")
if e > 0:
out.append("+")
out.append(str(e))
elif e == (p - 1):
out.append(m)
elif e >= 0:
out.append(m[: e + 1])
if e + 1 < len(m):
out.append(".")
out.extend(m[e + 1 :])
else:
out.append("0.")
out.extend(["0"] * -(e + 1))
out.append(m)
return "".join(out)
|
def remove_first_line(string):
"""
Returns the copy of string without first line (needed for descriptions which differ in one line)
:param string:
:return: copy of string.
"""
return '\n'.join(string.split('\n')[1:])
|
def col(loc, string):
"""Returns current column within a string, counting newlines as line separators.
The first column is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See
`ParserElement.parse_string` for more
information on parsing strings containing ``<TAB>`` s, and suggested
methods to maintain a consistent view of the parsed string, the parse
location, and line and column positions within the parsed string.
"""
s = string
return 1 if 0 < loc < len(s) and s[loc - 1] == "\n" else loc - s.rfind("\n", 0, loc)
|
def second_step_season(cal, teams):
"""
second_step_season(cal, teams) -> list
Create the second round for season
"""
scond_round_cal = []
for match in cal:
n, team1, team2 = match
scond_round_cal.append((int(n) + len(teams) - 1, team2, team1))
return scond_round_cal
|
def entity(ent):
"""
Returns the value of an entity separated from its datatype ('represented by a string')
:param ent:
:return:
"""
if ent.startswith('_'):
return ent, 'blank_node'
if ent.startswith('"'):
if '^^' in ent:
datatype, ent = ent[::-1].split('^^', maxsplit=1) # split once from the end
datatype, ent = datatype[::-1], ent[::-1]
datatype, ent = datatype[1:-1], ent[1:-1]
return ent, datatype
else:
return ent[1:-1], 'none'
else:
assert ent.startswith('http') or ent.startswith('file') or ent.startswith('urn') or ent.startswith('mailto')
# -- NB this assert only holds for this specific dataset.
return ent, 'uri'
|
def override_if_any(_ref, _path, _translated_ref, _translated_path, **kwargs):
"""override if any kwargs is True"""
return any(kwargs.values())
|
def from_uint8_bytes(uint8: bytes) -> int:
"""Convert from uint8 to python int."""
return int.from_bytes(uint8, byteorder="little")
|
def clean_number(text):
"""
>>> clean_number("3.14159")
3.14159
>>> clean_number("two")
>>> clean_number("1,956")
>>> row = ['heading', '23', '2.718']
>>> list(map(clean_number, row))
[None, 23.0, 2.718]
"""
try:
value= float(text)
except ValueError:
value= None
return value
|
def to_currency(n: int, currency: str = "USD") -> str:
"""
Returns numbers formatted as currency, in case of PYG
currency replaces default thousand separator ',' with '.'
"""
if currency == "PYG":
return str(n).translate(str.maketrans(",.", ".,"))
return f"{n:,}"
|
def deep_equals(value, other):
"""Compare elements and deeply compare lists,, tuples and dict values."""
value_type = type(value)
assert value_type is type(other), (value_type, type(other))
if value_type in (list, tuple):
return len(value) == len(other) and all(
deep_equals(value[i], other[i]) for i in range(len(value))
)
if value_type is set:
return len(value) == len(other) and all(element in other for element in value)
if value_type is dict:
return len(value) == len(other) and all(
key in other and deep_equals(value[key], other[key]) for key in value
)
return value == other
|
def bb_intersect(a,b):
"""Returns true if the bounding boxes (a[0]->a[1]) and (b[0]->b[1]) intersect"""
amin,amax=a
bmin,bmax=b
return not any(q < u or v < p for (p,q,u,v) in zip(amin,amax,bmin,bmax))
|
def cof2amp(z):
""" Calculate a signal amplitude from a model coefficient """
# z = amp*exp(phase*i) so amp is abs(z)
return abs(z)
|
def manhattan_dist(a, b):
"""
Returns the Manhattan distance between two points.
>>> manhattan_dist((0, 0), (5, 5))
10
>>> manhattan_dist((0, 5), (10, 7))
12
>>> manhattan_dist((12, 9), (2, 3))
16
>>> manhattan_dist((0, 5), (5, 0))
10
"""
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
def get_url(userid, access_token):
"""
Generates a useable facebook graph API url
"""
root = 'https://graph.facebook.com/'
endpoint = '%s/photos?type=uploaded&fields=source,updated_time&access_token=%s' % \
(userid, access_token)
return '%s%s' % (root, endpoint)
|
def _escape_regexp(s):
"""escape characters with specific regexp use"""
return (
str(s)
.replace('|', '\\|')
.replace('.', '\.') # `.` has to be replaced before `*`
.replace('*', '.*')
.replace('+', '\+')
.replace('(', '\(')
.replace(')', '\)')
.replace('$', '\\$')
)
|
def format_date(start_date, format, offset=None):
"""Format a date given an optional offset.
:param start_date: an Arrow object representing the start date
:param format: the format string
:param offset: an offset measured in days
:return: a formatted datestring
"""
if offset is not None:
start_date = start_date.shift(days=offset)
return start_date.format(format)
|
def get_viscosity_from_temperature(temperature):
"""
Finds the dynamics viscosity of air from a specified temperature. Uses Sutherland's Law
:param temperature: Temperature, in Kelvin
:return: Dynamic viscosity, in kg/(m*s)
"""
# Uses Sutherland's law from the temperature
# From CFDWiki
# Sutherland constant
C1 = 1.458e-6 # kg/(m*s*sqrt(K))
S = 110.4 # K
mu = C1 * temperature ** (3 / 2) / (temperature + S)
return mu
|
def fillout(template, adict):
"""returns copy of template filled out per adict
applies str.replace for every entry in adict
"""
rval = template[:]
for key in adict:
rval = rval.replace(key, adict[key])
return rval
|
def sphinx_type_in_doc(weight):
"""
:type weight: int
:param weight: weight of mail package, that we need to validate, type int
:return: if package weight > 200 - return False (we cannot deliver this package)
"""
if weight <= 0:
raise Exception("Weight of package cannot be 0 or below")
elif weight > 200:
return False
else:
return True
|
def _page_obj(json_object):
"""takes json input and returns a page object
Args:
json_object (dict): json data from api
Returns:
dict: json object for the 'pages' of an article
"""
query_object = json_object['query']
return(query_object['pages'])
|
def convert_mpas_fgco2(mpas_fgco2):
"""Convert native MPAS CO2 flux (mmol m-3 m s-1) to (molC m-2 yr-1)
Args:
mpas_fgco2 (xarray object): Dataset or DataArray containing native MPAS-O
CO2 flux output.
Returns:
conv_fgco2 (xarray object): MPAS-O CO2 flux in mol/m2/yr.
"""
# The -1 term ensures that negative is uptake of CO2 by the ocean.
# MPAS defaults to gregorian noleap calendar (thus, 365).
conv_fgco2 = mpas_fgco2 * -1 * (60 * 60 * 24 * 365) * (1 / 10 ** 3)
return conv_fgco2
|
def recipients_args(keys):
"""Returns the list representation of a set of GPG
keys to be used as recipients when encrypting."""
return [["--recipient", key.encode('ASCII')] for key in keys]
|
def enum_os_name(
os_int # type: int
):
"""Parse InMon-defined Operating System names"""
if os_int == 0:
os_name = "Unknown"
elif os_int == 1:
os_name = "Other"
elif os_int == 2:
os_name = "Linux"
elif os_int == 3:
os_name = "Windows"
elif os_int == 4:
os_name = "Darwin"
elif os_int == 5:
os_name = "HP-UX"
elif os_int == 6:
os_name = "AIX"
elif os_int == 7:
os_name = "Dragonfly"
elif os_int == 8:
os_name = "FreeBSD"
elif os_int == 9:
os_name = "NetBSD"
elif os_int == 10:
os_name = "OpenBSD"
elif os_int == 11:
os_name = "OSF"
elif os_int == 12:
os_name = "Solaris"
elif os_int == 13:
os_name = "Java"
else:
os_name = "Unknown"
return os_name
|
def index_where(collection, predicate):
""":yaql:indexWhere
Returns the index in the collection of the first item which value
satisfies the predicate. -1 is a return value if there is no such item
:signature: collection.indexWhere(predicate)
:receiverArg collection: input collection
:argType collection: iterable
:arg predicate: function of one argument to apply on every value
:argType predicate: lambda
:returnType: integer
.. code::
yaql> [1, 2, 3, 2].indexWhere($ > 2)
2
yaql> [1, 2, 3, 2].indexWhere($ > 3)
-1
"""
for i, t in enumerate(collection):
if predicate(t):
return i
return -1
|
def get_update_author_name(d_included):
"""Parse a dict and returns, if present, the post author name
:param d_included: a dict, as returned by res.json().get("included", {})
:type d_raw: dict
:return: Author name
:rtype: str
"""
try:
return d_included["actor"]["name"]["text"]
except KeyError:
return ""
except TypeError:
return "None"
|
def _select_cols(a_dict, keys):
"""Filteres out entries in a dictionary that have a key which is not part of 'keys' argument. `a_dict` is not
modified and a new dictionary is returned."""
if keys == list(a_dict.keys()):
return a_dict
else:
return {field_name: a_dict[field_name] for field_name in keys}
|
def _HighByte(x):
"""This reflects what can be expressed as immediates by add_imm and sub_imm"""
shift = 0
while x > 255:
x >>= 2
shift += 2
return x << shift
|
def cx_u(cD):
""" This calculates the coefficient of force in the x direction
with respect to the change in forward velocity of the aircraft
Assumptions:
None
Source:
J.H. Blakelock, "Automatic Control of Aircraft and Missiles"
Wiley & Sons, Inc. New York, 1991, (pg 23)
Inputs:
cD [dimensionless]
Outputs:
cx_u [dimensionless]
Properties Used:
N/A
"""
# Generating Stability derivative
cx_u = -2. * cD
return cx_u
|
def staticTunnelTemplate(user, device, ip, aaa_server, group_policy):
"""
Template for static IP tunnel configuration for a user.
This creates a unique address pool and tunnel group for a user.
:param user: username id associated with static IP
:type user: str
:param device: hostname of device
:type device: str
:param ip_start: first IP address in address pool
:type ip_start: str
:param aaa_server: name of authentication server for tunnel group
:type aaa_server: str
:param group_policy: name of group policy to attach tunnel groups to
:type group_policy: str
:return: configuration for the ASA
:rtype: str
"""
config = ""
# ip local pool <USER> X.X.X.X mask 255.255.255.255
config += f"ip local pool {user} {str(ip)} mask 255.255.255.255\n"
# tunnel-group <USER> type remote-access
config += f"tunnel-group {user} type remote-access\n"
# tunnel-group <USER> general-attributes
config += f"tunnel-group {user} general-attributes\n"
# address-pool <USER>
config += f"address-pool {user}\n"
# authentication-server-group <AAA_SERVER>
config += f"authentication-server-group {aaa_server}\n"
# default-group-policy <GROUP-POLICY>
config += f"default-group-policy {group_policy}\n"
# tunnel-group <USER> webvpn-attributes
config += f"tunnel-group {user} webvpn-attributes\n"
# group-url https://<DEVICE>/<USER> enable
config += f"group-url https://{device}/{user} enable\n"
return config
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.