content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_sanitize_callable_params():
"""Callback function are not serializiable.
Therefore, we get them a chance to return something and if the returned type is not accepted, return None.
"""
opt = "--max_epochs 1".split(" ")
parser = ArgumentParser()
parser = Trainer.add_argparse_args(parent_p... | 5,335,600 |
def get_url(bucket_name, filename):
"""
Gets the uri to the object.
"""
client = storage.Client()
bucket = client.bucket(bucket_name)
blob = bucket.blob(filename)
url = blob.public_url
if isinstance(url, six.binary_type):
url = url.decode('utf-8')
return url | 5,335,601 |
def distance():
"""
Return a random value of FRB distance,
choosen from a range of observed FRB distances.
- Args: None.
- Returns: FRB distance in meters
"""
dist_m = np.random.uniform(6.4332967e24,1.6849561e26)
return dist_m | 5,335,602 |
def p10k(n, empty="-"):
"""
Write number as parts per ten thousand.
"""
if n is None or np.isnan(n):
return empty
elif n == 0:
return "0.0‱"
elif np.isinf(n):
return _("inf") if n > 0 else _("-inf")
return format_number(10000 * n) + "‱" | 5,335,603 |
def output_file(filename: str, *codecs: Codec, **kwargs: Any) -> Output:
"""
A shortcut to create proper output file.
:param filename: output file name.
:param codecs: codec list for this output.
:param kwargs: output parameters.
:return: configured ffmpeg output.
"""
return Output(outpu... | 5,335,604 |
def selftest_validate_resilient_circuits_installed(attr_dict, **_):
"""
selftest.py validation helper method.
Validates that 'resilient-circuits' is installed in the env
and confirms that the version is >= constants.RESILIENT_LIBRARIES_VERSION
:param attr_dict: (required) dictionary of attributes d... | 5,335,605 |
def convert_topology(topology, model_name, doc_string, target_opset,
channel_first_inputs=None,
options=None, remove_identity=True,
verbose=0):
"""
This function is used to convert our Topology object defined in
_parser.py into a ONNX model (typ... | 5,335,606 |
def _get_intermediates(func_graph):
"""Returns all tensors in `func_graph` that should be accumulated."""
# We currently accumulate output tensors of most ops in the function and rely
# on the pruning pass to get rid of the unused accumulators at runtime.
# However, this can bloat the GraphDef and make debuggin... | 5,335,607 |
def multivariate_logrank_test(event_durations, groups, event_observed=None,
alpha=0.95, t_0=-1, suppress_print=False, **kwargs):
"""
This test is a generalization of the logrank_test: it can deal with n>2 populations (and should
be equal when n=2):
H_0: all event series ... | 5,335,608 |
def ae(y, p):
"""Absolute error.
Absolute error can be defined as follows:
.. math::
\sum_i^n abs(y_i - p_i)
where :math:`n` is the number of provided records.
Parameters
----------
y : :class:`ndarray`
One dimensional array with ground truth values.
p : :c... | 5,335,609 |
def create_masks_from_plane(normal, dist, shape):
"""
Create a binary mask of given size based on a plane defined by its
normal and a point on the plane (in voxel coordinates).
Parameters
----------
dist: Distance of the plane to the origin (in voxel coordinates).
normal: Normal of the plan... | 5,335,610 |
def untokenize(tokens: List[str], lang: str = "fr") -> str:
"""
Inputs a list of tokens output string.
["J'", 'ai'] >>> "J' ai"
Parameters
----------
lang : string
language code
Returns
-------
string
text
"""
d = MosesDetokenizer(lang=lang)
text: str = ... | 5,335,611 |
def RSS_LABEL_TO_DIR(label_, is_html_):
"""Return the directory path to store URLs and HTML downloaded from RSS
@param label_: the RSS label being crawled
@param is_html_: True to return HTML directory and FALSE to return URLs directory
"""
bottom_dir_ = '/'.join(label_.split('-'))
ret_ =... | 5,335,612 |
def unwrap_cachable(func):
"""
Converts any HashableNodes in the argument list of a function into their standard node
counterparts.
"""
def inner(*args, **kwargs):
args, kwargs = _transform_by_type(lambda hashable: hashable.node, HashableNode,
*args,... | 5,335,613 |
def write_config(config, config_template, config_path):
"""Writes a new config file based upon the config template.
:param config: A dict containing all the key/value pairs which should be
used for the new configuration file.
:param config_template: The config (jinja2-)template.
:par... | 5,335,614 |
def tuples_to_full_paths(tuples):
"""
For a set of tuples of possible end-to-end path [format is:
(up_seg, core_seg, down_seg)], return a list of fullpaths.
"""
res = []
for up_segment, core_segment, down_segment in tuples:
if not up_segment and not core_segment and not down_segment:
... | 5,335,615 |
def _fileobj_to_fd(fileobj):
"""Return a file descriptor from a file object.
Parameters:
fileobj -- file object or file descriptor
Returns:
corresponding file descriptor
Raises:
ValueError if the object is invalid
"""
if isinstance(fileobj, int):
fd = fileobj
else:
... | 5,335,616 |
def request_changes_pull_request(pull_request=None, body_or_reason=None):
"""
:param pull_request:
:param body_or_reason:
:return:
"""
if not pull_request:
raise ValueError("you must provide pull request")
if not body_or_reason:
raise ValueError("you must provide request ch... | 5,335,617 |
def handle(
func: Callable,
exception_type: Union[Type[Exception], Tuple[Type[Exception]]],
*args,
**kwargs
):
"""
Call function with errors handled in cfpm's way.
Before using this function, make sure all of func's errors are known and
can exit saftly after an error is raised whithout ... | 5,335,618 |
def hrnetv2_w32(**kwargs):
"""
HRNetV2-W32 model from 'Deep High-Resolution Representation Learning for Visual Recognition,'
https://arxiv.org/abs/1908.07919.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, defaul... | 5,335,619 |
def medicare_program_engagement():
"""
Produces a wide dataset at the NPI level that shows when a provider entered
and exited the three different medicare databases: Part B, Part D, and
Physician Compare
"""
from .utils.globalcache import c
partd = part_d_files(summary=True,
... | 5,335,620 |
def _is_bumf(value):
"""
Return true if this value is filler, en route to skipping over empty lines
:param value: value to check
:type value: object
:return: whether the value is filler
:rtype: bool
"""
if type(value) in (unicode, str):
return value.strip() == ''
return val... | 5,335,621 |
def pos_tag(words, engine="unigram", corpus="orchid"):
"""
Part of Speech tagging function.
:param list words: a list of tokenized words
:param str engine:
* unigram - unigram tagger (default)
* perceptron - perceptron tagger
* artagger - RDR POS tagger
:param str corpus:
... | 5,335,622 |
def derive(control):
"""
gui.derive will be removed after mGui 2.2; for now it's going to issue a deprecation warning and call `wrap()`
"""
warnings.warn("gui.derive() should be replaced by gui.wrap()", PendingDeprecationWarning)
return wrap(control) | 5,335,623 |
def test_which_set():
"""Test which_set selector."""
skip_if_no_sklearn()
# one label
this_yaml = test_yaml_which_set % {'which_set': 'train'}
trainer = yaml_parse.load(this_yaml)
trainer.main_loop()
# multiple labels
this_yaml = test_yaml_which_set % {'which_set': ['train', 'test']}
... | 5,335,624 |
def harmonizeClassifiedSamples(species,reference_exp_file, query_exp_file, classification_file,fl=None):
"""
The goal of this function is to take LineageProfilerIterative classified samples to a reference matrix,
combine the reference matrix and the query matrix at the gene symbol level, retain the origi... | 5,335,625 |
def convert_to_reduced_row_echelon_form(matrix):
"""
Runs the Gaussian elimination algorithm on the provided matrix, which
converts it into an equivalent reduced-row echelon form. This makes it
much easier to solve. Note that this will be a "mod-2" version of the
Gaussian elimination algorithm, sinc... | 5,335,626 |
def test_backward_for_binary_cmd_with_inputs_of_different_dim_and_autograd(cmd, shapes):
"""
Test .backward() on local tensors wrapped in an AutogradTensor
(It is useless but this is the most basic example)
"""
a_shape, b_shape = shapes
a = torch.ones(a_shape, requires_grad=True)
b = torch.o... | 5,335,627 |
def hex_to_base64(hex_):
""" Converts hex string to base64 """
return base64.b64encode(bytes.fromhex(hex_)) | 5,335,628 |
def test_no_match_context(current_context):
"""A context doesn't match if it is not "within" the pattern context."""
assert not adstrangerlib._match_context('foo', current_context) | 5,335,629 |
def p_rareopt(p):
"""rareopt : TOP_OPT EQ value"""
p[0] = ParseTreeNode('EQ', raw='assign')
opt_node = ParseTreeNode('OPTION', raw=p[1])
if opt_node.raw in boolean_options:
p[3].nodetype = 'BOOLEAN'
opt_node.values.append(p[3])
p[0].add_child(opt_node)
p[0].add_child(p[3]) | 5,335,630 |
def dt2iso(orig_dt):
"""datetime to is8601 format."""
return timeutils.isotime(orig_dt) | 5,335,631 |
def catalog(access_token, user_id, query=None): # noqa: E501
"""Query the list of all the RDF graphs' names (URIs) and the response will be JSON format.
# noqa: E501
:param access_token: Authorization access token string
:type access_token: dict | bytes
:param user_id: the ID of the organiz... | 5,335,632 |
def _make_chrome_policy_json():
"""Generates the json string of chrome policy based on values in the db.
This policy string has the following form:
{
"validProxyServers": {"Value": map_of_proxy_server_ips_to_public_key},
"enforceProxyServerValidity": {"Value": boolean}
}
Returns:
A json string ... | 5,335,633 |
def get_rgb_color(party_id):
"""Get RGB color of party."""
if party_id not in PARTY_TO_COLOR_OR_PARTY:
return UNKNOWN_PARTY_COLOR
color_or_party = PARTY_TO_COLOR_OR_PARTY[party_id]
if isinstance(color_or_party, tuple):
return color_or_party
return get_rgb_color(color_or_party) | 5,335,634 |
def view_application(application_id):
"""Views an application with ID.
Args:
application_id (int): ID of the application.
Returns:
str: redirect to the appropriate url.
"""
# Get user application.
application = ApplicationModel.query.filter_by(id=application_id).first()
is... | 5,335,635 |
def test_create_state_space_vs_specialized_kw97(model):
"""State space reproduces invariant features of the kw97 state space."""
params, options = process_model_or_seed(model)
optim_paras, options = process_params_and_options(params, options)
# Create old state space arguments.
n_periods = options[... | 5,335,636 |
def build_save_containers(platforms, bucket) -> int:
"""
Entry point to build and upload all built dockerimages in parallel
:param platforms: List of platforms
:param bucket: S3 bucket name
:return: 1 if error occurred, 0 otherwise
"""
if len(platforms) == 0:
return 0
platform_r... | 5,335,637 |
def make_map(
shape_df,
df,
dates,
adm_key,
cols,
output_dir,
title_prefix=None,
log_scale=True,
colormap="Reds",
outline_df=None,
):
"""Create a map for each date and column.
Parameters
----------
shape_df : geopandas.GeoDataFrame
Shapefile information a... | 5,335,638 |
def get_object_record(obj_key):
"""
Query the object's record.
Args:
obj_key: (string) The key of the object.
Returns:
The object's data record.
"""
record = None
model_names = OBJECT_KEY_HANDLER.get_models(obj_key)
for model_name in model_names:
try:
... | 5,335,639 |
def diff_cars(c1, c2):
"""
diffs two cars
returns a DiffSet containing DiffItems that tell what's missing in c1
as compared to c2
:param c1: old Booking object
:param c2: new Booking object
:return: DiffSet (c1-c2)
"""
strategy = Differ.get_strategy(CAR_DIFF_STRATEGY)
return str... | 5,335,640 |
def manage_playlists(user):
"""
List, add, and remove playlists.
Parameters
----------
user : user object
Object containing all user data.
"""
user.printPlaylists()
if cutie.prompt_yes_or_no('Would you like to remove a playlist?'):
user.removePlaylists()
if cutie.pr... | 5,335,641 |
def find_table_defs(sql_lines):
"""
Find the table definitions in the given SQL input (a sequence of
strings). Yield each complete table definition as a string.
Naïvely assumes that "create table" starts a table definition, that
");" ends it, that each of the previous occur on a single line, and
... | 5,335,642 |
def dist_env():
"""
Return a dict of all variable that distributed training may use.
NOTE: you may rewrite this function to suit your cluster environments.
"""
trainer_id = int(os.getenv("PADDLE_TRAINER_ID", "0"))
num_trainers = 1
training_role = os.getenv("PADDLE_TRAINING_ROLE", "TRAINER")
... | 5,335,643 |
def imsplot_tensor(*imgs_tensor):
"""
使用matplotlib.pyplot绘制多个tensor类型图片
图片尺寸应为(bn, c, h, w)
或是单个图片尺寸为(1, c, h, w)的序列
"""
count = min(8, len(imgs_tensor))
if(count==0): return
col = min(2, count)
row = count//col
if(count%col > 0):
row = row + 1
for i in range(count):
... | 5,335,644 |
def main(request, response):
"""Helper handler for Beacon tests.
It handles two forms of requests:
STORE:
A URL with a query string of the form 'cmd=store&sid=<token>&tidx=<test_index>&tid=<test_name>'.
Stores the receipt of a sendBeacon() request along with its validation result, returni... | 5,335,645 |
def set_unique_postfix(env_patch, default_instances):
"""
Generate a unique postfix and add it to an instance name to avoid 409 HTTP error
in case of the instance name was already used during last week
"""
unique_postfix = f'-{uuid.uuid4().hex[:5]}' # generate 5 digits unique postfix
for instan... | 5,335,646 |
def calc_chi2(model, dof=None):
"""
Calculate chi-square statistic.
Parameters
----------
model : Model
Model.
dof : int, optional
Degrees of freedom statistic. The default is None.
Returns
-------
tuple
chi2 statistic and p-value.
"""
if dof is Non... | 5,335,647 |
def QuadraticCommandAddControl(builder, control):
"""This method is deprecated. Please switch to AddControl."""
return AddControl(builder, control) | 5,335,648 |
def list_(ctx, show_train):
"""Show information about all builds"""
for build in ctx.obj['get_fl33t_client']().list_builds():
click.echo(build)
if show_train:
click.echo('Train:')
click.echo(' - {}'.format(build.train)) | 5,335,649 |
def test_max(non_square_gamma_tensor: IGT) -> None:
"""Test the max operator default behaviour (no args)"""
output = non_square_gamma_tensor.max()
original_values = non_square_gamma_tensor._values()
# Ensure both of these have the same shapes to begin with
assert non_square_gamma_tensor.shape == or... | 5,335,650 |
def authenticated_api(username, api_root=None, parser=None):
"""Return an oauthenticated tweety API object."""
auth = tweepy.OAuthHandler(settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET)
try:
user = User.objects.get(username__iexact=username)
sa... | 5,335,651 |
def stop_flops_count(self) -> None:
"""
A method that will be available after add_flops_counting_methods() is called
on a desired net object.
Stops computing the mean flops consumption per image.
Call whenever you want to pause the computation."""
remove_batch_counter_hook_function(self)
se... | 5,335,652 |
def run(shop):
"""
Go shopping.
"""
# This would possibly not do anything, as it runs when even when using
# help on an option.
print('Run')
print('shop: {0}\n'.format(shop)) | 5,335,653 |
def get_model_header(fpath):
"""
:param fpath:
:return:
"""
with gz.open(fpath, 'rt') as modelfile:
header = modelfile.readline().strip().strip('#').split()
return header | 5,335,654 |
def _parse_vertex(vertex_row):
"""Parses a line in a PLY file which encodes a vertex coordinates.
Args:
vertex_row: string with vertex coordinates and color.
Returns:
2-tuple containing a length-3 array of vertex coordinates (as
floats) and a length-3 array of RGB color values (as ints between 0
... | 5,335,655 |
def clean_tag(tag):
"""clean up tag."""
if tag is None:
return None
t = tag
if isinstance(t, list):
t = t[0]
if isinstance(t, tuple):
t = t[0]
if t.startswith('#'):
t = t[1:]
t = t.strip()
t = t.upper()
t = t.replace('O', '0')
t = t.replace('B', '8... | 5,335,656 |
def massM2(param):
""" Mass term in the neutrino mass basis.
@type param : PhysicsConstants
@param param : set of physical parameters to be used.
@rtype : numpy array
@return : mass matrix in mass basis.
"""
M2 = np.zeros([param.numneu,param.numneu],complex)... | 5,335,657 |
def remove_persistent_volume_claim(name, mount_path):
"""
Remove a persistent volume claim in the default notebook server.
Parameters
----------
name : str
mount_path : str
"""
load_kube_config()
v1 = client.CoreV1Api()
custom_api = client.CustomObjectsApi(api_client=ApiClientFor... | 5,335,658 |
def get_input_data(train_file_path='train.json', train=True):
"""Retrieves training (X) and label (y) matrices. Note that this can take a few seconds to run.
Args:
train_file_path is the path of the file containing training data.
Returns:
A tuple containing the X training matrix in the fir... | 5,335,659 |
def getitimer(*args, **kwargs): # real signature unknown
""" Returns current value of given itimer. """
pass | 5,335,660 |
def test_rebase_error():
""" Run 'git up' with a failing rebase """
os.chdir(repo_path)
from PyGitUp.gitup import GitUp
gitup = GitUp(testing=True)
gitup.run() | 5,335,661 |
def dice_coef(y_true, y_pred):
"""
:param y_true: the labeled mask corresponding to a mammogram scan
:param y_pred: the predicted mask of the scan
:return: A metric that accounts for precision and recall
on the scale from 0 - 1. The closer to 1, the
better.
Dice = 2 * (... | 5,335,662 |
def linmsg(x, end_pts_msg=None, max_msg=None, fill_value=1.e20):
"""
Linearly interpolates to fill in missing values.
x = Ngl.linmsg(x,end_pts_msg=None,max_msg=None,fill_value=1.e20)
x -- A numpy or masked array of any dimensionality that contains missing values.
end_pts_msg -- how missing beginning and end points... | 5,335,663 |
def test_auto_args_db(*args, **kwargs):
"""After you write a .csv file for args, test it here."""
print('Test of auto_args_db wrapper.')
print('Result for *args:')
print(args)
print('Results for **kwargs:')
print(kwargs) | 5,335,664 |
def get_or_create_actor_by_name(name):
"""
Return the actor corresponding to name if it does not exist,
otherwise create actor with name.
:param name: String
"""
return ta.ActorSystem().createActor(MyClass, globalName=name) | 5,335,665 |
async def test_init(hass, mock_light):
"""Test platform setup."""
state = hass.states.get("light.bedroom")
assert state.state == STATE_OFF
assert state.attributes == {
ATTR_FRIENDLY_NAME: "Bedroom",
ATTR_SUPPORTED_FEATURES: SUPPORT_BRIGHTNESS
| SUPPORT_COLOR
| SUPPORT_WHI... | 5,335,666 |
def client():
"""Client to call tests against"""
options = {
'bind': '%s:%s' % ('0.0.0.0', '8080'),
'workers': str(number_of_workers()),
}
return testing.TestClient(falcon.API(), options) | 5,335,667 |
async def test_encrypted_payload_not_supports_encryption(
hass, setup_comp, not_supports_encryption
):
"""Test encrypted payload with no supported encryption."""
await setup_owntracks(hass, {CONF_SECRET: TEST_SECRET_KEY})
await send_message(hass, LOCATION_TOPIC, MOCK_ENCRYPTED_LOCATION_MESSAGE)
asse... | 5,335,668 |
async def resolve(ctx, _id, *, msg=''):
"""Owner only - Resolves a report."""
if not ctx.message.author.id == OWNER_ID: return
report = Report.from_id(_id)
await report.resolve(ctx, msg)
report.commit()
await bot.say(f"Resolved `{report.report_id}`: {report.title}.") | 5,335,669 |
def hard_negative_mining(loss, labels, neg_pos_ratio=3):
"""
用于训练过程中正负例比例的限制.默认在训练时,负例数量是正例数量的三倍
Args:
loss (N, num_priors): the loss for each example.
labels (N, num_priors): the labels.
neg_pos_ratio: 正负例比例: 负例数量/正例数量
"""
pos_mask = labels > 0
num_pos = pos_mask.long()... | 5,335,670 |
def groups():
"""
Return groups
"""
return _clist(getAddressBook().groups()) | 5,335,671 |
def round_temp(value):
"""Round temperature for publishing."""
return round(value, dev_fan.round_temp) | 5,335,672 |
def test_cli_command_defines_a_cli_group() -> None:
"""Check that cli command defines a CLI group when invoked"""
assert isinstance(cli, ZenMLCLI) | 5,335,673 |
def scatter(n_dims, cuboids_per_concept, params, num_samples, max_dim_per_domain, operation):
"""Creates scatter plots for the betweenness values returned by different combinations of alphas and methods.
Parameters:
n_dims: number of dimensions
cuboids_per_concept: number of cuboids per co... | 5,335,674 |
def get_key_from_property(prop, key, css_dict=None, include_commented=False):
"""Returns the entry from the dictionary using the given key"""
if css_dict is None:
css_dict = get_css_dict()[0]
cur = css_dict.get(prop) or css_dict.get(prop[1:-1])
if cur is None:
return None
value = cu... | 5,335,675 |
def bbox_area(gt_boxes):
"""
gt_boxes: (K, 4) ndarray of float
area: (k)
"""
K = gt_boxes.size(0)
gt_boxes_area = ((gt_boxes[:,2] - gt_boxes[:,0] + 1) *
(gt_boxes[:,3] - gt_boxes[:,1] + 1)).view(K)
return gt_boxes_area | 5,335,676 |
def DecodedMessage(tG,x):
"""
Let G be a coding matrix. tG its transposed matrix. x a n-vector received after decoding.
DecodedMessage Solves the equation on k-bits message v: x = v.G => G'v'= x' by applying GaussElimination on G'.
-------------------------------------
Parameters:
... | 5,335,677 |
def get_ttp_card_info(ttp_number):
"""
Get information from the specified transport card number.
The number is the concatenation of the last 3 numbers of the first row and all the numbers of the second row.
See this image: https://tarjetatransportepublico.crtm.es/CRTM-ABONOS/archivos/img/TTP.jpg
:... | 5,335,678 |
def test_basic_message_strip_and_splitup():
"""
This tests these bits of functionality:
* white space and comment stripping similar to how git-commit does it
* line splitting
* subject extraction
* paragraph splitting
* body extraction
"""
m = CommitMessage('''\
# test st... | 5,335,679 |
def tag_matches(tag, impl_version='trunk', client_version='trunk'):
"""Test if specified versions match the tag.
Args:
tag: skew test expectation tag, e.g. 'impl_lte_5' or 'client_lte_2'.
impl_version: WebLayer implementation version number or 'trunk'.
client_version: WebLayer implementation version nu... | 5,335,680 |
def split_params(param_string):
"""
Splits a parameter string into its key-value pairs
>>> d = split_params('alpha-0.5_gamma-0.9')
>>> d['alpha']
0.5
>>> d['gamma']
0.9
>>> d = split_params('depth-15_features-a-b-c')
>>> d['depth']
15
>>> d['features']
['a', 'b', 'c']
>>> d = split_params('alpha-0.1_l-... | 5,335,681 |
def load_suites_from_directory(dir, recursive=True):
# type: (str, bool) -> List[Suite]
"""
Load a list of suites from a directory.
If the recursive argument is set to True, sub suites will be searched in a directory named
from the suite module: if the suite module is "foo.py" then the sub suites ... | 5,335,682 |
def run(core=-1):
"""
Parameters
----------
core: int
Integer from argparse module to be used as switcher.
Returns
-------
None
"""
"""for g_name, A in graphs.generate_n_nodes_graphs(100, get_graphs('cycle', 100)).items():
M = A / sum(A[0])
eigenvals = np.li... | 5,335,683 |
def upgrade(c, release='jhub', version='0.9.0', values='hub/config.yaml'):
"""Apply changes to the hub deployment."""
command = (
f'helm upgrade --cleanup-on-fail {release} jupyterhub/jupyterhub '
f'--version {version} --values {values}'
)
_print_command('Upgrade JupyterHub deployment', ... | 5,335,684 |
def defineRelationNM(TableA, TableB, sequence=Sequence('all_id_seq'), tableAItemName=None, tableBItemName=None):
"""defines relation N:M (TableA : TableB) between two tables
intermediated table is automaticaly defined
Parameters
----------
TableA
Model of first table
TableB
Mod... | 5,335,685 |
def usage():
"""Print usage info."""
print(("""%s [-l|--location <location>] [-t|--table <table>] [-u|--update] \
[-r|--recordTag <tag>] [-k|--keyTags <tag1,tag2,tag3,...>] [-d|--debug] \
[-h|--help] <xml doc>""" % sys.argv[0])) | 5,335,686 |
async def test_add_event_date_time(
hass: HomeAssistant,
mock_token_read: None,
component_setup: ComponentSetup,
mock_calendars_list: ApiResult,
test_api_calendar: dict[str, Any],
mock_insert_event: Mock,
) -> None:
"""Test service call that adds an event with a date time range."""
asse... | 5,335,687 |
def deep_parameters_back(param, back_node, function_params, count, file_path, lineno=0, vul_function=None,
isback=False):
"""
深层递归分析外层逻辑,主要是部分初始化条件和新递归的确定
:param isback:
:param lineno:
:param vul_function:
:param param:
:param back_node:
:param function_para... | 5,335,688 |
def get_latest_runtime(dotnet_dir: Optional[str] = None, version_major: Optional[int] = 5,
version_minor: Optional[int] = 0, version_build: Optional[int] = 0) -> Optional[str]:
"""
Search and select the latest installed .NET Core runtime directory.
"""
dotnet_dir = dotnet_dir or g... | 5,335,689 |
def choose_action(state, mdp_data):
"""
Choose the next action (0 or 1) that is optimal according to your current
mdp_data. When there is no optimal action, return a random action.
Args:
state: The current state in the MDP
mdp_data: The parameters for your MDP. See initialize_mdp_data.
... | 5,335,690 |
def test_rfloordiv():
"""Ensures that add works correctly."""
floordiv = _MathExpression() // 2
rfloordiv = 5 // _MathExpression()
assert floordiv(5) == rfloordiv(2) | 5,335,691 |
def print_rf_rainday_gt1mm_SGonly_plots(model, dest, optimal_k):
"""
i.e. taking the values but subtracting the baseline
"""
rfstarttime = timer(); print(f'{utils.time_now()} - Plotting proba of >1mm rainfall over SG now.\nTotal of {optimal_k} clusters. ')
# RFprec_to_ClusterLabels_dataset = utils... | 5,335,692 |
def get_formatted_reproduction_help(testcase):
"""Return url to reproduce the bug."""
help_format = get_value_from_job_definition_or_environment(
testcase.job_type, 'HELP_FORMAT')
if not help_format:
return None
# Since this value may be in a job definition, it's non-trivial for it to
# include new... | 5,335,693 |
def specialize_on(names, maxsize=None):
"""
A decorator that wraps a function, partially evaluating it with the parameters
defined by ``names`` (can be a string or an iterable of strings) being fixed.
The partially evaluated versions are cached based on the values of these parameters
using ``functoo... | 5,335,694 |
def parse_docstring(docstring: str, signature) -> str:
"""
Parse a docstring!
Note:
to try notes.
Args:
docstring: this is the docstring to parse.
Raises:
OSError: no it doesn't lol.
Returns:
markdown: the docstring converted to a nice markdown text.
"""
... | 5,335,695 |
def main():
"""Tool that takes a collection of theory-assertion examples and runs them through a theorem prover.
Supported input format 1: Jsonl format with json objects represented as per the
`TheoryAssertionRepresentationWithLabel` class.
Sample:
{ "json_class": "TheoryAssertionRepresentation",... | 5,335,696 |
def get_rgeo(coordinates):
"""Geocode specified coordinates
:argument coordinates: address coordinates
:type coordinates: tuple
:returns tuple
"""
params = {'language': GEOCODING_LANGUAGE,
'latlng': ','.join([str(crdnt) for crdnt in coordinates])}
result = get(url=GEOCODING... | 5,335,697 |
def norm_lib_size_log(assay, counts: daskarr) -> daskarr:
"""
Performs library size normalization and then transforms the
values into log scale.
Args:
assay: An instance of the assay object
counts: A dask array with raw counts data
Returns: A dask array (delayed matrix) containing ... | 5,335,698 |
def checkSymLinks(config):
"""
Scans Local directory which contain symlinks
"""
log.info("Scanning directory {} for symlinks")
scandir = scanner.Scanner()
for file in scandir.scanDirectory(config.LOCAL_DIR):
stats = os.path.stat(file, follow_symlink=False): | 5,335,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.