content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def retry(freq=3, retry_callback=None):
"""
装饰器,为函数添加此装饰器当函数抛出异常时会对函数重新调用,重新调用次数取决于freq指定的参数
:param freq: 重试次数
:param retry_callback: 重试时回调执行的函数
:return: 原函数返回值
"""
def decorator(func):
def wrap(*args, **kwargs):
now_freq = 1
while True:
tr... | 5,305,400 |
def models(draw, states=None, spread_probs=None, modalities=None):
"""Define search strategy for generating unilateral models"""
graph = draw(graphs(max_size=4))
model = Unilateral(graph)
if states is not None:
num_lnls = len(model.lnls)
model.state = draw(
hynp.arrays(dtype... | 5,305,401 |
def ExecuteCGI(config,
root_path,
handler_path,
cgi_path,
env,
infile,
outfile,
module_dict,
exec_script=ExecuteOrImportScript,
exec_py27_handler=ExecutePy27Handler):
"""Executes Pyth... | 5,305,402 |
def read_line_offset(file, offset):
""" Seek to offset in file, read a line and return the line and new offset """
fp = open(file, "r")
fp.seek(offset, 0)
line = fp.readline()
offset = fp.tell()
fp.close()
return (line, offset) | 5,305,403 |
def show_repos(repos, is_json=False, with_checks=False):
"""Show a list of repositories
:param repos: The list of repository names
:param is_json: Show as json string
"""
if is_json:
print json.dumps(repos)
else:
# Print out one repo name per line
print("Repositories:")
... | 5,305,404 |
def load_config(stream, config_globals):
"""Load a configuration file and generate importer and exporter classes.
Args:
stream: Stream containing config YAML.
config_globals: Dict to use to reference globals for code in the config.
Returns:
BulkloaderEntry
Raises:
InvalidConfiguration: If the... | 5,305,405 |
def endpoint_api_abort():
"""
Serves an API endpoint, non-gracefully emergency aborting what is being done now.
"""
machine_worker_process.kill()
return jsonify({'status': "OK"}) | 5,305,406 |
def setup(app):
"""Do any required setup actions like read config file, create tmp dir, etc."""
pass | 5,305,407 |
def test_get_username_return_none(entered_username, monkeypatch, config):
"""Prompt for username when it's not in keyring."""
class FailKeyring:
@staticmethod
def get_credential(system, username):
return None
monkeypatch.setattr(auth, "keyring", FailKeyring())
assert auth.R... | 5,305,408 |
def radial_integration(IM, radial_ranges=None):
""" Intensity variation in the angular coordinate.
This function is the :math:`\\theta`-coordinate complement to
:func:`abel.tools.vmi.angular_integration`
Evaluates intensity vs angle for defined radial ranges.
Determines the anisotropy parameter fo... | 5,305,409 |
def remove_trips():
"""
Allows for the removal of one or more trip(s) from the list of trips associated
with a particular user.
"""
try:
with open('trips.json') as f:
user_dict = json.load(f)
except FileNotFoundError:
print('\nNo user information has been col... | 5,305,410 |
def CytOpT(xSource, xTarget, labSource, labTarget=None, thetaTrue=None,
method=None, eps=1e-04, nIter=4000, power=0.99,
stepGrad=10, step=5, lbd=1e-04, nItGrad=10000, nItSto=10,
cont=True, monitoring=False, minMaxScaler=True, thresholding=True):
""" CytOpT algorithm. This methods is... | 5,305,411 |
def get_sessions(subj, date=None, one=None):
"""
Download and load in training data for a specfied subject. If a date is given it will load data
from the three (or as many are available) previous sessions up to the specified date, if not it
will load data from the last three training sessions that h... | 5,305,412 |
def crossproduct(first, other=FreeCAD.Vector(0,0,1)):
"""crossproduct(Vector,Vector) - returns the cross product of both vectors.
If only one is specified, cross product is made with vertical axis, thus returning its perpendicular in XY plane"""
if isinstance(first,FreeCAD.Vector) and isinstance(other,Free... | 5,305,413 |
def read_yaml(yaml_file):
"""Read YAML file and handle errors."""
try:
with open(yaml_file) as f:
data = yaml.load(f, Loader=yaml.FullLoader)
except yaml.scanner.ScannerError as e:
raise util.SparvErrorMessage("An error occurred while reading the configuration file:\n" + str(e))
... | 5,305,414 |
def test_wmediumd_path_simple(dev, apdev, params):
"""test a mesh path"""
# 0 and 1 is connected
# 0 and 2 is connected
# 1 and 2 is not connected
# 1 --- 0 --- 2
# | |
# +-----X-----+
# This tests if 1 and 2 can communicate each other via 0.
fd, fn = tempfile.mkstemp()
... | 5,305,415 |
def editProfileView(request):
"""Pulls up an editable profile, with previously inputted
values placed already in the form.
"""
profile_context = {}
form = EditProfile()
submitted = False
if 'username' in request.session and request.method == 'POST':
form = EditProfile(request.POST)
... | 5,305,416 |
def long_short_backtest(
pred,
topk=50,
deal_price=None,
shift=1,
open_cost=0,
close_cost=0,
trade_unit=None,
limit_threshold=None,
min_cost=5,
subscribe_fields=[],
extract_codes=False,
):
"""
A backtest for long-short strategy
:param pred: The trading sig... | 5,305,417 |
def get_ab_path():
""" Find the location of the ab (apache benchmark) program """
for name in ['ab', 'ab2', 'ab.exe', 'ab2.exe']:
path = os.path.join(os.path.split(HTTPD)[0], name)
if os.path.exists(path):
return quote_if_space(path)
return None | 5,305,418 |
def opt_v1(matrix: torch.Tensor, ternary: bool, skip: int = 1) -> torch.Tensor: # type: ignore
"""
Implement the algorithm to find v1 for least squares 2-bit and ternary algorithm.
Args:
matrix: A 2D tensor
ternary: whether to do ternary optimization
skip: increment in potential so... | 5,305,419 |
def calculate_bmi(weight, height):
"""
Calculates BMI given the weight and height as float
"""
bmi = (weight / (height * height)) * 703.0
return bmi | 5,305,420 |
def _jss_shutdown(data):
"""Return a formatted Slack message for the 'JSSShutdown' event.
:param dict data: The ``event`` data from a Jamf Pro webhook.
:returns: Formatted Slack message.
:rtype: dict
"""
text = 'The Jamf Pro web app *{}* has initiated a shutdown.'.format(
data['jssUrl'... | 5,305,421 |
def load_from_json(json_filename: str) -> dict:
"""
Loads data from file of filetype .json and returns the data as a chunk pack (dict),
containing the items from the json file. When loading data from the json file instead of csv,
the chunk pack is simply a dict of the json file itself with every... | 5,305,422 |
def get_table_countrydata(regressors, specification, data):
"""
Can generate the regression table 5
Inputs:
- regressors: array of column names
- specification: dictionary with column names
- data: data frame (regiondata)
Returns: container (pandas data frame with regres... | 5,305,423 |
def get_task_factor(task_name, overrides, override_type, factor):
"""Check for task override and return factor."""
for task_override in overrides.get(override_type, []):
if re.compile(task_override["task"]).match(task_name):
return task_override["factor"]
return factor | 5,305,424 |
def download(ctx, asset_name, key, folder):
"""Download asset implementation.
\b
- algo: the algo and its dependencies
- dataset: the opener script
- objective: the metrics and its dependencies
"""
client = get_client(ctx.obj)
# method must exist in sdk
method = getattr(client, f'do... | 5,305,425 |
def map_list(func: Callable[[Any], Any]=default_function(1)):
"""Applies a function to every element of a list and returns the
resulting list.
:param Callable func: The function to apply.
:input List[Any] data: The input list.
:output List[Any] result: The mapped list.
"""
def inner(data: L... | 5,305,426 |
def argstr(arg): # pragma: no cover
"""
Return string representation of a function argument.
:param object arg: Argument object. Differs between Python versions.
:return: String name of argument.
"""
if isinstance(arg, str):
return arg
if 'id' in arg._fields:
return arg.id
... | 5,305,427 |
def example_alt_alleles_indices(example):
"""Gets an iterable of the alt allele indices in example."""
return deepvariant_pb2.CallVariantsOutput.AltAlleleIndices.FromString(
example.features.feature['alt_allele_indices/encoded']
.bytes_list.value[0]).indices | 5,305,428 |
def task_tweet_todays_job():
"""
Tweets latest jobs from Indeed.
"""
"""
from hub.models import IndeedJob
consumer_key = settings.TWITTER_CONSUMER_KEY
consumer_secret = settings.TWITTER_CONSUMER_SECRET
access_token = settings.TWITTER_ACCESS_TOKEN
access_token_secret = settings.TWITT... | 5,305,429 |
def test_image_equal_clims(texture_format, num_channels):
"""Test image visual with equal clims."""
size = (40, 40)
input_dtype = np.uint8
shape = size + (num_channels,) if num_channels > 0 else size
np.random.seed(0)
data = _make_test_data(shape, input_dtype)
with TestingCanvas(size=size[::... | 5,305,430 |
def variable_step_roots(x0, func, dxmax=1, verbosity=False, root_niter_max_=1000, root_tolerance=1e-6):
"""
"""
itera = True
dx = dxmax
factor = 1
residual = func(x0)
xi = x0 + dx
ii = 1
while itera:
residual0 = residual
residual = func(xi)
if verbosity:
... | 5,305,431 |
def get_credentials():
"""
Retrieve the credentials.
Return:
credentials.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
credential_path = os.path.join(credential_dir, 'gmail-python-email-send.json')
credentials = None
# The fi... | 5,305,432 |
def get_silhouette(model):
"""
Get silhouette score from model
:param model: Topic_Model object
:return: silhouette score
"""
if model.method == 'LDA':
return #LDA dosen't have a silhouette score
lbs = model.cluster_model.labels_
vec = model.vec[model.method]
return... | 5,305,433 |
def prop_force_torque(dh_params, joint_points, end_force_torque, verbose=True, simple=True):
"""Propagates static forces and torques from the end-effector to the base of the manipulator.
Parameters
----------
dh_params: list of lists with D-H-parameters (alpha, a, d, theta)
joint_points: list of sy... | 5,305,434 |
def add_dir_to_zip(z,dirn,zip_top_dir=None):
"""Recursively add a directory and its contents to a zip archive
z is a zipfile.ZipFile object already opened for writing; this
function adds all files in directory dirn and its subdirectories
to z.
If zip_top_dir is not None then this is prepended to t... | 5,305,435 |
async def test_setting_sensor_value_expires_availability_topic(hass, mqtt_mock, caplog):
"""Test the expiration of the value."""
assert await async_setup_component(
hass,
binary_sensor.DOMAIN,
{
binary_sensor.DOMAIN: {
"platform": "mqtt",
"name... | 5,305,436 |
def test_arm_conditional():
"""
Currently, we don't model conditional execution in arm. So we don't allow
conditional execution in arm at this moment.
"""
proj = angr.Project(os.path.join(BIN_DIR, "tests", "armel", "helloworld"))
rop = proj.analyses.ROP(rebase=False)
rop.find_gadgets_single_... | 5,305,437 |
def test_endpoints_3():
"""Functional - Test endpoints: constructive simplify"""
with app.test_client() as client:
data = {
'resource': 'test_data/geo.csv',
'response': 'prompt',
'geom': 'WKT',
'crs': 'EPSG:3857',
'tolerance': 1.
}
... | 5,305,438 |
def num_zeros_init(num):
"""
Counts the number of zeros at the beginning
of the number 'num'.
"""
iszero = True
num_zeros = 0
i = 0
while iszero == True and (i != len(num)-1):
if num[i] == "0":
num_zeros += 1
... | 5,305,439 |
def getargspec(callable_):
"""
Return an Argspec for any callable object
:param callable_: a callable object
:type callable_: ``Callable``
:return: argspec for the callable
:rtype: ``ArgSpec``
"""
if not callable(callable_):
raise ValueError("{} is not callable".format(callable... | 5,305,440 |
def show_menu():
"""
菜单显示
:return:
"""
print("*" * 30)
print("名片管理系统V4.0")
print("")
print("1.创建名片")
print("2.显示名片")
print("3.查询名片")
print("4.存储名片")
print("5.导入名片")
print("")
print("0.退出系统")
print("*" * 30) | 5,305,441 |
def pmat76(date1, date2):
"""
Wrapper for ERFA function ``eraPmat76``.
Parameters
----------
date1 : double array
date2 : double array
Returns
-------
rmatp : double array
Notes
-----
The ERFA documentation is below.
- - - - - - - - - -
e r a P m a t 7 6
... | 5,305,442 |
def getresulthandle(whichresult, options=None):
"""get the filehandle of the result"""
filepath = options2filename(whichresult, options=options)
if whichresult in ("htm", "sql"):
return getfilehandle(filepath, mode="rb")
else:
return getfilehandle(filepath) | 5,305,443 |
def on_pspuser_saved(sender, instance, created, **kwargs):
"""
When a PSP user is saved, we check to see if they are associatde with the dwolla system ( dwolla_url )
if not, we will create a dwolla user
Args:
sender (customer.models.PSPUser): the model class that sends this event
instan... | 5,305,444 |
def downsample(img, scale, border='REFLECT'):
"""Bicubical downsample via **CONV2D**. Using PIL's kernel.
Args:
img: a tf tensor of 2/3/4-D.
scale: n or 1/n. `n` must be integer >= 2.
border: padding mode. Recommend to 'REFLECT'.
"""
kernel, s = weights_downsample(scale)
if s == 1:
return img... | 5,305,445 |
def test_hasher_1_case_2():
"""Test hasher_1 case_2"""
case_dict = test_hasher_1()
test_case_hash = "yn5tj7bteln4c5o4mtul7yvnq3pwu6dpmipcof4pwcbsd3avvn7a"
assert case_dict.get("urn_hash") == test_case_hash | 5,305,446 |
def getDistance(sensor):
"""Return the distance of an obstacle for a sensor."""
# Special case, when the sensor doesn't detect anything, we use an
# infinite distance.
if sensor.getValue() == 0:
return float("inf")
return 5.0 * (1.0 - sensor.getValue() / 1024.0) | 5,305,447 |
def drop_tables(ctx):
""" Alias for 'alembic downgrade base'.
Downgrade to no database tables
"""
current_session = get_current_session()
command.downgrade(setup_alembic_config(url=current_session.url),
revision='base', sql=False, tag=None) | 5,305,448 |
def test_parents_not_found_error(cli, unknown_uuid):
"""Tests the method ``parents`` of the class ``InventoryClient`` with an
unknown ``vid``."""
with pytest.raises(NotFoundError, match=f'.*{unknown_uuid}.*') as exc_info:
cli.parents(unknown_uuid)
assert exc_info.value.name == unknown_uuid | 5,305,449 |
def fit_svmrbf(X_train, y_train, seed=1):
"""
Fit an SVM-RBF with pre-selected hyperparameters.
"""
clf = SVC(C=10, gamma=0.01, kernel="rbf", probability=True, random_state=seed)
clf.fit(X_train, y_train)
return clf | 5,305,450 |
def subtract(
x1: ArrayLike,
x2: ArrayLike,
out: Optional[Union[ndarray, Tensor]] = None,
*,
where: Mask = True,
dtype: DTypeLikeReals = None,
constant: Optional[bool] = None,
) -> Tensor: # pragma: no cover
"""Subtract the arguments element-wise.
This docstring was adapted from th... | 5,305,451 |
def path_generator(graph, max_visits=1):
"""Adapted from
https://networkx.org/documentation/stable/_modules/networkx/algorithms/\
simple_paths.html#all_simple_paths
Can be improved but trying to catch up on the puzzles from a few days
behind!
"""
original_max_visits = max_visits
ta... | 5,305,452 |
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Snapcast platform."""
host = config.get(CONF_HOST)
port = config.get(CONF_PORT, CONTROL_PORT)
platform = entity_platform.current_platform.get()
platform.async_register_entity_service(SERVICE_SNAPSH... | 5,305,453 |
def test_path_and_query_parameters(
arg1,
arg2,
):
"""
Use same arg name as the one in path for receiving path args
For those args which names not matched path arg names, will be parsed as query parameter
```python
from django_mini_fastapi import Path
@api.get('/test_path_and_query_par... | 5,305,454 |
def get_residue_count(array):
"""
Get the amount of residues in an atom array (stack).
The count is determined from the `res_id` and `chain_id` annotation.
Each time the residue ID or chain ID changes,
the count is incremented. Special rules apply to hetero residues.
Parameters
---... | 5,305,455 |
def build_output_actions(acl_table, output_dict):
"""Implement actions to alter packet/output."""
output_actions = []
output_port = None
ofmsgs = []
# rewrite any VLAN headers first always
vlan_actions = rewrite_vlan(acl_table, output_dict)
if vlan_actions:
output_actions.extend(vlan... | 5,305,456 |
def test_weave_classification_reload():
"""Test weave model can be reloaded."""
np.random.seed(123)
tf.random.set_seed(123)
n_tasks = 1
# Load mini log-solubility dataset.
featurizer = dc.feat.WeaveFeaturizer()
tasks = ["outcome"]
mols = ["CC", "CCCCC", "CCCCC", "CCC", "COOO", "COO", "OO"]
n_samples ... | 5,305,457 |
def _bond_capacities(rgr):
""" the number of electron pairs available for further pi-bonding, by bond
"""
atm_unsat_vlc_dct = _atom_unsaturated_valences(rgr)
def _pi_capacities(bnd_key):
return min(map(atm_unsat_vlc_dct.__getitem__, bnd_key))
bnd_keys = list(_bond_keys(rgr))
bnd_caps =... | 5,305,458 |
def GENERIC_MAX(segment_pattern, lenv=None, renv=None):
"""Takes the regex pattern for segments being examined for
deletion, and a pair of lists indicating their deletion environment,,
and returns a function that will count how many times a segment
of that class is deleted from an input to an output str... | 5,305,459 |
def find_group_delay(attrs_dict):
"""Determine group delay from tables
Args:
attrs_dict (dict): dictionary of topspin acquisition parameters
Returns:
float: Group delay. Number of points FID is shifted by DSP. The ceiling of this number (group delay rounded up) is the number of points shou... | 5,305,460 |
def run_multiple_processes(exp: Experiment, instances_ids: list,
distances: dict, times: dict, matchings: dict,
printing: bool, t) -> None:
""" Single thread for computing distances """
for instance_id_1, instance_id_2 in instances_ids:
if t == 0 and printing... | 5,305,461 |
def quora_data_prep(data_path, save_path=None, split_perc=0.3):
"""Prepare data related to Quora dataset.
Args:
root_path (str): Path of dataset root.
info_prefix (str): The prefix of info filenames.
version (str): Dataset version.
out_dir (str): Output directory of the groundtr... | 5,305,462 |
def decompositions_bis(n : int) -> List[Tuple[int, int, int]]:
"""Précondition : n >= 0
Retourne la liste des triangles sur l'intervalle [1;n]."""
return [(i, j, i+j) for i in range(1, n+1)
for j in range(1, n+1) if i+j<=n] | 5,305,463 |
def check_subs(client):
""" Checks that all Subscriptions have been received"""
wcount = 0
while wcount < 10:
for t in client.topic_ack:
wcount += 1
if t[2] == 0:
logging.info("subscription to " + str(t[0]) + " not acknowledged")
break
... | 5,305,464 |
async def test_unload_entry(opp):
"""Test being able to unload an entry."""
mock_config = {HMIPC_AUTHTOKEN: "123", HMIPC_HAPID: "ABC123", HMIPC_NAME: "name"}
MockConfigEntry(domain=HMIPC_DOMAIN, data=mock_config).add_to_opp(opp)
with patch("openpeerpower.components.homematicip_cloud.HomematicipHAP") as... | 5,305,465 |
def preprocess(vocab, data_fp):
"""
Preprocess data
"""
orig = []
prep = []
# Read data
with open(data_fp, "r") as data_file:
for cnt, word in enumerate(data_file):
# End of sentence
if not word.split():
orig.append(word.strip())
... | 5,305,466 |
def create_port(port_data,
verify_port=True,
conn=None):
"""
:param port_data: <dict> dict matching Port()
:param verify_port: <bool>
:param conn: <rethinkdb.DefaultConnection>
:return: <dict> rethinkdb insert response value
"""
from .interfaces import create... | 5,305,467 |
def align(
wav_path: str,
text: str,
model_path: typing.Optional[typing.Union[Path, str]] = None,
julius_path: typing.Union[Path, str] = "/usr/bin/julius",
) -> typing.List[typing.Tuple[int, int, str]]:
"""Get the forced alignment from the given wav file and pronunciation.
Args:
wav_pat... | 5,305,468 |
def read_nrattle_ctl(fpath):
"""Read an nrattle control file."""
lines = list(fpath.open())
lines = [line for line in lines if line[0] != "!"]
d = {k: lines.pop(0) for k in ["revision", "prefix"]}
d["freq_count"], d["freq_max"] = split_line(lines.pop(0), [int, float])
d["out_depth"] = split_lin... | 5,305,469 |
def paragraphs(text):
"""Split a given text into paragraphs.
Args:
text (str)
Returns:
iterator
"""
return filter(
lambda line: len(unspace(line)) > 0,
text.split("\n")) | 5,305,470 |
def test_cosine_similarity_init1():
"""test_cosine_similarity_init1"""
with pytest.raises(ValueError):
CosineSimilarity(similarity="4") | 5,305,471 |
def init_multicomponent_source(
sky_coord,
frame,
observations,
obs_idx=0,
flux_percentiles=None,
thresh=1.0,
symmetric=True,
monotonic=True,
):
"""Initialize multiple components
See `MultiComponentSource` for a description of the parameters
"""
try:
iter(observat... | 5,305,472 |
def get_document(args):
"""
Метод для получения данных о документах
:param args:
:return:
"""
provider = Provider()
answer = provider.get_document(args)
return answer | 5,305,473 |
def convert_not_constraint(converter: 'pcc.ConstraintConverter',
constraint: pamlt.Not):
"""
Convert a paml_time.NotConstraint into the pysmt equivalent
"""
clause = converter.convert_constraint(constraint.constrained_elements)
return pysmt.shortcuts.Not(clause) | 5,305,474 |
def authenticate(request):
"""
GET: Will return the JSON authenticated user if any, otherwise the login HTML form.
POST: Same, but will try to authenticate the user with the provided data.
"""
return ajax_authenticate(request, from_api=True) | 5,305,475 |
def parse_jndi_proto_and_path(jndi: str, jndi_parts: JNDIParts) -> JNDIParts:
"""Split JNDI string into components."""
try:
colon_split = jndi.split(":")
protocol: str = colon_split[1]
slash_split: List[str] = jndi.split("/")
host_port = slash_split[2]
path: str = ""
... | 5,305,476 |
def init_model(config, net, optimizer=None):
"""
load model from checkpoint or pretrained_model
"""
checkpoints = config.get('checkpoints')
if checkpoints and optimizer is not None:
assert os.path.exists(checkpoints + ".pdparams"), \
"Given dir {}.pdparams not exist.".form... | 5,305,477 |
def vap_volume(temp,pres):
"""Calculate water vapour specific volume.
Calculate the specific volume of water vapour using the IAPWS-97
formulation.
:arg float temp: Temperature in K.
:arg float pres: Pressure in Pa.
:returns: Specific volume in m3/kg.
"""
v = vap_g(0,1,temp,pre... | 5,305,478 |
def repair_rate(f, params):
"""
Default unscaled repair rate (no Gamma0).
Uses gamman = params[1], R = params[2]
"""
return np.exp(-params[1]*f)/params[2] | 5,305,479 |
def create_empty_folder_setup(fold, name, author=None, description=None, url=None, durl=None, version="0.1",
subversion="0"):
"""
Creates a quick empty shell for a new project.
@param fold location
@param name name of the project
@param aut... | 5,305,480 |
def assert_approx_equal(
actual: numpy.float64,
desired: float,
significant: int,
err_msg: Literal["fail forp=0.200000"],
):
"""
usage.scipy: 1
"""
... | 5,305,481 |
def record_apply(domain_name):
"""
example jdata: {u'record_ttl': u'1800', u'record_type': u'CNAME', u'record_name': u'test4', u'record_status': u'Active', u'record_data': u'duykhanh.me'}
"""
#TODO: filter removed records / name modified records.
try:
jdata = request.json
submitted... | 5,305,482 |
def Get_Items(filename):
"""Convert plain text to class string"""
L = []
with open(filename, 'r') as file:
items = file.readlines()
for line in items:
L.append(line[:-1])
return L | 5,305,483 |
def deprecated(message):
"""Deprecated function decorator."""
def wrapper(fn):
def deprecated_method(*args, **kargs):
warnings.warn(message, DeprecationWarning, 2)
return fn(*args, **kargs)
# TODO: use decorator ? functools.wrapper ?
deprecated_method.__name__ = ... | 5,305,484 |
def circles_intersection(x_a, y_a, r_a, x_b, y_b, r_b):
"""
Returns the point of intersection of two circkes
:param x_a: x coordinate of the center of first circle
:param y_a: y coordinate of the center of first circle
:param r_a: radius of first circle
:param x_b: x coordinate of the center of ... | 5,305,485 |
def doxy_coverage_badge(filepath):
"""..."""
with open(filepath) as f:
linelist = f.readlines()
text = "doxy-coverage"
for l in reversed(linelist):
match = re.match(DOXY_COVERAGE_PATTERN, l)
if match:
value = int(match.group('value'))
break
... | 5,305,486 |
def readShapefileTable(shapefile):
"""
read in the datatable captured within the shapefile properties
shapefile: (dir) a path to the ESRI .shp shapefile
"""
#cent_df = gpd.read_file(shapefile)
shp = fiona.open(shapefile)
centroid = [eachpol['properties'] for eachpol in shp]
cent_df ... | 5,305,487 |
def update_dict(d, defaultd):
"""Update d with key,value pairs in defaultd if the key is not in d.
If the value is the empty string then that entry is removed from
the dictionary"""
for key, value in defaultd.iteritems():
if key not in d:
d[key] = value
elif value == '':
... | 5,305,488 |
def missing_translation(lang, message=None):
"""Return an explanation if a language is not supported at all
or if the translation is missing, to be used as a message for
a ValuError which is raised in that case.
"""
if lang not in SUPPORTED:
return 'Language {0!r} not supported!'.format(lang... | 5,305,489 |
def _CheckSuiteShouldBeDeprecated(suite):
"""Checks if a suite should be deprecated."""
# If this is a suite, check if we can deprecate the entire suite
if len(suite.key.id().split('/')) == 3:
# Check whether the test suite now contains only deprecated tests, and
# if so, deprecate it too.
all_depreca... | 5,305,490 |
def get_grade_map():
"""
Defines a mapping of Fontainebleau grades to integer values
"""
grade_map = {
'6B': 0, # V4
'6B+': 0, # V4
'6C': 1, # V5
'6C+': 1, # V5
'7A': 2, # V6
'7A+': 3, # V7
'7B': 4, # V8
'7B+': 4, # V8
'7C': 5, ... | 5,305,491 |
def gaussian_kl_divergence(mean, ln_var, reduce='sum'):
"""Computes the KL-divergence of Gaussian variables from the standard one.
Given two variable ``mean`` representing :math:`\\mu` and ``ln_var``
representing :math:`\\log(\\sigma^2)`, this function calculates
the KL-divergence in elementwise manner... | 5,305,492 |
def conflict_error(e):
"""Flask error handler for Conflict exceptions"""
return json_error(409, "Conflict", str(e)) | 5,305,493 |
def print_error(msg):
"""
Prints the given message to 'stderr'.
"""
import sys
print >>sys.stderr, msg | 5,305,494 |
def get_topics(input_file, judgements):
"""
Reads topics in the NTCIR-10 Math, NTCIR-11 Math-2, and NTCIR-12 MathIR format from an XML file.
Note
----
Topics are returneed in the order in which they appear in the XML file.
Parameters
----------
input_file : Path
The path to an ... | 5,305,495 |
def get_target_oligo_2(left_pos, right_pos, genome, homology = 90, attB_dir = '+', attB_fwd_seq = 'ggcttgtcgacgacggcggtctccgtcgtcaggatcat', attB_lock = False, verbose = False):
"""
Given a set of parameters, get an ORBIT oligo that targets the lagging strand.
Left and right positions are absolute genomic c... | 5,305,496 |
def meta_testing(test_dataset,
model,
epochs=10,
episodes=1000,
ways=5,
shots=5,
query_num=15):
"""
Implementation of 'ProtoNet(Prototypical Networks for Few-shot Learning)[1]', meta-testing.
This function ... | 5,305,497 |
def rebuild_rm_existing_rec():
"""
Remove existing records to prepare for the insert of new data.
Args:
None
Returns:
None
"""
connection = pymysql.connect(host=DB_SRV,
user=DB_USR,
password=DB_PWD,
... | 5,305,498 |
def check_article(entry, try_fix):
"""Check and fix article entries."""
if 'journal' not in entry:
err_message(entry, "Journal title is missing.")
# TODO try to recover from ISSN or paper name
else:
journal = entry['journal']
if journal == 'CoRR' or 'arXiv' in journal:
... | 5,305,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.