content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def GetIdentifierStart(token):
"""Returns the first token in an identifier.
Given a token which is part of an identifier, returns the token at the start
of the identifier.
Args:
token: A token which is part of an identifier.
Returns:
The token at the start of the identifier or None if... | 6b3ad9fb9d43411fc7df147ace872f75c70b5d11 | 11,400 |
def load_spec(filename):
"""
loads the IDL spec from the given file object or filename, returning a
Service object
"""
service = Service.from_file(filename)
service.resolve()
return service | 6dfea85635d3b610ee998999397fc92fd516933c | 11,401 |
import os
import configparser
def connect(db_config_name):
"""
Check the current environment to determine which database
parameters to use, then connect to the target database on the
specified host.
:return: A database connection object.
"""
config_path = os.path.join(
os.path.dir... | bb4a74887c38213a5089de79e06f67b6b8de606f | 11,402 |
import torch
def load_model(file_path, *, epoch, model, likelihood, mll, optimizer, loss):
"""モデルの保存関数
Parameters
----------
file_path : str
モデルの保存先のパスとファイル名
epoch : int
現在のエポック数
model : :obj:`gpytorch.models`
学習済みのモデルのオブジェクト
likelihood : :obj:`gpytorch.like... | ccc7f221164d89ed29326f720becd29e3442c52b | 11,403 |
import re
def valid_account_id(log, account_id):
"""Validate account Id is a 12 digit string"""
if not isinstance(account_id, str):
log.error("supplied account id {} is not a string".format(account_id))
return False
id_re = re.compile(r'^\d{12}$')
if not id_re.match(account_id):
... | 30f3aa9547f83c4bea53041a4c79ba1242ae4754 | 11,404 |
import numpy
def prod(a, axis=None, dtype=None, out=None):
"""
Product of array elements over a given axis.
Parameters
----------
a : array_like
Elements to multiply.
axis : None or int or tuple of ints, optional
Axis or axes along which a multiply is performed.
The de... | c33a506847b13924aa903b5daeece0312cc29c8f | 11,405 |
import random
def sample_pagerank(corpus, damping_factor, n):
"""
Return PageRank values for each page by sampling `n` pages
according to transition model, starting with a page at random.
Return a dictionary where keys are page names, and values are
their estimated PageRank value (a value between... | 32c89d7669718c714663e66a926bb27f9c219c38 | 11,406 |
def guess_layout_cols_lr(mr,
buf,
alg_prefix,
layout_alg_force=None,
verbose=False):
"""
Assume bits are contiguous in columns
wrapping around at the next line
Least significant bit at left
Can eithe... | dbbbf68ee251fb50c413648e97c9957ed7c086ec | 11,407 |
def decrease(rse_id, account, files, bytes, session=None):
"""
Decreases the specified counter by the specified amount.
:param rse_id: The id of the RSE.
:param account: The account name.
:param files: The amount of files.
:param bytes: The amount of bytes.
:param session: The database... | 2ad193e5f50c0bcb19f0d796c7f8b9da115a1f2d | 11,408 |
def get_import_error(import_error_id, session):
"""
Get an import error
"""
error = session.query(ImportError).filter(ImportError.id == import_error_id).one_or_none()
if error is None:
raise NotFound("Import error not found")
return import_error_schema.dump(error) | 37444be97de3c4fa97fba60d87f469c428011db1 | 11,409 |
import requests
import json
def get_violations(nsi_uuid=None):
"""Returns info on all SLA violations.
:param nsi_uuid: (Default value = None) uuid of a service instance.
:returns: A list. [0] is a bool with the result. [1] is a list of
SLA violations associated to a service instance.
"""
... | 83c9688ee401bbb19800f89cc78a07d1af2b2f6f | 11,410 |
def roll_dice():
""" simulate roll dice """
results = []
for num in range(times):
result = randint(1, sides)
results.append(result)
return results | 9a8442ff777c8c03146bcb9a0f8a2dc19e87a195 | 11,411 |
def _read_calib_SemKITTI(calib_path):
"""
:param calib_path: Path to a calibration text file.
:return: dict with calibration matrices.
"""
calib_all = {}
with open(calib_path, 'r') as f:
for line in f.readlines():
if line == '\n':
break
key, value = line.split(':', 1)
calib_all... | 2d71146ce79ce39309930bb8a452c185c35c3061 | 11,412 |
import torch
def _bias_act_cuda(dim=1, act='linear', alpha=None, gain=None, clamp=None):
"""Fast CUDA implementation of `bias_act()` using custom ops.
"""
# Parse arguments.
assert clamp is None or clamp >= 0
spec = activation_funcs[act]
alpha = float(alpha if alpha is not None else spec.def_a... | 44559520faf06fbf9b6f17ac1b29b829840e7f38 | 11,413 |
from typing import Mapping
def root_nodes(g: Mapping):
"""
>>> g = dict(a='c', b='ce', c='abde', d='c', e=['c', 'z'], f={})
>>> sorted(root_nodes(g))
['f']
Note that `f` is present: Isolated nodes are considered both as
root and leaf nodes both.
"""
nodes_having_parents = set(chain.fr... | 67c2043053f82a9a17f148c57bbf4d2501530f99 | 11,414 |
def _GetRemoteFileID(local_file_path):
"""Returns the checked-in hash which identifies the name of file in GCS."""
hash_path = local_file_path + '.sha1'
with open(hash_path, 'rb') as f:
return f.read(1024).rstrip() | 4a06dcdd30e379891fe3f9a5b3ecc2c4fd1a98ed | 11,415 |
def stress_stress(
bond_array_1, c1, etypes1, bond_array_2, c2, etypes2, sig, ls, r_cut, cutoff_func
):
"""2-body multi-element kernel between two partial stress components
accelerated with Numba.
Args:
bond_array_1 (np.ndarray): 2-body bond array of the first local
environment.... | c832b6951774eff3b37dd3a674be74ad917409df | 11,416 |
def is_color_rgb(color):
"""Is a color in a valid RGB format.
Parameters
----------
color : obj
The color object.
Returns
-------
bool
True, if the color object is in RGB format.
False, otherwise.
Examples
--------
>>> color = (255, 0, 0)
>>> is_col... | 46b8241d26fa19e4372587ffebda3690972c3395 | 11,417 |
def edit_post_svc(current_user, id, content):
"""
Updates post content.
:param current_user:
:param id:
:param content:
:return:
"""
post = single_post_svc(id)
if post is None or post.user_id != current_user:
return None
post.content = content
db.session.commit()
return True | a17b632f402ef3f915bf06bde86ab0ff40956177 | 11,418 |
from re import M
def free_free_absorp_coefPQ(n_e,n_i,T,f):
"""Returns a physical quantity for the free-free absorption coefficient
given the electron density, ion density, kinetic temperature and frequency
as physical quantities. From Shklovsky (1960) as quoted by Kraus (1966)."""
value = 9.8e-13 * n_e.inBase... | 17a09bf20f4363be4f273694168df2cf0eee8b38 | 11,419 |
def pixel_gain_mode_statistics(gmaps):
"""returns statistics of pixels in defferent gain modes in gain maps
gr0, gr1, gr2, gr3, gr4, gr5, gr6 = gmaps
"""
arr1 = np.ones_like(gmaps[0], dtype=np.int32)
return [np.sum(np.select((gr,), (arr1,), default=0)) for gr in gmaps] | b9c6b4c601724105d381e77f7c293e0bd00f3ba8 | 11,420 |
def run_parallel(ds1, ds2):
""" Run the calculation using multiprocessing.
:param ds1: list with points
:param ds2: list with points
:return: list of distances
"""
pool = mp.Pool(processes=mp.cpu_count())
result = pool.starmap(euclidian_distance, [(p1, p2) for p1 in ds1 for p2 in ds2])
... | e8a6b0124db1948ab72b9081863cdfe77a75e08d | 11,421 |
import re
def to_latin(name):
"""Convert all symbols to latin"""
symbols = (u"іїєабвгдеёжзийклмнопрстуфхцчшщъыьэюяІЇЄАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ",
u"iieabvgdeejzijklmnoprstufhzcss_y_euaIIEABVGDEEJZIJKLMNOPRSTUFHZCSS_Y_EUA")
tr = {ord(a): ord(b) for a, b in zip(*symbols)}
translat... | 06a0d535fa7a74feea33e58815da2792a6026def | 11,422 |
def network_instance_create(network, host, attrs=None):
"""
Creates a network_instance of given kind and host, configuring it with the given attributes.
Parameter *kind*:
The parameter *kind* must be a string identifying one of the supported
network_instance kinds.
Parameter *host*:
The parameter *host* ... | 23efa27090081bc59f917cdcf7497f75be0f93b4 | 11,423 |
def update_get():
"""Fetches the state of the latest update job.
Returns:
On success, a JSON data structure with the following properties:
status: str describing the status of the job. Can be one of
["NOT_RUNNING", "DONE", "IN_PROGRESS"].
Example:
{
... | 9e1a2438fc8b4d1dd1bd1354d478c4d4e3e58098 | 11,424 |
def create_github_url(metadata, is_file=False):
"""Constrói a URL da API
Constrói a URL base da API do github a partir
dos dados presentes no metadata.
Args:
metadata: JSON com informações acerca do dataset.
is_file: FLAG usada pra sinalizar se o dataset é apenas um elemento.
"""
url_params = metadata['url'... | 6c138d92cd7b76f87c225a1fd98e7d397b0d6d28 | 11,425 |
def kge_2012(obs, sim, missing="drop", weighted=False, max_gap=30):
"""Compute the (weighted) Kling-Gupta Efficiency (KGE).
Parameters
----------
sim: pandas.Series
Series with the simulated values.
obs: pandas.Series
Series with the observed values.
missing: str, optional
... | 974735f9deb8ffedf88711af5c059ac0aae90218 | 11,426 |
def hms_to_dms(h, m, s):
"""
Convert degrees, arcminutes, arcseconds to an ``(hour, minute, second)``
tuple.
"""
return degrees_to_dms(hms_to_degrees(h, m, s)) | b99b051699f8a5395fe24e2e909f1690c0e67e4c | 11,427 |
def color_calibration(
src_imgs,
src_color_space,
src_is_linear,
ref_imgs,
ref_color_space,
ref_is_linear,
verbose=False,
distance="de00",
):
"""Function that does color calibration for a given target image according to a given reference image
STEP1: load the colorcheckers from ... | 9a225096b760a3bda87adb8ae2d81690da43650d | 11,428 |
def getChiv6ch(mol):
"""
Chiv6h related to ring 6
"""
return getChivnch(mol, 6) | 31a688b1d0b98b75d81b9c4c5e93bb8d62ee732e | 11,429 |
def is_outside_of_range(type_key: CLTypeKey, value: int) -> bool:
"""Returns flag indicating whether a value is outside of numeric range associated with the CL type.
"""
constraints = NUMERIC_CONSTRAINTS[type_key]
return value < constraints.MIN or value > constraints.MAX | fb8ec41d7edc094242df6bad13b8f32285a86007 | 11,430 |
def read_skel(dset, path):
"""
:param dset: name of dataset, either 'ntu-rgbd' or 'pku-mmd'
:param path: path to the skeleton file
:return:
"""
if dset == 'ntu-rgbd':
file = open(path, 'r')
lines = file.readlines()
num_lines = len(lines)
num_frames = int(lines[0])
# print(num_lines, num_... | f461ecb30ec1e7b66ce5d162ccc21b3ba34e6be8 | 11,431 |
def humanize_date(date_string):
""" returns dates as in this form: 'August 24 2019' """
return convert_date(date_string).strftime("%B %d %Y") | d9656af2c4091219d6ee259b557caadbde2cc393 | 11,432 |
import os
def get_checkpoint(checkpoint_path, requested_step=None, basename='checkpoint'):
"""
根据checkpoint重载模型
"""
if requested_step is not None:
model_checkpoint_path = '%s/%s-%s' % (checkpoint_path, basename, requested_step)
if os.path.exists(model_checkpoint_path) is None:
... | 66a00e73ac032c2011fcf5d3f95ed457b06f1e51 | 11,433 |
import sys
import traceback
def handle_error(exception: Exception, request: Request=None):
"""
If an exception is thrown, deal with it and present an error page.
"""
if request is None:
request = {'_environ': {'PATH_INFO': ''}}
if not getattr(exception, 'hide_traceback', False):
(... | cc0a8c4344ebbe8d6119e5d89f3f119709431374 | 11,434 |
def tree_sanity_check(tree: Node) -> bool:
"""
Sanity check for syntax trees: One and the same node must never appear
twice in the syntax tree. Frozen Nodes (EMTPY_NODE, PLACEHOLDER)
should only exist temporarily and must have been dropped or eliminated
before any kind of tree generation (i.e. parsi... | 03b61729c67859bbf9820489ef8fc9768ea59f9f | 11,435 |
from pathlib import Path
import os
import logging
def fileCompare( filename1, filename2, folder1=None, folder2=None, printFlag=True, exitCount:int=10 ):
"""
Compare the two utf-8 files.
"""
filepath1 = Path( folder1, filename1 ) if folder1 else filename1
filepath2 = Path( folder2, filename2 ) if f... | e081e9266a01098d6d99a16ad2bc81bf4dfd36fc | 11,436 |
def compute_std_error(g,theta,W,Omega,Nobs,Nsim=1.0e+10,step=1.0e-5,args=()):
""" calculate standard errors from minimum-distance type estimation
g should return a vector with:
data moments - simulated moments as a function of theta
Args:
g (callable): moment function (ret... | 176710e3b6c18efc535c67e257bc1014b4862135 | 11,437 |
def lhs(paramList, trials, corrMat=None, columns=None, skip=None):
"""
Produce an ndarray or DataFrame of 'trials' rows of values for the given parameter
list, respecting the correlation matrix 'corrMat' if one is specified, using Latin
Hypercube (stratified) sampling.
The values in the i'th column... | 787042db9773f4da6a2dbb4552269ac2740fb02e | 11,438 |
def percentError(mean, sd, y_output, logits):
""" Calculates the percent error between the prediction and real value.
The percent error is calculated with the formula:
100*(|real - predicted|)/(real)
The real and predicted values are un normalized to see how accurate the true
predictions ... | 017291a71388ccf2ecb8db6808965b164dfbfe3d | 11,439 |
import os
def get_file_names(directory, prefix='', suffix='', nesting=True):
"""
Returns list of all files in directory
Args:
directory (str): the directory of interest
prefix (str): if provided, files returned must start with this
suffix (str): if provided, files returned must en... | b35d6a17ac93674a073076c36c0b84ba1361210b | 11,440 |
def parse_multiple_files(*actions_files):
"""Parses multiple files. Broadly speaking, it parses sequentially all
files, and concatenates all answers.
"""
return parsing_utils.parse_multiple_files(parse_actions, *actions_files) | 186a984d91d04ae82f79e7d22f24bd834b8a0366 | 11,441 |
def frequent_combinations(spark_df: DataFrame, n=10, export=True):
"""
takes a dataframe containing visitor logs and computes n most frequent visitor-visite pairs
:param spark_df: Spark Dataframe
:param n: number of top visitors
:return: pandas dataframe with visitor-visite pairs
"""
# com... | 5a4ce5e8199acd1462414fa2de95d4af48923434 | 11,442 |
import random
def reservoir_sampling(items, k):
"""
Reservoir sampling algorithm for large sample space or unknow end list
See <http://en.wikipedia.org/wiki/Reservoir_sampling> for detail>
Type: ([a] * Int) -> [a]
Prev constrain: k is positive and items at least of k items
Post constrain: the... | ab2d0dc2bb3cb399ae7e6889f028503d165fbbe4 | 11,443 |
import json
def create_db_engine(app: Flask) -> Engine:
"""Create and return an engine instance based on the app's database configuration."""
url = URL(
drivername=app.config['DATABASE_DRIVER'],
username=app.config['DATABASE_USER'],
password=app.config['DATABASE_PASSWORD'],
hos... | 5a67f294b58e699345f517ae07c80851ae30eca9 | 11,444 |
import math
def wgs84_to_gcj02(lat, lng):
"""
WGS84转GCJ02(火星坐标系)
:param lng:WGS84坐标系的经度
:param lat:WGS84坐标系的纬度
:return:
"""
dlat = _transformlat(lng - 105.0, lat - 35.0)
dlng = _transformlng(lng - 105.0, lat - 35.0)
radlat = lat / 180.0 * pi
magic = math.sin(radlat)
magic =... | 64f2d8a088a159c5751838ba1fc00824bcc3e91e | 11,445 |
def _normalize_kwargs(kwargs, kind='patch'):
"""Convert matplotlib keywords from short to long form."""
# Source:
# github.com/tritemio/FRETBursts/blob/fit_experim/fretbursts/burst_plot.py
if kind == 'line2d':
long_names = dict(c='color', ls='linestyle', lw='linewidth',
... | 829f4dfd449064f4c1fc92aa8e481364eb997973 | 11,446 |
def fprime_to_jsonable(obj):
"""
Takes an F prime object and converts it to a jsonable type.
:param obj: object to convert
:return: object in jsonable format (can call json.dump(obj))
"""
# Otherwise try and scrape all "get_" getters in a smart way
anonymous = {}
getters = [attr for att... | 899674167b51cd752c7a8aaa9979856218759022 | 11,447 |
import torch
def subsequent_mask(size: int) -> Tensor:
"""
Mask out subsequent positions (to prevent attending to future positions)
Transformer helper function.
:param size: size of mask (2nd and 3rd dim)
:return: Tensor with 0s and 1s of shape (1, size, size)
"""
mask = np.triu(np.ones((... | e065c32164d5250215c846aef39d510f6a93f0cd | 11,448 |
def process_entries(components):
"""Process top-level entries."""
data = {}
for index, value in enumerate(STRUCTURE):
label = value[0]
mandatory = value[1]
# Raise error if mandatory elements are missing
if index >= len(components):
if mandatory is True:
... | 344b9aa601b71fd9352fdb412d9dfa7492312d1a | 11,449 |
from typing import Tuple
def normalize_input_vector(trainX: np.ndarray, testX: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Normalize the input vector
Args:
trainX (np.ndarray): train embedding array.
testX (np.ndarray): test embedding array.
Returns:
np.ndarray, np.ndarray: ... | 34324541e7db302bd46d41f70bd7fdedb6055ae6 | 11,450 |
def update_cache(cache_data, new_data, key):
"""
Add newly collected data to the pre-existing cache data
Args:
cache_data (dict): Pre-existing chip data
new_data (dict): Newly acquired chip data
key (str): The chip UL coordinates
Returns:
"""
if key in cache_data.keys(... | f439f34d1e95ccd69dc10d5f8c06ca20fc869b1e | 11,451 |
def status(command, **keys):
"""Run a subprogram capturing it's output and return the exit status."""
return _captured_output(command, **keys).status | f2bb97448a812548dfbdea770db9a43d8c46301a | 11,452 |
def normalize(flow: Tensor) -> Tensor:
"""Re-scales the optical flow vectors such that they correspond to motion on the normalized pixel coordinates
in the range [-1, 1] x [-1, 1].
Args:
flow: the optical flow tensor of shape (B, 2, H, W)
Returns:
The optical flow tensor with flow vect... | 9164686650e0728ba1d99b65e5757b0e12d6c934 | 11,453 |
def to_graph6_bytes(G, nodes=None, header=True):
"""Convert a simple undirected graph to bytes in graph6 format.
Parameters
----------
G : Graph (undirected)
nodes: list or iterable
Nodes are labeled 0...n-1 in the order provided. If None the ordering
given by ``G.nodes()`` is used.... | 05617e6ebe6d4a374bfa125e3b5afb1bca3304c1 | 11,454 |
def get_arrays_from_img_label(img, label, img_mode=None):
"""Transform a SimpleITK image and label map into numpy arrays, and
optionally select a channel.
Parameters:
img (SimpleITK.SimpleITK.Image): image
label (SimpleITK.SimpleITK.Image): label map
img_mode (int or None): optional mode c... | 902cd2cd5f31121e4a57a335a37b42b4caeafb4a | 11,455 |
def _get_error_code(exception):
"""Get the most specific error code for the exception via superclass"""
for exception in exception.mro():
try:
return error_codes[exception]
except KeyError:
continue | c4c9a2ec2f5cf510b6e9a7f6058287e4faf7b5b4 | 11,456 |
def render_pep440_branch(pieces):
"""TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
The ".dev0" means not master branch. Note that .dev0 sorts backwards
(a feature branch will appear "older" than the master branch).
Exceptions:
1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
"""
if pieces["close... | 0f1c1207016695ee1440fea214f8f92f8c6398ac | 11,457 |
import json
def read_json_file(file_name: str, encoding: str = "utf-8") -> dict:
"""Reads a json file
:param file_name: path
:param encoding: encoding to use
:return: dict content
"""
with open(file_name, "r", encoding=encoding) as json_file:
return json.load(json_f... | 313aee72b06303dfffd8a2e9f3641d1346329a91 | 11,458 |
def pretty_print_row(col_full_widths, row, max_field_size):
"""
pretty print a row such that each column is padded to have the widths in the col_full_widths vector
"""
start = "| "
if len(row) == len(col_full_widths):
end = " |"
else:
end = "|"
return start + "|".join(pretty_... | c94807e4de18e4454e0263e25f4103cd914df2cd | 11,459 |
def _get_data_for_agg(new_svarcube, new_tacube):
"""Reshape data for use in iris aggregator based on two cubes."""
dims_to_collapse = set()
dims_to_collapse.update(new_svarcube.coord_dims('air_pressure'))
untouched_dims = set(range(new_svarcube.ndim)) -\
set(dims_to_collapse)
dims = list(unt... | 51c2683e3477528809fcf229c94125020cdfee6d | 11,460 |
def refs_changed_by_other_cc(current_user):
"""
Return dictionary with id of reference and log object changed by other cooperative centers
"""
current_user_cc = current_user.profile.get_attribute('cc')
result_list = defaultdict(list)
# get last references of current user cooperative center
... | aa2012f1efe6eeb796e3871af691b685e3388e67 | 11,461 |
from typing import Dict
def chain_head(head: int, child: int, heads: Dict[int, int]):
"""
>>> chain_head(0, 2, {1: 2, 2: 3, 3: 0})
True
>>> chain_head(2, 0, {1: 2, 2: 3, 3: 0})
False
"""
curr_child = child
while curr_child != -1:
if curr_child == head:
return True
... | d786d3dbbdc496a1a7515d9df04fa2a09968b87d | 11,462 |
def UpgradeFile(file_proto):
"""In-place upgrade a FileDescriptorProto from v2[alpha\d] to v3alpha.
Args:
file_proto: v2[alpha\d] FileDescriptorProto message.
"""
# Upgrade package.
file_proto.package = UpgradedType(file_proto.package)
# Upgrade imports.
for n, d in enumerate(file_proto.dependency):
... | 942646c67bb987757449fbb16a6164008957cf99 | 11,463 |
import ipaddress
import logging
def _get_ip_block(ip_block_str):
""" Convert string into ipaddress.ip_network. Support both IPv4 or IPv6
addresses.
Args:
ip_block_str(string): network address, e.g. "192.168.0.0/24".
Returns:
ip_block(ipaddress.ip_network)
"""
... | b887c615091926ed7ebbbef8870e247348e2aa27 | 11,464 |
def mul_ntt(f_ntt, g_ntt, q):
"""Multiplication of two polynomials (coefficient representation)."""
assert len(f_ntt) == len(g_ntt)
deg = len(f_ntt)
return [(f_ntt[i] * g_ntt[i]) % q for i in range(deg)] | 504838bb812792b6bb83b1d485e4fb3221dec36e | 11,465 |
import os
import yaml
import toml
import json
def load_config(filepath: str) -> DictStrAny:
"""Read config file.
The config file can be in yaml, json or toml.
toml is recommended for readability.
"""
ext = os.path.splitext(filepath)[1]
if ext == ".yaml":
with open_read_text(filepath) ... | 80fd4622e00dd5546fb2c3dcbbee6dcedd9601a7 | 11,466 |
def _expected_datatypes(product_type):
"""
Aux function. Contains the most current lists of keys we expect there to be in the different forms of metadata.
"""
if product_type == "SLC":
# Only the datetimes need to be parsed.
expected_dtypes = {
"acquisition_start_utc": "pars... | ea5a2d78bc5693259955e60847de7a663dcdbf2c | 11,467 |
from typing import List
import copy
def convert_vecs_to_var(
c_sys: CompositeSystem, vecs: List[np.ndarray], on_para_eq_constraint: bool = True
) -> np.ndarray:
"""converts hs of povm to vec of variables.
Parameters
----------
c_sys : CompositeSystem
CompositeSystem of this state.
vec... | cea5d80a7213e12113b1bec425b142667f9bb36e | 11,468 |
import glob
import os
def convert_CSV_into_df(file_loc):
"""
Generate Panda dataframe from CSV data (rotation and position).
"""
df = pd.DataFrame()
for directory in glob.glob(file_loc): # Selecting all the folders in dataset directory.
... | 9df958019b08d1b19b4591e5ef0a40f4af573914 | 11,469 |
def timetable_to_subrip(aligned_timetable):
"""
Converts the aligned timetable into the SubRip format.
Args:
aligned_timetable (list[dict]):
An aligned timetable that is output by the `Aligner` class.
Returns:
str:
Text representing a SubRip file.
"""
#... | cddcf115ccb9441966d9c1a0a2b67ba25e00e6da | 11,470 |
from re import T
def add(a: T.Tensor, b: T.Tensor) -> T.Tensor:
"""
Add tensor a to tensor b using broadcasting.
Args:
a: A tensor
b: A tensor
Returns:
tensor: a + b
"""
return a + b | a555de4341b874163c551fff4b7674af1e60ace2 | 11,471 |
def integrate(que):
"""
check if block nears another block and integrate them
@param que: init blocks
@type que: deque
@return: integrated block
@rtype: list
"""
blocks = []
t1, y, x = que.popleft()
blocks.append([y, x])
if t1 == 2:
blocks.append([y, x + 1])
elif ... | a91235f34e1151b6dd9c6c266658cca86b375278 | 11,472 |
def test_binary_query(cbcsdk_mock):
"""Testing Binary Querying"""
called = False
def post_validate(url, body, **kwargs):
nonlocal called
if not called:
called = True
assert body['expiration_seconds'] == 3600
else:
assert body['expiration_seconds']... | 5cfd7c7d1ab714b342e13c33cf896032f8387cde | 11,473 |
import typing
def parse_struct_encoding(struct_encoding: bytes) -> typing.Tuple[typing.Optional[bytes], typing.Sequence[bytes]]:
"""Parse an array type encoding into its name and field type encodings."""
if not struct_encoding.startswith(b"{"):
raise ValueError(f"Missing opening brace in struct type encoding: {... | 47455b192049b976dce392b928932d8291d1d008 | 11,474 |
def _comp_point_coordinate(self):
"""Compute the point coordinates needed to plot the Slot.
Parameters
----------
self : Slot19
A Slot19 object
Returns
-------
point_list: list
A list of Points
"""
Rbo = self.get_Rbo()
# alpha is the angle to rotate Z0 so ||Z1... | c74c28af57ea90f208ac61cd2433376e9c1a47ac | 11,475 |
import inspect
def getargspec(func):
"""Like inspect.getargspec but supports functools.partial as well."""
if inspect.ismethod(func):
func = func.__func__
if type(func) is partial:
orig_func = func.func
argspec = getargspec(orig_func)
args = list(argspec[0])
default... | df1745daaf7cad09d75937cce399d705ce10de2b | 11,476 |
from typing import Optional
from typing import Union
from typing import Tuple
from typing import Dict
def empirical_kernel_fn(f: ApplyFn,
trace_axes: Axes = (-1,),
diagonal_axes: Axes = ()
) -> EmpiricalKernelFn:
"""Returns a function that comp... | 890de1ebdd5f41f5aa257cedf1f03325f11e707c | 11,477 |
def read_image_batch(image_paths, image_size=None, as_list=False):
"""
Reads image array of np.uint8 and shape (num_images, *image_shape)
* image_paths: list of image paths
* image_size: if not None, image is resized
* as_list: if True, return list of images,
else return np.ndarray ... | 7ee4e01682c5175a6b22db5d48acdb76471d03da | 11,478 |
def dc_vm_backup(request, dc, hostname):
"""
Switch current datacenter and redirect to VM backup page.
"""
dc_switch(request, dc)
return redirect('vm_backup', hostname=hostname) | 168576ac2b3384c1e35a1f972b7362a9ba379582 | 11,479 |
def compute_total_distance(path):
"""compute total sum of distance travelled from path list"""
path_array = np.diff(np.array(path), axis=0)
segment_distance = np.sqrt((path_array ** 2).sum(axis=1))
return np.sum(segment_distance) | c0c4d0303bdeaafdfda84beb65fd4e60a4ff7436 | 11,480 |
def get_relative_positions_matrix(length_x, length_y, max_relative_position):
"""Generates matrix of relative positions between inputs."""
range_vec_x = tf.range(length_x)
range_vec_y = tf.range(length_y)
# shape: [length_x, length_y]
distance_mat = tf.expand_dims(range_vec_x, -1) - tf.expand_dims(... | 661cabfbcb3e8566dd8d9ec4e56a71a4d62091fd | 11,481 |
def func_split_item(k):
""" Computes the expected value and variance of the splitting item random variable S.
Computes the expression (26b) and (26c) in Theorem 8. Remember that r.v. S is the value of index s
such that $\sum_{i=1}^{s-1} w(i) \leq k$ and $\sum_{i=1}^s w(i) > k$.
Args:
k: Int. T... | 84ec7f4d76ced51ebdbd28efdc252b5ff3809e79 | 11,482 |
def eq(equation: str) -> int:
"""Evaluate the equation."""
code = compile(equation, "<string>", "eval")
return eval(code) | 5e88cad8009dc3dcaf36b216fa217fbadfaa50b3 | 11,483 |
def is_client_in_data(hass: HomeAssistant, unique_id: str) -> bool:
"""Check if ZoneMinder client is in the Home Assistant data."""
prime_config_data(hass, unique_id)
return const.API_CLIENT in hass.data[const.DOMAIN][const.CONFIG_DATA][unique_id] | 740e74b2d77bcf29aba7d2548930a98ec508fec0 | 11,484 |
from datetime import datetime
def parse_date(datestr):
""" Given a date in xport format, return Python date. """
return datetime.strptime(datestr, "%d%b%y:%H:%M:%S") | b802a528418a24300aeba3e33e9df8a268f0a27b | 11,485 |
def generate_database(m, n, uni_range_low=None, uni_range_high=None, exact_number=False):
"""
- Generate Universe by picking n random integers from low (inclusive) to high (exclusive).
If exact_number, then Universe.size == n
- Generate a Database of m records, over the Universe
"""
# generat... | a6fad1192d0c286f7fdb585933b5648f0ee9cb4c | 11,486 |
from Foundation import NSUserDefaults as NSUD
def interface_style():
"""Return current platform interface style (light or dark)."""
try: # currently only works on macOS
except ImportError:
return None
style = NSUD.standardUserDefaults().stringForKey_("AppleInterfaceStyle")
if style == "Da... | 5c30da34a3003ec52c3f97fb86dbf2ba73101a88 | 11,487 |
def get_num_forces(cgmodel):
"""
Given a CGModel() class object, this function determines how many forces we are including when evaluating the energy.
:param cgmodel: CGModel() class object
:type cgmodel: class
:returns:
- total_forces (int) - Number of forces in the coarse grained model
... | 5f5b897f1b0def0b858ca82319f9eebfcf75454a | 11,488 |
def cybrowser_dialog(id=None, text=None, title=None, url=None, base_url=DEFAULT_BASE_URL):
"""Launch Cytoscape's internal web browser in a separate window
Provide an id for the window if you want subsequent control of the window e.g., via cybrowser hide.
Args:
id (str): The identifier for the new ... | d892fe1a4e48cba8f8561fbe208aec7e2cb4afd7 | 11,489 |
def initialize_stat_dict():
"""Initializes a dictionary which will hold statistics about compositions.
Returns:
A dictionary containing the appropriate fields initialized to 0 or an
empty list.
"""
stat_dict = dict()
for lag in [1, 2, 3]:
stat_dict['autocorrelation' + str(lag)] = []
stat_dict... | 42a10b93a960663a42260e1a77d0e8f5a4ff693a | 11,490 |
def nrrd_to_nii(file):
"""
A function that converts the .nrrd atlas to .nii file format
Parameters
----------
file: tuples
Tuple of coronal, sagittal, and horizontal slices you want to view
Returns
-------
F_im_nii: nibabel.nifti2.Nifti2Image
A nifti file format that is... | 240e94758ef3f52d4e9a4ebb6f0574ade13a1044 | 11,491 |
def reqeustVerifyAuthhandler(request):
"""
본인인증 전자서명을 요청합니다.
- 본인인증 서비스에서 이용기관이 생성하는 Token은 사용자가 전자서명할 원문이 됩니다. 이는 보안을 위해 1회용으로 생성해야 합니다.
- 사용자는 이용기관이 생성한 1회용 토큰을 서명하고, 이용기관은 그 서명값을 검증함으로써 사용자에 대한 인증의 역할을 수행하게 됩니다.
"""
try:
# Kakaocert 이용기관코드, Kakaocert 파트너 사이트에서 확인
clientCode =... | 75bce664f11804ed0abb649ce80ef261ebfd0a34 | 11,492 |
import os
def _file_name_to_valid_time(bulletin_file_name):
"""Parses valid time from file name.
:param bulletin_file_name: Path to input file (text file in WPC format).
:return: valid_time_unix_sec: Valid time.
"""
_, pathless_file_name = os.path.split(bulletin_file_name)
valid_time_string ... | 5e26fa07507fee51c286f7ff0d0148e957a5eca6 | 11,493 |
import ipaddress
import six
def cidr_validator(value, return_ip_interface=False):
"""Validate IPv4 + optional subnet in CIDR notation"""
try:
if '/' in value:
ipaddr, netmask = value.split('/')
netmask = int(netmask)
else:
ipaddr, netmask = value, 32
... | 1c0afd08f3f4f079dc4004400449fe6e27cf0ef7 | 11,494 |
def rh2a(rh, T, e_sat_func=e_sat_gg_water):
"""
Calculate the absolute humidity from relative humidity, air temperature,
and pressure.
Parameters
----------
rh:
Relative humidity in Pa / Pa
T:
Temperature in K
e_sat_func: func, optional
Function to estimate the s... | cabbae69d28a68531cf79dfe645e0065ab34534e | 11,495 |
def encoder_decoder_generator(start_img):
"""
"""
layer1 = Conv2D(64, kernel_size=4, strides=2, activation='elu', padding='same')(start_img)
layer2 = Conv2D(64, kernel_size=4, strides=2, activation='elu', padding='same')(layer1)
layer3 = Conv2D(64, kernel_size=4, strides=1, activation='elu', paddin... | 9f0ccb7ebae8f0742fdcd464ce9cd072a9099d3e | 11,496 |
def off():
"""
Turns the buzzer off (sets frequency to zero Hz)
Returns:
None
"""
return _rc.writeAttribute(OPTYPE.BUZZER_FREQ, [0]) | 66e2160fed93ba49bf6c39dff0003a05f2875a77 | 11,497 |
import os
import sys
def ircelsos_data_dir():
"""Get the data directory
Adapted from jupyter_core
"""
home = os.path.expanduser('~')
if sys.platform == 'darwin':
return os.path.join(home, 'Library', 'ircelsos')
elif os.name == 'nt':
appdata = os.environ.get('APPDATA', os.path... | a8c79f3dde6d87aec8c79bd7d35f6fbab19fccd8 | 11,498 |
def get_shodan_dicts():
"""Build Shodan dictionaries that hold definitions and naming conventions."""
risky_ports = [
"ftp",
"telnet",
"http",
"smtp",
"pop3",
"imap",
"netbios",
"snmp",
"ldap",
"smb",
"sip",
"rdp",
... | 2aace61b8339db848e95758fcb9f30856915d6fc | 11,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.