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 |
|---|---|---|---|---|---|---|
800 | def is_empty_indexer(indexer) -> bool:
if is_list_like(indexer) and not len(indexer):
return True
if not isinstance(indexer, tuple):
indexer = (indexer,)
return any(isinstance(idx, np.ndarray) and len(idx) == 0 for idx in indexer)
# ----------------------------------------------------... |
Check if we have an empty indexer.
Parameters
----------
indexer : object
Returns
-------
bool
| 15 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def is_empty_indexer(indexer) -> bool:
if is_list_like(indexer) and not len(indexer):
return True
if not isinstance(indexer, tuple):
indexer = (indexer,)
ret... |
801 | def make_layoutgrids_gs(layoutgrids, gs):
if gs in layoutgrids or gs.figure is None:
return layoutgrids
# in order to do constrained_layout there has to be at least *one*
# gridspec in the tree:
layoutgrids['hasgrids'] = True
if not hasattr(gs, '_subplot_spec'):
# normal gridsp... |
Make the layoutgrid for a gridspec (and anything nested in the gridspec)
| 12 | 134 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def make_layoutgrids_gs(layoutgrids, gs):
if gs in layoutgrids or gs.figure is None:
return layoutgrids
# in order to do constrained_layout there has to be at least *on... |
802 | def test_sitemap_published_titles(self):
sitemap = CMSSitemap()
locations = []
urlset = sitemap.get_urls()
for item in urlset:
locations.append(item['location'])
for title in Title.objects.public():
page = title.page.get_public_object()
... |
Check that published titles are in the urls
| 8 | 44 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_sitemap_published_titles(self):
sitemap = CMSSitemap()
locations = []
urlset = sitemap.get_urls()
for item in urlset:
locations.... |
803 | def eye(N, chunks="auto", M=None, k=0, dtype=float):
eye = {}
if M is None:
M = N
if dtype is None:
dtype = float
if not isinstance(chunks, (int, str)):
raise ValueError("chunks must be an int or string")
vchunks, hchunks = normalize_chunks(chunks, shape=(N, M), dtype=... |
Return a 2-D Array with ones on the diagonal and zeros elsewhere.
Parameters
----------
N : int
Number of rows in the output.
chunks : int, str
How to chunk the array. Must be one of the following forms:
- A blocksize like 1000.
- A size in bytes, like "100 MiB" ... | 162 | 121 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def eye(N, chunks="auto", M=None, k=0, dtype=float):
eye = {}
if M is None:
M = N
if dtype is None:
dtype = float
if not isinstance(chunks, (int, str)):... |
804 | def is_composite_or_composite_value(tensor):
# TODO(b/125094323): This should be isinstance(CompositeTensor) or
# isinstance(CompositeTensorValue) once we support that.
return isinstance(
tensor,
(
tf.__internal__.CompositeTensor,
tf.compat.v1.SparseTensorValue,
... | Returns true if 'tensor' is a CompositeTensor or a CT Value object. | 12 | 24 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def is_composite_or_composite_value(tensor):
# TODO(b/125094323): This should be isinstance(CompositeTensor) or
# isinstance(CompositeTensorValue) once we support that.
retu... |
805 | def create_partition(tblname, start=None, end=None, partition_label=None, minutely=False):
current_time = now()
if not start:
if minutely:
start = current_time.replace(microsecond=0, second=0)
else:
start = current_time.replace(microsecond=0, second=0, minute=0)
... | Creates new partition table for events.
- start defaults to beginning of current hour
- end defaults to end of current hour
- partition_label defaults to YYYYMMDD_HH
- minutely will create partitions that span _a single minute_ for testing purposes
| 40 | 99 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def create_partition(tblname, start=None, end=None, partition_label=None, minutely=False):
current_time = now()
if not start:
if minutely:
start = current_ti... |
806 | def rbf_kernel(X, Y=None, gamma=None):
X, Y = check_pairwise_arrays(X, Y)
if gamma is None:
gamma = 1.0 / X.shape[1]
K = euclidean_distances(X, Y, squared=True)
K *= -gamma
np.exp(K, K) # exponentiate K in-place
return K
| Compute the rbf (gaussian) kernel between X and Y.
K(x, y) = exp(-gamma ||x-y||^2)
for each pair of rows x in X and y in Y.
Read more in the :ref:`User Guide <rbf_kernel>`.
Parameters
----------
X : ndarray of shape (n_samples_X, n_features)
A feature array.
Y : ndarray of s... | 85 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def rbf_kernel(X, Y=None, gamma=None):
X, Y = check_pairwise_arrays(X, Y)
if gamma is None:
gamma = 1.0 / X.shape[1]
K = euclidean_distances(X, Y, squared=True)
... |
807 | def _validate_argument_values(argument_spec, parameters, options_context=None, errors=None):
if errors is None:
errors = AnsibleValidationErrorMultiple()
for param, spec in argument_spec.items():
choices = spec.get('choices')
if choices is None:
continue
if is... | Ensure all arguments have the requested values, and there are no stray arguments | 13 | 248 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _validate_argument_values(argument_spec, parameters, options_context=None, errors=None):
if errors is None:
errors = AnsibleValidationErrorMultiple()
for param, sp... |
808 | def content(self):
if self._content is None:
self._load()
return self._content
|
The content of the artifact (representation varies)
| 7 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def content(self):
if self._content is None:
self._load()
return self._content
```
###Assistant :
The content of the artifact (repr... |
809 | def get_product_filter_data(query_args=None):
if isinstance(query_args, str):
query_args = json.loads(query_args)
query_args = frappe._dict(query_args)
if query_args:
search = query_args.get("search")
field_filters = query_args.get("field_filters", {})
attribute_filters = query_args.get("attribute_filters... |
Returns filtered products and discount filters.
:param query_args (dict): contains filters to get products list
Query Args filters:
search (str): Search Term.
field_filters (dict): Keys include item_group, brand, etc.
attribute_filters(dict): Keys include Color, Size, etc.
start (int): Offset items by
... | 55 | 143 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_product_filter_data(query_args=None):
if isinstance(query_args, str):
query_args = json.loads(query_args)
query_args = frappe._dict(query_args)
if query_args:
search = quer... |
810 | async def async_turn_on(self, **kwargs): # noqa: C901
should_update = False
on_command_type = self._config[CONF_ON_COMMAND_TYPE]
| Turn the device on.
This method is a coroutine.
| 9 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def async_turn_on(self, **kwargs): # noqa: C901
should_update = False
on_command_type = self._config[CONF_ON_COMMAND_TYPE]
```
###Assistant : Tur... |
811 | def test_fake_mac(self, modifiers, expected):
seq = keyutils.KeySequence()
info = keyutils.KeyInfo(key=Qt.Key.Key_A, modifiers=modifiers)
new = seq.append_event(info.to_event())
assert new[0] == keyutils.KeyInfo(Qt.Key.Key_A, expected)
| Make sure Control/Meta are swapped with a simulated Mac. | 9 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_fake_mac(self, modifiers, expected):
seq = keyutils.KeySequence()
info = keyutils.KeyInfo(key=Qt.Key.Key_A, modifiers=modifiers)
new = seq.append_ev... |
812 | def default_params(self) -> dict:
return {"order": "asc", "sort": self.sort_key, "limit": self.limit}
|
Returns the parameters to be sent together with the API call to Recurly
| 13 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def default_params(self) -> dict:
return {"order": "asc", "sort": self.sort_key, "limit": self.limit}
```
###Assistant :
Returns the parameters to be s... |
813 | def _should_start_new_health_check(self) -> bool:
if self._health_check_ref is not None:
# There's already an active health check.
return False
# If there's no active health check, kick off another and reset
# the timer if it's been long enough since the last he... | Determines if a new health check should be kicked off.
A health check will be started if:
1) There is not already an active health check.
2) It has been more than self._health_check_period_s since the
previous health check was *started*.
This assumes that self._h... | 61 | 69 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _should_start_new_health_check(self) -> bool:
if self._health_check_ref is not None:
# There's already an active health check.
return False
... |
814 | def numpy_pad_and_concatenate(array1, array2, padding_index=-100):
array1 = atleast_1d(array1)
array2 = atleast_1d(array2)
if len(array1.shape) == 1 or array1.shape[1] == array2.shape[1]:
return np.concatenate((array1, array2), axis=0)
# Let's figure out the new shape
new_shape = (arr... | Concatenates `array1` and `array2` on first axis, applying padding on the second if necessary. | 14 | 64 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def numpy_pad_and_concatenate(array1, array2, padding_index=-100):
array1 = atleast_1d(array1)
array2 = atleast_1d(array2)
if len(array1.shape) == 1 or array1.shape[1] == a... |
815 | def _ray(self) -> "ray":
global ray
if ray is None:
try:
import ray
except ImportError as exc:
raise RuntimeError(
"Using the `RayTaskRunner` requires `ray` to be installed."
) from exc
return ... |
Delayed import of `ray` allowing configuration of the task runner
without the extra installed and improves `prefect` import times.
| 19 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _ray(self) -> "ray":
global ray
if ray is None:
try:
import ray
except ImportError as exc:
raise Runtime... |
816 | def temperature_unit(self) -> str:
if (
self._unit_value
and self._unit_value.metadata.unit
and "f" in self._unit_value.metadata.unit.lower()
):
return UnitOfTemperature.FAHRENHEIT
return UnitOfTemperature.CELSIUS
| Return the unit of measurement used by the platform. | 9 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def temperature_unit(self) -> str:
if (
self._unit_value
and self._unit_value.metadata.unit
and "f" in self._unit_value.metadata.unit.low... |
817 | def get_point_of_rotated_vertical(origin, line_length, degrees):
rad = np.deg2rad(-degrees)
return [origin[0] + line_length * np.sin(rad),
origin[1] + line_length * np.cos(rad)]
fig, ax = plt.subplots(figsize=(8, 7))
ax.set(xlim=(0, 6), ylim=(-1, 4))
ax.set_title("Orientation of the bracket a... | Return xy coordinates of the vertical line end rotated by degrees. | 11 | 221 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_point_of_rotated_vertical(origin, line_length, degrees):
rad = np.deg2rad(-degrees)
return [origin[0] + line_length * np.sin(rad),
origin[1] + line_length * ... |
818 | def processEntityInAttribute(self, allowedChar):
self.consumeEntity(allowedChar=allowedChar, fromAttribute=True)
| This method replaces the need for "entityInAttributeValueState".
| 7 | 5 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def processEntityInAttribute(self, allowedChar):
self.consumeEntity(allowedChar=allowedChar, fromAttribute=True)
```
###Assistant : This method replaces the nee... |
819 | def _get_ordered_dummies(mul, verbose=False):
# setup dicts to avoid repeated calculations in key()
args = Mul.make_args(mul)
fac_dum = { fac: fac.atoms(Dummy) for fac in args }
fac_repr = { fac: __kprint(fac) for fac in args }
all_dums = set().union(*fac_dum.values())
mask = {}
for d i... | Returns all dummies in the mul sorted in canonical order.
Explanation
===========
The purpose of the canonical ordering is that dummies can be substituted
consistently across terms with the result that equivalent terms can be
simplified.
It is not possible to determine if two terms are equiva... | 415 | 67 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_ordered_dummies(mul, verbose=False):
# setup dicts to avoid repeated calculations in key()
args = Mul.make_args(mul)
fac_dum = { fac: fac.atoms(Dummy) for fac in ar... |
820 | def read_results_from_s3(query_execution_id):
s3_hook = S3Hook()
file_obj = s3_hook.get_conn().get_object(Bucket=S3_BUCKET, Key=f'{S3_KEY}/{query_execution_id}.csv')
file_content = file_obj['Body'].read().decode('utf-8')
print(file_content)
QUERY_CREATE_TABLE = f
QUERY_READ_TABLE = f
QUERY_DROP_TABL... |
CREATE EXTERNAL TABLE IF NOT EXISTS {ATHENA_DATABASE}.{ATHENA_TABLE} ( `name` string, `age` int )
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
WITH SERDEPROPERTIES ( 'serialization.format' = ',', 'field.delim' = ','
) LOCATION 's3://{S3_BUCKET}/{S3_KEY}/{ATHENA_TABLE}'
TBLPROPERTIES ('has_encr... | 40 | 107 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def read_results_from_s3(query_execution_id):
s3_hook = S3Hook()
file_obj = s3_hook.get_conn().get_object(Bucket=S3_BUCKET, Key=f'{S3_KEY}/{query_execution_id}.csv')
file_content... |
821 | def is_datetime64_ns_dtype(arr_or_dtype) -> bool:
if arr_or_dtype is None:
return False
try:
tipo = get_dtype(arr_or_dtype)
except TypeError:
if is_datetime64tz_dtype(arr_or_dtype):
tipo = get_dtype(arr_or_dtype.dtype)
else:
return False
retur... |
Check whether the provided array or dtype is of the datetime64[ns] dtype.
Parameters
----------
arr_or_dtype : array-like or dtype
The array or dtype to check.
Returns
-------
bool
Whether or not the array or dtype is of the datetime64[ns] dtype.
Examples
--------... | 86 | 37 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def is_datetime64_ns_dtype(arr_or_dtype) -> bool:
if arr_or_dtype is None:
return False
try:
tipo = get_dtype(arr_or_dtype)
except TypeError:
if is_d... |
822 | def regroup(parser, token):
bits = token.split_contents()
if len(bits) != 6:
raise TemplateSyntaxError("'regroup' tag takes five arguments")
target = parser.compile_filter(bits[1])
if bits[2] != 'by':
raise TemplateSyntaxError("second argument to 'regroup' tag must be 'by'")
if ... |
Regroup a list of alike objects by a common attribute.
This complex tag is best illustrated by use of an example: say that
``musicians`` is a list of ``Musician`` objects that have ``name`` and
``instrument`` attributes, and you'd like to display a list that
looks like:
* Guitar:
... | 230 | 131 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def regroup(parser, token):
bits = token.split_contents()
if len(bits) != 6:
raise TemplateSyntaxError("'regroup' tag takes five arguments")
target = parser.compile_... |
823 | def create_basic_list(cls) -> "Saved":
metadata = cls.get_metadata("saved")
urls = cls.get_urls("saved")
return cls(**metadata, urls=urls, songs=[])
|
Create a basic list with only the required metadata and urls.
### Returns
- The Saved object.
| 17 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def create_basic_list(cls) -> "Saved":
metadata = cls.get_metadata("saved")
urls = cls.get_urls("saved")
return cls(**metadata, urls=urls, songs=[])
... |
824 | def assert_lists_same(a, b):
assert len(a) == len(b)
for i in a:
assert i in b
for i in b:
assert i in a
| Compare two lists, ignoring order.
Check both that all items in a are in b and that all items in b are in a,
otherwise assert_lists_same(["1", "1"], ["1", "2"]) could be True.
| 32 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def assert_lists_same(a, b):
assert len(a) == len(b)
for i in a:
assert i in b
for i in b:
assert i in a
```
###Assistant : Compare two lists, ... |
825 | def test_dataframe_format_with_index():
pytest.importorskip("jinja2")
df = pd.DataFrame(
{
"A": [1, 2, 3, 4, 5, 6, 7, 8],
"B": list("ABCDEFGH"),
"C": pd.Categorical(list("AAABBBCC")),
},
index=list("ABCDEFGH"),
)
ddf = dd.from_pandas(df, 3)
... | <table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
<tr>
<th>npartitions=3</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<th>A</th>
<td>int64</... | 66 | 100 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_dataframe_format_with_index():
pytest.importorskip("jinja2")
df = pd.DataFrame(
{
"A": [1, 2, 3, 4, 5, 6, 7, 8],
"B": list("ABCDEFGH"),
... |
826 | def test_run_from_argv_closes_connections(self):
command = BaseCommand()
command.check = lambda: []
command.handle = lambda *args, **kwargs: args
with mock.patch("django.core.management.base.connections") as mock_connections:
command.run_from_argv(["", ""])
#... |
A command called from the command line should close connections after
being executed (#21255).
| 14 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_run_from_argv_closes_connections(self):
command = BaseCommand()
command.check = lambda: []
command.handle = lambda *args, **kwargs: args
wit... |
827 | def test_version_managing(self, data_handler):
# set up
df = pd.DataFrame([
{'a': 1, 'b': dt.datetime(2020, 1, 1)},
{'a': 2, 'b': dt.datetime(2020, 1, 2)},
{'a': 1, 'b': dt.datetime(2020, 1, 3)},
])
self.set_handler(data_handler, name='pg', tables={'t... |
CREATE PREDICTOR proj.task_model
from pg (select * from tasks)
PREDICT a
using engine='dummy_ml', tag = 'first'
SELECT m.*
FROM pg.tasks as t
JOIN proj.task_model as m
retra... | 109 | 536 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_version_managing(self, data_handler):
# set up
df = pd.DataFrame([
{'a': 1, 'b': dt.datetime(2020, 1, 1)},
{'a': 2, 'b': dt.datetime(2020, 1... |
828 | def _looks_like_red_hat_lib() -> bool:
from distutils.command.install import INSTALL_SCHEMES # type: ignore
return all(
k in INSTALL_SCHEMES
and _looks_like_red_hat_patched_platlib_purelib(INSTALL_SCHEMES[k])
for k in ("unix_prefix", "unix_home")
)
@functools.lru_cache(maxsi... | Red Hat patches platlib in unix_prefix and unix_home, but not purelib.
This is the only way I can see to tell a Red Hat-patched Python.
| 25 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _looks_like_red_hat_lib() -> bool:
from distutils.command.install import INSTALL_SCHEMES # type: ignore
return all(
k in INSTALL_SCHEMES
and _looks_like_re... |
829 | def get_valid_parent_pages(self, user):
# Get queryset of pages where this page type can be added
allowed_parent_page_content_types = list(
ContentType.objects.get_for_models(
*self.model.allowed_parent_page_models()
).values()
)
allowed_p... |
Identifies possible parent pages for the current user by first looking
at allowed_parent_page_models() on self.model to limit options to the
correct type of page, then checking permissions on those individual
pages to make sure we have permission to add a subpage to it.
| 43 | 83 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_valid_parent_pages(self, user):
# Get queryset of pages where this page type can be added
allowed_parent_page_content_types = list(
ContentType.o... |
830 | def get_attendance_list(conditions, filters):
attendance_list = frappe.db.sql(
% conditions,
filters,
as_dict=1,
)
if not attendance_list:
msgprint(_("No attendance record found"), alert=True, indicator="orange")
att_map = {}
for d in attendance_list:
att_map.setdefault(d.employee, frappe._dict()).s... | select employee, day(attendance_date) as day_of_month,
status from tabAttendance where docstatus = 1 %s order by employee, attendance_date | 17 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_attendance_list(conditions, filters):
attendance_list = frappe.db.sql(
% conditions,
filters,
as_dict=1,
)
if not attendance_list:
msgprint(_("No attendance record fou... |
831 | def _reorder_cache(past, beam_idx):
reordered_past = ()
for layer_past in past:
reordered_past += (tuple(tf.gather(past_state, beam_idx, axis=0) for past_state in layer_past),)
return reordered_past
@add_start_docstrings(
,
REMBERT_START_DOCSTRING,
) |
RemBERT Model transformer with a sequence classification/regression head on top e.g., for GLUE tasks.
| 14 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _reorder_cache(past, beam_idx):
reordered_past = ()
for layer_past in past:
reordered_past += (tuple(tf.gather(past_state, beam_idx, axis=0) for past_state in... |
832 | def test_remove_as_admin_not_in_team(self):
# an org with closed membership (byproduct of flags=0)
org = self.create_organization(owner=self.user, flags=0)
team = self.create_team(organization=org)
admin_user = self.create_user(email="foo@example.com", is_superuser=False)
... | Admins can't remove teams of which they're not a part, unless
open membership is on. | 15 | 66 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_remove_as_admin_not_in_team(self):
# an org with closed membership (byproduct of flags=0)
org = self.create_organization(owner=self.user, flags=0)
... |
833 | def batch_test(num_threads, delay):
with mock.patch(
"ray.autoscaler._private.aws.node_provider.make_ec2_client"
), mock.patch.object(AWSNodeProvider, "_create_tags", mock_create_tags):
provider = AWSNodeProvider(
provider_config={"region": "nowhere"}, cluster_name="default"
... | Run AWSNodeProvider.set_node_tags in several threads, with a
specified delay between thread launches.
Return the number of batches of tag updates and the number of tags
updated.
| 26 | 61 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def batch_test(num_threads, delay):
with mock.patch(
"ray.autoscaler._private.aws.node_provider.make_ec2_client"
), mock.patch.object(AWSNodeProvider, "_create_tags", mo... |
834 | def forward(self, feats, img_metas):
y = self.last_feat_conv(feats[-1])
for i in range(self.num_inputs - 2, -1, -1):
x = feats[i]
cur_fpn = self.lateral_convs[i](x)
y = cur_fpn + \
F.interpolate(y, size=cur_fpn.shape[-2:], mode='nearest')
... |
Args:
feats (list[Tensor]): Feature maps of each level. Each has
shape of (batch_size, c, h, w).
img_metas (list[dict]): List of image information. Pass in
for creating more accurate padding mask. Not used here.
Returns:
tuple: a tupl... | 62 | 42 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def forward(self, feats, img_metas):
y = self.last_feat_conv(feats[-1])
for i in range(self.num_inputs - 2, -1, -1):
x = feats[i]
cur_fpn = s... |
835 | async def test_remote_scanner_expires_non_connectable(hass):
manager = _get_manager()
switchbot_device = BLEDevice(
"44:44:33:11:23:45",
"wohand",
{},
rssi=-100,
)
switchbot_device_adv = generate_advertisement_data(
local_name="wohand",
service_uuids... | Test the remote scanner expires stale non connectable data. | 9 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_remote_scanner_expires_non_connectable(hass):
manager = _get_manager()
switchbot_device = BLEDevice(
"44:44:33:11:23:45",
"wohand",
{},
... |
836 | def convert_yaml_objects_to_native(obj):
if isinstance(obj, dict):
return dict((k, convert_yaml_objects_to_native(v)) for k, v in obj.items())
elif isinstance(obj, list):
return [convert_yaml_objects_to_native(v) for v in obj]
elif isinstance(obj, text_type):
return text_type(ob... | Older versions of the ``toml`` python library, and tomllib, don't have
a pluggable way to tell the encoder about custom types, so we need to
ensure objects that we pass are native types.
Used with:
- ``toml<0.10.0`` where ``toml.TomlEncoder`` is missing
- ``tomli`` or ``tomllib``
This func... | 101 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def convert_yaml_objects_to_native(obj):
if isinstance(obj, dict):
return dict((k, convert_yaml_objects_to_native(v)) for k, v in obj.items())
elif isinstance(obj, list)... |
837 | def make_future_dataframe(self, periods, freq='D', include_history=True):
if self.history_dates is None:
raise Exception('Model has not been fit.')
if freq is None:
# taking the tail makes freq inference more reliable
freq = pd.infer_freq(self.history_dates.t... | Simulate the trend using the extrapolated generative model.
Parameters
----------
periods: Int number of periods to forecast forward.
freq: Any valid frequency for pd.date_range, such as 'D' or 'M'.
include_history: Boolean to include the historical dates in the data
... | 59 | 94 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def make_future_dataframe(self, periods, freq='D', include_history=True):
if self.history_dates is None:
raise Exception('Model has not been fit.')
if fr... |
838 | def array_to_blobproto(arr, diff=None):
blob = caffe_pb2.BlobProto()
blob.shape.dim.extend(arr.shape)
blob.data.extend(arr.astype(float).flat)
if diff is not None:
blob.diff.extend(diff.astype(float).flat)
return blob
| Converts a N-dimensional array to blob proto. If diff is given, also
convert the diff. You need to make sure that arr and diff have the same
shape, and this function does not do sanity check.
| 36 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def array_to_blobproto(arr, diff=None):
blob = caffe_pb2.BlobProto()
blob.shape.dim.extend(arr.shape)
blob.data.extend(arr.astype(float).flat)
if diff is not None:
... |
839 | def test_cross_signing_keys_retry(self):
remote_user_id = "@john:test_remote"
remote_master_key = "85T7JXPFBAySB/jwby4S3lBPTqY3+Zg53nYuGmu1ggY"
remote_self_signing_key = "QeIiFEjluPBtI7WQdG365QKZcFs9kqmHir6RBD0//nQ"
# Register mock device list retrieval on the federation client... | Tests that resyncing a device list correctly processes cross-signing keys from
the remote server.
| 14 | 145 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_cross_signing_keys_retry(self):
remote_user_id = "@john:test_remote"
remote_master_key = "85T7JXPFBAySB/jwby4S3lBPTqY3+Zg53nYuGmu1ggY"
remote_self_s... |
840 | def test_exec_success(self, db_mock_class):
run = {
'new_cluster': NEW_CLUSTER,
'notebook_task': NOTEBOOK_TASK,
}
op = DatabricksSubmitRunOperator(task_id=TASK_ID, json=run)
db_mock = db_mock_class.return_value
db_mock.submit_run.return_value = 1
... |
Test the execute function in case where the run is successful.
| 11 | 50 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_exec_success(self, db_mock_class):
run = {
'new_cluster': NEW_CLUSTER,
'notebook_task': NOTEBOOK_TASK,
}
op = DatabricksSubm... |
841 | def dark_palette(color, n_colors=6, reverse=False, as_cmap=False, input="rgb"):
rgb = _color_to_rgb(color, input)
h, s, l = husl.rgb_to_husl(*rgb)
gray_s, gray_l = .15 * s, 15
gray = _color_to_rgb((h, gray_s, gray_l), input="husl")
colors = [rgb, gray] if reverse else [gray, rgb]
return ble... | Make a sequential palette that blends from dark to ``color``.
This kind of palette is good for data that range between relatively
uninteresting low values and interesting high values.
The ``color`` parameter can be specified in a number of ways, including
all options for defining a color in matplotlib... | 201 | 41 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def dark_palette(color, n_colors=6, reverse=False, as_cmap=False, input="rgb"):
rgb = _color_to_rgb(color, input)
h, s, l = husl.rgb_to_husl(*rgb)
gray_s, gray_l = .15 * s, ... |
842 | def contour(self, X, win=None, env=None, opts=None):
return self._surface(X=X, stype="contour", opts=opts, win=win, env=env)
|
This function draws a contour plot. It takes as input an `NxM` tensor
`X` that specifies the value at each location in the contour plot.
The following `opts` are supported:
- `opts.colormap`: colormap (`string`; default = `'Viridis'`)
- `opts.xmin` : clip minimum value (`nu... | 57 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def contour(self, X, win=None, env=None, opts=None):
return self._surface(X=X, stype="contour", opts=opts, win=win, env=env)
```
###Assistant :
This f... |
843 | def get_themes():
themes = {}
eps = set(importlib_metadata.entry_points(group='mkdocs.themes'))
builtins = {ep.name for ep in eps if ep.dist.name == 'mkdocs'}
for theme in eps:
if theme.name in builtins and theme.dist.name != 'mkdocs':
raise exceptions.ConfigurationError(
... | Return a dict of all installed themes as {name: EntryPoint}. | 10 | 87 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_themes():
themes = {}
eps = set(importlib_metadata.entry_points(group='mkdocs.themes'))
builtins = {ep.name for ep in eps if ep.dist.name == 'mkdocs'}
for them... |
844 | def test_subscribe_by_default(self):
NotificationSetting.objects.update_settings(
ExternalProviders.EMAIL,
NotificationSettingTypes.ISSUE_ALERTS,
NotificationSettingOptionValues.NEVER,
user=self.user,
)
response = self.get_success_respons... |
Test that we expect project-independent issue alert preferences to be
returned as `subscribe_by_default`.
| 13 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_subscribe_by_default(self):
NotificationSetting.objects.update_settings(
ExternalProviders.EMAIL,
NotificationSettingTypes.ISSUE_ALERTS,
... |
845 | def _get_users_with_any_permission_codenames_filter(self, permission_codenames):
permissions = Permission.objects.filter(
content_type=self._content_type, codename__in=permission_codenames
)
return (
Q(is_superuser=True)
| Q(user_permissions__in=permi... |
Given a list of permission codenames, return a filter expression which
will find all users which have any of those permissions - either
through group permissions, user permissions, or implicitly through
being a superuser.
| 34 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_users_with_any_permission_codenames_filter(self, permission_codenames):
permissions = Permission.objects.filter(
content_type=self._content_type, codena... |
846 | def _async_update_rssi_and_transients(self) -> None:
for (
unique_id,
ibeacon_advertisement,
) in self._last_ibeacon_advertisement_by_unique_id.items():
address = unique_id.split("_")[-1]
service_info = bluetooth.async_last_service_info(
... | Check to see if the rssi has changed and update any devices.
We don't callback on RSSI changes so we need to check them
here and send them over the dispatcher periodically to
ensure the distance calculation is update.
If the transient flag is set we also need to check to see
if... | 62 | 56 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _async_update_rssi_and_transients(self) -> None:
for (
unique_id,
ibeacon_advertisement,
) in self._last_ibeacon_advertisement_by_unique_... |
847 | def setup_app_for_worker(app, loglevel, logfile) -> None:
# type: (Celery, Union[str, int], str) -> None
app.finalize()
app.set_current()
app.set_default()
type(app.log)._setup = False
app.log.setup(loglevel=loglevel, logfile=logfile)
| Setup the app to be used for starting an embedded worker. | 11 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def setup_app_for_worker(app, loglevel, logfile) -> None:
# type: (Celery, Union[str, int], str) -> None
app.finalize()
app.set_current()
app.set_default()
type(app.... |
848 | def rank(self):
if self._rank is None:
self._rank = int(gray_to_bin(self.current), 2)
return self._rank
|
Ranks the Gray code.
A ranking algorithm determines the position (or rank)
of a combinatorial object among all the objects w.r.t.
a given order. For example, the 4 bit binary reflected
Gray code (BRGC) '0101' has a rank of 6 as it appears in
the 6th position in the cano... | 97 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def rank(self):
if self._rank is None:
self._rank = int(gray_to_bin(self.current), 2)
return self._rank
```
###Assistant :
Ranks th... |
849 | async def async_update(self, log_errors=True):
if not self._async_client:
self._async_client = get_async_client(
self._hass, verify_ssl=self._verify_ssl
)
rendered_headers = template.render_complex(self._headers, parse_result=False)
rendered_para... | Get the latest data from REST service with provided method. | 10 | 91 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def async_update(self, log_errors=True):
if not self._async_client:
self._async_client = get_async_client(
self._hass, verify_ssl=self._ver... |
850 | def set_default_timezone() -> None:
dotenv.load_dotenv(USER_ENV_FILE)
user_tz = os.getenv("OPENBB_TIMEZONE")
if not user_tz:
dotenv.set_key(USER_ENV_FILE, "OPENBB_TIMEZONE", "America/New_York")
| Set a default (America/New_York) timezone if one doesn't exist. | 9 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_default_timezone() -> None:
dotenv.load_dotenv(USER_ENV_FILE)
user_tz = os.getenv("OPENBB_TIMEZONE")
if not user_tz:
dotenv.set_key(USER_ENV_FILE, "OPENBB_TI... |
851 | def return_stopped_response(self) -> dict:
return {k: "Agent stopped due to max iterations." for k in self.return_values}
| Return response when agent has been stopped due to max iterations. | 11 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def return_stopped_response(self) -> dict:
return {k: "Agent stopped due to max iterations." for k in self.return_values}
```
###Assistant : Return response wh... |
852 | def clean(self, value):
if self.null_option is not None and value == settings.FILTERS_NULL_CHOICE_VALUE:
return None
return super().clean(value)
|
When null option is enabled and "None" is sent as part of a form to be submitted, it is sent as the
string 'null'. This will check for that condition and gracefully handle the conversion to a NoneType.
| 38 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def clean(self, value):
if self.null_option is not None and value == settings.FILTERS_NULL_CHOICE_VALUE:
return None
return super().clean(value)
... |
853 | def test_unexpected_auth_events(self):
creator = "@creator:example.com"
create_event = _create_event(RoomVersions.V9, creator)
join_event = _join_event(RoomVersions.V9, creator)
pl_event = _power_levels_event(
RoomVersions.V9,
creator,
{"stat... | Events with excess auth_events should be rejected
https://spec.matrix.org/v1.3/rooms/v9/#authorization-rules
2. Reject if event has auth_events that:
2. have entries whose type and state_key don’t match those specified by the
auth events selection algorithm described in the ser... | 37 | 76 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_unexpected_auth_events(self):
creator = "@creator:example.com"
create_event = _create_event(RoomVersions.V9, creator)
join_event = _join_event(Room... |
854 | async def _consume_incoming(self) -> None:
while True:
message_json = await self.incoming_queue.get()
if message_json is None:
self.incoming_queue.task_done()
break
type = message_json["type"]
if type == "client_log":
... | Consume messages from the incoming (client -> server) Queue, and print
the corresponding renderables to the console for each message.
| 20 | 67 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def _consume_incoming(self) -> None:
while True:
message_json = await self.incoming_queue.get()
if message_json is None:
self.i... |
855 | def _get_basic_ray_cr() -> dict:
cr_path = str(
Path(__file__).resolve().parents[2]
/ "python"
/ "ray"
/ "autoscaler"
/ "kuberay"
/ "ray-cluster.complete.yaml"
)
return yaml.safe_load(open(cr_path).read())
| Returns the example Ray CR included in the Ray documentation. | 10 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_basic_ray_cr() -> dict:
cr_path = str(
Path(__file__).resolve().parents[2]
/ "python"
/ "ray"
/ "autoscaler"
/ "kuberay"
/ "... |
856 | def spectral_graph_forge(G, alpha, transformation="identity", seed=None):
import numpy as np
import scipy as sp
import scipy.stats # call as sp.stats
available_transformations = ["identity", "modularity"]
alpha = np.clip(alpha, 0, 1)
A = nx.to_numpy_array(G)
n = A.shape[1]
level =... | Returns a random simple graph with spectrum resembling that of `G`
This algorithm, called Spectral Graph Forge (SGF), computes the
eigenvectors of a given graph adjacency matrix, filters them and
builds a random graph with a similar eigenstructure.
SGF has been proved to be particularly useful for synt... | 358 | 169 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def spectral_graph_forge(G, alpha, transformation="identity", seed=None):
import numpy as np
import scipy as sp
import scipy.stats # call as sp.stats
available_transfo... |
857 | def encode_example(self, example):
example = cast_to_python_objects(example)
return encode_nested_example(self, example)
|
Encode example into a format for Arrow.
Args:
example (`dict[str, Any]`):
Data in a Dataset row.
Returns:
`dict[str, Any]`
| 19 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def encode_example(self, example):
example = cast_to_python_objects(example)
return encode_nested_example(self, example)
```
###Assistant :
Enc... |
858 | def _add_unique_metric_name(self, metric_name, metric_fn, output_index):
# For multi-output models, prepend the output names to the metric name.
if len(self.output_names) > 1:
# If we're loading from an already-serialized model, we've already
# prepended the output name,... | Makes the metric name unique.
If there are multiple outputs for which the metrics are calculated, the
metric names have to be made unique by appending an integer.
Args:
metric_name: Metric name that corresponds to the metric specified by the
user. For example: 'acc'... | 72 | 117 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _add_unique_metric_name(self, metric_name, metric_fn, output_index):
# For multi-output models, prepend the output names to the metric name.
if len(self.output_n... |
859 | def strongly_connected_components(G):
preorder = {}
lowlink = {}
scc_found = set()
scc_queue = []
i = 0 # Preorder counter
neighbors = {v: iter(G[v]) for v in G}
for source in G:
if source not in scc_found:
queue = [source]
while queue:
v... | Generate nodes in strongly connected components of graph.
Parameters
----------
G : NetworkX Graph
A directed graph.
Returns
-------
comp : generator of sets
A generator of sets of nodes, one for each strongly connected
component of G.
Raises
------
Network... | 162 | 126 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def strongly_connected_components(G):
preorder = {}
lowlink = {}
scc_found = set()
scc_queue = []
i = 0 # Preorder counter
neighbors = {v: iter(G[v]) for v in G... |
860 | def score(self, X, y, sample_weight=None):
# TODO: Adapt link to User Guide in the docstring, once
# https://github.com/scikit-learn/scikit-learn/pull/22118 is merged.
#
# Note, default score defined in RegressorMixin is R^2 score.
# TODO: make D^2 a score function in mo... | Compute D^2, the percentage of deviance explained.
D^2 is a generalization of the coefficient of determination R^2.
R^2 uses squared error and D^2 uses the deviance of this GLM, see the
:ref:`User Guide <regression_metrics>`.
D^2 is defined as
:math:`D^2 = 1-\\frac{D(y_{true},y... | 127 | 172 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def score(self, X, y, sample_weight=None):
# TODO: Adapt link to User Guide in the docstring, once
# https://github.com/scikit-learn/scikit-learn/pull/22118 is merge... |
861 | def upsample_conv_2d(x, w, k=None, factor=2, gain=1, data_format='NCHW', impl='cuda'):
r
assert isinstance(factor, int) and factor >= 1
# Check weight shape.
w = tf.convert_to_tensor(w)
assert w.shape.rank == 4
convH = w.shape[0].value
convW = w.shape[1].value
inC = _shape(w, 2)
ou... | Fused `upsample_2d()` followed by `tf.nn.conv2d()`.
Padding is performed only once at the beginning, not between the operations.
The fused op is considerably more efficient than performing the same calculation
using standard TensorFlow ops. It supports gradients of arbitrary order.
Args:
x: ... | 158 | 198 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def upsample_conv_2d(x, w, k=None, factor=2, gain=1, data_format='NCHW', impl='cuda'):
r
assert isinstance(factor, int) and factor >= 1
# Check weight shape.
w = tf.convert... |
862 | def normalize_config(config):
return json.loads(json.dumps(config, cls=NumpyEncoder))
| Convert to json string and back again to remove numpy types. | 11 | 5 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def normalize_config(config):
return json.loads(json.dumps(config, cls=NumpyEncoder))
```
###Assistant : Convert to json string and back again to remove numpy t... |
863 | def ensure_srgb(img, srgb_profile=None):
img_info = dict(img.info)
icc = img_info.pop("icc_profile", None)
if not icc:
return img
if ImageCms is None:
raise RuntimeError("ImageCms is required for color profile utilities")
if srgb_profile is not None:
srgb_profile = Ima... |
Ensures that an image either has no ICC profile (and so is implicitly
sRGB) or has an sRGB color profile. If the image is sRGB, it is returned
unchanged. If it has a CMYK or Gray color profile, this function will
return an image converted to sRGB. Any color profiles in other color
spaces will retur... | 57 | 203 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def ensure_srgb(img, srgb_profile=None):
img_info = dict(img.info)
icc = img_info.pop("icc_profile", None)
if not icc:
return img
if ImageCms is None:
r... |
864 | def _cast_single_input(self, x):
if self._should_cast_single_input(x):
return tf.cast(x, self._compute_dtype_object)
else:
return x
# _dtype used to be an attribute set in the constructor. We still expose it
# because some clients still use it.
# TODO(reedwm... | Cast a single Tensor or TensorSpec to the compute dtype. | 10 | 41 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _cast_single_input(self, x):
if self._should_cast_single_input(x):
return tf.cast(x, self._compute_dtype_object)
else:
return x
# _d... |
865 | def queryset_in_batches(queryset):
start_pk = 0
while True:
qs = queryset.filter(pk__gt=start_pk)[:BATCH_SIZE]
pks = list(qs.values_list("pk", flat=True))
if not pks:
break
yield pks
start_pk = pks[-1]
| Slice a queryset into batches.
Input queryset should be sorted be pk.
| 12 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def queryset_in_batches(queryset):
start_pk = 0
while True:
qs = queryset.filter(pk__gt=start_pk)[:BATCH_SIZE]
pks = list(qs.values_list("pk", flat=True))
... |
866 | def execute():
frappe.reload_doc("stock", "doctype", "purchase_receipt")
frappe.reload_doc("stock", "doctype", "purchase_receipt_item")
frappe.reload_doc("stock", "doctype", "delivery_note")
frappe.reload_doc("stock", "doctype", "delivery_note_item")
frappe.reload_doc("stock", "doctype", "stock_settings")
def up... | update `tabPurchase Receipt Item`
set received_stock_qty = received_qty * conversion_factor
where docstatus = 1 | 14 | 81 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def execute():
frappe.reload_doc("stock", "doctype", "purchase_receipt")
frappe.reload_doc("stock", "doctype", "purchase_receipt_item")
frappe.reload_doc("stock", "doctype", "delivery_not... |
867 | def call_dex(self, other_args):
parser = argparse.ArgumentParser(
prog="dex",
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description=,
)
parser.add_argument(
"-l",
"--limit",
... | Process dex command
Shows top decentralized exchanges [Source: https://dappradar.com/]
Accepts --sort {Name,Daily Users,Daily Volume [$]}
to sort by column
| 19 | 55 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def call_dex(self, other_args):
parser = argparse.ArgumentParser(
prog="dex",
add_help=False,
formatter_class=argparse.ArgumentDefaultsHe... |
868 | def get_backend_for_dir(self, location):
# type: (str) -> Optional[VersionControl]
vcs_backends = {}
for vcs_backend in self._registry.values():
repo_path = vcs_backend.get_repository_root(location)
if not repo_path:
continue
logger.de... |
Return a VersionControl object if a repository of that type is found
at the given directory.
| 16 | 86 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_backend_for_dir(self, location):
# type: (str) -> Optional[VersionControl]
vcs_backends = {}
for vcs_backend in self._registry.values():
... |
869 | def has_access(self, action_name, resource_name, user=None) -> bool:
if not user:
user = g.user
if user.is_anonymous:
user.roles = self.get_user_roles(user)
has_access = self._has_access(user, action_name, resource_name)
# FAB built-in view access metho... |
Verify whether a given user could perform a certain action
(e.g can_read, can_write) on the given resource.
:param action_name: action_name on resource (e.g can_read, can_edit).
:param resource_name: name of view-menu or resource.
:param user: user name
:return: Whether... | 48 | 54 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def has_access(self, action_name, resource_name, user=None) -> bool:
if not user:
user = g.user
if user.is_anonymous:
user.roles = self.get_... |
870 | def has_refs(self) -> bool:
return len(self._session_report_run_counts) > 0
| True if this Entry has references from any AppSession.
If not, it can be removed from the cache.
| 18 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def has_refs(self) -> bool:
return len(self._session_report_run_counts) > 0
```
###Assistant : True if this Entry has references from any AppSession.
... |
871 | def _reshape_to_record_metrics(self, batch, losses, num_target_tokens, indices):
val_id_shape = batch.valid_indices.shape
reshaped_losses = torch.zeros(
val_id_shape, device=losses.device, dtype=losses.dtype
)
reshaped_num_target_tokens = torch.zeros(
val... |
MultitaskAgent shuffles and combines examples from both classifier and the
generator tasks in a single batch. We compute losses only for those exs in the
batch resulting in losses and num_target_tokens vectors that are smaller than
the.
This method reshapes the losses and num_t... | 136 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _reshape_to_record_metrics(self, batch, losses, num_target_tokens, indices):
val_id_shape = batch.valid_indices.shape
reshaped_losses = torch.zeros(
... |
872 | def add_support(self, location, type):
if location not in self._node_labels:
raise ValueError("Support must be added on a known node")
else:
self._supports[location] = type
|
This method adds a pinned or roller support at a particular node
Parameters
==========
location: String or Symbol
Label of the Node at which support is added.
type: String
Type of the support being provided at the node.
Examples
======... | 71 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def add_support(self, location, type):
if location not in self._node_labels:
raise ValueError("Support must be added on a known node")
else:
... |
873 | def makeport(self):
sock = socket.create_server(("", 0), family=self.af, backlog=1)
port = sock.getsockname()[1] # Get proper port
host = self.sock.getsockname()[0] # Get proper host
if self.af == socket.AF_INET:
resp = self.sendport(host, port)
else:
... | Create a new socket and send a PORT command for it. | 11 | 43 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def makeport(self):
sock = socket.create_server(("", 0), family=self.af, backlog=1)
port = sock.getsockname()[1] # Get proper port
host = self.sock.getsockna... |
874 | def test_all(gm_manager):
_save_script(test_gm_script, 'test.user.js')
gm_manager.load_scripts()
assert (gm_manager.all_scripts()[0].name ==
"qutebrowser test userscript")
@pytest.mark.parametrize("url, expected_matches", [
# included
('http://trolol.com/', 1),
# neither incl... | Test that a script gets read from file, parsed and returned. | 11 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_all(gm_manager):
_save_script(test_gm_script, 'test.user.js')
gm_manager.load_scripts()
assert (gm_manager.all_scripts()[0].name ==
"qutebrowser test u... |
875 | def split_path_msys(path):
if path.startswith(('/', '\\')) and not path.startswith(('//', '\\\\')):
global msysroot
if not msysroot:
msysroot = subprocess.check_output(['cygpath', '-w', '/']).decode(sys.stdout.encoding or 'latin-1')
msysroot = msysroot.strip()
path = ... |
Splits a path by / or \\; do not confuse this function with with ``os.path.split``
:type path: string
:param path: path to split
:return: list of string
| 27 | 59 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def split_path_msys(path):
if path.startswith(('/', '\\')) and not path.startswith(('//', '\\\\')):
global msysroot
if not msysroot:
msysroot = subprocess.che... |
876 | def find_image_duplicates(image, user, permission_policy):
instances = permission_policy.instances_user_has_permission_for(user, "choose")
return instances.exclude(pk=image.pk).filter(file_hash=image.file_hash)
|
Finds all the duplicates of a given image.
To keep things simple, two images are considered to be duplicates if they have the same `file_hash` value.
This function also ensures that the `user` can choose one of the duplicate images returned (if any).
| 43 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def find_image_duplicates(image, user, permission_policy):
instances = permission_policy.instances_user_has_permission_for(user, "choose")
return instances.exclude(pk=image.pk)... |
877 | def _trim_arity(func, maxargs=2):
global _trim_arity_call_line
if func in _single_arg_builtins:
return lambda s, l, t: func(t)
limit = 0
found_arity = False
| decorator to trim function calls to match the arity of the target | 12 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _trim_arity(func, maxargs=2):
global _trim_arity_call_line
if func in _single_arg_builtins:
return lambda s, l, t: func(t)
limit = 0
found_arity = False
... |
878 | def call_exmarkets(self, other_args):
parser = argparse.ArgumentParser(
prog="exmarkets",
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description=,
)
parser.add_argument(
"-e",
"--exchan... | Process exmarkets commandGet all exchange markets found for given exchange
You can display only N number of records with --limit parameter.
You can sort data by pair, base_currency_name, quote_currency_name, market_url, category,
reported_volume_24h_share, trust_score --s... | 82 | 101 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def call_exmarkets(self, other_args):
parser = argparse.ArgumentParser(
prog="exmarkets",
add_help=False,
formatter_class=argparse.Argume... |
879 | async def test_unload_config_entry(hass, entry, lcn_connection):
await hass.config_entries.async_unload(entry.entry_id)
assert hass.states.get("cover.cover_outputs").state == STATE_UNAVAILABLE
assert hass.states.get("cover.cover_relays").state == STATE_UNAVAILABLE
| Test the cover is removed when the config entry is unloaded. | 11 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_unload_config_entry(hass, entry, lcn_connection):
await hass.config_entries.async_unload(entry.entry_id)
assert hass.states.get("cover.cover_outputs").state == ST... |
880 | def topk(self, k, axis=-1, split_every=None):
from dask.array.reductions import topk
return topk(self, k, axis=axis, split_every=split_every)
| The top k elements of an array.
See :func:`dask.array.topk` for docstring.
| 11 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def topk(self, k, axis=-1, split_every=None):
from dask.array.reductions import topk
return topk(self, k, axis=axis, split_every=split_every)
```
###As... |
881 | def for_each_ternary(self, fn, selector=None, row=None, col=None) -> "Figure":
for obj in self.select_ternaries(selector=selector, row=row, col=col):
fn(obj)
return self
|
Apply a function to all ternary objects that satisfy the
specified selection criteria
Parameters
----------
fn:
Function that inputs a single ternary object.
selector: dict, function, or None (default None)
Dict to use as selection criteria.
... | 161 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def for_each_ternary(self, fn, selector=None, row=None, col=None) -> "Figure":
for obj in self.select_ternaries(selector=selector, row=row, col=col):
fn(obj)
... |
882 | def call(self, *args, **kwargs):
warnings.warn(
"'call()' method is deprecated. " + "Use '__call__()' instead",
DeprecationWarning,
)
return self.__call__(*args, **kwargs)
| Use ``__call__`` instead because this method is deprecated. | 8 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def call(self, *args, **kwargs):
warnings.warn(
"'call()' method is deprecated. " + "Use '__call__()' instead",
DeprecationWarning,
)
... |
883 | def validate_per_replica_inputs(distribution_strategy, x):
# Convert the inputs and targets into a list of PerReplica objects.
per_replica_list = tf.nest.flatten(x)
x_values_list = []
for x in per_replica_list:
# At this point x should contain only tensors.
x_values = distribution_strategy.unwrap(x)
... | Validates PerReplica dataset input list.
Args:
distribution_strategy: The current DistributionStrategy used to call
`fit`, `evaluate` and `predict`.
x: A list of PerReplica objects that represent the input or
target values.
Returns:
List containing the first element of each of the PerRepli... | 60 | 86 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def validate_per_replica_inputs(distribution_strategy, x):
# Convert the inputs and targets into a list of PerReplica objects.
per_replica_list = tf.nest.flatten(x)
x_values_list = ... |
884 | def get_mac_addr(self):
if (
self.bulb.host_firmware_version
and AwesomeVersion(self.bulb.host_firmware_version) >= FIX_MAC_FW
):
octets = [int(octet, 16) for octet in self.mac_addr.split(":")]
octets[5] = (octets[5] + 1) % 256
return ... | Increment the last byte of the mac address by one for FW>3.70. | 12 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_mac_addr(self):
if (
self.bulb.host_firmware_version
and AwesomeVersion(self.bulb.host_firmware_version) >= FIX_MAC_FW
):
... |
885 | def test_positive_integer_or_none_4():
assert positive_integer_or_none('none') is None
assert positive_integer_or_none('None') is None
| Assert that the TPOT CLI interface's positive_integer_or_none parsing return None when value is string 'None' or 'none'. | 17 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_positive_integer_or_none_4():
assert positive_integer_or_none('none') is None
assert positive_integer_or_none('None') is None
```
###Assistant : Assert th... |
886 | def get_local_part(value):
local_part = LocalPart()
leader = None
if value[0] in CFWS_LEADER:
leader, value = get_cfws(value)
if not value:
raise errors.HeaderParseError(
"expected local-part but found '{}'".format(value))
try:
token, value = get_dot_atom(val... | local-part = dot-atom / quoted-string / obs-local-part
| 7 | 112 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_local_part(value):
local_part = LocalPart()
leader = None
if value[0] in CFWS_LEADER:
leader, value = get_cfws(value)
if not value:
raise errors.... |
887 | def prepare_video_inputs(feature_extract_tester, equal_resolution=False, numpify=False, torchify=False):
assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"
video_inputs = []
for i in range(feature_extract_tester.batch_size):
if equal_resolu... | This function prepares a batch of videos: a list of list of PIL images, or a list of list of numpy arrays if
one specifies numpify=True, or a list of list of PyTorch tensors if one specifies torchify=True.
One can specify whether the videos are of the same resolution or not.
| 51 | 57 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def prepare_video_inputs(feature_extract_tester, equal_resolution=False, numpify=False, torchify=False):
assert not (numpify and torchify), "You cannot specify both numpy and PyTor... |
888 | def _verify_no_matching_http_header(self, ssl_vhost, header_substring):
header_path = self.parser.find_dir("Header", None,
start=ssl_vhost.path)
if header_path:
# "Existing Header directive for virtualhost"
pat = '(?:[ "]|^)(%s)... | Checks to see if there is an existing Header directive that
contains the string header_substring.
:param ssl_vhost: vhost to check
:type vhost: :class:`~certbot_apache._internal.obj.VirtualHost`
:param header_substring: string that uniquely identifies a header.
e.g: Str... | 46 | 38 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _verify_no_matching_http_header(self, ssl_vhost, header_substring):
header_path = self.parser.find_dir("Header", None,
start=s... |
889 | def indices(dimensions, dtype=int32, sparse=False):
dimensions = tuple(
core.concrete_or_error(operator.index, d, "dimensions argument of jnp.indices")
for d in dimensions)
N = len(dimensions)
output = []
s = dimensions
for i, dim in enumerate(dimensions):
idx = lax.iota(dtype, dim)
if spa... | \
Jax adds the optional `total_repeat_length` parameter which specifies the total
number of repeat, and defaults to sum(repeats). It must be specified for repeat
to be compilable. If `sum(repeats)` is larger than the specified
`total_repeat_length` the remaining values will be discarded. In the case of
`sum(repeats)` b... | 59 | 67 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def indices(dimensions, dtype=int32, sparse=False):
dimensions = tuple(
core.concrete_or_error(operator.index, d, "dimensions argument of jnp.indices")
for d in dimensions)
N... |
890 | def test_open_connection(tctx):
assert Playbook(tcp.TCPLayer(tctx, True)) << OpenConnection(tctx.server)
tctx.server.timestamp_start = 1624544785
assert Playbook(tcp.TCPLayer(tctx, True)) << None
|
If there is no server connection yet, establish one,
because the server may send data first.
| 16 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_open_connection(tctx):
assert Playbook(tcp.TCPLayer(tctx, True)) << OpenConnection(tctx.server)
tctx.server.timestamp_start = 1624544785
assert Playbook(tcp.TCPLay... |
891 | def get_connected_endpoints(self, obj):
endpoints = obj.connected_endpoints
if endpoints:
serializer = get_serializer_for_model(endpoints[0], prefix='Nested')
context = {'request': self.context['request']}
return serializer(endpoints, many=True, context=conte... |
Return the appropriate serializer for the type of connected object.
| 10 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_connected_endpoints(self, obj):
endpoints = obj.connected_endpoints
if endpoints:
serializer = get_serializer_for_model(endpoints[0], prefix='Nes... |
892 | def test_basic(self):
trees = [(nx.full_rary_tree(2, 2**2 - 1), 0) for i in range(2)]
actual = nx.join(trees)
expected = nx.full_rary_tree(2, 2**3 - 1)
assert nx.is_isomorphic(actual, expected)
| Tests for joining multiple subtrees at a root node. | 9 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_basic(self):
trees = [(nx.full_rary_tree(2, 2**2 - 1), 0) for i in range(2)]
actual = nx.join(trees)
expected = nx.full_rary_tree(2, 2**3 - 1)
... |
893 | def test_result_list_html(self):
new_parent = Parent.objects.create(name="parent")
new_child = Child.objects.create(name="name", parent=new_parent)
request = self.factory.get("/child/")
request.user = self.superuser
m = ChildAdmin(Child, custom_site)
cl = m.get_c... |
Inclusion tag result_list generates a table when with default
ModelAdmin settings.
| 11 | 77 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_result_list_html(self):
new_parent = Parent.objects.create(name="parent")
new_child = Child.objects.create(name="name", parent=new_parent)
request =... |
894 | def test_delete_uploaded_image(self):
# Send request
response = self.client.post(
reverse(
"wagtailimages:delete_upload_multiple", args=(self.uploaded_image.id,)
)
)
# Check response
self.assertEqual(response.status_code, 200)
... |
This tests that a POST request to the delete view deletes the UploadedImage
| 13 | 37 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_delete_uploaded_image(self):
# Send request
response = self.client.post(
reverse(
"wagtailimages:delete_upload_multiple", args=(... |
895 | def matrix(self) -> np.ndarray:
if not np.any(self._matrices[self._centering]):
matrix = self._matrices["legacy"].copy()
matrix[:, 2] -= self.pose.offset[self._centering]
self._matrices[self._centering] = matrix
logger.trace("original matrix: %s, new matr... | :class:`numpy.ndarray`: The 3x2 transformation matrix for extracting and aligning the
core face area out of the original frame, with no padding or sizing applied. The returned
matrix is offset for the given :attr:`centering`. | 33 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def matrix(self) -> np.ndarray:
if not np.any(self._matrices[self._centering]):
matrix = self._matrices["legacy"].copy()
matrix[:, 2] -= self.pose.of... |
896 | def read_docstub(filename):
in_documentation = False
capturing = False
indent_detection = ''
doc_stub = []
with open(filename, 'r') as t_module_data:
for line in t_module_data:
if in_documentation:
# start capturing the stub until indentation returns
... |
Quickly find short_description using string methods instead of node parsing.
This does not return a full set of documentation strings and is intended for
operations like ansible-doc -l.
| 28 | 100 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def read_docstub(filename):
in_documentation = False
capturing = False
indent_detection = ''
doc_stub = []
with open(filename, 'r') as t_module_data:
for l... |
897 | def test_02_train_predictor(self):
query = f
response = self.handler.native_query(query)
self.assertTrue(response.type == RESPONSE_TYPE.OK)
# def test_03_retrain_predictor(self):
# query = f"RETRAIN {self.test_model_name_1}"
# response = self.handler.native_query(query)
... |
CREATE PREDICTOR {self.test_model_name_1}
FROM {PG_HANDLER_NAME} (SELECT * FROM demo_data.home_rentals limit 50)
PREDICT rental_price
| 13 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_02_train_predictor(self):
query = f
response = self.handler.native_query(query)
self.assertTrue(response.type == RESPONSE_TYPE.OK)
# def test_03_retrain... |
898 | def get_dependencies(dsk, key=None, task=no_default, as_list=False):
if key is not None:
arg = dsk[key]
elif task is not no_default:
arg = task
else:
raise ValueError("Provide either key or task")
return keys_in_tasks(dsk, [arg], as_list=as_list)
| Get the immediate tasks on which this task depends
Examples
--------
>>> inc = lambda x: x + 1
>>> add = lambda x, y: x + y
>>> dsk = {'x': 1,
... 'y': (inc, 'x'),
... 'z': (add, 'x', 'y'),
... 'w': (inc, 'z'),
... 'a': (add, (inc, 'x'), 1)}
>>> get_... | 92 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_dependencies(dsk, key=None, task=no_default, as_list=False):
if key is not None:
arg = dsk[key]
elif task is not no_default:
arg = task
else:
... |
899 | def test_dict_checkpoint_fs(self):
checkpoint = self._prepare_dict_checkpoint()
# Convert into fs checkpoint
path = checkpoint.to_directory()
self.assertIsInstance(path, str)
# Create from path
checkpoint = Checkpoint.from_directory(path)
self.assertTru... | Test conversion from dict to FS checkpoint and back. | 9 | 24 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_dict_checkpoint_fs(self):
checkpoint = self._prepare_dict_checkpoint()
# Convert into fs checkpoint
path = checkpoint.to_directory()
self.a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.