content stringlengths 42 6.51k |
|---|
def strip_quotes(arg):
""" Strip outer quotes from a string.
Applies to both single and double quotes.
:param arg: str - string to strip outer quotes from
:return str - same string with potentially outer quotes stripped
"""
quote_chars = '"' + "'"
if len(arg) > 1 and arg[0] == arg[-1] an... |
def _finish_plot(ax, names, legend_loc=None, no_info_message="No Information"):
"""show a message in the axes if there is no data (names is empty)
optionally add a legend
return Fase if names is empty, True otherwise"""
if( not names ):
ax.text(0.5,0.5, no_info_message,
fon... |
def _priority_to_int(priority: str) -> int:
"""Get an int given a priority."""
priorities = {
"priority_critical": 90,
"priority_major": 70,
"priority_medium": 50,
"priority_low": 30,
}
return priorities.get(priority, 0) |
def get_type(object):
"""Convert a datetime.timedelta object into Days, Hours, Minutes, Seconds."""
return type(object).__name__ |
def mDistCompute(a, b):
"""Takes in two 1D arrays and computes sum of
manhattan distances. This function is an inner function of mDist()
"""
# Initialize the sum value
sum_dist = 0
# Both arrays must be of of the same length
length = len(a)
# Compute sum of differences
fo... |
def partial_product(start, stop):
"""Product of integers in range(start, stop, 2), computed recursively.
start and stop should both be odd, with start <= stop.
"""
numfactors = (stop - start) >> 1
if not numfactors:
return 1
elif numfactors == 1:
return start
else:
m... |
def get_process_data(indexes, processes):
"""Extract and label the process data from the ps command output.
Args:
indexes: dictionary with the indexes of the PID, PPID, and COMMAND headings in the column header
processes: array of the currently-running processes
Returns:
process_da... |
def parse_logistic_flag(kwargs):
""" Checks whether y_dist is binomial """
if "y_dist" in kwargs:
if kwargs["y_dist"] == "binomial":
return True
return False |
def diff_between_angles(angle_a: float, angle_b: float) -> float:
"""Calculates the difference between two angles angle_a and angle_b
Args:
angle_a (float): angle in degree
angle_b (float): angle in degree
Returns:
float: difference between the two angles in degree.
"""
de... |
def calculate_nps(scores):
"""Takes in a list of floats and returns the Net Promoter Score based
on those scores.
Args:
scores -- list of floats representing scores
Returns:
float -- Net Promoter Score from -100.0 to +100.0
"""
detractors, promoters = 0, 0
for s i... |
def str2dict(string):
"""Parse a str representation of a dict into its dict form.
This is the inverse of dict2str()
:param string: The string to parse.
:returns: A dict constructed from the str representation in string.
"""
res_dict = {}
for keyvalue in string.split(','):
(key, val... |
def get_crop_shape(dataset_name):
"""Returns cropping shape corresponding to dataset_name."""
if dataset_name == 'Pascal':
return (200, 272)
else:
raise ValueError('Unknown dataset name {}'.format(dataset_name)) |
def xds_detector_name(xia2_name):
"""Translate from a xia2 name from the detector library to an XDS detector
name."""
if "pilatus" in xia2_name:
return "PILATUS"
if "rayonix" in xia2_name:
return "CCDCHESS"
if "adsc" in xia2_name:
return "ADSC"
if "saturn" in xia2_name:
... |
def removeWords(answer):
"""Removes specific words from input or answer, to allow for more leniency."""
words = [' town', ' city', ' island', ' badge', 'professor ', 'team ']
answer = answer.lower()
for word in words:
answer = answer.replace(word, '')
return answer |
def hello(name = "person", lastname = "exposito"):
"""Function that prints "hello world!"""
"""print("Hello world!")"""
return f"Hello {name} {lastname}!" |
def get_resinum_to_resi_map(resiname_file, offset = 0, indexing = 1, aa_code = 3):
"""
This function returns a dictionary that relates the residue
number for a given system to a residue name. A PDB or prmtop file
for the system of interest is required. The string that comprises
the residue name (... |
def strip_newline(block):
"""
Strips any blank lines from the beginning and end of the block.
:param block: The block to parse.
:return: The block w/o the proceeding/trailing blank lines
"""
start = 0
end = len(block)
for line in block:
if line.strip():
break
... |
def is_valid_integer_response(response):
"""
Returns true if a integer response is valid.
str -> bool
"""
try:
return int(response)
except ValueError:
return False |
def region(lat, lon):
""" Return the SRTM1 region number of a given lat, lon.
Map of regions:
http://dds.cr.usgs.gov/srtm/version2_1/SRTM1/Region_definition.jpg
"""
if 38 <= lat and lat < 50 and -125 <= lon and lon < -111:
return 1
if 38 <= lat and lat < 50 and -111 <= ... |
def divisor(baudrate):
"""Calculate the divisor for generating a given baudrate"""
CLOCK_HZ = 50e6
return round(CLOCK_HZ / baudrate) |
def asset_france(gee_dir):
"""return the france asset available in our test account"""
return f"{gee_dir}/france" |
def indent(string, prefix):
""" a backward compatible textwrap.indent replacement """
if not string:
return ""
return "\n".join(prefix + l for l in string.splitlines()) |
def AFL(tlv_objects_list):
"""AFL():
"""
return tlv_objects_list.get('94', None) |
def comment(score, test):
"""Returns a comment on the complexity of text based on FRES and LIX."""
if (score > 90 and test == 'FRES') or (score < 25 and test == 'LIX'):
return ("Very easy to read", "5th grade")
elif (score > 80 and test == 'FRES') or (score < 30 and test == 'LIX'):
return ("... |
def get_command_line(pid):
"""
Given a PID, use the /proc interface to get the full command line for
the process. Return an empty string if the PID doesn't have an entry in
/proc.
"""
cmd = ''
try:
with open('/proc/%i/cmdline' % pid, 'r') as fh:
cmd = fh.read()
... |
def pretty_hex_str(byte_seq, separator=","):
"""Converts a squence of bytes to a string of hexadecimal numbers.
For instance, with the input tuple ``(255, 0, 10)``
this function will return the string ``"ff,00,0a"``.
:param bytes byte_seq: a sequence of bytes to process. It must be
compatible ... |
def _value_is_type_text(val):
"""
val is a dictionary
:param val:
:return: True/False
"""
if ((u'type' in val.keys()) and
(val['type'].lower() == u"text")):
return True
return False |
def word_score(word: str) -> int:
"""
A word's score is based on the length of the word:
1 point for 4-letter words, 5 points for 5-letter words,
6 points for 6-letter words, etc., plus a bonus of
7 points if the word contains 7 unique letters
"""
if len(word) == 4:
return 1
retu... |
def _remove_localizers_by_imagetype(dicoms):
"""
Search dicoms for localizers and delete them
"""
# Loop overall files and build dict
filtered_dicoms = []
for dicom_ in dicoms:
if 'ImageType' in dicom_ and 'LOCALIZER' in dicom_.ImageType:
continue
# 'Projection Image'... |
def exists(path):
"""
Check for file/URL existence with smart_open.
Recommended method at https://github.com/RaRe-Technologies/smart_open/issues/303
"""
try:
with open(path):
return True
except IOError:
return False |
def organize_reads(design: list):
"""
Organize reads
"""
samples = []
for sample in design:
reads = ','.join(sample[3:])
samples.append(f'{sample[0]},{sample[1]}_rep{sample[2]},{reads}')
return '\n'.join(samples) |
def fmeasure(precision, recall):
"""Computes f-measure given precision and recall values."""
if precision + recall > 0:
return 2 * precision * recall / (precision + recall)
else:
return 0.0 |
def evaluate_metrics(conf_matrix, label_filter=None):
"""
Evaluate Precision, Recall and F1 based on a confusion matrix as produced by `create_confusion_matrix`.
Args:
conf_matrix: a confusion matrix in form of a dictionary from `(gold_label,guess_label)` pairs to counts.
label_filter: a set... |
def chomp(text: str) -> str:
"""Remove any training spaces from string."""
return "\n".join([x.rstrip() for x in text.splitlines()]) |
def min(raw_metric):
"""
.. note:: Deprecated use `longMin`, `doubleMin' instead
"""
return {"type": "min", "fieldName": raw_metric} |
def number_of_neighbours_alive(board_array, cell_neighbours):
""" Returns the number of live cell neighbours of the given cell.
Parameters:
board_array (list(list(int, int...))): The 2D list representing the grid of cells
cell_neighbours (list(int, int...)): A list of integers representing the indexes of
... |
def set_xpath(blockette, identifier):
"""
Returns an X-Path String to a blockette with the correct identifier.
"""
try:
identifier = int(identifier)
except Exception:
msg = 'X-Path identifier needs to be an integer.'
raise TypeError(msg)
abbr_path = '/xseed/abbreviation_d... |
def indicator(cond):
"""Compute indicator function: cond ? 1 : 0"""
res = 1 if cond else 0
return res |
def ReadFileAsLines(file_path):
"""Read a file as a series of lines."""
with open(file_path) as f:
return f.readlines() |
def _fuzzy_match(match, search_string):
"""
Fuzzily matches match against search_string
e.g.: a_long_variable_name can be matched by:
alvn, aloname
but not:
a_bob, namebob, a_long_variable_name2
Args:
match |str| = The string to match against a list of strings
search_string |str| = The string... |
def mnormalize(matrix):
"""Scale a matrix according to the value in the center."""
width = len(matrix[0])
height = len(matrix)
factor = 1.0 / matrix[int(height / 2)][int(width / 2)]
if 1.0 == factor: return matrix
for i in range(height):
for j in range(width):
matrix[i][j] *= factor
return matrix |
def have_dollar_symbol(l):
"""Check dollar is present"""
if "$" in str(l):
return 1
else:
return 0 |
def filter_by_frequency(query_dict, reference_dict, score_modifier = 1):
"""
Compare the frequence of terms (keys) in query dict to the ones in the
reference dict
If the term have an higher frequency in the query_dict than in the
reference_dict then we keep it, it must be specific t... |
def point_is_on_frontier(point, cell_points):
""" Takes a point as an argument (as an (x, y) tuple) and decides whether the point is on the
edge of the given cell or not; this is done by checking whether any of the surrounding points
are still in the cell or not. The cell is specified by a list of points in... |
def factorial(n):
""" factorial """
if n == 0:
return 1
return n * factorial(n - 1) |
def append_missing_features(features, n_features):
"""Appends missing features to a list of features."""
all_features = range(n_features)
missing_features = [f for f in all_features if f not in features]
if len(missing_features):
features.append(missing_features)
return features |
def temp_pressure(p_temp, h_temp):
"""
Use this function as :attr:`~SenseEnviron.temp_source` if you want
to read temperature from the pressure sensor only. This is the default.
"""
# pylint: disable=unused-argument
return p_temp |
def render_dummy(title: str) -> str:
"""Render dummy markdown."""
return fr"""---
title: {title}
...
::: {{style="display:none"}}
$\,$
```c
```
:::
""" |
def is_end_offset_none(end_offsets: dict, start_offsets: dict) -> bool:
"""
Utility function to check if the partition that has start offset has end offset too.
:param end_offsets: topic partition and end offsets
:param start_offsets:topic partition and start offsets
:return: True/False
"""
... |
def mditem(indexlst, array):
"""
MDITEM indexlist array
outputs the member of the multidimensional ``array`` selected by
the list of numbers ``indexlist``.
"""
while indexlst:
array = array[indexlst[0]]
indexlst = indexlst[1:]
return array |
def is_valid_sender(sender):
"""Test if the sender config option is valid."""
length = len(sender)
if length > 1:
if sender[0] == '+':
return sender[1:].isdigit()
elif length <= 11:
return sender.isalpha()
return False |
def sum_to(options, goal, picks, force_take_all=False):
"""Returns numbers that sum as close to a goal value as possible.
options -- the numbers to select from
goal -- the value to attempt to sum to
picks -- the length of the list to be returned"""
selected = []
if not picks:
selected =... |
def division(a, b):
"""
Divides one operator from another one
Parameters:
a (int): First value
b (int): Second value
Returns:
int: division result
"""
if b == 0:
raise ValueError('Can not divide by zero')
return a / b |
def is_perfect_match(dict_a, dict_b):
"""Look for matching nsrid"""
try:
if dict_a['no-barnehage:nsrid'] == dict_b['no-barnehage:nsrid']:
return True
except KeyError:
pass
return False
# """A perfect match is in this case that all keys in a match those in b"""
# for ... |
def get_matches(lf, candidate_set, match_values=[1,-1]):
"""
A simple helper function to see how many matches (non-zero by default) an LF gets.
Returns the matched set, which can then be directly put into the Viewer.
"""
matches = []
for c in candidate_set:
label = lf(c)
if label... |
def smart_city_event_data(event_dict):
"""
Assembles smart_city event relevant data for transmission to smart_city cloud endpoint
params:
event_dict which contains event_type, speed, gps-coordinates, and time information
returns:
a dictionary that captures all the information that an insurance e... |
def serialize_uint32(n: int) -> bytes:
"""
Serialize an unsigned integer ``n`` as 4 bytes (32 bits) in big-endian
order.
Corresponds directly to the "ser_32(i)" function in BIP32
(https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#conventions).
:param n: The integer to be serialize... |
def create_in_term_for_db_queries(values, as_string=False):
"""
Utility method converting a collection of values (iterable) into a tuple
that can be used for an IN statement in a DB query.
:param as_string: If *True* the values of the list will be surrounded
by quoting.
:type as_string: :cl... |
def get_method(cls, name):
""" python3 doesn't need the __func__ to get the func of the
method.
"""
method = getattr(cls, name)
if hasattr(method, "__func__"):
method = method.__func__
return method |
def lineSegmentsIntersect(p1, p2, q1, q2):
"""Checks if two line segments intersect.
Keyword arguments:
p1 -- The start vertex of the first line segment.
p2 -- The end vertex of the first line segment.
q1 -- The start vertex of the second line segment.
q2 -- The end vertex of the second line se... |
def validate_chunk_width(chunk_width):
"""Validate a chunk-width string , returns boolean.
Expected to be a string representing either an integer, like '20',
or a comma-separated list of integers like '20,30,16'"""
if not isinstance(chunk_width, str):
return False
a = chunk_width.split(",")
... |
def cquote(x):
"""enquote a string with c rules"""
return str(x).replace('\\','\\\\').replace('"','\\"') |
def two_col_list(m) -> str:
"""Create two col css list from dict, used in reports
Parameters
----------
m : dict
Dict to convert\n
"""
body = ''
for name, val in m.items():
body = f'{body}<li><span>{name}:</span><span>{val}</span></li>'
return f'<ul class="two_col_list_... |
def reverse_list(lst):
"""
Returns the reversed form of a given list.
Parameters
----------
lst : list
Input list.
Returns
-------
reversed_list : list
Reversed input list.
Examples
--------
>>> lst = [5, 4, 7, 2]
>>> reverse_list(lst)
[2, 7, 4, 5]... |
def subdict(d, keep=None, drop=None):
"""Compute the "subdictionary" of a dict, *d*.
A subdict is to a dict what a subset is a to set. If *A* is a
subdict of *B*, that means that all keys of *A* are present in
*B*.
Returns a new dict with any keys in *drop* removed, and any keys
in *keep* stil... |
def update(value, iterable=None, **kwargs):
"""
Insert ``key: value`` pairs into the report
:param value: data chunk to operator on
:type value: :py:class:`dict` or :py:class:`~collections.Mapping`
:param iterable: iterable of ``(key, value)`` pairs
:type iterable: iterable[(str, T)]
:param... |
def set_dict_keys(d: dict, key_list: list):
"""Return a new dictionary with specified key order"""
assert set(d) == set(key_list)
return {k: d[k] for k in key_list} |
def use_node_def_or_num(given_value, default_func):
"""Transform a value of type (None, int, float, Callable) to a node annotation function."""
# Default: use pre-defined function from this module
if given_value is None:
func = default_func
# Transform: value to function that returns the value
... |
def sort_array_with_id(arr):
"""
Sort array ascending and keep track of ids.
:param arr: array with values
:return: array with tuples (id, val)
"""
tuple_arr = [(id, arr[id]) for id in range(len(arr))]
return sorted(tuple_arr, key=lambda t: t[1]) |
def bio_tagging_fix(pred_tags):
"""
Fix BIO tagging mistakes
:param pred_tags: list of predicted tags
:return: list of fixed tags
"""
start = 0
while start < len(pred_tags) and pred_tags[start][0] == 'I':
pred_tags[start] = 'B-other'
start += 1
for index in range(start, l... |
def factor_idx2compared_f_values(idx,k,nr_of_sim_parameters,proposed_worstcase):
"""p-rint('factor_idx2compared_f_values(idx,k,nr_of_sim_parameters,proposed_worstcase)')
p-rint('proposed_worstcase {}'.format(proposed_worstcase))
p-rint('len(proposed_worstcase) {}'.format(len(proposed_worstcas... |
def __zero_forward_closed(x, y, c, l):
"""convert coordinates to zero-based, both strand, open/closed coordinates.
Parameters are from, to, is_positive_strand, length of contig.
"""
y += 1
if not c: x, y = l - y, l - x
return x, y |
def almost_equal(a, b, places=3):
"""
Returns True or False if the number a and b are are equal inside the
decimal places "places".
:param a: a real number
:type a: int/float
:param b: a real number
:type b: int/float
:param places: number of decimal places
:type places: int
>>>... |
def split_time_value(sec):
"""Split a time value from seconds to hours / minutes / seconds.
Parameters
----------
sec : float
Time value, in seconds.
Returns
-------
hours, minutes, seconds : float
Time value, split up into hours, minutes, and seconds.
"""
minutes,... |
def union_list(*lists) -> list:
"""
Union elements in all given lists.
"""
l = list(set.union(*[set(lst) for lst in lists]))
l.sort()
return l |
def del_start_stop(x, start, stop):
"""
>>> l = [1,2,3,4]
>>> del_start_stop(l, 0, 2)
[3, 4]
>>> l
[3, 4]
>>> l = [1,2,3,4,5,6,7]
>>> del_start_stop(l, -1, -20)
[1, 2, 3, 4, 5, 6, 7]
>>> del_start_stop(l, -20, -8)
[1, 2, 3, 4, 5, 6, 7]
>>> del_start_stop(l, -6, -4)
[... |
def value(fn_or_value, *args, **kwargs):
"""
Evaluate argument, if it is a function or return it otherwise.
Args:
fn_or_value:
Callable or some other value. If input is a callable, call it with
the provided arguments and return. Otherwise, simply return.
Examples:
... |
def is_subsequence(needle, haystack):
"""Are all the elements of needle contained in haystack, and in the same order?
There may be other elements interspersed throughout"""
it = iter(haystack)
for element in needle:
if element not in it:
return False
return True |
def escape_filename_sh_ansic(name):
"""Return an ansi-c shell-escaped version of a filename."""
out =[]
# gather the escaped characters into a list
for ch in name:
if ord(ch) < 32:
out.append("\\x%02x"% ord(ch))
elif ch == '\\':
out.append('\\\\')
else:
... |
def _file_name_builder(test_name):
"""Build a name for the output file."""
try:
file_name = (test_name + ".dat").replace(' ', '_')
except TypeError:
file_name = ("NoName" + ".dat")
return file_name |
def latin1_to_ascii(unicrap):
"""This takes a UNICODE string and replaces Latin-1 characters with
something equivalent in 7-bit ASCII. It returns a plain ASCII string.
This function makes a best effort to convert Latin-1 characters into
ASCII equivalents. It does not just strip out the Latin... |
def url2id(url):
"""Extract the ID from a URL"""
return int(url.split("/")[-2]) |
def command_string(command_dict, command_number=None, numbers=True,
time=True):
"""Create the string representation for the command entry.
inputs:
command_dict: A command dictionary of the form {"cmd": "<command",
"ts": <timestamp>}. The "ts" arugment is optional.
numbers: If t... |
def is_number(s):
"""
Checks if the parameter s is a number
:param s: anything
:return: true if s is a number, false otherwise
"""
try:
float(s)
return True
except ValueError:
return False |
def test(predictions, labels, k=1):
"""
Return precision and recall modeled after fasttext's test
"""
precision = 0.0
nexamples = 0
nlabels = 0
for prediction, labels in zip(predictions, labels):
for p in prediction:
if p in labels:
precision += ... |
def bool_to_str(bool_val):
"""convert boolean to strings for YAML configuration"""
if not isinstance(bool_val, bool):
raise TypeError("The bool_val is required to be boolean type")
return "true" if bool_val else "false" |
def beam_curv(z, z0):
"""
doc
"""
return z + z0**2 / z |
def _get_wanted_channels(wanted_sig_names, record_sig_names, pad=False):
"""
Given some wanted signal names, and the signal names contained in a
record, return the indices of the record channels that intersect.
Parameters
----------
wanted_sig_names : list
List of desired signal name st... |
def splitword(word, start):
"""Split a starting string of from a word, return in tuple-form"""
return [start, word[len(start):]] |
def get_formatted_issue(repo, issue, title, url):
"""
Single place to adjust formatting output of PR data
"""
# Newline support writelines() call which doesn't add newlines
# on its own
return("* {}/{}: [{}]({})\n".format(repo, issue, title, url)) |
def GetSettingNames():
""" Return list of dictionary keys of selected settings and results. """
return ['active_channels'] |
def get_all_determinizations_comb(determinizations_of_all_effects):
"""
Generates all possible combinations of the given list of lists of
probabilistic effects determinizations.
Each element of the input variable is a tuple with all the determinizations of
a given probabilistic effect, as returned by fun... |
def compute_average_precision(positive_ranks):
"""
Extracted from: https://github.com/tensorflow/models/blob/master/research/delf/delf/python/detect_to_retrieve/dataset.py
Computes average precision according to dataset convention.
It assumes that `positive_ranks` contains the ranks for all expected po... |
def real_space_pixel_scales_tag_from_real_space_pixel_scales(real_space_pixel_scales):
"""Generate a sub-grid tag, to customize phase names based on the sub-grid size used.
This changes the phase name 'phase_name' as follows:
real_space_pixel_scales = None -> phase_name
real_space_pixel_scales = 1 -> ... |
def generate_discovery_cache_key(name, ext):
""" Generate cache key for office web app hosting discovery
name: Operations that you can perform on an Office document
ext: The file formats that are supported for the action
"""
return 'wopi_' + name + '_' + ext |
def json_pointer(*args):
"""
Get a list of strings and int and template them as a "json path"
exemple:
{% image_field "people" 0 'picture' as field %}
will return
people/0/picture
:param args: A list of string and int
:return: a "json pointer
"""
return "/".join([str(a) for a i... |
def verify_yolo_hyperparams(yolo_layers):
"""
----------
Author: Damon Gwinn (gwinndr)
----------
- Verifies hyperparams that should be the same across yolo layers (like nms_kind) are the same
- Returns True if all is good, False if all is not good
----------
"""
if(type(yolo_layers... |
def listtoslides(data):
"""Checks if format is correct + adds img and durration elements"""
slides = []
for slide in data:
slide = slide[:2]
slide[0] = slide[0][:25]
slide[1] = slide[1][:180]
slide.append("imgpath")
slide.append(0)
slides.append(slide)
ret... |
def average_gateset_infidelity(modelA, modelB):
""" Average model infidelity """
# B is target model usually but must be "modelB" b/c of decorator coding...
#TEMPORARILY disabled b/c RB analysis is broken
#from ..extras.rb import theory as _rbtheory
return -1.0 |
def dash(*txts):
"""Join non-empty txts by a dash."""
return " -- ".join([t for t in txts if t != ""]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.