content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Union
from typing import Optional
import sympy
def exponentiate_fermion_operator(
fermion_generator: Union[FermionOperator, InteractionOperator],
transformation: str = "Jordan-Wigner",
number_of_qubits: Optional[int] = None,
) -> Circuit:
"""Create a circuit corresponding to the exp... | a6c4e8203da1d1864dc3ee37a5c7b807b3f33b62 | 3,607,500 |
def mock_stats(
url,
token=None,
version=None):
"""mock_stats
mock stats
:param url: IEX resource url
:param token: optional - string token for your user's
account
:param version: optional - version string
"""
val = {
'url': url,
'version': ... | ef3f5df8f881575131ad4b9fd7a8baed6b6b4840 | 3,607,501 |
def build_help_text(command_class):
"""Generate help text from a command class."""
command = command_class()
parser = command.create_parser({})
return parser.format_help() | 3fc8491e37db2f0b96144ad0b34723ceb71a51ca | 3,607,502 |
import io
def read_names(f):
"""Read names, specified one per line, from a file."""
return (line.strip() for line in io.open(f, 'r', encoding='utf-8')) | 98724005ef5c647aa31205bc8afd07da50ece002 | 3,607,503 |
def create_clauses(m_int, true_p_int=None, true_q_int=None, apply_preprocessing=True, verbose=True):
"""
Creates clauses for the VQF algorithm.
If true_p_int or true_q_int are provided, algorithm treats their length as known.
This also means that it sets the leading bits to 1.
It returns dictionari... | 36f06dd83cc86fe7badd17de59554e0bed4880ff | 3,607,504 |
import numpy
def Sens_m(poly, dist, **kws):
"""
Variance-based decomposition/Sobol' indices.
First order sensitivity indices.
Args:
poly (chaospy.poly.ndpoly):
Polynomial to find first order Sobol indices on.
dist (Dist):
The distributions of the input used in... | 9069d726ad4d34c9ee2653532bf13fc4d2c00450 | 3,607,505 |
import getpass
def user():
"""
Return user (string), taken from environment or prompt
"""
try:
nexpose_user = environ["NEXPOSE_USER"]
except KeyError:
nexpose_user = getpass.getpass(prompt="Nexpose user:")
return nexpose_user | 7d05176b2ec147955ddc32b9c5468d568d9cda48 | 3,607,506 |
import uuid
def convert_uuid_to_es_fmt(uuid_str):
"""Converts uuid to e-series compatible name format."""
uuid_base32 = encode_hex_to_base32(uuid.UUID(str(uuid_str)).hex)
return uuid_base32.strip('=') | b8279f6c783da840326662d99f8e54a4371c1464 | 3,607,507 |
def QT_FROM_RR(rr):
"""
Returns the interval of acceptable QT durations with the given RR
intervals. It applies a linear regression model with the coefficients
obtained from the referenced study.
"""
return Iv(m2s(220) + 0.1 * rr.start, m2s(240) + 0.25 * rr.end) | ddf43e19faec4b95e9fe0f0fee076cfe1de3c830 | 3,607,508 |
import os
from datetime import datetime
def make_scores_df(directory):
"""
Takes a directory containing csvs (directory) The function concatenates all the dfs recording the users' scores over time.
"""
csv_list = []
filenames = os.listdir(directory)
user_scores_over_time = {}
for j in r... | 30767caac6a1de92a6b423cc98ff61154270597f | 3,607,509 |
import time
def _Retry(func, *args, **kwargs):
"""Retries the function if an exception occurs.
Args:
func: The function to call and retry.
*args: Args to pass to the function.
**kwargs: Kwargs to pass to the function.
Returns:
Whatever the function returns.
"""
retries = _RETRIES
while T... | 0d42e649612e7398e14d9ce4f303ae770efebc1f | 3,607,510 |
def get_astroconda_list(flavor="dev"):
"""return the list of astroconda packages.
Parameters
----------
flavor: string
The sub type of astroconda distribution
"""
if flavor not in ["dev", "contrib"]:
raise ValueError("Only dev and contrib flavors currently exist")
astrocon... | 26be357733ee80fd84f539edc9a93195972f74c6 | 3,607,511 |
import requests
def _get_pypi_versions():
"""List releases available from PyPI."""
response = requests.get(
"https://pypi.org/pypi/faculty-cli/json", timeout=1
)
versions = response.json()["releases"].keys()
return [StrictVersion(v) for v in versions] | 68ed3cdd9aca74673560089686ad7d301b268d01 | 3,607,512 |
import time
def performance(fn):
"""计算性能的修饰器"""
@wraps(fn)
def measurePerformance(*args, **kwargs):
t1 = time.time()
result = fn(*args, **kwargs)
t2 = time.time()
print(f'{fn.__name__}: {t2 - t1: .5f}s')
return result
return measurePerformance | 03f64c9cf472613b35ce288ac1b260d7f055a46b | 3,607,513 |
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Google Maps trackers."""
domain_data = hass.data[DOMAIN][config_entry.entry_id]
coordinator = domain_data[COORDINATOR]
tracked = set()
max_accuracy = config_entry.options.get(ATTR_GPS_ACCURACY)
@callback
def ... | 487b4b94ef0a9d478f589c357e0e2794c7709935 | 3,607,514 |
def update_fps(fps: int):
"""update_fps."""
logger.info("Updating fps")
logger.info(" fps: %s", fps)
return "ok" | 05a2fe397977c34f3e22e93354eb26b092c29239 | 3,607,515 |
import torch
def max_aggregation_fn(features, index, l):
"""
Arg: features: N x dim
index: N x 1, e.g. [0,0,0,1,1,...l,l]
l: lenght of keypoints
"""
index = index.unsqueeze(-1).expand(-1, features.shape[-1]) # N x 64
set_features = torch.zeros((l, features.shape[-1]), device=features.dev... | d75cb9574bbf3e80826b9d149529eee88949b7b5 | 3,607,516 |
from datetime import datetime
def pretty_date(time=False):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
"""
now = datetime.utcnow()
diff = now - time
second_diff = diff.seconds
day_d... | f5b449430dae7cf86fa6edb0aae29e5bc7e3efea | 3,607,517 |
def has_data():
"""Check if the PhosphoSite data is available and can be loaded.
Returns
-------
bool
True if the data can be loaded, False otherwise.
"""
global _has_data
if _has_data is None:
try:
_get_phospho_site_dataset()
# If we succeeded withou... | 0097fc4fc07e06244970e3a04ec68e3f52739b17 | 3,607,518 |
def getValue(inpt):
"""reads in an input field and extracts the value of it
Args:
inpt ([type]): html input field
Returns:
str: value of that field
"""
r: str = None
if inpt:
r = inpt.get('value')
return r | 7023ceb6724999b8d892307ac4c9bb822df0bc82 | 3,607,519 |
def format_cols_2digit(df, skip_last_col=True):
"""Formats a dataframes columns so that numbers are always two-digits (padded with 0)
Parameters
----------
df : pandas DataFrame
Input DataFrame.
skip_last_col : bool
A special case, where the very last column contains text, rather th... | 5c9bc98ed6298f8f3d181432320cc69dc4c30ea2 | 3,607,520 |
def parse_probe_chunk(chunk):
"""Prase nmap probe / port strings
"""
result = {'name': '', 'payload': '', 'ports': []}
lines = chunk.splitlines()
for line in lines:
if line.startswith('Probe '):
name, payload = parse_probestr(line)
result['name'] = name
r... | 3767d6d6e8fc4e73d633f632e7a5928e298701e3 | 3,607,521 |
from typing import Optional
from typing import Sequence
import warnings
def build_job_submit_torque(
job_name: str,
script_name: str,
target_system: Optional[TARGET_SYSTEM] = "woody",
nodes: Optional[int] = 1,
ppn: Optional[int] = 4,
walltime: Optional[str] = "24:00:00",
args: Optional[Seq... | b8e0be01c26d0fe007af9a024c4df0d5c606822a | 3,607,522 |
def load_shader(shaderpath, shadername, vertex_format_list=None,
fragment_formatlist=None):
"""Funcion que carga un shader y retorna un objeto del tipo ShaderProgram"""
fragment = Shader(shaderpath + shadername + ".fsh", FRAGMENT, True,
fragment_formatlist)
vertex = Sha... | cad1c71f19e3e964cb642c0957223b78806fafe0 | 3,607,523 |
def pdfgen(mean, sdev, bins_list):
"""
A function to generate 3 probability density function data
Parameters:
mean1 (numpy.ndarray, required): The means of the datasets.
sdev1 (numpy.ndarray,1 required): The standard deviation of
the dataset
bins_list(numpy.ndarray, requi... | dde1d1559f46d95f27e0cc08d91d851fe1825167 | 3,607,524 |
def soup_from_restart_files(basename, skip_solvent=True):
"""
Reads a Soup from the restart files.
"""
for module in [amber, gromacs, namd]:
try:
top, crds, vels = module.get_restart_files(basename)
return module.soup_from_restart_files(
top, crds, vels, skip_solvent)
except util.F... | d859c29268dba5c58734737e987efea4d456f869 | 3,607,525 |
def ec_filter(query_list, hit_list, ec_number):
"""
"""
passed_query = query_list.copy()
for i, query in enumerate(query_list):
anno = hit_list[i]
anno_ec_number = anno.split("|")[0].replace(">EC:", "").split(".")
if len(anno_ec_number) < 3:
passed_query.pop(i)
... | b8b66f19f79dc60cd2d044f4bcfdd46d3a3908b7 | 3,607,526 |
def remove_noisy_channels(data, data_properties, hist_num_buckets=100, hist_max_diff=10):
"""
Removes noisy channels from data.
Parameters
----------
data : NumPy Array
SPM data supplied by the user
data_properties : dict
channel properties of the SPM data
... | 461aa8c069f3f4ef1af99dbc207835eadca5946f | 3,607,527 |
def get_relative_path(root, path):
"""
Return the relative path from root to path, which should be nested under root.
"""
precondition(path.startswith(root), '%s is not under %s' % (path, root))
return path[len(root) :] | 986f2f1a8dd69ae15b4ee41d3bef635d3889dffb | 3,607,528 |
import ast
def clean_data(s):
"""Cleans the main `mag_papers` table.
Args:
s (`sqlalchemy.orm.session.Session`): PostgreSQL connection.
Returns:
mag (pd.DataFrame)
"""
# Read tables
mag = pd.read_sql(s.query(Paper).statement, s.bind)
flag = pd.read_sql(s.query(CoreContro... | cc5b6cfccb1a97076dd31b70469b4f1437bc2011 | 3,607,529 |
import sys
import os
def check_infrastructure_variables(project_xml, resources_xml, compss_home,
app_name, file_name, external_adaptation):
# type: (str, str, str, str, str, bool) -> dict
""" Checks the infrastructure variables and updates them if None.
:param project_x... | fa925bc247559c19941709327bcf80f561171b94 | 3,607,530 |
def L2_norm(doc_vec):
"""
Renormalize document vector onto the hypersphere.
Args:
doc_vec (numpy array): Document vector
Returns:
doc_vec: Normalized document vector
"""
# Renormalize onto the hypersphere
doc_vec /= np.linalg.norm(doc_vec)
# Sanity check, L2 norm and ... | 994114e04cb8051e42d8525878c54dc182d0a415 | 3,607,531 |
import sys
def FT2(x, y, f):
"""
2D Fourier Transform
Input Parameters:
x, y (1D array): axis range
f (2D numpy array of shape (x.size, y.size)): array to FT
Output Parameters:
F (2D numpy array of shape (x.size, y.size)): FT
Example:
... | a9bce5c92be49cdea6fe343f2dc122a6765c30c8 | 3,607,532 |
import time
def wait_for_text_not_visible(
driver, text, selector, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT
):
"""
Searches for the text in the element of the given selector on the page.
Returns True if the text is not visible on the page within the timeout.
Raises an exception if the te... | 2eb69b48b106e532811cb76dc75d5cb699e6d553 | 3,607,533 |
import os
def check_badger_config(badger_config, badger_dir):
"""
Make sure the badger file contains all the required info. Fill in default values if they don't exist yet.
nick-names and defaults for inputs/outputs are added automatically.
FIXME: this could also be done with some kind of json schema... | 9476198ecf62b5a084bc1bb6b150a673e68441f0 | 3,607,534 |
def reverse_complement_no_loops(seq):
"""Return WC complement of a base without loops"""
# Initialize rev_seq to a lowercase seq
rev_seq = seq.lower()
# Substitute bases
rev_seq = rev_seq.replace('t','A')
rev_seq = rev_seq.replace('a','T')
rev_seq = rev_seq.replace('g','C')
rev_seq = rev... | 2a94d38827cbda95272776b0bea652af9d30b64d | 3,607,535 |
def edit_assignment_group(request_ctx, course_id, assignment_group_id, **request_kwargs):
"""
Modify an existing Assignment Group.
Accepts the same parameters as Assignment Group creation
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param course_... | 635b07a5e230a446e6ce698c1b14ee4b0c87d085 | 3,607,536 |
import time
def RunInteractive(filter_text, modified_base, modified_client):
"""Runs interactive mode when presubmit is run as a standalone application.
This will run all files in the ontology as if they were new.
Args:
filter_text: command line arguments. The only available argument is
'match:<valu... | 3c0584d951d46827eebf124cfd23af508c616ebb | 3,607,537 |
from typing import Callable
def simplex_integral(
f: Callable, num_classes: int, boundary_offset=1e-10, coord_sum: float = 1, **kwargs
):
"""
Performs an integral over num_classes-1 dimensional simplex using scipy
:param f: function to integrate over the simplex. Should accept num_classes-1 variables... | 278cc82976178617784e980c30a853b136cb0689 | 3,607,538 |
from collections import OrderedDict
def update(data_df, cal_dict, param, bound, start, end):
"""Update calibration times for give parameter and boundary"""
if param not in cal_dict["parameters"]:
cal_dict["parameters"][param] = OrderedDict()
if bound not in cal_dict["parameters"][param]:
... | f8c63a528ad6533938f215179c17bd236eefeb67 | 3,607,539 |
import json
def addRemoteFriend():
"""
Processing POST method from local for adding friend on the server side
:return: Code 200 if ok
"""
method = request.method
if(method == "POST" and checkPassword(request, app.admin_password)):
j = json.loads(request.json)
username = j['user... | ef023de0ba4347b82ae0336915b2c9ec30acefd9 | 3,607,540 |
def manage_simple_models(request, operation, model):
"""
A unified handler function for all simple models
Parameters
----------
request :
operation : str
Currently supported operations: create, delete
model : str
Currently supported models:
Returns
-------
"""
... | 4737ae1d377bcd292beae56497609f13856d5076 | 3,607,541 |
import itertools
def euler131(lim=1000000):
"""Solution for problem 131."""
# m^3 = n^3 + p*n^2 = n*n*(n+p)
# 1) Proof that this is equivalent to n and (n+p) being perfect cube
# Let m = prod(pi^ei) be the prime decomposition of m
# n = prod(pi^fi) n
#... | 77036cb8d55a5ce14ba23ca5a6f90382672e5c1f | 3,607,542 |
def viaCombusta(obj):
""" Returns if an object is in the Via Combusta. """
return 195 < obj.lon < 225 | 531ab5b5725bf3ed6dc8c8ff99c3980b3533e558 | 3,607,543 |
from typing import Set
from typing import Callable
def route(
path_pattern: str,
http_methods: Set[str],
) -> Callable[..., Callable]:
"""
Register a decorated method so that it can be recognized as a route.
Args:
path_pattern: The end part of a URL pattern. E.g. `/targets` or
... | 2a24f717f7539afe90c1818f37cc4ceeb162ef04 | 3,607,544 |
def label_name(condition):
"""format label name
"""
label = condition.replace("_", " ").split(".")
label[0] = label[0].capitalize()
return " ".join(label) | 06ea2caf9bb881aa016ef3f74999fe376d30cb05 | 3,607,545 |
import numbers
def reshape(tensor, dims_list):
"""Reshape the given tensor by collapsing dimensions."""
shape = get_shape(tensor)
dims_prod = []
for dims in dims_list:
if isinstance(dims, numbers.Number):
dims_prod.append(shape[dims])
elif all([isinstance(shape[d], int) for... | fe228e50a7eb829129bb12434018eedaa51deb87 | 3,607,546 |
def lp(dic, data, pred="default", x1="default", xn="default", ord=8, mode='f',
append='after', bad_roots='auto', mirror=None, fix_mode='on',
method='tls'):
"""
Linear Prediction
Parameters
----------
dic : dict
Dictionary of NMRPipe parameters.
data : ndarray
Array... | ef5454d0fe7e9e53cd8a2da68399998f9208ceda | 3,607,547 |
def query(query_string, database=config.DEFAULT_DB):
"""
Execute a query given by param and return True/False and result.
result is a list of tuples with the query output info
"""
status = True
try:
conn = psycopg2.connect(user=config.USERNAME, \
password=config.PAS... | 269b3e38de5fe7b9c5697ffea2b48a85cfe4e596 | 3,607,548 |
def copresence(acc, w1, w2):
"""Results 1 if a pair of figures is on stage at the same time, and 0
otherwise."""
return int(acc + w1 + w2 > 0) | 3056b25df4a59bc421a3aec3d33e25db8ccb98bd | 3,607,549 |
def qratio(value_unit_1, value_unit_2, unit=None ):
"""
Return a quantity value for ``value_unit_1/value_unit_2``.
If the signature of the associated units are in simplified form,
signature information is retained in the quotient.
When ``unit`` is None, the reference unit is used.
Example ::
... | b60903481b8456a507356153344539ac8dfcc524 | 3,607,550 |
def key_line(cfgmap, key):
"""Get the line number of `key` in `cfgmap`."""
if not hasattr(cfgmap, "key2line"):
key2line = {}
for cfgkey in cfgmap:
key2line[cfgkey] = getattr(cfgkey, "line", -1)
cfgmap.key2line = key2line
return cfgmap.key2line.get(key, -1) | 94649a30f949e868610426642699e9ac43b644be | 3,607,551 |
from dit.utils import is_string_like
def log_func(b):
"""
Returns a base-`b` logarithm function.
Parameters
----------
b : positive float or 'e'
The base of the desired logarithm function.
Returns
-------
log : function
The base-`b` logarithm function. The returned fu... | 15083b0a5d51984647b42ff52799a22550148c08 | 3,607,552 |
def get_lad_list(lads, oa_points):
"""
Get a list of the local authority districts for which we have data for.
"""
oa_points = gpd.overlay(oa_points, lads, how='intersection')
lad_list = oa_points['name'].to_list()
return oa_points, lad_list | e7488b4b0f2a697e67d6708cbd0474dae091efa6 | 3,607,553 |
def _dict_from_labels(labels, separator='='):
"""Create a multidict from label string."""
return MultiDict(((label[0].strip(), label[1].strip()
if len(label) > 1 else None)
for label in (raw.split(separator, 1)
for raw in labels))) | a0614ca8867a8eeb211bfcd31e4c2cfc649515bb | 3,607,554 |
import logging
import torch
import operator
def build_hoi_train_loader(cfg, mapper=None):
"""
A data loader is created by the following steps:
1. Use the dataset names in config to query :class:`DatasetCatalog`, and obtain a list of dicts.
2. Start workers to work on the dicts. Each worker will:
... | 5234707be8d4e8f3eb2badbbae9fe3b9088179c5 | 3,607,555 |
def unf_rsb_Mccain_m3m3(rsp_m3m3, gamma_oil, psp_MPaa=0, tsp_K=0):
"""
Solution Gas-oil ratio at bubble point pressure calculation according to McCain (2002) correlation
taking into account the gas losses at separator and stock tank
ref1 "Reservoir oil bubblepoint pressures revisited; solution gas... | ab4296b7f22af15a8422a3cf0a23826b3ae9f7c7 | 3,607,556 |
def decode_token(request):
"""
Global function that ensures that will be used to decode the token
"""
token = request.headers.get('Authorization')
if token is None:
abort(401, message="No token provided")
try:
payload = jwt.decode(token, Config.SECRET_KEY)
except jwt.De... | 0ae42591c618cb4ba80024d41f0d45780be66d5e | 3,607,557 |
def gen_bool_parse(val):
"""Convert a string, as a human might type it, to a boolean. Unrecognized
values raise an exception.
"""
val = val.strip()
if not val:
return False
try:
return bool(int(val))
except:
pass
ch = val[0]
if ch in {'t', 'T', 'y', 'Y'}:
... | 3c1944c7633f329848569c6cb29af11e145dfa5c | 3,607,558 |
def baremetal_adapter(name, active, section):
"""Config adapter for "baremetal"."""
if not is_full_section(section):
return active
if name == 'MBEDTLS_NO_PLATFORM_ENTROPY':
return True
return include_in_full(name) and keep_in_baremetal(name) | 1db45112caa1031b51973c38ae3e2ef5e68927ac | 3,607,559 |
def params_to_cholesky(params):
"""TODO: docstring."""
params = jnp.atleast_1d(params)
d = params.shape[-1]
n = svec_to_mat_dim(d) # corresponding symmetric matrix dimension
rows, cols = jnp.tril_indices(n)
log_L = jnp.zeros((*params.shape[:-1], n, n)).at[...,
... | b7f4473704e466e8b5ca072ffd37382815a4b2f4 | 3,607,560 |
import inspect
from re import DEBUG
def printf2(*args0):
"""
debugging purposes
decorate the function with it and when executed on test, it will print the
environnements *args0 are the name of var to printf
"""
to_print = []
for arg in args0:
if isinstance(arg, str):
to... | c169b9a4c21417d90407e5d0b034f49f1ca331f6 | 3,607,561 |
import glob
def _expand_glob_path(file_roots):
"""
Applies shell globbing to a set of directories and returns
the expanded paths
"""
unglobbed_path = []
for path in file_roots:
try:
if glob.has_magic(path):
unglobbed_path.extend(glob.glob(path))
... | f765e3063f098d2bf185df619783b428b192b37a | 3,607,562 |
def read_memory_stats(target_file):
"""Reads and parses memory stats."""
target_file.readline()
test_line = target_file.readline()
if "MEMORY" in test_line:
target_string = target_file.readline()
warnings = ""
if target_string.find("WARNING") != -1:
warnings = target_... | a1fafc3d5f5d307e01d2252404a8e4ab8f73cfbf | 3,607,563 |
def read_ply(ply_fn):
"""
Read ply file
:param ply_fn: str
:return:
vertices: N x 3, numpy.ndarray(float)
faces: M x 3, numpy.ndarray(int)
"""
vertices, faces, n_vertices, n_faces = [], [], 0, 0
header_end = False
with open(ply_fn, 'r') as fin_ply:
# Read header
line = fin_p... | 4e2edaed2c20971ea839b96787bf520e83af97b6 | 3,607,564 |
def crop(image: np.ndarray, x: float, y: float, w: float, h: float,
relative: bool = False, loc: Loc = Loc.UPPER_LEFT) -> np.ndarray:
"""Crop an image using an (x,y) point, width, and height.
Args:
image (np.ndarray): Image to be cropped.
x (float): x coordinate of the point (relative ... | 24c33fffde01396965bd9f73f653ba0e86bcbf84 | 3,607,565 |
def stiffnessMatrixFromPot(Epot,u_dof):
""" Return stiffness matrices from an experssion of potential energy and a list of DOF"""
n=len(u_dof)
Ke= zeros(n,n)
for i in range(n):
for j in range(n):
Ke[i,j] = Epot.diff(u_dof[j]).diff(u_dof[i])
return Ke | 40c80daeaa9b059f7648990b55c08d26734a6f86 | 3,607,566 |
def stations_level_over_threshold(stations, tol):
"""Returns a list of tuples, where each contains the name of a station at which the relative
water level is above tol and the relative water level at that station"""
flooded_stations = []
for station in stations:
relative_level = station.relati... | 5c8a7562415e4a3c05f509bc4d922c775368d202 | 3,607,567 |
import collections
def _build_nightly_dict(
registered_ds: FullNamesDict,
stable_version_ds: FullNamesDict,
) -> NightlyDict:
"""Computes the nightly dict from the registered and stable dict."""
nightly_ds = collections.defaultdict(
lambda: collections.defaultdict( # pylint: disable=g-long-lambda
... | 366ca503bfd62c021769ac8c4b366b9c30bb8eaf | 3,607,568 |
def process_results(sources_list):
"""Function that process the results list and transforms them into a list of objects
Args: sources_list: A list of dictionaries that contains news sources details
Returns:
sources_results: a list of news sources objects"""
sources_results = []
for source_item ... | ea3fcd616412a8b0b8c9b03ed36779f81dd3908a | 3,607,569 |
import os
import torch
def train(model, dataloader, val_dataloader, config, logger, rank=0, world_size=1):
"""TODO"""
logger.info(f'My rank : {rank} / {world_size}')
device = rank
optimizer = initialize_optimizer(model.parameters(), config)
scheduler = initialize_scheduler(optimizer, config)
... | 6d0abbe2eaeb8797aea70e0f0b6e2815729364c9 | 3,607,570 |
import torch
def get_box_info(boxes):
"""
input: [batch_size, (x1,y1,x2,y2)]
output: [batch_size, (x1,y1,x2,y2,cx,cy,w,h)]
"""
return torch.cat((boxes / float(IM_SCALE), center_size(boxes) / float(IM_SCALE)), 1) | b5a76f66b08390447b2c49fbfa3350ce5ee66aa7 | 3,607,571 |
def add_index_levels(to, source, fill=""):
"""Add levels to the "to" index so it has all levels in the "source" index. The possible levels are, in this order: "Name", "Site", "Peptide", "Database_ID"
Parameters:
to (pandas.Index or pandas.MultiIndex): The index to add levels to.
source (pandas.Index or... | 42a4f6b58759e106aa28ca4cea7002b25070cf3a | 3,607,572 |
def browser_images(request):
"""display image browser"""
images = []
for full_model_name in settings.image_models():
app_name, model_name = full_model_name.split('.')
model = get_model(app_name, model_name)
if model:
images.extend(model.objects.all())
return render(... | 10adc32b1a50d148310cdf50ac457cd89eead9fe | 3,607,573 |
def cov(X, p):
"""vector autocovariance up to order p
Parameters
----------
X : ndarray, shape (N, n)
The N time series of length n
Returns
-------
R : ndarray, shape (p + 1, N, N)
The autocovariance up to order p
"""
N, n = X.shape
R = np.zeros((p + 1, N, N))
... | a6f8d1fa310e7070653fed013af880a66071bcd0 | 3,607,574 |
import torch
def get_test_loader(transform=None):
"""
Args:
transform (transform): Albumentations transform
Returns:
testloader: DataLoader Object
"""
if transform:
testset = Cifar10SearchDataset(transform=transform, train=False)
else:
testset = Cifar10SearchDataset(train=False)
test... | 28d21160a82a7b1c48822b00875df7dad5f34fe8 | 3,607,575 |
def _is_container_terminated(client, resource_group_name, name, container_name):
"""Check if a container should be considered terminated. """
container_group, container = _find_container(client, resource_group_name, name, container_name)
# If a container group is terminated, assume the container is also te... | 42ceb828397a130fd5a53333faf8cee5875826c0 | 3,607,576 |
def getW(D, K, Mu = 0.5):
"""
Return affinity matrix
[1] Wang, Bo, et al. "Similarity network fusion for aggregating data types on a genomic scale."
Nature methods 11.3 (2014): 333-337.
:param D: Self-similarity matrix
:param K: Number of nearest neighbors
"""
#W(i, j) = exp(-Dij^2/... | 8b8c5bb81acaf9a428a22654677f9ad3ebb5486b | 3,607,577 |
def makeTweetBin(startTime, stopTime):
""" Cuts the tweets into bins based on times
uses pymongo to connect to a db that has a bunch of tweets in it.
Args:
startTime (datetime): the starting time for the bin in datetime format
stopTime (datetime): the stopping point for the bin in datetime forma... | 754e123b482fb3c59257a35092733507fc5df1d1 | 3,607,578 |
def GetOriginalByte(ea):
"""
Get original value of program byte
@param ea: linear address
@return: the original value of byte before any patch applied to it
"""
return idaapi.get_original_byte(ea) | 16c3846da12f5c9f7c6ad5356759fd478cfbeeea | 3,607,579 |
def makeClones(name, num):
""" Creates a list of duplicate objects
- **parameters**, **types**, **return** and **return types**::
:param name: is the name of the Maya object to duplicate
:param num: is the number of duplicate copies to make
:type name: string
:type num: int... | bbc5636cc67c99a44fefb5c40c973ad3f3dc16e0 | 3,607,580 |
def integrand_deflection(r, rhofunc, args):
"""
The integrand for the deflection integral
deflection(R) \sim \frac{2}{R} \int_0^{R} r * sigma(r) dr
"""
return r * projected_mass(r, rhofunc, args) | 9c0de86e4869af5a8da677b7718f82ccb7e9f783 | 3,607,581 |
import json
import traceback
def request_data(api, bam_ip):
"""
Request data
:param api: API
:param bam_ip: IP of BAM -- IPv4
:return:
[Result] -- String
"""
result = None
try:
user_name, password, gateway_url, _ = common.get_configuration()
if not user_name or not ... | 8209aa05bc64d536d821ed1e1b58ad1bbb3cc54e | 3,607,582 |
def strip(context, mapping, args):
"""Strip characters from a string. By default,
strips all leading and trailing whitespace."""
if not (1 <= len(args) <= 2):
# i18n: "strip" is a keyword
raise error.ParseError(_("strip expects one or two arguments"))
text = evalstring(context, mapping,... | 802cd2ed93715842fc31af3c3728434c99de71fc | 3,607,583 |
def parse_site_infos(content_io, namespace, site_info_names):
"""parses information contained in site info elements out of a waterml file;
content_io should be a file-like object
"""
site_infos = {}
for site_info_name in site_info_names:
content_io.seek(0)
site_info_elements = [
... | 6ea28f4dab08cf006339b4a81c9e612519c396c6 | 3,607,584 |
def message():
"""
允许GET是因为在地址栏输入地址转到messages页面需要
POST是因为在messages页面内容点击"提交"按钮需要
主要的bug是转到message页面和message页面都都是同一个路由函数
:return: 返回message页面,并显示所有用户信息
"""
form = request.form
msg = Message.new(form)
# html元素失效
# msgs = '<br>'.join([str(m) for m in Message.all()])
body = rende... | 73da40bad15d4c64f212ef270c8f1bbbf0a48936 | 3,607,585 |
def rotate_image(image, t, q, K):
""" Apply warping corresponding to a random in-plane rotation
Arguments:
- image: Input image
- t, q: Object pose (location,orientation)
- K: Camera calibration matrix
- magnitude: 2 * maximum perturbation per roll
Return:
- image_warped: ... | 1f1aecb5eded0d83bc2236addfc412bc0371a77f | 3,607,586 |
def nth_triangle_number(n):
"""
Compute the nth triangle number
"""
return n * (n + 1) // 2 | 76ebd412200a04ae8a1bf5c4d18122db01cee526 | 3,607,587 |
import click
import json
import pathlib
def create_planetnicfi_command(cli):
"""Creates the stactools-planet-nicfi command line utility."""
@cli.group(
"planetnicfi",
short_help=("Commands for working with stactools-planet-nicfi"),
)
def planetnicfi():
pass
@planetnicfi.c... | 44d21bbffbaea4427d8b1e4166552b241b8ff034 | 3,607,588 |
import re
def check_ignore(item, ignores=[]):
"""
take a string (item)
and see if any of the strings in ignores list are in the item
if so ignore it.
"""
ignore = False
for i in ignores:
if i and re.search(i, str(item)):
# print "ignoring item: %s for ignore: %s" % (ite... | 0d31b2ef2ddbe48a4de7f743c412b1a72a19b774 | 3,607,589 |
def averageOverTime(field,makeTimes=0):
"""Average the values in each time step
If makeTimes is true (1) then we return a field mapping all of the times
to the average. Else we just return the average """
return GridMath.averageOverTime(field,makeTimes); | 10acb39e0043f62884cfed50dc8e356433299fc7 | 3,607,590 |
def to_CASG(code, language):
"""Transform CST provided from ANTLR parsers into a common ASG
Args:
filePath (Path): path of the class
Returns:
Node: A common Abstract Semantic Graph CASG
"""
tree = parse.parsef(code,language, start="compilation_unit", strict=False)
ast_proc = si... | a6cdf2f9862baa5a91ba64c33e4c466e4caa8f1a | 3,607,591 |
def bgfit(im, unc=None, order=1, mask=True):
"""Fit an image background.
Parameters
----------
im : array
The image.
unc : array, optional
Image uncertainties as a 2D array.
order : int
The polynomial order (in one dimension) of the fitting function.
mask : array, optional... | d253c3800685f3a01537efbd5e377479ae77b12a | 3,607,592 |
from typing import Dict
from typing import Any
import requests
def get_vendor_by_org_id(base_url: str, org_id: str) -> Dict[str, Any]:
"""
Get vendor using organization ID
Args:
base_url (str): Pyxis based API url
org_id (str): Organization ID
Returns:
Dict[str, Any]: Vendor ... | 85d8cd8e81bbae80798b4f6da9bd0180d1e95bd7 | 3,607,593 |
def all_segments(N):
"""
Return (start, end) pairs of indexes that orm segments of tour of length N
"""
return [(start, start + length)
for length in range(N, 2-1, -1)
for start in range(N - length + 1)] | d1b70d4f52c930e97ff82920abbf49f5b6d0af56 | 3,607,594 |
def normalize_mac(mac):
"""Remove '-' and ':' characters and lowercase the MAC string.
:param mac: MAC address to normalize.
:return: Normalized MAC address string.
"""
return mac.replace('-', '').replace(':', '').lower() | 9ba40e96f01274eb764f47078e22de34dddfd024 | 3,607,595 |
from argparse import ArgumentParser
from optparse import OptionParser
def main():
"""
Runs when the function is called from the command line. Don't alter this
function directly - instead, edit :func:`on_run` and :func:`add_to_parser`
:returns: A dictionary of the local variables from :func:`on_... | 839f71b3c0de0b1ef92ba50e275ac202bf1c9677 | 3,607,596 |
from typing import Optional
def one_cate_bar_data(
df : pd.DataFrame,
qdc : vs.QuestionDataContainer,
percentage : bool = False,
order : Optional[list] = None,
skip_miss : bool = False,
) -> pd.Series:
"""Obtain summarized data for barplot.
1. Value_counts of a specific column.
2. Re... | e3e0d4dfa2e425b04773fa9f9f91eb87ef764421 | 3,607,597 |
def get_anomalies(predicate, algorithm="lof"):
"""
:param predicate: {pd.dataframe} prediction result generated by get_outlier function
:param algorithm: {str} classification algorithm to get anomalies
:return:
preds: {pd.dataframe} df containing anomalies generated by corresponding algorithm
... | 1bffb998c71ba05249ef39037ec575881cea6d55 | 3,607,598 |
import torch
def epe(input_flow, target_flow):
"""
End-point-Error computation
Args:
input_flow: estimated flow [BxHxWx2]
target_flow: ground-truth flow [BxHxWx2]
Output:
Averaged end-point-error (value)
"""
return torch.norm(target_flow - input_flow, p=2, dim=1).mean() | ff68a331c1f3323585c6a351b4a3da50209ab9b9 | 3,607,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.