content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def get_reward(logits, lbl, args):
""" given logits, calculate score for Shapley value or interaction
Input:
logits: (B', num_class) tensor, B' can be (num_region+1)*bs or B'=1
lbl: (B,) tensor, B=1, label
Return:
v: (B',) tensor, reward score
"""
num_class = l... | 3a6ff438f1c5711a7767c5cdd655ded14dac599d | 69,246 |
def tunnelFromPhaseGW(phases, start_phase, V, dV, Tmax, Ttol = 1e-3, maxiter = 100, phitol = 1e-8, overlapAngle = 45.0,
nuclCriterion = lambda S, T: S/(T+1e-100) - 140, verbose = False, fullTunneling_params={}):
"""
Extends the function tunnelFromPhase by the calculation of the GW
parame... | dc3695f737d387b2b0a4620231878faa68482311 | 69,247 |
def to_df(song: Song):
"""Convert pydantic object to pandas dataframe with 1 row."""
return pd.DataFrame([dict(song)]) | 46f025e72ac042eb75a7afd6be38351b00c8e90e | 69,248 |
def hash_password(password: str, maxtime: int=1, length: int=64) -> bytes:
"""
Hash a password string using scrypt
Args:
password: password string
maxtime: maximum timed decryption should take
length: length of key to generate
Returns:
Hashed password
"""
return ... | c997bc99c50f0cddea697617f692d89f087bc035 | 69,250 |
def shout_echo(word1, echo=1):
"""Concatenate echo copies of word1 and three
exclamation marks at the end of the string."""
# Raise an error with raise
if echo < 0:
raise ValueError('echo must be greater than or equal to 0')
# Concatenate echo copies of word1 using *: echo_word
echo_wo... | 68e2cce4adc68b1c7e345d2d3e11b36e1cbbf84c | 69,251 |
import requests
import json
def _get_arxiv_metadata(identifier):
"""Get the DOI identifier (if it exists) from the arXiv API."""
response = requests.get(
f'https://api.semanticscholar.org/v1/paper/arXiv:{identifier}'
)
_validate_response(response, identifier)
parsed_response = json.loads(r... | 4139b495275babf9b4d818d797168894e27d5432 | 69,252 |
def get_member_names(group):
"""Get a list of resource names of the resources in the specified group.
Failed resources will be ignored.
"""
inspector = GroupInspector.from_parent_resource(group)
return list(inspector.member_names(include_failed=False)) | f1e4fc7018a1dd4449342d33c5aa522de4fdf455 | 69,253 |
def create_db(df):
"""
Create a nybb table in the test_geopandas PostGIS database.
Returns a boolean indicating whether the database table was successfully
created
"""
# Try to create the database, skip the db tests if something goes
# wrong
# If you'd like these tests to run, create a ... | 2a138481efc54233462e7cde4ca04ad907858a2e | 69,255 |
import pandas
def find_cycle_extrema(series, samples_per_cycle):
"""Find minima and maxima for each cycle in an oscillatory signal.
'series' is a pandas Series.
Does *not* directly find successive minima and maxima; instead,
looks for 1 of each per cycle.
Returns a boolean Series ("isma... | 83dccfa12da619282cd3dba99eff2202094cd677 | 69,256 |
def gravity_v1() -> ItemParser:
"""This method is returns a Gravity ItemParser for Gravity row version 1"""
def type_conversions(gravity: Gravity):
gravity.acc_x = float(gravity.acc_x)
gravity.acc_y = float(gravity.acc_y)
gravity.acc_z = float(gravity.acc_z)
parser = ItemParser(1, ... | fa31bc429438bf5ec35235b79d8c5d0cda00e2a2 | 69,257 |
def error_json_serializer(o):
"""Return a JSON serializable representation of error properties."""
if isinstance(o, sublime.Region):
return (o.a, o.b)
return o | 2f9c9a461159a32c370e53fc2258cfa5770801d5 | 69,258 |
def normalize_whitespace(text: str):
"""
Given ``text`` str, replace one or more spacings with a single space, and one
or more linebreaks with a single newline. Also strip leading/trailing whitespace.
Args:
text (str): ``Urdu`` text
Returns:
str: Returns a ``str`` object containing ... | 8817dd4d4f3b84fd0f3c7bef9389cb2fd78e5dbe | 69,261 |
def get_visitor_chat_id(cpf):
"""
Get a chat_id of a visitor
"""
session = Session()
visitor = session.query(Visitor).\
filter_by(
cpf=cpf).first()
session.close()
if visitor:
return visitor.chat_id
else:
return None | 3d3d59dd87883fbcd7997609aaaf7bd488c97c8c | 69,262 |
import numpy
def DerXYZEuler(alpha,beta,gamma):
""" derivatives of transformation matrix with respect to Euler angle
:param float alpha: euler angle alpha (radians)
:param float beta: euler angle beta (radians)
:param float gamma: euler angle gamma (radians)
:return: - du:lst(3*3*3) derivat... | dd620029cc143bca661c532c9d474e4a759fa2e3 | 69,263 |
def betaCost(price, is_etf, is_day_trading=False, volumn=1) -> Decimal:
"""
證交稅 = 賣出成交金額 * beta
:param price:
:param is_etf:
:param is_day_trading: 是否為當沖
:param volumn:
:return:
"""
# 證交稅:股票 0.003(當沖為 0.0015) ETF 0.001(當沖沒有折扣)
if is_etf:
beta = Decimal("0.001")
else:... | 53b41f30957a64e629b502f88f9463b2716902d1 | 69,264 |
import ast
def used_in_func(statement: str, filename: str = "<string>", mode: str = "exec"):
"""Parse a Python statement and analyze the symbols used. The result
will be used to determine what variables a step depends upon."""
try:
return get_used_in_func(ast.parse(statement, filename, mode))
... | 8d1ee04c492767794d2497053f09066aace91cc9 | 69,265 |
def get_trainer_with_mock_updater(
stop_trigger=(10, 'iteration'), iter_per_epoch=10):
"""Returns a :class:`~chainer.training.Trainer` object with mock updater.
The returned trainer can be used for testing the trainer itself and the
extensions. A mock object is used as its updater. The update funct... | 68f1e1b875a141f0e722c792489df42379006d47 | 69,266 |
from typing import List
from typing import Optional
import re
def filter_comments(
comments: List[AnyComment],
filter_regex: Optional[str] = None,
reverse: bool = False,
author: Optional[str] = None,
) -> List[AnyComment]:
"""
Filters comments from the given list.
Args:
comments: ... | 05922165c58342fd3f88b50229824216922b8283 | 69,267 |
def delete_task(task_id):
"""deletes a task from a project and removes it from the database"""
task_to_delete = Task.query.filter_by(task_id=task_id).first()
project_id = task_to_delete.project.project_id
project_tracker_db.session.delete(task_to_delete)
project_tracker_db.session.commit()
retur... | 64d4e9b295b1f94a3760384cefd9926fb5f73240 | 69,268 |
def filter_log_by_end_activities(end_activities, variants, vc, threshold, activity_key="concept:name"):
"""
Keep only variants of the log with an end activity which number of occurrences is above the threshold
Parameters
----------
end_activities
Dictionary of end attributes associated ... | fe587c58c775b1900a9e2b2209432cb479d4bfdd | 69,269 |
from typing import List
async def resolve_get_rent_events(_parent, args, _ctx, _info) -> List[RentEvent]:
"""
Resolves 'getRentEvents' graphql query for the Graphql Engine.
Returns:
List[RentEvent]: Event instance compatible with RentEvent sylvester Graphql schema.
"""
return await resol... | ccebf446fd60c5c056e2b3128490d7d21766d91e | 69,270 |
def filter_para(paras):
"""过滤空值和签名"""
for k, v in paras.items():
if not v or k in ['sign', 'sign_type']:
paras.pop(k)
return paras | c73123b15add26debbb3c60e11ca90b46782b6cc | 69,271 |
def remove_nan(data, mask=None):
"""
Remove nan values from data.
Optionally, it can update a mask (masked data = 1 in the mask, 0 otherwise).
:param data: numpy ndarray
:param mask: if provided, numpy ndarray of the same shape as the data
:return: the filtered data and (optionally) mask
"... | 6dd69f91ca95a7bac6b799f00182dd338cfddfcf | 69,272 |
def filter_connected(df: pd.DataFrame, dist: int = 2) -> pd.DataFrame:
"""Remove barcodes that are within hamming dist of eachother leving isolated sequences
Inspired by the Abseq analysis in https://www.nature.com/articles/srep44447
"""
clusterer = UMIClusterer(cluster_method="cluster")
# Encode ea... | 163a81c415414cc2f59abc91a2978459c89b3c8e | 69,273 |
def test_unexpected_error():
"""The credential should raise ClientAuthenticationError when the endpoint returns an unexpected error"""
error_message = "something went wrong"
for code in range(401, 600):
def send(request, **_):
if "resource" not in request.query:
# avai... | b4b547e8faac9aa302ec8d304a785698057616eb | 69,274 |
import requests
def scraper_setup(site):
"""
site: string url of site to be scraped
returns a page, or exits early if an error occurs
"""
print("[[ About to search {site} ]]".format(site=site))
page = requests.get(site)
if page.status_code != 200:
# Inform user of why it may have... | 545df7c51075bf4e41942e76930384811da90213 | 69,275 |
def irbo(topics, weight=0.9, topk=10):
"""
compute the inverted rank-biased overlap
Parameters
----------
topics: a list of lists of words
weight: p (float), default 1.0: Weight of each
agreement at depth d:p**(d-1). When set
to 1.0, there is no weight, the rbo returns
t... | 1ade13cd4358c5af759fc9806ebe4721c63163a0 | 69,276 |
import logging
def get_term_codes():
"""
Get a list of term codes and their names from the UW API. Returns a
TermInfo object and the ID of the current term
"""
#Create the url to query the API with
url = """https://api.uwaterloo.ca/v2/terms/list.json?key={}\
""".format(app.config['API_KE... | a1c5e34b5bca19a7d48865aa65888700394f36ca | 69,277 |
import torch
def test_early_stopping_patience(tmpdir, loss_values, patience, expected_stop_epoch):
"""Test to ensure that early stopping is not triggered before patience is exhausted."""
class ModelOverrideValidationReturn(EvalModelTemplate):
validation_return_values = torch.Tensor(loss_values)
... | 77d46a268f214287e055efc7f7d6041682e1efd6 | 69,278 |
def make_ip_simple_fixed_color_light(
device: hm_device.HmDevice, device_address: str, group_base_channels: list[int]
) -> list[hm_entity.BaseEntity]:
"""Creates simple fixed color light entities like HmIPW-WRC6."""
return make_custom_entity(
device=device,
device_address=device_address,
... | 8dd87a794e60a4d43803a8502a3862dc62be4c0d | 69,279 |
import pathlib
def get_fixture(filename):
"""Return the data fixture."""
current_root = pathlib.Path('.').resolve()
fixture_root = current_root / 'tests' / 'fixtures' / 'tools'
fixture_path = fixture_root / filename
return fixture_path.read_text() | 225d4cdc6d2682b0dac8ddfa54b819bea335b82b | 69,280 |
def SpotLightStart(builder):
"""This method is deprecated. Please switch to Start."""
return Start(builder) | fdb9a14e06c4856e82599fdacdc862b63aadca76 | 69,281 |
def clean_password_changes(old_pword, new_pword, new_pword_conf, user,
request):
"""Cleaner for password changes."""
errors = []
success_list = []
if old_pword != '' or new_pword != '':
if not user.check_password(old_pword):
errors.append('old_pword')
... | 0cee9abf7313c9d96fe09c118a4b93d3fc08a3c4 | 69,282 |
def mstest_box_post_process(result, cfg):
"""
Multi-scale Test
Only available for batch_size=1 now.
"""
post_bbox = {}
use_flip = False
ms_boxes = []
ms_scores = []
im_shape = result['im_shape'][0]
for k in result.keys():
if 'bbox' in k:
boxes = result[k][0]
... | 4b2fa80a2786f6ce8449ae7b236eccfd12546c7d | 69,283 |
def get_model_meta_info(model_name):
"""returns a dict with model information"""
return model_meta_info[model_name].copy() | 573fbd461bbde6850ef4b39d6ef69556d1b7198e | 69,284 |
def logout():
"""Clear the current session, including the stored user id."""
session.clear()
return redirect(url_for("index")) | 4046b49a3a3d7d018ee7d87cd37cdcf5b30de555 | 69,285 |
from typing import Optional
def dcfc_act_365_a(start: Date, asof: Date, end: Date, freq: Optional[Decimal] = None) -> Decimal:
"""
Computes the day count fraction for the "Act/365A" convention.
:param start: The start date of the period.
:param asof: The date which the day count fraction to be calcul... | c7cbcc5281551016dcb9d24a16014113eda6e0ae | 69,287 |
def get_last_commit_year(file_name):
"""Get year of last commit to the named file"""
cmd_list = [
'git', 'log', '-1', '--format=%ad', '--date=format-local:%Y', file_name
]
data = ''
try:
data = subprocess.check_output(cmd_list)
except subprocess.CalledProcessError as exc:
... | 23e0da921fb695ceaff32fff8f6c16342ae00c2b | 69,288 |
def get_bbox_from_points(pts):
"""
Return bbox from a points array
:param pts: the points coordinates
:return: y1, x1, y2, x2
"""
temp = np.array(pts)
x1 = np.amin(temp[:, 0])
x2 = np.amax(temp[:, 0])
y1 = np.amin(temp[:, 1])
y2 = np.amax(temp[:, 1])
return y1, x1, y2, x2 | c235506e64ab2a5f9c1070deb2456cc940bacf6d | 69,289 |
def getWnPos(treebank_tag : str):
"""
return WORDNET POS compliance to WORDNET lemmatization (a,n,r,v)
"""
if treebank_tag.startswith('J'):
return wn.ADJ
elif treebank_tag.startswith('V'):
return wn.VERB
elif treebank_tag.startswith('N'):
return wn.NOUN
elif treebank_... | ea4b749915d0be50e9f0445c09594da37b63a498 | 69,290 |
def list_all(t: ListableAPIResource):
"""Retrieve all objects of type t from Stripe. Should work for
Product, Plan. SKU.
"""
objects = []
last_id = None
has_more = True
while has_more:
response = t.list(limit=100, starting_after=last_id)
has_more = response.has_more
... | 6e46517f7405715a436c7e4c210138c065a31104 | 69,291 |
def gen_fake_msa(seqreclist):
"""
Fake an MSA by adding dashes to the end of sequences up to maximum length and
return it as an MSA
"""
mlength=max(map(len,seqreclist))
newseqreclist=list()
for s in seqreclist:
l=mlength-len(s.seq)
newseqreclist.append(SeqRecord(id=s.id,name... | 62598deebfb54eef91a17dd3cb64a13d8abff2f0 | 69,293 |
import pickle
def dump_qubo(model, output_path=_default_opath, prefix=_default_prefix, **markers):
"""
Pickle a QUBO using specific markers. See also :py:meth:`use_markers`. The default filename is
`qubo.pickle`.
:param model: an implementation of :py:class:`~hepqpr.qallse.QallseBase`
:param outp... | 2cc477190a9ab1f502258449102fa5255e25da82 | 69,294 |
import requests
def kmodify(host, server, keyword, value):
"""Modify the value of a keyword.
Reproduces the behaviour of modify -s server keyword
Parameters
----------
host : str
Instrument host computer
server : str
Server
keyword : str
Keyword
value : generi... | ad7a33848888efe748376989abc2021f5aea939d | 69,295 |
def get_direction_mask(nusc_map, patch_box, canvas_size):
"""
Return list of map mask layers of the specified patch.
:param patch_box: Patch box defined as [x_center, y_center, height, width]. If None, this plots the entire map.
:param patch_angle: Patch orientation in degrees. North-facing corresponds ... | 5ac166132a3d6c2d374ac1d87ba327b610a17dec | 69,296 |
def get_unique_points(
n, x_range=(0, 10), x_grid_dim=101, y_range=(0, 10), y_grid_dim=101
):
"""
Get array of unique points, randomly drawn from a uniform grid
"""
xs, ys = np.meshgrid(
np.linspace(x_range[0], x_range[1], x_grid_dim),
np.linspace(y_range[0], y_range[1], y_grid_d... | d433b456842bae8eec123ab22eab16f7190d5011 | 69,297 |
def CCW_ps(Pxx, Pyy, Pxy):
"""Counter clockwise power spectrum."""
QS = Pxy.imag
return (Pxx + Pyy + 2*QS)/2. | 76710ff31e4fead278afc9eb37691f2178f45def | 69,298 |
def generate_below_the_fold_css(theme):
"""
Returns a string containing below-the-fold Bootstrap CSS using the
given BootstrapTheme
"""
context = get_scss_template_context(theme)
scss_string = render_to_string('bootstrap_customizer/bootstrap_below_the_fold.scss', context)
if is_windows_envir... | 0e970d6bede0f3a3e5cfad20432d7cba9b07fca7 | 69,299 |
import pickle
import asyncio
async def main(client):
"""
Main function of the graph processing. \n
- Gets client and tries to connect \n
- Manage last channel database and saves the last after each iteration to `db.pkl` \n
- Manage total graph and saves the composed graph after each iteration to `... | 62edae0f44f2436ff2b09e634986162c68961683 | 69,300 |
import requests
def get_user_info():
"""
Gets name, credits, etc.
"""
head = {"request": "users/info/", "api_key": API_KEY}
ret = requests.get(url,params=head)
if ret.status_code != 200:
raise ValueError
else:
return ret.json()['data'] | 794df7bc1c97bcf45df04ae59e4555f81183688f | 69,301 |
import math
def spd_pgs_make_theta_spec(data_in, resolution=None, colatitude=False):
"""
Builds theta (latitudinal) spectrogram from simplified particle data structure.
Input:
data_in: dict
Particle data structure
Parameters:
resolution: int
Number of theta po... | d3f751d6040f3263b049b42b3cab8a906b17d0f2 | 69,302 |
def check_interval(child_span, parent_span):
"""
Given a child span and a parent span, check if the child is inside the parent
"""
child_start, child_end = child_span
parent_start, parent_end = parent_span
if (
(child_start >= parent_start)
&(child_end <= parent_end)
):
... | 6c6a8e636ad181af821d185ba35f18db41d0ce77 | 69,303 |
from typing import Tuple
from typing import Union
from typing import List
def pseudo_event_list(
x_lim: Tuple[int, Union[int, None]],
y_lim: Tuple[int, Union[int, None]],
exp_time: float,
) -> Tuple[List, List]:
"""
Generate a pseudo-events list with positions and timestamps.
Args:
x_... | b0b67091d751f879354fd3c2afab536d8f663be5 | 69,304 |
def filter_entities_by_noise(
true: list, pred: list, noise_lower: float, noise_upper: float
) -> tuple:
"""
Filter to keep any tokens with a LEVENSHTEIN distance within particular range.
If not given, the tokens are kept as well.
"""
filtered_true = []
filtered_pred = []
for tok_true,... | 8add64fe828e17d1c532a1c67cc1f7da232ae5f2 | 69,305 |
def loss_numba(
alpha: np.ndarray,
X: np.ndarray,
Y: np.ndarray,
epsilon: float,
lambda2: float,
beta: float,
) -> (float, np.ndarray):
"""
Smoothed (with sigmoid) version of the loss, that also calculates the gradient.
This function is sped up with numba.
"""
epsilon... | b8dfdd750d6a823887d7aebafc5d4307c502a73b | 69,306 |
def update_posterior_states(A, obs, prior=None, **kwargs):
"""
Update marginal posterior over hidden states using mean-field fixed point iteration
FPI or Fixed point iteration.
See the following links for details:
http://www.cs.cmu.edu/~guestrin/Class/10708/recitations/r9/VI-view.pdf, slides 13- ... | 3eddf4484789e63f349fe2962fa88cacfa78945a | 69,307 |
def fftn(data, axes=None, **kwargs):
"""Fourier transform wrapper
Args:
data: microstructure
axes: the axes over which to perform the transform
Returns:
the transformation
"""
return FFTMODULE.fftn(data, axes=axes, **kwargs) | 573e33d593cca83ce09d8324d76522a1f3b140be | 69,309 |
def merge_to_length(a, b, length):
"""Merge 2 lists into a specific length.
This method will merge 2 lists into a short list, replacing the last few
items of the first list if necessary.
For example, a = [1,2,3], b = [4,5,6,7], and length = 6. The result will
be [1,2,4,5,6,7]. If length = 5, the r... | bdadb57c04567bae2a6890d7e5be981f1ba18fc9 | 69,310 |
def run_model(
V,
initial_aerosols,
T,
P,
dt,
S0=-0.0,
max_steps=1000,
t_end=500.0,
solver="lsoda",
output_fmt="smax",
terminate=False,
solver_kws=None,
model_kws=None,
):
""" Setup and run the parcel model with given solver configuration.
Parameters
----... | 089eb1ffec516d2ecf7a06e9a094da7f6f416775 | 69,311 |
import pathlib
import torch
import logging
import json
def train(
checkpoint_dir: str = None,
load_checkpoint_dir: str = None,
# Dataset Parameters
mask_prob: float = 0.15,
random_replace_prob: float = 0.1,
unmask_replace_prob: float = 0.1,
max_seq_length: int =... | 15c33e612597a7d5311594b45b0c2fe349d9a940 | 69,312 |
def calc_bpe_bulk_electrolyte_resistance(characteristic_length, sigma):
"""
The area specific charge transfer resistance through the bulk electrolyte
units: Ohm*m2
Notes:
Adjari, 2006 - "(area specific) bulk electrolyte resistance"
Squires, 2010 - does not explicitly define this... | f6a08cd5997de8954faa41d69e7abca1541e3fa0 | 69,313 |
import random
def generate_verification_code():
"""
随机生成6位数
:return:
"""
code_list = []
for i in range(10): # 0-9数字
code_list.append(str(i))
myslice = random.sample(code_list, 6) # 从list中随机获取6个元素,作为一个片断返回
verification_code = ''.join(myslice) # list to string
return verif... | a319391d782e2ce34b9d95a36a823df05267dcb8 | 69,314 |
def lin_a98rgb_to_xyz(rgb):
"""
Convert an array of linear-light a98-rgb values to CIE XYZ using D50.D65.
(so no chromatic adaptation needed afterwards)
http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
which has greater numerical precision than section 4.3.5.3 of
https://www.ado... | 385d5557536dc92e3ca3c0679ce9d7e0d6ba2722 | 69,315 |
import time
def record_time_interval(section, start_time, line_break=False):
"""Record a time interval since the last timestamp"""
end_time = time.time()
delta = end_time - start_time
if delta < 1:
delta *= 1000
units = "ms"
else:
units = "s"
if line_break:
logg... | 60255615dd2d80e4cdd480ab8090a93665521ceb | 69,316 |
def getConfigurations(identifier: str):
"""Gets the configuration information for the project.
Args:
identifier (str): The directory or sln file or csproj file to parse the output names from.
Returns:
Any: The configurations.
"""
return _dynamicallyDetermine(identifier, 'getConfigurations') | 97807df7e9e229cb828d31d66767b6c9cba02ed6 | 69,317 |
from typing import Dict
from typing import Set
def _get_cone_size_helper(self,
as_obj: AS,
cone_dict: Dict[int, Set[int]]) -> Set[int]:
"""Recursively determines the cone size of an as"""
if as_obj.asn in cone_dict:
return cone_dict[as_obj.asn]
... | be7084bb46759be2955d7d951da8adace99ae5fe | 69,318 |
def build_resnet_fpn_gnbn_lowlevel_gala_cbp10_backbone(cfg, input_shape: ShapeSpec):
"""
Args:
cfg: a detectron2 CfgNode
Returns:
backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`.
"""
bottom_up = build_resnet_gnbn_lowlevel_model_backbone(cfg, input_shape... | 958e2d28ffad1e51b26363632838724dfce52b8b | 69,319 |
def concat_tas_dict_vectorized(frame: pd.DataFrame):
""" Given a DataFrame containing columns for all TAS components, build a Series of the TAS string.
Arguments:
frame: the DataFrame from whose columns to build the TAS display string
Returns:
A series containing TAS displa... | 61644a2ba245c6501a5f175936d777b680503922 | 69,320 |
import torch
def sample_point_labels(instances, point_coords):
"""
Sample point ori_annotation_file_list from ground truth mask given point_coords.
Args:
instances (list[Instances]): A list of N Instances, where N is the number of images
in the batch. So, i_th elememt of the list cont... | ff1d4a02e178e377eb501129d804625f22b434ba | 69,321 |
def get_abstract(pubmed_id, prepend_title=True):
"""Get the abstract of an article in the Pubmed database."""
article = get_article_xml(pubmed_id)
if article is None:
return None
return _abstract_from_article_element(article, prepend_title) | e497c93f0afbb66eed567e741ae44207e7f47c15 | 69,322 |
def get_square_dark_gray_dataset():
"""Create the dark gray square set from the images in the directory.
This test set is not meant for training, just for prediction, thus it doesn't have a split nor
labels.
"""
return _get_images(SQUARE_GRAY_DARK) | 574814aee8271327975d42d765fa0d59732653a8 | 69,323 |
import numpy
def load_spectra_data(json_path, group_label, group_ref):
"""load results from log-linear mutation spectrum analysis
Parameters
----------
json_path : str
path to file produced by spectra command
group_label : str
Factor name, e.g. "group", from which counts are extra... | bc617f4ab101e37b2484994314a4f363b0613321 | 69,324 |
def part_of_speech(input_text):
"""Part of speech tagging of sentence."""
doc = PARSER(input_text)
pos_lst = []
for word in doc:
pos_lst.append((word.text, word.pos_))
return pos_lst | 09a8d31963982322ba7006b743ceb914b27371e7 | 69,325 |
import random
def random_order(ugraph, num_nodes):
"""
return a list of nodes in ugraph in random order
:param ugraph:
:param num_nodes:
:return:
"""
if len(ugraph) is 0 or num_nodes is 0:
return []
random.seed()
return random.sample(ugraph.keys(), num_nodes) | 4bad993f22f6435648e3e0ff30992f1930961dc9 | 69,326 |
import csv
def get_students(csv_file):
"""
:param csv_file: csv file with list of students.\
Each row contains: first_name, last_name, email
:type csv_file: str
:rtype: 2 lists existing_students and new_students [[username, email], ..]
"""
with open(csv_file) as ff:
reader = c... | 01f9a3022d49856604d78129ca943c0defe6307f | 69,327 |
import requests
import re
def get_filenames(url):
"""
The location where the hydat database has the sqlite database
file itself, as well as supporting documentation.
This function returns the filenames of the documentation pdfs
in both languages, as well as the database filename.
Input the url... | 0ccfc46c74d5b89be904dd093a40b82cd4abed5d | 69,328 |
from typing import List
from typing import Tuple
def mock_ORBIT(
params: List[Quantity],
) -> Tuple[float, List[float], List[float], List[List[str]], List[int]]:
"""A function to mock ORBIT behaviour but return fixed non-changing values for
the goal and results
Parameters
----------
params : ... | 3e92eb99b413cfa10cf55eee3265d8ca486f902e | 69,329 |
def count_correl_above(correl_mat,limit):
"""
count numbers of correlation matrix elements above a certain threshold
Args:
correl_mat (array): Matrix correlation values
limit: Threshold for counting
Returns:
(float): Percentage of correlations above the limit
"""
... | 00fb1f0aea268a9333c3741255a2fd7cafcb43ee | 69,330 |
def threshold_gaussian(inputs, params):
"""Given importance scores, calculates stdev cutoff
and thresholds at that pval
Args:
signal: input tensor
pval: the pval threshold
Returns:
out_tensor: output thresholded tensor
"""
# get features and pass rest through
features = i... | f8934c028b9d0f68fc62703e881296e2a5042d36 | 69,332 |
def prepare_mhe(
biorbd_model: biorbd.Model, final_time: float, n_shooting: int, x_ref: np.ndarray, rt_ratio: int, use_noise: bool
):
"""
Prepare to build a blank ocp witch will be update several times
Parameters
----------
biorbd_model: biorbd.Model
biorbd model build with the bioMod
... | 47f5793de2888f4d4f96f4e23e764e38173eed18 | 69,333 |
def map_gazette_to_nodes(df, gazette_data, gazette_column):
"""[summary]maps the given gazette reference data and column to the naptan
nodes data.
Arguments:
df {[geodataframe]} -- [the naptan dataframe]
gazette_data {[gazette reference data]} -- []
gazette_column {[pandas series c... | 41fa9a4286f696d424aa7e7c2b201f1970137339 | 69,334 |
def eval_objectives(objectives, database):
"""Evaluate fitness/cost"""
fitness = np.array([objv(database) for objv in objectives])
return fitness | f73d61079121a84c112040890e1fdc01bd5980ce | 69,335 |
from pathlib import Path
def subtract_dark(
frames : ccdp.ImageFileCollection,
master_dark : CCDData,
output_path: Path
) -> ccdp.ImageFileCollection:
"""
Subtract dark from one of more frames
Parameters
----------
frames : ccdproc.ImageFileCollection
Frames fr... | a035cf28da49dbda1d62b56cf6efdd47c610180d | 69,336 |
import re
def derive_ip_address( cidr_block, delegate, final8 ):
"""
Given a CIDR block string, a delegate number, and an integer
representing the final 8 bits of the IP address, construct and return
the IP address derived from this values. For example, if cidr_block is
10.0.0.0/1... | 8c80d39fd1a86eee4ac61250bebe58760a2170ea | 69,337 |
def make_gaussian_mask_same(roi_point, boxes, sigma, shape):
"""Generates mask targets for each proposal.
Inputs:
roi_point: [NUM_INSTANCES, num_keypoint, 2] of float32. normalized point
boxes: [NUM_INSTANCES, 4] normalized location
Returns: Target masks.
masks: [NUM_INSTANC... | 254b290105fd8e7afe1935a2221ce4282e23f0d7 | 69,338 |
def fix_bad_indent(data_in: tuple) -> tuple:
"""Remove empty lines, bad indentation,...
Args:
data_in: list of lines
Returns:
tuple: cleaned text lines
"""
temp = []
# filter the '' out of data_in and store to temp
for x in data_in:
if x != "":
temp.append... | 1901b7e0aad73ade4ab59f7ab56f81a67fc0ab1f | 69,339 |
def get_cmo():
"""
update the Current Management Object (cmo) to current mbean in wlst.
:return: updated cmo
:raises: PyWLSTException: if a WLST error occurs
"""
_method_name = 'get_cmo'
_logger.entering(class_name=_class_name, method_name=_method_name)
try:
wlst.updateCmo()
... | 29345aeff4a9aebaed22e03edef7c48fa0e33c4f | 69,341 |
import itertools
def expand(elements):
"""Expand Transition Operations."""
transitions = []
# If string
if isinstance(elements, str):
trans_x = TransOperation(elements)
# Expand if there is list argument
if trans_x.has_list_arg:
expanded_trans_list =... | a6b82fe175a571f3778e2f3ec497d5d762ba94bf | 69,342 |
import time
def scanForDevices(scantime=5):
"""
@param scantime: The time (in seconds) to scan for BLE devices in range
@type scantime: float
@return: A DeviceList of any devices found during the scanning process
@rtype: DeviceList
"""
if args.verbose:
print("Starting BLE device sc... | d3e1abce48393bab911cfc49dcd0c45f71be7d10 | 69,343 |
def get_notify():
"""Get the notification."""
return Options.notify | 37777270c41a4735d5b0e9a8189610718252a152 | 69,344 |
def compress_indices(indices: utt.Vector) -> utt.NumpyVector:
"""
Given a vector of group ``indices`` per element, return a vector where the group indices are
consecutive.
If the group indices contain ``-1`` ("outliers"), then it is preserved as ``-1`` in the result.
"""
unique, consecutive = n... | a54566c519d426f80332c3b687bb13d4ef3669b9 | 69,345 |
def input_fn_builder(input_files,
is_training,
drop_remainder,
max_seq_length=32,
max_predictions_per_seq=5,
num_cpu_threads=4,
batch_size=16,
is_prediction=False):
"""Cre... | cb8efce5a64504789692fd52e7a4e2a3f9c9f4e1 | 69,346 |
from typing import Optional
from typing import Dict
def __get_source_file_for_analyzer_result_file(
analyzer_result_file_path: str,
metadata: Optional[Dict]
) -> Optional[str]:
""" Get source file for the given analyzer result file. """
if not metadata:
return None
result_source_files = {... | c40dec03234954bdb6cb43d43e0988d98c6f0bbd | 69,347 |
from typing import Tuple
from typing import List
from pathlib import Path
def synchronize_directories(directory_names: Tuple[str, ...],
dry_run: bool, verbose: bool) -> Tuple[str, ...]:
"""Synchronize some directories.
* Arguments:
* *directory_names* (Tuple[str, ...):
... | 58eb46ec717259c8935407668fe789c708d4df4c | 69,348 |
def _maybe_wrap_runtime_deps_as_build_time_deps(
name,
target,
visibility,
path_in_output = None,
dynamic_path_in_output = False):
"""
If necessary (see "When..."), wraps `target` with a new target named
`name`, in the current project.
Returns `(False, target)` i... | e9b620306e4439d2ed35995a2c2b9f6926d414f2 | 69,349 |
from typing import List
def fitness_proportionate_selection(evaluated_population: List[Eval], random_seed: int = 12345,
num_elites: int = 5) -> List[Parents]:
"""Uses the fitness proportionate selection to select parents from the population.
This selects chromosomes from t... | 0fd80ceff85f3abf4542d36b5279b922171a37b4 | 69,350 |
def make_trans_order_data(busi_type):
"""
交易订单号,仅需网络支付填写
:param busi_type:
:return:
"""
if busi_type == "01":
trans_order = make_random_num(20)
else:
trans_order = ""
return trans_order | 3b47fa672e3b600ed010ef4d62b4cad7a132074c | 69,352 |
import functools
import torch
def get_pc_inpainter(sde, predictor, corrector, inverse_scaler, snr,
n_steps=1, probability_flow=False, continuous=False,
denoise=True, eps=1e-5):
"""Create an image inpainting function that uses PC samplers.
Args:
sde: An `sde_lib.SDE` ... | 3f04f8e38f92026d023547a3aad4ce3a6a2e9a82 | 69,353 |
def _CreateUniqueJobKeyForYamlJob(job):
"""Creates a key from the YAML job instance's attributes passed as input.
Args:
job: An instance of a parsed YAML job object.
Returns:
A tuple of attributes used as a key to identify this job.
"""
retry_params = job.retry_parameters
return (
job.schedul... | 035ef1dff1033e49a3f521dfaf7567bfdd5d92ae | 69,354 |
def THALIANA():
"""Boolean network model of the control of flower morphogenesis in Arabidopsis thaliana
The network is defined in :cite:`Chaos:2006`.
Returns:
(BooleanNetwork)
"""
return BooleanNetwork.from_file(_path + '/thaliana.txt', name="Arabidopsis thaliana", keep_constants=True) | 1eb8f7018035cc5df6eec4124a3a3c76249e2549 | 69,355 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.