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... |
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... |
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... |
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:
"""
retu... |
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 rep... |
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, rep... |
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... |
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_si... |
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:
... |
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 + ... |
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 ... |
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 ... |
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 (v... |
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(... |
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
i... |
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 ... |
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 == ... |
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_color... |
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
el... |
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
-------
... |
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... |
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... |
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:
... |
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... |
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 = []
f... |
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 (i... |
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 :mat... |
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... |
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 fr... |
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 lin... |
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,... |
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
... |
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 =... |
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 pres... |
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
... |
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... |
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... |
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])
... |
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 va... |
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:
... |
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 ... |
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 ch... |
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
... |
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... |
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
----------
... |
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... |
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 varia... |
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 s... |
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 ile... |
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 build... |
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.... |
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:
-----------------------------... |
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 yo... |
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... |
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.res... |
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
... |
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].ap... |
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
... |
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:
ret... |
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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.