content stringlengths 42 6.51k |
|---|
def gasoline_cost_sek(dist, sekpl=20.0, kmpl=9.4):
"""Gets cost of commute via car in Swedish Krona.
Input
dist: distance in kilometers (numeric)
sekpl: Swedish Krona (SEK) per liter (L). Obtained from gasoline_price() function.
kmpl: Kilometers (km) per liter (L). (Fuel efficiency)
... |
def _is_list_like(x):
"""Helper which returns `True` if input is `list`-like."""
return isinstance(x, (tuple, list)) |
def get_mean_metric(metric_records, ground_truth_classes_records):
"""
Calculate mean metric, but only count classes which have ground truth object.
:param metric_records: get the metric dict like:
metric_records = {'arson':0.77, 'assault':0.60, 'shooting':0.88,..}
:param ground_truth_c... |
def name_relative_to(parent_abspath, child_abspath):
""" Determine the relative name of a child path with respect to a parent
system.
Args
----
parent_abspath : str
Asbolute path of the parent.
child_abspath : str
Absolute path of the child.
Returns
-------
str
... |
def bugs_mapper(bugs, package):
"""
Update package bug tracker and support email and return package.
https://docs.npmjs.com/files/package.json#bugs
The url to your project's issue tracker and / or the email address to
which issues should be reported.
{ "url" : "https://github.com/owner/project/i... |
def combine_dict(d1,d2):
"""Creates a dictionary which has entries from both of them.
:param d1: dictionary 1
:param d2: dictionary 2
:return: resulting dictionary
"""
d = d1.copy()
d.update(d2)
return d |
def generate_gbaoab_string(K_r=1):
"""K_r=1 --> 'V R O R V
K_r=2 --> 'V R R O R R V'
etc.
"""
Rs = ["R"] * K_r
return " ".join(["V"] + Rs + ["O"] + Rs + ["V"]) |
def type_coerce(type_, value, fallback):
"""Return type_(value), on ValueError return fallback."""
# turn user parameters into int/float where there is no try/except already
try:
return type_(value)
except ValueError:
return fallback |
def get_trimmed_string(value):
"""
Returns a string of value (stripped of \'.0\' at the end). Float values
are limited to 1 decimal place.
"""
if isinstance(value, float):
value = round(value, 1)
value_str = str(value)
if value_str.endswith('.0'): value_str = value_str[:-2]
retur... |
def get_text_or_binary(filename):
"""Read the first 1024 and attempt to decode it in utf-8. If this succeeds,
the file is determined to be text. If not, its binary."""
with open(filename, 'rb') as f:
chunk = f.read(1024)
try:
chunk.decode('utf-8')
return 'text/plain'
except U... |
def spg_line_search_cauchy_step_size(beta, sksk, alpha_min=1e-3, alpha_max=1e3):
"""Return next value of Cauchy step size parameter in SPG optimization."""
if beta <= 0:
return alpha_max
return min(alpha_max, max(alpha_min, sksk / beta)) |
def fix_sig(app, what, name, obj, options, signature,
return_annotation):
""" Underline class name and separate it from parameters
**Deprecated**
"""
if 'class' == what:
# underline class name manually
new_signature="\n"
new_signature+="-"*(len... |
def to_bytes(text, encoding=None, errors='strict'):
"""Return the binary representation of `text`. If `text`
is already a bytes object, return it as-is."""
if isinstance(text, bytes):
return text
if not isinstance(text, str):
raise TypeError('to_bytes must receive a str or bytes '
... |
def listCount(l):
"""returns len() of each item in a list, as a list."""
for i in range(len(l)):
l[i]=len(l[i])
return l |
def _make_track_ids_smallest(annotations):
"""
Adapted from motion3d:scripts/gen_pseudo_gt_tracks.py
Maps track_ids to smallest set of natural numbers
"""
tids = set(a['track_id'] for a in annotations)
tid2nat = {tid: i for i, tid in enumerate(sorted(tids))}
for a in annotations:
a[... |
def get_children(res,key):
"""
Returns a list with all keys in res starting with key
Parameters
----------
res : dict
results dictionary
key : string
a search key
Returns
-------
keys : list
list of keys that start with key
... |
def count_for(s, value):
"""Count the number of occurrences of value in sequence s.
>>> count_for(digits, 8)
2
"""
total = 0
for elem in s:
if elem == value:
total = total + 1
return total |
def hexToRGB01(hexColor):
"""
Return a hex color string as an RGB tuple of floats in the range 0..1
"""
h = hexColor.lstrip('#')
return tuple([x / 255.0 for x in [int(h[i:i + 2], 16) for i in (0, 2, 4)]]) |
def gnomeSort(array): # in-place | stable
"""
Best : O(n) Time | O(1) Space
Average : O(n^2) Time | O(1) Space
Worst : O(n^2) Time | O(1) Space
"""
index = 0
while index < len(array):
if index == 0:
index = index + 1
if array[index] >= array[index - 1]:
... |
def mod2plus5(x1, x2, x3):
"""returns the reminder plus 5 of three numbers"""
def inner(x):
"""Returns the reminder plus 5 of a value"""
return x % 2 + 5
return (inner(x1), inner(x2), inner(x3)) |
def merge_spans(spans):
"""Returns a sorted list of (start, end) spans with overlapping spans merged."""
result = sorted(spans)
result, rest = result[:1], result[1:]
for span in rest:
if span[0] <= result[-1][1]:
result[-1] = (result[-1][0], max(span[1], result[-1][1]))
else:... |
def _py_lazy_or(cond, b):
"""Lazy-eval equivalent of "or" in Python."""
return cond or b() |
def get_supported_os_for_architecture(architecture):
"""Return list of supported OSes for the specified architecture."""
oses = ["alinux2", "ubuntu1804", "centos8"]
if architecture == "x86_64":
oses.extend(["centos7", "alinux", "ubuntu1604"])
return oses |
def count_common_terms(list1, list2):
""" Returns the number of common terms in two lists of terms.
"""
if list1 is None or list2 is None:
return 0
return len(set(list1) & set(list2)) |
def validate_storage_type(storage_type):
"""
Validate StorageType for DBInstance
Property:
"""
VALID_STORAGE_TYPES = ("standard", "gp2", "io1")
if storage_type not in VALID_STORAGE_TYPES:
raise ValueError(
"DBInstance StorageType must be one of: %s" % ", ".join(VALID_STORAG... |
def clip(x, minimum=None, maximum=None):
"""Clip (limit) input value.
Parameters
----------
x : float
Value to be clipped.
minimum : float
Lower limit.
maximum : float
Upper limit.
Returns
-------
float
Clipped value.
"""
if minimum is not N... |
def get_output_actions(in_vlan,out_vlan):
"""
This is to setup rules for host to switch / switch to host.
It honors what we are trying to accomlish with testing Kilda:
1) Kilda will put rules on one or more switches
2) This code will put rules on the switches outside that set. For instance, ... |
def make_outfile_name(readsfile_basename, processing_action, output_type):
"""
Create a name for an output file based on action performed.
:param str readsfile_basename: path-less and extension-less version of name
of file of reads.
:param str processing_action: name for the processing action b... |
def _limit_grouped_results(results, limit):
"""Limit a grouped set of results
"""
return results[:limit] if limit else results |
def _bop_divisible(num1, num2):
"""Return True if num1 is divisible by num2."""
return (num1 % num2) == 0.0 |
def broker_range(n):
"""Return list of brokers with broker ids ranging from 0 to n-1."""
return {str(x): {"host": "host%s" % x} for x in range(n)} |
def _lexemes2synset_tfidf(a_germanet, a_synid2tfidf, a_lexemes, a_pos=None):
"""Convert lexemes to tf/idf vectors corresponding to their synsets
@param a_germanet - GermaNet instance
@param a_synid2tfidf - dictionary mapping synset id's to tf/idf vectors
@param a_lexemes - set of lexemes for which to e... |
def map_inds_to_intersect(lists1, lists2, ind2labs):
"""Converts 2 lists containing indices for phonemes from different
phoneme sets to a single phoneme so that comparing the equality
of the indices of the resulting lists will yield the correct
accuracy.
Arguments
---------
lists1 : list of... |
def get_wandb_project_dict(project_name):
"""Return wandb project dictionary
Args:
project_name (str): wandb project name
Returns:
dict: dictionary containing best models run_id split_name and dataset_name
"""
res = None
if project_name == "lastfm_dat":
res = {
... |
def quartiles(values):
"""
Returns the (rough) quintlines of a series of values. This is not intended
to be statistically correct - it's not a quick 'n' dirty measure.
"""
if not values:
return [0 for i in range(5)]
return [i * max(values) / 4 for i in range(5)] |
def divide(a: int = 0, b: int = 1) -> float:
"""Divide two numbers."""
print(a / b)
return a / b |
def change_making_greedy(target, coin_set):
"""
returns the minimal numbers of coins required to reach the target, or [] if
it can't be reached. Note that this algorithm fails for special sets of
coins called "non-canonical" sets. Most real-life sets are canonical though
and we can use this efficien... |
def calculate_degrees_between_angle(norm_1, norm_2, angle):
"""
Takes two normalized values in a range of [0, 1] and calculates a proportion inside an angle.
:param norm_1: First normalized value.
:param norm_2: Second normalized value.
:param angle: Angle in which to calculate the proportion.
... |
def create_end_piece(pos, strand, dist):
""" Creates a zero based interval of length 'dist' that starts inside the
transcript and ends with the transcript end."""
if strand == "+":
interval_start = pos - dist
interval_end = pos
elif strand == "-":
interval_start = pos
... |
def anything(text):
"""Method for parsing a string (or anything) between commas
string."""
if text:
return text
else:
return None |
def _merge(a, b):
""" a overwrites values in b
"""
for k in a.keys():
if isinstance(a[k], dict) and k in b and isinstance(b[k], dict):
b[k] = _merge(a[k], b[k])
else:
b[k] = a[k]
return b |
def _is_dense_dictionary_argument(argument, dense_indices):
"""Check whether all keys of the dictionary argument are also dense indices.
We cannot check whether all dense indices are in the argument because `splitted_df`
in :func:`split_and_combine_df` may not cover all dense combinations.
"""
ret... |
def check_list_palindrome(ls):
"""
Question 8.12: Check whether singly-linked
list is a palindrome
"""
if ls is None:
return True
slow = ls
fast = ls
first_half = []
while fast and fast.next:
first_half.append(slow.val)
slow = slow.next
fast = fast.n... |
def wrapStringToFunctionDef(functionName, scriptString, kwargs=None):
"""Generates function string which then can be compiled and executed
Example:
::
wrapStringToFunctionDef('test', 'print(a)', {'a': 5})
Will produce following function:
::
def test(a=5):
print(a)
... |
def _is_url(string):
"""
Checks if the given string is an url path.
Returns a boolean.
"""
return string.startswith("http") |
def binary_search(items, x):
"""Searches for an item in a sorted list of items.
Uses binary search to find the index of x in the list items.
Args:
items: A sorted list of items.
x: The item to be searched.
Returns:
The index of x if it is in the list items,
otherw... |
def GetTreeOfCombines(rule, tree=None):
"""Get the tree structure of combines in the rule syntax subtree."""
if not tree:
tree = {'rule': rule, 'variables': set(), 'subtrees': []}
if isinstance(rule, list):
for v in rule:
tree = GetTreeOfCombines(v, tree)
if isinstance(rule, dict):
if 'variab... |
def split(items):
"""
Usually everything in admin tool is ordered one-by-one from top to bottom
<form1>
--------
<form2>
--------
<links>
This may be space insufficient. Place two items inside this split, and result will be
<form1> | <form2>
-----------------
<links>
... |
def linear_anneal(base_lr, global_step, warmup_steps, min_lr):
"""
Linearly annealed learning rate from 0 in the first warming up epochs.
:param base_lr: base learning rate
:type base_lr: float
:param global_step: global training steps
:type global_step: int
:param warmup_steps: number of s... |
def get_form(count, variations):
""" Get form of a noun with a number """
count = abs(count)
if count % 10 == 1 and count % 100 != 11:
return variations[0]
if count % 10 in (2, 3, 4) and count % 100 not in (12, 13, 14):
return variations[1]
return variations[2] |
def profit_calculator_2nd(x, prices):
"""
:type x: list(float)
:type prices: list(float)
:rtype: float
"""
if len(x) == len(prices):
total = 0.0
for i in range(len(x)):
total += x[i] * prices[i]
return total
else:
raise ValueError("Mismatch number ... |
def to_str(slug):
"""
converts slug to str
:param slug:
:return: str
"""
if not isinstance(slug, str):
raise ValueError("to_str expects arguments of type 'str'")
return ' '.join(slug.split('-')) |
def substitute_labels(labels, old, new):
"""Replaces label names in a list of labels."""
return [new if label == old else label for label in labels] |
def find_largest_digit_helper(n, compare):
"""
:param n: int, the original integer
:param compare: int, the candidate of the biggest digit
:return: int, return the biggest digit
"""
if n == 0:
return compare
else:
if n % 10 > compare:
compare = n % 10
n = n // 10
return find_largest_digit_helper(n, co... |
def Trim(t, p=0.01):
"""Trims the largest and smallest elements of t.
Args:
t: sequence of numbers
p: fraction of values to trim off each end
Returns:
sequence of values
"""
n = int(p * len(t))
t = sorted(t)[n:-n]
return t |
def mean(mylist):
"""
Calculates the arithmetic average of mylist
:param mylist: The list to take the average over
:return: Arithmetic average of mylist
"""
# List is empty
if len(mylist) == 0:
return 0
else:
return sum(mylist) / len(mylist) |
def checkio(number, radix):
"""Convert a stringified number of given radix into an integer."""
try:
return int(number, base=radix)
except ValueError:
return -1 |
def SplitByN(seq, n):
"""
Split function
"""
return [seq[i:i + n] for i in range(0, len(seq), n)] |
def get_meterological_equation_case_hdd(t_min, t_max, t_base):
"""Calculate case number to calculate hdd with Meteorological Office
equations
Arguments
---------
t_min : float
Minimum daily temperature
t_max : float
Maximum dail temperature
t_base : float
Base temper... |
def gfmul(x, y):
"""Returns the 128-bit carry-less product of 64-bit x and y."""
ret = 0
for i in range(64):
if (x & (1 << i)) != 0:
ret ^= y << i
return ret |
def convert_dict(mydict, numentries):
""" Convert dict of lists to list of dicts.
Args:
mydict: dict
numentries: int
Returns: list
"""
data = []
for i in range(numentries):
row = {}
for k, l in mydict.items():
row[k] = l[i]
data... |
def num2str(n):
"""
from http://benkurtovic.com/2014/06/01/obfuscating-hello-world.html
"""
if n:
return chr(n % 256) + num2str(n // 256)
else:
return "" |
def flatten_pipes_dict(pipes_dict : dict) -> list:
"""
Convert the standard pipes dictionary into a list
"""
pipes_list = []
for ck in pipes_dict.values():
for mk in ck.values():
pipes_list += list(mk.values())
return pipes_list |
def sign(number):
"""
Returns the sign of the number (-1, 0 or 1)
Arg1: float
Returntype: int
"""
if number > 0:
return 1
elif number < 0:
return -1
else:
return 0 |
def cfg_tobool(v):
"""
>>> cfg_tobool('yes')
True
>>> cfg_tobool('true')
True
>>> cfg_tobool('T')
True
>>> cfg_tobool('1')
True
>>> cfg_tobool('no')
False
>>> cfg_tobool('false')
False
>>> cfg_tobool('F')
False
>>> cfg_tobool('0')
False
>>> cfg_tob... |
def get_item(obj, key):
"""
Template tag to return a given key dynamically from a dictionary or an object
"""
val = None
if obj and type(obj) == dict:
val = obj.get(key)
elif obj and hasattr(obj, key):
val = getattr(obj, key)
val = val or ""
return val |
def normalize_events_list(old_list):
"""Internally the `event_type` key is prefixed with underscore but the API
returns an object without that prefix"""
new_list = []
for _event in old_list:
new_event = dict(_event)
new_event['event_type'] = new_event.pop('_event_type')
new_list.... |
def check_loaded_dict(dkt) -> bool:
"""
Recursive check if dict `dkt` or any sub dict contains '__error__' key.
:param dkt: dict to check
"""
if not isinstance(dkt, dict):
return True
if "__error__" in dkt:
return False
for val in dkt.values():
if not check_loaded_di... |
def common_op_info(json_file):
"""
Create more detail info
:param json_file: origin json file
:return: origin json file
"""
json_file["L1_addr_offset"] = 0
json_file["L1_fusion_type"] = -1
json_file["L1_workspace_size"] = -1
json_file["addr_type"] = 0
json_file["slice_offset"] = ... |
def sort_obj(gen_info):
""" Hover info of objects type in fibers (wedge) plots.
input: gen_info= mergedqa['GENERAL_INFO']
returns: list(500)
"""
obj_type = ['']*500
for key in ['LRG', 'ELG', 'QSO', 'STAR', 'SKY']:
if gen_info.get(key+'_FIBERID', None):
print(k... |
def pymodule_fpaths_to_objects(fpaths):
"""
Takes an iterable of file paths reprenting possible python modules and will return an
iterable of tuples with the file path along with the contents of that file if the file
exists.
If the file does not exist or cannot be accessed, the thir... |
def is_float(s):
"""
Checks whether a string represents a valid float
"""
try:
_ = float(s)
except ValueError:
return False
return True |
def output_compareinfo_csv(file, info, fields=['p', 'r', 'F1']):
""" Pre-format a row that holds measures about similarity of a table
to the ground truth.
"""
lines = []
tabmatch = 1 if info['tabcount_match'] else 0
for tinfo in info['tables']:
lines.append([file, str(tabmatch)] + [s... |
def outer_product(func, x, y):
"""outer_product: outer product of func with x and y"""
res = []
tmp = []
for i in x:
tmp = []
for j in y:
tmp.append(func(i, j))
res.append(tmp)
return res |
def estimate_phones(x):
"""
Allocate consumption category given a specific luminosity.
"""
if x['mean_luminosity_km2'] > 5:
return 10
elif x['mean_luminosity_km2'] > 1:
return 5
else:
return 1 |
def _get_spline_mode(mode):
"""spline boundary mode for interpolation with order >= 2."""
if mode in ['mirror', 'reflect', 'grid-wrap']:
# exact analytic boundary conditions exist for these modes.
return mode
elif mode == 'grid-mirror':
# grid-mirror is a synonym for 'reflect'
... |
def display(keyword):
"""``display`` property validation."""
return keyword in (
'inline', 'block', 'inline-block', 'list-item', 'none',
'table', 'inline-table', 'table-caption',
'table-row-group', 'table-header-group', 'table-footer-group',
'table-row', 'table-column-group', 'ta... |
def convert_to_crlf(string):
"""Unconditionally convert LF to CRLF."""
return string.replace('\n', '\r\n') |
def get_limits(data):
""" Get the x, y ranges of the ST data.
"""
y_min = 1e6
y_max = -1e6
x_min = 1e6
x_max = -1e6
for doc in data:
x = doc["x"]
y = doc["y"]
y_min = y if y < y_min else y_min
y_max = y if y > y_max else y_max
x_min = x if x < x_min e... |
def get_aws_cloudtrail_write_s3_policy_statement(aws_account_id, s3_bucket_name, s3_prefix=''):
""" Return dictionary (that should be converted to json) of AWSCloudTrailWrite policy """
# Grabbed from:
# http://docs.aws.amazon.com/awscloudtrail/latest/userguide/create-s3-bucket-policy-for-cloudtrail.html
... |
def quote_string(v):
"""
RedisGraph strings must be quoted,
quote_string wraps given v with quotes incase
v is a string.
"""
if isinstance(v, bytes):
v = v.decode()
elif not isinstance(v, str):
return v
if len(v) == 0:
return '""'
v = v.replace('\\', '\\\\')... |
def grid3D(grid3D_width=100,
grid3D_height=100,
grid3D_depth=100,
grid3D_rotate_speed=10,
grid3D_rotate_sensitivity=1,
is_grid3D_rotate=False,
**kwargs):
"""
:param grid3D_width:
3D axis width
:param grid3D_height:
3D axis he... |
def ToBytes(in_string):
"""Converts a string into a byte stream.
Args:
string: The string to convert.
Returns:
The converted string, or the original string if already a byte stream.
"""
if isinstance(in_string, bytes):
return in_string
else:
return bytes(in_string, 'utf-8') |
def get_chrom_time_min_max(chromatograms):
"""
Get the highest and lowest retention times from a set of chromatograms.
Parameters
----------
chromatograms: list of Chromatogram objects.
Returns
-------
max_time, min_time: float
"""
max_time = 1e100
min_time = 0
for c i... |
def param_string(pdict):
"""A function for creating a reduced parameter input file."""
param_dict = {}
for pair in pdict.items():
genus = pair[0].split('.')[0]
species = pair[0].split('.')[1]
if genus not in param_dict.keys():
param_dict[genus] = {}
param_di... |
def ext(filename):
"""
:param filename: a file name with extension e.g. movie.mkv
:return: the extension of the filename e.g. .mkv
"""
return '.' + filename.split('.')[-1] |
def recurse_fib(n):
""" F(n) = F(n - 1) + F(n - 2) """
if n < 2:
return n
else:
return recurse_fib(n - 1) + recurse_fib(n - 2) |
def flatten_angles(angle_map, rad_angle_epsilon=8):
"""Concat similar angles together
Args:
angle_map (dict): list of something indexed by angles
rad_angle_epsilon (float): how much of the difference to squash in rad
"""
ret = {}
last_angle = None
for angle in sorted(angle_map):... |
def stepUp(val, step):
"""Convenience method for picking the maximum range of a filter"""
return (int(val/step)+1)/(1/step) |
def contig_name_to_plink_name(chrom):
"""Converts chromosome / contig name to the values expected by 'plink',
namely a digit or X/Y, or returns None if the chromosome could not be
identified.
"""
if chrom.isdigit():
return chrom
elif chrom.upper() in "XY":
return chrom.upper()
... |
def seq3(seq):
"""
Method that returns the amino acid sequence as a
list of three letter codes. Output follows the IUPAC standard plus 'Ter' for
terminator. Any unknown character, including the default
unknown character 'X', is changed into 'Xaa'. A noncoded
aminoacid selenocystein is recognized (Sel,... |
def color(text, color_code, readline=False):
"""Colorize text.
@param text: text.
@param color_code: color.
@return: colorized text.
"""
if readline:
# special readline escapes to fix colored input promps
# http://bugs.python.org/issue17337
return "\x01\x1b[%dm\x02%s\x01... |
def split_text_to_paragraphs(text: str) -> list:
"""Split text into paragraphs
A paragraphs is detected by an empty line
:param text: input text
:return: list of paragraphs
"""
paragraphs = []
current_paragraph = []
for line in text.splitlines():
# non empty line -> add to para... |
def i_to_black(i, normalize=False):
"""Convert a number between 0.0 and 1.0 to a shade of black.
Parameters
----------
i : float
A number between 0.0 and 1.0.
normalize : bool, optional
Normalize the resulting RGB values.
Default is to return integer values ranging from 0 to... |
def _hide_key(param, value):
"""Used to hide keys in the logging."""
if not param.endswith('_key'):
return value
if len(value) > 16:
return value[:3]+'...'+value[-3:]
else:
return '********' |
def action_list_to_string(action_list):
"""Util function for turning an action list into pretty string"""
action_list_string = ""
for idx, action in enumerate(action_list):
action_list_string += f"{action['name']} ({action['action']['class_name']})"
if idx == len(action_list) - 1:
... |
def preprocess_sentence(sentence):
"""Add a full stop to each sentence and make it lower case."""
return sentence.rstrip('\n').rstrip('.').lower() + '.' |
def between(s, substr_1, substr_2=None):
""" text between inner and outer substrings (exclusive)
eg:
'ell' = between('hello', 'h', 'o')
"""
if substr_2 is None:
substr_2 = substr_1
i_1 = s.index(substr_1) + len(substr_1)
i_2 = s.index(substr_2, i_1)
return s[i_1:i_2] |
def _py_while_stmt(test, body, init_state, opts):
"""Overload of while_stmt that executes a Python while loop."""
del opts
state = init_state
while test(*state):
state = body(*state)
return state |
def stopband_atten_to_dev (atten_db):
"""Convert a stopband attenuation in dB to an absolute value"""
return 10**(-atten_db/20) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.