content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def load_summary_data():
""" Function to load data
param DATA_URL: data_url
return: pandas dataframe
"""
DATA_URL = 'data/summary_df.csv'
data = pd.read_csv(DATA_URL)
return data | b5f09e845e1379fd00a03fd11b0174e3114eb7d3 | 11,313 |
import itertools
def _enumerate_trees_w_leaves(n_leaves):
"""Construct all rooted trees with n leaves."""
def enumtree(*args):
n_args = len(args)
# trivial cases:
if n_args == 0:
return []
if n_args == 1:
return args
# general case of 2 or more args:
# build index array
idx... | 574a2d3ec63d3aeeb06292ec361b83aebba0ff84 | 11,314 |
def gen_tfidf(tokens, idf_dict):
"""
Given a segmented string and idf dict, return a dict of tfidf.
"""
# tokens = text.split()
total = len(tokens)
tfidf_dict = {}
for w in tokens:
tfidf_dict[w] = tfidf_dict.get(w, 0.0) + 1.0
for k in tfidf_dict:
tfidf_dict[k] *= idf_dict... | 9217867b3661a8070cc1b2d577918c95d1ff7755 | 11,316 |
def timestamp_to_seconds(timestamp):
"""Convert timestamp to python (POSIX) time in seconds.
:param timestamp: The timestamp.
:return: The python time in float seconds.
"""
return (timestamp / 2**30) + EPOCH | 3d5ca5f5ec93b54e1d1a6c53cefba1d49f8ebac2 | 11,317 |
def fit_lowmass_mstar_mpeak_relation(mpeak_orig, mstar_orig,
mpeak_mstar_fit_low_mpeak=default_mpeak_mstar_fit_low_mpeak,
mpeak_mstar_fit_high_mpeak=default_mpeak_mstar_fit_high_mpeak):
"""
"""
mid = 0.5*(mpeak_mstar_fit_low_mpeak + mpeak_mstar_fit_high_mpeak)
mask = (mpeak_orig ... | 620275ad18173bb00d38f3d468be132d150fc1fa | 11,319 |
def load_ref_system():
""" Returns benzaldehyde as found in the IQMol fragment library.
All credit to https://github.com/nutjunkie/IQmol
"""
return psr.make_system("""
C 0.3179 1.0449 -0.0067
C 1.6965 0.8596 -0.0102
C 2.2283 -0.4253 -0... | 518ca10a84befa07fefa3c2f646e40095318d63c | 11,320 |
def get_department_level_grade_data_completed(request_ctx, account_id, **request_kwargs):
"""
Returns the distribution of grades for students in courses in the
department. Each data point is one student's current grade in one course;
if a student is in multiple courses, he contributes one value per cou... | 8dd40c7b7c7a734aa66d4f808224424c0c0df81d | 11,321 |
def allocate_samples_to_bins(n_samples, ideal_bin_count=100):
"""goal is as best as possible pick a number of bins
and per bin samples to a achieve a given number
of samples.
Parameters
----------
Returns
----------
number of bins, list of samples per bin
"""
if n_samples <= i... | 66d5fe32a89478b543818d63c65f2745fe242b33 | 11,322 |
from typing import Any
def create_algo(name: str, discrete: bool, **params: Any) -> AlgoBase:
"""Returns algorithm object from its name.
Args:
name (str): algorithm name in snake_case.
discrete (bool): flag to use discrete action-space algorithm.
params (any): arguments for algorithm.... | 4fab0f5581eb6036efba6074ab6e3b232bcf5679 | 11,323 |
def tf_inv(T):
""" Invert 4x4 homogeneous transform """
assert T.shape == (4, 4)
return np.linalg.inv(T) | 5bf7d54456198c25029956a7aebe118d7ee4fa87 | 11,324 |
def send_reset_password_email(token, to, username):
"""
send email to user for reset password
:param token: token
:param to: email address
:param username: user.username
:return:
"""
url_to = current_app.config["WEB_BASE_URL"] + "/auth/reset-password?token=" + token
response = _send... | dddcb66425de79a1a736bbbcc5cbc3f5855e7db9 | 11,325 |
def part1(data):
"""Solve part 1"""
countIncreased = 0
prevItem = None
for row in data:
if prevItem == None:
prevItem = row
continue
if prevItem < row:
countIncreased += 1;
prevItem = row
return countIncreased | e01b5edc9d9ac63a31189160d09b5e6e0f11e522 | 11,326 |
def yzrotation(theta = np.pi*3/20.0):
"""
Returns a simple planar rotation matrix that rotates
vectors around the x-axis.
args:
theta: The angle by which we will perform the rotation.
"""
r = np.eye(3)
r[1,1] = np.cos(theta)
r[1,2] = -np.sin(theta)
r[2,1] = np.sin(theta)
... | 59a2a251f8e8aa77548f749f49871536de29b0bb | 11,327 |
def is_compiled_release(data):
"""
Returns whether the data is a compiled release (embedded or linked).
"""
return 'tag' in data and isinstance(data['tag'], list) and 'compiled' in data['tag'] | ea8c8ae4f1ccdedbcc145bd57bde3b6040e5cab5 | 11,328 |
import numpy
def resize_frame(
frame: numpy.ndarray, width: int, height: int, mode: str = "RGB"
) -> numpy.ndarray:
"""
Use PIL to resize an RGB frame to an specified height and width.
Args:
frame: Target numpy array representing the image that will be resized.
width: Width of the res... | 941eb73961843e46b4e67d48439a09c0223c2af0 | 11,329 |
def get_proxies(host, user, password, database, port=3306, unix_socket=None):
""""Connect to a mysql database using pymysql and retrieve proxies for the scraping job.
Args:
host: The mysql database host
user: The mysql user
password: The database password
port: The mysql port, b... | d4595440c9d4d07a7d5e27740bf7049176dbe432 | 11,330 |
def APIRevision():
"""Gets the current API revision to use.
Returns:
str, The revision to use.
"""
return 'v1beta3' | c748e1917befe76da449e1f435540e10ee433444 | 11,331 |
def pretty_string_value_error(value, error, error_digits=2, use_unicode=True):
"""
Returns a value/error combination of numbers in a scientifically
'pretty' format.
Scientific quantities often come as a *value* (the actual
quantity) and the *error* (the uncertainty in the value).
... | bd7b1496880e7d1cb4ffd04d23df20d679ac8ade | 11,332 |
def sameSize(arguments) -> bool:
"""Checks whether given vectors are the same size or not"""
sameLength = True
initialSize = len(vectors[arguments[0]])
for vector in arguments:
if len(vectors[vector]) != initialSize:
sameLength = False
return sameLength | 0840adcb0f6a84c56ff3b0ce3aa23892e45d942e | 11,334 |
def db_read(src_path, read_type=set, read_int=False):
"""Read string data from a file into a variable of given type.
Read from the file at 'src_path', line by line, skipping certain lines and
removing trailing whitespace.
If 'read_int' is True, convert the resulting string to int.
Return r... | 811c6efb83d134d695c6dec2e34d3405818b8a48 | 11,335 |
import re
def get_config_keys():
"""Parses Keys.java to extract keys to be used in configuration files
Args: None
Returns:
list: A list of dict containing the following keys -
'key': A dot separated name of the config key
'description': A list of str
"""
desc_re =... | 8c04fcac2d05579ce47f5436999f0fe86fb1bdbd | 11,336 |
def new():
"""Create a new community."""
return render_template('invenio_communities/new.html') | 60ee1560f749d94833f57b6a34e2d514e3e04ccb | 11,337 |
import torch
def interpolate(results_t, results_tp1, dt, K, c2w, img_wh):
"""
Interpolate between two results t and t+1 to produce t+dt, dt in (0, 1).
For each sample on the ray (the sample points lie on the same distances, so they
actually form planes), compute the optical flow on this plane, then us... | d5cdae22a3fb324e9bdfdedabe0b69cb5d40ebdb | 11,338 |
def divisor(baudrate):
"""Calculate the divisor for generating a given baudrate"""
CLOCK_HZ = 50e6
return round(CLOCK_HZ / baudrate) | a09eee716889ee6950f8c5bba0f31cdd2b311ada | 11,339 |
def scm_get_active_branch(*args, **kwargs):
"""
Get the active named branch of an existing SCM repository.
:param str path: Path on the file system where the repository resides. If not specified, it defaults to the
current work directory.
:return: Name of the activ... | 6c18454548732cd8db4ba85b45cdc9a8d9b47fce | 11,340 |
def search_evaluations(campus, **kwargs):
"""
year (required)
term_name (required): Winter|Spring|Summer|Autumn
curriculum_abbreviation
course_number
section_id
student_id (student number)
"""
url = "%s?%s" % (IAS_PREFIX, urlencode(kwargs))
data = get_resource_by_campus(url, cam... | d7069c2e9135b350141b0053e3ec1202650b7c28 | 11,341 |
from typing import Optional
import select
async def get_user(username: str, session: AsyncSession) -> Optional[User]:
"""
Returns a user with the given username
"""
return (
(await session.execute(select(User).where(User.name == username)))
.scalars()
.first()
) | 0975c069d76414fbf57f4b8f7370d0ada40e39f5 | 11,342 |
import pandas
def compute_balances(flows):
"""
Balances by currency.
:param flows:
:return:
"""
flows = flows.set_index('date')
flows_by_asset = flows.pivot(columns='asset', values='amount').apply(pandas.to_numeric)
balances = flows_by_asset.fillna(0).cumsum()
return balances | 98728c2c687df60194eb11b479c08fc90502807a | 11,344 |
import json
def unjsonify(json_data):
"""
Converts the inputted JSON data to Python format.
:param json_data | <variant>
"""
return json.loads(json_data, object_hook=json2py) | 93a59f8a2ef96cbe25e89c2970969b0132b1a892 | 11,345 |
from typing import Tuple
from typing import List
def comp_state_dist(table: np.ndarray) -> Tuple[np.ndarray, List[str]]:
"""Compute the distribution of distinct states/diagnoses from a table of
individual diagnoses detailing the patterns of lymphatic progression per
patient.
Args:
table: Rows... | 1a2edacd40d4fea3ff3cc5ddd57d76bffc60c7bc | 11,346 |
def polyConvert(coeffs, trans=(0, 1), backward=False):
"""
Converts polynomial coeffs for x (P = a0 + a1*x + a2*x**2 + ...) in
polynomial coeffs for x~:=a+b*x (P~ = a0~ + a1~*x~ + a2~*x~**2 +
...). Therefore, (a,b)=(0,1) makes nothing. If backward, makes the
opposite transformation.
Note: backw... | 1a2607b28046a8dc67315726957a87a5d5c9a435 | 11,347 |
import random
def uniform(_data, weights):
"""
Randomly initialize the weights with values between 0 and 1.
Parameters
----------
_data: ndarray
Data to pick to initialize weights.
weights: ndarray
Previous weight values.
Returns
-------
weights: ndarray
N... | fbf7e853f11a888ee01dc840c6ffcb214560c5a8 | 11,348 |
def ingresar_datos():
"""Ingresa los datos de las secciones"""
datos = {}
while True:
codigo = int_input('Ingrese el código de la sección: ')
if codigo < 0:
break
cantidad = int_input(
'Ingrese la cantidad de alumnos: ', min=MIN, max=MAX
)
dato... | 3bacb0e5d6b234b2f90564c44a25d151a640fd1f | 11,349 |
def fetch_credentials() -> Credentials:
"""Produces a Credentials object based on the contents of the
CONFIG_FILE or, alternatively, interactively.
"""
if CONFIG_FILE_EXISTS:
return parse_config_file(CONFIG_FILE)
else:
return get_credentials_interactively() | 0b882c8c4c8066a1898771c66db6ccbe7cb09c37 | 11,350 |
def pool_adjacency_mat_reference_wrapper(
adj: sparse.spmatrix, kernel_size=4, stride=2, padding=1
) -> sparse.spmatrix:
"""Wraps `pool_adjacency_mat_reference` to provide the same API as `pool_adjacency_mat`"""
adj = Variable(to_sparse_tensor(adj).to_dense())
adj_conv = pool_adjacency_mat_reference(adj... | e72cb1e50bf7542d4175b9b3b3989e70a8812373 | 11,351 |
def send(socket, obj, flags=0, protocol=-1):
"""stringify an object, and then send it"""
s = str(obj)
return socket.send_string(s) | a89165565837ad4a984905d5b5fdd73e398b35fd | 11,352 |
def arraystr(A: Array) -> str:
"""Pretty print array"""
B = np.asarray(A).ravel()
if len(B) <= 3:
return " ".join([itemstr(v) for v in B])
return " ".join([itemstr(B[0]), itemstr(B[1]), "...", itemstr(B[-1])]) | 9cceed63c83812a7fd87dba833fc4d5b5a75088c | 11,353 |
def dist2_test(v1, v2, idx1, idx2, len2):
"""Square of distance equal"""
return (v1-v2).mag2() == len2 | 3a268a3ba704a91f83345766245a952fe5d943dd | 11,354 |
def extract_grid_cells(browser, grid_id):
"""
Given the ID of a legistar table, returns a list of dictionaries
for each row mapping column headers to td elements.
"""
table = browser.find_element_by_id(grid_id)
header_cells = table.find_elements_by_css_selector(
'thead:nth-child(2) ... | bee4265a18cfd428f25e3fdf3202fb5bfad820df | 11,355 |
import ast
def gatherAllParameters(a, keep_orig=True):
"""Gather all parameters in the tree. Names are returned along
with their original names (which are used in variable mapping)"""
if type(a) == list:
allIds = set()
for line in a:
allIds |= gatherAllVariables(line)
return allIds
if not isinstance(a, ... | e899e60d818750a4ff1656b039a6dc4413f8f181 | 11,356 |
def average_link_euclidian(X,verbose=0):
"""
Average link clustering based on data matrix.
Parameters
----------
X array of shape (nbitem,dim): data matrix
from which an Euclidian distance matrix is computed
verbose=0, verbosity level
Returns
-------
t a weightForest structur... | 17aae1e7f802f82765bcda8b403598a2c5a9f822 | 11,357 |
import functools
def cached(func):
"""Decorator cached makes the function to cache its result and return it in duplicate calls."""
prop_name = '__cached_' + func.__name__
@functools.wraps(func)
def _cached_func(self):
try:
return getattr(self, prop_name)
except AttributeEr... | 5b23c251c03160ba2c4e87848201be46ba2f34fb | 11,358 |
def SX_inf(*args):
"""
create a matrix with all inf
inf(int nrow, int ncol) -> SX
inf((int,int) rc) -> SX
inf(Sparsity sp) -> SX
"""
return _casadi.SX_inf(*args) | b11fba9e9b60eadb983d1203b1dd852abca9a2b7 | 11,359 |
def aes_encrypt(mode, aes_key, aes_iv, *data):
"""
Encrypt data with AES in specified mode.
:param aes_key: aes_key to use
:param aes_iv: initialization vector
"""
encryptor = Cipher(algorithms.AES(aes_key), mode(aes_iv), backend=default_backend()).encryptor()
result = None
for value in... | 94a39ddabe3ea186463808e79e86bec171fbaeda | 11,360 |
def _ebpm_gamma_update_a(init, b, plm, step=1, c=0.5, tau=0.5, max_iters=30):
"""Backtracking line search to select step size for Newton-Raphson update of
a"""
def loss(a):
return -(a * np.log(b) + a * plm - sp.gammaln(a)).sum()
obj = loss(init)
d = (np.log(b) - sp.digamma(init) + plm).mean() / sp.polygamma... | 038fb28824b3429b03887299af7a7feeec16b689 | 11,361 |
def edge_distance_mapping(graph : Graph,
iterations : int,
lrgen : LearningRateGen,
verbose : bool = True,
reset_locations : bool = True):
"""
Stochastic Gradient Descent algorithm for performing ... | f5c93cf83a7cd7892936246eb6c90562030ad819 | 11,362 |
def strip_extension(name: str) -> str:
"""
Remove a single extension from a file name, if present.
"""
last_dot = name.rfind(".")
if last_dot > -1:
return name[:last_dot]
else:
return name | 9dc1e3a3c9ad3251aba8a1b61f73de9f79f9a8be | 11,363 |
def validatePullRequest(data):
"""Validate pull request by action."""
if 'action' not in data:
raise BadRequest('no event supplied')
if 'pull_request' not in data or 'html_url' not in data.get('pull_request'):
raise BadRequest('payload.pull_request.html_url missing')
return True | a4577a1b719b11f1ea845fff436a78178ca9e370 | 11,365 |
def __adjust_data_for_log_scale(dataframe: pd.DataFrame) -> pd.DataFrame:
"""
This will clean and adjust some of the data so that Altair can plot it using a logarithmic scale. Altair does not
allow zero values on the Y axis when plotting with a logarithmic scale, as log(0) is undefined.
Args:
d... | 30d7a73f2f0d564f6e52e1a2fa4b521fa1265c3d | 11,366 |
import torch
def predict_sentence(model,vocab,sentence):
"""Predicts the section value of a given sentence
INPUT: Trained model, Model vocab, Sentence to predict
OUTPUT: Assigned section to the sentence"""
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
nlp=spacy.load('en_cor... | f8ef02bd92dfc3dfcea0f5a2e9d5da99050fe367 | 11,367 |
import spacy
import re
def ne_offsets_by_sent(
text_nest_list=[],
model='de_core_news_sm',
):
""" extracts offsets of NEs and the NE-type grouped by sents
:param text_nest_list: A list of list with following structure:\
[{"text": "Wien ist schön", "ner_dicts": [{"text": "Wien", "ne_type": "LOC"}]... | 1e4fdaba07bf562b1d91b5f2376955efa9974c56 | 11,368 |
from typing import Optional
def clone_repo(
url: str,
path: str,
branch: Optional[str] = None,
) -> bool:
"""Clone repo from URL (at branch if specified) to given path."""
cmd = ['git', 'clone', url, path]
if branch:
cmd += ['--branch', branch]
return run(cmd)[0].returncode == 0 | 56bc8641c3418216f1da5f0c87d33478888775c7 | 11,369 |
def get_inputtype(name, object_type):
"""Get an input type based on the object type"""
if object_type in _input_registry:
return _input_registry[object_type]
inputtype = type(
name,
(graphene.InputObjectType,),
_get_input_attrs(object_type),
)
_input_registry[object... | aee2a84c8aaf0d66554f022ac0fec0aaef808160 | 11,370 |
def get_engine_status(engine=None):
"""Return a report of the current engine status"""
if engine is None:
engine = crawler.engine
global_tests = [
"time()-engine.start_time",
"engine.is_idle()",
"engine.has_capacity()",
"engine.scheduler.is_idle()",
"len(engi... | 0d87692a991965c8b72204d241964a27a9499014 | 11,372 |
import tqdm
import requests
import json
def stock_em_jgdy_tj():
"""
东方财富网-数据中心-特色数据-机构调研-机构调研统计
http://data.eastmoney.com/jgdy/tj.html
:return: pandas.DataFrame
"""
url = "http://data.eastmoney.com/DataCenter_V3/jgdy/gsjsdy.ashx"
page_num = _get_page_num_tj()
temp_df = pd.DataFrame()
... | 1841702e6fb5c677245a2d213f489d95a789d68b | 11,373 |
def hpdi(x, prob=0.90, axis=0):
"""
Computes "highest posterior density interval" (HPDI) which is the narrowest
interval with probability mass ``prob``.
:param numpy.ndarray x: the input array.
:param float prob: the probability mass of samples within the interval.
:param int axis: the dimensio... | 579515ebb6d28c2a1578c85eab8cbff1b67bd5ee | 11,374 |
def a(n, k):
"""calculates maximum power of p(n) needed
>>> a(0, 20)
4
>>> a(1, 20)
2
>>> a(2, 20)
1
"""
return floor(log(k) / log(p(n))) | 581e2a23a3dc069fc457ed5a6fe7d5a355353242 | 11,375 |
import platform
def is_windows():
""" détermine si le système actuel est windows """
return platform.system().lower() == "windows" | fc9e2ca948f7cc5dc6b6cc9afb52ba701222bb7a | 11,376 |
def WTfilt_1d(sig):
"""
# 使用小波变换对单导联ECG滤波
# 参考:Martis R J, Acharya U R, Min L C. ECG beat classification using PCA, LDA, ICA and discrete
wavelet transform[J].Biomedical Signal Processing and Control, 2013, 8(5): 437-448.
:param sig: 1-D numpy Array,单导联ECG
:return: 1-D numpy Array,滤波后信号
"""
... | 8a3c65b35ac347b247a36e7d70705f76f41010d5 | 11,377 |
def discount_rewards(r):
""" take 1D float array of rewards and compute discounted reward """
gamma = 0.99
discounted_r = np.zeros_like(r)
running_add = 0
for t in reversed(range(0, r.size)):
running_add = running_add * gamma + r[t]
discounted_r[t] = running_add
return discounted... | b093c0d82ef82824c08d08ce4da1b840318bd7ed | 11,378 |
def mvn(tensor):
"""Per row mean-variance normalization."""
epsilon = 1e-6
mean = K.mean(tensor, axis=1, keepdims=True)
std = K.std(tensor, axis=1, keepdims=True)
mvn = (tensor - mean) / (std + epsilon)
return mvn | c205712d3a1a53450de0e0b9af0abe1b9d51f269 | 11,379 |
import re
def grapheme_to_phoneme(text, g2p, lexicon=None):
"""Converts grapheme to phoneme"""
phones = []
words = filter(None, re.split(r"(['(),:;.\-\?\!\s+])", text))
for w in words:
if lexicon is not None and w.lower() in lexicon:
phones += lexicon[w.lower()]
else:
... | 2bb5195a323aa712b2725851fdde64b8e38856f0 | 11,380 |
def mean_log_cosh_error(pred, target):
"""
Determine mean log cosh error.
f(y_t, y) = sum(log(cosh(y_t-y)))/n
where, y_t = predicted value
y = target value
n = number of values
:param pred: {array}, shape(n_samples,)
predicted values.
:param targ... | 85fd6c3d582e7bc41271e3212d43c5cfea8bcf7e | 11,381 |
def check_columns(board: list):
"""
Check column-wise compliance of the board for uniqueness (buildings of unique height)
and visibility (top-bottom and vice versa).
Same as for horizontal cases, but aggregated in one function for vertical case, i.e. columns.
>>> check_columns(['***21**', '412453*... | 85fd1f02b392c6b6219ce989f7439ec0140b9fa2 | 11,383 |
import numpy
import pathlib
import tqdm
import pandas
import warnings
def extract_header(mjds, path, keywords, dtypes=None, split_dbs=False, is_range=False):
"""Returns a `~pandas.DataFrame` with header information.
For a list or range of MJDs, collects a series of header keywords for
database files and ... | 65934d9b5e9c1e6eb639709a16e6e93c145b57e7 | 11,384 |
import pytz
from datetime import datetime
async def get_time():
"""获取服务器时间
"""
tz = pytz.timezone('Asia/Shanghai')
return {
'nowtime': datetime.now(),
'utctime': datetime.utcnow(),
'localtime': datetime.now(tz)
} | 282eb1136713df8045c6ad5f659042484fe4ec8b | 11,385 |
def health_check():
"""Attempt to ping the database and respond with a status code 200.
This endpoint is verify that the server is running and that the database is
accessible.
"""
response = {"service": "OK"}
try:
postgres.session.query(text("1")).from_statement(text("SELECT 1")).all()... | cd47815ada53281f2b13542dd8cad93398be5203 | 11,386 |
def find_ad_adapter(bus):
"""Find the advertising manager interface.
:param bus: D-Bus bus object that is searched.
"""
remote_om = dbus.Interface(
bus.get_object(constants.BLUEZ_SERVICE_NAME, '/'),
constants.DBUS_OM_IFACE)
objects = remote_om.GetManagedObjects()
for o, props... | 6b5f49a5908948a54f99438a38865293fca51cc7 | 11,387 |
def leaky_relu(x, slope=0.2):
"""Leaky Rectified Linear Unit function.
This function is expressed as :math:`f(x) = \max(x, ax)`, where :math:`a`
is a configurable slope value.
Args:
x (~chainer.Variable): Input variable.
slope (float): Slope value :math:`a`.
Returns:
~chai... | cf7624309543e24c70832249116b74d56c26d1f9 | 11,388 |
def GetConfig(user_config):
"""Decide number of vms needed to run oldisim."""
config = configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME)
config['vm_groups']['default']['vm_count'] = (FLAGS.oldisim_num_leaves
+ NUM_DRIVERS + NUM_ROOTS)
return config | b04380fe6dbc84ef4c353dd34354581fa69aac89 | 11,389 |
import re
def gen_answer(question, passages):
"""由于是MLM模型,所以可以直接argmax解码。
"""
all_p_token_ids, token_ids, segment_ids = [], [], []
for passage in passages:
passage = re.sub(u' |、|;|,', ',', passage)
p_token_ids, _ = tokenizer.encode(passage, maxlen=max_p_len + 1)
q_token_ids, _... | 536880c1318cc193be19561183e652c7668eb09b | 11,391 |
def compile(function_or_sdfg, *args, **kwargs):
""" Obtain a runnable binary from a Python (@dace.program) function. """
if isinstance(function_or_sdfg, dace.frontend.python.parser.DaceProgram):
sdfg = dace.frontend.python.parser.parse_from_function(
function_or_sdfg, *args, **kwargs)
el... | 7504344e8e9df5a395e51af1211db286188f3fcb | 11,392 |
import re
def is_untweeable(html):
"""
I'm not sure at the moment what constitutes untweeable HTML, but if we don't find DVIS in tiddlywiki,
that is a blocker
"""
# the same regex used in tiddlywiki
divs_re = re.compile(
r'<div id="storeArea"(.*)</html>',
re.DOTALL
)
return bool(divs_re.search(html)) | face6c6d30b6e26ffa3344ed8e42ed7d44cf2ea5 | 11,393 |
from typing import Optional
def create_1m_cnn_model(only_digits: bool = False, seed: Optional[int] = 0):
"""A CNN model with slightly under 2^20 (roughly 1 million) params.
A simple CNN model for the EMNIST character recognition task that is very
similar to the default recommended model from `create_conv_dropo... | 87353f8bd8e3b3d7602ad3dcd92b717b2590285b | 11,394 |
def _check_index(target_expr, index_expr):
"""
helper function for making sure that an index is valid
:param target_expr: the target tensor
:param index_expr: the index
:return: the index, wrapped as an expression if necessary
"""
if issubclass(index_expr.__class__, _Expression):
in... | 96d5bf6d6d19bfca0de30ea9915a38237cf9c80f | 11,395 |
def create_access_token(user: UserModel, expires_delta: timedelta = None) -> str:
"""
Create an access token for a user
:param user: CTSUser -> The user
:param expires_delta: timedelta -> The expiration of the token. If not given a default will be used
:return: str -> A token
"""
load_all_co... | d5ba53f0ecc7e7755988ad2540e4cd4c520b30dd | 11,396 |
def is_async_mode():
"""Tests if we're in the async part of the code or not."""
async def f():
"""Unasync transforms async functions in sync functions."""
return None
obj = f()
if obj is None:
return False
obj.close() # prevent unawaited coroutine warning
return True | 8e515efc767f75c4b90486089f0d8a7203da59d7 | 11,397 |
def remove_arm(frame):
"""
Removes the human arm portion from the image.
"""
##print("Removing arm...")
# Cropping 15 pixels from the bottom.
height, width = frame.shape[:2]
frame = frame[:height - 15, :]
##print("Done!")
return frame | 99b998da87f1aa2eca0a02b67fc5adc411603ee4 | 11,398 |
def cumulative_spread(array, x):
"""
>>> import numpy as np
>>> a = np.array([1., 2., 3., 4.])
>>> cumulative_spread(a, 0.)
array([0., 0., 0., 0.])
>>> cumulative_spread(a, 5.)
array([1., 2., 2., 0.])
>>> cumulative_spread(a, 6.)
array([1., 2., 3., 0.])
>>> cumulative_spread(a, 1... | c6966a97945f30cce6a794325091a31716a36e54 | 11,399 |
def GetIdentifierStart(token):
"""Returns the first token in an identifier.
Given a token which is part of an identifier, returns the token at the start
of the identifier.
Args:
token: A token which is part of an identifier.
Returns:
The token at the start of the identifier or None if... | 6b3ad9fb9d43411fc7df147ace872f75c70b5d11 | 11,400 |
def load_spec(filename):
"""
loads the IDL spec from the given file object or filename, returning a
Service object
"""
service = Service.from_file(filename)
service.resolve()
return service | 6dfea85635d3b610ee998999397fc92fd516933c | 11,401 |
import torch
def load_model(file_path, *, epoch, model, likelihood, mll, optimizer, loss):
"""モデルの保存関数
Parameters
----------
file_path : str
モデルの保存先のパスとファイル名
epoch : int
現在のエポック数
model : :obj:`gpytorch.models`
学習済みのモデルのオブジェクト
likelihood : :obj:`gpytorch.like... | ccc7f221164d89ed29326f720becd29e3442c52b | 11,403 |
import re
def valid_account_id(log, account_id):
"""Validate account Id is a 12 digit string"""
if not isinstance(account_id, str):
log.error("supplied account id {} is not a string".format(account_id))
return False
id_re = re.compile(r'^\d{12}$')
if not id_re.match(account_id):
... | 30f3aa9547f83c4bea53041a4c79ba1242ae4754 | 11,404 |
import numpy
def prod(a, axis=None, dtype=None, out=None):
"""
Product of array elements over a given axis.
Parameters
----------
a : array_like
Elements to multiply.
axis : None or int or tuple of ints, optional
Axis or axes along which a multiply is performed.
The de... | c33a506847b13924aa903b5daeece0312cc29c8f | 11,405 |
import random
def sample_pagerank(corpus, damping_factor, n):
"""
Return PageRank values for each page by sampling `n` pages
according to transition model, starting with a page at random.
Return a dictionary where keys are page names, and values are
their estimated PageRank value (a value between... | 32c89d7669718c714663e66a926bb27f9c219c38 | 11,406 |
def guess_layout_cols_lr(mr,
buf,
alg_prefix,
layout_alg_force=None,
verbose=False):
"""
Assume bits are contiguous in columns
wrapping around at the next line
Least significant bit at left
Can eithe... | dbbbf68ee251fb50c413648e97c9957ed7c086ec | 11,407 |
def decrease(rse_id, account, files, bytes, session=None):
"""
Decreases the specified counter by the specified amount.
:param rse_id: The id of the RSE.
:param account: The account name.
:param files: The amount of files.
:param bytes: The amount of bytes.
:param session: The database... | 2ad193e5f50c0bcb19f0d796c7f8b9da115a1f2d | 11,408 |
def get_import_error(import_error_id, session):
"""
Get an import error
"""
error = session.query(ImportError).filter(ImportError.id == import_error_id).one_or_none()
if error is None:
raise NotFound("Import error not found")
return import_error_schema.dump(error) | 37444be97de3c4fa97fba60d87f469c428011db1 | 11,409 |
def roll_dice():
""" simulate roll dice """
results = []
for num in range(times):
result = randint(1, sides)
results.append(result)
return results | 9a8442ff777c8c03146bcb9a0f8a2dc19e87a195 | 11,411 |
def _read_calib_SemKITTI(calib_path):
"""
:param calib_path: Path to a calibration text file.
:return: dict with calibration matrices.
"""
calib_all = {}
with open(calib_path, 'r') as f:
for line in f.readlines():
if line == '\n':
break
key, value = line.split(':', 1)
calib_all... | 2d71146ce79ce39309930bb8a452c185c35c3061 | 11,412 |
import torch
def _bias_act_cuda(dim=1, act='linear', alpha=None, gain=None, clamp=None):
"""Fast CUDA implementation of `bias_act()` using custom ops.
"""
# Parse arguments.
assert clamp is None or clamp >= 0
spec = activation_funcs[act]
alpha = float(alpha if alpha is not None else spec.def_a... | 44559520faf06fbf9b6f17ac1b29b829840e7f38 | 11,413 |
from typing import Mapping
def root_nodes(g: Mapping):
"""
>>> g = dict(a='c', b='ce', c='abde', d='c', e=['c', 'z'], f={})
>>> sorted(root_nodes(g))
['f']
Note that `f` is present: Isolated nodes are considered both as
root and leaf nodes both.
"""
nodes_having_parents = set(chain.fr... | 67c2043053f82a9a17f148c57bbf4d2501530f99 | 11,414 |
def _GetRemoteFileID(local_file_path):
"""Returns the checked-in hash which identifies the name of file in GCS."""
hash_path = local_file_path + '.sha1'
with open(hash_path, 'rb') as f:
return f.read(1024).rstrip() | 4a06dcdd30e379891fe3f9a5b3ecc2c4fd1a98ed | 11,415 |
def stress_stress(
bond_array_1, c1, etypes1, bond_array_2, c2, etypes2, sig, ls, r_cut, cutoff_func
):
"""2-body multi-element kernel between two partial stress components
accelerated with Numba.
Args:
bond_array_1 (np.ndarray): 2-body bond array of the first local
environment.... | c832b6951774eff3b37dd3a674be74ad917409df | 11,416 |
def is_color_rgb(color):
"""Is a color in a valid RGB format.
Parameters
----------
color : obj
The color object.
Returns
-------
bool
True, if the color object is in RGB format.
False, otherwise.
Examples
--------
>>> color = (255, 0, 0)
>>> is_col... | 46b8241d26fa19e4372587ffebda3690972c3395 | 11,417 |
def edit_post_svc(current_user, id, content):
"""
Updates post content.
:param current_user:
:param id:
:param content:
:return:
"""
post = single_post_svc(id)
if post is None or post.user_id != current_user:
return None
post.content = content
db.session.commit()
return True | a17b632f402ef3f915bf06bde86ab0ff40956177 | 11,418 |
from re import M
def free_free_absorp_coefPQ(n_e,n_i,T,f):
"""Returns a physical quantity for the free-free absorption coefficient
given the electron density, ion density, kinetic temperature and frequency
as physical quantities. From Shklovsky (1960) as quoted by Kraus (1966)."""
value = 9.8e-13 * n_e.inBase... | 17a09bf20f4363be4f273694168df2cf0eee8b38 | 11,419 |
def pixel_gain_mode_statistics(gmaps):
"""returns statistics of pixels in defferent gain modes in gain maps
gr0, gr1, gr2, gr3, gr4, gr5, gr6 = gmaps
"""
arr1 = np.ones_like(gmaps[0], dtype=np.int32)
return [np.sum(np.select((gr,), (arr1,), default=0)) for gr in gmaps] | b9c6b4c601724105d381e77f7c293e0bd00f3ba8 | 11,420 |
def run_parallel(ds1, ds2):
""" Run the calculation using multiprocessing.
:param ds1: list with points
:param ds2: list with points
:return: list of distances
"""
pool = mp.Pool(processes=mp.cpu_count())
result = pool.starmap(euclidian_distance, [(p1, p2) for p1 in ds1 for p2 in ds2])
... | e8a6b0124db1948ab72b9081863cdfe77a75e08d | 11,421 |
import re
def to_latin(name):
"""Convert all symbols to latin"""
symbols = (u"іїєабвгдеёжзийклмнопрстуфхцчшщъыьэюяІЇЄАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ",
u"iieabvgdeejzijklmnoprstufhzcss_y_euaIIEABVGDEEJZIJKLMNOPRSTUFHZCSS_Y_EUA")
tr = {ord(a): ord(b) for a, b in zip(*symbols)}
translat... | 06a0d535fa7a74feea33e58815da2792a6026def | 11,422 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.