content stringlengths 42 6.51k |
|---|
def flatten2d(l):
""" Returns a flattened version of a list of lists. """
try:
test = l[0][0]
return [item for sublist in l for item in sublist]
except TypeError:
return l |
def parse_result(result):
"""
This function is used to reorganize the result of my_lda_func for plotting.
"""
result_dic = {}
for topic_num, dist in result:
unpack = []
for obj in dist.split('+'):
prob, word = obj.split('*')
unpack.append((float(prob), word.st... |
def split_comma_list(comma_str: str):
"""
Split a comma-separated list of values, stripping whitespace
"""
return [item.strip() for item in comma_str.split(',')] |
def _matrix(nrows, ncols):
"""Creates a matrix with no borders."""
matrix = (
" x" + " x" * (ncols - 1) + " \n" + (
" " + " " * (ncols - 1) + " \n" +
" x" + " x" * (ncols - 1) + " \n") * (nrows - 1))
return matrix |
def add_blank_choice(choices):
"""
Add a blank choice to the beginning of a choices list.
"""
return ((None, "---------"),) + tuple(choices) |
def level_from_severity(severity):
"""Converts tool's severity to the 4 level
suggested by SARIF
"""
if severity == "CRITICAL":
return "error"
elif severity == "HIGH":
return "error"
elif severity == "MEDIUM":
return "warning"
elif severity == "LOW":
retur... |
def merge_dicts(*dicts):
"""
Shallow copy and merge dicts into a new dict; precedence goes to
key value pairs in latter dict. Only keys in both dicts will be kept.
:param dicts: iterable of dict;
:return: dict;
"""
merged = dict()
for d in dicts:
merged.update(d)
return mer... |
def strip_nulls(unicode_contents):
"""
CRS data seems to have null control characters (NUL) in various fields, which confuse pandas
"""
return unicode_contents.replace(u'\0', u'') |
def median(scores):
"""Returns the median of only valid scores in the given list [0,100]"""
# Checks and adds valid scores to valid_scores
valid_scores = []
for score in scores:
if not(score < 0 or score > 100):
valid_scores.append(score)
if len(valid_scores) == 0:
retu... |
def _mapping_repr(mapping):
"""Helper to return class names in the dict values."""
return {
version: [klass.__name__ for klass in classes_list]
for version, classes_list in mapping.items()
} |
def is_valid_transaction_hash(tx_hash):
"""Determines if the provided string is a valid Stellar transaction hash.
:param str tx_hash: transaction hash to check
:return: True if this is a correct transaction hash
:rtype: boolean
"""
if len(tx_hash) != 64:
return False
try:
... |
def Position_downrange(downrange, velocity, angle_of_attack):
""" **Still under development**
Calculates the position in the x direction from the launch site based on an ascent profile.
Args:
downrange (float): Position downrange calculated at timestep i-1. Initial value = 0
velocity (float)... |
def parse_wfo_location_group(form):
"""Parse wfoLimiter"""
limiter = ''
if 'wfo[]' in form:
wfos = form.getlist('wfo[]')
wfos.append('XXX') # Hack to make next section work
if 'ALL' not in wfos:
limiter = " and w.wfo in %s " % (str(tuple(wfos)),)
if 'wfos[]' in form... |
def worst_range(nums, target):
"""
Given a sorted list, find the range nums[lo:hi] such that all values in the range equal to target.
"""
if not target in nums:
return None
lo = nums.index(target)
if lo == len(nums) - 1:
return (lo, lo)
hi = lo + 1
while hi < len(nums):
... |
def I_beam(b, h):
"""gets the Iyy, Izz, Iyz for a solid beam"""
f = 1 / 12. * b * h
Iyy = f * h * h # 1/12.*b*h**3
Izz = f * b * b # 1/12.*h*b**3
Iyz = 0.
return (Iyy, Izz, Iyz) |
def _render_limit(limit):
"""Render the limit part of a query.
Parameters
----------
limit : int, optional
Limit the amount of data needed to be returned.
Returns
-------
str
A string that represents the "limit" part of a query.
"""
if not limit:
return ''
... |
def payloads_config(param):
"""Create a valid payloads config from the config file contents."""
if not param:
return {'enabled': True}
payloads_config = param.copy()
payloads_config['enabled'] = bool(param.get('enabled', True))
return payloads_config |
def prefixCombiner(prefix, itemlist, glue=''):
"""Returns a list of items where each element is prepend by given
prefix."""
result = []
for item in itemlist:
result.append(prefix + glue + item)
return result |
def extract_string(data, begin, end):
""" Extracts the main string from the message sent by the client and cuts it specifically.
:param end: The end of the string.
:param begin: The beginning of the string.
:param data: Data sent by the client.
:return: String part of the message.
"""
try:
... |
def duplicate_in(l):
"""Returns True if there is at least one duplicated element in the list of
strings l, and False otherwise"""
l.sort()
for i in range(len(l)-1):
if l[i] == l[i+1]: return True
return False |
def convert_conditions(conditions):
"""
Convert the conditions to a mapping of nodename->list of conditions.
"""
if conditions is None:
return {}
res = {}
if 'attributes' in conditions:
for condition in conditions['attributes']:
cond = condition[0]
node = ... |
def sortDictByKey(dct: dict) -> dict:
"""
@brief Sort the dict by its key as of Python 3.7.
@param dct The dict
@return The sorted dict
"""
dctNew = {}
for key in sorted(dct.keys()):
dctNew[key] = dct[key]
return dctNew |
def myfunc(a, b, c, d):
""" A random function. Important to define this globally
because the multiprocessing package can't pickle locally
defined functions."""
return a ** b + c * d |
def camel_to_snake(camel: str) -> str:
"""Convert camel case to snake."""
if not camel:
return camel
snake = camel[0].lower()
for c in camel[1:]:
if c.isupper():
snake = snake + '_'
snake = snake + c.lower()
return snake |
def to_none(text):
"""
Convert a string to None if the string is empty or contains only spaces.
"""
if str(text).strip():
return text
return None |
def buildBeat(time):
"""
The module class 64 of time (numbers time%64) are represented in binary
representation, changint the 0's by ones, this in order to be more
suitable to affec the result in the weight matrixes to be determined.
This in fact is a binary representation of the time withi... |
def diff(obj, amount):
"""Returns the difference between obj and amount (obj - amount).
Example usage: {{ my_counter|diff:"5" }} or {{ my_counter|diff:step_id }}
"""
return obj-float(amount) |
def suppress_none(value):
""" Returns empty string for none, otherwise the passed value """
return value if value else "" |
def sum_accumulators(accs):
"""Takes a list of accumulators or Nones and adds them together.
"""
valid = [acc for acc in accs if acc]
if len(valid) == 0:
return None
ret = valid[0]
for v in valid[1:]:
ret += v
return ret |
def any_value(dict_):
"""Return any value in dict."""
try:
return next(iter(dict_.values()))
except StopIteration:
raise ValueError("dict has no values") |
def derive_new_filename(filename):
"""Derives a non-numbered filename from a possibly numbered one."""
while filename[-1].isdigit():
filename = filename[:-1]
return filename |
def _build_final_method_name(method_name, dataset_name, repeat_suffix):
"""
Return a nice human friendly name, that almost looks like code.
Example: a test called 'test_something' with a dataset of (5, 'hello')
Return: "test_something(5, 'hello')"
Example: a test called 'test_other_stuff' wi... |
def mkdosname(company_name, default='noname'):
""" convert a string to a dos-like name"""
if not company_name:
return default
badchars = ' !@#$%^`~*()+={}[];:\'"/?.<>'
n = ''
for c in company_name[:8]:
n += (c in badchars and '_') or c
return n |
def _color_idx(val):
""" Take a value between 0 and 1 and return the idx of color """
return int(val * 30) |
def color_position_negative(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
color = 'darkred' if val < 0 else 'darkblue'
return 'color: %s' % color |
def sort_gift_code(code):
"""
Sorts a string in alphabetical order.
:param code: a string containing up to 26 unique alphabetical characters.
:return: a string containing the same characters in alphabetical order.
"""
return "".join(sorted(code)) |
def _b(s):
"""A byte literal."""
return s.encode("latin-1") |
def validateTransactionBody(data):
"""Validates incoming json body
Arguments:
data {[dict]} -- [json body]
Returns:
[bool] -- [if validation passes]
[dict] -- [if validation fails]
"""
keys = [*data]
allowedKeys = ["amount", "transactionType"]
if len(keys) != 2:
... |
def sanitize_href(href):
"""
Verify that a given href is benign and allowed.
This is a stupid check, which probably should be much more elaborate
to be safe.
"""
if href.startswith(("/", "mailto:", "http:", "https:", "#", "tel:")):
return href
return "#" |
def concatenate_path_pk(path, *args):
"""
Receive path and args and concatenate to create the path needed
for an object query.
Make sure parameters are plugged in in the right order. It must
be aligned with the Bexio API, so the endpoints are valid. Check
out the official docs to see, how the f... |
def include_tagcanvas(element_id, width, height, url_name='tagcanvas-list',
forvar=None, limit=3):
"""
Args:
element_id - str - html id
width - int - pixels width
height - int - pixels height
url_name - if url_name=='' then no links. Default: tagcanvas-list
... |
def yesno(question, noprompt=False):
"""Simple Yes/No Function."""
if noprompt:
return True
prompt = f"{question} ? (y/n): "
ans = input(prompt).strip().lower()
if ans not in ["y", "n"]:
print(f"{ans} is invalid, please try again...")
return yesno(question)
if ans == "y":... |
def read_path(path):
"""
Fetch the contents of a filesystem `path` as bytes.
"""
return open(path, 'rb').read() |
def find_multiples(integer, limit):
"""
Finds all integers multiples.
:param integer: integer value.
:param limit: integer value.
:return: a list of its multiples up to another value, limit.
"""
return [x for x in range(1, limit + 1) if x % integer == 0] |
def normalize(x, xmin, xmax):
"""Normalize `x` given explicit min/max values. """
return (x - xmin) / (xmax - xmin) |
def coord_to_index(x_coord, y_coord, width):
""" translate an (x, y) coord to an index """
return y_coord * width + x_coord |
def capture_current_size(thread_list, recorded):
"""
Amount captured so far is the sum of the bytes recorded by warcprox,
and the bytes pending in our background threads.
"""
return recorded + sum(getattr(thread, 'pending_data', 0) for thread in thread_list) |
def fix_django_headers(meta):
"""
Fix this nonsensical API:
https://docs.djangoproject.com/en/1.11/ref/request-response/
https://code.djangoproject.com/ticket/20147
"""
ret = {}
for k, v in meta.items():
if k.startswith("HTTP_"):
k = k[len("HTTP_"):]
elif k not in ("CONTENT_LENGTH", "CONTENT_TYPE"):
# ... |
def parse_key_val_var(var_str):
"""Convert key=val string to tuple.
Arguments:
var_str -- String in the format 'foo=bar'
"""
items = var_str.split('=')
return (items[0].strip(), items[1].strip()) |
def get_link(obj, rel):
"""Get link information from a resource.
Parameters
----------
obj : dict
rel : str
Returns
-------
dict
"""
if isinstance(obj, dict) and 'links' in obj:
if isinstance(obj['links'], dict):
return obj['links'].get(rel)
links ... |
def some_function(t):
"""Another silly function."""
return t + " python" |
def get_api_url(account):
"""construct the tumblr API URL"""
global blog_name
blog_name = account
if '.' not in account:
blog_name += '.tumblr.com'
return 'http://api.tumblr.com/v2/blog/' + blog_name + '/posts' |
def num_eights(x):
"""Returns the number of times 8 appears as a digit of x.
>>> num_eights(3)
0
>>> num_eights(8)
1
>>> num_eights(88888888)
8
>>> num_eights(2638)
1
>>> num_eights(86380)
2
>>> num_eights(12345)
0
>>> from construct_check import check
>>> # ... |
def strStr(haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
for i in range(len(haystack)-len(needle)+1):
if haystack[i:i+len(needle)] == needle:
return i
return -1 |
def dec_to_bin(decimal_number: int) -> str:
"""Convert decimal number to binary.
Examples:
>>> dec_to_bin(5)
'101'
>>> dec_to_bin("Q")
Traceback (most recent call last):
...
ValueError: Integer value expected!
"""
# Check for correct argument type.
if not isi... |
def append_line(buf, linearr):
"""Append lines
Args:
buf (obj): Nvim buffer
linearr (Array[string]): Line contents
Returns:
suc (bool): True if success
"""
for l in linearr:
buf.append(l)
return True |
def get_attribute(item, attribute):
"""A version of getattr that will return None if attribute
is not found on the item"""
if hasattr(item, attribute):
return getattr(item, attribute)
return None |
def beacon_link(variant_obj, build=None):
"""Compose link to Beacon Network."""
build = build or 37
url_template = (
"https://beacon-network.org/#/search?pos={this[position]}&"
"chrom={this[chromosome]}&allele={this[alternative]}&"
"ref={this[reference]}&rs=GRCh37"
)
# beacon... |
def instructions(r1, r2):
"""
"""
def robot1(x,y):
"""
convert coordinates of robot1 to island
"""
if x <= 2 and y <= 1:
return 'r1_home'
elif x <= 1 and y >= 3:
return 'r1_near'
elif x >= 3 and y >= 3:
return 'r1_far'
... |
def merge(arg_list):
"""Function: merge
Description: Method stub holder for git.Repo.git.merge().
Arguments:
"""
status = True
if arg_list:
status = True
return status |
def convert_aa_code(three_letter, convert):
"""
Assumes a string that contains a three letter aminoacid code and
returns the corresponding one letter code.
"""
aa_code = {
'CYS': 'C',
'ASP': 'D',
'SER': 'S',
'GLN': 'Q',
'LYS': 'K',
'ILE': ... |
def bytes2hr(byte):
"""Converts the supplied file size into a human readable number, and adds a suffix."""
result = None
_s = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
if not isinstance(byte, int):
try:
byte = int(byte)
except TypeError:
raise
_si = 0
while b... |
def Dic_Key_Value_Reverse(indic):
"""
Reverse key:value pair to value:key pair, note indic must be 1-1 projection.
"""
outdic={}
for key,value in indic.items():
outdic[value]=key
return outdic |
def get_marble(value=0, prev=None, next=None):
"""Get new marble, with value, prev and next."""
return {'value': value, 'prev': prev, 'next': next} |
def el_block_size(l):
"""Size needed for a given el in the dmat array."""
return (l + 1) * (l + 2) // 2 |
def bound_check(coord, w, h):
""" Checks if coord is within grid """
if (0 <= coord[1] < h) and (0 <= coord[0] < w):
return True
else:
return False |
def get_result_facets(work_keys):
"""
Helper function takes a list of Creative Works keys and returns
all of the facets associated with those entities.
:param work_keys: Work keys
"""
facets = []
return facets |
def distance_from_root_v1(root, key, distance=0):
"""
Distance from root is same as the level at which key is present.
:param root:
:param key:
:param distance:
:return:
"""
if root == None:
return -1
if root.key == key:
return distance
else:
ld = distanc... |
def parse_between(text, start, end):
"""Returns all substrings occurring between given start and end strings in the given text."""
if start in text and end in text:
data = []
string = text.split(start)
# we know no data will be in first position
del string[0]
for substrin... |
def cyclic_binary_derivative(string):
"""
Calculates the cyclic binary derivative, which is the "binary string of length n formed by XORing adjacent pairs of
digits including the last and the first." See:
.. code-block:: text
Croll, G. J. (2018). The BiEntropy of Some Knots on the Simple Cubi... |
def mutindex2pos(x, start, end, mut_pos):
"""
Convert mutation indices back to genome positions
"""
if x == -.5:
return start
elif x == len(mut_pos) - .5:
return end
else:
i = int(x - .5)
j = int(x + .5)
return (mut_pos[i] + mut_pos[j]) / 2.0 |
def read_key(fd):
""" [str] = read_key(fd)
Read the utterance-key from the opened ark/stream descriptor 'fd'.
"""
str_ = ''
while True:
char = fd.read(1)
if char == '':
break
if char == ' ':
break
str_ += char
str_ = str_.strip()
if str_ == '':
return None # end of... |
def _stringify(value):
"""
Local helper function to ensure a value is a string
:param value: Value to verify
:return: The string value
"""
if not isinstance(value, str):
return str(value)
else:
return value |
def _phaser_succeeded(llg, tfz):
"""Check values for job success"""
return llg > 120 and tfz > 8 |
def get_courseweeks(course_id):
"""
Returns a list of course weeks
Todo: Calculate from course table start and end date
Args:
course_id: course id
Returns:
list of course week numbers
"""
return [31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44] |
def parseMessageJson(messageList, username=None):
"""
messageList: list - Should be a bunch of dictionaries within a list.
username: string - optional - Used to find message only from that user. Username is case sensitive.
If username is not given, everyone's message will be used
Returns a big ... |
def arguments(function, extra_arguments=0):
"""Returns the name of all arguments a function takes"""
if not hasattr(function, '__code__'):
return ()
return function.__code__.co_varnames[:function.__code__.co_argcount + extra_arguments] |
def get_date_from_s1_raster(path_to_raster):
"""
Small utilty function that parses a s1 raster file name to extract date.
Args:
path_to_raster: path to the s1 raster file
Returns:
a string representing the date
"""
return path_to_raster.split("/")[-1].split("-")[4] |
def isNumber(s):
"""
Check if a string is a numeric (int or float) value
"""
try:
float(s)
return True
except ValueError:
return False |
def is_sitemap(content):
"""Check a string to see if its content is a sitemap or siteindex.
Attributes: content (string)
"""
try:
if 'www.sitemaps.org/schemas/sitemap/' in content or '<sitemapindex' in content:
return True
except:
return False
return False |
def passes_atomic_condition(inter, fs):
""" Tests an interpretation for the atomic condition.
For every formal species there exists an implementation species which
interprets to it.
"""
return all(any([f] == v for v in inter.values()) for f in fs) |
def E(x):
"""
Calculates expected value given list x of values.
:param x: list of observations
:returns expected value of X
"""
return float(sum(x)) / len(x) |
def image_inputs(images_and_videos, data_dir, text_tmp_images):
"""Generates a list of input arguments for ffmpeg with the given images."""
include_cmd = []
# adds images as video starting on overlay time and finishing on overlay end
img_formats = ['gif', 'jpg', 'jpeg', 'png']
for ovl in images_and_videos:
... |
def remove_duplicates(list1: list) -> list:
"""
Removes duplicates from a list
:param list1: list to remove duplicates from
:return: list with duplicates removed
Example:
>>> remove_duplicates([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4])
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 1... |
def transform_to_gps(point, origin, x, y):
"""
Transforms the input point from the local frame to gps coordinates
"""
tr_point = [0, 0]
tr_point[0] = origin[0] + point[0] * x[0] + point[1] * y[0]
tr_point[1] = origin[1] + point[0] * x[1] + point[1] * y[1]
return(tr_point) |
def chunks(l, n):
"""
@type l: list (or other iterable)
@param l: list that will be splited into chunks
@type n: int
@param n: length of single chunk
@return: list C{l} splited into chunks of length l
Splits given list into chunks. Length of the list has to be multiple of
C{chunk} o... |
def SplitLine(line, width):
"""Splits a single line at comma, at most |width| characters long."""
if len(line) <= width:
return (line, None)
n = 1 + line[:width].rfind(",")
if n == 0: # If comma cannot be found give up and return the entire line.
return (line, None)
# Assume there is a space after th... |
def product_from_name(name):
"""
Return a product name from this tag name or target name.
:param name: eg. "ceph-3.0-rhel-7"
:returns: eg. "ceph"
"""
if name.startswith('guest-'):
# deal with eg. "guest-rhel-X.0-image"
name = name[6:]
parts = name.split('-', 1)
return pa... |
def ht_cm_sqm(ht):
"""Converts height from centimeter to squared meter
Parameters
----------
ht: double
height in cms
Returns
-------
double
height in squared meter.
Examples
--------
>>> ht_cm_sqm(175)
1.75
"""
return (ht / 100) ** 2 |
def _WinPathToUnix(path):
"""Convert a windows path to use unix-style path separators (a/b/c)."""
return path.replace('\\', '/') |
def _check_groups(problem):
"""Check if there is more than 1 group."""
groups = problem.get('groups')
if not groups:
return False
if len(set(groups)) == 1:
return False
return groups |
def extract_sentiment(emotions):
"""Extract the sentiment from the facial annotations"""
joy = [0, 0, 0]
sorrow = [0, 0, 0]
anger = [0, 0, 0]
surprise = [0, 0, 0]
odds = ['VERY_LIKELY', 'LIKELY', 'POSSIBLE']
# Loop through the emotions we're pulling and get the count
for i in range(len(... |
def reverse(head):
""""Reverse a singly linked list."""
# If there is no head.
if not head:
# Return nothing.
return
# Create a nodes list.
nodes = []
# Set node equal to the head node.
node = head
# While node is truthy.
while node:
# Add the node to the ... |
def get_product_metadata(product_file):
"""
Metadata appended for labels xr.DataArray
"""
return dict({"product_file": product_file}) |
def quotas_panel(context, request, quota_form=None, quota_err=None, in_user=True):
"""quota form for 2 different user pages."""
return dict(
quota_form=quota_form,
quota_err=quota_err,
in_user=in_user,
) |
def primary_key(row):
"""input: dict(file=, sentId=, eId=, eiId=, eText=, )
output: (file, sentId, eId, eiId)
"""
return (row["file"], int(row["sentId"]), row["eId"], row["eiId"]) |
def strip_leading_secret(path):
"""Strip leading 'secret/'"""
if path[:7].lower() == "secret/":
path = path[7:]
while path[-1] == "/":
path = path[:-1]
if not path:
raise ValueError("A non-root secret path must be specified.")
return path |
def _build_backend_map():
"""
The set of supported backends is defined here.
"""
return {"pytorch"} |
def get_xml_version(version):
"""Determines which XML schema to use based on the client API version.
Args:
version: string which is converted to an int. The version string is in
the form 'Major.Minor.x.y.z' and only the major version number
is considered. If None is provided... |
def fix_fp(sequence, parallel):
"""
Fix footprints
Parameters
--------------
sequence
Sequence
parallel
Parallel
Returns
-------------
sequence
Sequence
parallel
Parallel
"""
sequence = sequence.difference(parallel)
return sequence, p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.