content stringlengths 42 6.51k |
|---|
def count_substructs(substructs):
"""
Given a list of non-unique substructures,
count the occurrence of each.
"""
counts = dict()
for s in substructs:
matched = False
for ss in counts.keys():
if s.HasSubstructMatch(ss) and ss.HasSubstructMatch(s):
coun... |
def asteroid_name(asteroid: dict):
"""
Return the proper display name for an asteroid name, with the custom one taking priority.
:param asteroid: asteroid of choice
:return: name as string
"""
return asteroid['customName'] if asteroid['customName'] else asteroid['baseName'] |
def parse_rearrangement_summary(rearrangement_summary):
"""Returns a tuple of (stop_codon, in_frame, productive) from IgBlast output.
Only used if no info can be parsed from IMGT-gapped IgBlast output by Change-O"""
i = 1
chain_type = rearrangement_summary[0][0:4]
if "IGH" in chain_type:
i =... |
def init_costs_table(w1, w2):
"""Construct and return table with identities and empty start."""
costs_table = []
# Notice we add 1, to account for the 'empty' cell at the start
for i in range(len(w1) + 1):
row = []
for j in range(len(w1) + 1):
row.append(0)
costs_t... |
def area(box):
"""calculates area of box"""
return (box[2]-box[0])*(box[3]-box[1]) |
def boxcontains(box, p):
"""True iff *box* (4-tuple of (s,n,w,e) ) contains point *p* (pair
of (lat,lon)."""
s, n, w, e = box
return s <= p[0] < n and w <= p[1] < e |
def twos_comp(val, bits):
"""compute the 2's compliment of int value val"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val - (1 << bits) # compute negative value
return val # return positive value as is |
def is_palindrome_v2(string):
"""check if the string is palindrome or not.
if 2 chars are palindrome pop the last item"""
letters = list(string)
for letter in letters:
if letter == letters[-1]:
letters.pop(-1)
else:
return False
return True |
def is_prime(n):
"""Returns True if n is a prime number and False otherwise.
>>> is_prime(2)
True
>>> is_prime(16)
False
>>> is_prime(521)
True
"""
"*** YOUR CODE HERE ***"
from math import sqrt
def checking(i, n):
if i == 1:
return True
elif n %... |
def has_instance(iterable, class_or_tuple):
"""returns True if iterable contains an instance of cls"""
for i in iterable:
if isinstance(i, class_or_tuple):
return True
return False |
def get_tag(tokens, tag):
"""
Extracts the value inside the given tag.
"""
start = tokens.index('<' + tag + '>') + 1
stop = tokens.index('</' + tag + '>')
return tokens[start:stop] |
def getIdFromVpcArn(resources):
""" given a vpc arn, strip off all but the id """
vpcStr = 'vpc/'
ids = []
for resource in resources:
if vpcStr in resource:
index = resource.rfind(vpcStr)
id = resource[index+len(vpcStr):]
ids.append(id)
return ids |
def get_option_title(a_string):
""" This function creates a title-like name for each option, out of the
option itself.
This function returns a title-like option name as a string.
"""
option_name = (a_string.split(":"))[0]
option_name = option_name.lower()
option_name = option_name.replace... |
def _cm_color(val, max_weight, plot_metric=None):
"""
weight matrix element color variant dependent on confusion matrix plot option - bycount, precision or recall
"""
plot_metric = plot_metric if plot_metric is not None else "precision"
min_thresh = max_weight/6
color = {val > 0 and val < ... |
def merge_group_answers_with_count(file_content):
"""
Merges the group answers together and count the number of people in each group
:param [str] file_content: Content from the input file
:return: For each group, a long string of all the answers and the number of people
:rtype: [(str, int)]
"""
... |
def getid(obj):
"""Return id if argument is a Resource.
Abstracts the common pattern of allowing both an object or an object's ID
(UUID) as a parameter when dealing with relationships.
"""
try:
if obj.uuid:
return obj.uuid
except AttributeError:
pass
try:
... |
def find_segments(j, e, c, OPT):
"""
Given an index j, a residuals dictionary, a line cost, and a
dictionary of optimal costs for each index,
return a list of the optimal endpoints for least squares segments from 0-j
"""
if j == -1:
return []
else:
vals = [(e[i][j] + c + OPT[... |
def zippify(iterable, len=2, cat=False):
"""
Zips an iterable with arbitrary length pieces
e.g. to create a moving window with len n
Example:
zippify('abcd',2, cat=False)
--> [('a', 'b'), ('b', 'c'), ('c', 'd')]
If cat = True, joins the moving windows together
... |
def cipher(text, shift, encrypt=True):
"""
Each letter is replaced by a letter some fixed number of positions down the alphabet.
Parameters
----------
text: str
A string of text to be encrypted or decrypted.
shift: int
An integer incidating the digits that would be used to encrypt or decrypt.
enc... |
def calc_billable_hours(entries):
"""
Calculates billable hours from an array of entry dictionaries
"""
billable_hours_count = 0.0
for entry in entries:
if entry['billable']:
billable_hours_count = billable_hours_count + float(entry['hours_spent'])
return billable_hours_count |
def word(l, h):
"""
Given a low and high bit, converts the number back into a word.
"""
return (h << 8) + l |
def _common_prefix(string_list):
"""
Given a list of pathnames, returns the longest common leading component
"""
if not string_list:
return ""
min_str = min(string_list)
max_str = max(string_list)
for i, c in enumerate(min_str):
if c != max_str[i]:
return min... |
def RGBtoHSV(R, G, B):
""" convert RGB to HSV color
:param R: red value (0;255)
:param G: green value (0;255)
:param B: blue value (0;255)
:return: HSV (HSB) tuple """
rgb = [i / 255.0 for i in (R, G, B)] # scale 8bits values to float 0;1
maxi, mini = max(rgb), min(rgb)
delta = maxi ... |
def get_ndistinct_subsequences(sequence):
"""
Computes the number of distinct subsequences for a given sequence, based on original implementation by
Mohit Kumar available `here <https://www.geeksforgeeks.org/count-distinct-subsequences/>`_.
Example
--------
>>> sequence = [1,2,1,3]
>>> ps.get_ndistinct_subseq... |
def into_key(*keys, fullpath=False):
"""Generate target key name for the data.
Args:
*keys (str): JSON Keys (name, index or trailing slice)
fullpath (bool): Use the full JSON Key path for the target name.
Returns:
str: Key name to store the data in.
Examples:
>>> into_... |
def intersect(range1, range2):
"""
Given two ranges *range1* and *range2* (which must both have a step of
1), returns the range formed by the intersection of the two ranges, or
``None`` if the ranges do not overlap. For example::
>>> intersect(range(10), range(5))
range(0, 5)
>>... |
def get_execution_platform(command, filename):
"""
<Purpose>
Returns the execution platform based on a best-guess approach using
the specified command, as well as the a file's extension. The
command takes precedence over the file extension. If the extension
is not recognized, then it will be assum... |
def _sortArrayLessThan(data, elementSize, a, b):
"""Return True iff element a is less than element b.
Each element consists of 'elementSize' array indices.
"""
# Pull out index 0 just for speed.
if data[a * elementSize] < data[b * elementSize]:
return True
if data[a * elementSize] >... |
def addCov(cov, iv):
"""
Add the coverage for a array. No value region is marked as False.
"""
if len(cov) < iv[1]:
cov.extend([False] * (iv[1] - len(cov) + 1))
for i in range(iv[0], iv[1]):
if cov[i] == False:
cov[i] = 0
cov[i] += 1
return cov |
def centerS(coor, maxS):
"""
Center vector coor in S axis.
:param coor: coordinate of vector from S center to M=0
:param maxS: value representing end of estatic axis
:return: S centered coordinate
"""
return int(maxS / 2.0 + coor) |
def tuple2list(tuple_to_convert):
"""
Converts a tuple of tuples of tuples ... into a list of lists of lists
(1, 2, ('A', 'B', ('alpha', 'beta', 'gamma'), 'C'), 3) -->
--> [1, 2, ['A', 'B', ['alpha', 'beta', 'gamma'], 'C'], 3]
https://stackoverflow.com/questions/1014352/how-do-i-convert-... |
def gf_lshift(f, n):
"""Efficiently multiply f by x**n. """
if not f:
return f
else:
return f + [0]*n |
def getattrchain(obj, chain, default=None):
"""Like getattr, but the attr may contain multiple parts separated by '.'"""
for part in chain.split('.'):
if hasattr(obj, part):
obj = getattr(obj, part, None)
else:
return default
return obj |
def getArrayDimensions(shape):
"""
Get the dimensions of the grid where the cell will be zoomed.
The zoomed cell contains a `numpy` array and will be displayed
in a table with the same shape than it.
:Parameter shape: the cell shape
:Returns: a tuple (rows, columns)
"""
#... |
def strip_unwanted(data_str):
"""
Strip out any unwanted characters from the table data string
"""
# Right now, this just requires stripping out commas
return data_str.replace(',', '') |
def snowval(val):
"""Make sure our snow value makes database sense."""
if val is None:
return None
return round(float(val), 1) |
def inherits_plotnine(other):
"""
checks if object is a plotnine one (but really only checks if comes
from plotnine package...)
"""
# https://stackoverflow.com/questions/14570802/python-check-if-object-is-instance-of-any-class-from-a-certain-module
module_tree = getattr(other, '__module__', None... |
def getShareDigits(a, b: list):
"""
from two list find the shared two digits between last two digits of a and first two digits of b
"""
la = sorted(set(int(str(x)[-2:]) for x in a))
lb = sorted(set(filter(lambda x: len(str(x)) == 2,
list(int(str(x)[:2]) for x in b))))
... |
def get_annual_data(gitlogs, year, my_emails):
"""Filters out git logs by the given year.
:param gitlogs: A list of (name, email, datetime) tuples
:type gitlogs: list
:type year: int
:param my_emails: A list of email addresses
:type my_emails: list
:return:
A dictionary containin... |
def mapnewParts(dlib, dlibid):
""" Assign a unique index to each part """
cmap = {}
for libi in sorted(dlib):
try:
construct = dlibid[libi]
except:
construct = libi
cmap[construct] = len(cmap)
for p in dlib[libi]:
if p not in cmap:
... |
def abbr(
abbreviation="",
fullWord=""):
"""
*Get HTML5 Abbreviation*
**Key Arguments:**
- ``abbreviation`` -- the abbreviation
- ``fullWord`` -- the full word
**Return:**
- abbr
"""
abbr = """<abbr title="%(fullWord)s" class="initialism">%(abbreviation... |
def get_current_density(I, surface_area=1):
"""current to current density"""
j = I / surface_area
return j |
def _getHandlerKey(handler):
"""Get a key which identifies a handler function.
This is needed because we store weak references, not the actual functions.
We store the key on the weak reference.
When the handler dies, we can use the key on the weak reference to remove the handler.
"""
inst = getattr(handler,... |
def user_display_name(user):
"""
Returns the preferred display name for the given user object: the result of
user.get_full_name() if implemented and non-empty, or user.get_username() otherwise.
"""
try:
full_name = user.get_full_name().strip()
if full_name:
return full_na... |
def _oid_key(qcl):
"""Build oid key from qualified class name."""
return 'oid(%s)' % qcl |
def is_blank(string):
"""
Check is a string is black or not, either none or only contains whitespace.
@param string: String to be checked
@return: Is blank or not
"""
return string is None or len(string) == 0 or string.isspace()
# return len(re.sub(r'[\s]+', '', s)) == 0 |
def first4_last4_every_other_removed(seq):
"""With the first and last 4 items removed, and every other item in between"""
return seq[4:-4:2] |
def from_exp_list_to_tau(g,n,a):
"""
Converts a list of psi exponents into a Witten tau list.
"""
d = [0] * (max(a) +1)
for ai in a:
d[ai] += 1
d[0] = n - len([ai for ai in a if ai != 0])
return d |
def fixture_sorted_param_names(allparams):
"""
Fixture for storing a sorted parameter list
"""
return sorted(list(allparams.keys())) |
def num_digits(n):
"""How many digits in integer n?"""
return len(str(n)) |
def lagrange(x_values, y_values, nth_term):
"""
If a polynomial has degree k, then it can be uniquely identified if it's values are known in k+1 distinct points
:param x_values: X values of the polynomial
:param y_values: Y values of the polynomial
:param nth_term: nth_term of the polynomial
:r... |
def merge_dicts(*dict_args):
""" Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result |
def parse_range(rng):
"""Convert this into bins"""
return [float(f) for f in rng.split("-")] |
def make_worlist_trie(wordlist):
"""
Creates a nested dictionary representing the trie created
by the given word list.
:param wordlist: str list:
:return: nested dictionary
>>> make_worlist_trie(['einander', 'einen', 'neben'])
{'e': {'i': {'n': {'a': {'n': {'d': {'e': {'r': {'__end__': '__... |
def testlabels_to_onehot(labels):
""" One-hot encode labels """
onehot = []
for i in range(0, 13):
onehot.append(0)
for i in range(0, 13):
if i in labels or str(i) in labels:
onehot[i] = 1
else:
onehot[i] = 0
return onehot |
def create_config(service):
"""
Creates an empty config file in pam.d when the user specifies
create_config=True and when the config does not already exist
"""
service_file = open('/etc/pam.d/%s' % service, 'a')
service_file.close()
return '/etc/pam.d/%s' % service |
def nested_list_to_list(n_lis):
"""
Parameters
----------
n_lis Nested list
Returns A list with only elements (that are not lists themselves)
-------
"""
lis = []
for item in n_lis:
lis.append(item[0])
return lis |
def to_list(value) -> list:
"""
Wrap value in list if it's not already in a list.
Arguments
---------
value : Any
Value to wrap in list.
Returns
-------
list
List with value inside.
"""
return value if isinstance(value, list) else [value] |
def is_iterable(value):
"""Checks if `value` is an iterable.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value is an iterable.
Example:
>>> is_iterable([])
True
>>> is_iterable({})
True
>>> is_iterable(())
True
... |
def is_subseq(l1, l2):
"""is every element of l1 also in l2? (non-unique and order sensitive)"""
it = iter(l2)
return all(d in it for d in l1) |
def _obtain_new_column_type(column_info):
""" Suggest in or float type based on the presence of nan and float values """
if column_info['float_number'] > 0 or column_info['nan_number'] > 0:
# Even if one of types are float - all elements should be converted into float
return float
else:
... |
def get_class_name_and_tags(form_data):
"""
Extract 'className', 'tag1' and 'tag2' from the given form data and make sure that the tags
are not empty or the same.
"""
class_name = form_data['className']
tag1 = form_data['tag1'] or f'{class_name}_tag1'
tag2 = form_data['tag2'] or f'{class_nam... |
def _DepsToLines(deps):
"""Converts |deps| dict to list of lines for output."""
if not deps:
return []
s = ['deps = {']
for _, dep in sorted(deps.iteritems()):
s.extend(dep.ToLines())
s.extend(['}', ''])
return s |
def _label_anchor_residues(ax, anchor_residues):
"""
Label bars in barplot that are listed as anchor residues.
Parameters
----------
ax : matplotlib.pyplot.axis
Plot axis for bar plot with 85 bars.
anchor_residues : None or dict (str: list of int)
Dictionary of anchor residues (... |
def estimate(hits):
""" Estimates Pi's value from hits """
from math import log10
hits = hits * 4 # one quadrant is used
r = hits / 10 ** int(log10(hits)) # make it irrational
return f"Pi's estimated value is {r}" |
def median(items):
###############################################################################
"""
>>> items = [2.3]
>>> median(items)
2.3
>>> items = [2.3, 8.1, 3.4, 1.5, 11, 3.42321]
>>> median(items)
3.4116049999999998
>>> items = [2.3, 8.1, 3.4, 1.5, 11, 3.42321, -3.1]
>>> me... |
def _set_default_application_id(
application_id: int,
subcategory_id: int,
type_id: int,
) -> int:
"""Set the default application ID for semiconductors.
:param application_id: the current application ID.
:param subcategory_id: the subcategory ID of the semiconductor with missing
default... |
def _longest_filename(matches):
"""find longest match by number of '/'."""
return max(matches, key=lambda filename: len(filename.split("/"))) |
def ll_start(line):
"""Returns True if line looks like the start of a LocusLink record."""
return line.startswith('>>') |
def compute_profile_updates(local_profiles, remote_profiles):
"""
Compare a local set of profiles with a remote set.
Return a list of profiles to add, and a list of profiles
that have been updated.
"""
# Note: no profile will ever be removed, I guess we don't care
new = list()
updated = ... |
def set_show_ad_highlights(show: bool) -> dict:
"""Highlights owner element of all frames detected to be ads.
Parameters
----------
show: bool
True for showing ad highlights
"""
return {"method": "Overlay.setShowAdHighlights", "params": {"show": show}} |
def clean_email_title(title):
"""
Validates emails.csv title.
"""
if not title:
return False
trails = title.split('-')[-1].split('.')
if len(trails) != 2:
return False
if trails[1] == 'csv' and len(trails[0]) == 6 and trails[0].isdigit():
return True
return Fal... |
def build_nsr(request_status, nsd, vnfr_ids, service_instance_id):
"""
This method builds the whole NSR from the payload (stripped nsr and vnfrs)
returned by the Infrastructure Adaptor (IA).
"""
nsr = {}
# nsr mandatory fields
nsr["descriptor_version"] = "nsr-schema-01"
nsr["id"] = serv... |
def error(message):
"""Creates a json error with given status code"""
return {"error": message} |
def contiguous_chunks(intlist):
"""Calculate a list of contiguous areas in a possibly unsorted list.
>>> contiguous_chunks([2, 9, 3, 5, 8, 1])
[(1, 3), (5, 1), (8, 2)]
"""
if len(intlist) == 0:
return []
mylist = sorted(intlist)
result = [[mylist[0], 1]]
for x in mylist[1:]:
... |
def selection_sort(x):
"""
Sorts an array x in non-decreasing order using the selection sort
algorithm.
@type x: array
@param x: the array to sort
@rtype: array
@return: the sorted array
"""
n = len(x)
for i in range(n):
min_idx = i;
for j in range(i + 1, n):
... |
def multiply(geometry):
"""Force a GeoJSON geometry to its Multi* counterpart.
This allows a table to load both polygons and multipolygons, for
example.
"""
_type = geometry['type'].lower()
if _type == 'polygon':
return {
'type': 'MultiPolygon',
'coordinates': [g... |
def year_month_flow(year, month):
"""function to get the correct response when clicking next previous on calendar feature"""
if month > 12:
month = 1
year = year+1
return (year, month)
elif month < 1:
month = 12
year = year-1
return (year, month)
else:
... |
def process_edition(edition):
"""
Turns a string with an edition in it into a processed string.
Turns '1' into '1st', '2017' into '2017', and 'International'
into 'International'. So it doesn't do a whole lot, but what it
does do, it does well.
Arguments:
edition: The edition string.
... |
def keep_digits(x: str) -> str:
"""Delete all digit from a string."""
return "".join([c for c in x if c.isdigit()]).strip() |
def get_current_percentage(state: int, total: int) -> float:
"""Calculates the percetage of completed tasks"""
result = 0.0
if state >= 0 and total:
result = round((state / total) * 100, 2)
return float(result) |
def unzip(iterable):
"""
unzip(iter: iterable)
example:
unzip([ [1,2], ["a","b"]])
return:
[(1, 'a'), (2, 'b')]
"""
return list(zip(*iterable)) |
def split_rgb(color):
"""
split rgb into red, green, blue
"""
red = (color & 0xff0000) / 0x10000
green = (color & 0xff00) / 0x100
blue = color & 0xff
return red, green, blue |
def _mgmtalgomac(rack, chassis, slot, idx, prefix=2):
""" Returns the string representation of an algorithmic mac address """
return "%02x:%02x:%02x:%02x:%02x:%02x" % (prefix, rack >> 8, rack & 0xFF, chassis, slot, idx << 4) |
def aggregate_tile(cells, ti, tj, aggregate, params, metadata, layout, summary):
"""
Call the user defined aggregation function on each cell and combine into a single json object
"""
tile = []
keys = cells.keys()
for i,key in enumerate(keys):
print("cell", i+1, "/", len(keys), end='\r')
cell_json ... |
def show_unprintable(res):
""" show line ends and tabs: \r \n \t \r\n """
res = res.replace('\r\n', '\\r\\n|_AX_RN_|')
res = res.replace('\t', '\\t\t')
res = res.replace('\r', '\\r\r')
res = res.replace('\n', '\\n\n')
res = res.replace('|_AX_RN_|', '\r\n')
return res |
def find_frontmatter_ending(mdx: str, stop_looking_after: int = 10) -> int:
"""Find the line number where the mdx frontmatter ends.
Args:
mdx (str): String representation of the mdx file.
stop_looking_after (int): Optional, default is 10. Number of lines to stop
looking for the end of t... |
def compare_elements(elements: list):
"""Check if all elements are the same"""
if len(set(elements)) == 1:
return True
return False |
def financial_summary_processor(totals, formatter):
""" Process totals data by getting the label and hierarchy level for each value
"""
processed = []
for i in formatter:
if i in totals:
line = (totals[i], formatter[i])
processed.append(line)
return processed |
def steps_on_same_face_and_layer(prev_step, step):
"""
>>> steps_on_same_face_and_layer(None, "U")
False
>>> steps_on_same_face_and_layer("U", "U")
True
>>> steps_on_same_face_and_layer("U", "U'")
True
>>> steps_on_same_face_and_layer("U", "U2")
True
>>> steps_on_same_face_an... |
def refreshment(choice ='popcorn'):
"""
The cost of refreshments.
Choices are popcorn or fizzy pop
Keyword arguments:
choice The users choice of refreshment (default = 'popcorn')
"""
#fill in your code here
return 0.0 |
def _inter_pos_list(obs, target):
"""
Get the list of positions of obs in target
"""
pos_list = [0]
if len(obs) != 0:
pos_list = [i for i,o in enumerate(obs, start=1) if o in target]
if len(pos_list) == 0:
pos_list = [0]
return pos_list |
def add_article(name):
""" Returns a string containing the correct indefinite article ('a' or 'an')
prefixed to the specified string.
"""
if name[:1].lower() in 'aeiou':
return 'an ' + name
return 'a ' + name |
def centered_average(nums):
"""
take out 1 value of the smallest and largst
compute and return the mean of the rest
int div --> truncate the floating part?
ASSUME:
+3 ints
pos/neg
unsorted
dupes possible
Intutition:
- computing an average (sum / # of points)
Approac... |
def cleanHtmlBody(htmlBody):
"""For some reason htmlBody values often have the following tags that
really shouldn't be there."""
if htmlBody is None:
return ""
return (htmlBody.replace("<html>", "")
.replace("</html>", "")
.replace("<body>", "")
... |
def _dd_to_dms(dd):
"""convert lat or lon in decimal degrees (dd) to degrees, minutes, seconds"""
""" return tuple of int(deg), int(min), float(sec) """
dd = float(dd)
negative = dd < 0
dd = abs(dd)
min_, sec_ = divmod(dd * 3600, 60)
deg_, min_ = divmod(min_, 60)
if negative:
if ... |
def get_accelerator_type(accl_type):
"""Returns the accelerator type to be used on a GCP machine."""
accl_type_map = {
"CPU": "ACCELERATOR_TYPE_UNSPECIFIED",
"K80": "NVIDIA_TESLA_K80",
"P100": "NVIDIA_TESLA_P100",
"V100": "NVIDIA_TESLA_V100",
"P4": "NVIDIA_TESLA_P4",
... |
def prepare_pif_kps(kps_in):
"""Convert from a list of 51 to a list of 3, 17"""
assert len(kps_in) % 3 == 0, "keypoints expected as a multiple of 3"
xxs = kps_in[0:][::3]
yys = kps_in[1:][::3] # from offset 1 every 3
ccs = kps_in[2:][::3]
return [xxs, yys, ccs] |
def get_users_for_manager(manager, valid_users):
"""get_users_for_manager(manager, valid_users)"""
users_for_manager=[]
for user in valid_users:
user_manager_email=user["manager"]
if (user_manager_email == manager["email"]):
users_for_manager.append(user)
return users_for_ma... |
def to_alnum(skill_id):
"""Convert a skill id to only alphanumeric characters
Non alpha-numeric characters are converted to "_"
Args:
skill_id (str): identifier to be converted
Returns:
(str) String of letters
"""
return ''.join(c if c.isalnum() else '_' for c in str(skill_id)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.