content
stringlengths 42
6.51k
|
---|
def harmonic_epmi_score(pdict, wlist1, wlist2):
""" Calculate harmonic mean of exponentiated PMI over all word pairs
in two word lists, given pre-computed PMI dictionary
- If harmonic ePMI is undefined, return -inf
"""
total_recip_epmi = None
# Number of pairs for which PMI exists
N = 0
for word1 in wlist1:
for word2 in wlist2:
# Enforce alphabetical order in pair
pair = tuple(sorted([word1, word2]))
wi, wj = pair
if wi in pdict and wj in pdict[wi]:
if total_recip_epmi is None:
total_recip_epmi = 0
total_recip_epmi += 1/(2**pdict[wi][wj])
N += 1
if total_recip_epmi is not None:
return N/total_recip_epmi
else:
return float("-inf")
|
def alternate_solution(lines, draw_diagonal=False):
"""
Inspired by a few solutions I saw - instead of a graph, just use a dict with coordinates as keys
Also, splice in the crossed line counting to avoid a final sweep through the dict at the end
This solution should be faster, but harder to troubleshoot, as you cannot just print out the graph
"""
from collections import defaultdict
graph = defaultdict(int)
crossing_lines = 0
# add coordinates to the "graph":
for line in lines:
x1, y1, x2, y2 = line[0], line[1], line[2], line[3]
# vertical line:
if x1 == x2:
for i in range(min(y1, y2), max(y1, y2)+1):
graph[(i, x1)] += 1
if graph[(i, x1)] == 2:
crossing_lines += 1
# horizontal line:
elif y1 == y2:
for i in range(min(x1, x2), max(x1, x2)+1):
graph[(y1, i)] += 1
if graph[(y1, i)] == 2:
crossing_lines += 1
# everything else must be a diagonal line:
elif draw_diagonal:
if x1 > x2:
# ensure x increases from x1 to x2
x1, y1, x2, y2 = line[2], line[3], line[0], line[1]
while x1 <= x2:
graph[(y1, x1)] += 1
if graph[(y1, x1)] == 2:
crossing_lines += 1
x1 += 1
if y1 < y2:
y1 += 1
else:
y1 -= 1
return crossing_lines
|
def period2pos(index, date):
"""Returns the position (index) of a timestamp vector.
Args:
index (list): timestamp vector.
date (string): date to search.
Returns:
position (int): position of date in index.
"""
x = [i for i, elem in enumerate(index) if elem == date]
if x == []:
raise ValueError('Date does not exists: ' + date.__repr__())
return x[0]
|
def export_locals(glob,loc):
"""
Combines two dictionaries.
:return: combined dictionary.
"""
glob = glob.copy()
glob.update(loc)
return glob
|
def g(x, y):
"""Constraint penalty"""
return (x + 5) ** 2 + (y + 5) ** 2 - 25
|
def add_not_to_str(a_str, not_):
"""
Prefix a string with a not depending on the bool parameter
>>> add_not_to_str("hello", True) # "hello"
>>> add_not_to_str("hello", False) # "not hello"
:param a_str:
:type a_str:
:param add_not:
:type not_:
:return:
:rtype:
"""
return "{}{}".format(
"" if not_ else "not ", a_str)
|
def chomp_element(base, index, value):
"""Implementation of perl = and chomp on an array element"""
if value is None:
value = ''
base[index] = value.rstrip("\n")
return len(value) - len(base[index])
|
def unescape(inp, char_pairs):
"""Unescape reserved characters specified in the list of tuples `char_pairs`
Parameters
----------
inp : str
Input string
Returns
-------
str
Unescaped output
See also
--------
escape_GFF3
"""
for repl, char_ in reversed(char_pairs):
inp = inp.replace(char_, repl)
return inp
|
def has_rep(chrn, rfrom, rto, rstrand, rep_pos):
"""
Return the names of the REP elements in the region
Arguments:
- `chrn`: chromosome name
- `rfrom`: region from
- `rto`: region to
- `rstrand`: region strand
- `rep_pos`: REP positions dictionary
"""
reps = []
for repel, repp in rep_pos.items():
if repp[0] == chrn and repp[3] == rstrand:
if repp[1]<rto and repp[2]>=rfrom:
reps.append(repel)
return reps
|
def _update_progress(
start_time,
current_time,
progress_increment,
current_progress,
total,
unit,
callback_function,
):
"""Helper function for updating progress of a function and making a call to the progress callback
function, if provided. Adds the progress increment to the current progress amount and returns the
updated progress amount.
If provided, the callback function should accept the following parameters:
- update (int): change in progress since last call
- progress (int): the progress so far in the calculations
- total (int): the total number of calculations to do
- unit (str): unit of measurement for progress/total
- time_elapsed (float): total time in seconds elapsed since start of call
"""
if callback_function is not None:
new_progress = current_progress + progress_increment
elapsed_time = current_time - start_time
callback_function(progress_increment, new_progress, total, unit, elapsed_time)
return new_progress
|
def filer_actions(context):
"""
Track the number of times the action field has been rendered on the page,
so we know which value to use.
"""
context['action_index'] = context.get('action_index', -1) + 1
return context
|
def get_floor_for_offer(item, *args, **kwargs):
""" Parse information about number of the floor
:param item: Tag html found by finder in html markup
:return: Number of the floor or None if information not given
:rtype: int, None
"""
if not item:
return None
floor = item.find_next_sibling().text
return int(floor) if floor != 'Parter' else 0
|
def factorize_names(list_of_list_of_names):
"""
Factorize the list of list of names so that we can extract
the common parts and return the variable parts of the name
Args:
list_of_list_of_names: a list of [name1, name2, ..., nameN]
Returns:
"""
if len(list_of_list_of_names) == 0:
return None, None
factorized = []
list_of_names = []
rotated_list_of_names = list(zip(*list_of_list_of_names))
for values in rotated_list_of_names:
unique_values = set(values)
if len(unique_values) == 1:
factorized.append(values[0])
else:
list_of_names.append(values)
list_of_names = list(zip(*list_of_names))
if len(list_of_names) == 0:
list_of_names = [''] # we MUST have hat least 1 name even if eveything is factorized
assert len(list_of_list_of_names) == len(list_of_names)
return factorized, list_of_names
|
def currency(x, pos):
"""The two args are the value and tick position"""
if x > 1e6:
s = '${:1.1f}M'.format(x*1e-6)
else:
s = '${:1.0f}K'.format(x*1e-3)
return s
|
def closedIntegral(l, omegas) :
"""
Let :math:`e` denote :py:obj:`len(omegas)`.
This function computes the integral of
.. math::
\\prod_{1 \leq i \leq e} \\frac{1}{1-\\psi_i/\\omega_i} := \\sum_{j_1,...,j_e} \\prod_i \\left(\\frac{\\psi_i}{\\omega_i}\\right)^{j_i}
over :math:`\\overline{\\mathcal{M}}_{0,l + e}`.
If :math:`l + e < 3` this is just the unit class. Otherwise, we apply the string equation (see Exercise 25.2.8 in `MS book <http://www.claymath.org/library/monographs/cmim-1.pdf>`_) and simplify to find this is just
.. math::
(\\sum_i \\frac{1}{\\omega_i})^{l + e -3}
"""
dim = max(l + len(omegas)-3,0)
return sum(o**(-1) for o in omegas)**dim
|
def linear_fit(x, a, b):
"""
Linear function used to fit CPI data
"""
return a * x + b
|
def make_commands(xtv2dmx_executable: str,
xtv_filenames: list,
dmx_filenames: list) -> list:
"""Create list of shell command to convert xtv files into dmx files
The conversion includes compression to reduce space requirements
:param xtv2dmx_executable: the name of the xtv2dmx executable
:param xtv_filenames: the list of xtv filenames to be converted
:param dmx_filenames: the list of dmx filenames as target output
:return: a list of xtv2dmx shell command to be executed
"""
xtv2dmx_commands = []
for xtv_filename, dmx_filename in zip(xtv_filenames, dmx_filenames):
xtv2dmx_command = [xtv2dmx_executable,
"-r", xtv_filename,
"-d", dmx_filename]
xtv2dmx_commands.append(xtv2dmx_command)
return xtv2dmx_commands
|
def check_title(title):
"""
Verifies that the title is alphanumeric, lacks leading and trailing spaces,
and is within thespecified length (<80 characters)
:param title: the title to be checked
:return: True if title meets criteria, False otherwise
"""
# iterate over string and return False if any character
# is neither alphanumeric nor a space
for char in title:
if (not char.isalnum()) and (not char.isspace()):
return False
# Could just use strip here, but I'm following the project
# guidelines as written
if title.startswith(" ") or title.endswith(" "):
return False
if len(title) > 80:
return False
return True
|
def check_similarity(var1, var2, error):
"""
Check the simulatiry between two numbers, considering a error margin.
Parameters:
-----------
var1: float
var2: float
error: float
Returns:
-----------
similarity: boolean
"""
if((var1 <= (var2 + error)) and (var1 >= (var2 - error))):
return True
else:
return False
|
def labels_to_dict(labels: str) -> dict:
"""
Converts labels to dict, mapping each label to a number
Args:
labels:
Returns: dictionary of label -> number
"""
return dict([(labels[i], i) for i in range(len(labels))])
|
def read_cmd(argv):
"""
splits a list of strings `'--flag=val'` with combined flags and args
into a dict: `{'flag' : 'val'}` (lstrips the dashes)
if flag `' flag '` passed without value returns for that flag: `{'flag' : True}`
"""
output = {}
for x in argv:
x = x.lstrip('-')
pair = x.split('=',1)
if len(pair) < 2:
pair = pair + [True]
output[pair[0]] = pair[1]
return output
|
def get_l2_cols(names):
"""
Extract column names related to Layer 2
Parameters
----------
names : list
list with column names
Returns
-------
list
list containing only Layer 2 column names
"""
ret_names = []
for n in names:
if "RtGAMSE" in n: continue
if "RtGAM" in n: ret_names.append(n)
return(ret_names)
|
def wheel(pos):
"""Colorwheel."""
# Input a value 0 to 255 to get a color value.
# The colours are a transition r - g - b - back to r.
if pos < 0 or pos > 255:
return (0, 0, 0)
if pos < 85:
return (255 - pos * 3, pos * 3, 0)
if pos < 170:
pos -= 85
return (0, 255 - pos * 3, pos * 3)
pos -= 170
return (pos * 3, 0, 255 - pos * 3)
|
def get_month(month):
"""
convert from a month string to a month integer.
"""
if month == "Jan" :
return 1
elif month == "Feb" :
return 2
elif month == "Mar" :
return 3
elif month == "Apr":
return 4
elif month == "May" :
return 5
elif month == "Jun" :
return 6
elif month == "Jul" :
return 7
elif month == "Aug" :
return 8
elif month == "Sep" :
return 9
elif month == "Oct" :
return 10
elif month == "Nov" :
return 11
elif month == "Dec" :
return 12
else :
raise Exception("Invalid month string " + month)
|
def n_content(dna):
"""Calculate the proportion of ambigious nucleotides in a DNA sequence."""
ncount = dna.count('N') + dna.count('n') + \
dna.count('X') + dna.count('x')
if ncount == 0:
return 0.0
return float(ncount) / float(len(dna))
|
def gen_colors(num_colors):
"""Generate different colors.
# Arguments
num_colors: total number of colors/classes.
# Output
bgrs: a list of (B, G, R) tuples which correspond to each of
the colors/classes.
"""
import random
import colorsys
hsvs = [[float(x) / num_colors, 1., 0.9] for x in range(num_colors)]
random.seed(2333)
random.shuffle(hsvs)
rgbs = list(map(lambda x: list(colorsys.hsv_to_rgb(*x)), hsvs))
bgrs = [(int(rgb[2] * 255), int(rgb[1] * 255), int(rgb[0] * 255))
for rgb in rgbs]
return bgrs
|
def get_id_or_none(model):
"""
Django explodes if you dereference pk before saving to the db
"""
try:
return model.id
except:
return None
|
def make_custom_geoid(sumlev, feature_id):
"""
Generate a unique geoid for the given feature.
"""
return '%s_%s' % (sumlev, feature_id)
|
def difference(seq1, seq2):
"""
Return all items in seq1 only;
a set(seq1) - set(seq2) would work too, but sets are randomly
ordered, so any platform-dependent directory order would be lost
"""
return [item for item in seq1 if item not in seq2]
|
def dirname(path: str) -> str:
"""Get directory name from filepath."""
slash_i = path.rfind("/")
if slash_i == -1:
return ""
return path[:slash_i] if slash_i != 0 else "/"
|
def _from_exif_real(value):
"""Gets value from EXIF REAL type = tuple(numerator, denominator)"""
return value[0]/value[1]
|
def departition(before, sep, after):
"""
>>> departition(None, '.', 'after')
'after'
>>> departition('before', '.', None)
'before'
>>> departition('before', '.', 'after')
'before.after'
"""
if before is None:
return after
elif after is None:
return before
else:
return before + sep + after
|
def split_variant(variant):
"""
Splits a multi-variant `HGVS` string into a list of single variants. If
a single variant string is provided, it is returned as a singular `list`.
Parameters
----------
variant : str
A valid single or multi-variant `HGVS` string.
Returns
-------
list[str]
A list of single `HGVS` strings.
"""
prefix = variant[0]
if len(variant.split(";")) > 1:
return ["{}.{}".format(prefix, e.strip()) for e in variant[3:-1].split(";")]
return [variant]
|
def set_value(matrix: list, cell: tuple, value: str) -> list:
""" Changes the value at the x, y coordinates in the matrix """
row, col = cell
matrix[row][col] = value
return matrix
|
def get_engine_turbo(t):
"""
Function to get turbo or regular for engine type
"""
tt = t.split(" ")[-1]
if "turbo" in tt:
return "turbo"
return "regular"
|
def _extract_etag(response):
""" Extracts the etag from the response headers. """
if response and response.headers:
return response.headers.get('etag')
return None
|
def offset_stopword(rank):
"""Offset word frequency rankings by a small amount to take into account the missing ranks from ignored stopwords"""
return max(1, rank - 160)
|
def collatz(number):
"""Main function, if the number is even, // 2, if odd, * by 3 and add 1."""
if number % 2 == 0:
print(number // 2)
return number // 2
else:
print(3 * number + 1)
return 3 * number + 1
|
def copy_graph(graph):
"""
Make a copy of a graph
"""
new_graph = {}
for node in graph:
new_graph[node] = set(graph[node])
return new_graph
|
def parse_node_list(node_list):
"""convert a node into metadata sum, remaining list"""
number_of_children = node_list.pop(0)
metadata_entries = node_list.pop(0)
metadata_total = 0
# make a copy of the list so we don't disturb the caller's version
remaining_list = node_list[:]
while number_of_children > 0:
metadata_from_kid, remaining_list = parse_node_list(remaining_list)
metadata_total += metadata_from_kid
number_of_children -= 1
while metadata_entries > 0:
# we should just have metadata remaining. Pop it
metadata_total += remaining_list.pop(0)
metadata_entries -= 1
return metadata_total, remaining_list
|
def format_seconds(duration, max_comp=2):
"""
Utility for converting time to a readable format
:param duration: time in seconds and miliseconds
:param max_comp: number of components of the returned time
:return: time in n component format
"""
comp = 0
if duration is None:
return '-'
# milliseconds = math.modf(duration)[0]
sec = int(duration)
formatted_duration = ''
years = sec / 31536000
sec -= 31536000 * years
days = sec / 86400
sec -= 86400 * days
hrs = sec / 3600
sec -= 3600 * hrs
mins = sec / 60
sec -= 60 * mins
# years
if comp < max_comp and (years >= 1 or comp > 0):
comp += 1
if days == 1:
formatted_duration += str(years) + ' year, '
else:
formatted_duration += str(years) + ' years, '
# days
if comp < max_comp and (days >= 1 or comp > 0):
comp += 1
if days == 1:
formatted_duration += str(days) + ' day, '
else:
formatted_duration += str(days) + ' days, '
# hours
if comp < max_comp and (hrs >= 1 or comp > 0):
comp += 1
if hrs == 1:
formatted_duration += str(hrs) + ' hr, '
else:
formatted_duration += str(hrs) + ' hrs, '
# mins
if comp < max_comp and (mins >= 1 or comp > 0):
comp += 1
if mins == 1:
formatted_duration += str(mins) + ' min, '
else:
formatted_duration += str(mins) + ' mins, '
# seconds
if comp < max_comp and (sec >= 1 or comp > 0):
comp += 1
if sec == 1:
formatted_duration += str(sec) + " sec, "
else:
formatted_duration += str(sec) + " secs, "
if formatted_duration[-2:] == ", ":
formatted_duration = formatted_duration[:-2]
return formatted_duration
|
def query_update(querydict, key=None, value=None):
"""
Alters querydict (request.GET) by updating/adding/removing key to value
"""
get = querydict.copy()
if key:
if value:
get[key] = value
else:
try:
del(get[key])
except KeyError:
pass
return get
|
def translate_toks(a_toks, a_translation):
"""Translate tokens and return translated set.
Args:
a_toks (iterable): tokens to be translated
a_translation (dict): - translation dictionary for tokens
Returns:
frozenset: translated tokens
"""
if a_translation is None:
return a_toks
ret = set()
for tok in a_toks:
for t_tok in a_translation[tok]:
ret.add(t_tok)
return frozenset(ret)
|
def slices(string, slice_size):
"""Return list of lists with size of given slice size."""
result = []
if slice_size <= 0 or slice_size > len(string):
raise ValueError
for i in range(len(string) + 1 - slice_size):
string_slice = string[i:i + slice_size]
slice_array = []
for character in string_slice:
slice_array.append(int(character))
result.append(slice_array)
return result
|
def get_midpoint(bounding_box):
""" Get middle points of given frame
Arguments:
----------
bounding_box : (width,height) or (x, y, w, h)
"""
if(len(bounding_box) == 2):
width, height = bounding_box
y = float(height) / float(2)
x = float(width) / float(2)
return (int(x), int(y))
if(len(bounding_box) == 4):
x, y, w, h = bounding_box
w = int(w)/2
h = int(h)/2
return(int(x) + int(w), int(y) + int(h))
|
def inv2(k:int) -> int:
""" Return the inverse of 2 in :math:`\mathbb{Z}/3^k \mathbb{Z}`. \
The element 2 can always be inverted in :math:`\mathbb{Z}/3^k \mathbb{Z}`. \
It means for all :math:`k` there exists :math:`y\in\mathbb{Z}/3^k \mathbb{Z}` \
such that :math:`2y = 1`. The value of :math:`y` is given by the formula :math:`\\frac{3^k+1}{2}`.
:Example:
>>> inv2(2)
5
>>> inv2(3)
14
"""
return (3**k + 1)//2
|
def get_values(column_to_query_lst, query_values_dict_lst ):
"""
makes flat list for update values.
:param column_to_query_lst:
:param query_values_dict_lst:
:return:
"""
column_to_query_lst.append("update")
values = []
for dict_row in query_values_dict_lst:
for col in column_to_query_lst:
values.append(dict_row[col])
return values
|
def calculateHandlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string int)
returns: integer
"""
# TO DO... <-- Remove this comment when you code this function
length = 0
for i in hand:
length += hand[i]
return length
|
def bubble_sort(array, ascending=True):
"""Sort array using bubble sort algorithm.
Parameters
----------
array : list
List to be sorted; Can contain any Python objects that can be compared
ascending : bool, optional
If True sort array from smallest to largest; False -> sort array from
largest to smallest
Returns
-------
list
Input array sorted.
"""
# Create copy to avoid modifying array inplace
array = array.copy()
# Use swap_count to keep track of number of swaps on each sweep
swap_count = 1
# Keep track of number of times array has been iterated over
sweep_count = 0
# Keep sweeping through array until no swaps need to occur
while swap_count > 0:
# Reset swap scount at beginning of sweep
swap_count = 0
for i in range(len(array) - sweep_count - 1):
# Swap pair of elements being compared if out of order
if array[i] > array[i+1]:
# Perform swap
temp = array[i+1]
array[i+1] = array[i]
array[i] = temp
# Increment swap count
swap_count += 1
# Increment sweep_count, to avoid checking elements that are already in
# correct order, at end of array
sweep_count += 1
if ascending:
return array
else:
# Reverse array for descending order sort
return array[::-1]
|
def galois_conjugate(a):
"""
Galois conjugate of an element a in Q[x] / (x ** n + 1).
Here, the Galois conjugate of a(x) is simply a(-x).
"""
n = len(a)
return [((-1) ** i) * a[i] for i in range(n)]
|
def remove_sas_token(sas_uri: str) -> str:
"""Removes the SAS Token from the given URI if it contains one"""
index = sas_uri.find("?")
if index != -1:
sas_uri = sas_uri[0:index]
return sas_uri
|
def read_arguments(t_input, split1="\n", split2="\""):
"""Function serves as a slave to read_cfg, it'll pull arguments from config lines."""
t_list = []
t_fulldata = str(t_input).split(split1)
for x in t_fulldata:
t_value = x.split(split2)
if len(t_value) != 3: # Check for an empty line
continue
t_list.append(t_value[1])
return t_list
|
def remove_extra_digits(x, prog):
"""
Remove extra digits
x is a string,
prog is always the following '_sre.SRE_Pattern':
prog = re.compile("\d*[.]\d*([0]{5,100}|[9]{5,100})\d*\Z").
However, it is compiled outside of this sub-function
for performance reasons.
"""
if not isinstance(x, str):
return x
result = prog.match(x)
if result:
decimals = result.string.split('.')[1]
result = result.string
if decimals[-3] == '0':
result = x[:-2].rstrip('0')
if decimals[-3] == '9':
result = x[:-2].rstrip('9')
try:
last_digit = int(result[-1])
result = result[:-1] + str(last_digit + 1)
except ValueError:
result = float(result[:-1]) + 1
#if result != x:
# print('changing {} to {}'.format(x, result))
return result
return x
|
def parse_notes(notes):
"""Join note content into a string for astrid."""
return "\n".join(
["\n".join([n.get('title'), n.get('content')]) for n in notes]
)
|
def iob_to_iob2(labels):
"""Check that tags have a valid IOB format. Tags in IOB1 format are converted to IOB2."""
for i, tag in enumerate(labels):
if tag == 'O':
continue
split = tag.split('-')
if len(split) != 2 or split[0] not in ['I', 'B']:
return False
if split[0] == 'B':
continue
elif i == 0 or labels[i - 1] == 'O': # conversion IOB1 to IOB2
labels[i] = 'B' + tag[1:]
elif labels[i - 1][1:] == tag[1:]:
continue
else:
labels[i] = 'B' + tag[1:]
return True
|
def get_sphere_inertia_matrix(mass, radius):
"""Given mass and radius of a sphere return inertia matrix.
:return: ixx, ixy, ixz, ixy, iyy, iyz, ixz, iyz, izz
From https://www.wolframalpha.com/input/?i=inertia+matrix+sphere
"""
ixx = iyy = izz = (2.0 / 5.0) * radius**2 * mass
ixy = 0.0
ixz = 0.0
iyz = 0.0
return [ixx, ixy, ixz, ixy, iyy, iyz, ixz, iyz, izz]
|
def median(lst, presorted=False):
"""
Returns the median of a list of float/int numbers. A lot of our median
calculations are done on presorted data so the presorted flag can be
set to skip unnecessary sorting.
:param lst: list
:param presorted: Boolean
:return: float
"""
if not presorted:
sorted_lst = sorted(lst)
else:
sorted_lst = lst
n = len(lst)
if n < 1:
return None
if n % 2 == 1:
return sorted_lst[n//2]
else:
return sum(sorted_lst[n//2-1:n//2+1])/2.0
|
def linear_growth_model(a_0, k, t):
"""Compute bacterial area using linear model.
:param a_0: initial area
:type a_0: float
:param k: growth rate
:type k: float
:param t: time since last division, in minutes
:type t: float
:return: estimated bacterial area based on provided parameters
:rtype: float
"""
return a_0 * (1 + k * t)
|
def _is_number(x):
""" "Test if a string or other is a number
Examples
--------
>>> _is_number('3')
True
>>> _is_number(3.)
True
>>> _is_number('a')
False
"""
try:
float(x)
return True
except (ValueError, TypeError):
return False
|
def transpose(list):
"""
a transpose command, rotates a mtrix or equivalent by 90
more like a transpose from R than anything else.
"""
newl = []
try:
rows = len(list[0])
except:
rows = 1 # probably.
cols = len(list)
for row in range(rows):
newl.append([0 for x in range(cols)])
for r in range(rows):
for c in range(cols):
newl[r][c] = list[c][r]
return(newl)
|
def _tpu_host_device_name(job, task):
"""Returns the device name for the CPU device on `task` of `job`."""
if job is None:
return "/task:%d/device:CPU:0" % task
else:
return "/job:%s/task:%d/device:CPU:0" % (job, task)
|
def _filter_features(example, keys):
"""Filters out features that aren't included in the dataset."""
return {
key: example[key] for key in keys
}
|
def subnote_text(content: str, publish=True):
"""
```
{
'jsonmodel_type': 'note_text',
'content': content,
'publish': publish
}
```
"""
return {
'jsonmodel_type': 'note_text',
'content': content,
'publish': publish
}
|
def maybe_download(train_data, test_data, test1_data=""):
"""Maybe downloads training data and returns train and test file names."""
if train_data:
train_file_name = train_data
else:
train_file_name = "training_data.csv"
if test_data:
test_file_name = test_data
else:
#test_file_name = "./data/test-1.csv"
test_file_name = "testing_data.csv"
if test1_data:
test1_file_name = test1_data
else:
test1_file_name = "test.csv"
#test_file_name = "./data/train-1.csv"
return train_file_name, test_file_name, test1_file_name
|
def _convert_coords_for_scatter(coords):
"""returns x, y coordinates from [(start_x, start_y), (end_x, end_y), ..]
Plotly scatter produces disjoint lines if the coordinates are separated
by None"""
new = {"x": [], "y": []}
for (x1, y1), (x2, y2) in coords:
new["x"].extend([x1, x2, None])
new["y"].extend([y1, y2, None])
# drop trailing None
x = new["x"][:-1]
y = new["y"][:-1]
return x, y
|
def get_recursively(search_dict, field):
"""
Takes a dict with nested lists and dicts, and searches all dicts for a key of the field provided.
"""
fields_found = set()
for key, value in search_dict.items():
if key == field:
if isinstance(value, list):
for x in value:
fields_found.add(x)
else:
fields_found.add(value)
elif isinstance(value, dict):
results = get_recursively(value, field)
for result in results:
fields_found.add(result)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = get_recursively(item, field)
for another_result in more_results:
fields_found.add(another_result)
return fields_found
|
def format_as_code_block(text_to_wrap: str) -> str:
"""
Wrap the text in a JIRA code block.
Args:
text_to_wrap: The text to wrap.
Returns:
A JIRA formatted code block.
"""
return "".join(["{code:java}", "{}".format(text_to_wrap), "{code}"])
|
def akirichards(vp1, vs1, rho1, vp2, vs2, rho2):
"""Aki-Richards linearisation of the Zoeppritz equations for A, B and C.
R(th) ~ A + Bsin2(th) + Csin2(th)tan2(th)
A = 0.5 (dVP/VP + dRho/rho)
B = dVp/2Vp - 4*(Vs/Vp)**2 * (dVs/Vs) - 2*(Vs/Vp)**2 * (dRho/rho)
C = dVp/2*Vp
Args:
vp1, vs1, vp2, vs2 (array-like [MxN]): velocities for 2 halfspaces
rho1, rho2 (array-like [MxN]): densities for 2 halfspaces
Returns:
(numpy.ndarray): Rp(theta)
"""
dvp = vp2 - vp1
dvs = vs2 - vs1
drho = rho2 - rho1
vp = (vp1 + vp2)/2.0
vs = (vs1 + vs2)/2.0
rho = (rho1 + rho2)/2.0
k = (vs/vp)**2
avo_a = 0.5 * (dvp/vp + drho/rho)
avo_b = dvp/(2*vp) - 4*k*(dvs/vs) - 2*k*(drho/rho)
avo_c = dvp/(2*vp)
return avo_a, avo_b, avo_c
|
def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
"""Compare if param1 is greater than param2.
Example function with PEP 484 type annotations.
`PEP 484`_ type annotations are supported. If attribute, parameter, and
return types are annotated according to `PEP 484`_, they do not need to be
included in the docstring:
The return type must be duplicated in the docstring to comply
with the NumPy docstring style.
Parameters
----------
param1
The first parameter.
param2
The second parameter.
Returns
-------
bool
True if successful, False otherwise.
Raises
------
ValueError
If `param2` is not a `str`.
TypeError
If `param1` is not an `int`
"""
result = None
try:
converted_param2 = int(param2)
if param1 > converted_param2:
result = True
else:
result = False
except ValueError:
print("Parameter 2 must be a string representing a number using digits [0-10]")
raise ValueError
except TypeError:
print("Parameter 1 must be an integer")
raise TypeError
print(f"Function called with: {param1} and {param2}")
print(f"Function returns: {result}")
return result
|
def r_det(td, r_i):
"""Calculate detected countrate given dead time and incident countrate."""
tau = 1 / r_i
return 1.0 / (tau + td)
|
def is_data_valid(data, check_for_name_too=False):
"""
validate the payload
must have age:int and city:str
"""
if 'age' not in data or \
'city' not in data or \
not isinstance(data['age'], int) or \
not isinstance(data['city'], str):
return False
if check_for_name_too:
if 'name' not in data or \
not isinstance(data['name'], str):
return False
return True
|
def rreplace(string, old, new):
"""Replaces the last occurrence of the old string with the new string
Args:
string (str): text to be checked
old (str): text to be replaced
new (str): text that will replace old text
Returns:
str: updated text with last occurrence of old replaced with new
"""
return new.join(string.rsplit(old, 1))
|
def html_section(title, fgcol, bgcol, contents, width=6,
prelude='', marginalia=None, gap=' '):
"""Format a section with a heading."""
if marginalia is None:
marginalia = '<tt>' + ' ' * width + '</tt>'
result = '''
<p>
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="%s">
<td colspan=3 valign=bottom> <br>
<font color="%s" face="helvetica, arial">%s</font></td></tr>
''' % (bgcol, fgcol, title)
if prelude:
result = result + '''
<tr bgcolor="%s"><td rowspan=2>%s</td>
<td colspan=2>%s</td></tr>
<tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap)
else:
result = result + '''
<tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap)
return result + '\n<td width="100%%">%s</td></tr></table>' % contents
|
def filterFields(obj, fields=[]):
"""
Filters out fields that are not in specified array
"""
return {k: v for k, v in obj.items() if k in fields}
|
def get_significance_filter(filters, field, significant_only=True):
""" This function returns the appropriate mask to filter on significance
of the given field. It assumes the filters are in the same order as the
output of get_significant_differences.
Parameters
----------
filters : tuple
The result of the call to get_significant_differences
field : string
The name of the field on which to filter. Valid options are:
* ribo
* rna
* te
is_significant : bool
Whether to return the "significant" filter (True, default) or
the "basic" filter
Returns
-------
significant_only : boolean mask
The appropriate mask for filtering for significance based on the
given field.
"""
# just map from the field to the index of the significant filters
index_map = {
"te": 0,
"rna": 1,
"ribo": 2
}
index = index_map[field]
if significant_only:
index += 3
return filters[index]
|
def insertionsort(a):
""" insertion sort implementation
>>> insertionsort([6, 4, 8, 2, 1, 9, 10])
[1, 2, 4, 6, 8, 9, 10]
"""
for i in range(len(a)):
item = a[i]
j = i
while j > 0 and a[j-1] > item:
a[j] = a[j-1]
j -= 1
a[j] = item
return a
|
def normalize_cdap_params(spec):
"""
The CDAP component specification includes some optional fields that the broker expects.
This parses the specification, includes those fields if those are there, and sets the broker defaults otherwise
"""
Params = {}
p = spec["parameters"]
#app preferences
Params["app_preferences"] = {} if "app_preferences" not in p else {param["name"] : param["value"] for param in p["app_preferences"]}
#app config
Params["app_config"] = {} if "app_config" not in p else {param["name"] : param["value"] for param in p["app_config"]}
#program preferences
if "program_preferences" not in p:
Params["program_preferences"] = []
else:
Params["program_preferences"] = []
for tup in p["program_preferences"]:
Params["program_preferences"].append({"program_id" : tup["program_id"],
"program_type" : tup["program_type"],
"program_pref" : {param["name"] : param["value"] for param in tup["program_pref"]}})
return Params
|
def any_heterozygous(genotypes):
"""Determine if any of the genotypes are heterozygous
Parameters
----------
genoytypes : container
Genotype for each sample of the variant being considered
Returns
-------
bool
True if at least one sample is heterozygous at the variant being
considered, otherwise False
"""
return bool(
{'0|1', '1|0', '0/1'}
& {genotype.split(':')[0] for genotype in genotypes}
)
|
def float_or_None(x):
"""Cast a string to a float or to a None."""
try:
return float(x)
except ValueError:
return None
|
def step(x):
"""
Step function
"""
return 1 * (x > 0)
|
def titleProcess(title: str) -> str:
"""Process the title, avoiding unnormal naming on Windows."""
replaceList = ["?", "\\", "*", "|", "<", ">", ":", "/", " "]
for ch in title:
if ch in replaceList:
title = title.replace(ch, "-")
return title
|
def format_float(number, decimals):
"""
Format a number to have the required number of decimals. Ensure no trailing zeros remain.
Args:
number (float or int): The number to format
decimals (int): The number of decimals required
Return:
formatted (str): The number as a formatted string
"""
formatted = ("{:." + str(decimals) + "f}").format(number).rstrip("0")
if formatted.endswith("."):
return formatted[:-1]
return formatted
|
def seeds2synids(a_germanet, a_terms, a_pos):
"""Convert list of lexical terms to synset id's.
@param a_germanet - GermaNet instance
@param a_terms - set of terms to check
@param a_pos - part-of-speech tag of the lexical term or None
@return list of synset id's
"""
ret = set()
for ilex in a_terms:
for ilexid in a_germanet.lex2lexid[ilex]:
for isynid in a_germanet.lexid2synids[ilexid]:
if a_pos is None or a_germanet.synid2pos[isynid] in a_pos:
ret.add(isynid)
return ret
|
def check_index(active_array, item):
"""Check row and column index of 2d array"""
for c in range(5):
for r in range(5):
if active_array[c][r] == item:
return [c, r]
|
def _get_standardized_platform_name(platform):
"""Return the native project standards platform name for the target platform string"""
if platform.lower() == 'darwin' or platform.lower() == 'macosx':
return 'macos'
if platform.lower()[:3] == 'win':
return 'win32' # true even for 64-bit builds
if platform.lower()[:3] == 'lin':
return 'linux'
|
def tokenize(chars: str) -> list:
"""
Converte uma string de caracteres em uma lista de tokens.
"""
### BEGIN SOLUTION
return chars.replace('(', ' ( ').replace(')', ' ) ').split()
### END SOLUTION
|
def observe_state(obsAction, oppID, oppMood, stateMode):
"""Keeping this as a separate method in case we want to manipulate the observation somehow,
like with noise (x chance we make an observational mistake, etc)."""
# print('oppmood', oppMood)
state = []
if stateMode == 'stateless':
state.append(obsAction)
elif stateMode == 'agentstate':
state.append(obsAction)
state.append(oppID)
elif stateMode == 'moodstate':
state.append(obsAction)
state.append(oppID)
state.append(oppMood)
# Returns a list, but this should be utilised as a tuple when used to key a Q value
# print('state:', state)
return state
|
def sort_repos(repo_list):
"""
Sort the repo_list using quicksort
Parameters
----------------------------------
repo_list : [gitpub.Repository()]
Array of friends (loaded from the input file)
=================================================
Returns:
-----------------------------------
repo_list : [gitpub.Repository()]
List of repositories sorted by number of stars
"""
if repo_list == []:
return []
else:
pivot = repo_list[0]
lesser = sort_repos([repo for repo in repo_list[1:] if repo.stargazers_count < pivot.stargazers_count])
greater = sort_repos([repo for repo in repo_list[1:] if repo.stargazers_count >= pivot.stargazers_count])
return lesser + [pivot] + greater
|
def ERR_UNKNOWNCOMMAND(sender, receipient, message):
""" Error Code 421 """
return "ERROR from <" + sender + ">: " + message
|
def format_msg(msg, com_typ, msg_dict=None):
"""Formats the given msg into a dict matching the expected format used by
nxt socket servers and clients.
:param msg: Object to be formatted as a socket message
:param com_typ: COM_TYPE constant
:param msg_dict: Optionally if you are combining commands you can pass an
existing msg_dict returned from a previous call to this function.
:return: dict
"""
if not msg_dict:
msg_dict = {}
msg_dict[com_typ] = msg
return msg_dict
|
def is_ufshost_error(conn, cloud_type):
"""
Returns true if ufshost setting is not resolvable externally
:type conn: boto.connection.AWSAuthConnection
:param conn: a connection object which we get host from
:type cloud_type: string
:param cloud_type: usually 'aws' or 'euca'
"""
ufshost = conn.host if cloud_type == 'euca' else ''
return ufshost in ['localhost', '127.0.0.1']
|
def exception_is_4xx(exception):
"""Returns True if exception is in the 4xx range."""
if not hasattr(exception, "response"):
return False
if exception.response is None:
return False
if not hasattr(exception.response, "status_code"):
return False
return 400 <= exception.response.status_code < 500
|
def get_digit(number: int, i_digit: int) -> int:
""" Get a digit from a number
Parameters
----------
number: int
number to get digit from
i_digit: int
index of the digit
Returns
-------
digit: int
digit or 0 if i_digit is too large
Notes
-----
`i_digit` does refer to a digit from the
lowest position counting. Thus
123 with `i_digit=0` is `3`.
"""
digit_list = []
def _get_digit_recursive(x: int):
if x < 10:
digit_list.append(x)
return x
else:
_get_digit_recursive(x // 10)
digit_list.append(x % 10)
# do the thing
_get_digit_recursive(number)
# revert list from smallest to biggest
digit_list = digit_list[::-1]
return digit_list[i_digit] if i_digit < len(digit_list) else 0
|
def is_empty_object(n, last):
"""n may be the inside of block or object"""
if n.strip():
return False
# seems to be but can be empty code
last = last.strip()
markers = {
')',
';',
}
if not last or last[-1] in markers:
return False
return True
|
def unpack(matrix):
"""
unpacks the matrix so that each column represent a single particle.
returns the new matrix
"""
numP = len(matrix[0])
unpacked = list()
for i in range(numP):
unpacked.append(list())
for j in matrix:
for k in range(numP):
unpacked[k].append(j[k])
return unpacked
|
def module_exists(module_name):
"""Test if a module is importable."""
try:
__import__(module_name)
except ImportError:
return False
else:
return True
|
def getTypeAndLen(bb):
""" bb should be 6 bytes at least
Return (type, length, length_of_full_tag)
"""
# Init
value = ''
# Get first 16 bits
for i in range(2):
b = bb[i:i + 1]
tmp = bin(ord(b))[2:]
#value += tmp.rjust(8,'0')
value = tmp.rjust(8, '0') + value
# Get type and length
type = int(value[:10], 2)
L = int(value[10:], 2)
L2 = L + 2
# Long tag header?
if L == 63: # '111111'
value = ''
for i in range(2, 6):
b = bb[i:i + 1] # becomes a single-byte bytes() on both PY3 and PY2
tmp = bin(ord(b))[2:]
#value += tmp.rjust(8,'0')
value = tmp.rjust(8, '0') + value
L = int(value, 2)
L2 = L + 6
# Done
return type, L, L2
|
def leapForwardColumn(l_, l):
"""
Returns the number of columns the toad moves forward when leaping from lane l_ to l.
When l and l_ are the same lane, then the number should just be 1.
"""
if l_ == l:
return 0 #1 if pos < self.m else 0
elif abs(l_) > abs(l) and l * l_ >= 0:
return 0
elif abs(l_) < abs(l) and l * l_ >= 0:
return abs(l - l_)
else:
return abs(l - l_) - abs(l_)
|
def get_settings_note(burl):
""" xxx """
ret = ''
description = 'To customize your newsfeed and select your default '+\
'market and asset class type <a href="'+\
burl +'settings/#'+'"><strong><SET> <GO></strong></a>'
ret = description
return ret
|
def distinct_elements(container, preserve_order=False):
"""
Returns distinct elements from sequence
while preserving the order of occurence.
"""
if not preserve_order:
return list(set(container))
seen = set()
seen_add = seen.add
return [x for x in container if not (x in seen or seen_add(x))]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.