content stringlengths 42 6.51k |
|---|
def zotero_note_update(resp, note_dict):
"""
params:
resp, {}
note_dict, {}
return: note_dict, {}
"""
#
parent_key = resp["success"]["0"]
note_dict["parentItem"] = parent_key
#
return note_dict |
def to_root_latex(s):
"""
Converts latex expressions in a string *s* to ROOT-compatible latex.
"""
return s.replace("$", "").replace("\\", "#") |
def validate_custom_page_path(path):
"""
Check if a custom page path is valid or not,
to prevent malicious requests.
:param path: custom page path (url path)
:return: valid or not
"""
sp = path.split('/')
if '.' in sp or '..' in sp:
return False
return True |
def round_to_even(value):
""" rounds the value to the nearest even integer """
return 2*int(value/2 + 0.5) |
def is_divisible_by_any(number, divisors):
"""Return True if a number is divisible by any divisor in a list, False otherwise"""
for x in divisors:
if number % x == 0: return True
return False |
def filter_secrets(txt: str) -> str:
"""Replaces secrets with *'s"""
# Example:
# output = txt.replace(password, '*' * len(password))
# output = output.replace(username, '*' * len(username))
# return output
return txt |
def isRXCY(s):
"""
>>> isRXCY('RRCC233')
False
>>> isRXCY('R22C22')
True
"""
try:
idx0 = s.index('R')
idx1 = s.index('C')
except:
return False
if idx0 != -1 and idx1 != -1:
return any([str(i) in s[idx0+1:idx1] for i in range(10)])
return False |
def checkout(cash: float, list: dict) -> float:
"""
build a function that sums up the value of the grocery list and subtracts that
from the cash passed into the function.
return the "change" from the cash minus the total groceries value.
"""
# values = list.values()
total = sum(list.values()... |
def intervalLength(aa, wrapAt=360.):
"""Returns the length of an interval."""
if wrapAt is None:
return (aa[1] - aa[0])
else:
return (aa[1] - aa[0]) % wrapAt |
def gcd(a, b):
"""returns their greatest common divisor"""
if b == 0:
return a
return gcd(b, a % b) |
def properties_to_string(props: dict) -> str:
"""
Converts a dictionary of blockstate properties to a string
:param props: The dictionary of blockstate properties
:return: The string version of the supplied blockstate properties
"""
result = []
for key, value in props.items():
resul... |
def is_envar_enabled(envars, name):
"""
Check whether the specified environment variable is enabled.
This returns True if the specified environment variable is
already defined and set to nonempty and nonzero value.
Otherwise this returns False.
envars: A dict of environment variables
name:... |
def apply_format(n):
"""
Function to convert number to string in 6-digit format
:param n: number to convert
:return: string format
"""
return format(n, "05") |
def intuplelist(pair, list):
"""Tests to see if pair == (a,b,c) is in list, but handles None entries in
list as wildcards (only allowed in positions "a" and "c"). We take a
shortcut by only considering "c" if "b" has already matched."""
a, b, c = pair
if (b, c) == (None, None):
#This is a t... |
def clean_hotel_url(string):
"""
"""
r = string[: string.find('?')]
return r |
def block_renormalization(signal):
"""Renormalization step of blocking method."""
signal = [0.5 * (signal[2 * i] + signal[2 * i + 1])
for i in range(len(signal) // 2)]
return signal |
def two_places_at_once(sequence):
"""
Demonstrates iterating (looping) through a sequence,
but examining TWO places in the sequence on the SAME ITERATION.
This particular example returns the number of items in the sequence
that are bigger than the previous item in the sequence.
For example, if ... |
def _nonzero_int(integer_string, strict=False, cutoff=None):
"""
Cast a string to a strictly non-zero integer.
"""
if integer_string:
ret = int(integer_string)
else:
return integer_string
if ret == 0 and strict:
raise ValueError()
if cutoff:
return min(ret, cu... |
def usable_decode(text: bytes) -> str:
"""Decode the text so it can be used.
vars:
:param text: a string of bytes that needs decoding
:returns: string
"""
try:
decoded_text = text.decode("utf8")
except:
decoded_text = text.decode("latin1", errors="replace"... |
def preinstall_packages(answer):
"""Enable prompt for list of packages or path to requirments.txt"""
return "preinstall python packages" in answer['tasks'] |
def _is_extended_parameter(string):
"""
Returns whether the given string is an extended parameter of a content disposition parameter.
Parameters
----------
string : `str`
The string to check.
Returns
-------
is_extended_parameter : `bool`
"""
return string.endswith(... |
def count_occurances(comment, word):
"""
A helper function to count the number of words in a comment.
"""
comment = comment.replace('?', ' ')
comment = comment.replace('.', ' ')
comment = comment.replace('-', ' ')
comment = comment.replace('/', ' ')
a = comment.split(" ")
count = 0
... |
def safe_int(n):
"""Sort key for probably-numeric strings
Sorts unparseable strings first in lexicographical order, then
everything that intifies in numerical order.
"""
try: return (1, int(n))
except (ValueError, TypeError): return (0, n) |
def relax_w(min_w, relax_factor, base=2):
"""
Scale min_w by relax_factor and round to the nearest multiple of base.
"""
relaxed_w = int(base * round(min_w * relax_factor / base))
return relaxed_w |
def bool_or_none(val):
"""
Arguments:
- `x`:
"""
from distutils.util import strtobool
if val is None:
return None
elif val == "":
return None
else:
return bool(strtobool(val)) |
def is_record(type_field):
"""
Is the avro field a record or a non record?
Non-records return true. Fields that are scalar, null *or* a record
also return True.
"""
if isinstance(type_field, list):
for avro_type in type_field:
if isinstance(avro_type, dict):
i... |
def get_type(filename):
""" Get the type of an update """
return 'Fastboot' if filename.endswith('.tgz') else 'Recovery' |
def list2str(li, **kwargs):
"""
For SU.
"""
s = ''
for i in range(len(li)):
s += str(li[i]) + ','
s = s[:-1] # REMOVE THE TRAILING COMMA
return s |
def evaluate(conf_matrix, label_filter=None):
"""
Evaluate Precision, Recall and F1 based on a confusion matrix as produced by `create_confusion_matrix`.
Args:
conf_matrix: a confusion matrix in form of a dictionary from `(gold_label,guess_label)` pairs to counts.
label_filter: a set of gold... |
def is_palindrome(n):
"""
:param n: number
:return: True if number is palindrome
"""
string_n = str(n)
return string_n == string_n[::-1] |
def square_rect_knoll(x, y, rect_x, rect_y, width, height):
"""Given a square and a rectangle, gives a pair of integer cartesian co-ordinates that identify the square in the rectangle"""
return (x - rect_x, y - rect_y) |
def rivers_with_station(stations):
"""Takes in a list of station objects, returns a list of rivers with at least one station"""
output_set = set()
for station in stations:
output_set.add(station.river)
return output_set |
def parse_structure(astr, level):
"""
The returned line number is from the beginning of the string, starting
at zero. Returns an empty list if no loops found.
"""
if level == 0 :
loopbeg = "/**begin repeat"
loopend = "/**end repeat**/"
else :
loopbeg = "/**begi... |
def convert_time(time):
"""Convert a time in seconds into the biggest unit"""
units = [
(24 * 60 * 60, 'days'),
(60 * 60, 'hours'),
(60, 'minutes'),
(1, 'seconds'),
]
if time == 0:
return ('0', 'seconds')
for unit in units:
if time >= unit[0]:
... |
def remove_values_above(threshold, line):
"""
Args:
threshold (float)
line (str)
"""
parts = line.split(' ')
watts = float(parts[1])
if watts > threshold:
return None
else:
return line |
def sub_slash(adr_str):
"""This regex statement processes the initial spill files to avoid a case where intersections were improperly parsed
as street addresses"""
# https: // regex101.com / r / YlbKq2 / 1
import re
regex = r"( st)(/)(\w+)"
subst = "\\g<1> & \\g<3>"
# You can ma... |
def wr(nr):
"""Weight function, r>0 is mutual distance"""
return (1 - nr) if nr < 1.0 else 0.0 |
def get_key0(adict):
"""Gets the "first" key in a dictionary
The entry is kind of irrelevant.
"""
keys = list(adict.keys())
return keys[0] |
def get_short_name(description):
"""
Get short band name from full description
"""
if ',' in description:
return description[:description.find(',')]
if ' ' in description:
return description[:description.find(' ')]
return description[:3] |
def sort_list(a, order):
"""
Return the elements sorted in the given order
:param a: an iterable object
:param order: the order of elements you want to sort
:return: the new list contains only elements in the order
Example:
>>> a = [1, 2, 'a', 'b']
>>> order = [1,3]
... |
def get_nested_dict_item(dic: dict, key_list: list):
"""
Get a nested dictionary item.
If key_list is empty, return dic itself.
Args:
dic (dict): dictionary of items
key_list (list): list of keys
Returns:
dict: nested dictionary
.. code-block:: python
:linenos:... |
def hex_to_percent(hex_value: float) -> float:
"""Convert hex 0-255 values to percent."""
return round((hex_value / 255) * 100) |
def formatNumber(number):
"""The number of a journal, magazine, technical report, or of a work in a
series. An issue of a journal or magazine is usually identified by its
volume and number; the organization that issues a technical report
usually gives it a number; and sometimes books are gi... |
def findPath(locations):
"""
Parses a list of locations, returning the first file that exists.
If none exist, then None is returned.
"""
import os.path
for location in locations:
if location is not None and os.path.exists(location):
return os.path.abspath(location)
return None |
def valid_tags(tag_list):
""" checks tags for invalid chars """
for tag in tag_list:
if ':' in tag['Key']:
return False
return True |
def find_chan_corr(chan, corr, shape, chan_idx, corr_idx):
"""
1. Get channel and correlation from shape if not set and the shape is valid
2. Check they agree if they already agree
Parameters
----------
chan : int
Existing channel size
corr : int
Existing correlation size
... |
def from_c_str(v):
"""
C str to Python str
"""
try:
return v.decode("utf-8")
except Exception:
pass
return "" |
def sum_numbers(n: int) -> float:
"""
BIG-O Notation = O(c)
"""
return (n * (n + 1)) / 2 |
def to_camel_case(d):
"""
Convert data with snake_case keys to lowerCamelCase
Parameters
----------
d : str or list or dict
Data with snake case keys
Returns
-------
str or list or dict
Data with camel case keys
"""
def camel(s):
first, *others = s.split(... |
def domain_match(domain, suffix):
"""Test if `domain` ends with `suffix`.
Args:
domain (str): a domain name.
suffix (str): a string the domain name should end with. Multiple
suffixes are possible and should be separated by whitespace,
for example: 'lizard.net ddsc.nl'.
Retu... |
def checkH1(strings_h1, text_h1):
"""Checks if the string in h1 tags is present.
:param strings_h1: A list with all the strings contained in the H1 tags.
:param text_h1: the string to look for inside the tags.
:return: True if the text is present in the tags, False otherwise
:rtype:... |
def variable_id(evaluator, ast, state):
"""Evaluates "varName [= initData]"."""
var_name = ast["varName"]
array_decl = list(map(lambda decl: evaluator.eval_ast(decl, state), ast["arrayDecl"]))
init_data = evaluator.eval_ast(ast["initData"], state) if ast.get("initData") else None
return {"varName": ... |
def get_posterior_predictive_params(posterior_params):
""" Likelihood covariance matrix is an Identity matrix. """
pp_params = posterior_params.copy()
for k, k_params in pp_params.items():
k_params['cov_diag'] += 1
return pp_params |
def initialize2DArray(rowCount: int, colCount: int, value=None):
"""
-----------------------------
Purpose:
- Creates a 2D array with an initial value of 'value'
- Used for filling in data into the QTableView model
Arguments:
- rowCount: the number of rows des... |
def write_list(data, delims="[]"):
"""Writes a formatted string from a list.
The format of the output is as for a standard python list,
[list[0], list[1],..., list[n]]. Note the space after the commas, and the
use of square brackets.
Args:
data: The value to be read in.
delims: An optional... |
def calculate_hue_offsets(color_wheel):
"""
parse color wheel and give hue offsets compared to traditional hsv
>>> cw = {300: (120, 0, 106)}
>>> print(calculate_hue_offsets(cw))
{307: 300}
"""
from colorsys import rgb_to_hsv
return {
round(rgb_to_hsv(*[rgb/255 for rgb in color_w... |
def query_builder(active_filters):
"""Build the query according to the activated shelf and filters"""
paras = {}
para_list = ()
query = ""
for _filter in active_filters:
if 'stat_Read' == _filter:
query += " AND read_count > 0"
elif 'stat_Unread' == _filter:
q... |
def isSecurePort(port):
"""
Returns True if port is root-owned at *nix systems
"""
if port is not None:
return port < 1024
else:
return False |
def SanitizeKernelPrototype(text: str) -> str:
"""Sanitize OpenCL prototype.
Ensures that OpenCL prototype fits on a single line.
Args:
text: OpenCL source.
Returns:
Source code with sanitized prototypes.
"""
# Ensure that prototype is well-formed on a single line:
try:
prototype_end_idx = ... |
def paddingSize(value, align):
"""
Compute size of a padding field.
>>> paddingSize(31, 4)
1
>>> paddingSize(32, 4)
0
>>> paddingSize(33, 4)
3
Note: (value + paddingSize(value, align)) == alignValue(value, align)
"""
if value % align != 0:
return align - (value % al... |
def fill_columns(columns,board):
"""Returns list of columns of the board.
>>> fill_columns(['', '', '', '', '', '', ''],['***21**', '412453*', '423145*',\
'*543215', '*35214*', '*41532*', '*2*1***'])
['*44****', '*125342', '*23451*', '2413251', '154213*', '*35142*', '***5***']
"""
for i in range(le... |
def postmean(g_hat, g_bar, n, d_star, t2):
"""
Parameters
----------
g_hat
g_bar
n
d_star
t2
Returns
-------
out
"""
return (t2 * n * g_hat + d_star * g_bar) / (t2 * n + d_star) |
def invert_octet(octet):
"""
Given a integer in range 0 - 255, return its value with all bits logically
inverted.
@param int octet - Integer in range 0 to 255.
Values > 255 are masked using 0xFF to force them into the
range of 0 to 255.)
@returns int i... |
def contains(item, elements):
"""Returns True if the item is contained in the list elements"""
for element in elements:
if item.equals(element):
return True
return False |
def get_parameter(net, children):
"""Return list of parameter dicts for this type of meta-variable.
Parameters:
-----------
net : dict
Complete network dictionary containing all nps, sps, plasts, ifs.
children : list of str
This list contains the item names of all child items this m... |
def mult_tuple_by_scalar(tup, scalar):
"""Multiplies every value of tup by scalar."""
return (tup[0]*scalar, tup[1]*scalar) |
def get_brightness(p):
"""CCIR601 RGB -> Luma conversion"""
return (299.0 * p[0] + 587.0 * p[1] + 114.0 * p[2]) / 1000.0 |
def is_sedes(obj):
"""
Check if `obj` is a sedes object.
A sedes object is characterized by having the methods
`serialize(obj)` and `deserialize(serial)`.
"""
return hasattr(obj, 'serialize') and hasattr(obj, 'deserialize') |
def find(value_to_find, attribute, search_space):
"""Find a video with matching id in a dict or list"""
for video in search_space:
if video[attribute] == value_to_find:
return video
raise KeyError(f'Metadata for {value_to_find} does not exist') |
def check_header_keywords(keywords, hdunum, hdr):
"""Check for keywords in header.
"""
# missing has the keywords which are missing in the file and are required for processing
# extra are the keywords which are not required and are present in the system
# not required are the ones which are not requ... |
def last(inlist):
"""
Return the last element from a list or tuple, otherwise return untouched.
Examples
--------
>>> last([1, 0])
0
>>> last("/path/somewhere")
'/path/somewhere'
"""
if isinstance(inlist, (list, tuple)):
return inlist[-1]
return inlist |
def growth(t):
"""
Calculate grain size growth
From IPW albedo > growth
"""
a = 4.0
b = 3.
c = 2.0
d = 1.0
factor = (a+(b*t)+(t*t))/(c+(d*t)+(t*t)) - 1.0
return(1.0 - factor) |
def get_var_list(var_observed):
"""
Merge called variants
"""
if var_observed == []:
return "NA"
return "_".join(var_observed) |
def is_clustering_finished(terminals):
"""
Given a list of leave nodes, return True if all of them
only contain a single word, otherwise return False.
"""
leaf_sizes = [len(node['vecs']) for node in terminals]
if max(leaf_sizes) > 1:
return False
else:
return True |
def revbits(x):
"""Reverse bit order."""
rev = 0
while x:
rev <<= 1
rev += x & 1
x >>= 1
return rev |
def _encode(encoding, string):
"""
Subrouting to encode a string using an iterable of tuples.
"""
for search, replace in encoding:
string = string.replace(search, replace)
return string |
def sig_code(p_value):
"""create a significance code in the style of R's lm
Arguments
---------
p_value : float on [0, 1]
Returns
-------
str
"""
assert 0 <= p_value <= 1, 'p_value must be on [0, 1]'
if p_value < 0.001:
return '***'
if p_value < 0.01:
return... |
def jq_format(code):
"""
Use before throwing raw code such as 'div[tab="advanced"]' into jQuery.
Selectors with quotes inside of quotes would otherwise break jQuery.
This is similar to "json.dumps(value)", but with one less layer of quotes.
"""
code = code.replace('\\', '\\\\').replace('\t', '\\... |
def indent(text, marker=" |"):
"""
Return the given text indented with 3 space plus a pipe for display.
"""
lines = text.split("\n")
return "\n".join(marker + l for l in lines) |
def has_strings(word, s, c, e):
"""
Compare a string to 3 other
"""
if word.startswith(s):
if word.index(c) > -1:
if word.endswith(e):
return "Match"
return "No match" |
def fixFilename(file):
"""
Rosetta cannot use spaces in the filename...
"""
x=file.split()
if len(x) > 1:
newFile = x[0]
for i in range (1, len(x)):
newFile = newFile + "\ " + x[i]
return newFile
else:
return file |
def remove_element_from_list(x, element):
"""
Remove an element from a list
:param x: a list
:param element: an element to be removed
:return: a list without 'element'
Example:
>>>x = [1, 2, 3]
>>>print(arg_find_list(x, 3))
[1, 2]
"""
return list(filter(... |
def are_all_chips_connected(generators, microchips):
"""Check if all chips are connected to generator."""
return all(chip in generators for chip in microchips) |
def build_bridge_body(bridge_dict, interface_uri):
"""
Removes interface from bridge table
:param bridge_dict: current bridge configuration
:param interface_uri: interface uri that shall be removed
:return: json object (dict)
"""
uri = "/rest/v1/system/ports/{}".format(interface_uri[27:])
... |
def is_set(tdict, path):
"""
:param tdict: a dictionary representing a argument tree
:param path: a path list
:return: True/False if the value is set
"""
t = tdict
for step in path:
try:
t = t[step]
except KeyError:
return False
if t is not None:... |
def validate_max_execs(value):
"""Validate "max_execs" parameter."""
try:
value = int(value)
except ValueError:
raise ValueError("Must be integer")
if value < 0:
raise ValueError("Negative value is not allowed")
return value |
def hello_people(name):
""" hello people """
return 'hello ' + name + '\n' |
def module_name_set(l): # noqa: E741
"""
Converts a list of target modules into a set of module names, disregarding
any configuration that may be present.
"""
modules = set()
for m in l:
if m and isinstance(m, dict):
modules.update(m.keys())
else:
modules... |
def stringify(*args):
"""
little function to convert many inputs to string
so i can easily replace print by logging
"""
output_string = ''
for chunk in args:
output_string = output_string + ' ' + str(chunk)
return output_string[1:] |
def parse_authstring(authstring):
"""Parse an auth string into a dict
Given an authentication header string [RFC2617], parse the fields and
return a dict object of each key/pair
"""
# Ensure the string starts with 'MAC '
if not authstring or not authstring.startswith('MAC '):
raise Exc... |
def make_date_range_query(from_date, to_date):
""" Forms a Solr date range query of form [from_date TO to_date] based on the
values of from_date and to_date in the arguments."""
query = "[{} TO {}]".format(from_date, to_date)
return query |
def is_iterable(obj):
"""Return if an object is iterable and not callable."""
return not callable(obj) and (hasattr(obj, '__iter__') and not type(obj) == type) |
def left_join(hashmap1, hashmap2):
"""Takes in two hash maps and left joins them. The first parameter will look the the second parameter for matching keys and get those values, if no match is found null will be return for that row in the the table. Result will be a returned combination of both.
"""
output =... |
def simple_instruction(opcode_name, offset):
# type: (str, int) -> int
"""Utility function for simple instructions."""
print("{}".format(opcode_name))
return offset + 1 |
def find_name_hard(function):
"""
Looks for a name in the partial proper BF format: f = <expression>.
Adds to the functionality of "find_name" in strings.py.
"""
rv = ""
for i in range(len(function)):
if function[i] != "=":
rv += function[i]
elif i+1 < len(function) ... |
def _set_default_resistance(resistance: float, subcategory_id: int) -> float:
"""Set the default resistance for resistors.
:param resistance: the current resistance.
:param subcategory_id: the subcategory ID of the resistor with missing defaults.
:return: _resistance
:rtype: float
"""
if re... |
def round_filters(width_coefficient, filters, depth_divisor=8.0):
""" Round number of filters based on width coefficient.
Args:
width_coefficient: Coefficient to scale network width.
filters: Number of filters for a given layer.
depth_divisor: Constant.
From tensorflow implementati... |
def get_longest_substrings(string_set):
"""Return list of strings of maximal length in a set of strings."""
longest = len(max(string_set, key=lambda x: len(x)))
return [x for x in string_set if len(x) == longest] |
def parse_name(name):
"""Parse the topic or subscription name."""
components = name.split('/')
if len(components) != 4:
raise ValueError('Invalid pubsub name.')
project = components[1]
name = components[3]
return project, name |
def welfords_online_algorithm(sample, mean, count, m2):
"""
Obtain the next iteration for Welford's online algorithm to stably
calculate the running mean and standard deviation
https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm
Parameters
----------
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.