content stringlengths 42 6.51k |
|---|
def mk_eqv_expr(expr1, expr2):
"""
returns an or expression
of the form (EXPR1 <=> EXPR2)
where EXPR1 and EXPR2 are expressions
"""
return {"type" : "eqv" ,
"expr1" : expr1 ,
"expr2" : expr2 } |
def get_zk_path(config_file_path):
"""Get zk path based upon config file path.
e.g. '/var/config/config.manageddata.spam.domain_hidelist' ->
'/config/manageddata/spam/domain_hidelist'
"""
return '/' + config_file_path.split('/')[-1].replace('.', '/') |
def reconstruct_by_ids(raw_dct, key, reference_list, default_dct):
"""
Filling missing values in the dict read by raw_read_file.
:param raw_dct: initial dict
:param key: key with indexes in the raw_dct
:param reference_list: reference list of indexes containing all values
:param default_dct: dic... |
def minhash_lsh_probability(s: float, bands: int, rows: int) -> float:
"""Probability of Minhash LSH returning item with similarity s"""
return 1 - (1 - s ** rows) ** bands |
def _padding(length):
"""
Figure out how much padding is required to pad 'length' bits
up to a round number of bytes.
e.g. 23 would need padding up to 24 (3 bytes) -> returns 1
:param length: the length of a bit array
:return: the number of bits needed to pad the array to a round number of byt... |
def dict2argstring(argString):
"""Converts an argString dict into a string otherwise returns the string unchanged
:Parameters:
argString : str | dict
argument string to pass to job - if str, will be passed as-is else if dict will be
converted to compatible string
:return: a... |
def check_permutations(s_one, s_two):
"""
Question 2: Given two strings, write a method to decide if one is a permutation
of the other.
"""
if len(s_one) != len(s_two):
return False
h_table = {}
for index, char in enumerate(s_two):
h_table[char] = index
for char in set(... |
def get_tracking_sort_by_urls(direction, sort_by):
"""
Args:
direction - string, either 'asc' or 'desc'
sort_by - column name to sort by
Returns:
dict with keys for name and value is the url
"""
urls = {}
base = '/tracking?sort={}&direction={}'
urls['date'] = base.for... |
def check_config(H, P, N, O, C):
"""
Checks if config data format is correct
"""
if H != 'irc.twitch.tv': return False
if not isinstance(P, int): return False
if P != 6697: return False
if not isinstance(N, str): return False
if not isinstance(O, str): return False
if O[:6] != 'oaut... |
def shunt(infix):
"""Function which returns the infix expression in postfix"""
# Convert input input to a stack ish list
infix = list(infix)[::-1]
# Operator Stack Output list.
opers , postfix = [] ,[]
# Operator precedence
prec = {'*': 100 , '.': 80, '|': 60, ')': 40 , '(':20}
# Loop through the input ... |
def filter_entity(entity_ref):
"""Filter out private items in an entity dict.
:param entity_ref: the entity dictionary. The 'dn' field will be removed.
'dn' is used in LDAP, but should not be returned to the user. This
value may be modified.
:returns: entity_ref
"""
if entity_re... |
def expmod(b, e, m):
""" b^e mod m """
if e == 0:
return 1
t = expmod(b, e / 2, m)**2 % m
if e & 1:
t = (t * b) % m
return t |
def get_present_types(robots):
"""Get unique set of types present in given list"""
return {type_char for robot in robots for type_char in robot.type_chars} |
def parse_csv_data(csv_filename):
"""
This function takes a csv file and returns the data in a list
:param csv_filename: the name of the csv file to be read
:return: the data in a list format
"""
csv_data = []
f = open(csv_filename, 'r')
for line in f.readlines():
sp... |
def set_bit(value, index, new_bit):
""" Set the index'th bit of value to new_bit, and return the new value.
:param value: The integer to set the new_bit in
:type value: int
:param index: 0-based index
:param new_bit: New value the bit shall have (0 or 1)
:return: Changed value
:rtype... |
def fetch(addr=None, heap=None):
"""Symbolic accessor for the fetch command"""
return '@', addr, heap |
def _is_kanji(char):
""" Check if given character is a Kanji. """
return ord("\u4e00") < ord(char) < ord("\u9fff") |
def _has_callable(type, name) -> bool:
"""Determine if `type` has a callable attribute with the given name."""
return hasattr(type, name) and callable(getattr(type, name)) |
def dehumanize_time(time):
"""Convert a human readable time in 24h format to what the database needs.
Args:
time::String - The time to convert.
Returns:
_::Int - The converted time.
"""
if time[3:] == '15':
return int(time[:2] + '25')
if time[3:] == '30':
... |
def valuefy(strings, type_cast=None):
"""Return a list of value, type casted by type_cast list
Args:
strings (str): A string with value seperated by '_'
type_cast (List[types]): A list with type for each elements
Returns:
List[any]: A list of values typecasted by type_cast ... |
def _find_shortest_indentation(lines):
"""Return most shortest indentation."""
assert not isinstance(lines, str)
indentation = None
for line in lines:
if line.strip():
non_whitespace_index = len(line) - len(line.lstrip())
_indent = line[:non_whitespace_index]
... |
def basesStr(bases):
"""Pretty print list of bases"""
return ', '.join([str(base) for base in bases]) |
def strip_unexecutable(lines):
"""Remove all code that we can't execute"""
valid = []
for l in lines:
if l.startswith("get_ipython"):
continue
valid.append(l)
return valid |
def pure_literal(ast_set):
"""
Performs pure literal rule on list format CNF
:param: Result of cnf_as_disjunction_lists
:return: CNF with clauses eliminated
>>> pure_literal([['a']])
[]
>>> pure_literal([[(Op.NOT, 'a')], ['x', (Op.NOT, 'y'), 'b'], ['z'], ['c', 'd']])
[]
>>> pure_lite... |
def _dict_path(d, *steps):
"""Traverses throuth a dict of dicts.
Returns always a list. If the object to return is not a list,
it's encapsulated in one.
If any of the path steps does not exist, an empty list is returned.
"""
x = d
for key in steps:
try:
x = x[key]
... |
def isRepeatedNumber(string):
""" Returns True if any value in the list passed
as a parameter repeats itself """
for i in string:
if string.count(i) > 1:
return True |
def cut(word, part="www."):
"""
Where word is a string
Removes the section specified by part
"""
split = word.split(part)
truncated = "".join(split)
return truncated |
def SplitVersion(version):
"""Splits version number stored in an int.
Returns: tuple; (major, minor, revision)
"""
assert isinstance(version, int)
(major, remainder) = divmod(version, 1000000)
(minor, revision) = divmod(remainder, 10000)
return (major, minor, revision) |
def check_any_str(list_to_check, input_string):
"""Check if any items in a list have a string in them.
Parameters
----------
list_to_check : list[str]
A list of strings.
input_string : str
A string to check items in the list.
Returns
-------
Boolean
True or Fals... |
def parse_search(data):
""" parse search result from tunein """
qr_name = data['head']['title']
search_result = []
search_error = {}
if data['head']['status'] == "200":
for r in data['body']:
if 'type' in r:
if r['type'] == 'audio':
search_resu... |
def get_stream_names(streams, type=None):
"""
extract stream name from xdf stream
:param streams: list of dictionnaries
xdf streams to parse
:param type: string
type of stream, eg. 'Signal' or 'Markers'
:return: list
list of stream name contained in streams
"""
if... |
def dict2opts(
dct,
doubledash=True,
change_underscores=True,
assign_sign='='):
""" dictionary to options """
opts = []
for kw in dct.keys():
# use long or short options?
dash = '--' if doubledash else '-'
# remove first underscore if it is present
opt... |
def count(n, target):
"""Count # of times non-None target exists in linked list, n."""
ct = 0
if n is None:
return 0
if n.value == target:
ct = 1
return ct + count(n.next, target) |
def repeating_key(bs, key):
"""
Implementation of repeating-key XOR.
"""
# XOR each byte of the byte array with its appropriate key byte.
return bytearray([bs[i] ^ key[i%len(key)] for i in range(len(bs))]) |
def z_fn_nu(nu, f, p, pv0, e, B, R, eta):
"""
Steady-state solution for z as a fn of nu,
where nu is calculated at steady-state using cubsol3
"""
return (B*(1 - e*nu)*p - p/pv0)/(1 + B*(1 - e*nu)*p - p/pv0) |
def repr(obj):
""" :func:`repr` is a function for representing of object using object's name
and object's properties
"""
properties = {k: v for k, v in vars(obj).items()}
return f"{type(obj).__name__}({properties})" |
def get_expression(date):
"""Returns a date expression for a date object.
Concatenates start and end dates if no date expression exists.
:param dict date: an ArchivesSpace date
:returns: date expression for the date object.
:rtype: str
"""
try:
expression = date["expression"]
... |
def pad_sentences(sentences_indexed, sequence_length):
"""
Pad setences to same length
"""
sentences_padded = []
for sentence in sentences_indexed:
num_padding = sequence_length - len(sentence)
sentences_padded.append(sentence[:sequence_length - 1] + [0] * max(num_padding, 1))... |
def event_summary(event_info, summary_keys=['host', 'task', 'role', 'event']):
""" Provide a quick overview of the event code_data
:param event_info: dict/json of a job event
:param summary_keys: list of fields that represent a summary of the event
the event data is checked at the ... |
def get_stereo_cymbal2_note(instrument=24, start=0.0, duration=0.5, amplitude=30000, pitch=8.00,
pan=0.7, fc=5333, q=40.0, otamp=0.5, otfqc=1.5, otq=0.2, mix=0.2, hit=None):
"""
; Cymbal
; Sta Dur Amp Pitch Pan Fc Q OTAmp OTFqc OTQ Mix
i24 0.0 0.25 30000 8.00 0.7 5333 40.... |
def evaluate_sensitivity(tp: int, fn: int) -> float:
"""Sensitivity, aka Recall, aka True Positive Rate (TPR).
$TPR=\dfrac{TP}{TP + FN}$
Args:
tp: True Positives
fn: False Negatives
"""
try:
return tp / (tp + fn)
except ZeroDivisionError:
return 0.0 |
def binary_xor(a: int, b: int):
"""
Take in 2 integers, convert them to binary,
return a binary number that is the
result of a binary xor operation on the integers provided.
>>> binary_xor(25, 32)
'0b111001'
>>> binary_xor(37, 50)
'0b010111'
>>> binary_xor(21, 30)
'0b01011'
... |
def in_3d_box(box, coords):
"""
Check if point is in a box
Args:
box (tuple): ((x0, x1), (y0, y1), (z0, z1)).
coords (tuple): (x, y, z).
Returns
bool
"""
cx = coords[0] >= box[0][0] and coords[0] <= box[0][1]
cy = coords[1] >= box[1][0] and coords[1] <= box[1][1]
cz =... |
def get_distance_by_dir(inputD, genom_loc, intern_loc, Dhit):
"""Limits the hit by a distance window depending on peak's position relative-to-feature """
[D_upstr, D_downstr] = inputD
# D_upstr = D_downstr when len(input_D) = 1
if genom_loc == "upstream" or genom_loc == "overlapStart":
... |
def good_fit_step(x, y):
"""Returns a step interval to use when selecting keys.
The step will ensure that we create no more than num_shards.
"""
step, remainder = divmod(x, y)
if remainder:
step = (x + remainder) // y
if step == 0:
step = 1
return step |
def get_vg_obj_name(obj):
""" Gets the name of an object from the VG dataset.
This is necessary because objects are inconsistent--
some have 'name' and some have 'names'. :(
Args:
obj: an object from the VG dataset
Returns string containing the name of the object
"""
try:
na... |
def sort_employees_by_salary(employee_list):
"""
Returns a new employee list, sorted by low to high salary then last_name
"""
employee_list.sort(key=lambda employee: (employee.last_name, employee.job.salary))
return employee_list |
def common_start(*args):
""" returns the longest common substring from the beginning of sa and sb """
def _iter():
for s in zip(*args):
if len(set(s)) < len(args):
yield s[0]
else:
return
out = "".join(_iter()).strip()
result = [s for s in... |
def not_none(**kwargs):
"""Confirms that at least one of the items is not None.
Parameters
----------
**kwargs : dict of any, optional
Items of arbitrary type.
Returns
-------
dict of any
Items that are not None.
Raises
-------
ValueError
If all of the ... |
def agreement_type(value):
"""Display agreement_type"""
value = value.strip()
return {
'OG': 'Original general',
'OS': 'Original specific',
}.get(value, 'Unknown') |
def is_start_byte(b: int) -> bool:
"""Check if b is a start character byte in utf8
See https://en.wikipedia.org/wiki/UTF-8
for encoding details
Args:
b (int): a utf8 byte
Returns:
bool: whether or not b is a valid starting byte
"""
# a non-start char has encoding 10xx... |
def clear_timestamp(x):
"""Replaces (recursively) values of all keys named 'timestamp'."""
if isinstance(x, dict):
if 'timestamp' in x:
x['timestamp'] = 'cleared'
for v in x.values():
clear_timestamp(v)
elif isinstance(x, list) or isinstance(x, tuple):
for v i... |
def _swap_list_items(arr, i1, i2) -> list:
"""Swap position of two items in a list.
Parameters
----------
arr :
list in which to swap elements
i1 :
element 1 in list
i2 :
element 2 in list
Returns
-------
list
copy of list with swapped elements
... |
def _UTMLetterDesignator(Lat):
"""
This routine determines the correct UTM letter designator for the given latitude
returns 'Z' if latitude is outside the UTM limits of 84N to 80S
Written by Chuck Gantz- chuck.gantz@globalstar.com
"""
if 84 >= Lat >= 72:
return 'X'
elif 72 > Lat >= 6... |
def check_number_threads(numThreads):
"""Checks whether or not the requested number of threads has a valid value.
Parameters
----------
numThreads : int or str
The requested number of threads, should either be a strictly positive integer or "max" or None
Returns
-------
numThreads ... |
def redondeo(coordenadas, base=1/12):
"""
Devuelve las coordenadas pasadas redondeadas
Parametros:
coordenadas -- lista de latitud y longitud
base -- base del redondeo
"""
return base * round(coordenadas/base) |
def isnointeger(number):
""" This method decides if a given floating point number is an integer or not --
so only 0s after the decimal point.
For example 1.0 is an integer 1.0002 is not."""
return number % 1 != 0 |
def formatFilename( name ):
"""
replace special characters in filename and make lowercase
"""
return name.\
replace( " ", "" ).\
replace( ".", "_" ).\
replace( "-", "_" ).\
replace( "/", "_" ).\
replace( "(", "_" ).\
replace( ")", "_" ).\
low... |
def cat_arg_and_value(arg_name, value):
"""Concatenate a command line argument and its value
This function returns ``arg_name`` and ``value
concatenated in the best possible way for a command
line execution, namely:
- if arg_name starts with `--` (e.g. `--arg`):
`arg_name=value` is returned (... |
def python_to_swagger_types(python_type):
"""
:param python_type:
"""
switcher = {
"str": "string",
"int": "integer",
"float": "number",
"complex": "number",
"datetime.datetime": "string",
"datetime": "string",
"dict": "object",
"bool": "... |
def readable(filename: str) -> bool:
"""Conditional method to check if the given file (via filename)
can be opened in this thread.
:param filename: name of the file
:type filename: str
:return: true if file can be read, otherwise false
:rtype: bool
"""
try:
handler = open(filena... |
def strip_yaml_extension(filename):
"""
remove ending '.yaml' in *filename*
"""
return filename[:-5] if filename.lower().endswith('.yaml') else filename |
def build_s3_path(s3_filepath, unit, category, filename):
"""
Input:
maria-quiteria/files/tcmbapublicconsultation/2020/mensal/12/consulta-publica-12-2020.json
Output:
s3://dadosabertosdefeira/maria-quiteria/files/tcmbapublicconsultation/2020/mensal/12/<unit>/<category>/<filename>
"""
... |
def apply_func(key_kwargs_, func):
"""
given some keywords and a function call the function
:param key_kwargs_: a tuple of (key, args) to use
:param func: function to call
:return: the key for this and the value returned from calling the func
"""
key = key_kwargs_[0]
kwargs_ = ke... |
def p_approx ( a, rho, temperature ):
"""Returns approximate pressure."""
# Original expression given by Groot and Warren, J Chem Phys 107, 4423 (1997), alpha = 0.101
# This is the revised formula due to Liyana-Arachchi, Jamadagni, Elke, Koenig, Siepmann,
# J Chem Phys 142, 044902 (2015)
import nu... |
def sum_pairs(ints, s):
"""Pair to sum up to s."""
lookup = {}
for n, i in enumerate(ints):
lookup.setdefault(i, []).append(n)
options = []
for k in lookup:
if s - k in lookup:
if s - k == k and len(lookup[s - k]) < 2:
continue
if s - k == k ... |
def stem(word: str) -> str:
"""Get the stem of a word"""
return word.lower().rstrip(",.!:;'-\"").lstrip("'\"") |
def represents_int(s):
""" A custom Jinja filter function which determines if a string input represents a number"""
try:
int(s)
return True
except ValueError:
return False |
def push_n(int_n):
"""
Opcode to push some number of bytes.
"""
assert 1 <= int_n <= 75, "Can't push more than 75 bytes with PUSH(N) in a single byte."
n = hex(int_n)[2:]
n = n if len(n) == 2 else '0' + n
return bytes.fromhex(n) |
def expand_cond(cond):
"""
Change the input SQL condition into a dict.
:param cond: the input SQL matching condition
:type cond: list or dict
:rtype: dict
"""
conddict = {
'join': [], # list of tuple (type, table, [(var1, var2), ...])
'where': [], # list of tuple (type, va... |
def extensions(includes):
"""Format a list of header files to include."""
return [
"".join([i.split(".")[0], ".h"]) for i in includes if i.split(".")[0] != "types"
] |
def validDate(date: str) -> bool:
"""Return whether a string follows the format of ####-##-##."""
if len(date) == 10:
return date[0:4].isnumeric() and date[5:7].isnumeric() and date[8:10].isnumeric() and date[4] == "-" and date[7] == "-"
return False |
def locToPath(p):
"""Back compatibility -- handle converting locations into paths.
"""
if "path" not in p and "location" in p:
p["path"] = p["location"].replace("file:", "")
return p |
def fabclass_2_umax(fab_class):
"""
Maximum displacement for a given fabrication class acc. to EC3-1-6.
Parameters
----------
fab_class : {"fcA", "fcB", "fcC"}
"""
# Assign imperfection amplitude, u_max acc. to the fabrication class
if fab_class is 'fcA':
u_max = 0.0... |
def connect_vec_list(vec_list1, vec_lists2):
"""
get connected vec lists of two lists
"""
return (vec_list1 + vec_lists2) |
def get_teaching_hours(school_type):
"""Return the number of teaching hours / day for different school types."""
teaching_hours = {
'primary':4,
'primary_dc':4,
'lower_secondary':6,
'lower_secondary_dc':6,
'upper_secondary':8,
'secondary':8,
'secondary_dc':8
}
return teaching_hours[school_type] |
def is_int(str_val: str) -> bool:
""" Checks whether a string can be converted to int.
Parameters
----------
str_val : str
A string to be checked.
Returns
-------
bool
True if can be converted to int, otherwise False
"""
return not (len(str_val) == 0 or any([c not ... |
def isnumeric(s):
""" Converts strings into numbers (floats) """
try:
x = float(s)
return x
except ValueError:
return float('nan') |
def _describe_instance_attribute_response(response, attribute, attr_map):
"""
Generates a response for a describe instance attribute request.
@param response: Response from Cloudstack.
@param attribute: Attribute to Describe.
@param attr_map: Map of attributes from EC2 to Cloudstack.
@return: R... |
def comp_float(x, y):
"""Approximate comparison of floats."""
return abs(x - y) <= 1e-5 |
def from_epsg(code):
"""Given an integer code, returns an EPSG-like mapping.
Note: the input code is not validated against an EPSG database.
"""
if int(code) <= 0:
raise ValueError("EPSG codes are positive integers")
return {'init': "epsg:%s" % code, 'no_defs': True} |
def Bayes_runtime(fmin, rt_40):
"""
Compute runtime of Bayesian PE for a min. freq. fmin
given the rt_40 as the runtime when fmin=40 Hz.
"""
return rt_40 * (fmin / 40.)**(-8./3.) |
def bids_dir_to_fsl_dir(bids_dir):
"""Converts BIDS PhaseEncodingDirection parameters (i,j,k,i-,j-,k-) to FSL direction (x,y,z,x-,y-,z-)."""
fsl_dir = bids_dir.lower()
if "i" not in fsl_dir and "j" not in fsl_dir and "k" not in fsl_dir:
raise ValueError(
f"Unknown PhaseEncodingDirection ... |
def isSvnUrl(url):
""" this function returns true, if the Url given as parameter is a svn url """
if url.startswith("[svn]"):
return True
elif "svn:" in url:
return True
return False |
def filter_stories(stories, triggerlist):
"""
Takes in a list of NewsStory-s.
Returns only those stories for whom
a trigger in triggerlist fires.
"""
filtered_stories = []
for story in stories:
for trigger in triggerlist:
if trigger.evaluate(story):
filt... |
def split(sorting_list):
"""
Divide the unsorted list at midpoint into sublist
Returns two sublist - left and right
Takes overall O(log n) time
"""
mid = len(sorting_list) // 2
left = sorting_list[: mid]
right = sorting_list[mid:]
return left, right |
def count_affected_areas(hurricanes):
"""Find the count of affected areas across all hurricanes and return as a dictionary with the affected areas as keys."""
affected_areas_count = dict()
for cane in hurricanes:
for area in hurricanes[cane]['Areas Affected']:
if area not in affected_areas_count:
... |
def SetPageSize(unused_ref, args, request):
"""Set page size to request.pageSize.
Args:
unused_ref: unused.
args: The argparse namespace.
request: The request to modify.
Returns:
The updated request.
"""
if hasattr(args, 'page_size') and args.IsSpecified('page_size'):
request.pageSize ... |
def task10(number: int) -> None:
"""
Function that take an integer number as string and print the "It is an even number" if the number is even,
otherwise print "It is an odd number".
Input: number
Output: None
"""
if number % 2 == 0:
print("It is an even number")
else:
p... |
def get_features(geojson):
"""
Helper function to extract features
from dictionary. If it doesn't find
it, raise a value error with a more
informative error message.
"""
try:
features = geojson["features"]
except KeyError:
raise KeyError(f"{geojson} is an invalid GeoJSON.... |
def prime_check(n):
"""Checks if natural number n is prime.
Args:
n: integer value > 0.
Returns:
A boolean, True if n prime and False otherwise.
"""
assert type(n) is int, "Non int passed"
assert n > 0, "No negative values allowed, or zero"
if n == 1:
return... |
def parse_cluster_pubsub_numsub(res, **options):
"""
Result callback, handles different return types
switchable by the `aggregate` flag.
"""
aggregate = options.get('aggregate', True)
if not aggregate:
return res
numsub_d = {}
for _, numsub_tups in res.items():
for chann... |
def generate_marketplace(queue_size):
"""
Generates the marketplace
:type queue_size: int
:param queue_size: the queue size for each producer
:return dict
:return: a dict representing the markeplace
"""
marketplace = {"queue_size_per_producer": queue_size}
return marketplace |
def namestr(obj, namespace):
"""
called via:
>>> a = 'some var'
>>> b = namestr(a, globals())
assert b == ['a'] #for test
"""
return [name for name in namespace if namespace[name] is obj] |
def ModelMatch(comp):
"""
Summary : This functions compares a list to model with
typo handling
Parameters : comparison list
Return : Boolean
"""
for item in comp:
try:
item = item.lower()
except:
continue
if item == 'mode... |
def dechaffify(chaffy_val, chaff_val = 98127634):
""" Dechaffs the given chaffed value.
chaff_val must be the same as given to chaffify().
If the value does not seem to be correctly chaffed, raises a ValueError. """
val, chaff = divmod(chaffy_val, chaff_val)
if chaff != 0:
raise ValueError... |
def CONCAT_ARRAYS(*arrays):
"""
Concatenates arrays to return the concatenated array.
See https://docs.mongodb.com/manual/reference/operator/aggregation/concatArrays/
for more details
:param arrays: A set of arrays(expressions).
:return: Aggregation operator
"""
return {'$concatArrays': ... |
def suit_to_color(a):
"""Red is 1. Black is 0."""
return (a == 'H' or a == 'D') |
def apply_pbcs(index: int, boundary: int) -> int:
"""Applies periodic boundary conditions (PBCs).
Args:
index (int): Index to apply the PBCs to
boundary (int): Length of the boundary
Returns:
int: Index with PBCs applied to it
"""
if index < 0:
index += boundary
... |
def tokenize_char(sent):
"""
Tokenize a string by splitting on characters.
"""
return list(sent.lower()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.