content stringlengths 42 6.51k |
|---|
def _check_dimensions_objects(R):
"""
:param R: dictionary from (type, type) to relational matrix
:return: dictionary string to int (dimension of that type)
"""
print(R)
dimensions = {}
for r in R:
t1, t2 = r
for l in range(len(R[r])):
if dimensions.get(t1) is no... |
def beta_mean(x,y):
"""Calculates the mean of the Beta(x,y) distribution
Args:
x (float): alpha (shape) parameter
y (float): beta (scale) parameter
Returns:
float: A float that returns x/(x+y)
"""
output = x / (x+y)
return output |
def _pick_geographic_location(parameters_json: dict) -> list:
""" Sometimes, curate has an array, and sometimes an array within an array, where the inner-most array will have strings. We need to accommodate both. """
""" placeOfCreation has this format: ["Ani, Kars Province, Turkey", " +40.507500+43.572777.",... |
def generate_level_sequence(nested_list,root_rank=0):
"""
Return a level sequence representation of a tree or subtree,
based on a nested list representation.
"""
level_sequence = [root_rank]
for child in nested_list:
level_sequence += generate_level_sequence(child,root_rank=root_rank+1)
... |
def compare(a, b):
""" Constant time string comparision, mitigates side channel attacks. """
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0 |
def escape_colons(string_to_escape):
"""
Escape the colons. This is necessary for secure password stanzas.
"""
return string_to_escape.replace(":", "\\:") |
def remove_non_breaking_space(string):
"""replace non breaking space characters"""
return string.replace("\xc2\xa0", "").replace("\xa0", "") if string else "" |
def site_email_prefix(request, registry, settings):
"""Expose website URL from ``tm.site_email_prefix`` config variable to templates.
This is used as the subject prefix in outgoing email. E.g. if the value is ``SuperSite`` you'll email subjects::
[SuperSite] Welcome to www.supersite.com
"""
r... |
def fib2(n):
""" return Fibonacci series up to n """
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result |
def calInitVec(tag_tag_n, tags_n):
"""
It is a function to calculate init vector.
:param tag_tag_n: Tag-tag type and its number
:param tags_n: Tag type and its number
:return: init vec
"""
# Calculate sum of tag_tag_n
sum_tag = sum(list(tag_tag_n.values()))
init_vec = [tags_n[value] ... |
def flows_from_generic(flows):
"""SequenceCollection from generic seq x pos data: seq of seqs of chars.
This is an InputHandler for SequenceCollection. It converts a generic list
(each item in the list will be mapped onto an object using
seq_constructor and assigns sequential integers (0-based) as ... |
def listify(x):
""" allow single item to be treated same as list. simplifies loops and list comprehensions """
if isinstance(x, tuple):
return list(x)
if not isinstance(x, list):
return [x]
return x |
def create_coco_refs(data_ref):
"""Create MS-COCO human references JSON."""
out = {'info': {}, 'licenses': [], 'images': [], 'type': 'captions', 'annotations': []}
ref_id = 0
for inst_id, refs in enumerate(data_ref):
out['images'].append({'id': 'inst-%d' % inst_id})
for ref in refs:
... |
def Secant(f, x_minus2, x_minus1, epsilon = 1.0E-4, N = 10000):
"""
Uses the Secant method to solve for f(x) = 0 given the values
to start at x_-2 and x_-1. returns a 3-tuple of x, n, and f(x)
"""
x = x_minus2
n = 0
while abs(f(x)) > epsilon and n <=N:
n+= 1
temp = x
... |
def get_lesion_size_ratio(corners, patch_shape):
"""Compute bbox to patch size ratio
Args:
corner_resize: tightest bbox coord of lesion (xmin, ymin, xmax, ymax)
patch_shape: in the order of (y_size, x_size)
Returns:
lesion_size_ratio: sqrt(lesion_area / patch_area)
"""
xmin... |
def factorial(num):
"""Calculates the factorial for a given number"""
total = 1
for i in range(2, (num + 1)):
total *= i
return total |
def language_check(message ,texts):
"""
check if the input is a correct language
"""
if message not in texts:
return False
return True |
def calculate_change(start: float, end: float) -> float:
"""Use Yahoo Finance API to get the relevent data."""
return round(((end - start) / start) * 100, 2) |
def dumps_requirement_options(
options,
opt_string,
quote_value=False,
one_per_line=False,
):
"""
Given a list of ``options`` and an ``opt_string``, return a string suitable
for use in a pip requirements file. Raise Exception if any option name or
value type is unknown.
"""
optio... |
def numToHex(n):
"""Convert integer n in range [0, 15] to hex."""
try:
return ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"][n]
except:
return -1 |
def sum_of_digits(number):
"""
What comes in: An integer.
What goes out: Returns the sum of the digits in the given integer.
Side effects: None.
Example:
If the integer is 83135,
this function returns (8 + 3 + 1 + 3 + 5), which is 20.
"""
# -----------------------------------... |
def text_length(text):
""" Get text length
"""
text = text.decode('utf-8')
return len(text) |
def get_dict_keys(d):
"""Return keys of a dictionary"""
return [key for key in d] |
def fib(n: int) -> int:
"""Calculate n-th Fibonacci number recursively, long version."""
assert n >= 0
if n in [0, 1]:
return 1
else:
return fib(n - 1) + fib(n - 2) |
def _kbase_log_name(name):
"""Smarter name of KBase logger."""
# no name => root
if not name:
return "biokbase"
# absolute name
if name.startswith("biokbase."):
return name
# relative name
return "biokbase." + name |
def gendot(adj):
"""
Return a string representing the graph in Graphviz DOT format
with all p->q edges. Parameter adj is an adjacency list.
"""
dot = "digraph g {\n"
dot += " rankdir=LR;\n"
# fill in
dot += "}\n"
return dot |
def set_query_string_parameter(page: int, data_order: str="") -> str:
"""
Create the query string to add at the end of the request url.
:param page: Page number to extract the data
:param data_order: Order of the data
:return: Query string parameter
"""
# Data is returned in ascend... |
def round_tat(num):
"""Changes the turnaround time from a float into natural language hours + minutes."""
remain = num%1
if num.is_integer():
if int(num) == 1:
return str(int(num)) + " hour."
else:
return str(int(num)) + " hours."
else:
if num < 1:
return str(int(remain*60)) + " minutes."
elif num-... |
def _fully_qualified_typename(cls):
"""Returns a 'package...module.ClassName' string for the supplied class."""
return '{}.{}'.format(cls.__module__, cls.__name__) |
def unquote(s):
"""Kindly rewritten by Damien from Micropython"""
"""No longer uses caching because of memory limitations"""
res = s.split('%')
for i in range(1, len(res)):
item = res[i]
try:
res[i] = chr(int(item[:2], 16)) + item[2:]
except ValueError:
... |
def reverse(x):
"""
:type x: int
:rtype: int
"""
new_str = str(x)
i = 1
rev_str = new_str[::-1]
if rev_str[-1] == "-":
rev_str = rev_str.strip("-")
i = -1
if (int(rev_str)>=2**31):
return 0
return (int(rev_str)) * i |
def cloudfront_public_lookup(session, hostname):
"""
Lookup cloudfront public domain name which has hostname as the origin.
Args:
session(Session|None) : Boto3 session used to lookup information in AWS
If session is None no lookup is performed
hostname: name ... |
def mixrange(s):
"""
Expand a range which looks like "1-3,6,8-10" to [1, 2, 3, 6, 8, 9, 10]
"""
r = []
for i in s.split(","):
if "-" not in i:
r.append(int(i))
else:
l, h = list(map(int, i.split("-")))
r += list(range(l, h + 1))
return r |
def flatten_list(obj):
"""
Given a set of embedded lists, return a single, "flattened" list.
:param obj:
:return:
"""
if not isinstance(obj, list):
return [obj]
else:
ret_list = []
for elt in obj:
ret_list.extend(flatten_list(elt))
return ret_list |
def d(a, b, N):
"""Wrapped distance"""
if b < a:
tmp = a
a = b
b = tmp
return min(b - a, N - (b - a)) |
def fizzbuzz(num: int) -> str:
"""For the given number, returns the correct answer in the Fizzbuzz game.
Args:
num: An integer number > 0
Returns:
A string corresponding to the game answer.
"""
if num % 3 == 0 and num % 5 == 0:
return f"{ num } - FizzBuzz"
elif num %... |
def ratio(num, denom, max_val, MAX_MULTIPLIER=2):
"""
function to define ratio and handle o denominator
"""
if denom == 0:
return float(max_val * MAX_MULTIPLIER)
else:
return float(num / denom) |
def concatenate_list_into_string(alist):
"""
Given a list like
alist = ["ada", "subtract", "divide", "multiply"]
the aim is to concatentate the to have a
string of the form: "adasubstractdividemultiply"
:param alist: list [list of items]
:return: str
"""
string = ""
for item in a... |
def unpack_meta(*inputs, **kwinputs):
"""Update ``kwinputs`` with keys and values from its ``meta`` dictionary."""
if 'meta' in kwinputs:
new_kwinputs = kwinputs['meta'].copy()
new_kwinputs.update(kwinputs)
kwinputs = new_kwinputs
return inputs, kwinputs |
def steering2(course, power):
"""
Computes how fast each motor in a pair should turn to achieve the
specified steering.
Input:
course [-100, 100]:
* -100 means turn left as fast as possible,
* 0 means drive in a straight line, and
... |
def is_starter(index, reason=None):
"""Takes index and reason column, returns either S, R or DNP.
Used on boxscore df. Reason is either Nan or 'Did Not Play'.
Keyword arguments:
index -- Used to define if starter or not
reason -- Used to define if DNP or not
"""
# Any reason converted to DN... |
def serialize_class(cls):
""" Serialize Python class """
return '{}:{}'.format(cls.__module__, cls.__name__) |
def _IsInstanceShutdown(instance_info):
"""Determine whether the instance is shutdown.
An instance is shutdown when a user shuts it down from within, and we do not
remove domains to be able to detect that.
The dying state has been added as a precaution, as Xen's status reporting is
weird.
"""
return in... |
def clamp(val, valmin, valmax):
"""Simple clamping function, limits to [min, max]"""
if val < valmin: return valmin
if val > valmax: return valmax
return val |
def calc_loop_steps(n, step_size, offset=0):
"""Calculates a list of 2-tuples for looping
through `n` results with steps of size `step_size`.
"""
steps = (n - offset) // step_size
remainder = (n - offset) % step_size
moves = [
(offset + (step_size * s), offset + (step_size * (s + 1))) fo... |
def _wick_length(close, low, open, high, upper):
"""
:param close:
:param low:
:param open:
:param high:
:return:
"""
if close > open:
top_wick = high - close
bottom_wick = open - low
else:
top_wick = high - open
bottom_wick = close - low
if up... |
def _dict_to_strings(kwds):
"""Convert all values in a dictionary to strings."""
ot = {}
assert isinstance(kwds, dict)
for k, v in kwds.items():
ot[k] = str(v)
return ot |
def efficientnet_params(model_name):
""" Map EfficientNet model name to parameter coefficients. """
params_dict = {
# Coefficients: width,depth,res,dropout
'efficientnet-b0': (1.0, 1.0, 224, 0.2),
'efficientnet-b1': (1.0, 1.1, 240, 0.2),
'efficientnet-b2': (1.1, 1.2, 260, 0.3),... |
def abreArquivos(arquivo):
"""
:param arquivo: arquivo que ira ser aberto
:return: palavras separas em lista
"""
palavrasArquivo = list ()
with open (str (arquivo), 'r') as arquivoCriptografado:
for linha in arquivoCriptografado:
if linha.strip ('\n') != '':
... |
def next_instruction_is_function_or_class(lines):
"""Is the first non-empty, non-commented line of the cell either a function or a class?"""
for i, line in enumerate(lines):
if not line.strip(): # empty line
if i > 0 and not lines[i - 1].strip():
return False
con... |
def average(lst):
"""Averages a list, tuple, or set of numeric values"""
return sum(lst) / len(lst) |
def omt_check(grade_v, grade_i, grade_j):
"""
A check used in omt table generation
"""
# A_r ^ B_s = <A_r B_s>_|r+s|
return grade_v == (grade_i + grade_j) |
def get_merged_jobs_steps(jobs, processed_cfg):
""" Merge and filter steps from all jobs """
blocked_steps = ['persist_to_workspace', 'attach_workspace', 'store_artifacts']
merged_steps = []
for jname in jobs:
steps = processed_cfg['jobs'][jname]['steps']
merged_steps += list(filter(lamb... |
def tzy_flatten(ll):
"""
Own flatten just for use of this context.
Expected outcome:
> flatten([1, 2, [3, 4], [5]])
[1, 2, 3, 4, 5]
Only goes 1 depth so should be O(n) time, but also O(n) space
"""
ret = []
for item in ll:
if isinstance(item, list):
for su... |
def give_color_to_direction_static(dir):
"""
Assigns a color to the direction (static-defined colors)
Parameters
--------------
dir
Direction
Returns
--------------
col
Color
"""
direction_colors = [[-0.5, "#4444FF"], [-0.1, "#AAAAFF"], [0.0, "#CCCCCC"], [0.5, "... |
def bus_resolve(bus_descriptor: str):
"""
>>> bus_resolve('bus2.3.1.2')
('bus2', (3, 1, 2))
>>> bus_resolve('bus2.33.14.12323.2.3.3')
('bus2', (33, 14, 12323, 2, 3, 3))
"""
bus_descriptor.replace('bus.', '')
tkns = bus_descriptor.split('.')
bus = tkns[0]
terminals = tuple(int(x... |
def err_msg(_format, _type, path):
"""Assertion error message."""
return "while testing format={}, data type={} saved as {}.".format(
_format, _type, path
) |
def FindApprovalValueByID(approval_id, approval_values):
"""Find the specified approval_value in the given list or return None."""
for av in approval_values:
if av.approval_id == approval_id:
return av
return None |
def helloworld(name):
"""Testando
Multiplas linhas
Args:
name (string): parametro entrada nome
Returns:
string: parametro saida nome
"""
print("Hello World!")
print(name)
return name |
def get_contours_points(found, contours):
"""
get contour's all inner points
:param found:
:param contours:
:return: contour's all inner points
"""
contours_points = []
for i in found:
c = contours[i]
for sublist in c:
for p in sublist:
contour... |
def parse_metadata_json(data):
""" Function to parse the json response from the metadata or the
arxiv_metadata collections in Solr. It returns the dblp url.
docs is a list of one result, so this is obtained by docs[0].get('url')"""
# docs contains authors, title, id generated by Solr, url
docs = da... |
def get_positions_at_time(positions, t):
"""
Return a list of positions (dicts) closest to, but before time t.
"""
# Assume positions list is already sorted.
# frame is a list of positions (dicts) that have the same timestamp.
frame = []
frame_time = 0.0
for pos in positions:
# I... |
def get_snapshots_from_text(query_output):
""" Translate expanded snapshots from `cali-query -e` output into list of dicts
Takes input in the form
attr1=x,attr2=y
attr1=z
...
and converts it to `[ { 'attr1' : 'x', 'attr2' : 'y' }, { 'attr1' : 'z' } ]`
"""
... |
def to_query_str(params):
"""Converts a dict of params to a query string.
Args:
params (dict): A dictionary of parameters, where each key is a
parameter name, and each value is either a string or
something that can be converted into a string. If `params`
is a list, i... |
def get_starting_chunk(filename, length=1024):
"""
:param filename: File to open and get the first little chunk of.
:param length: Number of bytes to read, default 1024.
:returns: Starting chunk of bytes.
"""
# Ensure we open the file in binary mode
try:
with open(filename, 'rb') as ... |
def decimalRound(toRound, numDec):
"""
decimalRound
Function used to round numbers to given decimal value with the following rules:
-should add zeroes if numDec > current number of decimal places
-should round up/down properly
-numDec = 0 should return an int
@param toRound << n... |
def do_pick(pick_status : int):
"""
This function takes one integer type argument and returns a boolean.
Pick Status = Even ==> return True (user's turn)
Pick Status = Odd ==> return False (comp's turn)
"""
if (pick_status % 2) == 0:
return True
else:
return False |
def save(level, save_type):
"""
Calculate a character's saves based off level
level: character's level
save_type: "good" or "poor"
returns a number representing the current base save
"""
if save_type == "good":
return int(round(level/2)) + 2
else:
return int(round(leve... |
def roundup_20(x):
"""
Project: 'ICOS Carbon Portal'
Created: Tue May 07 09:00:00 2019
Last Changed: Tue May 07 09:00:00 2019
Version: 1.0.0
Author(s): Karolina
Description: Function that takes a number as input and
ro... |
def is_point_on_border(
point_x, point_y,
margin_x=0, margin_y=0
):
"""Tell if a point is on the border of a rectangular area.
Arguments
+++++++++
:param int point_x: point's x coordinate
:param int point_y: point's y coordinate
Keyword arguments
+++++++++++++++++
:p... |
def _imf_salpeter(x):
"""
Compute a Salpeter IMF
Parameters
----------
x : numpy vector
masses
Returns
-------
imf : numpy vector
unformalized IMF
"""
return x ** (-2.35) |
def as_frozen(x):
"""Return an immutable representation for x."""
if isinstance(x, dict):
return tuple(sorted((k, as_frozen(v)) for k, v in x.items()))
elif isinstance(x, (list, tuple)):
return tuple(as_frozen(y) for y in x)
else:
return x |
def get_name_length(name):
"""
Returns the length of first name.
Parameters:
------
name: (str)
the input name
Returns:
-------
length of name: (float)
"""
if name == name:
return len(name)
else:
return 0 |
def fruit_into_baskets(fruits):
"""Find the maximum contiguous fruits that can be picked with two baskets.
Time: O(n)
Space: O(1)
>>> fruit_into_baskets(['A', 'B', 'C', 'A', 'C'])
3
>>> fruit_into_baskets(['A', 'B', 'C', 'B', 'B', 'C', 'A'])
5
"""
fruit_counts = {}
max_fruits... |
def getDecile(type):
"""
Return decile in either string or numeric form
"""
if type == 'numeric': return [0.05, 0.15, 0.25, 0.35, 0.45, 0.50, 0.55, 0.65, 0.75, 0.85, 0.95]
elif type == 'string': return ['5p','15p','25p','35p','45p','50p','55p','65p','75p','85p','95p']
else: raise ValueError |
def _NormalizedScript(script):
"""Translates $PYTHON_LIB in the given script. Returns the translation."""
if script:
return script.replace('$PYTHON_LIB/', '')
return script |
def clean_name(name: str) -> str:
"""Clean a name to a ticker
Parameters
----------
name : str
The value to be cleaned
Returns
----------
str
A cleaned value
"""
return name.replace("beta_", "").upper() |
def _safe(key, dic):
"""Safe call to a dictionary. Returns value or None if key or dictionary does not exist"""
if dic is not None and key in dic:
return dic[key]
else:
return None |
def byte_to_megabyte(byte):
"""
Convert byte value to megabyte
"""
return byte / (1024.0**2) |
def kewley_agn_oi(log_oi_ha):
"""Seyfert/LINER classification line for log([OI]/Ha)."""
return 1.18 * log_oi_ha + 1.30 |
def squeeze_whitespace(text):
"""Remove extra whitespace, newline and tab characters from text."""
return ' '.join(text.split()) |
def find_exml(val, attrib=False):
"""Test that the XML value exists, return value, else return None"""
if val is not None:
if attrib: # it's an XML attribute
return val
else: # it's an XML value
return val.text
else:
return None |
def lerp(a, b, t):
"""lerp = linear interpolation.
Returns a value between a and b, based on the value of t
When t=0, a is returned. When t=1, b is returned.
When t is between 0 and 1, a value mixed between a and b is returned.
For example, lerp(10,20,0.5) will return 15.
Note the result is not ... |
def filter_attributes(resource_type):
"""Returns a list of attributes for a given resource type.
:param str resource_type: type of resource whose list of attributes we want
to extract. Valid values are 'adminTask', 'task', 'adminVApp', 'vApp'
and 'adminCatalogItem', 'catalogItem'.
:return:... |
def _test_pgm(h):
"""PGM (portable graymap)"""
if len(h) >= 3 and \
h[0] == ord(b'P') and h[1] in b'25' and h[2] in b' \t\n\r':
return 'pgm' |
def is_counting_line_passed(point, counting_line, line_orientation):
"""
To check if the point passed the counting line by the x coord if it left/right or y coord if it bottom/top.
:param point: the object location.
:param counting_line: the coordinates list of the area.
:param line_orientation: the... |
def format_resource_id(resource_type, resource_id):
"""Format the resource id as $RESOURCE_TYPE/$RESOURCE_ID.
Args:
resource_type (str): The resource type.
resource_id (str): The resource id.
Returns:
str: The formatted resource id.
"""
return '%s/%s' % (resource_type, reso... |
def normalize_to_list(obj, lst):
"""Returns a matching member of a Player or Card list, if possible.
Assumes names of objects in the list are unique, for match by name.
Arguments:
obj -- a Player, Card, or a name (string) representing one
lst -- a list of Players or Cards
Returns:
... |
def rgb_to_hex(rgb):
"""Receives (r, g, b) tuple, checks if each rgb int is within RGB
boundaries (0, 255) and returns its converted hex, for example:
Silver: input tuple = (192,192,192) -> output hex str = #C0C0C0"""
hash_ = "#"
for i in rgb:
if i not in range(0, 256):
ra... |
def clog2(x):
"""Ceiling log 2 of x.
>>> clog2(0), clog2(1), clog2(2), clog2(3), clog2(4)
(0, 0, 1, 2, 2)
>>> clog2(5), clog2(6), clog2(7), clog2(8), clog2(9)
(3, 3, 3, 3, 4)
>>> clog2(1 << 31)
31
>>> clog2(1 << 63)
63
>>> clog2(1 << 11)
11
"""
x -= 1
i = 0
w... |
def solutionClosed(n: int, p: float) -> float:
"""
A closed-form solution to solutionRecursive's recurrence relation.
Derivation:
Let q = (-2p + 1).
h[0] = 1,
h[n] = q h[n-1] + p.
By iterating,
h[1] = q + p,
h[2] = q (q + p) + p = q^2 + pq + p,
h[3] = q (q^2 + pq + p) + p = q^3 + pq^2 + pq + p,
h[n] = ... |
def with_apostroves_if_necessary(str_in: str) -> str:
"""
Returns the same string, surrounded with apostrophes, only if it contains whitespaces.
"""
if str_in.find(' ') == -1:
return str_in
else:
return '"' + str_in + '"' |
def convert_dataset_name(store_name):
"""Parse {dataset}-{split} dataset name format."""
dataset, *split = store_name.rsplit('-')
if split:
split = split[0]
else:
split = None
return dataset, split |
def tuple_multiply(t, k):
"""
Multiplies the tuple `t` by the scalar `k`
Example
>>> t = (1, 2, 3)
>>> tuple_multiply(t, -1)
(-1, -2, -3)
"""
return tuple(k * t_i for t_i in t) |
def level_validation(user_level, all_data_info):
"""
Check if the level selected by the user exists in the database.
Returns the level number entered by the user, if it exists.
If the level entered doesn't exist, it returns an error message and exits the program.
Params:
1) user_level - Th... |
def symbols_db(db):
""" return dictionary like version of database"""
return db if type(db) is dict else {symbol.name: symbol for symbol in db} |
def _couple_exists(dict_, a, b):
"""Check if couple exists in a dict"""
if a in dict_:
if dict_[a] == b:
return True
if b in dict_:
if dict_[b] == a:
return True
return False |
def _convert_pandas_csv_options(pandas_options, columns):
""" Translate `pd.read_csv()` options into `pd.DataFrame()` especially for header.
Args:
pandas_options (dict):
pandas options like {'header': None}.
columns (list):
list of column name.
"""
_columns = pa... |
def get_t_demand_list(temp_curve, th_curve):
"""
Sorts thermal energy demand based on values of ambient temperatures.
Parameters
----------
temp_curve : list of ambient temperatures for one year
th_curve : list of thermal energy demand for one year
Returns
-------
t_demand_curve : ... |
def get_modules_for_includes(included_files, include_file_index):
""" given a set of included files return the set of modules that
contain these files, as well as the set of include files which
were not found in any module """
included_modules = set()
unknown_includes = set()
for include... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.