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 |
|---|---|---|---|---|---|---|
300 | def test_type_eventpage_two_indexes(self):
self.make_event_section("Other events")
self.assertEqual(
self.get_best_root({"page_type": "tests.EventPage"}), self.home_page
)
|
The chooser should start at the home page, as there are two
EventIndexes with EventPages.
| 15 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_type_eventpage_two_indexes(self):
self.make_event_section("Other events")
self.assertEqual(
self.get_best_root({"page_type": "tests.EventPage"})... |
301 | def parse(self, filename, constraint):
# type: (str, bool) -> Iterator[ParsedLine]
yield from self._parse_and_recurse(filename, constraint)
| Parse a given file, yielding parsed lines.
| 7 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def parse(self, filename, constraint):
# type: (str, bool) -> Iterator[ParsedLine]
yield from self._parse_and_recurse(filename, constraint)
```
###Assis... |
302 | def sparse_bincount(inputs, depth, binary_output, dtype, count_weights=None):
result = tf.sparse.bincount(
inputs,
weights=count_weights,
minlength=depth,
maxlength=depth,
axis=-1,
binary_output=binary_output,
)
result = tf.cast(result, dtype)
if inpu... | Apply binary or count encoding to an input and return a sparse tensor. | 13 | 44 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def sparse_bincount(inputs, depth, binary_output, dtype, count_weights=None):
result = tf.sparse.bincount(
inputs,
weights=count_weights,
minlength=depth,
... |
303 | def unmarshal(self, serialized_data):
logger.debug("data type: %s", type(serialized_data))
try:
retval = self._unmarshal(serialized_data)
except Exception as err:
msg = f"Error unserializing data for type {type(serialized_data)}: {str(err)}"
raise Fac... | Unserialize data to its original object type
Parameters
----------
serialized_data: varies
Data in serializer format that is to be unmarshalled to its original object
Returns
-------
data: varies
The data in a python object format
Examp... | 50 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def unmarshal(self, serialized_data):
logger.debug("data type: %s", type(serialized_data))
try:
retval = self._unmarshal(serialized_data)
except ... |
304 | def copyDataFiles():
for included_datafile in getIncludedDataFiles():
# TODO: directories should be resolved to files.
if (
not isinstance(included_datafile, (IncludedDataFile))
or included_datafile.needsCopy()
):
_handleDataFile(
inc... | Copy the data files needed for standalone distribution.
Notes:
This is for data files only, not DLLs or even extension modules,
those must be registered as entry points, and would not go through
necessary handling if provided like this.
| 39 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def copyDataFiles():
for included_datafile in getIncludedDataFiles():
# TODO: directories should be resolved to files.
if (
not isinstance(included_data... |
305 | def toggler(self, attr):
if attr not in self._options:
raise KeyError("No such option: %s" % attr)
o = self._options[attr]
if o.typespec != bool:
raise ValueError("Toggler can only be used with boolean options")
|
Generate a toggler for a boolean attribute. This returns a callable
that takes no arguments.
| 15 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def toggler(self, attr):
if attr not in self._options:
raise KeyError("No such option: %s" % attr)
o = self._options[attr]
if o.typespec != bool:... |
306 | def disable_terminal_wrapping(monkeypatch):
monkeypatch.setattr(
"prefect.cli.profile.console", rich.console.Console(soft_wrap=True)
)
|
Sometimes, line wrapping makes it hard to make deterministic assertions about the
output of a CLI command. Wrapping can be disabled by using this fixture.
| 25 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def disable_terminal_wrapping(monkeypatch):
monkeypatch.setattr(
"prefect.cli.profile.console", rich.console.Console(soft_wrap=True)
)
```
###Assistant :
... |
307 | def __add__(self, other):
rank = (self.rank() + other) % self.cardinality
rv = self.unrank_lex(self.size, rank)
rv._rank = rank
return rv
| Return permutation that is other higher in rank than self.
The rank is the lexicographical rank, with the identity permutation
having rank of 0.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> I = Permutation([0, 1, 2, 3])
>>> a = Permutat... | 57 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __add__(self, other):
rank = (self.rank() + other) % self.cardinality
rv = self.unrank_lex(self.size, rank)
rv._rank = rank
return rv
``... |
308 | def test_set_presence_from_syncing_not_set(self):
user_id = "@test:server"
status_msg = "I'm here!"
self._set_presencestate_with_status_msg(
user_id, PresenceState.UNAVAILABLE, status_msg
)
self.get_success(
self.presence_handler.user_syncing(us... | Test that presence is not set by syncing if affect_presence is false | 12 | 43 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_set_presence_from_syncing_not_set(self):
user_id = "@test:server"
status_msg = "I'm here!"
self._set_presencestate_with_status_msg(
use... |
309 | def test_stringy_integers(self):
input = {
"a": "100",
"b": {
"foo": 99,
"bar": "-98",
},
"d": "0999",
}
output = copy_and_fixup_power_levels_contents(input)
expected_output = {
"a": 100,... | String representations of decimal integers are converted to integers. | 9 | 37 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_stringy_integers(self):
input = {
"a": "100",
"b": {
"foo": 99,
"bar": "-98",
},
"d"... |
310 | def get_ec_matching_query(bank_account, company, amount_condition):
# get matching Expense Claim query
mode_of_payments = [
x["parent"]
for x in frappe.db.get_all(
"Mode of Payment Account", filters={"default_account": bank_account}, fields=["parent"]
)
]
mode_of_payments = "('" + "', '".join(mode_of_payme... |
SELECT
( CASE WHEN employee = %(party)s THEN 1 ELSE 0 END
+ 1 ) AS rank,
'Expense Claim' as doctype,
name,
total_sanctioned_amount as paid_amount,
'' as reference_no,
'' as reference_date,
employee as party,
'Employee' as party_type,
posting_date,
'{company_currency}' as currency
F... | 65 | 41 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_ec_matching_query(bank_account, company, amount_condition):
# get matching Expense Claim query
mode_of_payments = [
x["parent"]
for x in frappe.db.get_all(
"Mode of Payment ... |
311 | def run_exec_plan(cls, plan, index_cols, dtypes, columns):
omniSession = DbWorker()
# First step is to make sure all partitions are in HDK.
frames = plan.collect_frames()
for frame in frames:
if frame._partitions.size != 1:
raise NotImplementedError(... |
Run execution plan in HDK storage format to materialize frame.
Parameters
----------
plan : DFAlgNode
A root of an execution plan tree.
index_cols : list of str
A list of index columns.
dtypes : pandas.Index
Column data types.
... | 53 | 114 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def run_exec_plan(cls, plan, index_cols, dtypes, columns):
omniSession = DbWorker()
# First step is to make sure all partitions are in HDK.
frames = plan.co... |
312 | def to_numeric_dtype(dtype):
dtype = np.dtype(dtype)
return np.dtype('int32') if dtype == np.dtype('bool') else dtype
| Promotes a dtype into an numeric dtype, if it is not already one. | 13 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def to_numeric_dtype(dtype):
dtype = np.dtype(dtype)
return np.dtype('int32') if dtype == np.dtype('bool') else dtype
```
###Assistant : Promotes a dtype into an numeric... |
313 | def test_do_schedule_max_active_runs_task_removed(self, session, dag_maker):
with dag_maker(
dag_id='test_do_schedule_max_active_runs_task_removed',
start_date=DEFAULT_DATE,
schedule_interval='@once',
max_active_runs=1,
session=session,
... | Test that tasks in removed state don't count as actively running. | 11 | 58 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_do_schedule_max_active_runs_task_removed(self, session, dag_maker):
with dag_maker(
dag_id='test_do_schedule_max_active_runs_task_removed',
... |
314 | def forward(self, xs, masks):
if isinstance(self.embed, (Conv2dSubsampling, VGG2L)):
xs, masks = self.embed(xs, masks)
else:
xs = self.embed(xs)
xs, masks = self.encoders(xs, masks)
if isinstance(xs, tuple):
xs = xs[0]
if self.normal... | Encode input sequence.
:param torch.Tensor xs: input tensor
:param torch.Tensor masks: input mask
:return: position embedded tensor and mask
:rtype Tuple[torch.Tensor, torch.Tensor]:
| 22 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def forward(self, xs, masks):
if isinstance(self.embed, (Conv2dSubsampling, VGG2L)):
xs, masks = self.embed(xs, masks)
else:
xs = self.embed(... |
315 | def save_class(self):
if gtff.REMEMBER_CONTEXTS:
controllers[self.PATH] = self
| Saves the current instance of the class to be loaded later | 11 | 7 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def save_class(self):
if gtff.REMEMBER_CONTEXTS:
controllers[self.PATH] = self
```
###Assistant : Saves the current instance of the class to be load... |
316 | def _decode_messages(self, messages):
messages_len = len(messages)
# if it was one message, then its old style
if messages_len == 1:
payload = salt.payload.loads(messages[0])
# 2 includes a header which says who should do it
elif messages_len == 2:
... |
Take the zmq messages, decrypt/decode them into a payload
:param list messages: A list of messages to be decoded
| 19 | 119 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _decode_messages(self, messages):
messages_len = len(messages)
# if it was one message, then its old style
if messages_len == 1:
payload = sa... |
317 | def test_get_release_wheel_url():
# This should be a commit for which wheels have already been built for
# all platforms and python versions at
# `s3://ray-wheels/releases/2.2.0/<commit>/`.
test_commits = {"2.2.0": "b6af0887ee5f2e460202133791ad941a41f15beb"}
for sys_platform in ["darwin", "linu... | Test the code that generates the filenames of the `release` branch wheels. | 12 | 74 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_get_release_wheel_url():
# This should be a commit for which wheels have already been built for
# all platforms and python versions at
# `s3://ray-wheels/releases/2... |
318 | def test_keep_media_by_date(self) -> None:
# timestamp before upload
now_ms = self.clock.time_msec()
server_and_media_id = self._create_media()
self._access_media(server_and_media_id)
channel = self.make_request(
"POST",
self.url + "?before_ts=... |
Tests that media is not deleted if it is newer than `before_ts`
| 12 | 61 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_keep_media_by_date(self) -> None:
# timestamp before upload
now_ms = self.clock.time_msec()
server_and_media_id = self._create_media()
sel... |
319 | def test_fetch_openml_requires_pandas_in_future(monkeypatch):
params = {"as_frame": False, "parser": "auto"}
data_id = 1119
try:
check_pandas_support("test_fetch_openml_requires_pandas")
except ImportError:
_monkey_patch_webbased_functions(monkeypatch, data_id, True)
warn_ms... | Check that we raise a warning that pandas will be required in the future. | 14 | 112 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_fetch_openml_requires_pandas_in_future(monkeypatch):
params = {"as_frame": False, "parser": "auto"}
data_id = 1119
try:
check_pandas_support("test_fetch_ope... |
320 | def get_connection(self, url, proxies=None):
proxy = select_proxy(url, proxies)
if proxy:
proxy = prepend_scheme_if_needed(proxy, "http")
proxy_url = parse_url(proxy)
if not proxy_url.host:
raise InvalidProxyURL(
"Please c... | Returns a urllib3 connection for the given URL. This should not be
called from user code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param url: The URL to connect to.
:param proxies: (optional) A Requests-style dictionary of p... | 48 | 62 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_connection(self, url, proxies=None):
proxy = select_proxy(url, proxies)
if proxy:
proxy = prepend_scheme_if_needed(proxy, "http")
pr... |
321 | def feature_engineering_expand_all(self, dataframe, period, **kwargs):
dataframe["%-rsi-period"] = ta.RSI(dataframe, timeperiod=period)
dataframe["%-mfi-period"] = ta.MFI(dataframe, timeperiod=period)
dataframe["%-adx-period"] = ta.ADX(dataframe, timeperiod=period)
dataframe["%... |
*Only functional with FreqAI enabled strategies*
This function will automatically expand the defined features on the config defined
`indicator_periods_candles`, `include_timeframes`, `include_shifted_candles`, and
`include_corr_pairs`. In other words, a single feature defined in this fu... | 106 | 70 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def feature_engineering_expand_all(self, dataframe, period, **kwargs):
dataframe["%-rsi-period"] = ta.RSI(dataframe, timeperiod=period)
dataframe["%-mfi-period"] = ... |
322 | def get_script_prefix(self, scope):
if settings.FORCE_SCRIPT_NAME:
return settings.FORCE_SCRIPT_NAME
return scope.get("root_path", "") or ""
|
Return the script prefix to use from either the scope or a setting.
| 13 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_script_prefix(self, scope):
if settings.FORCE_SCRIPT_NAME:
return settings.FORCE_SCRIPT_NAME
return scope.get("root_path", "") or ""
```... |
323 | def test_get_first_menu_and_fail():
part_one = f
part_two = f
command = ["storage", "create"]
invoke_and_assert_in(
command=command,
desired_contents=(part_one, part_two),
expected_code=1,
user_input=f"{INVALID_OPTION}\n",
)
|
Make sure that our utility function is returning as expected
Found the following storage types:
0) Azure Blob Storage
Store data in an Azure blob storage container.
1) File Storage
Store data as a file on local or remote file systems.
2) Google Cloud Storage
Store data ... | 72 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_get_first_menu_and_fail():
part_one = f
part_two = f
command = ["storage", "create"]
invoke_and_assert_in(
command=command,
desired_contents=(p... |
324 | def check_planarity(G, counterexample=False):
planarity_state = LRPlanarity(G)
embedding = planarity_state.lr_planarity()
if embedding is None:
# graph is not planar
if counterexample:
return False, get_counterexample(G)
else:
return False, None
else... | Check if a graph is planar and return a counterexample or an embedding.
A graph is planar iff it can be drawn in a plane without
any edge intersections.
Parameters
----------
G : NetworkX graph
counterexample : bool
A Kuratowski subgraph (to proof non planarity) is only returned if set... | 228 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def check_planarity(G, counterexample=False):
planarity_state = LRPlanarity(G)
embedding = planarity_state.lr_planarity()
if embedding is None:
# graph is not plana... |
325 | def _get_bool(val) -> Optional[bool]:
if isinstance(val, bool):
return val
elif isinstance(val, str):
if val.strip().lower() == 'true':
return True
elif val.strip().lower() == 'false':
return False
return None
|
Converts val to bool if can be done with certainty.
If we cannot infer intention we return None.
| 18 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_bool(val) -> Optional[bool]:
if isinstance(val, bool):
return val
elif isinstance(val, str):
if val.strip().lower() == 'true':
return True
... |
326 | def load_data_ptb(batch_size, max_window_size, num_noise_words):
sentences = read_ptb()
vocab = d2l.Vocab(sentences, min_freq=10)
subsampled, counter = subsample(sentences, vocab)
corpus = [vocab[line] for line in subsampled]
all_centers, all_contexts = get_centers_and_contexts(
corpus,... | Download the PTB dataset and then load it into memory.
Defined in :numref:`subsec_word2vec-minibatch-loading` | 13 | 76 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def load_data_ptb(batch_size, max_window_size, num_noise_words):
sentences = read_ptb()
vocab = d2l.Vocab(sentences, min_freq=10)
subsampled, counter = subsample(sentences, ... |
327 | async def async_config_changed(self) -> None:
assert self.driver is not None
await self.hass.async_add_executor_job(self.driver.config_changed)
| Call config changed which writes out the new config to disk. | 11 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def async_config_changed(self) -> None:
assert self.driver is not None
await self.hass.async_add_executor_job(self.driver.config_changed)
```
###A... |
328 | def setDebugActions(self, startAction, successAction, exceptionAction):
self.debugActions = (startAction or _defaultStartDebugAction,
successAction or _defaultSuccessDebugAction,
exceptionAction or _defaultExceptionDebugAction)
self.debu... |
Enable display of debugging messages while doing pattern matching.
| 9 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def setDebugActions(self, startAction, successAction, exceptionAction):
self.debugActions = (startAction or _defaultStartDebugAction,
successAct... |
329 | def get_qty_amount_data_for_cumulative(pr_doc, doc, items=None):
if items is None:
items = []
sum_qty, sum_amt = [0, 0]
doctype = doc.get("parenttype") or doc.doctype
date_field = (
"transaction_date" if frappe.get_meta(doctype).has_field("transaction_date") else "posting_date"
)
child_doctype = "{0} Item".... | and `tab{child_doc}`.warehouse in ({warehouses})
SELECT `tab{child_doc}`.stock_qty,
`tab{child_doc}`.amount
FROM `tab{child_doc}`, `tab{parent_doc}`
WHERE
`tab{child_doc}`.parent = `tab{parent_doc}`.name and `tab{parent_doc}`.{date_field}
between %s and %s and `tab{parent_doc}`.docstatus = 1
{condi... | 28 | 99 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_qty_amount_data_for_cumulative(pr_doc, doc, items=None):
if items is None:
items = []
sum_qty, sum_amt = [0, 0]
doctype = doc.get("parenttype") or doc.doctype
date_field = (
... |
330 | def make_system(A, M, x0, b):
A_ = A
A = aslinearoperator(A)
if A.shape[0] != A.shape[1]:
raise ValueError(f'expected square matrix, but got shape={(A.shape,)}')
N = A.shape[0]
b = asanyarray(b)
if not (b.shape == (N,1) or b.shape == (N,)):
raise ValueError(f'shapes of A... | Make a linear system Ax=b
Parameters
----------
A : LinearOperator
sparse or dense matrix (or any valid input to aslinearoperator)
M : {LinearOperator, Nones}
preconditioner
sparse or dense matrix (or any valid input to aslinearoperator)
x0 : {array_like, str, None}
... | 123 | 62 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def make_system(A, M, x0, b):
A_ = A
A = aslinearoperator(A)
if A.shape[0] != A.shape[1]:
raise ValueError(f'expected square matrix, but got shape={(A.shape,)}')
... |
331 | def dodecahedral_graph(create_using=None):
G = LCF_graph(20, [10, 7, 4, -4, -7, 10, -4, 7, -7, 4], 2, create_using)
G.name = "Dodecahedral Graph"
return G
|
Returns the Platonic Dodecahedral graph.
The dodecahedral graph has 20 nodes and 30 edges. The skeleton of the
dodecahedron forms a graph. It is one of 5 Platonic graphs [1]_.
It can be described in LCF notation as:
``[10, 7, 4, -4, -7, 10, -4, 7, -7, 4]^2`` [2]_.
Parameters
----------
... | 91 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def dodecahedral_graph(create_using=None):
G = LCF_graph(20, [10, 7, 4, -4, -7, 10, -4, 7, -7, 4], 2, create_using)
G.name = "Dodecahedral Graph"
return G
```
... |
332 | def arc_tangent(value, default=_SENTINEL):
try:
return math.atan(float(value))
except (ValueError, TypeError):
if default is _SENTINEL:
raise_no_default("atan", value)
return default
| Filter and function to get arc tangent of the value. | 10 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def arc_tangent(value, default=_SENTINEL):
try:
return math.atan(float(value))
except (ValueError, TypeError):
if default is _SENTINEL:
raise_no_defa... |
333 | def sparse_top_k_categorical_matches(y_true, y_pred, k=5):
reshape_matches = False
y_true = tf.convert_to_tensor(y_true)
y_pred = tf.convert_to_tensor(y_pred)
y_true_rank = y_true.shape.ndims
y_pred_rank = y_pred.shape.ndims
y_true_org_shape = tf.shape(y_true)
# Flatten y_pred to (batc... | Creates float Tensor, 1.0 for label-TopK_prediction match, 0.0 for mismatch.
Args:
y_true: tensor of true targets.
y_pred: tensor of predicted targets.
k: (Optional) Number of top elements to look at for computing accuracy.
Defaults to 5.
Returns:
Match tensor: 1.0 for label-pr... | 46 | 92 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def sparse_top_k_categorical_matches(y_true, y_pred, k=5):
reshape_matches = False
y_true = tf.convert_to_tensor(y_true)
y_pred = tf.convert_to_tensor(y_pred)
y_true_ran... |
334 | def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
company_currency = erpnext.get_company_currency(filters.get("company"))
def get_accounts(with_account_type_filter):
account_type_condition = ""
if with_account_type_filter:
account_type_condition = "AND account_type in %(account_types... |
SELECT name, parent_account
FROM `tabAccount`
WHERE `tabAccount`.docstatus!=2
{account_type_condition}
AND is_group = 0
AND company = %(company)s
AND disabled = %(disabled)s
AND (account_currency = %(currency)s or ifnull(account_currency, '') = '')
AND `{searchfield}` LIKE %(txt)s
... | 42 | 57 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def tax_account_query(doctype, txt, searchfield, start, page_len, filters):
company_currency = erpnext.get_company_currency(filters.get("company"))
def get_accounts(with_account_type_filt... |
335 | def test_add_post_duplicate_choose_permission(self):
# Create group with access to admin and add permission.
bakers_group = Group.objects.create(name="Bakers")
access_admin_perm = Permission.objects.get(
content_type__app_label="wagtailadmin", codename="access_admin"
... |
When a duplicate image is added but the user doesn't have permission to choose the original image,
the add views lets the user upload it as if it weren't a duplicate.
| 31 | 49 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_add_post_duplicate_choose_permission(self):
# Create group with access to admin and add permission.
bakers_group = Group.objects.create(name="Bakers")
... |
336 | def netmiko_commands(*commands, **kwargs):
conn = _netmiko_conn(**kwargs)
ret = []
for cmd in commands:
ret.append(conn.send_command(cmd))
return ret
@proxy_napalm_wrap |
.. versionadded:: 2019.2.0
Invoke one or more commands to be executed on the remote device, via Netmiko.
Returns a list of strings, with the output from each command.
commands
A list of commands to be executed.
expect_string
Regular expression pattern to use for determining end o... | 157 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def netmiko_commands(*commands, **kwargs):
conn = _netmiko_conn(**kwargs)
ret = []
for cmd in commands:
ret.append(conn.send_command(cmd))
return ret
@proxy_na... |
337 | def decoder(self, side):
input_ = Input(shape=(8, 8, 512))
var_x = input_
var_x = UpscaleBlock(256, activation="leakyrelu")(var_x)
var_x = UpscaleBlock(128, activation="leakyrelu")(var_x)
var_x = UpscaleBlock(64, activation="leakyrelu")(var_x)
var_x = Conv... | The original Faceswap Decoder Network.
The decoders for the original model have separate weights for each side "A" and "B", so two
instances are created in :func:`build_model`, one for each side.
Parameters
----------
side: str
Either `"a` or `"b"`. This is... | 63 | 58 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def decoder(self, side):
input_ = Input(shape=(8, 8, 512))
var_x = input_
var_x = UpscaleBlock(256, activation="leakyrelu")(var_x)
var_x = Upsca... |
338 | def test_users_getting_add_peer_event(self) -> None:
streams_to_sub = ["multi_user_stream"]
othello = self.example_user("othello")
cordelia = self.example_user("cordelia")
iago = self.example_user("iago")
orig_user_ids_to_subscribe = [self.test_user.id, othello.id]
... |
Check users getting add_peer_event is correct
| 6 | 101 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_users_getting_add_peer_event(self) -> None:
streams_to_sub = ["multi_user_stream"]
othello = self.example_user("othello")
cordelia = self.example_us... |
339 | def show_trace_2d(f, results):
d2l.set_figsize()
d2l.plt.plot(*zip(*results), '-o', color='#ff7f0e')
x1, x2 = d2l.meshgrid(d2l.arange(-5.5, 1.0, 0.1),
d2l.arange(-3.0, 1.0, 0.1))
d2l.plt.contour(x1, x2, f(x1, x2), colors='#1f77b4')
d2l.plt.xlabel('x1')
d2l.plt.ylab... | Show the trace of 2D variables during optimization.
Defined in :numref:`subsec_gd-learningrate` | 11 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def show_trace_2d(f, results):
d2l.set_figsize()
d2l.plt.plot(*zip(*results), '-o', color='#ff7f0e')
x1, x2 = d2l.meshgrid(d2l.arange(-5.5, 1.0, 0.1),
... |
340 | def test_dataset(ray_start_4_cpus, use_local):
model_creator = mlp_identity.model_creator
optimizer_creator = mlp_identity.optimizer_creator
dataset_creator = mlp_identity.dataset_creator
DatasetOperator = TrainingOperator.from_creators(
model_creator=model_creator,
optimizer_crea... |
This test tries training the mlp_identity example. We check the accuracy of
the model as an all inclusive way of ensuring that we are properly sharding
and iterating over the entire dataset (instead of repeating the first set
of points for example).
| 42 | 51 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_dataset(ray_start_4_cpus, use_local):
model_creator = mlp_identity.model_creator
optimizer_creator = mlp_identity.optimizer_creator
dataset_creator = mlp_identity.... |
341 | def lovasz_softmax_flat(probas, labels, classes='present', weighted=None):
if probas.numel() == 0:
# only void pixels, the gradients should be 0
return probas * 0.
C = probas.size(1)
losses = []
class_to_sum = list(range(C)) if classes in ['all', 'present'] else classes
for c in... |
Multi-class Lovasz-Softmax loss
probas: [P, C] Variable, class probabilities at each prediction (between 0 and 1)
labels: [P] Tensor, ground truth labels (between 0 and C - 1)
classes: 'all' for all, 'present' for classes present in labels, or a list of classes to average.
| 45 | 115 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def lovasz_softmax_flat(probas, labels, classes='present', weighted=None):
if probas.numel() == 0:
# only void pixels, the gradients should be 0
return probas * 0.
... |
342 | def mixin_distributed_feature_parser(parser):
gp = add_arg_group(parser, title='Distributed')
gp.add_argument(
'--quiet-remote-logs',
action='store_true',
default=False,
help='Do not display the streaming of remote logs on local console',
)
gp.add_argument(
... | Mixing in arguments required by :class:`BaseDeployment` into the given parser.
:param parser: the parser instance to which we add arguments
The files on the host to be uploaded to the remote
workspace. This can be useful when your Deployment has more
file dependencies beyond a single YAML file, e.g.
Python fil... | 121 | 53 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def mixin_distributed_feature_parser(parser):
gp = add_arg_group(parser, title='Distributed')
gp.add_argument(
'--quiet-remote-logs',
action='store_true',
... |
343 | def get_bootstrap_modules():
# Import 'struct' modules to get real paths to module file names.
mod_struct = __import__('struct')
# Basic modules necessary for the bootstrap process.
loader_mods = TOC()
loaderpath = os.path.join(HOMEPATH, 'PyInstaller', 'loader')
# On some platforms (Windows... |
Get TOC with the bootstrapping modules and their dependencies.
:return: TOC with modules
| 13 | 155 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_bootstrap_modules():
# Import 'struct' modules to get real paths to module file names.
mod_struct = __import__('struct')
# Basic modules necessary for the bootstrap ... |
344 | def getquoted(self):
if self.is_geometry:
# Psycopg will figure out whether to use E'\\000' or '\000'.
return b"%s(%s)" % (
b"ST_GeogFromWKB" if self.geography else b"ST_GeomFromEWKB",
self._adapter.getquoted(),
)
else:
... |
Return a properly quoted string for use in PostgreSQL/PostGIS.
| 9 | 41 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def getquoted(self):
if self.is_geometry:
# Psycopg will figure out whether to use E'\\000' or '\000'.
return b"%s(%s)" % (
b"ST_Geog... |
345 | def _set_skip_list(self) -> None:
if self._skip_num == 1 and not self._alignments.data:
logger.debug("No frames to be skipped")
return
skip_list = []
for idx, filename in enumerate(self._images.file_list):
if idx % self._skip_num != 0:
... | Add the skip list to the image loader
Checks against `extract_every_n` and the existence of alignments data (can exist if
`skip_existing` or `skip_existing_faces` has been provided) and compiles a list of frame
indices that should not be processed, providing these to :class:`lib.image.ImagesLo... | 42 | 90 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _set_skip_list(self) -> None:
if self._skip_num == 1 and not self._alignments.data:
logger.debug("No frames to be skipped")
return
skip_l... |
346 | def caplog(caplog):
config = setup_logging()
for name, logger_config in config["loggers"].items():
if not logger_config.get("propagate", True):
logger = get_logger(name)
logger.handlers.append(caplog.handler)
yield caplog
|
Overrides caplog to apply to all of our loggers that do not propagate and
consequently would not be captured by caplog.
| 21 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def caplog(caplog):
config = setup_logging()
for name, logger_config in config["loggers"].items():
if not logger_config.get("propagate", True):
logger = ge... |
347 | def _show_mesh(self, mesh_ids, face_index, detected_face, top_left):
state = "normal" if (self._tk_vars["selected_editor"].get() != "Mask" or
self._optional_annotations["mesh"]) else "hidden"
kwargs = dict(polygon=dict(fill="", width=2, outline=self._canvas.control_... | Display the mesh annotation for the given face, at the given location.
Parameters
----------
mesh_ids: dict
Dictionary containing the `polygon` and `line` tkinter canvas identifiers that make up
the mesh for the given face
face_index: int
The face in... | 73 | 57 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _show_mesh(self, mesh_ids, face_index, detected_face, top_left):
state = "normal" if (self._tk_vars["selected_editor"].get() != "Mask" or
se... |
348 | def _get_curr_status(self) -> Tuple[DeploymentStatusInfo, bool]:
# TODO(edoakes): we could make this more efficient in steady-state by
# having a "healthy" flag that gets flipped if an update or replica
# failure happens.
target_version = self._target_version
target_rep... | Get the current deployment status.
Checks the difference between the target vs. running replica count for
the target version.
TODO(edoakes): we should report the status as FAILED if replicas are
repeatedly failing health checks. Need a reasonable heuristic here.
Returns:
... | 42 | 248 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_curr_status(self) -> Tuple[DeploymentStatusInfo, bool]:
# TODO(edoakes): we could make this more efficient in steady-state by
# having a "healthy" flag that... |
349 | def generate_square_subsequent_mask(self, length):
return paddle.tensor.triu(
(paddle.ones(
(length, length), dtype=paddle.get_default_dtype()) * -np.inf),
1)
|
Generate a square mask for the sequence. The mask ensures that the
predictions for position i can depend only on the known outputs at
positions less than i.
Parameters:
length (int|Tensor): The length of sequence.
Returns:
Tensor: Generated square mask ... | 110 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def generate_square_subsequent_mask(self, length):
return paddle.tensor.triu(
(paddle.ones(
(length, length), dtype=paddle.get_default_dtype()) *... |
350 | def find_requirement(self, req, upgrade):
# type: (InstallRequirement, bool) -> Optional[InstallationCandidate]
hashes = req.hashes(trust_internet=False)
best_candidate_result = self.find_best_candidate(
req.name, specifier=req.specifier, hashes=hashes,
)
bes... | Try to find a Link matching req
Expects req, an InstallRequirement and upgrade, a boolean
Returns a InstallationCandidate if found,
Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
| 25 | 37 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def find_requirement(self, req, upgrade):
# type: (InstallRequirement, bool) -> Optional[InstallationCandidate]
hashes = req.hashes(trust_internet=False)
bes... |
351 | def wrap(self, source, outfile):
if self.wrapcode:
return self._wrap_div(self._wrap_pre(self._wrap_code(source)))
else:
return self._wrap_div(self._wrap_pre(source))
|
Wrap the ``source``, which is a generator yielding
individual lines, in custom generators. See docstring
for `format`. Can be overridden.
| 20 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def wrap(self, source, outfile):
if self.wrapcode:
return self._wrap_div(self._wrap_pre(self._wrap_code(source)))
else:
return self._wrap_div... |
352 | def get_assessment_criteria(course):
return frappe.get_all(
"Course Assessment Criteria",
fields=["assessment_criteria", "weightage"],
filters={"parent": course},
order_by="idx",
)
@frappe.whitelist() | Returns Assessmemt Criteria and their Weightage from Course Master.
:param Course: Course
| 12 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_assessment_criteria(course):
return frappe.get_all(
"Course Assessment Criteria",
fields=["assessment_criteria", "weightage"],
filters={"parent": course},
order_by="idx",
... |
353 | def rm_filesystems(name, device, config="/etc/filesystems"):
modified = False
view_lines = []
if "AIX" not in __grains__["kernel"]:
return modified
criteria = _FileSystemsEntry(name=name, dev=device)
try:
fsys_filedict = _filesystems(config, False)
for fsys_view in fsy... |
.. versionadded:: 2018.3.3
Remove the mount point from the filesystems
CLI Example:
.. code-block:: bash
salt '*' mount.rm_filesystems /mnt/foo /dev/sdg
| 20 | 93 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def rm_filesystems(name, device, config="/etc/filesystems"):
modified = False
view_lines = []
if "AIX" not in __grains__["kernel"]:
return modified
criteria = ... |
354 | def complete_graph(n, create_using=None):
_, nodes = n
G = empty_graph(nodes, create_using)
if len(nodes) > 1:
if G.is_directed():
edges = itertools.permutations(nodes, 2)
else:
edges = itertools.combinations(nodes, 2)
G.add_edges_from(edges)
return G... | Return the complete graph `K_n` with n nodes.
A complete graph on `n` nodes means that all pairs
of distinct nodes have an edge connecting them.
Parameters
----------
n : int or iterable container of nodes
If n is an integer, nodes are from range(n).
If n is a container of nodes, t... | 106 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def complete_graph(n, create_using=None):
_, nodes = n
G = empty_graph(nodes, create_using)
if len(nodes) > 1:
if G.is_directed():
edges = itertools.perm... |
355 | def fit_predict(self, X, y=None, **fit_params):
self._validate_params()
fit_params_steps = self._check_fit_params(**fit_params)
Xt = self._fit(X, y, **fit_params_steps)
fit_params_last_step = fit_params_steps[self.steps[-1][0]]
with _print_elapsed_time("Pipeline", self.... | Transform the data, and apply `fit_predict` with the final estimator.
Call `fit_transform` of each transformer in the pipeline. The
transformed data are finally passed to the final estimator that calls
`fit_predict` method. Only valid if the final estimator implements
`fit_predict`.
... | 118 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def fit_predict(self, X, y=None, **fit_params):
self._validate_params()
fit_params_steps = self._check_fit_params(**fit_params)
Xt = self._fit(X, y, **fit_pa... |
356 | def test_issue4849(entity_ruler_factory):
nlp = English()
patterns = [
{"label": "PERSON", "pattern": "joe biden", "id": "joe-biden"},
{"label": "PERSON", "pattern": "bernie sanders", "id": "bernie-sanders"},
]
ruler = nlp.add_pipe(
entity_ruler_factory,
name="entity_rule... |
The left is starting to take aim at Democratic front-runner Joe Biden.
Sen. Bernie Sanders joined in her criticism: "There is no 'middle ground' when it comes to climate policy."
| 30 | 94 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_issue4849(entity_ruler_factory):
nlp = English()
patterns = [
{"label": "PERSON", "pattern": "joe biden", "id": "joe-biden"},
{"label": "PERSON", "pattern": ... |
357 | def get_serializer_context(self):
context = super().get_serializer_context()
if hasattr(self.queryset.model, 'custom_fields'):
content_type = ContentType.objects.get_for_model(self.queryset.model)
context.update({
'custom_fields': content_type.custom_fie... |
For models which support custom fields, populate the `custom_fields` context.
| 10 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_serializer_context(self):
context = super().get_serializer_context()
if hasattr(self.queryset.model, 'custom_fields'):
content_type = ContentTyp... |
358 | def execute (func, args, msg=None, verbose=0, dry_run=0):
if msg is None:
msg = "%s%r" % (func.__name__, args)
if msg[-2:] == ',)': # correct for singleton tuple
msg = msg[0:-2] + ')'
log.info(msg)
if not dry_run:
func(*args)
| Perform some action that affects the outside world (eg. by
writing to the filesystem). Such actions are special because they
are disabled by the 'dry_run' flag. This method takes care of all
that bureaucracy for you; all you have to do is supply the
function to call and an argument tuple for it (to e... | 66 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def execute (func, args, msg=None, verbose=0, dry_run=0):
if msg is None:
msg = "%s%r" % (func.__name__, args)
if msg[-2:] == ',)': # correct for singleton tu... |
359 | def call(self, features, cols_to_output_tensors=None, training=None):
if training is None:
training = backend.learning_phase()
if not isinstance(features, dict):
raise ValueError(
"We expected a dictionary here. Instead we got: ", features
)
... | Returns a dense tensor corresponding to the `feature_columns`.
Example usage:
>>> t1 = tf.feature_column.embedding_column(
... tf.feature_column.categorical_column_with_hash_bucket("t1", 2),
... dimension=8)
>>> t2 = tf.feature_column.numeric_column('t2')
>>> feat... | 191 | 74 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def call(self, features, cols_to_output_tensors=None, training=None):
if training is None:
training = backend.learning_phase()
if not isinstance(features... |
360 | def patch_pickle() -> Iterator[None]:
orig_loads = pkl.loads
try:
setattr(pkl, "loads", loads)
yield
finally:
setattr(pkl, "loads", orig_loads)
|
Temporarily patch pickle to use our unpickler.
| 7 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def patch_pickle() -> Iterator[None]:
orig_loads = pkl.loads
try:
setattr(pkl, "loads", loads)
yield
finally:
setattr(pkl, "loads", orig_loads)
... |
361 | def get_filesystem_type(filepath):
# We import it locally so that click autocomplete works
import psutil
root_type = "unknown"
for part in psutil.disk_partitions():
if part.mountpoint == '/':
root_type = part.fstype
continue
if filepath.startswith(part.mount... |
Determine the type of filesystem used - we might want to use different parameters if tmpfs is used.
:param filepath: path to check
:return: type of filesystem
| 27 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_filesystem_type(filepath):
# We import it locally so that click autocomplete works
import psutil
root_type = "unknown"
for part in psutil.disk_partitions():
... |
362 | def panther_similarity(G, source, k=5, path_length=5, c=0.5, delta=0.1, eps=None):
r
import numpy as np
num_nodes = G.number_of_nodes()
if num_nodes < k:
warnings.warn(
f"Number of nodes is {num_nodes}, but requested k is {k}. "
"Setting k to number of nodes."
)
... | Returns the Panther similarity of nodes in the graph `G` to node ``v``.
Panther is a similarity metric that says "two objects are considered
to be similar if they frequently appear on the same paths." [1]_.
Parameters
----------
G : NetworkX graph
A NetworkX graph
source : node
... | 275 | 240 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def panther_similarity(G, source, k=5, path_length=5, c=0.5, delta=0.1, eps=None):
r
import numpy as np
num_nodes = G.number_of_nodes()
if num_nodes < k:
warnings.wa... |
363 | def _phonemize_preprocess(self, text) -> Tuple[List[str], List]:
text = text.strip()
if self._keep_puncs:
# a tuple (text, punctuation marks)
return self._punctuator.strip_to_restore(text)
return [self._punctuator.strip(text)], []
| Preprocess the text before phonemization
1. remove spaces
2. remove punctuation
Override this if you need a different behaviour
| 19 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _phonemize_preprocess(self, text) -> Tuple[List[str], List]:
text = text.strip()
if self._keep_puncs:
# a tuple (text, punctuation marks)
... |
364 | def ensure_pathy(path):
from pathy import Pathy # noqa: F811
return Pathy.fluid(path)
| Temporary helper to prevent importing Pathy globally (which can cause
slow and annoying Google Cloud warning). | 16 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def ensure_pathy(path):
from pathy import Pathy # noqa: F811
return Pathy.fluid(path)
```
###Assistant : Temporary helper to prevent importing Pathy globally (wh... |
365 | def index(self, request, extra_context=None):
app_list = self.get_app_list(request)
context = {
**self.each_context(request),
"title": self.index_title,
"subtitle": None,
"app_list": app_list,
**(extra_context or {}),
}
... |
Display the main admin index page, which lists all of the installed
apps that have been registered in this site.
| 20 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def index(self, request, extra_context=None):
app_list = self.get_app_list(request)
context = {
**self.each_context(request),
"title": self.... |
366 | def generate_config_from_template(config_dir, config_path, environ, ownership):
for v in ("SYNAPSE_SERVER_NAME", "SYNAPSE_REPORT_STATS"):
if v not in environ:
error(
"Environment variable '%s' is mandatory when generating a config file."
% (v,)
)
... | Generate a homeserver.yaml from environment variables
Args:
config_dir (str): where to put generated config files
config_path (str): where to put the main config file
environ (dict): environment dictionary
ownership (str|None): "<user>:<group>" string which will be used to set
... | 49 | 279 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def generate_config_from_template(config_dir, config_path, environ, ownership):
for v in ("SYNAPSE_SERVER_NAME", "SYNAPSE_REPORT_STATS"):
if v not in environ:
er... |
367 | def donation_vector(donate_argnums, args, kwargs) -> Tuple[bool, ...]:
res: List[bool] = []
for i, arg in enumerate(args):
donate = bool(i in donate_argnums)
res.extend((donate,) * tree_structure(arg).num_leaves)
res.extend((False,) * tree_structure(kwargs).num_leaves)
return tuple(res)
| Returns a tuple with a boolean value for each leaf in args. | 12 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def donation_vector(donate_argnums, args, kwargs) -> Tuple[bool, ...]:
res: List[bool] = []
for i, arg in enumerate(args):
donate = bool(i in donate_argnums)
res.extend((donat... |
368 | def set_exception(self, exception):
if self._state != _PENDING:
raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
if isinstance(exception, type):
exception = exception()
if type(exception) is StopIteration:
raise TypeError("StopIteration ... | Mark the future done and set an exception.
If the future is already done when this method is called, raises
InvalidStateError.
| 21 | 44 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_exception(self, exception):
if self._state != _PENDING:
raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
if isinstance(exception, t... |
369 | def statistics(self, refresh=False, approximate=False):
# Prepare array with arguments for capi function
smin, smax, smean, sstd = c_double(), c_double(), c_double(), c_double()
stats_args = [
self._ptr,
c_int(approximate),
byref(smin),
by... |
Compute statistics on the pixel values of this band.
The return value is a tuple with the following structure:
(minimum, maximum, mean, standard deviation).
If approximate=True, the statistics may be computed based on overviews
or a subset of image tiles.
If refresh=T... | 93 | 98 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def statistics(self, refresh=False, approximate=False):
# Prepare array with arguments for capi function
smin, smax, smean, sstd = c_double(), c_double(), c_double()... |
370 | def test_smaller_request_deduplicated(self) -> None:
req1 = ensureDeferred(
self.state_datastore._get_state_for_group_using_inflight_cache(
42, StateFilter.from_types((("test.type", None),))
)
)
self.pump(by=0.1)
# This should have gone t... |
Tests that duplicate requests for state are deduplicated.
This test:
- requests some state (state group 42, 'all' state filter)
- requests a subset of that state, before the first request finishes
- checks to see that only one database query was made
- completes the dat... | 58 | 116 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_smaller_request_deduplicated(self) -> None:
req1 = ensureDeferred(
self.state_datastore._get_state_for_group_using_inflight_cache(
42, S... |
371 | def get_observation(self, agent):
speed = 0
distance = self._config["scenario_config"]["misc"]["max_distance"]
if agent in self.simulation.veh_subscriptions:
speed = round(
self.simulation.veh_subscriptions[agent][tc.VAR_SPEED] * MS_TO_KMH
)
... |
Returns the observation of a given agent.
See http://sumo.sourceforge.net/pydoc/traci._simulation.html
| 9 | 55 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_observation(self, agent):
speed = 0
distance = self._config["scenario_config"]["misc"]["max_distance"]
if agent in self.simulation.veh_subscriptions:... |
372 | def register(self, name, color_list):
if name in self._BUILTIN_COLOR_SEQUENCES:
raise ValueError(f"{name!r} is a reserved name for a builtin "
"color sequence")
color_list = list(color_list) # force copy and coerce type to list
for color in col... |
Register a new color sequence.
The color sequence registry stores a copy of the given *color_list*, so
that future changes to the original list do not affect the registered
color sequence. Think of this as the registry taking a snapshot
of *color_list* at registration.
... | 86 | 51 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def register(self, name, color_list):
if name in self._BUILTIN_COLOR_SEQUENCES:
raise ValueError(f"{name!r} is a reserved name for a builtin "
... |
373 | def test_get_states_no_attributes(hass_recorder):
hass = hass_recorder()
now, future, states = _setup_get_states(hass)
for state in states:
state.attributes = {}
# Get states returns everything before POINT for all entities
for state1, state2 in zip(
states,
sorted(
... | Test getting states without attributes at a specific point in time. | 11 | 145 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_get_states_no_attributes(hass_recorder):
hass = hass_recorder()
now, future, states = _setup_get_states(hass)
for state in states:
state.attributes = {}
... |
374 | def set_until(self, frame, lineno=None):
# the name "until" is borrowed from gdb
if lineno is None:
lineno = frame.f_lineno + 1
self._set_stopinfo(frame, frame, lineno)
| Stop when the line with the lineno greater than the current one is
reached or when returning from current frame. | 20 | 24 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_until(self, frame, lineno=None):
# the name "until" is borrowed from gdb
if lineno is None:
lineno = frame.f_lineno + 1
self._set_stopinf... |
375 | async def get_device_state(self, hass):
websession = async_get_clientsession(hass, self._verify_ssl)
rendered_headers = template.render_complex(self._headers, parse_result=False)
rendered_params = template.render_complex(self._params)
| Get the latest data from REST API and update the state. | 11 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def get_device_state(self, hass):
websession = async_get_clientsession(hass, self._verify_ssl)
rendered_headers = template.render_complex(self._headers, parse... |
376 | def reset_channel(self) -> None:
if self.channel:
self.channel.close()
self.channel = grpc.insecure_channel(self.real_addr, options=GRPC_OPTIONS)
grpc.channel_ready_future(self.channel)
self.task_servicer.set_channel(self.channel)
self.data_servicer.set_chann... |
Manually close and reopen the channel to the real ray server. This
simulates a disconnection between the client and the server.
| 21 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def reset_channel(self) -> None:
if self.channel:
self.channel.close()
self.channel = grpc.insecure_channel(self.real_addr, options=GRPC_OPTIONS)
... |
377 | def wait_scroll_pos_changed(self, x=None, y=None):
__tracebackhide__ = (lambda e:
e.errisinstance(testprocess.WaitForTimeout))
if (x is None and y is not None) or (y is None and x is not None):
raise ValueError("Either both x/y or neither must be given!"... | Wait until a "Scroll position changed" message was found.
With QtWebEngine, on older Qt versions which lack
QWebEnginePage.scrollPositionChanged, this also skips the test.
| 23 | 78 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def wait_scroll_pos_changed(self, x=None, y=None):
__tracebackhide__ = (lambda e:
e.errisinstance(testprocess.WaitForTimeout))
if (x is ... |
378 | def test_write_tfrecords(ray_start_regular_shared, tmp_path):
import tensorflow as tf
# The dataset we will write to a .tfrecords file.
ds = ray.data.from_items(
[
# Row one.
{
"int_item": 1,
"int_list": [2, 2, 3],
"float... | Test that write_tfrecords writes TFRecords correctly.
Test this by writing a Dataset to a TFRecord (function under test),
reading it back out into a tf.train.Example,
and checking that the result is analogous to the original Dataset.
| 36 | 231 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_write_tfrecords(ray_start_regular_shared, tmp_path):
import tensorflow as tf
# The dataset we will write to a .tfrecords file.
ds = ray.data.from_items(
[... |
379 | def test_float_conversion_dtype(self):
x = np.array([-1, 1])
# Test all combinations of dtypes conversions
dtype_combin = np.array(
np.meshgrid(
OutputPreprocessing.float_dtype_list,
OutputPreprocessing.float_dtype_list,
)
... | Test any convertion from a float dtype to an other. | 10 | 38 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_float_conversion_dtype(self):
x = np.array([-1, 1])
# Test all combinations of dtypes conversions
dtype_combin = np.array(
np.meshgrid(... |
380 | def fix_mime_types():
# Known to be problematic when Visual Studio is installed:
# <https://github.com/tensorflow/tensorboard/issues/3120>
# https://github.com/spotDL/spotify-downloader/issues/1540
mimetypes.add_type("application/javascript", ".js")
# Not known to be problematic, but used by sp... | Fix incorrect entries in the `mimetypes` registry.
On Windows, the Python standard library's `mimetypes` reads in
mappings from file extension to MIME type from the Windows
registry. Other applications can and do write incorrect values
to this registry, which causes `mimetypes.guess_type` to return
... | 78 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def fix_mime_types():
# Known to be problematic when Visual Studio is installed:
# <https://github.com/tensorflow/tensorboard/issues/3120>
# https://github.com/spotDL/spotif... |
381 | def _get_threads(self) -> MultiThread:
# TODO Check if multiple threads actually speeds anything up
save_queue = queue_manager.get_queue("convert_out")
patch_queue = queue_manager.get_queue("patch")
return MultiThread(self._converter.process, patch_queue, save_queue,
... | Get the threads for patching the converted faces onto the frames.
Returns
:class:`lib.multithreading.MultiThread`
The threads that perform the patching of swapped faces onto the output frames
| 26 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_threads(self) -> MultiThread:
# TODO Check if multiple threads actually speeds anything up
save_queue = queue_manager.get_queue("convert_out")
patch... |
382 | def verify_metadata(self):
# send the info to the server and report the result
(code, result) = self.post_to_server(self.build_post_data('verify'))
log.info('Server response (%s): %s', code, result)
| Send the metadata to the package index server to be checked.
| 11 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def verify_metadata(self):
# send the info to the server and report the result
(code, result) = self.post_to_server(self.build_post_data('verify'))
log.info(... |
383 | def test_subscriptions_add_for_principal_invite_only(self) -> None:
invitee = self.example_user("iago")
current_streams = self.get_streams(invitee)
invite_streams = self.make_random_stream_names(current_streams)
self.assert_adding_subscriptions_for_principal(
invitee... |
You can subscribe other people to invite only streams.
| 9 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_subscriptions_add_for_principal_invite_only(self) -> None:
invitee = self.example_user("iago")
current_streams = self.get_streams(invitee)
invite_st... |
384 | def get_module_dict_key_from_name(name):
key = name.replace(".", "__ludwig_punct_period__")
return key + FEATURE_NAME_SUFFIX
| Returns a key that's guaranteed to be compatible with torch. | 10 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_module_dict_key_from_name(name):
key = name.replace(".", "__ludwig_punct_period__")
return key + FEATURE_NAME_SUFFIX
```
###Assistant : Returns a key that'... |
385 | def test_hdk_import(import_strategy, has_other_engines):
remove_other_engines =
if not has_other_engines:
import_strategy = f"{remove_other_engines}\n{import_strategy}"
res = subprocess.run(
[sys.executable, "-c", import_strategy],
stderr=subprocess.PIPE,
stdout=subp... |
Test import of HDK engine.
The import of DbWorker requires to set special dlopen flags which make it then
incompatible to import some other libraries further (like ``pyarrow.gandiva``).
This test verifies that it's not the case when a user naturally imports Modin
with HDK engine.
Parameters
... | 176 | 41 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_hdk_import(import_strategy, has_other_engines):
remove_other_engines =
if not has_other_engines:
import_strategy = f"{remove_other_engines}\n{import_strategy... |
386 | def _iter_tree_entries_next(root_full, dir_rel, memo, on_error, follow_links):
dir_full = os.path.join(root_full, dir_rel)
dir_real = os.path.realpath(dir_full)
# Remember each encountered ancestor directory and its canonical
# (real) path. If a canonical path is encountered more than once,
# ... |
Scan the directory for all descendant files.
*root_full* (:class:`str`) the absolute path to the root directory.
*dir_rel* (:class:`str`) the path to the directory to scan relative to
*root_full*.
*memo* (:class:`dict`) keeps track of ancestor directories
encountered. Maps each ancestor real... | 74 | 240 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _iter_tree_entries_next(root_full, dir_rel, memo, on_error, follow_links):
dir_full = os.path.join(root_full, dir_rel)
dir_real = os.path.realpath(dir_full)
# Remember ... |
387 | def _remove_gens(base, strong_gens, basic_orbits=None, strong_gens_distr=None):
from sympy.combinatorics.perm_groups import _orbit
base_len = len(base)
degree = strong_gens[0].size
if strong_gens_distr is None:
strong_gens_distr = _distribute_gens_by_base(base, strong_gens)
if basic_orb... |
Remove redundant generators from a strong generating set.
Parameters
==========
``base`` - a base
``strong_gens`` - a strong generating set relative to ``base``
``basic_orbits`` - basic orbits
``strong_gens_distr`` - strong generators distributed by membership in basic
stabilizers
... | 115 | 88 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _remove_gens(base, strong_gens, basic_orbits=None, strong_gens_distr=None):
from sympy.combinatorics.perm_groups import _orbit
base_len = len(base)
degree = strong_gens[... |
388 | def from_dict(cls, file_dict):
return cls(
file_dict["filename"],
file_dict["content"],
file_dict.get("content-type", "text/plain"),
)
|
Create a SimpleUploadedFile object from a dictionary with keys:
- filename
- content-type
- content
| 15 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def from_dict(cls, file_dict):
return cls(
file_dict["filename"],
file_dict["content"],
file_dict.get("content-type", "text/plain"),
... |
389 | def test_change_list_sorting_callable(self):
response = self.client.get(
reverse("admin:admin_views_article_changelist"), {"o": 2}
)
self.assertContentBefore(
response,
"Oldest content",
"Middle content",
"Results of sorting on... |
Ensure we can sort on a list_display field that is a callable
(column 2 is callable_year in ArticleAdmin)
| 18 | 41 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_change_list_sorting_callable(self):
response = self.client.get(
reverse("admin:admin_views_article_changelist"), {"o": 2}
)
self.assertC... |
390 | def pre_encode(self) -> Optional[Callable[[np.ndarray], List[bytes]]]:
dummy = np.zeros((20, 20, 3), dtype="uint8")
test = self._writer.pre_encode(dummy)
retval: Optional[Callable[[np.ndarray],
List[bytes]]] = None if test is None else self._writer.pre_... | python function: Selected writer's pre-encode function, if it has one,
otherwise ``None`` | 12 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def pre_encode(self) -> Optional[Callable[[np.ndarray], List[bytes]]]:
dummy = np.zeros((20, 20, 3), dtype="uint8")
test = self._writer.pre_encode(dummy)
ret... |
391 | def disconnect(self):
if self.is_connected is False:
return
self.connection.close()
self.is_connected = False
return self.is_connected
|
Close any existing connections.
| 4 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def disconnect(self):
if self.is_connected is False:
return
self.connection.close()
self.is_connected = False
return self.is_co... |
392 | def resolve(self) -> Tuple[List, Dict]:
objects_mapping = []
for obj_ref in self.workflow_outputs:
obj, ref = _resolve_object_ref(obj_ref.ref)
objects_mapping.append(obj)
workflow_ref_mapping = _resolve_dynamic_workflow_refs(self.workflow_refs)
with ser... |
This function resolves the inputs for the code inside
a workflow step (works on the callee side). For outputs from other
workflows, we resolve them into object instances inplace.
For each ObjectRef argument, the function returns both the ObjectRef
and the object instance. If th... | 94 | 60 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def resolve(self) -> Tuple[List, Dict]:
objects_mapping = []
for obj_ref in self.workflow_outputs:
obj, ref = _resolve_object_ref(obj_ref.ref)
... |
393 | def _maybe_create_attribute(self, name, default_value):
if not hasattr(self, name):
self.__setattr__(name, default_value)
| Create the attribute with the default value if it hasn't been created.
This is useful for fields that is used for tracking purpose,
_trainable_weights, or _layers. Note that user could create a layer subclass
and assign an internal field before invoking the Layer.__init__(), the
__setat... | 74 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _maybe_create_attribute(self, name, default_value):
if not hasattr(self, name):
self.__setattr__(name, default_value)
```
###Assistant : Create ... |
394 | def add_nodes_from(self, nodes_for_adding, **attr):
for n in nodes_for_adding:
try:
newnode = n not in self._node
newdict = attr
except TypeError:
n, ndict = n
newnode = n not in self._node
newdict =... | Add multiple nodes.
Parameters
----------
nodes_for_adding : iterable container
A container of nodes (list, dict, set, etc.).
OR
A container of (node, attribute dict) tuples.
Node attributes are updated using the attribute dict.
attr : key... | 260 | 56 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def add_nodes_from(self, nodes_for_adding, **attr):
for n in nodes_for_adding:
try:
newnode = n not in self._node
newdict = attr
... |
395 | def test_submitted_email_notifications_sent(self):
self.login(self.submitter)
self.submit()
self.assertEqual(len(mail.outbox), 4)
task_submission_emails = [
email for email in mail.outbox if "task" in email.subject
]
task_submission_emailed_addresse... | Test that 'submitted' notifications for WorkflowState and TaskState are both sent correctly | 12 | 153 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_submitted_email_notifications_sent(self):
self.login(self.submitter)
self.submit()
self.assertEqual(len(mail.outbox), 4)
task_submission_e... |
396 | def forward(self, masks_queries_logits, class_queries_logits, mask_labels, class_labels) -> List[Tuple[Tensor]]:
indices: List[Tuple[np.array]] = []
preds_masks = masks_queries_logits
preds_probs = class_queries_logits.softmax(dim=-1)
# downsample all masks in one go -> save me... | Performs the matching
Params:
masks_queries_logits (`torch.Tensor`):
A tensor` of dim `batch_size, num_queries, num_classes` with the
classification logits.
class_queries_logits (`torch.Tensor`):
A tensor` of dim `batch_size, num_queries... | 114 | 229 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def forward(self, masks_queries_logits, class_queries_logits, mask_labels, class_labels) -> List[Tuple[Tensor]]:
indices: List[Tuple[np.array]] = []
preds_masks = m... |
397 | def cancel_dispatcher_process(self):
if not self.celery_task_id:
return
canceled = []
try:
# Use control and reply mechanism to cancel and obtain confirmation
timeout = 5
canceled = ControlDispatcher('dispatcher', self.controller_node).can... | Returns True if dispatcher running this job acknowledged request and sent SIGTERM | 12 | 58 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def cancel_dispatcher_process(self):
if not self.celery_task_id:
return
canceled = []
try:
# Use control and reply mechanism to cance... |
398 | def _mangle_index_names(cls, names):
return [
f"__index__{i}_{'__None__' if n is None else n}"
for i, n in enumerate(names)
]
|
Return mangled index names for index labels.
Mangled names are used for index columns because index
labels cannot always be used as HDK table column
names. E.e. label can be a non-string value or an
unallowed string (empty strings, etc.) for a table column
name.
... | 61 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _mangle_index_names(cls, names):
return [
f"__index__{i}_{'__None__' if n is None else n}"
for i, n in enumerate(names)
]
```
... |
399 | def get_b2cs_json(data, gstin):
company_state_number = gstin[0:2]
out = []
for d in data:
if not d.get("place_of_supply"):
frappe.throw(
_(
).format(frappe.bold("Place Of Supply"))
)
pos = d.get("place_of_supply").split("-")[0]
tax_details = {}
rate = d.get("rate", 0)
tax = flt((d["t... | {0} not entered in some invoices.
Please update and try again | 11 | 101 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_b2cs_json(data, gstin):
company_state_number = gstin[0:2]
out = []
for d in data:
if not d.get("place_of_supply"):
frappe.throw(
_(
).format(frappe.bold("Place... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.