content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def subtract_mean(images):
"""Takes RGB images with 0-255 values and subtraces
the mean pixel and converts it to float. Expects image
colors in RGB order.
"""
return images.astype(np.float32) - Config.IMAGE.MEAN_PIXEL | 55e52fdab5d47151196e4adcd671a77f348ca6dc | 56,000 |
def _linear_idx2coordinate(mesh_shape, linear_idx):
"""
mapping a linear scala into multidimensional mesh space, return it coordinate in that space.
it is the inverse function of _coordinate2linear_idx.
assume:
the size of i-th dimension to be: S[i]
the index of j-th dimension is: I[... | 94237cb93b8d1daa5e47e0ddb7aebb0ad28db461 | 56,001 |
def create_tab(do_display: bool = True) -> Tab:
"""Creates a `ipywidgets.Tab` which can display outputs in its tabs."""
output = Output()
tab = Tab(children=(output,))
tab.set_title(0, "Info")
if do_display:
display(tab)
with output:
# Prints it in the Output inside the tab.
... | 44df8c8686e2e78aad92fc72205470d3d2fd878f | 56,002 |
def is_slice_as_str(x):
"""
Test if string x is a slice. If not a string return False.
"""
try:
x = x.strip("[]()")
m = SLICE_REG.fullmatch(x)
if m:
return True
except AttributeError:
pass
return False | 8a175547ec133753c35f70dee51497d874536291 | 56,003 |
def response_processing(response):
"""
Выделение подходящих адресов из области поиска.
"""
authorized_areas = [area.title.lower() for area in SearchArea.objects.all()]
all_address = response.json()["response"]["GeoObjectCollection"]["featureMember"]
for address in all_address:
area = ad... | 666c8b13a117b90e1720a6174bb9b83bfa1e726f | 56,004 |
def rollaxis(img, axis, inverse=False):
""" Roll `axis` backwards, until it lies in the first position.
It also reorders the reference coordinates by the same ordering.
This is done to preserve a diagonal affine matrix if image.affine
is diagonal. It also makes it possible to unambiguously specify
... | b55b4845030460d84d8ec8f905c2c63fe9e8e78f | 56,005 |
def get_fingerprint(path, passphrase=None, content=None, backend='pyopenssl', prefer_one=False):
"""Generate the fingerprint of the public key. """
privatekey = load_privatekey(path, passphrase=passphrase, content=content, check_passphrase=False, backend=backend)
return get_fingerprint_of_privatekey(priva... | 83acdd1f941b6094a03d6362bb84c091afcc5ab7 | 56,006 |
import functools
def get_generator_map():
"""Returns a map from the generator ID to a SequenceGenerator class creator.
Binds the `config` argument so that the arguments match the
BaseSequenceGenerator class constructor.
Returns:
Map from the generator ID to its SequenceGenerator class creator with a
... | 593207c3f9857e79c73db7b2d0979caac0f7723e | 56,007 |
def get_file(task_id, name):
"""Helper function for spitting out a file on s3"""
# Validate credentials and check status
app_id, app_key, status = check_credentials_and_status(task_id)
key = "output/" + make_key(app_id, app_key, task_id) + "/" + name
app.logger.info("Results delivered. name: %s, app... | 18d1ec2f5e31b6025bfeddabee4db465d53068bd | 56,008 |
import sys
def app_template() -> int:
"""
Write a template of a translation table JSON structure to standard out and exit
"""
sys.stdout.write(TEMPLATE_EXAMPLE)
return sys.exit(0) | 5b39466e65c962872df728705b1c381faef4ce0b | 56,009 |
def run_auto_arima(train, m):
"""
Performs grid search to discover optimal order for an ARIMA model
based on Akaike Information Criterion ("AIC")
Args:
train: pandas dataframe training set
m (int): Period for seasonal differencing; 4 for quarterly,
12 for monthly, or 1 f... | 9ba5064dc33b2036fa9e10cf0e810f1af63fcdb0 | 56,010 |
from typing import Union
def is_valid_bind_request(request_data: dict) -> Union[dict, bool]:
"""
Check is a bind request is valid.
:param request_data:
:return:
"""
if 'command' in request_data and request_data['command'] in BIND_FIELDS:
command = request_data['command']
form... | cea376305e3e262731eb27643ff980f6cfee01a3 | 56,011 |
from typing import Literal
from typing import Callable
import logging
def level_logger_factory(
log_level:Literal['debug', 'info', 'warning', 'error'] = 'info',
log_formatter:TLogFormatter = DEFAULT_INFO_LOG_FORMATTER
) -> Callable[[str, TLogFormatter], TLogger]:
"""
a file based logger fa... | 440f13a7aeb242e39c2ae02e4dbbc63bd77097d8 | 56,012 |
import os
def read_ioc_config():
"""Function for reading the CONFIGURE file.
Returns a dictionary of configure options, a list of IOCAction instances,
and a boolean representing if binaries are flat or not
Returns
-------
ioc_actions : List of IOCAction
list of IOC actions that... | 96f41d8fc62af5d4b11f0e5441cc04b76cc3fb6e | 56,013 |
def SignerTest(input_proto, output_proto, _config):
"""Run image tests.
Args:
input_proto (image_pb2.ImageTestRequest): The input message.
output_proto (image_pb2.ImageTestResult): The output message.
_config (api_config.ApiConfig): The API call config.
"""
image_path = input_proto.image.path
re... | 3137974447dbf4f5facfac6bda4b04fa2debbc9e | 56,014 |
def is_circle(root: ET.Element):
"""Returns true if root is an SVG circle."""
return root.tag == circle_tag | bc7b408b11ca9442c603aac75427e60660dd29e6 | 56,015 |
from typing import Dict
from typing import Tuple
def make_densebox_target(gt_boxes: np.array, config: Dict) -> Tuple:
""" v1
Model training target generation function for densebox
Arguments
---------
gt_boxes : np.array
ground truth bounding boxes with class, shape=(N, 5), order=(x0, y0, ... | bd029dae7850fea7beafa9486401c32799406f66 | 56,016 |
def quat_rotate(quat, vec):
"""Rotate a vector by a unit quaternion.
Args:
quat: A unit quaternion [w, i, j, k]. The norm of this vector should be 1.
vec: A 3-vector representing a position.
Returns:
The rotated vector.
"""
vec = np.atleast_2d(vec)
qvec = np.hstack([np.zeros(vec.shape[0:-1] + ... | a19cbd62e9f05ef4aecb5f1e70e6e04084591fab | 56,017 |
def random_clustering(num_nodes, num_clusters):
"""Partitioning graph randomly"""
parts = np.random.choice(num_clusters, size=num_nodes)
return parts | ed862454f30e7cb94abb6b1366c870f33f6aadb2 | 56,018 |
def classifyData(classifier, testdata, classMap):
"""
Classifies data based on the previously trained model.
Args:
classifier: A classifier object that has been trained on the test corpus.
testdata: A dataset to classify based on reads.
classMap: A dictionary mapping class names to ... | ea2782a31b159cc937c8c8c69a634b403959e722 | 56,019 |
import inspect
import os
import traceback
def _pymake_compile(
srcfiles,
target,
fc,
cc,
expedite,
dryrun,
double,
debug,
fflags,
cflags,
syslibs,
arch,
intelwin,
sharedobject,
verbose,
):
"""Standard compile method.
Parameters
-------
srcfi... | 102c7c1fad5463f51d3dd6447f7231a825e7d2a7 | 56,020 |
def predict(algo, pairs, nprocs=None):
"""
Generate predictions for user-item pairs. The provided algorithm should be a
:py:class:`algorithms.Predictor` or a function of two arguments: the user ID and
a list of item IDs. It should return a dictionary or a :py:class:`pandas.Series`
mapping item IDs ... | 7b032f903b0bd42f3ae89d77296172b44dc1d206 | 56,021 |
def page_1(fake_element_namedtuple):
"""Faked page."""
return Page(
addr='http://mock_url',
contents=[
fake_element_namedtuple(('p', 'Zażółć gęślą jaźń')),
fake_element_namedtuple(('a', 'Etiam aliquam')),
fake_element_namedtuple(('p', '')),
fake_el... | 3609c444a6573ce4bc158f496f0a1cde61f06528 | 56,022 |
from . import measure_methods
from ..database import filter_inputs
import time
def create_measure_batch(task, options):
"""Get a standard measure_batch function.
Parameters
----------
task: tvm.autotvm.task.Task
The tuning task
options: dict
The option for measuring generated code... | 8c321e822dfa355ba822fe209bec98e4898ce4fb | 56,023 |
def generate_action_single_step(inputs, dim_fc_action):
"""Generate the action for single steps.
Args:
inputs: The input tensor.
dim_fc_action: Dimension of action encoding.
Returns:
The generated action.
"""
with slim.arg_scope(
[slim.fully_connected],
... | a232dbb300d1251ddfcc0cafe8bab058fba31b93 | 56,024 |
import requests
import json
def get_authorization_info(wx, auth_code):
"""
获取微信授权方公众号/小程序的授权信息
:param wx: [dict]
:param auth_code:
:return:
"""
access_token = get_component_access_token(wx)
if not access_token:
return
wx_url = 'https://api.weixin.qq.com/cgi-bin/component/a... | 7c440d9f9301f67717f405046a6224d6b1928dc6 | 56,025 |
import re
from datetime import datetime
def generate_identifier():
"""Generate unique date and time based identifier"""
return re.sub(' |:','',str(datetime.datetime.today())) | 3a44399783c75962760ba4fb4cea078378744fae | 56,026 |
def get_public_key(context, signature_certificate_uuid, signature_key_type):
"""Create the public key object from a retrieved certificate.
:param context: the user context for authentication
:param signature_certificate_uuid: the uuid to use to retrieve the
certificat... | ba78c9cc5d1cc4d92cc8a482877c03a795ec8cd2 | 56,027 |
def setup_prim(results, classify, threshold, incl_unc=[], **kwargs):
"""Helper function for setting up the prim algorithm
Parameters
----------
results : tuple
tuple of DataFrame and dict with numpy arrays
the return from :meth:`perform_experiments`.
classify : str or cal... | e3747b28c675734866e50208872ceb6ac2b93d8b | 56,028 |
def indexd_client(indexd_server, create_indexd_tables, indexd_admin_user):
"""Create the tables and add an auth user"""
return IndexClient(indexd_server.baseurl, auth=(indexd_admin_user[0], indexd_admin_user[1])) | 7cc45ad1140b0893915ba3bf89251693e88cb4d0 | 56,029 |
def load_class(module_name, class_name):
"""Return class object specified by module name and class name.
Return None if module failed to be imported.
:param module_name: string module name
:param class_name: string class name
"""
try:
plugmod = import_module(module_name)
except Exc... | d90ed0f39b41fb19db8418c324a75ded96b2d295 | 56,030 |
def send_user_email_copy_admins(title, from_address, to_addresses, request, template="email/default.txt", context={}):
"""
Send a message on behalf of a user to another user, cc'ing
the sender and the Perma admins.
Use reply-to for the user address so we can use email services that require a... | ee05d2b290cc0bfde0e7ae510e9051e7b9850d12 | 56,031 |
def render_row(row):
"""
Renders a row as an HTML table element.
"""
return "".join(_render_row(row)) | e9f01c246c3d22b9c67cb7236c6561843ba67660 | 56,032 |
def dropout(inputs,
is_training,
scope,
keep_prob=0.5,
noise_shape=None):
""" Dropout layer.
Args:
inputs: tensor
is_training: boolean tf.Variable
scope: string
keep_prob: float in [0,1]
noise_shape: list of ints
Returns:
tensor variable
"""
with tf.variable_scope(scope) as sc:
outputs ... | 4651f66dd7bc7d31f841f5460039724f4578ad38 | 56,033 |
import re
def checkOS():
""" This finction need from checked OS type and use specific key package manager"""
fin = open("/etc/os-release", "rt")
data = fin.read()
findkey = re.search(
r'^NAME=\"Arch Linux\"|NAME=\"Debian GNU/Linux\"|NAME=\"Ubuntu GNU/Linux\"|NAME=\"CentOS Linux\"'
r'|N... | ddf1764535afaad15494e7605d46ae011d4c949f | 56,034 |
import gzip
def rows_from_gz_flowlog_stream(gz, key):
"""Return the rows of a compressed stream (.i.e COS object)"""
with gzip.open(gz) as bstream:
return rows_from_flowlog_stream(bstream, key) | bebdf431944c9121d1a547f1b7b5545e0577e1e5 | 56,035 |
def mk_falls(data_id, data): # measurement group 12
"""
transforms a g-falls.json form into the triples used by insertMeasurementGroup to
store each measurement that is in the form
:param data_id: unique id from the json form
:param data: data array from the json... | 597591e22d1bd5fb4a4f5920a3de6dd4545ac1dd | 56,036 |
def ctrees2arg(trees, names, times, verbose=False, delete_arg=True):
"""
Convert a C data structure for the ARG into a python ARG
"""
if verbose:
util.tic("convert arg")
# get local trees info
nnodes = get_local_trees_nnodes(trees)
ntrees = get_local_trees_ntrees(trees)
# allo... | 792819b6e3d5b7ee42f80d44139fadefc7e560c3 | 56,037 |
import click
def install_package(package_name: str, verbose=True):
"""
Installs a system package with the given "package_name"
"""
operating_system = CONFIG['install']['os']
package_install_command = CONFIG['install'][operating_system]['package_install']
click.secho('Installing package "{}"..... | a83f5397e3f27fe0bda8f9ad47cf187a14e4c18c | 56,038 |
def query_wolfram_alpha_api(url: str) -> dict:
"""
Query the Wolfram|Alpha API and return the result
:param url: Wolfram|Alpha API URL to query
:return: dict status_code, content, encoding
"""
result = SESSION.get(url)
return {"status_code": result.status_code,
"content": result... | b4d8ce81304021015d6b4fb239089806afe1d735 | 56,039 |
def l2_norm(params):
"""Computes l2 norm of params by flattening them into a vector."""
flattened, _ = weights_flatten(params)
return np.dot(flattened, flattened) | 94a74801b450515ead098f008dd6ae320853b84d | 56,040 |
def test_clustercron_returns_1_when_not_master(monkeypatch):
"""
Test if `main.clustercron` returns 1 when not `lb.master`
"""
class ElbMock(object):
def __init__(self, name):
pass
def master(self):
return False
monkeypatch.setattr(elb, "Elb", ElbMock)
... | 504a41262a9abeae7d1672041b4e04f3818b112b | 56,041 |
def delete_repo( request, repo_id ):
"""
Delete a data repository.
Checks if the user is the original owner of the repository and removes
the repository and the accompaning repo data.
"""
repo = get_object_or_404( Repository, mongo_id=repo_id )
# Check that this user has permi... | d9b5995c4f1216457386f4ed372733b0407b793b | 56,042 |
import time
import requests
import socket
import errno
import random
def azure_request(req, timeout=None, *args, **kwargs):
"""Wrapper method to issue/retry requests to Azure, works with both
the Azure Python SDK and Requests
Parameters:
req - request to issue
timeout - timeout in seconds
... | c94072ee98a3a930ee6ad33c205115c12867456e | 56,043 |
def build_params_test():
"""Cheap parameter set for test runs."""
params = sitk.GetDefaultParameterMap('translation')
return params | 9a5dfa25ff34cf0a8418fc753370fcb5b1b41582 | 56,044 |
import re
def to_kebab_case(input):
"""Convert a string into its kebab case representation."""
str1 = re.sub("(.)([A-Z][a-z]+)", r"\1-\2", input).replace("_", "-")
return re.sub("([a-z0-9])([A-Z])", r"\1-\2", str1).lower() | f2203888f556626271a66dca150e13817fedc1f2 | 56,045 |
def locate_hodogram(st: Stream, event: Event, inventory: Inventory,
window_length: float = 20e-3, linearity_threshold=0.7):
"""
measure the incidence angle from hodogram
:param st: a stream object containing the waveforms
:type st: uquake.core.stream.Stream
:param picks: a list o... | 01b7198d4d3d314f0df2810b9cec27443178c1d5 | 56,046 |
import scipy
import collections
def location_significant_place_features(df, **kwargs):
"""Calculates features related to Significant Places"""
assert 'speed_threshold' in kwargs
speed_threshold = kwargs['speed_threshold']
def compute_features(df):
"""Compute features for a single user"""... | 39d88a26f984762f0484cf190501ade19011a1d0 | 56,047 |
def concatenation_based_attention(
hidden_states,
dt,
e_num_units,
d_num_units,
attention_size,
initializer=layers.xavier_initializer(),
activation_fn=tf.tanh):
"""
Concatenation-based Attention
args:
`hidden_states`: the hidden states of encoder w... | 98ac5de6836aee94f572810a24b2597929199242 | 56,048 |
from typing import Tuple
import subprocess
def check_neo4j_running() -> Tuple[bool, str]:
"""Run shell commands to see if the neo4j instance is running.py
Returns:
Tuple[bool, str]: First value is boolean indicating if neo4j is running, second is a suggested stop command
"""
neo4j_status_chec... | f37089c9971cae9c3472400f03af6026b4800043 | 56,049 |
from typing import Dict
from typing import Any
from typing import List
def get_human_readable_for_my_asi_insights_command(results: Dict[str, Any], priority: str, active_insights: int,
total_insights: int, total_observations: int) -> str:
"""
Parse and convert... | 6f1b1f4770476d7fd9bdcd2981c91886dbc07ec8 | 56,050 |
def encode_datetime_to_ml(series, col_name) -> pd.DataFrame:
"""
This method converts datetime pandas series to machine learning acceptable format.
It extracts year, month, day, hour, and minute from the datetime object.
The method returns a dataframe, as shown in below example.
Example:
pd... | c9e61521d3692afea4bc29526e49b9bea3c27e3f | 56,051 |
def get_port(duthost, ptfhost, interface_ranges, port_type):
"""
Get port configurations from DUT and PTF
Args:
duthost: DUT host object
ptfhost: PTF host object
interface_ranges: numbers of ports
port_type: Type of port
Returns:
Tuple with port configurations o... | e13702b7116a61a43dc6298c3b7341a599a2c3f7 | 56,052 |
import sys
import functools
def main():
"""Program entry point."""
term = blessed.Terminal(stream=sys.__stderr__)
# This table was generated with the aide of bin/new-wide-by-version.py in
# the wcwidth repository, note that 4.1.0 and 5.0.0 have identical wide
# characters.
previous_version = '... | e9808f20f56b1ab8e72705165dd5d5153dba0e28 | 56,053 |
def rank_perturbation_genes(adata, pkey="j_delta_x_perturbation", prefix_store="rank", **kwargs):
"""Rank genes based on their raw and absolute perturbation effects for each cell group.
Parameters
----------
adata: :class:`~anndata.AnnData`
AnnData object that contains the gene-wise per... | 1134754051458c378a1077ba4b82147bc288ec4f | 56,054 |
from typing import Any
import os
import logging
import re
import shlex
def getCDefinesAsString( targetPlatform, targetName ):
"""
Returns a long string with all compiler definitions set for the
package using the addDefinitions() directive.
This means all definitions passed to the compiler... | 1053f0692fc4d538c33fd8ba6957f39233a34b92 | 56,055 |
def extract_details(df):
"""Extract step details for last 3 steps (deBoc, BHA and SNAr)."""
df_RSinfo = df[['pentamer', 'Step details', 'RouteScore details',
'Isolated', 'RouteScore', 'log(RouteScore)']]
last3_rxns = ['Buchwald_deprotection', 'Buchwald', 'SNAr']
for rxn in last3_rxn... | c361f91b36a5270c93739d546779bcbb89944fbb | 56,056 |
from typing import Any
def test_for_fraction_exception(item: Any, next_item: Any) -> bool:
"""
Returns True if a combination 'item' and 'next_item' appear to indicate
a fraction in the symbolic deque. False otherwise.
e.g. item=deque([...]), next_item="/" -> True
item="/", next_item=dequ... | d304eae78319c27f3aa0c185e81c7e6dba0db22f | 56,057 |
def user_num_documents(user):
"""Count the number of documents a user has contributed to. """
return Document.objects.filter(
revisions__creator=user).exclude(
html__startswith='<p>REDIRECT <a').distinct().count() | 0f7b19cd87d8dfb5f262b8ed799559bf07c49987 | 56,058 |
import os
def get_callbacks(
config,
model,
training_model,
prediction_model,
validation_generator=None,
evaluation_callback=None,
lr=1e-5,
epochs=100,
):
""" Returns the callbacks indicated in the config.
Args
config : Dictionary with indications about the callbacks.
model : ... | af48bc46aa85d6eddfdd4b7c3a70ad416a29cda7 | 56,059 |
from typing import Optional
import torch
from typing import Tuple
from typing import Iterator
from typing import Callable
from typing import OrderedDict
def cppn(
size: int,
num_output_channels: Optional[int] = 3,
num_hidden_channels: Optional[int] = 24,
num_layers: Optional[int] = 8,
activatio... | af10dcf402c0455647841aa824ba053a5e231b51 | 56,060 |
def validate_velocity(a):
"""
Checks that the array 'a' is a valid velocity vector, meaning:
It must be a scalar, or 1-D array of numbers
It must only contain finite and defined values
If successful, returns 'a' with the given changes
"""
a = np.array(a)
a = che... | d797f6b18f54e5b41fc5e50ae8bd669136795d27 | 56,061 |
def multi_backend_test(globals_dict,
relative_module_name,
backends=('jax', 'tf'),
test_case=None):
"""See backend.multi_backend_test."""
if test_case is None:
return lambda test_case: multi_backend_test( # pylint: disable=g-long-lambda
... | 7e3ec1e7cb5b85490b9e54e2ad951ad2786e3fed | 56,062 |
import os
def _test_data_dir():
"""Return path to directory for bot and server data."""
root_dir = os.environ['ROOT_DIR']
return os.path.join(root_dir, '_test_data') | b6dd9032f3e7d2ed8609af5629a915339ed77794 | 56,063 |
def iam_auth(endpoint_url):
"""
Helper function to return auth for IAM
"""
url = urlparse(endpoint_url)
region = boto3.session.Session().region_name
return BotoAWSRequestsAuth(aws_host=url.netloc,
aws_region=region,
aws_service='exe... | dab1267360ba80a2bcdb0dd9e00525435d02e0fe | 56,064 |
import torch
import os
def train_methods(systems_dict, system_type, epochs):
"""
take the systems dictionary and return the final solution and final weights for each
args:
systems_dict: the dictionary of diffeqs e.g. exp:[lambda u,t:diff(u,t) -u]
"""
SOLUTIONS = {}
DYDX = {}
DYDW ... | 86428c9d7bb80a1352831834ed1e4a2ffafa3a28 | 56,065 |
def create_slider_severity(x: str):
""" X = symptom """
return st.slider(f'Please rate the severity of {x}', 1, 3, 1) | f4914c242cbe5a5fb1b9ca5e4562d26eef3c4aef | 56,066 |
def waveform_2_magnitude(waveform, frame_length=512, frame_step=128, log_magnitude=True,
n_mel_bins=None, mel_lower_hertz_edge=0.0,
mel_upper_hertz_edge=8000.0):
"""Transform a Waveform to a Magnitude Spectrum.
This function is a wrapper for waveform_2_spectogr... | 64f1aa8aaaee01875c758c9b40afc33fa3d43af9 | 56,067 |
import os
import shutil
import test
def main():
"""Main entrypoint"""
args = parse_args()
sourcedir = os.path.join(os.path.dirname(__file__), '..')
workdir = os.path.join(sourcedir, 'build')
# setup build/ dir
if os.path.exists(workdir):
if args.rebuild:
shutil.rmtree(work... | 96e74ad0cbddd31522289440a7fadddfc9988f92 | 56,068 |
import sys
def get_hw_num_and_type_from_zip_name(zip_file_name):
"""Determinate homework number and it's type
from the zip file name.
"""
try:
file_name = zip_file_name.lower()
is_project = "проект" in file_name
is_main_hw = not is_project and not "практикум" in file_name
... | 7fecc39a3e10317744626f4e562129edb91c006a | 56,069 |
def phaseinfo(xs, ys, sphase):
"""Compute the mutual information between firing phase and position."""
xbins = ybins = INFO_PHASE_POS_BINS
xmin, xmax = INFO_PHASE_POS_XRANGE
ymin, ymax = INFO_PHASE_POS_YRANGE
pmin, pmax = PHASE_MIN, PHASE_MAX
pbins = INFO_PHASE_BINS
sample = np.c_[xs, ys, s... | 6e00edd738d436f1f29eac9490ee403a050b564e | 56,070 |
def expect_value_OABs(params, NN_params, Sample, key):
"""
There is a bug in pennylane 0.21, that prevents us from simply using
Obs_AB[j][1]@Obs_AB[j][2]. This is why we do it like this
"""
μ_I_diagonal = 0.
for j in range(number_of_overlapping_Ops):
Observable = qml.Hermitian(np.matmu... | a46250afb1bdfc42220714651cb45b8eb4bd7269 | 56,071 |
from typing import Callable
from typing import Any
from typing import Union
from typing import List
from typing import Type
def _return_types(func: Callable[..., Any]) -> Union[TypesDict, List[TypesDict]]:
"""Get the callables return types"""
func = _unwrap_function(func) # type: ignore
args_spec = getfu... | 59a40f1e4fe6d5c5727676fe2134764a8853a8b6 | 56,072 |
import sys
def google_adwords_sale(context):
"""
Output our receipt in the format that Google Adwords needs.
"""
order = context['order']
try:
request = context['request']
except KeyError:
print("Template satchmo.show.templatetags.google.google_adwords_sale couldn't get the req... | 7fe22567f5d65c2c2ea40da2b3d67000ad8bf71e | 56,073 |
import sys
import yaml
import traceback
def read_file(file, hdrnum, print_trace,
outstream=sys.stdout, errstream=sys.stderr, output_mode="verbose",
write_heading=False):
"""Read the specified file and process it.
Parameters
----------
file : `str`
The file from whi... | 18bae8f8f0200c19efbeda06901af0981df735e8 | 56,074 |
def create_mixed_plot(dataframe, groupby, primary_measure, secondary_measure, title):
"""
Description: This function can be used to create a plot with 2 measures
Arguments:
df: the dataframe
group: columns to be grouped of the dataframe (can be multiple ones)
primary_measure: the pr... | 43de28978877a1d54819d0d75ed30f95b6114add | 56,075 |
from typing import Callable
from typing import Tuple
def loss(
vector_field: Callable,
zo: Tuple[np.ndarray],
step_size: float,
omega: float,
mu: np.ndarray
) -> np.ndarray:
"""A loss function representing violation of the constraint function with
respect to the inputs.... | 65c8f9b53c9d8fd929f22f0797c78f8b44b03223 | 56,076 |
def format_singular_csc_error(system, matrix):
"""
Format a coherent error message when the CSC matrix is singular.
Parameters
----------
system : <System>
System containing the Directsolver.
matrix : ndarray
Matrix of interest.
Returns
-------
str
New error... | b833ebdc647cc74a33ed66173d4426b64dbd6d56 | 56,077 |
def _is_vcf_version_at_least_0_6_8():
"""
The behaviour of vcfReader.fetch changed significantly from version 0.6.8
onwards.
:return: boolean
"""
major, minor, patch = vcf.VERSION.split(".")
if int(major) == 0 and int(minor) == 6 and int(patch) >= 8:
return True
elif int(major) =... | 1b9ca7796dc4938cc0265c4886289c7a4c52f585 | 56,078 |
import random
def random_names(count=10):
"""Returns a random selection of ``count`` names.
No repetitions.
"""
return random.sample(NAMES_2K, count) | a406919008b874d879eba80f92e9ca21abcfee3d | 56,079 |
def thresholdcoloring(coloring, names):
"""
Threshold a coloring dictionary for a given list of column names.
Threshold `coloring` based on `names`, a list of strings in::
coloring.values()
**Parameters**
**coloring** : dictionary
Hierarchical structure on the columns g... | affe639d0863468390d02f7dac2840239520419c | 56,080 |
def ComputeMultiLevelLogsig1dBM(BM_paths, number_of_segment, depth_of_tensors, T):
"""
Compute the log-signature of all samples
"""
no_of_samples = np.shape(BM_paths)[0]
if depth_of_tensors == 1:
MultiLevelLogSigs = np.zeros([no_of_samples , 2 * number_of_segment], dtype=float)
else... | ed82f7c40be63681bfa135a5b837ee64dcd6eff1 | 56,081 |
def add_spray_angle(raw_df: pd.DataFrame, adjusted: bool = False) -> pd.DataFrame:
"""Adds spray angle and adjusted spray angle to StatCast DataFrames
- Spray angle is the raw left-right angle of the hit
- Adjusted spray angle flips the sign for left handed batters, making it a push/pull angle
Args:
... | 092a8134980d32c13d793137945575a49414f4ec | 56,082 |
async def verify_token(x_key: str = Header(None)):
"""
Note: this isn't meant to be secure
could also use a cache ...
You have to pass a valid key
curl -H "X-Key: your_key" http://127.0.0.1:8000/
"""
if x_key is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
... | 504077ae8a81c5ece58de3af63762a7fa11cbffa | 56,083 |
def cmd_trader_stream(trader: Trader, data: dict) -> dict:
"""
Subscribe/unsubscribe to different trader data stream :
- trades or ticks data
- OHLCs data
- market Depth data
- market update
@param trader:
@param data:
@return:
"""
results = {
'messag... | f230252c332ed4131374bcd5bfd0afffe4e205e3 | 56,084 |
def _VarintDecoder(mask):
"""Return an encoder for a basic varint value (does not include tag).
Decoded values will be bitwise-anded with the given mask before being
returned, e.g. to limit them to 32 bits. The returned decoder does not
take the usual "end" parameter -- the caller is expected to do bo... | 19738e8a1a09464525af18a0689a04b601e9869b | 56,085 |
def getDownSampleImage(image, imageSize=320):
"""
Function take image and down sample to imageSize, while keeping the original ratio
Args:
image (numpy.array): image use for cropping (h,w,c)
imageSize (int): target size
Returns:
* **resized_image** (numpy.array) - cropped image (h,w,c)
"""
image_ratio = ... | 0ec64b549656a67bab113681a59c6905eccc2f04 | 56,086 |
import os
def reverse(args):
"""
Given a Python-compiled executable, will attempt to fully reverse engineering and
extrapolate source code. If Boa can accurately detect the packing routine, it will statically
recover the bytecode. Otherwise, the binary will be instrumented to dump bytecode dynamically... | a9bf57a590c2077c5a9f4742dd1c389d82f495e5 | 56,087 |
def thiran_delay1(source, delta, fillvalue=0.0):
"""First order Thiran allpass delay."""
k = int(floor(delta - 0.5))
d = delta - k
a0 = 1.0
a1 = -d / (1.0 + d)
return delay(polezero(source, a0, a1, a1, a0), k, fillvalue) | 8b3801b20b45c2e3b278c878fdac94a5420ea250 | 56,088 |
def kontejnery_verejne(kontejnery_json):
"""Funkce vybere jen kontejnery s veřejným přístupem"""
verejne_kont = []
for kontejnery in kontejnery_json["features"]:
pristup = kontejnery["properties"]["PRISTUP"]
if pristup == "volně":
souradnice = kontejnery["geometry"]["coordinates... | d9179acd6ad8c94330c1c0499815cda77e84fbf4 | 56,089 |
import os
import numpy
def readScan(scanNum, dirName):
""" Reads a DICOM file from a directory
Given a directory name and the number of the file containing the image to be read, reads in and returns a numpy representation of the image. Also normalizes the pixel values of the image.
Args:
scanNum... | 8d3a843c2e585858c083ab068e930e2de210bcbd | 56,090 |
def generate_token(clientKey, clientSecret):
"""Generate the token. Please respect these credentials :)"""
credentials = oauth2.SpotifyClientCredentials(
client_id=clientKey,
client_secret=clientSecret)
token = credentials.get_access_token()
return token | 58badd42f550b9d523ddf7ca770e6b2b68a640c4 | 56,091 |
import os
def get_blobs_from_im(data_dir, imgs, batch_size):
"""Read image files to blobs [3, 256, 256]"""
if batch_size != len(imgs):
raise RuntimeError(
'batch_size:{} != len(imgs):{}'.format(batch_size, len(imgs)))
blobs_data = np.zeros((batch_size, 3, 256, 256), np.uint8)
for ... | 882cba1812e7295a45e1416351fbac0de6d3f089 | 56,092 |
import torch
def _is_unit(symmetric_matrix):
"""Check if a matrix is a Unit matrix
This is a private method for the moment.
Args:
symmetric_matrix: input is assumed to be a symmetric matrix
Returns:
bool: True if the matrix is Unit, False otherwise
"""
r = symmetric_matrix.s... | 844c6bf9b88466168cd3c2bc878790b2024698fe | 56,093 |
def rcv_winner(L, tie_breaker, printing_wanted=False):
"""
Return RCV (aka IRV) winner for ballot list L.
Args:
L (list): list of ballots (this should be a "cleaned" list)
tie_breaker: list of all choices, most-favored first
printing_wanted (bool): True if printing desired
Retu... | e657447fa1de89dfe6baf0bede068512a2d358b1 | 56,094 |
def structuredToVTK(
path: str,
x: np.ndarray,
y: np.ndarray,
z: np.ndarray,
cellData: DataType = None,
pointData: DataType = None,
fieldData: DataType = None,
**kwargs
) -> str:
"""Write data to a RectilinearGrid
:param path: path to file without... | ef0ff3a5575d49d8068abeddc535833bec77f11e | 56,095 |
def _zf_pad(data, pad=0, mid=False, **kwargs):
"""
Zero fill by padding with zeros.
Parameters
----------
dataset : ndarray
Array of NMR data.
pad : int
Number of zeros to pad data with.
mid : bool
True to zero fill in middle of data.
Returns
-------
nda... | 655871e2edc052e75180e47b6ad1ae6ec789480b | 56,096 |
def magma_strerror(error):
"""
Return string corresponding to specified MAGMA error code.
"""
return _libmagma.magma_strerror(error) | d28f26d1418ef60f70919209af466a4f8469cac0 | 56,097 |
import os
def plot_four(folder_name):
"""
Plots all four images from location specified by folder_names
"""
images_path = "../../data/raw/data/" + folder_name
image_paths = []
for path in os.listdir(images_path):
image_paths.append(os.path.join(images_path, path))
"sort by degree f... | 99682dee2e7e390f71008e932515e12994ceab54 | 56,098 |
import scipy
def rms(arr, size=5):
"""
A linear n-D smoothing filter. Can be used as a moving average on 1D data.
Args:
arr (ndarray): an n-dimensional array, such as a seismic horizon.
size (int): the kernel size, e.g. 5 for 5x5. Should be odd,
rounded up if not.
Returns... | 36f804512bec220a8544bf7c67b3e279fc0faaf5 | 56,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.