content stringlengths 42 6.51k |
|---|
def a2hex(s):
"""Converts strin to hex representation: ff:00:ff:00 ..."""
return ':'.join(x.encode('hex') for x in s) |
def quote_dsn_param(s, _special=' \\\''):
"""Apply the escaping rule required by PQconnectdb."""
if not s:
return "''"
for char in _special:
if char in s:
return "'%s'" % s.replace("\\", "\\\\").replace("'", "\\'")
return s |
def path_cost(path):
"""The total cost of a path (which is stored in a tuple
with the final action."""
# path = (state, (action, total_cost), state, ... )
if len(path) < 3:
return 0
else:
action, total_cost = path[-2]
return total_cost |
def increment_counts(counters, data):
"""
Counter structure:
{
"PRDP (program)": {
"2014 (year)":
{
"budget": 123,
"count": 123,
"has_kml": 123,
"has_image": 123,
"has_clas... |
def get_bounds(im_centre, xlen, width, height):
"""
calculate the bottom left and top right coordinates
"""
x, y = im_centre
ylen = xlen * (width / height)
hx = xlen / 2
hy = ylen / 2
# bottom left and then top right
return (x - hx, y - hy), (x + hx, y + hy) |
def render_to_log_kwargs(wrapped_logger, method_name, event_dict):
"""
Render `event_dict` into keyword arguments for :func:`logging.log`.
The `event` field is translated into `msg` and the rest of the `event_dict`
is added as `extra`.
This allows you to defer formatting to :mod:`logging`.
..... |
def get_xdist_worker_id(config):
"""
Parameters
----------
config: _pytest.config.Config
Returns
-------
str
the id of the current worker ('gw0', 'gw1', etc) or 'master'
if running on the 'master' node.
If not distributing tests (for example passing `-n0` or not pas... |
def weighted_average(items, weights):
"""
Returns the weighted average of a list of items.
Arguments:
items is a list of numbers.
weights is a list of numbers, whose sum is nonzero.
Each weight in weights corresponds to the item in items at the same index.
items and weights must be... |
def rectangle_default(length=7, width=4):
"""
7. Function with more than one default input arguments
This function demonstrates how a function handles more than one input
arguments and returns multiple outputs
This function calculates the area and perimeter of a rectangle
length: the length of ... |
def find_possible_orientations(field, coords, length):
"""
Find possible orientations for a ship.
ARGUMENTS:
field - field in which to find orientations
coords - origin coords of ship in format [x, y]
length - length of ship in format int(length)
RETURNS:
list of possible orientations... |
def gc(i):
"""Return the Gray code index of i."""
return i ^ (i >> 1) |
def logistic(y, t=0, r=1, k=1):
"""Logistic growth model
"""
dydt = r*y*(1 - y/k)
return dydt |
def get_window_start_times(profileDict):
"""
Gets the times of the start of the sampling windows used in the profiled
run
Args:
profileDict (dict): Dictionary of values representing an Arm MAP
profiled run
Returns:
List of start times of sampling window
"""
asse... |
def filter_groups(lint_list):
"""Remove lints"""
return [x for x in lint_list if x['cellId'] != 'group'] |
def get_band_names(list_of_contents):
"""
Will return a dictionary of names of bands
:param list_of_contents:
:return: dict of bands
"""
bands = {}
for x in list_of_contents:
if x.endswith('.tif'):
if 'band4' in x:
bands['red'] = x
if 'band... |
def get_neighbours(x, y, z):
"""Get neighbours for three dimension point."""
neighbours = []
for nx in (x - 1, x, x + 1):
for ny in (y - 1, y, y + 1):
for nz in (z - 1, z, z + 1):
if (any(num < 0 for num in (nx, ny, nz))
or (x, y, z) == (nx, ny, nz... |
def treatment(pop_input, variables_input, treatment_method_input):
"""Modular function which receives the treatment method that will be applied for individuals which get out of the function borders."""
return treatment_method_input(pop_input, variables_input) |
def delete_resource(payload):
"""Delete resource"""
return {'Dummy': 'ResourceDeleted'} |
def in_ranges(char, ranges):
"""Determines whether the given character is in one of several ranges.
:param int char: An integer encoding a Unicode character.
:param ranges: A sequence of pairs, where the first element of each pair is
the start Unicode character code (including) and the second elem... |
def _calc_histogram_bins(count):
"""
Calculates experience-based optimal bins number for histogram.
There should be enough number in each bin. So we calc bin numbers according to count. For very small count(1 -
10), we assign carefully chosen number. For large count, we tried to make sure there are 9-1... |
def handle_filename_collision(filename, filenames):
"""
Avoid filename collision, add a sequence number to the name when required.
'file.txt' will be renamed into 'file-01.txt' then 'file-02.txt' ...
until their is no more collision. The file is not added to the list.
Windows don't make the d... |
def choose(n, k, d={}):
"""The binomial coefficient "n choose k".
Args:
n: number of trials
k: number of successes
d: map from (n,k) tuples to cached results
Returns:
int
"""
if k == 0:
return 1
if n == 0:
return 0
try:
return d[n, k]
ex... |
def edits1(word):
"""
Return all strings that are one edits away.
"""
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def splits(word):
"""
return a list of all possible pairs
that the input word is made of
"""
return [(word[:i], word[i:]) for i in range(len(word)+1)]... |
def lookup_verbs(roots, spacy_lemmas):
"""Return a full of list light verbs and all its forms"""
def flatten(list_of_lists):
"Return a flattened list of a list of lists"
return [item for sublist in list_of_lists for item in sublist]
verblist = []
for root in roots:
verbs = [key... |
def locate_candidate_recommendation(recommendation_list):
"""
Locates a candidate recommendation for workflow testing in our recommendation list.
Args:
recommendation_list (list[Recommendation]): List of possible recommendations to be our candidate.
Returns:
Recommendation: A candidate... |
def ipc_error_response(resp_data):
"""Make error response."""
response = ("error", resp_data)
return response |
def flux(rho, u_max, rho_max):
"""
Computes the traffic flux F = V * rho.
Parameters
----------
rho : numpy.ndarray
Traffic density along the road as a 1D array of floats.
u_max : float
Maximum speed allowed on the road.
rho_max : float
Maximum car density allowed on ... |
def pick_one(iterable):
"""
Helper function that returns an element of an iterable (it the iterable is ordered this will be the first
element).
"""
it = iter(iterable)
return next(it) |
def extract_fixed_price(fixed_payment_type: str) -> int:
""" Returns the fixed price as int for message_printer() if-statement """
# Accounts for job_post["Budget"] == "$1,234"
if "," in fixed_payment_type:
return int((fixed_payment_type).replace(",", "").lstrip("$"))
# Accounts for job_post["Bu... |
def normalize_name(name):
"""Normalizes a transformice nickname."""
if name[0] == "+":
name = "+" + (name[1:].capitalize())
else:
name = name.capitalize()
if "#" not in name:
name += "#0000"
return name |
def get_relation_phrases(relations):
"""
:param relations: yaml dict of relation to partial phrases
:return: a mapping from relation to all possible phrases
"""
rel_to_phrases = {}
for key, val in relations.items():
for gender in ['male', 'female']:
rel = val[gender]['rel']
... |
def guess_ip_version(ip_string):
""" Guess the version of an IP address, check its validity
\param ip_string A string containing an IP address
\return The version of the IP protocol used (int(4) for IPv4 or int(6) for IPv6, int(0) otherwise)
"""
import socket
try:
ipv4_bu... |
def create_dictionary(all_groups, sub_keys):
"""
Create nested dictionary - each group within a file and its properties.
Parameters
----------
all_groups : List, groups within .h5 file.
sub_keys : List, keys for each group within .h5 file.
Returns
-------
dictionary : Dictionary in... |
def calculate_sample_required(conc1, conc2, vol2):
"""Classic C1V1 = C2V2. Calculates V1.
All arguments should be floats.
"""
if conc1 == 0.0:
conc1 = 0.000001 # don't want to divide by zero :)
return (conc2 * vol2) / conc1 |
def multv(A, V, MOD):
""" produit matrice/vecteur: A * V """
a00, a10, a01, a11 = A
b0, b1 = V
return [(a00 * b0 + a10 * b1) % MOD,
(a01 * b0 + a11 * b1) % MOD] |
def rk4_step(f, x0, t0, t1):
"""
One time step of Runge-Kutta method
f : function dx_dt(t0, x0)
x0 : initial condition
t0 : this step time
t1 : next step time
"""
delta_t = (t1 - t0)
delta_t_half = delta_t * 0.5
t_half = t0 + delta_t_half
# Step 1
s1 = f(t0, x0)
... |
def nside2npix(nside):
"""
Convert healpix resolution (nside) to the number of healpix pixels in a full-sky map.
"""
return 12 * nside * nside |
def _check_n_components(n_features, n_components):
"""Checks that n_components is less than n_features and deal with the None
case"""
if n_components is None:
return n_features
if 0 < n_components <= n_features:
return n_components
raise ValueError('Invalid n_components, must be in [1, %d]' % n... |
def Newcombprecangles(epoch1, epoch2):
"""
----------------------------------------------------------------------
Purpose: Calculate precession angles for a precession in FK4, using
Newcombs method (Woolard and Clemence angles)
Input: Besselian start epoch1 and Besselian end epoch2
Returns: A... |
def polygon_clip(poly, clip_poly):
"""
Computes the intersection of an arbitray polygon with a convex clipping polygon, by
implementing Sutherland-Hodgman's algorithm for polygon clipping.
:param poly: list of tuples, representing the arbitrary polygon
:param clip_poly: list of tuples, representing... |
def kHat(c, ell, em, ess=-2):
"""
Compute diagonal elements of sparse matrix to be solved.
Inputs:
c (float): a * omega
ell (int): swsh mode number
em (int): mode number
ess (int) [-2]: spin number
Returns:
kHat (float): diagonal element
"""
# print(ell)... |
def prune_empty(row):
"""
prune attributes whose value is None
"""
new_row = {}
for k in row:
if row[k]:
new_row[k] = row[k]
return new_row |
def test_lambda(n):
"""
>>> [f() for f in test_lambda(3)]
[0, 1, 2]
"""
return [lambda v=i: v for i in range(n)] |
def flt(val):
"""
Returns
-------
returns a float value
"""
try:
return float(val)
except:
return float(0) |
def getdate(targetconnection, ymdstr, default=None):
"""Convert a string of the form 'yyyy-MM-dd' to a Date object.
The returned Date is in the given targetconnection's format.
Arguments:
- targetconnection: a ConnectionWrapper whose underlying module's
Date format is used
- ym... |
def is_float(s):
"""
Returns True if string 's' is float and False if not.
's' MUST be a string.
:param s: string with number
:type s: str
:rtype: bool
"""
try:
float(s)
return True
except ValueError:
return False |
def getAliasString(emailList):
"""
Function to extract and return a list (String, comma separated)
of Mamga aliases from provided email list
"""
toAlias = ''
for toAdd in emailList:
toA = toAdd.split('@molten-magma.com')[0]
if toAlias == '':
toAlias = '%s'... |
def reverse_list(in_list):
"""Return list in reversed index order"""
return list(reversed(in_list)) |
def lever_pressing(eventcode, lever1, lever2=False):
"""
:param eventcode: list of event codes from operant conditioning file
:param lever1: eventcode for lever pressing or
:param lever2: optional parameter for second lever eventcode if two levers are used
:return: count of first lever presses, seco... |
def check_theme(theme, themes):
"""Check if theme is legit.
"""
if theme in themes:
return theme
print(('(!) Theme "{0}" not in {1}, '
'using "{2}"').format(theme, themes, themes[0]))
return themes[0] |
def flat_list(l):
""" Convert a nested list to a flat list """
try:
return [item for sublist in l for item in sublist]
except:
return l |
def deepupdate_dict(target, update):
"""
Updates dicts and calls itself recursively if a list or dict is encountered
to perform updating at nesting levels instead of just the first one.
Does not work with tuples.
"""
for k, v in update.items():
if isinstance(v, list):
target[k] = target.get(k, []) + v
elif... |
def generate_power_sets(sample_list):
"""Generate all possible subsets from the `sample_list`.
Parameters
----------
sample_list : [int]
Returns
-------
[[int]]
All possible subsets
"""
num_of_combinations = pow(2, len(sample_list))
all_sets = []
for elemen... |
def classify(gc_content):
"""
gc_content - a number representing the GC content
Returns a string representing GC Classification. Must return one of
these: "low", "moderate", or "high"
"""
classification = "high"
if gc_content < .4:
classification = "low"
elif gc_content <= .6:
... |
def df_string(*args):
"""
Creates DF command line string
"""
return ('df', ) + args |
def get_vcf(config, var_caller, sample):
"""
input: BALSAMIC config file
output: retrieve list of vcf files
"""
vcf = []
for v in var_caller:
for s in sample:
vcf.append(config["vcf"][v]["type"] + "." +
config["vcf"][v]["mutation"] + "." + s + "." + v)... |
def show_popover_descripcion(descripcion):
"""
mostrar un pop up con la descripcion
de las notificaciones
"""
return {'descripcion': descripcion} |
def report_spdu(spdu_dict: dict) -> str:
"""A testing/debugging function that returns a printable report of SPDU contents after parsing
:param spdu_dict: a dictionary containing SPDU fields such as returned from parse_received_spdu()
:type spdu_dict: dict
:return: a string representation of the SPDU f... |
def generate_city_code(citi):
"""
A dictionary of city codes used by megabus to identify each city.
:return: The proper city code, string.
"""
citi = citi.strip() # Strips the city provided of any extra spaces
citi = citi.upper()
citi_codes = {
'ALBANY, NY': '89',
'A... |
def move1(course):
"""Meh
>>> move1(EX_INPUT.split('\\n'))
(15, 10, 150)
"""
horiz = 0
depth = 0
for mvt in course:
if not len(mvt):
continue
where, count = mvt.split(" ")
count = int(count)
if where == "forward":
horiz += count
... |
def calculate_initial_position_of_sliding_window(num_seeds):
"""
Calculate the initial position where the sliding position
will start its calculations.
"""
# Calculate the initial position of the sliding window:
# We know that the left part of the first interval in the sliding window is:
# i... |
def get_selected_sentences_with_different_vocabulary(sorted_score_index, sorted_indeces_no_predicted_chunks, step_size, majority_category, inactive_learning, prefer_predicted_chunks):
"""
Help function to do the final selection of samples.
"""
#print("sorted_score_index", sorted_score_index)
#print... |
def comma_separated_list(value):
"""
Configuration-friendly list type converter.
Supports both list-valued and string-valued inputs (which are comma-delimited lists of values, e.g. from env vars).
"""
if isinstance(value, list):
return value
if value == "":
return []
retu... |
def cross(A, B):
"""Calculate the cross product of two arrays.
Args:
A(list) - the left side of the cross product
B(list) - the right side of the cross product
Returns:
A list containing all possible combinations of elements from A and B
"""
return [ s+t for s in A for t in ... |
def get_head(page, marker):
""" Returns page content before the marker """
if page is None: return None
if marker in page:
return page.split(marker,1)[0] |
def get_uce_name(header):
"""use own function vs. import from match_contigs_to_probes - we don't want lowercase"""
return header.lstrip('>').split(' ')[0].split('_')[0] |
def cvtRange(x, in_min, in_max, out_min, out_max):
"""
Convert a value, x, from its old range of
(in_min to in_max) to the new range of
(out_min to out_max)
"""
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min |
def unique(x):
"""Convert a list in a unique list."""
return list(set(x)) |
def tenth(raw_table, base_index):
""" Word value divide by ten """
raw_value = raw_table[base_index]
if raw_value == 0xFFFF:
return None
sign = 1
if raw_value & 0x8000:
sign = -1
return sign * (raw_value & 0x7FFF) / 10 |
def combine_dictionaries(
dictionaries):
"""Utility for merging entries from all dictionaries in `dictionaries`.
If there are multiple dictionaries with the same key, the entry from the
latest dictionary is used for that key.
Args:
dictionaries: Iterable of dictionaries to combine entries of.
Retur... |
def fetch_token_mock(self,
token_url=None,
code=None,
authorization_response=None,
body='',
auth=None,
username=None,
password=None,
method='POST',
... |
def compress(uncompressed):
# uncompressed is a string
"""Compress a string to a list of output symbols."""
# Build the dictionary.
dict_size = 256
dictionary = {chr(i): i for i in range(dict_size)}
w = ""
result = []
for c in uncompressed:
wc = w + c
if wc in dictionary:... |
def birth_x(well):
"""If the chosen well is empty, will create an xantophore"""
if well == 'S':
return 'X'
else:
return well |
def inRegion(reg, site):
"""given a region tuple, (start, end)
returns True if site is >= start <= end"""
return site >= reg[0] and site <= reg[1] |
def intcode_parse(code):
"""Accepts intcode. Parses intcode and returns individual parameters. """
actual_code = code % 100
parameter_piece = code - actual_code
parameter_piece = parameter_piece // 100
parameter_code_list = []
while parameter_piece > 0:
parameter_code_list.append(param... |
def calculate_m(q_c1ncs):
"""
m parameter from CPT, Eq 2.15b
"""
m = 1.338 - 0.249 * q_c1ncs ** 0.264
if q_c1ncs >= 254:
m = 0.263823991466759
if q_c1ncs <= 21:
m = 0.781756126201587
return m |
def __is_dead(ref):
"""Return ``True`` if the weak reference `ref` no longer points to an
in-memory object.
"""
return ref() is None |
def clear(x, y, player, game_map):
""" check if cell is safe to move in """
# if there is no shipyard, or there is player's shipyard
# and there is no ship
if ((game_map[x][y]["shipyard"] == player or game_map[x][y]["shipyard"] == None) and
game_map[x][y]["ship"] == None):
retu... |
def strongly_connected_components(graph):
"""
Tarjan's Algorithm (named for its discoverer, Robert Tarjan) is a graph
theory algorithm for finding the strongly connected components of a graph.
graph should be a dictionary mapping node names to lists of
successor nodes.
Based on: http://en.wiki... |
def druckumrechner(inHG):
"""
Umwandlung von inHG in mBar
:param inHG: int, float or None
:return: float or None
"""
if isinstance(inHG, (int, float)):
mbar = inHG * 33.86389
mbar = round(mbar, 2)
return mbar
else:
return None |
def number_of_ways_for_the_frog_to_jump_n_feet(n):
"""number of ways for the frog to jump n feet
:param n: num of feets
:return:
"""
global total
if n == 0:
return 1
if n < 0:
return 0
return number_of_ways_for_the_frog_to_jump_n_feet(n - 1) + number_of_ways_for_the_fro... |
def location_name(country=None, state=None):
"""return the name of the country and/or state used in the current filter"""
locations = []
if state:
locations.append(state)
if country:
locations.append(country)
return " - ".join(locations) if len(locations) > 0 else "everywhere" |
def is_subpath(x, y):
"""Returns True if x is a subpath of y, otherwise return False.
Example:
is_subpath('/a/', '/b/') = False
is_subpath('/a/', '/a/') = True
is_subpath('/a/abc', '/a/') = True
is_subpath('/a/', '/a/abc') = False
"""
if y.endswith("/"):
return x.startswith(y) o... |
def sanitize_name(name: str):
"""
Sanitize the callsites for general dataset.
"""
ret_name = ""
if name is None:
ret_name = "Unknown"
return ret_name
if "/" in name:
name_split = name.split("/")
ret_name = name_split[len(name_split) - 1]
else:
ret_name... |
def format_nri_list(data):
"""Return NRI lists as dict with names or ids as the key."""
if not data:
return None
info = {}
for item in data:
if item.get("name") is not None:
key = item.pop("name")
elif item.get("id") is not None:
key = item.pop("id")
... |
def merge_two_dicts(x, y):
"""Given two dicts, merge them into a new dict as a shallow copy. Credit: http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression"""
z = x.copy()
z.update(y)
return z |
def validate_tag(tag):
""" Chceks if tag is valid. Tag should not be empty and should start with '#' character """
tag = tag.strip().lower()
return len(tag) > 1 and tag.startswith("#") |
def get_public_members(obj):
"""
Retrieves a list of member-like objects (members or properties) that are
publically exposed.
:param obj: The object to probe.
:return: A list of strings.
"""
return {attr: getattr(obj, attr) for attr in dir(obj)
if not attr.startswith("_")
... |
def cast_string_to_int_error(what):
"""
Retrieves the "can not cast from string to integer" error message.
:param what: Environment variable name.
:return: String - Can not cast from string to integer.
"""
return "ERROR: " + what + " value cannot be cast from string to int" |
def column_names(row, colnames):
"""
Pair items in row with corresponding column name.
Return dictionary keyed by the column names.
"""
mapped = {col_name: val for val, col_name in zip(row, colnames)}
return mapped |
def get_bucket_name(gem_group, barcode, num_buckets):
""" gem_group - integer
barcode - barcode sequence
num_buckets - desired number of buckets for gem group """
# NOTE: Python modulo returns non-negative numbers here, which we want
return str(gem_group) + '-' + str(hash(barcode) % num_buc... |
def make_table_options(param):
"""make table param of Embedding tables
Args:
param (dict or list): param can be initializer or list of column_option. initializer can be made by make_uniform_initializer or make_normal_initializer, column options can be made by make_column_options
Returns:
d... |
def power_bin_recursive(base, exp):
"""Funkce vypocita hodnotu base^exp pomoci rekurzivniho algoritmu
v O(log(exp)). Staci se omezit na prirozene hodnoty exp.
"""
if exp == 0:
return 1
if exp % 2 == 1:
return base * power_bin_recursive(base * base, exp // 2)
return power_bin_re... |
def mass_to_richness(mass, norm=2.7e13, slope=1.4):
"""Calculate richness from mass.
Mass-richness relation assumed is:
mass = norm * (richness / 20) ^ slope.
Parameters
----------
mass : ndarray or float
Cluster mass value(s) in units of solar masses.
norm : float, optional
... |
def trim_string(text: str, max_length: int = 200, ellipsis: str = "...") -> str:
"""
If text is longer than max_length then return a trimmed string.
"""
assert max_length >= len(ellipsis)
if len(text) > max_length:
return text[: max_length - len(ellipsis)] + ellipsis
else:
return... |
def _escape_column(column):
"""
transfer columns, return tuple, such as ('a', 'b', 'c'),
when constructing SQL, direct use the__ str__ () method
"""
if not len(column):
raise ValueError('Field cannot be empty')
if len(column) == 1:
column = column[0]
if isinstance(column... |
def center(numpoints, refcoords):
"""Center a molecule using equally weighted points.
:param numpoints: number of points
:type numpoints: int
:param refcoords: list of reference coordinates, with each set a list of
form [x,y,z]
:type refcoords: [[float, float, float]]
:return: (cen... |
def replace(txt, start, end, repltxt):
"""Replaces the part of txt between index start and end with repltxt"""
return txt[:start] + repltxt + txt[end+1:] |
def vec_is_void(a):
"""
Check whether a given vector is empty
A vector is considered "void" if it is None or has no
elements.
Parameters
----------
a: list[]
The vector to be checked
Returns
-------
bool
True if the vector is empty, False otherwise
"""
... |
def float_or_string(arg):
"""Force float or string
"""
try:
res = float(arg)
except ValueError:
res = arg
return res |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.