content stringlengths 42 6.51k |
|---|
def fix_bayes_factor(bayes_factor):
"""
If one of the bayes factors is 'inf' we get a string instead of a
tuple back. This is hacky but fixes that.
"""
# Maximum cut off for Bayes factor value
max_bf = 1e12
if type(bayes_factor) == str:
bayes_factor = bayes_factor.split(",")
... |
def get_vggish_poolings_from_features(n_mels=96, n_frames=1360):
"""
Get the pooling sizes for the standard VGG-based model for audio tagging.
Code from: https://github.com/keunwoochoi/transfer_learning_music/blob/master/models_transfer.py
Todo:
- This code is ugly, reorganise in a config file;... |
def deleteAnnotations(paths, storageIds):
"""Removes stored annotations from the sqlth_annotations table.
Requires the full tag path (including history provider) for each
annotation, as well as each annotation's storage ID. Storage ID
values can be retrieved with system.tag.queryAnnotations.
Args:... |
def convert_aux_to_base(new_aux: float, close: float):
"""converts the aux coin to the base coin
Parameters
----------
new_base, the last amount maintained by the backtest
close, the closing price of the coin
Returns
-------
float, amount of the last aux divided by the closin... |
def get_parent_child_from_xpath(name):
"""Returns the parent and child elements from XPath."""
if '/' in name:
(pname, label) = name.rsplit('/', 1)
else:
pname = None
label = name
return (pname, label) |
def replace_rating(x):
"""
Function to replace string ratings to int ratings.
"""
if "Elementary" in str(x):
return 0
elif "Intermediate" in str(x):
return 1
elif "Advanced" in str(x):
return 2
elif "B2" and "C1" in str(x):
return 1
elif "B1" and not ... |
def GetAdminKeyName(email):
"""Returns a str used to uniquely identify an administrator.
Args:
email: str user email.
Returns:
A str that can be used to uniquely identify a given administrator.
"""
return 'Admin_' + email.lower() |
def _auth_update(old_dict, new_dict):
"""Like dict.update, except handling the nested dict called auth."""
for (k, v) in new_dict.items():
if k == 'auth':
if k in old_dict:
old_dict[k].update(v)
else:
old_dict[k] = v.copy()
else:
... |
def get_filename(url: str) -> str:
"""Returns the filename from a link.
Args:
url (str): The url to a file location on the website.
Returns:
str: Only the filename.
"""
return url.split("/")[-1] |
def apply_rect_mask_to_layer(source, alpha):
""" Same as apply_mask_to_layer(), but for single pixels. Also always uses black background,
since it's for greyscale masks.
"""
dest = 0
# Handle the easy cases first:
if alpha == 0:
return dest
if alpha == 255:
return sourc... |
def find_longest_span(text_spans):
"""find the longest match
Args:
text_spans ([TextSpan]): the set of matches we are filtering
"""
if len(text_spans) == 0:
return None
return text_spans[0]
sorted_spans = sorted(text_spans, key=lambda s: len(s), reverse=True)
return sorted_... |
def _check_option(parameter, value, allowed_values, extra=''):
"""Check the value of a parameter against a list of valid options.
Return the value if it is valid, otherwise raise a ValueError with a
readable error message.
Parameters
----------
parameter : str
The name of the parameter... |
def make_matrix(num_rows, num_cols, entry_fn):
"""returns a num_rows x num_cols matrix
whose (i,j)-th entry is entry_fn(i, j)"""
return [[entry_fn(i, j) for j in range(num_cols)]
for i in range(num_rows)] |
def gatvc_to_gatcv(gatvc):
"""
Checks if the input contains 5 parts and if so, it swaps the last two.
:param gatvc: combination of groupId:artifactId:type:version:classifier where classifier is not mandatory
:return: combination of groupId:artifactId:type:classifier:version if classifier available, inp... |
def whitener(buf, coef):
"""Whiten and dewhiten data according to the given coefficient."""
data = bytearray(buf)
for i, byte in enumerate(data):
res, mask = (0, 1)
for _ in range(8):
if coef & 1:
coef ^= 0x88
byte ^= mask
mask <<= 1
... |
def Overlaps(j, k):
"""Inputs, j and k, are tuples/lists with a start and a end
coordinate as in: (start, end). If they overlap True is returned,
if they do not overlap, False is returned.
"""
j = sorted([int(i) for i in j])
k = sorted([int(i) for i in k])
jk = sorted([j,k], key=lambda x:x... |
def fill_names(vals, spws, default='spw'):
"""Create name base
"""
if len(vals)==0:
base = default
else:
base = vals[0]
return ['%s%s' % (base, spw[0]) for spw in spws] |
def no_start_menu_music(on=0):
"""Remove a Opcao "Minhas Musicas" do Menu Iniciar
DESCRIPTION
Esta restricao remove a opcao "Minhas Musicas" do menu iniciar.
COMPATIBILITY
Windows 2000/Me/XP
MODIFIED VALUES
NoStartMenuMyMusic : dword : 00000000 = Desabilitado;... |
def sanitize_doc_id(doc_id):
"""Not strictly required, but remove slashes from Elastic Search ids"""
return ':'.join(doc_id.split('/')) |
def _vec_scalar(vector, scalar):
"""Multiply a vector by an scalar."""
return [v * scalar for v in vector] |
def _strip(text):
"""Normalize expected strings to allow more readable definition."""
return text.lstrip('\n').rstrip(' ') |
def get_op_list(arch):
"""
code modified from project https://github.com/naszilla/naszilla
"""
# given a string, get the list of operations
tokens = arch.split('|')
ops = [t.split('~')[0] for i,t in enumerate(tokens) if i not in [0,2,5,9]]
return ops |
def custom404handler(err):
"""Custom handler for 404 errors."""
return dict(err=err) |
def get_pytest_marks_on_function(f):
"""
Utility to return *ALL* pytest marks (not only parametrization) applied on a function
:param f:
:return:
"""
try:
return f.pytestmark
except AttributeError:
try:
# old pytest < 3: marks are set as fields on the function ob... |
def factorial(input_number: int) -> int:
"""
Calculate the factorial of specified number
>>> factorial(1)
1
>>> factorial(6)
720
>>> factorial(0)
1
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: factorial() not defined for negative values
>>... |
def trim_padding(data, len):
"""
trim the start of the buffer until the first null, return everything after that
"""
if len is None:
# from RSA, find first null
return data[data.find(chr(0x00))+1:]
else:
# from RC5, follow length
return data[len:] |
def get_youtube_url(data: dict) -> str:
"""
Returns the YouTube's URL from the returned data by YoutubeDL, like
https://www.youtube.com/watch?v=dQw4w9WgXcQ
"""
return data['entries'][0]['webpage_url'] |
def get_box_coord(flare_x, flare_y, box_size):
"""
A function that takes a flare location and returns co-ordinates for a box around the flare
Param: flare_x,integer flare location x
flare_y, integer flare location y
box_size, length of the sides of the box
return: list of... |
def _get_new_user_identities_for_remove(exist_user_identity_dict, user_identity_list_to_remove):
"""
:param exist_user_identity_dict: A dict from user-assigned managed identity resource id to identity objecct.
:param user_identity_list_to_remove: None, an empty list or a list of string of user-assigned mana... |
def create_error_response(code, jrpc_id, message):
"""
Function to create error response
Parameters:
- code: error code enum which corresponds to error response
- jrpc_id: JRPC id of the error response
- message: error message which corresponds to error response
"""
error_res... |
def get_metric_name_from_task(task: str) -> str:
"""Get the name of the metric for the corresponding GLUE task.
If using `load_best_model_at_end=True` in TrainingArguments then you need
`metric_for_best_model=metric_name`. Use this method to get the metric_name
for the corresponding GLUE task.
"""
... |
def col(matlist, i):
"""
Returns the ith column of a matrix
Note: Currently very expensive
Examples
========
>>> from sympy.matrices.densetools import col
>>> from sympy import ZZ
>>> a = [
... [ZZ(3), ZZ(7), ZZ(4)],
... [ZZ(2), ZZ(4), ZZ(5)],
... [ZZ(6), ZZ(2), ZZ(3)]]
... |
def get_four_corners_from_2_corners(x1, y1, x2, y2):
"""
Function returns all corners of a bounding box given 2 corners
Args:
x1, y1, x3, y2 (int) - top left and bottom right corners of
box
returns
list containing all corners of box.
"""
return [x1, y1, x1, ... |
def coord(x_coordinate = 0, y_coordinate = 0):
"""function to form a coordinate string from x and y integers"""
return '(' + str(x_coordinate) + ',' + str(y_coordinate) + ')' |
def parse_user_prefix(prefix):
"""
Parses:
prefix = nickname [ [ "!" user ] "@" host ]
Returns:
triple (nick, user, host), user and host might be None
"""
user = None
host = None
nick = prefix
host_split = prefix.split('@', 1)
if len(host_split) == 2:
nick = h... |
def fahrenheit_to_celsius(fahrenheit: float) -> float:
"""
Convert a given value from Fahrenheit to Celsius and round it to 2 decimal places.
>>> fahrenheit_to_celsius(0)
-17.78
>>> fahrenheit_to_celsius(20.0)
-6.67
>>> fahrenheit_to_celsius(40.0)
4.44
>>> fahrenheit_to_celsius(60)
... |
def resolve_profile_alias(profile_name=None, region_name=None):
"""Wrapper around boto3.Session that behaves better with `~/.aws/config`
Will follow the source_profile of `profile_name` in `~/.aws/config` if found
and the only keys it has are `source_profile` and `region`. More complicated
configuratio... |
def get_keys(d, *keys):
"""Takes a dict and returns a new dict
where only given keys are present.
If there is no some key in original dict,
then it will be absent in the resulting dict too.
"""
return {key: value
for key, value in d.items()
if key in keys} |
def predict_pecies(sepal_width=None,
petal_length=None,
petal_width=None):
""" Predictor for species from model/52952081035d07727e01d836
Predictive model by BigML - Machine Learning Made Easy
"""
if (petal_width is None):
return u'Iris-virginica'
if... |
def countObjects(skel):
"""
Number of object required for exporting the specified skeleton.
"""
if skel:
nBones = skel.getBoneCount()
return (2*nBones + 1)
else:
return 0 |
def check_coordinating_cjc(sw, idx, edge, c_cjc, e_cjc, n_cjc):
"""
Check out coordinating conjunctions
"""
if c_cjc != []:
for cj in c_cjc:
if [e[-1] for e in edge if e[0] == cj] != [e[-1] for e in edge if e[0] == cj+1]:
return 0
if e_cjc != []:
for ej in... |
def find_first(predicate, iterable):
""" Return the first element in iterable that satisfies predicate or None """
try: return next(filter(predicate, iterable))
except StopIteration: return None |
def str2hex(number):
"""
Convert an hex based string number to int
:param string number: string hex number to convert
:return int: Integer value of the hex number
"""
return int(number, 16) |
def format_version(string):
"""Format version input from 1.1 to 01.01.00"""
version = [i.zfill(2) for i in string.split(".")] + ["00", "00"]
return ".".join(version[:3]) |
def subtraction(x, y):
"""
Subtraction x and y
>>> subtraction(10, 5)
5
>>> subtraction('10', 5)
Traceback (most recent call last):
...
AssertionError: x needs to be an integer or float
"""
assert isinstance(x, (int, float)), 'x needs to be an integer or float'
assert isinst... |
def ifexpr(fpredicate, ftrue, ffalse, arg):
"""Functional if expression.
Args:
fpredicate: true/false function on arg
ftrue: run if fpredicate is true with arg
ffalse: run if fpredicate is false with arg
arg: the arg to run on the functions
Returns:
the result of either ftrue... |
def hello(name=None):
"""Assuming that name is a String and it checks for user typos to return a name with a first capital letter (Xxxx).
Args:
name (str): A persons name.
Returns:
str: "Hello, Name!" to a given name, or says Hello, World! if name is not given (or passed as an empty String... |
def contains(text, pattern):
"""Return a boolean indicating whether pattern occurs in text.
Runtime, worst case: O(n^2), n is the len(text)
Runtime, best case: O(1), if text == ''
Space Complexity: O(n), n is the len(text)
"""
assert isinstance(text, str), 'text is not a string: {}'.format(text)... |
def ddvv(xyz1, xyz2):
"""Distance squared between two vectors."""
dx=xyz1[0]-xyz2[0]
dy=xyz1[1]-xyz2[1]
dz=xyz1[2]-xyz2[2]
return dx*dx+dy*dy+dz*dz |
def get_matching_connections(cxs_1, cxs_2):
"""returns connections in cxs_1 that share an innovation number with a connection in cxs_2
and connections in cxs_2 that share an innovation number with a connection in cxs_1"""
return sorted([c1 for c1 in cxs_1 if c1.innovation in [c2.innovation for c2 in ... |
def concat_relations(relations, offsets):
"""combine relation dictionaries from multiple datasets
Args:
relations (list): list of relation dict to combine
offsets (list): offset to add to the indices
Returns: new_relations (dict): dictionary of combined relations
"""
new_relations... |
def getJ1939ProtocolString(protocol = 1, Baud = "Auto", Channel = -1,
SampleLocation = 95, SJW = 1,
PROP_SEG = 1, PHASE_SEG1 = 2, PHASE_SEG2 = 1,
TSEG1 = 2, TSEG2 = 1, SampleTimes = 1) -> bytes:
"""
Generates fpchProtocol string for ClientC... |
def add_metric_suffix(num: int):
"""
Adds the classic (b, m, k) suffixes to the end of a number
:param num: The number to add the suffix to
"""
# Billion
if num >= 1000000000:
x = num / 1000000000
return '{:,}b'.format(int(x) if 1 % x == 0 else round(x, 1))
# Million
i... |
def all_tasks(loop=None):
"""Return a set of all tasks for the loop."""
# We could do this, but we will not.
return {} |
def is_integer(string):
"""Checks if the string is an integer
Args:
string (str): The string to check
Returns:
Boolean: Whether the string could be converted to an integer or not
"""
try:
int(string)
return True
except ValueError:
return False |
def upstream_authority(authority_and_code):
"""
Authority of the upstream API used to the validation of the requests from APIcast
"""
authority, _ = authority_and_code
return authority |
def expand_sided_value(value):
"""Returns 4-tuple with values corresponding
to top, right, bottom, and left.
Possible inputs:
style /* One-value syntax */ E.g. 1em;
vertical horizontal /* Two-value syntax */ E.g. 5% auto;
top horizontal bottom /* Three-value syntax */ E.g. 1... |
def no_op(event, context):
"""Don't do anything.
Args:
event (dict): Event data passed to handler
context (object): Runtime information
"""
# Just return a success code.
return True |
def binarySearch(match_item, itemList):
"""
match_item and itemList's data should always be on their normalized form
"""
left = 0
right = len(itemList) - 1
while left <= right:
mid = left + (right - left) // 2
if itemList[mid] == match_item:
return mid
... |
def leap_year(y):
"""
@purpose Returns whether the year is leap year or not
@param y: the year to test for leap year
@complexity:
Best Case: O(2): When user input a year before 1582
Worst Case: O(7): When user enter a year after 1582
@precondition Passing ... |
def read_kfold_config(split: dict):
""" KFold values reader
This function ensures that the parameters of the KFold splitting method are defined.
:param dict split: A dictionary that contains the parameters about the KFold splitting method.
:return:
- n_fold - An integer that refers to the... |
def indent_new_lines(text: str, num: int = 4):
"""Inserts spaces at the beginning of each new line"""
return text.replace("\n", "\n" + (" " * num)) |
def mapvalue(value, leftMin, leftMax, rightMin=0.0, rightMax=1.0):
"""
map a value between two ranges
"""
# Figure out how 'wide' each range is
leftSpan = leftMax - leftMin
rightSpan = rightMax - rightMin
# Convert the left range into a 0-1 range (float)
valueScaled = float(value... |
def robustmin(data):
"""Like min() but handles empty Lists."""
if data:
return min(data)
return None |
def build_image_name(config, os_type, os_version):
"""build_image_name
Returns a standard docker image name based upon package parameters
"""
name = "%s%s-%s-builder" % (os_type, os_version, config['project'])
return name |
def create_ogblob(ogheader):
"""create <meta> tags from Open Graph dict
if ogheader is empty dict, then return empty string.
if ogheader has some values but not the minimum, then raise ValueError.
if og:image is a path, not a URL of http or https scheme, then
'https://help.rerobots.net/' is prepen... |
def suffix_eq(text, pos, expected):
"""Check if the suffix of text starting at pos equals expected.
This is effectively equivalent to ``text[pos:] == expected``, but avoids
allocating a huge substring.
If ``pos`` is 0, this is equal to ``text == expected``.
:param str text: Text to compare.
:... |
def rangify(number_list):
"""Assumes the list is sorted."""
if not number_list:
return number_list
ranges = []
range_start = prev_num = number_list[0]
for num in number_list[1:]:
if num != (prev_num + 1):
ranges.append((range_start, prev_num))
range_start = ... |
def RPL_VERSION(sender, receipient, message):
""" Reply Code 351 """
return "<" + sender + ">: " + message |
def config_dict_to_object(config_dict):
"""Recursively converts a dictionary to an object
Args:
config_dict: config dictionary to convert
Returns:
ConfigObj configuration object
"""
def convert(item):
if isinstance(item, dict):
return type('ConfigObj', (), {k: ... |
def merge_dicts(x, y):
"""
Merges the entries specified by two dicts.
"""
z = x.copy()
z.update(y)
return z |
def trim_word_space(words, possible_letters, known_letters):
"""
Trim the word space by removing words that don't have the letters we know
"""
valid_words = words.copy()
for word in words:
for i in range(len(word)):
if word[i] not in possible_letters[i]:
valid_wor... |
def safe_xml_tag_name(
name: str, numeric_prefix: str = "tag-", empty_fallback: str = "empty-tag"
) -> str:
"""
Returns a safe xml tag name by replacing invalid characters with a dash.
:param name: The name that must be converted to a safe xml tag name.
:param numeric_prefix: An xml tag name can't ... |
def line_text(*fields, **kargs):
"""
Transform a list of values into a tsv line
:param fields: list of values as parameters
:param kargs: optional arguments: null_value: value to interpret as None
:return: tsv line text
"""
null_value = kargs.get("null_value", "")
return "\t".join([str(x) if x is not None else ... |
def bytelist2string(bytelist):
""" Convert a list of byte values (e.g. [0x10 0x20 0x00]) to a string
(e.g. '\x10\x20\x00').
"""
return ''.join(chr(b) for b in bytelist) |
def pad_block(block: bytes, block_size: int) -> bytes:
"""
Pads a plaintext block of bytes to the desired block size using PKCS#7 padding
:param block:
:param block_size:
:return: The original block padded using PKCS#7 padding. If the block is already greater than or equal to the
des... |
def _get_nodes(x, prefix=""):
"""
Args:
x: a tree where internal nodes are dictionaries, and leaves are lists.
prefix: not meant to be passed. The parent prefix of a label. e.g. given A -> B -> C,
the parent prefix of C is 'A [sep] B'.
sep: the separator to use between labels... |
def _diff_properties(expected, current):
"""Calculate the difference between the current and the expected
properties
* 'expected' is expressed in a dictionary like: {'property': value}
* 'current' contains the same format retuned by 'btrfs.properties'
If the property is not available, will throw ... |
def get_next_xp(level: int) -> int:
"""Returns the xp need to level up"""
return (level + 1) ** 3 |
def make_meters_map(meters, meter):
"""Add meter to meters by its ID."""
meters[str(meter["id"])] = meter
del meter["id"]
return meters |
def get_rounds(number):
"""
:param number: int - current round number.
:return: list - current round and the two that follow.
"""
return [number, number + 1, number + 2] |
def compile_word(word):
"""Compile a word of uppercase letters as numeric digits.
E.g., compile_word('YOU') => '(1*U+10*O+100*Y)'
Non-uppercase words unchanged: compile_word('+') => '+'"""
if word.isupper():
terms = [('%s*%s' % (10**i, d))
for (i, d) in enumerate(word[::-1])]
... |
def target_path(log_file):
"""Return a target location for an RDS log file.
Given an RDS log file name ('error/postgresql.log.2020-03-03-21'),
return a 2-tuple ('error/<date>/', 'postgresql.log.2020-03-03-21')
representing the target path and filename to save the file.
"""
date = log_file.rsp... |
def flatten(x: float, y: float, z: float, scale: int, distance: int) -> tuple:
"""
Converts 3d point to a 2d drawable point
```python
>>> flatten(1, 2, 3, 10, 10)
(7.6923076923076925, 15.384615384615385)
```
"""
projected_x = ((x * distance) / (z + distance)) * scale
projected_y = (... |
def _split_n_in_m_parts(n, m):
""" Split integer n in m integers which sum up to n again, even if m * (n//m) != n.
"""
a = [n // m] * m
a[0] = n - (m - 1) * a[0]
return a |
def leapYear(year: int = 2020)-> None:
"""
This function tests and `prints` whether a given year is a `Leap year` or not. Returns `None` if bound to a variable.
Args: This function takes exactly one argument.
`year: int` : The literal of this argument should be of `integer (int)` data type.
"""
... |
def check_lead_zero(to_check):
"""Check if a number has a leading 0.
Args:
to_check (str): The number to be checked.
Returns:
True if a leading 0 is found or the string is empty, False otherwise.
"""
if str(to_check) in (None, ''):
return True
elif str(to_check[0]) != '... |
def detect_clause(parser, clause_name, tokens):
"""Helper function detects a certain clause in tag tokens list.
Returns its value.
"""
if clause_name in tokens:
t_index = tokens.index(clause_name)
clause_value = parser.compile_filter(tokens[t_index + 1])
del tokens[t_index:t_ind... |
def browse(i):
"""
Input: {
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
# TBD: should calculate url
url='https://github.com... |
def normalize_id(id):
"""Normalize any ids used in the IOC to make the compatible with CybOX
This is just in case the normal UUID type is not used.
"""
if id is None:
return None
return id.replace(":", "-") |
def is_group_in_sorted(s: str) -> bool:
"""Assuming s is sorted, is there a repeated character?"""
return any(x >= 2 for x in map(s.count, s)) |
def get_submit_attr_str(submit_attrs):
"""Convert submit attributes from a dictionary form to the corresponding configuration string
Args:
submit_attrs (dict): the dictionary containing the submit attributes
Returns:
string: the string representing the xml submit attributes section for a s... |
def invert_dict(dic):
"""
"""
return {dic[k]:k for k in dic} |
def remove_unspecified_unicode(value):
"""In a very small number of cases, NiH has some pre-processed badly
formatted unspecifed unicode characters. The following recipe seems to
clean up all of the discovered cases."""
# These are all spaces
for char in ('\xa0\xa0', '\xa0 ', '\xa0'):
value ... |
def find_option(block, key, type, default, loud=False, layer_name=None, layer_idx=-1):
"""
----------
Author: Damon Gwinn (gwinndr)
----------
- Finds the option specified by key and sets the value according to type
- If option not found, uses default
- If default is used and loud is True, p... |
def detectLoop(head):
"""
Take two pointers one that moves one step, the other moves two steps
if at any point both meet its a loop
Imagine it in a form of circle, where the first pointer completes half the
second has completed one full cycle. Again when the first completes
one half the other co... |
def git_config_bool (value):
"""Convert the given git config string value to True or False.
Raise ValueError if the given string was not recognized as a
boolean value.
"""
norm_value = str(value).strip().lower()
if norm_value in ("true", "1", "yes", "on", ""):
return True
if norm_v... |
def lim_eps(a, eps):
#==================================================================
"""
Return min / max of an array a, increased by eps*(max(a) - min(a)).
Handy for nice looking axes labeling.
"""
mylim = (min(a) - (max(a)-min(a))*eps, max(a) + (max(a)-min(a))*eps)
return mylim |
def generate_job_name(
endpoint_name: str, perturb_prefix: str, dataset_name: str, timestamp: int
):
"""Generate the job name with a given timestamp.
The timestamp need to be properly spaced out, because they need to be unique
across all jobs in the same AWS region.
This is taken care of by `_set_j... |
def is_manual_format_params(format_params):
"""Says if the format_params is from a manual specification
See Also: is_automatic_format_params
"""
assert not isinstance(
format_params, str
), "format_params can't be a string (perhaps you meant is_manual_format_string?)"
return all((x is no... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.