content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def log_access(request, location=None, reason=None):
"""
Checkin form used by LNL members when accessing a storage location (contact tracing)
:param location: The name of the location (must match a location that contains equipment)
:param reason: Should be set to "OUT" if user is checking out of a loca... | 401b08bd1bd736551aac33dc5855e250e88d4944 | 43,600 |
import os
import re
import pickle
def compute_microstructure(molten_salt_system, ensemble, start, stop, step, nbins=500, rdf_flag=True, cn_flag=True, adf_flag=True):
"""
Description:
compute microstructure info including radial distribution fuction(rdf), coordination number(cn) and angle distribution function(a... | 3f2ee881223736a410a9461f7ada157cfcbf4318 | 43,601 |
import array
import logging
def oep(atoms,orbs,energy_func,grad_func=None,**kwargs):
"""oep - Form the optimized effective potential for a given energy expression
oep(atoms,orbs,energy_func,grad_func=None,**kwargs)
atoms A Molecule object containing a list of the atoms
orbs A matrix of ... | a6036f391aa0b3435550abcfcf69d70044477267 | 43,602 |
from jeepney.bindgen import code_from_xml # type: ignore[import]
from typing import Generator
def generate(conn: znc.Socket, save_path: str) -> Generator[None, None, str]:
"""Dump latest Signal interface description to file.
See ``jeepney.bindgen.generate``.
"""
message = yield from send_dbus_messa... | 863037b02f8133972d8238e0099b4d9eaa4baa48 | 43,603 |
import copy
import torch
def deepfool(image, net, device, num_classes=10, overshoot=0.02, max_iter=50):
"""
:param image: 输入图像:1x1x28x28
:param net: network
:device: cuda or cpu
:param num_classes: num_classes (limits the number of classes to test against, by default = 10)
:par... | db92768fda05fe8e37856082e4e353bc7184b304 | 43,604 |
def preprocess_cost_reward(data, ind_trace, steps_per_epoch, window=1):
"""Preprocess the given cost and the given reward and return
the mean, mean+std and mean-std values as metrics. This function
requires data from a single trace (execution). EVolution with respect
to the number of epochs.
"""
... | a89d477900e9dd1ff858baaff30c7d93b71edc22 | 43,605 |
def is_valid_url(string: str) -> bool:
"""Returns boolean describing if the provided string is a url"""
result = urlparse(string)
return all((result.scheme, result.netloc)) | a111a1ac4d4821d5baa00f3053f808f3ffdff5d6 | 43,606 |
import sys
def check_nan(data_dict):
"""Remove the curve if ``nan`` is in ``x`` or ``y`` data.
Parameters
----------
data_dict : dict
Report data dictionary.
Returns
-------
data_dict : dict
Checked report data dictionary.
"""
for plot_name in data_dict.keys():
... | b4de043774c8e36069112bec549e57786cf6c149 | 43,607 |
def MLP(
input_shape,
output_size,
loss,
optimizer,
hidden_layers=[32, 16, 8],
dropout=0.0,
activation="linear",
out_activation="linear",
):
"""Multi Layer Perceptron.
Args:
input_shape (tuple): Shape of the input data
output_size (int): Number of neurons of the ... | 0db53ded4d0e7ac87f2ddb296bffdacec586c285 | 43,608 |
def _get_crm_resource_v1(credentials):
"""
Instantiates a Google Compute Resource Manager v1 resource object to call the Resource Manager API.
See https://cloud.google.com/resource-manager/reference/rest/.
:param credentials: The GoogleCredentials object
:return: A CRM v1 resource object
"""
... | adc1f2576404e67f95262711ab1089ca80ed5153 | 43,609 |
def line_intersection(lines, lines2, abs_tolerance = 1e-14, full_output = False):
"""
Generic Line to line intersection function
:param lines: The first set of lines, with shape [n_lines, 2, 2] where lines[i, 0, :] is the first point of the ith line
:type line: np.ndarray
:param lines2: Th... | d68d07499da2bbd0e8532862abf1181fc86ab800 | 43,610 |
import re
def get_tag_name(tag):
"""
Get the name field of a tag:
{#x:name_field:t}
Parameters
----------
tag: str
Returns
-------
name: str
"""
name = re.findall(NAME_REGEX, tag)[0]
return name | 976891bfe6e4a286f1b47f0a1fcd0cf061ac7101 | 43,611 |
from typing import Dict
from typing import Callable
def snap_array_registry(
file_pointer: h5py.File, data_source: str, name_map: Dict[str, str] = None,
) -> Dict[str, Callable]:
"""Generate snap array registry.
Parameters
----------
file_pointer
The h5py file pointer to the snap file.
... | 21bf78ebc33c9d213c49f360fa2f05a22a11bf7a | 43,612 |
import inspect
def get_storage(dictionary, index=None):
"""Get a unique storage point within a class method.
Parameters
----------
dictionary : dict
A dictionary used for storage.
index : hashable
An index under which to load the element. Needs to be hashable.
This is usef... | 199aa57fc9b04a0d4ec64b0357b31ec2877e2b03 | 43,613 |
def sample_hyperparameters():
"""
Yield possible hyperparameter choices.
"""
return {
"no_components": np.random.randint(5, 64),
"learning_schedule": np.random.choice(["adagrad", "adadelta"]),
"loss": np.random.choice(["bpr", "warp", "warp-kos"]),
"learning_rate": np.ran... | 89100422e66312450b8c0ab2232fdd69ea9efebe | 43,614 |
def waypoint_sampling(X, n_waypoints=100):
"""
Min-max sampling of waypoints in a two dimensional embedding.
:param X:
:param n_waypoints:
:return:
"""
# store waypoints and initiate distances
wps = []
N = X.shape[0]
dists = np.zeros((N, n_waypoints))
# random sampling of f... | a2fa30d90c94d6a9323b6f73ff0711315719267b | 43,615 |
import threading
def threadpool_waited_join(thread_object, timeout):
"""
Call threadpool.join() with timeout. If join completed return True, otherwise False
Notice: This function creates another daemon thread and kills it, use with care.
:param thread_object: Thread to join
:param float timeout: ... | a1f143775684aecca85c02c26879e8ec546938a9 | 43,616 |
from typing import Union
def get_relevant_terms(
phi: Union[ndarray, DataFrame],
topic: int,
lambda_: float = 0.6) -> Series:
"""Select relevant terms.
Parameters
----------
phi : Union[np.ndarray, DataFrame]
Words vs topics matrix (phi).
topic : int
Topic ... | e7266c9258cd7b36b2ec976ab41bfece8b1d9a03 | 43,617 |
import posixpath
import re
def GetCudaToolkitVersion(vm):
"""Get the CUDA toolkit version on the vm, based on nvcc.
Args:
vm: the virtual machine to query
Returns:
A string containing the active CUDA toolkit version,
None if nvcc could not be found
Raises:
NvccParseOutputError: On can not p... | e3f18651e4865b40012e53d6762b8297fab76295 | 43,618 |
def divided_by_sentences(abstract):
"""Divides abstracts by sentences
:param abstract:load
:return: list of sentences of the abstract
"""
nlp_l = English()
nlp_l.add_pipe(nlp_l.create_pipe('sentencizer'))
doc = nlp_l(abstract)
sentences = [sent.string.strip() for sent in doc.sents]
... | 360f21f0d4a5caa2c906b4691503a99a2f8a885b | 43,619 |
import sys
def deep_getsizeof(data, ids=None):
"""
Returns the memory footprint of a (essentially) any object;
based on sys.getsizeof, but uses a recursive method to handle collections
of objects.
"""
if ids is None:
ids = set()
if id(data) in ids:
return 0
size = sys... | 5e92a2b2e917f6d3a3bee06d305b580e669573c1 | 43,620 |
def write_submission_pool(outputs, args, dataset,
conf_thresh=0.1,
horizontal_flip=False,
max_workers=20):
"""
For accelerating filter image
:param outputs:
:param args:
:param dataset:
:param conf_thresh:
:param horizontal_flip:... | 2fbe04fef67bc52c49840ba176837a6f1ff22ff0 | 43,621 |
def transform_one(transformer, X=None, y=None):
"""Transform the data using one estimator."""
def prepare_df(out):
"""Convert to df and set correct column names and order."""
use_cols = inc or [c for c in X.columns if c not in exc]
# Convert to pandas and assign proper column names
... | c2f7a177bc6a547419c38bfa0a8ca62dbe2f748c | 43,622 |
def calculateHeaders(tokens: list, rawHeaders: tuple) -> tuple:
"""
Takes sanitised, tokenised URCL code and the rawHeaders.
Calculates the new optimised header values, then returns them.
"""
BITS = rawHeaders[0]
bitsOperator = rawHeaders[1]
MINREG = 0
MINHEAP = rawHeaders[3]
... | 472eeb4397d68e232b66517064f91e5688c33e3c | 43,623 |
import toml
import logging
def from_file():
"""try to load the configuration from file"""
try:
return toml.load(Config.get_path_to_conf())
except FileNotFoundError:
logging.info(f"Configuration file '{Config.get_path_to_conf()}' not found.") | 4a833987e563fdc52fabb861f84f89dbf889bf92 | 43,624 |
def synthetic_data(w, b, num_examples):
"""
y = Xw + b + noise
"""
X = tf.zeros((num_examples, w.shape[0]))
X += tf.random.normal(shape=X.shape)
y = tf.matmul(X, tf.reshape(w, (-1, 1))) + b
y += tf.random.normal(shape=y.shape, stddev=0.01)
y = tf.reshape(y, (-1, 1))
return X, y | e861c9af287108f1f08c491142093ad10bcd5a8f | 43,625 |
def weg(m) -> str:
"""capture multiple "weg"s"""
return m | 2be9b16a4969d04f1322c22b07ffd98318fa05fb | 43,626 |
from typing import Iterable
def cossin(X, p=None, q=None, separate=False,
swap_sign=False, compute_u=True, compute_vh=True):
"""
Compute the cosine-sine (CS) decomposition of an orthogonal/unitary matrix.
X is an ``(m, m)`` orthogonal/unitary matrix, partitioned as the following
where uppe... | 2350d8b65a470346631d2d657f900c899c6b3bec | 43,627 |
def getBlankBoard():
"""Create a new, blank tic tac toe board."""
board = {} # The board is represented as a Python dictionary.
for space in ALL_SPACES:
board[space] = BLANK # All spaces start as blank.
return board | 1db53045128b6ae246d9be6ef52d443aa9d8e7a1 | 43,628 |
def isopycnal_arr(arrin,target_density,pd,interp=None):
"""
Returns the value of an input array along an isopycnal.
"""
if target_density < 100:
target_density += 1000
if not interp:
i0 = isopycnal_mask(target_density,pd)
if len(arrin.shape) > 1:
i1,i2 = np.indi... | 51bdd3dbb5c410178bc2581bb14a0f48230c559f | 43,629 |
def forecast(model, predict_data, seq_len=50, forward=10, stride=1):
"""Step through the out-of-sample data and make predictions.
Args:
model (keras.Model): Trained model.
predict_data (numpy.array): Out-of-sample data.
seq_len (int): Sequence length.
forward (int): Forward.
stride (int): Step size.
Retu... | d1e520f2008d0ef74b17c1c91f5e8d8bdba26bbf | 43,630 |
def _run_on_failure_decorator(method, *args, **kwargs):
"""
A decorator to run when the tests fail
:param method: the method to run
:param args: the tuple arguments to pass to the method
:param kwargs: the dict arguments to pass to the method
:return: runs the method on failure, raises exception... | fbc6a273da852eeecb269dd89b851b6965b48a9a | 43,631 |
import os
import sys
import gc
def load_blackrock(
exp_path, test, electrode, connections=(),
downsamp=15, page_size=10, bandpass=(), notches=(),
save=True, snip_transient=True, lowpass_ord=12, units='uV',
**extra
):
"""
Load raw data in an HDF5 table stripped from Bl... | 45da5d5a76a2ad2ee82f83218b9761628e69e373 | 43,632 |
def get_xy_arrs(m_size, ant_rad):
"""Finds the x/y position of each pixel in the image-space
Returns arrays that contain the x-distances and y-distances of every
pixel in the model.
Parameters
----------
m_size : int
The number of pixels along one dimension of the model
ant_rad : f... | 6ce7b6aed1a4d1e3535ef57dfc2f5dac976b99f0 | 43,633 |
def debugindex(orig, ui, repo, file_=None, **opts):
"""dump the contents of an index file"""
if (
opts.get('changelog')
or opts.get('manifest')
or opts.get('dir')
or not shallowutil.isenabled(repo)
or not repo.shallowmatch(file_)
):
return orig(ui, repo, file_... | 3dcc3623e00505a86482909a425a0f3fd67786cd | 43,634 |
import json
def build_data(known_languages):
"""Build primary objects edge_struct and nodes from graph_base."""
with (SRC_DATA / 'graph_base.json').open() as base_fh:
primary_data = json.load(base_fh)
edge_struct = {}
for relation_type, edges in primary_data['edges'].items():
edge_str... | a3af7ae5aaf45e5a52d97f45a4fb126daee52439 | 43,635 |
def PrepareSipCollection(adornedRuleset):
"""
Takes adorned ruleset and returns an RDF dataset
formed from the sips associated with each adorned
rule as named graphs. Also returns a mapping from
the head predicates of each rule to the rules that match
it - for efficient retrieval later
"""
... | dde70f55c559e01ca2c050a56b3903a2658958bc | 43,636 |
def negate_q(a: ElementModQ) -> ElementModQ:
"""
Computes (Q - a) mod q.
"""
return ElementModQ(_Q_gmp - a.elem, make_formula("negate_q", a)) | 39d9e845adf52e41a6d4ff063aac0116be8e7c52 | 43,637 |
def candidate_synsets(lemma, pos):
"""
Used to restrict our attention only to synsets from the entire probability distribution over the output layer
:param lemma:
:param pos:
:return: list(Candidate synsets) or lemma if nothing in Wordnet
"""
pos_dict = {"ADJ": wn.ADJ, "ADV": wn.ADV, "NOUN":... | f7f5f02765a0c93b499a706c4d1d30ea7bdb8632 | 43,638 |
from unittest.mock import patch
def start_session(username="user", password="password", enterprise="enterprise", api_url="https://vsd:8443", version="3.2", api_prefix="api"):
""" Log in and fetch api key """
session = NURESTTestSession(username=username, password=password, enterprise=enterprise, api_url=api_... | b82a0ea396084e9fdbc11c93926f08b77ed6d2b3 | 43,639 |
def nodes_or_number(which_args):
"""PORTED FROM NETWORKX
Decorator to allow number of nodes or container of nodes.
Parameters
----------
which_args : int or sequence of ints
Location of the node arguments in args. Even if the argument is a
named positional argument (with a default va... | 3166c80d6bd5c2faaee16d70b919eda412f4d33a | 43,640 |
def _crosscorr(x, y, **kwargs):
"""
Returns the crosscorrelation sequence between two ndarrays.
This is performed by calling fftconvolve on x, y[::-1]
Parameters
x: ndarray
y: ndarray
axis: time axis
all_lags: {True/False}
whether to return all nonzero lags, or to clip the length ... | 850c1c7ded00968de889589758558397fa06ffc0 | 43,641 |
def get_qword(*args):
"""get_qword(ea_t ea) -> ulonglong"""
return _idaapi.get_qword(*args) | 28659cfc633d6e9170dc0fda2005ed967973108c | 43,642 |
def wine_key(wine_cate=DEFAULT_WINE_CAT):
"""Constructs a Datastore key for a Wine entity."""
return ndb.Key('WineCategory', wine_cate.lower()) | 13d94093f7d160747a7cf222b284295b569be04e | 43,643 |
import torch
from typing import Tuple
def run_knn(
train_features: torch.Tensor,
train_targets: torch.Tensor,
test_features: torch.Tensor,
test_targets: torch.Tensor,
k: int,
T: float,
distance_fx: str,
) -> Tuple[float]:
"""Runs offline knn on a train and a test dataset.
Args:
... | 0157714d48cdf3f3ee797666e367898023fc7e34 | 43,644 |
def create_account(create_account_key):
"""Checks the key. If valid, displays the create account page."""
user_id = auth_utils.check_create_account_key(create_account_key)
if user_id is None:
flask.current_app.logger.warn(
f'Invalid create_account_key: {create_account_key}')
flas... | c921336f59009fb2684f671dc8b409b8ae268e1f | 43,645 |
def determine_inventory_groups(vm_directory):
"""
Determine the Ansible inventory groups that this
VM is a member of.
:param vm_directory: directory to issue `vagrant' commands in
:return: list of Ansible inventory groups
"""
group_config = join(vm_directory, 'groups.yml')
if exists(gro... | c2d36706d7d6860c5c623c81a949926e26b345f2 | 43,646 |
def data_value(value: str) -> float:
"""Convert to a float; some trigger values are strings, rather than
numbers (ex. indicating the letter); convert these to 1.0."""
if value:
try:
return float(value)
except ValueError:
return 1.0
else:
# empty string
... | 5d46ab47c3d8c0ebb9a5f9b06d7bb6b2a47a0939 | 43,647 |
def _monom(n):
"""
monomial in `eta` variables from the number `n` encoding it
"""
v = []
i = 0
while n:
if n % 2:
v.append(i)
n = n >> 1
i += 1
return v | 42621ddbca95b8fc3ca3d7eea51cc1dc97524758 | 43,648 |
def _combin(points,n, max_dist):
"""Summary
Args:
points (lst): sample points
n (integer): number of samples
max_dist (float): maximum permissible distance
Returns:
lst: List of tuples containing the permissible pairs
"""
dist =[]
p = 0
for i in range(0,n):
for j in range((i+1),n):
... | 086a53d697de499489809b6ba1d75651789c5d75 | 43,649 |
import os
def get_buildtime(in_list, start_year, path_list):
""" Calculates the buildtime required for reactor
deployment in months.
Parameters
----------
in_list: list
list of reactors
start_year: int
starting year of simulation
path_list: list
list of paths to re... | 4d7078178009e23da6f861f7a4c0e7c5633d03e1 | 43,650 |
import multiprocessing
def concat(rlist, method="gridded", enhance=False, parallel=False):
"""
This function takes a list of Radial objects or radial file paths and
combines them along the time dimension using xarrays built-in concatenation
routines.
Args:
rlist (list):
list o... | c511817e7cb7f215b2dfba284bed4b7db9903781 | 43,651 |
from datetime import datetime
def month_counter(fm, LAST_DAY_OF_TRAIN_PRD=(2015, 10, 31)):
"""Calculate number of months (i.e. month boundaries) between the first
month of train period and the end month of validation period.
Parameters:
-----------
fm : datetime
First day of first month o... | e10e6be0eb8a7762b182d073ca85ed1b97f831d3 | 43,652 |
def warning(message):
"""Log helper function for jinja2 tasks"""
l.warning(message)
return "" | b8f6545518409952446a5be4192727a039e4ab72 | 43,653 |
def demean(X, weights=None, return_mean=False, inplace=False):
"""Remove weighted mean over rows (samples).
Parameters
----------
X : array, shape=(n_samples, n_channels[, n_trials])
Data.
weights : array, shape=(n_samples)
return_mean : bool
If True, also return signal mean (de... | 7fec1b9cafed481219b1deb8848483cd050d4852 | 43,654 |
def l10n_overview_rows(locale, product=None):
"""Return the iterable of dicts needed to draw the Overview table."""
# The Overview table is a special case: it has only a static number of
# rows, so it has no expanded, all-rows view, and thus needs no slug, no
# "max" kwarg on rows(), etc. It doesn't fit... | 8cc7d77a61eb95904ae23c1d894429033cc4802e | 43,655 |
def tupleize(series_dict, tuple_name="obs"):
"""Creates an observation list of NamedTuples."""
kwarg_dict = {}
keys = [i for i in series_dict.keys()]
for i in range(0, len(keys)):
kwarg_dict[keys[i]] = list(series_dict[keys[i]])
return create_observation_list(tuple_name, **kwarg_dict) | df1fa1e8d52d13a580f1b5db2bac2ab9ea72e2e1 | 43,656 |
def symmetry_specified(self, x, bond_order):
""" Specify the symmetry of the bond and then calculate separately,
before concatenating them together.
TODO: finish implementing
"""
return tf.cond(
lambda: tf.greater(
bond_order,
tf.constant(1, dtype=tf.float32)),
... | c38a209aba084bfdc333c37a26f8b107facb1971 | 43,657 |
def get_background(background_img=BACKGROUND):
"""Start with a background image"""
_img = Image.open(background_img)
# Check the width and height of the image
assert _img.size == (400, 300), "Background must be 400x300"
# Convert the image to use a white / black / red colour palette
# hopefull... | ce4fc6e897cbfd6cb8ad821adb26f53fe4b2b4b6 | 43,658 |
def ZonalComputeUrl(project, zone, collection, name):
"""Generate zone compute URL."""
return ''.join([COMPUTE_URL_BASE, 'projects/', project, '/zones/', zone, '/', collection, '/', name]) | d04730be1fa84a2e130ed3613c6389b1605f9376 | 43,659 |
import glob, time, gc
def check_repo(repo_dir = '../../models/all_from_repository',
model_suffix = 'xml',
invalid_if_warnings = False,
compare=True):
"""
Validate every model in the CellML repository, and return a list
of invalid models.
If compare is ... | c47bc626766806d175585e3ee9ebf767da87f0e9 | 43,660 |
def build_get_long_valid_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Get integer dictionary value {"0": 1, "1": -1, "2": 3, "3": 300}.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:return: Returns an ... | bc601a1107941e59285bb32800a08f3a8c4f2152 | 43,661 |
def fromKML(filename=None, data=None, crs=None, encoding=None):
""" Create a list of Features from a KML file. Return a python tuple
with ee.Feature inside. This is due to failing when attempting to create a
FeatureCollection (Broken Pipe ERROR) out of the list. You can try creating
it yourself casting ... | afff38a3dbdf439da32a87fc1f1a9d4d9bd38d5c | 43,662 |
import threading
def run_as_thread(fn):
"""Run function as thread"""
@wraps(fn)
def run(*args, **kwargs):
t = threading.Thread(target=fn, args=args, kwargs=kwargs)
t.daemon = True
t.start()
return t
return run | a388ca61b041e04d5e487654a1a3b738dd3da06b | 43,663 |
def to_unicode(obj):
"""Convert object to unicode"""
if isinstance(obj, bytes):
return obj.decode('utf-8', 'ignore')
return str(obj) | e54c02e04109b8a99a7eb4e357e95ead89166137 | 43,664 |
def positive_definite_matrix(N, M=None):
"""return an array of M positive-definite matrices with shape (N, N)"""
if M is None:
V = np.random.random((N, N))
V = np.dot(V, V.T)
else:
V = np.random.random((M, N, N))
for i in range(M):
V[i] = np.dot(V[i], V[i].T)
... | f458397ee3b993ca6bc05d937512c777b0861051 | 43,665 |
def restore_agent(agent_class, learner_config, env_config, session_config, render):
"""
Restores an agent from a model.
"""
agent = agent_class(
learner_config=learner_config,
env_config=env_config,
session_config=session_config,
agent_id=0,
agent_mode='eval_deter... | 9c9647aaff3157511cbf08309ec9a2077b487d14 | 43,666 |
def get_pretrained_model_last_layer_change(model_name, n_classes):
"""
:param model_name: 불러올 pre trained 모델 이름
:param n_classes: 분류할 클래스 갯수
:return: 불러온 모델의 분류기 부분만 수정한 구조를 리턴한다.
"""
if model_name == 'alexnet':
model = models.alexnet(pretrained=True)
# Freeze early layers
... | 31da5843c16a80e5bb9959d10021929d82946bb0 | 43,667 |
from io import StringIO
def download_image(ses, url):
""" dumps image into memory """
dl = ses.get(url, stream=True)
img = StringIO()
img.write(dl.content)
img.seek(0) # rewind to beginning
return img | 7a02dd3161b3e010addd79a33b7b1ae9dbaf91c7 | 43,668 |
import _locale
def get_masteries():
"""
https://developer.riotgames.com/api/methods#!/968/3317
Returns:
MasteryList: all the masteries
"""
request = "{version}/masteries".format(version=cassiopeia.dto.requests.api_versions["staticdata"])
params = {"tags": "all"}
if _locale:
... | 7b55c40c20eaa1a08df65b82f51bbbf3803f8cc7 | 43,669 |
def get_shape(x, unknown_dim_size=1):
"""
Extract shape from onnxruntime input.
Replace unknown dimension by default with 1.
Parameters
----------
x: onnxruntime.capi.onnxruntime_pybind11_state.NodeArg
unknown_dim_size: int
Default: 1
"""
shape = x.shape
# replace unknow... | 1c719191922a46b948fb567273e3a5152769e190 | 43,670 |
import csv
def process_fields(filename, field_occurrences=defaultdict(list)):
"""
Create a dict of fieldnames and the forms that include them.
Args:
filename (str): CSV
field_occurrences (dict): A dictionary of the sort we'll be returning.
Returns:
A dictionary of lists, inde... | 721e5fadfb6f9cc8dbd6f8ec71ebe6b9bbc50c7f | 43,671 |
def sensemap_sim(
shape=(64, 64),
spacings=(3, 3),
ncoil=8,
rcoil=100,
orbit=360,
orbit_start=None,
coil_distance=1.5,
nring=1,
dz_coil=None,
scale="default",
dtype=np.complex128,
xp=np,
):
"""Simulate sensitivity maps for sensitivity-encoded MRI.
Parameters
... | 890d6ccaf860fb2be531dfddb98820b7e58a2b4c | 43,672 |
def _check_typeclass_signature(
typeclass_signature: CallableType,
instance_signature: CallableType,
ctx: MethodContext,
) -> bool:
"""
Checks that instance signature is compatible with.
We use contravariant on arguments and covariant on return type logic here.
What does this mean?
Let... | 577622e18dc3ce110f2ed2a465ac5788cec2d4ab | 43,673 |
def quaternion_matrix(quaternion):
"""Return homogeneous rotation matrix from quaternion."""
q = np.array(quaternion, dtype=np.float64, copy=True)
n = np.dot(q, q)
if n < _EPS:
return np.identity(4)
q *= np.sqrt(2.0 / n)
q = np.outer(q, q)
return np.array([
[1.0-q[2, 2]-q[3, ... | 3ca7b86e6c00530b9b9ad9c640dd97061fd59993 | 43,674 |
def rhex_str(length: int = 4) -> str:
"""Returns a random hex string
:param length: length of random bytes to turn into hex (defaults to 4)
:type length: int
:return: random hexadecimal string
:rtype: str
.. doctest:: python
>>> a = rhex_str()
>>> isinstance(a, str)
Tr... | a6fd1c4ba1fc485b0cdce7607b971ee1ca53e484 | 43,675 |
import os
def logfile():
"""Return path to log file."""
return os.path.join(env.flags["log_dir"], env.flags["log_file"]) | 409d33d1c7e44b96bd9d0146039992a513b343d7 | 43,676 |
def word_tally(word_list):
"""
Compiles a dictionary of words. Keys are the word, values are the number of occurrences
of this word in the page.
:param word_list: list
List of words
:return: dictionary
Dict of words: total
"""
word_dict = {}
for word in word_list:
... | 5ab1f7ac4c8a72cd5ceda2a391cef8a62a1ec34f | 43,677 |
from typing import Dict
from typing import Tuple
from typing import Sequence
from typing import Any
def _matches(
spec: jax.core.Jaxpr,
capture_literals: Dict[int, str],
graph: jax.core.Jaxpr,
eqn_idx: int,
) -> Tuple[
bool, int, Sequence[jax.core.Var], Sequence[jax.core.Var], Dict[str, Any]]:
"... | 828851c9426b858d9d99836d9607af23e6ee433b | 43,678 |
import os
def read_file(file_: str, question: str) -> str:
"""Read file or ask for data to write in text file."""
if not os.path.isfile(f'assets/{file_}.txt'):
open(f'assets/{file_}.txt', 'a')
with open(f'assets/{file_}.txt', 'r+', encoding='utf-8') as file:
text = file.read()
if t... | 58ee1d458080702a32d2e687f16aefd165231cf8 | 43,679 |
def complexity(sequence, N):
"""
Computes the Shannon Entropy of a given sequence of a
biopolymer with `N` possible residues. See (Wooton, 1993)
for more.
:param sequence: the nucleotide or protein sequence whose Shannon Entropy is to calculated.
:param N: the total number of possible residues ... | 38f41c7673010297019cec8616571f6e83aac5a2 | 43,680 |
from typing import Tuple
import copy
import re
def regex_replace_nb(
notebook: NotebookNode, replacements: Tuple[Tuple[str, str, str]]
) -> NotebookNode:
"""Return a new notebook with string regex replacements applied.
:param replacements: list of (path, regex, replacement), path is a string of form
... | ad9f8230aa8ea2bf3c1c6580bf051416fbf790a2 | 43,681 |
import typing
from typing import Any
from typing import Dict
def Axis(
color: str = None,
grid_color: str = None,
grid_lines: str = "solid",
label: str = "",
label_color: str = None,
label_location: str = "middle",
label_offset: str = None,
num_ticks: int = None,
offset: dict = {},... | eb9f5a75cb445a8bd01dcc8c7dce63944b463a07 | 43,682 |
def _kuhn_munkres_algorithm(true_lab, pred_lab):
"""
Private function that implements the Hungarian method. It selects the best label permutation of the
classification output that minimizes the
misclassification error when compared to the clustering labels.
:param true_lab: clustering algorithm lab... | a3abe2c6e47625963e2d243dc58c508b8de10f24 | 43,683 |
import json
async def load_test_system(dir_name, config: dict = None) -> Gateway:
"""Create a system state from a packet log (using an optional configuration)."""
try:
with open(f"{dir_name}/config.json") as f:
kwargs = json.load(f)
except FileNotFoundError:
kwargs = {"config"... | 25d1ff1e1bfefef6bc045eed4c004e65fe90e59a | 43,684 |
def score_segment(previous_segment, current_segment, next_segment):
"""
Computing scores for current segment based on it's surroundings
:param previous_segment: segment tuple for previous segment defined as (start, end, gt_event_index, det_event_index, standard_score) or None
:param current_segment: seg... | aa971050dbba9aa5211611c9356ff1adfb768173 | 43,685 |
def te(s, assignment=None):
"""Convenience wrapper around the meta-language parser."""
return meta.TypedExpr.factory(s, assignment=assignment) | 1f4fdb5b4c05b15f4428012c7b4ffe3b759dca06 | 43,686 |
def edit_party(party_id):
"""Edit a specific party."""
details = request.get_json()
party = PartyModels().update_party(party_id, details)
if party:
n_success = make_response(jsonify({
"status" : 200,
"mg": "party updated successfully",
"data": party
}... | 619c90c5a868a9d54b1f9cd72edb296e27cec0ac | 43,687 |
from typing import Dict
from typing import Tuple
def get_usage_summary(client: AmberApi, site_id: str, start_date: date, end_date: date) -> \
Dict[Tuple[date, str], UsageSummary]:
"""
Uses the given client to query the Amber API for all Usage data for the specified Site between the given dates
(bo... | 0313d4c77c26d9e638123722da80776644c19b62 | 43,688 |
import logging
def _convert_to_fzx(font):
"""Convert monobit font to FZX properties and glyphs."""
# select glyphs that can be included
# only codepoints 32--255 inclusive
# on extraction 32--127 will be assumed to be ASCII
includable = font.subset(codepoints=set(_FZX_RANGE))
dropped = font.wi... | fbe5c3336448e97498a626ef4943033a0087bab2 | 43,689 |
def validate_dataset(data):
"""
Validate user given dataset
"""
if data:
if not isinstance(data, DatasetAutoFolds):
raise ValidationError(
"data",
'Unknown data format. Must be and instance of "DatasetAutoFolds". Got "%s"'
% type(data),... | 58273c47114ff88facf8c27d4f9e7b5ef6a70d44 | 43,690 |
def Linear_Regularized(
name,
alphas=(0.1, 1.0, 10.0),
folds=10,
):
"""
FUNCTION:
Used to create a Linear Machine Learning model with built-in
regularization and cross validation
PARAMS:
name: str
A name/alias given to the model by the user
al... | c6cba028f21516f35f4d3a212f64b053c7ce061a | 43,691 |
import string
import random
def randomString(url, stringLength=30):
"""Generate a random string of fixed length """
Letters = string.ascii_lowercase + string.ascii_uppercase + string.digits
url_split = url.split(".")
format_ = url_split[-1]
s = ''.join(random.choice(Letters) for i in range(string... | bf3787fdb22ba1f06d9f2e5626282125040a81c5 | 43,692 |
def calculateExtents(values):
"""
Calculate the maximum and minimum for each coordinate x, y, and z
Return the max's and min's as:
[x_min, x_max, y_min, y_max, z_min, z_max]
"""
x_min = 0; x_max = 1
y_min = 0; y_max = 1
z_min = 0; z_max = 2
if values:
initial_value = values[... | 47378c219d5d9b49db7196ed999ba906a2add4d7 | 43,693 |
from typing import Counter
def split_data_train_dev_test(df):
"""
Creating sets for model building and testing. Steps:
1. Training set (70%) - for building the model
2. Development set a.k.a. hold-out set (15%) - for optimizing model parameters
3. Test set (15%) - For testing the performance of th... | 384419c869e707b47ed283e86e22bcfa0c39f733 | 43,694 |
def start_simulate(pid):
"""Function for starting Circle-Map simulate"""
print("\nRunning Circle-Map Simulate\n")
sp.call("mkdir temp_files_%s" % pid, shell=True)
return(pid) | 53044da24a8b24915e07bd8e86bfe40c90cc371d | 43,695 |
def _prep_inputs_(X, y, theta, penalty=None, center=None):
"""Internal use function to simplify variable transformations for regression. This function is used on the inputs
to ensure they are the proper shapes
Parameters
----------
X : ndarray
y : ndarray
theta : ndarray
penalty : ndarr... | 4fc747fc97176d612e7f39d28bd60e8fdc6c6579 | 43,696 |
def place_order(order='buy', price=0.0, currency='krw', coin_amount=0.0,
order_type='limit'):
"""Place an order.
:param order: ``buy`` | ``sell``
:param price: Price per BTC
:param currency: KRW by default. I wouldn't assume Korbit supports any other
currency at the... | 3a00844950b302928eaa7963ef236135e3a9256e | 43,697 |
def shuffle_isis(spiketrain, n=1, decimals=None):
"""
Generates surrogates of a neo.SpikeTrain object by inter-spike-interval
(ISI) shuffling.
The surrogates are obtained by randomly sorting the ISIs of the given input
:attr:`spiketrain`. This generates independent `SpikeTrain` object(s) with
s... | 113d4688755cc799fbddc85dc105f287db6df0c9 | 43,698 |
def is_installed(name):
"""
Check if a CRUX package is installed.
"""
with settings(hide("running", "stdout", "stderr", "warnings"), warn_only=True):
res = run("prt-get listinst {}".format(name))
return res.succeeded | 1a0ae488c7efd2536fbf1ebcb768235482bcdf6d | 43,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.