content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def average_filter(values, n=3):
"""
Calculate the sliding window average for the give time series.
Mathematically, res[i] = sum_{j=i-t+1}^{i} values[j] / t, where t = min(n, i+1)
:param values: list.
a list of float numbers
:param n: int, default 3.
window size.
:return res: lis... | 50616baf5255242a0b19b345743ed088745730d3 | 3,630,000 |
def _get_int_val(val, parser):
"""Get a possibly `None` single element list as an `int` by using
the given parser on the element of the list.
"""
if val is None:
return 0
return parser.parse(val[0]) | d2e029657b3424027e83ee8e1e2be76e3abf8fda | 3,630,001 |
def read_csv_folder_into_tidy_df(csv_glob, drop_columns=[' '], sample_id_categories=None, regex_exp="[a-z]\dg\d\d?"):
"""
Input
-----
Takes glob (str) to csv folder as input. Optional sample_id_categories (e.g. list).
Function
--------
Combines into tidy dataframe.
Returns
-------
... | 824a2f5b0605c0472ded58e3dd1d37099237e261 | 3,630,002 |
def read_gps(gps_filename):
"""
read gps data and output arrays of coordinates, one with speeds,
one with altitudes
:param gps_filename: the gps filename
:return: 2 lists of points, one containing speed, the other altitude
"""
speed_data = [] # list for storing gps coordinates with speed
... | 83129a91c62db1e9ac272b3d84170c76366d7506 | 3,630,003 |
def gram_schmidt(vs, normalised=True):
"""Gram-Schmidt Orthonormalisation / Orthogonisation.
Given a set of vectors, returns an orthogonal set of vectors
spanning the same subspace.
Set `normalised` to False to return a non-normalised set of vectors."""
us = []
for v in np.array(vs):
u =... | 9bd67f9a412166dd0be15724677cc71ce94f4307 | 3,630,004 |
def gcd(a, b):
"""Compute greatest common divisor of a and b.
This function is used in some of the functions in PyComb module.
"""
r = a % b
while r != 0:
a = b
b = r
r = a % b
return b | 10f09e979b525dffe480ca870726459ad0420c0d | 3,630,005 |
import math
def circle_line_intersect(circle, a, b):
"""a and b are endpoints"""
assert isinstance(a, Point) and isinstance(b, Point)
c, r = circle
ab = b - a
p = a + ab * (c - a).dot(ab) / ab.dist2()
s = Point.cross(b-a, c-a)
h2 = r*r - s * s / ab.dist2()
if h2 < 0:
return ()
... | 09a9fc06aac9bed7fbf9abc8167d1a96d9d57816 | 3,630,006 |
import json
def rekognition_json_to_df(path, filter_poseNAs=False):
"""Convert AWS Rekognition output json into Pandas DataFrame.
Works for json responses written by AWS Rekognition GetFaceSearch function
(or as run in VidFaceSearch.py)
Arguments:
path -- (string) path/file
filter_pos... | a8a608b3059862602ff251446c786ab014cfa109 | 3,630,007 |
def horizontal_flip(img, boxes, labels):
""" Function to horizontally flip the image
The gt boxes will be need to be modified accordingly
Args:
img: the original PIL Image
boxes: gt boxes tensor (num_boxes, 4)
labels: gt labels tensor (num_boxes,)
Returns:
img: the ... | 11e789ad1f3f459a2a4cd5ad586560d15ff8b7ce | 3,630,008 |
def is_micropython_usb_device(port):
"""Checks a USB device to see if it looks like a MicroPython device.
"""
if type(port).__name__ == 'Device':
# Assume its a pyudev.device.Device
if ('ID_BUS' not in port or port['ID_BUS'] != 'usb' or
'SUBSYSTEM' not in port or port['SUBSYSTEM'... | 4b7e00abab0c927b982a5f326d4cb27f307a1eae | 3,630,009 |
def gauss_paramters():
"""
Generate a random set of Gaussian parameters.
Parameters
----------
None
Returns
-------
comps: int
Number of components
amp: float
Amplitude of the core component
x: array
x positions of components
y: array
y posit... | a921426f6b56303ff0f74b3a0e9c8111e390121c | 3,630,010 |
def ignore_previously_commented(reviews, username=None, email=None):
"""Ignore reviews where I'm the last commenter."""
filtered_reviews = []
for review in reviews:
if _name(review['comments'][-1]['reviewer']) not in (username, email):
filtered_reviews.append(review)
return filtered_... | dfce6f8553326799c5894501368cc93d881ef048 | 3,630,011 |
def get_n_p(A_A, n_p_in='指定しない'):
"""付録 C 仮想居住人数
Args:
A_A(float): 床面積
n_p_in(str): 居住人数の入力(「1人」「2人」「3人」「4人以上」「指定しない」)
Returns:
float: 仮想居住人数
"""
if n_p_in is not None and n_p_in != '指定しない':
return {
'1人': 1.0,
'2人': 2.0,
'3人': 3.0,
'4人以上':... | db257abdb76ee35f16b07e5baccec82211737971 | 3,630,012 |
def parse_ma_file(seq_obj, in_file):
"""
read seqs.ma file and create dict with
sequence object
"""
name = ""
index = 1
total = defaultdict(int)
ratio = list()
with open(in_file) as handle_in:
line = handle_in.readline().strip()
cols = line.split("\t")
samples... | ba17eba1a26cd913423fe685f10f1375bbbf04e1 | 3,630,013 |
def make_mmvt_boundary_definitions(cv, milestone):
"""
Take a Collective_variable object and a particular milestone and
return an OpenMM Force() object that the plugin can use to monitor
crossings.
Parameters
----------
cv : Collective_variable()
A Collective_variable object whi... | 45baaaa70ea24cb564c529cd885597415561a25d | 3,630,014 |
def mask(inputs, queries=None, keys=None, type=None):
"""Masks paddings on keys or queries to inputs
inputs: 3d tensor. (N, T_q, T_k)
queries: 3d tensor. (N, T_q, d)
keys: 3d tensor. (N, T_k, d)
e.g.,
>> queries = tf.constant([[[1.],
[2.],
[0.]]],... | a4a9953cbab03bde821be0079339ca35705f0423 | 3,630,015 |
def is_leaf_module(module):
"""Utility function to determine if the given module is a leaf module - that is, does not have children modules
:return:
True if the module is a leaf, False otherwise
"""
module_list = list(module.modules())
return bool(len(module_list) == 1) | f34cbd4e961a467117a980ab0b7829f4a8245d2f | 3,630,016 |
import os
def get_dir_url(user_path):
"""
Gets the URL for a directory
"""
return os.path.join(DIR_URL_ROOT, user_path.lstrip('/')) | a31c84112fca63307d9f40d4baae38880cc26768 | 3,630,017 |
import macfs, MACFS
def _gettempdir_inner():
"""Function to calculate the directory to use."""
global tempdir
if tempdir is not None:
return tempdir
try:
pwd = os.getcwd()
except (AttributeError, os.error):
pwd = os.curdir
attempdirs = ['/tmp', '/var/tmp', '/usr/tmp', p... | 89f9d1f68b892552f6e0f4759959b6d0b2d4423e | 3,630,018 |
def edit_subgroup_purchases(request, delivery, subgroup):
"""Allows to change the purchases of user's subgroup. Subgroup staff only."""
delivery = get_delivery(delivery)
user = request.user
subgroup = get_subgroup(subgroup)
if user not in subgroup.staff.all() and user not in delivery.network.staff.... | 799e068aad1eef95cbccb69f5a30ee78b2c526f8 | 3,630,019 |
def get_biggest_pv_to_exchange_ratio(dataset):
"""Return the largest ration of production volume to exchange amount.
Considers only reference product exchanges with the ``allocatable product`` classification.
In theory, this ratio should always be the same in a multioutput dataset. However, this is quite ... | dc52622bc464372801deeab011a54ed1a862f659 | 3,630,020 |
def sequence_processing_pipeline(qclient, job_id, parameters, out_dir):
"""Sequence Processing Pipeline command
Parameters
----------
qclient : tgp.qiita_client.QiitaClient
The Qiita server client
job_id : str
The job id
parameters : dict
The parameter values for this jo... | aa95360945183293a6f80adcff9ec8726c217219 | 3,630,021 |
def Reorder(x, params, output=None, **kwargs):
"""Reorder a tuple into another tuple.
For example, we can re-order (x, y) into (y, x) or even (y, (x, y), y).
The output argument specifies how to re-order, using integers that refer
to indices in the input tuple. For example, if
input = (x, y, z)
then
... | 42dc6bbf9d0a40af0f86d1fa1ed1afb7fc2ee402 | 3,630,022 |
def _is_fix_comment(line, isstrict):
""" Check if line is a comment line in fixed format Fortran source.
References
----------
:f2008:`3.3.3`
"""
if line:
if line[0] in '*cC!':
return True
if not isstrict:
i = line.find('!')
if i!=-1:
... | 8ac7f74f2b4e57b9fb65183a46ed3dbfc0f7ef79 | 3,630,023 |
def parseConfigFile(configFilePath):
"""
:param configFilePath:
:return: a hash map of the parameters defined in the given file.
Each entry is organized as <parameter name, parameter value>
"""
# parse valid lines
lines = []
with open(configFilePath) as f:
for line in f:
... | aee6a1da052f4c2ef907bf41b2cfaa4b93612a5e | 3,630,024 |
def powerset(iterable):
"""
powerset([1,2,3]) --> [(), (1,), (2,), (3,), (1,2), (1,3), (2,3), (1,2,3)]
Args:
iterable : iterable (e.g. list, tuple,...) - set to generate possible subsets of
Returns:
list - list of possible subsets
"""
xs = list(iterable)
# note we return an... | 31f986c10641ee5c97275f67cd9ee210c27f752a | 3,630,025 |
def request_artifact_published(etos, artifact_id):
"""Request an artifact published event from graphql.
:param etos: ETOS library instance.
:type etos: :obj:`etos_lib.etos.Etos`
:param artifact_id: ID of artifact created the artifact published links to.
:type artifact_id: str
:return: Response ... | 300f681a2993320932eaa1f16e2ff6a2ae0b33cb | 3,630,026 |
import requests
from datetime import datetime
def get_stats(selected_sensors=None):
""" return a dictionary of { sensorname: {stats} }
NOTE: runs immediately not - used when we _need_ a result
"""
Config.logger.debug("Get Stats: {}".format(selected_sensors))
if is_str(selected_sensors):
... | 06a92a2d417632cd7b638933ccc1f0d89fb1edca | 3,630,027 |
from scipy.signal import find_peaks
def count_abs_peak(arr1d, threshold):
"""
calculates the number of scenes which are underflooded depending on the peak count function which
calculates how often the signal drops beneath a certain threshold
----------
arr1d: numpy.array
... | 4af85024aa562087eee51d5848a06d4eca2323de | 3,630,028 |
from typing import List
def torch_to_numpy(data: Dataset) -> List[np.ndarray]:
"""Convert data from torch dataset to list of numpy arrays [input, target]."""
# Create empty numpy arrays.
images_shape = (len(data), *data[0][0].shape)
images = np.zeros(images_shape)
labels = np.zeros(len(data))
... | 148c3ca20ec127d70ccb95d1f98b814a65a4446a | 3,630,029 |
def planck_taper(tlist, t1, t2):
"""tlist: array of times
t1. for t<=t1 then return 0
t2. for t>=t2 then return 1
else return 1./(np.exp((t2-t1)/(t-t1)+(t2-t1)/(t-t2))+1)"""
tout = []
for t in tlist:
if t<=t1:
tout.append(0.)
elif t>=t2:
tout.append(1.)
... | 75a899df53209b0fd161ad274b7622a8e819c188 | 3,630,030 |
def has_annotations(doc):
""" Check if document has any mutation mention saved. """
for part in doc.values():
if len(part['annotations']) > 0:
return True
return False | 6b57893bc35af45950ec2eeb5008b663028d48bf | 3,630,031 |
def xmon_to_arc(xmon: XmonDevice) -> Architecture:
"""Generates a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Architecture` object for a Cirq :py:class:`XmonDevice` .
:param xmon: The device to convert
:return: The corresponding :math:`\\mathrm{t|ket}\\rangle` :py:class:`Architecture`
"""
node... | fec0bf1a9e4f343a4f06f1bf1965e9d4ab6ddfa3 | 3,630,032 |
def LoadAcqSA():
"""Acquisition Loading per Sum Assured"""
param1 = SpecLookup("LoadAcqSAParam1", Product())
param2 = SpecLookup("LoadAcqSAParam2", Product())
return param1 + param2 * min(PolicyTerm / 10, 1) | a038b4e5b22cba0755a4d7ad3ab73ccdd046d283 | 3,630,033 |
def DEFAULT_APPLICANT_SCRUBBER(raw):
"""Remove all personal data."""
return {k: v for k, v in raw.items() if k in ("id", "href", "created_at")} | 16fa853551cd03bcf1124639e23b0c72ec9db75d | 3,630,034 |
import io
def _has_fileno(f):
# type: (Any) -> bool
""" test that a file-like object is really a filehandle
Only filehandles can be given to apt_pkg.TagFile.
"""
try:
f.fileno()
return True
except (AttributeError, io.UnsupportedOperation):
return False | 07e7ffb43886775125d314196c5b0acc20d090a6 | 3,630,035 |
import binascii
def _sign_rsa(hash_algorithm_name: str,
sig_base_str: str,
rsa_private_key: str):
"""
Calculate the signature for an RSA-based signature method.
The ``alg`` is used to calculate the digest over the signature base string.
For the "RSA_SHA1" signature method,... | 22c0cdd1168d3e20c9ec564b1636ce6bd8ea33d5 | 3,630,036 |
def partition(my_list: list, part: int) -> list:
""" Function which performs Partition """
begin = 0
end = len(my_list) - 1
while begin < end:
check_lower = my_list[begin] < part
check_higher = my_list[end] >= part
if not check_lower and not check_higher:
# Swap
... | 754a039eede5e143400b0fd58b622d57e083a671 | 3,630,037 |
import numpy
import logging
import multiprocessing
def GenerateHoverDatabase():
"""Generates a hover aerodynamics database in the DVL format.
A hover aerodynamic database models all the aerodynamic surfaces as
independent airfoils and accounts for the effect of the propwash on
these surfaces. The database i... | 60ad7d806092875a7756cc6f0f8584588fc89b03 | 3,630,038 |
def silhouette_k(data, n_clusters):
"""Generates a silhouette plot for n_clusters
"""
fig, ax1 = plt.subplots(1)
ax1.set_xlim([-.1, 1])
ax1.set_ylim([0, data.shape[0] + (n_clusters + 1) * 10])
clusterer = KMeans(n_clusters=n_clusters)
cluster_labels = clusterer.fit_predict(data)
silhouet... | 11667bf2f7db63425cabbbea1111c8b23a85bec6 | 3,630,039 |
from typing import Tuple
import torch
def _get_value(point: Tuple[int, int, int], volume_data: torch.Tensor) -> float:
"""
Gets the value at a given coordinate point in the scalar field.
Args:
point: data of shape (3) corresponding to an xyz coordinate.
volume_data: a Tensor of size (D, H... | 7353d43b4d1cc4375a38c3cf616a083690d71ab8 | 3,630,040 |
import hashlib
from io import StringIO
from datetime import datetime
def generate(request, name):
"""
Generate initialcons for a given name as a .png.
Accepts custom size and font as query parameters.
"""
if name == '':
name = '?'
name = name.encode('utf-8').upper()
# Custom size
... | 9ab9b5d85ef4d9740e04ebd77c7712a6b7668f85 | 3,630,041 |
from typing import List
from typing import Dict
from typing import Any
import time
import yaml
import copy
import ray
import re
from typing import Counter
def run_learning_tests_from_yaml(
yaml_files: List[str],
*,
max_num_repeats: int = 2,
smoke_test: bool = False,
) -> Dict[str, Any]... | 71f418e85f1466fe3294b80f20bdc8405f45ed06 | 3,630,042 |
def make_interpolant(a, b, func, order, error, basis="chebyshev",
adapt_type="Remez", dtype='64', accurate=True, optimizations=[]):
"""
Takes an interval from a to b, a function, an interpolant order, and a
maximum allowed error and returns an Approximator class representing
a mono... | 3370da9128bdfe9c6663b327482d074353bb5b5b | 3,630,043 |
def handle_UnknownLanguageError(exc, *args):
"""Handles error raised when an unknown language is requested
"""
_ = gettext_lang.lang
lang = exc.args[0]
all_langs = exc.args[1]
message = _(
" AvantPy exception: UnknownLanguageError\n\n"
" The following unknown language was ... | 9ca38b740d6dc5b218e4b9f0aedf196946fe961f | 3,630,044 |
import requests
def get_title(bot, trigger):
""" Get the title of the page referred to by a chat message URL """
DOMAIN_REMAPS = [("mobile.twitter.com", "twitter.com")]
url = trigger.group(1)
for substr, repl in DOMAIN_REMAPS:
url = url.replace(substr, repl)
host = urlparse(url).hostname
... | 19cfa071a2282f7b5d4e46f9e32632a6f0e7e1dd | 3,630,045 |
def assumption_html():
"""Produces an HTML list of all assumption descriptions."""
# full_descriptions = [a.description.format(a.value) for a in ASSUMPTIONS_TO_DISPLAY]
items = _list_items(map(_prettyprint, ASSUMPTIONS_TO_DISPLAY))
return ASSUMPTION_TEXT.format("\n".join(items)) | a41a44c82a87e1f65111ff373409f8fedd3f6159 | 3,630,046 |
from typing import OrderedDict
def edit_page_element(project, pagenumber, pchange, location, tag_name, brief, hide_if_empty, attribs):
"""Given an element at project, pagenumber, location
sets the element values, returns page change uuid """
proj, page = get_proj_page(project, pagenumber, pchange)
... | f1b236a5cf972c494dde0d9bae281c8941a3cb73 | 3,630,047 |
import os
def check_predicted_masks():
"""
Returns the list of images for which we have a mask.
The length of this list must be equal to the total number of original images. Because there should be a black and white
mask for every image.
:return: python list of strings
"""
path_to_masks = ... | 34cc6acf2a60c52c76ae691467bd44c08476596c | 3,630,048 |
def _sparse_elm_mul(spmat_csr, col):
"""
spmat (n, m)
col (n,)
"""
for i in range(spmat_csr.shape[0]):
i0, i1 = spmat_csr.indptr[i], spmat_csr.indptr[i+1]
if i1 == i0:
continue
spmat_csr.data[i0:i1] *= col[i]
return spmat_csr | 55c7ca7f848989eaa95a5917cfa40edf2d7e1372 | 3,630,049 |
def list_ports():
"""
Return a list of current port trees managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_ports
"""
_check_config_exists()
cmd = "poudriere ports -l"
res = __salt__["cmd.run"](cmd).splitlines()
return res | 84342edd644e890b5bcd233b5adf3bcb36033d01 | 3,630,050 |
def _make_vc_curves(ch_data_cache: analyzer.CalcCache):
"""
Format the VC curves of the main accelerometer channel into a pandas object.
"""
df_vc = ch_data_cache._VCCurveData * analyzer.MPS_TO_UMPS # (m/s) -> (μm/s)
df_vc["Resultant"] = calc_stats.L2_norm(df_vc.to_numpy(), axis=1)
if df_vc.siz... | a5beaec9920046a9fb34e36f29e3130d26edc4f2 | 3,630,051 |
from typing import Any
from typing import Optional
def match_attribute_node(obj: Any, name: Optional[str] = None) -> bool:
"""
Returns `True` if the first argument is an attribute node matching the name, `False` otherwise.
Raises a ValueError if the argument name has to be used, but it's in a wrong format... | 6e50bce0e4a8419cea31a8be86eca53a228c6272 | 3,630,052 |
def get_data_accessor_predicate(
data_type: DataTypeLike = None,
format_id: str = None,
storage_id: str = None
) -> ExtensionPredicate:
"""
Get a predicate that checks if a data accessor extensions's name is
compliant with *data_type*, *format_id*, *storage_id*.
:param data_type... | 4089a9149322257d7dbc155130d149f1c9afbd98 | 3,630,053 |
from typing import Any
from typing import Type
import dataclasses
from typing import is_typeddict
from typing import get_origin
from typing import Literal
from typing import Union
def check(value: Any, ty: Type[Any]) -> Result:
"""
# Examples
>>> assert is_error(check(1, str))
>>> assert not is_erro... | 127fd7990cebd217f598303cb0a837a87bd50e68 | 3,630,054 |
def construct_feature_columns():
"""Construct the TensorFlow Feature Columns.
Returns:
A set of feature columns
"""
# There are 784 pixels in each image.
return set([tf.feature_column.numeric_column('pixels', shape=784)]) | 1ee64be4f1ed6783aeb54acdb76b592488d078c8 | 3,630,055 |
def is_array_str(obj):
"""
Check if obj is a list of strings or a tuple of strings or a set of strings
:param obj: an object
:return: flag: True or False
"""
# TODO: modify the use of is_array_str(obj) in the code to is_array_of(obj, classinfo)
flag = False
if isinstance(obj, str):
... | c1c6a37befb70b481eb82b0a4778b45013156c68 | 3,630,056 |
def generate_sample_path(n):
"""
Generates a sample path
:param n: path length
:returns x, y: state and observations sample path
"""
x = np.zeros((n + 1, m_W.shape[0]))
y = np.zeros((n + 1, m_Nu.shape[0]))
# w = np.random.normal(self.m_w, self.std_w, (n + 1, self.m_w.shape[0]))
# nu ... | 50ecbc58bb47cae72302bb1b2ee8425cbb5ee32f | 3,630,057 |
def get_pod_by_label_selector(
kube_client, label_selector, pod_namespace=namespace
) -> str:
"""Return the name of a pod found by label selector."""
pods = kube_client.list_namespaced_pod(
pod_namespace, label_selector=label_selector
).items
assert (
len(pods) > 0
), f"Expected ... | 408b9073ed996d4349b28243fd99201dc642bda9 | 3,630,058 |
import os
def make_file_path(file, args):
"""Create any directories and subdirectories needed to store data in the specified file,
based on inputs_dir and inputs_subdir arguments. Return a pathname to the file."""
# extract extra path information from args (if available)
# and build a path to the spec... | 58ac390734f60daf67adcd6e05b3bf721f4b2383 | 3,630,059 |
import re
def get_ticket_refs(text, prefixes=None):
"""Returns a list of ticket IDs referenced in given text.
Args:
prefixes (list of unicode):
Prefixes allowed before the ticket number.
For example, prefixes=['app-', ''] would recognize
both 'app-1' and '1' as tic... | 41c0f25f387e5f6045c94f6b160afeac6862d3ab | 3,630,060 |
import builtins
def xsh_session():
"""return current xonshSession instance."""
return builtins.__xonsh__ | 25006760522733cfd27c2b189a4d0b934ff59b90 | 3,630,061 |
def is_date_valid(keyid, date, lookup_dict=movie_dict):
"""
Function to see if a date is valid for a given key.
:param keyid: key into the dictionary
:param date: a date to check for in the list corresponding to 'keyid'
:param lookup_dict: lookup dictionary
Note, the date is treated as an exact ... | 841b4ce7c5447f6ed32fa25d85695888cd172865 | 3,630,062 |
import string
def format_filename(name):
"""Take a string and return a valid filename constructed from the string.
Uses a whitelist approach: any characters not present in valid_chars are
removed. Also spaces are replaced with underscores.
Note: this method may produce invalid filenames such as ``, `.` or `..`
W... | bb8bf76421d372d6e0c0ae13dd7743cd164d61ea | 3,630,063 |
def bin_plot(frame, x = None, target = 'target', iv = True):
"""plot for bins
"""
group = frame.groupby(x)
table = group[target].agg(['sum', 'count']).reset_index()
table['badrate'] = table['sum'] / table['count']
table['prop'] = table['count'] / table['count'].sum()
prop_ax = tadpole.barp... | 7ee014167e9af5bd327f31606f95213ba8b4cc2a | 3,630,064 |
import os
import re
def getCtimeOfFile(fileName):
"""
input: string
output: string
description: Get the first line of the file to determine whether there
is a date,
if any, change to the specified date format(yyyymmddHHMM)
and return,
if not, retu... | 3848e82728bea615bf834be719ed958b91253634 | 3,630,065 |
import time
def Get_ConfusionMatrix(TrueLabels, PredictedLabels, Classes, Normal=False, Title='Confusion matrix', ColorMap='rainbow',
FigSize=(30,30), save=False):
""" Function designed to plot the confusion matrix of the predicted labels versus the true leabels
INPUT: vector containi... | e42b59f723c8380951fce3cc930aeab80e96564e | 3,630,066 |
def _noncentrality_chisquare(chi2_stat, df, alpha=0.05):
"""noncentrality parameter for chi-square statistic
`nc` is zero-truncated umvue
Parameters
----------
chi2_stat : float
Chisquare-statistic, for example from a hypothesis test
df : int or float
Degrees of freedom
alp... | 7d179db6e4b503b3890b6f1ca71365b04fff13b0 | 3,630,067 |
import os
import subprocess
import threading
def delete_helm_release(release):
"""Delete helm release
This method deletes a helm release without --purge which removes
all associated resources from kubernetes but not from the store(ETCD)
In the scenario of updating application, the method is needed t... | 36b0af7612b38c7b20144bc3fdfe65e061bd158e | 3,630,068 |
from typing import cast
import select
def get_subjects():
"""
Get all subjects from the database
"""
connection = db_engine.connect()
subject = get_table("subject")
columns = [
subject.c.id, cast(subject.c.date_created, Text), subject.c.date_created.label('date_created'),
cast(... | df817e536f436babe314d1f3ac1f6f32045ac01b | 3,630,069 |
def get_rest_api(*, config: Config) -> FastAPI:
"""Creates a FastAPI app."""
container = setup_container(config=config)
container.wire(modules=["ucs.adapters.inbound.fastapi_"])
api = FastAPI()
api.include_router(router)
configure_app(api, config=config)
return api | a6d579f5d79108136b356f5bea67607a7119fd95 | 3,630,070 |
def read_expression_profiles(pro_file):
"""
Return a DataFrame containing data from a FluxSimulator .pro file.
Return a DataFrame encapsulating the data from a FluxSimulator
transcriptome profile (.pro) file.
pro_file: Path to a FluxSimulator transcriptome profile file.
"""
return pd.read_c... | ec90c27da9f5aa01383745f25898895a2019c570 | 3,630,071 |
def format_list(lst):
"""
Format a list as a string, ignore if it is string
:param lst the list to format
:return the formatted string
"""
if not isinstance(lst, basestring):
return " ".join(str(i) for i in lst)
return lst | d2602666351e0bf3e08882a9f6f3eecc6726889b | 3,630,072 |
def sampler_paraphrase(sentence, sampling_temp=1.0):
"""Paraphrase by sampling a distribution
Args:
sentence (str): A sentence input that will be paraphrased by
sampling from distribution.
sampling_temp (int) : A number between 0 an 1
Returns:
str: a candidate paraphra... | ced919e216a891bb8477234017a2547cec613ca7 | 3,630,073 |
def create_graph(tensorboard_scope, mode_scope, input_file, input_len=2, output_len=1, batch_size=1, verbose=True, reuse=None, n_threads=2):
"""
create or reuse graph
:param tensorboard_scope: variable scope name
:param mode_scope: 'train', 'valid', 'test'
:param input_file: train or valid or test f... | 901ea6c32bccc898ca51734c6c779e0a1655ad51 | 3,630,074 |
def update_trip_public(request, trip_id):
"""
Makes given trip public
:param request:
:param trip_id:
:return: 400 if user not present in the trip
:return: 404 if trip or user does not exist
:return: 200 successful
"""
try:
trip = Trip.objects.get(pk=trip_id)
# if si... | 4805e9c850c314ec8ab9dbf20ded6966a40678cc | 3,630,075 |
def get_peer_count(ihash):
"""Return count of all participating peers we've seen"""
return g.redis.scard("%s:peers:N" % ihash) | be3c08ff07b548123e4b994e0f7539dd82601c22 | 3,630,076 |
import hashlib
def calc_checksum(filename):
"""
Calculates a checksum of the contents of the given file.
:param filename:
:return:
"""
try:
f = open(filename, "rb")
contents = f.read()
m = hashlib.md5()
m.update(contents)
checksum = m.hexdigest()
... | 080e3686279ae126951cd1b66efdb9a0d2448011 | 3,630,077 |
def alignment_matrix(subject, target, precision=BASE_PREC, verbosity=0, max_steps=BASE_STEPS):
"""
Numerically find the rotation matrix necessary to rotate the `subject` vector to the `target` direction.
Args:
subject (np.ndarray): Length-3 vector to rotate.
target (np.ndarray): Length-3 ve... | 0c495a03674f2d48c6a63f944a1be969997221d6 | 3,630,078 |
def make_batch(sentences):
"""
create batch data from sentences (list)
"""
input_batch = []
target_batch = []
for sen in sentences:
word = sen.split()
input = [word_dict[n] for n in word[:-1]]
target = word_dict[word[-1]]
input_batch.append(np.eye(n_class)[input... | ac7e0ea67cded93146182a77ba170192e0340094 | 3,630,079 |
def query_to_str(statement, bind=None):
"""
returns a string of a sqlalchemy.orm.Query with parameters bound
WARNING: this is dangerous and ONLY for testing, executing the results
of this function can result in an SQL Injection attack.
"""
if isinstance(statement, sqlalchemy.orm.Que... | b02bdeae54fab8b93817c6d7c5975e6240c6fe90 | 3,630,080 |
def __filter_card_id(cards: list[str]):
"""Filters an list with card ids to remove
repeating ones and non-ids"""
ids = list()
for c in cards:
try:
int(c)
except ValueError:
continue
else:
if c not in ids:
ids.append(c)
ret... | 53f7cfa979ac8c7bc5357216eb903f5fe5abc02b | 3,630,081 |
import time
def get_elapsed_time(start_time) -> str:
""" Gets nicely formatted timespan from start_time to now """
end = time.time()
hours, rem = divmod(end-start_time, 3600)
minutes, seconds = divmod(rem, 60)
return "{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds) | d75a1873254e1b1cc9ffc714e65d3a9ed95e5803 | 3,630,082 |
def predict_causalforest(cforest, X, num_workers):
"""Predicts individual treatment effects for a causal forest.
Predicts individual treatment effects for new observed features *X*
on a fitted causal forest *cforest*. Predictions are made in parallel with
*num_workers* processes.
Args:
cfo... | b0ec16ebc0192fe4cb8888713b4ce94d90dcde3a | 3,630,083 |
def sectnum(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
"""Automatic section numbering."""
pending = nodes.pending(parts.SectNum)
pending.details.update(options)
state_machine.document.note_pending(pending)
return [pending] | 794374bdaa1c4bc12ad9543f2aecb31a31c29587 | 3,630,084 |
import logging
import re
def make_vectorized_optimizer_class(cls):
"""Constructs a vectorized DP optimizer class from an existing one."""
child_code = cls.compute_gradients.__code__
if child_code is not parent_code:
logging.warning(
'WARNING: Calling make_optimizer_class() on class %s that overrides... | 5a808036e20692463ccf10a3f596269215789ebb | 3,630,085 |
import fnmatch
def filename_matches_pattern(filepath, pattern):
"""
"""
if isinstance(pattern, string_types):
pattern = (pattern, )
for p in tuple(pattern):
if fnmatch(filepath, p):
return True
return False | 8573040959a659eb5531e7893dbe367f1d967651 | 3,630,086 |
import time
def gmt_time():
"""
Return the time in the GMT timezone
@rtype: string
@return: Time in GMT timezone
"""
return time.strftime('%Y-%m-%d %H:%M:%S GMT', time.gmtime()) | 6009f0c3bc185bca9209827f2c89e39917c1e418 | 3,630,087 |
import string
def convertbase(num, base=10):
"""
Convert a number in base 10 to another base
:type num: number
:param num: The number to convert.
:type base: integer
:param base: The base to convert to.
>>> convertbase(20, 6)
'32'
"""
sign = 1 if num > 0 else -1... | a01ba8f729a9b79b29f042551b6440e17a471c7c | 3,630,088 |
import inspect
def get_riskmodel(taxonomy, oqparam, **extra):
"""
Return an instance of the correct riskmodel class, depending on the
attribute `calculation_mode` of the object `oqparam`.
:param taxonomy:
a taxonomy string
:param oqparam:
an object containing the parameters needed... | 2c2015da689980edec7af1678d99f6fe7fac9fec | 3,630,089 |
import os
def is_subdirectory(path_a, path_b):
"""Returns True if `path_a` is a subdirectory of `path_b`."""
path_a = os.path.realpath(path_a)
path_b = os.path.realpath(path_b)
try:
relative = os.path.relpath(path_a, path_b)
except ValueError:
# Different mounts on Windows:
... | 935a5897ff447cc3c6e757d6528f795732bed56f | 3,630,090 |
def add_str(arg1, arg2):
"""concatenate arg1 & arg2
Using in template:
'{{ arg1|add_str:arg2 }}'
"""
return str(arg1) + str(arg2) | 2876195d1fe51e0d7f2a86146f0e49f9b4de4598 | 3,630,091 |
def clean_string_columns(df):
"""Clean string columns in a dataframe."""
try:
df.email = df.email.str.lower()
df.website = df.website.str.lower()
except AttributeError:
pass
str_columns = ["name", "trade_name", "city", "county"]
for column in str_columns:
try:
... | eb9aaa474fe517b346eaa8cd93e669b3fcc3459d | 3,630,092 |
def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile | 6d2dbf19d7b4faf283db84485dab6a8f7e2a646b | 3,630,093 |
def _QueryForUser(user, role=None, target=None):
"""Gets all _Permissions for the user's ID and e-mail domain."""
return _Query(user.id, role, target) + _Query(user.email_domain, role, target) | f873e23f302b7bc85ead4e2da5938edc799a80d3 | 3,630,094 |
def decode_transfer2(instruction: TransactionInstruction) -> Transfer2Params:
"""Decode a transfer2 token transaction and retrieve the instruction params."""
parsed_data = __parse_and_validate_instruction(instruction, 4, InstructionType.TRANSFER2)
return Transfer2Params(
program_id=instruction.progr... | 443f1731176b350bcfb24d36d85ac4cf4e18781c | 3,630,095 |
import os
import gzip
def postprocess(annotator, genomes, working_dir):
"""
Finds eCIS-screen output files and creates file with annotations for upload into DB
"""
output_file = os.path.join(annotator.config['cgcms.temp_dir'], 'ecis-screen-plugin-output.txt')
accessions = {}
for genom... | 120d6231bd527f74f51055bfaae3e76763bbc8b6 | 3,630,096 |
def deep_predict(data: pd.DataFrame, model, kernel: str):
"""
Deepl Predict Method.
"""
data = feature_time(data)
print(data.shape)
print(data.tail(5))
# normalization
data = data.set_index('time')
data_norm = (data - data.mean()) / data.std()
print("name: ", model.name)
thi... | 9d3ce07840e473e97387f7648a79b1d21f995b9c | 3,630,097 |
def create(user_id):
"""
Create User Function
"""
req_data = request.get_json()
isuser = UserModel.get_one_user(user_id)
#Check if user exist
if isuser:
return custom_response({'error': 'User already exist'}, 400)
req_data["user_guid"] = user_id
user = UserModel(req_data)
message = user.create... | 1d150be1a7e29fc600cc4f7ddcc49c5a6ecd65db | 3,630,098 |
def ordinal(n: int) -> str:
"""
from: https://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1st-2nd-3rd#answer-4712
"""
result = "%d%s" % (n, "tsnrhtdd"[((n / 10 % 10 != 1) * (n % 10 < 4) * n % 10)::4])
return result.replace('11st', '11th').replace('12nd', '12th').replace('13r... | 97eecb539ae37c89ea3e4e76c5c913877fbf2365 | 3,630,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.