content stringlengths 42 6.51k |
|---|
def remove_symbol(text, symbol):
"""
Method to remove given symbol in the text. All the symbol occurrences will be replaced by "".
parameters
-----------
:param text: str
:param symbol: str
Symbol which need to be removed (e.g., '#')
:return: str
Symbol removed text
"""
... |
def _tablify_result(data):
"""Convert the JSON dict structure to a regular list."""
if isinstance(data, dict):
keys = [i for i in list(data.keys()) if i != "_meta"]
if len(keys) == 1:
data = data[keys[0]]
if not isinstance(data, list):
data = [data]
return data |
def rgb2hex(rgbcolor):
"""Convert a tuple of (r, g, b) to the hex equivilent."""
return '#%02x%02x%02x' % rgbcolor |
def pad_to_5_str(num):
"""
Converts an int to a string, and pads to 5 chars (1 -> '00001')
:param num: int to be padded
:return: padded string
"""
return '{:=05d}'.format(num) |
def _check_len(x):
""" Utility function to get the length of the tensor """
if hasattr(x, 'shape'):
return x.shape[0]
else:
return len(x) |
def weighting(distance):
"""Weighting function for pyresample."""
weight = 1 / distance**2
return weight |
def need_to_remove_last_ckpt(last_epoch: int, ckpt_save_strategy: int or list or tuple) -> bool:
"""Judging whether to remove last checkpoint by `ckpt_save_strategy`
`ckpt_save_strategy` should be None, an int value, a list or a tuple
if `ckpt_save_strategy` is None, remove last checkpoint file every epoch... |
def r_shift(a, RShft_n):
""" Bitwise Right Shift """
b_rightshiftedVal = bin(int(a)>>RShft_n)[2:].zfill(32)
return b_rightshiftedVal |
def bound_precision(tp, fp, e):
"""Bound precision, given numbers of TP, FP, and validation errors.
This is a non-obvious theorem in the benchmarking paper.
"""
p = tp + fp
if not p or e > p:
return 0, 0
return (tp - e) / p, (tp + e) / p |
def NAMED(n, e):
"""
Puts the expression in a named-group
:param:
- `n`: the name of the group
- `e`: regular expression
:return: named-group
"""
return "(?P<{n}>{e})".format(n=n, e=e) |
def flip_nested_dict(nested_dict):
"""Flip nested dictionary inside out."""
flipped = dict()
for key, subdict in nested_dict.items():
for k, v in subdict.items():
flipped[k] = flipped.get(k, dict())
flipped[k][key] = v
return flipped |
def _shard_kwargs(shard_idx: int, kwargs: dict) -> dict:
"""Return a copy of the input kwargs but with only one shard"""
# Having lists of different sizes makes sharding ambigious, raise an error in this case
# until we decide how to define sharding without ambiguity for users
lists_lengths = {key: len(... |
def get_range( value ):
"""
Filter - returns a list containing range made from given value
Usage (in template):
<ul>{% for i in 3|get_range %}
<li>{{ i }}. Do something</li>
{% endfor %}</ul>
Results with the HTML:
<ul>
<li>0. Do something</li>
<li>1. Do... |
def mat_mul(mat1, mat2):
"""Matrix multiplication"""
rowLen1 = len(mat1)
colLen1 = len(mat1[0])
rowLen2 = len(mat2)
colLen2 = len(mat2[0])
if colLen1 != rowLen2:
return None
ans = [[0] * colLen2 for i in range(rowLen1)]
for i in range(rowLen1):
for j in range(colLen2)... |
def check_if_audio(filename):
"""
check_if_audio - checks if a file is an audio file
Parameters
----------
filename : str, the name of the file to be checked
Returns
-------
bool
"""
return (
filename.endswith(".wav")
or filename.endswith(".mp3")
or file... |
def contrast(color):
"""Compute luminous efficiency of given color and return either
white or black based on which would contrast more.
"""
# I know this is not exact; just my guess
R = eval('0x'+color[1:3])
G = eval('0x'+color[3:5])
B = eval('0x'+color[5:7])
lumen = 0.6*R + G + 0.3*B
... |
def __k_chk(k):
"""
Ensures a kelvin value is not below absolute zero. If it is
not, we raise a ValueError instead. If it is valid, we return it.
"""
if k < 0:
if k % 1 == 0:
k = int(k)
raise ValueError(f'{k}K is below absolute zero, and is invalid.')
return k |
def flatten(l):
"""
Flattens a hierarchy of nested lists into a single list containing all elements in order
:param l: list of arbitrary types and lists
:returns: list of arbitrary types
"""
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], list):
if not l[i... |
def get_next_job(job_dict, jobs_done, jobs_in_progress):
"""Get the next job from job_dict whose dependencies are met"""
for char, dependencies in sorted(job_dict.items()):
if char in jobs_done | jobs_in_progress:
continue
if set(dependencies).issubset(set(jobs_done)):
re... |
def translateLine(line, dict):
"""Translates and returns a given line of text."""
text = ""
lastChar = ""
lineStart = True
translated = False
for char in line:
# Use the matching value in the dictionary, otherwise output the existing character
try:
value = dict[char]
... |
def avoid_zero(denominator, precision=8):
"""
Avoids division by zero by scaling the denominator, aka "alpha scale".
Keyword arguments:
denominator -- the denominator to be scaled
precision -- (defaults to 8), the amount of scaling that is performed
Return value:
denominator * precision + ... |
def min2(a, b):
"""
Wrapper around the min build-in that is robust to None.
"""
if a and not b:
return a
elif b and not a:
return b
else:
return min(a, b) |
def hexagonal_n(n):
"""Returns the nth hexagonal number"""
return int(n * (2 * n - 1)) |
def dec2hp(dec):
"""
Converts Decimal Degrees to HP Notation (float)
:param dec: Decimal Degrees
:type dec: float
:return: HP Notation (DDD.MMSSSS)
:rtype: float
"""
minute, second = divmod(abs(dec) * 3600, 60)
degree, minute = divmod(minute, 60)
hp = degree + (minute / 100) + (s... |
def pad_list(l, size, value=0):
"""Pads the right side of the list `l` to `size` if len(l) is less than size with `value`."""
if len(l) >= size:
return l
return l + ([value] * (size - len(l))) |
def number_of_1(n):
"""
:param n: max number
:return: times that digit 1 appear
"""
count = 0
for i in range(1, n+1):
count += str(i).count('1')
return count |
def compact(source, keep_if=lambda k, v: v is not None):
"""
Takes a dictionary and returns a copy with elements matching a given lambda removed. The
default behavior will remove any values that are `None`.
Args:
source (dict): The dictionary to operate on.
keep_if (lambda(k,v), option... |
def calculate_step_or_functional_element_assignment(child_assignments: list, sufficient_scheme=False):
"""
Assigns a step result or functional element result based of the assignments of its children. In the case of steps,
this would be functional element assignments. In the case of functional elements this ... |
def _jwt_decode_handler_with_defaults(token): # pylint: disable=unused-argument
"""
Accepts anything as a token and returns a fake JWT payload with defaults.
"""
return {
'scopes': ['fake:scope'],
'is_restricted': True,
'filters': ['fake:filter'],
} |
def origin_identifier(msg):
"""
Extract the message identifier of a callback query's origin. Returned value
is guaranteed to be a tuple.
``msg`` is expected to be ``callback_query``.
"""
if 'message' in msg:
return msg['message']['chat']['id'], msg['message']['message_id']
if 'inlin... |
def addPt(ptA, ptB):
"""Add two vectors"""
return ptA[0] + ptB[0], ptA[1] + ptB[1] |
def is_factor_term(obj):
""" Is obj a FactorTerm?
"""
return hasattr(obj, "_factor_term_flag") |
def url_stix_pattern_producer(data):
"""Convert a URL from TC to a STIX pattern."""
return f"[url:value = '{data.get('summary')}']" |
def is_even(x):
"""
Return whether or not an integer ``x`` is even, e.g., divisible by 2.
EXAMPLES::
sage: is_even(-1)
False
sage: is_even(4)
True
sage: is_even(-2)
True
"""
try:
return x.is_even()
except AttributeError:
return x ... |
def class_name_from_object(obj):
"""
Helper to quickly retrieve a class name from an object.
"""
return obj.__class__.__name__ |
def secondsToHMS(intervalInSeconds):
"""converts time in seconds to a string representing time in hours, minutes, and seconds
:param intervalInSeconds: a time measured in seconds
:returns: time in HH:MM:SS format
"""
interval = [0, 0, intervalInSeconds]
interval[0] = (inter... |
def bin_range_strings(bins, fmt=':g'):
"""Given a list of bins, make a list of strings of those bin ranges
Parameters
----------
bins : list_like
List of anything, usually values of bin edges
Returns
-------
bin_ranges : list
List of bin ranges
>>> bin_range_strings((0... |
def consumer_1st_n(x, resource):
"""
:type x: list(float)
:type resource: float
:rtype: float
"""
return resource - (x[0] + x[1]) |
def Fix_01(val):
"""
Convert a 0.1 value to a value of 1. It was a mistake in this generation of DYD data.
Inputs:
-------
val -> float
Outputs:
--------
-> converted value
"""
if val == 0.1:
return 1
else:
return val |
def sanitize_data_model_dict(flat_dict):
"""Given data model keyword dict `d`, sanitize the keys and values to
strings, upper case the keys, and add fake keys for FITS keywords.
"""
flat_dict = dict(flat_dict)
# Reformat history paths so they sort correctly by using 0-filled sequence number.
... |
def index_config(config, path, index_structure=True):
"""Index a configuration with a path-like string."""
key = None
sections = path.split("/")
if not index_structure:
key = sections[-1]
sections = sections[:-1]
for section in sections:
if isinstance(config, dict):
... |
def get_features(words, word_features):
"""
Given a string with a word_features as universe,
it will return their respective features
: param words: String to generate the features to
: param word_features: Universe of words
: return: Dictionary with the features for document string
"""
... |
def _dirname(path_str):
"""Returns the path of the direcotry from a unix path.
Args:
path_str (str): A string representing a unix path
Returns:
str: The parsed directory name of the provided path
"""
return "/".join(path_str.split("/")[:-1]) |
def classname(obj):
"""Returns the name of an objects class"""
return obj.__class__.__name__ |
def add_parameters_to_doc(doc, doc_params):
"""
Inserts doc_params in the first empty line after Parameters if possible.
"""
if not doc:
return doc
doc = doc.split("\n")
found = False
for i, line in enumerate(doc):
words = line.split()
if not found and len(words) == ... |
def compute_eer(target_scores, nontarget_scores):
"""Calculate EER following the same way as in Kaldi.
Args:
target_scores (array-like): sequence of scores where the
label is the target class
nontarget_scores (array-like): sequence of scores where the
... |
def str2bool(x):
"""Convert a string to a boolean.
Args:
x (str)
Returns:
bool: True if `x.lower()` is 'y', 'yes', '1', 't', or 'true'; False if `x.lower()` is 'n', 'no', '0', 'f', or 'false'.
Raises:
ValueError: If `x.lower()` is not any of the values above.
"""
if x... |
def _prune(values, last_n=0, skip_first_n=0, skip_last_n=0):
"""inline function to select first or last items of input list
:param values: input list to select from
:param int last_n: select last 'n' items of values. default is 0.
:param int skip_first_n: skip first n items of values. default is 0. las... |
def left_justify_cells_in_rows(rows):
"""Pad each cell on the right till each column lines up vertically"""
# Convert each cell to string
strung_rows = list(list(str(cell) for cell in row) for row in rows)
# Add empty cells till every row is as wide as the widest row
# completed_rows = complete_... |
def check_not_finished_board(board: list):
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', '*?????*', '*?????*', '*2*1***'])
False
>>> check_n... |
def _minBandwidthAvailable(a,b):
"""
Helper Function: Prints lowest of two bandwidth amounts
Author:
David J. Stern
Date:
DEC 2017
Parameters:
a: (int): number
b: (int): number
Returns:
(int) lowest of two numbers compared.
"""
return sorted([a,b])[0... |
def rotate_letter(letter, n):
"""Rotates a letter by n places. Does not change other chars.
letter: single-letter string
n: int
Returns: single-letter string
"""
if letter.isupper():
start = ord('A')
elif letter.islower():
start = ord('a')
else:
return letter
... |
def nrzi(data, cycles=4, init="J"):
"""Converts string of 0s and 1s into NRZI encoded string.
>>> nrzi("11 00000001", 1)
'JJ KJKJKJKK'
It will do bit stuffing.
>>> nrzi("1111111111", 1)
'JJJJJJKKKKK'
Support single ended zero
>>> nrzi("1111111__", 1)
'JJJJJJKK__'
Support pre-... |
def _do_cmp_op(func, exprs):
"""Do comparable operation."""
for i in range(len(exprs)-1):
if not func(exprs[i], exprs[i+1]):
return False
return True |
def steady_state_replacement(random, population, parents, offspring, args):
"""Performs steady-state replacement for the offspring.
This function performs steady-state replacement, which means that
the offspring replace the least fit individuals in the existing
population, even if those offspring a... |
def get_entry_enclosures(entry):
"""
Returns a list of either media_content or enclosures for the entry.
The enclosures (or media_content) are only returned if they are non-empty
and contain a non-empty first item.
"""
media_content = entry.get('media_content')
if media_content and media_c... |
def autoname(ind):
"""Automatically turn an index into a system name."""
# sequence A-Z, AA-AZ-ZZ, AAA-AAZ-AZZ-ZZZ ...
chars = []
while True:
chars.append(chr(65 + ind % 26))
if ind < 26:
break
ind = ind // 26 - 1
return "System " + "".join(chars[::-1]) |
def get_num(string_with_number):
"""
get numbers in a string
:param string_with_number:
:return:
"""
try:
return int(''.join(ele for ele in string_with_number if ele.isdigit())) # get digits
except ValueError: # if no digits in the string, just assign -1
return -... |
def _get_single_dict(nova, neutron, cinder):
"""Create a single dictionary of quota values"""
if type(nova) is not dict:
nova = nova.to_dict()
if type(cinder) is not dict:
cinder = cinder.to_dict()
single_dict = nova
single_dict.update(neutron)
single_dict.update(cinder)
... |
def shift_right(value, shift_value):
"""Shift right that allows for negative values, which shift left
(Python shift operator doesn't allow negative shift values)"""
if shift_value == None:
return 0
if shift_value < 0:
return value << (-shift_value)
else:
return value >> shift... |
def optimized_binary_search(tab, logsize):
"""Binary search in a table using bit operations
:param tab: boolean monotone table
of size :math:`2^\\textrm{logsize}`
with tab[hi] = True
:param int logsize:
:returns: first i such that tab[i]
:complexity: O(logsize)
"""
hi = (1 << ... |
def get_risk_characterization(combined_risk_assessment):
"""
Compute the risk characterization for the combined risk assessment. See table 12
:param combined_risk_assessment: combined risk assessment of the attack goal at the scenario with the selected impact
:return: risk characterization for the combi... |
def header(mesg):
"""Return a simple header string for given message."""
return '\n' + mesg + '\n' + '=' * len(mesg) |
def get_pi_index(pi_set):
"""
Parameters
----------
pi_set Pi set in Simple Buckingham format
Returns The index of the next pi number to ba added to the set
-------
"""
if pi_set is not None:
return len(pi_set.splitlines()) + 1
else:
return 1 |
def ccw(ax, ay, bx, by, cx, cy):
"""
If the slope of the line AB is less than the slope of the line AC then the three points are listed in a
counterclockwise order. This method expects x/y components of each point to come separately
Source: https://bryceboe.com/2006/10/23/line-segment-intersection-algor... |
def is_int(s):
"""
Check value is integer using cast
params: string value
return: boolean
"""
try:
int(s)
return True
except ValueError:
return False |
def add_overview_buttons(campaign_data, submission):
"""Returns list of submission specific buttons (Submit, Edit, Quit).
If not submission, then different list of buttons are
returned (Edit (not same as submit), Back)
Args:
campaign_data:
CampaignData used to populate button values
... |
def um_in(input):
"""
convert micrometers to inches
"""
return 1 / 25400 * input |
def first_non_repeated(s: str):
"""
You need to write a function, that returns the
first non-repeated character in the given string.
For example for string "test" function should return 'e'.
For string "teeter" function should return 'r'.
If a string contains all unique characters, then return... |
def colors_in_list(color_list):
"""
Return a list of colors
"""
return [x["color"] for x in color_list] |
def _score_str(val):
"""Returns + sign for positive values (used in plots)"""
return ("" if "-" in val else "+") + str(val) |
def collapse_json(text, indent=4):
"""Compacts a string of json data by collapsing whitespace after the
specified indent level
NOTE: will not produce correct results when indent level is not a multiple
of the json indent level
"""
initial = " " * indent
out = [] # final json output
sub... |
def hsl_time_to_time(hsltime):
"""
Converts HSL API timestamp to hh:dd format
:param hsltime: HSL API timestamp (hour maybe bigger than 24!)
:return: timestamp in hh:dd format
"""
return "%02d.%02d" % (hsltime / 100 % 24, hsltime % 100) |
def link_keys():
"""Link definition"""
return ["type", "id", "url"] |
def make_me_happier(sentence):
"""
This function takes a sentence and returns a version of the sentence
with the word "happy" replaced with the word "sad".
"""
return sentence.replace("happy", "sad") |
def mel2hz(mel):
"""Convert a value in Mels to Hertz
:param mel: a value in Mels. This can also be a numpy array, conversion proceeds element-wise.
:returns: a value in Hertz. If an array was passed in, an identical sized array is returned.
"""
return 700 * (10 ** (mel / 2595.0) - 1) |
def _known_populations(row, pops):
"""Find variants present in substantial frequency in population databases.
"""
cutoff = 0.01
out = set([])
for pop, base in [("esp", "aaf_esp"), ("1000g", "aaf_1kg"),
("exac", "aaf_adj_exac")]:
for key in [x for x in pops if x.startswi... |
def check_min_req_GSvar(row):
"""
checking the presence of mandatory columns
:param row: dictionary of a GSvar row
:return: boolean, True if min req met
"""
if ("#chr" in row.keys() and "start" in row.keys() and "end" in row.keys() and "ref" in row.keys() and "obs" in row.keys() and ("coding_and... |
def map_names(str):
"""Map a FreeBSD name to OE"""
maps = {
"libpurple" : "pidgin",
"php4" : "php",
"php5" : "php",
"expat2" : "expat",
"freeciv-gtk" : "freeciv",
"pcre" : "libpcre",
"vim-gnome" : "vim",
"python23" : "python",
"python24" : ... |
def utc_offset_to_str(utc_offset: int) -> str:
"""Convert a UTC offset to a readable string.
:param utc_offset: The UTC offset in seconds.
"""
sign = "-" if utc_offset < 0 else "+"
hours = abs(utc_offset) // (60 * 60)
minutes = (abs(utc_offset) % (60 * 60)) // 60
return f"UTC{sign}{... |
def convert_words_to_index(words, dictionary):
""" Replace each word in the dataset with its index in the dictionary """
return [dictionary[word] if word in dictionary else 0 for word in words] |
def _test_data(**overrides):
"""Returns a valid set of test data to use during API integration tests
overrides allows the caller to replace one or more items in the returned
dictionary without having to specify the entire thing every time.
"""
test_data = {
'sender': 'someemail@somedomain.c... |
def find_missing_functions(keywords, text):
"""
%timeit find_missing_funcs(funcs, text)
1 loops, best of 3: 973 ms per loop
"""
found = set()
for line in text.splitlines():
if not line.strip().startswith('def '):
for f in keywords:
if f in line:
... |
def check_order_triggers(
current_price, is_debit, is_long, stop_price=None, limit_price=None
):
"""Given current market value of position, returns order triggers
Parameters
----------
current_price : float
The current value of the position, this can be negative if credit position
is_lo... |
def get_first_list_prop(lst):
"""
Returns the first element in the list that starts with list_, -1 if not found.
Arguments:
lst {list}
"""
for i, e in enumerate(lst):
if e.startswith("list_"):
return i
return -1 |
def bpm_process_control(_destination, _destination_process_id, _command, _reason, _message_id, _source,
_source_process_id, _user_id):
"""
Created a BPM process control message, user to tell a process to stop, kill, etcetera.
"""
return {
"destination": _destination,
... |
def stay_within_heading(params):
"""
Example of using waypoints and heading to make the car in the right direction
"""
import math
# Read input variables
waypoints = params['waypoints']
closest_waypoints = params['closest_waypoints']
heading = params['heading']
# Initialize the re... |
def _ucfirst(string):
"""Implementation of ucfirst and \ u in interpolated strings: uppercase the first char of the given string"""
return string[0:1].upper() + string[1:] |
def euclidian_distance(a, b):
"""
Calculating Euclidian distance between 2 vectors
:param a: 1st vector
:param b: 2nd vector
:return:
"""
assert len(a) == len(b)
d = 0
for feature in range(len(a)):
d += (a[feature] - b[feature]) ** 2
return d ** 0.5 |
def mkdir(name, children=[], meta={}):
"""Return directory node."""
return {
'name': name,
'children': children,
'meta': meta,
'type': 'directory'
} |
def ReverseComplement(barcode):
"""
barcode: (str) just "A""C""T""G"
We return reverse complement: ACCAGT -> ACTGGT
"""
revc_bc = ""
barcode = barcode.upper()
transl_d = {"A":"T","C":"G","T":"A","G":"C"}
for char in barcode:
if char not in ["A","C","T","G"]:
raise Exc... |
def _StripApiName(api_name):
"""Strips Dev, Private, and Trusted suffixes from the API name."""
if api_name.endswith('Trusted'):
api_name = api_name[:-len('Trusted')]
if api_name.endswith('_Dev'):
api_name = api_name[:-len('_Dev')]
if api_name.endswith('_Private'):
api_name = api_name[:-len('_Privat... |
def how_many_days(month_number):
"""Returns the number of days in a month.
WARNING: This function doesn't account for leap years!
"""
days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
#todo: return the correct value
return days_in_month[month_number-1] |
def median (X):
"""X most be sorted"""
if len(X)%2 == 0:
return (X[len(X)//2-1]+X[len(X)//2])/2
else:
return X[len(X)//2] |
def default_format(source, language, class_name, options, md, **kwargs):
"""Default format."""
return '<custom lang="%s" class_name="class-%s">%s</custom>' % (language, class_name, source) |
def _loaded_dice_roll(chance_num, cur_state):
"""Generate a loaded dice roll based on the state and a random number
"""
if cur_state == 'F':
if chance_num <= (float(1) / float(6)):
return '1'
elif chance_num <= (float(2) / float(6)):
return '2'
elif chance_num... |
def to_edges(graph):
"""
treat graph as a Graph and returns it's edges
to_edges(['a','b','c','d']) -> [(a,b), (b,c),(c,d)]
"""
return list(zip(graph[:-1], graph[1:])) |
def _remove_new_line_from_usage_patterns(docstr):
"""Removes new line from usage patterns in docopt CLI description.
:param str docstr: docopt CLI description.
:return: Reformatted docstring ready for docopt consumption.
:rtype: :py:class:`str`
"""
lines = []
usage = False
for line in d... |
def lengthOfLastWord(s):
"""
:type s: str
:rtype: int
"""
sentence_list = s.split()
if sentence_list == []:
return 0
else:
return len(sentence_list[-1]) |
def make_url(hostname: str, api_method: str, branch_id: int = 0) -> str:
"""
Make url for api call
:param hostname: hostname
:param api_method: api method
:param branch_id: branch id
:return: full url
"""
if branch_id:
return f"https://{hostname}/v2api/{branch_id}/{api_method}"
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.