content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
from collections import namedtuple
def extract_image_id_from_longitudinal_segmentation(freesurfer_id):
"""Extract image ID from longitudinal segmentation folder.
This function will extract participant, session and longitudinal ID from `freesurfer_id`.
Example:
>>> from clinica.utils.freesurfer i... | 9b5a2c0149c64dedb07b9005c80ad3e16604250e | 198,618 |
import random
def d5() -> int:
"""Roll a D5"""
return random.randint(1, 5) | 9029c0b9962aeffb412e1b131e0731f0bb69d042 | 413,302 |
def invertMask(mask):
"""
Inverts a numpy binary mask.
"""
return mask == False | f6a668a9b2f0928e2a71dc7e4de4d1e04cf307de | 23,978 |
def options(arg):
"""Extract options from given arg string"""
opts = []
for par in arg.split():
if len(par) > 0 and par[0] == '-':
opts.append(par)
return opts | abe33aaeb7642b0ccac5ecdb2b88441acc92405c | 612,892 |
from functools import reduce
def multiply_list_elements(in_list):
"""
Multiply list elements together, e.g. [1,2,3,4,5,6] -> 1*2*3*4*5*6=720.
"""
return reduce(lambda x, y: x*y, in_list) | 076e3f83c872fccb904495abf9f89ad088fdd0cf | 332,083 |
def esc_format(text):
"""Return text with formatting escaped
Markdown requires a backslash before literal underscores or asterisk, to
avoid formatting to bold or italics.
"""
for symbol in ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']:
text = str... | 12770a69da56cd6e9de92a6a301857d42ee1381b | 685,345 |
def crop_op(x, cropping, data_format="NCHW"):
"""Center crop image.
Args:
x: input image
cropping: the substracted amount
data_format: choose either `NCHW` or `NHWC`
"""
crop_t = cropping[0] // 2
crop_b = cropping[0] - crop_t
crop_l = cropping[1] // 2
crop_r... | 8071f0863b24def71b4643cee4385beb39d4a0d7 | 506,141 |
def n_considered_cells(cc, look_at):
"""
Calculates the number of considered cells
"""
count = 0
for p in cc:
if not look_at[p]:
continue
if p==0 or cc[p]==0:
continue
count += 1
return count | b969422cd3f1fff0bfa2c5aaa27fd386238e9027 | 216,423 |
def decimal_to_base(n, base):
"""Convert decimal number to any base (2-16)"""
chars = "0123456789ABCDEF"
stack = []
is_negative = False
if n < 0:
n = abs(n)
is_negative = True
while n > 0:
remainder = n % base
stack.append(remainder)
n = n // base
... | 5d94af3d37eaa3d18e3e6f56e0c278668ce118e1 | 689,980 |
import socket
def validate_ipv6(ip):
"""
Validate an ipv6 address
:param ip: The string with the ip
:return: True ip if it's valid for ipv6, False otherwise
"""
ip = str(ip)
try:
socket.inet_pton(socket.AF_INET6, ip)
except socket.error:
return False
return True | 020570f461e17e2003b9385fb7219434fba283fa | 620,652 |
def is_grouped_by_project(parameters):
"""Determine if grouped or filtered by project."""
group_by = list(parameters.parameters.get("group_by", {}).keys())
return [key for key in group_by if "project" in key] | 2c77ff48b66cbb38d1ce8ab1c170c623497340ba | 508,549 |
import math
def distance_between_points(p1, p2):
"""Computes the distance between two Point objects.
p1: Point
p2: Point
returns: float
"""
dx = p1.x - p2.x
dy = p1.y - p2.y
dist = math.sqrt(dx**2 + dy**2)
return dist | c9d9706a98580bccbfa4f8b6819d195e11a94601 | 472,320 |
import unicodedata
def maketrans_remove(accents=("COMBINING ACUTE ACCENT", "COMBINING GRAVE ACCENT")):
""" Makes a translation for removing accents from a string. """
return str.maketrans("", "", "".join([unicodedata.lookup(a) for a in accents])) | 516114526f6d7d36b2b454cd07e40302bd7a83f7 | 49,424 |
def uptime_seconds(uptime_list):
"""
Convert a list of the following form:
[years, weeks, days, hours, minutes]
To an uptime in seconds
"""
years = uptime_list[0]
weeks = uptime_list[1]
days = uptime_list[2]
hours = uptime_list[3]
minutes = uptime_list[4]
# No leap day ca... | abf29658193ab373c8e7e8c722fe308d3642c176 | 40,835 |
from datetime import datetime
def now_str() :
"""
easily returns current time in human readable format
use the real `datetime` package if you need sophisticated control over formatting.
"""
return datetime.now().strftime("%d %H:%M") | da4c3c389851c61025534676700d5941eeb27017 | 323,419 |
def param_group(pattern, **kwargs):
"""A helper function used for human-friendly declaration of param groups."""
return (pattern, kwargs) | da44d58e982f812e940c00ff0a21792cfeffd731 | 316,626 |
def number_of_pluses_before_an_equal(reaction):
"""
Args:
reaction (str) - reaction with correctly formatted spacing
Returns (int):
number_of - the number of pluses before the arrow `=>`
Example:
>>>number_of_pluses_before_an_equal("C6H12O6 + 6O2=> 6CO2 + 6H2O")... | f532ee41dee797d7c2ae1639fae9f1cb61c3f037 | 25,260 |
def diff_complex(x_re, x_im, y_re, y_im):
"""Difference of complex vectors"""
return x_re - y_re, x_im - y_im | 0c7dd4308294ec93eb25580fcb1a7c616640e00a | 454,629 |
def lower_list(li):
""" Convert all element of a list to lowercase"""
if li:
return [x.lower() for x in li]
else:
return None | 0fbe2b8390c468d27a0733613121dc544059ae2e | 102,554 |
def transitions_in_episode_batch(episode_batch):
"""Number of transitions in a given episode batch.
"""
shape = episode_batch['u'].shape
return shape[0] * shape[1] | 7734eb329046603c1e0336cb22435e579a087e02 | 455,543 |
def _expand_ranges(ranges_text, delimiter=',', indicator='-'):
""" Expands a range text to a list of integers.
For example:
.. code-block:: python
range_text = '1,2-4,7'
print(_expand_ranges(range_text)) # [1, 2, 3, 4, 7]
:param str ranges_text: The text of ranges to expand
:retu... | ab63ef63e9ac545a4566259fe9a2a78c7c2d57fb | 334,824 |
def get_releases(events):
"""
Get all target releases from a list of events.
:return: List of (major, minor) release tuples, sorted in ascending order
"""
return sorted({event.to_release for event in events}) | adbf665c3b7a0068810a44c3c916bfcad6a3ef14 | 47,973 |
def extract_wikiproject_templates(templates):
"""
Iterates over a list of templates and returns WikiProject related templates
from them
"""
wikiprojects = []
for tpl in templates:
if tpl['title'].startswith("Template:WikiProject"):
wikiprojects.append(tpl['title'])
return... | c077b3b246a9895dce33ac450f2e182f298a9284 | 414,975 |
import fnmatch
def _fnmatch_lower(name: str | None, pattern: str) -> bool:
"""Match a lowercase version of the name."""
if name is None:
return False
return fnmatch.fnmatch(name.lower(), pattern) | e04d207de691dd3ee5d35dccf88a8c0ed8e5fc3c | 656,000 |
def jaccard_index_calc(TP, TOP, P):
"""
Calculate Jaccard index for each class.
:param TP: true positive
:type TP : int
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:return: Jaccard index as float
"""
try:
return TP / ... | 13f5a53ca114db2b3af928db0ab9fac885ad2923 | 52,565 |
def format_timedelta(td):
"""Format td in seconds to HHH:MM:SS."""
td = int(td)
hours, remainder = divmod(td, 3600)
minutes, seconds = divmod(remainder, 60)
return '{:03}:{:02}:{:02}'.format(hours, minutes, seconds) | b8febccac40fe17a061e0cdba255b9a8b420cabb | 587,780 |
import torch
def optimizer_creator(model, config):
"""Constructor of one or more Torch optimizers.
Args:
models: The return values from ``model_creator``. This can be one
or more torch nn modules.
config (dict): Configuration dictionary passed into ``TorchTrainer``.
Returns:
... | ea006e131ecd356793a596efe6e32c28bce6be40 | 513,831 |
import re
def unescape(value):
""" Removes escapes from a string
"""
return re.sub(r'\\(.)', r'\1', value) | 8bcba66fde82d0af226e36405cad44fe78474bc3 | 124,570 |
def compute_52_week_range(df, column_source_low, column_source_high, column_target_low, column_target_high):
"""
Compute 52 Week Range (Low~High).
:param df: dataframe (sorted in ascending time order)
:param column_source_low: name of source column in dataframe with low values to compute
:param col... | 0d65c7ea9656585632045519a2c72f08261ecf46 | 343,457 |
def fst(t):
"""Return first element of a tuple"""
return t[0] | 7d5ad11dd9ba6a220395c5e049a3ec614ee4cbc1 | 167,283 |
def is_strf_param(nm):
"""Check if a parameter name string is one of STRF parameters."""
return any(n in nm for n in ("rates_", "scales_", "phis_", "thetas_")) | 995ab39c2ac86d2213a6180fb2bac427e041b110 | 621,087 |
import re
def normalize_subject(subject):
"""
Strips any leading Re or Fwd from the subject, and returns it. This is
sometimes useful for grouping messages.
"""
return re.sub(r'(?i)(re:|fw:|fwd:)\s+', '', subject) | 2e03d5f332734982b65d441f5bc7e0d9f3fcb7e8 | 505,903 |
def find_nums_within_range_for_current_row(row, minimum, maximum):
"""Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
count = 0
for n in row:
if minimum <= n <= maximum:
count = count + 1
return count | 4f12c34c84f102e058c5906222dd304ed8f3a9ea | 426,460 |
def _relative_path(path):
"""Strips leading slash from a path.
Args:
path - a file path
Returns:
string
"""
if path.startswith('/'):
return path[1:]
return path | effe58ffc230ac026a8467d41a45568e7b14f069 | 359,490 |
def snapPath(basePath, snapNum, chunkNum=0):
""" Return absolute path to a snapshot HDF5 file (modify as needed). """
snapPath = basePath + '/snapdir_' + str(snapNum).zfill(3) + '/'
filePath = snapPath + 'snap_' + str(snapNum).zfill(3)
filePath += '.' + str(chunkNum) + '.hdf5'
return filePath | 0f1839f2249ea104b17c0b876d146a77dda2fb79 | 256,376 |
def demo_to_dict(demo):
"""
Convert an instance of the Demo model to a dict.
:param demo: An instance of the Demo model.
:return: A dict representing the demo.
"""
return {
'id': demo.id,
'name': demo.name,
'guid': demo.guid,
'createdAt': demo.createdAt,
... | 5c3f00e963ba5bf92e8b79e69434a9494fd4a784 | 284,733 |
def find_ccs(unmerged):
"""
Find connected components of a list of sets.
E.g.
x = [{'a','b'}, {'a','c'}, {'d'}]
find_cc(x)
[{'a','b','c'}, {'d'}]
"""
merged = set()
while unmerged:
elem = unmerged.pop()
shares_elements = False
for s in merged.copy... | 4bff4cc32237dacac7737ff509b4a68143a03914 | 1,827 |
def _effect_brightness(brightness: int) -> int:
"""Convert hass brightness to effect brightness."""
return round(brightness / 255 * 100) | 0822678465f3cb3924e6e8e7b8946df8e74b8635 | 342,882 |
def dict_to_arg_flags_str(flags_dict):
"""
Converts a dictionary to a commandline arguments string
in the format '--<key0>=value0 --<key1>=value1 ...'
"""
return ' '.join(
['--{}={}'.format(k, flags_dict[k]) for k in flags_dict.keys()]) | e7becc710f0ad8b040cd005434ebcf478a7a3aee | 167,725 |
def _map_captured_resources_to_created_resources(
original_captures, resource_map):
"""Maps eager resources captured by a function to Graph resources for export.
Args:
original_captures: A dictionary mapping from resource tensors captured by
the function to interior placeholders for those resources (... | 9acb1816ff1ec14970961103b4451f1f61568d45 | 509,712 |
def _format_path_with_rank_zero(path: str) -> str:
"""Formats ``path`` with the rank zero values."""
return path.format(
rank=0,
local_rank=0,
node_rank=0,
) | 7ce5bca2317cda83ffcba08236c2c9ff51e01f19 | 300,911 |
def colourfulness_correlate(F_L, C_94):
"""
Returns the *colourfulness* correlate :math:`M_94`.
Parameters
----------
F_L : numeric
Luminance adaptation factor :math:`F_L`.
numeric
*Chroma* correlate :math:`C_94`.
Returns
-------
numeric
*Colourfulness* corr... | ba723f2e68d6e0ed576f3aa340b17af11df63de7 | 470,734 |
import logging
def error(line):
"""Log error"""
return logging.error(line) | afdd6ca2b58bd0eb10b411c2052aeb3cbde66a82 | 481,230 |
import traceback
def _FormatException(exc):
"""Format an Exception the way it would be in a traceback.
>>> err = ValueError('bad data')
>>> _FormatException(err)
'ValueError: bad data\n'
"""
return ''.join(traceback.format_exception_only(type(exc), exc)) | 42041266fa83c727c95b726eeeb22b7d928b0f04 | 415,506 |
def list_datasets(print_list=True):
"""Print available datasets in the cptac.pancan module.
Parameters:
print_list (bool, optional): Whether to print the list. Default is True. Otherwise, it's returned as a string.
"""
datasets = [
"PancanBrca",
"PancanCcrcc",
"PancanCoad",... | 037e101a9c907fbb0a773c845a1a2b4af3ff2504 | 618,820 |
def escape_attribute_value(attrval: str):
"""
Escapes the special character in an attribute value
based on RFC 4514.
:param str attrval: the attribute value.
:return: The escaped attribute value.
:rtype: str
"""
# Order matters.
chars_to_escape = ("\\", '"', "+", ",", ";", "<", "=",... | bcb06fba8799904897f80a3a55ea3892024a6d83 | 144,009 |
def get_FOV_ends(cent, FOV):
"""Take center of FOV and FOV in degrees [0-360]
and return low and high endpoints in degrees.
"""
l = (cent - FOV/2) % 360
h = (cent + FOV/2) % 360
return [l,h] | bd79c1f42b978c09a7cd0d8fbb7a20230f78e842 | 511,428 |
def deduplicate(reply):
"""
list deduplication method
:param list reply: list containing non unique items
:return: list containing unique items
"""
reply_dedup = list()
for item in reply:
if item not in reply_dedup:
reply_dedup.append(item)
return reply_dedup | 2f3f6368e8c525e3fdc31cd88bbe13923b4416cf | 565,135 |
from pathlib import Path
def extract_sequence(fasta: Path, target_contig: str) -> str:
"""
Given an input FASTA file and a target contig, will extract the nucleotide/amino acid sequence
and return as a string. Will break out after capturing 1 matching contig.
"""
sequence = ""
write_flag = Fal... | 547ba39dc3658e6c28c77012eba79393c01690ee | 652,612 |
def format_decimal_as_string(value):
"""
Convert a decimal.Decimal to a fixed point string. Code borrowed from
Python's moneyfmt recipe.
https://docs.python.org/2/library/decimal.html#recipes
"""
sign, digits, exp = value.as_tuple()
if exp > 0:
# Handle Decimals like '2.82E+3'
... | f31cf34006ea44969213d3810c6a70a38f19a307 | 615,114 |
from typing import Iterable
from typing import Any
from functools import reduce
def concat(*it: Iterable[Any]) -> Any:
"""
Concatenation of iterable objects
Args:
it: Iterable object
Examples:
>>> fpsm.concat([1, 2, 3], [4, 5, 6])
[1, 2, 3, 4, 5, 6]
"""
return reduce(... | e2b9d1604630198486fa0649d62784078547031a | 11,675 |
import torch
import itertools
def pit_loss(
estimate: torch.Tensor,
target: torch.Tensor,
axis: int,
loss_fn=torch.nn.functional.mse_loss,
return_permutation: bool = False
):
"""
Permutation invariant loss function. Calls `loss_fn` on every possible
permutation betw... | feabf5b625e915a1bee86df13394a49bfdf6f6f9 | 88,387 |
def _input_wrap(prompt, default=None):
"""
Run input() with formatted prompt, and return
The while loop can be used to ensure correct output
"""
understood = False
while not understood:
result = input(prompt.format(default=default)).lower().strip()
if result in {"y", "yes"}:
... | 112e1bf613e1fc79d570107e881edbb8f721076c | 633,738 |
def point_partners_to_partner_indices(point_partners, n_partners):
"""
Convert the partner indices for each point to a list of lists with the
indices for all partners.
"""
partner_indices = [[] for i in range(n_partners)]
for i, partner_index in enumerate(point_partners):
if partner_inde... | 2255b367c03802d9606ec5893654985a9fe18b9d | 467,485 |
from unittest.mock import patch
def patch_bond_device_state(return_value=None, side_effect=None):
"""Patch Bond API device state endpoint."""
if return_value is None:
return_value = {}
return patch(
"homeassistant.components.bond.Bond.device_state",
return_value=return_value,
... | a200f10ad5c8451fecefce2506e63ab371dfc886 | 435,455 |
def check_instance_tag(tag_key, tag_value, app):
"""
Check if instance tag given matches the application configuration
:param tag_key:
:param tag_value:
:param app:
:return: bool
>>> my_app = {'_id': '123456789', 'name': 'webapp', 'env': 'dev', 'role': 'webfront'}
>>> check_instance_tag... | eb41647f7bb999ea734e124e68f6d78ac0f952ec | 298,992 |
def requires_reload(action, plugins):
"""
Returns True if ANY of the plugins require a page reload when action is taking place.
"""
for plugin in plugins:
plugin_class = plugin.get_plugin_class_instance()
if plugin_class.requires_reload(action):
return True
return False | 5ecc2a004e3a25d85435909acc4a04d9ee727b5e | 329,206 |
def _join(c):
"""Return `str` with one element of `c` per line."""
return '\n'.join(str(x) for x in c) | 516fc920996e6bb58836c7cefe0d3e70b16e6db8 | 224,926 |
import re
def eliminate_newlines_after_function_definition_in_string(code: str) -> str:
"""Eliminates all newlines after the function definition in a string, e.g.
def foo(a):
return a + 1
will become:
def foo(a):
return a+1"""
return re.sub(
pattern=r"(def \w+\([^:]*\)... | 1a664c4aa798f066b5d7b0fcf81abb9c75342708 | 322,871 |
def doy(dt):
""" Find the day of year of the datetime.
The returned DoY is in the range [1-366].
"""
date = dt.date()
jan01 = date.replace(month=1, day=1)
doy = (date - jan01).days + 1
return doy | b81e54432113bb51ce5fa3ae0e770a892f3110bc | 156,560 |
def intersection(bb1, bb2):
""" Calculates the Intersection of two aabb's
"""
min_w = min(bb1[2], bb2[2])
min_h = min(bb1[3], bb2[3])
if bb1[0] < bb2[0]:
leftbb, rightbb = bb1, bb2
else:
leftbb, rightbb = bb2, bb1
if bb1[1] < bb2[1]:
topbb, bottombb = bb1, bb2
el... | 368177cc00fcfff507198f39be3184fc2eed1855 | 29,040 |
def get_group_detail(groups):
"""
Iterate over group details from the response and retrieve details of groups.
:param groups: list of group details from response
:return: list of detailed element of groups
:rtype: list
"""
return [{
'ID': group.get('id', ''),
'Name': group.g... | dc56db5bb7fb4775a6b3d778fc22a20b90029137 | 475,176 |
def duplicate_count(counts):
""" Return the number of entries in COUNTS with a value of 2 or more. """
count = 0
for v in counts.values():
if v > 1:
count += 1
return count | c2b4fd6800f92b8aea5d17ae93d3e1fa1ac035ee | 339,511 |
def _false(*args):
"""
Returns ``False`` (used internally as a default method).
"""
return False | a363b75ec087c037555f3fa6f38b6c64963c08c9 | 536,755 |
def extract_titles(row):
"""Creates a list of dictionaries with the titles data and alternatives if exists
Args:
list: row[1:5].values
Return:
list of dictionaries with title and title type
"""
data = [
{"title":row[0], "type": "OriginalTitle"}
]
for item in... | c0b505d7d3617361f044f1025e29aa67f19a521f | 160,643 |
def capital_recovery_factor(interest_rate, years):
"""Compute the capital recovery factor
Computes the ratio of a constant loan payment to the present value
of paying that loan for a given length of time. In other words,
this works out the fraction of the overnight capital cost you need
to pay back... | 4a92ca527557087537973e2adfedd48279a7c59e | 36,625 |
def get_all_users(client):
"""
Get all current Zulip users.
:param client: A Zulip client object
:return: Dictionary containing all current users.
"""
result = client.get_members()
return result | d0bd98e503db8fe50d7e489fd68cc8c23dfb5f2c | 267,546 |
def chunker(seq, size):
"""
Iterate over an iterable in 'chunks' of a given size
Parameters
----------
seq : iterable,
The sequence to iterate over
size : int,
The number of items to be returned in each 'chunk'
Returns
-------
chunk : seq,
The items of the c... | f483646d9bc8b8de0bd817e510ddc67becc5ff29 | 521,166 |
import fnmatch
def getLabels(source, path):
"""Get all labels for given path
:param source: Labels definition
:type path: dict
:param path: File full path
:type path: string
:return: Labels
:rtype: list[string]
"""
result = []
for label, patterns in source.items():
... | 0310e38b185016f781ff2a958f4e6bbd82d86d39 | 660,352 |
import random
def roll(dice):
"""Takes arguments in the format "{#}d{#}", e.g. 2d6 returns the total"""
try:
num, die = dice.split('d')
total = 0
for i in range(0,int(num)):
roll = random.randint(1,int(die))
print("rolling... " + str(roll))
total += ... | 3ba2284b49895ed57116e336c65199f643fc1a14 | 275,967 |
def get_df_attr(df, attr_name, default_val):
""" Get Dataframe attribute if exists otherwise default value
:return: Dataframe attribute
"""
return df.__dict__.get(attr_name, default_val) | 501caef9d2f8dbe721d4fe03879423d3bbe091ab | 399,653 |
import random
def random_seq(length: int,
charset: str = "ATCG") -> str:
"""Get a random sequence.
:param length: Length of sequence.
:param charset: Char population.
:return: Random sequence
"""
return "".join(random.choices(charset, k=length)) | 036742e9777d15a813b99b61e54dfb03f8a7ab80 | 48,674 |
def fade_copies_right(s):
""" Returns the string made by concatenating `s` with it's right slices of
decreasing sizes.
Parameters
----------
s : string
String to be repeated and added together.
Returns
-------
output : string
String after it has had ever decreasing sli... | 1c2612da69b12e245d87f9df3c57e7a399191398 | 436,121 |
def verify_social_media_platform(platform_name: str) -> bool:
"""
A helper function to make verifying social media platform strings easier
Parameters
----------
platform_name: str
The name of the social media platform to be verified.
Valid inputs are: 'f', 't', 'i', 'a'
Returns... | c6a52430ff5c2d0c6bf71fe3d8717b7628ccc897 | 586,164 |
def collect_nodes(kind, collection, gen):
"""
Collects nodes with a given kind from a generator,
and puts them in the provided list.
Returns the first node from the generator that does not
match the provided kind.
"""
tail = None
for node in gen:
if node.kind is not kind:
... | 7f2a996bea6c222c6fca045490be21f34177b030 | 154,801 |
def convert_number_to_month(month_int):
"""
Return a month as string given a month number
:param month_int: int
:return: str
"""
months = ['January',
'February',
'March',
'April',
'May',
'June',
'July',
... | 2b43ee6d7978a1a131e3a4a5560fe37e3d1ae98f | 381,114 |
def extractGeom(lineList):
"""
Function used by loadPd_q to extract the geometries.
:lineList: line with geometries in clean format, partial charges and energies
:return: list of geometry in format [['H',-0.5,0.0,0.0,'H',0.5,0.0,0.0], ['H',-0.3,0.0,0.0,'H',0.3,0.0,0.0]...
"""
geomPart = lineLis... | f4b84b96a58ebe4dc286bb9c41d86ffedbeb0334 | 493,240 |
def linear_interpolation(left, right, alpha):
"""
Linear interpolation between `left` and `right`.
:param left: (float) left boundary
:param right: (float) right boundary
:param alpha: (float) coeff in [0, 1]
:return: (float)
"""
return left + alpha * (right - left) | c4b75b9143d066d298d83628881442e2946c6d41 | 211,931 |
def mediana(valores):
"""
Encontra a mediana de 'valores', isto é, o valor que ocupa a posição
central da lista ordenada. Quando a lista tem tamanho par,
definimos a mediana como o valor da primeira posição na segunda
metada da lista ordenada.
Parâmetros: lista de floats.
Retorna: a mediana... | 01897bf8cecf7292c3d02148e4fb8f1f8cd44195 | 539,713 |
import requests
def get_sequence(UniprotID):
"""Get protein sequence from UniProt Fasta (using REST API).
"""
# collect UniProtID data
fasta_URL = 'https://www.uniprot.org/uniprot/'+UniprotID+'.fasta'
request = requests.post(fasta_URL)
request.raise_for_status()
fasta_string = request.tex... | ede837154bda738dc8e7e83c97c5f81b284db17c | 73,574 |
def _match_first_key(skip_first_axis=None, feature=""):
"""Helper function to match and remove skip_first_axis from feature
:param skip_first_axis: True or string. if set, ignore first axis of input histogram(s)
:param feature: input feature
:return: match and (rest of) feature
"""
assert isins... | 8dd0278a2754cc6d9e31b34a83477cd4396a920b | 416,238 |
def count_trajectories(n: int) -> int:
"""
The Grasshopper is in position 1.
The Grasshopper may jump to +1, +2 or +3.
How many possible trajectories does the grasshopper have to get to position n?
If n<=1, consider that the Grasshopper has 0 possible trajectory.
>>> count_trajectories(0)
0... | d9c0127e2a21346872783d6b4b9ea44fc2bde285 | 672,815 |
def egcd(a,b): # a > b > 0
""" Extended great common divisor, returns x , y
and gcd(a,b) so ax + by = gcd(a,b) """
if a%b==0: return (0,1,b)
q=[]
while a%b != 0:
q.append(-1*(a//b))
(a,b)=(b,a%b)
(a,b,gcd)=(1,q.pop(),b)
while q:(a,b)=(b,b*q.pop()+a)
retu... | fe0f1738d46e1371e144f328c70fe480c219584f | 316,860 |
def is_valid_label(label, all_labels):
"""a function to return whether the input "label" exist in the all_labels, which is a list of string"""
return label in all_labels | dbd7e05b9a097a96940a6f95dcde042274121cf4 | 504,539 |
import re
def get_readable_path_str(original_path, max_len):
"""
Truncates path to max_len characters if necessary
If the result is a path within nested directory, will remove partially
truncated directories names
"""
if len(original_path) < max_len:
return original_path
trunca... | f2d8bd7499a087f561a1b3830f06c983751fe642 | 523,836 |
def empty_name(got):
""" Empty name error. """
return "Expected non-empty name, got {}.".format(repr(got)) | ec621d1833afca1a164ab11f99b8693ba0472fa1 | 247,015 |
def square(x: int) -> int:
""" This function squares numbers. You can use it like that:
:code:`square(5)`.
Args:
`x` (int): number to square
Returns:
int: squared number
:Example:
>>> square(3)
9
>>> square(10)
100
"""
return x**2 | f32d838ef011c97bd17eee16a6d731ad044ede12 | 591,793 |
def duration_to_string(value):
"""Converts the given timedelta into an appropriate ISO-8601 duration format for JSON. Only handles positive
durations correctly. Fractional seconds are rounded.
:param value: The timedelta to convert
:type value: :class:`datetime.timedelta`
:returns: The ISO-8601 dur... | 06bc74c30de00ac223c208db06f0b48cd0cb2ad5 | 664,603 |
def convert_pandas_dtypes_to_builtin_types(col_type):
"""Convert pandas data types to python builtin ones, like pandas object to python str."""
col_type = str(col_type)
if "str" in col_type:
return str
elif "int" in col_type:
return int
elif "float" in col_type:
return float
... | b53cc870ef947c4630b9990535289b5d00de3eca | 122,852 |
def seq_type(seq):
"""
Determines whether a sequence consists of 'N's only
(i.e., represents a gap)
"""
return 'gap' if set(seq.upper()) == {'N'} else 'bases' | 5555e5cd0ccdbf8f5e7b475c5c983ab54a17fb07 | 9,475 |
def user_exists(cursor,username):
"""
Test whether a user exists, from its username
Parameters:
==========
cursor: Psycopg2 cursor
Cursor of type RealDict in the postgres database
username: Str
Name of the user
"""
SQL = "SELECT count(*) AS nb FROM users WHERE username=%s... | c221cbb6dd3c99d1eacfc88c8f2161276680b938 | 17,646 |
def _conv_type(s, func):
"""Generic converter, to change strings to other types.
Args:
s (str): String that represents another type.
func (function): Function to convert s, should take a singe parameter
eg: int(), float()
Returns:
The type of func, otherwise str
""... | e72cab10a0256cb57cddfad7da7f5f1239476852 | 586,488 |
def true_or_false(in_str):
"""Returns True/False if string represents it, else None."""
in_str = in_str.lower()
if in_str.startswith(('true', 'y', '1', 'on')):
return True
elif in_str.startswith(('false', 'n', '0', 'off')):
return False
else:
return None | e23adf40237d6111cb0a6388a95aab79ba2aa35b | 607,138 |
def convert_to_number(string):
"""
Tries to cast input into an integer number, returning the
number if successful and returning False otherwise.
"""
try:
number = int(string)
return number
except:
return False | 30110377077357d3e7d45cac4c106f5dc9349edd | 708,626 |
def unauthorized_update_message_text(update_message_text):
"""Fixture for mocking an incoming update of type message/text that is not in our `allowed_chat_ids`."""
update_message_text["message"]["from"]["id"] = 1234
update_message_text["message"]["chat"]["id"] = 1234
return update_message_text | a846e3cc2f2752c58c8a61749536a9f89d85fb73 | 317,794 |
import random
def randomLabels(intree, p_speciation=0.7):
"""
Function to assign random speciation and duplication nodes to a tree.
Returns a new tree (leaves the input tree unchanged)
:param intree: a tree as Dendropy object
:param p_speciation: probability of a speciation node.
"""
t ... | f73e26b53a2b40ef48ad661fb287ebcc47d7bfbe | 220,026 |
def custom_admin_notification(session, notification_type, message, task_id=None):
"""
Function for implementing custom admin notifications.
notifications are stored in session and show to user when user refreshes page.
A valid session object must be passed to this function with notification type and me... | 6ab3b478c5109a821fc64201c9468e3d8d132cff | 635,646 |
import bz2
import gzip
def open_output(output, opts):
"""Open output file with right compression library
"""
if opts.bzip:
return bz2.open(output, 'wt')
elif opts.gzip:
return gzip.open(output, 'wt')
else:
return open(output, 'w') | 9f830afb3422f0707ef6b49c9b2000a35b4bc0a0 | 57,036 |
def sizes(ranges):
"""Get a list with the size of the ranges"""
sizes = []
for r in ranges:
sizes.append(r[1] - r[0]) # 1: end, 0: start
return sizes | c612ec12172d7c6e0eac14cbd8ef262a3ee8efe2 | 330,798 |
def restore_training(fn, netclass, trainclass, valclass, valdata, gpu=True):
"""Restore training from file.
:param fn: filename to load
:param netclass: :class:`.network.Network` class to use
:param trainclass: :class:`TrainAlgorithm` class to use
:param valclass: :class:`.validate.Validation` clas... | c9fcfb9e0635ca911a86f93e25f57ad779eee4ff | 181,656 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.