content stringlengths 42 6.51k |
|---|
def accuracy_evaluation_boolean_categ(attribute, values_range):
"""
This function calculate the accuracy considering if each value is in the provided range.
:param attribute: The attribute to evaluate
:param values_range: The range of values admitted for each attribute in analysis
e.g.: va... |
def _full_class_name(obj):
"""
Returns the full name of the class of the given object
:param obj: Any Python object
:return: The full name of the class of the object (if possible)
"""
module = obj.__class__.__module__
if module is None or module == str.__class__.__module__:
return o... |
def _try_cast(obj, cls):
"""Attempts to cast an object to a class, returning the resulting casted
object or the original object if the cast raises a ValueError.
"""
try:
return cls(obj)
except ValueError:
return obj |
def is_port_in_use(port: int) -> bool:
"""
Check if a porty is in use.
"""
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('localhost', port)) == 0 |
def expand_dict(target, namespace_sep='.'):
"""Expand a flat dict to a nested one.
This is an inverse of 'flatten_dict'.
:seealso: flatten_dict
"""
nested = {}
for k, v in target.items():
sub = nested
keys = k.split(namespace_sep)
for key in keys[:-1]:
sub = ... |
def sigma_o(T):
"""Error on hits of period T as predicted by Lindegren."""
return 126 * T ** (-1.5) |
def extract_top_level_dict(current_dict):
"""
Builds a graph dictionary from the passed depth_keys, value pair. Useful for dynamically passing external params
:param depth_keys: A list of strings making up the name of a variable. Used to make a graph for that params tree.
:param value: Param value
:... |
def ordall(d):
"""
Given a dict with string values, returns an equivalent dict where
the strings have been transformed into arrays of integers. This is
a data "wrapper" to avoid a weird issue with cPickle where
undefined unicode chars were modified in the pickling/unpickling
process. (Try to pi... |
def _IsSillyFilesystem(fstype):
"""Filesystems which are not interesting to export to the ACS."""
SILLY = frozenset(['devtmpfs', 'proc', 'sysfs', 'usbfs', 'devpts',
'rpc_pipefs', 'autofs', 'nfsd', 'binfmt_misc', 'fuseblk'])
return fstype in SILLY |
def _parse_kwargs(kwargs):
"""Extract kwargs for layout and placement functions. Leave the remaining
ones for :func:`minorminer.find_embedding`.
"""
layout_kwargs = {}
# For the layout object
if "dim" in kwargs:
layout_kwargs["dim"] = kwargs.pop("dim")
if "center" in kwargs:
... |
def remove_wiki_info(example):
"""Remove unnecessary texts in the wikipedia corpus."""
keywords = ("See also", "References", "Category")
for keyword in keywords:
index = example["text"].find(keyword)
if index != -1:
example["text"] = example["text"][:index]
return example |
def strxor(str1, str2):
"""Xors 2 strings character by character.
"""
minlen = min(len(str1), len(str2))
ans = ""
for (c1, c2) in zip(str1[:minlen], str2[:minlen]):
ans += chr(ord(c1) ^ ord(c2))
return ans |
def find_pivot(unsorted, start, end):
"""
Find the pivot value using the Median of Three method in a Python list
Expected Complexity: O(1) (time and space)
:param unsorted: an unsorted Python list to find the pivot value in
:param start: integer of starting index to find the pivot value in
:par... |
def remove_blanks(lst):
"""
Removes empty elements from a list
"""
return [el for el in lst if el != ''] |
def genre_choices( entity_instance ):
"""Choices for the possible movie genres"""
return [
((None),('')),
(('action'),('Action')),
(('animation'),('Animation')),
(('comedy'),('Comedy')),
(('drama'),('Drama')),
(('sci-fi'),('Sci-Fi')),
(('war'),('War')),
(('thriller'),('... |
def get_current_key_index(
key_method, current_file_number, current_record_number, record_count
):
"""Returns the current key with details.
Keyword arguments:
key_method -- the key method to use
current_file_number -- the number of the current file being processed
current_record_number -- the n... |
def process_dilations(dilations):
""" helper function to validate and process the dilation rate of
the wavenet model. The dilation rate at each layer must be a power of 2
:param dilations: list of dilation rate at each layer
:returns: valid dilation rate
:rtype: list
"""
def is_power_of_tw... |
def verify_hash_bool(b: bool) -> bool:
"""
Verify the manifest verify_hash flag (boolean)
:param b:
:return:
"""
return type(b) is bool |
def is_to_calculate_expectation(slate_size: int, item_size: int) -> bool:
"""
Switch between calculating and sampling expectations, balanced by execution
time and accuracy
Return:
True to calculate
False to sample
"""
return (
slate_size < 4
or (slate_size == 4 an... |
def contains_any(string, candidates=[]):
"""Return True if a string contains any of the given candidate strings."""
for candidate in candidates:
if candidate.lower() in string.lower():
return True
return False |
def calc_delta(sample_parent, model_parent):
"""Calculates the delta value, given the sample parent and model parent
composition.
Parameters
----------
sample_parent : float
Measured parent composition.
model_parent : float
Model parent composition. (Typically CHUR or DM ... |
def long_substr(ilist: list) -> str:
"""
Find the longest common substring (sstr) from a list of strings.
This is from:
https://stackoverflow.com/questions/2892931/\
longest-common-substring-from-more-than-two-strings-python#
"""
sstr = ""
if len(ilist) > 1 and len(ilist[0]) > 0:
... |
def genmsg_describe(url, seq, user_agent, auth_seq):
"""Generate RTSP describe message"""
msg_ret = "DESCRIBE " + url + " RTSP/1.0\r\n"
msg_ret += "CSeq: " + str(seq) + "\r\n"
msg_ret += "Authorization: " + auth_seq + "\r\n"
msg_ret += "User-Agent: " + user_agent + "\r\n"
msg_ret += "Accept: app... |
def get_best_image(item):
"""Determines the best image for a given video metadata blob """
if 'maxres' in item['snippet']['thumbnails']:
return item['snippet']['thumbnails']['maxres']['url']
elif 'standard' in item['snippet']['thumbnails']:
return item['snippet']['thumbnails']['standard']['u... |
def integer_cube_root_binary_search(n):
"""Returns the largest number n such that n ** 3 <= num"""
high = (n // 2) + 1
low = 0
while low < high:
mid = (low + high) // 2
if mid ** 3 < n:
# mid works, but higher option might work too
low = mid + 1
else:
... |
def toBoolean(val, default=True):
"""convert strings from CSV to Python bool
if they have an empty string - default to true unless specified otherwise
"""
if default:
trueItems = ["true", "t", "yes", "y", "1", "on", ""]
falseItems = ["false", "f", "no", "n", "none", "0"]
else:
... |
def capitalize(text):
"""Capitalises the specified text: first letter upper case,
all subsequent letters lower case."""
if not text:
return ''
return text[0].upper() + text[1:].lower() |
def processResult( solution ) :
"""
Do any processing on the given solution before yielding
it for the last time. For instance, maybe create a human
readable string of the solutin and yield that instead.
Parameters:
Solution is a 2 tuple of (score, solution)
"""
return (1000000... |
def ui_calc(swir, nir):
"""
Urban index
wrong formula in paper
"""
return ( ((swir - nir)/(swir - nir)) + 1.0 )*100 |
def get_all_tasks_from_state(mesos_state, include_orphans=False):
"""Given a mesos state, find the tasks from all frameworks.
:param mesos_state: the mesos_state
:returns: a list of tasks
"""
tasks = [task for framework in mesos_state.get('frameworks', []) for task in framework.get('tasks', [])]
... |
def combine_common_sections(data):
"""Combine sections declared in separate apps."""
sections = []
sections_dict = {}
for each in data:
if each["label"] not in sections_dict:
sections_dict[each["label"]] = each
sections.append(each)
else:
sections_dict[each["label"]]["items"] += each["items"]
return ... |
def to_list(l):
""" If not list, wraps parameter into a list."""
if not isinstance(l, list):
return [l, ]
else:
return l |
def prep_str(s):
"""
"""
ns = ''
if s is None:
s = ''
for c in s:
oc = ord(c)
if not 0x20 <= oc <= 0x7E:
c = '[{:02d}]'.format(ord(c))
ns += c
return ns |
def cast_no_data_value(no_data_value, dtype):
"""Handles casting nodata values to correct type"""
int_types = ['uint8', 'uint16', 'int16', 'uint32', 'int32']
if dtype in int_types:
return int(no_data_value)
else:
return float(no_data_value) |
def get_unique_variants(variants):
"""Get only unique variants, with respect to:
- position in genome,
- set of alternative alleles
- ensembl gene id
All transcript affected by variants sharing listed properties
will expand "affected_transcripts" set of returned variant.
"""
... |
def get_rules_for(app_name: str, rule_groups: list) -> list:
"""Find rule group for a specific application.
Prometheus charm creates a rule group for each related scrape
target. This method finds the rule group for one specific
application.
Args:
app_name: string name of scrape target appl... |
def truncate_to_fit(text, len):
"""
Truncate text to specified length.
"""
return text[:len] |
def filter_words(text_list, dictionary):
""" Filter sentences to remove any words from that does not appear in our dictionary
Args:
text_list: list of words in a sentence
dictionary: dictionary of words in training set
Returns:
Filtered list of words in a sentence
... |
def wrap_index(idx, size):
"""
Function which converts an index of a sequence into a positive one.
Hereby, a positive index remains unaltered while a negative index is
converted.
.. note:: This function mimics the behavior of standard Python sequences.
:param idx: The index.
:param size: T... |
def get_average_monthly_donwloads(daily_donwloads_list):
"""
Calculate the average monthly downloads from the download API response
"""
total = 0
for daily_donwloads in daily_donwloads_list:
total += daily_donwloads['downloads']
return total // len(daily_donwloads_list) |
def fold_description(fold: float) -> str:
"""
Return a string for describing a fraction (including a percent representation).
"""
if fold is None:
return "None"
if fold >= 0:
value = 2 ** fold
char = "X"
else:
value = 2 ** -fold
char = "/"
return f"{... |
def min_operations(target):
"""
Return number of steps taken to reach a target number
input: target number (as an integer)
output: number of steps (as an integer)
"""
operation = 0
while target > 0:
if target % 2 == 0:
target = target // 2
else:
target... |
def unique_list(seq):
"""Make a list unique and preserve the elements order
Modified version of Dave Kirby solution
"""
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)] |
def format_artist(__, data):
"""Returns a formatted HTML line describing the artist."""
return "<li><a href='{artist_tag}/index.html'>{artist}</a></li>\n".format(**data) |
def _make_version(major, minor, micro, level, serial):
"""
Generate version string from tuple (almost entirely from coveragepy)
"""
level_dict = {'alpha': 'a', 'beta': 'b', 'candidate': 'rc', 'final':''}
if level not in level_dict:
raise RuntimeError('Invalid release level')
version = '{... |
def sum_formula_general(a: int, d: float, n: int) -> int:
"""
SUM k=0 to n-1 of (a + k*d)
= n/2 (2a + (n-1)d)
https://www.mathsisfun.com/algebra/sequences-sums-arithmetic.html
a = first term
d = difference between terms
n = amount of terms
"""
assert n > 0, n
return n * (2 * a + ... |
def _tw_kern(x, m, h):
"""Triweight kernel.
Parameters
----------
x : array-like or scalar
The value at which to evaluate the kernel.
m : array-like or scalar
The mean of the kernel.
h : array-like or scalar
The approximate 1-sigma width of the kernel.
Returns
-... |
def get_dataset(city, dataset):
"""
Loads the dataset from the data folder
:param city: City selected by the user
:param dataset: Corresponding dataset for the city selected by the user
:return: User selected dataset
"""
if city == 'chicago':
dataset = './data/chicago.csv'
if c... |
def entity_encode(arg):
""" Be sure it's a string, vs int, etc, and encode &, <, ". """
return str(arg).replace('&', '&').replace('<', '<').replace('"', '"') |
def rho_beta_heaviside(levels , ps, check=False):
"""
This function returns the Boer beta field, given the levels in G and the ps (hPa)
uses xarray
returns:
xr.DataArray in the same dimension as ps levels
"""
aa= (levels < ps)
if check is True:
print('ratio ' + str( aa.sum()/flo... |
def uri_is_internal(uri):
"""
>>> uri_is_internal('/word/media/image1.png')
True
>>> uri_is_internal('http://google/images/image.png')
False
"""
return uri.startswith('/') |
def get_cycle_total_info(data):
"""Get total information of cycle from profile data
Parameters
----------
data : list[dict[str, dict[str, object]]]
Original data
res : dict
Total information
"""
res = {"cycle": 0, "time_ms": 0.0}
for d in data:
res["cycle"] += d... |
def clean_doc_str(doc, overview=False):
"""
Transform a Python doc string into a Markdown string.
First, it finds the indentation of the whole block. It's assumed that
everything in the block shares the same basic indentation.
Any line that starts with ":" is considered to be Python meta-informat... |
def _cleaned_tag_name(name):
"""Get the cleaned up version of the given name.
The returned tag name only has standard ascii alphanumerical characters.
"""
cleaned_list = []
for char in name.lower(): # I /could/ do list comprehension, but nah.
num = ord(char)
if 48 <= num <= 57 or 9... |
def all_rotations(number):
"""Finds all rotations of a number (e.g. 123 => 123, 231, 312"""
out = [number]
str_num = str(number)
current = str_num[-1] + str_num[:-1]
while int(current) not in out:
out.append(int(current))
current = current[-1] + current[:-1]
return out |
def getqname(namespaces, qname):
"""
Convert a namespaced text value element to James Clark's universal form.
For example::
(Assuming the prefix "p" corresponds to "http://my.ns")
p:foo => {http://my.ns}foo
@type namespaces: C{iterable} of C{(str, str)}
@param namespaces: An iter... |
def format(t):
"""
converts time in tenths of seconds into formatted string A:BC.D
"""
milliseconds = t % 10
seconds = (t // 10) % 60
minutes = (t // 10) // 60
if seconds < 10:
return str(minutes) + ":" + "0" + str(seconds) + "." + str(milliseconds)
else:
return str(minu... |
def is_intable(s):
"""True if the passed value can be turned into a int, False otherwise"""
rc = False
try:
int(s)
rc = True
except ValueError:
pass
return rc |
def dictionary_update(dict1, dict2):
"""
Updates dictionary values if required
: dict1 (dict): reference dictionary
: dict2 (dict): dictionary with potential updates
"""
# Generate a set of common keys
common_keys = dict1.keys() & dict2.keys()
# Updating hyperparamete... |
def norm_histogram(hist):
"""
takes a histogram of counts and creates a histogram of probabilities
:param hist: list
:return: list
"""
total_sum = sum(hist)
hist_prob = []
for i in hist:
prob = i / total_sum
hist_prob.append(prob)
return(hist_prob)
... |
def wacc(equity_share, interest, return_on_investment, corporate_tax):
"""
Weighted Average Cost of Capital
Best but perhaps to detailed representation for cost of capital.
"""
e = equity_share
d = 1 - e
i = interest
roi = return_on_investment
t = corporate_tax
tf = 1-t
wi ... |
def _dict_remove_none(my_dict):
"""If any values in dictionary are of dtype 'None', replace with
an empty string. Used for consistency in results: don't want to have a mix
of empty strings (e.g. from empty string in DB) and 'None' (e.g. from a LEFT OUTER JOIN).
"""
for key, val in my_dict.items():
if val is None... |
def dp_port_id(switch: str, port: str) -> str:
"""
Return a unique id of a DP switch port based on switch name and port name
:param switch:
:param port:
:return:
"""
return 'port+' + switch + ':' + port |
def splice(l, a, b, c):
""" JS's Array.prototype.splice
var x = [1, 2, 3],
y = x.splice(0, 2, 1337);
eq
x = [1, 2, 3]
x, y = splice(x, 0, 2, 1337)
"""
return l[:a] + [c] + l[a + b:], l[a:a + b] |
def scrub_object(obj):
"""Remove protected fields from object (dict or list)."""
if isinstance(obj, list):
return [scrub_object(item) for item in obj]
elif isinstance(obj, dict):
clean_dict = {key: scrub_object(value)
for key, value in obj.items()
... |
def normalize_input(answer):
"""Take a string and normalize it to a standard format."""
return answer.strip() |
def node_by_id(items: list, id):
"""
Finds a dictionary with the id provided
"""
for item in items:
if str(item["id"]) == str(id):
return item
raise KeyError(f"ID '{id}' not found in list") |
def expand(pos, s, offset=False):
"""find a palindrome by expanding around the center
>>> expand(1, 'abc')
'b'
>>> expand(1, 'aaa')
'aaa'
>>> expand(0, 'bb', True)
'bb'
"""
if offset: # shift right pos by 1
right = pos + 1
left = pos
else:
left = right =... |
def select_equal(list_lists, select_amount):
"""
Select equal elements from a list of lists.
Parameters
----------
list_lists: list
A list of lists of elements. The lists could be unequal in size.
select_amount: int
An integer of samples to take.
Examples
--------
... |
def _resolve_subkeys(key, separator='.'):
"""Resolve a potentially nested key.
If the key contains the ``separator`` (e.g. ``.``) then the key will be
split on the first instance of the subkey::
>>> _resolve_subkeys('a.b.c')
('a', 'b.c')
>>> _resolve_subkeys('d|e|f', separator='|')
... |
def MAR(z, Mh):
"""
Equation 9 from McBride et al. (2009).
..note:: This is the *median* MAH, not the mean.
"""
return 24.1 * (Mh / 1e12)**1.094 * (1. + 1.75 * z) * (1. + z)**1.5 |
def json_serial(obj):
"""Serialize json.
Args:
obj (Any): A python object.
Example:
json.dumps(data, default=json_serial)
"""
if isinstance(obj, set):
return list(obj)
raise TypeError |
def rreplace(s, old, new, occurrence):
"""Reverse replace."""
li = s.rsplit(old, occurrence)
return new.join(li) |
def can_put(t, i, j, v):
"""Tell whether we can put digit v in position (i, j) in grid t"""
for x in range(9):
if t[x][j] == v:
return False
if t[i][x] == v:
return False
i0 = (i // 3) * 3
j0 = (j // 3) * 3
for x in range(i0, i0 + 3):
for y in range(j0... |
def colorstr(*inputs):
"""return platform-dependent emoji-safe version of string
Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. \
colorstr('blue', 'hello world')
"""
*args, string = inputs if len(inputs) > 1 else ('blue', 'bold', inputs[0])
colors = {'black': '\033[30m', # b... |
def bigram_shingler(str):
"""Extract a set of 2 character n-grams (character bigrams) from string"""
big_set = {str[x:x+2] for x in range(0, len(str) -1) if len(str) > 1}
return big_set |
def mean(data: list, prec=3):
"""Calc mean value of a list.
Args:
data(list): a list.
prec(int): round precision.
Returns:
(float) mean value.
Example:
>>> mean([1, 2, 3, 4])
>>> # 2.5
"""
return round(sum(data) / len(data), prec) |
def __check_possible_pointer_type(var_name: str, rhs: str) -> bool:
"""Checks conditions for possible pointer types.
:param var_name: target variable name
:param rhs: right hand side string to be analyzed
:return: True, of None should be returned by __get_alias_statement. False, otherwise.
"""
#... |
def get_macro(name, macros):
"""
Return macro from macro list by name.
"""
for themacro in (macro for macro in macros if macro.get('name') == name):
if themacro:
return(themacro)
else:
pass |
def justify_to_box(
boxstart: float,
boxsize: float,
itemsize: float,
just: float = 0.0) -> float:
"""
Justifies, similarly, but within a box.
"""
return boxstart + (boxsize - itemsize) * just |
def compare_pval_alpha(p_val, alpha):
""" this functions tests p values vs our chosen alpha"""
status = ''
if p_val > alpha:
status = "Fail to reject"
else:
status = 'Reject'
return status |
def load_text(file_name):
"""
Load lines from a plain-text file and return these as a list, with
trailing newlines stripped.
Arguments:
file_name (str or unicode): file name.
Returns:
list of str or unicode: lines.
"""
with open(file_name) as text_file:
lines = text_... |
def reduce_loom(op, operands):
"""Apply a binary LoomOp on `operands` to obtain one result."""
if not operands:
raise ValueError('operands is empty')
# Binary tree reduction.
while len(operands) > 1:
evens = operands[::2]
odds = operands[1::2]
new_operands = [op(*pair) for pair in zip(evens, od... |
def phex(n):
"""Pretty hex.
The `hex()` function can append a trailing 'L' signifying the long
datatype. Stripping the trailing 'L' does two things:
1. Can double click it in the IDA output window to jump to that address
2. Looks cleaner
Args:
n (numbers.Integral): Number to prettify
... |
def sieve (number):
"""
@type number: integer
@param number: number > 0
@rtype: list
@return: list of the primes until number.
"""
i = 2
cont = 0
primes = []
while i <= number:
while cont < len(primes) and i % primes[cont] != 0:
cont = cont + 1
if cont... |
def init_aux(face_lines):
"""
initialize animation
"""
for k, f in enumerate(face_lines):
f.set_data([], [])
return face_lines |
def set_config_defaults(data_extraction_dict: dict) -> dict:
"""Set default values for some data configs if they are not defined.
Note:
'skip' is not currently used in derivation
Args:
data_extraction_dict (dict): Dict from the benchmark definition dict
that defined how data wi... |
def bulleted_list(items, max_count=None, indent=2):
"""Format a bulleted list of values."""
if max_count is not None and len(items) > max_count:
item_list = list(items)
items = item_list[: max_count - 1]
items.append("...")
items.append(item_list[-1])
line_template = (" " * ... |
def plot_graph(path):
"""
Writes a template.
:param path: Path to write it to.
:type path: str
:return: The file name
"""
file_name = r'/plot_graph_template.py'
file = open(path + file_name, 'w')
file.write("# Imports\n")
file.write("import sys\n")
file.write("import platf... |
def extract_authors(pubs):
"""Get list of author IDs from a list of namedtuples representing
publications.
"""
l = [x.author_ids.split(";") for x in pubs if isinstance(x.author_ids, str)]
return [au for sl in l for au in sl] |
def decode_value(metric_name, value):
"""Convert values to human readible format based on metric name"""
result = value
if metric_name == 'learned_macs':
result = ':'.join(
format(octet, '02x') for octet in int(value).to_bytes( # pytype: disable=attribute-error
6, byteor... |
def is_isbn13(s):
"""
Check whether the given string is a valid, normalized ISBN-13 number.
This only passes if the given value is a string that has exactly 13
decimal digits, and the last decimal digit is a proper ISBN-13 check
digit.
Parameters:
s : str | mixed - the value to check
Return:
... |
def makepatch(original, modified):
"""Create a patch object.
Some methods support PATCH, an efficient way to send updates to a resource.
This method allows the easy construction of patch bodies by looking at the
differences between a resource before and after it was modified.
Args:
original: object, the... |
def codon_dict( filler=0 ):
"""Return a dictionary of codon:filler pairs for all 64 codons."""
d = {}
for one in 'AGCT':
for two in 'AGCT':
for three in 'AGCT':
d.update({ one+two+three:filler })
return d |
def MakeValLimitsTriplet( value, blob ):
"""Given a central value and a string including the lower and upper bounds,
returns a triplet of value, -err, +err
blob = string in one of the following formats:
[' (-1.0135,-0.2338',
' (0.0509,0.1322',
' (10.0960,10.2437',
' (0.5136,0.6842)']
"""
blob = blob... |
def cast_id(idVal, field_type):
"""If possible, re-cast a value to a specific field type
Otherwise, cast it as a string."""
if "String" in field_type:
idVal = str(idVal)
else:
try:
idVal = int(idVal)
except ValueError:
idVal = str(idVal)
return id... |
def _phylowgs_compatible_chroms(chrom):
"""PhyloWGS prep scripts to not correctly support chr-prefixed contigs, so we remove them.
"""
return chrom if not chrom.startswith("chr") else chrom.replace("chr", "") |
def bubbleSort(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
#################################
# Selection Sort
n = len(nums)
if n<=1:
return nums
for i in range(n):
smallest_val = nums[i]
smallest_idx = i
# find the smallest element
... |
def nextpow2( x: int ) -> int:
"""Returns the lowest power-of-2 integer that is at least as large as 'x'."""
v = 1
while v < x:
v = v * 2
return v |
def piecewise_compare(a, b):
""" Check if the two sequences are identical regardless of ordering """
return sorted(a) == sorted(b) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.