content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def construct_system(sp, scale=1.0):
"""Construct systems according to job statepoint.
Parameters
----------
sp: dict (from job.sp)
Dictionary contains information necessary to construct a system.
Stored as state of job. The dictionary should resemble:
{"molecule": str,
... | c0f610b527d7d4873d72e46438a9a9b67931f379 | 35,600 |
def _tile_images(imgs, tile_shape, concatenated_image, margin_color=None):
"""Concatenate images whose sizes are same.
@param imgs: image list which should be concatenated
@param tile_shape: shape for which images should be concatenated
@param concatenated_image: returned image. if it is None, new imag... | 0698245a08ce2115fe7154d07f8ccdfb228aca28 | 35,601 |
def true_positive_rate(y_true, y_pred):
"""Returns True Positive Rate.
Wrapper function of metrics_K()
Args:
y_true (Tensorflow Tensor): Array of 'true' 0s and 1s
y_pred (Tensorflow Tensor): Array of predicted 0s and 1s
Returns:
specificity_loss (Tensor): True Positive Rate ([... | 602138bec793f4c80dabf12db987fd75769920f6 | 35,602 |
def create_camera_widget(name):
"""Create a camera control widget"""
obj = create_widget(name)
if not obj.data.vertices:
verts = [(0.275136, 0, -0.275136), (0.359483, 0, -0.148903),
(0.389102, 0, 0), (0.359483, 0, 0.148903),
(0.275136, 0, 0.275136), (0.148903, 0, 0.... | 8cdac505c83a9a90bd6f7c4a415850a9d20d0646 | 35,603 |
def query_related(uri, filter=None, limit=20):
"""
Query for terms that are related to a term, or list of terms, according
to the mini version of ConceptNet Numberbatch.
"""
if uri.startswith('/c/'):
query = uri
elif uri.startswith('/list/') and uri.count('/') >= 3:
try:
... | 18b2908bbe8559388b52697b515e8b1ad23bb3c5 | 35,604 |
import numpy
def chain(pairs):
"""
Generate chain from location pairs.
"""
table, chain = [], []
for i in numpy.unique(numpy.array(pairs).flatten()):
if chain == []:
chain.append(i)
value = i
continue
if i == value + 1:
chain.append... | 01c55e204d56cbef9e08bd509422846bb844c7fe | 35,605 |
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 get_config_from_args(config_dict=None, **kwargs):
"""
Reads arguments and resolves the string configuration to appropriate
class instances.
:param config_file: yaml file containing the configurations
:type config_file: `str`
:return: dictionary of class references
:rtype: `dict`
"""
... | e624bf064c669c17b19020c35c834a863a57048a | 35,609 |
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 Callable
def nose_hoover_invariant(energy_fn: Callable[..., Array],
state: NVTNoseHooverState,
kT: float,
**kwargs) -> float:
"""The conserved quantity for the Nose-Hoover thermostat.
This function is normally used f... | a6c77a4d16ebcd39e4adc811137544d16d522cfe | 35,613 |
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 |
import click
import yaml
import warnings
def parse_config_from_file(file: str) -> MachConfig:
"""Parse file into MachConfig object."""
click.echo(f"Parsing {file}...")
dictionary_config, encrypted = yaml.load(file)
try:
with warnings.catch_warnings():
# Suppress a 'Unknown type Fo... | 263d50027e416168daa9716ab657f70d5ba73714 | 35,616 |
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 |
import sys
def init():
"""
Intialize parameters that will be used in the program.
Parameters
----------
None
Returns
----------
dataset: ndarray
The whole dataset read from the input file.
outFileName: String
Name of output file.
iterNum: int
Number of... | 5b9acd413a168b0f5e3f5978d2a5e7b8b1887790 | 35,624 |
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 |
from re import T
def display_features():
"""
Cut-down version of the Map Viewing Client.
Used as a link from the RHeader.
URL generated server-side
Shows all locations matching a query.
@ToDo: Most recent location is marked using a bigger Marker.
@ToDo: Move to ... | b6c54103d1e6eb5cd2bf8476ac78a6112c072bd1 | 35,638 |
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 json
def serviceCIDR(runner: Runner):
"""
Get service IP range, based on heuristic of constructing CIDR from
existing Service IPs. We create more services if there are less
than 8, to ensure some coverage of the IP range.
"""
def get_service_ips():
services = json.loads(
... | 2855831301bbecd28e8419be1b296525c21127c2 | 35,643 |
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 |
import sys
def read_inference_command():
"""
read inputs from the command line
:return:
"""
cprint('[INFO]', bc.dgreen, 'read inputs from the command')
try:
parser = ArgumentParser()
parser.add_argument("--deezy_mode",
help="DeezyMatch mode",
... | 1f3f46b598b98de276388b2ba747d608f98ddf9f | 35,653 |
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 |
def job_use(jobs, d_from, target, d_to='', use_unit='cpu', job_state='all',
time_ref='', grouper_interval='S', usage_interval='H', serialize_queued='', serialize_running='',
serialize_dist=''):
"""Takes a DataFrame full of job information and
returns usage based on specified unit.
... | 8a456766c9ae2a3b3f4e482f3593ba8d08f35da3 | 35,661 |
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 |
import sys
def get_drive_path(volumename, alldrivelist, drive_type=None):
"""Return the drive letter (windows) or mount point (linux) of a volume's name
volumename is the name of the volume you want the mount point.
alldrivelist is a list of drives or volume:
- Windows: The list should be a list of list, lik... | 4948ecff645cc849a16ad45f7cdc3b5c2c3b8500 | 35,670 |
import os
import asyncio
async def runCmdWithUser(cmd, addToEnv=None) :
"""Runs a command allowing the users to interact with the command and
then returns the return code. Based upon the Python asyncio subprocesses
documentation. """
if addToEnv is not None :
for aKey, aValue in addToEnv.items() :
... | e3c075c9e6ccd946724921f763bfe240fb40e4fe | 35,671 |
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 |
def rose_fig(metdat, catinfo, category=None, vertloc=80, bins=6, nsector=36, ylim=None, noleg=False,normed=True):
"""**Get Wind Rose Figure**.
Plot the wind rose of a given variable (or category of variables) grouped by a given condition (or set of conditions).
Parameters:
1. metdat (Pandas Da... | e46be370c16c93f6eea2e1affe6ad1a270abb064 | 35,681 |
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 json
def _is_status_not_found(error):
"""Decodes the error from the API to check if status is NOT_FOUND.
Args:
error (errors.HttpError): The error response from the API.
Returns:
bool: True if the error is application not found, else False.
"""
if isinstance(error, errors.... | 4f7112b7089674571e0107636a3863a8a2eff90d | 35,683 |
import logging
def get_head(client):
"""get_head(client_socket) -> (head_str, body_u8)
Create a byte buffer, recv once and check if the response filled the
buffer. If it didn't, search for \r\n\r\n (HTTP body start). If found, split
the byte buffer at that point and return the decoded head, and raw b... | 9424e9621a7470ef7ffbba8f9b4107762bcac34a | 35,684 |
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 generate_DML_queries(cursor, dml_mod_values):
"""Generate insert, upsert, update, delete DML statements.
For each table in the database that cursor is connected to, create 4 DML queries
(insert, upsert, update, delete) for each mod value in 'dml_mod_values'. This value
controls which rows will be affected.... | 88e906ec53f3eee0817176bf9e0b87488713bfc6 | 35,692 |
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 |
from typing import List
from typing import Tuple
def cancel_experiment(exp_name: str, runs_to_cancel: List[Run], namespace: str) -> Tuple[List[Run], List[Run]]:
"""
Cancel experiment with a given name by cancelling runs given as a parameter. If given experiment
contains more runs than is in the list of ru... | f75487fa993c52df3d013d94bd29b858bc324884 | 35,698 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.