content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
from typing import Union
from typing import Optional
import importlib
def search_import(
method: str, modules: List[Union[str, ModuleType]]
) -> Optional[object]:
"""
Method has to check if any of `modules` contains
`callable` object with name `method_name`
and return list ... | 14cd9d6c02081915a1de394b041d80c7b6cc518b | 35,606 |
def retrieve_context_connectivity_service_end_point_capacity_total_size_total_size(uuid, local_id): # noqa: E501
"""Retrieve total-size
Retrieve operation of resource: total-size # noqa: E501
:param uuid: ID of uuid
:type uuid: str
:param local_id: ID of local_id
:type local_id: str
:rty... | 7b154007da10064cfd6ed72e4fa6c883697955df | 35,607 |
def identity(n):
"""
Creates a n x n identity matrix.
"""
I = zeroes(n, n)
for i in range(n):
I.g[i][i] = 1.0
return I | 3c59a042f91dfe8778a9676436a26d14b8db1ed9 | 35,608 |
def mnist_test_labels_file():
"""
Train images of MNSIT.
:return: filepath
:rtype: str
"""
return data_file('mnist/test_labels', HDF5_EXT) | 48bd7426fd89f4f2f8319c7c3cba4a62ab33813d | 35,610 |
def is_eval_epoch(cur_epoch):
"""Determines if the model should be evaluated at the current epoch."""
return cfg.TRAIN.EVAL_PERIOD != -1 and (
(cur_epoch + 1) % cfg.TRAIN.EVAL_PERIOD == 0 or
(cur_epoch + 1) == cfg.OPTIM.MAX_EPOCH
) | 41f5375aab3147371eaf7862dcc5b2919e47f46a | 35,611 |
from datetime import datetime
def utc_now_to_file_str():
"""
Format UTC now to _YYYYmmdd_HHMMSS
:return:
"""
return datetime.datetime.strftime(datetime.datetime.utcnow(), '_%Y%m%d_%H%M%S') | 3f41612f871d6a5bd2b55156e9a418e5baee52cb | 35,612 |
from typing import Union
from typing import cast
def intersect1d(
pda1: groupable, pda2: groupable, assume_unique: bool = False
) -> Union[pdarray, groupable]:
"""
Find the intersection of two arrays.
Return the sorted, unique values that are in both of the input arrays.
Parameters
---------... | a5408d3e738d88fb76e355ec9acf8a26e3c6b5aa | 35,614 |
def less_or_equal(left: ValueOrExpression, right: ValueOrExpression) -> Expression:
"""
Constructs a *less than or equal to* expression.
"""
return Comparison(
operators.ComparisonOperator.LE, ensure_expr(left), ensure_expr(right)
) | f790a117516c1ecd90fdcc289e56050449a106c4 | 35,615 |
def build_birnn_multifeature_coattention_model(
voca_dim, time_steps, num_feature_channels, num_features, feature_dim, output_dim, model_dim, atten_dim, mlp_dim,
item_embedding=None, rnn_depth=1, mlp_depth=1,
drop_out=0.5, rnn_drop_out=0., rnn_state_drop_out=0.,
trainable_embedding=False... | f212f748323136ec994035d8b71d330f5e02b601 | 35,617 |
def splitext(value):
"""
Return a filename sans extension. Alias to os.splitext.
"""
return pathsplitext(value)[0] | b5a72e03895e32903ac912d8e1527d659b377bd9 | 35,618 |
def normspec(*specs, smooth=False, span=13, order=1):
"""
Normalize a series of 1D signals.
**Parameters**\n
*specs: list/2D array
Collection of 1D signals.
smooth: bool | False
Option to smooth the signals before normalization.
span, order: int, int | 13, 1
Smoothing pa... | 9fa751fe0cfada0114ba071135399a1ea8a461c5 | 35,619 |
import pickle
def load():
"""
Load the bibmanager database of BibTeX entries.
Returns
-------
List of Bib() entries. Return an empty list if there is no database
file.
Examples
--------
>>> import bibmanager.bib_manager as bm
>>> bibs = bm.load()
"""
try:
with open(u.BM_DATABASE, 'rb'... | 501adedfb1bb5a4203351ea5ab0acd3e9b495780 | 35,620 |
def repeat_n_m(v):
"""Repeat elements in a vector .
Returns a vector with the elements of the vector *v* repeated *n* times,
where *n* denotes the position of the element in *v*. The function can
be used to order the coefficients in the vector according to the order of
spherical harmonics. If *v* i... | e26cec345f4ed88a64d85452f518b5d497dc0f1e | 35,621 |
def contingency(cont_table=None, alpha=0.05, precision=4):
"""
Check RULE of FIVE before running the test
>>> return chi2, p, dof, ex
"""
chi2, p, dof, ex = stats.chi2_contingency(cont_table, correction=False)
chi2_cv = stats.chi2.ppf(1 - alpha, dof)
flag = False
if p < alpha:
fl... | 3006636096be34032de612b1272cd508ae312b42 | 35,622 |
def smp_dict():
"""Returns a dictionary containing typical options for a generic Sample object"""
out = base_dict()
out['mro']['current'] = ['Sample']
out['name']['current'] = 'Sample'
ao(out, 'idx', 'Integer', attr=['Hidden'])
ao(out, 'ii', 'Integer', attr=['Hidden'])
ao(out, 'initialDimens... | 7ef58042c2826591f2fb5ba21b055f334528b157 | 35,623 |
def setup():
"""
Connect to the Arango database and Elasticsearch.
Returns
-------
Connection, Database, list
1. The connection to Elasticsearch
2. The ArangoDB database that holds the collection
3. The list of fields that are take over from ArangoDB to Elasticsearch
Ra... | f140a72a1e05d34a810bb7ef8ea3ae855c0307f6 | 35,625 |
def test_timedelta_tests():
"""These test cases are taken from CPython's Lib/test/datetimetester.py"""
# Create compatibility functions so rest of test can be pasted with minimal
# changes
def eq(a, b):
assert a == b
def td(days=0, seconds=0, microseconds=0):
return TimeDelta(days=d... | dc61cd77621a3e8a7b1ffd9999a147c84af1da59 | 35,626 |
def shorten_line(line: Line, intersections: list[Matchstick], gw: GameWindow) -> Line:
"""
Shorten a line so that it fits nicely within the row and doesn't get too close to adjacent sticks when drawn
:param line: the line to shorten
:param intersections: the sticks that the line intersects with
:param gw: th... | 381c70da0e5ee740e1c563e033d851e920e62702 | 35,627 |
def uprev_overlays(overlays, build_targets=None, chroot=None, output_dir=None):
"""Uprev the given overlays.
Args:
overlays (list[str]): The list of overlay paths.
build_targets (list[build_target_lib.BuildTarget]|None): The build targets
to clean in |chroot|, if desired. No effect unless |chroot| is... | 0190e28ff270596cd2829c7956044a4af69fb328 | 35,628 |
import math
def find_closest_pucker(phi, theta, pucker_dict):
"""
Calculated based on cord length:
delta_x = sin(phi2) * cos(theta2) - cos(ph1)*cos(theta1)
delta_y = sin(phi2) * sin(theta2) - cos(phi1)*sin(theta1)
delta_z = cos(phi2) - cos(phi1)
chord_length = sqrt( delta_x^2 + delta_y^2 + del... | 224395dad4514062e6e065e8506c64e06832bb9d | 35,629 |
def signal_ramp(k_start):
"""Signal generator for a ramp signal
Parameters
----------
k_start : SignalUserTemplate
the sampling index as returned by counter() at which the ramp starts increasing.
Returns
-------
SignalUserTemplate
the output signal
Details
-------
... | 045d1e8530993e47c9da2bbfb38105c86007ba37 | 35,630 |
def pooling_layer(inputs, pooling=constants.MAXPOOL, pool_size=2, strides=2,
name=None):
"""
Args:
inputs: (4d tensor) input tensor of shape
[batch_size, height, width, n_channels]
pooling: (Optional, {AVGPOOL, MAXPOOL}, defaults to MAXPOOL) Type of
pooling to be used, which... | 856c4c9c378d11764f2885defe433d1b9ec85814 | 35,631 |
import types
def test_equal_ImageDecoderSlice_ImageDecoder():
"""
Comparing results of pipeline: (ImageDecoder -> Slice), with the same operation performed by fused operator
"""
batch_size =128
eii = ExternalInputIterator(128)
pos_size_iter = iter(eii)
class NonFusedPipeline(Pipeline)... | 6dc72175560dba39d54a03da9aaaca67e6cf16c9 | 35,632 |
from typing import Union
def count_tiles(reader_or_writer: Union[BioReader, BioWriter]) -> int:
""" Returns the number of tiles in a BioReader/BioWriter.
"""
tile_size = TILE_SIZE_2D if reader_or_writer.Z == 1 else TILE_SIZE_3D
num_tiles = (
len(range(0, reader_or_writer.Z, tile_size)) *
... | 1e70208c4269dc9cbee3d6926283a78554fcac44 | 35,633 |
import re
def fn(groups, lsv_fn):
"""Regular expression did not contain a match"""
field, pattern = groups
route_regex = re.compile(pattern)
return lambda data: route_regex.search(str(lsv_fn(data, field))) == None | 65667e58af7e9e6bb4e38d28b267d60e9bc6bd46 | 35,634 |
import glob
import random
def airq_data_loader(normalize="none"):
"""Function to load the Air Quality dataset into TF dataset objects
The data is loaded, normalized, padded, and a mask channel is generated to indicate missing observations
The raw csv files can be downloaded from:
https://... | c70217ed045633d39b7758bfc00ede6aaa483c58 | 35,635 |
def get_living_neighbors(i, j, generation):
"""
returns living neighbors around the cell
"""
living_neighbors = 0 # count for living neighbors
neighbors = [(i-1, j), (i+1, j), (i, j-1), (i, j+1),
(i-1, j+1), (i-1, j-1), (i+1, j+1), (i+1, j-1)]
for k, l in neighbors:
... | 437229b8152c3b2ce5b90ef6ddef83daa5c24a85 | 35,636 |
def hook_makeOutline(VO, blines):
"""Return (tlines, bnodes, levels) for Body lines blines.
blines is either Vim buffer object (Body) or list of buffer lines.
"""
Z = len(blines)
tlines, bnodes, levels = [], [], []
tlines_add, bnodes_add, levels_add = tlines.append, bnodes.append, levels.append
... | b755b6580e983f5758bb301318b862bab083a240 | 35,637 |
def domain_min():
""" Variable evaluator that represents the minimum value in the current domain
of the variable chosen by the search.
Returns:
An evaluator of integer variable
"""
return CpoFunctionCall(Oper_domain_min, Type_IntVarEval, ()) | 9dadab36bac75053e5b62012c27a9e1a1c484af7 | 35,639 |
def StrToList(val):
""" Takes a string and makes it into a list of ints (<= 8 bits each)"""
return [ord(c) for c in val] | 79ee38dc4952b677896a77379c3cccca8f74eb2c | 35,640 |
def our_completion_DFA(states, alphabet, transitions,
initialState, finalStates):
""" For every transition (from, to, c) adds every transition
(from, to, s') where s' represents c plus every other symbol """
table = powerset_table(alphabet)
new_alphabet = alphabe... | 851b96bd218cda81197c636f942488404a11654e | 35,641 |
def createCopy(source):
"""Link the source set to the destination
If one does not find the value in the destination set,
search will go on to the source set to get the value.
Value from source are copy-on-write. i.e. any try to
modify one of them will end up putting the modified value
in t... | 0cd045dff53f0dcda2b9b3d86d595fb6d4b7bd25 | 35,642 |
import torch
def generate_data(network_list, data_set, Lb, Ub, total_data_num, NUM):
"""
NUM为需要生成的数据量
"""
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = "cpu"
# 网络使用
total_predicts_data = []
for k in range(len(data_set)):
model = network_lis... | 9e13ec3d722930883fdde7874731d7325f2f987a | 35,644 |
from typing import Any
def convert_audio(
in_sound: ArrayLike, in_rate: int, *, out_rate: int, out_format: DTypeLike, out_channels: int
) -> NDArray[Any]:
"""Convert an audio sample into a format supported by this device.
Returns the converted array. This might be a reference to the input array if no co... | 5069db14d2cca3233ecc96d57874c6badf08b341 | 35,645 |
def normalize_tags(string):
"""Return a list of normalized tags from a string with comma separated
tags"""
tags = string.split(',')
result = []
for tag in tags:
normalized = normalize(tag)
if normalized and not normalized in result:
result.append(normalized)
return r... | 6a03e6681246709e33d4a34c169158d02b4d191c | 35,646 |
def basemz(df):
"""
The mz of the most abundant ion.
"""
# returns the
d = np.array(df.columns)[df.values.argmax(axis=1)]
return Trace(d, df.index, name='basemz') | 8843b0065e8de383743a5c0442246a01edd1de23 | 35,647 |
def M_matrix_old(s, c, m, l_max):
"""Legacy function. Same as :meth:`M_matrix` except trying to be cute
with ufunc's, requiring scope capture with temp func inside
:meth:`give_M_matrix_elem_ufunc`, which meant that numba could not
speed up this method. Remains here for testing purposes. See
document... | 2d6576c56663d6cd7226d02b6d794305bb943ae7 | 35,648 |
def create_model(modelfunc, fname='', listw=[], outfname=''):
""":modelfunc: is a function that takes a word and returns its
splits. for ngram model this function returns all the ngrams of a
word, for PCFG it will return te split of the password.
@modelfunc: func: string -> [list of strings]
@fnam... | 7a6494b8017829e94fbfe364e07267b4f882a0b2 | 35,649 |
from typing import Collection
def iterable_to_wikitext(items: Collection[object]) -> str:
"""Convert iterable to wikitext."""
if len(items) == 1:
return f"{next(iter(items))}"
text = ""
for item in items:
text += f"\n* {item}"
return text | b4b082eb25e20deac738ae85d4141a0d3a98c349 | 35,650 |
def ElemMatch(q, *conditions):
"""
The ElemMatch operator matches documents that contain an array field with at
least one element that matches all the specified query criteria.
"""
new_condition = {}
for condition in conditions:
if isinstance(condition, (Condition, Group)):
... | cd45f06cc5bd19ecfc2539ec7de0f43d8e0bb05b | 35,651 |
from typing import List
def get_links(client: SymphonyClient) -> List[Link]:
"""This function returns all existing links
Returns:
List[ `pyinventory.common.data_class.Link` ]
Example:
```
all_links = client.get_links()
```
"""
links = Links... | 683f605239ade48e8938d9e7a23c3033a533abe6 | 35,652 |
def set(data,c):
"""
Set Data to a Constant
Parameters:
* data Array of spectral data.
* c Constant to set data to (may be complex)
"""
data[...,:]=c
return data | cff2592b3973bbd3f9a1a4dbaa6d6ba4b99260bc | 35,654 |
def browse_announcements():
"""
This function is used to browse Announcements Department-Wise
made by different faculties and admin.
@variables:
cse_ann - Stores CSE Department Announcements
ece_ann - Stores ECE Department Announcements
me_ann - Stores ME Department Announcement... | eaa72fbbd845c2b1b0771659fab2c0f772932d1e | 35,655 |
def set_point_restraint(self,point,restraints):
"""
params:
point: str, name of point
restraints: bool, list of 6 to set restraints
return:
status of success
"""
try:
assert len(restraints)==6
pt=self.session.query(Point).filter_by(name=point).first()
... | 1b512de2fc9dd1a9f57e85cab65eb029be1e036c | 35,656 |
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6) -> float:
"""Numpy implementation of the Frechet Distance.
The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
and X_2 ~ N(mu_2, C_2) is
d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
Stable... | 01a7434325192472add5030581df17d79a79b5e0 | 35,657 |
from typing import Any
from typing import Dict
def get_meta(instance: Any) -> Dict[str, Any]:
"""
Returns object pjrpc metadata.
"""
return getattr(instance, '__pjrpc_meta__', {}) | 1357cab8698297b8ba9c10423e4c0473690cb8f0 | 35,658 |
def initial_pop(size, password):
"""
Generate a population consisting of random words, each with the same
length as the password, and the population has the size specified.
"""
return [word_generate(len(password)) for _ in range(size)] | 08e797996928e94565a822c7b2e5075145568edd | 35,659 |
from pathlib import Path
def getAllComicImagePaths(source = "./comic_pages"):
"""Collect an ordered list of comic page images."""
p = Path(source)
files = [x for x in p.iterdir() if x.is_file()]
return [f for f in sorted(files) if _isImage(f)] | 1f9a560085ec090352d3a9e48c2d3521a2ee9bb5 | 35,660 |
import requests
def login():
"""[summary]
Returns:
[type]: [description]
"""
if current_user.is_authenticated:
return flask.redirect(flask.url_for("bp.index"))
if flask.request.method == "POST":
if flask.request.form["submit_button"] == "GOOGLE LOGIN":
# Find ... | e25058f928b586b75a022b6438f882e24a596f1c | 35,662 |
def settings_page():
"""
The data web pages where you can download/delete the raw gnss data
"""
return render_template("settings.html") | 6c12dedb13ac88ebda7c67eabe25a73da54eaa21 | 35,663 |
def SaveNumResults(doc:NexDoc, fileName):
"""Saves the numerical results to a text file with the specified name."""
return NexRun("SaveNumResults", locals()) | 9a1750d3bf92e2a5a459da5563705abe9e177bb0 | 35,664 |
def load_laplacian(n=0):
"""
Laplacians have these normalizations (from Ashish Raj):
n=0: L0 = diag(rowdegree) - C;
n=1: L1 = eye(nroi) - diag(1./(rowdegree+eps)) * C;
n=2: L2 = eye(nroi) - diag(1./(sqrt(rowdegree)+eps)) * C* diag(1./(sqrt(coldegree)+eps)) ;
n=3: L3 = eye(nroi) -... | 188f5e3d920d4a7a660b4f2133c6675888efd7f8 | 35,665 |
def parse_host_port(address, default_port=None):
"""
Parse an endpoint address given in the form "host:port".
"""
if isinstance(address, tuple):
return address
def _fail():
raise ValueError("invalid address %r" % (address,))
def _default():
if default_port is None:
... | 883f09d67e6be048b98806f0f1bbb5e00472c47b | 35,666 |
def free_residents(residents_prefs_dict, matched_dict):
"""
In this function, we return a list of resident who do not have empty prefrences list and unmatched with any hospital.
"""
fr = []
for res in residents_prefs_dict:
if residents_prefs_dict[res]:
if not (any(res in mat... | b07991f6286be3c0e4b163ca2f0991630f910b4c | 35,667 |
def index():
"""View of providing a feedback from the client side"""
form = FeedbackForm()
if form.validate_on_submit():
try:
data = {
'email': form.email.data,
'title': form.title.data,
'content': form.content.data,
}
... | 5974112cd5b87bfa204b73080346e50e63fb5ece | 35,668 |
def predict_increment(big_n, obs_t, mu, basis_lag, coef):
"""
This should return predicted increments
between successive observations
"""
rate_hat = predict_intensity(
big_n, obs_t, mu, basis_lag, coef
)
increment_size = np.diff(obs_t)
return rate_hat * increment_size | dbb17ac3538e25c1da4e426c7629f6c9c05737a1 | 35,669 |
def _dualprf_error_unwrap(data_ma, ref_ma, err_mask, pvel_arr, prf_arr):
"""
Finds the correction factor that minimises the difference between
the gate velocity and the reference velocity
Parameters
----------
data_ma : masked array
Data
ref_ma : masked array
Reference data
... | 60230960aa37024f78d26e4df107ab22c91dafce | 35,672 |
import pickle
def load(directory):
"""Loads pkl file from directory"""
with open(directory, 'rb') as f:
data = pickle.load(f)
return data | d500c6f717535ee95f452abd435be4d8688a59a4 | 35,673 |
from typing import Callable
from typing import Iterable
def choose(
chooser: Callable[[_TSource], Option[_TResult]]
) -> Callable[[Iterable[_TSource]], Iterable[_TResult]]:
"""Choose items from the sequence.
Applies the given function to each element of the list. Returns
the list comprised of the res... | 388a98d8c9a7b5cf34a19515a66a72216ba64817 | 35,674 |
from .src import connect_s_fast
def connect_fast(ntwkA: Network, k: int, ntwkB: Network, l: int) -> Network:
"""
Connect two n-port networks together (using C-implementation)
Specifically, connect ports `k` on `ntwkA` to ports
`l` thru on `ntwkB`. The resultant network has
`(ntwkA.nports + ntwkB... | 2e2fe2f57d5bc26ee3f6b1d11583f96d9f9c1ebc | 35,675 |
import numpy
def interleave(left, right):
"""Convert two mono sources into one stereo source."""
return numpy.ravel(numpy.vstack((left, right)), order='F') | 29833d8b4516de2bdab9a33246cb165556d287bc | 35,676 |
from typing import Tuple
from typing import OrderedDict
from operator import concat
def DIN(
item_seq_feat_group: EmbdFeatureGroup,
other_feature_group: FeatureGroup,
dnn_hidden_units: Tuple[int] = (64, 32, 1),
dnn_activation: str = "dice",
dnn_dropout: float = 0,
dnn_bn: bool = False,
l2_... | da49559837584b53989e4d0989a09796f130fb51 | 35,677 |
def get_seconds(time_string):
"""
Convert e.g. 1m5.928s to seconds
"""
minutes = float(time_string.split("m")[0])
seconds = float(time_string.split("m")[1].split("s")[0])
return minutes * 60.0 + seconds | 5a729d24ab6c437fca536cae8ac3d34a45bb9054 | 35,678 |
import time
def generate_features_for_all_nodes(n_feature, features_filename):
"""
generates node-list with features for RiWalk-NA
"""
# generate node-features-df
print("\tFeatures generation starts.")
start_time = time.time()
nodes_all_features_df = n_feature.gen_features_all_nodes()
... | e1f65c523a3140aa718ff867751657e04945fc38 | 35,679 |
def sharesnet34(**kwargs):
"""
ShaResNet-34 model from 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, ... | 50706761947f605fc0716740b07a661a6ad91277 | 35,680 |
import requests
from bs4 import BeautifulSoup
def query_spikeins(accession):
"""
Query spikeines IDs from Encode Websites
"""
query = f'https://www.encodeproject.org/experiments/{accession}/'
page = requests.get(query)
soup = BeautifulSoup(page.content, 'html.parser')
for div in soup.find... | c05d9480bba0b052a44b4a683da4ef16fa01e6fc | 35,682 |
import tqdm
def pinnuts(f, M, Madapt, theta0, delta=0.6, epsilon=None):
"""
Implements the multinomial Euclidean Hamiltonian Monte Carlo sampler
described in Betancourt (2016).
Runs Madapt steps of burn-in, during which it adapts the step size
parameter epsilon, then starts generating samples to ... | 242c48e97137eb5ca843a3254c35b7e921d32703 | 35,685 |
from .source import importable, getname
import tempfile
def dump_source(object, **kwds):
"""write object source to a NamedTemporaryFile (instead of dill.dump)
Loads with "import" or "dill.temp.load_source". Returns the filehandle.
>>> f = lambda x: x**2
>>> pyfile = dill.temp.dump_source(f, alias='_f')
... | 978ed048c875856a38c711a06fcbb063b8757023 | 35,686 |
async def remove_role_requirement(reaction_role: _ReactionRole, ctx: _Context, abort_text: str) -> _Tuple[bool, bool]:
"""
Returns: (success: bool, aborted: bool)
"""
role_requirement = await inquire_for_role_requirement_remove(ctx, reaction_role.role_requirements, abort_text)
if role_requirement:
... | 0daf6b243a685e993fc110e93cb1e4188208db93 | 35,687 |
def get_predicates():
"""
I'm not quite sure how to best get at all the predicates and tag them as relations with id's
"""
"""
results = GolrAssociationQuery(
rows=0,
facet_fields=['relation']
).exec()
facet_counts = results['facet_counts']
relations = facet_c... | 2b0ec74aa91b099278c0fde7479dd90665897670 | 35,688 |
def study_dir(study_name: str) -> str:
"""(Deprecated) old name for storage directory
Args:
study_name: storage name
Returns:
Absolute path of storage directory
Warnings:
Deprecated in favor of :func:`storage_dir`
"""
return storage_dir(study_name) | 7b0183fe16eea9b711fb023bd7c24c761f184885 | 35,689 |
def to_adjacent_matrix(m, threshold=5e-3):
"""given a numeric dxd matrix, convert it adjcent matrix
Args:
m: dxd ndarray
threshold: (Default value = 5e-3)
Returns:
dxd binary adjacent matrix
"""
m_ = m.copy()
m_[np.where(abs(m) > threshold)] = 1
# otherwise make it zer... | 61349dddc057ce0f3f46157c2d89dc4d82dfdef2 | 35,690 |
import re
def hour_min_to_sec(hm):
"""Convert string in format hh:mm to seconds"""
h, m = re.match(r'(\d{1,2}):(\d{2})', hm).groups()
return 3600 * (int(h) + float(m) / 60.) | 4b186810c1c4fe6f9767b5e3914e8869168fffbf | 35,691 |
def create_target(hosts, name=None, comment=None):
""" In short: Create a target.
The client uses the create_target command to create a new target.
"""
if name is None:
name = hosts
root = etree.Element("create_target")
tree_name = etree.SubElement(root, "name")
tree_comment = etre... | 0f1fca078f9a13f9cf71e36b80dcb98211ae125b | 35,693 |
import json
def get_slow_queries(**kwargs):
"""Simple function to construct and pass the args
for a redis LRANGE query on the slow_queries log."""
pipe = redis.pipeline()
resp = {}
hash_key='SLOW_QUERIES'
# minus 1 from the actual integer passed for row limit
pipe.lrange(hash_key, 0, kwa... | 27bbc3910da8055682de284e503dee6c0c6419bd | 35,694 |
def getEscInfo(esc_record):
"""Extracts ESC information from a ESC record.
Args:
esc_record: A ESC record (dict of schema |EscSensorRecord|)).
Returns:
A tuple of:
esc_point: A (longitude, latitude) tuple.
esc_info: A |EscInformation| tuple.
"""
esc_install_params = esc_record['installati... | ad3e3adaf15ff9ba4cf7f34ec70afb24a9085f63 | 35,695 |
def crcremainder(data, key):
"""
crcremainder Function
Function to calculate the CRC
remainder of a CRC message.
Contributing Author Credit:
Shaurya Uppal
Available from: geeksforgeeks.org
Parameters
----------
data: string of bits
The bit-str... | 6c0e401014d1a26a80c14f26f6b43a126bc0c17e | 35,696 |
def test_method_nesting(server):
"""Test that we correctly nest namespaces"""
def handler(message):
return {
"jsonrpc": "2.0",
"result": True if message.params[0] == message.method else False,
"id": 1,
}
server._handler = handler
assert server.nest.te... | 9c8264f357e0e958b94669ef82ee70b3efff7e8c | 35,697 |
def merge_nn_dicts(
peaks, n_neighbors, peaks_in_chunk_idx_list, knn_indices_list, knn_distances_list
):
"""merge together peaks_in_chunk_idx_list and knn_indices_list
to build final graph
Args:
peaks (_type_): array of peaks
n_neighbors (_type_): number of neighbors
peaks_in_ch... | 030ff04b74f532507945c2dfd6570836e6ece941 | 35,699 |
import io
def bytes_to_PCM_16bits(bytes, start=0, end=None):
"""
Transform audio file to a format readable by scipy, ie. uncompressed PCM 16-bits.
Support transformation from any format supported by ffmpeg.
"""
try:
audiofile = AudioSegment.from_file(bytes)
except Exception as e:
... | cac297a610b90a3459542def406cd62f58dd86bd | 35,700 |
import keras
from keras.datasets import cifar10
from keras.utils import np_utils
def data_cifar10(train_start=0, train_end=50000, test_start=0, test_end=10000):
"""
Preprocess CIFAR10 dataset
:return:
"""
global keras
if keras is None:
# These values are specific to CIFAR10
img_rows = 32
img_cols ... | 1a23e78aa1cb873f18b31df616f467cea8db3f5e | 35,702 |
def create_log_group_arn(logs_client, hosted_zone_test_name):
"""Return ARN of a newly created CloudWatch log group."""
log_group_name = f"/aws/route53/{hosted_zone_test_name}"
response = logs_client.create_log_group(logGroupName=log_group_name)
assert response["ResponseMetadata"]["HTTPStatusCode"] == 2... | 79113cc7c9ac844c4d38cd1780b38d14a112b40d | 35,703 |
def _make_filetags(attributes, default_filetag = None):
"""Helper function for rendering RPM spec file tags, like
```
%attr(0755, root, root) %dir
```
"""
template = "%attr({mode}, {user}, {group}) {supplied_filetag}"
mode = attributes.get("mode", "-")
user = attributes.get("user", "-"... | 56898ec1fc974721150b7e1055be3ab3782754a2 | 35,704 |
from typing import Union
def button_callback(update: Update, context: CallbackContext) -> Union[None, str]:
"""Обработчик запросов обратного вызова"""
query = update.callback_query
query.answer()
message = query.data.split()
return callbacks[message[0]](update=update, context=context, query=query,... | 0c9e04f29fd931288cdb0d4cab0c732b03fd8fa0 | 35,705 |
def has_banking_permission(data):
""" CHecks to see if the user hs the correct permission. Based on Castorr91's Gamble"""
if not Parent.HasPermission(data.User, CESettings.BankingPermissions, CESettings.BankingPermissionInfo):
message = CESettings.PermissionResp.format(data.UserName, CESettings.Banking... | 39dcb62c36e2f89a51503902db183a4c128128e6 | 35,706 |
from datetime import datetime
def calc_temps(start='start_date'):
"""min, max, avg temp for start range"""
start_date = datetime.strptime('2016-08-01', '%Y-%m-%d').date()
start_results = session.query(func.max(Measurements.tobs), \
func.min(Measurements.tobs),\
... | 78aaa7721c7f0d83843d85af55d2262faad69cdc | 35,707 |
def reindex(tensor, shape, displacement=.5):
"""
Re-color the given tensor, by sampling along one axis at a specified frequency.
.. image:: images/reindex.jpg
:width: 1024
:height: 256
:alt: Noisemaker example output (CC0)
:param Tensor tensor: An image tensor.
:param list[int... | a9aa0e323b7e2ee4f06e4f6a44fecb0c57e1acb7 | 35,708 |
def test_dal_getitem_access():
"""
Verify `__getitem__` is identical to `__getattr__`
"""
expected = "foo"
class SampleService(Service):
def sample_method(self):
return expected
dm = _BaseDataManager()
dm.register_services(sample=SampleService())
with dm.context()... | 8202385241a8ec7f4c4634b644dd8f459f5642cf | 35,709 |
def seq_to_matrix(seq, letter_to_index=None):
"""Convert a list of characters to an N by 4 integer matrix
Parameters
----------
seq : list
list of characters A,C,G,T,-,=; heterozygous locus is separated by semiconlon. '-' is filler
for heterozygous indels; '=' is homozygous deletions
... | f43e406bc8efecc0b00ec7a22b57ebee4e16efc2 | 35,710 |
def plot(
title: str,
body_system: Body_System,
x_start: float = -1,
x_end: float = 1,
y_start: float = -1,
y_end: float = 1,) -> None:
"""
Utility function to plot how the given body-system evolves over time.
No doctest provided since this function does not have a return value.... | 33cdeee3be9625c82643d3cefa75a5d554b0f54e | 35,712 |
from caffe2.python import workspace, core
def GetGPUMemoryUsageStats():
"""Get GPU memory usage stats from CUDAContext/HIPContext. This requires flag
--caffe2_gpu_memory_tracking to be enabled"""
workspace.RunOperatorOnce(
core.CreateOperator(
"GetGPUMemoryUsage",
[],
... | 84cd6d5b4786f666bfa756addf4d3010af6737f9 | 35,713 |
import typing
def from_jsonable(return_type: typing.Any, obj: typing.Any) -> typing.Any:
"""Return an instance of the specified 'return_type' that has been
constructed based on the specified 'obj', which is a composition of python
objects as would result from JSON deserialization by the 'json' module.
... | 6e7df09a53c116fe48cabb6e18587f297640e2cc | 35,714 |
def _convert_symbol(op_name, inputs, attrs,
identity_list=None,
convert_map=None):
"""Convert from mxnet op to nnvm op.
The converter must specify some conversions explicitly to
support gluon format ops such as conv2d...
Parameters
----------
op_name : st... | bf525a15b131369cb5f77d4681cab374afc1287c | 35,715 |
from typing import List
from typing import Union
def non_parametric_double_ml_learner(df: pd.DataFrame,
feature_columns: List[str],
treatment_column: str,
outcome_column: str,
... | 0a78944ecf81d5d40114a517dbae587bfc5bb13c | 35,716 |
def convert_image_cv2_to_cv(image, depth=cv.IPL_DEPTH_8U, channels=1):
"""
Converts an OpenCV2 wrapper of an image to an OpenCV1 wrapper.
Source: http://stackoverflow.com/a/17170855
Args:
image: image used by OpenCV2
depth: depth of each channel of the image
... | 9a803eedadbb1082d8614f823b6d4063772fdaa3 | 35,717 |
def split_game_path(path):
"""Split a game path into individual components."""
# filter out empty parts that are caused by double slashes
return [p for p in path.split('/') if p] | 9b939058aa7f8b3371d3e37b0252a5a01dba4e7b | 35,719 |
def create_complete_dag(workbench: Workbench) -> nx.DiGraph:
"""creates a complete graph out of the project workbench"""
dag_graph = nx.DiGraph()
for node_id, node in workbench.items():
dag_graph.add_node(
node_id,
name=node.label,
key=node.key,
versio... | 026cb6ab7e168f6c4f1d84e7ae574d4b62bbbfe2 | 35,721 |
import csv
def read_single_disk(image_id):
""" Stores a single image to disk.
Parameters:
---------------
image_id integer unique ID for image
Returns:
----------
image image array, (32, 32, 3) to be stored
label associated meta data, int lab... | 094b8b98fba85a224d613efc7623ed497129bfc7 | 35,723 |
import click
def try_get_balance(agent_config: AgentConfig, wallet: Wallet, type_: str) -> int:
"""
Try to get wallet balance.
:param agent_config: agent config object.
:param wallet: wallet object.
:param type_: type of ledger API.
:retun: token balance.
"""
try:
if type_ no... | 5cf32708c493b54a4950eee01144259be3be481d | 35,724 |
def test_self_iat_hook_success():
"""Test hook success in single(self) thread"""
pythondll_mod = [m for m in windows.current_process.peb.modules if m.name.startswith("python") and m.name.endswith(".dll")][0]
RegOpenKeyEx = [n for n in pythondll_mod.pe.imports['advapi32.dll'] if n.name == function_to_hook][0... | 682a8c251d0dee3e923f92bdfe0b4402d69c6b69 | 35,725 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.