content stringlengths 42 6.51k |
|---|
def _GenerateAdditionalProperties(values_dict):
"""Format values_dict into additionalProperties-style dict."""
props = [{'key': k, 'value': v} for k, v in sorted(values_dict.items())]
return {'additionalProperties': props} |
def get_github_stars(github_page_data):
"""Retrieve number of github stars from github data"""
num_stars = "No github found"
if github_page_data["github_page"]:
# If data on github comes form github API, parse json
if github_page_data["github_data_source"] == "API":
num_stars =... |
def validate_data_transfer(expected_data, s_client_out, s2nd_out):
"""
Verify that the application data written between s_client and s2nd is encrypted and decrypted successfuly.
"""
found = 0
for line in s2nd_out.splitlines():
if expected_data in line:
found = 1
brea... |
def _ensure_lists(length, args):
"""Make sure each argument is a list of the same length as ``commands``.
This works only if the value of each argument cannot be of list type.
"""
for var_idx, val in enumerate(args):
if not isinstance(val, list):
args[var_idx] = [val] * length
... |
def _create_query_dict(query_text):
"""
Create a dictionary with query key:value definitions
query_text is a comma delimited key:value sequence
"""
query_dict = dict()
if query_text:
for arg_value_str in query_text.split(','):
if ':' in arg_value_str:
... |
def map_missing_dict_keys(y_pred, struct):
"""Replaces missing dict keys in `struct` with `None` placeholders."""
if not isinstance(y_pred, dict) or not isinstance(struct, dict):
return struct
for k in y_pred.keys():
if k not in struct:
struct[k] = None
return struct |
def find_first_between(string, left, right):
""" Find first string in `string` that is between two strings `left` and `right`. """
start = string.find(left)
if start != -1:
end = string.find(right, start + len(left))
if end != -1:
return string[start + len(left):end] |
def convert_param_step(mr_old):
"""
For pure forecast with steps greater than 23 hours, the older versions
writes out a list of steps instead with the syntax 'to' and 'by'.
e.g. 000/003/006/009/012/015/018/021/024/027/030/033/036
Convert this to 0/to/36/by/3
"""
#if 'to' in str(mr_ol... |
def multiselect_dict_to_list(environment, dict_multiselect):
""" return list of keys in a dictionary who's values are True """
keys_list = []
for key, val in dict_multiselect.items():
if val:
keys_list.append(key)
return keys_list |
def pick_composite_transform_from_list(composite_transform_as_list):
"""
This function...
:param composite_transform_as_list:
:return:
"""
if isinstance(composite_transform_as_list, str):
return composite_transform_as_list
return composite_transform_as_list[0] |
def long_substr(data: list) -> str:
"""
https://stackoverflow.com/questions/2892931/\
longest-common-substring-from-more-than-two-strings-python#
"""
substr = ""
if len(data) > 1 and len(data[0]) > 0:
for i in range(len(data[0])):
for j in range(len(data[0]) - i + 1):
... |
def GenerateSingleQueryParameter(name, param_type, param_value):
"""Generates a single valued named parameter.
Args:
name: name of the parameter.
param_type: Type of the parameter. E.g. STRING, INT64, TIMESTAMP, etc.
param_value: Value of this parameter.
"""
return {
'name': name,
'para... |
def get_inventory_file(config: dict, options: dict):
"""
Function returning relativ path to inventory file.
:param config:
:param options:
:return:
"""
inv_file = None
for item in config["infra"]:
if item["name"] == options["infra"]:
for elem in item["stages"]:
... |
def _convert_list_of_objs_to_list_of_dicts(list_of_objects):
"""
Recursively convert a list of objects to a list of dicts.
This works recursively and is needed because the NLP Textanalyzer
sometimes gives back a list of non-json-serializable objects, which
need to be converted to dicts. The list st... |
def is_xyz_space(obj):
""" True if `obj` appears to be an XYZ space definition """
return (hasattr(obj, 'x') and
hasattr(obj, 'y') and
hasattr(obj, 'z') and
hasattr(obj, 'to_coordsys_maker')) |
def Color(red, green, blue):
"""Return the provided red, green, blue colors as a list.
Each color component should be a value 0-255 where 0 is the lowest intensity
and 255 is the highest intensity.
red, green, blue: int, 0-255
return: list
"""
rgb = [red, green, blue]
return rgb |
def merge_prems_and_housholds(premises_data, household_data):
"""
Merges two aligned datasets, zipping row to row.
Deals with premises_data having multiple repeated dict references due to expand function.
"""
result = [a.copy() for a in premises_data]
[a.update(b) for a, b in zip(result, house... |
def _get_float_val(string):
"""
returns the last word in a string as a float
"""
return float(string.split()[-1]) |
def eliminate_subpaths(masterList, path):
"""Return a path list with the sub paths removed."""
subPaths = [path[0:i] for i in range(len(path)+1)]
listCopy = masterList[:]
for list_ in masterList:
for subPath in subPaths:
if list_ == subPath:
listCopy.remove(... |
def is_nondecreasing(arr):
""" Returns true if the sequence is non-decreasing. """
return all([x <= y for x, y in zip(arr, arr[1:])]) |
def apply_replace_map(text, replace_map):
"""Apply replace map to a text.
:type text: str
:type replace_map: dict[str, str]
:param text: The text.
:param replace_map: The map.
"""
# Do replacing.
for to_replace in replace_map:
text = text.replace(to_replace, replace_map[to_rep... |
def merge_dicts(left, right, overwrite=True):
"""Merges two dictionaries.
Values of right dictionary recursively get merged into left dictionary.
:param left: Left dictionary.
:param right: Right dictionary.
:param overwrite: If False, left value will not be overwritten if exists.
"""
if l... |
def clean_debian_comma_logic(exp):
"""
Convert an ``exp`` expression with Debian specific logic regarding comma to
a parsable license expression.
For example:
>>> clean_debian_comma_logic('lgpl-3 or gpl-2, and apache-2.0')
'(lgpl-3 or gpl-2) and (apache-2.0)'
"""
subexps = []
while ... |
def xor_hex_strings(str1, str2):
"""
Return xor of two hex strings.
An XOR of two pieces of data will be as random as the input with the most randomness.
We can thus combine two entropy sources in this way as a safeguard against one source being
compromised in some way.
For details, see http://c... |
def subarraySum(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if not nums:
return 0
tally = {0:1}
n = len(nums)
count = 0
s = 0
for num in nums:
s += num
if s - k in tally:
count += tally[s-k]
if s in tally:
... |
def hsv_to_rgb(h, s, v):
"""Converts HSV value to RGB values
Hue is in range 0-359 (degrees), value/saturation are in range 0-1 (float)
Direct implementation of:
http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_HSV_to_RGB
"""
h, s, v = [float(x) for x in (h, s, v)]
hi = (h / 60) % ... |
def strconv(ch):
"""return ch if already a string; otherwise return its str as it will be a number"""
if isinstance(ch, str):
return ch
else:
return str(ch) |
def _guess_type(edge):
"""
Backfill old journals. New journals will have the type built into the videomasks.
:param edge:
:return:
@type edge: dict
"""
return 'audio' if edge['op'].find('Audio') >= 0 else 'video' |
def index_of(an_element, a_list):
""" Function to find index of an element in a list """
for i in range(0, len(a_list)):
if a_list[i] == an_element:
return i
return -1 |
def to_perc(value):
"""Convert hex value to percentage."""
return value * 100 / 255 |
def manifest_header(type_name, version='1.0'):
"""Returns a header, suitable for use in a manifest.
>>> manifest_header("signature")
"Signature-Version: 1.0"
:param type_name: The kind of manifest which needs a header:
"manifest", "signature".
:param version: The manifest version to encode... |
def lookup(predicate, collection, default=None):
"""
Looks up the first value in *collection* that satisfies
*predicate*.
"""
for e in collection:
if predicate(e):
return e
return default |
def IsInRange(observed, min_val, max_val):
"""Returns True if min_val <= observed <= max_val.
If any of min_val or max_val is missing, it means there is no lower or
upper bounds respectively.
"""
if min_val is not None and observed < min_val:
return False
if max_val is not None and observed > max_val:
... |
def complex_reverse(in_dict):
"""Complex reverse."""
tmp_values = set(in_dict.values())
out_dict = {v: [] for v in tmp_values}
# pylint: disable=invalid-name
for k, v in in_dict.items():
out_dict[v].append(k)
return out_dict |
def parity(lst):
"""
Finds parity of a list of numbers
"""
parity = 1
for i in range(0,len(lst)-1):
if lst[i] != i:
parity *= -1
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i],lst[mn] = lst[mn],lst[i]
return parity |
def tripleMap(fun, l):
"""
Returns a new list r where each element in r is fun(fun((fun(i))) for the
corresponding element i in l
:param fun: function
:param l: list
:return: list
"""
# Fill in
newL = []
for i in l:
t = fun(fun(fun(i)))
newL.append(t)
... |
def create_argument_list_wrapped(arguments):
"""Create a wrapped argument list, remove trailing ',' """
argument_list = ''
length = 0
for argument in arguments:
argument_list += argument + ','
length += len(argument)+1
# Split args so that lines don't exceed 260 characters (for P... |
def IsInt(str):
""" Is the given string an integer? """
ok = True
try:
num = int(str)
except ValueError:
ok = False
return ok |
def g(x, y):
"""
A multivariate function for testing on.
"""
return -x**2 + y |
def letter_to_num(letter):
"""Returns the distance from 'a' of a character
letter_to_num('a') == 0, letter_to_num('y') == 24"""
return ord(letter) - 97 |
def get_subtraces(trace, i):
"""
Trisects one trace at time point i into a list of (t_past, t_present, t_future)
:param trace: One trace (a list of states in time)
:param i: A time instance at which the trace is to be trisected
:return: a tuple of (t_past, t_present, t_future)
"""
if i == f... |
def do_duration(seconds):
"""Jinja template filter to format seconds to humanized duration.
3600 becomes "1 hour".
258732 becomes "2 days, 23 hours, 52 minutes, 12 seconds".
"""
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
tokens = []
if d > 1:
tokens... |
def is_proto_only_paramater(parameter: dict):
"""Whether the parameter is only included in the proto file and not the driver API."""
return parameter.get("proto_only", False) |
def read_vx(pointdata):
"""Read a variable-length index."""
if pointdata[0] != 255:
index= pointdata[0]*256 + pointdata[1]
size= 2
else:
index= pointdata[1]*65536 + pointdata[2]*256 + pointdata[3]
size= 4
return index, size |
def _int_to_riff(i: int, length: int) -> bytes:
"""Convert an int to its byte representation in a RIFF file.
Represents integers as unsigned integers in *length* bytes encoded
in little-endian.
Args:
i (int):
The integer to represent.
length (int):
The number of... |
def _std_string(s):
"""Cast a string or byte string to an ASCII string."""
return str(s.decode('US-ASCII')) |
def get_noise_range(db: float) -> int:
"""Returns the lower limit of one of the six pre-defined dB ranges based on dB.
"""
if db >= 70.0:
return 70
elif db >= 65.0:
return 65
elif db >= 60.0:
return 60
elif db >= 55.0:
return 55
elif db >= 50.0:
return... |
def is_low_point(data: list, i: int, j: int) -> bool:
"""
Return whether the neighboring numbers are all higher or not
"""
p = data[i][j]
if j > 0 and p >= data[i][j - 1]:
return False
if j < len(data[0]) - 1 and p >= data[i][j + 1]:
return False
if i > 0 and p >= data[i - 1... |
def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile |
def _is_dictionary_with_integer_keys(candidate):
"""Infer whether the argument is a dictionary with integer keys."""
return isinstance(candidate, dict) and all(
isinstance(key, int) for key in candidate
) |
def determine_block_positions(lines, block_start_marker, block_end_marker):
"""Determine the line indices of a block in a list of lines indicated by a given start and end marker.
:param lines: list of strings
:param block_start_marker: string marking the beginning of the block
:param block_end_marker: ... |
def flatten(lst):
"""Flatten a list of lists to a list."""
return sum(lst, []) |
def parse_secs_to_str(duration=0):
"""
Do the reverse operation of :py:func:`parse_str_to_secs`.
Parse a number of seconds to a human-readable string.
The string has the form XdXhXmXs. 0 units are removed.
:param int duration: The duration, in seconds.
:return: A formatted string containing th... |
def print(*args, **kwargs):
"""
Currently no purpose.
"""
return __builtins__.print(*args, **kwargs) |
def create_empty(val=0x00):
"""Create an empty Userdata object.
val: value to fill the empty user data fields with (default is 0x00)
"""
user_data_dict = {}
for index in range(1, 15):
key = "d{}".format(index)
user_data_dict.update({key: val})
return user_data_dict |
def invert_yang_modules_dict(in_dict, debug_level):
"""
Invert the dictionary of key:draft name, value:list of YANG models
Into a dictionary of key:YANG model, value:draft name
:param in_dict: input dictionary
:return: inverted output dictionary
"""
if debug_level > 0:
print("DEBUG:... |
def levenshtein_distance(s1: str, s2: str) -> int:
"""Returns the levenshtein distance between two strings"""
# https://stackoverflow.com/a/32558749
if len(s1) > len(s2):
s1, s2 = s2, s1
distances = range(len(s1) + 1)
for i2, c2 in enumerate(s2):
distances_ = [i2 + 1]
for i1... |
def try_int_to_str(val, max_dec=1024):
"""Make string from int. Hexademical representaion will be used if input value greater that 'max_dec'."""
if isinstance(val, int):
if val > max_dec:
return "0x%x" % val
else:
return "%d" % val
else:
return val |
def most_common(iterable):
"""
>>> most_common([1, 2, 2, 3, 4, 4, 4, 4])
4
>>> most_common(list('Anthony'))
'n'
>>> most_common('Stephen')
'e'
Exceptionally quick! Benchmark at 12.1 us
:param iterable:
:return:
"""
from collections import Counter
data = Counter(iter... |
def maximoEncabezado(nombreEncabezado,numDecisiones):
"""
maximo encabezado funcion que nos permite hacer un numero maximo
de encabezados.
@param nombre encabezado string
@param numDecision int
"""
nombre=""
lista=[]
for i in range(numDecisiones):
nombre=nombreEncabezado + "... |
def get_transcript_length(transcript_row, exon_lengths):
""" Compute the length of the supplied transcript model based on its
exons. Expected input format consists of a transcript row from a
TALON database. """
length = 0
start_exon = transcript_row['start_exon']
end_exon = transcript_r... |
def get_delete_nodes_query(node_label: str, id_name: str):
"""
build the query to delete a node by matching the node with the given property (id_name). The query will
have a parameter $id which is the matched value for the "id_name" property
:param node_label: the label of the node to be deleted
:p... |
def sum_of_squared_digits(number):
"""
Returns the sum of squares of the digits of a number
"""
sum = 0
while number > 0:
digit = number%10
number = number//10
sum += digit**2
return sum |
def handle021a(tokens):
"""
Processes the 021A (Hauptsachtitel) field. Currently, only subfield a and d are supported.
For details (in German), see: https://www.gbv.de/bibliotheken/verbundbibliotheken/02Verbund/01Erschliessung/02Richtlinien/01KatRicht/4000.pdf
:param tokens: a list of tokens of the fiel... |
def clean(s):
"""
Attempt to render the (possibly extracted) string as legible as possible.
"""
result = s.strip().replace("\n", " ")
result = result.replace("\u00a0", " ") # no-break space
result = result.replace("\u000c", " ") # vertical tab
while " " in result:
result = result.... |
def data_string_to_float(number_string):
"""
The result of our regex search is a number stored as a string, but we need a float.
- Some of these strings say things like '25M' instead of 25000000.
- Some have 'N/A' in them.
- Some are negative (have '-' in front of the numbers).
-... |
def filter_characteristic_properties(characteristic_dict):
"""
Takes the dict from a charactistic, and spits out a string of all the
properly formatted properties of that characteristic.
"""
property_name_mapping = {"@indicate": "indicate",
"@notify": "notify",
... |
def remove_known_traits(trait_names):
""" Remove the irrelevant trait names from a list of trait names in order to
get to the useful trait names.
Also, sort the list for ease of use in testing.
"""
return sorted([
x for x in trait_names
if x not in ('_context', '_synched', 'trait_ad... |
def fond(n):
"""
Cree un fond avec des murs sur les cotes
"""
t=[[1 for x in range(n)] for x in range(n)]
for x in range(n):
t[0][x]=2
t[x][0]=2
t[n-1][x]=2
t[x][n-1]=2
return(t) |
def _str2bool(text):
"""Convert string to boolean (PRIVATE)."""
if text == 'true' or text == '1':
return True
if text == 'false' or text == '0':
return False
raise ValueError('String could not be converted to boolean: ' + text) |
def force2bytes(s):
"""
Convert the given string to bytes by encoding it.
If the given argument is not a string (already bytes?), then return it verbatim.
:param s: Data to encode in bytes, or any other object.
:return: Bytes-encoded variant of the string, or the given argument verbatim.
"""
... |
def chemicallimits(rxndict):
"""Return the molarmins and maxes for each chemical in the run
:param rxndict:
:return:
"""
climits = {}
for k, v in rxndict.items():
if "chem" in k and "molarmin" in k:
climits[k] = v
if "chem" in k and "molarmax" in k:
climi... |
def preproc_bool(value):
"""Turn a preprocessor value into a boolean"""
if isinstance(value, bool):
line_val = value
else:
try:
ival = int(value)
line_val = ival != 0
except ValueError:
line_val = value != "0"
# end try
# end if
ret... |
def p(x,xtrue):
"""
Calculate percentage difference between two values
"""
return 100.0*(x-xtrue)/xtrue |
def sizeof_fmt(num: float, suffix: str = 'B') -> str:
"""
Formats a number of bytes in a human-readable binary format (e.g. ``2048``
becomes ``'2 KiB'``); from http://stackoverflow.com/questions/1094841.
"""
for unit in ('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi'):
if abs(num) < 1024.0:
... |
def is_valid_v4addr(addr):
"""check is ipv4 addr is valid"""
if not addr:
return False
if addr.find('.') != -1:
addr_list = addr.split('.')
if len(addr_list) != 4:
return False
for each_num in addr_list:
if not each_num.isdigit():
ret... |
def int_or_none(arg):
"""Returns None or int from a `int_or_none` input argument.
"""
if arg is None or str(arg).lower() == 'none':
return None
return int(arg) |
def is_multiline_comment_end(code, idx=0):
"""Position in string ends a multi-line comment."""
return idx-1 >= 0 and idx+1 <= len(code) and code[idx-1:idx+1] == '*/' |
def _bech32_polymod(values):
"""
Internal function that computes the Bech32 checksum
"""
generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
chk = 1
for value in values:
top = chk >> 25
chk = (chk & 0x1ffffff) << 5 ^ value
for i in range(5):
... |
def get_nominal(attribute):
"""If attribute is nominal, returns a list of the values"""
return attribute.split(',') |
def check_order(order: int) -> int:
"""Confirms the input is a valid parity order."""
if not isinstance(order, int):
raise TypeError("`order` must be an integer.")
if order <= 0:
raise ValueError("`order` must be greater than zero.")
return order |
def format_csv(factor_name, entry):
"""Format a data entry as a csv line."""
return "%s, %s, %s" % (entry[factor_name], entry['quarter'], entry['count']) |
def find_instance_in_args(obj, args):
"""find instance of given object type args.
Args:
obj(type): type of object to look for.
args(iterable): arguments to search for the given object type.
Returns:
obj. instance of the obj type that found in args.
"""
return next(filter(l... |
def merge_dicts(a, b, path=None):
""" Merge dict :b: into dict :a:
Code snippet from http://stackoverflow.com/a/7205107
"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dicts(a[key]... |
def no_odds(values):
"""
Finds all the even integers inside an array.
:param values: an array of integers.
:return: an array of even integers.
"""
return [x for x in values if x % 2 == 0] |
def shorten_unicode_message(message, max_length, ellipsis):
"""An internal specialized version of shorten_message() when the both the
message and ellipsis are str (in Python 3) or unicode (in Python 2).
"""
if max_length <= 0 or len(message) <= max_length:
# Nothing to shorten.
return me... |
def merge_two_dicts(first_dict, second_dict):
""" Merges two python dicts by making a copy of first then updating with second.
Returns a copy. """
return_dict = first_dict.copy() # start with x's keys and values
return_dict.update(
second_dict
) # modifies z with y's keys and values &... |
def union(bbox1, bbox2):
"""
:ivar bbox1: bounding box tuple (llx, lly, urx, ury).
:ivar bbox2: bounding box tuple (llx, lly, urx, ury) to aggregate with bbox1
:return: union of bbox1 and bbox2 as tuple, (llx, lly, urx, ury)
"""
llx = min(bbox1[0], bbox2[0])
lly = min(bbox1[1], bbox2[1])
... |
def title_phrase(value):
"""Converts a snake case key into a title with spaces"""
return value.replace("_", " ").title() |
def _overlap(x1,w1, x2, w2):
"""
A utility function for testing for overlap on a single axis. Returns true
if a line w1 above and below point x1 overlaps a line w2 above and below point x2.
"""
if x1+w1 < x2-w2: return False
if x1-w1 > x2+w2: return False
return True |
def parsemsg(s):
"""
Breaks a message from an IRC server into its prefix, command, and arguments.
"""
prefix = ''
tags = ''
if not s:
raise ValueError("Empty line.")
if s[0] == "@":
all_tags, s = s[1:].split(' ', 1)
tags = all_tags.split(";")
if s[0] == ':':
... |
def verse(number):
"""Create a verse"""
ordinal = {
1: "first",
2: "second",
3: "third",
4: "fourth",
5: "fifth",
6: "sixth",
7: "seventh",
8: "eighth",
9: "ninth",
10: "tenth",
11: "eleventh",
12: "twelfth"
}
... |
def top_sentences(query, sentences, idfs, n):
"""
Given a `query` (a set of words), `sentences` (a dictionary mapping
sentences to a list of their words), and `idfs` (a dictionary mapping words
to their IDF values), return a list of the `n` top sentences that match
the query, ranked according to idf... |
def flatten(arraytoflat):
"""docstring for flatten"""
def flatten_aux(arraytoflat, acc):
if arraytoflat:
head, *tail = arraytoflat
if type(head) is not str:
flatten_aux(head, acc)
flatten_aux(tail, acc)
else:
acc.append(... |
def _get_truncated_setting_value(value, max_length=None):
"""
Returns the truncated form of a setting value.
Returns:
truncated_value (object): the possibly truncated version of the value.
was_truncated (bool): returns true if the serialized value was truncated.
"""
if isinstance(va... |
def average(data):
"""Create a list containing 100 random integers between 0 and 1000 (use
iteration, append, and the random module). Write a function called average
that will take the list as a parameter and return the average."""
return sum(data)/len(data) |
def check_array_sorted(array) -> bool:
"""Checks if given array is sorted
Args:
array: list that shall be checked
Returns:
True if array is sorted, False in other case
"""
for i in range(len(array) - 1):
if array[i] > array[i + 1]:
return False
return True |
def get_r(x,y,z):
"""Get density r"""
den = x**2+z**2
return den |
def List_num_activity(Counter_num_activity):
"""Gets list from counter of number each activity was performed per individual."""
num_activity = [k for k in Counter_num_activity.keys()]
num_activity.sort()
counts_num_activity = [Counter_num_activity[v] for v in num_activity]
counts_num_activity_non_ze... |
def add_commas(num: int) -> str:
"""Adds commas to an integer in the international number format
- 1000 -> 1,000
- 100000 -> 100,000
- 1000000 -> 1,000,000
Args:
num (int): The number
Returns:
str: The number with commas
"""
return "{:,}".format(num) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.