content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def sample_categorical(pmf):
"""Sample from a categorical distribution.
Args:
pmf: Probablity mass function. Output of a softmax over categories.
Array of shape [batch_size, number of categories]. Rows sum to 1.
Returns:
idxs: Array of size [batch_size, 1]. Integer of category sa... | 5b270e63bb5e290a97cacede9bd0f8bf34fc0ecf | 22,200 |
def make_Dex_3D(dL, shape, bloch_x=0.0):
""" Forward derivative in x """
Nx, Ny , Nz= shape
phasor_x = np.exp(1j * bloch_x)
Dex = sp.diags([-1, 1, phasor_x], [0, Nz*Ny, -Nx*Ny*Nz+Nz*Ny], shape=(Nx*Ny*Nz, Nx*Ny*Nz))
Dex = 1 / dL * sp.kron(sp.eye(1),Dex)
return Dex | 1d3a47624f180d672f43fb65082f29727b42f720 | 22,201 |
def feature_decoder(proto_bytes):
"""Deserializes the ``ProtoFeature`` bytes into Python.
Args:
proto_bytes (bytes): The ProtoBuf encoded bytes of the ProtoBuf class.
Returns:
:class:`~geopyspark.vector_pipe.Feature`
"""
pb_feature = ProtoFeature.FromString(proto_bytes)
retur... | ff7cdc6c0d7f056c69576af2a5b5eb98f57266af | 22,202 |
async def calculate_board_fitness_report(
board: list, zone_height: int, zone_length: int
) -> tuple:
"""Calculate Board Fitness Report
This function uses the general solver functions api to calculate and return all the different collisions on a given board array
representation.
Args:
boa... | a770863c044a4c4452860f9fccf99428dbfb5013 | 22,203 |
def quote_fqident(s):
"""Quote fully qualified SQL identifier.
The '.' is taken as namespace separator and
all parts are quoted separately
Example:
>>> quote_fqident('tbl')
'public.tbl'
>>> quote_fqident('Baz.Foo.Bar')
'"Baz"."Foo.Bar"'
"""
tmp = s.split('.', 1)
if len(tmp)... | 26cf409a09d2e8614ac4aba04db1eee6cac75f08 | 22,204 |
def row_generator(x, H, W, C):
"""Returns a single entry in the generated dataset.
Return a bunch of random values as an example."""
return {'frame_id': x,
'frame_data': np.random.randint(0, 10,
dtype=np.uint8, size=(H, W, C))} | e99c6e8b1557890b6d20ea299bc54c0773ea8ade | 22,205 |
def accuracy(output, target, topk=(1,)):
"""Computes the precor@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
... | 80e73c907e57b9666a8f399b8ed655c919d79abb | 22,206 |
def define_model(input_shape, output_shape, FLAGS):
"""
Define the model along with the TensorBoard summaries
"""
data_format = "channels_last"
concat_axis = -1
n_cl_out = 1 # Number of output classes
dropout = 0.2 # Percentage of dropout for network layers
num_datapoints = input_sh... | 4d6bea9444935af1b95e9b209eee2df7d455e90c | 22,207 |
import re
import collections
def group_files(config_files, group_regex, group_alias="\\1"):
"""group input files by regular expression"""
rx = re.compile(group_regex)
for key, files in list(config_files.items()):
if isinstance(files, list):
groups = collections.defaultdict(list)
... | 7f0c14387a9a63d03e8fdcb2297502a4ebf31e80 | 22,208 |
def get_current_icmp_seq():
"""See help(scapy.arch.windows.native) for more information.
Returns the current ICMP seq number."""
return GetIcmpStatistics()['stats']['icmpOutStats']['dwEchos'] | 4e5798a6187cd8da55b54698deab4f00aec19144 | 22,209 |
def text_mocked_request(data: str, **kwargs) -> web.Request:
"""For testng purposes."""
return mocked_request(data.encode(), content_type="text/plain", **kwargs) | fe9acfd2d7801a387f6497bdd72becd94da57ea9 | 22,210 |
def get_imu_data():
"""Returns a 2d array containing the following
* ``senses[0] = accel[x, y, z]`` for accelerometer data
* ``senses[1] = gyro[x, y, z]`` for gyroscope data
* ``senses[2] = mag[x, y, z]`` for magnetometer data
.. note:: Not all data may be aggregated depending on the IMU device co... | 24f24316a051a4ac9f1d8d7cbab00be05ff11c25 | 22,211 |
def parse_proc_diskstats(proc_diskstats_contents):
# type: (six.text_type) -> List[Sample]
"""
Parse /proc/net/dev contents into a list of samples.
"""
return_me = [] # type: List[Sample]
for line in proc_diskstats_contents.splitlines():
match = PROC_DISKSTATS_RE.match(line)
if ... | af24bc01d7e31dc43cf07057fae672ba62b20e53 | 22,212 |
def normalize(x):
"""Normalize a vector or a set of vectors.
Arguments:
* x: a 1D array (vector) or a 2D array, where each row is a vector.
Returns:
* y: normalized copies of the original vector(s).
"""
if x.ndim == 1:
return x / np.sqrt(np.sum(x ** 2))
eli... | f4e813b22a9088c3a9a209e94963b33c24fab88e | 22,213 |
def compute_perrakis_estimate(marginal_sample, lnlikefunc, lnpriorfunc,
lnlikeargs=(), lnpriorargs=(),
densityestimation='histogram', **kwargs):
"""
Computes the Perrakis estimate of the bayesian evidence.
The estimation is based on n marginal pos... | 70a287e3ed8391ecef1e48d7db846593fe240823 | 22,214 |
def postNewProfile(profile : Profile):
"""Gets all profile details of user with given profile_email
Parameters:
str: profile_email
Returns:
Json with Profile details """
profile_email = profile.email
profile_query = collection.find({"email":profile_email})
profile_query = [it... | be81eac071e89a9ff8d44ac8e2cd479e911763b6 | 22,215 |
from datetime import datetime
def buy():
"""Buy shares of stock."""
# if user reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# ensure SYMBOL and Share is submitted
if request.form.get("symbol") == "" or request.form.get("share") == "":
... | 5565de080d4593618ea3b79ddca738b2d9f5d1ae | 22,216 |
from typing import List
def get_templates() -> List[dict]:
"""
Gets a list of Templates that the active client can access
"""
client = get_active_notification_client()
if not client:
raise NotificationClientNotFound()
r = _get_templates(client=client)
return r | b7603ba33e1628eb6dad91b861bf17ecb914c1eb | 22,217 |
def svn_mergeinfo_intersect2(*args):
"""
svn_mergeinfo_intersect2(svn_mergeinfo_t mergeinfo1, svn_mergeinfo_t mergeinfo2,
svn_boolean_t consider_inheritance, apr_pool_t result_pool,
apr_pool_t scratch_pool) -> svn_error_t
"""
return _core.svn_mergeinfo_intersect2(*args) | 5c8176eec56fb1a95b306af41c2d98caa75459ec | 22,218 |
import time
import multiprocessing
def _update_images():
"""Update all docker images in this list, running a few in parallel."""
any_new = False
def comment(name, new):
nonlocal any_new
if new:
log.info(f"Downloaded new Docker image for {name} - {docker.image_size(name)}")
... | ecb95955d3f2514cb53849384de0815f88dae133 | 22,219 |
def conv_backward(dZ, A_prev, W, b, padding="same", stride=(1, 1)):
"""
Performs back propagation over a convolutional layer of a neural network
dZ is a numpy.ndarray of shape (m, h_new, w_new, c_new) containing the
partial derivatives with respect to the unactivated output of the
convolutional lay... | d55eab80411efa903e03b584464ff50196468d7d | 22,220 |
import os
def clone(repo, user, site, parent=None):
"""
Clone a repo from the requested site and user.
:param repo: The name of the repo.
:param user: The name of the user.
:param site: The site to download from.
:param parent: The parent folder where the repo will be cloned. By default,
... | 11b9eb1a448fa2b0915602129ea2f0695d9f6992 | 22,221 |
import collections
def get_final_text(pred_text, orig_text, do_lower_case):
"""Project the tokenized prediction back to the original text."""
# When we created the data, we kept track of the alignment between original
# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
# now `orig_... | 5ca989a4ae5ce00cd9c09c4d9480dbeb935d6ca8 | 22,222 |
def createContext(data, id=None, keyTransform=None, removeNull=False):
"""Receives a dict with flattened key values, and converts them into nested dicts
:type data: ``dict`` or ``list``
:param data: The data to be added to the context (required)
:type id: ``str``
:keyword id: The I... | a97c599689932cbfea7063fdae32702d413352ac | 22,223 |
import os
def default_xonshrc(env) -> "tuple[str, ...]":
"""
``['$XONSH_SYS_CONFIG_DIR/xonshrc', '$XONSH_CONFIG_DIR/xonsh/rc.xsh', '~/.xonshrc']``
"""
dxrc = (
os.path.join(xonsh_sys_config_dir(env), "xonshrc"),
os.path.join(xonsh_config_dir(env), "rc.xsh"),
os.path.expanduser... | de58924da5fd6d8683edcbe049dbc2eb7a7c8b45 | 22,224 |
import math
def haversine(phi1, lambda1, phi2, lambda2):
"""
calculate angular great circle distance with haversine formula
see parameters in spherical_law_of_cosines
"""
d_phi = phi2 - phi1
d_lambda = lambda2 - lambda1
a = math.pow(math.sin(d_phi / 2), 2) + \
math.cos(phi1) * math... | acb25fc8d305dde7b18059a770bdcd9b135b295a | 22,225 |
import yaml
from datetime import datetime
def get_backup_start_timestamp(bag_name):
"""
Input: Fisrt bag name
Output: datatime object
"""
info_dict = yaml.load(Bag(bag_name, 'r')._get_yaml_info())
start_timestamp = info_dict.get("start", None)
start_datetime = None
if start_timestamp i... | b8ee55c3028fb6f6e1137d614e836724c3e00bd6 | 22,226 |
import os
def ResidualSlopesSequence2ResidualPhase(Gradients,S2M,M2V,name='residual_phase_cube.fits',\
path='.',binning=40):
"""
Same functions as ResidualSlopes2ResidualPhase but applies it to a sequence
of slopes (gradients) instead of a single vector.
Input:
- Gradie... | e6845f199c7901e5b640e4081aa9363f7b60e667 | 22,227 |
def get_mask_areas(masks: np.ndarray) -> np.ndarray:
"""Get mask areas from the compressed mask map."""
# 0 for background
ann_ids = np.sort(np.unique(masks))[1:]
areas = np.zeros((len(ann_ids)))
for i, ann_id in enumerate(ann_ids):
areas[i] = np.count_nonzero(ann_id == masks)
return are... | bf584c9529118d9946e461b4df22cf64efbeb251 | 22,228 |
def cursor_from_image(image):
"""
Take a valid cursor image and create a mouse cursor.
"""
colors = {(0,0,0,255) : "X",
(255,255,255,255) : "."}
rect = image.get_rect()
icon_string = []
for j in range(rect.height):
this_row = []
for i in range(rect.width):
... | 173c3fc6bfcc6bb45c9e1e6072d7c68244750da9 | 22,229 |
def h_matrix(jac, p, lamb, method='kotre', W=None):
"""
JAC method of dynamic EIT solver:
H = (J.T*J + lamb*R)^(-1) * J.T
Parameters
----------
jac: NDArray
Jacobian
p, lamb: float
regularization parameters
method: str, optional
regularization method
Ret... | fc4d225bb2d98ee067b03c10f14ad23db6fad1a9 | 22,230 |
def _get_flavors_metadata_ui_converters_from_configuration():
"""Get flavor metadata ui converters from flavor mapping config dir."""
flavors_metadata_ui_converters = {}
configs = util.load_configs(setting.FLAVOR_MAPPING_DIR)
for config in configs:
adapter_name = config['ADAPTER']
flavor... | 4cb8dc1737579cd76dd696ec08f984015e3ef77b | 22,231 |
def outermost_scope_from_subgraph(graph, subgraph, scope_dict=None):
"""
Returns the outermost scope of a subgraph.
If the subgraph is not connected, there might be several
scopes that are locally outermost. In this case, it
throws an Exception.
"""
if scope_dict is None:
scope_dict... | 0bd649d00b745065e75e2dcfc37d9b16eaa0c3db | 22,232 |
def calc_entropy_ew(molecule, temp):
"""
Expoential well entropy
:param molecule:
:param temp:
:param a:
:param k:
:return:
"""
mass = molecule.mass / Constants.amu_to_kg * Constants.amu_to_au
a = molecule.ew_a_inv_ang * Constants.inverse_ang_inverse_au
k = molecule.ew_k_kca... | 7d4d2c13ce5b081e4b209169a3cf996dd0b34a44 | 22,233 |
import json
import uuid
import sys
def registerCreatorDataCallbackURL():
"""
params:
creatorID
dataCallbackURL
"""
try:
global rmlEngine
rawRequest = request.POST.dict
for rawKey in rawRequest.keys():
keyVal = rawKey
jsonPayload... | 215780a12b232aaf7993ccc3dccb5905a2fe0cc7 | 22,234 |
def csm(A, B):
"""
Calculate Cosine similarity measure of distance between two vectors `A` and `B`.
Parameters
-----------
A : ndarray
First vector containing values
B : ndarray
Second vector containing values
Returns
--------
float
d... | cebca4a53ed3200d4820041fca7886df57f4a40c | 22,235 |
def RationalsModP(p):
"""Assume p is a prime."""
class RationalModP(_Modular):
"""A rational modulo p
The rational is stored with numerator and denominator relatively prime.
This is done to prevent growth in numerator or denominator which causes
overflow and makes math harder.
"""
de... | 137ac2b7f728b49c83e5e02dcbae7c782cc2877f | 22,236 |
import random
import string
def rand_email():
"""Random email.
Usage Example::
>>> rand_email()
Z4Lljcbdw7m@npa.net
"""
name = random.choice(string.ascii_letters) + \
rand_str(string.ascii_letters + string.digits, random.randint(4, 14))
domain = rand_str(string.ascii... | 9898669f59511d5b8fd403de0ab7174e7710d898 | 22,237 |
import os
import re
def __parse_quic_timing_from_scenario(in_dir: str, scenario_name: str, pep: bool = False) -> pd.DataFrame:
"""
Parse the quic timing results in the given scenario.
:param in_dir: The directory containing all measurement results
:param scenario_name: The name of the scenario to pars... | 71990b317f2e5d87ae62403bb730a1ea0b2ab8e2 | 22,238 |
import asyncio
async def value_to_deep_structure(value, hash_pattern):
"""build deep structure from value"""
try:
objects = {}
deep_structure0 = _value_to_objects(
value, hash_pattern, objects
)
except (TypeError, ValueError):
raise DeepStructureError(hash_patte... | 05df4e4cec2a39006631f96a84cd6268a6550b68 | 22,239 |
def get_users_run(jobs, d_from, target, d_to='', use_unit='cpu',
serialize_running=''):
"""Takes a DataFrame full of job information and
returns usage for each "user"
uniquely based on specified unit.
This function operates as a stepping stone for plotting usage figures
and return... | ab40605468e40b7e76a35d4bc2c1344be9050d5f | 22,240 |
import collections
def get_classes_constants(paths):
"""
Extract the vtk class names and constants from the path.
:param paths: The path(s) to the Python file(s).
:return: The file name, the VTK classes and any VTK constants.
"""
res = collections.defaultdict(set)
for path in paths:
... | e58531e99c37c1c23abb46b18f4b2af0b95c5db9 | 22,241 |
def predict_unfolding_at_temperature(temp, data, PDB_files):
"""
Function to predict lables for all trajectoires at a given temperature
Note: The assumption is that at a given temperature, all snapshots are at the same times
Filter should be 'First commit' or 'Last commit' or 'Filter osc' as descri... | 9fec4ee407bf41692c57899e96ff16ad2acdf4ea | 22,242 |
def _frac_scorer(matched_hs_ions_df, all_hyp_ions_df, N_spectra):
"""Fraction ion observed scorer.
Provides a score based off of the fraction of hypothetical ions that were observed
for a given hypothetical structure.
Parameters
----------
matched_hs_ions_df : pd.DataFrame
Dataframe of... | a341b02b7ba64eb3b29032b4fe681267c5d36a00 | 22,243 |
def role_in(roles_allowed):
"""
A permission checker that checks that a role possessed by the user matches one of the role_in list
"""
def _check_with_authuser(authuser):
return any(r in authuser.roles for r in roles_allowed)
return _check_with_authuser | 24ff0423dc50187f3607329342af6c8930596a36 | 22,244 |
from typing import List
def elements_for_model(model: Model) -> List[str]:
"""Creates a list of elements to expect to register.
Args:
model: The model to create a list for.
"""
def increment(index: List[int], dims: List[int]) -> None:
# assumes index and dims are the same length > 0
... | a0769d762fc31ac128ad077e1601b3ba3bcd6a27 | 22,245 |
def form_IntegerNoneDefault(request):
"""
An integer field defaulting to None
"""
schema = schemaish.Structure()
schema.add('myIntegerField', schemaish.Integer())
form = formish.Form(schema, 'form')
form.defaults = {'myIntegerField':None}
return form | 322671035e232cfd99c7500fe0995d652a4fbe7a | 22,246 |
import string
def tokenize(text, stopwords):
"""Tokenizes and removes stopwords from the document"""
without_punctuations = text.translate(str.maketrans('', '', string.punctuation))
tokens = word_tokenize(without_punctuations)
filtered = [w.lower() for w in tokens if not w in stopwords]
return fil... | 7a231d124e89c97b53779fee00874fb2cb40155e | 22,247 |
def to_dict(prim: Primitive) -> ObjectData:
"""Convert a primitive to a dictionary for serialization."""
val: BasePrimitive = prim.value
data: ObjectData = {
"name": val.name,
"size": val.size,
"signed": val.signed,
"integer": prim in INTEGER_PRIMITIVES,
}
if val.min... | 32d57b89e6740239b55b7f491e16de7f9b31a186 | 22,248 |
import requests
def get_raw_img(url):
"""
Download input image from url.
"""
pic = False
response = requests.get(url, stream=True)
with open('./imgs/img.png', 'wb') as file:
for chunk in response.iter_content():
file.write(chunk)
pic = True
response.close()
... | 67b2cf9f2c89c26fca865ea93be8f6e32cfa2de5 | 22,249 |
def get_and_validate_study_id(chunked_download=False):
"""
Checks for a valid study object id or primary key.
If neither is given, a 400 (bad request) error is raised.
Study object id malformed (not 24 characters) causes 400 error.
Study object id otherwise invalid causes 400 error.
Study does n... | 405420481c343afcaacbcfc14bc75fc7acf5aae9 | 22,250 |
import re
def tokenize_char(pinyin: str) -> tuple[str, str, int] | None:
"""
Given a string containing the pinyin representation of a Chinese character, return a 3-tuple containing its
initial (``str``), final (``str``), and tone (``int; [0-4]``), or ``None`` if it cannot be properly tokenized.
"""
... | e4bfb4712857d9201daff187ab63c9846be17764 | 22,251 |
def is_in_cell(point:list, corners:list) -> bool:
"""
Checks if a point is within a cell.
:param point: Tuple of lat/Y,lon/X-coordinates
:param corners: List of corner coordinates
:returns: Boolean whether point is within cell
:Example:
"""
y1, y2, x1, x2 = corners[2][0], corn... | 5f8f13a65ea4da1909a6b701a04e391ebed413dc | 22,252 |
def json_response(function):
"""
This decorator can be used to catch :class:`~django.http.Http404` exceptions and convert them to a :class:`~django.http.JsonResponse`.
Without this decorator, the exceptions would be converted to :class:`~django.http.HttpResponse`.
:param function: The view function whi... | 0b13ff38d932c64fd5afbb017601e34c1c26648b | 22,253 |
import re
def generate_junit_report_from_cfn_guard(report):
"""Generate Test Case from cloudformation guard report"""
test_cases = []
count_id = 0
for file_findings in report:
finding = file_findings["message"]
# extract resource id from finsind line
resource_regex = re.search... | cdf747c535042bf93c204fe8d2b647b3045f7ed7 | 22,254 |
def new_custom_alias():
"""
Create a new custom alias
Input:
alias_prefix, for ex "www_groupon_com"
alias_suffix, either .random_letters@simplelogin.co or @my-domain.com
optional "hostname" in args
Output:
201 if success
409 if the alias already exists
"""
... | 552812711eefd182d7671e3ac72776bbf908ff33 | 22,255 |
def setup_pen_kw(penkw={}, **kw):
"""
Builds a pyqtgraph pen (object containing color, linestyle, etc. information) from Matplotlib keywords.
Please dealias first.
:param penkw: dict
Dictionary of pre-translated pyqtgraph keywords to pass to pen
:param kw: dict
Dictionary of Matplo... | d6b2c68501a88896b7eb09032e2ac7cde6812e94 | 22,256 |
def seq(seq_aps):
"""Sequence of parsers `seq_aps`."""
if not seq_aps:
return succeed(list())
else:
ap = seq_aps[0]
aps = seq_aps[1:]
return ap << cons >> seq(aps) | ab94d3372f229e13a83387b256f3daa3ab2357a5 | 22,257 |
def Growth_factor_Heath(omega_m, z):
"""
Computes the unnormalised growth factor at redshift z given the present day value of omega_m. Uses the expression
from Heath1977
Assumes Flat LCDM cosmology, which is fine given this is also assumed in CambGenerator. Possible improvement
could be to tabulate... | c14e93a871f57c0566b13adb9005c54e68fbfa0f | 22,258 |
def freq2bark(freq_axis):
""" Frequency conversion from Hertz to Bark
See E. Zwicker, H. Fastl: Psychoacoustics. Springer,Berlin, Heidelberg, 1990.
The coefficients are linearly interpolated from the values given in table 6.1.
Parameter
---------
freq_axis : numpy.array
... | f6bd27c54debe8cd8b79099f106e1bf7d4350010 | 22,259 |
import requires_internet
import urllib.request
import sys
import os
import distutils
import getopt
def main(argv):
"""Run tests, return number of failures (integer)."""
# insert our paths in sys.path:
# ../build/lib.*
# ..
# Q. Why this order?
# A. To find the C modules (which are in ../build/... | 87b7a0c49cc488a7ad2e4a508fdff06a84f30049 | 22,260 |
def close_connection(conn: Connection):
"""
Closes current connection.
:param conn Connection: Connection to close.
"""
if conn:
conn.close()
return True
return False | bca91687677860a7937875335701afb923ba49cc | 22,261 |
import warnings
def tile_memory_free(y, shape):
"""
XXX Will be deprecated
Tile vector along multiple dimension without allocating new memory.
Parameters
----------
y : np.array, shape (n,)
data
shape : np.array, shape (m),
Returns
-------
Y : np.array, shape (n, *sha... | f800c44ddd2a66553619157d8c8374a4c33dde18 | 22,262 |
def load_ref_system():
""" Returns d-talose as found in the IQMol fragment library.
All credit to https://github.com/nutjunkie/IQmol
"""
return psr.make_system("""
C -0.6934 -0.4440 -0.1550
C -2.0590 0.1297 0.3312
C -3.1553 -0.9249 0.167... | 7b41df916cb06dccaa53f13461f2bb7c6bfd882a | 22,263 |
def format_user_id(user_id):
"""
Format user id so Slack tags it
Args:
user_id (str): A slack user id
Returns:
str: A user id in a Slack tag
"""
return f"<@{user_id}>" | 2b3a66739c3c9c52c5beb7161e4380a78c5e2664 | 22,264 |
import socket
import ssl
def test_module(params: dict):
"""
Returning 'ok' indicates that the integration works like it is supposed to.
This test works by running the listening server to see if it will run.
Args:
params (dict): The integration parameters
Returns:
'ok' if test pass... | 0f49bff09fcb84fa810ee2c6d32a52089f2f0147 | 22,265 |
def class_loss_regr(num_classes, num_cam):
"""Loss function for rpn regression
Args:
num_anchors: number of anchors (9 in here)
num_cam : number of cam (3 in here)
Returns:
Smooth L1 loss function
0.5*x*x (if x_abs < 1)
x_abx - 0... | cad962f1af1a1acb2013063c6803261535652c18 | 22,266 |
import smtplib
import ssl
def smtplib_connector(hostname, port, username=None, password=None, use_ssl=False):
""" A utility class that generates an SMTP connection factory.
:param str hostname: The SMTP server's hostname
:param int port: The SMTP server's connection port
:param str username: The SMTP... | 511fe48b1f3f2d5d3b9ef3a803166be1519a1b7f | 22,267 |
def _to_one_hot_sequence(indexed_sequence_tensors):
"""Convert ints in sequence to one-hots.
Turns indices (in the sequence) into one-hot vectors.
Args:
indexed_sequence_tensors: dict containing SEQUENCE_KEY field.
For example: {
'sequence': '[1, 3, 3, 4, 12, 6]' # This is the amino acid ... | 32ff14139b53f181d6f032e4e372357cf54c1d62 | 22,268 |
def kaiser_smooth(x,beta):
""" kaiser window smoothing """
window_len=41 #Needs to be odd for proper response
# extending the data at beginning and at the end
# to apply the window at the borders
s = np.r_[x[window_len-1:0:-1],x,x[-1... | 2b766edd85927766330c8cddded3af639d5f16f3 | 22,269 |
def get_indel_dicts(bamfile, target):
"""Get all insertion in alignments within target. Return dict."""
samfile = pysam.AlignmentFile(bamfile, "rb")
indel_coverage = defaultdict(int)
indel_length = defaultdict(list)
indel_length_coverage = dict()
for c, s, e in parse_bed(target):
s = i... | e8f6883f1cf1d653fe0825b4f10518daa2801178 | 22,270 |
def _ComputeRelativeAlphaBeta(omega_b, position_b, apparent_wind_b):
"""Computes the relative alpha and beta values, in degrees, from kinematics.
Args:
omega_b: Array of size (n, 3). Body rates of the kite [rad/s].
position_b: Array of size (1, 3). Position of the surface to compute local
a... | 6aa5f82e85b50abab0c72800b5e2b11ec613bcbd | 22,271 |
def make_chord(midi_nums, duration, sig_cons=CosSignal, framerate=11025):
"""Make a chord with the given duration.
midi_nums: sequence of int MIDI note numbers
duration: float seconds
sig_cons: Signal constructor function
framerate: int frames per second
returns: Wave
"""
freqs = [midi... | babc9d22b92b2e7085680178718959cd7ef15eca | 22,272 |
def calculate_percent(partial, total):
"""Calculate percent value."""
if total:
percent = round(partial / total * 100, 2)
else:
percent = 0
return f'{percent}%' | 4d3da544dd1252acec3351e7f67568be80afe020 | 22,273 |
import requests
def okgets(urls):
"""Multi-threaded requests.get, only returning valid response objects
:param urls: A container of str URLs
:returns: A tuple of requests.Response objects
"""
return nest(
ripper(requests.get),
filt(statusok),
tuple
)(urls) | 0933f4df68745a6c9d69d0b42d4bb005c1c69772 | 22,274 |
def worker(args):
"""
This function does the work of returning a URL for the NDSE view
"""
# Step 1. Create the NDSE view request object
# Set the url where you want the recipient to go once they are done
# with the NDSE. It is usually the case that the
# user will never "finish" with the N... | abcb2a94e5d14519a708ae8d531e47f30bc3c0da | 22,275 |
import warnings
import math
def plot_horiz_xsection_quiver_map(Grids, ax=None,
background_field='reflectivity',
level=1, cmap='pyart_LangRainbow12',
vmin=None, vmax=None,
u_vel_c... | 7f093435ad5488226232a6028d94e6f22b1a2688 | 22,276 |
def register(registered_collection, reg_key):
"""Register decorated function or class to collection.
Register decorated function or class into registered_collection, in a
hierarchical order. For example, when reg_key="my_model/my_exp/my_config_0"
the decorated function or class is stored under
registered_col... | affba6b7ee1294040633f488752623b3fa0462e4 | 22,277 |
def form_hhaa_records(df,
team_locn='h',
records='h',
feature='ftGoals'):
"""
Accept a league table of matches with a feature
"""
team_records = []
for _, team_df in df.groupby(by=team_locn):
lags = range(0, len(team_df))
... | af618fa0fe3c1602018ba6830c381bde73c158c3 | 22,278 |
def process_dataset(material: str, frequency: float, plot=False,
pr=False) -> float:
"""
Take a set of data, fit curve and find thermal diffustivity.
Parameters
----------
material : str
Gives material of this dataset. 'Cu' or 'Al'.
frequency : float
Frequenc... | 64e25b326ddf33adf568b395320e9dddcc9c637d | 22,279 |
import os
def load_shuttle(main_data_path, folder='shuttle', df=None):
"""
____ _ _ _ _ ___ ___ _ ____
[__ |__| | | | | | |___
___] | | |__| | | |___ |___
From UCI https://archive.ics.uci.edu/ml/datasets/Shuttle+Landing+Control
"""
#... | 4f7394ed18d168742db8cb747a57b3d01cc2ed52 | 22,280 |
from collections import OrderedDict
from matplotlib.gridspec import GridSpec
from matplotlib.ticker import MultipleLocator
def show_drizzle_HDU(hdu):
"""Make a figure from the multiple extensions in the drizzled grism file.
Parameters
----------
hdu : `~astropy.io.fits.HDUList`
HDU list o... | 9ca8efd9278d495765eee08566ff56e0ec63efeb | 22,281 |
def make_ln_func(variable):
"""Take an qs and computed the natural log of a variable"""
def safe_ln_queryset(qs):
"""Takes the natural log of a queryset's values and handles zeros"""
vals = qs.values_list(variable, flat=True)
ret = np.log(vals)
ret[ret == -np.inf] = 0
ret... | 200c17c011788e53aa3f678ede22c02bad10613a | 22,282 |
def calc_all_energies(n, k, states, params):
"""Calculate all the energies for the states given. Can be used for Potts.
Parameters
----------
n : int
Number of spins.
k : int
Ising or Potts3 model.
states : ndarray
Number of distinct states.
params : ndarray
... | 9de47da0f0dfa2047fdddc7796ada861d7be0f6b | 22,283 |
from heroku_connect.models import TriggerLog, TriggerLogArchive
def create_heroku_connect_schema(using=DEFAULT_DB_ALIAS):
"""
Create Heroku Connect schema.
Note:
This function is only meant to be used for local development.
In a production environment the schema will be created by
... | bb7eacbf4775bb08f723b69adc6a43c10ffe9287 | 22,284 |
import re
def extract_sentences(modifier, split_text):
"""
Extracts the sentences that contain the modifier references.
"""
extracted_text = []
for sentence in split_text:
if re.search(r"\b(?=\w)%s\b(?!\w)" % re.escape(modifier), sentence,
re.IGNORECASE):
e... | 4e31a250520b765d998aa8bc88f2414fe206901c | 22,285 |
def get_1_neighbours(graph, i):
"""
This function gets all the 1-neighborhoods including i itself.
"""
nbhd_nodes = graph.get_out_neighbours(i)
nbhd_nodes = np.concatenate((nbhd_nodes,np.array([i])))
return nbhd_nodes | 4b19f6eb2cbd7044cf0da26e6770a2be85ae901d | 22,286 |
def window_slice(frame, center, window):
"""
Get the index ranges for a window with size `window` at `center`, clipped to the boundaries of `frame`
Parameters
----------
frame : ArrayLike
image frame for bound-checking
center : Tuple
(y, x) coordinate of the window
window : ... | 111c53b7b2ead44e462cc3c5815e9d44b4c3d024 | 22,287 |
def revnum_to_revref(rev, old_marks):
"""Convert an hg revnum to a git-fast-import rev reference (an SHA1
or a mark)"""
return old_marks.get(rev) or b':%d' % (rev+1) | 13730de4c1debe0cecdd1a14652490b9416b22f5 | 22,288 |
def onset_precision_recall_f1(ref_intervals, est_intervals,
onset_tolerance=0.05, strict=False, beta=1.0):
"""Compute the Precision, Recall and F-measure of note onsets: an estimated
onset is considered correct if it is within +-50ms of a reference onset.
Note that this metric ... | aa4747925a59116246ece29e4cec55a2f91a903d | 22,289 |
def parse_acs_metadata(acs_metadata, groups):
"""Returns a map of variable ids to metadata for that variable, filtered to
specified groups.
acs_metadata: The ACS metadata as json.
groups: The list of group ids to include."""
output_vars = {}
for variable_id, metadata in acs_metadata["variabl... | f0bfb0172b0b2d5fec92b613b5f2e2baf6e7c8f0 | 22,290 |
def split_series_using_lytaf(timearray, data, lytaf):
"""
Proba-2 analysis code for splitting up LYRA timeseries around locations
where LARs (and other data events) are observed.
Parameters
----------
timearray : `numpy.ndarray` of times understood by `sunpy.time.parse_time`
function.
... | 2cc509ede0f2f74f999fae180acb23049a87f165 | 22,291 |
def getrqdata(request):
"""Return the request data.
Unlike the now defunct `REQUEST
<https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.REQUEST>`_
attribute, this inspects the request's `method` in order to decide
what to return.
"""
if request.method in (... | d385943c4c8c7fc7e0b5fc4b1d0f1ba0bc272a13 | 22,292 |
from typing import List
def generate_per_level_fractions(highest_level_ratio: int, num_levels: int = NUM_LEVELS) -> List[float]:
"""
Generates the per-level fractions to reach the target sum (i.e. the highest level ratio).
Args:
highest_level_ratio:
The 1:highest_level_ratio ratio for... | 6c7aee63a2b89671ae65bd28fb8616ffc72d014b | 22,293 |
def choose_transformations(name):
"""Prompts user with different data transformation options"""
transformations_prompt=[
{
'type':'confirm',
'message':'Would you like to apply some transformations to the file? (Default is no)',
'name':'confirm_transformations',
... | f24c560cb23573daa57e4fece7a28b3a809ae478 | 22,294 |
from typing import Dict
from typing import Tuple
def update_list_item_command(client: Client, args: Dict) -> Tuple[str, Dict, Dict]:
"""Updates a list item. return outputs in Demisto's format
Args:
client: Client object with request
args: Usually demisto.args()
Returns:
Outputs
... | 6471170d72bec7dd19d102470e2b29dec2131e17 | 22,295 |
import torch
def fft(input, inverse=False):
"""Interface with torch FFT routines for 3D signals.
fft of a 3d signal
Example
-------
x = torch.randn(128, 32, 32, 32, 2)
x_fft = fft(x)
x_ifft = fft(x, inverse=True)
Parameters
----------
x : te... | 8b7bdfbaeaf712ee8734c7d035f404fd154d3838 | 22,296 |
def dbdescs(data, dbname):
"""
return the entire set of information for a specific server/database
"""
# pylint: disable=bad-continuation
return {
'admin': onedesc(data, dbname, 'admin', 'rw'),
'user': onedesc(data, dbname, 'user', 'rw'),
'viewer': onedesc(data, dbname, 'viewer', 'ro')
} | 895f87300192fbad1045665eef0a08c64c6ba294 | 22,297 |
from datetime import datetime
def format_date(date):
"""Format date to readable format."""
try:
if date != 'N/A':
date = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S').strftime('%d %b %Y')
except ValueError:
logger.error("Unexpected ValueError while trying to format date... | 48d6d426925e45f0c3b92e492efa5d23e1550a2f | 22,298 |
def favor_attention(query,
key,
value,
kernel_transformation,
causal,
projection_matrix=None):
"""Computes FAVOR normalized attention.
Args:
query: query tensor.
key: key tensor.
value: value tensor.
... | b01a9385b321b1bd008a818cba0630cfbb3a93c3 | 22,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.