content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def LRPermTest(otuDf, labels, statfunc=_dmeanStat, nperms=999, adjMethod='fdr_bh', seed=110820):
"""Calculates pairwise log ratios between all OTUs and performs
permutation tests to determine if there is a significant difference
in OTU ratios with respect to the label variable of interest.
Parameters
... | 28e23a53ce8e1f3d0bce1f5486095581c0752bac | 3,606,747 |
def get_traitset_map(pop):
"""
Utility method which returns a map of culture ID's (hashes) and the trait set
corresponding to a random individual of that culture (actually, the first one
we encounter).
"""
traitsets = {}
graph = pop.agentgraph
for nodename in graph.nodes():
tra... | c80f1f05e0dd5268990e62e6b87726d5349b53f7 | 3,606,748 |
def is_image_file(filename):
"""Checks if a file is an allowed image extension.
Args:
filename (string): path to a file
Returns:
bool: True if the filename ends with a known image extension
"""
return has_file_allowed_extension(filename, IMG_EXTENSIONS) | b6b72bf54a4266fcce6994423e4418a6d8dd8dfc | 3,606,749 |
def load_image_to_numpy(image_path, mode="RGB"):
"""
Arguments:
image_path (str): Path to an image or mask
mode (str, optional): The mode to convert to
"""
return np.array(Image.open(image_path).convert(mode)) | 0aff5cd0757019bb3eee3543ff4340442c86cc07 | 3,606,750 |
def most_read_creators(num=10):
"""
Returns a QuerySet of the Creators who have the most Readings associated
with their Publications.
Because we're after "most read" we'll only include Creators whose role
was left empty or is 'Author'.
"""
return Creator.objects.by_readings()[:num] | 7e2a1b60c24601e6cb0645846114c92479a11afe | 3,606,751 |
def get_current_term_start(*args, **kwargs):
"""*args and **kwargs passed to timedelta if supplied.
Timedelta with no arguments is identity.
"""
term = Term.objects.first()
if term:
return term.start + timedelta(*args, **kwargs) | 4919ab04381df6a74dfc20a5983ccb106a04b765 | 3,606,752 |
def softmax_loss(user_embeddings, movie_embeddings, labels):
"""Returns the cross-entropy loss of the softmax model.
Args:
user_embeddings: A tensor of shape [batch_size, embedding_dim].
movie_embeddings: A tensor of shape [num_movies, embedding_dim].
labels: A tensor of [batch_size], such that labels[i... | a642e614b44f0c3feac9be62cd2a2f57f2df0aad | 3,606,753 |
def prefix(txt, pref):
"""
Place a prefix in front of the text.
"""
return str(pref) + str(txt) | e9b4efd78f9132f7855cccba84c8a2d4b58ae8bb | 3,606,754 |
def prettycode(str):
"""Try to beautify a line of code."""
if len(str) < 80:
return str
lparen = str.find('(')
rparen = str.rfind(')')
if lparen < 0 or rparen < 0:
Fatal("Invalid code string")
head = str[ 0 : lparen ]
inner = str[ lparen+1 : rparen ]
tail = str[ rparen+1 : ]
args = inner.spl... | 1803a36b9934ae9d6184edcc437c0a04ae60e4e9 | 3,606,756 |
import json
def get(event, context):
"""
Get All Sheets
"""
sheets_folder = event['sheets_folder']
all_current_sheet_names = get_all_sheets_names_for_a_folder(s3_client, sheets_folder, SHEET_DATA_S3_BUCKET)
return {
"statusCode": 200,
"body": json.dumps({
'result': ... | ffe77e71137287399b35072974ea56b6104a95fb | 3,606,758 |
def filter2():
"""
Returns a 1x1x12x12 matrix filled with a simple corner and shifts of it
"""
f = _get_filter(2)
# Reshape a 12x12 filter to 1x1x12x12
f = np.reshape(_roll_out_rows(f), [1, 1, 12, 12])
return tf.constant(f, tf.complex64) | fd56d3272e73afef5436eb72beb85713760da6be | 3,606,759 |
from typing import Tuple
import torch
import multiprocessing
def build(
task_config: task_config_pb2.TaskConfig
) -> Tuple[
SeqToSeq, int, torch.utils.data.DataLoader, torch.utils.data.DataLoader
]:
"""Builds a ``task_config`` and returns each component.
Args:
task_config: A :py:class:`task_c... | 2b5dbbaf560a3ea4e961e019f553970473da4979 | 3,606,760 |
def _f_dot_kinematic_car(state: EgoState, vehicle: VehicleParameters) -> EgoState:
"""
Compute x_dot = f(x) for a kinematic car
:param state for which to compute motion model
:param vehicle parameters
"""
lf = vehicle.front_length - vehicle.cog_position_from_rear_axle
lr = vehicle.rear_leng... | a477f9b9e464935d6e2291b946e9ce62b4c827f3 | 3,606,762 |
def _fix_basebox_url(url):
"""
Kinda fix a basebox URL
"""
if not url.startswith('http'):
url = 'http://%s' % url
if not url.endswith('/meta'):
url += '/meta'
return url | 5c1b446809089ae9239c232588b3f6176ec79549 | 3,606,763 |
def floodplain_elevation(
ds_model: xr.Dataset,
adjust_river_d8: bool = False,
connectivity=4,
logger=logger,
**kwargs,
) -> xr.Dataset:
"""Returns a binary floodplain classification and hydrologically adjusted elevation.
Parameters
----------
ds_model : xr.Dataset
Model dat... | d77700ed8a9b592571b9b4ce58022e4a04aa056d | 3,606,764 |
def altair_style(return_colors=True, return_palette=True, **kwargs):
"""
Assigns the plotting style for matplotlib generated figures.
Parameters
----------
return_colors : bool
If True, a dictionary of the colors is returned. Default is True.
return_palette: bool
If True, a... | c5cc1b93a626bcb5fe638b45c9329d9bcf825ae8 | 3,606,765 |
def isinstance_all(iterable, class_or_tuple):
"""
Check if all items of an iterable are instance of
a class ou tuple of classes
>>> isinstance_all(['Hello', 'World'], str)
True
>>> isinstance_all([1, 'Hello'], (str, int))
True
>>> isinstance_all([True, 'Hello', 5], int)
False
""... | 1ea1bf7d66e5436ac429123fef4b33ba92195292 | 3,606,766 |
import pyclbr
def get_module_classes(module_name):
"""Returns all classes in module."""
module_members = pyclbr.readmodule_ex(module_name, [])
module_members = dict(sorted(module_members.items(), key=lambda a: getattr(a, 'lineno', 0)))
module_members = module_members.values()
classes = [x for x i... | 67d0a83d50bec7d40e051447e675824df6c77986 | 3,606,767 |
def _tagging(clip_ending_second, onsets, offsets):
"""
Tag the audio by judging whether the clip contains a dialogue.
If the clip contains dialogues in it, we tag it as 1. Otherwise we tag it as 0.
"""
assert int(clip_ending_second)%DatasetConfig.dataset_clip_time == 0., 'Sorry, there is a length mi... | 397a7410cfe1d6bdda263c9e8168b9145f7b6061 | 3,606,768 |
def sample_recipe(user,**kwargs):
""" Create and return a sample recipe """
defaults = {
'title':'Sample recipe',
'time_miniutes':10,
'price':5.00
}
defaults.update(kwargs)
return Recipe.objects.create(user = user, **defaults) | 81d731b700c80bcaf3f7ac2c3674443515f3dd7a | 3,606,770 |
import plistlib
def GetPlistFromExec(cmd, stdin=None):
"""Executes a command and returns a parsed plist from the output.
Args:
cmd: str or sequence, command and optional arguments to execute.
stdin: str, optional, to send to standard in.
Returns:
Dict from plistlib.readPlistFromString.
Raises:
... | b7a7ad78e24fab063c7bb7bc3e509f0369b8b981 | 3,606,774 |
from typing import Optional
from typing import Collection
def resume(
id: Optional[str],
namespaces: Collection[references.NamespacePattern],
clusterwide: bool,
peering_name: str,
) -> None:
""" Resume the resource handling in the operator(s). """
identity = peering.Identity(id... | d03ee817c895fd3388eaa8641838bc7d39d32d4d | 3,606,775 |
from typing import Any
import torch
def _recursive_copy_to_device(value: Any, non_blocking: bool, device: torch.device) -> Any:
"""
Recursively searches lists, tuples, dicts and copies tensors to device if
possible. Non-tensor values are passed as-is in the result.
.. note: These are all copies, so ... | 2778c9e9cfb942cb019eb119e24d1556af6fa48d | 3,606,776 |
def getDivisionsCount(xStarts: [int], yStarts: [int]):
"""
Return the number of division for given starting x and y coordinates
:param xStarts: the x-axis starting coordinates
:param yStarts: the y-axis starting coordinates
:return: number of divisions
"""
return len(xStarts) * len(yStarts) | 5f3f1133917a108ab2ef9546380b5f58dacfa562 | 3,606,777 |
from pathlib import Path
def config(base_config):
""":py:class:`nemo_nowcast.Config` instance from YAML fragment to use as config for unit tests."""
config_file = Path(base_config.file)
with config_file.open("at") as f:
f.write(
"""
vhfr fvcom runs:
host: arbutus.cloud
ssh key: Sal... | adaa1f4d53e912128e665d1915d70b3c9102a4b8 | 3,606,778 |
import random
def make_data(n,m):
"""make_data: prepare matrix of m times n random processing times"""
p = {}
for i in range(1,m+1):
for j in range(1,n+1):
p[i,j] = random.randint(1,10)
return p | 3a51402c3807ab8ca0f1f3386663299a3e254bf1 | 3,606,779 |
def get_errors(job_types=None, error_ids=None, error_names=None):
"""Exports all the errors in the system based on the given filters.
:param job_types: Only include errors that are referenced by the given job types.
:type job_types: list[:class:`job.models.JobType`]
:param error_ids: A list of unique e... | 68e42b99b3ae84098aa63c7cc0f2ce827e3262c5 | 3,606,780 |
def to_gigabytes(number):
"""Convert a number from KiB to GiB
This is used mainly for the gauge, everything else uses the dynamic
`unit` function.
"""
return number / 1024 ** 2 | d930541627f32415e432fea57da4c0bc2fa7909f | 3,606,782 |
import configparser
def upgrade_config(thelogger, cfg):
"""Upgrade config file if needed."""
try:
cfg.get("settings", "initial-stoploss-percentage")
except configparser.NoOptionError:
cfg.set("settings", "initial-stoploss-percentage", "[]")
with open(f"{datadir}/{program}.ini", "w... | bc6acd5faa86d442d02fe782710d4eeed171fde6 | 3,606,783 |
from typing import List
def get_bond_pairs(mol: Chem.Mol) -> List[List[int]]:
"""Returns a list of all pairs of atoms that have a bond between each other.
"""
bonds = mol.GetBonds()
res = [[],[]]
for bond in bonds:
res[0] += [bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()]
res[1] +=... | 9c86600757f9a2daff182cf13bf1d818fc63195d | 3,606,786 |
def get_sorted_main_channels(mean_masks, unmasked_channels):
"""Weighted mean of the channels, weighted by the mean masks."""
main_channels = np.argsort(mean_masks)[::-1]
main_channels = np.array([c for c in main_channels
if c in unmasked_channels])
return main_channels | 290a74bc4343e786811dd2ceac8e3a6e968af41b | 3,606,787 |
import torch
def differential(f, A, E):
""" Computes the differential of f at A when acting on E: (df)_A(E) """
n = A.size(0)
M = torch.zeros(2*n, 2*n, dtype=A.dtype, device=A.device, requires_grad=False)
M[:n, :n] = A
M[n:, n:] = A
M[:n, n:] = E
return f(M)[:n, n:] | d424c9fbe7344b3ba4293c1e3e8e192dfa253f66 | 3,606,788 |
import scipy
def convert_sparse(data):
"""Convert columns with sparse data into sparse matrix.
Use sparse related function in Scipy to convert sparse data columns into
sparse matrix.
:param data: Dataframe. The Pandas dataframe to be processed.
:return: Dataframe. The converted dataframe.
"... | 318badefe9a1c6a1cdceaa55766e70ab88f1e999 | 3,606,789 |
def arctan(x):
"""
A generic tangent operator with backend selector
"""
backend = getBackend(x)
if backend == 'scalar':
return np.arctan(x)
elif backend == 'numpy':
return np.arctan(x)
elif backend == 'arrayfire':
return arrayfire.arith.atan(x)
elif backend == 'to... | 848592e2836881c4c3b76e96a2de2bca6a69f265 | 3,606,790 |
def get_distance(vectors):
"""[Calculate the euclidian distance between two vectors,
represented as columns in a DataFrame.]
Args:
vectors ([DataFrame]): [DataFrame containing the
two columns representing the vectors.]
Returns:
[Float]: [Euclidian distance of the vectors.]
... | 761681dd2f63cdd18b5d34bb28dfb8805d4e27d7 | 3,606,791 |
def comp_error_multi_init(x,C,n,*args,**kwargs):
""" computes the expected L1 norm between the empirical probabilities of a
choice set and those inferred by the MMNL with specified parameters
Arguments:
x- tuple of list of MMNL parameters and best parameters
K- number of MNL mixed
C- data for evaluation
"""
... | 9d7f96c6e6d6c3615bb10c399a5905e704ff1cdd | 3,606,792 |
def cal_similarity_matrix(x, y):
"""计算两个向量的增强皮尔逊相关系数
"""
nonzero_x = np.nonzero(x)[0]
nonzero_y = np.nonzero(y)[0]
intersect = np.intersect1d(nonzero_x, nonzero_y) # 交集
# 如果向量交集为空,则相似度为0
# 如果一个向量中所有值都相等,则无法计算皮尔逊相关距离(分母为0)
if len(intersect) == 0 or len(set(x[intersect])) == 1 or len(
... | c52791d9dffd118c45a2147256258293536f7f84 | 3,606,793 |
def cloudfront_distributions():
"""
Retrieve all CloudFront distributions (global).
Tags retrieved.
"""
service = boto3.client("cloudfront", config=MSAM_BOTO3_CONFIG)
response = service.list_distributions()
items = response["DistributionList"]["Items"]
while "NextMarker" in response["Dis... | 068f75000d31a9d50a35701108adc590e0e9f22b | 3,606,794 |
def inference_by_sample(n_steps, control_params):
"""
Returns
-------
output :
indference results
"""
# get input data
placeholders = control_params["placeholders"]
x = placeholders["x"]
pot_points = placeholders["potential_points"]
# get parameters
hy_param = hy.get_hyperparameter()
... | 4a7d0ba7c3724f7fb8eee530da092dc0965cb761 | 3,606,795 |
import torch
def swap_channels(img_1: np.ndarray, img_2: np.ndarray, ch_start: int, ch_end: int, model, swap_levels=None):
"""
rec_img_n1d2 has base of img_2 and selected channels from img_1 are inculcated.
"""
with torch.no_grad():
if swap_levels is None:
swap_levels = [True] * le... | 73f18ff24beeaa6e36635935458387b1fc76a258 | 3,606,796 |
def authorize_role(role=None):
"""
This route is used to ensure sensitive static content is witheld from withheld from clients.
"""
if role == "user" and safe_fail(api.user.get_user):
return "Client is logged in.", 200
elif role == "teacher" and safe_fail(api.user.is_teacher):
retur... | 54889dd6b2167e0ada4f656780b7ce9e85033e08 | 3,606,797 |
def pairwise_rho(X=None, reference_components=None, centroid="mean", interval_type="open", xlr=None, vlr=None):
"""
# Description
Pairwise proportionality `rho` (Erb et al. 2016)
# Parameters
* X: pd.DataFrame or 2D np.array of compositional data (rows=samples, columns=components)
*... | 70785f420a06c5ea9ff4d81baaed069cb3900845 | 3,606,798 |
def draw_polygons(img, polys):
"""Draw polygons on image.
Args:
img (np.ndarray): The original image.
polys (list[list[float]]): Detected polygons.
Return:
out_img (np.ndarray): Visualized image.
"""
dst_img = img.copy()
color_list = gen_color()
out_img = dst_img
... | 64f331348a4d068ff549b6e894949c92b0c0030c | 3,606,799 |
from core.profile import Profile
from core.yml import write_yml
from core.exceptions import ProfileTypeError
def update_profile(profile=None):
""" Take a Profile Object and write his data in type.yml file.
:param: profile: a Profile object
:type: profile: Profile Object
:return: True if s... | 38ddeb72a81e32ff360789a23bb94f2b8b8a0b4e | 3,606,800 |
def time_table(period: str, start_time: str = None) -> Table:
"""Creates a table that adds a new row on a regular interval.
Args:
period (str): time interval between new row additions
start_time (str): start time for adding new rows
Returns:
a Table
Raises:
DHError
... | 56d8bdc3188683eab59d5cdaa293ec74b7b9f751 | 3,606,801 |
from typing import Optional
from typing import Union
from typing import List
import logging
import csv
def tocsy(bmrb_ids: Optional[Union[str, List[str], int, List[int]]] = None,
input_file_names: Optional[Union[str, List[str]]] = None,
entry_objects: Optional[Union[pynmrstar.Entry, List[pynmrstar... | 55441a5f94ec20b6edf0ab2d59326a4f7d44b8d8 | 3,606,803 |
import tarfile
import pathlib
def _strip_paths(tarinfo: tarfile.TarInfo) -> tarfile.TarInfo:
"""Ensure source filesystem absolute paths are not reflected in tar file."""
original_path = pathlib.Path(tarinfo.name)
tarinfo.name = f"{original_path.name}"
return tarinfo | 06e262f93b3c5d0b8beab36b2ae7320a2464ad5b | 3,606,804 |
def eval_attr(utt, history, next_post, attr):
"""
Given a conversational history and an utterance, compute the requested
sentence-level attribute for utt.
Inputs:
utt: string. The utterance, tokenized and lowercase
history: list of string. This represents the conversation history.
... | 28b94d3b3d442605fd741a2ca33dd322c8cdeccf | 3,606,805 |
from aiida.common.links import LinkType
def get_pseudos_of_calc(calc):
"""Return a dictionary of pseudos used by a given (pw.x, cp.x) calculation.
This returns a dictionary ``pseudos`` that can be set in a builder as ``builder.pseudo = pseudos``.
:param calc: a pw.x or cp.x calculation.
:return: a d... | 928e6b2505a550791fbd41c275d21c94baeafd1d | 3,606,806 |
def get_optim(optimizer_params, model_parameters):
"""
Returns optimizer.
:param optimizer_params: Parameters used to configure the optimizer.
:param model_parameters: Parameters of the network.
:return:
"""
if optimizer_params.kind == "adam":
return optim.Adam(model_parameters, lr=o... | 0e02a1f023cd54efa98065545c6619fcf3276dc1 | 3,606,807 |
def matrix_to_adjacency(source: Matrix) -> Adjacency:
"""Converts adjacency matrix to an adjacency list."""
matrix = source[0]
names = source[1]
name_mapping = dict(zip(range(len(matrix)), names))
raw_adjacency = {
i: [j for j, adjacent in enumerate(row) if adjacent]
for i, row in e... | f927b2551cf6cc346ceaf6fae6c93e4cae12c71a | 3,606,808 |
from scipy import sparse
def combine_adjacency(*structure):
"""Create a sparse binary adjacency/neighbors matrix.
Parameters
----------
*structure : list
The adjacency along each dimension. Each entry can be:
- ndarray or sparse matrix
A square binary adjacency matrix for... | 3cd3404c5cc81c4fc29d1641ff80a48feb7ce8e3 | 3,606,809 |
def find_best_merge(text_dir, ids_files, emb_models, ext='txt', workers=1, processes=1):
"""
Find the best pair to merge
ids_files: list of (id, f) pairs, where ids are in chronical order and
each file f contains a text from one period in consecutive order
emb_models: list of word em... | a439d167f1857b985548d23cd0bdc7eaaa33d114 | 3,606,810 |
def listise(arg):
"""Convert arg into a list.
:Param arg:
This may be a list, tuple, non-string iterable or single value.
"""
return list(iterize(arg)) | 48c75ba8026398725a2516aa9e8e0db2dedfdeda | 3,606,811 |
def sequentially_executed(nb):
"""Return True if notebook appears freshly executed from top-to-bottom."""
exec_counts = [
cell["execution_count"]
for cell in nb.get("cells", [])
if (
cell["source"]
and cell.get("execution_count", None) is not None
)
]
... | d4d6f24f966726c6a6521888bea6fe13f57d1a21 | 3,606,812 |
def router_ref(conn, id_, required=True):
"""Fetch reference dict of Router identified by ID `id_`. Use
OpenStack SDK connection `conn` to fetch the info. If `required`,
ensure the fetch is successful.
Returns: the ref dict, or None if not found and not `required`
Raises: openstack's ResourceNotFo... | f0f38e073b305a5c339c0697b642d74c560d3d4d | 3,606,813 |
def GetCareMap(which, imgname):
"""Returns the care_map string for the given partition.
Args:
which: The partition name, must be listed in PARTITIONS_WITH_CARE_MAP.
imgname: The filename of the image.
Returns:
(which, care_map_ranges): care_map_ranges is the raw string of the care_map
RangeSet; ... | 849c96492014da14433d052f7f8ca49cdad95d0a | 3,606,814 |
def my_func_3(x, y):
"""
Возвращает возведение числа x в степень y.
Именованные параметры:
x -- число
y -- степень
(number, number) -> number
>>> my_func_3(2, 2)
4
"""
if y < 0:
r = 1.0
for _ in range(abs(y)):
r *= x
r = 1 / r
return... | fd9f4d5dc31b530cef2ee495b16c5781f74530b5 | 3,606,815 |
def matrix_to_timeseries(image, matrix, mask=None):
"""
converts a matrix to a ND image.
ANTsR function: `matrix2timeseries`
Arguments
---------
image: reference ND image
matrix: matrix to convert to image
mask: mask image defining voxels of interest
Returns
-------
AN... | 822f01e6306e3b10ee6cf955935725f9a78d0200 | 3,606,816 |
from datetime import datetime
def webfinger(request):
"""An implementation the webfinger protocol (http://tools.ietf.org/html/draft-ietf-appsawg-webfinger-12)
in order to provide information about up and downstream metadata available at this pyFF instance.
Example:
.. code-block:: bash
# curl h... | 5c78467b854f39c0ef597e8a1e913dedf24b938c | 3,606,817 |
def outdated(package, version):
"""Determine if version +version+ of +package+ is supported but not latest.
Returns True if it is; False otherwise.
"""
# versions = all()[package]
# Ignore anything with only 1 version available.
# if len(versions) == 1:
# return False
return numbe... | a55f3784b0781fee15f65ad0601981c4abfbe2b4 | 3,606,818 |
def flavors_ram(nova):
"""Get a dict of flavor IDs to the RAM limits.
:param nova: A Nova client.
:return: A dict of flavor IDs to the RAM limits.
"""
return dict((str(fl.id), fl.ram) for fl in nova.flavors.list()) | 796be050d98dac01a36da15a9de41466ebfbd75d | 3,606,819 |
def backupjob_update(context, backupjob_id, values):
"""
Set the given properties on a backupjob and update it.
Raises NotFound if backupjob does not exist.
"""
return IMPL.backupjob_update(context, backupjob_id, values) | 675dfc9e1ade1fa7abe1d008dcc27f2f3f9b22f7 | 3,606,820 |
def valuetable(items, columns='', enumeration=False):
"""
Common template tag to show a table with columns in detail pages.
:param enumeration: Show enumerations, see ``valuelist`` template tag.
"""
columns = columns.split(',')
letters = alphabet_enumeration(len(items))
records = []
f... | 03a28597746caece75c095137aadff617d02217f | 3,606,821 |
from datetime import datetime
def now():
"""Returns timezoned now date."""
return datetime.utcnow().replace(tzinfo=utc) | 8894674dc1a3d2880ed0c200eda730599fc50afc | 3,606,822 |
def mutate(individual, threshold, genePool):
"""
Mutates a solution by picking a random point along the solution, and
generating a new valid path from that point onwards.
Mutations will depend on a threshold, which is between 0 and 1. This
roughly translates to the likihood of a mutation occu... | 99bad7b745b88813c04f333555857147c30288f5 | 3,606,824 |
import re
def address_to_zipcode(text):
"""
Return the departement number from any text which contains any zip code
"""
for line in text.splitlines():
zipcode_match = re.search(r"(?<!TSA)(?<!BP)(?<!B.P.)(?<!CS)(?:[^\d]|^)(?<!TSA)(?<!BP)(?<!B.P.)(?<!CS)(?P<zipcode>\d{2}\s?\d{3})\s*([^\d\s]|$)"... | 250aa46091b74731977cefe4c6d80a4f4361b729 | 3,606,825 |
def crs(cov_array):
"""Calculate cumulative read sum """
vert_array = np.insert(np.ediff1d(cov_array), [0], 0)
vert_sum_array = np.cumsum(np.absolute(vert_array))
if max(vert_sum_array) == 0:
vert_sum_norm_array = ['NA']
else:
vert_sum_norm_array = vert_sum_array / max(vert_sum_array)
return vert_sum_norm_arr... | 8bd46a447a77acbf8bd13d75c91b838845b430bb | 3,606,826 |
def environment(
combined_challenge,
domain,
task,
log_output = None,
environment_kwargs = None):
"""RWRL environment."""
env = rwrl_envs.load(
domain_name=domain,
task_name=task,
log_output=log_output,
environment_kwargs=environment_kwargs,
combined_challenge=combi... | c9ecefec96ef48c3d048f82e6446a3e24ffe7f1f | 3,606,827 |
import re
def re_cap(*regexes):
"""
Capture first of the supplied regex
:param regexes: list or regex strings
:return: captured string | None
"""
def go(string):
for reg in regexes:
matches = re.search(reg, string)
if matches:
return matches.grou... | 8029a2d475c43b0873e676ba4049e970a2077664 | 3,606,828 |
def Enumerate(evidence):
"""Uses dfVFS to enumerate partitions in a disk / image.
Args:
evidence: Evidence object to be scanned.
Raises:
TurbiniaException if source evidence can't be scanned.
Returns:
list[dfVFS.path_spec]: path specs for identified partitions
"""
options = volume_scanner.Vol... | 9152a038757ec20b5c5538e65896337be8d21f19 | 3,606,829 |
def NgramAnalyzer(minsize, maxsize=None):
"""Composes an NgramTokenizer and a LowercaseFilter.
>>> ana = NgramAnalyzer(4)
>>> [token.text for token in ana(u"hi there")]
[u"hi t", u"i th", u" the", u"ther", u"here"]
"""
return NgramTokenizer(minsize, maxsize=maxsize) | LowercaseFilter() | edc3d66d2bf4ba7eb393d90cafa696d42c2249d9 | 3,606,830 |
from sirepo import uri_router
def authorize(simulation_type, app, oauth_type):
"""Redirects to an OAUTH request for the specified oauth_type ('github').
If oauth_type is 'anonymous', the current session is cleared.
"""
oauth_next = '/{}#{}'.format(simulation_type, flask.request.args.get('next') or ''... | 880994adbedd8e75412518a344bd7b8af240733a | 3,606,831 |
def prepare_create_transaction(*,
signers,
recipients=None,
asset=None,
metadata=None):
"""
Prepares a ``"CREATE"`` transaction payload, ready to be
fulfilled.
Args:
signe... | 894c69e4e13438dc50baae718b603fe50a00a812 | 3,606,832 |
def render_to_json(templates, response_kwargs, context, request):
"""
Generate a JSON HttpResponse with rendered template HTML.
"""
html = render_to_string(
templates,
response_kwargs,
RequestContext(request, context)
)
_json = simplejson.dumps({
"html": html
... | 7aae13d13f3588330549450a3c431d086c48ea6e | 3,606,833 |
def SQuAD2(*args, **kwargs):
""" Defines SQuAD2 datasets.
Examples:
>>> train, dev = torchtext.experimental.datasets.raw.SQuAD2()
"""
return _setup_datasets(*(("SQuAD2",) + args), **kwargs) | dcb5ac4815dbb978837ac2b0c9b8fb77d56c24ea | 3,606,834 |
import dateutil
def _DiscardResultsBeforeDate(results, date):
"""Return a list of results that occur after the given date.
Args:
results: Results parsed from a raw JSON file into list of dicts
date: A date of type datetime.datetime
Returns:
List of results whose date_taken value comes after the gi... | 2dbebeece75ff33e53f8c6e0ee24b308338c81e4 | 3,606,835 |
def downloadPage(url, downloadTo, **kw):
"""Request and download it directyl to disk..
Similar to twisted.web.dowloadPage.
Arguments:
url -- A URL str OR an instance of URLPath OR an instance of Request
pathOrStream --
A file path (str) or object (file) to which the respon... | 98a299a7fa5df23e45f8c2c0603a4dfa62c98c59 | 3,606,836 |
def score2act(score):
"""
Convert the Z-score predicted by PADDLE to a fold-activation value.
Only useful as a rough reference for activation in S. cerevisiae, as the
fold-activation will vary between different experimental conditions.
"""
return 1.5031611623938073**score | 044cf53813623e5427e7bda2e69afba47f435af0 | 3,606,839 |
def required(value, context=None):
"""validates that a field exists in the input"""
if value:
return value
if value == 0:
return value
raise ValidationException('This field is required') | af95022bc9960da7678323ecb96120f39ef26b22 | 3,606,841 |
def get_mask_pallete(npimg, dataset='detail'):
"""Get image color pallete for visualizing masks"""
# recovery boundary
if dataset == 'pascal_voc':
npimg[npimg == 21] = 255
# put colormap
out_img = Image.fromarray(npimg.squeeze().astype('uint8'))
if dataset == 'ade20k':
out_img.pu... | 7130945b6a8ba8d1379753e93b1ec9ee9b429ade | 3,606,842 |
def quadratic_max(xs, ys):
"""
Find the maximum from a list, using a quadratic interpolation.
Note: REQUIRES (and `assert`s) that the xs grid is uniform.
"""
delta = xs[1] - xs[0]
assert np.allclose(xs[1:] - xs[:-1], delta), "quadratic_max: not uniform grid!"
ii = np.nanargmax(ys)
if ii ... | 3f9fe5747055e39f94e39f44ec2a6c6bbe06a6e0 | 3,606,843 |
def convert_blackhurst_data_to_gal_per_employee(df_wsec, attr, method):
"""
Load BLS employment data and use to transporm original units to gallons per employee
:param df_wsec: dataframe that includes sector columns
:param attr: attribute data from fba method yaml
:param method: The name of the fba ... | f79503c3ddb597697beac648200359d7d747189d | 3,606,844 |
import urllib
def get_label_like(current_row):
"""Get labels, OBO synonyms (and possibly more) from submitted ontology/IRI pairs"""
global ols_session
anything_useful = []
once = urllib.parse.quote(current_row['iri'], safe='')
twice = urllib.parse.quote(once, safe='')
term_retr_base = 'https:/... | 2e737c089bdf5194988ddef300e6069ee27a9550 | 3,606,845 |
def get_metadata(estimator_name):
"""Get init annotations for estimator.
Parameters
----------
estimator_name : str
Name of estimator
Returns
-------
metadata: dict
"""
annotations = _ALL_ANNOTATIONS[estimator_name]
try:
return {
"parameters": annota... | 9d767f0b55500cc41a8be52b05db7e45544e3d45 | 3,606,846 |
def get_linked_lengths(frames, linker, *args, **kw):
"""Track particles and return the length of each trajectory."""
linked = link(frames, linker, *args, **kw)
return linked.groupby('particle').x.count() | fe0db1aa38db99fbdd9a22c3ce39adc7f7d268ee | 3,606,847 |
def rotate2(degs, header):
"""Return a rotation matrix for counterclockwise rotation by ``deg`` degrees."""
rads = np.radians(degs)
s = np.sin(rads)
c = np.cos(rads)
return np.array([[c*header['CDELT1'], -s*header['CDELT2']],
[s*header['CDELT1'], c*header['C... | ef2cea6c8990a0032eaebcaec528c7c5ad4fa051 | 3,606,848 |
def restore_project(c):
"""
Restore latest version of project files.
"""
file_name = f'{c.config.data.backup_path}/{c.config.project.name}.last.tar.gz'
result = c.run(f'stat {file_name}', hide=True)
if not result.ok:
print(f'{RED}Could not find project backup: {file_name}{COL_END}')
... | 5c838113f5a8977295a4d1dfe348883a68d5d32d | 3,606,851 |
def import_module(path):
"""
import module from string
:param str funcpath: the string of absolute path a module
"""
try:
if "." in path:
modpath, hcls = path.rsplit('.', 1)
mod = __import__(modpath, None, None, [''])
mod = getattr(mod, hcls)
... | 125b846e489572008708052ab8a14d0fbd4f582e | 3,606,852 |
import time
def train(train_loader, model, optimizer, scheduler, epoch, args, device, streams=None, scaler=None, blackbox=None):
"""training function"""
batch_time = metric.AverageMeter('Time', ':6.3f')
data_time = metric.AverageMeter('Data', ':6.3f')
avg_ce_loss = metric.AverageMeter('ce_loss', ':.4e... | 29ba425bfef3af348c0d533b145360a0fc23656a | 3,606,853 |
def generate_verify_email_url(user):
"""
生成邮箱激活链接
:param user: 当前登录用户
:return: token
"""
s = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
data = {'user_id': user.id, 'email': user.email}
token = s.dumps(data)
return settings.EMAIL_VERIFY_URL + '?token=' + tok... | 1c86ea85b32660e85022ce461b9b073d978735aa | 3,606,854 |
def unpooling_3d(voxel_tensor_batch, reuse, name='unpooling_3d'):
"""Unpooling 3D. Only upsamples by a factor of 2 in every spatial dimension.
Args:
voxel_tensor_batch: [batch, x, y, z, channel].
"""
with tf.variable_scope(name, reuse=reuse):
# Use fixed batch size
batch_shape =... | b4acec3f547594770c4fe9884ecfa7cfb34bce24 | 3,606,855 |
def make_grpc_unary_method(channel, service_name, method_descriptor, symbol_database_instance):
# type (Channel, str, MethodDescriptor, Any) -> Callable
"""Make grp callable on the channel.
Args:
channel: grpc channel
service_name: name of service
method_descriptor: method descripto... | 7d3d6b3708185f7f243756804a2030db12fc1daf | 3,606,857 |
def set_crs(gdf, crs):
"""
Set CRS in GeoDataFrame when current projection is not defined.
Parameters
----------
gdf : geopandas.GeoDataFrame
the geodataframe to set the projection
Returns
-------
gdf : geopandas.GeoDataFrame
the ge... | 77fc8f303882116fb450149c61332879fb28f6db | 3,606,860 |
def make_train_graph(target_dist,
model,
batch_size,
eval_batch_size,
lr,
eval_num_samples=1000):
"""Code for the TRS, SNIS, and HIS training loops."""
train_batch = target_dist.sample(batch_size)
eval_batch =... | 2de40d1f7d847a5ad4ec09e1a124a694b4e62df3 | 3,606,861 |
def svn_wc_restore(*args):
"""
svn_wc_restore(svn_wc_context_t * wc_ctx, char const * local_abspath, svn_boolean_t use_commit_times,
apr_pool_t scratch_pool) -> svn_error_t
"""
return _wc.svn_wc_restore(*args) | 5e402322b3930ffb44e278d81d5a8b67ee450239 | 3,606,862 |
from typing import List
from typing import Dict
from typing import Any
def get_enclosed_containers() -> List[Dict[str, Any]]:
"""Return all object definitions that have 'enclosed_areas' whose value is a non-empty list."""
global _ENCLOSED_CONTAINERS
if _ENCLOSED_CONTAINERS is None:
all_defs = get_... | fe6afe40617de4779f218387c85259e75e870954 | 3,606,863 |
def get_format_string_from_puid(puid):
"""Return file format and version info for a PUID or None
:param puid: PUID (str)
:returns: "File format (version)", "File Format", or None.
"""
file_with_puid = File.query.filter_by(puid=puid).first()
if file_with_puid is None:
return None
tr... | a7ace597dd6bb3b137001fb6b88434f0032f7b93 | 3,606,864 |
def dataset_type(dataset):
"""
Parameters
----------
dataset : dataset script object
Returns
-------
str : The type of dataset.
Example
-------
>>> for dataset in reload_scripts():
... if dataset.name=='aquatic-animal-excretion':
... print(dataset_type(datas... | 4a63021ce725c116b0ed23c851da5983df5c79b5 | 3,606,865 |
def orient2d(
point: Point,
projection: Point,
from_vert: Point,
to_vert: Point
) -> float:
"""Calculate the orientation and offset distance of a point from a line
Parameters:
point: point for which we want to determine orientation left or right of a line
projection: point of pr... | da5f92cb7f63901dc7ec5b7b0ffbf67c20d894e6 | 3,606,866 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.