Unnamed: 0 int64 0 2.93k | code stringlengths 101 62.2k | docs stringlengths 51 10.7k | doc_len int64 4 1.74k | words int64 4 4.82k | lang stringclasses 1
value | prompt stringlengths 320 71.2k |
|---|---|---|---|---|---|---|
2,700 | def format_command(self) -> str:
command = 'ansible-test %s' % self.command
if self.test:
command += ' --test %s' % self.test
if self.python_version:
command += ' --python %s' % self.python_version
return command
| Return a string representing the CLI command associated with the test failure. | 12 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def format_command(self) -> str:
command = 'ansible-test %s' % self.command
if self.test:
command += ' --test %s' % self.test
if self.python_ve... |
2,701 | def act(self):
obs = self.observation
reply = {'text': INVALID, 'id': self.getID(), 'episode_done': False}
if obs is None or obs['text'] == DO_NOT_RETRIEVE:
return Message(reply)
# construct the search query
labels = obs.get('labels', obs.get('eval_labels', ... |
Search for overlap with the observation label.
Return the best fitting document. A document is valid if the f1 is above the
threshold AND the f1 is less than 1.0 AND the target label is not in the
document.
| 39 | 102 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def act(self):
obs = self.observation
reply = {'text': INVALID, 'id': self.getID(), 'episode_done': False}
if obs is None or obs['text'] == DO_NOT_RETRIEVE:
... |
2,702 | def print_help(self):
help_text = f
console.print(text=help_text, menu="Forex - Quantitative Analysis")
| Print help[cmds]
pick pick target column for analysis[/cmds]
[param]Pair: [/param]{self.ticker}
[param]Target Column: [/param]{self.target}
[cmds]
[info]Statistics:[/info]
summary brief summary statistics of loaded pair.
normality normality statistics and tests
unitroot unit root test fo... | 142 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def print_help(self):
help_text = f
console.print(text=help_text, menu="Forex - Quantitative Analysis")
```
###Assistant : Print help[cmds]
pick ... |
2,703 | def chain(self, klass=None):
obj = self.clone()
if klass and obj.__class__ != klass:
obj.__class__ = klass
if not obj.filter_is_sticky:
obj.used_aliases = set()
obj.filter_is_sticky = False
if hasattr(obj, "_setup_query"):
obj._setup_q... |
Return a copy of the current Query that's ready for another operation.
The klass argument changes the type of the Query, e.g. UpdateQuery.
| 23 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def chain(self, klass=None):
obj = self.clone()
if klass and obj.__class__ != klass:
obj.__class__ = klass
if not obj.filter_is_sticky:
... |
2,704 | def run_test_gbm_non_number_inputs(tmpdir, backend_config):
input_features = [binary_feature(), category_feature(encoder={"reduce_output": "sum"})]
output_feature = binary_feature()
output_features = [output_feature]
csv_filename = os.path.join(tmpdir, "training.csv")
dataset_filename = genera... | Test that the GBM model can train and predict with non-number inputs. | 12 | 81 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def run_test_gbm_non_number_inputs(tmpdir, backend_config):
input_features = [binary_feature(), category_feature(encoder={"reduce_output": "sum"})]
output_feature = binary_featu... |
2,705 | def i2len(self, pkt, val):
fld_len = self.fld.i2len(pkt, val)
return fld_len + self.padlen(fld_len, pkt)
| get the length of the field, including the padding length | 10 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def i2len(self, pkt, val):
fld_len = self.fld.i2len(pkt, val)
return fld_len + self.padlen(fld_len, pkt)
```
###Assistant : get the length of the field... |
2,706 | def get_kerning(self, next):
advance = self._metrics.advance - self.width
kern = 0.
if isinstance(next, Char):
kern = self.fontset.get_kern(
self.font, self.font_class, self.c, self.fontsize,
next.font, next.font_class, next.c, next.fontsize,
... |
Return the amount of kerning between this and the given character.
This method is called when characters are strung together into `Hlist`
to create `Kern` nodes.
| 26 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_kerning(self, next):
advance = self._metrics.advance - self.width
kern = 0.
if isinstance(next, Char):
kern = self.fontset.get_kern(
... |
2,707 | def _get_num_samples_or_steps(data, steps_per_epoch):
flat_inputs = tf.nest.flatten(data)
if hasattr(flat_inputs[0], "shape"):
return int(flat_inputs[0].shape[0]), False
return steps_per_epoch, True
| Returns number of samples or steps, and whether to use steps count mode. | 13 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_num_samples_or_steps(data, steps_per_epoch):
flat_inputs = tf.nest.flatten(data)
if hasattr(flat_inputs[0], "shape"):
return int(flat_inputs[0].shape[0]), False... |
2,708 | def test_retrieve_product_attributes_input_type(staff_api_client, product, channel_USD):
query =
variables = {"channel": channel_USD.slug}
found_products = get_graphql_content(
staff_api_client.post_graphql(query, variables)
)["data"]["products"]["edges"]
assert len(found_products) == 1
... |
query ($channel: String){
products(first: 10, channel: $channel) {
edges {
node {
attributes {
values {
inputType
}
}
}
}
}
}
mutation... | 64 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_retrieve_product_attributes_input_type(staff_api_client, product, channel_USD):
query =
variables = {"channel": channel_USD.slug}
found_products = get_graphql_content(... |
2,709 | def apply(self, project_state, schema_editor, collect_sql=False):
for operation in self.operations:
# If this operation cannot be represented as SQL, place a comment
# there instead
if collect_sql:
schema_editor.collected_sql.append("--")
... |
Take a project_state representing all migrations prior to this one
and a schema_editor for a live database and apply the migration
in a forwards order.
Return the resulting project state for efficient reuse by following
Migrations.
| 36 | 124 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def apply(self, project_state, schema_editor, collect_sql=False):
for operation in self.operations:
# If this operation cannot be represented as SQL, place a com... |
2,710 | def safe_to_scale(self) -> bool:
# Get the list of nodes.
node_set = set(self.node_data_dict.keys())
worker_groups = self._raycluster["spec"].get("workerGroupSpecs", [])
# Accumulates the indices of worker groups with non-empty workersToDelete
non_empty_worker_group_ind... | Returns False iff non_terminated_nodes contains any pods in the RayCluster's
workersToDelete lists.
Explanation:
If there are any workersToDelete which are non-terminated,
we should wait for the operator to do its job and delete those
pods. Therefore, we back off the autoscaler ... | 95 | 122 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def safe_to_scale(self) -> bool:
# Get the list of nodes.
node_set = set(self.node_data_dict.keys())
worker_groups = self._raycluster["spec"].get("workerGrou... |
2,711 | def get_distance(self, f, value, lookup_type):
if not value:
return []
value = value[0]
if isinstance(value, Distance):
if f.geodetic(self.connection):
dist_param = value.m
else:
dist_param = getattr(
... |
Return the distance parameters given the value and the lookup type.
On Oracle, geometry columns with a geodetic coordinate system behave
implicitly like a geography column, and thus meters will be used as
the distance parameter on them.
| 38 | 58 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_distance(self, f, value, lookup_type):
if not value:
return []
value = value[0]
if isinstance(value, Distance):
if f.geodetic... |
2,712 | def test_standard_get_document_model(self):
del settings.WAGTAILDOCS_DOCUMENT_MODEL
from wagtail.documents.models import Document
self.assertIs(get_document_model(), Document)
| Test get_document_model with no WAGTAILDOCS_DOCUMENT_MODEL | 5 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_standard_get_document_model(self):
del settings.WAGTAILDOCS_DOCUMENT_MODEL
from wagtail.documents.models import Document
self.assertIs(get_document... |
2,713 | def _safe_assign(X, values, *, row_indexer=None, column_indexer=None):
row_indexer = slice(None, None, None) if row_indexer is None else row_indexer
column_indexer = (
slice(None, None, None) if column_indexer is None else column_indexer
)
if hasattr(X, "iloc"): # pandas dataframe
... | Safe assignment to a numpy array, sparse matrix, or pandas dataframe.
Parameters
----------
X : {ndarray, sparse-matrix, dataframe}
Array to be modified. It is expected to be 2-dimensional.
values : ndarray
The values to be assigned to `X`.
row_indexer : array-like, dtype={int, bo... | 80 | 51 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _safe_assign(X, values, *, row_indexer=None, column_indexer=None):
row_indexer = slice(None, None, None) if row_indexer is None else row_indexer
column_indexer = (
s... |
2,714 | def copy_sign(self, a, b):
a = _convert_other(a, raiseit=True)
return a.copy_sign(b)
| Copies the second operand's sign to the first one.
In detail, it returns a copy of the first operand with the sign
equal to the sign of the second operand.
>>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Decimal('1.50')
>>> ExtendedContext.copy_sign(Decimal('-1... | 60 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def copy_sign(self, a, b):
a = _convert_other(a, raiseit=True)
return a.copy_sign(b)
```
###Assistant : Copies the second operand's sign to the first on... |
2,715 | def get_validated_ordering(self):
orderable_fields = self.orderable_fields or ()
ordering = {}
if self.is_export:
# Revert to CSV order_by submit_time ascending for backwards compatibility
default_ordering = self.ordering_csv or ()
else:
defa... | Return a dict of field names with ordering labels if ordering is valid | 13 | 82 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_validated_ordering(self):
orderable_fields = self.orderable_fields or ()
ordering = {}
if self.is_export:
# Revert to CSV order_by submi... |
2,716 | def test_chordal_cycle_graph(p):
G = nx.chordal_cycle_graph(p)
assert len(G) == p
# TODO The second largest eigenvalue should be smaller than a constant,
# independent of the number of nodes in the graph:
#
# eigs = sorted(sp.linalg.eigvalsh(nx.adjacency_matrix(G).toarray()))
# ... | Test for the :func:`networkx.chordal_cycle_graph` function. | 5 | 48 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_chordal_cycle_graph(p):
G = nx.chordal_cycle_graph(p)
assert len(G) == p
# TODO The second largest eigenvalue should be smaller than a constant,
# independent o... |
2,717 | def convert_dataset_split_sizes(left_size,right_size,total_size):
left_size_type = type(left_size)
right_size_type = type(right_size)
if left_size is not None and left_size_type not in [int,float]:
raise ValueError(f'Invalid `left_size` type Got {left_size_type}'
'It should be one ... | Helper function to convert left_size/right_size relative to dataset's size
| 9 | 278 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def convert_dataset_split_sizes(left_size,right_size,total_size):
left_size_type = type(left_size)
right_size_type = type(right_size)
if left_size is not None and left_size_type... |
2,718 | def active_count(self):
return self.order_by().exclude(inventory_sources__source='controller').values(name_lower=Lower('name')).distinct().count()
| Return count of active, unique hosts for licensing.
Construction of query involves:
- remove any ordering specified in model's Meta
- Exclude hosts sourced from another Tower
- Restrict the query to only return the name column
- Only consider results that are unique
... | 51 | 4 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def active_count(self):
return self.order_by().exclude(inventory_sources__source='controller').values(name_lower=Lower('name')).distinct().count()
```
###Assist... |
2,719 | async def test_set_avatar_incorrect_mime_type(self) -> None:
handler = self.hs.get_sso_handler()
# any random user works since image check is supposed to fail
user_id = "@sso-user:test"
self.assertFalse(
self.get_success(handler.set_avatar(user_id, "http://my.serve... | Tests that saving an avatar fails when its mime type is not allowed | 13 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_set_avatar_incorrect_mime_type(self) -> None:
handler = self.hs.get_sso_handler()
# any random user works since image check is supposed to fail
... |
2,720 | def layer_uses_training_bool(layer):
if layer._expects_training_arg: # pylint: disable=protected-access
return True
visited = {layer}
to_visit = list_all_layers(layer)
while to_visit:
layer = to_visit.pop()
if layer in visited:
continue
if getattr(layer,... | Returns whether this layer or any of its children uses the training arg. | 13 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def layer_uses_training_bool(layer):
if layer._expects_training_arg: # pylint: disable=protected-access
return True
visited = {layer}
to_visit = list_all_layers(lay... |
2,721 | async def test_edgeql_for_in_computable_09(self):
# This is basically test_edgeql_for_in_computable_01 but with
# a WITH binding in front of the whole shape
await self.assert_query_result(
r |
WITH
U := (
SELECT User {
select_deck := (
FOR letter IN {'I', 'B'}
UNION (
SELECT User.deck {
... | 28 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_edgeql_for_in_computable_09(self):
# This is basically test_edgeql_for_in_computable_01 but with
# a WITH binding in front of the whole shape
await sel... |
2,722 | def get_actual_details(name, filters):
budget_against = frappe.scrub(filters.get("budget_against"))
cond = ""
if filters.get("budget_against") == "Cost Center":
cc_lft, cc_rgt = frappe.db.get_value("Cost Center", name, ["lft", "rgt"])
cond = .format(
lft=cc_lft, rgt=cc_rgt
)
ac_details = frappe.db.sql(
... |
and lft >= "{lft}"
and rgt <= "{rgt}"
select
gl.account,
gl.debit,
gl.credit,
gl.fiscal_year,
MONTHNAME(gl.posting_date) as month_name,
b.{budget_against} as budget_against
from
`tabGL Entry` gl,
`tabBudget Account` ba,
`tabBudget` b
where
b.name = ba.parent... | 70 | 52 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_actual_details(name, filters):
budget_against = frappe.scrub(filters.get("budget_against"))
cond = ""
if filters.get("budget_against") == "Cost Center":
cc_lft, cc_rgt = frappe... |
2,723 | def print_index(toc):
dash = "-"*(100 - 7)
space = " "*47
print(f"{space}INDEX")
print(f"\n\nName : {dash} PageNo.\n\n\n")
for topic in toc:
eq_dash = "-"*(100 - len(topic[1]))
print(f"{topic[1]} {eq_dash} {topic[2]}")
| Prints out the index in proper format with title name and page number
Args:
toc (nested list): toc[1] - Topic name
toc[2] - Page number
| 25 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def print_index(toc):
dash = "-"*(100 - 7)
space = " "*47
print(f"{space}INDEX")
print(f"\n\nName : {dash} PageNo.\n\n\n")
for topic in toc:
eq_dash =... |
2,724 | def pie(self, X, win=None, env=None, opts=None):
X = np.squeeze(X)
assert X.ndim == 1, "X should be one-dimensional"
assert np.all(np.greater_equal(X, 0)), "X cannot contain negative values"
opts = {} if opts is None else opts
_title2str(opts)
_assert_opts(opts... |
This function draws a pie chart based on the `N` tensor `X`.
The following `opts` are supported:
- `opts.legend`: `list` containing legend names
| 23 | 63 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def pie(self, X, win=None, env=None, opts=None):
X = np.squeeze(X)
assert X.ndim == 1, "X should be one-dimensional"
assert np.all(np.greater_equal(X, 0)), ... |
2,725 | def dry_run(self) -> None:
pod = self.build_pod_request_obj()
print(yaml.dump(prune_dict(pod.to_dict(), mode='strict')))
|
Prints out the pod definition that would be created by this operator.
Does not include labels specific to the task instance (since there isn't
one in a dry_run) and excludes all empty elements.
| 33 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def dry_run(self) -> None:
pod = self.build_pod_request_obj()
print(yaml.dump(prune_dict(pod.to_dict(), mode='strict')))
```
###Assistant :
Pr... |
2,726 | def ExponentialPower(name, mu, alpha, beta):
r
return rv(name, ExponentialPowerDistribution, (mu, alpha, beta))
#-------------------------------------------------------------------------------
# F distribution ---------------------------------------------------------------
|
Create a Continuous Random Variable with Exponential Power distribution.
This distribution is known also as Generalized Normal
distribution version 1.
Explanation
===========
The density of the Exponential Power distribution is given by
.. math::
f(x) := \frac{\beta}{2\alpha\Gamm... | 152 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def ExponentialPower(name, mu, alpha, beta):
r
return rv(name, ExponentialPowerDistribution, (mu, alpha, beta))
#-------------------------------------------------------------------... |
2,727 | def get_palette(num_cls):
n = num_cls
palette = [0] * (n * 3)
for j in range(0, n):
lab = j
palette[j * 3 + 0] = 0
palette[j * 3 + 1] = 0
palette[j * 3 + 2] = 0
i = 0
while lab:
palette[j * 3 + 0] |= (((lab >> 0) & 1) << (7 - i))
... | Returns the color map for visualizing the segmentation mask.
Args:
num_cls: Number of classes
Returns:
The color map
| 18 | 99 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_palette(num_cls):
n = num_cls
palette = [0] * (n * 3)
for j in range(0, n):
lab = j
palette[j * 3 + 0] = 0
palette[j * 3 + 1] = 0
pa... |
2,728 | def _Net_forward_backward_all(self, blobs=None, diffs=None, **kwargs):
# Batch blobs and diffs.
all_outs = {out: [] for out in set(self.outputs + (blobs or []))}
all_diffs = {diff: [] for diff in set(self.inputs + (diffs or []))}
forward_batches = self._batch({in_: kwargs[in_]
... |
Run net forward + backward in batches.
Parameters
----------
blobs: list of blobs to extract as in forward()
diffs: list of diffs to extract as in backward()
kwargs: Keys are input (for forward) and output (for backward) blob names
and values are ndarrays. Refer to forward() and ba... | 73 | 144 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _Net_forward_backward_all(self, blobs=None, diffs=None, **kwargs):
# Batch blobs and diffs.
all_outs = {out: [] for out in set(self.outputs + (blobs or []))}
all_diffs =... |
2,729 | def test_user_does_not_exist(self) -> None:
url = "/_synapse/admin/v2/users/@unknown_person:test/devices"
channel = self.make_request(
"GET",
url,
access_token=self.admin_user_tok,
)
self.assertEqual(404, channel.code, msg=channel.json_body)
... |
Tests that a lookup for a user that does not exist returns a 404
| 14 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_user_does_not_exist(self) -> None:
url = "/_synapse/admin/v2/users/@unknown_person:test/devices"
channel = self.make_request(
"GET",
... |
2,730 | def send_ping(self) -> None:
now = self.clock.time_msec()
if self.time_we_closed:
if now - self.time_we_closed > PING_TIMEOUT_MS:
logger.info(
"[%s] Failed to close connection gracefully, aborting", self.id()
)
ass... | Periodically sends a ping and checks if we should close the connection
due to the other side timing out.
| 19 | 66 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def send_ping(self) -> None:
now = self.clock.time_msec()
if self.time_we_closed:
if now - self.time_we_closed > PING_TIMEOUT_MS:
logger... |
2,731 | def workflow_logging_context(job_id) -> None:
node = ray.worker._global_node
original_out_file, original_err_file = node.get_log_file_handles(
get_worker_log_file_name("WORKER")
)
out_file, err_file = node.get_log_file_handles(
get_worker_log_file_name("WORKER", job_id)
)
tr... | Initialize the workflow logging context.
Workflow executions are running as remote functions from
WorkflowManagementActor. Without logging redirection, workflow
inner execution logs will be pushed to the driver that initially
created WorkflowManagementActor rather than the driver that
actually subm... | 83 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def workflow_logging_context(job_id) -> None:
node = ray.worker._global_node
original_out_file, original_err_file = node.get_log_file_handles(
get_worker_log_file_name("... |
2,732 | def console_entry_point():
if "--profile" in sys.argv:
with cProfile.Profile() as profile:
entry_point()
stats = pstats.Stats(profile)
stats.sort_stats(pstats.SortKey.TIME)
# Use snakeviz to visualize the profile
stats.dump_stats("spotdl.profile")
else... |
Wrapper around `entry_point` so we can profile the code
| 9 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def console_entry_point():
if "--profile" in sys.argv:
with cProfile.Profile() as profile:
entry_point()
stats = pstats.Stats(profile)
stats.so... |
2,733 | def callbacks(self, callbacks_class) -> "TrainerConfig":
self.callbacks_class = callbacks_class
return self
| Sets the callbacks configuration.
Args:
callbacks_class: Callbacks class, whose methods will be run during
various phases of training and environment sample collection.
See the `DefaultCallbacks` class and
`examples/custom_metrics_and_callbacks.py` fo... | 37 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def callbacks(self, callbacks_class) -> "TrainerConfig":
self.callbacks_class = callbacks_class
return self
```
###Assistant : Sets the callbacks confi... |
2,734 | def test_get_dynamic_sampling_after_migrating_to_new_plan_default_biases(self):
self.project.update_option("sentry:dynamic_sampling", self.dynamic_sampling_data)
with Feature(
{
self.universal_ds_flag: True,
self.old_ds_flag: True,
s... |
Tests the case when an organization was in EA/LA and has setup previously Dynamic Sampling rules,
and now they have migrated to an AM2 plan, but haven't manipulated the bias toggles yet so they get the
default biases. This also ensures that they no longer receive the deprecated dynamic sampling... | 51 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_get_dynamic_sampling_after_migrating_to_new_plan_default_biases(self):
self.project.update_option("sentry:dynamic_sampling", self.dynamic_sampling_data)
w... |
2,735 | def strtobool(val):
# type: (str) -> int
val = val.lower()
if val in ("y", "yes", "t", "true", "on", "1"):
return 1
elif val in ("n", "no", "f", "false", "off", "0"):
return 0
else:
raise ValueError(f"invalid truth value {val!r}")
| Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
| 39 | 38 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def strtobool(val):
# type: (str) -> int
val = val.lower()
if val in ("y", "yes", "t", "true", "on", "1"):
return 1
elif val in ("n", "no", "f", "false", "off", ... |
2,736 | def convert_xunits(self, x):
ax = getattr(self, 'axes', None)
if ax is None or ax.xaxis is None:
return x
return ax.xaxis.convert_units(x)
|
Convert *x* using the unit type of the xaxis.
If the artist is not contained in an Axes or if the xaxis does not
have units, *x* itself is returned.
| 30 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def convert_xunits(self, x):
ax = getattr(self, 'axes', None)
if ax is None or ax.xaxis is None:
return x
return ax.xaxis.convert_units(x)
... |
2,737 | def value_as_datetime(self) -> tp.Tuple[datetime, datetime] | None:
if self.value is None:
return None
v1, v2 = self.value
if isinstance(v1, numbers.Number):
d1 = datetime.utcfromtimestamp(v1 / 1000)
else:
d1 = v1
if isinstance(v2, num... | Convenience property to retrieve the value tuple as a tuple of
datetime objects.
Initial or selected range.
Initial or selected value, throttled to report only on mouseup.
The minimum allowable value.
The maximum allowable value.
The step between consecutive val... | 48 | 81 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def value_as_datetime(self) -> tp.Tuple[datetime, datetime] | None:
if self.value is None:
return None
v1, v2 = self.value
if isinstance(v1, numb... |
2,738 | def test_first_event_with_minified_stack_trace_received(self, record_analytics):
now = timezone.now()
project = self.create_project(first_event=now)
project_created.send(project=project, user=self.user, sender=type(project))
url = "http://localhost:3000"
data = load_data... |
Test that an analytics event is recorded when
a first event with minified stack trace is received
| 17 | 88 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_first_event_with_minified_stack_trace_received(self, record_analytics):
now = timezone.now()
project = self.create_project(first_event=now)
project_... |
2,739 | def arange(start, /, stop=None, step=1, *, dtype=None, meta=None, **kwargs):
raise NotImplementedError
| Create an ascending or descending array
Returns evenly spaced values within the half-open interval
``[start, stop)`` as a one-dimensional array.
| 20 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def arange(start, /, stop=None, step=1, *, dtype=None, meta=None, **kwargs):
raise NotImplementedError
```
###Assistant : Create an ascending or descending arr... |
2,740 | def best_checkpoints(self):
checkpoints = sorted(self._top_persisted_checkpoints, key=lambda c: c.priority)
return [wrapped.tracked_checkpoint for wrapped in checkpoints]
| Returns best PERSISTENT checkpoints, sorted by score. | 7 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def best_checkpoints(self):
checkpoints = sorted(self._top_persisted_checkpoints, key=lambda c: c.priority)
return [wrapped.tracked_checkpoint for wrapped in checkpo... |
2,741 | def get_config_directory() -> Path:
if os.getenv('NNI_CONFIG_DIR') is not None:
config_dir = Path(os.getenv('NNI_CONFIG_DIR')) # type: ignore
elif sys.prefix != sys.base_prefix or Path(sys.prefix, 'conda-meta').is_dir():
config_dir = Path(sys.prefix, 'nni')
elif sys.platform == 'win32'... |
Get NNI config directory.
Create it if not exist.
| 9 | 44 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_config_directory() -> Path:
if os.getenv('NNI_CONFIG_DIR') is not None:
config_dir = Path(os.getenv('NNI_CONFIG_DIR')) # type: ignore
elif sys.prefix != sys.bas... |
2,742 | def test_background_update_min_batch_set_in_config(self):
# a very long-running individual update
duration_ms = 50
self.get_success(
self.store.db_pool.simple_insert(
"background_updates",
values={"update_name": "test_update", "progress_json"... |
Test that the minimum batch size set in the config is used
| 12 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_background_update_min_batch_set_in_config(self):
# a very long-running individual update
duration_ms = 50
self.get_success(
self.store.... |
2,743 | def swap_memory():
mem = cext.virtual_mem()
total_phys = mem[0]
free_phys = mem[1]
total_system = mem[2]
free_system = mem[3]
# Despite the name PageFile refers to total system memory here
# thus physical memory values need to be subtracted to get swap values
total = total_system ... | Swap system memory as a (total, used, free, sin, sout) tuple. | 11 | 79 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def swap_memory():
mem = cext.virtual_mem()
total_phys = mem[0]
free_phys = mem[1]
total_system = mem[2]
free_system = mem[3]
# Despite the name PageFile refer... |
2,744 | def get_supplier_invoice_details():
inv_details = {}
for d in frappe.db.sql(
,
as_dict=1,
):
inv_details[d.name] = d.bill_no
return inv_details
| select name, bill_no from `tabPurchase Invoice`
where docstatus = 1 and bill_no is not null and bill_no != '' | 19 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_supplier_invoice_details():
inv_details = {}
for d in frappe.db.sql(
,
as_dict=1,
):
inv_details[d.name] = d.bill_no
return inv_details
```
###Assistant : s... |
2,745 | def dce_rpc_endianess(pkt):
if pkt.endianness == 0: # big endian
return ">"
elif pkt.endianness == 1: # little endian
return "<"
else:
return "!"
| Determine the right endianness sign for a given DCE/RPC packet | 10 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def dce_rpc_endianess(pkt):
if pkt.endianness == 0: # big endian
return ">"
elif pkt.endianness == 1: # little endian
return "<"
else:
return "!"
... |
2,746 | def deserialize_object(model, fields, pk=None):
content_type = ContentType.objects.get_for_model(model)
if 'custom_fields' in fields:
fields['custom_field_data'] = fields.pop('custom_fields')
data = {
'model': '.'.join(content_type.natural_key()),
'pk': pk,
'fields': fie... |
Instantiate an object from the given model and field data. Functions as
the complement to serialize_object().
| 16 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def deserialize_object(model, fields, pk=None):
content_type = ContentType.objects.get_for_model(model)
if 'custom_fields' in fields:
fields['custom_field_data'] = field... |
2,747 | async def test_component_not_installed_if_requirement_fails(hass):
hass.config.skip_pip = False
mock_integration(hass, MockModule("comp", requirements=["package==0.0.1"]))
with patch("homeassistant.util.package.install_package", return_value=False):
assert not await setup.async_setup_component... | Component setup should fail if requirement can't install. | 8 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_component_not_installed_if_requirement_fails(hass):
hass.config.skip_pip = False
mock_integration(hass, MockModule("comp", requirements=["package==0.0.1"]))
... |
2,748 | def use_numba_cb(key) -> None:
from pandas.core.util import numba_
numba_.set_use_numba(cf.get_option(key))
with cf.config_prefix("compute"):
cf.register_option(
"use_bottleneck",
True,
use_bottleneck_doc,
validator=is_bool,
cb=use_bottleneck_cb,
)
cf.regis... |
: int
Floating point output precision in terms of number of places after the
decimal, for regular formatting as well as scientific notation. Similar
to ``precision`` in :meth:`numpy.set_printoptions`.
: int
Default space for DataFrame columns.
: int
If max_rows is exceeded, switch to truncate vie... | 960 | 105 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def use_numba_cb(key) -> None:
from pandas.core.util import numba_
numba_.set_use_numba(cf.get_option(key))
with cf.config_prefix("compute"):
cf.register_option(
"use_... |
2,749 | def test_twitter_tag(self) -> None:
html = b
tree = decode_body(html, "http://example.com/test.html")
og = parse_html_to_open_graph(tree)
self.assertEqual(
og,
{
"og:title": None,
"og:description": "Description",
... | Twitter card tags should be used if nothing else is available.
<html>
<meta name="twitter:card" content="summary">
<meta name="twitter:description" content="Description">
<meta name="twitter:site" content="@matrixdotorg">
</html>
<html>
<meta name="twitte... | 40 | 55 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_twitter_tag(self) -> None:
html = b
tree = decode_body(html, "http://example.com/test.html")
og = parse_html_to_open_graph(tree)
self.assert... |
2,750 | def get_tax_template(posting_date, args):
args = frappe._dict(args)
conditions = []
if posting_date:
conditions.append(
f
)
else:
conditions.append("(from_date is null) and (to_date is null)")
conditions.append(
"ifnull(tax_category, '') = {0}".format(frappe.db.escape(cstr(args.get("tax_category")))... | Get matching tax rule(from_date is null or from_date <= '{posting_date}')
and (to_date is null or to_date >= '{posting_date}')select * from `tabTax Rule`
where {0} | 24 | 159 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_tax_template(posting_date, args):
args = frappe._dict(args)
conditions = []
if posting_date:
conditions.append(
f
)
else:
conditions.append("(from_date is null) and (... |
2,751 | def wheel_graph(n, create_using=None):
_, nodes = n
G = empty_graph(nodes, create_using)
if G.is_directed():
raise NetworkXError("Directed Graph not supported")
if len(nodes) > 1:
hub, *rim = nodes
G.add_edges_from((hub, node) for node in rim)
if len(rim) > 1:
... | Return the wheel graph
The wheel graph consists of a hub node connected to a cycle of (n-1) nodes.
Parameters
----------
n : int or iterable
If an integer, node labels are 0 to n with center 0.
If an iterable of nodes, the center is the first.
create_using : NetworkX graph construc... | 76 | 40 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def wheel_graph(n, create_using=None):
_, nodes = n
G = empty_graph(nodes, create_using)
if G.is_directed():
raise NetworkXError("Directed Graph not supported")
... |
2,752 | def get_changes():
with open(HISTORY) as f:
lines = f.readlines()
block = []
# eliminate the part preceding the first block
for i, line in enumerate(lines):
line = lines.pop(0)
if line.startswith('===='):
break
lines.pop(0)
for i, line in enumerate(lin... | Get the most recent changes for this release by parsing
HISTORY.rst file.
| 12 | 70 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_changes():
with open(HISTORY) as f:
lines = f.readlines()
block = []
# eliminate the part preceding the first block
for i, line in enumerate(lines):
... |
2,753 | def _check_valid_data(self) -> bool:
logger.debug("Validating data. %s",
{key: len(val) for key, val in self._display_data.stats.items()})
if any(len(val) == 0 # pylint:disable=len-as-condition
for val in self._display_data.stats.values()):
retur... | Check that the selections holds valid data to display
NB: len-as-condition is used as data could be a list or a numpy array
Returns
-------
bool
``True` if there is data to be displayed, otherwise ``False``
| 36 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _check_valid_data(self) -> bool:
logger.debug("Validating data. %s",
{key: len(val) for key, val in self._display_data.stats.items()})
if an... |
2,754 | def _async_check_unavailable_groups_with_random_macs(self) -> None:
now = MONOTONIC_TIME()
gone_unavailable = [
group_id
for group_id in self._group_ids_random_macs
if group_id not in self._unavailable_group_ids
and (service_info := self._last_see... | Check for random mac groups that have not been seen in a while and mark them as unavailable. | 18 | 144 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _async_check_unavailable_groups_with_random_macs(self) -> None:
now = MONOTONIC_TIME()
gone_unavailable = [
group_id
for group_id in self... |
2,755 | def restore_optimizers_and_schedulers(self) -> None:
if not self._loaded_checkpoint:
return
if self.trainer.strategy.lightning_restore_optimizer:
# validation
if "optimizer_states" not in self._loaded_checkpoint:
raise KeyError(
... | Restores the optimizers and learning rate scheduler states from the pre-loaded checkpoint. | 12 | 76 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def restore_optimizers_and_schedulers(self) -> None:
if not self._loaded_checkpoint:
return
if self.trainer.strategy.lightning_restore_optimizer:
... |
2,756 | def urldefragauth(url):
scheme, netloc, path, params, query, fragment = urlparse(url)
# see func:`prepend_scheme_if_needed`
if not netloc:
netloc, path = path, netloc
netloc = netloc.rsplit("@", 1)[-1]
return urlunparse((scheme, netloc, path, params, query, ""))
|
Given a url remove the fragment and the authentication part.
:rtype: str
| 12 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def urldefragauth(url):
scheme, netloc, path, params, query, fragment = urlparse(url)
# see func:`prepend_scheme_if_needed`
if not netloc:
netloc, path = path, netl... |
2,757 | def test_approval_not_required(self) -> None:
self.get_success(self.store.register_user(self.user_id, self.pwhash))
user = self.get_success(self.store.get_user_by_id(self.user_id))
assert user is not None
self.assertTrue(user["approved"])
approved = self.get_success(se... | Tests that if we don't require approval for new accounts, newly created
accounts are automatically marked as approved.
| 18 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_approval_not_required(self) -> None:
self.get_success(self.store.register_user(self.user_id, self.pwhash))
user = self.get_success(self.store.get_user_by_i... |
2,758 | def get_all(self, name, failobj=None):
values = []
name = name.lower()
for k, v in self._headers:
if k.lower() == name:
values.append(self.policy.header_fetch_parse(k, v))
if not values:
return failobj
return values
| Return a list of all the values for the named field.
These will be sorted in the order they appeared in the original
message, and may contain duplicates. Any fields deleted and
re-inserted are always appended to the header list.
If no such fields exist, failobj is returned (defaults t... | 51 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_all(self, name, failobj=None):
values = []
name = name.lower()
for k, v in self._headers:
if k.lower() == name:
values.ap... |
2,759 | def test_explorer_private_child(self):
response = self.client.get(
reverse("wagtailadmin_explore", args=(self.private_child_page.id,))
)
# Check the response
self.assertEqual(response.status_code, 200)
# Check the privacy indicator is public
self.as... |
This tests that the privacy indicator on the private child pages explore view is set to "PRIVATE"
| 17 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_explorer_private_child(self):
response = self.client.get(
reverse("wagtailadmin_explore", args=(self.private_child_page.id,))
)
# Check... |
2,760 | def find_backend(line):
if _re_test_backend.search(line) is None:
return None
backends = [b[0] for b in _re_backend.findall(line)]
backends.sort()
return "_and_".join(backends)
| Find one (or multiple) backend in a code line of the init. | 12 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def find_backend(line):
if _re_test_backend.search(line) is None:
return None
backends = [b[0] for b in _re_backend.findall(line)]
backends.sort()
return "_and_"... |
2,761 | def subgraph_view(G, filter_node=no_filter, filter_edge=no_filter):
newG = nx.freeze(G.__class__())
newG._NODE_OK = filter_node
newG._EDGE_OK = filter_edge
# create view by assigning attributes from G
newG._graph = G
newG.graph = G.graph
newG._node = FilterAtlas(G._node, filter_node)
... | View of `G` applying a filter on nodes and edges.
`subgraph_view` provides a read-only view of the input graph that excludes
nodes and edges based on the outcome of two filter functions `filter_node`
and `filter_edge`.
The `filter_node` function takes one argument --- the node --- and returns
`Tru... | 333 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def subgraph_view(G, filter_node=no_filter, filter_edge=no_filter):
newG = nx.freeze(G.__class__())
newG._NODE_OK = filter_node
newG._EDGE_OK = filter_edge
# create vie... |
2,762 | def _deprecate_ci(errorbar, ci):
if ci != "deprecated":
if ci is None:
errorbar = None
elif ci == "sd":
errorbar = "sd"
else:
errorbar = ("ci", ci)
msg = (
"\n\nThe `ci` parameter is deprecated. "
f"Use `errorbar={repr(... |
Warn on usage of ci= and convert to appropriate errorbar= arg.
ci was deprecated when errorbar was added in 0.12. It should not be removed
completely for some time, but it can be moved out of function definitions
(and extracted from kwargs) after one cycle.
| 45 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _deprecate_ci(errorbar, ci):
if ci != "deprecated":
if ci is None:
errorbar = None
elif ci == "sd":
errorbar = "sd"
else:
... |
2,763 | def __sub__(self, other):
if self._delegate_binop(other):
return NotImplemented
return np.subtract(self, other)
|
Subtract other from self, and return a new masked array.
| 10 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __sub__(self, other):
if self._delegate_binop(other):
return NotImplemented
return np.subtract(self, other)
```
###Assistant :
... |
2,764 | def mock_smile_adam_2() -> Generator[None, MagicMock, None]:
chosen_env = "m_adam_heating"
with patch(
"homeassistant.components.plugwise.gateway.Smile", autospec=True
) as smile_mock:
smile = smile_mock.return_value
smile.gateway_id = "da224107914542988a88561b4452b0f6"
... | Create a 2nd Mock Adam environment for testing exceptions. | 9 | 51 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def mock_smile_adam_2() -> Generator[None, MagicMock, None]:
chosen_env = "m_adam_heating"
with patch(
"homeassistant.components.plugwise.gateway.Smile", autospec=True
... |
2,765 | def plot_wireframe(self, X, Y, Z, **kwargs):
had_data = self.has_data()
if Z.ndim != 2:
raise ValueError("Argument Z must be 2-dimensional.")
# FIXME: Support masked arrays
X, Y, Z = np.broadcast_arrays(X, Y, Z)
rows, cols = Z.shape
has_stride = 'rs... |
Plot a 3D wireframe.
.. note::
The *rcount* and *ccount* kwargs, which both default to 50,
determine the maximum number of samples used in each direction. If
the input data is larger, it will be downsampled (by slicing) to
these numbers of points.
... | 198 | 393 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def plot_wireframe(self, X, Y, Z, **kwargs):
had_data = self.has_data()
if Z.ndim != 2:
raise ValueError("Argument Z must be 2-dimensional.")
# ... |
2,766 | def check_response(self, response, callback, name=None):
if not (response is None or asyncio.iscoroutine(response)):
return
if not name:
if isinstance(callback, types.FunctionType): # FBV
name = "The view %s.%s" % (callback.__module__, callback.__name__)... |
Raise an error if the view returned None or an uncalled coroutine.
| 12 | 97 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def check_response(self, response, callback, name=None):
if not (response is None or asyncio.iscoroutine(response)):
return
if not name:
if i... |
2,767 | def _meta_from_array(x, columns=None, index=None, meta=None):
if x.ndim > 2:
raise ValueError(
"from_array does not input more than 2D array, got"
" array with shape %r" % (x.shape,)
)
if index is not None:
if not isinstance(index, Index):
raise... | Create empty DataFrame or Series which has correct dtype | 9 | 234 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _meta_from_array(x, columns=None, index=None, meta=None):
if x.ndim > 2:
raise ValueError(
"from_array does not input more than 2D array, got"
"... |
2,768 | def rows(self):
for row in self.row_data:
yield [
column["block"].bind(value)
for column, value in zip(self.columns, row["values"])
]
|
Iterate over the rows of the table, with each row returned as a list of BoundBlocks
| 16 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def rows(self):
for row in self.row_data:
yield [
column["block"].bind(value)
for column, value in zip(self.columns, row["values"... |
2,769 | def Uniform(name, left, right):
r
return rv(name, UniformDistribution, (left, right))
#-------------------------------------------------------------------------------
# UniformSum distribution ------------------------------------------------------
|
Create a continuous random variable with a uniform distribution.
Explanation
===========
The density of the uniform distribution is given by
.. math::
f(x) := \begin{cases}
\frac{1}{b - a} & \text{for } x \in [a,b] \\
0 & \text{otherwise... | 157 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def Uniform(name, left, right):
r
return rv(name, UniformDistribution, (left, right))
#-------------------------------------------------------------------------------
# UniformSum ... |
2,770 | def get_ttext(value):
m = _non_token_end_matcher(value)
if not m:
raise errors.HeaderParseError(
"expected ttext but found '{}'".format(value))
ttext = m.group()
value = value[len(ttext):]
ttext = ValueTerminal(ttext, 'ttext')
_validate_xtext(ttext)
return ttext, val... | ttext = <matches _ttext_matcher>
We allow any non-TOKEN_ENDS in ttext, but add defects to the token's
defects list if we find non-ttext characters. We also register defects for
*any* non-printables even though the RFC doesn't exclude all of them,
because we follow the spirit of RFC 5322.
| 47 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_ttext(value):
m = _non_token_end_matcher(value)
if not m:
raise errors.HeaderParseError(
"expected ttext but found '{}'".format(value))
ttext = m... |
2,771 | def kwargs(self, exclude=(), apply=None):
kwargs = {k: getattr(self, k) for k in self._fields if k not in exclude}
if apply is not None:
return {k: apply(v) for k, v in kwargs.items()}
else:
return kwargs
| Get instance's attributes as dict of keyword arguments.
Parameters
==========
exclude : collection of str
Collection of keywords to exclude.
apply : callable, optional
Function to apply to all values.
| 30 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def kwargs(self, exclude=(), apply=None):
kwargs = {k: getattr(self, k) for k in self._fields if k not in exclude}
if apply is not None:
return {k: apply... |
2,772 | def _execute_impl(self, *args, **kwargs) -> RayServeHandle:
return self._deployment_handle
| Does not call into anything or produce a new value, as the time
this function gets called, all child nodes are already resolved to
ObjectRefs.
| 25 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _execute_impl(self, *args, **kwargs) -> RayServeHandle:
return self._deployment_handle
```
###Assistant : Does not call into anything or produce a new value... |
2,773 | def test_settings_use_default_site(self):
context = {}
# This should use the default site
template = '{{ settings("tests.testsetting", use_default_site=True).title}}'
self.assertEqual(
self.render(template, context, request_context=False),
self.default_... |
Check that the {{ settings(use_default_site=True) }} option works with
no site in the context
| 14 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_settings_use_default_site(self):
context = {}
# This should use the default site
template = '{{ settings("tests.testsetting", use_default_site=True... |
2,774 | def test_stream_square_brackets_and_language():
infos =
d = FFmpegInfosParser(infos, "clip.mp4").parse()
assert d
assert len(d["inputs"][0]["streams"]) == 2
assert d["inputs"][0]["streams"][0]["language"] == "eng"
assert d["inputs"][0]["streams"][1]["language"] is None
|
Input #0, mpeg, from 'clip.mp4':
Duration: 00:02:15.00, start: 52874.498178, bitrate: 266 kb/s
Stream #0:0[0x1e0](eng): Video: ..., 25 tbr, 90k tbn, 50 tbc
Stream #0:1[0x1c0](und): Audio: mp2, 0 channels, s16p
At least one output file must be specified | 37 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_stream_square_brackets_and_language():
infos =
d = FFmpegInfosParser(infos, "clip.mp4").parse()
assert d
assert len(d["inputs"][0]["streams"]) == 2
assert d["... |
2,775 | async def wait(self) -> None:
if self._is_set:
return
if not self._loop:
self._loop = get_running_loop()
self._event = asyncio.Event()
await self._event.wait()
|
Wait until the flag has been set.
If the flag has already been set when this method is called, it returns immediately.
| 22 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def wait(self) -> None:
if self._is_set:
return
if not self._loop:
self._loop = get_running_loop()
self._event = asyncio.E... |
2,776 | async def get_and_submit_flow_runs(self) -> List[FlowRun]:
if not self.started:
raise RuntimeError("Agent is not started. Use `async with OrionAgent()...`")
self.logger.debug("Checking for flow runs...")
before = pendulum.now("utc").add(
seconds=self.prefetch_s... |
The principle method on agents. Queries for scheduled flow runs and submits
them for execution in parallel.
| 17 | 134 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def get_and_submit_flow_runs(self) -> List[FlowRun]:
if not self.started:
raise RuntimeError("Agent is not started. Use `async with OrionAgent()...`")
... |
2,777 | def conv_output_length(input_length, filter_size, padding, stride, dilation=1):
if input_length is None:
return None
assert padding in {"same", "valid", "full", "causal"}
dilated_filter_size = filter_size + (filter_size - 1) * (dilation - 1)
if padding in ["same", "causal"]:
output_... | Determines output length of a convolution given input length.
Args:
input_length: integer.
filter_size: integer.
padding: one of "same", "valid", "full", "causal"
stride: integer.
dilation: dilation rate, integer.
Returns:
The output length (integer).
| 32 | 68 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def conv_output_length(input_length, filter_size, padding, stride, dilation=1):
if input_length is None:
return None
assert padding in {"same", "valid", "full", "causal"... |
2,778 | def get_split_nodes(self):
rearport = path_node_to_object(self._nodes[-1])
return FrontPort.objects.filter(rear_port=rearport)
|
Return all available next segments in a split cable path.
| 10 | 7 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_split_nodes(self):
rearport = path_node_to_object(self._nodes[-1])
return FrontPort.objects.filter(rear_port=rearport)
```
###Assistant :
... |
2,779 | def get_template_names(self):
try:
names = super().get_template_names()
except ImproperlyConfigured:
# If template_name isn't specified, it's not a problem --
# we just start with an empty list.
names = []
# If the list is a queryset, we'... |
Return a list of template names to be used for the request. Must return
a list. May not be called if render_to_response is overridden.
| 24 | 113 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_template_names(self):
try:
names = super().get_template_names()
except ImproperlyConfigured:
# If template_name isn't specified, it's... |
2,780 | def remove_lines(fname, entries):
to_remove = []
for entry in entries:
msg, issue, lineno, pos, descr = entry
# 'module imported but not used'
if issue == 'F401' and handle_f401(fname, lineno):
to_remove.append(lineno)
# 'blank line(s) at end of file'
eli... | Check if we should remove lines, then do it.
Return the number of lines removed.
| 15 | 112 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def remove_lines(fname, entries):
to_remove = []
for entry in entries:
msg, issue, lineno, pos, descr = entry
# 'module imported but not used'
if issue =... |
2,781 | def _get_one_trial_job(self):
if not self.generated_hyper_configs:
ret = {
'parameter_id': '-1_0_0',
'parameter_source': 'algorithm',
'parameters': ''
}
self.send(CommandType.NoMoreTrialJobs, nni.dump(ret))
... | get one trial job, i.e., one hyperparameter configuration.
If this function is called, Command will be sent by BOHB:
a. If there is a parameter need to run, will return "NewTrialJob" with a dict:
{
'parameter_id': id of new hyperparameter
'parameter_source': 'algorithm'
... | 67 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_one_trial_job(self):
if not self.generated_hyper_configs:
ret = {
'parameter_id': '-1_0_0',
'parameter_source': 'algorit... |
2,782 | def global_array_to_host_local_array(global_inputs, global_mesh, pspecs):
def _convert(arr, pspec):
local_aval = global_mesh._global_to_local(
pxla._get_array_mapping(pspec), arr.aval)
return array.ArrayImpl(
local_aval, MeshPspecSharding(global_mesh.local_mesh, pspec),
arr._arrays,... | Converts a global `jax.Array` to a host local `jax.Array`.
You can use this function to transition to `jax.Array`. Using `jax.Array` with
`pjit` has the same semantics of using GDA with pjit i.e. all `jax.Array`
inputs to pjit should be globally shaped and the output from `pjit` will also
be globally shaped `j... | 119 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def global_array_to_host_local_array(global_inputs, global_mesh, pspecs):
def _convert(arr, pspec):
local_aval = global_mesh._global_to_local(
pxla._get_array_mapping(pspec)... |
2,783 | def __setitem__(self, key, value):
super(Py27Dict, self).__setitem__(key, value)
self.keylist.add(key)
|
Override of __setitem__ to track keys and simulate Python2.7 dict
Parameters
----------
key: hashable
value: Any
| 16 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __setitem__(self, key, value):
super(Py27Dict, self).__setitem__(key, value)
self.keylist.add(key)
```
###Assistant :
Override of __setitem... |
2,784 | def virtualenv_no_global() -> bool:
# PEP 405 compliance needs to be checked first since virtualenv >=20 would
# return True for both checks, but is only able to use the PEP 405 config.
if _running_under_venv():
return _no_global_under_venv()
if _running_under_regular_virtualenv():
... | Returns a boolean, whether running in venv with no system site-packages. | 11 | 43 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def virtualenv_no_global() -> bool:
# PEP 405 compliance needs to be checked first since virtualenv >=20 would
# return True for both checks, but is only able to use the PEP 405... |
2,785 | def autocomplete(self):
texts = []
for field in self.search_fields:
for current_field, value in self.prepare_field(self.obj, field):
if isinstance(current_field, AutocompleteField):
texts.append((value))
return " ".join(texts)
|
Returns all values to index as "autocomplete". This is the value of all AutocompleteFields
| 14 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def autocomplete(self):
texts = []
for field in self.search_fields:
for current_field, value in self.prepare_field(self.obj, field):
if i... |
2,786 | def list_to_tuple(maybe_list):
if isinstance(maybe_list, list):
return tuple(maybe_list)
return maybe_list
| Datasets will stack the list of tensor, so switch them to tuples. | 12 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def list_to_tuple(maybe_list):
if isinstance(maybe_list, list):
return tuple(maybe_list)
return maybe_list
```
###Assistant : Datasets will stack the list o... |
2,787 | def test_not_recorded_for_unused(self, dag_maker, xcom_value):
with dag_maker(dag_id="test_not_recorded_for_unused") as dag:
| A value not used for task-mapping should not be recorded. | 10 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_not_recorded_for_unused(self, dag_maker, xcom_value):
with dag_maker(dag_id="test_not_recorded_for_unused") as dag:
```
###Assistant : A value not used... |
2,788 | def _ragged_tensor_mse(y_true, y_pred):
return _ragged_tensor_apply_loss(mean_squared_error, y_true, y_pred)
@keras_export(
"keras.metrics.mean_absolute_error",
"keras.metrics.mae",
"keras.metrics.MAE",
"keras.losses.mean_absolute_error",
"keras.losses.mae",
"keras.losses.MAE",
)
@tf.... | Implements support for handling RaggedTensors.
Args:
y_true: RaggedTensor truth values. shape = `[batch_size, d0, .. dN]`.
y_pred: RaggedTensor predicted values. shape = `[batch_size, d0, .. dN]`.
Returns:
Mean squared error values. shape = `[batch_size, d0, .. dN-1]`.
When the number ... | 69 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _ragged_tensor_mse(y_true, y_pred):
return _ragged_tensor_apply_loss(mean_squared_error, y_true, y_pred)
@keras_export(
"keras.metrics.mean_absolute_error",
"keras.met... |
2,789 | def test_does_not_allow_extra_kwargs() -> None:
template = "This is a {foo} test."
with pytest.raises(KeyError):
formatter.format(template, foo="good", bar="oops")
| Test formatting does not allow extra key word arguments. | 9 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_does_not_allow_extra_kwargs() -> None:
template = "This is a {foo} test."
with pytest.raises(KeyError):
formatter.format(template, foo="good", bar="oops")
... |
2,790 | def score_samples(self, X):
check_is_fitted(self)
X = check_array(X, accept_sparse="csr")
distances_X, neighbors_indices_X = self.kneighbors(
X, n_neighbors=self.n_neighbors_
)
X_lrd = self._local_reachability_density(distances_X, neighbors_indices_X)
... | Opposite of the Local Outlier Factor of X.
It is the opposite as bigger is better, i.e. large values correspond
to inliers.
**Only available for novelty detection (when novelty is set to True).**
The argument X is supposed to contain *new data*: if X contains a
point from train... | 148 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def score_samples(self, X):
check_is_fitted(self)
X = check_array(X, accept_sparse="csr")
distances_X, neighbors_indices_X = self.kneighbors(
X,... |
2,791 | def get_payroll_period_days(start_date, end_date, employee, company=None):
if not company:
company = frappe.db.get_value("Employee", employee, "company")
payroll_period = frappe.db.sql(
,
{"company": company, "start_date": start_date, "end_date": end_date},
)
if len(payroll_period) > 0:
actual_no_of_days =... |
select name, start_date, end_date
from `tabPayroll Period`
where
company=%(company)s
and %(start_date)s between start_date and end_date
and %(end_date)s between start_date and end_date
| 21 | 63 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_payroll_period_days(start_date, end_date, employee, company=None):
if not company:
company = frappe.db.get_value("Employee", employee, "company")
payroll_period = frappe.db.sql(
... |
2,792 | def density(B, nodes):
n = len(B)
m = nx.number_of_edges(B)
nb = len(nodes)
nt = n - nb
if m == 0: # includes cases n==0 and n==1
d = 0.0
else:
if B.is_directed():
d = m / (2 * nb * nt)
else:
d = m / (nb * nt)
return d
| Returns density of bipartite graph B.
Parameters
----------
B : NetworkX graph
nodes: list or container
Nodes in one node set of the bipartite graph.
Returns
-------
d : float
The bipartite density
Examples
--------
>>> from networkx.algorithms import bipartite
... | 113 | 52 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def density(B, nodes):
n = len(B)
m = nx.number_of_edges(B)
nb = len(nodes)
nt = n - nb
if m == 0: # includes cases n==0 and n==1
d = 0.0
else:
... |
2,793 | def redirect_or_json(origin, msg, status=""):
if request.headers.get('Accept') == 'application/json':
return {'status': status, 'message': msg}
else:
if status:
flash(msg, status)
else:
flash(msg)
return redirect(origin)
############################... |
Some endpoints are called by javascript,
returning json will allow us to more elegantly handle side-effects in-page
| 17 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def redirect_or_json(origin, msg, status=""):
if request.headers.get('Accept') == 'application/json':
return {'status': status, 'message': msg}
else:
if status:
... |
2,794 | def _map_drop_idx_to_infrequent(self, feature_idx, drop_idx):
if not self._infrequent_enabled:
return drop_idx
default_to_infrequent = self._default_to_infrequent_mappings[feature_idx]
if default_to_infrequent is None:
return drop_idx
# Raise error when... | Convert `drop_idx` into the index for infrequent categories.
If there are no infrequent categories, then `drop_idx` is
returned. This method is called in `_compute_drop_idx` when the `drop`
parameter is an array-like.
| 31 | 62 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _map_drop_idx_to_infrequent(self, feature_idx, drop_idx):
if not self._infrequent_enabled:
return drop_idx
default_to_infrequent = self._default_to_... |
2,795 | def test_dashboard_module_decorator(enable_test_module):
head_cls_list = dashboard_utils.get_all_modules(dashboard_utils.DashboardHeadModule)
agent_cls_list = dashboard_utils.get_all_modules(
dashboard_utils.DashboardAgentModule
)
assert any(cls.__name__ == "TestHead" for cls in head_cls_list)
... |
import os
import ray.dashboard.utils as dashboard_utils
os.environ.pop("RAY_DASHBOARD_MODULE_TEST")
head_cls_list = dashboard_utils.get_all_modules(
dashboard_utils.DashboardHeadModule)
agent_cls_list = dashboard_utils.get_all_modules(
dashboard_utils.DashboardAgentModule)
print(head_cls_list)
print(a... | 34 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_dashboard_module_decorator(enable_test_module):
head_cls_list = dashboard_utils.get_all_modules(dashboard_utils.DashboardHeadModule)
agent_cls_list = dashboard_utils.get_all... |
2,796 | def parsestr(self, text, headersonly=False):
return self.parse(StringIO(text), headersonly=headersonly) | Create a message structure from a string.
Returns the root of the message structure. Optional headersonly is a
flag specifying whether to stop parsing after reading the headers or
not. The default is False, meaning it parses the entire contents of
the file.
| 43 | 7 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def parsestr(self, text, headersonly=False):
return self.parse(StringIO(text), headersonly=headersonly)
```
###Assistant : Create a message structure from a stri... |
2,797 | def get_prerequisite_model(queryset):
if not queryset.exists():
for prereq in getattr(queryset.model, 'prerequisite_models', []):
model = apps.get_model(prereq)
if not model.objects.exists():
return model
|
Return any prerequisite model that must be created prior to creating
an instance of the current model.
| 17 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_prerequisite_model(queryset):
if not queryset.exists():
for prereq in getattr(queryset.model, 'prerequisite_models', []):
model = apps.get_model(prereq)
... |
2,798 | def filter_empty_gradients(grads_and_vars):
grads_and_vars = tuple(grads_and_vars)
if not grads_and_vars:
return grads_and_vars
filtered = []
vars_with_empty_grads = []
for grad, var in grads_and_vars:
if grad is None:
vars_with_empty_grads.append(var)
else:... | Filter out `(grad, var)` pairs that have a gradient equal to `None`. | 12 | 95 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def filter_empty_gradients(grads_and_vars):
grads_and_vars = tuple(grads_and_vars)
if not grads_and_vars:
return grads_and_vars
filtered = []
vars_with_empty_gr... |
2,799 | def real_gaunt(l_1, l_2, l_3, m_1, m_2, m_3, prec=None):
r
l_1, l_2, l_3, m_1, m_2, m_3 = [
as_int(i) for i in (l_1, l_2, l_3, m_1, m_2, m_3)]
# check for quick exits
if sum(1 for i in (m_1, m_2, m_3) if i < 0) % 2:
return S.Zero # odd number of negative m
if (l_1 + l_2 + l_3) % 2:... |
Calculate the real Gaunt coefficient.
Explanation
===========
The real Gaunt coefficient is defined as the integral over three
real spherical harmonics:
.. math::
\begin{aligned}
\operatorname{RealGaunt}(l_1,l_2,l_3,m_1,m_2,m_3)
&=\int Z^{m_1}_{l_1}(\Omega)
... | 429 | 231 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def real_gaunt(l_1, l_2, l_3, m_1, m_2, m_3, prec=None):
r
l_1, l_2, l_3, m_1, m_2, m_3 = [
as_int(i) for i in (l_1, l_2, l_3, m_1, m_2, m_3)]
# check for quick exits
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.