content stringlengths 42 6.51k |
|---|
def fade(begin, end, factor):
""" return value within begin and end at < factor > (0.0..1.0)
"""
# check if we got a bunch of values to morph
if type(begin) in [list, tuple]:
result = []
# call fade() for every of these values
for i in range(len(begin)):
result.append... |
def abs_val(num):
"""
Find the absolute value of a number.
>>abs_val(-5)
5
>>abs_val(0)
0
"""
if num < 0:
return -num
# Returns if number is not < 0
return num |
def _clip_count(cand_d, ref_ds):
"""Count the clip count for each ngram considering all references"""
count = 0
for m in cand_d.keys():
m_w = cand_d[m]
m_max = 0
for ref in ref_ds:
if m in ref:
m_max = max(m_max, ref[m])
m_w = min(m_w, m_max)
count += m_w
return count |
def to_bool(value):
"""
Converts 'something' to boolean. Raises exception for invalid formats
Possible True values: 1, True, "1", "TRue", "yes", "y", "t"
Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ...
"""
if str(value).lower() == "true... |
def get_int_with_default(val, default):
"""Atempts to comvert input to an int. Returns default if input is None or unable to convert to
an int.
"""
if val is None:
return default
try:
return int(val)
except ValueError:
pass
return default |
def cnr(mean_gm, mean_wm, std_bg):
"""Calculate Contrast-to-Noise Ratio (CNR) of an image.
- CNR = |(mean GM intensity) - (mean WM intensity)| /
(std of background intensities)
:type mean_gm: float
:param mean_gm: The mean value of the gray matter voxels.
... |
def get_object_map(id_offset: int) -> dict:
"""
Returns ID to communication object mapping of a given CAN node ID.
Map taken from https://en.wikipedia.org/wiki/CANopen#Predefined_Connection_Set[7]
"""
return {
0x000 : "NMT_CONTROL",
0x001 : "FAILSAFE",
... |
def make_negative(number):
"""Return the negative of the absolute value of number."""
return abs(number) * -1 |
def get_filings_query(api_key):
"""
keys = ["total_disbursements", "committee_id", "candidate_id"]
"""
return "https://api.open.fec.gov/v1/filings/?sort_nulls_last=false&sort=-receipt_date&sort_hide_null=false&per_page=20&page=1&api_key={api_key}&sort_null_only=false".format(
api_key=api_key
... |
def calc(number: int) -> int:
"""Makes the number a multiple of 80 (fix incorrect matrix multiplication in Transform class)"""
return (number // 80 + 1) * 80 if number % 80 > 40 else number // 80 * 80 |
def valid_password(password):
"""
The password must be at least nine characters long. Also, it must include characters from
two of the three following categories:
-alphabetical
-numerical
-punctuation/other
"""
punctuation = set("""!@#$%^&*()_+|~-=\`{}[]:";'<>?,./""")
alpha = False
num = Fa... |
def healthcheck_timeout_calculate(data):
"""Calculate a BIG-IP Health Monitor timeout.
Args:
data: BIG-IP config dict
"""
# Calculate timeout
# See the f5 monitor docs for explanation of settings:
# https://goo.gl/JJWUIg
# Formula to match up the cloud settings with f5 settings:
... |
def gcd(a,b):
"""Find GCD"""
if(b==0):
return a
else:
return gcd(b,a%b) |
def itemize(*items):
"""Restructured text formatted itemized list
>>> print itemize('alpha', 'beta')
* alpha
* beta
"""
return '\n'.join(['* ' + item for item in items]) |
def pentagonal(n):
"""Return nth pentagonal number e.g. 1, 5, 12, 22, 35, ..."""
return n*(3*n - 1)/2 |
def readLinesFromFile(filename):
"""
Returns the read file as a list of strings.
Each element of the list represents a line.
On error it returns None.
"""
try:
with open(filename, "r") as input_file:
lines = input_file.readlines()
return lines
except EnvironmentE... |
def add_latex_line_endings(lines):
"""Add latex newline character to each line"""
return [line + r" \\" for line in lines] |
def invalid_sn_vsby(i, v):
"""Checks if visibility is inconsistent with SN or DZ
Returns 0 if consistent, -1 if too high, +1 if too low"""
if i == '+':
if v > 0.25:
return -1
else:
return 0
elif i == '':
if v > 0.5:
return -1
elif v <= 0.25... |
def is_power_of_2(x):
"""Determine if a number is a power of 2"""
return ((x != 0) and not(x & (x - 1))) |
def is_match_coverage_less_than_threshold(license_matches, threshold):
"""
Returns True if any of the license matches in a file-region has a `match_coverage`
value below the threshold.
:param license_matches: list
List of LicenseMatch.
:param threshold: int
A `match_coverage` thresh... |
def hra(basic):
""" hra Is 15% Of Basic Salary """
hra = basic*15/100
return hra |
def permutate_NNlayer_combo_params(layer_nums, node_nums, dropout_list, max_final_layer_size):
"""
to generate combos of layer_sizes(str) and dropouts(str) params from the layer_nums (list), node_nums (list), dropout_list (list).
The permutation will make the NN funnel shaped, so that the next layer can on... |
def only_printable(string):
""" Converts to a string and removes any non-printable characters"""
string = str(string)
return "".join([s for s in string if s.isprintable()]) |
def help(command=""):
"""
Return a help manual to slack, which helps the user understand how to use a command.
@params:
input -> A specific command that the user want to look for. Default is "",
which would lead to an explanation of all command.
"""
command = command.lower()... |
def scramble(lis1, lis2):
""" Takes two lists, one as values and the other as indies. Then sorts
the value list according to the indies and returns a list. """
# This is very much like flatten() from above. Only keys and values
# are reversed.
temp_zip = zip(range(len(lis1)), lis1)
temp_dict = {... |
def normalize_bbox(bbox, rows, cols):
"""Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates
by image height.
Args:
bbox (tuple): Denormalized bounding box `(x_min, y_min, x_max, y_max)`.
rows (int): Image height.
cols (int): Image width.
... |
def unique_values(rows, idx):
"""Checking for unique values in table.
rows : [{ }, { }, ...]
idx : dict key (column name)
"""
# counting occurances of the values (value for "idx" key)
cnt = {}
for i,x in enumerate(rows):
try:
value = x[idx]
except KeyError:
... |
def return_user_filter(user_to_search: str, users_list):
"""
Looks through the inputted list and if the user to search for exists, will return the user. Otherwise, it will
return an empty dict
Args:
user_to_search: The user we are searching for
users_list: A list of user dictionaries to... |
def find_moves(board):
"""returns list of valid moves"""
moves = []
for col in range(7):
if board[0][col] == " ":
moves.append(col)
return moves |
def is_arithmetic_series(series: list) -> bool:
"""
checking whether the input series is arithmetic series or not
>>> is_arithmetic_series([2, 4, 6])
True
>>> is_arithmetic_series([3, 6, 12, 24])
False
>>> is_arithmetic_series([1, 2, 3])
True
"""
if len(series) == 1:
... |
def md_getLat(field):
"""Get latitude"""
return field.split(',')[1].strip() |
def divide1(a, b):
"""Manually exam to avoid error.
"""
if b == 0:
raise ValueError("Zero division Error!")
return a * 1.0 / b |
def b_oblate(kappa):
"""
-1 = oblate <= b_O <= 0 = prolate
Townes and Schawlow, Ch. 4
"""
return (kappa-1.)/(kappa+3.) |
def ordinal_suffix(day):
"""Return ordinal english suffix to number of a day."""
condition = 4 <= day <= 20 or 24 <= day <= 30
return 'th' if condition else ["st", "nd", "rd"][day % 10 - 1] |
def V1compat(t):
"""V1compat - create a V1 compatible tick record from a V20 tick."""
T = t['time']
T = T[0:len(T)-4]+"Z"
rv = dict()
if t['type'] == 'PRICE':
rv = {"tick": {"instrument": t['instrument'],
"time": T,
"bid": float(t['bids'][0]['pr... |
def divide(arg1, arg2):
""" (float, float) -> float
Divides two numbers (arg1 / arg2)
Returns arg1 / arg2
"""
try:
return arg1 / arg2
except TypeError:
return 'Unsupported operation: {0} / {1} '.format(type(arg1), type(arg2))
except ZeroDivisionError as zero_... |
def convertType(pair:tuple):
"""Convert items to the appropriate types
Arguments:
pair: A tuple containing 2 items
Returns:
pair: A tuple containing 2 items where the second item is converted to the appropriate types
"""
#If it is not a pair
if len(pair) != 2:
... |
def distND(pt1, pt2):
"""Returns distance between two nD points (as two n-tuples)"""
return (sum((vv2 - vv1)**2.0 for vv1, vv2 in zip(pt1, pt2)))**0.5 |
def read_input(filename):
"""
Read data from input file on form:
eg.
5 14 1 5 6 3 10
where first number is N, second is K and rest is data set.
args:
filename :: string
path to input file
returns:
out :: list of tuples.
"""
out = []
with open(filename,... |
def tokenize(s):
"""
:param s: string of the abstract
:return: list of word with original positions
"""
def white_char(c):
return c.isspace() or c in [',', '?']
res = []
i = 0
while i < len(s):
while i < len(s) and white_char(s[i]): i += 1
l = i
while i < ... |
def is_numeric(input_str):
"""
Takes in a string and tests to see if it is a number.
Args:
text (str): string to test if a number
Returns:
(bool): True if a number, else False
"""
try:
float(input_str)
return True
except ValueError:
return False |
def gr1c_to_python(ast, symtable=None):
"""Create new AST that uses Python from one having gr1c syntax.
If symtable is not None, it will be used to ensure primed
variables get unique names. Else, every primed variable is named
as the original variable with the suffix '_next'.
"""
if isinstance(... |
def proportional_resize(orig_size, desired_width, aspect_ratio=2.0):
"""proportionally resize an image with a given aspect-ratio"""
w,h = orig_size
return (desired_width, int(round(desired_width / aspect_ratio / w * h)) ) |
def column_integer_to_index(idx):
"""Convert integer column index to XLS-style equivalent
Given an integer index, converts it to the XLS-style
equivalent e.g. 'A', 'BZ' etc, using a zero-based
counting system (so zero is equivalent to 'A', 1 to 'B'
etc).
"""
# Convert integer column to ind... |
def valid_taxa(value):
"""Given a queryset of taxa, filters so only valid taxa stays"""
return [taxon for taxon in value if taxon.is_valid] |
def Sort_Points_2(x_values, y_values):
"""
Combine three arrays and sorts by ascending values of the first.
Args:
x_values (1darray):
Array of x-values. This array is the one which sorting will be based.
Each index of this array is related to the same index value of the othe... |
def extract_QnA_Ans_Sent(tab):
"""
Preprocessing of Data
"""
input_tuple =[]
extract = []
for index, item in enumerate(tab):
src = item['question']+ " <sep> "+ item['answer']
trg = item['answer_sentence']
input_tuple = [src,trg]
extract.append(input_tuple)
... |
def is_tag_restriction_pattern_valid(text):
"""
Determines if a given piece of text is considered a valid restricted tag pattern.
Valid patterns:
- Length: 0 < x <= 100 -- Prevents absurd tag lengths.
- If string contains a ``*``, must only contain one *, and be three characters or more.
Param... |
def return_limit(x):
"""Returns the standardized values of the series"""
dizionario_limite = {'BENZENE': 5,
'NO2': 200,
'O3': 180,
'PM10': 50,
'PM2.5': 25}
return dizionario_limite[x] |
def forecasted_occlusion_position(occlusion_bool_list):
""" Given a boolean list of occlusion events, return the index position of the forecasts
that indicate that an occlusion event has been predicted. """
positional_list = []
for i in range(len(occlusion_bool_list)):
if occlusion... |
def is_error(data):
"""check for error indication in data"""
return data[0] == 255 |
def parse_unwanted_urls(content):
"""
Parse the unwanted urls file.
This parse the raw content of the unwanted_urls file in order to get a nice
list. This file is originally a host file to prevent connection to/from
nasty websites (http://sbc.io/hosts/alternates/fakenews-gambling-po... |
def check_true(expr, ex=AssertionError, msg="expr was not True"):
"""
Raises an Exception when expr evaluates to False.
:param expr: The expression
:param ex: (optional, default AssertionError) exception to raise.
:param msg: (optional) The message for the exception
:return: True otherwise
... |
def config_parser(*args):
"""
<config> ::= <m-confs> <symbols>
<m-confs> ::= " " | <id> | "[" <id> {<id>} "]"
<symbols> ::= [["Not"] (<id> | "[" <id> {<id>} "]")]
Empty spaces in <m-confis> means "keep the previous input m-configuration
list <m-confs>". Both "None" and "Any", as symbol <id>s, h... |
def startswith(text, starts):
"""Filter to check if a string starts with a specific format"""
if isinstance(text, str):
starts = starts.split(",")
for start in starts:
if text.startswith(start):
return True
return False |
def get_messages_by_line(messages):
"""Return dictionary that maps line number to message."""
line_messages = {}
for message in messages:
line_messages[message.lineno] = message
return line_messages |
def add_suffix(signals, suffix):
"""Adds `suffix` to every element of `signals`."""
return [s + suffix for s in signals] |
def get_value(item, path: list):
""" Goes through the json item to get the information of the specified path """
child = item
count = 0
# Iterates over the given path
for i in path:
# If the child (step in path) exists or is equal to zero
if i in child or i == 0:
# Counts... |
def generateGetoptsFlags(emailFlagTuples):
"""
Generates the part of the getopts argument,
which declares the flags to look for.
Uses flags in emailFlagTuples.
"""
flagsString = ''
for emailFlagTuple in emailFlagTuples:
flagsString += emailFlagTuple[1]
return flagsString |
def bmi_to_bodytype(bmi):
"""
desc : converts bmi to a category body type based on CDC guidelines https://www.cdc.gov/healthyweight/assessing/bmi/adult_bmi/index.html
args:
bmi (float) : the users bmi
returns:
bodytype (string) : The users bodytype
"""
if bmi < 18.5:
... |
def strip_string_literals(code, prefix='__Pyx_L'):
"""
Normalizes every string literal to be of the form '__Pyx_Lxxx',
returning the normalized code and a mapping of labels to
string literals.
"""
new_code = []
literals = {}
counter = 0
start = q = 0
in_quote = False
hash_mar... |
def quarter_from_month(month: int) -> int:
"""Calculate quarter (1 indexed) from month (1 indexed).
>>> [quarter_from_month(month) for month in range(1, 13)]
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
"""
return ((month - 1) // 3) + 1 |
def null_distance_results(string1, string2, max_distance):
"""Determines the proper return value of an edit distance function
when one or both strings are null.
**Args**:
* string_1 (str): Base string.
* string_2 (str): The string to compare.
* max_distance (int): The maximum distance allowed.... |
def findval(elems, key):
"""Help function for looking up values in the lmf."""
def iterfindval():
for form in elems:
att = form.get("att", "")
if att == key:
yield form.get("val")
yield ""
return next(iterfindval()) |
def format_time_to_HMS( num_seconds ):
"""
Formats 'num_seconds' in H:MM:SS format. If the argument is a string,
then it checks for a colon. If it has a colon, the string is returned
untouched. Otherwise it assumes seconds and converts to an integer before
changing to H:MM:SS format.
"""
i... |
def added_json_serializer(obj):
"""
Default json encoder function for supporting additional object types.
Parameters
----------
obj : `iterable`
Returns
-------
result : `Any`
Raises
------
TypeError
If the given object is not json serializable.
"""... |
def simplify_nested_dict(dictionary, name, separator='_'):
"""
Takes a nested dictionary and transforms it into a flat one.
:param dictionary: (dict) dictionary to transform
:return: (dict) result dictionary
"""
res = dict()
for key in dictionary:
if isinstance(dictionary[key], dict... |
def are_strings_mappable(s1, s2):
"""
Takes in two strings and evaluates if a direct mapping relationship is possible
Returns True if possible or False otherwise
"""
if type(s1) != str or type(s2) != str:
raise TypeError("Arguments of are_strings_mappable must be a string")
if len(s1) !... |
def search_data(sequence_length, num_of_depend, label_start_idx,
num_for_predict, units, points_per_hour):
"""
Parameters
----------
sequence_length: int, length of all history data
num_of_depend: int,
label_start_idx: int, the first index of predicting target
num_for_predict... |
def taskname(*items):
"""A task name consisting of items."""
s = '_'.join('{}' for _ in items)
return s.format(*items) |
def coerce_url(url, default_schema='http'):
"""
>>> coerce_url('https://blog.guyskk.com/feed.xml')
'https://blog.guyskk.com/feed.xml'
>>> coerce_url('blog.guyskk.com/feed.xml')
'http://blog.guyskk.com/feed.xml'
>>> coerce_url('feed://blog.guyskk.com/feed.xml')
'http://blog.guyskk.com/feed.xm... |
def tofloat(x):
"""Convert to floating point number without throwing exception"""
from numpy import nan
try: return float(x)
except: return nan |
def check_last_chunk(sublist, full_list):
""" Identify if the current list chunk is the last chunk """
if sublist[-1] == full_list[-1]:
return True
return False |
def t_gate_counts_nondeterministic(shots, hex_counts=True):
"""T-gate circuits reference counts."""
targets = []
if hex_counts:
# T.H
targets.append({'0x0': shots / 2, '0x1': shots / 2})
# X.T.H
targets.append({'0x0': shots / 2, '0x1': shots / 2})
# H.T.T.H = H.S.H
... |
def merge_lists(a, b):
"""
Merge lists - e.g.,
[1, 2, 3, 4, 5, 6] & ['a', 'b', 'c']
=> [1, 'a', 2, 'b', 3, 'c', 4, 5, 6]
:param a: List a
:param b: List b
:return: Merged lists
"""
result = []
length = min([len(a), len(b)])
for i in range(length):
result.append(a[i])
... |
def is_palindrome(n):
"""Determine whether n is palindrome."""
# Convert the given number into list.
number_original = list(map(int, str(n)))
# First, store a copy of the list of original number.
number_reversed = number_original[:]
# Then, reverse the list.
number_reversed.reverse()
r... |
def combine_dict(dict0, dict1, update_func=lambda a, b: b):
"""Combine two dictionaries
Args:
dict0: dict
dict1: dict
update_func: the function to combine two values from the same key;
default function uses the value from dict1
Returns:
dict2: combined dict
Examples:
dic... |
def get_geometry_type(gi):
""" Return the geometry type from a __geo_interface__ dictionary """
if gi["type"] == "Feature":
return get_geometry_type(gi["geometry"])
elif gi["type"] in ("FeatureCollection", "GeometryCollection"):
return get_geometry_type(gi["geometries"][0])
else:
... |
def get_most_significant_bits(uuid_val):
"""Equivalent to getMostSignificantBits() in Java."""
msb_s = ''.join(str(uuid_val).split('-')[:3])
msb = int(msb_s, 16)
if int(msb_s[0], 16) > 7:
msb = msb - 0x10000000000000000
return msb |
def __assert_sorted(collection):
"""Check if collection is sorted, if not - raises :py:class:`ValueError`
:param collection: collection
:return: True if collection is sorted
:raise: :py:class:`ValueError` if collection is not sorted
Examples:
>>> __assert_sorted([0, 1, 2, 4])
True
>>>... |
def is_prime(n):
""" Return True if n is a prime number, else False. """
if n < 2:
return False
raise NotImplementedError("This exercise is still unsolved.") |
def base_url(skin, variables):
""" Returns the base_url associated to the skin.
"""
return variables['skins'][skin]['base_url'] |
def merge_from_cfg(cfg, base_cfg):
"""
merge the cfg to base cfg
"""
for k, v in cfg.items():
if base_cfg.get(k) and isinstance(v, dict):
base_cfg.update({k: merge_from_cfg(v, base_cfg.get(k))})
else:
base_cfg.update({k: v})
return base_cfg |
def to_num(numstr):
"""Turns a comma-separated number string to an int"""
return int(numstr.replace(",", "")) |
def list_remove_repeat(x):
"""Remove the repeated items in a list, and return the processed list.
You may need it to create merged layer like Concat, Elementwise and etc.
Parameters
----------
x : list
Input
Returns
-------
list
A list that after removing it's repeated ... |
def shower(pct, data):
"""show a proper point based on the percentage"""
absolute = round(pct / 100 * sum(data), 2)
return f'{round(pct,2)} %\n{absolute} GB' |
def bitCount(int_type):
"""
Counting bits set, Brian Kernighan's way.
Source: http://wiki.python.org/moin/BitManipulation
"""
count = 0
while int_type:
int_type &= int_type - 1
count += 1
return count |
def make_dicts(param_list):
"""
makes array of dictionaries with parameters to load
"""
param_dicts = []
for teff in param_list[0]:
for logg in param_list[1]:
for feh in param_list[2]:
for aM in param_list[3]:
param_dict = {'Teff':teff, 'logg':... |
def parse_adr(feature):
"""
returns dict
'id', 'category' - required keys
'dist_meters' - distance from point in search
"""
res = {
'id' : feature['id'],
'category' : 'adr_address',
'adr_name' : feature['properties']['name'],
'str_name' : feature['proper... |
def child_max(dependencies, dependents, scores):
""" Maximum-ish of scores of children
This takes a dictionary of scores per key and returns a new set of scores
per key that is the maximum of the scores of all children of that node plus
its own score. In some sense this ranks each node by the maximum
... |
def ndvi(nir, red):
"""
Compute Vegetation Index from RED and NIR bands
NDVI = \\frac { NIR - RED } { NIR + RED }
:param nir: Near-Infrared band
:param red: Red band
:return: NDVI
"""
return (nir-red) / (nir+red) |
def _relative_path(from_dir, to_path):
"""Returns the relative path from a directory to a path via the repo root."""
return "../" * (from_dir.count("/") + 1) + to_path |
def function_to_vector(function, model):
"""Assigns a vector to a function.
Args:
function (str): the function name.
model (dict): A mapping that words as follows:
model[function] == vector
Returns:
vector: A numpy array, or None if the function was not found in the
... |
def clean_command_type(text: str) -> str:
"""Remove parents from the command type"""
text = text.replace("Command.", "")
text = text.replace("CommandType.", "")
return text |
def _get_rule_conditional_format(type_, values, format_, ranges):
"""
Get rule to conditionally highlight cells.
:param type_: Type of conditional comparison to make.
:param values: User entered values (using '=A1' notation).
:param format_: Format of cells matching condition.
:param ranges: Ran... |
def obinfo(ob):
"""A bit of information about the given object. Returns
the str representation of the object, and if it has a shape,
also includes the shape."""
result = str(ob)
if hasattr(ob,"shape"):
result += " "
result += str(ob.shape)
return result |
def teams_and_members(review_teams):
"""Fixture with a dictionary contain a few teams with member lists."""
return {
"one": ["first", "second"],
"two": ["two"],
"last_team": [str(i) for i in range(10)],
**review_teams,
} |
def get_chars_match_up(data: list) -> dict:
"""
Gets the relevant match ups for all characters
"""
match_up = {}
for game in data:
win_char = game["_source"]["winner_char"]
lose_char = game["_source"]["loser_char"]
if win_char not in match_up:
match_up[win_char] =... |
def reynolds(rhosuspension, flowrate, tubediameter, mususpension_value):
"""Returns Reynolds number in a pipe.
#Inputs:
#rhosuspension : Density of the culture suspension ; kg.m-3
#flowrate : Flow rate in the pipe ; m.s-1
#tubediameter : Tube diameter ; m
#mususpension_value :... |
def parse_etraveler_response(rsp, validate):
""" Convert the response from an eTraveler clientAPI query to a
key,value pair
Parameters
----------
rsp : return type from
eTraveler.clientAPI.connection.Connection.getHardwareHierarchy
which is an array of dicts information about the 'c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.