content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def eval_postprocess(positive_path, negative_type):
""" get accuracy """
files = os.listdir(positive_path)
log = []
for f in files:
score_file = os.path.join(config.result_path, f.split('.')[0] + '_0.bin')
positive_file = os.path.join(positive_path, f)
argsort = np.fr... | a5bc76ff06ffd791f39e687c4eaaf055889ea75f | 3,627,000 |
def compute_q10_correction(q10, T1, T2):
"""Compute the Q10 temperature coefficient.
As explained in [1]_, the time course of voltage clamp recordings are
strongly affected by temperature: the rates of activation and inactivation
increase with increasing temperature. The :math:`Q_{10}` temperature
... | eed7d7f38c1f9d98b1a6a89a28eb4f1a6656b6c7 | 3,627,001 |
import collections
def get_frameworks_table():
"""
Generates a dataframe containing the supported auto classes for each model type, using the content of the auto
modules.
"""
# Dictionary model names to config.
config_maping_names = transformers_module.models.auto.configuration_auto.CONFIG_MAP... | 189b521e81a2e3622534f34e258f4d3fbe665084 | 3,627,002 |
import torch
def extract_video_features(model, get_frame_fn, video_names, video_frame_counts, update_progress_cb=None):
"""
:param model:
:param get_frame_fn:
:param video_names:
:param video_frame_counts:
:param update_progress_cb:
:return: VxF np.float32 array
"""
clip_features ... | 48fe01307ef56f48dcd3acbfc350717d75bdb21a | 3,627,003 |
def osarch_is_amd64():
"""Check if the architecture maps to amd64."""
return osarch_match("amd64") | ec34b586247c4206093f0a89c3fe875f3a6774c5 | 3,627,004 |
from skimage import exposure
def increase_contrast(im, method = 'adaptive'):
""" Adative method seems to deal with background gradients the best, but two other options are possible using scikit package
"""
## SEE: https://scikit-image.org/docs/dev/auto_examples/color_exposure/plot_equalize.html
if me... | 966bfeb6487d6a7add8c4e1bfbfd0c31d8683fb1 | 3,627,005 |
def without(array, *values):
"""Creates an array with all occurrences of the passed values removed.
Args:
array (list): List to filter.
values (mixed): Values to remove.
Returns:
list: Filtered list.
Example:
>>> without([1, 2, 3, 2, 4, 4], 2, 4)
[1, 3]
.... | 21bddf5244a591a261f704557fb8017a2401ef77 | 3,627,006 |
def get_total_mnsp_ramp_rate_violation(model):
"""Get total MNSP ramp rate violation"""
ramp_up = sum(v.value for v in model.V_CV_MNSP_RAMP_UP.values())
ramp_down = sum(v.value for v in model.V_CV_MNSP_RAMP_DOWN.values())
return ramp_up + ramp_down | 9e326a70966edce51f82036977fcec1b26991c21 | 3,627,007 |
def get_row_line(p1,p2):
"""
Compute x,y values and alpha angle for the line between start (p1) and ending (p2) points
"""
l,alpha = line_polar(p1,p2)
x,y = line_polar_to_cart(l,alpha,p1)
return (np.round(x).astype("int"),np.round(y).astype("int"),alpha) | 3c253c8e768204af53bb26a50afbce952229e57a | 3,627,008 |
import re
def parse_traceroute(raw_result):
"""
Parse the 'traceroute' command raw output.
:param str raw_result: traceroute raw result string.
:rtype: dict
:return: The parsed result of the traceroute command in a \
dictionary of the form:
::
{1: {'time_stamp2': '0.189',
... | 2a12d72a4e2e9a64287c65525b7eca6997849f97 | 3,627,009 |
def get_scheds(aircraft_list, flights):
"""
Generates a list of Schedule objects with the appropriate attributes
Parameters
----------
aircraft_list : list,
aircrafts in plan
flights : list,
list of classes.Flight objects
Returns
-------
schedules : list,
l... | 13d0bc2326190261fd4b4a93603f2c533d326174 | 3,627,010 |
def _transform_get_item_to_module(module: Module, debug: bool) -> GraphModule:
"""Transforms the built-in getitem function to ReduceTuple module.
This function is usually used to reduce the tuple output of RNNs.
Args:
module: container module to transform
debug: whether to print debug mess... | c3b1d95db04c891a7c83d1ddb71940a0b2158b75 | 3,627,011 |
from typing import Optional
from typing import List
import argparse
from pathlib import Path
def build_parser(argv: Optional[List] = None):
"""Return ArgumentParser parser for script."""
# Create parser object
parser = argparse.ArgumentParser(
prog="cw_query_database",
description="Interro... | c426c5a58b1d9794c6f819c39d21aca2a73c77ba | 3,627,012 |
def symptom_LDAP_user_enabled_emulation_use_group_config_ignored():
"""`[ldap] user_enabled_emulation_use_group_config` is being ignored.
There is no reason to set this value unless `keystone.conf [ldap]
user_enabled_emulation` is also enabled.
"""
return (
not CONF.ldap.user_enabled_emulat... | f16071879f5b43a7a076207e7ccedef5c281709a | 3,627,013 |
def add_user():
"""Add a new user, you must have permissions"""
form = UserForm()
resp_message = 'Invalid payload.'
if not form.validate():
return BadRequest(resp_message)
username = form.username.data
email = form.email.data
password = form.password.data
user = User.query.filte... | 1b9a3c154c05e4aca9eb9a7f7f120174c35b99a9 | 3,627,014 |
import _sha256
def _fetch_remote(remote, dirname=None):
"""Helper function to download a remote dataset into path
Fetch a dataset pointed by remote's url, save into path using remote's
filename and ensure its integrity based on the SHA256 Checksum of the
downloaded file.
Parameters
---------... | ffa19832ac69a20891d084d0610c2c264d696a27 | 3,627,015 |
import torch
def evaluate(config: ConfigLoader, model, validationloader):
""" evaluate model using the data given by validationloader
Args:
config (ConfigLoader): config of the experiment
model (nn.Module): model to be evaluated
validationloader (torch.utils.data.DataLoader): dataload... | 7e977a140174db610249689b2257255cd9fc651c | 3,627,016 |
from typing import Union
from typing import Literal
def curve(
data: dict,
*,
ax: Union[plt.Axes, None] = None,
curve_layout: Literal["overlay", "stacked", "shifetd"] = "overlay",
shade: bool = True,
kde_norm: bool = True,
order: Union[list, None] = None,
kernel_kws: Union[dict, None] ... | fa42743b997064882bacf9c90ed6734b211e8f0f | 3,627,017 |
def load_kaldi_hmms(fctx):
"""Load HMMs from text output of context to pdf binary"""
hmms ={}
hmm = []
for line in open(fctx):
lx = line.strip().split()
ctx = (lx[0], lx[1], lx[2])
n = int(lx[3])
pdf = int(lx[4])
# we do not need disambig phones
if "#" in ctx[0] or "#" in ctx[1] or "#" in ctx[2]:
c... | 7703ac442377e541b6d33aed4a33ca5a858f960e | 3,627,018 |
def mask (raster, threshold, symName):
"""Highlight those raster pixels that reach/exceed the given threshold."""
return layer(Local("U8", "Greater Than Equal", Resample(raster,5), threshold), symName) | d10b29e4da8caf1189276dc90e7d6d765b40f5cb | 3,627,019 |
def get_vector_w2v(sent:Series, model:gensim.models.keyedvectors.Word2VecKeyedVectors):
"""
Create a word vector for a given sentence using a Word2Vec model.
This function is called in a lambda expression in `core.get_vectors`.
Returns list
"""
tokens = [token for token in sent.phrase if token ... | 3e50be76496f350109274ed205f27e1450dd4f9e | 3,627,020 |
def inc(initial_value):
"""Return arithmetic increase of 1 to initial_value"""
print "In inc() subroutine now"
return initial_value + 1 | d0ffcd97f4a2fa6c62526c8ee89c73f42a50aa46 | 3,627,021 |
def search():
"""Search page ui."""
return render_template(current_app.config["SEARCH_UI_SEARCH_TEMPLATE"]) | c5bfda79f0695beb7b5299a5d7d61eb20945a095 | 3,627,022 |
def vendor_id(request):
"""
Return the paddle.com vendor ID as a context variable
"""
return {"DJPADDLE_VENDOR_ID": settings.DJPADDLE_VENDOR_ID} | 5420c2c049e32f16e8dccd85ea9fdb46090c1704 | 3,627,023 |
import importlib
import inspect
import sys
def factory(cls, modules=None, **kwargs):
"""
Factory for creating objects. Arguments are passed directly to the
constructor of the chosen class.
"""
# Format modules into a list
if modules is None: modules = [__name__]
elif isinstance(modules,bas... | 71261043c10057d8e79cb052c9cd783ca76a6dfc | 3,627,024 |
def filter_samplesheet_by_project(file_path, proj_id,
project_column_label='SampleProject',
output_ini_headers=False):
"""
Windows \r\n
:param file_path:
:type file_path:
:param proj_id:
:type proj_id:
:param project_column... | d2e1fff7c9514654643b9c3949ef1850faf5ba94 | 3,627,025 |
import math
def ecliptic_obliquity_radians(time):
"""Returns ecliptic obliquity radians at time."""
return math.radians(23.439 - 0.0000004 * time) | 384199a506d29cb14b2a42facf2d6c46bf44f111 | 3,627,026 |
def hessian_Y(D , Gamma, eigQ, W, sigma_t):
"""
this is the linear operator for the CG method
argument is D
Gamma and W are constructed beforehand in order to evaluate more efficiently
"""
tmp1 = eval_jacobian_phiplus(D, Gamma, eigQ)
tmp2 = eval_jacobian_prox_p( D , W)
res = - sigma_t *... | 27f1e2a0ef69a9cf4b38dc8396921247c09e93fb | 3,627,027 |
def spec_pix_to_world(pixel, wcs, axisnumber, unit=None):
"""
Given a WCS, an axis ID, and a pixel ID, return the WCS spectral value at a
pixel location
.. TODO:: refactor to use wcs.sub
"""
coords = list(wcs.wcs.crpix)
coords[axisnumber] = pixel+1
coords = list(np.broadcast(*coords... | 1da3cc761f16ead462b114253af484c8af0b1279 | 3,627,028 |
def share_replica_get(context, replica_id, with_share_data=False,
with_share_server=False, session=None):
"""Returns summary of requested replica if available."""
session = session or get_session()
result = _share_replica_get_with_filters(
context, with_share_server=with_share... | 319285b3c38274ff928dd37e13286890408fdb06 | 3,627,029 |
async def playing_song(this, ctx: Context):
"""재생중인 컨텐츠 정보 보기
:param this: self
:param ctx: discord.ext.commands.Context
"""
vc = ctx.voice_client
if not vc or not vc.is_connected():
return await ctx.send(embed=embed_ERROR, delete_after=20)
player = this.get_player(ctx)
if not... | 543b9f39c112099fdc5f6e11d01e952648924471 | 3,627,030 |
import time
def check_and_record_restart_request(service, changed_files):
"""Check if restarts are permitted, if they are not log the request.
:param service: Service to be restarted
:type service: str
:param changed_files: Files that have changed to trigger restarts.
:type changed_files: List[st... | 08b779823732d9798f5875fdc5615eed4e0d2ed6 | 3,627,031 |
from typing import Union
import requests
def get_user_wantlist(user: Union[UserWithoutAuthentication,
UserWithUserTokenBasedAuthentication],
username: str,
page: Union[int, None] = None,
per_page: Union[int, None] = No... | 060338f7a6cf88799c4913130be5bcce6961acb1 | 3,627,032 |
def gaussian_additive_noise(x, sigma):
"""Gaussian additive noise.
Parameters
----------
x : array
input data matrix.
sigma : float
noise standard deviation. Noise values are sampled from N(0, sigma) for each input feature.
Returns
-------
x_noise : array
output... | 50f67c6b5695dbf3f6a997bbf9cfc6f9b9464e4d | 3,627,033 |
import global_vars as GV
def LCOH_fn(well_cost = None, Ed = None, mdot = None, dP_inj = None):
"""
Calculates the LCOH based on the well cost as capital cost
and the pumping cost for operating cost, and the thermal energy recovered.
Results match simplified_LCOH_fn, but simplified_LCOH_fn is preferre... | f44d8b1d2c6100db3baa4d4e0b9885052c27a87f | 3,627,034 |
def confirm_uid(request):
"""confirm with code sent to uid"""
params = request.get_params(schemas.AddUIDCodeSchema())
device = get_device(request)
customer = device.customer
wc_params = {
'secret': params['secret'],
'code': params['code'],
'attempt_id': params['attempt_id'],... | cd076ff03aa2bcbaecb15f5bf96e5a0c7bf374a7 | 3,627,035 |
def get_coverage(file, label, regions=None, nth=1, readcount=-1):
"""Get coverage for every `nth` position from alignment file."""
readcount = float(readcount)
contigs_coverage = defaultdict(dd)
with pysam.AlignmentFile(file) as f:
if isinstance(regions, str):
regions = [regions]
... | b972133f98208f0c916f6221b75b7755d3b48ab8 | 3,627,036 |
def equations_to_matrix() -> list:
"""
:return: augmented matrix formed from user input (user inputs = linear equations)
:rtype: list
"""
n = int(input("input number of rows "))
m = int(input("input number of columns "))
A = []
for row_space in range(n):
print("input row ", row_... | 702c252fed2d7127e4e5f9e5433ca4c29867138c | 3,627,037 |
from datetime import datetime
async def base_control(timestamp: datetime.datetime, base_id: int,
new_faction_id: int, old_faction_id: int,
server_id: int, continent_id: int,
conn: Connection[Row]) -> bool:
"""Dispatch a ``BaseControl`` Blip to t... | a9737f23f64baca2a8e1fa608815da54292b2321 | 3,627,038 |
def get_ports():
"""List all serial port with connected devices.
Returns
-------
port_list : list(str)
Names of all the serial ports with connected devices.
"""
port_list = list(list_ports.comports())
for i in range(len(port_list)):
port_list[i] = port_list[i].device
... | 61ebb00920f466ecc6e0fd48114a3c31b431d8db | 3,627,039 |
def same_origin(origin1, origin2):
"""
Return True if these two origins have at least one common ASN.
"""
if isinstance(origin1, int):
if isinstance(origin2, int):
return origin1 == origin2
return origin1 in origin2
if isinstance(origin2, int):
return origin2 in o... | 1fbc55d9dcfb928c173128a5b386cc6375ec0cde | 3,627,040 |
import random
def generate_output(model,
sequences,
idx_word,
seed_length=50,
new_words=50,
diversity=1,
return_output=False,
n_gen=1):
"""Generate `new_words` words of outpu... | 8072723e9744e8322de87ebb3437d6e96517e6db | 3,627,041 |
def stagewise_grad(w, X, Y, alpha, valpha):
"""
the gradient loss used in the stage-wise gradient descent (where the value-at-risk is fixed)
Parameters
----------
w : d-array, candidate
X : d-n array, sample
Y : n array, sample
alpha : float, quantile leve... | af2b734c150d65f3ee8d7e6815a4065e31ad754c | 3,627,042 |
def parse_location(url):
"""
Parse latitude and longitude from a Google Maps URL.
URL is in the form:
https://maps.google.com/maps/ms?...&ll=9.029795,-83.299043&...
Sometimes there is a weird ll query param like this:
https://maps.google.com/maps/ms?...&ll=9.029795, -83.299043,255&..... | 6964f031d58d4bcedbced4d6bb90db8e75e1b006 | 3,627,043 |
def conv2d_zeros(name,
x,
width,
filter_size=[3, 3],
stride=[1, 1],
pad="SAME",
logscale_factor=3,
skip=1,
edge_bias=True):
"""Conv2dZeros is just a normal Conv2d layer with zero i... | 77804460ca179eb45bd89b7876f4ac2842f93c87 | 3,627,044 |
def deepcopy(value):
"""
The default copy.deepcopy seems to copy all objects and some are not
`copy-able`.
We only need to make sure the provided data is a copy per key, object does
not need to be copied.
"""
if not isinstance(value, (dict, list, tuple)):
return value
if isins... | e74c22cb8980ce70085f3d58873698c5a03c4681 | 3,627,045 |
import re
def split_delimited_symbol(symbol):
"""
Takes in a symbol that may be delimited and splits it in to a company
symbol and share class symbol. Also returns the fuzzy symbol, which is the
symbol without any fuzzy characters at all.
Parameters
----------
symbol : str
The pos... | 770247e4b6a61794aedb73deab3fd85329b5a7c1 | 3,627,046 |
import urllib
import hashlib
def gravatar(email, size=48):
"""hacked from djangosnippets.org, but basically given an email address
render an img tag with the hashed up bits needed for leetness
omgwtfstillreading
"""
url = "http://www.gravatar.com/avatar.php?%s" % urllib.urlencode({
'grava... | 8133e9857311e2163c7fde400db7d47aedc4da86 | 3,627,047 |
def carli(
p0: np.array,
p1: np.array,
) -> float:
"""
Carli bilateral index, using price information.
.. math::
\\text{Carli} = \\frac{\\sum_{i=1}^{n} p_i}{\\sum_{i=1}^{n} p_0}
:param p0: Base price vector.
:param p1: Current price vector.
"""
return np.mean(p1 / p0) | 6361747561919d0c0451c87e387994f82708cd70 | 3,627,048 |
def format_outcome_results(outcome_results):
"""
Cleans up formatting of outcome_results DataFrame
:param outcome_results: outcome_results DataFrame
:return: Reformatted outcomes DataFrame
"""
new_col_names = {"links.learning_outcome": "outcome_id"}
outcome_results = outcome_results.rename(c... | 9c22481725f2782d614b48582edfcd60db284c13 | 3,627,049 |
from torch import from_numpy, autograd
def infer(batch, model, lite, framework):
"""
Perform inference on supplied image batch.
Args:
batch: ndarray
Stack of preprocessed images
model: deep learning model
Initialized EfficientPose model to utilize (RT, I, II, I... | 671e33563a2b890b089c475600c3f74c8245fb18 | 3,627,050 |
import os
def get_package_data(package):
"""
Return all files under the root package, that are not in a
package themselves.
"""
walk = [(dirpath.replace(package + os.sep, "", 1), filenames)
for dirpath, dirnames, filenames in os.walk(package)
if not os.path.exists(os.path.j... | a3e52a03681fdd65c46798b79a7f1427a16221d3 | 3,627,051 |
import sys
import requests
def delete_saved_search(search_name, owner):
"""Deletes an existing saved search. This is used when overwriting a saved search."""
try:
voyager_server = sys.argv[2].split('=')[1].split('solr')[0][:-1]
get_url = "{0}/api/rest/display/ssearch/export".format(voyager_ser... | f923b2acd95f07ae4d96b46119cf8ead283be1f6 | 3,627,052 |
def get_edges(t, p):
"""
Gets the edges (segments) that contain point p as their right
endpoint or in the interior
"""
lr = []
lc = []
for s in AVLTree(t):
if s.rp == p:
lr.append(s)
elif s.lp == p and s.status == INTERIOR:
lc.append(s)
elif si... | 6252f4ca41836f6f7203d115d37cc4da6d220b0e | 3,627,053 |
def register_derived_unit(symbol, singular_name, base_unit, multiple=1, plural_name=None):
"""Registers a unit based on another unit.
i.e. it should be a measure of the same quantity."""
return register_unit(symbol, singular_name, base_unit.quantities,
base_unit.quantity_vector, mul... | d069ab157c5c85729a1a9a2ea8b77419d483b601 | 3,627,054 |
from typing import Optional
import requests
def soup(
url: str, *args, session: Optional[requests.Session] = None, **kwargs
) -> bs4.BeautifulSoup:
"""Get a url as a BeautifulSoup.
Args:
url: The url to get a soup from.
*args: Passed to session.get().
session: The session to use t... | 25e37b9ecf59a5aa9ef4ef5d6ee50c3b33f123ec | 3,627,055 |
from win32api import GetSystemMetrics
def _get_max_width():
"""Hamta information om total skarmbredd och -hojd
"""
#Hamta information om total skarmbredd over alla anslutna skarmar
width = GetSystemMetrics(78)
#Hamta information om total skarmhojd over alla anslutna skarmar
height = GetSystemM... | e2382eab98faecd7d8cf9ba2689897d2512c39db | 3,627,056 |
def preprocess_stack_parallel(hier_graph_dict:dict,circuit_name,G):
"""
Preprocess the input graph by reducing parallel caps, series resistance, identify stacking, adding parallel transistors.
Parameters
----------
hier_graph_dict : dict
dictionary of all circuit in spice file
circuit_n... | dd16d10fd321c01f27a83963165041519edbe235 | 3,627,057 |
def list_table_names():
"""List known table names from configuration, without namespace."""
return get_config().yaml['schemas'].keys() | 27dcf56818a120ebfffc633c36ade84b4fc905cf | 3,627,058 |
def execute_quantum_request(backend, quantum_request):
"""
Takes a quantum request and execute the content,
returns the messages for Alice and Bob.
"""
method = quantum_request["method"]
A_basis = quantum_request["A_basis"]
B_basis = quantum_request["B_basis"]
if method == "BB84":
... | 1e80a8dcfcd2908fe1916c76a8340c2127056e57 | 3,627,059 |
def get_ResidualDemand(demand_sector):
"""loader function for parameter ResidualDemand
"""
return get_demand_sector_parameter("ResidualDemand",
demand_sector) | d467be1ed8be1ff5a048558cfad53422aaa03399 | 3,627,060 |
import six
def parse_bar_separated_phrase(bar_separated_phrase):
"""
Parses a vertical bar separated phrase into a Phrase object.
The expect format is that used by e.g. the LCC:
Aber|KON es|PPER gibt|VVFIN keine|PIAT Garantie|NN
:param bar_separated_phrase:
:return:
"""
assert i... | 2773e51f1667318a8a7b86e7771cc81803bbeaaa | 3,627,061 |
def preprocess(filename):
"""
Preprocesses the file at the specified name and returns only
the branching (conditional) lines in the dump, defined to have
(in the format specified for the offline dump versions):
1) Reads the flags register (that is, conditionRegister == 'R'), and
2) Is either tak... | a3ccab311151ed45d8c6a4ff776fc410381098a8 | 3,627,062 |
import os
def load_paste_app(filename, appname):
"""Builds a wsgi app from a paste config, None if app not configured."""
filename = os.path.abspath(filename)
app = None
try:
app = deploy.loadapp("config:%s" % filename, name=appname)
except LookupError:
pass
return app | 374b933923367756e091a723789cc666f251fec3 | 3,627,063 |
def Hunter_Lab_to_XYZ(
Lab: ArrayLike,
XYZ_n: ArrayLike = TVS_ILLUMINANTS_HUNTERLAB[
"CIE 1931 2 Degree Standard Observer"
]["D65"].XYZ_n,
K_ab: ArrayLike = TVS_ILLUMINANTS_HUNTERLAB[
"CIE 1931 2 Degree Standard Observer"
]["D65"].K_ab,
) -> NDArray:
"""
Converts from *Hunter... | e9270f674a63b728c15b3865134c01f0d6197dfd | 3,627,064 |
def post_multipart(host, selector, fields, files):
"""
Post fields and files to an http host as multipart/form-data.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return the server's re... | d8a50bc086f673798c33b191248f059f44f07aea | 3,627,065 |
def client():
"""Static link to MongoDB connection."""
return AsyncIOMotorClient(URI) | 3a48977481d3cba66f98b459d559bd78974748e5 | 3,627,066 |
def mask_ring_median(values_array, positions_array, alpha): # pragma: no cover
"""Find outlier pixels in a single ring via a single pass with the median.
Parameters
----------
values_array : ndarray
The ring values
positions_array : ndarray
The positions of the values
alpha: fl... | 7223e985ccf9e6f395f1ae92326d3743190296b2 | 3,627,067 |
from core.models import Snapshot
from pathlib import Path
from typing import List
def load_main_index(out_dir: Path=OUTPUT_DIR, warn: bool=True) -> List[Link]:
"""parse and load existing index with any new links from import_path merged in"""
try:
return Snapshot.objects.all()
except (KeyboardInte... | b02ab8349d44553c7780255867edceaa89a68c5d | 3,627,068 |
import subprocess
def upstream(env=env):
"""Get 'upstream' URL for the git repository."""
remotes = remotes('fetch')
# Try the remote tracking value for this branch
try:
upstream = subprocess.check_output(
['git', 'rev-parse', '--symbolic-full-name', '@{u}'], env=env,
).de... | 9c680f2a06b7d38be7b9ee800f537e74bd0bc8e8 | 3,627,069 |
def ref_model_and_multivariate_training_data(training_data_covar_complex):
"""
defines a multivariate GP model and the data it is defined by
:return: covars
:return: train_X, train_Y (training data, from custom_models_simple_training_data_4elements above)
:return: model_obj (model object, SingleTask... | b56e9f211bcc1d526f4526172f81ee321518880f | 3,627,070 |
def get_all_movies(request):
"""
List of all movies names
"""
try:
name = request.GET.get('name', None)
offset = request.GET.get('offset', 0)
limit = request.GET.get('limit', 10)
movies_list = []
count = 0
if not name:
movies_list = Movie.objects.filter().order_by('-date_created')[offset:limit]
... | df426e8a7331cc6a8458d647ebef8aca350145f1 | 3,627,071 |
def is_email_or_url(string: str) -> bool:
"""Checks if string is either an email or url.
"""
out = False
try:
URL_VALIDATOR(string)
out = True
except ValidationError:
pass
try:
URL_VALIDATOR(string)
out = True
except ValidationError:
pass
... | 2e8e0540ee1a81b898287b7b54509ce46f9bcacf | 3,627,072 |
def get_synthetic_preds(synthetic_data_func, n=1000, estimators={}):
"""Generate predictions for synthetic data using specified function (single simulation)
Args:
synthetic_data_func (function): synthetic data generation function
n (int, optional): number of samples
estimators (dict of ... | c2e775c894fdb6b66d099a8d7130d3458e6cb381 | 3,627,073 |
def arrays_from_dataset(dataset):
"""Converts a tf.data.Dataset to nested np.ndarrays."""
return tf.nest.map_structure(
lambda tensor: np.asarray(tensor), # pylint: disable=unnecessary-lambda
tensors_from_dataset(dataset)) | 35db90ed14481fd635710b220c9cb7270cf0fa58 | 3,627,074 |
def ldns_buffer_status_ok(*args):
"""LDNS buffer."""
return _ldns.ldns_buffer_status_ok(*args) | ad2299bedb24fae1098fd8a48f25c5d42e9a3f26 | 3,627,075 |
import argparse
import logging
import time
def parse_args() -> argparse.Namespace:
"""Parse command line arguments
:return: argparse.Namespace
"""
parser = argparse.ArgumentParser()
parser.add_argument('--log', dest='log', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
... | c51e56210bb3a191ad50b0e4535fe6ffe6c8b57f | 3,627,076 |
import torch
def upsample(img, scale, border='reflect'):
"""Bicubical upsample via **CONV2D**. Using PIL's kernel.
Args:
img: a tf tensor of 2/3/4-D.
scale: must be integer >= 2.
border: padding mode. Recommend to 'REFLECT'.
"""
device = img.device
kernels, s = _weights_upsample(scale)
kernel... | 68f30b9f94139a9c1f6222d9d9082e02251e0b42 | 3,627,077 |
import copy
def first_round_phase(tableau, phase_stabilizer, phase_destabilizer):
"""This phase round adds a diagonal matrix D to the Z stabilizer matrix such that Z + D = M*M' for some
invertible M"""
num_qubits = int(len(tableau[0, :]) / 2)
x_destab = tableau[0:num_qubits, 0:num_qubits]
z_destab... | e798da4e1700592b4089358f45fb883b3b81a629 | 3,627,078 |
async def read_address2account(address: PyAddress, cur: Cursor):
"""read account by address or raise exception"""
user = await read_address2userid(address, cur)
if user is None:
raise BlockChainError('Not found account {}'.format(address))
return await read_account_info(user, cur) | 366b1d28af966bd2deebbdb63d2f203f1169ae50 | 3,627,079 |
def _get_ntddi(osvi):
"""
Determines the current operating system.
This function allows you to quickly tell apart major OS differences.
For more detailed information call L{kernel32.GetVersionEx} instead.
@note:
Wine reports itself as Windows XP 32 bits
(even if the Linux host is 64 ... | 54ca095610a0eb92da244c55d9f7313985699c9e | 3,627,080 |
def mel_dropout(mel: tf.Tensor, drop_prob: int = 0.05) -> tf.Tensor:
""" mel drop out
Args:
mel (tf.Tensor): [freq, time] float32, float32
drop_prob (int, optional): keep prob. Defaults to 0.05.
Returns:
tf.Tensor: [freq, time] float32, float32
"""
return tf.nn.dropout(mel, rate=1 - drop_prob) | ea3d42dcba9599197deb5399cfed1c9b66f00c20 | 3,627,081 |
def getPortableIpRangeServices(config):
""" Reads config values related to portable ip and fills up
services accordingly"""
services = {}
attributeError = False
if config.portableIpRange.startip:
services["startip"] = config.portableIpRange.startip
else:
attributeError = True
... | 0b2a9c863b4b1ccf0084ff4f8bbc4d4f8af7e2a1 | 3,627,082 |
from datetime import datetime
import functools
import time
def function_timer(func):
"""This is a timer decorator when defining a function if you want that function to
be timed then add `@function_timer` before the `def` statement and it'll time the
function
Arguments:
func {function} -- it t... | 6ddcca82ae60aafb2c072e62497f8b27d557ccdc | 3,627,083 |
def breadcrumbs(category):
"""
Renders a category tree path using a customizable delimiter.
Usage::
{% breadcrumbs <category> %}
Example::
{% breadcrumbs category %}
"""
return {'ancestors': category.get_ancestors()} | 3c83a7ad7e8ae30ad297fd9d3d7aa5ffa5631449 | 3,627,084 |
def resnext34(**kwargs):
"""Constructs a ResNeXt-34 model.
"""
model = ResNeXt(BasicBlockX, [3, 4, 6, 3], **kwargs).cuda()
name = "resnext34"
return model, name | 542cb4810fb56209ed8c504a5dd985e7d323725a | 3,627,085 |
def _draw_latex_header(table, drop_columns):
"""Draw the Latex header.
- Applies header border if appropriate.
Example Output:
\hline
Name & Age & Nickname \\
\hline
"""
out = ""
if table._has_border():
out += _indent_text("\\hline\n", 3)
# Drop header colu... | 804361428780ee7782dd53cbc48bdef7435fd342 | 3,627,086 |
def register():
"""Register a new user, and send them a confirmation email."""
form = RegistrationForm()
if form.validate_on_submit():
user = User(
first_name=form.first_name.data,
last_name=form.last_name.data,
email=form.email.data,
confirmed=True,
... | 75cee330a981a36553c5680e93d0d7ef0f100aa1 | 3,627,087 |
from typing import List
def combine_results_dicts(results_summaries: List[dict]) -> dict:
"""For a list of dictionaries, each with keys 0..n-1,
combine into a single dictionary with keys 0..ntot-1"""
combined_summary = {}
n_overall = 0
for d in results_summaries:
n_this = len(d)
fo... | 67e5654b3f4b045526bc181ddb9b05eb9f7ce018 | 3,627,088 |
import json
def svc_get_objects_in_collection(database, collection):
"""
Get objects from a collection.
These forms of query strings are supported
* No query string implies all objects in a collection are returned
* A query string with a single "query_string" parameter results in the value of this... | 4212e350c88e29d914ecc830508c88e849e23d20 | 3,627,089 |
def conv_model(features, labels, mode):
"""2-layer convolution model."""
# Reshape feature to 4d tensor with 2nd and 3rd dimensions being
# image width and height final dimension being the number of color channels.
feature = tf.reshape(features[X_FEATURE], [-1, 28, 28, 1])
# First conv layer will compute 32 ... | d371901c36c513cb2db629414320719759dda291 | 3,627,090 |
def MapColoringCSP(colors, neighbors):
"""Make a CSP for the problem of coloring a map with different colors
for any two adjacent regions. Arguments are a list of colors, and a
dict of {region: [neighbor,...]} entries. This dict may also be
specified as a string of the form defined by parse_neighbors.""... | 8c79a9f5f0237d0e6891d2ebe29b93e5538e44ef | 3,627,091 |
def direction_resend_n3(limit):
"""
Вернуть:
Направления, в к-рых все исследования подтверждены, и подтверждены после определенной даты
в SQL:
"""
with connection.cursor() as cursor:
cursor.execute(
"""
SELECT id FROM public.directions_napravleniya
WHERE ... | 1fabb5260d130b0953091b2205d48ae10f68a3cd | 3,627,092 |
def StringToId(peg_positions):
""" input a list of strings representing peg positions
returns the game bitfield as integer number
"""
my_string = [''] * 36
cur_pos = 0
cur_bitfield = 0
for row in ['A', 'B', 'C', 'D', 'E', 'F']:
for col in ['1', '2', '3', '4', '5', '6']:
... | 71845dd2a9166bf1e43fc68040de81f93806b322 | 3,627,093 |
def hide(obj):
"""Convert object to hidden task.
"""
converted_object = convert(obj, Hidden=True)
return converted_object | d106fe028ed2be620261d77a53c3f3b299295c10 | 3,627,094 |
from datetime import datetime
def trim_prediction(
data,
prediction_days,
history_days=CREST_RANGE
):
"""trim predicted dataframe into shape for results
Args:
data (:obj:`pandas.DataFrame`): data reported
history_days (int): number of days BACK to report
predic... | eeb2120568392e732775c8f0d24a3a572dff948e | 3,627,095 |
def series_simple_math(
ser: pd.Series, function: str, number: int
) -> pd.core.series.Series:
"""Write some simple math helper functions for series.
Take the given series, perfrom the required operation and
return the new series.
For example. Give the series:
0 0
1 1
... | 4ade703df1de1f16315f5c0be1a2019f4015b89c | 3,627,096 |
def _gl_matrix(array):
"""
Convert a sane numpy transformation matrix (row major, (4,4))
to an stupid GLfloat transformation matrix (column major, (16,))
"""
a = np.array(array).T.reshape(-1)
return (gl.GLfloat * len(a))(*a) | 5a1678a505d813e04e512841140aec8fdd01a888 | 3,627,097 |
def create_vshieldr_controller(vmm_domp, provider, vcenter_domain, controller, host_or_ip, **args):
"""Create vShield Controller"""
args = args['optional_args'] if 'optional_args' in args.keys() else args
vmm_ctrlrp = CtrlrP(vmm_domp, controller,
hostOrIp=host_or_ip,
... | 89c0f98f759ca3b5f6a41ffafd3c56041790049b | 3,627,098 |
from typing import List
from typing import Optional
def get_all_by_type_and_status(
*, db_session, service_type: str, is_active: bool
) -> List[Optional[Service]]:
"""Gets services by type and status."""
return (
db_session.query(Service)
.filter(Service.type == service_type)
.filt... | 3c52ce959a8d065c1f7a908f4925e9517ebdb39f | 3,627,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.