content stringlengths 42 6.51k |
|---|
def _stringify(s):
"""Convert input to string, wrap with quotes if already a string"""
return '"{}"'.format(s) if isinstance(s, str) else str(s) |
def decode_dict(value):
"""Recursively converts dictionary keys to strings."""
if not isinstance(value, dict):
if isinstance(value, bytes):
return value.decode()
else:
return value
return {k.decode(): decode_dict(v) for k, v in value.items()} |
def is_prime(n):
"""Checks if the argument n is a prime number. Returns True if it is, False otherwise."""
# 1 is not prime by definition
if n <= 1:
return False
# check up to sqrt(n) + 1 if there exists a number that divides n
for divisor in range(2, int(n ** 0.5) + 1):
if n % divi... |
def rerun_probability(n_runs):
"""
Calculates a probability for running another episode with the same
genome.
"""
if n_runs <= 0:
return 1
return 1 / n_runs**2 |
def constructCorpus(contigs, classMap, binary, target):
"""
Construct a corpus, or body of training data for the decision tree, as well as the data under test.
Args:
contigs: A list of sidr.common.Contig objects with test variables.
classMap: A dictionary mapping class names to their class ... |
def base_dir_length(base_dir_path):
"""Return the length of a base directory path, including the last '/'."""
if not base_dir_path.endswith('/'):
return len(base_dir_path) + 1
return len(base_dir_path) |
def _merkle_concat(left: bytes, right: bytes) -> bytes:
""" Concatenate two byte sequences in the way that works without altering the hashing function.
"""
return bytes(reversed(left)) + bytes(reversed(right)) |
def linspace(start, stop, num, decimals=6):
""" Returns a list of evenly spaced numbers over a specified interval.
Inspired from Numpy's linspace function: https://github.com/numpy/numpy/blob/master/numpy/core/function_base.py
:param start: starting value
:type start: float
:param stop: end value
... |
def split_intervals_by_boundaries(intervals, boundaries):
""" Splits every interval by every boundary
:param intervals:
list of intervals
:param boundaries:
set of boundaries
"""
boundaries = sorted(list(boundaries))
splitted_intervals = []
for i in intervals:
bitoffset, bitsize = i... |
def validate_config(config):
"""Validate configuration"""
errors = []
required_config_keys = [
'host',
'port',
'user',
'password',
'dbname'
]
# Check if mandatory keys exist
for k in required_config_keys:
if not config.get(k, None):
er... |
def gen_k1_graph_in(size: int) -> str:
""" Generate K1 graph input
:param size: size of graph
"""
input_graph = f"{size} {size}"
for i in range(size // 2):
input_graph += f" {i*2} {i*2+1} 1"
input_graph += f" {i*2+1} {i*2} 1"
return input_graph |
def reporting_level_status(election, reporting_level):
"""
Get the availability of results for a reporting level
This uses provisional logic to prepare the metadata for the website
launch for ONA 2014. It is designed to show the likely availability of
results with a minimum of backfilling the '{re... |
def model_id_match(match_list, id_tuple):
"""Matches `id_tuple` to the list of tuples `exception_list`, which can contain
wildcards (match any entry) and lists (match any entry that is in the list).
Parameters
----------
match_list : list
list of tuples with id strings corresponding to e.g.... |
def _indent(string, indent_level=4):
"""Indent each line by `indent_level` of spaces."""
return '\n'.join('%s%s' % (' '*indent_level, x) for x in
string.splitlines()) |
def epochTime(startTime: int, endTime: int):
"""Calculate elapsed (elapsedMins, elapsedSecs) of epoch"""
elapsedTime = endTime - startTime
elapsedMins = int(elapsedTime / 60)
elapsedSecs = int(elapsedTime - (elapsedMins * 60))
return elapsedMins, elapsedSecs |
def modify(phones, rule, match_result):
"""
Modify the phones list by rule.
:param phones:
:param rule:
:param match_result:
:return: a new phones list modified according to the rule.
"""
new_phones = []
new_phones.extend(phones[:match_result[1]])
new_phones.append(rule... |
def points_equal(a, b):
"""
checks if 2 [x, y] points are equal
"""
for i in range(0, len(a)):
if a[i] != b[i]:
return False
return True |
def getSep(path, pattern='/\\'):
"""
Get path separator or indicator.
:param path: relative or absolute path (str).
:param pattern: guess characters to compare path (str).
:return: sep (str).
.. note:: It is equivalent to os.path.sep but obtained from the given path and patterns.
"""
i... |
def normalize_output_name(output_name):
"""Remove :0 suffix from tensor names."""
return output_name.split(":")[0] if output_name.endswith(
":0") else output_name |
def get_waze_navigation_link(xy_tuple):
"""
Create a navigation link from a tuple containing an x and y tuple for Waze.
:param xy_tuple: Tuple of (x,y) coordinates.
:return: String url opening directly in waze for navigation.
"""
return 'waze://?ll={lat},{lon}&navigate=yes'.format(lat=xy_t... |
def return_segments(shape, break_points):
"""Break a shape into segments between stops using break_points.
This function can use the `break_points` outputs from
`find_segments`, and cuts the shape-sequence into pieces
corresponding to each stop.
"""
# print 'xxx'
# print stops
# print s... |
def clean_word(word):
"""
word (str): word to clean
Returns word with specific special characters removed
"""
string = ''
for c in word:
if c in [',', '!', '?', '.', '(', ')', '"']:
continue
string += c
return string |
def argsort(indexable, key=None, reverse=False):
"""
Returns the indices that would sort a indexable object.
This is similar to np.argsort, but it is written in pure python and works
on both lists and dictionaries.
Args:
indexable (list or dict): indexable to sort by
key (Function... |
def find_short(s):
""" Given a string of words, return the length of the shortest word(s)."""
return min(len(x) for x in s.split()) |
def _dict_to_tuple(d):
"""
Recursively converts a dictionary to a list of key-value tuples
Only intended for use as a helper function inside memoize!!
May break when keys cant be sorted, but that is not an expected use-case
"""
if isinstance(d, dict):
return tuple([(k, _dict_to_tuple(d[k... |
def int_to_unknown_bytes(num, byteorder='big'):
"""Converts an int to the least number of bytes as possible."""
return num.to_bytes((num.bit_length() + 7) // 8 or 1, byteorder) |
def disappear_round_brackets(text):
"""
:param text:
:return:
>>> disappear_round_brackets("trib(unus) mil(itum) leg(ionis) III")
'tribunus militum legionis III'
"""
text = text.replace("(", "")
return text.replace(")", "") |
def full_term_match(text, full_term, case_sensitive):
"""Counts the match for full terms according to the case_sensitive option
"""
if not case_sensitive:
text = text.lower()
full_term = full_term.lower()
return 1 if text == full_term else 0 |
def __to_float(num):
"""
Try to convert 'num' to float, return 'num' if it's not possible, else
return converted :code:`num`.
"""
try:
float(num)
return float(num)
except ValueError:
return num |
def guess_data_type(shape, risky=False):
"""Infer the type of data based on the shape of the tensors
Arguments:
risky(bool): some guesses are more likely to be wrong.
"""
# (samples,) or (samples,logits)
if len(shape) in (1, 2):
return "label"
# Assume image mask like fashion mn... |
def divide(a: int, b: int) -> int:
"""
>>> divide(10, 2)
5
>>> divide(10, 0)
Traceback (most recent call last):
...
ValueError: divisor can't be zero
"""
try:
return a // b
except ArithmeticError:
raise ValueError("divisor can't be zero")
finally:
pass |
def flatten(inp):
"""
The function to flatten a nested list or tuple of lists, tuples or ranges,
with any number of nested levels.
From StackOverflow by James Brady (http://stackoverflow.com/users/29903/james-brady)
http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python/406822... |
def stdout2html(string):
"""
This function takes the output of stdout and formats it to be shown as basic html.
Our main sources of stdout are the bash scripts to update grammars, which include
ACE output when compiling grammars. The changes included here are on a necessity basis.
"""
r = strin... |
def flatten_dict(d):
"""
Function to transform a nested dictionary to a flattened dot notation dictionary.
:param d: Dict
The dictionary to flatten.
:return: Dict
The flattened dictionary.
"""
def expand(key, value):
if isinstance(value, dict):
return [(key... |
def truncate_str(input_str, maxstr_len=512):
"""
:param input_str:
:return:
"""
if input_str is None:
return input_str
if len(input_str) <= maxstr_len:
return input_str
return input_str[0:maxstr_len] + '...' |
def linear_damped_SHO(t, U):
"""x' = -0.1x+2y
y' = -2x-0.1y
"""
return [-0.1 * U[0] + 2 * U[1], -2 * U[0] - 0.1 * U[1]] |
def __combine_windows(w1, w2):
"""
Joins two windows (defined by tuple of slices) such that their maximum
combined extend is covered by the new returned window.
"""
res = []
for s1, s2 in zip(w1, w2):
res.append(slice(min(s1.start, s2.start), max(s1.stop, s2.stop)))
return tuple(res) |
def get_local_rl(module, blade):
"""Return Bucket Replica Link or None"""
try:
res = blade.bucket_replica_links.list_bucket_replica_links(
local_bucket_names=[module.params["name"]]
)
return res.items[0]
except Exception:
return None |
def sorted_ext_names(config, ext_names):
"""Sort extensions if `EXT_ORDER` is specified. Extensions not listed in
`EXT_ORDER` will be appended to the end of the list in an arbitrary order.
"""
ext_order = [e.strip() for e in config['EXT_ORDER'].split(',')]
def sort_key(ext_name):
try:
... |
def check_strand(strand):
""" Check the strand format. Return error message if the format is not as expected. """
if (strand != '-' and strand != '+'):
return "Strand is not in the expected format (+ or -)" |
def _closest_line_num(fil, orig_line_num, orig_line):
"""
Find the line in @fil that best matches the @orig_line found at
@orig_line_num.
This is currently done by:
- finding all the lines in @fil that, when stripped, match the
@orig_line exactly
- returning the number the matching line... |
def _none_str(value):
"""Shorthand for displaying a variable as a string or the text None"""
if value is None:
return 'None'
else:
return "'{0}'".format(value) |
def parse_geometry(s):
"""Parse a WxH geometry string."""
cols, rows = s.split('x')
cols = int(cols.strip())
rows = int(rows.strip())
return rows, cols |
def get_sound_effect_for_answer(answer_was_right):
"""get the appropriate sound effect"""
print("=====get_sound_effect_for_answer fired...")
print("=====answer_was_right: " + str(answer_was_right))
if answer_was_right is None:
return ""
if answer_was_right:
return "<audio src=\"http... |
def patch_name(tile_id, patch_id):
"""
convert the nth tile in a string which is padded with 0 up to tile_max_len positions
convert the nth tile in a string which is padded with 0 up to patch_max_len positions
:param tile_id: number of actual tile
:param patch_id: number of actual patch
:return:... |
def get_slotted_joint_adds(joint, _, parameters):
"""generator for slotted joints"""
"""Nothing to add for slotted"""
adds = {}
return adds |
def get_ratio(C):
"""Get a/b representation of a continued fraction."""
a, b = 1, 0
for x in reversed(C):
a, b = b + a * x, a
return a, b |
def soil_variable(WLM, WUM, WDM, WU, WL, WD, S0, SM):
"""
Analyze the inputs for soil water to make sure that the input variables are of consistence.
"""
if WU > WUM:
WL = WL + WU - WUM
WU = WUM
if WL > WLM:
WD = WD + WL - WLM
WL = WLM
if WD > WDM: WD = WDM... |
def build_response(session_attributes, speechlet_response):
""" Build Response """
return {
'version': '1.0',
'sessionAttributes': session_attributes,
'response': speechlet_response
} |
def flatten_fos(row):
"""Flatten field of study info into a list
Args:
row (dict): Row of article data containing a field of study field
Returns:
fields_of_study (list): Flat list of fields of study
"""
return [f for fields in row['fields_of_study']['nodes']
for f in fie... |
def is_number(s):
""" Is input string a number """
try:
dummy = float(s)
return True
except ValueError:
return False |
def set_reqe_user_agent(name='https://github.com/ophlr/reqe'):
"""
Return a string representing the default user agent.
:rtype: str
"""
return '%s' % name |
def _get_str_value(loc_json: dict, key_to_find: str, language: str = 'en') -> str:
""" Return a string value associated with key_to_find['@value'] given a key_to_find and language """
for item in loc_json.get(key_to_find, []):
# Note: "http://id.loc.gov/authorities includes @language for given nodes BU... |
def _prefix_keys(results: dict, prefix: str) -> dict:
"""
Add a prefix to existing keys
Args:
results (dict): The dictionary of results
prefix (str): A string to prefix each key with
Returns:
dict: The result dictionary with prefixed keys.
"""
prefixed = {}
for key,... |
def twochannel37(tb37v, tb37h, tiepts):
"""Simple 2 channel algorithm 37 GHz
"""
ow37v = tiepts[0]
ow37h = tiepts[3]
fy37v = tiepts[2]
fy37h = tiepts[5]
my37v = tiepts[1]
my37h = tiepts[4]
cf = ((tb37h - ow37h)*(my37v - ow37v) - (tb37v - ow37v)*(my37h - ow37h))/((fy3... |
def clean_name(name):
"""
Cleans a proposed character name.
"""
new_name = ''.join(ch for ch in name if ch.isalpha())
new_name = new_name.title()
return new_name |
def set_intersection(*args):
"""Finds intersection of n number of sets"""
result = set(args[0])
for i in range(1, len(args)):
result = result & args[i]
return result |
def uses_only(w, s):
"""
Check if the word consists only of the characters specified in a string.
Return False if it does not
"""
for l in w:
if s.find(l) == -1:
return False
return True |
def get_website(text):
"""Extracts the website which should be the penultimate value in a string split on spaces"""
strings = text.split()
# strings should now have all the items in our line separated by spaces,
# we want the penultimate one..
website_string = strings[len(strings) - 2]
return we... |
def _liftover_data_path(data_type: str, version: str) -> str:
"""
Paths to liftover gnomAD Table.
:param data_type: One of `exomes` or `genomes`
:param version: One of the release versions of gnomAD on GRCh37
:return: Path to chosen Table
"""
return f"gs://gnomad-public-requester-pays/relea... |
def verify_json_data(data: object) -> bool:
"""
Checks whether the data if of the followgin schema:
{
"alias_key": "command"
}
both must be of type string
"""
if isinstance(data, dict):
if all(isinstance(i, str) for i in data) and all(isinstance(i, str) for i in data.values... |
def format_str(x):
"""Format as string if a value is missing or bool."""
if x is None:
return ""
elif isinstance(x, bool):
return "true" if x else "false"
else:
return str(x) |
def delete_comments(line):
"""Deletes comments in parentheses from a line."""
fields = line.split(')')
result = []
for f in fields:
if '(' in f:
result.append(f.split('(',1)[0])
else:
result.append(f)
return ''.join(result) |
def should_break_line(node, profile):
"""
Need to add line break before element
@type node: ZenNode
@type profile: dict
@return: bool
"""
if not profile['inline_break']:
return False
# find toppest non-inline sibling
while node.previous_sibling and node.previous_sibling.is_inline():
node = node.previous... |
def merge_dicts(dict_a, dict_b):
"""Return dict issue from merge from dict_a and dict_b, dict_a having precedence"""
# inspired from https://stackoverflow.com/questions/7204805/dictionaries-of-dictionaries-merge/7205107#7205107
if not dict_a:
return dict_b
if not dict_b:
return dict_a
... |
def decrement_arr(array,decrement=1):
"""
#### returns an decremented array
#### Example:
x = [1,2,3,4,5]
decrement_arr(x)
### print(x)
### [0, 1, 2, 3, 4]
"""
for num in range(len(array)):
array[num]=array[num]-decrement
return array |
def tell_me_about(s):
"""Return a tuple containing the type of the input string and the input
string itself.
"""
return (type(s), s) |
def merge_list_to_dict(test_keys,test_values):
"""Using dictionary comprehension to merge two lists to dictionary"""
merged_dict = {test_keys[i]: test_values[i] for i in range(len(test_keys))}
return merged_dict |
def _reduce_shapesdict(shapes_dict):
"""Iteratively remove elements from shapes dictionary with falsy values."""
for shape in shapes_dict["shapes"]:
for sc in shape["statement_constraints"]:
if sc.get("extra_elements"):
for (k, v) in sc["extra_elements"].items():
... |
def first_client(clients, flag_shift):
"""
Returns the first client what allows the specified intent flag. If no client allows it, then returns `None`.
Parameters
----------
clients : `list` of ``Client``
A list of client to search from.
flag_shift : `int`
The intent flag's ... |
def add_default_copy_options(copy_options=None):
"""Adds in default options for the ``COPY`` job, unless those specific
options have been provided in the request.
Parameters
----------
copy_options : list, optional
List of copy options to be provided to the Redshift copy command
Return... |
def _get_chars(qrcode_chars: list) -> list:
"""
Retrieves the set of characters that make up the QR code.
:param qrcode_chars: The ASCII QR code.
:return: A list of two QR code characters.
"""
first_char = qrcode_chars[0][0]
for line in qrcode_chars:
for c in line:
if c !... |
def RgbToHsv(RGB):
""" Converts an integer RGB tuple (value range from 0 to 255) to an HSV tuple """
# Unpack the tuple for readability
R, G, B = RGB
# Compute the H value by finding the maximum of the RGB values
RGB_Max = max(RGB)
RGB_Min = min(RGB)
# Compute the value
V = RGB_Max
i... |
def calc_npv(true_neg, false_neg):
"""
function to calculate negative predictive value
Args:
true_neg: Number of true negatives
false_neg: Number of false negatives
Returns:
None
"""
try:
npv = true_neg / float(true_neg + false_neg)
return round(npv, 3)
except BaseException:
retu... |
def hex_to_dec(hex_code):
"""
Converts from a 6 digit hexadecimal value with a leading hash to a list of 3 decimal values.
"""
conversion_dict = {"A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15,
"a": 10, "b": 11, "c": 12, "d": 13, "e": 14, "f": 15}
hex_code = hex_code[1:... |
def get_widths(rows, start_counts=None):
"""
Return an list of integers of widest values for each column in ``rows``.
If ``start_counts`` is not given, the return value is initialized to all
zeroes.
:param rows: Sequence of sequences representing rows
:param list start_counts: Optional start c... |
def convert_coord(coord_line):
"""
coord_line is in this format: <x=5, y=-1, z=5>
"""
coord_list = coord_line.replace('<', '').replace('>', '').split(',')
return tuple([int(coord.split('=')[1]) for coord in coord_list]) |
def find_parentheses(s):
""" Find and return the location of the matching parentheses pairs in s.
Given a string, s, return a dictionary of start: end pairs giving the
indexes of the matching parentheses in s. Suitable exceptions are
raised if s contains unbalanced parentheses.
Source: https://sci... |
def font_info(
family='arial',
color='black',
weight='normal',
size=8
):
"""
"""
font_additional_info = {
'family': 'arial',
'color': 'black',
'weight': 'normal',
'size': size}
return font_additional_info |
def check_sign(trend_data, var):
"""Check the sign of the trend"""
if 'easterly_magnitude' in var:
trend_data = trend_data * -1
return trend_data |
def y_gate_counts_deterministic(shots, hex_counts=True):
"""Y-gate circuits reference counts."""
targets = []
if hex_counts:
# Y
targets.append({'0x1': shots})
# YY = I
targets.append({'0x0': shots})
# HYH = -Y
targets.append({'0x1': shots})
else:
... |
def build_style_name(data, width_key, weight_key, custom_key, italic):
"""Build style name from width, weight, and custom style strings in data,
and whether the style is italic.
"""
italic = 'Italic' if italic else ''
width = data.pop(width_key, '')
weight = data.pop(weight_key, 'Regular')
... |
def check_input(s: dict, i: int):
"""Checks to see if user supplied input is in a dictionary
:param s<dict>: Dictionary with options to check against
:param i<int>: Integer value to check if it exists as a key in `s`
"""
if i in s.keys():
return s[i]
else:
return False |
def convert_square(square,is_white):
"""Convert int to find row and colomn
Args:
square (int): case number of the piece on the board
is_white (bool): if the piece is white
Returns:
Array: array composed with the row and the colomn of the piece
"""
if(is_white):
row ... |
def side_len(ring):
"""
>>> side_len(0)
1
>>> side_len(1)
2
>>> side_len(2)
4
>>> side_len(3)
6
"""
if ring == 0:
return 1
else:
return ring * 2 |
def mirrorBoard(b):
"""b is a 64-bit score4 board
Return: a mirrored board as follow (looking from above)
C D E F 0 1 2 3
8 9 A B ==> 4 5 6 7
4 5 6 7 8 9 A B
0 1 2 3 C D E F
"""
return (b & 0x000F000F000F000F) << 12 \
| (b & 0x00F000F000F000F0) << 4 ... |
def safe_index(elements, value):
"""Find the location of `value` in `elements`, return -1 if `value` is
not found instead of raising ``ValueError``.
Parameters
----------
elements : Sequence
value : object
Returns
-------
location : object
Examples
--------
>>> sequenc... |
def simplified_tag(t):
"""
Returns a simplified POS tag:
NP-SBJ -> NP
PP=4 -> PP
-RRB- -> -RRB-
"""
if t == None:
return None
if t[0:1] == "-":
return t
else:
caret_pos = t.find("-")
t_minus_caret = ""
... |
def dir_list_no_dunder2(string):
"""Reduce the list to only the dunder methods using list comprehension
Args:
string (str): argument
Returns:
[list]: [list of string object methods without dunder methods]
"""
return [item for item in dir(string) if not item.startswith("__")] |
def steps_to_list(string_literal):
"""Takes a comma separated list and returns a list data type."""
new_list = []
for item in string_literal.split(','):
new_list.append(item)
return new_list |
def parse_cmd_line_argv(argv) -> list :
""" Parse arguments by scheme - ``--<key>=<value>`` """
result = list()
for arg in argv :
if not isinstance(arg, str) or len(arg) == 0 :
continue
if len(arg) <= 2 or (arg[0] != '-' and arg[1] != '-') :
result.append(["", arg])
continue
name_e... |
def parse_attendance_dict_to_html_string(presence_dict: dict) -> str:
""" Returns string data wrapped into HTML tags """
parsed_data_string = ""
for name, is_present in presence_dict.items():
if is_present:
parsed_data_string += f'<p>{name} <i class="fas fa-check present"></i></p>'
... |
def all_of(pred, iterable):
"""
Returns ``True`` if ``pred`` returns ``True`` for all the elements in
the ``iterable`` range or if the range is empty, and ``False`` otherwise.
>>> all_of(lambda x: x % 2 == 0, [2, 4, 6, 8])
True
:param pred: a predicate function to check a value from th... |
def _get_yaml_path(path, parameter):
"""Compose the parameter path following the YAML Path standard.
Standard: https://github.com/wwkimball/yamlpath/wiki/Segments-of-a-YAML-Path#yaml-path-standard
"""
yaml_path = []
if path:
yaml_path.extend(path)
if parameter:
yaml_path.append(... |
def hello_get(request):
"""Returns Hello in JSON."""
return {'Hello': 'World'} |
def subp_args(args):
"""
According to subcommand, when using shell=True, its recommended not to pass in an argument list but the full command line as a single string.
That means in the argument list in the configuration make sure to provide the proper escapements or double-quotes for paths with spaces
... |
def argmax(x):
"""
Returns the index of the largest element of the iterable `x`.
If two or more elements equal the maximum value, the index of the first
such element is returned.
>>> argmax([1, 3, 2, 0])
1
>>> argmax(-abs(x) for x in range(-3, 4))
3
"""
argmax_ = None
max_... |
def default_if_empty(value, arg):
"""
Set default one if the value is empty.
String: None, ''
Integer: None, 0
"""
if not value:
return arg
return value |
def repr_float_precision(f, round_fn):
"""
Get's the value which was most likely entered by a human in C.
Needed since Python will show trailing precision from a 32bit float.
"""
f_round = round_fn(f)
f_str = repr(f)
f_str_frac = f_str.partition(".")[2]
if not f_str_frac:
return... |
def color(s, color_int):
"""color_int: 30 Gray,31 Red,32 Green,33 Yellow,34 Blue,
35 Magenta,36 Cyan,37 White,38 Crimson,41-48 highlighted
"""
return "\033[1;%dm%s\033[1;m" % (color_int, s) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.