content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def unnormalise_density(c, rho):
"""Reverses any desnity normalisation
As a general rule this should be done using the units read in from the file,
with unit conversion done afterwards"""
return c * rho | 1ffa7b4f5e08a071d5f8e94489d363a085f31930 | 72,900 |
def test_parser():
"""A parser for testing convenience"""
return parser("Testing", "Use this from a test", "") | ec20c957efee80ee7781eb3cf30efa442454fdcf | 72,901 |
def fit_function_latticeparameters(varying_parameters_values_array,
varying_parameters_keys,
Miller_indices,
allparameters,
absolutespotsindices,
... | 12fb928c0cb6d816d8381bfa5c6df5e5073fae5f | 72,902 |
def _set_quality(in_bam):
"""
change all quality to 255
"""
bam = pysam.AlignmentFile(in_bam, "rb")
out_file = utils.append_stem(in_bam, "_normqual")
if file_exists(out_file):
return out_file
with file_transaction(out_file) as tx_out:
with pysam.AlignmentFile(tx_out, "wb", te... | e5cbf239b34e330c65006dba0bf9b352e14da516 | 72,903 |
def gaussian(sigma):
"""
The Fourier transform of a Gaussian
G(w) = 1/(sqrt(2pi) sigma) * exp(- 1/2 (w/sigma)^2 )
is again a Gaussian
g(t) = 1/(2pi) exp(-1/2 sigma^2 * t^2)
Parameters
----------
sigma : float
standard deviation of Gaussian in energy domain
Returns
... | 1f4afeeaa816227a230f619699ba21ff4fd552c2 | 72,904 |
def watch():
"""Watch an example movie, streamed directly to you from hug"""
return 'movie.mp4' | fc72e5cf6570a667f86a9a9e2e764d07090b482c | 72,905 |
def get_transcription_id_base(page_id: int) -> int:
""" Get the current transcription id that should be based off of """
return (
db.session.query(Transcription)
.filter(Transcription.page_id == page_id)
.filter(Transcription.partial == False)
.order_by(Transcription.start_time.d... | 5bbbb1696e1eee599040a0958d8cfe5e236a4457 | 72,906 |
def remove_gps_photo(photo, new_photo=None):
"""Remove GPS from EXIF of a given photo. Returns flag indicating if
original file had GPS EXIF data.
photo: Location of original photo.
new_photo: Location for modified photo. Optional. Default is to overwrite
the original photo.
gps: Flag indic... | 1a82b059db0ec3ae547f2b0fba74bbc8d0239a3d | 72,907 |
def relocate_deps(target_src, target_dst, config):
"""
Make the target relocatable and copy all of its dependencies into the
artifact directory.
"""
if IS_LINUX:
return relocate_deps_linux(target_src, target_dst, config)
if IS_MACOS:
return relocate_deps_macos(target_src, target_dst, config)
raise... | e46ec86a02276b98e080ae9e2dc04e65b17f11f8 | 72,908 |
def read_scene_bbox(cziobject, metadata,
sceneindex=0,
channel=0,
timepoint=0,
zplane=0,
scalefactor=1.0):
"""Read a specific scene from a CZI image file.
: param cziobject: The CziFile reader object from aicspy... | 0b5ae2ca6dfc0a2e66df44f7ce0bb107876a310b | 72,909 |
def ikeep(hcenter, frame, dom):
""" hcenter is a histogram in time
return indices of hcenter that fall outside of the saturation window and calibration errata
"""
iskips = [np.array([False]*len(hcenter))]
if frame.Has('CalibrationErrata') and dom in frame['CalibrationErrata']:
for cerrata i... | d998937fa4118dcb9b6f2e40aeb264198117f579 | 72,910 |
def sparsifyApprox(probs, err_thresh):
""" Sparsify a probability vector. """
# FIXME
# sorted_indices = None
return probs | b28d00221e21cdb10431bab753e71905b36b7204 | 72,911 |
import math
def acosh(x):
"""
Return the hyperbolic arc cosine of x.
There is one branch cut, extending left from 1 along the real axis to -∞, continuous from above.
"""
ret = _SPECIAL_VALUE(x, _acosh_special_values)
if ret is not None:
return ret
if math.fab... | 4ad8ed09e90f369f57bf93303130f97661676c66 | 72,912 |
def get_vlans(netmiko_session, vdc=None) -> list:
"""Get vlans"""
vlan_table = []
iter_vlan = "1"
ports = ['']
if vdc is not None:
vdc_command = f"switchto vdc {vdc}"
get_vdcs = send_command(netmiko_session, vdc_command)
get_vlans = 'show vlan brief'
vlan_ports = None
... | d595a7a6931627e0af964886b7fa5805246920ac | 72,913 |
def get_ip(base_url, session_key):
"""Get the IP address set on the router"""
return get_info(base_url, session_key)['wan_ipaddr'] | e55796ea6c7eeab009a9f9e5bfa4bb216969e9fe | 72,914 |
def seekret(seekret_session, request) -> Context:
"""
Seekret context and functions.
"""
context = Context(session=seekret_session, scope=request.scope)
default_user: Mark = request.node.get_closest_marker('default_user')
if default_user is not None:
context.default_user = default_user... | 651405ce2bcae47296f219d8bfa6248ec145cf2c | 72,915 |
def xy2hadec(x,y,tel_ha,tel_dec) :
"""
Convert tangent plane x,y to HA,Dec given a telescope pointing tel_ha, tel_dec
Args:
x: float or 1D np.array with tangent plane coord.
y: float or 1D np.array with tangent plane coord.
tel_ha: float; telescope pointing Hour Angle in degree... | f8b47c4347537d99ec47c78965529664e9fb9e40 | 72,916 |
def _mean(fiberTree, scalarType, idxes=None):
""" *INTERNAL FUNCTION*
Finds the average of all fibers in bundle at specific sample points
INPUT:
fiberTree - tree containing spatial and quantitative information of
fibers
scalarType - type of quantitative data to find aver... | eb633f8fb5bfa555e305b1bd2f292615967e04a1 | 72,917 |
def make_fun ( fun , args , name ) :
"""Helper function to create the function
"""
assert fun and isinstance ( fun , ROOT.RooAbsReal ), 'make_fun: Invalid type %s' % type ( fun )
num = len ( args )
if 1 == num : return Fun1D ( fun , name = name , *args )
elif 2 == num : return Fun2D... | 21c9fd67687b550c09b1a45cf6fe04a92c8003e4 | 72,918 |
def parse_to_int_or_float(value):
"""
Tries to parse `value` as float or int, if not possible will raise a ValueError
"""
try:
return parse_int_with_commas(value)
except ValueError:
return float(value) | 302975f3f81cee78f10220cd3b7b63758d2a6723 | 72,919 |
import os
def paper_mrc_msra_ner_dataset() -> MRCNERDataset:
"""
数据集生成
:return: msra flat ner dataset
"""
dataset_file_path = "data/dataset/mrc_msra_ner/sample.json"
dataset_file_path = os.path.join(ROOT_PATH, dataset_file_path)
vocab_path = os.path.join(ROOT_PATH,
... | 509b42a835db71826497705bef748712992caf4f | 72,920 |
import os
def fix(request, fix_type, fix_info, fix_function):
"""Apply a fix a direcory"""
arrivals_dir = request.user.uploaderprofile.data_directory
if request.method == 'GET':
# create a form instance and populate it with data from the request:
stream = request.GET["stream"]
rel... | 0e0cf0998a5f3c9d29d4b7bde7ba42ce52ac459d | 72,921 |
import random
def mutate_color(color):
"""
Mutates one coordinate of a color in a HSV cube.
"""
color[random.randrange(0, 3)] = random.random() % 1
return color | 5fdfef8b7c29be367dee85f195458924bb8421aa | 72,922 |
def create_stub_multiplexed_library() -> MultiplexedLibrary:
"""
Creates a `MultiplexedLibrary` stub.
:return: stub a `MultiplexedLibrary` model
"""
multiplexed_library = MultiplexedLibrary()
multiplexed_library.internal_id = INTERNAL_ID
multiplexed_library.name = NAME
return multiplexed... | 264759d125438c1e9075819de84aac786e06aaf3 | 72,923 |
def _bring_problem_in_right_form(cls: CLS):
"""
Brings the CLS problem in the right format so that qpsolvers.solve_ls can solve it.
:param cls: CLS
:return: r, s, g, h, a, b, lb
"""
r = cls.h
s = cls.y
if cls.inequality_constrained:
g = - cls.c
h = - cls.d
else:
... | af09fda59fceffe64bde7ea36ccee0dfb1a30938 | 72,924 |
def singlesummarise(question, docstext, n=2):
"""Return the output of the default single-document summariser
>>> question = "my sentence"
>>> text = ["This is one sentence.",\
"This is another sentence.",\
"This is yet another sentence.",\
"And this is the fin... | 87b732229e38cfe8c203403ca8789f19c1e14c5f | 72,925 |
import pickle
def model_encode(data):
"""Pickle data utilising the patched_model context manager."""
with patched_model():
return pickle.dumps(data) | 4b8b7db1abc9c658c1d3cc0c0808775fa5d6d49a | 72,926 |
import itertools
def tensors_from_data(data_dict, batch_size, axes=None, shuffle=False):
"""Turns a dict of numpy.ndarrays into a dict of minibatch tensors.
Arrays are split into minibatches of `batch_size` along `axes`. If `axes` is None,
then all arrays are split along axis==0. Tensors can iterate sequ... | 2a2ec944268906fda7ed61e7738c11b8d94aa1e6 | 72,927 |
def find_monster(grid, mon):
"""
Given a grid and a list of
indices of monster,
find the number of "#" that
are not part of any monster.
:param grid: An (8 * 12) x (8 * 12)
list of chars.
:param mon: A list of indices of
the monster.
:return: The count of "#" that
are not p... | 90ff7da5800addd0ba2ae469e9c00be822a3cfde | 72,928 |
def _ensure_spacing(coord, spacing, p_norm):
"""Returns a subset of coord where a minimum spacing is guaranteed.
Parameters
----------
coord : ndarray
The coordinates of the considered points.
spacing : float
the maximum allowed spacing between the points.
p_norm : float
... | d13a134a9ad8578650c6740a1e7826cbb9f19102 | 72,929 |
import numpy
def hist2func(x, H, binEdges):
"""
Example:
import numpy
import matplotlib.pylab as p
H = numpy.array([0,2,1])
binEdges = numpy.array([0,5,10,15])
x = numpy.linspace(-5, 20, 50)
y = hist2func(x, H, binEdges)
p.plot(x,y)
p.show()
"""
if type(x) == float o... | ac3e7b7162862aede936205be528b7af05af73f0 | 72,930 |
def test_post_getattr():
"""Test the post_getattr behaviors.
"""
class ModuloInt(Int):
def __init__(self):
super(ModuloInt, self).__init__()
mode = PostGetAttr.MemberMethod_ObjectValue
self.set_post_getattr_mode(mode, 'post_getattr')
def post_getattr(se... | 0c9239a8738393042b48576e7ca83a68cf35870e | 72,931 |
def create_merge_consecutive_day_input_filenames(datestring):
""" Create the list of filenames for merge_consecutive_day_trajectories.py. """
prev_datestring = iso8601_previous_day(datestring)
return [create_matching_ids_filename(PREV_DAY, datestring)] + \
create_match_consecutive_day_input_filename... | 2e708330c9a587b3d6774778d5c914d0a7841c9b | 72,932 |
def raw_commands(layout_in):
"""Return raw command set. (<command(str)>, <index(int)>).
Args:
layout_in(str): Simple layout string.
"""
panes = _generate_panes(layout_in)
return panes.commands | d19056f0a0577e9a69451348cd9d4ab0fc24577b | 72,933 |
def EnsureHeapMetadataHomogeneity(Metadata):
"""Ensures that all of the metadata provded are homoenous on the
size, offset-from-base, and backtrace for all heap interactions.
Returns:
Tuple containing (size,offset,backtrace) for the common
allocation type.
"""
HeapMeta = tuple(M for... | 9236730f2e1ebd2c0f8fafd6f8ca490db22d138a | 72,934 |
def _create_fake_dataset(output_path, seq_length, num_labels, num_examples):
"""Creates a fake dataset."""
writer = tf.io.TFRecordWriter(output_path)
def create_int_feature(values):
f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
return f
for i in range(num_examples):
featu... | 5d1db578b3959c32a70946a2fefd95a2ee2cf305 | 72,935 |
def do_embed(parser, token):
"""{% embed %} template tag. Allows to include a template and optionally override its slots, in a similar fashion
to block tags in extended templates.
Example::
{% embed 'section.html' %}
{% slot title %}<h1>Title</h1>{% endslot %}
{% slot conte... | 557d2aa7fe4d808fae8c7abd6cf7f7ce51df45aa | 72,936 |
def dispatch_samples(sample, scheme, n_agents, fields=None):
""" transform samples from buffer to feed in maddpg learner
specify how to decode sample to per-agent experience
Arguments:
sample: SampleBatch/EpisodeBatch, each is (B,D)
scheme: multi-agent sample scheme
Returns:
... | 4ed79713a3ef4768c9921b17d71ab4510b4aab59 | 72,937 |
def container_with_most_water(heights):
"""
Parameters
----------
heights : list
A list of integers representing heights of containers
Returns
-------
int
area of container with most water
>>> container_with_most_water([1, 8, 6, 2, 5, 4, 8, 3, 7])
49
>>> conta... | d25c602bac1aab4484ca60680bcaa21abbb78dc7 | 72,938 |
def log_loss(actual, predicted):
"""
Computes the log loss.
This function computes the log loss between two lists
of numbers.
Parameters
----------
actual : list of numbers, numpy array
The ground truth value
predicted : same type as actual
The predicted va... | 24a067d0fcb98489acb59b59e5af0f66fb975c8d | 72,939 |
from . import components
def incidence_matrix(network, branch_components=None, busorder=None):
"""
Construct a sparse incidence matrix (directed)
Parameters
----------
branch_components : iterable sublist of `branch_components`
Buses connected by any of the selected branches are adjacent
... | ae5c477e84f7ff1a9d995b5350d21c50723ae8d5 | 72,940 |
def preprocess_data(data):
"""preprocessing the text data, conversion to numerical array format."""
def deal_line(line):
pos, rating = line.split(',')
row, col = pos.split("_")
row = row.replace("r", "")
col = col.replace("c", "")
return int(row), int(col), float(rating)
... | 1a9c8e01e8ca80a2b6ebe162510a902b69170a83 | 72,941 |
from .._tier1 import set
def generate_distance_matrix(coordindate_list1 :Image, coordinate_list2 :Image, distance_matrix_destination :Image = None):
"""Computes the distance between all point coordinates given in two point lists.
Takes two images containing pointlists (dimensionality n * d, n: number of ... | 794f338af8c118f2f92a1da939008d6c6c67b721 | 72,942 |
def getClampState(data_handle):
"""
Return the full clamp state
"""
if not isClampFile(data_handle):
raise Exception('%s not a clamp file.' % data_handle.shortName())
data = data_handle.read(readAllData=False)
info = data._info[-1]
if 'ClampState' in info.keys():
return info[... | 03a3b5818ad1005057d972fd60b2f993ad594130 | 72,943 |
import random
import functools
def compute_background_loss(model, state, params, key, points, noise_std,
alpha=-2, scale=0.001):
"""Compute the background regularization loss."""
metadata = random.choice(key, model.warp_embeds, shape=(points.shape[0], 1)) # for each of the point, choos... | 44746f8eb45f4ed7f0f207b81423d1719a48a6f0 | 72,944 |
from pathlib import Path
from typing import Iterable
def process_boto3_stubs_lite(
session: Session,
output_path: Path,
service_names: Iterable[ServiceName],
generate_setup: bool,
version: str,
) -> Boto3StubsPackage:
"""
Parse and write stubs package `boto3-stubs-lite`.
Arguments:
... | e7301510edb3ae5b28a529a7b868a9398f2ee4eb | 72,945 |
import os
import random
def parse_folder(folder, labels_file,
train_file=None, percent_train=None,
val_file=None, percent_val=None,
test_file=None, percent_test=None,
min_per_category=2,
max_per_category=None,
):
"""
Parses a folder of images into three textfile... | 0c080c470f73c9a131d3dd5f0c25f77b96a4d462 | 72,946 |
import hashlib
def calculate_file_hash(file_path):
"""
Quickly compute a hash (md5) of a file
:param file_path:
:return:
"""
with open(file_path) as file_to_hash:
file_content = file_to_hash.read()
digest = hashlib.md5()
digest.update(file_content)
hash_result = digest.hexd... | 907c458ee4a93b1e2d18c34fa7b74e28134443b5 | 72,947 |
def sec_dev_max(f, a, b):
"""
Calculates the max second derivative within the range [a,b]
"""
n = 999999
i = (b - a) / float(n)
max = abs(sec_dev(f, a))
for counter in range(n):
temp = abs(sec_dev(f, a + (counter + 1) * i))
if temp > max:
max = temp
return max | 23fc1d32452b925b60270cc9f26b8b1f37cece65 | 72,948 |
def is_ok_title(title: str) -> bool:
"""
タイトルにNGワードを含んでいないかを確認する
:param str title: イベントのタイトル
:return: True: 含んでいない(OK)、False: 含んでいる(NG)
"""
for word in NG_WORDS:
if word in title:
return False
return True | 1ae4e5bd4a205052d797ac7c242cbfe05b69bfcb | 72,949 |
import re
def trim_arn_to_name(arn: str) -> str:
"""
Extract just the name of function from full ARN. Supports versions, aliases or raw name (without ARN).
More information about ARN Format:
https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-arns
"""
# Special ... | f0f02b0e965d245ef61942c7bfd5d7e91bcc5fff | 72,950 |
def param(nnet, Mb=True):
"""
Return number parameters(not bytes) in nnet
"""
neles = sum([param.nelement() for param in nnet.parameters()])
return neles / 10**6 if Mb else neles | 1121b19ffe63176d1f7f08345bc8295aa56a9a4c | 72,951 |
def paga(
adata,
solid_edges='confidence',
dashed_edges=None,
layout=None,
root=0,
groups=None,
color=None,
threshold=None,
threshold_solid=None,
threshold_dashed=None,
fontsize=None,
node_size_scale=1,
node_size_pow... | 4d4bb8ff24ab9a1e43605b54a4d94a193f009ec7 | 72,952 |
import mimetypes
import cgi
def _get_content_type(conn) -> str:
"""Pull out mime type from a connection.
Prefer explicit header if available, otherwise guess from url.
"""
content_type = mimetypes.guess_type(conn.url)[0] or ""
if hasattr(conn, "getheaders"):
content_type = dict(conn.gethea... | 22a093210fcebd5b080106b7484d6ff3b8dfee3a | 72,953 |
from typing import Any
from typing import Optional
def max_elevation_selector(_: Any, pass_: PredictedPass, left_range: Optional[DateTimeRange], right_range: Optional[DateTimeRange]) -> Optional[DateTimeRange]:
"""
This selection strategy selects the passes that have highest elevation during TCA.
"""
... | c33437faf4554093f5264a6815f22e1dfd44699b | 72,954 |
def basic_req(url: str, types: int, proxies=None, data=None, header=None, need_cookie: bool = False):
"""
requests
@types XY: X=0.->get; =1.->post;
Y=0.->html; =1.->json; =2.->basic; =3.->text;
"""
req_set(url)
result = None
if not types:
result = get_html(url, prox... | d1a8b6b8cae77042c9465c6db63451483cfc42d2 | 72,955 |
def get_disk(compute, project, zone, name):
"""Get info of disk in GCE
:param compute: GCE compute resource object using googleapiclient.discovery
:param project: string, GCE Project Id
:param zone: string, GCE Name of zone
:param name: string, GCE disk name
:return: GCE disk information
:r... | b139f0cbec91b4903c791fff557250e6762442aa | 72,956 |
import datetime as dt
import calendar
def _parse_date(row):
"""parse the date of a single row into datetime object."""
day_ix = 4; mon_ix = 5; year_ix = 6;
date = dt.date(int(row[year_ix]),
list(calendar.month_abbr).index(row[mon_ix]),
int(row[day_ix]))
del row[... | 51b3c86d98f2c7686b34fbae3dd1306e0f00f817 | 72,957 |
def iris_classifier(verbose=False):
"""Basic Decision Tree Classifier for Iris problem.
Based on: http://scikit-learn.org/stable/modules/tree.html
"""
# Load dataset:
iris = load_iris()
# Build and train classifier:
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.tar... | d6b015f0e0512863043ee79ed15623db1b7fe5cd | 72,958 |
def parse_dft_forces(outfile: str):
"""
Get forces from a pwscf file in eV/A
:param outfile: str, Path to pwscf output file
:return: list[nparray] , List of forces acting on atoms
"""
forces = []
total_energy = np.nan
with open(outfile, "r") as outf:
for line in outf:
... | c66d391b2b51fea59f862e8de9b309e7f7e13607 | 72,959 |
from mws.mws import MWSError
def clean_params_dict(params):
"""Clean multiple param values in a dict, returning a new dict
containing the original keys and cleaned values.
"""
cleaned_params = dict()
for key, val in params.items():
try:
cleaned_params[key] = clean_value(val)
... | e9759efa3ddf7d0d4e5ab3d9fed9846689e356db | 72,960 |
def pd_dt_concat(frames, axis=0):
"""
Concatenate sequence of datatable Frames or pandas DataFrames `frames` along `axis` (0 means rows, 1 means columns).
"""
if USE_DT:
if axis == 0:
return dt.rbind(*frames)
elif axis == 1:
return dt.cbind(*frames)
else:... | 54ea2b6bf442285c84068d9d79a859a4ed4b923f | 72,961 |
def _DetailedHelp(version):
"""Construct help text based on the command release track."""
detailed_help = {
'brief': 'SSH into a virtual machine instance',
'DESCRIPTION': """\
*{command}* is a thin wrapper around the *ssh(1)* command that
takes care of authentication and the translation of the
instance ... | 08b0046cf279e6577f27cb45869a9067adecbfc3 | 72,962 |
def shiny_gold_in(bag: str, rules: dict) -> bool:
"""Recursively check for shiny gold bags."""
if "shiny gold" in rules[bag].keys():
return True
elif not rules[bag]: # bag holds no others
return False
else:
for inner in rules[bag]:
if shiny_gold_in(inner, rules):
... | 1859f499b72a938a58a78af5ca1a78e9f7221731 | 72,963 |
def gen_featweight_worker(tup):
"""
Function to be parallelized by multiprocessing / joblib / whatever.
Must take in one argument to be used by multiprocessing.map_async
Args:
tup (aid, tuple(kpts(ndarray), probchip_fpath )): keypoints and
probability chip file path aid, kpts, probc... | 3722032f2ef21f259d5b73679567e467691726c2 | 72,964 |
def get_position_type(salary_plan):
"""
Given a salary plan code, map to one of the VIVO position types
"""
position_dict = {
'CPFI': 'postdoc',
'CTSY': 'courtesy-faculty',
'FA09': 'faculty',
'FA9M': 'clinical-faculty',
'FA10': 'faculty',
'FA12': 'faculty'... | eaaa64bfe35d27476eb9218d6401e0565126392d | 72,965 |
def asim_jac_edges(graph_premise, graph_hypothesis):
"""
Asymmetric Jaccard similarity between the edges of the definition graphs
:param graph_premise: the definition graph of the premise
:param graph_hypothesis: the definition graph of the hypothesis
:return: the ratio of overlapping edges per the ... | 41102b8cf7fa7f6b06595ded242997d6cef0627f | 72,966 |
import ast
import logging
def _generate_trees(filename, with_filenames=False, with_file_content=False):
"""
Generated trees.
:param filename: filename
:param with_filenames: boolean
:param with_file_content: boolean
:return: list of ast object
"""
trees = []
with open(filename, 'r... | 258ccfabebb4de21d971939dfa3369a4658bace4 | 72,967 |
def find_datasets(detector=None, type=None, host=api.DEFAULT_URL):
"""Find datasets available on the given GW open science host
Parameters
----------
detector : `str`, optional
prefix of GW detector
type : `str`, optional
type of datasets to restrict, one of ``'run'`` or ``'event'`... | a828797108bcf92d9bf1993bd57ab8a46a03da59 | 72,968 |
import os
def setup(i):
"""
Input: {
cfg - meta of this soft entry
self_cfg - meta of module soft
ck_kernel - import CK kernel module (to reuse functions)
host_os_uoa - host OS UOA
host_os_uid - host ... | 67f9fd43f5f0ae98adf936270615f66068f30e44 | 72,969 |
from typing import Iterable
from datetime import datetime
from typing import List
def _calculate_displayable_predictions(
fitted_formulas: Iterable[FittedFormula],
max_peak_distance: datetime.timedelta,
max_peak_variability: datetime.timedelta,
now: datetime.datetime,
) -> List[FittedFormula]:
"""... | f42cd4385c33ec68a83e8d0a5994acff821c15a6 | 72,970 |
import re
def cleanup(string):
"""
Cleans up pathway long-names for presentation.
:param string:
:return:
"""
string = re.sub("|", "", string) # vertical bar
string = re.sub("<[^<]+?>", '', string) # HTML tags
string = re.sub("\'", "", string) # remove quotes
return string | 02a66153cf92815f53acfb61edf58df9dd9a8752 | 72,971 |
import builtins
def is_builtin(name: str) -> bool:
"""return true if <name> could be considered as a builtin defined by python
"""
return name in builtins or name in SPECIAL_BUILTINS | 7dd7d770f728e8a57ac310ef257a3469307a341d | 72,972 |
def perkalian(matrix_a: list[list], matrix_b: list[list]) -> list[list]:
"""
>>> perkalian([[1,2],[3,4]],[[5,5],[7,5]])
[[19, 15], [43, 35]]
>>> perkalian([[1,2.5],[3,4.5]],[[5,5],[7,5]])
[[22.5, 17.5], [46.5, 37.5]]
>>> perkalian([[1, 2, 3]], [[2], [3], [4]])
[[20]]
"""
if _check_no... | 4b37e9c2a92e3c9f5a35c74169449f74627d95c8 | 72,973 |
def parser_config(p):
"""Graphical user interface runner."""
loader.parser_config(p)
p.add_argument('--iterations',
default=1,
type=int,
help='The number of iterations. 0=infinite')
return on_cmd | 8ea0c4e94320ac115d82ff0c32c1d04d381d57f9 | 72,974 |
def loads_state(string):
"""Loads the state from a string object. This does not import any
modules."""
return StateUnpickler(BytesIO(string)).load() | 24c330b9baecd3377a07648d8653a6d2da3a0b03 | 72,975 |
def construct_affine_vanishing_polynomial_Moore(field: Field, aff: AffineSpace) -> Poly:
"""Constructs a polynomial which vanishes over a given affine space."""
# pick a basis a_1, ..., a_d for the space
b = aff.basis
#construct Moore matrix with d+1 colums, The Moore matrix has successive powers of the Frobeni... | bdc8e9041432ed71cbfdc92fc4350b6089a591d6 | 72,976 |
def compose_postprocessing(prng, queries, epsilon, alg, **kwargs):
"""
The composed algorithm with postprocessing actually tested by StatP.
"""
algorithm = alg.algorithm
postprocessing = alg.postprocessing
new_kwargs = kwargs.copy()
del new_kwargs['_d1']
b = algorithm(prng, queries, epsi... | 1b132231c561463edfb37913ca0fe97ad7e13ee7 | 72,977 |
from typing import OrderedDict
def group_by(self, key, key_name=None, key_type=None):
"""
Create a :class:`.TableSet` with a table for each unique key.
Note that group names will always be coerced to a string, regardless of the
format of the input column.
:param key:
Either the name of a... | 104668b798dab4e989d377224d9fdbd4d9c6447e | 72,978 |
import math
def i4_sobol(dim_num, seed):
"""Generates a new quasirandom Sobol vector with each call."""
# Parameters:
#
# Input, integer DIM_NUM, the number of spatial dimensions.
# DIM_NUM must satisfy 1 <= DIM_NUM <= 40.
#
# Input/output, integer SEED, the "seed" for the sequence.... | c3c792b0537c28e95efbaeaadec6689d50765e46 | 72,979 |
def compute_cost(AL, Y):
"""
Implement the cost function defined by equation (7).
Arguments:
AL -- probability vector corresponding to your label predictions, shape (1, number of examples)
Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples)
... | 5d85f71a1c904009f73ef0a8b5cf3f9aa4c6302b | 72,980 |
import os
def validated_key_file(key_file):
"""This method would validate a given key file and raise a exception if the file format
is incorrect or not found.
Args:
key_file (str): Key file name
public_key (bool): Denote if the key file is public key or not.
Returns:
key (RSA K... | 11a788483f31fee952b5206cdf349bc99e05b17f | 72,981 |
import time
def eof(scheme, tests=10000, prob=None):
"""
:param scheme: Input scheme.
:param tests: Number of tests.
:param prob: Probability of error in single element. If None, prob will be set on 1 / scheme.elements().
:return: Probability of scheme failure.
"""
if prob is None:
... | 313a9bd2616199065ece9bfcf7ab192fc6863b26 | 72,982 |
def testcmd(dbg, verbose, pydoc, cmd, regex, error, return_code, negate, stdin, comment, timer, backslash, min):
"""\b
tcmd - test a commands output against a regular expression
\b
Desc: tcmd [Options] cmd regEx
====================================================================
cmd ......... | 4f6dac5ba9681c78259ec311e47ce3a77bb1c782 | 72,983 |
def str2ms(s):
"""
Convert the time strings from an SRT file to milliseconds.
Arguments:
s: A time value in the format HH:MM:SS,mmm where H, M, S and m are
digits.
Returns:
The time string converted to an integer value in milliseconds.
"""
s = s.strip()
time, ms ... | 552f9ffbd557cc0729c035901dc1a1a1bfae66d8 | 72,984 |
def _preprocess_keras_inputs(context_keras_inputs, example_keras_inputs,
tf_transform_output, hparams):
"""Preprocesses the inputs, including vocab lookup and embedding."""
lookup_layer = tf.keras.layers.experimental.preprocessing.StringLookup(
max_tokens=(
tf_transform_... | 14f935984c20fea11f9750a349ee4b5fe9e9df99 | 72,985 |
import warnings
def nan_circmean(samples, high=2.0*np.pi, low=0.0, axis=None):
"""NaN insensitive version of scipy's circular mean routine
Parameters
-----------
samples : array_like
Input array
high: float or int
Upper boundary for circular standard deviation range (default=2 pi)... | 1634d72d3b0a1447aafb8d2f00453c8b8af7c25d | 72,986 |
from typing import Dict
from typing import List
from datetime import datetime
async def compose_upcoming(start_date: str, end_date: str) -> str:
"""
Get the list of episodes between start_date and end_date and format them as a list, grouped by day, highlighting current day and file-status of episodes
:par... | 70e82c17e89252758a5f921c170ee16e71e413fa | 72,987 |
def getEscalation(E, arg=None) :
"""Return escalation of event's primary alert."""
if isinstance(E, dict) : E = Event.objects.get(pk=E['id'])
A = E.get_primary_alert()
if A is None : return None
R = A.reference
if R : return R.escalation_contact
else : return None | 9d04a92440eeb0a45ec900f3b42dd3bad34e6620 | 72,988 |
def _vector_quadratic_form(matrix, vector):
"""Computes a quadratic form along the last dimension.
Equivalent to v.T @ M @ v.
Parameters
----------
matrix : (..., N, N) ndarray
vector : (..., N) ndarray
Returns
-------
quadratic_form : (...) ndarray
"""
# TODO: take advant... | 9641acbe5aa86afa9e649375c0aff53d5e652f24 | 72,989 |
import typing
import ctypes
import os
def mklog(testname: str, flags: int = 0) -> typing.BinaryIO:
"""
Create and open a log file for a test, as implemented by ptef_mklog(3).
Instead of returning an open file descriptor number, like the C function
would, this interface transforms it into a python Fil... | c0ec43b23e16c2e7b3a2813af58dd916483e6a22 | 72,990 |
from .Interactive import Interactive as interactive
def interactive():
"""
An application shell based on {script} that enters interactive mode after the application
is finished running
"""
# grab the component class record
# and return it
return interactive | cc00b4ced10b43268de6cc7d580a368ff2b50030 | 72,991 |
def pipeline_function(fn):
"""Create a pipeline step from a function.
The provided function must receive `self` as its first argument, and
then the pipeline fields it needs (the variable names are inspected
by the pipeline to determine what values to give this step).
"""
class PipelineStepFunct... | 9c33e46aac4cb799d9ab4c3ddab76f3ec96c4201 | 72,992 |
import warnings
def peth(sts, w, t_start=None, t_stop=None, output='counts', clip=False):
"""
Peri-Event Time Histogram (PETH) of a list of spike trains.
Parameters
----------
sts : list of neo.core.SpikeTrain objects
Spiketrains with a common time axis (same t_start and t_stop)
w : Q... | 3d8e95b599fdfdb06068b3f37016e21fff111dc8 | 72,993 |
from .automate_install import find_module_install
import sys
def pywin32_set():
"""
list of modules to add to python to get python with pywin32
"""
names = ["pywin32" if sys.platform.startswith("win") else None,
"pywin32-ctypes" if sys.platform.startswith("win") else None,
"w... | f86ded35935f5208a90936db883aed9a4b6f8dec | 72,994 |
def create_corresponds_to_df(leads_to_df):
"""
Creates the dataframe for the corresponds_to relationship and the nodes for the intents table.
Eliminates duplicate nodes from the leads_to table
and reassigns new IIDs to these nodes. Labels nodes with their node type {root, internal, terminal}.
Also a... | 204dfb9d581e5f0ac2de94bec59d0ba492b4d1a1 | 72,995 |
def get_threecommas_account(accountid):
"""Get account details."""
error, data = api.request(
entity="accounts",
action="",
additional_headers={"Forced-Mode": "real"},
)
if data != {}:
for account in data:
if account["id"] == accountid:
market... | 3d48a24e09cfe81f09e61657452fdb6076108b27 | 72,996 |
import collections
def find_apache_memory_usage(exe_name='apache2'):
"""
Find the memory usage of Apache workers.
:param exe_name: The base name of the Apache executable (a string).
:returns: A tuple of two values:
1. A :class:`StatsList` of integers with the resident set size
... | 6b239650452e465ee6cf5033a953e64f085aed10 | 72,997 |
def modify_error(lc, error_floor=0.):
"""Add an error floor of `error_floor` times the maximum flux of the band
to each observation
"""
data = sncosmo.photdata.photometric_data(lc).normalized(zp=25., zpsys='ab')
new_lc = {'time': data.time,
'band': data.band,
'flux': data... | ca6291ba94819cd295d4d8a4f98eb19b213916dc | 72,998 |
def __get_delta_jg(spectrum, sig_matrix):
"""
Initialize the probability matrix of each mutation in the spectrum originating from the given signature.
:param spectrum: Original spectrum to decompose. (numpy.array)
:param sig_matrix: The matrix containing the weights of each mutational type in each ref... | 23327ec7b47404d7531bb68f473439969eece50f | 72,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.