content stringlengths 42 6.51k |
|---|
def is_test_file_name(file_name):
"""
Returns whether the given file name is the name of a test file.
Parameters
----------
file_name : `str`
A file's name.
Returns
-------
is_test_file_name : `bool`
"""
if file_name == 'test.py':
return True
if... |
def get_exchange_name(cls):
"""Returns the exchange name of the given class, or None"""
return getattr(cls, '__exchange_name__', None) |
def GassmannModel(Phi, Kdry, Gdry, Kmat, Kfl):
"""
GASSMANN MODEL
Gassmann's equations.
Written by Dario Grana (August 2020)
Parameters
----------
Phi : float or array_like
Porosity (unitless).
Kdry : float
Bulk modulus of dry rock (GPa).
Gdry : float
Shear m... |
def tri_state_value(tri_state: str) -> bool:
"""Returns whether a tri-state code turns a switch on or off.
:param tri_state: The tri-state code.
:type tri_state: str
:returns: True if the tri-state codes turns a switch on, False otherwise.
:rtype: str
"""
return 'F' == tri_state[-1:] |
def _IsPemSectionMarker(line):
"""Returns (begin:bool, end:bool, name:str)."""
if line.startswith('-----BEGIN ') and line.endswith('-----'):
return True, False, line[11:-5]
elif line.startswith('-----END ') and line.endswith('-----'):
return False, True, line[9:-5]
else:
return False, False, '' |
def search_for_vowels_return_data(word):
"""Return data based on any vowels found."""
vowels = set('aeiou')
return vowels.intersection(set(word)) |
def _find_by_prior_token(tokens, keys):
"""
If any key in keys appears in tokens, return the token following said key.
If more than one key in keys matches, use the first matching key in keys.
Otherwise, return None.
"""
# Determine which key matches
match_key = None
for key in keys:
... |
def tail(sequence):
"""
Returns the slice of *sequence* containing all elements after the first.
"""
return sequence[1:] |
def is_cast(field_spec):
"""
is this spec requires casting
:param field_spec: to check
:return: true or false
"""
if not isinstance(field_spec, dict):
return False
config = field_spec.get('config', {})
return 'cast' in config |
def get_particles(words, _lines):
"""parser particles command"""
if len(words) <= 0:
raise Exception("Decay need particles")
name = words[0]
return ("Particle", {"name": name, "params": words[1:]}) |
def sanitize_list_values(value):
"""Parse a string of list items to a Python list.
This is super hacky...
:param str value: string-representation of a Python list
:return: List of strings
:rtype: list
"""
if not value:
return []
if value.startswith("["):
value = value[... |
def two_complement_2_decimal(value, n_bits):
"""Converts a two's component binary integer into a decimal integer."""
for current_bit in range(n_bits):
bit = (value >> current_bit) & 1
if bit == 1:
left_part = value >> (current_bit + 1)
left_mask = 2**(n_bits - (current_bi... |
def getFieldShortName(field_name):
""" Simplifies `field_name` in the exported dataframe by removing Watson Assistant prefixes """
return field_name.replace('request.','').replace('response.','').replace('context.system.','').replace('context.','') |
def convert_power_to_energy(power_col, sample_rate_min="10T"):
"""
Compute energy [kWh] from power [kw] and return the data column
Args:
df(:obj:`pandas.DataFrame`): the existing data frame to append to
col(:obj:`string`): Power column to use if not power_kw
sample_rate_min(:obj:`fl... |
def toggleprefix(s):
"""Remove - prefix is existing, or add if missing."""
return ((s[:1] == '-') and [s[1:]] or ["-"+s])[0] |
def reverse(lst):
""" Helping function for convex_hull() that reverses the order of a list
pre: lst is a python list
post: returns a list which is a mirror image of lst (lst is reversed)
"""
new_lst = []
for i in range(len(lst) - 1, -1, -1):
new_lst.append(lst[i])
return ... |
def _list_complement(A, B):
"""Returns the relative complement of A in B (also denoted as A\\B)"""
return list(set(B) - set(A)) |
def non_repeating_substring(str1: str) -> int:
"""
This problem follows the Sliding Window pattern, and we can use a similar dynamic sliding window strategy as
discussed in Longest Substring with K Distinct Characters. We can use a HashMap to remember the last index of each
character we have processed. ... |
def _get_instance_id_from_arn(arn):
"""
Parses the arn to return only the instance id
Args:
arn (str) : EC2 arn
Returns:
EC2 Instance id
"""
return arn.split('/')[-1] |
def _parse_boolean(value, default=False):
"""
Attempt to cast *value* into a bool, returning *default* if it fails.
"""
if value is None:
return default
try:
return bool(value)
except ValueError:
return default |
def get_hertz(reg, key):
"""Returns the hertz for the given key and register"""
return int(reg * 2 ** (key / 12)) |
def removeParenthesis(s):
""" Remove parentheses from a string.
Params
------
s (str): String with parenthesis.
"""
for p in ('(', ')'):
s = s.replace(p, '')
return s |
def signal_initialization(signature):
"""Generate the Signal initialization from the function signature."""
paren_pos = signature.find('(')
name = signature[:paren_pos]
parameters = signature[paren_pos:]
return f' {name} = Signal{parameters}\n' |
def run_program(program, opcode_pos):
""" Runs a supplide Intcode program.
>>> run_program([1,0,0,0,99])
[2,0,0,0,99]
"""
opcode = program[opcode_pos]
if opcode == 99:
return program
operand1 = program[program[opcode_pos + 1]]
operand2 = program[program[opcode_pos + 2... |
def to_int(inp):
"""
returns items converted to int if possible also works for tuples\n
also works recursively
watch out because passing a string '12t' will be ripped into a list [1,2,t]
"""
if isinstance(inp[0],list):
return tuple(to_int(l) for l in inp)
if isinstance(... |
def normalize_pipeline_name(name=''):
"""Translate unsafe characters to underscores."""
normalized_name = name
for bad in '\\/?%#':
normalized_name = normalized_name.replace(bad, '_')
return normalized_name |
def rescale(value, orig_min, orig_max, new_min, new_max):
"""
Rescales a `value` in the old range defined by
`orig_min` and `orig_max`, to the new range
`new_min` and `new_max`. Assumes that
`orig_min` <= value <= `orig_max`.
Parameters
----------
value: float, default=None
... |
def merge_mappings(target, other, function=lambda x, y: x + y):
"""
Merge two mappings into a single mapping. The set of keys in both
mappings must be equal.
"""
assert set(target) == set(other), 'keys must match'
return {k: function(v, other[k]) for k, v in target.items()} |
def encapsulate_name(name):
"""
Encapsulates a string in quotes and brackets
"""
return '[\"'+name+'\"]' |
def handle_config_cases(some_config): # C
"""
Simply used to standardise the possible config entries. We always want a list
"""
if type(some_config) is list:
return some_config
if some_config is None:
return []
else:
return [some_config] |
def get_dict_buildin(dict_obj, _types=(int, float, bool, str, list, tuple, set, dict)):
"""
get a dictionary from value, ignore non-buildin object
"""
ignore = {key for key in dict_obj if not isinstance(dict_obj[key], _types)}
return {key: dict_obj[key] for key in dict_obj if key not in ignore} |
def lfilter(*args, **kwargs):
"""Take filter generator and make a list for Python 3 work"""
return list(filter(*args, **kwargs)) |
def get_struct_neighbors(grid, structure_num, proximity):
"""Given a grid of structures, returns the closest proximity neighbors to the given structure
params:
- Grid: 2D numpy array
- structure_num: int
- proximity: int
:returns
- A list of neighboring structures to the current structure_... |
def res_spec2res_no(res_spec):
"""simple extraction function"""
if not res_spec:
return False
if (len(res_spec) == 4):
return res_spec[2]
if (len(res_spec) == 3):
return res_spec[1]
return False |
def __formulate_possible_contexts(doctype=None, docname=None, fieldname=None, parenttype=None, parent=None):
"""
Possible Contexts in Precedence Order:
key:doctype:name:fieldname
key:doctype:name
key:parenttype:parent
key:doctype:fieldname
key:doctype
key:parenttype
"""
... |
def construct_fip_id(subscription_id, group_name, lb_name, fip_name):
"""Build the future FrontEndId based on components name.
"""
return ('/subscriptions/{}'
'/resourceGroups/{}'
'/providers/Microsoft.Network'
'/loadBalancers/{}'
'/frontendIPConfigurations/{}... |
def vat_checksum(number):
"""
Calculate the check digit for romanian VAT numbers.
"""
weights = (7, 5, 3, 2, 1, 7, 5, 3, 2)
number = (9 - len(number)) * '0' + number
check = 10 * sum(w * int(n) for w, n in zip(weights, number))
return check % 11 % 10 |
def tasks_to_job_ids(task_list):
"""Returns the set of job IDs for the given tasks."""
return set([t.get_field('job-id') for t in task_list]) |
def reasoner_graph_to_cytoscape(graph):
"""Generate cytoscape spec for query graph."""
cs_graph = {}
nodes = []
edges = []
for node in graph["nodes"]:
cs_node = {}
node_types = ""
if isinstance(node["type"], str):
node_types = node["type"]
else:
... |
def find_zeroes(f, a, b, epsilon=1e-10):
"""
Find the zero-crossing of the function f in the interval [a, b]. The function assumes that there is a single
zero-crossing in the interval.
:param f: The function.
:param a: The lower bound of the interval.
:param b: The upper bound of the interval.... |
def convert_dict_of_sets_to_dict_of_lists(dictionary):
"""
Returns the same dictionary, but the values being sets are now lists
@param dictionary: {key: set(), ...}
"""
out = dict()
for key, setvalue in dictionary:
out[key] = list(setvalue)
return out |
def convert_celsius_to_fahrenheit(deg_celsius):
"""
Convert degress celsius to fahrenheit
Returns float value - temp in fahrenheit
Parameters:
-----------
deg_celcius: float
temp in degrees celsius
Returns:
-------
float
"""
return (9/5) * deg_celsius + ... |
def has_only_valid_characters(hex: str) -> bool:
"""Return True if hex has only valid hexadecimal characters."""
_valid_hex_characters = set("#abcdef0123456789")
return set(hex) <= _valid_hex_characters |
def _is_png(filename):
"""Determine if a file contains a PNG format image.
Args:
filename: string, path of the image file.
Returns:
boolean indicating if the image is a PNG.
"""
return filename.endswith('.png') |
def fix_v(value, other=False, dot=False):
"""
share.fix_v(T.trade_info()[1][1]))
:param other: if True, the "()%:" will be removed
:param dot: if True, the dot will be removed
:param value: value is editing here
:return: list of float number, first item is the value of the share,
second of... |
def shortcut_Euler_Tour(tour):
"""Find's the shortcut of the Euler Tour to obtain the Approximation.
"""
Tour = []
for vertex in tour:
if vertex not in Tour:
Tour.append(vertex)
Tour.append(tour[0])
return Tour |
def relative_refractive_index(n_core, n_clad):
"""
Calculate the relative refractive index (Delta) for an optical fiber.
Args:
n_core : the index of refraction of the fiber core [-]
n_clad: the index of refraction of the fiber cladding [-]
Returns:
the relative refract... |
def greet(friend, money):
"""Greet people. Say hi they are your friend. Give them $20 if they are your friend and you have enough money. Steal $10 from them if they are not your friend.
"""
if friend and (money > 20):
print("Hi")
money = money - 20
elif friend:
print("Hello")... |
def valToBool(rawVal):
"""
Convert string or integer value from the config file or command line to a boolean.
"""
retVal = False
if type(rawVal) == str:
retVal = (rawVal.strip().strip('"').lower()[0] in ['y','t','1'])
else:
try:
retVal = bool(rawVal)
except:
retVal = False
retur... |
def lower_case(words):
"""
Set ALL words to LOWER case.
"""
return [w.lower() for w in words] |
def get_epsilon_array(gamma_array):
"""Flip 0 and 1 for epsilon from gamma"""
return list(map(lambda d: '1' if d == '0' else '0', gamma_array)) |
def refines_constraints(storage, constraints):
"""
Determines whether with the storage as basis for the substitution map there is a substitution that can be performed
on the constraints, therefore refining them.
:param storage: The storage basis for the substitution map
:param constraints: The const... |
def parse_authentication(authentication):
"""Split the given method:password field into its components.
authentication (str): an authentication string as stored in the DB,
for example "plaintext:password".
return (str, str): the method and the payload
raise (ValueError): when the authenticati... |
def createExpressionString(exprList):
"""Creates a string of expressions
Keyword arguments:
exprList -- List of expression strings
Joins the expression strings to one String using as delimiter semicolon
Returns string of expressions
"""
expressionString = ";".join(exprList)... |
def is_writable_file_like(obj):
"""return true if *obj* looks like a file object with a *write* method"""
return callable(getattr(obj, 'write', None)) |
def extract_minor(chord):
"""Checks whether the given cord is specified as "minor". If so, it pops out
the specifier and returns a boolean indicator along with the clean chord.
E.g.
----
Am --> True, A
B# --> False, B#
F#m --> True, F#
"""
if chord[-1] == 'm':
... |
def split_in_words_and_lowercase(line):
"""Split a line of text into a list of lower-case words."""
parts = line.strip('\n').replace('-', ' ').replace("'", " ").replace('"', ' ').split()
parts = [p.strip('",._;?!:()[]').lower() for p in parts]
return [p for p in parts if p != ''] |
def set_dict_values(d, value):
"""
Return dict with same keys as `d` and all values equal to `value'.
"""
return dict.fromkeys(d, value) |
def c(n, alpha, beta, x):
"""The third term of the recurrence relation from Wikipedia, * P_n-2^(a,b)."""
term1 = 2 * (n + alpha - 1)
term2 = (n + beta - 1)
term3 = (2 * n + alpha + beta)
return term1 * term2 * term3 |
def parse_line(data):
""" Takes an IRC line and breaks it into the three main parts; the prefix,
command, and parameters. It gets returned in the form of
``(prefix, command, params)``.
This follows :rfc:`2812#section-2.3.1`, section 2.3.1 regarding message
format.
>>> mes... |
def minkowski_distance(x, y, p=2):
"""
Calculates the minkowski distance between two points.
PARAMETERS
x - the first point
y - the second point
p - the order of the minkowski algorithm.
Default = 2. This is equal to the euclidian distance.
If the order is 1,... |
def parse_records(database_records):
"""
A helper method for converting a list of database record objects into a list of dictionaries, so they can be returned as JSON
Param: database_records (a list of db.Model instances)
Example: parse_records(User.query.all())
Returns: a list of dictionaries, e... |
def create_distr_name(dep_vars=None, cond_vars=None) -> str:
"""
Creates a name based on the given variables of a distribution and the variables it is
conditioned on
:param dep_vars: The random variables of a distribution. x in p(x|z)
:param cond_vars: The conditioned-on variables of a distribution.... |
def bisect_true_first(arr):
"""Binary search (first True) arr = [0, ..., 0, 1, ..., 1].
^
"""
lo, hi = 0, len(arr)
while lo < hi:
mid = lo + hi >> 1
if arr[mid]: hi = mid
else: lo = mid + 1
return lo |
def call_method(obj, methodName):
"""
Execute a method of an object using previously passed arguments with setarg filter
"""
method = getattr(obj, methodName)
if hasattr(obj, '__call_arguments'):
ret = method(*obj.__call_arguments)
del obj.__call_arguments
return ret
retu... |
def get_class_string(obj):
"""
Return the string identifying the class of the object (module + object name,
joined by dots).
It works both for classes and for class instances.
"""
import inspect
if inspect.isclass(obj):
return "{}.{}".format(
obj.__module__,
... |
def get_total_categories(studios):
"""Gets total category counts.
Args:
studios (array-like): a list of studios, either as MongoDB representations
or as dictionaries.
Returns:
A dictionary mapping each category to a total block count.
"""
categories = dict()
fo... |
def group_anagrams_ver1(strs: list) -> list:
"""Mine solution
this is slower than the ver2 because the ver1 has one more for loop iteration."""
anagrams = []
for i, word in enumerate(strs):
if i == 0:
anagrams.append([word])
else:
exist = False
# Compa... |
def GetNextTokenIndex(tokens, pos):
"""Get the index of the next token after 'pos.'"""
index = 0
while index < len(tokens):
if (tokens[index].lineno, tokens[index].column) >= pos:
break
index += 1
return index |
def _get_prefixes_for_action(action):
"""
:param action: iam:cat
:return: [ "iam:", "iam:c", "iam:ca", "iam:cat" ]
"""
(technology, permission) = action.split(':')
retval = ["{}:".format(technology)]
phrase = ""
for char in permission:
newphrase = "{}{}".format(phrase, char)
... |
def door_from_loc(env, loc):
"""
Get the door index for a given location
The door indices correspond to: right, down, left, up
"""
if loc == 'east' or loc == 'front':
return (2, 1), 2
if loc == 'south' or loc == 'right':
return (1, 2), 3
if loc == 'west' or loc == 'behind':
... |
def make_node_bodies(objects, meta):
"""Return the node containing internationalized data."""
node = {}
for body_id, body in objects.items():
node[body_id] = body
return node |
def bin_position(max_val):
""" ` _ @ """
symbol_map = {0: " `", 1: " _", 2: " @"}
if max_val <= 3:
return [symbol_map[i] for i in range(max_val)]
first = max_val // 3
second = 2 * first
return [" `"] * first + [" _"] * (second - first) + [" @"] * (max_val - second) |
def squareSum(upperLimit):
""" Returns the square of the sum of [1,upperLimit]
--param
upperLimit : integer
--return
square of sums : integer
"""
totalSum = sum(list(range(1,upperLimit+1)))
return (totalSum ** 2) |
def calcular_costo_envio(kilometros):
"""
num -> num
calcular el costo del envio cuando se trabaja fuera de la ciudad
>>> calcular_costo_envio(500)
57500
>>> calcular_costo_envio(50)
5750
:param kilometros: num que representa los kilometros recorridos en el envio
:return: num q... |
def squareCoordsForSide(s):
"""
Square with side s
origin = 0,0
"""
coords = (
( # path
(0,0), (s,0), (s,s), (0,s),
),
)
return coords |
def transform_members_list_into_motif_dic(center_dic, members_dic_list, mdl_cost, mean_dist):
"""
This functions creates the dictionary related to the motif composed by the subsequences in members_dic_list
:param center_dic: dictionary related to the center of motif
:type center_dic: dic
:param mem... |
def wrap(x, m):
"""
Mathematical modulo; wraps x so that 0 <= wrap(x,m) < m. x can be negative.
"""
return (x % m + m) % m |
def clean_label(labels):
""" Remove undesired '' cases """
labels = list(filter(''.__ne__, labels))
return labels |
def merge(seq1, seq2):
"""Merge two sorted arrays into a single array"""
if not seq1 or not seq2:
raise ValueError("Input sequences do not exist or empty")
merged_size = len(seq1) + len(seq2)
merged_seq = [None] * merged_size
seq1_index = 0
seq2_index = 0
merged_index = 0
... |
def lmap_call(func, args_seq):
"""map every func call and return list result
>>> from operator import add
>>> lmap_call(add, [(1, 2), (3, 4)])
[3, 7]
"""
result = []
for args in args_seq:
result.append(func(*args))
return result |
def get_data_version(str_hash, hash_dict):
"""
Obtain version string from hash
:param str_hash: Hash string to check
:param hash_dict: Dictionary with hashes for different blocks
:return: List with version string and hash string
"""
str_version = 'Unknown'
if 'versions' in hash_dict:
... |
def split(list):
"""
Divide the unsorted list at midpoint into sublists
Returns two sublists - left and right
Take overall O(k log n) time
"""
mid = len(list)//2
left = list[:mid]
right = list[mid:]
return left, right |
def apply_formatting(msg_obj, formatter):
"""
Receives a messages object from a thread and returns it with
all the message bodies passed through FORMATTER. Not all
formatting functions have to return a string. Refer to the
documentation for each formatter.
"""
for x, obj in enumerate(msg_obj... |
def subspan(arg1, arg2):
"""Return whether the (x,y) range indicated by arg1 is entirely contained in arg2
>>> subspan((1,2), (3,4))
False
>>> subspan((1,3), (2,4))
False
>>> subspan((3,4), (1,2))
False
>>> subspan((2,4), (1,3))
False
>>> subspan((1,4), (2,3))
False
>>> ... |
def chunks(lst, *lens):
"""Split the supplied list into sub-lists of the given lengths, and return the list of sub-lists."""
retval = []
start = 0
for n in lens:
retval.append(lst[start:start + n])
start += n
return retval |
def new_file_path(photo_date):
"""
Get the new file path for the photo. An example would be 2019/January/31st
:param photo_date: The list for the date that is supplied from the exif data
:return: Array of all the new file paths
"""
if len(photo_date) == 3:
month = photo_date[0]
d... |
def _strip_unsafe_kubernetes_special_chars(string: str) -> str:
"""
Kubernetes only supports lowercase alphanumeric characters, "-" and "." in
the pod name.
However, there are special rules about how "-" and "." can be used so let's
only keep
alphanumeric chars see here for detail:
https://... |
def R6(FMmin, alpha_A):
"""
R6 Determining the maximum assembly preload FMmax
(Sec 5.4.3)
---
FMmin :
alpha_A :
"""
#
FMmax = alpha_A * FMmin # (R6/1)
#
return FMmax
# |
def convert_ft_to_in(len_ft):
"""Function to convert length in ft to inches"""
ans = len_ft * 12
return round(ans,2) |
def check_vulnerable_package(version, version_string):
"""Check if the request version available in vulnerable_versions."""
if(version in version_string.split(",")):
return True
return False |
def is_anno_moderate(anno):
"""
Check if the difficulty of the KITTI annotation is "moderate"
Args:
anno: KITTI annotation
Returns: bool if "moderate"
"""
height = anno['bbox'][3] - anno['bbox'][1]
if (anno['occluded'] > 1) or (anno['truncated'] > 0.30) or height < 25:
retu... |
def create_grid(taille):
"""
Function that generate a grid of size: taille*taille
The grid is empty (only ' ')
"""
game_grid = []
for i in range(0,taille):
game_grid.append([' ' for j in range(taille)])
return game_grid |
def builtin_2swap(a, b, c, d):
"""Modify the stack: ( a b c d -- c d a b )."""
return (c, d, a, b) |
def all_to_bytes(some_type):
"""Makes UTF-8 string from bytes, int, float"""
if isinstance(some_type, bytes):
return some_type
elif isinstance(some_type, int):
return str(some_type).encode()
elif isinstance(some_type, float):
return str(some_type).encode()
else:
retur... |
def set_r0_multiplier(params_dict, mul):
"""[summary]
Args:
params_dict (dict): model parameters
mul (float): float to multiply lockdown_R0 by to get post_lockdown_R0
Returns:
dict: model parameters with a post_lockdown_R0
"""
new_params = params_dict.copy()
new_par... |
def normalize( p ):
""" Naive renormalization of probabilities """
S = sum( p )
return [ pr/S for pr in p ] |
def get_api_url(remote):
""" Default Artifactory API URL, based on remote name
:param remote: Remote name (e.g. bincrafters)
:return: Artifactory URL
"""
return f"https://{remote}.jfrog.io/artifactory/api" |
def swap_position(string, pos1, pos2):
"""
swap position X with position Y means that the letters at indexes X and Y
(counting from 0) should be swapped.
"""
new_string = list(string)
new_string[pos1] = string[pos2]
new_string[pos2] = string[pos1]
return ''.join(new_string) |
def flatten(x, par = '', sep ='.'):
"""
Recursively flatten dictionary with parent key separator
Use to flatten augmentation labels in DataFrame output
Args:
x (dict): with nested dictionaries.
par (str): parent key placeholder for subsequent levels from root
sep (str: '.', '|',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.