content stringlengths 42 6.51k |
|---|
def coerce_to_ascii(s) :
"""
Forces a string to ascii chars, ignoring other characters.
"""
# We dont need this anymore
return s |
def _map_key_to_format(key):
"""
given key, get FITS format code. Works for arbitrary number of apertures. see
http://docs.astropy.org/en/stable/io/fits/usage/table.html for
details.
"""
# example keys being mapped for TESS:
# ['bge', 'bgv', 'fdv', 'fkv', 'fsv',
# 'ife1', 'ife2', 'ife... |
def RPL_TOPIC(sender, receipient, message):
""" Reply Code 332 """
return "<" + sender + ">: " + message |
def can_pack(data_list):
"""
Converts list of tuples and combines them into an array
rendition. Each val is broken into individual byte values
and appended to bytearr output (LSB first)
Args:
List of tuples in form ((int) val, (int) len_in_bytes). val must be
in range [0, 2**len_in_b... |
def transform_string_feature_range_into_list(text):
"""Converts features from string to list of ids"""
values = []
for part in text.split(","):
if part.strip() == "":
continue
if "-" in part:
start, end = part.split("-")[:2]
values.extend(list(range(int(st... |
def binary_count(a: int) -> int:
"""
ambil 1 bilangan integer
dan kemudian mengambil angka
yaitu jumlah bit yang berisi 1
dalam representasi biner
dari nomor itu
contoh bilangan biner dari 25
25 = 11001
yang berarti 3 angka 1 dari 25
>>> binary_count(25)
3
>>> binary_coun... |
def __get_default_data_size(size=None):
"""Return default data size"""
return 500 if size is None else size |
def minus(a, *ops):
"""
(- a) ;=> a
(- a op) ;=> a - op
(- a op1 op2 ...)
"""
for op in ops:
a -= op
return a |
def is_odd(number):
"""Return True if number is odd, else False."""
return number % 2 != 0 |
def merge_single_batch(batch):
"""Merges batched input examples to proper batch format."""
batch_size = len(batch)
result = {}
for idx, example in enumerate(batch):
for feature in example:
if feature not in result:
# New feature. Initialize the list with None.
result[feature] = [None] ... |
def find_zeros(list_of_lists, height, width):
"""
Finds the indices of zeros in a height by width list of lists
"""
zeros_lst = []
for row in range(height):
for col in range(width):
if list_of_lists[row][col] == 0:
zeros_lst.append([row, col])
return zeros_lst |
def int_to_uint(val, octals):
"""compute the 2's compliment of int value val for negative values"""
bits = octals << 2
if val < 0:
val = val + (1 << bits)
return val |
def subterps(so_far, reg_part):
"""Logic to build subterps, collections of interpretations for subparts,
the empty subpart, or appendices"""
elements = []
found_subpart = False
found_appendix = False
for el in so_far:
if el.get('is_subpart'):
found_subpart = True
... |
def missing_seats(seat_ids):
"""Find missing seat id in the seat_ids."""
reference = {seat_id for seat_id in range(
min(seat_ids), max(seat_ids) + 1)}
return reference - set(seat_ids) |
def _get_h3_range_lst(h3_min, h3_max):
"""Helper to get H3 range list."""
return list(range(h3_min, h3_max + 1)) |
def dict_remove(x, exclude=[]):
"""Remove keys from a dict."""
return dict((k, v) for k, v in x.items() if k not in exclude) |
def decipherInput(input):
"""
resolution input format
"""
extension = input.split('.')[-1].lower()
choice = {"bam": 0, \
"sam": 1, \
"fasta": 2, \
"fastq": 2, \
"fa": 2, \
"fq": 2}
return choice[extension] |
def solution1(inp):
"""Solves the first part of the challenge"""
groups = inp.split('\n\n')
s = 0
for group in groups:
letters = set(group.replace("\n", ""))
print(group, len(letters))
s += len(letters)
return s |
def ranges_to_list(range_str):
""" ranges_to_list("1-3,5-7") == [1,2,3,5,6,7] """
num_list = []
for rng in range_str.split(','):
a, b = map(int, rng.split('-'))
num_list.extend(range(a, b+1))
return num_list |
def prefix(values, content):
"""
Discover start and separate from content.
:param list[str] values:
Will scan through up to the one ``content`` starts with.
:param str content:
The value to scan, will separate from the start if found.
:raises:
:class:`ValueError` if no sta... |
def normalize_vector(V):
"""
If sum vector==0, random element should have all coverage
"""
Vector = V[0:]
# Z=1E-20
# if sum(Vector)==0:
# for i in range(len(Vector)):
# Vector[i]=Z
if sum(Vector)==0:
Vector[0]=0.5
Vector[-1]=-0.5
else:
su... |
def _deduplicate(lst):
"""Auxiliary function to deduplicate lst."""
out = []
for i in lst:
if i not in out:
out.append(i)
return out |
def is_list(p):
"""
Returns if given variable is a list or not.
"""
return isinstance(p, list) |
def b_if_a_is_none(a, b):
""" Returns 'b' if 'a' is None, otherwise returns 'a' """
if a is None:
return b
else:
return a |
def minus_something(num1, num2):
"""This function substracts two numbers and returns the result
>>> minus_something(8, 5)
3
"""
return(num1 - num2) |
def suma_inversos_(x :int, y : int) -> float:
"""
Retorna la suma de sus inversos
Precondicion: x, y enteros distintos de 0
Postcondicion: vr:float es la suma del inverso de x con el inverso de y (1/x + 1/y)
y / (x*y) + (x*y) * x / (x*y)*(x*y)
1 / x + (x**2 * y) / (x**2 * y**2)
1/x + 1/y
"""
a : int = x ... |
def quote(name):
"""return value surrounded with substitutable quote marks"""
return '{Q}' + name + '{Q}' |
def metacyc_url(pathway):
""" Return the url for the pathway on the MetaCyc website
Args:
pathway (string): The MetaCyc pathway
Returns
(string): The url to the website for the pathway
"""
return "http://metacyc.org/META/NEW-IMAGE?type=NIL&object="+pathway |
def catalan_factorial(n):
"""
O(n): H(n) = C(2n, n) / (n + 1)
"""
import math
a = math.factorial(2 * n)
b = math.factorial(n)
return a // b // b // (n + 1) |
def get_prev_offset(offset, limit):
"""
Calculates the previous offset value provided the current one and the page limit
:param offset:
:param limit:
:param size:
:return:
"""
pref_offset = offset - limit
if pref_offset >= 0:
return pref_offset |
def receptor_bound(pdb_code):
"""Augment pdb code with receptor partner and bound binding notation."""
return pdb_code + '_r_b' |
def clear_data(data):
"""Clear empty list or dict attributes in data.
This is used to determine what input data provided to to_ufos was not
loaded into an UFO."""
if isinstance(data, dict):
for key, val in data.items():
if not clear_data(val):
del data[key]
... |
def total_number_of_clusters(tree) -> int:
"""Get the number of leaves in the tree."""
if tree is None:
return 1
return sum(total_number_of_clusters(subtree)
for subtree in tree.subregions) |
def dist2(a, b):
"""Squared distance between two 2D points."""
x, y = a[0] - b[0], a[1] - b[1]
return x**2 + y**2 |
def testing_folds(fold, k=10):
"""
Return a tuple of all the training folds.
>>> testing_folds(4)
(4,)
"""
assert fold < k
return (fold,) |
def rotated(matrix):
"""Returns the given matrix rotated 90 degrees clockwise."""
return [list(r) for r in zip(*matrix[::-1])] |
def mirror_y(point, height):
"""
Converts a point from standard cartesian to graphics cartesian for use by GUI just before drawing to the screen,
as the QGraphicsScene has (0,0) in the top left
"""
return point[0], height-point[1] |
def count_words(sentence):
"""
Count the number of words in a sentence.
param: str the sentence to count words
return: dictionary of word (str) keys and count (int) values
"""
input = str.lower(sentence)
special_characters = [
"!",
"@",
"#",
"$",
"%"... |
def fofn2fns(i_fofn):
"""Get filenames from fofn"""
fns = []
for fn in open(i_fofn, 'r'):
fn = fn.strip()
if len(fn) == 0 or fn[0] == '#':
continue
fns.append(fn)
return fns |
def spacer(value):
"""Adds leading space if value is not empty"""
return ' ' + value if value is not None and value else '' |
def _ascii(v):
"""pickle decodes certains strings as unicode in Python 2"""
if v is None or isinstance(v, (str)) or not hasattr(v, 'encode'):
return v
return v.encode('ascii') |
def _delete_full_gap_columns(full_gaps, sequence, start, end):
"""
Return the sequence without the full gap columns.
>>> full_gaps = [False, True, False, False, False, True]
>>> _delete_full_gap_columns(full_gaps, "Q-V-Q-", 1, 6)
'V-Q'
"""
cleaned_seq = []
for i in range(start, end):
... |
def calc_csi(fn: float, fp: float, tp: float) -> float:
"""
:param fn: false negative miss
:param fp: false positive or false alarm
:param tp: true positive or hit
:return: Critical Success Index or Threat score
"""
try:
calc = tp / (tp + fn + fp)
except ZeroDivisionEr... |
def update_dict(origin, extras):
"""Update the content of ORIGIN with the content of EXTRAS
:param origin: the dictionary to update
:type origin: dict
:param extras: the dictionary to update ORIGIN with
:type extras: dict
:rtype: dict
"""
final = origin.copy()
final.update(extras)
... |
def inconfmode(text):
"""
Check if in config mode.
Return True or False.
"""
return bool('(config)' in text) |
def dict_union(*dicts):
"""Returns a union of the passed in dictionaries."""
combined = dicts[0].copy()
for d in dicts:
combined.update(d)
return combined |
def calculoImpuesto(cantidad):
"""
Funcion que dependiendo la cantidad
te calcula el 32%
lleva una cantidad como param
retorna un cantidad con el impuesto
"""
impuesto = cantidad * 0.32
return impuesto |
def header_population(headers):
"""make column headers from a list
:param headers: list of column headers
:return: a list of dictionaries
"""
return [{'id': field, 'name': field, 'field': field, 'sortable': True} for field in headers] |
def swegen_link(variant_obj):
"""Compose link to SweGen Variant Frequency Database."""
url_template = ("https://swegen-exac.nbis.se/variant/{this[chromosome]}-"
"{this[position]}-{this[reference]}-{this[alternative]}")
return url_template.format(this=variant_obj) |
def deterministic_async_update_scheme(regulatory_functions, step, current_state):
""" Asynchronously update species values in a deterministic order
Args:
regulatory_functions (:obj:`dict` of :obj:`str`, :obj:`function`): dictionary of regulatory functions for each species
step (:obj:`int`): ste... |
def multiLevelConstantSampleNumber(inputDict, newLevels):
"""
Returns a list of sample numbers of same length as the number of levels of
deault hierarchy. Keeps constant the number of samples from defaultHierarchy if an
entry of newLevels exists in deafultHierarchy. If not, allocate a default
newSam... |
def class_fullname(clazz):
"""
Gets the fully qualified class name of the parameter clazz
:param clazz: Either a type or any object
:return: the full name of the type or the type of the object
"""
if clazz.__class__.__name__ == "type":
return ".".join((clazz.__module__, clazz.__name__))
... |
def givens(A, b):
""" solve linear equation
cf. http://www.slideshare.net/tmaehara/ss-18244588
complexity: O(n^3)
used in kupc2012_C
"""
def mkrot(x, y):
r = pow(x**2+y**2, 0.5)
return x/r, y/r
def rot(x, y, c, s):
return c*x+s*y, -s*x+c*y
n = len(b)... |
def parse_br(text: str):
"""
parse_br will replace \\n with br
"""
return text.replace("\n", "<br>") |
def create_image_autolink(alt_text='', img_width='', img_height='', path=''):
"""create an image autolink formatted markdown string """
alt = ''
width = ''
height = ''
if alt_text:
alt = f'alt="{alt_text}" '
src = f'src="{path}" '
if img_width:
width = f'width="{img_width}" '... |
def by_since(timespec, tiddlers):
"""
Return those tiddlers new than the provided timespec.
"""
if len(timespec) == 12:
timespec = timespec + '00'
def newer(tiddler):
modified = tiddler.modified
if len(modified) == 12:
modified = modified + '00'
return int... |
def str_to_int(string):
"""
Parses a string number into an integer, optionally converting to a float
and rounding down.
Some LVM values may come with a comma instead of a dot to define decimals.
This function normalizes a comma into a dot
"""
try:
integer = float(string.replace(',',... |
def was_phishtank_data_ever_reloaded(context: dict):
"""
Checking if PhishTank data was ever reloaded by checking IntegrationContext. (IntegrationContext set during
the reload command).
Args:
context (dict) : IntegrationContext that is empty / contains PhishTank data.
Returns: True if cont... |
def tokenize(string, wset, token):
"""Returns either false if the string can't be segmented by
the current wset or a list of words that segment the string
in reverse order."""
# Are we done yet?
if string == "":
return [token]
# Find all possible prefixes
for pref in wset:
i... |
def is_int_even_v02(num):
"""
Use the modulo operator to evaluate whether an integer provided by
the caller is even or odd, returning either True or False.
Parameters:
num (int): the integer to be evaluated.
Returns:
is_even (boolean): True or False depending on the modulo check
... |
def str_2_byte_array(s, length=None):
"""
string to byte array
"""
s_len = len(s)
if not length:
length = s_len
if length > s_len:
s = s + '\0' * (length - s_len)
return [ord(i) for i in s[:length]] |
def get_change(m):
"""The goal in this problem is to find the minimum number of coins needed to change the input
value (an integer) into coins with denominations 1, 5, and 10.
Outputs the minimum number of coins with denominations 1, 5, 10 that changes m.
"""
i = m % 10
return (m // 10) + (i //... |
def min_distance_bottom_up(word1: str, word2: str) -> int:
"""
>>> min_distance_bottom_up("intention", "execution")
5
>>> min_distance_bottom_up("intention", "")
9
>>> min_distance_bottom_up("", "")
0
"""
m = len(word1)
n = len(word2)
dp = [[0 for _ in range(n + 1)] for _ in ... |
def TestingResources(network_ref, subnet_ref, region, zones):
"""Get the resources necessary to test an internal load balancer.
This creates a test service, and a standalone client.
Args:
network_ref: A reference to a GCE network for resources to act in.
subnet_ref: A reference to a GCE subnetwork for r... |
def getMajorCharacters(entityNames):
"""
Adds names to the major character list if they appear frequently.
"""
return {name for name in entityNames if entityNames.count(name) > 10} |
def fact(n):
"""To Find Factorial Value"""
prod=1
while n>=1:
prod*=n
n-=1
return prod |
def create_electric_system_summary (web_object, community ):
"""
creates a summary of the current electrical systems
inputs:
community_results the results for a given community
returns a list of items to use with the HTML template
"""
#~ community_results = web_object.resul... |
def shedule(timetable):
"""Optimally shedule timeslots for given room."""
timetable = sorted(timetable.copy(), key=lambda name: name[2])
sheduled = []
while timetable:
# Find soonest ending class
endtime = timetable[0][2]
sheduled.append(timetable.pop(0))
# Remove overl... |
def interpret_lanes( *lanes ):
"""
Helper function to interpret inputs for lanes argument.
Input can either be:
- A list of integers or floats in the range [1,2,3,4] or arbitrary length (other numbers will be ignored)
- A list of precisely four booleans corresponding to lanes 1, 2, 3, and 4.
... |
def is_three_channeled(value):
"""Missing channels! Colors in an RGB collection should be of the form [R,G,B] or (R,G,B)"""
return len(value) == 3 |
def fibonacci_one(n):
""" Return the n-th fibonacci number"""
if n in (0, 1):
return n
return (fibonacci_one(n - 2) + fibonacci_one(n - 1)) |
def text_to_integer(text):
"""
Converts any text string to an integer,
for example: 'Hello, world!' to 2645608968347327576478451524936
"""
# byteorder should be the same as in integer_to_text(), if you want to change it to 'big', change it there too
return int.from_bytes(bytes(text, 'utf-8'), b... |
def trapezoid_area(base_minor, base_major, height):
"""Returns the area of a trapezoid"""
# You have to code here
# REMEMBER: Tests first!!!
return ((base_minor * height)/2) + ((base_major*height)/2) |
def parse_line(input):
""" Parse properties files """
key, value = input.split('=')
key = key.strip() # handles key = value as well as key=value
value = value.strip()
return key, value |
def return_list(
incoming) -> list:
"""
Checks to see if incoming is a String or a List. If a String, adds the
string to a list and returns.
"""
url_list = []
if isinstance(incoming, str):
url_list.append(incoming)
elif isinstance(incoming, list):
url_list = incoming
... |
def parse_instance_lookup(results):
"""Parse the resultset from lookup_instance
Returns:
--------
String in host form <address>:<port>
"""
if results:
# Just grab first
result = results[0]
return "{address}:{port}".format(address=result["ServiceAddress"],
... |
def deep_tuple(array_like):
"""convert nested tuple/list mixtures to pure nested tuple"""
if isinstance(array_like, (list, tuple)):
return tuple(map(deep_tuple, array_like))
return array_like |
def rotLeft(a, d):
"""
Performs left rotation of array a by d rotations.
Args:
a: input array.
d: number of rotations to do.
Returns:
list of ints, rotated array.
"""
if d == len(a):
return a
# No point in rotating over len of array.
if d > len(a):
... |
def convert_header2map(header_list):
"""
Transfer a header list to dict
:type s: list
:param s: None
=======================
:return:
**dict**
"""
header_map = {}
for a, b in header_list:
if isinstance(a, str):
a = a.strip('\"')
if i... |
def limitChars(s:str, limit:int=50):
"""If input string is too long, truncates to first `limit` characters of the first line"""
if s is None: return ""
s = f"{s}".split("\n")[0]
return s[:limit-3] + "..." if len(s) > limit else s |
def is_symmetric(seq1, seq2):
"""@
determines if a sequence and its complement are idential
(symmetric) or not
"""
is_sym = False
debug = False
if debug:
print ("seq1: ", seq1)
print ("seq2: ", seq2)
#
# Note: to reverse a sequence, you can use the followin... |
def span_in_span(span1, span2):
""" Tests if span1 is included in span2. Spans are expected to be 2-tuples of (start, end) character offsets."""
# span1
start1 = span1[0]
end1 = span1[1]
# span2
start2 = span2[0]
end2 = span2[1]
# check if span2 includes span1 or not
return (start2 <... |
def get_container_properties(container, host_name):
""" Gets the container properties from a container object
:param container: The container object
:param host_name: The host name
:return: dict of (Docker host, Docker image, Docker container id, Docker container name)
"""
return {'Docker host':... |
def _md_fix(text):
"""
sanitize text data that is to be displayed in a markdown code block
"""
return text.replace("```", "``[`][markdown parse fix]") |
def legend(is_legend_show=True,
legend_orient="horizontal",
legend_pos="center",
legend_top='top',
legend_selectedmode='multiple',
**kwargs):
""" Legend component.
Legend component shows symbol, color and name of different series.
You can click ... |
def remove_newline(line):
"""Remove (\r)\n from the end of a string and return it."""
if line.endswith('\n'):
line = line[:-1]
if line.endswith('\r'):
line = line[:-1]
return line |
def entity_similarity(K, R):
"""
The similarity metric for chains is based on how many common mentions two chains share (Luo, 2005):
similarity = 2 * |K intersects R|/ (|K| + |R|)
:param K: an entity (set of mentions) from the key entities
:param R: an entity (set of mentions) from the respons... |
def nest_dict(d, prefixes, delim="_"):
"""Go from {prefix_key: value} to {prefix: {key: value}}."""
nested = {}
for k, v in d.items():
for prefix in prefixes:
if k.startswith(prefix + delim):
if prefix not in nested:
nested[prefix] = {}
nested[prefix][k.split(delim, 1)[... |
def build_index_l(l, key):
"""Build an index using key for a list of dicts where key is not unique
"""
our_dict = dict()
for d in l:
if key not in d:
continue
idx = d[key]
if idx in our_dict:
our_dict[idx].append(d)
else:
our_dict[idx] ... |
def nand(a: bool, b: bool) -> bool:
"""Sheffer stroke (AND-NOT)"""
return not (a and b) |
def clamp_to(n, clamp):
"""A step function where n = clamp * int(n / clamp) + clamp"""
return n - (n % clamp) + clamp |
def has_poor_grammar(token_strings):
"""
Returns whether the output has an odd number of double quotes or if it does not have balanced
parentheses.
"""
has_open_left_parens = False
quote_count = 0
for token in token_strings:
if token == '(':
if has_open_left_parens:
... |
def sanitize_int(i, default_value=1):
"""
Ensures that i is a positive integer
"""
return i if isinstance(i, int) and i > 0 else default_value |
def get_priceBuy_Quantity(list_table_report: list) -> dict:
"""This function returns a dict with the purchase price and the quantity purchased
Args:
list_table_report (list): List with the last buy record
Ex: [(2, Decimal('1.5821'), 0, Decimal('0.0000'), 10, 'XRPUSDT', datetime.date(2021, 5, 2)... |
def get_fibonacci_for_range(range):
"""
Get Fibonacci series
Function to take fibonacci_range as integer and return fibonacci series
Parameters
----------
range : int
Range of number
Returns
-------
list
Author
------
Prabodh M
Date
------
28 Nov... |
def wsize(dict_o_lists):
"""
Count the number of entries in the list values of a dictionary
@param dictionary dictionary with lists as values
@return int Total number of entries in all lists
"""
counter = 0
for entry in dict_o_lists:
counter += len(dict_o_lists[entry])
return co... |
def check_scheme(url):
"""Check URL for a scheme."""
if url and (url.startswith('http://') or url.startswith('https://')):
return True
return False |
def uri_parser(uri):
""" Split S3 URI into bucket, key, filename """
if uri[0:5] != 's3://':
raise Exception('Invalid S3 uri %s' % uri)
uri_obj = uri.replace('s3://', '').split('/')
return {
'bucket': uri_obj[0],
'key': '/'.join(uri_obj[1:]),
'filename': uri_obj[-1]
... |
def last(iterable):
"""A next(iterable) that drops everything but the last item"""
it = iter(iterable)
item = next(it)
for item in it:
pass
return item |
def poly(*args):
"""
f(x) = a*x + b*x**2
*args = (x, a, b)
"""
if len(args) == 1:
raise Exception("You have only entered a value for x, and no coefficients.")
x = args[0] # X value
coef = args[1:]
result = 0
for power, c in enumerate(coef):
result += c * (x ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.