content stringlengths 42 6.51k |
|---|
def balance_queue_modifier(count_per_day: float) -> float:
"""
Create a modifier to use when setting filter values.
Because our queue is only ever 1k posts long (reddit limitation), then
we never want any given sub to take up any more than 1/100th of the queue
(seeing as how we have ~73 partners ri... |
def validate_chronam_url(url):
""""Naive check. Ensures that the url goes to a
chroniclingamerica.loc.gov newspaper and references the .json
representation
Params: url -> url of JSON file for newspaper to download: str
Return: Boolean"""
domain_check = 'chroniclingamerica.loc.gov/lccn/sn' in ... |
def _fmt_scalar(s):
"""Helper function to round metrics"""
if not isinstance(s, float) and (not hasattr(s, 'dtype') or s.dtype!='f'):
return s # non-floats left alone
elif s >=1.0:
return round(s, 1)
elif s>=0.01:
return round(s, 3)
else:
return s |
def _get_exported_include_tree(dep):
"""
Generate the exported swig source includes target use for the given
swig library target.
"""
return dep + "-swig-includes" |
def quadKey_to_Bing_URL(quadKey, api_key):
"""
The function to create a tile image URL linking to a Bing tile server
Parameters
----------
quadKey : str
the quad key for Bing for the given tile
api_key : str
the Bing maps api key
Returns
-------
tile_url : str
... |
def scanner_port(s):
"""
Break up a port name into scanner and port number.
The naming convention used by the DTC Initium is that
pressure ports are named XYZ where X is the number of the
scanner and YZ is the port number in said scanner.
This function receives a port name and makes sure it is ... |
def reverse_with_name(ctx, args):
"""command that takes some args and returns them reversed"""
return list(reversed(args)) |
def UspWeaknessVerifier(U, p, s):
"""
Verifies an assigment to permutations @p and @s.
Returns True iff the assignment shows @U is a weak USP.
"""
n = len(U)
k = len(U[0])
def is_identity(x): return sum([x[i] == i for i in range(n)]) == n
if is_identity(p) and is_identity(s):
r... |
def _shape2size(shape):
"""
Compute the size which corresponds to a shape
"""
out = 1
for item in shape:
out *= item
return out |
def rt_delta(maxdiff, precision=5):
# type: (float, int) -> float
"""Return the delta tolerance for the given retention time.
Keyword Arguments:
maxdiff -- maximum time difference between a feature edge and
an adjacent frame to be considered part of the same
... |
def get_filename(name):
"""Return filename for astrocats event."""
return name.replace('/', '_') + '.json' |
def longest_common_prefix(fst: str, snd: str) -> str:
"""
Finds the longest prefix shared by both input strings.
Args:
fst: First string
snd: Second string
Returns:
Longest common prefix string
"""
bound = 0
for a, b in zip(fst, snd):
if a != b:
... |
def merge_converters(*converters_to_merge):
"""
Merges the given converter groups.
Parameters
----------
converters_to_merge : `dict` of (`str`, `FunctionType`)
Audit log change converters.
Returns
-------
merged_converters : `dict` of (`str`, `FunctionType`)
"""
... |
def get_qual(fsize):
"""Returns file size qualifier"""
if (fsize > 2**30):
fsize = fsize/float(2**30)
qual = 'Giga'
elif (fsize > 2**20):
fsize = fsize/float(2**20)
qual = 'Mega'
elif (fsize > 2**10):
fsize = fsize/float(2**10)
qual = 'Kilo'
else... |
def _get_include_flags(commands):
"""
Return a list of all include flags used in the compilation.
This is used to be able to run tools on individual headers, which don't
have an associated compile command to use directly. It assumes that there
are no clashing includes and that it makes sense to ma... |
def estimate_total_conversion_runtime(
total_mb: float,
transfer_rate_mb: float = 20.0,
conversion_rate_mb: float = 17.0,
upload_rate_mb: float = 40,
compression_ratio: float = 1.7,
):
"""
Estimate how long the combined process of data transfer, conversion, and upload is expected to take.
... |
def add_2d(a, b):
"""
Adds matrix 'a' with matrix 'b' to produce a matrix result
that contains the added values.
:param a: 2d matrix of type 'list' to be added to 'b'
:param b: 2d matrix of type 'list' to be added with 'a'
:return: (list) 2d matrix result of a + b
"""
# check if... |
def l12(pos, b, l):
""" Find out if position is under line 1
top of the rectangle
"""
x, y = pos
if (y < b):
return True
else:
return False |
def str_to_bool(s_in):
""" Checks if a string is "true" or "True" and resturns True if so,
False otherwise as a bool.
"""
if ((type(s_in) == type("") and s_in.strip() in ["True", "true"]) or
(type(s_in) == type(True) and s_in)):
return True
else:
return False |
def random_digits(length):
"""generate a random string"""
import string
from random import choice
return ''.join([choice(string.digits) for i in range(length)]) |
def remove_duplicates(old, warnings):
"""
Removes all duplicate tests from the list
old -- the list of tests
warnings -- any warnings produced during testing
return -- a list without duplicates
"""
new = []
for file in old:
if file in new:
warnings.append("Warning: File " + file + " already in list")
... |
def norm_lon(x):
""" Normalize longitude x into range [0,360]. """
if x == 360:
return 360
else:
return x % 360 |
def find_grid_size(min_size):
""" Finds the minimum grid size that is at least the size of the input grid, but has
only factors of 2,3,5,7 raised to any power and either 11 or 13 appearing once. """
prime_factors = [2, 3, 5, 7]
current_size = min_size
while 1:
remainder = current_size
... |
def sanatize(program):
"""Removes excess characters from program"""
accepted = "<>+-.,[]"
sanatized = ""
for char in program:
if char in accepted:
sanatized += char
return sanatized |
def rr_and_single(x, y, nx, ny):
"""Dimensionless production rate for a gene regulated by two
repressors with AND logic in the absence of leakage with
single occupancy.
Parameters
----------
x : float or NumPy array
Concentration of first repressor.
y : float or NumPy array
... |
def _nest_vars_in_rec(var_items, rec_items, input_order, items_by_key, parallel):
"""Nest multiple variable inputs into a single record or list of batch records.
Custom CWL implementations extract and merge these.
"""
num_items = var_items
var_items = list(var_items)[0]
if rec_items:
re... |
def sanitize_cr(realmrep):
""" Removes probably sensitive details from a realm representation.
:param realmrep: the realmrep dict to be sanitized
:return: sanitized realmrep dict
"""
result = realmrep.copy()
if 'secret' in result:
result['secret'] = '********'
if 'attributes' in res... |
def _list_to_matcher(matcher_list):
"""Converts a matcher as a list to a dict matcher."""
return {"default": matcher_list} |
def prettifyXml(uglyxml) :
"""
Create and returns a correct XML formating from a string.
"""
# /!\ NOT EFFICIENT FOR HUGE TREES
# This is a faster solution if it takes too long, but it's ugly with no indentation,
# so use only for debug purposes or if the xml creation takes too long :
""" return uglyxml.replace(... |
def _best_art(arts):
"""Return the best art (determined by list order of arts) or an empty string if none is available"""
return next((art for art in arts if art), '') |
def update_user_data(commit_edges, filtered_users=None):
"""
Updates or creates user commits data in JSON format
"""
users = filtered_users if filtered_users else {}
for commit in commit_edges:
# print(f"EDGE {commit}")
# print(f"EDGE type {type(commit)}")
node = commit["node... |
def exception_match(x, y):
"""Check the relation between two given exception `x`, `y`:
- `x` equals to `y`
- `x` is a subclass/instance of `y`
Note that `BaseException` should be considered.
e.g. `GeneratorExit` is a subclass of `BaseException` but which is not a
subclass of `Exception`, and i... |
def dd2dms(dd):
"""
Decimal degrees to DMS.
Args:
dd (float). Decimal degrees.
Return:
tuple. Degrees, minutes, and seconds.
"""
m, s = divmod(dd * 3600, 60)
d, m = divmod(m, 60)
return int(d), int(m), s |
def select_closest_mass_offset(max_counts, unique_elements_with_count):
"""Select select the mass offset closest to zero if several mass offsets occur the same number of times
"""
mass_offset = None
for unique_element in unique_elements_with_count:
if unique_element[1] == max_counts and unique... |
def class_method():
"""cls.meth(): Class method defined by metaclass."""
class Meta(type):
def get_value(cls):
return "method inherited by {}".format(cls.__name__)
class ItemClass(metaclass=Meta):
pass
return ItemClass.get_value() |
def part1(data):
"""Solve part 1"""
return sum(mass // 3 - 2 for mass in data) |
def create_wildcard(text, extensions):
"""
Create wildcard for use in open/save dialogs.
"""
return "%s (%s)|%s" % (text,
", ".join(["*" + e for e in extensions]),
";".join(["*" + e for e in extensions])) |
def collapse_umi(cells):
"""
Input set of genotypes for each read
Return list with one entry for each UMI, per cell barcode
"""
collapsed_data = {}
for cell_barcode, umi_set in cells.items():
for _, genotypes in umi_set.items():
if len(set(genotypes)) > 1:
pas... |
def check_and_remove_trailing_occurrence(txt_in, occurrence):
"""Check if a string ends with a given substring. Remove it if so.
:param txt_in: Input string
:param occurrence: Substring to search for
:return: Tuple of modified string and bool indicating if occurrence was found
"""
n_occurrence... |
def fecha(campo):
"""
Procesa un campo que representa una fecha en YYYYMMDD
y lo pasa como un string YYYY-MM-DD
"""
return '-'.join((campo[:4], campo[4:6], campo[6:])) if not campo.isspace() else '' |
def countSolutionsLogfile(logfile_path):
"""
Count the number of solutions in a CryptoMiniSat Logfile
"""
with open(logfile_path, "r") as logfile:
logged_solutions = 0
for line in logfile:
if "s SATISFIABLE" in line:
logged_solutions += 1
return logged... |
def bubble_sort(seq):
"""Bubble sort implementation"""
# seq = [4,8,6,3,7,2]
count = 0
length = len(seq)
for i in range(length - 1):
sorted = True
for j in range(length - 1):
if seq[j] > seq[j+1]:
seq[j],seq[j+1] = seq[j+1],seq[j]
count += 1
sorted = False
if sorted:
break
... |
def getGuessedWord(secretWord: str, lettersGuessed: list) -> str:
"""
secretWord: the word the user is guessing
lettersGuessed: letters that have been guessed so far
returns: string, comprised of letters and underscores that
represents what letters in secretWord have been guessed so far.
"""
... |
def fixquotes(u):
"""
Given a unicode string, replaces "smart" quotes, ellipses, etc.
with ASCII equivalents.
"""
if not u:
return u
# Double quotes
u = u.replace('\u201c', '"').replace('\u201d', '"')
# Single quotes
u = u.replace('\u2018', "'").replace('\u2019', "'")
# E... |
def build_item(
title,
key=None,
synonyms=None,
description=None,
img_url=None,
alt_text=None,
event=None,
):
"""
Builds an item that may be added to List or Carousel
"event" represents the Dialogflow event to be triggered on click for Dialogflow Messenger
Arguments:
... |
def build_call(*args):
"""
Create a URL for a request to the OEC API.
Args:
*args (str): strings to be appended to the API call.
Returns:
str: url for the API request.
"""
call_url = 'https://legacy.oec.world/'
for val in args:
call_url += str(val) + '/'
return ... |
def is_type_or_null_property(property_):
"""
Serpyco use "anyOf" (null, or defined type) key to define optional properties.
Example:
``` json
[...]
"properties":{
"id":{
"type":"integer"
},
"name":{
... |
def tamper(payload, **kwargs):
"""
Slash escape single and double quotes (e.g. ' -> \')
>>> tamper('1" AND SLEEP(5)#')
'1\\\\" AND SLEEP(5)#'
"""
return payload.replace("'", "\\'").replace('"', '\\"') |
def mild_in(item, container):
"""Returns true iff item, or its reverse, is already in container"""
assert len(item) == 2
return item in container or tuple(reversed(item)) in container |
def get_ascending_digits(n):
"""Gets the digits in ascending order as a list"""
return sorted([int(i) for i in str(n)]) |
def mask_to_cidr(mask):
"""
Determine the CIDR suffix for a given dotted decimal IPv4 netmask.
"""
# convert netmask to 32 binary digits
tmp = "".join([format(int(x), "08b") for x in mask.split(".")])
# count leading ones
return len(tmp) - len(tmp.lstrip("1")) |
def test_csv(distribution):
"""
Test if a DCAT:distribution is CSV.
"""
return (
distribution.get("mediaType") == "text/csv"
or distribution.get("format", "").lower() == "csv"
) |
def _number_of_links(shape):
"""Number of links in a structured quad grid.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
Returns
-------
int :
Number of links in grid.
Examples
--------
>>> from landlab.components.overland_flow._links impor... |
def format_notif(app, job):
"""
Returns a formatted title and message couple
>>> app = {'name': 'myapp', 'env': 'preprod', 'role': 'webfront'}
>>> job = {'command': 'deploy', 'user': 'john', '_created': '2015-06-10 17:09:38', 'status': 'done', 'message': 'Deployment OK: [mymodule]'}
>>> title, mess... |
def create_ppis_dictionary(interactions_with_old_id, id_mapping):
"""Create dictionary protein --> set of interactiors in lexicographic order"""
result = {}
for from_old_id, to_old_id_set in interactions_with_old_id.items():
if from_old_id in id_mapping.keys():
for to_old_id in to_old_id... |
def case_sensitive(stem, word):
""" Applies the letter case of the word to the stem:
Ponies => Poni
"""
ch = []
for i in range(len(stem)):
if word[i] == word[i].upper():
ch.append(stem[i].upper())
else:
ch.append(stem[i])
return "".join(ch) |
def remove_dash(text):
"""
Variable name can't have - in javascript
"""
text = str(text)
return text.replace('-', '') |
def quadratic_probs(num_values):
"""Make an array containing quadratically increasing probabilities."""
total = (num_values - 1) * num_values * (2 * (num_values - 1) + 1) / 6.0
probs = [i * i / total for i in range(num_values)]
return probs |
def ul(depth_and_txt_list):
"""
Wants a list of tuples containing depths and txt.
Don't know how robust this function is to depth errors.
depth_and_txt_list = [ (0, 'Things I want for x-mas'),
(1, 'Computer'),
(1, 'Fancy shoes'),
... |
def gen_all_sequences(outcomes, length):
"""
Iterative function that enumerates the set of all sequences of
outcomes of given length.
"""
answer_set = set([()])
for dummy_idx in range(length):
temp_set = set()
for partial_sequence in answer_set:
for item in outco... |
def noise_f(x):
"""function with different noise levels.
"""
if x > 0:
return -1.0 + 2.0 * x
else:
return -1.0 - 2.0 * x |
def get_creds_from_kwargs(kwargs):
"""Helper to get creds out of kwargs."""
creds = {
'key_file': kwargs.pop('key_file', None),
'http_auth': kwargs.pop('http_auth', None),
'project': kwargs.get('project', None),
'user_agent': kwargs.pop('user_agent', None)
}
return (creds... |
def A004086(i: int) -> int:
"""Digit reversal of i."""
result = 0
while i > 0:
unit = i % 10
result = result * 10 + unit
i = i // 10
return result |
def equivalent_resistance_in_parallel(*resistances):
"""
Calculate and return the value of equivalent resistance in parallel using given values of the resistances
How to Use:
Give a list of resistance which are placed in parallel,
Parameters:
resistances (list): resistance... |
def transliterate(line, trans_dict):
"""
Core function for transliteration of one line, one word at time
:param line: source string line for transliteration
:param trans_dict: transliteration instructions via 4 dictionaries
:return: transliterated string
"""
words = line.split()
... |
def build_entity(key, value):
"""
build_entity return a dict that can be passed back to rasa as an entity
using the given string key and value
"""
return {"entity": key, "value": value, "start": 0, "end": 0} |
def normalize_package_name(_s: str) -> str:
"""All comparisons of distribution names MUST be case insensitive,
and MUST consider hyphens and underscores to be equivalent.
ref: https://www.python.org/dev/peps/pep-0426/#name"""
return _s.replace('_', '-').lower() |
def recipRank(cls, ranking):
"""
This function takes a class and returns its reciprocal rank score in the
sorted association list of scores [(cls1,score), ..., (clsN,score)] 'ranking'
(sorted in descending order by score).
Note that the reciprocal rank for classes not in the ranked list of scores is... |
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
:param v:
... |
def parse_vars(string):
"""Parse a list of var/values separated by \\n"""
d = {}
for line in string.split('\n'):
if '=' not in line:
continue
name, value = line.strip().split('=')
value = value.strip('"')
d[name] = value
return d |
def linear_sum(S, n):
"""Return the sum of the first n numbers of sequence S."""
if n == 0:
return 0
else:
return linear_sum(S, n - 1) + S[n - 1] |
def SEIR_Map(state):
"""
Encodes the literal SEIR state to an integer.
Args:
(str): State of the human i.e. S, E, I, or R
"""
if state == "S":
return 0
if state == "E":
return 1
if state == "I":
return 2
if state == "R":
return 3 |
def isPalindrome(s):
"""
:type s: str
:rtype: bool
"""
s = "".join([i.lower() for i in s if i.isalnum()])
if len(s) == 0:
return True
count = -1
for i in range(len(s)):
if s[i] == s[count]:
count -= 1
else:
return False
re... |
def _shorten_mods(modifier_list):
"""replace modifier names with their first letters and in a fixed sequence
"""
result = ''
for values, outval in ((('Ctrl', 'CTRL', 'CLTR'), 'C'), (('Alt', 'ALT'), 'A'),
(('Shift', 'SHIFT'), 'S'), (('WinKey',), 'W')):
for test in value... |
def space_to_depth_x2_output_shape(input_shape):
"""Determine space_to_depth output shape for block_size=2.
Note: For Lambda with TensorFlow backend, output shape may not be needed.
"""
return (input_shape[0], input_shape[1] // 2, input_shape[2] // 2, 4 *
input_shape[3]) if input_shape[1] e... |
def weight_normalize1D(lst, invert, normalize_max):
"""
Used to normalize 1 dimensional list (unary values) according to their weight (normalize_max) and also takes into
inversion into account while returning.
:param lst: 1D list of items.
:param invert: boolean variable, invert the values or not
... |
def recursive_search(
arr: list,
x: int,
x_max: int,
y: int,
y_max: int,
word: str,
index: int,
w_len: int,
direction: str,
) -> bool:
"""
dir: None - both directions are available
h - horizontally
v - vertically
"""
if index == w_len:
return... |
def SortByEnds(l_orig):
"""
Convenient to have a one-line macro for swapping list order if first>last
"""
l = [x for x in l_orig]
if l[0] > l[-1]:
l.reverse()
return l |
def _parse_tags(tags):
"""Parse tags from CSV into a list."""
return [x.strip() for x in (tags or "").split(",")] |
def sectionize(parts, first_is_heading=False):
"""Join parts of the text after splitting into sections with headings.
This function assumes that a text was splitted at section headings,
so every two list elements after the first one is a heading-section pair.
This assumption is used to join sections wi... |
def resolve_wikipedia_link(link):
"""
Given a link like [[813 (film)|813]]
Return the string 813
"""
link = link.strip()
# first remove the brackets
if link.startswith("[[") and link.endswith("]]"):
link = link.strip()[2:-2]
# split the link into the title and the link if there i... |
def strip_article_title_word(word: str):
"""
Used when tokenizing the titles of articles
in order to index them for search
"""
return word.strip('":;?!<>\'').lower() |
def dict2str(opt: dict, indent_l: int = 1) -> str:
"""Dictionary to string for logger."""
msg = ''
for k, v in opt.items():
if isinstance(v, dict):
msg += ' ' * (indent_l * 2) + k + ':[\n'
msg += dict2str(v, indent_l + 1)
msg += ' ' * (indent_l * 2) + ']\n'
... |
def parse_tags(tags):
"""
>>> parse_tags('writing')
'writing'
>>> parse_tags(['news', 'steemit', 3, {'5': {}, '3': {}, '1': {}}, {'39': {}, '45': {}, '11': {}}, {}, 'esteem'])
['news', 'steemit', 'esteem']
>>> parse_tags(['dlive', 'dlive-broadcast', 'game', 'DLIVEGAMING'])
['dlive', 'dliv... |
def timeToSeconds(t: str) -> int:
"""
Convert the parsed time string from config.yaml to seconds
Args:
t (str): Supported format "hh:mm:ss"
Returns:
int: Total of seconds
"""
n = [int(x) for x in t.split(":")]
n[0] = n[0] * 60 * 60
n[1] = n[1] * 60
return sum(n) |
def are_event_tags_valid(event_tags):
""" Determine if event tags provided are dict or not.
Args:
event_tags: Event tags which need to be validated.
Returns:
Boolean depending upon whether event_tags are in valid format or not.
"""
return type(event_tags) is dict |
def convert_str(strr):
"""Convert a string to float, if it's not a float value, return string to represent itself."""
if strr.lower() == 'true' or strr.lower() == 't':
return True
elif strr.lower() == 'false' or strr.lower() == 'f':
return False
try:
float_value = float(strr)
... |
def _paradox_temp_table_keyword_args(cfg, eng):
"""Insert DocString Here."""
return {"prefixes": ["TMP"]} |
def partition(sort_list, low, high):
"""
All the elements smaller than the pivot
will be on the left side of the list
and all the elements on the right side
will be greater than the pivot.
"""
i = (low - 1)
pivot = sort_list[high]
for j in range(low, high):
if sort_list[j] ... |
def collect_key_values(key, data):
"""
Builds a list of values for all keys matching the given "key" in a nested
dictionary.
Args:
key (object): Dictionary key to search for
data (dict): Nested data dict
Returns:
list: List of values for given key
"""
values = []
... |
def value_change(paramter_name, old_value, new_value):
"""
Register a change in a value.
Arguments:
paramter_name - name of the parameter
old_value - old parameter value
new_value - new parameter value
Return:
html_content - html code registering a change in a parameter ... |
def parse_youtube_title(full_title):
"""
Parse song tags from youtube title.
Current logic is to assumme the youtube title is always in format 'author-song title'.
If there exists dashes in the title, up to the first dash is the author and the rest is the song title.
If there are no dashes, return original title ... |
def _hashString (text):
"""
Compute hash for a string, returns an unsigned 64 bit number.
"""
value = 0x35af7b2c97a78b9e
step = 0x072f2b592a4c57f9
for ch in text:
value = ((value * 104297) + (step * ord (ch))) & 0xFFFFFFFFFFFFFFFF
return value |
def ReverseBitsInt64(v):
"""Reverse the bits of a 64-bit integer.
Args:
v: Input integer of type 'int' or 'long'.
Returns:
Bit-reversed input as 'int' on 64-bit machines or as 'long' otherwise.
"""
v = ((v >> 1) & 0x5555555555555555) | ((v & 0x5555555555555555) << 1)
v = ((v >> 2) & 0x33333333333... |
def scalar_minmod(a, b):
"""Minmod function for two scalars
Idea from http://codegolf.stackexchange.com/questions/42079/shortest-minmod-function
"""
return sorted([a, b, 0])[1] |
def calc_qos(total_queries, success_queries_cnt):
""" Calculate QoS """
return (float(success_queries_cnt)/float(total_queries)) * 100 |
def chtype(var):
"""
get type of variable as str
Parameter
------
var : any type
Return
------
type_of_var : str
"""
return str(type(var)).split('\'')[1] |
def _try_load_functions(dll):
"""
Try to bind to aiImportFile and aiReleaseImport
library_path: path to current lib
dll: ctypes handle to library
"""
try:
_load = dll.aiImportFile
_release = dll.aiReleaseImport
_load_mem = dll.aiImportFileFromMemory
_ex... |
def ingredient_checker(ing, **kwargs):
"""
Takes in a popular grocery ingredient as a string and names of people
who have recently been shopping with the items they bought stored in
a list and returns a list of tuples revealing the name of the shopper
and a boolean revealing whether or n... |
def cvtCatHHStr(hhstr, numvals):
""" Convert concatenated HH hex string into list of integers.
Parameters:
hhstr - concatenated HH string
format: "HHHHHHHH..."
numvals - number of HH values in string to convert
Return Value:
Returns list of converted ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.