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 |
|---|---|---|---|---|---|---|
600 | def get_model_dir(cfg):
for key in cfg.keys():
if type(cfg[key]) == dict and \
("enable" in cfg[key].keys() and cfg[key]['enable']
or "enable" not in cfg[key].keys()):
if "model_dir" in cfg[key].keys():
model_dir = cfg[key]["model_dir"]
... |
Auto download inference model if the model_path is a url link.
Otherwise it will use the model_path directly.
| 18 | 116 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_model_dir(cfg):
for key in cfg.keys():
if type(cfg[key]) == dict and \
("enable" in cfg[key].keys() and cfg[key]['enable']
or "enable" n... |
601 | def component(self, x, y):
if x >= 0 and x < self.__height and y >= 0 and y < self.__width:
return self.__matrix[x][y]
else:
raise Exception("changeComponent: indices out of bounds")
|
returns the specified (x,y) component
| 5 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def component(self, x, y):
if x >= 0 and x < self.__height and y >= 0 and y < self.__width:
return self.__matrix[x][y]
else:
raise Exception(... |
602 | def toggle(self, all=None, ticks=None, ticklabels=None, label=None):
if all:
_ticks, _ticklabels, _label = True, True, True
elif all is not None:
_ticks, _ticklabels, _label = False, False, False
else:
_ticks, _ticklabels, _label = None, None, None
... |
Toggle visibility of ticks, ticklabels, and (axis) label.
To turn all off, ::
axis.toggle(all=False)
To turn all off but ticks on ::
axis.toggle(all=False, ticks=True)
To turn all on but (axis) label off ::
axis.toggle(all=True, label=False)
| 35 | 79 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def toggle(self, all=None, ticks=None, ticklabels=None, label=None):
if all:
_ticks, _ticklabels, _label = True, True, True
elif all is not None:
... |
603 | def mock_json_schema(request, monkeypatch, tmp_path):
# Do not patch integration tests
if "integration" in request.keywords:
return
# Mock the subclasses list to make it very small, containing only mock nodes
monkeypatch.setattr(
haystack.nodes._json_schema,
"find_subclasse... |
JSON schema with the master version and only mocked nodes.
| 10 | 82 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def mock_json_schema(request, monkeypatch, tmp_path):
# Do not patch integration tests
if "integration" in request.keywords:
return
# Mock the subclasses list to ma... |
604 | def _has_nchw_support():
explicitly_on_cpu = _is_current_explicit_device("CPU")
gpus_available = bool(_get_available_gpus())
return not explicitly_on_cpu and gpus_available
# VARIABLE MANIPULATION
| Check whether the current scope supports NCHW ops.
TensorFlow does not support NCHW on CPU. Therefore we check if we are not
explicitly put on
CPU, and have GPUs available. In this case there will be soft-placing on the
GPU device.
Returns:
bool: if the current scope device placement would... | 52 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _has_nchw_support():
explicitly_on_cpu = _is_current_explicit_device("CPU")
gpus_available = bool(_get_available_gpus())
return not explicitly_on_cpu and gpus_available
... |
605 | def tensor2img(tensor, out_type=np.uint8, min_max=(0, 1)):
tensor = tensor.squeeze().float().cpu().clamp_(*min_max) # squeeze first, then clamp
tensor = (tensor - min_max[0]) / (min_max[1] - min_max[0]) # to range [0,1]
n_dim = tensor.dim()
if n_dim == 4:
n_img = len(tensor)
img_n... |
Converts a torch Tensor into an image Numpy array of BGR channel order
Input: 4D(B,(3/1),H,W), 3D(C,H,W), or 2D(H,W), any range, RGB channel order
Output: 3D(H,W,C) or 2D(H,W), [0,255], np.uint8 (default)
# --------------------------------------------
# Augmentation, flipe and/or rotate
# ------------... | 62 | 117 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def tensor2img(tensor, out_type=np.uint8, min_max=(0, 1)):
tensor = tensor.squeeze().float().cpu().clamp_(*min_max) # squeeze first, then clamp
tensor = (tensor - min_max[0]) /... |
606 | def get_local_ip_address() -> str:
try:
ip_address = requests.get(
"https://checkip.amazonaws.com/", timeout=3
).text.strip()
except (requests.ConnectionError, requests.exceptions.ReadTimeout):
ip_address = "No internet connection"
return ip_address
| Gets the public IP address or returns the string "No internet connection" if unable to obtain it. | 17 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_local_ip_address() -> str:
try:
ip_address = requests.get(
"https://checkip.amazonaws.com/", timeout=3
).text.strip()
except (requests.Connec... |
607 | def get_tip(self):
tips = self.get_tips()
if len(tips) == 0:
raise Exception("tip not found")
else:
return tips[0]
| Returns the TipableVMobject instance's (first) tip,
otherwise throws an exception. | 10 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_tip(self):
tips = self.get_tips()
if len(tips) == 0:
raise Exception("tip not found")
else:
return tips[0]
```
#... |
608 | def shuffle(self, func, lengths, **kwargs):
num_splits = len(lengths)
# We add these to kwargs and will pop them off before performing the operation.
kwargs["manual_partition"] = True
kwargs["_lengths"] = lengths
args = [self.axis, func, num_splits, False]
args.e... |
Shuffle the order of the data in this axis partition based on the `lengths`.
Parameters
----------
func : callable
The function to apply before splitting.
lengths : list
The list of partition lengths to split the result into.
**kwargs : dict
... | 60 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def shuffle(self, func, lengths, **kwargs):
num_splits = len(lengths)
# We add these to kwargs and will pop them off before performing the operation.
kwargs[... |
609 | def test_background_add_room_type_column(self):
# Create a room without a type
room_id = self._generate_room()
# Get event_id of the m.room.create event
event_id = self.get_success(
self.store.db_pool.simple_select_one_onecol(
table="current_state_e... | Test that the background update to populate the `room_type` column in
`room_stats_state` works properly.
| 14 | 136 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_background_add_room_type_column(self):
# Create a room without a type
room_id = self._generate_room()
# Get event_id of the m.room.create event
... |
610 | def get_feedback():
labels = DOCUMENT_STORE.get_all_labels()
return labels
@router.delete("/feedback") |
This endpoint allows the API user to retrieve all the feedback that has been submitted
through the `POST /feedback` endpoint.
| 20 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_feedback():
labels = DOCUMENT_STORE.get_all_labels()
return labels
@router.delete("/feedback")
```
###Assistant :
This endpoint allows the API user to... |
611 | def get_formatter_for_filename(fn, **options):
fn = basename(fn)
for modname, name, _, filenames, _ in FORMATTERS.values():
for filename in filenames:
if _fn_matches(fn, filename):
if name not in _formatter_cache:
_load_formatters(modname)
... | Lookup and instantiate a formatter by filename pattern.
Raises ClassNotFound if not found.
| 13 | 52 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_formatter_for_filename(fn, **options):
fn = basename(fn)
for modname, name, _, filenames, _ in FORMATTERS.values():
for filename in filenames:
if _fn... |
612 | def setup_sigterm_on_parent_death():
try:
import ctypes
import signal
libc = ctypes.CDLL("libc.so.6")
# Set the parent process death signal of the command process to SIGTERM.
libc.prctl(1, signal.SIGTERM) # PR_SET_PDEATHSIG, see prctl.h
except OSError as e:
... |
Uses prctl to automatically send SIGTERM to the child process when its parent is
dead. The child process itself should handle SIGTERM properly.
| 23 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def setup_sigterm_on_parent_death():
try:
import ctypes
import signal
libc = ctypes.CDLL("libc.so.6")
# Set the parent process death signal of the c... |
613 | def force_reads(self) -> "Dataset[T]":
blocks = self.get_internal_block_refs()
bar = ProgressBar("Force reads", len(blocks))
bar.block_until_complete(blocks)
return self
| Force full evaluation of the blocks of this dataset.
This can be used to read all blocks into memory. By default, Datasets
doesn't read blocks from the datasource until the first transform.
| 32 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def force_reads(self) -> "Dataset[T]":
blocks = self.get_internal_block_refs()
bar = ProgressBar("Force reads", len(blocks))
bar.block_until_complete(blocks)... |
614 | def __iter__(self) -> Iterator[tuple[Widget, Region, Region, Size, Size]]:
layers = sorted(self.map.items(), key=lambda item: item[1].order, reverse=True)
intersection = Region.intersection
for widget, (region, _order, clip, virtual_size, container_size) in layers:
yield (
... | Iterate map with information regarding each widget and is position
Yields:
Iterator[tuple[Widget, Region, Region, Size, Size]]: Iterates a tuple of
Widget, clip region, region, virtual size, and container size.
| 29 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __iter__(self) -> Iterator[tuple[Widget, Region, Region, Size, Size]]:
layers = sorted(self.map.items(), key=lambda item: item[1].order, reverse=True)
intersecti... |
615 | def get_names_flat(adtype):
listnames = []
names = adtype.names
for name in names:
listnames.append(name)
current = adtype[name]
if current.names is not None:
listnames.extend(get_names_flat(current))
return tuple(listnames)
|
Returns the field names of the input datatype as a tuple. Input datatype
has to have fields otherwise error is raised.
Nested structure are flattened beforehand.
Parameters
----------
adtype : dtype
Input datatype
Examples
--------
>>> from numpy.lib import recfunctions as... | 72 | 24 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_names_flat(adtype):
listnames = []
names = adtype.names
for name in names:
listnames.append(name)
current = adtype[name]
if current.names is ... |
616 | def test_memory_leak(self):
import gc
import weakref
results = {}
for kind in plotting.PlotAccessor._all_kinds:
args = {}
if kind in ["hexbin", "scatter", "pie"]:
df = DataFrame(
{
"A": np.rand... | Check that every plot type gets properly collected. | 8 | 124 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_memory_leak(self):
import gc
import weakref
results = {}
for kind in plotting.PlotAccessor._all_kinds:
args = {}
i... |
617 | def disabled_excepthook() -> Iterator[None]:
old_excepthook = sys.excepthook
sys.excepthook = sys.__excepthook__
try:
yield
finally:
# If the code we did run did change sys.excepthook, we leave it
# unchanged. Otherwise, we reset it.
if sys.excepthook is sys.__except... | Run code with the exception hook temporarily disabled. | 8 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def disabled_excepthook() -> Iterator[None]:
old_excepthook = sys.excepthook
sys.excepthook = sys.__excepthook__
try:
yield
finally:
# If the code we did... |
618 | def trigger_import(*dfs):
if ASV_USE_STORAGE_FORMAT != "hdk" or ASV_USE_IMPL == "pandas":
return
from modin.experimental.core.execution.native.implementations.hdk_on_native.db_worker import (
DbWorker,
)
for df in dfs:
df.shape # to trigger real execution
df._quer... |
Trigger import execution for DataFrames obtained by HDK engine.
Parameters
----------
*dfs : iterable
DataFrames to trigger import.
| 18 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def trigger_import(*dfs):
if ASV_USE_STORAGE_FORMAT != "hdk" or ASV_USE_IMPL == "pandas":
return
from modin.experimental.core.execution.native.implementations.hdk_on_na... |
619 | def _jacfwd(f, primals):
jac_flat = []
flat_primals = tf.nest.flatten(primals)
tangent_mask = [tf.zeros_like(primal) for primal in flat_primals]
for primal_index, primal in enumerate(flat_primals):
primal_vector = tf.reshape(primal, [-1])
primal_vector_length = tf.size(primal_vector... | Compute the jacobian of `f` at `primals` using forward-mode autodiff. | 10 | 63 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _jacfwd(f, primals):
jac_flat = []
flat_primals = tf.nest.flatten(primals)
tangent_mask = [tf.zeros_like(primal) for primal in flat_primals]
for primal_index, primal... |
620 | def record_timing(name, duration=None, description=None):
timing_information = getattr(flask.g, "timing_information", {})
if name in timing_information:
raise KeyError(f'Duplicate resource name "{name}" found.')
timing_information[name] = {"dur": round(duration * 1000), "d... | Records timing information for a server resource.
:param name: The name of the resource.
:type name: string
:param duration: The time in seconds to report. Internally, this
is rounded to the nearest millisecond.
:type duration: float or None
:param description: A d... | 50 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def record_timing(name, duration=None, description=None):
timing_information = getattr(flask.g, "timing_information", {})
if name in timing_information:
... |
621 | def admin_actions(context):
context["action_index"] = context.get("action_index", -1) + 1
return context
@register.tag(name="admin_actions") |
Track the number of times the action field has been rendered on the page,
so we know which value to use.
| 21 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def admin_actions(context):
context["action_index"] = context.get("action_index", -1) + 1
return context
@register.tag(name="admin_actions")
```
###Assistant :
... |
622 | async def test_lights(hass, mock_bridge_v2, v2_resources_test_data):
await mock_bridge_v2.api.load_test_data(v2_resources_test_data)
await setup_platform(hass, mock_bridge_v2, "light")
# there shouldn't have been any requests at this point
assert len(mock_bridge_v2.mock_requests) == 0
# 6 enti... | Test if all v2 lights get created with correct features. | 10 | 264 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_lights(hass, mock_bridge_v2, v2_resources_test_data):
await mock_bridge_v2.api.load_test_data(v2_resources_test_data)
await setup_platform(hass, mock_bridge_v2, ... |
623 | def setup_data(self, path):
for message, new_episode in super().setup_data(path):
assert (
message['text'] == '__SILENCE__'
), 'The expected original context string is not found!'
message['text'] = 'Person 1:'
yield message, new_episode
|
Modify each output message to add in an OPT-compatible context string.
| 11 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def setup_data(self, path):
for message, new_episode in super().setup_data(path):
assert (
message['text'] == '__SILENCE__'
), 'The e... |
624 | def _get_input_locations(self) -> List[str]:
if not self._args.batch_mode or os.path.isfile(self._args.input_dir):
return [self._args.input_dir] # Not batch mode or a single file
retval = [os.path.join(self._args.input_dir, fname)
for fname in os.listdir(self._ar... | Obtain the full path to input locations. Will be a list of locations if batch mode is
selected, or a containing a single location if batch mode is not selected.
Returns
-------
list:
The list of input location paths
| 39 | 40 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_input_locations(self) -> List[str]:
if not self._args.batch_mode or os.path.isfile(self._args.input_dir):
return [self._args.input_dir] # Not batch mod... |
625 | def get_party_gle_currency(party_type, party, company):
def generator():
existing_gle_currency = frappe.db.sql(
,
{"company": company, "party_type": party_type, "party": party},
)
return existing_gle_currency[0][0] if existing_gle_currency else None
return frappe.local_cache(
"party_gle_currency", (pa... | select account_currency from `tabGL Entry`
where docstatus=1 and company=%(company)s and party_type=%(party_type)s and party=%(party)s
limit 1 | 15 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_party_gle_currency(party_type, party, company):
def generator():
existing_gle_currency = frappe.db.sql(
,
{"company": company, "party_type": party_type, "party": party},
)... |
626 | def load_breast_cancer(*, return_X_y=False, as_frame=False):
data_file_name = "breast_cancer.csv"
data, target, target_names, fdescr = load_csv_data(
data_file_name=data_file_name, descr_file_name="breast_cancer.rst"
)
feature_names = np.array(
[
"mean radius",
... | Load and return the breast cancer wisconsin dataset (classification).
The breast cancer dataset is a classic and very easy binary classification
dataset.
================= ==============
Classes 2
Samples per class 212(M),357(B)
Samples total 569
... | 356 | 125 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def load_breast_cancer(*, return_X_y=False, as_frame=False):
data_file_name = "breast_cancer.csv"
data, target, target_names, fdescr = load_csv_data(
data_file_name=data... |
627 | def get_filter_by_name(filtername, **options):
cls = find_filter_class(filtername)
if cls:
return cls(**options)
else:
raise ClassNotFound('filter %r not found' % filtername)
| Return an instantiated filter.
Options are passed to the filter initializer if wanted.
Raise a ClassNotFound if not found.
| 19 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_filter_by_name(filtername, **options):
cls = find_filter_class(filtername)
if cls:
return cls(**options)
else:
raise ClassNotFound('filter %r not fou... |
628 | def wide_resnet50_2(pretrained=False, **kwargs):
kwargs['width'] = 64 * 2
return _resnet('wide_resnet50_2', BottleneckBlock, 50, pretrained, **kwargs)
| Wide ResNet-50-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
Examples:
.. code-block:: python
import paddle
from paddle.vision.models import wide_resnet50_2... | 57 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def wide_resnet50_2(pretrained=False, **kwargs):
kwargs['width'] = 64 * 2
return _resnet('wide_resnet50_2', BottleneckBlock, 50, pretrained, **kwargs)
```
###Assis... |
629 | def test_username_available(self) -> None:
url = "%s?username=%s" % (self.url, "allowed")
channel = self.make_request("GET", url, access_token=self.admin_user_tok)
self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
self.assertTrue(channel.json_body["available... |
The endpoint should return a HTTPStatus.OK response if the username does not exist
| 13 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_username_available(self) -> None:
url = "%s?username=%s" % (self.url, "allowed")
channel = self.make_request("GET", url, access_token=self.admin_user_tok)
... |
630 | def test_with_include_glob_filtering_case4a_include_strong():
incl_dom = {}
incl_glob = {"*working"}
incl_ent = {"binary_sensor.specificly_included"}
excl_dom = {}
excl_glob = {"*broken", "*notworking", "binary_sensor.*"}
excl_ent = {"light.ignoreme"}
testfilter = generate_filter(
... | Test case 4 - include and exclude specified, both have globs, and a specifically included entity. | 16 | 84 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_with_include_glob_filtering_case4a_include_strong():
incl_dom = {}
incl_glob = {"*working"}
incl_ent = {"binary_sensor.specificly_included"}
excl_dom = {}
e... |
631 | def get_sales_orders(self):
so_filter = item_filter = ""
bom_item = "bom.item = so_item.item_code"
date_field_mapper = {
"from_date": (">=", "so.transaction_date"),
"to_date": ("<=", "so.transaction_date"),
"from_delivery_date": (">=", "so_item.delivery_date"),
"to_delivery_date": ("<=", "so_item.delivery_d... |
select distinct so.name, so.transaction_date, so.customer, so.base_grand_total
from `tabSales Order` so, `tabSales Order Item` so_item
where so_item.parent = so.name
and so.docstatus = 1 and so.status not in ("Stopped", "Closed")
and so.company = %(company)s
and so_item.qty > so_item.work_order_qty {so_... | 80 | 93 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_sales_orders(self):
so_filter = item_filter = ""
bom_item = "bom.item = so_item.item_code"
date_field_mapper = {
"from_date": (">=", "so.transaction_date"),
"to_date": ("<=",... |
632 | def test_copy_published_emits_signal(self):
christmas_page = EventPage.objects.get(url_path="/home/events/christmas/")
signal_fired = False
signal_page = None
| Test that copying of a published page emits a page_published signal. | 11 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_copy_published_emits_signal(self):
christmas_page = EventPage.objects.get(url_path="/home/events/christmas/")
signal_fired = False
signal_page = No... |
633 | def get_all_tests():
test_root_dir = os.path.join(PATH_TO_TRANFORMERS, "tests")
# test folders/files directly under `tests` folder
tests = os.listdir(test_root_dir)
tests = sorted(
list(filter(lambda x: os.path.isdir(x) or x.startswith("tests/test_"), [f"tests/{x}" for x in tests]))
)
... |
Return a list of paths to all test folders and files under `tests`. All paths are rooted at `tests`.
- folders under `tests`: `tokenization`, `pipelines`, etc. The folder `models` is excluded.
- folders under `tests/models`: `bert`, `gpt2`, etc.
- test files under `tests`: `test_modeling_common.py`, `... | 46 | 55 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_all_tests():
test_root_dir = os.path.join(PATH_TO_TRANFORMERS, "tests")
# test folders/files directly under `tests` folder
tests = os.listdir(test_root_dir)
tes... |
634 | def test_vtrace(self):
seq_len = 5
batch_size = 10
# Create log_rhos such that rho will span from near-zero to above the
# clipping thresholds. In particular, calculate log_rhos in
# [-2.5, 2.5),
# so that rho is in approx [0.08, 12.2).
space_w_time = Bo... | Tests V-trace against ground truth data calculated in python. | 9 | 150 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_vtrace(self):
seq_len = 5
batch_size = 10
# Create log_rhos such that rho will span from near-zero to above the
# clipping thresholds. In p... |
635 | def pdfdump(self, filename=None, **kargs):
# type: (Optional[str], **Any) -> None
from scapy.config import conf
from scapy.utils import get_temp_file, ContextManagerSubprocess
canvas = self.canvas_dump(**kargs)
if filename is None:
fname = get_temp_file(autoe... |
pdfdump(filename=None, layer_shift=0, rebuild=1)
Creates a PDF file describing a packet. If filename is not provided a
temporary file is created and xpdf is called.
:param filename: the file's filename
| 29 | 45 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def pdfdump(self, filename=None, **kargs):
# type: (Optional[str], **Any) -> None
from scapy.config import conf
from scapy.utils import get_temp_file, Contex... |
636 | def index_sample(x, index):
x_s = x.shape
dim = len(index.shape) - 1
assert x_s[:dim] == index.shape[:dim]
if len(x_s) == 3 and dim == 1:
r_x = paddle.reshape(x, shape=[-1, x_s[1], x_s[-1]])
else:
r_x = paddle.reshape(x, shape=[-1, x_s[-1]])
index = paddle.reshape(index, s... |
Select input value according to index
Arags:
input: input matrix
index: index matrix
Returns:
output
>>> input
[
[1, 2, 3],
[4, 5, 6]
]
>>> index
[
[1, 2],
[0, 1]
]
>>> index_sample(input, index)
[
[2, 3],
... | 42 | 105 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def index_sample(x, index):
x_s = x.shape
dim = len(index.shape) - 1
assert x_s[:dim] == index.shape[:dim]
if len(x_s) == 3 and dim == 1:
r_x = paddle.reshape(x... |
637 | def __new__(cls, name, patch, symbols=None, relations={}, **kwargs):
if not isinstance(name, Str):
name = Str(name)
# canonicallize the symbols
if symbols is None:
names = kwargs.get('names', None)
if names is None:
symbols = Tuple(
... |
The 'names' argument to CoordSystem is deprecated. Use 'symbols' instead. That
is, replace
CoordSystem(..., names={names})
with
CoordSystem(..., symbols=[{', '.join(["Symbol(" + repr(n) + ", real=True)" for n in names])}])
Passing a string as the coordinate symbol name to CoordSystem i... | 78 | 188 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __new__(cls, name, patch, symbols=None, relations={}, **kwargs):
if not isinstance(name, Str):
name = Str(name)
# canonicallize the symbols
if symbol... |
638 | def tab_focus(*, info):
model = _tabs(win_id_filter=lambda win_id: win_id == info.win_id,
add_win_id=False, current_win_id=info.win_id)
special = [
("last", "Focus the last-focused tab"),
("stack-next", "Go forward through a stack of focused tabs"),
("stack-prev",... | A model to complete on open tabs in the current window. | 11 | 43 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def tab_focus(*, info):
model = _tabs(win_id_filter=lambda win_id: win_id == info.win_id,
add_win_id=False, current_win_id=info.win_id)
special = [
("... |
639 | def get_mode_of_payment_details(filters):
mode_of_payment_details = {}
invoice_list = get_invoices(filters)
invoice_list_names = ",".join("'" + invoice["name"] + "'" for invoice in invoice_list)
if invoice_list:
inv_mop_detail = frappe.db.sql(
.format(
invoice_list_names=invoice_list_names
),
as_dict... |
select t.owner,
t.posting_date,
t.mode_of_payment,
sum(t.paid_amount) as paid_amount
from (
select a.owner, a.posting_date,
ifnull(b.mode_of_payment, '') as mode_of_payment, sum(b.base_amount) as paid_amount
from `tabSales Invoice` a, `tabSales Invoice Payment` b
where a.n... | 169 | 80 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_mode_of_payment_details(filters):
mode_of_payment_details = {}
invoice_list = get_invoices(filters)
invoice_list_names = ",".join("'" + invoice["name"] + "'" for invoice in invoic... |
640 | def get_config_context(self):
data = {}
if not hasattr(self, 'config_context_data'):
# The annotation is not available, so we fall back to manually querying for the config context objects
config_context_data = ConfigContext.objects.get_for_object(self, aggregate_data=Tr... |
Compile all config data, overwriting lower-weight values with higher-weight values where a collision occurs.
Return the rendered configuration context for a device or VM.
| 24 | 85 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_config_context(self):
data = {}
if not hasattr(self, 'config_context_data'):
# The annotation is not available, so we fall back to manually quer... |
641 | def test_displayname_is_set_avatar_is_none(self) -> None:
channel = self.make_request(
"POST",
self.url,
access_token=self.admin_user_tok,
content={
"user_id": self.other_user,
"content": {"msgtype": "m.text", "body": "test... |
Tests that sending a server notices is successfully,
if a display_name is set, avatar_url is `None` and
"check avatar size and mime type" is set.
| 25 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_displayname_is_set_avatar_is_none(self) -> None:
channel = self.make_request(
"POST",
self.url,
access_token=self.admin_user_tok... |
642 | def cur_iter_done(self) -> bool:
return all(
self._get_result_time(result) >= self._cumul_r
for result in self._live_trials.values()
)
| Checks if all iterations have completed.
TODO(rliaw): also check that `t.iterations == self._r` | 13 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def cur_iter_done(self) -> bool:
return all(
self._get_result_time(result) >= self._cumul_r
for result in self._live_trials.values()
)
... |
643 | def get_attendance_years():
year_list = frappe.db.sql_list(
)
if not year_list:
year_list = [getdate().year]
return "\n".join(str(year) for year in year_list)
| select distinct YEAR(date) from `tabStudent Attendance` ORDER BY YEAR(date) DESC | 10 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_attendance_years():
year_list = frappe.db.sql_list(
)
if not year_list:
year_list = [getdate().year]
return "\n".join(str(year) for year in year_list)
```
###A... |
644 | async def test_discovery_notification(hass):
mock_integration(hass, MockModule("test"))
mock_entity_platform(hass, "config_flow.test", None)
with patch.dict(config_entries.HANDLERS):
| Test that we create/dismiss a notification when source is discovery. | 10 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_discovery_notification(hass):
mock_integration(hass, MockModule("test"))
mock_entity_platform(hass, "config_flow.test", None)
with patch.dict(config_entries.... |
645 | def get_preference(self, identifier, resolutions, candidates, information):
raise NotImplementedError
| Produce a sort key for given requirement based on preference.
The preference is defined as "I think this requirement should be
resolved first". The lower the return value is, the more preferred
this group of arguments is.
:param identifier: An identifier as returned by ``identify()``. ... | 279 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_preference(self, identifier, resolutions, candidates, information):
raise NotImplementedError
```
###Assistant : Produce a sort key for given requiremen... |
646 | def prepare_metadata(self) -> None:
assert self.source_dir
details = self.name or f"from {self.link}"
if self.use_pep517:
assert self.pep517_backend is not None
if (
self.editable
and self.permit_editable_wheels
an... | Ensure that project metadata is available.
Under PEP 517 and PEP 660, call the backend hook to prepare the metadata.
Under legacy processing, call setup.py egg-info.
| 26 | 72 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def prepare_metadata(self) -> None:
assert self.source_dir
details = self.name or f"from {self.link}"
if self.use_pep517:
assert self.pep517_bac... |
647 | def get_image_filename(self, image, filterspec):
name, ext = os.path.splitext(os.path.basename(image.file.name))
return "{}images/{}.{}{}".format(settings.MEDIA_URL, name, filterspec, ext)
|
Get the generated filename for a resized image
| 8 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_image_filename(self, image, filterspec):
name, ext = os.path.splitext(os.path.basename(image.file.name))
return "{}images/{}.{}{}".format(settings.MEDIA_URL,... |
648 | def min(self, other, context=None):
other = _convert_other(other, raiseit=True)
if context is None:
context = getcontext()
if self._is_special or other._is_special:
# If one operand is a quiet NaN and the other is number, then the
# number is always... | Returns the smaller value.
Like min(self, other) except if one is not a number, returns
NaN (and signals if one is sNaN). Also rounds.
| 24 | 95 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def min(self, other, context=None):
other = _convert_other(other, raiseit=True)
if context is None:
context = getcontext()
if self._is_special ... |
649 | def test_simplelistfilter_with_none_returning_lookups(self):
modeladmin = DecadeFilterBookAdminWithNoneReturningLookups(Book, site)
request = self.request_factory.get("/", {})
request.user = self.alfred
changelist = modeladmin.get_changelist_instance(request)
filterspec ... |
A SimpleListFilter lookups method can return None but disables the
filter completely.
| 12 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_simplelistfilter_with_none_returning_lookups(self):
modeladmin = DecadeFilterBookAdminWithNoneReturningLookups(Book, site)
request = self.request_factory.ge... |
650 | def precompute_fill_value(dataset_cols, feature, preprocessing_parameters, backend):
missing_value_strategy = preprocessing_parameters["missing_value_strategy"]
if missing_value_strategy == FILL_WITH_CONST:
return preprocessing_parameters["fill_value"]
elif missing_value_strategy == FILL_WITH_M... | Precomputes the fill value for a feature.
NOTE: this is called before NaNs are removed from the dataset. Modifications here must handle NaNs gracefully.
| 24 | 157 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def precompute_fill_value(dataset_cols, feature, preprocessing_parameters, backend):
missing_value_strategy = preprocessing_parameters["missing_value_strategy"]
if missing_value... |
651 | def loss_labels(self, outputs, targets, indices, num_boxes, log=True):
if "logits" not in outputs:
raise ValueError("No logits were found in the outputs")
source_logits = outputs["logits"]
idx = self._get_source_permutation_idx(indices)
target_classes_o = torch.cat... | Classification loss (NLL)
targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes]
| 16 | 84 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def loss_labels(self, outputs, targets, indices, num_boxes, log=True):
if "logits" not in outputs:
raise ValueError("No logits were found in the outputs")
... |
652 | def test_stacking_classifier_multilabel_predict_proba(estimator):
X_train, X_test, y_train, y_test = train_test_split(
X_multilabel, y_multilabel, stratify=y_multilabel, random_state=42
)
n_outputs = 3
estimators = [("est", estimator)]
stacker = StackingClassifier(
estimators=e... | Check the behaviour for the multilabel classification case and the
`predict_proba` stacking method.
Estimators are not consistent with the output arrays and we need to ensure that
we handle all cases.
| 31 | 62 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_stacking_classifier_multilabel_predict_proba(estimator):
X_train, X_test, y_train, y_test = train_test_split(
X_multilabel, y_multilabel, stratify=y_multilabel, ran... |
653 | def get_page(self, url):
# http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api
scheme, netloc, path, _, _, _ = urlparse(url)
if scheme == 'file' and os.path.isdir(url2pathname(path)):
url = urljoin(ensure_slash(url), 'index.html')
if url in self._p... |
Get the HTML for an URL, possibly from an in-memory cache.
XXX TODO Note: this cache is never actually cleared. It's assumed that
the data won't get stale over the lifetime of a locator instance (not
necessarily true for the default_locator).
| 41 | 199 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_page(self, url):
# http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api
scheme, netloc, path, _, _, _ = urlparse(url)
if scheme == '... |
654 | def enable_all_warnings() -> None:
__diag__.enable_all_warnings()
# hide abstract class
del __config_flags
|
Enable all global pyparsing diagnostic warnings (see :class:`Diagnostics`).
| 8 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def enable_all_warnings() -> None:
__diag__.enable_all_warnings()
# hide abstract class
del __config_flags
```
###Assistant :
Enable all global pyparsing diagno... |
655 | def export_yaml(self):
yaml_data = [obj.to_yaml() for obj in self.queryset]
return '---\n'.join(yaml_data)
|
Export the queryset of objects as concatenated YAML documents.
| 9 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def export_yaml(self):
yaml_data = [obj.to_yaml() for obj in self.queryset]
return '---\n'.join(yaml_data)
```
###Assistant :
Export the query... |
656 | def url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False):
if url is not None:
url = url.strip()
if not url:
return False
if allowed_hosts is None:
allowed_hosts = set()
elif isinstance(allowed_hosts, str):
allowed_hosts = {allowed_hosts}
# Chr... |
Return ``True`` if the url uses an allowed host and a safe scheme.
Always return ``False`` on an empty url.
If ``require_https`` is ``True``, only 'https' will be considered a valid
scheme, as opposed to 'http' and 'https' with the default, ``False``.
Note: "True" doesn't entail that a URL is "s... | 70 | 79 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False):
if url is not None:
url = url.strip()
if not url:
return False
if allowed_hosts... |
657 | def get_ps(module, pattern):
found = False
if platform.system() == 'SunOS':
flags = '-ef'
else:
flags = 'auxww'
psbin = module.get_bin_path('ps', True)
(rc, psout, pserr) = module.run_command([psbin, flags])
if rc == 0:
for line in psout.splitlines():
if... |
Last resort to find a service by trying to match pattern to programs in memory
| 15 | 60 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_ps(module, pattern):
found = False
if platform.system() == 'SunOS':
flags = '-ef'
else:
flags = 'auxww'
psbin = module.get_bin_path('ps', True)
... |
658 | def apply(self, sample, context=None):
im = sample['image']
im = im.astype(np.float32, copy=False)
if self.is_scale:
scale = 1.0 / 255.0
im *= scale
if self.norm_type == 'mean_std':
mean = np.array(self.mean)[np.newaxis, np.newaxis, :]
... | Normalize the image.
Operators:
1.(optional) Scale the pixel to [0,1]
2.(optional) Each pixel minus mean and is divided by std
| 20 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def apply(self, sample, context=None):
im = sample['image']
im = im.astype(np.float32, copy=False)
if self.is_scale:
scale = 1.0 / 255.0
... |
659 | def _check_m2m_through_same_relationship(cls):
errors = []
seen_intermediary_signatures = []
fields = cls._meta.local_many_to_many
# Skip when the target model wasn't found.
fields = (f for f in fields if isinstance(f.remote_field.model, ModelBase))
# Skip wh... | Check if no relationship model is used by more than one m2m field. | 13 | 88 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _check_m2m_through_same_relationship(cls):
errors = []
seen_intermediary_signatures = []
fields = cls._meta.local_many_to_many
# Skip when the... |
660 | def image(self) -> "np.ndarray":
assert self._image is not None
return self._image
| :class:`numpy.ndarray`: The source frame for this object. | 7 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def image(self) -> "np.ndarray":
assert self._image is not None
return self._image
```
###Assistant : :class:`numpy.ndarray`: The source frame for this... |
661 | def test_sends_deployment_notification(self, record_analytics):
release = self.create_release()
version_parsed = self.version_parsed = parse_release(release.version)["description"]
url = f"/api/0/organizations/{self.organization.slug}/releases/{release.version}/deploys/"
with s... |
Test that an email AND Slack notification are sent with
the expected values when a release is deployed.
| 18 | 113 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_sends_deployment_notification(self, record_analytics):
release = self.create_release()
version_parsed = self.version_parsed = parse_release(release.version... |
662 | def get_all_mode_of_payments(doc):
return frappe.db.sql(
,
{"company": doc.company},
as_dict=1,
)
|
select mpa.default_account, mpa.parent, mp.type as type
from `tabMode of Payment Account` mpa,`tabMode of Payment` mp
where mpa.parent = mp.name and mpa.company = %(company)s and mp.enabled = 1 | 27 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_all_mode_of_payments(doc):
return frappe.db.sql(
,
{"company": doc.company},
as_dict=1,
)
```
###Assistant :
select mpa.default_account, mpa.parent, mp.type ... |
663 | def _on_move(self, event):
if not self.button_pressed:
return
if self.get_navigate_mode() is not None:
# we don't want to rotate if we are zooming/panning
# from the toolbar
return
if self.M is None:
return
x, y = e... |
Mouse moving.
By default, button-1 rotates, button-2 pans, and button-3 zooms;
these buttons can be modified via `mouse_init`.
| 18 | 203 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _on_move(self, event):
if not self.button_pressed:
return
if self.get_navigate_mode() is not None:
# we don't want to rotate if we are ... |
664 | def install(name=None, refresh=False, pkgs=None, version=None, test=False, **kwargs):
targets = salt.utils.args.split_input(pkgs) if pkgs else [name]
if not targets:
return {}
if pkgs:
log.debug("Removing these fileset(s)/rpm package(s) %s: %s", name, targets)
# Get a list of the ... |
Install the named fileset(s)/rpm package(s).
.. versionadded:: 3005
preference to install rpm packages are to use in the following order:
/opt/freeware/bin/dnf
/opt/freeware/bin/yum
/usr/bin/yum
/usr/bin/rpm
Note: use of rpm to install implies ... | 172 | 248 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def install(name=None, refresh=False, pkgs=None, version=None, test=False, **kwargs):
targets = salt.utils.args.split_input(pkgs) if pkgs else [name]
if not targets:
ret... |
665 | def is_false(self, ds_key_long):
value = self.get_value(ds_key_long)
return False if value is None else not bool(value)
|
Returns `True`/``False` only if the value is set, always `False` otherwise. So use this method to ask the very
specific question of whether the value is set to `False` (and it's not set to `True`` or isn't set).
| 38 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def is_false(self, ds_key_long):
value = self.get_value(ds_key_long)
return False if value is None else not bool(value)
```
###Assistant :
Retu... |
666 | def extract_pytorch_structures():
for opt in lmo.optimizer_registry:
# Get the torch class:
optimizer_class = lmo.optimizer_registry[opt][0]
# Parse and clean the class structure:
path = get_fully_qualified_class_name(optimizer_class)
opt_struct = get_pytkdocs_structure... | Extracts and saves the parsed structure of all pytorch classes referenced in
`ludwig.modules.optimization_modules.optimizer_registry` as JSON files under
`ludwig/validation/generated/torch/`. | 18 | 62 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def extract_pytorch_structures():
for opt in lmo.optimizer_registry:
# Get the torch class:
optimizer_class = lmo.optimizer_registry[opt][0]
# Parse and cle... |
667 | def test_hf_classification_bin(self, mock_handler):
# create predictor
create_sql =
model_name = 'spam_classifier'
predict_sql =
self.hf_test_run(mock_handler, model_name, create_sql, predict_sql)
|
CREATE PREDICTOR huggingface.spam_classifier
predict PRED
USING
task='text-classification',
model_name= "mrm8488/bert-tiny-finetuned-sms-spam-detection",
input_column = 'text_spammy',
labels=['ham','spam']
... | 23 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_hf_classification_bin(self, mock_handler):
# create predictor
create_sql =
model_name = 'spam_classifier'
predict_sql =
self.hf_test_ru... |
668 | def match_submerged_margins(layoutgrids, fig):
for sfig in fig.subfigs:
match_submerged_margins(layoutgrids, sfig)
axs = [a for a in fig.get_axes()
if a.get_subplotspec() is not None and a.get_in_layout()]
for ax1 in axs:
ss1 = ax1.get_subplotspec()
if ss1.get_grid... |
Make the margins that are submerged inside an Axes the same size.
This allows axes that span two columns (or rows) that are offset
from one another to have the same size.
This gives the proper layout for something like::
fig = plt.figure(constrained_layout=True)
axs = fig.subplot_mosa... | 158 | 190 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def match_submerged_margins(layoutgrids, fig):
for sfig in fig.subfigs:
match_submerged_margins(layoutgrids, sfig)
axs = [a for a in fig.get_axes()
if a.get... |
669 | def parse_version_info(version_str):
version_info = []
for x in version_str.split('.'):
if x.isdigit():
version_info.append(int(x))
elif x.find('rc') != -1:
patch_version = x.split('rc')
version_info.append(int(patch_version[0]))
version_info.... | Parse a version string into a tuple.
Args:
version_str (str): The version string.
Returns:
tuple[int | str]: The version info, e.g., "1.3.0" is parsed into
(1, 3, 0), and "2.0.0rc1" is parsed into (2, 0, 0, 'rc1').
| 37 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def parse_version_info(version_str):
version_info = []
for x in version_str.split('.'):
if x.isdigit():
version_info.append(int(x))
elif x.find('rc')... |
670 | def adjust_settings_for_relay_tests(settings):
settings.ALLOWED_HOSTS = [
"localhost",
"testserver",
"host.docker.internal",
"0.0.0.0",
"127.0.0.1",
]
settings.KAFKA_CLUSTERS = {
"default": {
"common": {"bootstrap.servers": "127.0.0.1:9092"},
... |
Adjusts the application settings to accept calls from a Relay instance running inside a
docker container.
:param settings: the app settings
| 21 | 40 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def adjust_settings_for_relay_tests(settings):
settings.ALLOWED_HOSTS = [
"localhost",
"testserver",
"host.docker.internal",
"0.0.0.0",
"127.... |
671 | def clear_backends():
if xc._version < 79:
raise RuntimeError("clear_backends is not supported in the jaxlib used."
"Please update your jaxlib package.")
xb._clear_backends()
jax.lib.xla_bridge._backends = {}
dispatch.xla_callable.cache_clear() # type: ignore
dispatch.xla_prim... |
Clear all backend clients so that new backend clients can be created later.
| 13 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def clear_backends():
if xc._version < 79:
raise RuntimeError("clear_backends is not supported in the jaxlib used."
"Please update your jaxlib package.")
... |
672 | def get_power_utilization(self):
powerfeeds = PowerFeed.objects.filter(rack=self)
available_power_total = sum(pf.available_power for pf in powerfeeds)
print(f'available_power_total: {available_power_total}')
if not available_power_total:
return 0
powerports ... |
Determine the utilization rate of power in the rack and return it as a percentage.
| 15 | 54 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_power_utilization(self):
powerfeeds = PowerFeed.objects.filter(rack=self)
available_power_total = sum(pf.available_power for pf in powerfeeds)
print(... |
673 | def cleanup(self):
orphaned = []
for w in self.workers[::]:
if not w.alive:
# the worker process has exited
# 1. take the task it was running and enqueue the error
# callbacks
# 2. take any pending tasks delivered to... |
Perform some internal account and cleanup. This is run on
every cluster node heartbeat:
1. Discover worker processes that exited, and recover messages they
were handling.
2. Clean up unnecessary, idle workers.
IMPORTANT: this function is one of the few places in... | 69 | 270 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def cleanup(self):
orphaned = []
for w in self.workers[::]:
if not w.alive:
# the worker process has exited
# 1. take the... |
674 | def test_token_node_empty_csrf_cookie(self):
req = self._get_request(cookie="")
mw = CsrfViewMiddleware(token_view)
mw.process_view(req, token_view, (), {})
resp = token_view(req)
token = get_token(req)
self.assertIsNotNone(token)
csrf_secret = _unmask_c... |
A new token is sent if the csrf_cookie is the empty string.
| 12 | 24 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_token_node_empty_csrf_cookie(self):
req = self._get_request(cookie="")
mw = CsrfViewMiddleware(token_view)
mw.process_view(req, token_view, (), {})
... |
675 | def save(self, envs):
assert isinstance(envs, list), "envs should be a list"
if len(envs) > 0:
for env in envs:
assert isstr(env), "env should be a string"
return self._send(
{
"data": envs,
},
"save",
... |
This function allows the user to save envs that are alive on the
Tornado server. The envs can be specified as a list of env ids.
| 26 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def save(self, envs):
assert isinstance(envs, list), "envs should be a list"
if len(envs) > 0:
for env in envs:
assert isstr(env), "env s... |
676 | def test_has_related_field_in_list_display_o2o(self):
media = Media.objects.create(name="Foo")
Vodcast.objects.create(media=media)
response = self.client.get(reverse("admin:admin_views_vodcast_changelist"), {})
response.context["cl"].list_display = ["media"]
self.assert... | Joins shouldn't be performed for <O2O>_id fields in list display. | 10 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_has_related_field_in_list_display_o2o(self):
media = Media.objects.create(name="Foo")
Vodcast.objects.create(media=media)
response = self.client.get... |
677 | def binary_crossentropy(target, output, from_logits=False):
target = tf.convert_to_tensor(target)
output = tf.convert_to_tensor(output)
# Use logits whenever they are available. `softmax` and `sigmoid`
# activations cache logits on the `output` Tensor.
if hasattr(output, "_keras_logits"):
... | Binary crossentropy between an output tensor and a target tensor.
Args:
target: A tensor with the same shape as `output`.
output: A tensor.
from_logits: Whether `output` is expected to be a logits tensor.
By default, we consider that `output`
encodes a probability di... | 46 | 176 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def binary_crossentropy(target, output, from_logits=False):
target = tf.convert_to_tensor(target)
output = tf.convert_to_tensor(output)
# Use logits whenever they are avail... |
678 | def test_process_pulled_event_with_missing_state(self) -> None:
return self._test_process_pulled_event_with_missing_state(False)
| Ensure that we correctly handle pulled events with lots of missing state
In this test, we pretend we are processing a "pulled" event (eg, via backfill
or get_missing_events). The pulled event has a prev_event we haven't previously
seen, so the server requests the state at that prev_event. There... | 83 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_process_pulled_event_with_missing_state(self) -> None:
return self._test_process_pulled_event_with_missing_state(False)
```
###Assistant : Ensure that ... |
679 | def test_resolved_in_release(self, mock_func):
notification = ResolvedInReleaseActivityNotification(
Activity(
project=self.project,
group=self.group,
user=self.user,
type=ActivityType.SET_RESOLVED_IN_RELEASE,
d... |
Test that a Slack message is sent with the expected payload when an issue is resolved in a release
| 19 | 45 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_resolved_in_release(self, mock_func):
notification = ResolvedInReleaseActivityNotification(
Activity(
project=self.project,
... |
680 | def get_vocabulary(self, include_special_tokens=True):
# The lookup table data will not be sorted, so we will create a inverted
# lookup here, and use that to lookup a range of indices [0,
# vocab_size).
if self.lookup_table.size() == 0:
vocab, indices = [], []
... | Returns the current vocabulary of the layer.
Args:
include_special_tokens: If True, the returned vocabulary will include
mask and OOV tokens, and a term's index in the vocabulary will equal
the term's index when calling the layer. If False, the returned
vocabulary ... | 49 | 100 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_vocabulary(self, include_special_tokens=True):
# The lookup table data will not be sorted, so we will create a inverted
# lookup here, and use that to lookup... |
681 | def test_error_raised_with_float_limited_eval_batches():
model = BoringModel()
dl_size = len(model.val_dataloader())
limit_val_batches = 1 / (dl_size + 2)
trainer = Trainer(limit_val_batches=limit_val_batches)
trainer._data_connector.attach_data(model)
with pytest.raises(
Misconfigu... | Test that an error is raised if there are not enough batches when passed with float value of
limit_eval_batches. | 19 | 63 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_error_raised_with_float_limited_eval_batches():
model = BoringModel()
dl_size = len(model.val_dataloader())
limit_val_batches = 1 / (dl_size + 2)
trainer = Trai... |
682 | def not_none_device_or_backend_on_jit(backend, device, num_ins):
# TODO(yashkatariya): Remove this entire function when backend and device are
# removed as arguments on jit.
from jax.experimental import sharding
if device is not None and backend is not None:
raise ValueError("can't specify both a devic... | This is to support the backend and device argument on jit. It's a feature
that's deprecated but needs to be supported for feature parity and so that we
can delete the non-Array paths when Array is switched on.
| 38 | 130 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def not_none_device_or_backend_on_jit(backend, device, num_ins):
# TODO(yashkatariya): Remove this entire function when backend and device are
# removed as arguments on jit.
from j... |
683 | def is_mouse_scrolling(self, *args):
return 'button' in self.profile and 'scroll' in self.button
| Returns True if the touch event is a mousewheel scrolling
.. versionadded:: 1.6.0
| 13 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def is_mouse_scrolling(self, *args):
return 'button' in self.profile and 'scroll' in self.button
```
###Assistant : Returns True if the touch event is a mousewh... |
684 | def easy_print(*args, size=(None, None), end=None, sep=None, location=(None, None), relative_location=(None, None), font=None, no_titlebar=False,
no_button=False, grab_anywhere=False, keep_on_top=None, do_not_reroute_stdout=True, echo_stdout=False, text_color=None, background_color=None, colors=None, c=N... |
Works like a "print" statement but with windowing options. Routes output to the "Debug Window"
In addition to the normal text and background colors, you can use a "colors" tuple/string
The "colors" or "c" parameter defines both the text and background in a single parm.
It can be a tuple or a single s... | 444 | 60 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def easy_print(*args, size=(None, None), end=None, sep=None, location=(None, None), relative_location=(None, None), font=None, no_titlebar=False,
no_button=False, grab_anywher... |
685 | def wait_start_success(self):
_timeout = self.args.timeout_ready
if _timeout <= 0:
_timeout = None
else:
_timeout /= 1e3
if self._wait_for_ready_or_shutdown(_timeout):
self._check_failed_to_start()
self.logger.debug(__ready_msg__)
... | Block until all pods starts successfully.
If not success, it will raise an error hoping the outer function to catch it
| 21 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def wait_start_success(self):
_timeout = self.args.timeout_ready
if _timeout <= 0:
_timeout = None
else:
_timeout /= 1e3
if s... |
686 | def _rank_decomposition(M, iszerofunc=_iszero, simplify=False):
r
F, pivot_cols = M.rref(simplify=simplify, iszerofunc=iszerofunc,
pivots=True)
rank = len(pivot_cols)
C = M.extract(range(M.rows), pivot_cols)
F = F[:rank, :]
return C, F
| Returns a pair of matrices (`C`, `F`) with matching rank
such that `A = C F`.
Parameters
==========
iszerofunc : Function, optional
A function used for detecting whether an element can
act as a pivot. ``lambda x: x.is_zero`` is used by default.
simplify : Bool or Function, option... | 291 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _rank_decomposition(M, iszerofunc=_iszero, simplify=False):
r
F, pivot_cols = M.rref(simplify=simplify, iszerofunc=iszerofunc,
pivots=True)
rank = len(pivot_cols... |
687 | def normalize(X, norm="l2", *, axis=1, copy=True, return_norm=False):
if norm not in ("l1", "l2", "max"):
raise ValueError("'%s' is not a supported norm" % norm)
if axis == 0:
sparse_format = "csc"
elif axis == 1:
sparse_format = "csr"
else:
raise ValueError("'%d' i... | Scale input vectors individually to unit norm (vector length).
Read more in the :ref:`User Guide <preprocessing_normalization>`.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data to normalize, element by element.
scipy.sparse matrices shoul... | 220 | 172 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def normalize(X, norm="l2", *, axis=1, copy=True, return_norm=False):
if norm not in ("l1", "l2", "max"):
raise ValueError("'%s' is not a supported norm" % norm)
if axi... |
688 | def find_version_to_install(self, name):
version = Version.parse(name)
if version.patch is not None:
return name
try:
best_match = max(
(
inst_version
for inst_version in self.iter_installable_versions()
... | Find a version in the installer from the version supplied.
A ValueError is raised if a matching version cannot be found.
| 21 | 41 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def find_version_to_install(self, name):
version = Version.parse(name)
if version.patch is not None:
return name
try:
best_match = ma... |
689 | def copy_safe_request(request):
meta = {
k: request.META[k]
for k in HTTP_REQUEST_META_SAFE_COPY
if k in request.META and isinstance(request.META[k], str)
}
return NetBoxFakeRequest({
'META': meta,
'COOKIES': request.COOKIES,
'POST': request.POST,
... |
Copy selected attributes from a request object into a new fake request object. This is needed in places where
thread safe pickling of the useful request data is needed.
| 29 | 45 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def copy_safe_request(request):
meta = {
k: request.META[k]
for k in HTTP_REQUEST_META_SAFE_COPY
if k in request.META and isinstance(request.META[k], str)
... |
690 | def batchify(self, obs_batch, sort=False):
batch = super().batchify(obs_batch, sort=sort)
if batch.valid_indices is None:
return batch
batch.classifier_label = torch.tensor(
[
[obs_batch[i].get('classifier_label_idx', -1)]
for i ... |
This method calls the parent class's batchify method and then add
classifier_label and is_ltr property to the the batch.
| 19 | 38 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def batchify(self, obs_batch, sort=False):
batch = super().batchify(obs_batch, sort=sort)
if batch.valid_indices is None:
return batch
batch.cl... |
691 | def calculate_post_conv_height(height, kernel_size, stride, pad, n_convs):
for _ in range(n_convs):
height = (height - kernel_size + 2 * pad) // stride + 1
return height
| Height of spec after n convolutions with fixed kernel/stride/pad. | 9 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def calculate_post_conv_height(height, kernel_size, stride, pad, n_convs):
for _ in range(n_convs):
height = (height - kernel_size + 2 * pad) // stride + 1
... |
692 | async def test_hls_playlist_view(hass, setup_component, hls_stream, stream_worker_sync):
stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings())
stream_worker_sync.pause()
hls = stream.add_provider(HLS_PROVIDER)
for i in range(2):
segment = Segment(sequence=i, duration=SE... | Test rendering the hls playlist with 1 and 2 output segments. | 11 | 76 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_hls_playlist_view(hass, setup_component, hls_stream, stream_worker_sync):
stream = create_stream(hass, STREAM_SOURCE, {}, dynamic_stream_settings())
stream_worker... |
693 | def _create_local_rank_map(self) -> Dict:
rank_mapping = {}
ip_dict = defaultdict(int)
for world_rank in range(len(self.worker_group)):
worker = self.worker_group.workers[world_rank]
node_ip = worker.metadata.node_ip
rank_mapping[world_rank] = ip_dict... | Create mapping from worker world_rank to local_rank.
Example:
Worker 0: 0.0.0.0
Worker 1: 0.0.0.0
Worker 2: 0.0.0.1
Worker 3: 0.0.0.0
Worker 4: 0.0.0.1
Workers 0, 1, 3 are on 0.0.0.0.
Workers 2, 4 are on 0.0.0.1.
... | 55 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _create_local_rank_map(self) -> Dict:
rank_mapping = {}
ip_dict = defaultdict(int)
for world_rank in range(len(self.worker_group)):
worker = ... |
694 | def _output_groups(self) -> None:
is_rename = self._args.sort_method != "none"
logger.info("Creating %s group folders in '%s'.",
len(self._sorter.binned), self._args.output_dir)
bin_names = [f"_{b}" for b in self._sorter.bin_names]
if is_rename:
... | Move the files to folders.
Obtains the bins and original filenames from :attr:`_sorter` and outputs into appropriate
bins in the output location
| 22 | 124 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _output_groups(self) -> None:
is_rename = self._args.sort_method != "none"
logger.info("Creating %s group folders in '%s'.",
len(self._sorte... |
695 | def _setSharedLibraryRPATHElf(filename, rpath):
# TODO: Might write something that makes a shell script replacement
# in case no rpath is present, or use patchelf, for now our use
# case seems to use rpaths for executables.
# patchelf --set-rpath "$ORIGIN/path/to/library" <executable>
with withEnvi... | \
Error, needs 'patchelf' on your system, due to 'RPATH' settings that need to be
set. | 16 | 53 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _setSharedLibraryRPATHElf(filename, rpath):
# TODO: Might write something that makes a shell script replacement
# in case no rpath is present, or use patchelf, for now our use
... |
696 | def _get_columns(self):
if self._columns_cache is None:
self._columns_cache, column_widths = self._compute_axis_labels_and_lengths(
1
)
if self._column_widths_cache is None:
self._column_widths_cache = column_widths
return self... |
Get the columns from the cache object.
Returns
-------
pandas.Index
An index object containing the column labels.
| 17 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_columns(self):
if self._columns_cache is None:
self._columns_cache, column_widths = self._compute_axis_labels_and_lengths(
1
... |
697 | async def async_update(self) -> None:
# Update values from controller's device dictionary
self._connected = self._controller.is_connected
self._current_temp = self._controller.get_temperature(self._device_id)
self._fan_speed = self._controller.get_fan_speed(self._device_id)
... | Copy values from controller dictionary to climate device. | 8 | 90 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def async_update(self) -> None:
# Update values from controller's device dictionary
self._connected = self._controller.is_connected
self._current_temp ... |
698 | def test_kb_valid_entities(nlp):
mykb = InMemoryLookupKB(nlp.vocab, entity_vector_length=3)
# adding entities
mykb.add_entity(entity="Q1", freq=19, entity_vector=[8, 4, 3])
mykb.add_entity(entity="Q2", freq=5, entity_vector=[2, 1, 0])
mykb.add_entity(entity="Q3", freq=25, entity_vector=[-1, -6... | Test the valid construction of a KB with 3 entities and two aliases | 13 | 94 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_kb_valid_entities(nlp):
mykb = InMemoryLookupKB(nlp.vocab, entity_vector_length=3)
# adding entities
mykb.add_entity(entity="Q1", freq=19, entity_vector=[8, 4, 3])... |
699 | def eye(N, M=None, k=0, dtype=float, order='C', *, like=None):
if like is not None:
return _eye_with_like(N, M=M, k=k, dtype=dtype, order=order, like=like)
if M is None:
M = N
m = zeros((N, M), dtype=dtype, order=order)
if k >= M:
return m
# Ensure M and k are integers, ... |
Return a 2-D array with ones on the diagonal and zeros elsewhere.
Parameters
----------
N : int
Number of rows in the output.
M : int, optional
Number of columns in the output. If None, defaults to `N`.
k : int, optional
Index of the diagonal: 0 (the default) refers to the ma... | 176 | 104 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def eye(N, M=None, k=0, dtype=float, order='C', *, like=None):
if like is not None:
return _eye_with_like(N, M=M, k=k, dtype=dtype, order=order, like=like)
if M is None:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.