content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def createMode():
"""Required to initialize the module. RV will call this function to create your mode."""
return AudioForSequence() | aa3095a7b0754da8cb4739c3e3198f8304a21661 | 27,500 |
def pre_process(cpp_line):
"""预处理"""
# 预处理
cpp_line = cpp_line.replace('\t', ' ')
cpp_line = cpp_line.replace('\n', '')
cpp_line = cpp_line.replace(';', '')
return cpp_line | 4c0db8ae834286106472aba425c45a8eeded3183 | 27,501 |
def actions_db(action_id):
"""
replaces the actual db call
"""
if action_id == 'not found':
return None
elif action_id == 'state error':
return {
'id': 'state error',
'name': 'dag_it',
'parameters': None,
'dag_id': 'state error',
... | cd9e8e87ce5535648b4e7a5e58d0333b80e9ae1c | 27,502 |
import os
def _safe_clear_dirflow(path):
"""
Safely check that the path contains ONLY folders of png files,
if any other structure, will simply ERROR out.
Parameters
----------
path: str
string to the path to the folders of data images to be used
"""
print("Clearing {}...".fo... | af92454143fee21c497e1dca2c268c9cb915dbd2 | 27,503 |
def parse(argv):
"""
Parse command line options. Returns the name of the command
and any additional data returned by the command parser.
May raise CommandParsingError if there are problems.
"""
# Find the command
if len(argv) < 1:
full = None
cmd = command_dict[None... | 09867eeb1a17f7609c5f99fc9c5b2d80442a7b44 | 27,504 |
def _get_answer_spans(text, ref_answer):
"""
Based on Rouge-L Score to get the best answer spans.
:param text: list of tokens in text
:param ref_answer: the human's answer, also tokenized
:returns max_spans: list of two numbers, marks the start and end position with the max score
"""
max_s... | aa99c85dec40bcb01457b31b358aac9b50238284 | 27,505 |
from functools import cmp_to_key
def order(list, cmp=None, key=None, reverse=False):
""" Returns a list of indices in the order as when the given list is sorted.
For example: ["c","a","b"] => [1, 2, 0]
This means that in the sorted list, "a" (index 1) comes first and "c" (index 0) last.
"""
... | 7bcc6f44f02be4fb329b211b5caadf057d6d9b9a | 27,506 |
def get_maximum_batch_id(path: Pathy) -> int:
"""
Get the last batch ID. Works with GCS, AWS, and local.
Args:
path: The path folder to look in.
Begin with 'gs://' for GCS. Begin with 's3://' for AWS S3.
Supports wildcards *, **, ?, and [..].
Returns: The maximum ba... | f299189417ef19e59ad155e223f306a51e27d756 | 27,507 |
import requests
def curl_post(method, txParameters=None, RPCaddress=None, ifPrint=False):
"""
call Ethereum RPC functions
"""
payload = {"jsonrpc": "2.0",
"method": method,
"id": 1}
if txParameters:
payload["params"] = [txParameters]
headers = {'Content-ty... | 1b403e91cf542127038b7a79b54a28b69105be39 | 27,508 |
def intRoexpwt2(g1, g2, p, w, t):
""" Integral of the roexpwt filter Oxenham & Shera (2003) equation (3)
Parameters
----------
g1, g2 - Limits of the integral in normalized terms (eg.: g1=0.1,g2=0.35)
p - SLope parameter
t - Factor by which second slope is shallower than first
w - relative ... | fc6e312a5f5134e43d63569b35fc1e6e7af74084 | 27,509 |
def create_connection(query):
"""
クエリを発行するためのデコレータ
:param query: クエリストリング
:return:
"""
def wrapper(*args, **kargs):
config = Config()
connection = pymysql.connect(host= config.nijo_db_host,
user= config.nijo_db_user,
password= config... | 8e6d0733eef3210b2ee074430cf79dd3bdbf8dfc | 27,510 |
def numentries(arrays):
"""
Counts the number of entries in a typical arrays from a ROOT file,
by looking at the length of the first key
"""
return arrays[list(arrays.keys())[0]].shape[0] | e3c9f2e055f068f12039741ff9bb1091716263d5 | 27,511 |
from typing import Callable
import functools
def build_jax_solve_eval_fwd(fenics_templates: FenicsVariable) -> Callable:
"""Return `f(*args) = build_jax_solve_eval(*args)(ofunc(*args))`. This is forward mode AD.
Given the FEniCS-side function ofunc(*args), return the function
`f(*args) = build_jax_solve_e... | 4e9d7bff6e8580dd9970f25026ba813e6b4cc37f | 27,512 |
import torch
def gen_gcam_target(imgs, model, target_layer='layer4', target_index=None, classes=get_imagenet_classes(), device='cuda', prep=True):
"""
Visualize model responses given multiple images
"""
# Get model and forward pass
gcam, probs, ids, images = gen_model_forward(imgs, model, d... | f685b17b030643fbd29eed0b69be140422b3e730 | 27,513 |
def get_insert_query(table_name):
"""Build a SQL query to insert a RDF triple into a PostgreSQL dataset"""
return f"INSERT INTO {table_name} (subject,predicate,object) VALUES (%s,%s,%s) ON CONFLICT (subject,predicate,object) DO NOTHING" | 423ccbf1d69e85316abdb81207d6e0f04729c2b8 | 27,514 |
import torch
def q_mult(q1, q2):
"""Quaternion multiplication."""
w = q1[0] * q2[0] - q1[1] * q2[1] - q1[2] * q2[2] - q1[3] * q2[3]
x = q1[1] * q2[0] + q1[0] * q2[1] + q1[2] * q2[3] - q1[3] * q2[2]
y = q1[0] * q2[2] - q1[1] * q2[3] + q1[2] * q2[0] + q1[3] * q2[1]
z = q1[0] * q2[3] + q1[1] * q2[2] ... | cafafa392d9e41e7680c703415ed6df87207f0d0 | 27,515 |
def is_object_group(group):
"""True if the group's object name is not one of the static names"""
return not group.name.value in (IMAGE, EXPERIMENT, OBJECT_RELATIONSHIPS) | d111781f39feef74698b625186f3937a85fa8713 | 27,516 |
import time
def plugin_poll(handle):
""" Extracts data from the sensor and returns it in a JSON document as a Python dict.
Available for poll mode only.
Args:
handle: handle returned by the plugin initialisation call
Returns:
returns a sensor reading in a JSON document, as a Python d... | 05f3974c919fdd9c5ee4b853b37bf07bbd45738c | 27,517 |
def autodetect_camera() -> str:
"""Auto-detect camera using gphoto2.
Returns:
string returned from gphoto2.
"""
_logger.debug('Auto detecting camera.')
result = execute('gphoto2 --auto-detect')
if result.returncode:
raise ValueError(result.stderr)
return result.stdout.dec... | 8320782c40cb3cbec37925479d52d781904a1a0c | 27,518 |
def info(token, customerid=None):
""" Returns the info for your account
:type token: string
:param token: Your NodePing API token
:type customerid: string
:param customerid: Optional subaccount ID for your account
:return: Return contents from the NodePing query
:rtype: dict
"""
ur... | d106bf166e846bc2b3627af4e43e74074a519cd1 | 27,519 |
import math
def overlay(*fields: SampledField or Tensor) -> Tensor:
"""
Specify that multiple fields should be drawn on top of one another in the same figure.
The fields will be plotted in the order they are given, i.e. the last field on top.
```python
vis.plot(vis.overlay(heatmap, points, veloci... | 629eb69c15d814384b70bac2ac78cebdd93ef20d | 27,520 |
def load_identifier(value):
"""load identifier"""
if value == "y":
return True
return False | 0292439c8eeb3788a6b517bb7b340df2c0435b4d | 27,521 |
def IKinSpaceConstrained(screw_list, ee_home, ee_goal, theta_list,
position_tolerance, rotation_tolerance, joint_mins, joint_maxs, max_iterations):
"""
Calculates IK to a certain goal within joint rotation constraints
Args:
screw_list: screw list
ee_home: home end effector position
... | 7c59a8eaa7cff24f6c5359b100e006bbc58e8c00 | 27,522 |
def add_hidden_range(*args):
"""
add_hidden_range(ea1, ea2, description, header, footer, color) -> bool
Mark a range of addresses as hidden. The range will be created in the
invisible state with the default color
@param ea1: linear address of start of the address range (C++: ea_t)
@param ea2: linear ad... | 8f844c14b348bdcf58abe799cb8ed0c91d00aeef | 27,523 |
import json
def _fetch_certs(request, certs_url):
"""Fetches certificates.
Google-style cerificate endpoints return JSON in the format of
``{'key id': 'x509 certificate'}``.
Args:
request (google.auth.transport.Request): The object used to make
HTTP requests.
certs_url (s... | 3141c78d604bbed10236b5ed11cfc2c06a756ef2 | 27,524 |
def get_mock_personalization_dict():
"""Get a dict of personalization mock."""
mock_pers = dict()
mock_pers['to_list'] = [To("test1@example.com",
"Example User"),
To("test2@example.com",
"Example User")]
mo... | 4be81a67715bc967c8d624d784008ed3cb6775f8 | 27,525 |
def load_python_bindings(python_input):
"""
Custom key bindings.
"""
bindings = KeyBindings()
sidebar_visible = Condition(lambda: python_input.show_sidebar)
handle = bindings.add
@handle("c-l")
def _(event):
"""
Clear whole screen and render again -- also when the sideb... | 2725352272d001da7dc74e7c29819b8ddae5521e | 27,526 |
def batch_retrieve_pipeline_s3(pipeline_upload):
""" Data is returned in the form (chunk_object, file_data). """
study = Study.objects.get(id = pipeline_upload.study_id)
return pipeline_upload, s3_retrieve(pipeline_upload.s3_path,
study.object_id,
... | 9f48186a116fab7826dd083ab80e4f5383e813ba | 27,527 |
import re
import os
def indent(instr, nspaces=4, ntabs=0, flatten=False):
"""Indent a string a given number of spaces or tabstops.
indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
Parameters
----------
instr : basestring
The string to be indented.
nspaces : int (default:... | 3872630a0fcd697ebd0c7a59f7a7cb05b004b465 | 27,528 |
def gat(gw,
feature,
hidden_size,
activation,
name,
num_heads=8,
feat_drop=0.6,
attn_drop=0.6,
is_test=False):
"""Implementation of graph attention networks (GAT)
This is an implementation of the paper GRAPH ATTENTION NETWORKS
(https://arxiv.o... | c653dc26dc2bb1dccf37481560d93ba7eee63f7c | 27,529 |
def _number(string):
"""
Extracts an int from a string.
Returns a 0 if None or an empty string was passed.
"""
if not string:
return 0
else:
try:
return int(string)
except ValueError:
return float(string) | d14a7a04f33f36efd995b74bc794fce2c5f4be97 | 27,530 |
def get_email(sciper):
"""
Return email of user
"""
attribute = 'mail'
response = LDAP_search(
pattern_search='(uniqueIdentifier={})'.format(sciper),
attribute=attribute
)
try:
email = get_attribute(response, attribute)
except Exception:
raise EpflLdapExce... | 5f9ce9f69e4e7c211f404a50b4f420eb6e978d64 | 27,531 |
import math
def convert_size(size):
""" Size should be in bytes.
Return a tuple (float_or_int_val, str_unit) """
if size == 0:
return (0, "B")
KILOBYTE = 1024
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size, KILOBYTE)))
p = math.po... | b2bc18df8ae268e1b03bcc7addadca8e07309f7c | 27,532 |
def _backward(gamma, mask):
"""Backward recurrence of the linear chain crf."""
gamma = K.cast(gamma, 'int32') # (B, T, N)
def _backward_step(gamma_t, states):
# print('len(states)=', len(states))
# print(type(states))
# y_tm1 = K.squeeze(states[0], 0)
y_tm1 = states[0]
... | ab71548e87023e09ccd28aac81b95a6671384205 | 27,533 |
def t3err(viserr, N=7):
""" provided visibilities, this put these into triple product"""
amparray = populate_symmamparray(viserr, N=N)
t3viserr = np.zeros(int(comb(N,3)))
nn=0
for kk in range(N-2):
for ii in range(N-kk-2):
for jj in range(N-kk-ii-2):
t3viserr[nn+j... | f5d774bb361c389f470de504adc2a467c71f0ec7 | 27,534 |
import torch
from typing import Tuple
def compute_average_ml_vae(z0_mean: torch.Tensor, z0_var: torch.Tensor, z1_mean: torch.Tensor, z1_var: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Compute the product of the encoder distributions.
- Ada-ML-VAE Averaging function
(✓) Visual inspection ... | 9c7b1c559dda2b158ad400cf8634f0a8eb36fdee | 27,535 |
def safe_sign_and_autofill_transaction(
transaction: Transaction, wallet: Wallet, client: Client
) -> Transaction:
"""
Signs a transaction locally, without trusting external rippled nodes. Autofills
relevant fields.
Args:
transaction: the transaction to be signed.
wallet: the wallet... | ce2b898529e15c65c8c84906c12093b9865e4768 | 27,536 |
def getMetricValue(glyph, attr):
"""
Get the metric value for an attribute.
"""
attr = getAngledAttrIfNecessary(glyph.font, attr)
return getattr(glyph, attr) | 9637e8c1ee3e295b1d1da67d9a77108b761acddc | 27,537 |
from typing import Optional
from typing import Union
def temporal_train_test_split(
y: ACCEPTED_Y_TYPES,
X: Optional[pd.DataFrame] = None,
test_size: Optional[Union[int, float]] = None,
train_size: Optional[Union[int, float]] = None,
fh: Optional[FORECASTING_HORIZON_TYPES] = None,
) -> SPLIT_TYPE:... | 4bb59ead5a035114f067ab37c40289d0d660df2d | 27,538 |
import re
def split_range_str(range_str):
"""
Split the range string to bytes, start and end.
:param range_str: Range request string
:return: tuple of (bytes, start, end) or None
"""
re_matcher = re.fullmatch(r'([a-z]+)=(\d+)?-(\d+)?', range_str)
if not re_matcher or len(re_matcher.groups(... | a6817017d708abf774277bf8d9360b63af78860d | 27,539 |
from typing import Union
def get_valid_extent(array: Union[np.ndarray, np.ma.masked_array]) -> tuple:
"""
Return (rowmin, rowmax, colmin, colmax), the first/last row/column of array with valid pixels
"""
if not array.dtype == 'bool':
valid_mask = ~get_mask(array)
else:
valid_mask =... | 9b906fcd88c901f84ff822d8ba667936d8b623ed | 27,540 |
import os
def get_downloaded_dataset_ids(preprocess=Preprocess.RAW):
"""Get all dataset ids in the corresponding preprocessed data folder"""
dataset_filenames = os.listdir(get_folder(preprocess))
dataset_filenames.sort()
return [int(filename.rstrip(OLD_PICKLE_EXT)) for filename in dataset_filenames] | d506ed1cd12c77f9cad21ff49814a39bd61d3089 | 27,541 |
def epsmu2nz(eps, mu):#{{{
""" Accepts permittivity and permeability, returns effective index of refraction and impedance"""
N = np.sqrt(eps*mu)
N *= np.sign(N.imag)
Z = np.sqrt(mu / eps)
return N, Z | 7575d4596706f574f2a88627982edfb704d81d94 | 27,542 |
from typing import List
import re
def tokenize_numbers(text_array: List[str]) -> List[str]:
"""
Splits large comma-separated numbers and floating point values.
This is done by replacing commas with ' @,@ ' and dots with ' @.@ '.
Args:
text_array: An already tokenized text as list
Returns:
... | f87b94850baeefd242ad2bcc89858fc05662a638 | 27,543 |
def main(
datapath,
kwdpath,
in_annot,
note_types,
batch,
):
"""
Select notes for an annotation batch, convert them to CoNLL format and save them in folders per annotator. The overview of the batch is saved as a pickled DataFrame.
Parameters
----------
datapath: Path
pat... | cdbb4a6dbd91adccd4fdfdb2bb7c653d109801f2 | 27,544 |
def mask_to_bbox(mask):
""" Convert mask to bounding box (x, y, w, h).
Args:
mask (np.ndarray): maks with with 0 and 255.
Returns:
List: [x, y, w, h]
"""
mask = mask.astype(np.uint8)
contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
x = 0
y =... | d8fc111bdb3a2c52866ad35b8e930e5ac8ebf0ba | 27,545 |
def find_divisor(n, limit=1000000):
"""
Use sieve to find first prime divisor of given number
:param n: number
:param limit: sieve limit
:return: prime divisor if exists in sieve limit
"""
primes = get_primes(limit)
for prime in primes:
if n % prime == 0:
return prime... | c990f25e055d8f8b1053cf94d6f9bb2d4fcff0bb | 27,546 |
def sort_all(batch, lens):
""" Sort all fields by descending order of lens, and return the original indices. """
if batch == [[]]:
return [[]], []
unsorted_all = [lens] + [range(len(lens))] + list(batch)
sorted_all = [list(t) for t in zip(*sorted(zip(*unsorted_all), reverse=True))]
return so... | 175f97a88371992472f1e65a9403910f404be914 | 27,547 |
def bh(p, fdr):
""" From vector of p-values and desired false positive rate,
returns significant p-values with Benjamini-Hochberg correction
"""
p_orders = np.argsort(p)
discoveries = []
m = float(len(p_orders))
for k, s in enumerate(p_orders):
if p[s] <= (k+1) / m * fdr:
... | ace0924fa72b39085d4504c3bb015f81e1c78546 | 27,548 |
import sys
import os
import asyncio
def runner(fun, *args):
"""
Generic asyncio.run() equivalent for Python >= 3.5
"""
if sys.version_info >= (3, 7):
if os.name == "nt" and sys.version_info < (3, 8):
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
re... | 1893c46c40e1d42fc4927b0fb3d240c209405318 | 27,549 |
from datetime import datetime
def guess_if_last(lmsg):
"""Guesses if message is the last one in a group"""
msg_day = lmsg['datetime'].split('T')[0]
msg_day = datetime.datetime.strptime(msg_day, '%Y-%m-%d')
check_day = datetime.datetime.today() - datetime.timedelta(days=1)
if msg_day >= check_day:
... | 2d62caeb21daff4c5181db4a0b5cd833916fb945 | 27,550 |
import time
def refine_by_split(featIds, n, m, topo_rules, grid_layer, progress_bar = None, labelIter = None ) :
"""
Description
----------
Split input_features in grid_layer and check their topology
Parameters
----------
featIds : ids of features from grid_layer to be refined
n : num... | 6a604bbea471d8401cbabe65a04e13a51c389413 | 27,551 |
def read_custom_enzyme(infile):
"""
Create a list of custom RNase cleaving sites from an input file
"""
outlist = []
with open(infile.rstrip(), 'r') as handle:
for line in handle:
if '*' in line and line[0] != '#':
outlist.append(line.rstrip())
return outlist | 144c6de30a04faa2c9381bfd36bc79fef1b78443 | 27,552 |
def all_features(movie_id):
"""Returns the concatenation of visual and audio features for a movie
The numbers of frames are not egal for the visual and the audio feature.
The overnumerous frame are deleted.
"""
T_v = all_visual_features(movie_id)
T_a = all_audio_features(movie_id)
min_ = mi... | df46d70d2023beb0d707d62ef9cf4f2af6f9c102 | 27,553 |
def resnet34(pretrained=False, shift='TSM',num_segments = 8, flow_estimation=0,**kwargs):
"""Constructs a ResNet-34 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if (shift =='TSM'):
model = ResNet(BasicBlock, BasicBlock, [3, 4, 6, 3],num_segments=n... | db8468b1eb0c0d5ed022ee70623c67390dedef15 | 27,554 |
def normalize_data_v3(data, cal_zero_points=np.arange(-4, -2, 1),
cal_one_points=np.arange(-2, 0, 1), **kw):
"""
Normalizes data according to calibration points
Inputs:
data (numpy array) : 1D dataset that has to be normalized
cal_zero_points (range) : range specifying ... | 3c9017abb58745964cd936db21d79a6df4896b4e | 27,555 |
def read(path, encoding="utf-8"):
"""Read string from text file.
"""
with open(path, "rb") as f:
return f.read().decode(encoding) | 674a20d7dca76f2c18b140cde0e93138b69d94ea | 27,556 |
def min_equals_max(min, max):
"""
Return True if minimium value equals maximum value
Return False if not, or if maximum or minimum value is not defined
"""
return min is not None and max is not None and min == max | 1078e9ed6905ab8b31b7725cc678b2021fc3bc62 | 27,557 |
def loadDataSet(fileName):
""" 加载数据
解析以tab键分隔的文件中的浮点数
Returns:
dataMat : feature 对应的数据集
labelMat : feature 对应的分类标签,即类别标签
"""
# 获取样本特征的总数,不算最后的目标变量
numFeat = len(open(fileName).readline().split('\t')) - 1
dataMat = []
labelMat = []
fr = open(fileName)
for line... | 3c9fd81d1aeb2e3723081e3a1b11d07ec08e2118 | 27,558 |
def infer_app_url(headers: dict, register_path: str) -> str:
"""
ref: github.com/aws/chalice#485
:return: The Chalice Application URL
"""
host: str = headers["host"]
scheme: str = headers.get("x-forwarded-proto", "http")
app_url: str = f"{scheme}://{host}{register_path}"
return app_url | f3c0d1a19c8a78a0fd2a8663e2cb86427ff8f61b | 27,559 |
def get_index_where_most_spikes_in_unit_list(unit_list):
"""Returns the position in the list of units that has the most spikes.
:param unit_list: list of unit dictionaries
:return: index
:rtype: int
"""
return np.argmax(Recordings.count_spikes_in_unit_list(unit_list)) | 41f4b1f4ae1fc1b813769bf9f4606848cb700c11 | 27,560 |
def ocr_boxes(
img,
boxes,
halve=False,
resize=False,
blur=True,
sharpen=False,
erode=False,
dilate=False,
lang='eng',
config=None):
"""
Detect strings in multiple related boxes and concatenate the results.
Parameters
----------
halve : bool, optional
... | c273118beb263e6ad837cbb343ad0829bd367d30 | 27,561 |
def multiply_inv_gaussians(mus, lambdas):
"""Multiplies a series of Gaussians that is given as a list of mean vectors and a list of precision matrices.
mus: list of mean with shape [n, d]
lambdas: list of precision matrices with shape [n, d, d]
Returns the mean vector, covariance matrix, and precision m... | d8bdce66668ebf5e94f86310633c699ae7c98e16 | 27,562 |
import random
def mutationShuffle(individual, indpb):
"""
Inputs : Individual route
Probability of mutation betwen (0,1)
Outputs : Mutated individual according to the probability
"""
size = len(individual)
for i in range(size):
if random.random() < indpb:
swap_... | dea67e03b2905f1169e1c37b3456364fb55c7174 | 27,563 |
def best_shoot_angle(agent_coord: tuple, opponents: list):
""" Tries to shoot, if it fail, kicks to goal randomly """
# Get best shoot angle:
best_angles = []
player_coord = np.array(agent_coord)
goal_limits = [np.array([0.9, -0.2]), np.array([0.9, 0]),
np.array([0.9, 0.2])]
f... | 98c7cb90fc28b4063ce6c14a84fe8989907268d6 | 27,564 |
import json
import os
import subprocess
def adjust(*args, stdin=None):
"""run 'adjust' with the current directory set to the dir where this module is found.
Return a tuple (exitcode, parsed_stdout), the second item will be None if stdout was empty. An exception is raised if the process cannot be run or parsin... | 262d757520ff97a666df62b0700391acc03a42ba | 27,565 |
import os
def read_STAR_Logfinalout(Log_final_out):
"""
Log_final_out -- Folder or Log.final.out produced by STAR
"""
if os.path.isdir(Log_final_out):
Log_final_out = Log_final_out.rstrip('/')
dirfiles = os.listdir(Log_final_out)
if 'Log.final.out' in dirfiles:
... | 9599a71624f5b65092cf67fd28c9dd3d7f44e259 | 27,566 |
from typing import Optional
def _parse_line(lineno: int, line: str) -> Optional[UciLine]: # pylint: disable=unsubscriptable-object
"""Parse a line, raising UciParseError if it is not valid."""
match = _LINE_REGEX.match(line)
if not match:
raise UciParseError("Error on line %d: unrecognized line t... | eab49cf766b15d769d7b194176276741d197d359 | 27,567 |
from django.contrib.auth import login
from django.contrib.auth import authenticate
from django.contrib.auth import login
def login(request, template_name="lfs/checkout/login.html"):
"""Displays a form to login or register/login the user within the check out
process.
The form's post request goes to lfs.cu... | 33d23ba50cff73580ca45519ad26d218194bd341 | 27,568 |
import inspect
def _is_valid_concrete_plugin_class(attr):
"""
:type attr: Any
:rtype: bool
"""
return (
inspect.isclass(attr)
and
issubclass(attr, BasePlugin)
and
# Heuristic to determine abstract classes
not isinstance(attr.secret_type, abstractpro... | 383e0bff4edac6623b9a2d2da45c3c47c982d72e | 27,569 |
import os
def connect(production=False):
"""Connect to MTurk"""
# Load API keys
reseval.load.api_keys()
# Connect to MTurk
return boto3.Session(
aws_access_key_id=os.environ['AWSAccessKeyId'],
aws_secret_access_key=os.environ['AWSSecretKey']
).client(
'mturk',
... | 82084de6160ce957360e3ed4e1d77de82094e114 | 27,570 |
def arrQuartiles(arr, arrMap=None, method=1, key=None, median=None):
"""
Find quartiles. Also supports dicts.
This function know about this quartile-methods:
1. Method by Moore and McCabe's, also used in TI-85 calculator.
2. Classical method, also known as "Tukey's hinges". In common cases it use v... | 52de942dc59f293a35696579bd35c877e15c091d | 27,571 |
def check_response_status_code(url, response, print_format):
"""
check and print response status of an input url.
Args:
url (str) : url text.
response (list) : request response from the url request.
print_format (str) : format to print the logs according to.
"""
... | c16f453174ef48b2e6accfba4ec075bb8f2cad0d | 27,572 |
def make_state_manager(config):
"""
Parameters
----------
config : dict
Parameters for this StateManager.
Returns
-------
state_manager : StateManager
The StateManager to be used by the Controller.
"""
manager_dict = {
"hierarchical": HierarchicalStateManager... | f662b97c052ccc9188b9f7236b79228cfba983c2 | 27,573 |
from datetime import datetime
def get_books_information(url: str, headers: dict = None) -> list:
"""
Create list that contains dicts of cleaned data from google book API.
Parameters
----------
url: str
link to resources (default: link to volumes with q=war, target of recrutment task)... | 1643c2368ed452f9f12ea81f25c468c0240404b4 | 27,574 |
from typing import Dict
from typing import Type
import pkg_resources
def get_agents() -> Dict[str, Type[Agent]]:
"""Returns dict of agents.
Returns:
Dictionary mapping agent entrypoints name to Agent instances.
"""
agents = {}
for entry_point in pkg_resources.iter_entry_points("agents"):
... | 5b6959278f0dd4b53d81c38d1ef919b0756a5533 | 27,575 |
from typing import MutableMapping
from typing import Any
from typing import Set
import yaml
def rewrite_schemadef(document: MutableMapping[str, Any]) -> Set[str]:
"""Dump the schemadefs to their own file."""
for entry in document["types"]:
if "$import" in entry:
rewrite_import(entry)
... | d6beec5cb41cef16f23cbcad154998b6d79f1cdb | 27,576 |
def decor(decoration, reverse=False):
"""
Return given decoration part.
:param decoration: decoration's name
:type decoration:str
:param reverse: true if second tail of decoration wanted
:type reverse:bool
:return decor's tail
"""
if isinstance(decoration, str) is False:
ra... | c8fb59478f72ab76298361fa2dfa4a8720c5a46b | 27,577 |
def group_data(data, degree=3, hash=hash):
"""
numpy.array -> numpy.array
Groups all columns of data into all combinations of triples
"""
new_data = []
m,n = data.shape
for indicies in combinations(range(n), degree):
if 5 in indicies and 7 in indicies:
print "feature Xd"
elif 2 ... | 886afd2f12dc0b4bf0da5648de8bcbf294b74c74 | 27,578 |
def get_dataset(dataset_name: str, *args, **kwargs):
"""Get the Dataset instancing lambda from the dictionary and return its evaluation.
This way, a Dataset object is only instanced when this function is evaluated.
Arguments:
dataset_name:
The name of the Dataset to be instanced. Must b... | f3ab44f6ebb9d867bdf9b08d31d70f25832fbb7d | 27,579 |
def _numeric_handler_factory(charset, transition, assertion, illegal_before_underscore, parse_func,
illegal_at_end=(None,), ion_type=None, append_first_if_not=None, first_char=None):
"""Generates a handler co-routine which tokenizes a numeric component (a token or sub-token).
Args:... | 5033f406918b6e9aeecba9d1470f3b6bc10761fa | 27,580 |
def unsafe_content(s):
"""Take the string returned by safe_content() and recreate the
original string."""
# don't have to "unescape" XML entities (parser does it for us)
# unwrap python strings from unicode wrapper
if s[:2]==unichr(187)*2 and s[-2:]==unichr(171)*2:
s = s[2:-2].encode('us-as... | ec92c977838412ff6fb67297a300cbc77a450661 | 27,581 |
def _AcosGrad(op, grad):
"""Returns grad * -1/sqrt(1-x^2)."""
x = op.inputs[0]
with ops.control_dependencies([grad.op]):
x = math_ops.conj(x)
x2 = math_ops.square(x)
one = constant_op.constant(1, dtype=grad.dtype)
den = math_ops.sqrt(math_ops.subtract(one, x2))
inv = math_ops.reciprocal(den)
... | 7a6d67e09f6b2997476c41fe37c235349e5c5c79 | 27,582 |
def converter(n, decimals=0, base=pi):
"""takes n in base 10 and returns it in any base (default is pi
with optional x decimals"""
# your code here
result = [] # setting list to capture converted digit
# check for a proper base
if base <= 0:
base = pi
# if n is zero then set the sta... | e14b2667ad73ddee13df2dd526c5cdcdfde8a2f5 | 27,583 |
import json
import requests
def mediaAddcastInfo():
"""
:return:
"""
reqUrl = req_url('media', "/filmCast/saveFilmCastList")
if reqUrl:
url = reqUrl
else:
return "服务host匹配失败"
headers = {
'Content-Type': 'application/json',
'X-Region-Id': '2',
}
body... | 0826c22acea653234817f9838cd82cbc7045b07b | 27,584 |
def process_register_fns(): # noqa: WPS210
"""Registration in FNS process."""
form = RegisterFnsForm()
if form.validate_on_submit():
email = current_user.email
name = current_user.username
phone = form.telephone.data
registration_fns(email, name, phone)
flash('Ждите ... | f5e7b3b88bbcd610d675aef020538fb87d1a8887 | 27,585 |
import socket
def validate_args(args):
""" Checks if the arguments are valid or not. """
# Is the number of sockets positive ?
if not args.number > 0:
print("[ERROR] Number of sockets should be positive. Received %d" % args.number)
exit(1)
# Is a valid IP address or valid name ?
tr... | 37a77f59ae78e3692e08742fab07f35cf6801e54 | 27,586 |
import re
def register(request):
"""注册"""
if request.method == 'GET':
# 显示注册页面
return render(request, 'register.html')
else:
# 进行注册处理
# 1.接收参数
username = request.POST.get('user_name') # None
password = request.POST.get('pwd')
email = request.POST.ge... | 54f8a1eb8a0378e18634f0708cc5c4de44b88b20 | 27,587 |
def triangulation_to_vedo_mesh(tri, **kwargs):
"""
Transform my triangulation class to Trimesh class
:param kwargs:
"""
coords = tri.coordinates
trias = tri.triangulation
m = vedo.Mesh([coords, trias], **kwargs)
return m | 73c14809269dab93ef3acef973e8727528e7d1bf | 27,588 |
def build_dropout(cfg, default_args=None):
"""Builder for drop out layers."""
return build_from_cfg(cfg, DROPOUT_LAYERS, default_args) | e04797e311992da39ea2b3b07c90508e3afa44ce | 27,589 |
def conv2d_transpose(inputs,
num_output_channels,
kernel_size,
scope,
stride=[1, 1],
padding='SAME',
use_xavier=True,
stddev=1e-3,
weight_decay=0.0,
... | df0bd44b9ef10ca9af3f1106f314b82cf84358b8 | 27,590 |
def open_py_file(f_name):
"""
:param f_name: name of the .py file (with extension)
:return: a new file with as many (1) as needed to not already exist
"""
try:
f = open(f_name, "x")
return f, f_name
except IOError:
return open_py_file(f_name[:-3] + "(1)" + f_name[-3:]) | bcc40f7757e0e4573b69b843c5050ad27546be53 | 27,591 |
def cast_rays(rays_o, rays_d, z_vals, r):
"""shoot viewing rays from camera parameters.
Args:
rays_o: tensor of shape `[...,3]` origins of the rays.
rays_d: tensor of shape `[...,3]` directions of the rays.
z_vals: tensor of shape [...,N] segments of the rays
r: radius of ray c... | a647feda10263755e519e6965517ca311fcf87df | 27,592 |
from typing import Any
def ifnone(x: Any, y: Any):
"""
returns x if x is none else returns y
"""
val = x if x is not None else y
return val | f2c7cf335ff919d610a23fac40d6af61e6a1e595 | 27,593 |
def get_session(region, default_bucket):
"""Gets the sagemaker session based on the region.
Args:
region: the aws region to start the session
default_bucket: the bucket to use for storing the artifacts
Returns:
`sagemaker.session.Session instance
"""
boto_session = boto3.Ses... | e4944e2b21f9bc666ad29a8ad1d09ac8c44df390 | 27,594 |
def xi_einasto_at_r(r, M, conc, alpha, om, delta=200, rhos=-1.):
"""Einasto halo profile.
Args:
r (float or array like): 3d distances from halo center in Mpc/h comoving
M (float): Mass in Msun/h; not used if rhos is specified
conc (float): Concentration
alpha (float): Profile ex... | 68b86aabc08bd960e1fa25691a1f421414dc25fa | 27,595 |
import re
def _rst_links(contents: str) -> str:
"""Convert reStructuredText hyperlinks"""
links = {}
def register_link(m: re.Match[str]) -> str:
refid = re.sub(r"\s", "", m.group("id").lower())
links[refid] = m.group("url")
return ""
def replace_link(m: re.Match[str]) -> str:... | c7c937cdc04f9d5c3814538978062962e6407d65 | 27,596 |
def fibonacci(n: int) -> int:
"""
Calculate the nth Fibonacci number using naive recursive implementation.
:param n: the index into the sequence
:return: The nth Fibonacci number is returned.
"""
if n == 1 or n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2) | 08de1ff55f7cada6a940b4fb0ffe6ba44972b42d | 27,597 |
def validator_msg(msg):
"""Validator decorator wraps return value in a message container.
Usage:
@validator_msg('assert len(x) <= 2')
def validate_size(x):
return len(x) <= 2
Now, if `validate_size` returns a falsy value `ret`, for instance if
provided with range(4), we wi... | 1913408a9e894fbe3ca70a4b6529322958e75678 | 27,598 |
def iter_fgsm_t(x_input_t, preds_t, target_labels_t,
steps, total_eps, step_eps,
clip_min=0.0, clip_max=1.0, ord=np.inf, targeted=False):
"""
I-FGSM attack.
"""
eta_t = fgm(x_input_t, preds_t, y=target_labels_t, eps=step_eps, ord=ord,
clip_min=clip_min, clip_max=clip_max, tar... | 381f50b66ce3105c13f31afae5127e8574346a36 | 27,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.