content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def ConstVal(val):
"""
Creates a LinComb representing a constant without creating a witness or instance variable
Should be used carefully. Using LinCombs instead of integers where not needed will hurt performance
"""
if not isinstance(val, int):
raise RuntimeError("Wrong type for ConstVal")
... | d715564ea09224590be827d3e32043c4b66c5cfd | 18,833 |
def filter_required_flat_tensor_spec(flat_tensor_spec):
"""Process a flat tensor spec structure and return only the required subset.
Args:
flat_tensor_spec: A flattened sequence (result of flatten_spec_structure)
with the joined string paths as OrderedDict. Since we use OrderedDicts we
can safely c... | aa55e790cd335030cf2c821dd006213db022b78a | 18,834 |
def callback(photolog_id):
""" twitter로부터 callback url이 요청되었을때
최종인증을 한 후 트위터로 해당 사진과 커멘트를 전송한다.
"""
Log.info("callback oauth_token:" + request.args['oauth_token']);
Log.info("callback oauth_verifier:" + request.args['oauth_verifier']);
# oauth에서 twiter로 부터 넘겨받은 인증토큰을 세션으로 부터 가져온다.
... | 3dcca97278cf20f819fa357b85e971dae9a6dac8 | 18,835 |
def calc_adjusted_pvalues(adata, method='fdr_by'):
"""Calculates pvalues adjusted per sample with the given method.
:param data: AnnData object annotated with model fit results.
:param method: Name of pvalue adjustment method (from
statsmodels.stats.multitest.multipletests).
:return: AnnData ob... | 0097ceca4918ef4a4c4376c092b040752f408036 | 18,836 |
def create_model(model_type='mobilenet'):
"""
Create a model.
:param model_type: Must be one of 'alexnet', 'vgg16', 'resnet50' or 'mobilenet'.
:return: Model.
"""
if model_type is 'alexnet':
net = mdl.alexnet(input_shape, num_breeds, lr=0.001)
elif model_type is 'vgg16':
net ... | 44ab632eff28e40b5255094e2009b479e042b00b | 18,837 |
def generate_voter_groups():
"""Generate all possible voter groups."""
party_permutations = list(permutations(PARTIES, len(PARTIES)))
voter_groups = [VoterGroup(sequence) for sequence in party_permutations]
return voter_groups | 16c55002600bf76178c529f1140fb28831d5065e | 18,838 |
import random
def generator(fields, instance):
"""
Calculates the value needed for a unique ordered representation of the fields
we are paginating.
"""
values = []
for field in fields:
neg = field.startswith("-")
# If the field we have to paginate by is the pk, get the... | 3d6f3837e109720ec78460dcd56b6cf1b3ddc947 | 18,840 |
from typing import Any
from typing import Union
def token_hash(token: Any, as_int: bool = True) -> Union[str, int]:
"""Hash of Token type
Args:
token (Token): Token to hash
as_int (bool, optional): Encode hash as int
Returns:
Union[str, int]: Token hash
"""
return _hash((... | 3adfc8dce2b37b86376d47f8299cb6813faab839 | 18,841 |
import six
import base64
from datetime import datetime
def generate_totp_passcode(secret):
"""Generate TOTP passcode.
:param bytes secret: A base32 encoded secret for TOTP authentication
:returns: totp passcode as bytes
"""
if isinstance(secret, six.text_type):
secret = secret.encode('utf-... | 2f0392e86b5d84970ec43bbd4d647ca29345a373 | 18,842 |
def all_ndcubes(request):
"""
All the above ndcube fixtures in order.
"""
return request.getfixturevalue(request.param) | 906412ebe9a26de5cfddcb1d1431ab014c8084c6 | 18,843 |
from pathlib import Path
import warnings
def read_xmu(fpath: Path, scan: str='mu', ref: bool=True, tol: float=1e-4) -> Group:
"""Reads a generic XAFS file in plain format.
Parameters
----------
fpath
Path to file.
scan
Requested mu(E). Accepted values are transmission ('mu'), flu... | e5889fa309b7fb836cc5b7ea50f8987a647f00a2 | 18,844 |
def filter_order_by_oid(order, oid):
"""
:param order:
:type order: :class:`tests.testapp.testapp.trading.models.Order`
:param oid: Order ID
:type oid: int
"""
return order.tid == oid | bf84e2e9f2fa19dc19e1d42ceef92dd3050d1e89 | 18,845 |
from skaldship.passwords.utils import process_password_file, insert_or_update_acct
import logging
def process_pwdump_loot(loot_list=[], msf=None):
"""
Takes an array of loot records in loot_list, downloads the pwdump file and
adds the users.
"""
db = current.globalenv['db']
#cache = current.g... | 57448b24350dd66271906ba5fcdc0e4453d898e9 | 18,846 |
def has_poor_grammar(token_strings):
"""
Returns whether the output has an odd number of double quotes or if it does not have balanced
parentheses.
"""
has_open_left_parens = False
quote_count = 0
for token in token_strings:
if token == '(':
if has_open_left_parens:
... | b35c6af0ec771ac22ff66d9ca875f5d916cb9489 | 18,847 |
import pandas as pd
def csv_dataset_reader(path):
"""
This function reads a csv from a specified path and returns a Pandas dataframe representation of it, and renames
columns.
:param path: Path to and name of the csv file to read.
:return: A Pandas dataframe.
"""
data = pd.read_csv(path, s... | 59a298c50bf060809ebbebc5d0ff3d9670e84244 | 18,849 |
def get_daily_blurb_info():
"""Get daily blurb info."""
html, ss_image_1day_file, ss_image_1year_file = _scrape()
return _parse(html, ss_image_1day_file, ss_image_1year_file) | ffe84accebda5780e55d34e58137288d02bc072d | 18,850 |
def otsu_binarization(img):
"""
Method to perform Otsu Binarization
:param img: input image
:return: thresholded image
"""
ret2, th2 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
return th2 | 99953288b893d56e17a9e9654393aa284eaae4b7 | 18,852 |
def rosstack_depends_1(s):
"""
@param s: stack name
@type s: str
@return: A list of the names of the stacks which s depends on directly
@rtype: list
"""
return rosstackexec(['depends1', s]).split() | e917c62c628498e1f100c045bf8e966ea3bfd355 | 18,853 |
def _config_file_is_to_update():
"""
Ask the user if the configuration file should be updated or not.
:return: Returns True if the user wants to update the configuration file and False otherwise.
:rtype: bool
"""
if yes_or_no_input("Do you want to save the account on the configuration file?") ==... | e14be78e150e28b87a0e8f179cc86f4a240a60d3 | 18,854 |
def funcScrapeTableWunderground(html_tree, forecast_date_str):
"""
"""
# This will get you the Wunderground table headers for future hour conditions
columns = html_tree.xpath("//table[@id='hourly-forecast-table']/thead//button[@class='tablesaw-sortable-btn']")
rows = html_tree.xpath("//table[@i... | aa6745565e8fa01df8b8f52f1314ee7bf1a434a8 | 18,856 |
from re import S
def as_finite_diff(derivative, points=1, x0=None, wrt=None):
"""
Returns an approximation of a derivative of a function in
the form of a finite difference formula. The expression is a
weighted sum of the function at a number of discrete values of
(one of) the independent variable(... | 4b76eae0578434a9a087b08f01eefbcd3018bc01 | 18,857 |
def is_prime(pp: int) -> bool:
"""
Returns True if pp is prime
otherwise, returns False
Note: not a very sophisticated check
"""
if pp == 2 or pp == 3:
return True
elif pp < 2 or not pp % 2:
return False
odd_n = range(3, int(sqrt(pp) + 1), 2)
return not any(not pp % ... | f8661a7f625c198dd1d0b5b477aea22f50596a39 | 18,858 |
def createChromosome( totQty, menuData ):
"""
Creates the chromosome with Qty assigned to Each Dish such that
sum of all Qty equals to the number of dishes to be ordered
totQty = Number of Dishes to be Ordered
returns chromosome of dish id and corresponding quantity
"""
chromosome = []
... | 6dae9c5a610a50df67e18f2034513a090088e524 | 18,859 |
def add_residual(transformed_inputs, original_inputs, zero_pad=True):
"""Adds a skip branch to residual block to the output."""
original_shape = original_inputs.shape.as_list()
transformed_shape = transformed_inputs.shape.as_list()
delta = transformed_shape[3] - original_shape[3]
stride = int(np.ceil(origina... | e32897c6e80873b863fbc3358eaec8b6191086f0 | 18,860 |
def _find_bad_channels_in_epochs(epochs, picks, use_metrics, thresh, max_iter):
"""Implements the fourth step of the FASTER algorithm.
This function attempts to automatically mark bad channels in each epochs by
performing outlier detection.
Additional Parameters
---------------------
use_metri... | 6b4a0acc1eb4e1fc4f229cc237e071bf87047b5e | 18,861 |
def solution(A): # O(N^2)
"""
For a given value A, compute the number with the fewest number of
squared values and return them within an array.
eg. 26 can be computed with squared values [25, 1] or [16, 9, 1], but the
answer is only [25, 1] as ... | 56f899d94cfc07a412a357a305553ad0ed8af092 | 18,862 |
def get_device_path():
"""Return device path."""
if is_gce():
return None
devices = get_devices()
device_serial = environment.get_value('ANDROID_SERIAL')
for device in devices:
if device_serial == device.serial:
return device.path
return None | 5bd8bf47859c3721e47cfc45b49aaa06bed4159e | 18,864 |
def pattern_maker(size, dynamic):
"""
Generate a pattern with pixel values drawn from the [0, 1] uniform
distribution
"""
def pattern():
return np.random.rand(size)
def static():
a_pattern = pattern()
def fn():
return a_pattern
return fn
return... | 3fd256fe3f8c7669faec8a7d1757a334a51145ba | 18,865 |
def RMSE(a, b):
""" Return Root mean squared error """
return np.sqrt(np.square(np.subtract(a, b)).mean()) | 7d853535fb9e4072f983f05ad192cc38f2bbea8e | 18,866 |
def alpha_a_b(coord, N, silent=True):
"""Calculate alpha, a, b for a rectangle with coordinates coord and
truncation at N."""
[x0, x1, y0, y1] = coord
a = 0
for zero in zeros[:N]:
a += exp(-zero*y0)/abs(complex(0.5, zero))
b = 0
for zero in zeros[N:]:
b += exp(-zero*y0)/abs(... | 41cc57c16a7526bf7a88503ea9315872062b8ac5 | 18,867 |
from typing import Any
from typing import Optional
def asdataset(
dataclass: Any,
reference: Optional[DataType] = None,
dataoptions: Any = None,
) -> Any:
"""Create a Dataset object from a dataclass object.
Args:
dataclass: Dataclass object that defines typed Dataset.
reference: D... | 4baf2df39f906f2b1981cb597cb6430e95bb1ca1 | 18,868 |
def get_edge_size(reader: ChkDirReader, chunks: list[ChunkRange], tilesize: int) -> int:
"""Gets the size of an edge tile from an unknown chunk"""
for chunk in chunks:
data: bytes = deflate_range(reader, chunk.start, chunk.end, True)
if data is None:
continue
try:
... | 54da5c4adafbcccae4cee9112e35470a97172b00 | 18,869 |
import time
import torch
def multi_gpu_test(model, data_loader, tmpdir=None, gpu_collect=False):
"""Test model with multiple gpus.
This method tests model with multiple gpus and collects the results
under two different modes: gpu and cpu modes. By setting 'gpu_collect=True'
it encodes results to gpu ... | 8ec9bf7efcd126485a8066c7d5932b0c84c44b63 | 18,870 |
def toRegexp(exp,terminate=False,lower=False):
""" Case sensitive version of the previous one, for backwards compatibility """
return toCl(exp,terminate,wildcards=('*',),lower=lower) | d550164d7d2a628a0b0bcf37f5ee95de958fc2e5 | 18,871 |
def marker_used_in_game(marker_id: int) -> bool:
"""
Determine whether the marker ID is used in the game.
:param marker_id: An official marker number, mapped to the competitor range.
:returns: True if the market is used in the game.
"""
return any([marker_id in marker_range for marker_range in ... | 437d5b8c3ff80683e3f19d5cb3786243c6e430b3 | 18,872 |
def iround(x):
"""
Round an array to the nearest integer.
Parameters
----------
x : array_like
Input data.
Returns
-------
y : {numpy.ndarray, scalar}
The rounded elements in `x`, with `int` dtype.
"""
return np.round(x).astype(int) | 64837773f12eb096ede5d8963360ab28427b015d | 18,873 |
def get_ec2_conn():
"""
Requried: env.aws_region, env.aws_access_key, env.aws_secret_access_key
return conneciton to aws ec2
"""
conn = boto.ec2.connect_to_region(
env.aws_region,
aws_access_key_id=env.aws_access_key,
aws_secret_access_key=env.aws_secret_access_key
... | 5c2014f7d1a3ba465ec7f205ac34a5c1feeb2aac | 18,875 |
def create_final_comment_objects():
"""Goes through the final comments and returns an array
of objects."""
arr = [] # Stores objects
for line in final_file:
row = line.split(",")
# Set object variables for each object before adding it to the array
comment_number, commen... | 02107ba5ebc23e5a8db1c30fa8709793e1fcbe7e | 18,877 |
import re
def normalise_target_name(name, used=[], max_length=None):
"""
Check that name[:max_length] is not in used and
append a integer suffix if it is.
"""
def generate_name(name, i, ml):
# Create suffix string
i_name = '' if i == 0 else '_' + str(i)
# Return con... | bffc78525d766cbb941382b6f7dd9371cffee492 | 18,878 |
def construct_pairwise_df(sr: pd.Series, np_fun):
"""Constructs an upper diagonal df from all pairwise comparisons of a sr"""
sr = sr.sort_index()
_mat = np.triu(np_fun(sr.to_numpy() - sr.to_numpy()[:, None]), k=1)
_mat[np.tril_indices(_mat.shape[0])] = None
return pd.DataFrame(_mat, index=sr.index.... | bfef4a9c64e619e2d70efb3dea1fde9da5894634 | 18,879 |
def privacy(request):
"""This returns the privacy policy page"""
return render(request=request, template_name="registration/privacy.html") | c3467b0f670facb152c1f2cd793e6dd46301bc25 | 18,880 |
def seq_search(items, key):
"""顺序查找"""
for index, item in enumerate(items):
if item == key:
return index
return -1 | 1271555aea5f7291ebb3679a219d4b3eb81d87a7 | 18,881 |
def parse_prediction_key(key):
"""The "name" or "key" of a predictor is assumed to be like:
`ProHotspotCtsProvider(Weight=Classic(sb=400, tb=8), DistanceUnit=150)`
Parse this into a :class:`PredictionKey` instance, where
- `name` == "ProHotspotCtsProvider"
- `details` will be the dict: {"Weigh... | 4d971da8097a237f6df8d96bb407c9706c6ed8f6 | 18,883 |
def tick2dayfrac(tick, nbTicks):
"""Conversion tick -> day fraction."""
return tick / nbTicks | 50d01778f62203d37e733a6b328455d3ea10e239 | 18,884 |
from datetime import datetime
def get_business_day_of_month(year, month, count):
"""
For a given month get the Nth business day by count.
Count can also be negative, e.g. pass in -1 for "last"
"""
r = rrule(MONTHLY, byweekday=(MO, TU, WE, TH, FR),
dtstart=datetime.datetime(year, mon... | f0322df24f63ee836cf4f98099ccc0e4eff20c67 | 18,886 |
def inpolygon(wkt, longitude, latitude):
""" To determine whether the longitude and latitude coordinate is within the orbit
:param wkt(str): the orbit wkt info
:param longitude: to determine whether the longitude within the orbit
:param latitude: to determine whether the latitude within the orbit
:r... | b844361f2fb3002a1d6df2a0301d19cc5b75470d | 18,887 |
def matrixMultVec(matrix, vector):
"""
Multiplies a matrix with a vector and returns the result as a new vector.
:param matrix: Matrix
:param vector: vector
:return: vector
"""
new_vector = []
x = 0
for row in matrix:
for index, number in enumerate(row):
x += numb... | 8a03b3acfec0d91fcf0d2c85b4e2bdd4f3053dd2 | 18,888 |
def get_dev_value(weight, error):
"""
:param weight: shape [N, 1], the importance weight for N source samples in the validation set
:param error: shape [N, 1], the error value for each source sample in the validation set
(typically 0 for correct classification and 1 for wrong classification)
"""
... | 740dbd755cf540b0133ddf321207ea0bbd74fc83 | 18,889 |
def biLSTM(f_lstm, b_lstm, inputs, dropout_x=0.):
"""Feature extraction through BiLSTM
Parameters
----------
f_lstm : VariationalDropoutCell
Forward cell
b_lstm : VariationalDropoutCell
Backward cell
inputs : NDArray
seq_len x batch_size
dropout_x : float
Var... | dc3cdc07a20e4ae5fbe257a81d92f15fb51333d9 | 18,890 |
import torch
def refer_expression(captions, n_ground=1, prefix="refer expressions:", sort=True):
"""
n_ground > 1
ground_indices
[1, 0, 2]
source_text
refer expressions: <extra_id_0> red crayon <extra_id_1> Yellow banana <extra_id_2> black cow
target_text
<vis_extra_id_1>... | 57919ee416dbb981dbb7f03163beec779785cc2f | 18,891 |
def url_to_filename(base, url):
"""Return the filename to which the page is frozen.
base -- path to the file
url -- web app endpoint of the page
"""
if url.endswith('/'):
url = url + 'index.html'
return base / url.lstrip('/') | 35084e8b5978869bf317073c76bafc356a7d9046 | 18,892 |
def _msd_anom_3d(time, D_alpha, alpha):
"""3d anomalous diffusion function."""
return 6.0*D_alpha*time**alpha | e5204c52368202665e4dd4acd7d86096349c0d29 | 18,893 |
import json
def make_json_response(status_code, json_object, extra_headers=None):
"""
Helper function to serialize a JSON object and add the JSON content type header.
"""
headers = {
"Content-Type": 'application/json'
}
if extra_headers is not None:
headers.update(extra_headers... | 4857b806819e44b7a77e0a9a51df7b4fe6678656 | 18,894 |
from datetime import datetime
def calc_dst_temerin_li(time, btot, bx, by, bz, speed, speedx, density, version='2002n', linear_t_correction=False):
"""Calculates Dst from solar wind input according to Temerin and Li 2002 method.
Credits to Xinlin Li LASP Colorado and Mike Temerin.
Calls _jit_calc_dst_temer... | f333217e34656c4566a254c1c383191f11e8c3d0 | 18,896 |
def reconstruct(vars_to_reconstruct, scheme, order_used):
"""
Reconstructs all variables using the requested scheme.
:param vars_to_reconstruct: The variables at the cell centers.
:type vars_to_reconstruct: list of list of double
:param Reconstruction.Scheme scheme: The reconstruction scheme to us... | b1e3cd8b8ed91b6c7ccdd5d6903fbce3109a3871 | 18,899 |
import json
import re
from datetime import datetime
import random
def dev_view(request, slug=""):
"""View for homepage or individual developer."""
if slug == "":
dev_name = list(Dev.objects.all().values_list('dev_name', flat=True))
dev_img_address = list(Dev.objects.values_list('dev_image_add... | 363819f854e26b8c62f8fe41fbfbf2e64296246f | 18,901 |
def dpuEnableTaskProfile(task):
"""
Enable profiling facility of DPU Task while running to get its performance metrics
task: DPU Task. This parameter should be gotten from the result of dpuCreatTask()
Returns: 0 on success, or report error in case of any failure
"""
return pyc_libn2cube.pyc_... | 5bb1435ca194b214695891d451f2f56a4cdf6857 | 18,902 |
def get_isotopic_distribution(z):
"""
For an element with number ``z``, returns two ``np.ndarray`` objects containing that element's weights and relative abundances.
Args:
z (int): atomic number
Returns:
masses (np.ndarray): list of isotope masses
weights (np.ndarray): list of ... | 4b038319c37dfd13f0ef085c2b3286f6fc2749c3 | 18,903 |
def url_root():
"""根路径"""
return """
<p>Hello ! Welcome to Rabbit's WebServer Platform !</p>
<a href="http://www.miibeian.gov.cn/" target="_blank" style="">京ICP备 18018365 号</a> @2018Rabbit
""" | 2e6d1d5301ac67bdec30cdeeaeed3c8638568de9 | 18,904 |
import uuid
def CreateMatrix(args, context, history_id, gcs_results_root, release_track):
"""Creates a new iOS matrix test in Firebase Test Lab from the user's params.
Args:
args: an argparse namespace. All the arguments that were provided to this
gcloud command invocation (i.e. group and command argum... | e536001e768f2574d6c5d773b70e6b4e58c6c3da | 18,905 |
def map_keys(func, d):
""" Returns a new dict with func applied to keys from d, while values
remain unchanged.
>>> D = {'a': 1, 'b': 2}
>>> map_keys(lambda k: k.upper(), D)
{'A': 1, 'B': 2}
>>> assert map_keys(identity, D) == D
>>> map_keys(identity, {})
{}
"""
return dict(... | 5e9798d208db5e43dad497d64a4b8e469c67eb3b | 18,907 |
from qiniu import Auth
def generate_qiniu_token(object_name, use_type, expire_time=600):
"""
用于生成七牛云上传所需要的Token
:param object_name: 上传到七牛后保存的文件名
:param use_type: 操作类型
:param expire_time: token过期时间,默认为600秒,即十分钟
:return:
"""
bucket_name = PRIVATE_QINIU_BUCKET_NAME
# 需要填写你的 Access Ke... | 9d0b65fb08032ad557f50cb73c00b4ed0f8eae5a | 18,908 |
def get_s3_object(bucket, key_name, local_file):
"""Download a S3 object to a local file in the execution environment
Parameters
----------
bucket: string, required
S3 bucket that holds the message
key: string, required
S3 key is the email object
Returns
-------
... | 02b10623e30eff1ee5093d4e0f1ee51b3b97d0ac | 18,909 |
def jaxpr_eqns_input_sizes(jaxpr) -> np.ndarray:
"""Return a list of input sizes for each equation in the jaxpr.
Args:
jaxpr: Jaxpr to get input sizes for.
Returns:
A #eqns * #eqns numpy array of input sizes. cost[l, r] represents the
input size of the l-th to (r - 1)-th equation i... | 0209c0342725ae83ea8051ef47852134e6ad4502 | 18,910 |
def extract_message(raw_html):
"""Returns the content of the message element.
This element appears typically on pages with errors.
:param raw_html: Dump from any page.
"""
results = re_message.findall(raw_html)
if results:
return results[0]
return None | 498ee1c38c08db365b1bf91ecd32a79c2d2f5f68 | 18,911 |
from typing import Callable
from typing import Tuple
def _weighted_essentially_non_oscillatory_vectorized(
eno_order: int, values: Array, spacing: float, boundary_condition: Callable[[Array, int],
Array]) -> Tuple[Array, Array... | debd652ddf02419e191d9d0c5d21640760d3f227 | 18,912 |
def defaults(dictionary, overwriteNone=False, **kwargs):
"""
Set default values of a given dictionary, option to overwrite None values.
Returns given dictionary with values updated by kwargs unless they already existed.
:param dict dictionary:
:param overwriteNone: Whether to overwrite None values.... | 6def5bb71839b3b627a5597ea6fa7fa1b48e463b | 18,913 |
from typing import Union
from typing import Optional
from typing import Dict
import tqdm
def expected_average_shortest_distance_to_miner(
crawl_graph: Union[
ProbabilisticWeightedCrawlGraph[CrawledNode], CrawlGraph[CrawledNode]
],
distances: Optional[np.ndarray] = None,
miner_probability: Opti... | 6ea56881dce6d589eebec6422a0a5ffae41fe153 | 18,914 |
from typing import Callable
def dummy_state_sb(dummy_state: State, dummy_train_dataloader: DataLoader, conv_model: MosaicClassifier,
loss_fun_tuple: Callable, epoch: int, batch: int) -> State:
"""Dummy state with required values set for Selective Backprop
"""
dummy_state.train_dataload... | 4f4af7193ccf0a4fb883a7d4b42ef58da49333b3 | 18,915 |
def create_model(species={}, parameters={}, reactions={}, events={}):
"""Returns an SBML Level 3 model.
Example:
species = { 'E': 1, \
'EM': 0, \
'EM2': 0, \
'F': 100, \
}
parameters = {'k': (1e-06,'per_min'), \
}
r... | 1950509f83b858ef7829aa6f30caaa3734ff2946 | 18,916 |
def get_network_connection_query(endpoint_ids: str, args: dict) -> str:
"""Create the network connection query.
Args:
endpoint_ids (str): The endpoint IDs to use.
args (dict): The arguments to pass to the query.
Returns:
str: The created query.
"""
remote_ip_list = args.get... | 6390c6ae4436632055fb90687e51cfac2ca09a05 | 18,917 |
import json
def dump_into_json(filename, metrics):
"""Dump the metrics dictionary into a JSON file
It will automatically dump the dictionary:
metrics = {'duration': duration,
'voltage_extremes': voltage_extremes,
'num_beats': num_beats,
'mean_hr_bpm': mean_hr_... | 2e6effbcefe7cb3033c4c472cbee3850c00ae06b | 18,918 |
def _costfun(params, pose0, fixed_pt3d, n_cams, n_pts, cam_idxs, pt3d_idxs, pts2d, K, px_err_sd):
"""
Compute residuals.
`params` contains camera parameters and 3-D coordinates.
"""
if isinstance(params, (tuple, list)):
params = np.array(params)
params = np.hstack((pose0, params))
p... | 3e97e7d14712fe8b89b60de958fd743c728e8cba | 18,919 |
import base64
import requests
def get_headers(base_url: str, client_id: str, client_secret: str, grant_type: str, verify: bool):
"""
Create header with OAuth 2.0 authentication information.
:type base_url: ``str``
:param base_url: Base URL of the IdentityIQ tenant.
:type client_id: ``str``
:... | 06ced982595d4abe99e193ec7ab43e366d575f7b | 18,921 |
import logging
from datetime import datetime
def draw_pie(fracs, labels):
"""
This method is to plot the pie chart of labels, then save it into '/tmp/' folder
"""
logging.info("Drawing the pie chart..")
fig = plt.figure()
plt.pie(fracs, labels=labels, autopct=make_autopct(fracs), shadow=True)
... | 18ee8d0b6054467b9612e282c0d12fa9a10c549b | 18,922 |
import re
def eval_function_old(param, param_type):
""" Eval Function (Deprecated)
isOwner 0xe982E462b094850F12AF94d21D470e21bE9D0E9C
:param param:
:param param_type:
:return:
"""
try:
splitted_input = param.split(' ')
except TypeError:
pass
else:
try:
... | 6c28fdad6803330bcea8b086cc2e15209125a8d6 | 18,923 |
def _multi_convert(value):
"""
Function try and convert numerical values to numerical types.
"""
try:
value = int(value, 10)
except ValueError:
try:
value = float(value)
except ValueError:
pass
return value | abcd3656fdf5ce7ab1427ee6884a18853bdfaf59 | 18,924 |
def dbinom(n, p):
"""Binomial Distribution
n = number of repetitions
p = success probability
Used when a certain experiment is repeated n times
with a 0 ≤ P ≤ 1 probability to succeed once.
This doesn't return a value, but rather the specified binomial function
"""
def b(k):
"""Retu... | 8917b3eb5ce189094f2b129c596a99d20dfcdcc5 | 18,925 |
def array_to_image(x, data_format='channels_last'):
"""Converts a 3D Numpy array to a PIL Image instance.
Args:
x: Input Numpy array.
data_format: Image data format, either "channels_first" or "channels_last".
Returns:
A PIL Image instance.
Raises:
ValueError: if inv... | 2278a317e6d820b9d1aee2d7d796261b14d719f2 | 18,926 |
import time
import logging
import re
def worker_process_download_tvtorrent(
tvTorUnit, client = None, maxtime_in_secs = 14400,
num_iters = 1, kill_if_fail = False ):
"""
Used by, e.g., :ref:`get_tv_batch`, to download missing episodes on the Plex_ TV library. Attempts to use the Deluge_ serve... | 899b13f70d1673168eab4b533ce7e5219d25d365 | 18,927 |
from operator import or_
def find_fixture(
gameweek,
team,
was_home=None,
other_team=None,
kickoff_time=None,
season=CURRENT_SEASON,
dbsession=session,
):
"""Get a fixture given a gameweek, team and optionally whether
the team was at home or away, the kickoff time and the other tea... | fcf90acd4fd8dd663c5cdf2ec99bd428c8cf7a45 | 18,928 |
import errno
def plat_specific_errors(*errnames):
"""Return error numbers for all errors in errnames on this platform.
The 'errno' module contains different global constants depending on
the specific platform (OS). This function will return the list of
numeric values for a given list of potential nam... | acb70b2b7d6b16fbe2cfc9f559606efd504b8e3f | 18,929 |
from pymatgen.util.num import make_symmetric_matrix_from_upper_tri
from typing import Union
def make_symmetric_matrix(d: Union[list, float]) -> list:
"""
d (list or float):
len(d) == 1: Suppose cubic system
len(d) == 3: Suppose tetragonal or orthorhombic system
len(d) == 6: Suppose the... | 318caf380a8f0a0878eac54bae49c86722e532bb | 18,931 |
def convert_lds_to_block_tridiag(As, bs, Qi_sqrts, ms, Ri_sqrts):
"""
Parameterize the LDS in terms of pairwise linear Gaussian dynamics
and per-timestep Gaussian observations.
p(x_{1:T}; theta)
= [prod_{t=1}^{T-1} N(x_{t+1} | A_t x_t + b_t, Q_t)]
* [prod_{t=1}^T N(x_t |... | d16721ffb77f06cd55ca3c70238ca56fad76970d | 18,932 |
def extract_string_from_tensor(input_ids, mode="single", config=None, tokenizer=None):
"""
Args:
input_ids (Tensor): input sentences with shape [batch_size, seq_len].
mode (str): ["pair", "single"]
"pair" for tasks with paired inputs `<bos> A <eos> B <eos>`,
... | 27cf8905350db53ec908f3b8ef8674a7ac3a17eb | 18,933 |
def schema_validation_matching(source_fields, target_fields):
"""Compare schemas between two dictionary objects"""
results = []
# Go through each source and check if target exists and matches
for source_field_name, source_field_type in source_fields.items():
# target field exists
if sour... | 7af82c39462de09e326c6f4413a2d6be7fd6c977 | 18,934 |
import pkg_resources
def find_thirdparty_marshaller_plugins():
""" Find, but don't load, all third party marshaller plugins.
Third party marshaller plugins declare the entry point
``'hdf5storage.marshallers.plugins'`` with the name being the
Marshaller API version and the target being a function that... | 7aad132f520b67d5b39e857175e4bc006fd3ad72 | 18,935 |
def justTransportResponse(transport):
"""
Helper function for creating a Response which uses the given transport.
All of the other parameters to L{Response.__init__} are filled with
arbitrary values. Only use this method if you don't care about any of
them.
"""
return Response((b'HTTP', 1, ... | 02a18a500cb9a623c287d4e2f3777237e3574ef6 | 18,936 |
def object_comparator_lookup(src_obj, dst_obj):
"""
Compare an object with another entry by entry
"""
dont_match = []
no_upstream = []
for i in dst_obj:
count_name = 0
count_value = 0
for j in src_obj:
if list(j.keys())[0] == list(i.keys())[0]:
... | ba5767624255da915d9c07d25b62880c387f6f00 | 18,938 |
def line(
data_frame=None,
x=None,
y=None,
line_group=None,
color=None,
line_dash=None,
hover_name=None,
hover_data=None,
custom_data=None,
text=None,
facet_row=None,
facet_row_weights=None,
facet_col=None,
facet_col_weights=None,
facet_col_wrap=0,
facet_r... | bcedfe2c9297f4d3c049e500265f9ffbc0dde85a | 18,939 |
def is_primitive(v):
"""
Checks if v is of primitive type.
"""
return isinstance(v, (int, float, bool, str)) | d22607c0e2b93b82b1da6beb50de68668624dd71 | 18,940 |
def linkify_only_full_urls(attrs, new=False):
"""Linkify only full links, containing the scheme."""
if not new: # This is an existing <a> tag, leave it be.
return attrs
# If the original text doesn't contain the scheme, don't linkify.
if not attrs['_text'].startswith(('http:', 'https:')):
... | 89fcc7f3fc53353686260779ae8ddb4c0523c57b | 18,941 |
def Precedence(op):
"""The numeric precedence of a binary operator."""
# Particularly convenient during layout of binary operators.
return float(sum(i * (op in grp[1:])
for i, grp in enumerate(precedence))) / len(precedence) | 0071d2972474c57376c334401c43673f1c4bde49 | 18,945 |
from typing import Dict
from typing import Any
def _FeastToExampleTransform(
pipeline: beam.Pipeline, exec_properties: Dict[str, Any], split_pattern: str
) -> beam.pvalue.PCollection:
"""Read from BigQuery and transform to TF examples.
Args:
pipeline: beam pipeline.
exec_properties: A dict of... | 76451a98b9e11188eda42b5141e73647b87df94b | 18,946 |
import re
import logging
def parse_host_info(qhost_tree, queues_tree, queues_to_ignore=[]):
"""
:return: dictionary key: host, value HostInfo
"""
dctRet = {}
for host_node in qhost_tree.findall('host'):
host_name = host_node.get('name')
dct_hostvalues = dict([(hostvalue_node.get('n... | a5f5154ac50d358b4a523872ffcaba3030d2f722 | 18,948 |
import click
def _get_param_type_from_str(
type_name: str = None,
param_doc: docstring_parser.DocstringParam = None,
) -> t.Tuple[_ParamArgs, t.Union[click.ParamType, None]]:
"""Guess parameter type from parameter type name."""
type_name = type_name or ""
desc = param_doc.description if pa... | a13621ffbed428fbc32f6285e2fc0a2b53097cad | 18,949 |
def solve(task: str) -> int:
"""How many differently colored bags can contain shiny gold?"""
parents = process_data(task)
seen = set()
candidates = parents["shiny gold"]
while candidates:
candidate = candidates.pop()
if candidate not in seen:
seen.add(candidate)
... | ea505c346a4482b9516ad22baa71d251b7e1dc41 | 18,950 |
import urllib
import base64
import hashlib
import requests
def cityDesc(codePostal):
"""
code de retour :
100 : tout est normal
200 : la requete n'a pas abouti
300 : pas de cine dans la ville
400 : la ville n'existe pas
"""
headersUA = init_connect()
YMDstr = getDate()
searchField = codePostal
... | 06da49d9afe5420869204a423a2db31df11cc58e | 18,951 |
async def get_reposet(request: AthenianWebRequest, id: int) -> web.Response:
"""List a repository set.
:param id: Numeric identifier of the repository set to list.
:type id: repository set ID.
"""
rs_cols = [
RepositorySet.name,
RepositorySet.items,
RepositorySet.precomputed... | a3a2cf6cb1152aadb81798cfa3e1be214635edad | 18,952 |
def is_called_at_module_level() -> bool:
"""
Check if the current function is being called at the module level.
Raise `RuntimeError` if `is_called_at_module_level()` is not called in a function.
"""
if not (frame := getcallerframe().f_back):
raise RuntimeError(
"is_called_at_mo... | 0c807205472021b20c7b7bad27c8b5f7a634dd85 | 18,954 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.