content stringlengths 42 6.51k |
|---|
def round_channels(channels, divisor=8):
"""
Round weighted channel number (make divisible operation).
Parameters:
----------
channels : int or float
Original number of channels.
divisor : int, default 8
Alignment value.
Returns:
-------
int
Weighted number ... |
def parse_by_integration(sensors):
"""Returns a list of devices that can be integrated."""
can_integrate = []
for sensor in sensors.values():
if sensor.get('integrate'):
can_integrate.append(sensor)
return can_integrate |
def process_results(results: dict, min_stars: int = 5) -> dict:
"""Sort and filer results
Args:
results: results to process
min_stars: minimum amount of stars required to include a repository in results
Returns:
Processed results
"""
filtered_d = {k: v for k, v in results.i... |
def term_to_integer(term):
"""
Return an integer corresponding to the base-2 digits given by ``term``.
Parameters
==========
term : a string or list of ones and zeros
Examples
========
>>> from sympy.logic.boolalg import term_to_integer
>>> term_to_integer([1, 0, 0])
4
>>... |
def _is_public(name: str) -> bool:
"""Return true if the name is not private, i.e. is public.
:param name: name of an attribute
"""
return not name.startswith('_') |
def append_name_to_key(entities, name):
"""To append value to corrispondent key"""
temp_result = []
for item in entities:
temp_item = {}
for key, value in item.items():
temp_item[f"[{name}]{key}"] = item[key]
temp_result.append(temp_item)
return temp_result |
def get_result_dir(result_dir, substring="results/"):
"""
:param result_dir:
:param substring:
:return:
"""
pos = result_dir.find(substring)
return result_dir[pos + len(substring):] |
def object_dist_to_mag(efl, object_dist):
"""Compute the linear magnification from the object distance and focal length.
Parameters
----------
efl : `float`
focal length of the lens
object_dist : `float`
object distance
Returns
-------
`float`
linear magnificati... |
def full_class(obj: object) -> str:
"""The full importable path to an object's class."""
return type(obj).__module__ + '.' + type(obj).__name__ |
def get_crowd_selection(selection_count, selection_map):
"""
Figure out what the crowd actually selected
:param selection_count: number of responses per selection
:type selection_count: dict
:param selection_map: maps selections to output fields
:type selection_map: dict
:return: the respo... |
def color565(r, g, b):
"""
Convert red, green, blue components to a 16-bit 565 RGB value.
Components should be values 0 to 255.
:param r: Red byte.
:param g: Green byte.
:param b: Blue byte.
:returns pixel : 16-bit 565 RGB value
"""
return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3) |
def c2hex(char):
"""Convert to HEX (2 bytes)."""
return "{:02x}".format(ord(char)) |
def parse_time_to_seconds(time: str) -> int:
"""needs hour:minutes:seconds as paramter, returns time in seconds"""
timelist = time.split(":")
seconds = int(timelist[0]) * 60 * 60 + int(timelist[1]) * 60 + int(timelist[2])
return seconds |
def sr3d_collate_fn(batch):
"""
Collate function for SR3D grounding.
See sr3d_parser_collate_fn for most arguments.
"""
return {
"utterances": [ex["utterance"] for ex in batch],
"raw_utterances": [ex["raw_utterance"] for ex in batch],
"tag_dicts": [ex["tag_dict"] for ex in ba... |
def strip_py_ext(options, path):
"""Return path without its .py (or .pyc or .pyo) extension, or None.
If options.usecompiled is false:
If path ends with ".py", the path without the extension is returned.
Else None is returned.
If options.usecompiled is true:
If Python is running wi... |
def ordinal(n: int) -> str:
"""
from: https://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1st-2nd-3rd#answer-4712
"""
result = "%d%s" % (n, "tsnrhtdd"[((n / 10 % 10 != 1) * (n % 10 < 4) * n % 10)::4])
return result.replace('11st', '11th').replace('12nd', '12th').replace('13r... |
def comment_part_of_string(line, comment_idx):
""" checks if the symbol at comment_idx is part of a string """
if (
line[:comment_idx].count(b"'") % 2 == 1
and line[comment_idx:].count(b"'") % 2 == 1
) or (
line[:comment_idx].count(b'"') % 2 == 1
and line[comment_idx:].count... |
def convert_to_decimal(seat_code):
""" Takes a seat code and converts it to a tuple containing seat row and column in decimal.
:param seat_code: string with first seven letters: B, F and last 3 letters: L, R
:return: decimal tuple
"""
# get row and column information
row = seat_code[:7]
col... |
def counting_sort(arr):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/countingsort2/problem
Given an unsorted list of integers, use the counting sort method to sort the list and then print the sorted list.
Args:
arr (list): List of integers to sort
Returns:
list: The li... |
def count_digit(value):
"""Count the number of digits in the number passed into this function"""
digit_counter = 0
while value > 0:
digit_counter = digit_counter + 1
value = value // 10
return digit_counter |
def create_assume_role_policy_document(trusted_entity_list):
"""
Create assume role policy document for IAM role
:type trusted_entity_list: typing.List[str]
:rtype: dict
Example::
create_assume_role_policy_document([
TrustedEntityList.aws_lambda
])
"""
return ... |
def bfs(graph, start):
"""
Implementation of Breadth-First-Search (BFS) using adjacency matrix.
This returns nothing (yet), it is meant to be a template for whatever you want to do with it,
e.g. finding the shortest path in a unweighted graph.
This has a runtime of O(|V|^2) (|V| = number of Nodes), ... |
def foldchange(origin, modified):
"""caculate the fold change between modified and origin outputs."""
return modified / origin
# return np.square(modified - origin) |
def pivot_median(seq, lo, hi):
"""Returns index to the median of seq[lo], seq[mid], seq[hi - 1]"""
m = lo + (hi - lo) // 2 # middle element
if seq[lo] < seq[m]:
if seq[m] < seq[hi - 1]:
return m
elif seq[hi - 1] < seq[lo]:
return lo
else:
if seq[hi - 1] <... |
def of_cmp(s1, s2):
"""Compare openflow messages except XIDs"""
if (not s1 and s2) or (s1 and not s2): # what if one is None
return False
#pdb.set_trace()
val= len(s1) == len(s2) and s1[0:8] == s2[0:8] and (len(s1) <= 16 or s1[16:] == s2[16:])
#print " of_cmp("+ s1 +" , "+ s2 + ") == "+ str... |
def get_utxos(tx, address):
"""
Given a transaction, find all the outputs that were sent to an address
returns => List<Dictionary> list of UTXOs in bitcoin core format
tx - <Dictionary> in bitcoin core format
address - <string>
"""
utxos = []
for output in tx["vout"]:
if "addre... |
def form_columns(board: list) -> list:
"""
Takes the game board as a list of rows, "rotates" it and returns a list of columns.
>>> form_columns(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 9 5 ", " 6 83 *", "3 1 **", " 8 2***", " 2 ****"])
['**** 3 ', '*** 6 ', '** ... |
def is_duplicate_affix(affixes, affix):
"""
Check if the properties for an affix are already known.
"""
for properties in affixes['properties']:
if properties == affix['properties']:
return True
return False |
def descope_queue_name(scoped_name):
"""Returns the unscoped queue name, given a fully-scoped name."""
# NOTE(kgriffs): scoped_name can be either '/', '/global-queue-name',
# or 'project-id/queue-name'.
return scoped_name.partition('/')[2] or None |
def is_vlanid_in_range(vid):
"""Check if vlan id is valid or not"""
if vid >= 1 and vid <= 4094:
return True
return False |
def check_list_elements(list):
"""Check if the list is made all by Trues
Arguments:
list {[bool]} -- list that stores old indexes choose by the random number
Returns:
bool -- if the list is made by all true returns true else false
"""
for i in range(0, len(list)):
if list[i... |
def dispatch_strategy(declaration):
"""How are we going to call the underlying implementation of a
declaration? There are two strategies:
- use_derived: we want to call the implementation on CPUDoubleType
(or a similar, derived Type instance). Because these derived
instances deal ... |
def cumulative_allele_count(samples_obj):
"""Return cumulative allele count for each sample in a dictionary
Accepts:
samples_obj(dict) example: {sample1 : {call_count:1}, sample2:{call_count:2} }
Returns:
call_count(int) example: 3
"""
allele_count = 0
for sampleid, value in s... |
def capabilities_to_dict(caps):
"""Convert the Node's capabilities into a dictionary."""
if not caps:
return {}
if isinstance(caps, dict):
return caps
return dict([key.split(':', 1) for key in caps.split(',')]) |
def expandmarker(text: str, marker: str = '', separator: str = '') -> str:
"""
Return a marker expanded whitespace and the separator.
It searches for the first occurrence of the marker and gets the combination
of the separator and whitespace directly before it.
:param text: the text which will be ... |
def format_repeats(file):
"""
Deal with the repeating blocks in the model
by keeping track of the encompassed rows and
multiplying them before appending.
"""
ret = []
while True:
try:
l = next(file).lstrip().replace('\n','')
except StopIteration:
break... |
def _dict_to_kv(d):
"""Convert a dictionary to a space-joined list of key=value pairs."""
return " " + " ".join(["%s=%s" % (k, v) for k, v in d.items()]) |
def get_message_headers(message):
"""Get headers from message."""
headers = message["payload"]["headers"]
return headers |
def is_latin(name):
"""Check if a species name is Latin.
Parameters
----------
name : str
species name to check
Returns
-------
bool
whether species name is Latin
"""
if name == '':
return False
elif name.count(' ') != 1:
return False
str_ = ... |
def _get_range(val, multiplier):
"""Get range of values to sweep over."""
range_min = max(0, val - val * multiplier / 100.)
range_max = val + val * multiplier / 100.
ranges = {'initial': val, 'minval': range_min, 'maxval': range_max}
return ranges |
def _IsLink(args):
"""Determines whether we need to link rather than compile.
A set of arguments is for linking if they contain -static, -shared, are adding
adding library search paths through -L, or libraries via -l.
Args:
args: List of arguments
Returns:
Boolean whether this is a link operation o... |
def make_service_domain_name(service, region=''):
""" Helper function for creating proper service domain names. """
tld = ".com.cn" if region == "cn-north-1" else ".com"
return "{}.amazonaws{}".format(service, tld) |
def SkipNItems(iterable, n):
"""
Generator yielding all but the first n items of a stream.
SkipNItems(iterable, n) -> iterator
iterable -- a sequence, iterator, or some object which supports
iteration, yielding items of any type.
n -- an integer or None
Example:
# R... |
def _vsplitter(version):
"""Kernels from Calxeda are named ...ceph-<sha1>...highbank.
Kernels that we generate are named ...-g<sha1>.
This routine finds the text in front of the sha1 that is used by
need_to_install() to extract information from the kernel name.
:param version: Name of the kernel
... |
def recursive_glob(rootdir='.', pattern='*'):
"""Search recursively for files matching a specified patterns.
Arguments
---------
rootdir : str, optional
Path to directory to search (default is '.')
pattern : str, optional
Glob-style pattern (default is '*')
Returns
-------
... |
def unique(value):
"""ENsure that al values are unique."""
try:
result = set(value)
except TypeError:
result = []
for x in value:
if x not in result:
result.append(x)
return result |
def xgcd(a,b):
"""
Extended euclidean algorithm: Iterative version
http://anh.cs.luc.edu/331/notes/xgcd.pdf
"""
prevx, x = 1, 0; prevy, y = 0, 1
while b:
q = a/b
x, prevx = prevx - q*x, x
y, prevy = prevy - q*y, y
a, b = b, a % b
return a, prevx, prevy |
def filter_dense_annotation(image_paths_per_class):
"""
Returns dict containing label as the key and the
list of image paths containing the class annotation as values
after deleting the key:value pair, for the label that contains
the highest number of annotations
Args:
image_paths_per_c... |
def base10toN(num, base):
"""Convert a decimal number (base-10) to a number of any base/radix from 2-36."""
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
if num == 0:
return '0'
if num < 0:
return '-' + base10toN((-1) * num, base)
left = num // base
if left == 0:
re... |
def _format_parameter(parameter: object) -> str:
"""
Format the parameter depending on its type and return
the string representation accepted by the API.
:param parameter: parameter to format
"""
if isinstance(parameter, list):
return ','.join(parameter)
else:
return str(par... |
def fit_transform(*args):
"""
fit_transform(iterable)
fit_transform(arg1, arg2, *args)
"""
if len(args) == 0:
raise TypeError('expected at least 1 arguments, got 0')
categories = args if isinstance(args[0], str) else list(args[0])
uniq_categories = set(categories)
bin_format = f... |
def unzip(l):
"""Unzips a list of tuples into a tuple of two lists
e.g. [(1,2), (3, 4)] -> ([1, 3], [2, 4])
"""
xs = [t[0] for t in l]
ys = [t[1] for t in l]
return xs, ys |
def find_elf_header(fi, data, offset, output):
"""
Used by guess_multibyte_xor_keys()
"""
i = 0
pos = 0
found = 0
length = len(data)
machine_dict = {0x02: "sparc", 0x03: "x86", 0x08: "mips", 0x14: "powerpc", 0x28: "arm", 0x2A: "superh", 0x32: "ia_64",
0x3E: "... |
def generate_blade_tup_map(bladeTupList):
"""
Generates a mapping from blade tuple to linear index into
multivector
"""
blade_map = {}
for ind,blade in enumerate(bladeTupList):
blade_map[blade] = ind
return blade_map |
def get_common_elements(list1, list2):
"""find the common elements in two lists. used to support auto align
might be faster with sets
Parameters
----------
list1 : list
a list of objects
list2 : list
a list of objects
Returns
-------
list : list
list of... |
def eval_where(pred, gold):
"""
Args:
Returns:
"""
pred_conds = [unit for unit in pred['where'][::2]]
gold_conds = [unit for unit in gold['where'][::2]]
gold_wo_agg = [unit[2] for unit in gold_conds]
pred_total = len(pred_conds)
gold_total = len(gold_conds)
cnt = 0
cnt_wo_ag... |
def _parse_arg_line(line):
"""
pull out the arg names from a line of CLI help text introducing args
>>> _parse_arg_line(' -s, --sudo run operations with sudo (nopasswd) (deprecated, use')
['-s', '--sudo']
"""
return [
part.strip().split(' ')[0].split('=')[0]
for par... |
def create_array(rows, cols, value):
"""Creates and returns array of inputted size, fills with inputted value"""
array = [[value for x in range(cols)] for y in range(rows)]
return array |
def buildAreaElement(shape, nodeString, x1, y1, x2, y2):
"""Build an AREA element for an imagemap
shape -- typically either "rect" or "default"
nodeString -- name of node to show/hide
x1, y1, x2, y2 -- coordinates of the rectangle
"""
return """<area shape="%s" alt="" coords="%d,%d,%d,%d" ... |
def list_terms(terms, arabic_column, english_column):
""" list all terms in dict"""
for term in terms:
print(
"\n\t", terms[term][english_column], " : ", terms[term][arabic_column], "\n"
)
return None |
def person_waistsize_uri(cleaned):
"""in cm
unmarked waist < 60 is interpreted as in, >=60 as cm"""
if cleaned:
return "person_waistsize/" + str(cleaned)
else:
return None |
def clean_comment(line):
"""
Clean up a comment, removing # , #! and starting space,
and adding missing \n if necessary
>>> clean_comment("#")
'\n'
>>> clean_comment("# This is ...")
'This is ...\n'
>>> clean_comment("#! This is ...")
'This is ...\n'
"""
if line.startswith("#... |
def contains_alternate_node(json_resp):
"""Check for the existence of alternate node in the stack analysis."""
result = json_resp.get('result')
return bool(result) and isinstance(result, list) \
and (result[0].get('recommendation', {}) or {}).get('alternate', None) is not None |
def global_pct_id( segments ):
"""
Calculated like this:
10bp @ 50% id = 5 matching residues, 10 total residues
10bp @ 80% id = 8 matching residues, 10 total residues
13 matching residues, 20 total residues
---------------------------------------
... |
def get_error_res(eval_id):
"""Creates a default error response based on the policy_evaluation_result structure
Parameters:
eval_id (String): Unique identifier for evaluation policy
Returns:
PolicyEvalResultStructure object: with the error state with the given id
"""
return {
... |
def line_to_tensor(line, EOS_int=1):
"""Turns a line of text into a tensor
Args:
line (str): A single line of text.
EOS_int (int, optional): End-of-sentence integer. Defaults to 1.
Returns:
list: a list of integers (unicode values) for the characters in the `line`.
"""
... |
def is_iterable(obj):
"""
Check if obj is iterable.
"""
try:
iter(obj)
except TypeError:
return False
else:
return True |
def reverse_lookup(d, value):
"""Return first key found with given value.
Raise ValueError exception if no matches found.
"""
for (k,v) in d.items():
if v == value:
return k |
def findTrend(trend, trendList):
""" Finds a specific trend tuple within a list of tuples """
# Assuming the lack of duplicates
for tIndex in range(len(trendList)):
if len(trendList[tIndex]) == 2:
if trendList[tIndex][0] == trend:
return tIndex, trendList[tIndex]
retu... |
def pharse_experiments_input(experiments):
"""
Pharse experiments number input to valid list.
----------
experiments : use input
Returns
-------
experiments : TYPE
DESCRIPTION.
"""
experiments = experiments.split(',')
new_experiments = []
indeces_to_remove = []
... |
def multiline_test(line):
"""
test if the current line is a multiline with "=" at the end
:param line: 'O1 3 -0.01453 1.66590 0.10966 11.00 0.05 ='
:type line: string
>>> line = 'C1 1 0.278062 0.552051 0.832431 11.00000 0.02895 0.02285 ='
>>> multiline_test(line)
True
... |
def pluralize( string ):
""" Correctly convert singular noung to plural noun. """
if string.endswith('y'):
plural = string[:-1] + 'ies'
elif string.endswith('us'):
plural = string[:-2] + 'i'
else:
plural = string + 's'
return plural |
def _crit(*args):
"""
return a dict of the criteria caracteristic. args need to be given in the keys order
used to reduce duplicate code
"""
keys = ["tooltip", "layer", "header", "content"]
return dict(zip(keys, args)) |
def merge_two_dicts(x, y):
"""Given two dicts, merge them into a new dict as a shallow copy."""
z = dict(x)
z.update(y)
return z |
def get_error_rate(predicted, actual):
"""Return the average error rate"""
error = 0
for i in range(len(predicted)):
error += abs(predicted[i][0] - actual[i][0])
return error/len(predicted) |
def keyboard_data_signals_an_interrupt(
keyboard_data, stop_signal_chars=frozenset(['\x03', '\x04', '\x1b'])
):
"""The function returns a positive stop signal (1) if the character is in the
`stop_signal_chars` set.
By default, the `stop_signal_chars` contains:
* \x03: (ascii 3 - End of Text)
* \... |
def show_user(username):
"""Some Comment"""
return 'Welcome: %s' % username |
def arrange_array_size(batch_size: int, array_size: tuple):
"""
Decide array size given batch size and array size [batch_size, height, width, channel].
:param batch_size: batch size
:param array_size: array (img) size
:return: final array size
"""
output = list(array_size)
output.insert(... |
def _check_func_names(selected, feature_funcs_names):
""" Checks if the names of selected feature functions match the available
feature functions.
Parameters
----------
selected : list of str
Names of the selected feature functions.
feature_funcs_names : dict-keys or list
Names... |
def empty(data):
"""
@type data : can be a list, string, dict
@rtype: boolean
"""
if data is None:
return True
if type(data) == list:
return len(data) == 0
if type(data) == dict:
return len(data.keys()) == 0
return '%s' % data == '' |
def hailstone(n):
"""Print out the hailstone sequence starting at n, and return the
number of elements in the sequence.
>>> a = hailstone(10)
10
5
16
8
4
2
1
>>> a
7
"""
"*** YOUR CODE HERE ***"
print(n)
if n <= 1:
return 1
else:
if n ... |
def func_bump(x, offset=0, amplitude=1, exponent=2):
"""
Function that looks like: __/\__ and which can be scaled.
:param x:
:param offset:
:param amplitude:
:param exponent:
:return:
"""
return offset + amplitude/(1 + x**exponent) |
def view_method(request):
"""Function that simulates a Django view.
"""
if hasattr(request, 'flash'):
request.flash.update()
return True
return False |
def get_custom_headers(manifest_resource):
"""Generates the X-TAXII-Date-Added headers based on a manifest resource"""
headers = {}
times = sorted(map(lambda x: x["date_added"], manifest_resource.get("objects", [])))
if len(times) > 0:
headers["X-TAXII-Date-Added-First"] = times[0]
head... |
def _sec_to_str(t):
"""Format time in seconds.
Parameters
----------
t : int
Time in seconds.
"""
from functools import reduce
return "%d:%02d:%02d.%02d" % \
reduce(lambda ll, b: divmod(ll[0], b) + ll[1:],
[(t*100,), 100, 60, 60]) |
def get_announcement(message, reminder_offset):
"""
Generates the announcement message
:param str message: Message about the event
:param number reminder_offset: Minutes in which event is about to happen
"""
pos = message.find(":")
if pos == -1:
activity = message.strip()
m... |
def getLoopSize(key, subjectNumber):
"""Reverse engineers the loop size from the given key and subject number.
This is done by continually dividing the key by the subject number
until the result matches 1.
If the result has decimal digits 20201227 gets added to the previous
key, before it is di... |
def clean_name(value):
""" remove bad character from possible file name component """
deletechars = r"\/:*%?\"<>|'"
for letter in deletechars:
value = value.replace(letter, '')
return value |
def Int(value):
"""Return the int of a value"""
n = float(value)
if -32767 <= n <= 32767:
return int(n)
else:
raise ValueError("Out of range in Int (%s)" % n) |
def concat(s):
"""This function takes a more user friendly regex (E.g: 'abc'), and
inserts '.' concat operators where appropriate. (E.g: 'a.b.c')"""
my_list = list(s)[::-1] # convert regex string to a reverse ordered list
# characters with special rules
special_characters = ['*', '|', '(', ')', '+... |
def allocate_receiver_properties(receivers, params, demand):
"""
Generate receiver locations as points within the site area.
Sampling points can either be generated on a grid (grid=1)
or more efficiently between the transmitter and the edge
of the site (grid=0) area.
Parameters
----------... |
def rivers_with_station(stations):
"""
Args:
stations: list of MonitoringStation objects
Returns:
A set of names (string) of rivers that have an associated monitoring station.
"""
rivers = set()
for s in stations:
rivers.add(s.river)
return rivers |
def _prefix_master(master):
"""Convert user-specified master name to full master name.
Buildbucket uses full master name(master.tryserver.chromium.linux) as bucket
name, while the developers always use shortened master name
(tryserver.chromium.linux) by stripping off the prefix 'master.'. This
function does ... |
def reformROIArray(data, x1, x2):
"""Loops through flat ROI array and turns into 2d ROI array"""
counter = 0
arr = []
tempArr = []
length = x2-x1
for i in range(len(data)):
if counter == length-1:
tempArr.append(data[i])
arr.append(tempArr)
tempArr = []
counter = 0
else:
... |
def remove_list_characters(some_list: list):
"""
:param some_list:
:return: The list as a string without the
default list characters [, [, `, and ,.
"""
return str(some_list).replace('[', '').replace(']', '').replace(',', '').replace("'", "") |
def get_table_id(current_page, objects_per_page, loop_counter):
"""
Calculate correct id for table in project page. This function is used only for pagination purposes.
"""
return ((current_page - 1) * objects_per_page) + loop_counter |
def interval(f,a,b,dx):
"""f must be previously defined. Gives the y-values of f over interval (a,b) with distance dx between each point"""
n = int((b-a)/dx)
return [f(a+i*dx) for i in range(n+1)] |
def spoiler(text):
"""Return text in a spoiler"""
return f"||{text}||" |
def _to_linear(x):
"""Converts a sRGB gamma-encoded value to linear"""
if x <= 0.04045:
return x/12.92
else:
return ((x + 0.055)/1.055)**2.4 |
def tidy_path(path):
"""Helper function for formatting a path
:param str path: path to be formatted
:return: formatted path
"""
if (not path.startswith('/')):
path = '/' + path
if (not path.endswith('/')):
path += '/'
return path |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.