content stringlengths 42 6.51k |
|---|
def producer_config(config):
"""Filter the producer config"""
for field in ["group.id", "partition.assignment.strategy", "session.timeout.ms", "default.topic.config"]:
if field in config:
del config[field]
return config |
def get_normal_form(obj_name, with_space=True):
"""Transform object name to title form.
Example:
if with_space=True then risk_assessments -> Risk Assessments
if with_space=False then risk_assessments -> RiskAssessments
"""
normal = obj_name.replace("_", " ").title()
if with_space is True:
return normal
... |
def last(l):
"""
Returns the last element of a collection.
.. note::
Useful when we do not want to have numbers in the code.
Furthermore, it can be directly used in the function composition.
Examples
--------
>>> last([1, 2, 3])
3
"""
return l[-1] |
def meets_requirements(count, r):
"""Does the password have enough of each type of character to meet the
requirements?"""
if (count['d'] >= r['d'] and count['l'] >= r['l'] and
count['u'] >= r['u'] and count['s'] >= r['s']):
return True
else:
return False |
def getFactoryCreditMultiplier(factoryId):
"""
Returns the skill credit multiplier for a particular factory.
factoryId is the factory-interior zone defined in ToontownGlobals.py.
"""
# for now, there's only one factory
return 2. |
def _frequency_of_pair(a, b, v, w, matrix):
""" builds a map from (v, w) -> (p(a=v and b=w) for all possible pairs (v, w)
a, b indeces of columns to be compared
v, w respective values of columns a and b, we're looking at
(not cheap)
"""
count=0
worry_count=0
for row in matri... |
def format_month(month):
"""Formats a month to first 3 characters of the month input
Args:
month: user input month
Returns:
A ValueError if the input is not a month, or a 3 character month.
"""
months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov... |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
if number**2 == number:
return number
low, high = 0, number
while low <= high:
m = (low +... |
def get_status_from_msg(finished_msg):
"""Return a job status based on the finished job message.
'complete' if the job created both output files successfully.
'failed' otherwise.
"""
if(len(finished_msg['upload_files']) == 2):
return 'complete'
else:
return 'failed' |
def _try_int(value):
"""Try to make some value into an int."""
try:
return int(value)
except (ValueError, TypeError):
return None |
def ensure_set(value):
"""
Given a single value or multiple values, ensure that we return a set.
"""
if isinstance(value, int):
return {value}
return set(value) |
def transform_with(sample, transformers):
"""Transform a list of values using a list of functions.
:param sample: list of values
:param transformers: list of functions
"""
assert not isinstance(sample, dict)
assert isinstance(sample, (tuple, list))
if transformers is None or len(transforme... |
def is_consecutive_rows(lst):
"""Check if a list of integers is consecutive.
Args:
lst (list): The list of integers.
Returns:
True/False: If the list contains consecutive integers.
Originally taken from and modified:
http://stackoverflow.com/
questions/40091617/tes... |
def getSafe(dict,key):
"""
Tests if the dictionary has the given key. If so, it retrieves the value and returns it. If not, returns None.
:param dict:
:param key:
:return:
"""
if key in dict and dict[key]:
return dict[key]
else:
return None |
def _check(key: str) -> bool:
"""Returns `True` if `key` is valid identifier string else `False`."""
return isinstance(key, str) and key.isidentifier() |
def print_pipeline(message, args, pipeline_data):
""" Displays the current state of the pipeline in the console """
print("Message: ", message)
print("Data", pipeline_data)
return True |
def euler1(lim=1000):
"""Solution for problem 1."""
# could use sum formula here
return sum(i for i in range(lim) if i % 3 == 0 or i % 5 == 0) |
def genpixmap(targetlevel):
"""Generate pixel value map."""
v=256.0/(targetlevel+1)
m=[]
j=0
for i in range(256):
m.append(int(i/v))
return m |
def sort_by_size(L):
"""
Return a copy of precinct list L, sorted into decreasing order by size.
"""
answer = L[:]
answer.sort()
answer.reverse()
return answer |
def _format_key(key: str) -> str:
"""Internal function for formatting keys in Tensorboard format."""
return key.title().replace('_', '') |
def luminace(color_component):
"""Luminance of an individual Red, Green, or Blue, color component.
:param color_component: Value between 0 and 255 (inclusive)
:type color_component: int
:return: Luminance value of the color component
:rtype: float
"""
i = float(color_component) / 255
i... |
def split_grad_list(grad_list):
"""
Args:
grad_list: K x N x 2
Returns:
K x N: gradients
K x N: variables
"""
g = []
v = []
for tower in grad_list:
g.append([x[0] for x in tower])
v.append([x[1] for x in tower])
return g, v |
def sdf_count(file_obj):
"""Count the number of molecules in an SDF file.
Counts the number of times '$$$$' occurs at the start of lines
in the file.
Parameters
----------
file_obj: A file-like object
Returns
-------
count: The number of molecules in the file (int)
"""
ret... |
def bold_first_italics(graph):
"""For a newly broken-up graph, convert the first italics text to bold."""
if graph.count('*') > 1:
return graph.replace('*', '**', 2)
else:
return graph |
def reverse(current_block, *args):
"""Reverses the data of the current block."""
return current_block[::-1] |
def create_ngrams(tokens, ngram=2, determiner='_'):
"""Create n_grams.
"""
new_tokens = []
for i in range(len(tokens)-ngram+1):
new_token = determiner.join(tokens[i:i+ngram])
new_tokens.append(new_token)
return new_tokens |
def research_order(technology_id, after_technology_id, civ_ids):
"""Report research that began after a specified research finished."""
query = """
select
imp.match_id, imp.player_number as number, imp.finished as imp_time, late.started::interval(0) as timestamp
from research as imp
... |
def _num_pre_blank_frames(stim_dict):
"""
_num_pre_blank_frames(stim_dict)
Retrieves number of blank frames before stimulus starts.
Arguments:
stim_dict (dict): An Allen Institute session stimulus dictionary.
Returns:
num_pre_blank_frames (int): number of blank frames before stimu... |
def check_valid_base_fraction(base_fraction):
"""
Checks that base fraction specified is either None, and therefore won't be used, or is between 0 and 1.
:param base_fraction: Base fraction, which should be either None or a float.
:return: True if base fraction is valid, False if not.
"""
if bas... |
def neighbor_candidate_generator(src_cortical_area, src_neuron_id, dst_cortical_area):
"""
Identifies the list of candidate neurons in the destination cortical area that based on the rules defined by
source cortical area are suitable fit for synapse creation.
Args:
src_cortical_area:
sr... |
def threshold_counts(counts, threshold=30, number=1):
""" Returns True
Makes sure that at least one of the samples meet a read count threshold.
"""
counter = 0
for i in counts:
if sum(i) > threshold: counter += 1
if counter >= number:return True
else: return False |
def arg_keys(arg_name, keys):
"""Appends arg_name to the front of all values in keys.
Args:
arg_name: (string) String containing argument name.
keys: (list of strings) Possible inputs of argument.
Returns:
List of strings with arg_name append to front of keys.
"""
return ["... |
def parse_int(token):
"""Convert a token of a integer literal to its integer value.
>>> parse_int("100")
100
>>> parse_int("0xA")
10
"""
if token.startswith("0x"):
return int(token, base=16)
elif token.startswith("0o"):
return int(token, base=8)
else:
return... |
def _make_iter(obj, make_fn, **options):
"""
:param obj: An original mapping object
:param make_fn: Function to make/convert to
"""
return type(obj)(make_fn(v, **options) for v in obj) |
def countit(objs):
"""Return a dict with counts for each item in a list."""
out = {}
for el in objs:
out[el] = 1 + out.get(el, 0)
out = {k: v for k, v in out.items()}
return out |
def check_bidi_comp(cond0, cond1, arg0, arg1):
"""
Check whether conditions are True for two arguments regardless of order.
Parameters
----------
cond0, cond1 : callable
Function of one variable that evaluate to a bool.
arg0, arg1 : object
Arguments to pass to `cond0` and `cond1... |
def lorentz1D(x, x0, w):
"""Returns the probability density function of the Lorentzian (aka Cauchy) function with maximum at 1.
Parameters
----------
x: ndarray or list
A 1D vector of points for the dependent variable
x0: float
The center of the peak maximum
... |
def anyhasprefix(value, prefixes):
""" Check if `value` starts with on of the possible `prefixes` """
for p in prefixes:
if value.startswith(p):
return True
return False |
def find_group_missing_numbers(squares: list, grid: list) -> list:
"""
Gets the missing numbers from the group of squares
:param squares: A list of tuples (row, column) coordinates of squares
:param grid: The sudoku grid as a 3D list
:return: A list containing all the numbers (1-9) missing from the... |
def number(lines):
"""Apply enumerate approach."""
# dict: {number->c}
# list: ['number: c']
# number_c_d = {i + 1: c for i, c in enumerate(lines)}
# return number_c_d
if lines == []:
return []
number_c_ls = [str(i + 1) + ': ' + c for i, c in enumerate(lines)]
return number_... |
def parsimony_pressure(fitness: float,
size: int,
p_coeff: float) -> float:
"""Parsimony pressure method.
Koza, 1992; Zhang & Muhlenbein, 1993; Zhang et al., 1993
:param fitness: Original fitness
:param size: Size of individual
:param p_coeff: Parsimon... |
def merge_two_dicts(dict_01, dict_02):
"""
Merge 2 dictionaries and return the merged dictionary.
Compatible with python 3.4 or lower
"""
merged_dict = dict_01.copy() # start with x's keys and values
merged_dict.update(dict_02) # modifies z with y's keys and values & returns None
... |
def concat(l1, l2):
""" Join two possibly None lists """
if l1 is None:
return l2
if l2 is None:
return l1
return l1 + l2 |
def score_calc_5(sumI, n, beta_a_b, beta_aB, beta_c_d, beta_w_x, beta_y_z_P, gamma, L, sumI_all):
"""
Scoring function with 5 ion series: sumI(matched) / sumI(all) * n / L * ( 1 + beta[a + b] + beta[a-B] + beta[c + d]
+ beta[w + x] + beta[y + z + y-P + z-P])
n = total number of matching MS2 ions for t... |
def make_spaces(in_string: str) -> str:
"""
This filter takes a string and replaces all dashes and underscores with spaces
:param in_string: The string to change
:type in_string: str
:returns: A string with no dashes or underscores
:rtype: str
"""
return in_string.r... |
def sanitize(name):
"""Make the name able to be a valid path name.
No spaces or slashes, everything lowercase"""
return name.lower().replace(" ", "_").replace("/", "-slash-") |
def sum_of_matrices(matrix1, matrix2):
"""
Sums the input matrices (matrix1 + matrix2). If dimension sizes are not match returns -1!
Args:
matrix1: 2D list
matrix2: 2D list
Return:
result: 2D list. If dimension sizes are not match returns -1!
result = []
"""
resu... |
def map_pressure_to_coeff(pressure_str):
"""
:param str pressure:
:return:
"""
pressure = int(pressure_str)
if pressure <= 1008:
pressure_coeff = 3
elif pressure >= 1023:
pressure_coeff = 1
else:
pressure_coeff = 2
return pressure_coeff |
def _revert(converter,
result,
converted=False,
result_conversion=None,
estimator=None,
**converter_args):
"""
Use the `converter` to convert the given `result` if necessary.
sklearn toolkit produces all its results as numpy format by default.
... |
def human_format(num: int) -> str:
"""Returns num in human-redabale format
from https://stackoverflow.com/a/579376
Args:
num (int): number.
Returns:
str: Human-readable number.
"""
# f
if num < 10000:
return str(num)
magnitude = 0
while abs(num) >= 1000:
... |
def fix_segment_table(segment_table):
"""Given a list of dictionaries in the form [{"start":start_frequency,
"stop":stop_frequency,"number_points":number_points,"step":frequency_step}...] returns a table that is ordered by start
frequency and has no overlapping points"""
segment_table = sorted(segment_t... |
def _get_padding(num_bins, bin_size):
"""
For parallel iteration: gets the smallest number L' >= bin_size
such that num_bins is smaller than the lowest factor of L'.
"""
trial_size = bin_size
while True:
success_flag = True
for divisor in range(2, num_bins - 1):
if tr... |
def handle_domainlist(url, _domain, _method, **_):
"""
:param url: Incoming URL dictionary
:type url: dict
:param _domain: Incoming domain (it's not being used for this handler)
:type _domain: str
:param _method: Incoming request method (it's not being used for this handler)
:type _method: s... |
def _split_name(name):
"""Splits a name in two components divided by '.'"""
comp = name.split('.')
if len(comp) > 1:
return (comp[0], '.'.join(comp[1:]))
return (None, name) |
def decipher_all(decipher, objid, genno, x):
"""Recursively deciphers the given object.
"""
if isinstance(x, bytes):
return decipher(objid, genno, x)
if isinstance(x, list):
x = [decipher_all(decipher, objid, genno, v) for v in x]
elif isinstance(x, dict):
for (k, v) in x.ite... |
def is_one_to_one(d):
"""
(dict of {str: int}) -> bool
Return True if and only if no two of d's keys
map to the same value.
>>> is_one_to_one({'a': 1, 'b': 2, 'c': 3})
True
>>> is_one_to_one({'a': 1, 'b': 2, 'c': 1})
False
>>> is_one_to_one({})
True
"""
values = []
... |
def csc_norm(n, Ap, Ax):
"""
Computes the 1-norm of a sparse matrix = max (sum (abs (A))), largest
column sum.
@param A: column-compressed matrix
@return: the 1-norm if successful, -1 on error
"""
norm = 0
for j in range(n):
s = 0
for p in range(Ap[j], Ap[j + 1]):
... |
def argument_name(name: str) -> str:
"""Standardises argument name.
Examples:
```python
argument_name("hello") == "--hello"
argument_name("hello_world") == "--hello-world"
```
Args:
name (str): Name of the argument.
Returns:
str: Standardised name of th... |
def scaling_transform(w1, h1, w2, h2):
"""Rescale rectangle (w1, h1) to fit in rectangle (w2, h2) without changing the ratio."""
r1 = w1 / h1
r2 = w2 / h2
if r1 <= r2:
h = h2
w = r1 * h2
else:
w = w2
h = w2 / r1
return w, h |
def clipped(piece_idx, move_idx):
"""
Determines whether the move is a valid knight move and is not clipped given
the 8x8 geometry
"""
if move_idx not in range(64):
return True
move_x, move_y = (move_idx % 8, move_idx // 8)
piece_x, piece_y = (piece_idx % 8, piece_idx // 8)
x_dif... |
def remove_trailing(number: int):
"""
Verwijderd de trailing 0 van integers
https://stackoverflow.com/questions/52908011/better-way-to-remove-trailing-zeros-from-an-integer
"""
while number % 10 == 0 and number != 0:
number //= 10
return number |
def apply_deltas(start,deltas):
""" Return a list of the sums of DELTAS starting from START. """
result = []
current = start
for delta in deltas:
current = current + delta
result.append(current)
return result |
def buckle_thickness(D_o, P_p, sig_y):
"""Return the nominal buckle thickness [t] based on the propagation pressure.
Considers the worst case maximum external pressure and ignores internal
pressure - PD8010-2 Equation (G.21).
:param float D_o: Outside Diameter [m]
:param float P_p: Propagation pres... |
def get_content(context, target):
"""
It gets the content from any file with
data in it(auto generated) and returns in list
"""
lines = []
try:
with open(target,encoding='UTF-8') as file:
for line in file:
line = line.strip()
lines.appe... |
def _clean_2007_text(s):
"""Replace special 2007 formatting strings (XML escaped, etc.) with
actual text.
@param s (str) The string to clean.
@return (str) The cleaned string.
"""
s = s.replace("&", "&")\
.replace(">", ">")\
.replace("<", "<")\
.replac... |
def min_board(list_of_board):
"""
get the board with the min cost
"""
cost = float("inf")
board = None
index = -1
for i in range(len(list_of_board)):
elem_cost, elem_board = list_of_board[i]
if (elem_cost < cost):
cost = elem_cost
board = elem_board
... |
def idToMQTTClientID(id:str, isCSE:bool=True) -> str:
""" Convert a oneM2M ID to an MQTT client ID.
"""
return f'{"C::" if isCSE else "A::"}{id.lstrip("/")}' |
def NormalizeEmail(email):
"""Normalizes the email from git repo.
Some email is like: test@chromium.org@bbb929c8-8fbe-4397-9dbb-9b2b20218538.
"""
parts = email.split('@')
return '@'.join(parts[0:2]) |
def hsl_to_rgb(hue, saturation, lightness):
"""
:param hue: degrees
:param saturation: percentage
:param lightness: percentage
:returns: (r, g, b) as floats in the 0..1 range
"""
hue = (hue / 360) % 1
saturation = min(1, max(0, saturation / 100))
lightness = min(1, max(0, lightness /... |
def format_assignments(text):
"""
Aligns assignment statements in the source file and return a text.
"""
lines = text.split("\n")
# process text line by and store each line at its starting index
formated_text = []
a_block_left = []
a_block_right = []
# these statements may contain ... |
def threads(threads: int, single_threaded: bool) -> int:
"""
Number of threads to run in each Gunicorn worker.
"""
if single_threaded:
return 1
return threads |
def is_in_mapping_cache(referenced_revision_tag, referenced_section,
mapping_cache):
""" Checks if the referenced section is in the mapping cache
Supports both entry formats (1.2:3.4 and 1.2/3.4)
"""
s1 = ":".join(referenced_section)
s2 = "/".join(referenced_section)
... |
def _find_room_helper(room_obj_list, room):
"""simple list search for finding object in first part of a tuple"""
for r_obj in room_obj_list:
if r_obj[0] == room:
return r_obj[1]
return None |
def match(patternSuffix: str, wordSuffix: str):
"""Returns False if patternSuffix[0] does not match wordSuffix[0].
A match is when patternSuffix[0] == '?' or patternSuffix[0] == wordSuffix[0].
This function recures until both or one of the two inputs are exhausted or a match
of patternSuffi... |
def obj_of(k, v):
"""Creates an object containing a single key:value pair"""
return {k: v} |
def extent(obj):
"""Get the start and end offset attributes of a dict-like object"""
return obj.get('startOffset', -1), obj.get('endOffset', -1) |
def parse_boolean(value, length, cursor):
"""Typecast the postgres boolean to a python boolean.
Postgres returns the boolean as a string with 'true' or 'false'
"""
return value[:1] == b"t" if value is not None else None |
def lagrange_poly(x, xp, fp):
""" given points (xp, fp), fit a lagrange polynomial and return
the value at point x """
f = 0.0
# sum over points
m = 0
while (m < len(xp)):
# create the Lagrange basis polynomial for point m
l = None
n = 0
while ... |
def pixels_to_figsize(opt_dim, opt_dpi):
"""Converts pixel dimension to inches figsize
"""
w, h = opt_dim
return (w / opt_dpi, h / opt_dpi) |
def _get_proxy_type(type_id):
"""
Return human readable proxy type
Args:
type_id: 0=frontend, 1=backend, 2=server, 3=socket/listener
"""
proxy_types = {
0: 'frontend',
1: 'backend',
2: 'server',
3: 'socket/listener',
}
return proxy_types.get(in... |
def prime_factors(n):
"""Returns all the prime factors of a positive integer"""
factors = []
d = 2
while n > 1:
while n % d == 0:
factors.append(d)
n //= d
d = d + 1
if d*d > n:
if n > 1: factors.append(n)
break
return factors |
def confirm_membership(required_set, proposed):
"""
Return True if all elements in required set are present in proposed
>>> confirm_membership({'a', 'b'}, {'c': 0, 'a': 2, 'b': 0})
True
>>> confirm_membership({'a':3, 'b':4}, {'c': 0, 'a': 2, 'b': 0})
True
"""
return set(required_set... |
def parse_ranges(s):
"""Parse s as a list of range specs."""
range_list = [] # return value is a list of doc indexes
ranges = s.split(",")
# list of ranges
for r in ranges:
try:
i = int(r)
range_list.append(i)
except ValueError:
# check if range
... |
def modexp5(b,m):
"""e=5, use addition chain"""
b2=(b*b)%m
b4=(b2*b2)%m
b5=(b*b4)%m
assert(b5==pow(b,5,m))
return b5 |
def limit_labels_for_label_normalizer(
label_normalizer,
acceptable_labels):
"""Limits keys and values in label_normalizer to acceptable labels."""
limited_label_normalizer = {}
for k, v in label_normalizer.items():
if k in acceptable_labels:
limited_label_normalizer[k] = sorted(
accep... |
def ParseGTestListTests(raw_list):
"""Parses a raw test list as provided by --gtest_list_tests.
Args:
raw_list: The raw test listing with the following format:
IPCChannelTest.
SendMessageInChannelConnected
IPCSyncChannelTest.
Simple
DISABLED_SendWithTimeoutMixedOKAndTimeout
Return... |
def _is_gse2(filename):
"""
Checks whether a file is GSE2.0 format.
:type filename: str
:param filename: Name of the GSE2.0 file to be checked.
:rtype: bool
:return: ``True`` if GSE2.0 file.
"""
try:
with open(filename, 'rb') as fh:
temp = fh.read(12)
except Exce... |
def short_doc(obj):
"""
Returns the first line of the object's docstring
"""
if obj.__doc__:
lines = obj.__doc__.strip(' \n').splitlines()
if lines:
return lines[0]
return None |
def atmDensPoly6th(ht, dens_co):
""" Compute the atmosphere density using a 6th order polynomial. This is used in the ablation simulation
for faster execution.
Arguments:
ht: [float] Height above sea level (m).
dens_co: [list] Coeffs of the 6th order polynomial.
Return:
a... |
def replace_ellipsis(n, index):
"""Replace ... with slices, :, : ,:
>>> replace_ellipsis(4, (3, Ellipsis, 2))
(3, slice(None, None, None), slice(None, None, None), 2)
>>> replace_ellipsis(2, (Ellipsis, None))
(slice(None, None, None), slice(None, None, None), None)
"""
# Careful about using ... |
def dev_merge_dicts(dicta: dict, dictb: dict):
"""merge two dicts.
under development.
"""
if not isinstance(dicta, dict) or not isinstance(dictb, dict):
return dicta
new_dicta = {**dicta, **dictb}
for k, v in new_dicta.items():
if isinstance(v, dict):
if (k in dicta)... |
def area(r):
"""returns surface"""
return(333/106*r**2) |
def _strip_double_quote(value: str) -> str:
"""Strip one leading/single trailing double-quote."""
if value[0] == '"':
value = value[1:]
if value[-1] == '"':
value = value[:-1]
return value |
def capability(event, endpoint, name, description, others=None):
"""
A helper function to generate one capability line for the capabilities()
"""
path = event['path']
named_path_element = path.rfind('/capabilities')
if named_path_element>0:
prefix = path[0:named_path_element]
else:
... |
def add_file_to_dict(dictionary, file):
"""
Populates a dictionary with
key: file name
value: number of instances in the directory
Args:
dictionary: dictionary of file names
file: file name to be added to dictionary
Returns:
The modified dictionary
"""
# ... |
def flatten_keys(dictionary):
"""
Flattens the keys for a nested dictionary using dot notation. This
returns all the keys which can be accessed via `get_by_path`.
Example:
For example, {'a': None, 'b': {'x': None}} would return ['a', 'b.x']
Args:
dictionary (dict):
A di... |
def _make_triplets(seq, phase=0):
"""Select a valid amino acid sequence given a 3-letter code input (PRIVATE).
This function takes a single three-letter amino acid sequence and the phase
of the sequence to return the longest intact amino acid sequence possible.
Parts of the input sequence before and af... |
def get_suit_of_card(position_of_card, deck):
"""Returns the suit of the card that has the specific position in the deck"""
suit_int = deck[position_of_card][0]
if suit_int == 0:
return "Spades"
elif suit_int == 1:
return "Hearts" |
def xeval(sexpr):
"""
>>> xeval('')
0
>>> xeval('1234567')
1234567
>>> xeval('+1234567')
1234567
>>> xeval('-1234567')
-1234567
>>> xeval('2+3')
5
>>> xeval('2-3')
-1
>>> xeval('2-23+4')
-17
>>> xeval('2-01+3-1')
3
>>> xeval('1-2-3-4-5')
-13
... |
def duration(s):
"""Turn a duration in seconds into a human readable string"""
m, s = divmod(s, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
parts = []
if d:
parts.append('%dd' % (d))
if h:
parts.append('%dh' % (h))
if m:
parts.append('%dm' % (m))
if s:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.