content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_partner_rows(*args, **kwargs):
"""
获取列表
:param args:
:param kwargs:
:return:
"""
return db_instance.get_rows(AAPartner, *args, **kwargs) | 962dc226d6fa56d6219984c688fe625db5e2ebff | 42,361 |
def random_val(matrix,mean,std):
"""Function to apply normally distributed random noise to the matrix that represents sarcomeres as voxels."""
mat = np.random.normal(mean,std,matrix.shape)
matrix += mat
return matrix | baa36e2bd5ae92f1f02aa5ed5860e25bd5e48c1c | 42,362 |
import gzip
import struct
def load_mnist_labels(file_name, onehot, num_classes=10):
"""Load MNIST image labels."""
with gzip.open(file_name, 'rb') as mnist_file:
_, num_labels = struct.unpack(
">II", mnist_file.read(8))
buf = mnist_file.read(num_labels)
labels = np.frombuff... | d1ed83386750af081ea4c5a23643a5b17778e5f4 | 42,364 |
def sinr(
received_signal_dbm: float,
received_interference_dbm: float,
noise_floor_dbm: float,
):
"""
Calculate the Signal Interference Noise Ratio in decibels.
That means that
$10^{sinr/10} . (noise+interference) = signal$
Should always hold.
"""
# We need to convert to watts... | 4f7dd997ce76574bf7c3bad04efb94dca850b704 | 42,366 |
def load_services(config, bus, path=None):
"""Load builtin services as well as service plugins
The builtin service folder is scanned (or a folder indicated by the path
parameter) for services and plugins registered with the
"mycroft.plugin.audioservice" entrypoint group.
Args:
config: conf... | ab92e41492ffc9fd3245d30a538c3fcfebaad8e4 | 42,367 |
def generateInput_v4(fout=False):
"""
Generate complete observation matrix
"""
des, X = generate_corina_features('ca')
pvt = X[:,2] # poverty index of each CA
popul = X[:,0].reshape(X.shape[0],1)
# poi_cnt = getFourSquareCount()
# poi_cnt = np.divide(poi_cnt, popul) * 10000
... | 1c437669f706b54caa2891668f6efc2288167299 | 42,368 |
def validate_gwdevice_list(data, valid_values=None):
"""Validate the list of devices."""
if not data:
# Devices must be provided
msg = _("Cannot create a gateway with an empty device list")
return msg
try:
for device in data:
interface_data = device.get(constants.... | 7b87dba712d18c7577ef70fc6190806fbb702b95 | 42,369 |
from typing import List
from typing import Tuple
def deflate_spans(
spans: List[Tuple[int, int, int]]
) -> List[List[Tuple[int, int]]]:
"""[summary]
Args:
spans (List[Tuple[int, int, int]]): [description]
Returns:
List[List[Tuple[int, int]]]: [description]
"""
# assuming last... | 037c11b0c5d4707b2d19a0b0cc457a93908f5186 | 42,371 |
def correlation_coeff(score, gold_data):
"""
It will take the list of similarity score and calculates pearson correlation and
spearman correlation. Finally, it returns the score as per competition standard.
"""
a = spearmanr(score, gold_data)[0]
b = pearsonr(score, gold_data)[0]
return (2*a... | 82784c270c039af087887a4b7a8b0faaa41b36d7 | 42,372 |
def operate_status_template(open_now: bool) -> tuple:
"""Flex Message 餐廳營業狀況
Args:
open_now (bool): 營業中
Returns:
tuple: (營業狀況, 營業文字顏色)
"""
if open_now:
operate_status = {
"type": "text",
"text": "營業中",
"size": "xs",
"color": "... | 366d291b5e847192401f76f0c8a560c02452cef7 | 42,373 |
def paramset_to_rootnames(paramset):
"""
Generates parameter names for parameters in the set as ROOT would do.
Args:
paramset (:obj:`pyhf.paramsets.paramset`): The parameter set.
Returns:
:obj:`List[str]` or :obj:`str`: The generated parameter names
(for the non-scalar/scalar c... | 0fc4732a7accff55f8015c5b46cb1c44c002ef18 | 42,374 |
import base64
import json
from datetime import datetime
def create_access_token(token):
# type: (str) -> azure.core.credentials.AccessToken
"""Creates an instance of azure.core.credentials.AccessToken from a
string token. The input string is jwt token in the following form:
<token_header>.<token_paylo... | 2cad1e621c717305742aaae9b6b101973f4ca23e | 42,375 |
def get_resolution(token):
"""Parse a <resolution> token in ddpx."""
if token.type == 'dimension':
factor = RESOLUTION_TO_DPPX.get(token.unit)
if factor is not None:
return token.value * factor | 2bb6e05610ebdb5275c7ed4910bb980e99edc564 | 42,376 |
from datetime import datetime
def format_date(date_string, date_format):
"""
"""
formatted_date = datetime.datetime.strptime(date_string, date_format)
year_directives = ['%y', '%Y', '%c', '%x']
contains_year = any(directive in date_format for directive in year_directives)
if not contains_ye... | 7445438c83822f5407963375aa633061304906bd | 42,377 |
def query_neo_nodes(port, pwd):
"""
查询所有的节点
Args:
port:
pwd:
Returns:
"""
graph = Graph(f"bolt://{NEO_HOST}:" + port, password=pwd)
nodes_matcher = NodeMatcher(graph)
nodes = list(nodes_matcher.match())
return {node.identity: node["s_name"] for node in nodes} | c594f108ca1fa0b3704f3ad5458a850b9984c082 | 42,378 |
def __select_constraints_pairwise(data, labels, samples, samples_labels, n_neighbors):
"""select constraints of the form x-y where x,y have different labels"""
constraints = []
# nearest neighbors are selected from the entire set
neighbors = {}
data_by_label = {}
smallest_norm = np.inf
for i... | 03b01a8aa47528822ab5a398594c29a2f2ef7312 | 42,379 |
from typing import Callable
from typing import Iterable
from typing import Tuple
def take_while(predicate: Callable, iterable: Iterable) -> Tuple:
"""
Constructs a iterable list by taking elements from ``iterable`` while ``predicate`` is true,
Stop taking after the first element falsifies the predicate.
... | 01a32a6484e209dcc48d6f9e67f4fd8ba9b1270b | 42,380 |
def comprobar_restricciones_check(parameters, check):
"""Comprueba las restricciones CHECK
:param parameters: tipo de dato Number: ["Number", nombre_col, precision, escala]
tipo de dato String: ["String", nombre_col, varying, max_size]
:param check: campo check de la sent... | 69874b8f21f66586b1d971e4d7f87ae253e681b3 | 42,381 |
from typing import Optional
async def check_response_route(
uid: int = Query.i(description="user id", gt=10, lt=1000),
email: Optional[str] = Query.i(default="example@xxx.com", description="user email"),
user_name: str = Query.i(description="user name", min_length=2, max_length=4),
age: int = Query.i(... | ce889fa36b1cd0d78d72c2f636cebbc66d1a1689 | 42,382 |
def _n_dist(v, n, randomize=False):
"""
Creates grouping factor with
distributed excess elements
"""
len_v = float(len(v))
divisor = len_v / n
# Create range the length of v (+1 because it starts at 0)
# Divide each element and get everything but the first element (0)
v_divided = ... | 5ff74c95a78acbe4e6415a85584dc80e848b9758 | 42,384 |
def forward_sensitivity_model(t, s, args):
"""
This solves a system of (P+1)*N differential equations (needs to solve the
original ODE in conjunction)
"""
y = s.reshape((2, 5))[:, 0]
sensitivities = s.reshape((2, 5))[:, 1:]
del_f__del_u = jax.jacobian(model, argnums=1)(t, y, args)
del_f... | d565c1f1a82613082931c59a965f1c261a2c85ad | 42,385 |
def create_code_index(model, **kwargs):
"""
Creates an value/id index of the model
args:
model: datatstore class, babel datastore table
kwargs: dict, filters to be applied to query
returns:
idx: dict, {column value: datastore id}
"""
idx = {}
with session_scope() as s... | 5c98aa00b0262572bff29079a50ce2db82a5e369 | 42,386 |
def get_exploration_recommendations(exp_id):
"""Gets a list of ids of at most 10 recommended explorations to play
after completing the exploration keyed by exp_id.
Args:
exp_id: str. The ID of the exploration for which to get
the recommendations.
Returns:
list(str). List of... | fff4f812086dfa01161a15e1409d876010302f5f | 42,387 |
def BNNoReLU(x, name=None):
"""
A shorthand of BatchNormalization.
"""
if name is None:
x = BatchNorm('bn', x)
else:
x = BatchNorm(name, x)
return x | af0c0cbe3a8c78f207afd54c4adf7799d67200db | 42,388 |
def symPT(x, Ps, Ts, window_half):
"""
Measure of asymmetry between oscillatory peaks and troughs
Parameters
----------
x : array-like 1d
voltage time series
Ps : array-like 1d
time points of oscillatory peaks
Ts : array-like 1d
time points of oscillatory troughs
... | 49ec586d8925e0154313a91747d3c7ea5d8780e2 | 42,389 |
import time
def get_items_serial_number(prefix, obj):
"""获取物品唯一货号"""
date_str = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
# 生成一个固定6位数的流水号
objmodel = obj.objects.last()
serial_number = objmodel.id if objmodel else 0
serial_number = "{0:06d}".format(serial_number + 1)
return... | c8482b0debe680b36845d3ee933d0771c4efe05f | 42,390 |
import time
def tmtuple(tmsecs=None):
""" Return a time tuple.
This is currently an alias for gmtime(), but allows later tweaking.
"""
# avoid problems due to timezones etc. - especially a underflow
if -86400 <= tmsecs <= 86400: # if we are around 0, we maybe had
tmsecs = 0 ... | 5c848afca1247e55215a3858a774419a6b6c8961 | 42,391 |
def make_gaussian_prf(size):
"""Generate various pRFs based on 2d Gaussian kernel with different
parameters.
Return a pRF matrixs which shape is (size, size, size*size*fwhm#)
"""
fwhm_num = 10
fwhms = np.arange(1, fwhm_num+1)
prfs = np.zeros((size, size, size*size*fwhm_num))
for k in r... | bb8d2058508652426a99b609d188c75160a99bb7 | 42,392 |
def split(array, nrows, ncols):
"""Split a matrix into sub-matrices."""
r, h = array.shape
return (array.reshape(h // nrows, nrows, -1, ncols)
.swapaxes(1, 2)
.reshape(-1, nrows, ncols)) | be105c055c08288ff3d387f34975bda223030faf | 42,393 |
from typing import Optional
from typing import Union
from typing import Tuple
from typing import List
def enumerate_blobs_to_file(
output_file: str,
account_name: str,
container_name: str,
sas_token: Optional[str] = None,
blob_prefix: Optional[str] = None,
blob_suffix: ... | 595b464efb2a8ba7a96562688bcba8064ffb4f18 | 42,395 |
def origin_trial_enabled_function_name(definition_or_member):
"""Returns the name of the OriginTrials enabled function.
An exception is raised if both the OriginTrialEnabled and RuntimeEnabled
extended attributes are applied to the same IDL member. Only one of the
two attributes can be applied to any m... | 6284f1a3ab8773382f3cc2a1e121cd68592b7553 | 42,396 |
def validate_yn(answer):
"""Validate y/n prompts
:param answer: User response to y/n prompt. If a boolean value is passed
(e.g. if a prompt received parsed_input=True), it is treated as a y/n
answer and considered valid input
:return: True if user answered yes, False if user answered no
... | 4b41cfeeca6eebc6f287c37090379d7423bc6aca | 42,397 |
from httplib import HTTPConnection
def wget(URL):
"""Upload a file across the network using HTTP protocol
data: content of the file to upload.
URL: e.g. "http://id14timing3.cars.aps.anl.gov/tmp/test.txt"
"""
URL = URL.replace("http://","")
ip_address = URL.split("/")[0]
script = "/"+"/".jo... | 0f97206943941aefa0d542931a57f68a3fadfdc5 | 42,398 |
def other_document(database, document):
"""
Returns:
Document: Copy of 'document' fixture, but with an additional revision.
"""
other_document = Document(database, document.doc_id)
other_document.retrieve()
other_document.data['more'] = 'stuff'
other_document.create_update()
retu... | 0e9936408c4618aceaec853d42af2c5799bcd83b | 42,399 |
def trial_division_5(n):
"""试除法,境界5层"""
prime_number_list = []
for i in range(2, n):
for j in prime_number_list:
# if j > int(i**0.5)+1:
# break
if i % j == 0 and j < int(i**0.5)+1:
break
else:
prime_number_list.append(i)
... | ed5235f4a09f0ff9a46d7af5a90486a6c7aefdb5 | 42,400 |
from typing import Type
def _type(array: Array) -> Type | None:
"""Get the type object associated with an array.
Parameters
----------
array : dask_awkward.Array
The collection.
Returns
-------
Type
The awkward type object of the array; if the array does not
conta... | 16fe65aa7d857ae4d7abf282b3e2aa847f31c333 | 42,401 |
def dcgan_discriminator(x, flags, scope=None, reuse=None, return_acts=False):
"""DCGAN-style discriminator network."""
nonlinearity = nonlinearity_fn(flags.nonlinearity_d, True)
ds_fs = flags.downsample_conv_filt_size
x_fs = flags.extra_conv_filt_size
acts = []
with tf.variable_scope(scope, reuse=reuse):
... | 69fe5199083d94b5d5b95e797b9363118969c67d | 42,402 |
def reconstruct_cfcoeffcients(output_dict, atomtype=None):
"""
Reconstruct the CFCoefficient list from the output dictionary
of the FleurCFCoeffWorkChain
:param output_dict: output dictionary node or the corresponding
dictionary
:param atomtype: int of the atomtype to recons... | 8a9f365d140537b370632f0894a008ec1744f7b5 | 42,403 |
def test_map_args_size():
"""
Feature: Check the size of inputs of map.
Description: The size of inputs of map must be greater than 1.
Expectation: The size of inputs of map must be greater than 1.
"""
class MapNet(Cell):
def __init__(self):
super().__init__()
sel... | 7944831bcd81e7b5598970b9146f217809f2790e | 42,404 |
def get_int_forms(ref_group, isomorphisms):
"""Return a list of integer forms ('permutations') for a list of isomorphisms,
i.e., mappings, based on a reference group."""
return [get_integer_form([iso[elem] for elem in ref_group.elements])
for iso in isomorphisms] | 73f23085b8818233c4081f7829ad6691b8618c6c | 42,405 |
def header_string(key_length=0, number_of_seconds=2):
""" return a header string for the output file """
header_string = '#'
header_string += ' ' * (key_length+8)
header_string += ' 1 2 3 ' * number_of_seconds + '\n'
header_string += '#'
header_string += ' ' * (key_l... | 8da90fa3171be1f3ce20932777835c5f2239d4a0 | 42,406 |
import requests
def send_message(gmess, address):
"""
Envia un mensaje usando un request y retorna la respuesta como
un grafo RDF
"""
msg = gmess.serialize(format='xml')
r = requests.get(address, params={'content': msg})
# Procesa la respuesta y la retorna como resultado como grafo
gr... | c6f6e09e312fa01f1f36b5a679b2b803f743c77b | 42,407 |
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
config = Configurator(settings=settings)
config.include('pyramid_chameleon')
log.info('Starting RaspiServer...')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('hom... | cb1d37e2b5ccaba271dedc3836d110e0d245f6f4 | 42,408 |
def sparse_average_precision_at_k(y_true: csr_matrix, y_scores: csr_matrix, k: int = 5) -> float:
"""
Computes the average precision at k for sparse binary matrices.
:param y_true: grounded truth in binary format (n_samples, n_labels)
:param y_scores: predictions in representation that can be ranked (e.... | 6ca71dcc4d91bc315bddafb01b651aff2442e29c | 42,409 |
import array
def calc_contour_normals_2d(pts,seg):
"""calc 2d normals of contour pts
assume the pts are clockwise around the object
(row,col)
"""
pset = set([tuple(x) for x in pts])
normals = empty((len(pts),2),int)
j=0
for i in xrange(len(seg)):
p1,p2,p3 = [array(seg[x]) for x... | c68f72307f4c4e7e993684bbed795dcc583a2212 | 42,411 |
def build_model(X_train, X_test, y_train, y_test):
"""Build and evaluate a model. Also returns the test-set predictions."""
count_vect = sktext.CountVectorizer()
X_train_counts = count_vect.fit_transform(X_train)
tfidf_transformer = sktext.TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_tra... | d20d99b4dcb8f4887c9007ca267f5832fb2f1707 | 42,412 |
from typing import Optional
def int_to_comma_hex(n: int, blength: Optional[int] = None) -> str:
"""
int_to_comma_hex
Translates an integer in its corresponding hex string
:type n: ``int``
:param n: Input integer
:type blength: ``Optional[int]``
:param blength: Add padding to reach length... | a1833b68b4c179070f454bb675909b3e3495b8cf | 42,413 |
import json
def load_sqlalchemy_response_from_json(filename):
""" Load a sqlalchemy response from a json file """
with open(filename, 'r', encoding="utf-8") as tmp:
data = json.load(tmp)
return load_sqlalchemy_response_from_object(data) | b74b9b3321d17cfdcae02977cfeda75c259ff539 | 42,414 |
def get_peaks(runs, signal_type, version='xenonnt_v7', output_folder='/project2/lgrandi/yuanlq/xenonnt/', **kargs):
"""wrapper around get_array to get peaks of a certain source. Now supporting KrS1A, KrS1B, Ar37.
Args:
runs (str or 1darray): runs to extract certain signal. Assumed all type of runs if p... | 850856b8eac7cabd451722d106b297d72521cc00 | 42,415 |
def imshow(image, ax=None, title=None):
"""
Print the given image
"""
if ax is None:
fig, ax = plt.subplots()
# PyTorch tensors assume the color channel is the first dimension
# but matplotlib assumes is the third dimension
image = image.transpose((1, 2, 0))
# Undo... | 3f889b5d228fa0700f6f12ca326c5fb5170c2f13 | 42,416 |
def svn_wc_diff_callbacks3_invoke_dir_opened(*args):
"""
svn_wc_diff_callbacks3_invoke_dir_opened(svn_wc_diff_callbacks3_t _obj, svn_wc_adm_access_t adm_access,
svn_boolean_t tree_conflicted, char path,
svn_revnum_t rev, void diff_baton) -> svn_error_t
"""
return apply(_wc.svn_wc_diff_call... | 6f58cf86b66b7fc05e3fa3bfaeebcef9fb461d0b | 42,417 |
def get_reset_password():
"""Get the user name and email address to reset the password.
:returns: the html form for resetting password
:rtype: str
"""
return template('get_reset_code.html') | 56dfa000b4c7b91f1019f431791981df79303e64 | 42,418 |
def update_config(original, update):
"""
Recursively update a dict.
Parameters must be specified in original to be overwritten
"""
for basekey, baseval in original.items():
if isinstance(baseval, dict):
for key, val in baseval.items():
if key in update:
... | cff13b8b5a36fae226d81dfca5e0599466f77f36 | 42,419 |
def get_request_id():
"""
获取request_id
"""
try:
return get_request().request_id
except AttributeError:
return "" | c697e1cf872e8e7e6334aeae88c7dd702e56c6b1 | 42,421 |
import base64
def create_message(to, subject, message_text):
"""Create a message for an email and return a dictionary
object with its "raw" field containing a base64url encoded
string
{'raw': str}
Example for MIMEText object
>>> message = email.mime.text.MIMEText("Hello world")
>>> messa... | 921302ed31240bb860e826e1696c0a2ad6b3bd3b | 42,422 |
def adcm_api_credentials() -> dict:
"""ADCM credentials for use in tests"""
return {"user": "admin", "password": "admin"} | a2efa47ee588086b0d5dc089728e18b9108964a8 | 42,423 |
import copy
def unfill_isogeny_matrix(M):
"""
Reverses the action of ``fill_isogeny_matrix``.
INPUT:
- ``M`` -- a square symmetric matrix of integers.
OUTPUT:
(matrix) a square symmetric matrix obtained from ``M`` by
replacing non-prime entries with `0`.
EXAMPLES::
sage: ... | 5ccfa256198d689d366fd3950de5eb68e6d798a1 | 42,424 |
def _from_csr_ss(csr: _CSR, rsp, rep):
"""
Convert a subset of a Numba CSR to an MKL sparse matrix handle.
"""
_sp = ffi.from_buffer(csr.rowptrs)
_cols = ffi.from_buffer(csr.colinds)
_vals = ffi.from_buffer(csr.values)
return _lk_mkl_spsubset(rsp, rep, csr.ncols, _sp, _cols, _vals) | 5db405aaee625af29e8f036c9912df8548dfa7a1 | 42,426 |
import pydantic
def dc(cls: type):
"""Pydantic dataclass decorator with custom configuration and auto update forward references"""
cls = pydantic.dataclasses.dataclass(config=Config)(cls)
cls.__pydantic_model__.update_forward_refs()
return cls | 6a409111500d1e423378eb37c7642dd7abae18f5 | 42,427 |
def register_game_events(window):
"""
Function used to register all prepared methods inside window property of GameWindow object.
:param window: GameWindow object
"""
@window.window.event
def on_draw():
on_draw_factory(window)()
@window.window.event
def on_mouse_motion(x, y, dx,... | 2ed235bdb40355203f4da77acd40da5779b4a185 | 42,428 |
def get_contour_data(model, pipeline, n_points=1000):
"""Create the data used to show the boundary of the decision function."""
x0s = np.linspace(X_AXIS[0], X_AXIS[1], n_points)
x1s = np.linspace(Y_AXIS[0], Y_AXIS[1], n_points)
x0, x1 = np.meshgrid(x0s, x1s)
X = np.c_[x0.ravel(), x1.ravel()]
... | 2079abaca7e25e865396d7ade60467527766ce92 | 42,429 |
def parse_args():
""" parse_args """
parser = ArgumentParser(description="resnet50 example")
parser.add_argument("--model", type=str, default="resnet50",
help="the network architecture for training or testing")
parser.add_argument("--phase", type=str, default="test",
... | a92a72a89584a7aa5a87ebb521615d58729e34ae | 42,430 |
from typing import Dict
from typing import Union
import threading
def test__synchronized_on_instance__class__no_parentheses() -> None:
"""Test `@synchronized_on_instance` with no parentheses."""
# pylint: disable=missing-function-docstring
@synchronized_on_instance
class _Class:
def method(s... | 885f20bdea0201c3a840c019363c94775929b716 | 42,431 |
def edit_blogpost(request,blogpost_id):
"""编辑已有条目"""
blogpost = BlogPost.objects.get(id = blogpost_id)
title = blogpost.title
#确认请求的主题属于当前登陆的用户,使用函数check_blog_owner
check_blog_owner(request,title)
if request.method !='POST':
#初次请求,使用当前条目填充表单
form = BlogPostForm(instance = blogpost)
else:
#POST提交的数据,对数据进行处理
... | 4a4bf61cadb8ef1abe47801275ca1bfce37b907a | 42,433 |
import warnings
def get_points_simple(**kwargs):
"""Load a DataFrame of points with the most typical query
Parameters
----------
**kwargs
Optional arguments that are passed to get_credentials()
Returns
-------
points_df : pandas DataFrame
DataFrame of all points
"""
... | d108db09eeb3dda02270d4d028588e652defca12 | 42,434 |
def run_text_query(cand_provider,
top_qty,
query_text,
query_id=FAKE_QUERY_ID, field_name=TEXT_FIELD_NAME):
"""Run a text query.
:param cand_provider: a candidate provider object
:param top_qty: a number of top-scored entries to return
:param que... | b62222f1088daaa7baa88e34a8640d6481822715 | 42,435 |
def all_scatter_plots(data):
"""
Generate scatter plots for all hard-coded variable pairs
Arguments:
data: pandas dataframe
Returns: scripts, divs
scripts: list of scripts, each as returned by scatter_plot()
divs: list of divs, each as returned by scatter_plot()
"""
# ... | 06041d1f340bad932e13c92f992105d076beb1fd | 42,436 |
def make_predictions(*, input_data, save_as: str) -> dict:
"""Predict probability of device failure for the test data
Parameters
----------
input_data : _type_
A csv file containing the test data
save_as : str, optional
name to save the file as, by default None
Returns
----... | 121a700a545cd72361283a39a41f71264f48280e | 42,437 |
def analyze_mds(mds, files):
"""
Return dictionary with names of package`s type
===================ARGUMENTS==================
mds - list of mds
files - list of files that situated in cwd
"""
builtin = check_builtin(mds)
local = parse_local(mds, files)
outside = parse_outside(mds, lo... | aac20962f294f8573d9c63a2ac06ca1487bc96d2 | 42,438 |
def init_serializer(serializer=None, **kwargs):
"""Initialize a serializer from a name, class, or instance"""
serializer = serializer or 'pickle'
# Backwards=compatibility with 0.6; will be removed in 0.8
if serializer == 'safe_pickle' or (serializer == 'pickle' and 'secret_key' in kwargs):
seri... | b38ddd32ebe06cda5ced69ab1855a952ca5c19e9 | 42,439 |
import json
def load_json_dataset(path):
"""Load json file and store fields separately."""
# Read dataset
data = []
with open(path, encoding='utf-8') as f:
dataset = json.load(f)
# Iterate and write question-answer pairs
for article in dataset['data']:
doc_truth = [utils.normal... | b84bd9d4fcb27b10e8d51d2e919db91b60a903d8 | 42,440 |
def create_single_mnist(samples=60000, dataset="training", noise=False):
""" Create a dataset where a single MNIST digit is located in the middle of a long image. """
# Extract images and labels from base MNIST files
images, labels = load_mnist(dataset)
new_images = []
new_labels = []
if sample... | 6f7105abbc1cd83bb2e17bd206f96d8f34e31d31 | 42,441 |
def get_policy_group(description=None,display_name=None,domain=None,id=None,opts=None):
"""
Use this data source to access information about an existing resource.
"""
__args__ = dict()
__args__['description'] = description
__args__['displayName'] = display_name
__args__['domain'] = domain
... | 5461adccb4349e0e12f8b3838dfc874e1110386d | 42,442 |
def get_rot_from_mat(m_mat):
"""
Extracts the rotation from a given MMatrix.
Args:
m_mat
Return:
rot
"""
trans_matrix = oMa.MTransformationMatrix(m_mat)
rot = trans_matrix.rotation()
return rot | b5f604b5187cc00cb59b90700cf1d307fb49f802 | 42,443 |
def _dH_df(bss_data, freq_range=None):
"""
Median frequency derivative value of the PS representation of the BSS
components
Parameters
----------
bss_data : numpy.ndarray
Array containing source signals. It must have dimensions CxTxE, where C
is the number of components, T the n... | 8fdce6c1279c759180fc6d5186ffaac9d78d6352 | 42,444 |
def ask_support_exchanges(intent, session):
""" responds support exchanges.
"""
session_attributes = {}
reprompt_text = None
card_title = intent['name']
session_attributes = {}
should_end_session = False
speech_output = "Latest prices are updated from all major crypto currency exchanges... | 37823b10eae58fd7de9a3723e33a2dc33e0580b8 | 42,445 |
import re
def Language_req(description):
"""Create a function that captures the language requirements from the job description"""
description = description.lower()
matches = re.findall(r"\benglish\sand\sgerman\b|\bgerman\sand\senglish\b\benglisch\sund\sdeutsch\b|\benglish\b|\benglisch\b|\bgerman\b|\bdeuts... | cb6ce14d3cba497f668c701d16c13fdfd78f5dc5 | 42,446 |
def LogN(mu, sigma, tag=None):
"""
A Log-Normal random variate
Parameters
----------
mu : scalar
The location parameter
sigma : scalar
The scale parameter (must be positive and non-zero)
"""
assert sigma>0, 'Sigma must be positive'
return uv(rv=ss.lognorm(sigma, ... | 504668be43fe9c56ec0ceb77ff5624b17cd5a35e | 42,447 |
import logging
def matrix_hits(binary_matrix):
"""Gets the number of cells with value 1 in matrix."""
logging.info("Counting how many contacts are predicted.")
count = 0
(n1, n2) = binary_matrix.shape
for i in range(n1):
for j in range(n2):
if j > i:
count += ... | 0242b2844fb2f761e6ba542031f6b188e7d5286e | 42,448 |
def svn_wc_create_notify_url(*args):
"""svn_wc_create_notify_url(char url, svn_wc_notify_action_t action, apr_pool_t pool) -> svn_wc_notify_t"""
return _wc.svn_wc_create_notify_url(*args) | 1f6789ccee5c76e0c11133eb004c96778cef5a1a | 42,449 |
def cal_wordInCategory_fre(train_file):
"""
:param trian_file: 训练文件 : 分为两列 <label,doc_words>
:return:
"""
# 统计每个类别中,每个词的词频
wordInCategory_dict = {} # key:label value: dict{key:word value:count}
with open(train_file,'r',encoding='utf-8') as f:
for line in f.readlines():
... | c2240708d4c22e3d0fc7f860c5410f2c1e70a2bd | 42,452 |
import time
def get_elapsed_time_ms(start_time_in_seconds: float):
"""
Returns the elapsed time in millis from the given start time.
"""
end_time = time.time()
return int((end_time - start_time_in_seconds) * 1000) | 72853679a2793b0cb09e83287ab3e3510ec8502d | 42,453 |
def to_rgba(color):
"""
Convert from `colRGB`.
`colRGB` is a `wxPython` type which is basically `BGR`. We don't want to work with
`BGR`, so being able to simply convert `RGB` is preferable.
The algorithm is actually the same swapping in either direction, but having a clear name
makes it obviou... | 0cc76f266421a1939abf4665a669114b59c921ad | 42,454 |
def days_in_month_366(month, year=0):
"""Days of the month (366 days calendar).
Parameters
----------
month : int
numerical value of the month (1 to 12).
year : int, optional
(dummy value).
Returns
-------
out : list of int
days of the month.
Notes
----... | 868500d7022c102562688345b46313203b7ba79b | 42,455 |
def connectedvmware_extension_list(
client: MachineExtensionsOperations,
resource_group_name,
vm_name,
expand=None
):
"""
List all the vm extension of a given vm.
"""
return client.list(resource_group_name=resource_group_name,
name=vm_name,
... | f0fce17339fc6eb8d165857a51b59f1afce9a72f | 42,456 |
def plot_energy_from_initial_source(
energy_bins=np.linspace(0, 20e6, 50),
input_filename='initial_source.h5'):
"""makes a plot of the energy distribution of the source"""
f = h5py.File(input_filename,'r')
dset = f['source_bank']
e_values = []
for particle in dset:
e_value... | 92c3509ff24c88b148a9643739537a1594e33ccf | 42,457 |
from datetime import datetime
def _get_date_from_yyyymmdd(original_date):
""" if date is in YYYYMMDD format, return date """
valid_date = ""
try:
valid_date = datetime.datetime.strptime(original_date, '%Y%m%d')
except ValueError:
pass
return valid_date | b83f7122d1cb8327cce171a80bc3029aa9b405e5 | 42,458 |
import requests
import time
import numpy as np
def run_request(bunch, url):
"""Run and time a request with the python requests library
"""
try:
time.sleep(np.random.random_sample()*10)
start = time.time()
response = requests.post(url=url, json=bunch)
assert response.status_... | 8cdf2328fce74b3daeb538e62317a829aa15a496 | 42,460 |
def numeric_plots(df):
"""
Creating a matrix of correlation plots with the numeric features.
Parameters
----------
df: pandas.dataframe
A pandas dataframe
Returns
-------
splom: Altair chart object
The Altair object for the plots
Example
-------
... | 63c7ed0c9f28afa14a6654104738a6428f89d976 | 42,461 |
def _kv_read_checked(conf, key, default=None):
# type: (dict, str, obj) -> obj
"""Read a key as some value with a check against None and length
:param dict conf: configuration dict
:param str key: conf key
:param obj default: default to assign
:rtype: obj or None
:return: value of key
""... | bb04276daa624db8b48f591760351874c848ecc1 | 42,462 |
import base64
def authorization(request, user_name):
""" 메일로 발송된 인증 url로 요청했을 때 작동하는 views """
name = base64.b64decode(user_name.encode('utf-8')) # 인코딩되었던 email name 부분을 디코딩
email = name.decode('utf-8') + '@knu.ac.kr' # 뒤에 knu.ac.kr를 붙여서 완전한 메일 구성
user = User.objects.get(email=email)
user.is... | eddeefa4f58610f3aa7ebedd0edc5387e7902b32 | 42,463 |
import ctypes
def _Cfunction(name, flags, *types):
"""(INTERNAL) New ctypes function binding.
"""
if hasattr(dll, name):
p = ctypes.CFUNCTYPE(*types)
f = p((name, dll), flags)
_Cfunctions[name] = f
return f
raise NameError('no function %r' % (name,)) | 06c28696e4d3125be66438c592b95300028010af | 42,465 |
import copy
def no_alpha(rv, host, companion, limits, new_x=None, normalize=True):
"""Entangled spectrum model with entrinsic flux ratio.
Need to make sure to mulitply by the radius**2 of the respective star.
Parameters
----------
rv: float
rv offset of the companion spectrum.
host: ... | 79b560f2bc181b9feff7bfb0bfca96a4e739c135 | 42,466 |
def intersect_models(dict1, dict2):
"""Combine two dictionaries that are returned from a source method call to
keep only those models that are present in both. It assumes that the models
present in both dictionaries are identical and takes them for the first
input dictionary.
:param dict1: The firs... | 41e98f58823b7894d2f98129bd9bd0c8da1e8a5d | 42,467 |
def post_multipart(site, address, fields, files, cookies):
""" Post fields and files to an http host as multipart/form-data.
@param fields: sequence of (name, value) elements for regular form fields.
@param files: sequence of (name, filename, value) elements for data to be
uploaded as files
@re... | d0388ebdcdacc2b910369306b6f267ae8f398673 | 42,468 |
import math
def hex2meter(level, hex_x, hex_y):
"""hex xy to meter"""
h_len = HEX_LEN / math.pow(3, level)
y = (hex_x + hex_y) * h_len * math.sqrt(3) / 2.0
x = (hex_x - hex_y) * h_len * 3.0 / 2.0
return x, y | ef585f590d3ce30875c5e4480d4ba91dc7935a67 | 42,469 |
def _extract_base_type(typed):
"""Extracts the name of the type from a _GenericAlias
Assumes that the derived types are only of length 1 as the __args__ are [0] recursed... this is not true for
tuples
Args:
typed: the type of the parameter
Returns:
name of type
"""
if hasa... | 29b20155f97990eeab17b48e515121a5758b0d14 | 42,471 |
def _UploadFileToObjectResumable(src_url, src_obj_filestream,
src_obj_size, dst_url, dst_obj_metadata,
preconditions, gsutil_api, logger):
"""Uploads the file using a resumable strategy.
Args:
src_url: Source FileUrl to upload. Must not be a st... | 3ca1a7959bce07b58acbdcf1c96e8005572b6c81 | 42,472 |
def get_openstack_connection_raw(auth_args):
"""obtains an OpenStack connection from a supplied dictionary of auth args"""
print("Connecting to Openstack at {0}".format(auth_args['auth_url']))
conn = connection.Connection(**auth_args)
return conn | 7c60f6bc38e5a138df52ffa82a56a85a75a8ca99 | 42,473 |
def recent_feed_like(bot: InstaBot):
"""
Automatically fetches ank like recent_feed_likes
:param bot:
:return:
"""
# first check if self.media_on feed has length zero.
if len(bot.media_to_like) == 0:
print("Refreshing New Media")
if bot.startup:
first_init(bot)
... | 5bc6d42bad606ac96886abd6675461c56290c2db | 42,474 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.