content stringlengths 42 6.51k |
|---|
def create_featseltuple(ids):
"""Add the flat y coordinate to an index list."""
newlist = []
for part_id in ids:
newlist.extend([part_id, part_id + 91])
return tuple(sorted(newlist)) |
def cursorBoxHit(mouse_x, mouse_y, x1, x2, y1, y2, tab):
"""Description.
More...
"""
if (mouse_x >= x1) and (mouse_x <= x2) and (mouse_y >= y1) and (mouse_y <= y2) and tab:
return True
else:
return False |
def split64(long_int):
"""Split long_int into 64-bit words big-endian"""
assert(long_int >= 0)
if long_int == 0:
return [ "0" ]
result = []
while long_int:
result += [ "0x%xULL" % (long_int & (2**64-1)) ]
long_int >>= 64
return result |
def listdict2dict(L_dict, i):
"""
:param L_dict: dictionary of lists, all same length
:param i: index in to L_dict lists
:return: dictionary with same keys as L_dict, in which key k maps to element i of L_dict[i]
"""
return {key:L_dict[key][i] for key in L_dict.keys()} |
def bed_convert_coords(reg_s, reg_e, ref_s, ref_e, pol):
"""
Convert BED coordinates derived from a region within a subsequence
of the reference (chromsome or transcript) to chromosome or
transcript reference coordinates. Return start + end (BED format)
positions.
reg_s:
Region within s... |
def font(unit, size, family=None, style=None):
"""Font setter for all the widgets"""
f, s, sy = 'Comic Sans MS', 1, 'bold'
rem = int(unit / 100 * (size * 0.05 + s))
if not family and not style:
return f, rem, sy
if family and style:
return family, rem, style
if not family and sty... |
def part_a(f, x, h):
"""Forward difference"""
return (f(x+h) - f(x)) / h |
def _comp_nom(nco):
"""
To be correctly read in a MED viewer, each component must be a
string of width 16. Since we do not know the physical nature of
the data, we just use V1, V2, ...
"""
return "".join(["V%-15d" % (i + 1) for i in range(nco)]) |
def fibonacci(n):
"""
ecursive function that return the nth Fibonacci number in the sequence
Parameters
----------
n : int
The element of the Fibonacci sequence that is desired.
Raises
------
ValueError
If n <= 0.
Returns
-------
int
The value of t... |
def computeLogSubTicks(ticks, lowBound, highBound):
"""Return the sub ticks for the log scale for all given ticks if subtick
is in [lowBound, highBound]
:param ticks: log10 of the ticks
:param lowBound: the lower boundary of ticks
:param highBound: the higher boundary of ticks
:return: all the ... |
def right_pad(message, pad_to=20, pad_with=' '):
"""Pad a string with chars on the right until it reaches a certain width
Useful for aligning columns in console outputs.
"""
message = str(message)
while len(message) < pad_to:
message = message + pad_with
return message |
def argListToString(argList):
"""Converts a list of arguments into a single argument string"""
string = ""
for arg in argList:
stringVersion = str(arg)
# Wrap arguments with spaces in them in "" so they stay together
if stringVersion.find(' ') >= 0:
string = string + '"... |
def _to_bool(s):
"""Convert a value into a CSV bool."""
if s == 'True':
return True
elif s == 'False':
return False
else:
raise ValueError('String cannot be converted to bool') |
def prefix_from_bowtie2_index(index_files):
"""
Given a list of index files for bowtie2, return the corresponding prefix.
"""
if isinstance(index_files, str):
return '.'.join(index_files.replace('.rev', '').split('.')[:-2])
else:
prefixes = list(
set(
map(... |
def is_remote(file):
"""
Does the filename start with 'gs://'?
:param file:
:return: true or false
"""
return file is not None and file.startswith('gs://') |
def _handle_arg(arg):
"""
Clean up arguments. Mostly used to handle strings.
Returns:
Cleaned up argument.
"""
if (arg.startswith("'") and arg.endswith("'")) or (
arg.startswith('"') and arg.endswith('"')
):
return arg[1:-1] |
def average(x):
"""calculates the averade of a list x"""
assert len(x) > 0
return float(sum(x)) / len(x) |
def is_int_as_str(x):
"""
Test if string x is an integer. If not a string return False.
"""
try:
return x.isdecimal()
except AttributeError:
return False |
def dehex(s):
""" convert input string containing \x00 into hex values in string
:todo: Python3
>>> dehex('abc')
'abc'
>>> dehex(r'abc\x00')
'abc\x00'
>>> dehex(r'\xffabc\x00')
'\xffabc\x00'
"""
sr = ''
while s:
sl = s.split(r'\x',1)
sr += sl[0]
if... |
def r_size(x):
"""Returns the difference between the largest and smallest value in a collection.
Parameters
----------
x : collection of numbers
Examples
--------
>>> r_size([2,4,6,8])
6
>>> r_size({3,6,9,11})
8
"""
return max(x) - min(x) |
def ra_dec_to_deg(right_ascension, declination):
"""Converts right ascension and declination to degrees
Args:
right_ascension (str): Right ascension in the format hh:mm:ss.sss
declination (str): Declination in the format dd:mm:ss.sss
Returns:
right_ascension_deg (float): Right asce... |
def in_time_frame(sim_start_epoch, sim_end_epoch,
rec_start_epoch, rec_end_epoch):
"""
Check wheter record is inside the simulation time frame.
:param sim_start_epoch: simluation start.
:param sim_end_epoch: simulation end.
:param rec_start_epoch: record start.
:param rec_end_e... |
def _remove_spaces_column_name(name):
"""Check if name contains any spaces, if it contains any spaces
the spaces will be removed and an underscore suffix is added."""
if not isinstance(name, str) or " " not in name:
return name
return name.replace(" ", "_") + "_BACKTICK_QUOTED_STRING" |
def angle_adjust(angle):
"""Adjust angle from sensehat range to game range.
Args:
angle (float): sensehat angle reading.
Returns:
float
"""
if angle > 180.0:
angle -= 360.0
return angle |
def _optional_dict_to_list(param_value_dict, key_string='id', value_string='stringValue'):
"""
If given a dictionary, convert it to a list of key-value dictionary entries.
If not given a dictionary, just return whatever we were given.
"""
if not isinstance(param_value_dict, dict):
return par... |
def better_approach(digits, steps,offset = 0):
"""Things to improve on:
Avoid unnecessary multiplications and additions of zero
"""
L = len(digits)
digits = digits[offset:]
PAT = [0,1,0,-1]
for i in range(steps):
output = []
for cycle_length in range(offset,L): # Cycle length... |
def custom_hash(key:str) -> int:
"""
Hashes the key in a consistent manner, since python changes the seeding
between sessions for ''''''security reasons''''''
"""
h = ""
for character in key:
h += str(ord(character))
return int(h) |
def generate_root_filename(rawname, add="_mass"):
"""Generate the appropriate root filename based on a file's LJH name.
Takes /path/to/data_chan33.ljh --> /path/to/data_mass.root
"""
import re
fparts = re.split(r"_chan\d+", rawname)
prefix_path = fparts[0]
return prefix_path + add + "... |
def calculate_score(args):
"""Parallelize at the score level (not currently in use)"""
gene, function, scoring_args = args
score = function(gene, scoring_args)
return score |
def custom_validator(language, options):
"""Custom validator."""
okay = True
for k in options.keys():
if k != 'opt':
okay = False
break
if okay:
if options['opt'] != "A":
okay = False
return okay |
def instanceof(obj, classinfo):
"""Wrap isinstance to only return True/False"""
try:
return isinstance(obj, classinfo)
except TypeError: # pragma: no cover
# No coverage since we never call this without a class,
# type, or tuple of classes, types, or such typles.
return Fals... |
def _to_list(a):
"""Return a as list for unroll_scan."""
if isinstance(a, list):
return a
elif isinstance(a, tuple):
return list(a)
elif a is None:
return []
else:
return [a] |
def get_assign_name(guid, state):
"""Get the assigned name for the entity."""
guid = " ".join(guid.split())
if 'name_table' not in state:
state['name_table'] = {}
if 'names' not in state:
state['names'] = {}
if guid not in state['names']:
names = state['name_table']
... |
def concatenate_items(items, sep=', '):
"""Concatenate a sequence of tokens into an English string.
Parameters
----------
items : list-like
List / sequence of items to be printed.
sep : str, optional
Separator to use when generating the string
Returns
-------
str
"... |
def charCodeAt(src: str, pos: int):
"""
Returns the Unicode value of the character at the specified location.
@param - index The zero-based index of the desired character.
If there is no character at the specified index, NaN is returned.
This was added for compatibility with python
"""
try... |
def hanleyMcNeil(auc: float, n0: int, n1: int) -> float:
"""The very good power-law variance estimate from Hanley/McNeil"""
auc2=auc*auc
q1=auc/(2.-auc)
q2=2.*auc2/(1.+auc)
return( (auc-auc2+(n1-1.)*(q1-auc2)+(n0-1.)*(q2-auc2))/n0/n1 ) |
def clamp(num, min_val, max_val):
"""Clamps `min` within the range [`min_val`..`max_val`]."""
return max(min_val, min(num, max_val)) |
def _calculate_value_in_range(min_val, max_val, percentage):
"""Get the value within a range based on percentage.
Example:
A percentage 0.0 maps to min_val
A percentage of 1.0 maps to max_val
"""
value_range = max_val - min_val
return min_val + int(percentage * value_range) |
def get_items_from_index(x,y):
""" decipher the values of items in a list from their indices.
"""
z = []
for i in y:
try:
z.append(x[i])
except:
pass
return z
"""
#example:
x = [1,3,5,8]
y = [1, 3]
get_items_from_index(x, y)
#result
... |
def calcBTreeEuropeanOpValue(po, p, pstar, step_discount):
"""Computes and returns the options value at time 0."""
if po is None:
po = []
po = [(p * po[i + 1] + pstar * po[i]) * step_discount for i in range(len(po) - 1)]
if len(po) == 1:
return po[0]
else:
return calcBTreeE... |
def uses_all( word, letters ):
"""Return True if the word uses all the required letters.
"""
for letter in letters:
if letter not in word:
return False
return True |
def bounding_boxes_xyxy2xywh(bbox_list):
"""
Transform bounding boxes coordinates.
:param bbox_list: list of coordinates as: [[xmin, ymin, xmax, ymax], [xmin, ymin, xmax, ymax]]
:return: list of coordinates as: [[xmin, ymin, width, height], [xmin, ymin, width, height]]
"""
new_coordinates = []
... |
def update_active_boxes(cur_boxes, active_boxes=None):
"""
Args:
cur_boxes:
active_boxes:
Returns:
"""
if active_boxes is None:
active_boxes = cur_boxes
else:
active_boxes[0] = min(active_boxes[0], cur_boxes[0])
active_boxes[1] = min(active_boxes[1], cu... |
def add_path(tdict, path):
"""
Create or extend an argument tree `tdict` from `path`.
:param tdict: a dictionary representing a argument tree
:param path: a path list
:return: a dictionary
Convert a list of items in a 'path' into a nested dict, where the
second to last item becomes the key... |
def mongodb_uri(mongodb_url, mongodb_port, db_name='tuplex-history'):
"""
constructs a fully qualified MongoDB URI
Args:
mongodb_url: hostname
mongodb_port: port
db_name: database name
Returns:
string representing MongoDB URI
"""
return 'mongodb://{}:{}/{}'.forma... |
def exponential_backoff(c_factor):
"""Calculate backoff time for reconnect."""
return int(((2**c_factor)-1)/2) |
def _merged_gaps(a_gaps: dict, b_gaps: dict) -> dict:
"""merges gaps that occupy same position
Parameters
----------
a_gaps, b_gaps
[(gap position, length),...]
Returns
-------
Merged places as {gap position: length, ...}
Notes
-----
If a_gaps and b_gaps are from the s... |
def split_array(text):
"""Split a string assuming it's an array.
:param text: the text to split
:type text: str
:returns: list of splitted strings
:rtype: list
"""
if not isinstance(text, str):
return text
# for some reason, titles.akas.tsv.gz contains \x02 as a separator
se... |
def example_keys_response(default_kid, rsa_public_key, rsa_public_key_2):
"""
Return an example response JSON returned from the ``/jwt/keys`` endpoint in
fence.
"""
return {"keys": [[default_kid, rsa_public_key], ["key-02", rsa_public_key_2]]} |
def get_fieldnames(content):
"""
Return the longest Dict Item for csv header writing
"""
item_length = 0
csv_header = []
for item in content:
if len(item) >= item_length:
longest_item = item
item_length = len(item)
for key in longest_item.keys():
... |
def binarySearch(arr, x):
"""Returns the lowest index of the element equal to `x` or NaN if not found."""
if len(arr) == 0:
return 0
m = len(arr) // 2
if arr[m] < x:
return m + 1 + binarySearch(arr[m + 1:], x)
elif x < arr[m] or (0 < m and arr[m - 1] == x):
return binarySearc... |
def is_valid_followup_permutation(perm, prev_perm):
"""
Checks if a given permutation is a valid following permutation to all previously known permutations. (only one more)
"""
for p in prev_perm:
if len(perm - p) == 1:
return True
return False |
def tagref(row, args):
"""A single tag pattern standing alone.
@param row: the HXL data row
@param args: the arguments parsed
"""
return row.get(args[0]) |
def dict_to_list(dict_to_convert):
"""Converts a dictionary to a multi-dimensional array. The first item of the
tuple is the key from the dictionary"""
result_list = []
for name, values in dict_to_convert.items():
result_list.append([name] + values.get_all_stats())
return result_list |
def code(string: str) -> str:
"""
Add code md style.
:param string: The string to process.
:type string:str
:return: Formatted String.
:rtype: str
"""
return f"`{string}`" |
def superclass_in_base_classes(base_classes, the_class):
"""
recursively determine if the_class is among or is a superclass of
one of the classes in base_classes. The comparison is done by
name so that even if reload is called on a module, this still
works.
"""
for base_cl... |
def binary_string_to_int(binary):
"""
Convert a binary string to a decimal number.
@type binary: str
@param binary: Binary string
@rtype: int
@return: Converted bit string
"""
return int(binary, 2) |
def _param(param, value):
"""
create 'parameter=value'
"""
return "{0}={1}".format(param, value) |
def DAY_OF_MONTH(expression):
"""
Returns the day of the month for a date as a number between 1 and 31.
See https://docs.mongodb.com/manual/reference/operator/aggregation/dayOfMonth/
for more details
:param expression: expression or variable of a Date, a Timestamp, or an ObjectID
:return: Aggreg... |
def _html_escape(string):
"""HTML escape all of these " & < >"""
html_codes = {
'"': '"',
'<': '<',
'>': '>',
}
# & must be handled first
string = string.replace('&', '&')
for char in html_codes:
string = string.replace(char, html_codes[char])
... |
def is_scoped_package(name):
"""
Return True if name contains a namespace.
For example::
>>> is_scoped_package('@angular')
True
>>> is_scoped_package('some@angular')
False
>>> is_scoped_package('linq')
False
>>> is_scoped_package('%40angular')
True
"""
return name.st... |
def _parse_line(line):
"""If line is in the form Tag=value[#Comment] returns a (tag, value)
tuple, otherwise returns None."""
non_comment = line.split('#')[0].strip()
if len(non_comment) > 0:
tag_value = [x.strip() for x in non_comment.split('=')]
if len(tag_value) != 2:
rais... |
def style_function_color_map(item, style_dict):
"""Style for geojson polygons."""
feature_key = item['id']
if feature_key not in style_dict:
color = '#d7e3f4'
opacity = 0.0
else:
color = style_dict[feature_key]['color']
opacity = style_dict[feature_key]['opacity']
sty... |
def to_base_10_int(n, input_base):
"""
Converts an integer in any base into it's decimal representation.
Args:
n - An integer represented as a tuple of digits in the specified base.
input_base - the base of the input number.
Returns:
integer converted into base 10.
... |
def number_strip(meaning):
"""
strips numbers from the meaning array
:param meaning: array
:return: stripped list of meaning
"""
integer_array = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
returnVal = []
flag = False
for everyWord in meaning:
for everyChar in everyWord... |
def der_value_offset_length(der):
"""Returns the offset and length of the value part of the DER tag-length-value object."""
tag_len = 1 # Assume 1 byte tag
if der[tag_len] < 0x80:
# Length is short-form, only 1 byte
len_len = 1
len = int(der[tag_len])
else:
# Length is ... |
def parse_sam_region(string):
"""Parse 1-based genomic region string into 0-based tuple."""
if not string:
return ()
parts = string.strip().split(":")
if len(parts) == 1:
chrom = parts[0]
return (chrom,)
else:
chrom = parts[0]
positions = parts[1].split("-")
... |
def ms(val):
""" Turn a float value into milliseconds as an integer. """
return int(val * 1000) |
def encode(sample_encoder, label_encoder, variant):
"""Generate sample and label encoding for variant."""
encoding = sample_encoder(variant)
label = label_encoder(variant)
return (encoding, label) |
def fib(x):
"""
@desc assumes x an int >= 0
@param {int} x Assumes it is an integer at least 0 or greater
@return Fibonacci of x
"""
if x == 0 or x == 1:
return 1
else:
return fib(x - 1) + fib(x - 2) |
def intersection(a, b):
"""
intersection(list, list):
"""
if not a: return []
if not b: return []
d = []
for i in a:
if (i in b) and (i not in d):
d.append(i)
for i in b:
if (i in a) and (i not in d):
d.append(i)
return d |
def smallest_evenly_divisible(min_divisor, max_divisor, minimum_dividend=0):
"""Returns the smallest number that is evenly divisible (divisible
with no remainder) by all of the numbers from `min_divisor` to
`max_divisor`. If a `minimum_dividend` is provided, only dividends
greater than this number will ... |
def polar_line_boundaries(polar_line, boundaries = None):
"""
Input `polar_line` should contain: (rho, cos_theta, sin_theta)
Returns line points in cartesian space from the polar space parameters for that line:
(x1, y1, x2, y2)
`boundaries` if provided define the image boundaries over which th... |
def compare(parameter=0):
"""
Enumerate devices on host
"""
return 'compare', 'ifconfig -s | tail -n +2 | awk \'{print $1}\' | xargs echo -e NET: && lsblk -l | grep / | awk \'{print $1}\' | xargs echo DISK:' |
def _remove_dot_from_extension(
extensions
):
"""remove the dot from an extension
Args:
extensions (str or list): the extension
Returns:
the extension without the dot
"""
if isinstance(extensions, str):
ext : str = extensions
extensions = ext.replace(".","")
... |
def separate_appetizers(dishes, appetizers):
"""
:param dishes: list of dish names
:param appetizers: list of appetizer names
:return: list of dish names
The function should return the list of dish names with appetizer names removed.
Either list could contain duplicates and may require de-dupin... |
def is_basic_datatype(value):
"""
We only save "basic" datatypes like ints, floats, strings and
lists, dictionaries or sets of these as pickles in restart files
This function returns True if the datatype is such a basic data
type
"""
if isinstance(value, (int, float, str, bytes, bool)):
... |
def convert_number(number, denominators):
""" Convert floats to mixed fractions """
int_number = int(number)
if int_number == number:
return int_number, 0, 1
frac_number = abs(number - int_number)
if not denominators:
denominators = range(1, 21)
for denominator in denominators:... |
def expand_part(app, part):
"""Expand the single string 'part' into a list of strings
Expands:
- '%n' to [filename of the selected item]
- '%f' to [full path of selected item]
- '%s' to [full path of selected item 1, full path of selected item 2, ...]
- '%p' to [full path of folder of selec... |
def phy_re_ratio(carbon, d_carbon, previous_ratio, nutrient_limiter):
"""carbon and d_carbon im moles"""
return ((carbon+d_carbon) /
((1/previous_ratio)*(carbon+d_carbon*nutrient_limiter))) |
def n_mass(e):
"""
Calculate and return the value of mass using given value of the energy of nuclear reaction
How to Use:
Give arguments for e parameter,
*USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE
IT'LL BE HARD TO UNDERSTAND AND USE.'
Parameters:
e (int):nuclear e... |
def extract_usertag(data):
"""Extract user tag
"""
user = data['user']
position = data.get('position')
if not position:
position = [data['x'], data['y']]
return {
"user": {
"pk": int(user.get("id", user.get("pk"))),
"username": user["username"],
... |
def find_previous_match(_list, _start_idx, _match):
"""Finds previous _match from _start_idx"""
for _curr_idx in range(_start_idx, 0, -1):
if _list[_curr_idx] == _match:
return _curr_idx
return -1 |
def constant_time_compare(val1, val2):
"""
Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match.
Lifted from: http://code.djangoproject.com/svn/django/trunk/django/utils/crypto.py
>>> constant_time_compare("ABC", "ABC")
... |
def gcd(a, b):
"""Find the greatest common divisor using Euclid's algorithm.
>>> gcd(1, 3)
1
>>> gcd(2, 10)
2
>>> gcd(6, 9)
3
>>> gcd(17, 289)
17
>>> gcd(2512561, 152351)
1
"""
if a % b == 0:
return b
return gcd(b, a % b) |
def splitter(number):
"""
splits the number in 10's for correct pronunciation.
"""
if number <= 20:
return number, 0
elif 21 <= number <= 100:
x, y = divmod(number, 10)
return 10 * x, y
elif 101 <= number <= 1000:
x, y = divmod(number, 100)
return 100 * x,... |
def min_max_scale(X):
"""Scale the element of X into an interval [0, 1]
Arguments:
X {list} -- 2d list object with int or float
Returns:
list -- 2d list object with float
"""
m = len(X[0])
x_max = [-float('inf') for _ in range(m)]
x_min = [float('inf') for _ in range(m)]
... |
def count(text):
"""
Count net number of braces in text (add 1 for each opening brace,
subtract one for each closing brace).
Parameters
----------
text: String
A string.
Returns
-------
counts: Integer
Net number of braces.
Examples
--------
>>> from bibmanager.utils import count
... |
def format_thousands(x, pos=None):
"""The two args are the value and tick position."""
return '%1.0fK' % (x * 1e-3) |
def diagnose(start, end):
"""Format a line of diagnosis markers from a range of character positions"""
return (' ' * start) + ('^' * (end - start)) |
def has_method(obj, method):
""" Returns whether input object contains the given method """
method_op = getattr(obj, method, None)
return callable(method_op) |
def factorial(n):
"""Return the factorial of n, an exact integer >= 0.
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(30)
265252859812191058636308480000000
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0
Factoria... |
def fibo(n):
"""Returns nth fibonacci number."""
a, b = 0, 1
for i in range(1, n):
a, b = b, a+b
return b |
def build_zooma_query(trait_name: str, filters: dict, zooma_host: str) -> str:
"""
Given a trait name, filters and hostname, create a url with which to query Zooma. Return this
url.
:param trait_name: A string containing a trait name from a ClinVar record.
:param filters: A dictionary containing fi... |
def uniquify_tablewidgetitems(a):
""" Eliminates duplicate list entries in a list
of TableWidgetItems. It relies on the row property
being available for comparison.
"""
if (len(a) == 0):
tmp = []
else:
tmp = [a[0]]
# XXX: we need to compare row #s because
... |
def avg_side_metrics(side_metrics):
"""
:param side_metrics: list of metric dicts
:return: dict of metric dicts with average
"""
keys = side_metrics[0].keys()
result = {}
for key in keys:
acum = sum(d[key] for d in side_metrics)
result[key] = acum / len(side_metrics)
retu... |
def convert_logical(logic_func):
""" Converts the func as per format needed by the truths module"""
logic_operator = {'.': '&',
'+': '|',
'~': 'not',
'XOR': '^',
'xor': '^'}
for exp in logic_operator.keys():
log... |
def five_year_fcf(FCF,growth_rate = 0.25):
"""
Returns 5 year cashflow projection in a list of float
elements calculated from estimated short term growth rate and free
cash flow.
"""
#make it into dictionary
year_0 = FCF
year_1 = year_0*(1+growth_rate)
year_2 = year_1*(1+growth_rate... |
def f(x, y):
"""
sample func
"""
return x * x - y * y |
def _email_validator(value):
"""Email address."""
# ridiculously yet robust simple email validator ;)
if value.count('@') != 1:
raise ValueError('Incorrect email format: {}'.format(value))
return value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.