content stringlengths 42 6.51k |
|---|
def _has_same_url(data_from_db:tuple, data:tuple):
"""
Returns true if two data share the same url.
Else returns false.
This method is craeted for comparing facebook data as
_is_same_data return false for same article where
pic url are different.
"""
if data_from_db == None:
return False
temp = tuple(data_f... |
def select_one_patient_instance(ids_):
""" Note: Will not be deterministic due to the set """
ids = set()
patient_ids = []
for id_ in ids_:
patient_id = id_.split('_')[0]
if patient_id in patient_ids:
continue
ids.add(id_)
patient_ids.append(patient_id)
re... |
def distHamming(lineA, lineB):
"""
Hamming distance
Input: two bytearrays of equal length
Output: number of differing bits
"""
if len(lineA) != len(lineB): raise ValueError("lineA and lineB need to be same length")
diffBits = 0
for i in range(len(lineA)):
a = lineA[i]
b... |
def config_lookup(key: str, d1: dict, d2: dict, d3: dict) -> str:
"""
Given three dictionaries, look up a configuration string, allowing overrides
d1 overrides d2 which overrides d3
"""
return d1.get(key, d2.get(key, d3.get(key, ""))) |
def get_min(fps, arrs):
""" Find the file with the current first row with the smallest start time """
return min([fp for fp in fps if not arrs[fp] is None], key=lambda fp: arrs.get(fp)[0][0]) |
def U(n):
"""
Effectively reduce the numbers that we bother to test
"""
return 3*n +1 |1 |
def color_percents(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
if val == 100:
color = 'green'
elif val >= 99:
color = 'greenyellow'
elif val >= 95:
color = 'yellow'
else:
... |
def defaultBBoxDeltaFun(w):
"""
When we reduce the width or height of a bounding box, we use this function to compute the deltaX or deltaY
, which is applied on x1 and x2 or y1 and y2
For instance, for horizontal axis
x1 = x1 + deltaFun(abs(x1-x2))
x2 = x2 + deltaFun(abs(x1-x2))
... |
def days_in_year_365(cycle=0, year=0):
"""Days of the year (365 days calendar).
Parameters
----------
cycle : int, optional
(dummy value).
year : int, optional
(dummy value).
Returns
-------
out : list of int
365 days of the year.
Notes
-----
Approp... |
def tvir_from_T_w(T, w):
"""T in L, w in kg/kg"""
t_vir = T*(1+0.61*w)
return t_vir |
def merge(*args, **kwargs):
"""
Merges several dictionaries. Checks for consistent values.
:param args: dictionaries
:return: merged dict
"""
ret = dict(args[0])
for d in args[1:] + (kwargs,):
for k in d:
if k in ret:
if d[k] != ret[k]:
... |
def detab(contents):
"""
Removes formatting tabs from Python code so it can be executed without a
syntax error
"""
lines = contents.splitlines()
# Removes empty beginning/ending lines
while len(lines) > 0 and lines[0].strip() == "":
lines = lines[1:]
while len(lines) > 0 and lin... |
def RGBtoHSL(r, g, b):
"""
Function manually written to convert RGB to HSL (not used anywhere)
"""
r, g, b = r / 255, g / 255, b / 255
min_channel = min(r, g, b)
max_channel = max(r, g, b)
delta = max_channel - min_channel
hue, saturation, lightness = 0, 0, 0
# Calculating hue
... |
def order_by_area(panels):
""" Returns a list of panel objects ordered by area.
:param panels: Input list of Panels
:return panels: Output list of sorted Panels
"""
def get_area(panel):
return panel.area
panels.sort(key=get_area)
return panels |
def flatten(d):
"""Return a dict as a list of lists.
>>> flatten({"a": "b"})
[['a', 'b']]
>>> flatten({"a": [1, 2, 3]})
[['a', [1, 2, 3]]]
>>> flatten({"a": {"b": "c"}})
[['a', 'b', 'c']]
>>> flatten({"a": {"b": {"c": "e"}}})
[['a', 'b', 'c', 'e']]
>>> flatten({"a": {"b": "c", "... |
def str_to_bool(string, true_options=("yes", "y", "true"),
false_options=("no", "n", "false")):
"""Convert string to boolean, e.g. for parsing shell input
parameters
----------
string : str or bool
string to convert to bool (case insensitive)
true_options : [str]
(l... |
def add_try_clause(code, excpt):
"""Add a try/except clause, excepting 'excpt' around code."""
code = code.replace('\t', ' ')
return ("try:\n" + '\n'.join([" " + line for line in code.split('\n')])
+ "\nexcept " + excpt.__name__ + ":\n pass") |
def system(_evaluator, ast, _state):
"""Evaluates the instance system initialization."""
return ast["processNames"] |
def binomial(n, k):
"""
Computes n chooses k
:param n: number of items to choose from
:param k: number of items chosen
:return: n chooses k
"""
if 2 * k > n:
return binomial(n, n - k)
if k < 0 or k > n:
return 0
r = 1
for i in range(1, k + 1):
r = (r * (n ... |
def sow2dow(sow):
""" GPS seconds of week to day of week
"""
if sow < 0 or sow > 86400e0 * 7:
raise RuntimeError('[ERROR] gnssdates::sow2dow Invalid date.')
return int(sow) // 86400 |
def reverse(lst):
"""returns the input of a list of elements, but in reverse order"""
if(lst == []):
return []
return reverse(lst[1:]) + [lst[0]]
#add first index to the end - this works because the lst is not updated
#until the end!!! |
def get_product_bucket(volatile: bool = False) -> str:
"""Retrurns correct s3 bucket."""
return "cloudnet-product-volatile" if volatile else "cloudnet-product" |
def extract_bids_identifier_from_caps_filename(caps_dwi_filename):
"""Extract BIDS identifier from CAPS filename"""
import re
m = re.search(r'(sub-[a-zA-Z0-9]+)_(ses-[a-zA-Z0-9]+).*_dwi',
caps_dwi_filename)
if m is None:
raise ValueError('Input filename is not in a CAPS compl... |
def add_default_module_params(module_parameters):
"""
Adds default fields to the module_parameters dictionary.
Parameters
----------
module_parameters : dict
Returns
-------
module_parameters : dict
Same as input, except default values are added for the following fields:
... |
def cluster_spec(num_workers, num_ps, port=12222):
"""
More tensorflow setup for data parallelism
"""
cluster = {}
all_ps = []
host = '127.0.0.1'
for _ in range(num_ps):
all_ps.append('{}:{}'.format(host, port))
port += 1
cluster['ps'] = all_ps
all_workers = []
for _ in... |
def pairs(N):
"""
Returns the ordered set of pairs of elements in {0, ..., N-1} for iterating.
"""
pind=[]
for i in range(N):
for j in range(i+1,N): pind.append((i,j))
return pind |
def last_prime(L):
"""Returns the last prime in the list L.
Parameters
----------
L : list
A list of primes.
Returns
-------
lastPrime : int
The first prime in the list L.
"""
for i in range(len(L)-1, 0, -1):
if L[i] <= 1:
continue
for j... |
def tempfile_name(tfile):
"""get the name of a temp file"""
if tfile:
return tfile.name
return '' |
def bits2MiB(bits):
"""
Convert bits to MiB.
:param bits: number of bits
:type bits: int
:return: MiB
:rtype: float
"""
return bits / (8 * 1024 * 1024) |
def set_control_user(user_id, prefix='', rconn=None):
"""Set the user who has current control of the telescope and resets chart parameters.
Return True on success, False on failure"""
if user_id is None:
return False
if rconn is None:
return False
try:
rconn.set(prefix+'vi... |
def is_prime(number):
"""Return True if *number* is prime."""
for element in range(2, number): # Don't use 0 and 1
if number % element == 0:
return False
return True |
def state_from_scratch(args: tuple, kwargs: dict) -> dict:
"""Create pipeline state from (args, kwargs)."""
state = {i: v for i, v in enumerate(args)}
state.update(kwargs)
return state |
def mat_splice(matrix, r, c):
"""
Function which returns a matrix with the first r rows and first c
columns of the original matrix
"""
result = list()
for i in range(r):
row = matrix[i]
result.append(row[:c])
return result |
def get_idx_from_sent(sent, word_idx_map):
"""
Transforms sentence into a list of indices. Pad with zeroes.
"""
x = []
words = sent.split()
for word in words:
if word in word_idx_map:
x.append(word_idx_map[word])
else:
x.append(1)
return x |
def shift_list(l, x):
"""
shift_list(l, x)
Shifts all values in a list l, by x.
"""
return [i+x for i in l] |
def reverse(xfrom, xto):
"""
reverse(xfrom, xto)
xto is reverse of xfrom.
"""
n = len(xfrom)
return [xto[i] == xfrom[n-i-1] for i in range(n)] |
def clean_whitespace(string, compact=False):
"""Return string with compressed whitespace."""
for a, b in (('\r\n', '\n'), ('\r', '\n'), ('\n\n', '\n'),
('\t', ' '), (' ', ' ')):
string = string.replace(a, b)
if compact:
for a, b in (('\n', ' '), ('[ ', '['),
... |
def generate_soiud_from_seriesuid(default_series_uid, instance_number):
"""Fabricate a new sop instance uid."""
return default_series_uid + '.' + str(instance_number) |
def make_mean_error_trace(mean_recon_error):
"""
Sert marker for mean error of sample file
"""
mean_error_trace = dict(visible=True,
type='scatter',
x=[mean_recon_error],
y=[5],
mode='markers'... |
def findRunTests(lines):
""" From the lines of the build output, figures out which tests were run
Parameters
----------
lines : list of str
The lines of the build output file
Returns
-------
list of str
A list of the names of the tests that were run
"""
ran = []
... |
def convert_labels_iwp_to_scalabel( iwp_labels ):
"""
Converts IWP labels to Scalabel labels.
NOTE: This create a Scalabel label, not a *frame*.
Takes 1 argument:
iwp_labels - List of IWP labels to convert.
Returns 1 value:
scalabel_labels - List of converted Scalabel labels.
"... |
def modify_new_values(tmp_attr_names, attr_names_list, attr_dictionary):
""" Set new data set attributes """
new_attr_names = []
for attr in attr_names_list:
if attr in tmp_attr_names:
new_attr_names.append(attr)
else:
attr_dictionary.pop(attr)
attr_names_list = n... |
def sum_add(first, second):
"""Kind of cheating to use Python's sum function."""
return sum([first, second]) |
def unfieldify(s, sep="_"):
"""
Makes a best effort to reverse the algorithm from `fieldify`.
Replaces instances of `sep` in `s` with a space and converts the result to
title case:
>>> unfieldify('the_xml_http_request_contained_data')
'The Xml Http Request Contained Data'
Args:
s ... |
def dequote(string: str) -> str:
""" Return string by removing surrounding double or single quotes. """
if (string[0] == string[-1]) and string.startswith(('\'', '"')):
return string[1:-1]
return string |
def disp_to_pos(disp_dx, disp_dy, cog_x, cog_y):
"""
Calculates source position in camera coordinates(x,y) from the reconstructed disp
Parameters:
-----------
disp: DispContainer
cog_x: float
Coordinate x of the center of gravity of Hillas ellipse
cog_y: float
Coordinate y of the ce... |
def escape_backticks(content):
"""
Replace any backticks in 'content' with a unicode lookalike to allow
quoting in Discord.
"""
return content.replace("`", "\N{ARMENIAN COMMA}").replace(":", "\N{RATIO}") |
def is_affirmative(key: str, config: dict, default=False) -> bool:
"""
Checks if the config value is one of true, yes, or on (case doesn't matter), default is False
Args:
key: to check
config: to lookup key in
default: if not found, False if not specified
Returns:
if th... |
def is_hidden(file_path):
"""Returns true if the file should not be uploaded to the site.
A file is hidden if its name or the name of any parent directory
begins with an underscore. For example, these files are not
published to the site, even if they appear in a content source
directory:
/fo... |
def sanitize_word(word):
"""returns word after replacing common punctuation with the empty string
"""
word = word.replace(".","").replace(",","").replace("?","").replace(":","")\
.replace("(","").replace(")","").replace("*","").replace(";","").replace('"',"").replace("!","")
word = word.replace(... |
def tuplesort(seq):
"""
Sort a list by a sequence.
Parameters
----------
seq : tuple
Sequence to sort by
"""
return sorted(range(len(seq)), key=seq.__getitem__) |
def shortest_path_search(start, successors, is_goal):
"""Find the shortest path from start state to a state
such that is_goal(state) is true."""
if is_goal(start):
return [start]
explored = set() # set of states we have visited
frontier = [ [start] ] # ordered list of paths we have blazed
... |
def create_section(title, content=[], version=None, date=None):
"""Each section has a title and a list of content objects.
Each content object is either a text or a list object.
"""
result = dict(title=title, content=content)
if version:
result['version'] = version
result['date'] = date
... |
def location_to_hex(location):
"""convert location to hex for display"""
return "%08X" % location |
def key_has_dollar(d):
"""Recursively check if any key in a dict contains a dollar sign."""
for k, v in d.items():
if k.startswith('$') or (isinstance(v, dict) and key_has_dollar(v)):
return True |
def _is_valid_timestamp(timestamp):
"""
Determines if the timestamp for is valid.
Args:
timestamp (str): Time stamp string in question
Returns:
bool: Whether or not the time stamp is valid.
"""
if type(timestamp) != str:
return False
return True |
def combine_slices(slice1, slice2, length):
"""
Given two slices that can be applied to a 1D array and the length of that
array, this returns a new slice which is the one that should be applied to
the array instead of slice2 if slice1 has already been applied.
"""
beg1, end1, step1 = slice1.ind... |
def truncate_text(text, cutoff=11):
"""Cut off outputs that exceed 11 lines.
"""
t = text.split('\n')
if len(t) > cutoff:
t = t[:cutoff]
t.append('[Output truncated]')
return '\n'.join(t)
else:
return text |
def get_lc_cwt_params(mode: str) -> dict:
"""
Return sane default values for performing CWT based peak picking on LC data.
Parameters
----------
mode : {"hplc", "uplc"}
HPLC assumes typical experimental conditions for HPLC experiments:
longer columns with particle size greater than ... |
def extract_ratelimit ( headers_dict ):
"""Returns rate limit dict, extracted from full headers.
"""
return {
'used' : int(headers_dict.get('X-RateLimit-Used',0)),
'expire' : float(headers_dict.get('X-RateLimit-Expire',0)),
'limit' : int(headers_dict.get('X-RateLimit-Limit', 0)),
'remain' : int(headers_dic... |
def build_feature_dict(opt):
"""Make mapping of feature option to feature index."""
feature_dict = {}
if opt['use_in_question']:
feature_dict['in_question'] = len(feature_dict)
feature_dict['in_question_uncased'] = len(feature_dict)
if opt['use_tf']:
feature_dict['tf'] = len(fea... |
def url_get_parent(url):
"""
http://one/two/three => http://one/two
http://one => http://one
"""
index = url.rfind("/")
if index > 8: # avoid https://
return url[0:index]
else:
return url |
def obs_filter_step(distance, view):
"""
Perfectly observe the agent if it is within the observing agent's view. If
it is not within the view, then don't observe it at all.
"""
return 0 if distance > view else 1 |
def assign( from_signal_name, to_signal_name ):
"""
generate code to assign a value
- from_signal_name
- to_signal_name
"""
return to_signal_name + ' = ' + from_signal_name + ';\n' |
def shift_speed(speed_series, shift, dt):
"""Given series of speeds, returns the speed shifted by 'shift' amount of time.
speed_series is a list speeds with constant discretization dt. We assume that the last entry in
speed_series is the current speed, and we want the speed from shift time ago. If shift is... |
def _copy_block(block):
"""
Makes a copy of block as used by 'partition_block'
"""
new_block = []
if isinstance(block[0], list):
for row in block:
new_block.append(list(row))
else: #isinstance(block, list)
new_block = list(block)
return new_block |
def point_in_quadrilateral(pt_x, pt_y, corners):
"""point in quadrilateral"""
ab0 = corners[2] - corners[0]
ab1 = corners[3] - corners[1]
ad0 = corners[6] - corners[0]
ad1 = corners[7] - corners[1]
ap0 = pt_x - corners[0]
ap1 = pt_y - corners[1]
abab = ab0 * ab0 + ab1 * ab1
abap =... |
def hex_xor(hexdata1, hexdata2):
"""Takes 2 equal length hex encoded buffers and returns their xor combination"""
if (len(hexdata1) != len(hexdata2)): # Asserts size matching
return "Not Compatible Sizes"
dec1 = int(hexdata1, 16)
dec2 = int(hexdata2, 16)
xor = dec1 ^ dec2
return hex(xor... |
def is_divisible_by_6(s):
"""Return a list of all numbers divisible by 6 given input string and asterisk
replaced by a digit."""
if s == '*': return ['6']
out = []
num = [c for c in s]
idx = num.index('*')
for n in range(10):
num[idx] = str(n)
if int(num[-1]) % 2 == 0 and sum... |
def assign_label(sample, classes, case_sensitive):
"""
This simplistic function will go through each class in order,
it stops once it finds a class which is contained in the sample string.
"""
label = '__no_class__'
flag = 'go'
for current_class in classes:
if flag == 'go':
... |
def foam_add_path(*args):
"""A string with args prepended to 'PATH'"""
return '"' + ':'.join(args) + ':${PATH}"' |
def _get_identifiers(item):
"""Pull identifiers from an item into a dict."""
identifiers = {"eissn": "", "issn": "", "doi": "", "prop_id": "", "isbn": ""}
for identifier in item["Item_ID"]:
if identifier["Type"] == "Print_ISSN":
identifiers["issn"] = identifier["Value"]
elif iden... |
def autoparse(text):
"""
Guesse the type of a value encoded in a string and parses
"""
# int
try:
return int(text)
except:
pass
# float
try:
return float(text)
except ValueError:
pass
# string
return text |
def highProbabilityContours(contourList, threshold):
"""Deprecated. Returns set with contours that have confidence above a certain threshold."""
highProbabilityContourList = []
#for contour in contours[0:2000:10]:
for contour in contourList:
#mitochondriaLikeness = contour.features['mitochondr... |
def split_rule(rule):
"""
>>> split_rule('AB/CD')
[['A', 'B'], ['C', 'D']]
"""
return [list(row) for row in rule.split('/')] |
def nested_lookup(n, idexs):
"""Function to fetch a nested sublist given its nested indices.
Parameters
----------
n: list,
the main list in which to look for the sublist
idexs: list,
the indices of the sublist
Returns
-------
list: sublist with given indices
"""... |
def signal_received_anchors(anchor_info):
""" Assume that we receive the signal from 10 anchors. """
anchor_info_ids = list(anchor_info.keys())
anchor_info_coords = list(anchor_info.values()) # all anchors in system
signal_received_anchor_info = dict()
sig = 10
for cnt in range(sig):
... |
def isabn(obj):
"""isabn(string or int) -> True|False
Validate an ABN (Australian Business Number).
http://www.ato.gov.au/businesses/content.asp?doc=/content/13187.htm
Accepts an int or a string of exactly 11 digits and no leading zeroes.
Digits may be optionally separated with spaces. Any other i... |
def bit_length(x):
"""
Calculate the bit length of an integer.
"""
n = 0
while x > 0:
x >>= 1
n += 1
return n |
def intcode_six(parameter_list, code_list, i):
"""If first parameter is zero, sets instruction pointer to second parameter. Returns i"""
if parameter_list[0] == 0:
i = parameter_list[1]
return i |
def filter_none(data, split_by_client=False):
"""This function filters out ``None`` values from the given list (or list of lists, when ``split_by_client`` is enabled)."""
if split_by_client:
# filter out missing files and empty clients
existing_data = [
[d for d in client_data if d ... |
def _float2str(val):
""" Return accurate string value for float. """
return '%.16g' % val |
def score(matches):
"""Assign winning amplicon set id based on match stats"""
# naive: take max of all bins
m = 0
winner = None
for k, v in matches.items():
if v >= m:
m = v
winner = k
return winner |
def mul_interval(x, y):
"""Return the interval that contains the product of any value in x and any
value in y."""
p1 = x[0] * y[0]
p2 = x[0] * y[1]
p3 = x[1] * y[0]
p4 = x[1] * y[1]
return [min(p1, p2, p3, p4), max(p1, p2, p3, p4)] |
def process_unknown_mechanism(m: dict, domain: str) -> dict:
"""
this method is called if we get an unknown mechanism and returns an error
"""
return {"error": f"Unknown mechanism: {m['mechanism']}"} |
def binboolflip(item):
"""
Convert 0 or 1 to False or True (or vice versa).
The converter works as follows:
- 0 > False
- False > 0
- 1 > True
- True > 1
:type item: integer or boolean
:param item: The item to convert.
>>> binboolflip(0)
False
>>> binboolflip(False)
... |
def _check_spawnable(source_channels, target_channels):
"""Check whether gate is spawnable on the target channels."""
if len(target_channels) != len(set(target_channels)):
raise Exception('Spawn channels must be unique')
return source_channels.issubset(
set(target_channels)) |
def noConsecDups(theList):
"""
noConsecDups is a function that takes a list of items or
a string and returns a copy of that string list with no
consecutive duplicates
produces: the same list with any consecutive duplicates remove
example: noConsecDups([2,3,3,3,4,4,5,6,6,2,2,1,5,3,3,2]
produ... |
def forwardFilename(module):
"""Returns the generated forwards header filename for a module name."""
return module + "_generated_forwards.h" |
def filterEvents(eventDict, currentTime):
"""
:param eventDict: event dictionary at time Current time
:param currentTime: the time wanted to be taken care of
:return: dictionary of filtered events that are opened at time Current time
"""
return {e['id']: e for e in eventDict.values() if not e['a... |
def cleanup_report(report):
"""Given a dictionary of a report, return a new dictionary for output as
JSON."""
report_data = report
report_data["id"] = str(report["_id"])
report_data["user"] = str(report["user"])
report_data["post"] = str(report["post"])
del report_data["_id"]
r... |
def order_manually(sub_commands):
"""Order sub-commands for display"""
order = [
"switch",
"sync",
"publish",
"unpublish",
"undo",
"branches",
]
ordered = []
commands = dict(zip([cmd for cmd in sub_commands], sub_commands))
for k in order:
... |
def get_number_of_symbols(text, original_text):
"""
Get Text
Clean empty symbols
Get number of symbols
Return number of symbols in text
"""
clean_text = text
number_of_symbols_with_empty = len(original_text)
clean_text = clean_text.replace(' ', "")
number_of_sy... |
def calculate_difference(array: list, x: int) -> int:
"""
calculates the number of even elements given the difference between the value of x
Args:
array (list): integers to be calculated
x (int): difference between list numbers
Returns:
int: number of occurrences where the diff... |
def h4(text):
"""Heading 4.
Args:
text (str): text to make heading 4.
Returns:
str: heading 4 text.
"""
return '#### ' + text + '\r\n' |
def uppercase_each_word(string):
"""Uppercase the first letter of each word."""
if type(string) is not str:
raise ValueError("This is not a string")
return string.title() |
def to_text(lines):
"""Re-joins the lines into a single newline-separated string."""
return '\n'.join(lines) |
def simple_reduce_function(results):
"""general purpose reduce function that sums up the results
of previous activations of map functions """
total = 0
for map_result in results:
total = total + map_result
return total |
def is_yaml(file):
"""
Checks whether or not the specified file is a yaml-file.
Parameters
----------
file : str
The relative path to the file that should be checked.
Returns
-------
bool
Whether or not the specified file is a yaml-file.
"""
extension = file.spl... |
def get_indices(batch_size, window_size):
"""Retrieves batch indices for for source and target frames.
This is intended to be used with the UnderTheRadar model.
"""
src_ids = []
tgt_ids = []
for i in range(batch_size):
for j in range(window_size - 1):
idx = i * window_size... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.