Unnamed: 0 int64 0 2.93k | code stringlengths 101 62.2k | docs stringlengths 51 10.7k | doc_len int64 4 1.74k | words int64 4 4.82k | lang stringclasses 1
value | prompt stringlengths 320 71.2k |
|---|---|---|---|---|---|---|
2,300 | def probiou_loss(pred, target, eps=1e-3, mode='l1'):
gbboxes1 = gbb_form(pred)
gbboxes2 = gbb_form(target)
x1, y1, a1_, b1_, c1_ = gbboxes1[:,
0], gbboxes1[:,
1], gbboxes1[:,
... |
pred -> a matrix [N,5](x,y,w,h,angle - in radians) containing ours predicted box ;in case of HBB angle == 0
target -> a matrix [N,5](x,y,w,h,angle - in radians) containing ours target box ;in case of HBB angle == 0
eps -> threshold to avoid infinite values
mode -> ('l1' in... | 58 | 181 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def probiou_loss(pred, target, eps=1e-3, mode='l1'):
gbboxes1 = gbb_form(pred)
gbboxes2 = gbb_form(target)
x1, y1, a1_, b1_, c1_ = gbboxes1[:,
... |
2,301 | def mayDisableConsoleWindow():
# TODO: What about MSYS2?
return isWin32Windows() or isMacOS()
| :returns: bool derived from platform support of disabling the console, | 10 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def mayDisableConsoleWindow():
# TODO: What about MSYS2?
return isWin32Windows() or isMacOS()
```
###Assistant : :returns: bool derived from platform support of d... |
2,302 | def compat_cfg(cfg):
cfg = copy.deepcopy(cfg)
cfg = compat_imgs_per_gpu(cfg)
cfg = compat_loader_args(cfg)
cfg = compat_runner_args(cfg)
return cfg
| This function would modify some filed to keep the compatibility of
config.
For example, it will move some args which will be deprecated to the correct
fields.
| 27 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def compat_cfg(cfg):
cfg = copy.deepcopy(cfg)
cfg = compat_imgs_per_gpu(cfg)
cfg = compat_loader_args(cfg)
cfg = compat_runner_args(cfg)
return cfg
```
... |
2,303 | def getsourcelines(object):
object = unwrap(object)
lines, lnum = findsource(object)
if istraceback(object):
object = object.tb_frame
# for module or frame that corresponds to module, return all source lines
if (ismodule(object) or
(isframe(object) and object.f_code.co_name ==... | Return a list of source lines and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of the lines
corresponding to the object and the line number indicates where in the
original source file ... | 71 | 44 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def getsourcelines(object):
object = unwrap(object)
lines, lnum = findsource(object)
if istraceback(object):
object = object.tb_frame
# for module or frame tha... |
2,304 | def get_del_batches(self, objs, fields):
field_names = [field.name for field in fields]
conn_batch_size = max(
connections[self.using].ops.bulk_batch_size(field_names, objs), 1
)
if len(objs) > conn_batch_size:
return [
objs[i : i + conn_b... |
Return the objs in suitably sized batches for the used connection.
| 11 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_del_batches(self, objs, fields):
field_names = [field.name for field in fields]
conn_batch_size = max(
connections[self.using].ops.bulk_batch_siz... |
2,305 | def save(self, global_step):
save_path = osp.join(self.directory, f"{global_step:09d}.ckpt")
self.checkpoint.save(save_path)
self.latest_checkpoint = save_path
self.queue.put(True)
| Create a new checkpoint.
Args:
global_step (int): The iteration number which will be used
to name the checkpoint.
| 18 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def save(self, global_step):
save_path = osp.join(self.directory, f"{global_step:09d}.ckpt")
self.checkpoint.save(save_path)
self.latest_checkpoint = save_pa... |
2,306 | def versions_from_file(filename):
try:
with open(filename) as f:
contents = f.read()
except OSError:
raise NotThisMethod("unable to read _version.py")
mo = re.search(r"version_json = # END VERSION_JSON",
contents, re.M | re.S)
if not mo:
mo =... | Try to determine the version from _version.py if present.\n(.*)\r\n(.*) | 9 | 52 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def versions_from_file(filename):
try:
with open(filename) as f:
contents = f.read()
except OSError:
raise NotThisMethod("unable to read _version.py"... |
2,307 | def get_total_allocated_amount(payment_entry):
return frappe.db.sql(
,
(payment_entry.payment_document, payment_entry.payment_entry),
as_dict=True,
)
|
SELECT
SUM(btp.allocated_amount) as allocated_amount,
bt.name
FROM
`tabBank Transaction Payments` as btp
LEFT JOIN
`tabBank Transaction` bt ON bt.name=btp.parent
WHERE
btp.payment_document = %s
AND
btp.payment_entry = %s
AND
bt.docstatus = 1 | 30 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_total_allocated_amount(payment_entry):
return frappe.db.sql(
,
(payment_entry.payment_document, payment_entry.payment_entry),
as_dict=True,
)
```
###Assistant :... |
2,308 | def min_weight_matching(G, maxcardinality=False, weight="weight"):
if len(G.edges) == 0:
return max_weight_matching(G, maxcardinality, weight)
G_edges = G.edges(data=weight, default=1)
min_weight = min(w for _, _, w in G_edges)
InvG = nx.Graph()
edges = ((u, v, 1 / (1 + w - min_weight))... | Computing a minimum-weight maximal matching of G.
Use reciprocal edge weights with the maximum-weight algorithm.
A matching is a subset of edges in which no node occurs more than once.
The weight of a matching is the sum of the weights of its edges.
A maximal matching cannot add more edges and still b... | 146 | 53 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def min_weight_matching(G, maxcardinality=False, weight="weight"):
if len(G.edges) == 0:
return max_weight_matching(G, maxcardinality, weight)
G_edges = G.edges(data=wei... |
2,309 | def site_config_dir(self) -> str:
return self._append_app_name_and_version("/Library/Preferences")
| :return: config directory shared by the users, e.g. ``/Library/Preferences/$appname`` | 9 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def site_config_dir(self) -> str:
return self._append_app_name_and_version("/Library/Preferences")
```
###Assistant : :return: config directory shared by the us... |
2,310 | def _cmp_op(self, other, op_name):
lhs_dtype_class = self._get_dtype_cmp_class(self._dtype)
rhs_dtype_class = self._get_dtype_cmp_class(other._dtype)
res_dtype = get_dtype(bool)
# In HDK comparison with NULL always results in NULL,
# but in pandas it is True for 'ne' com... |
Build a comparison expression.
Parameters
----------
other : BaseExpr
A value to compare with.
op_name : str
The comparison operation name.
Returns
-------
BaseExpr
The resulting comparison expression.
| 28 | 99 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _cmp_op(self, other, op_name):
lhs_dtype_class = self._get_dtype_cmp_class(self._dtype)
rhs_dtype_class = self._get_dtype_cmp_class(other._dtype)
res_dty... |
2,311 | def set_active(self, index):
if index not in range(len(self.labels)):
raise ValueError(f'Invalid CheckButton index: {index}')
if colors.same_color(
self._crosses.get_facecolor()[index], colors.to_rgba("none")
):
self._crosses.get_facecolor()[inde... |
Toggle (activate or deactivate) a check button by index.
Callbacks will be triggered if :attr:`eventson` is True.
Parameters
----------
index : int
Index of the check button to toggle.
Raises
------
ValueError
If *index* is inva... | 36 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_active(self, index):
if index not in range(len(self.labels)):
raise ValueError(f'Invalid CheckButton index: {index}')
if colors.same_color(
... |
2,312 | async def async_update(self) -> None:
await self.ebox_data.async_update()
if self.entity_description.key in self.ebox_data.data:
self._attr_native_value = round(
self.ebox_data.data[self.entity_description.key], 2
)
| Get the latest data from EBox and update the state. | 10 | 17 | 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:
await self.ebox_data.async_update()
if self.entity_description.key in self.ebox_data.data:
self._attr_native_value ... |
2,313 | def panoptic_evaluate(self, dataset, results, topk=20):
# image to annotations
gt_json = dataset.coco.img_ann_map
result_files, tmp_dir = dataset.format_results(results)
pred_json = mmcv.load(result_files['panoptic'])['annotations']
pred_folder = osp.join(tmp_dir.name, ... | Evaluation for panoptic segmentation.
Args:
dataset (Dataset): A PyTorch dataset.
results (list): Panoptic segmentation results from test
results pkl file.
topk (int): Number of the highest topk and
lowest topk after evaluation index sorting. ... | 78 | 102 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def panoptic_evaluate(self, dataset, results, topk=20):
# image to annotations
gt_json = dataset.coco.img_ann_map
result_files, tmp_dir = dataset.format_res... |
2,314 | def _compute_mi_cd(c, d, n_neighbors):
n_samples = c.shape[0]
c = c.reshape((-1, 1))
radius = np.empty(n_samples)
label_counts = np.empty(n_samples)
k_all = np.empty(n_samples)
nn = NearestNeighbors()
for label in np.unique(d):
mask = d == label
count = np.sum(mask)
... | Compute mutual information between continuous and discrete variables.
Parameters
----------
c : ndarray, shape (n_samples,)
Samples of a continuous random variable.
d : ndarray, shape (n_samples,)
Samples of a discrete random variable.
n_neighbors : int
Number of nearest n... | 126 | 113 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _compute_mi_cd(c, d, n_neighbors):
n_samples = c.shape[0]
c = c.reshape((-1, 1))
radius = np.empty(n_samples)
label_counts = np.empty(n_samples)
k_all = np.empt... |
2,315 | def handle_app_config(self, app_config, **options):
raise NotImplementedError(
"Subclasses of AppCommand must provide a handle_app_config() method."
)
|
Perform the command's actions for app_config, an AppConfig instance
corresponding to an application label given on the command line.
| 19 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def handle_app_config(self, app_config, **options):
raise NotImplementedError(
"Subclasses of AppCommand must provide a handle_app_config() method."
)
... |
2,316 | def test_inferred_max_features_integer(max_features):
clf = RandomForestClassifier(n_estimators=5, random_state=0)
transformer = SelectFromModel(
estimator=clf, max_features=max_features, threshold=-np.inf
)
X_trans = transformer.fit_transform(data, y)
assert transformer.max_features_ =... | Check max_features_ and output shape for integer max_features. | 8 | 38 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_inferred_max_features_integer(max_features):
clf = RandomForestClassifier(n_estimators=5, random_state=0)
transformer = SelectFromModel(
estimator=clf, max_feat... |
2,317 | def test_naive_all_pairs_lowest_common_ancestor3(self):
all_pairs = product(self.DG.nodes(), self.DG.nodes())
ans = naive_all_pairs_lca(self.DG, pairs=all_pairs)
self.assert_lca_dicts_same(dict(ans), self.gold)
| Produces the correct results when all pairs given as a generator. | 11 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_naive_all_pairs_lowest_common_ancestor3(self):
all_pairs = product(self.DG.nodes(), self.DG.nodes())
ans = naive_all_pairs_lca(self.DG, pairs=all_pairs)
... |
2,318 | def _resolve_dependency(dependency):
if dependency[0] != "__setting__":
return dependency, False
resolved_app_label, resolved_object_name = getattr(
settings, dependency[1]
).split(".")
return (resolved_app_label, resolved_object_name.lower()) + dependenc... |
Return the resolved dependency and a boolean denoting whether or not
it was swappable.
| 14 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _resolve_dependency(dependency):
if dependency[0] != "__setting__":
return dependency, False
resolved_app_label, resolved_object_name = getattr(
... |
2,319 | def lowest_common_ancestor(G, node1, node2, default=None):
ans = list(all_pairs_lowest_common_ancestor(G, pairs=[(node1, node2)]))
if ans:
assert len(ans) == 1
return ans[0][1]
else:
return default
@not_implemented_for("undirected")
@not_implemented_for("multigraph") | Compute the lowest common ancestor of the given pair of nodes.
Parameters
----------
G : NetworkX directed graph
node1, node2 : nodes in the graph.
default : object
Returned if no common ancestor between `node1` and `node2`
Returns
-------
The lowest common ancestor of node1 ... | 155 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def lowest_common_ancestor(G, node1, node2, default=None):
ans = list(all_pairs_lowest_common_ancestor(G, pairs=[(node1, node2)]))
if ans:
assert len(ans) == 1
r... |
2,320 | def get_data(filters=None):
data = []
conditions = get_filter_conditions(filters)
fee_details = frappe.db.sql(
% (conditions),
as_dict=1,
)
for entry in fee_details:
data.append(
{
"program": entry.program,
"fees_collected": entry.paid_amount,
"outstanding_amount": entry.outstanding_amou... |
SELECT
FeesCollected.program,
FeesCollected.paid_amount,
FeesCollected.outstanding_amount,
FeesCollected.grand_total
FROM (
SELECT
sum(grand_total) - sum(outstanding_amount) AS paid_amount, program,
sum(outstanding_amount) AS outstanding_amount,
sum(grand_total) AS grand_total
... | 42 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_data(filters=None):
data = []
conditions = get_filter_conditions(filters)
fee_details = frappe.db.sql(
% (conditions),
as_dict=1,
)
for entry in fee_details:
data.ap... |
2,321 | def get_dependencies_from_json(ireq):
if ireq.editable or not is_pinned_requirement(ireq):
return
# It is technically possible to parse extras out of the JSON API's
# requirement format, but it is such a chore let's just use the simple API.
if ireq.extras:
return
session = re... | Retrieves dependencies for the given install requirement from the json
api.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pipenv.patched.pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallRequirements.
:rtype: set(str) or N... | 33 | 46 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_dependencies_from_json(ireq):
if ireq.editable or not is_pinned_requirement(ireq):
return
# It is technically possible to parse extras out of the JSON API's
... |
2,322 | def assign(self, **kwargs) -> DataFrame:
r
data = self.copy(deep=None)
for k, v in kwargs.items():
data[k] = com.apply_if_callable(v, data)
return data
|
Assign new columns to a DataFrame.
Returns a new object with all original columns in addition to new ones.
Existing columns that are re-assigned will be overwritten.
Parameters
----------
**kwargs : dict of {str: callable or Series}
The column names are key... | 268 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def assign(self, **kwargs) -> DataFrame:
r
data = self.copy(deep=None)
for k, v in kwargs.items():
data[k] = com.apply_if_callable(v, data)
retur... |
2,323 | def resize_feats(self, feats):
out = []
for i in range(len(feats)):
if i == 0:
out.append(
F.interpolate(
feats[0],
size=feats[i + 1].shape[-2:],
mode='bilinear',
... | Downsample the first feat and upsample last feat in feats. | 10 | 40 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def resize_feats(self, feats):
out = []
for i in range(len(feats)):
if i == 0:
out.append(
F.interpolate(
... |
2,324 | def get_bin_list(filters):
conditions = []
if filters.item_code:
conditions.append("item_code = '%s' " % filters.item_code)
if filters.warehouse:
warehouse_details = frappe.db.get_value(
"Warehouse", filters.warehouse, ["lft", "rgt"], as_dict=1
)
if warehouse_details:
conditions.append(
" exists... | select item_code, warehouse, actual_qty, planned_qty, indented_qty,
ordered_qty, reserved_qty, reserved_qty_for_production, reserved_qty_for_sub_contract, projected_qty
from tabBin bin {conditions} order by item_code, warehouse
| 19 | 71 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_bin_list(filters):
conditions = []
if filters.item_code:
conditions.append("item_code = '%s' " % filters.item_code)
if filters.warehouse:
warehouse_details = frappe.db.get_v... |
2,325 | def run_eagerly(self):
if (
self.dynamic and self._run_eagerly is False
): # pylint:disable=g-bool-id-comparison
# TODO(fchollet): consider using py_func to enable this.
raise ValueError(
"Your model contains layers that can only be "
... | Settable attribute indicating whether the model should run eagerly.
Running eagerly means that your model will be run step by step,
like Python code. Your model might run slower, but it should become easier
for you to debug it by stepping into individual layer calls.
By default, we wil... | 72 | 113 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def run_eagerly(self):
if (
self.dynamic and self._run_eagerly is False
): # pylint:disable=g-bool-id-comparison
# TODO(fchollet): consider ... |
2,326 | def get_preview_context(self, request, *args, **kwargs):
return {"object": self, "request": request}
|
Returns a context dictionary for use in templates for previewing this object.
| 12 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_preview_context(self, request, *args, **kwargs):
return {"object": self, "request": request}
```
###Assistant :
Returns a context dictionary fo... |
2,327 | async def test_default_disabling_entity(hass, create_registrations, webhook_client):
webhook_id = create_registrations[1]["webhook_id"]
webhook_url = f"/api/webhook/{webhook_id}"
reg_resp = await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
... | Test that sensors can be disabled by default upon registration. | 10 | 61 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_default_disabling_entity(hass, create_registrations, webhook_client):
webhook_id = create_registrations[1]["webhook_id"]
webhook_url = f"/api/webhook/{webhook_id}... |
2,328 | def _create_dd_meta(cls, dataset_info):
# Collect necessary information from dataset_info
schema = dataset_info["schema"]
index = dataset_info["index"]
categories = dataset_info["categories"]
partition_obj = dataset_info["partitions"]
partitions = dataset_info["... | Use parquet schema and hive-partition information
(stored in dataset_info) to construct DataFrame metadata.
This method is used by both arrow engines.
| 21 | 379 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _create_dd_meta(cls, dataset_info):
# Collect necessary information from dataset_info
schema = dataset_info["schema"]
index = dataset_info["index"]
... |
2,329 | def convert_type(self, value, schema_type, stringify_dict=True):
if isinstance(value, datetime.datetime):
iso_format_value = value.isoformat()
if value.tzinfo is None:
return iso_format_value
return pendulum.parse(iso_format_value).float_timestamp
... |
Takes a value from Postgres, and converts it to a value that's safe for
JSON/Google Cloud Storage/BigQuery.
Timezone aware Datetime are converted to UTC seconds.
Unaware Datetime, Date and Time are converted to ISO formatted strings.
Decimals are converted to floats.
:p... | 60 | 54 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def convert_type(self, value, schema_type, stringify_dict=True):
if isinstance(value, datetime.datetime):
iso_format_value = value.isoformat()
if val... |
2,330 | def _filter_top_k(x, k):
_, top_k_idx = tf.math.top_k(x, k, sorted=False)
top_k_mask = tf.reduce_sum(
tf.one_hot(top_k_idx, tf.shape(x)[-1], axis=-1), axis=-2
)
return x * top_k_mask + NEG_INF * (1 - top_k_mask)
| Filters top-k values in the last dim of x and set the rest to NEG_INF.
Used for computing top-k prediction values in dense labels (which has the same
shape as predictions) for recall and precision top-k metrics.
Args:
x: tensor with any dimensions.
k: the number of values to keep.
Returns... | 59 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _filter_top_k(x, k):
_, top_k_idx = tf.math.top_k(x, k, sorted=False)
top_k_mask = tf.reduce_sum(
tf.one_hot(top_k_idx, tf.shape(x)[-1], axis=-1), axis=-2
)
... |
2,331 | def test_pick_two_individuals_eligible_for_crossover_bad():
ind1 = creator.Individual.from_string(
'BernoulliNB(input_matrix, BernoulliNB__alpha=1.0, BernoulliNB__fit_prior=True)',
tpot_obj._pset
)
ind2 = creator.Individual.from_string(
'BernoulliNB(input_matrix, BernoulliNB__a... | Assert that pick_two_individuals_eligible_for_crossover() returns the right output when no pair is eligible | 12 | 102 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_pick_two_individuals_eligible_for_crossover_bad():
ind1 = creator.Individual.from_string(
'BernoulliNB(input_matrix, BernoulliNB__alpha=1.0, BernoulliNB__fit_prior... |
2,332 | def get_ips(v6=False):
# type: (bool) -> Dict[NetworkInterface, List[str]]
res = {}
for iface in six.itervalues(conf.ifaces):
if v6:
res[iface] = iface.ips[6]
else:
res[iface] = iface.ips[4]
return res
| Returns all available IPs matching to interfaces, using the windows system.
Should only be used as a WinPcapy fallback.
:param v6: IPv6 addresses
| 23 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_ips(v6=False):
# type: (bool) -> Dict[NetworkInterface, List[str]]
res = {}
for iface in six.itervalues(conf.ifaces):
if v6:
res[iface] = iface.i... |
2,333 | def _set_gradient_checkpointing(self, module, value=False):
if isinstance(module, (OPTDecoder)):
module.gradient_checkpointing = value
OPT_GENERATION_EXAMPLE = r
OPT_INPUTS_DOCSTRING = r
|
Generation example:
```python
>>> from transformers import AutoTokenizer, AutoModelForCausalLM
>>> model = OPTForCausalLM.from_pretrained("ArthurZ/opt-350m")
>>> tokenizer = GPT2Tokenizer.from_pretrained("patrickvonplaten/opt_gpt2_tokenizer")
>>> TEXTS_TO_GENERATE = "Hey, are you consciours?... | 470 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _set_gradient_checkpointing(self, module, value=False):
if isinstance(module, (OPTDecoder)):
module.gradient_checkpointing = value
OPT_GENERATION_EXAMPLE = r
OPT_I... |
2,334 | def to(self, device=None, dtype=None) -> None:
r
# .to() on the tensors handles None correctly
self.shadow_params = [
p.to(device=device, dtype=dtype) if p.is_floating_point() else p.to(device=device)
for p in self.shadow_params
]
| Move internal buffers of the ExponentialMovingAverage to `device`.
Args:
device: like `device` argument to `torch.Tensor.to`
| 15 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def to(self, device=None, dtype=None) -> None:
r
# .to() on the tensors handles None correctly
self.shadow_params = [
p.to(device=device, dtype=dtype) if ... |
2,335 | def get_granger_causality(dependent_series, independent_series, lags):
granger_set = pd.concat([dependent_series, independent_series], axis=1)
granger = grangercausalitytests(granger_set, [lags], verbose=False)
return granger
| Calculate granger tests
Parameters
----------
dependent_series: Series
The series you want to test Granger Causality for.
independent_series: Series
The series that you want to test whether it Granger-causes time_series_y
lags : int
The amount of lags for the Granger test. B... | 47 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_granger_causality(dependent_series, independent_series, lags):
granger_set = pd.concat([dependent_series, independent_series], axis=1)
granger = grangercausalitytests(g... |
2,336 | def _multi_decorate(decorators, method):
if hasattr(decorators, "__iter__"):
# Apply a list/tuple of decorators if 'decorators' is one. Decorator
# functions are applied so that the call order is the same as the
# order in which they appear in the iterable.
decorators = decorato... |
Decorate `method` with one or more function decorators. `decorators` can be
a single decorator or an iterable of decorators.
| 19 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _multi_decorate(decorators, method):
if hasattr(decorators, "__iter__"):
# Apply a list/tuple of decorators if 'decorators' is one. Decorator
# functions are app... |
2,337 | def generate_level_targets(self, img_size, text_polys, ignore_polys):
h, w = img_size
lv_size_divs = self.level_size_divisors
lv_proportion_range = self.level_proportion_range
lv_text_polys = [[] for i in range(len(lv_size_divs))]
lv_ignore_polys = [[] for i in range(len... | Generate ground truth target on each level.
Args:
img_size (list[int]): Shape of input image.
text_polys (list[list[ndarray]]): A list of ground truth polygons.
ignore_polys (list[list[ndarray]]): A list of ignored polygons.
Returns:
level_maps (list(ndar... | 40 | 191 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def generate_level_targets(self, img_size, text_polys, ignore_polys):
h, w = img_size
lv_size_divs = self.level_size_divisors
lv_proportion_range = self.leve... |
2,338 | def get_reserved_qty(item_code, warehouse):
reserved_qty = frappe.db.sql(
,
(item_code, warehouse, item_code, warehouse),
)
return flt(reserved_qty[0][0]) if reserved_qty else 0
|
select
sum(dnpi_qty * ((so_item_qty - so_item_delivered_qty) / so_item_qty))
from
(
(select
qty as dnpi_qty,
(
select qty from `tabSales Order Item`
where name = dnpi.parent_detail_docname
and (delivered_by_supplier is null or delivered_by_supplier = 0)
) as so_item_qty,
... | 163 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_reserved_qty(item_code, warehouse):
reserved_qty = frappe.db.sql(
,
(item_code, warehouse, item_code, warehouse),
)
return flt(reserved_qty[0][0]) if reserved_qty else 0
... |
2,339 | def cool():
set_cmap('cool')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost. |
Set the colormap to 'cool'.
This changes the default colormap as well as the colormap of the current
image if there is one. See ``help(colormaps)`` for more information.
| 28 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def cool():
set_cmap('cool')
# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
```
###Assistant :
Set the colormap to 'cool'.
This cha... |
2,340 | def add_parent(self, parent):
# type: (Packet) -> None
self.parent = parent
| Set packet parent.
When packet is an element in PacketListField, parent field would
point to the list owner packet. | 19 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def add_parent(self, parent):
# type: (Packet) -> None
self.parent = parent
```
###Assistant : Set packet parent.
When packet is an element in P... |
2,341 | def make_tempfile(name):
open(name, 'w', encoding='utf-8').close()
try:
yield
finally:
os.unlink(name)
| Create an empty, named, temporary file for the duration of the context.
| 12 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def make_tempfile(name):
open(name, 'w', encoding='utf-8').close()
try:
yield
finally:
os.unlink(name)
```
###Assistant : Create an empty, name... |
2,342 | def update_cached_response(self, request, response):
cache_url = self.cache_url(request.url)
cached_response = self.serializer.loads(request, self.cache.get(cache_url))
if not cached_response:
# we didn't have a cached response
return response
# Lets u... | On a 304 we will get a new set of headers that we want to
update our cached value with, assuming we have one.
This should only ever be called when we've sent an ETag and
gotten a 304 as the response.
| 42 | 120 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def update_cached_response(self, request, response):
cache_url = self.cache_url(request.url)
cached_response = self.serializer.loads(request, self.cache.get(cache_u... |
2,343 | def binary_xloss(logits, labels, ignore=None):
logits, labels = flatten_binary_scores(logits, labels, ignore)
loss = StableBCELoss()(logits, Variable(labels.float()))
return loss
# --------------------------- MULTICLASS LOSSES ---------------------------
|
Binary Cross entropy loss
logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty)
labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
ignore: void class id
| 33 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def binary_xloss(logits, labels, ignore=None):
logits, labels = flatten_binary_scores(logits, labels, ignore)
loss = StableBCELoss()(logits, Variable(labels.float()))
return... |
2,344 | def generate_navigator_js(os=None, navigator=None, platform=None, device_type=None):
config = generate_navigator(
os=os, navigator=navigator, platform=platform, device_type=device_type
)
return {
"appCodeName": config["app_code_name"],
"appName": config["app_name"],
"ap... |
Generates web navigator's config with keys corresponding
to keys of `windows.navigator` JavaScript object.
:param os: limit list of oses for generation
:type os: string or list/tuple or None
:param navigator: limit list of browser engines for generation
:type navigator: string or list/tuple or... | 95 | 38 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def generate_navigator_js(os=None, navigator=None, platform=None, device_type=None):
config = generate_navigator(
os=os, navigator=navigator, platform=platform, device_type... |
2,345 | def printable_text(text):
# These functions want `str` for both Python2 and Python3, but in one case
# it's a Unicode string and in the other it's a byte string.
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("... | Returns text encoded in a way suitable for print or `tf.logging`. | 11 | 79 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def printable_text(text):
# These functions want `str` for both Python2 and Python3, but in one case
# it's a Unicode string and in the other it's a byte string.
if six.PY3... |
2,346 | def is_tradesignal(self, action):
# trade signal
return not ((action == Actions.Neutral.value and self._position == Positions.Neutral)
or (action == Actions.Short.value and self._position == Positions.Short)
or (action == Actions.Long.value and self._pos... |
not trade signal is :
Action: Neutral, position: Neutral -> Nothing
Action: Long, position: Long -> Hold Long
Action: Short, position: Short -> Hold Short
| 25 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def is_tradesignal(self, action):
# trade signal
return not ((action == Actions.Neutral.value and self._position == Positions.Neutral)
or (actio... |
2,347 | def log_message(self, format, *args):
sys.stderr.write("%s - - [%s] %s\n" %
(self.address_string(),
self.log_date_time_string(),
format%args))
| Log an arbitrary message.
This is used by all other logging functions. Override
it if you have specific logging wishes.
The first argument, FORMAT, is a format string for the
message to be logged. If the format string contains
any % escapes requiring parameters, they should b... | 66 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def log_message(self, format, *args):
sys.stderr.write("%s - - [%s] %s\n" %
(self.address_string(),
self.log_date_time_st... |
2,348 | def warning_advice(self, *args, **kwargs):
no_advisory_warnings = os.getenv("DIFFUSERS_NO_ADVISORY_WARNINGS", False)
if no_advisory_warnings:
return
self.warning(*args, **kwargs)
logging.Logger.warning_advice = warning_advice
|
This method is identical to `logger.warninging()`, but if env var DIFFUSERS_NO_ADVISORY_WARNINGS=1 is set, this
warning will not be printed
| 19 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def warning_advice(self, *args, **kwargs):
no_advisory_warnings = os.getenv("DIFFUSERS_NO_ADVISORY_WARNINGS", False)
if no_advisory_warnings:
return
self.warning(*ar... |
2,349 | def zip_row_op(self, i, k, f):
for j in range(self.cols):
self[i, j] = f(self[i, j], self[k, j])
| In-place operation on row ``i`` using two-arg functor whose args are
interpreted as ``(self[i, j], self[k, j])``.
Examples
========
>>> from sympy import eye
>>> M = eye(3)
>>> M.zip_row_op(1, 0, lambda v, u: v + 2*u); M
Matrix([
[1, 0, 0],
[2, 1... | 54 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def zip_row_op(self, i, k, f):
for j in range(self.cols):
self[i, j] = f(self[i, j], self[k, j])
```
###Assistant : In-place operation on row ``i`` ... |
2,350 | def legendre_poly(n, x=None, polys=False):
r
return named_poly(n, dup_legendre, QQ, "Legendre polynomial", (x,), polys)
| Generates the Legendre polynomial `P_n(x)`.
Parameters
==========
n : int
Degree of the polynomial.
x : optional
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
| 31 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def legendre_poly(n, x=None, polys=False):
r
return named_poly(n, dup_legendre, QQ, "Legendre polynomial", (x,), polys)
```
###Assistant : Generates the Legendre polyno... |
2,351 | def _concat_short_text_reuslts(self, input_texts, results):
long_text_lens = [len(text) for text in input_texts]
concat_results = []
single_results = {}
count = 0
for text in input_texts:
text_len = len(text)
while True:
if len(sin... |
Concat the model output of short texts to the total result of long text.
| 14 | 91 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _concat_short_text_reuslts(self, input_texts, results):
long_text_lens = [len(text) for text in input_texts]
concat_results = []
single_results = {}
... |
2,352 | def get_pred(self, bboxes, bbox_num, im_shape, scale_factor):
origin_shape = paddle.floor(im_shape / scale_factor + 0.5)
origin_shape_list = []
scale_factor_list = []
# scale_factor: scale_y, scale_x
for i in range(bbox_num.shape[0]):
expand_shape = paddle.e... |
Rescale, clip and filter the bbox from the output of NMS to
get final prediction.
Args:
bboxes(Tensor): bboxes [N, 10]
bbox_num(Tensor): bbox_num
im_shape(Tensor): [1 2]
scale_factor(Tensor): [1 2]
Returns:
bbox_pred(Tensor): T... | 54 | 191 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_pred(self, bboxes, bbox_num, im_shape, scale_factor):
origin_shape = paddle.floor(im_shape / scale_factor + 0.5)
origin_shape_list = []
scale_factor... |
2,353 | def unset_existing_data(company):
linked = frappe.db.sql(
,
as_dict=True,
)
# remove accounts data from company
update_values = {d.fieldname: "" for d in linked}
frappe.db.set_value("Company", company, update_values, update_values)
# remove accounts data from various doctypes
for doctype in [
"Account",
... | select fieldname from tabDocField
where fieldtype="Link" and options="Account" and parent="Company"delete from `tab{0}` where `company`="%s" | 14 | 65 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def unset_existing_data(company):
linked = frappe.db.sql(
,
as_dict=True,
)
# remove accounts data from company
update_values = {d.fieldname: "" for d in linked}
frappe.db.set_valu... |
2,354 | def simple_test(self, feats, batch_img_metas, rescale=False):
outs = self.forward(feats)
results_list = self.get_results(
*outs, batch_img_metas=batch_img_metas, rescale=rescale)
return results_list
| Test function without test-time augmentation.
Args:
feats (tuple[torch.Tensor]): Multi-level features from the
upstream network, each is a 4D-tensor.
batch_img_metas (list[dict]): List of image information.
rescale (bool, optional): Whether to rescale the res... | 91 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def simple_test(self, feats, batch_img_metas, rescale=False):
outs = self.forward(feats)
results_list = self.get_results(
*outs, batch_img_metas=batch_im... |
2,355 | def compare_pt_tf_models(pt_model, pt_input, tf_model, tf_input):
pt_outputs = pt_model(**pt_input, output_hidden_states=True)
tf_outputs = tf_model(**tf_input, output_hidden_states=True)
# 1. All output attributes must be the same
pt_out_attrs = set(pt_outputs.keys())
... |
Compares the TensorFlow and PyTorch models, given their inputs, returning a tuple with the maximum observed
difference and its source.
| 20 | 59 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def compare_pt_tf_models(pt_model, pt_input, tf_model, tf_input):
pt_outputs = pt_model(**pt_input, output_hidden_states=True)
tf_outputs = tf_model(**tf_input, outp... |
2,356 | def _get_all_parser_float_precision_combinations():
params = []
ids = []
for parser, parser_id in zip(_all_parsers, _all_parser_ids):
if hasattr(parser, "values"):
# Wrapped in pytest.param, get the actual parser back
parser = parser.values[0]
for precision in pa... |
Return all allowable parser and float precision
combinations and corresponding ids.
| 11 | 64 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_all_parser_float_precision_combinations():
params = []
ids = []
for parser, parser_id in zip(_all_parsers, _all_parser_ids):
if hasattr(parser, "values"):
... |
2,357 | def test_egg3(self):
egg_name = "%s/omelet.egg" % self.egg_dir
with extend_sys_path(egg_name):
with self.settings(INSTALLED_APPS=["omelet.app_with_models"]):
models_module = apps.get_app_config("app_with_models").models_module
self.assertIsNotNone(mod... | Models module can be loaded from an app located under an egg's top-level package | 14 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_egg3(self):
egg_name = "%s/omelet.egg" % self.egg_dir
with extend_sys_path(egg_name):
with self.settings(INSTALLED_APPS=["omelet.app_with_models... |
2,358 | def test_auditing_case_names(lgpo, setting_name, setting, enable_legacy_auditing):
lgpo.set_computer_policy(setting_name, setting)
result = lgpo.get_policy(setting_name, "machine")
assert result == setting
@pytest.mark.parametrize("setting", ["Enabled", "Disabled"]) |
Helper function to set an audit setting and assert that it was successful
| 13 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_auditing_case_names(lgpo, setting_name, setting, enable_legacy_auditing):
lgpo.set_computer_policy(setting_name, setting)
result = lgpo.get_policy(setting_name, "machin... |
2,359 | def test_get(self):
# Generate signature
signature = generate_signature(self.image.id, "fill-800x600")
# Get the image
response = self.client.get(
reverse(
"wagtailimages_serve", args=(signature, self.image.id, "fill-800x600")
)
)... |
Test a valid GET request to the view
| 8 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_get(self):
# Generate signature
signature = generate_signature(self.image.id, "fill-800x600")
# Get the image
response = self.client.get(
... |
2,360 | def _object2proto(self) -> Slice_PB:
slice_pb = Slice_PB()
if self.start:
slice_pb.start = self.start
slice_pb.has_start = True
if self.stop:
slice_pb.stop = self.stop
slice_pb.has_stop = True
if self.step:
slice_pb.s... |
Serialize the Slice object instance returning a protobuf.
Returns:
Slice_PB: returns a protobuf object class representing this Slice object.
| 19 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _object2proto(self) -> Slice_PB:
slice_pb = Slice_PB()
if self.start:
slice_pb.start = self.start
slice_pb.has_start = True
if s... |
2,361 | def __call__(self) -> List[Tuple[int, int]]:
logger.info("Sorting face distances. Depending on your dataset this may take some time...")
if self._threshold:
self._threshold = self._result_linkage[:, 2].max() * self._threshold
result_order = self._seriation(self._result_linka... | Process the linkages.
Transforms a distance matrix into a sorted distance matrix according to the order implied
by the hierarchical tree (dendrogram).
Returns
-------
list:
List of indices with the order implied by the hierarchical tree or list of tuples of
... | 49 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __call__(self) -> List[Tuple[int, int]]:
logger.info("Sorting face distances. Depending on your dataset this may take some time...")
if self._threshold:
... |
2,362 | def get_pred(self, bboxes, bbox_num, im_shape, scale_factor):
if self.export_eb:
# enable rcnn models for edgeboard hw to skip the following postprocess.
return bboxes, bboxes, bbox_num
if not self.export_onnx:
bboxes_list = []
bbox_num_list = []... |
Rescale, clip and filter the bbox from the output of NMS to
get final prediction.
Notes:
Currently only support bs = 1.
Args:
bboxes (Tensor): The output bboxes with shape [N, 6] after decode
and NMS, including labels, scores and bboxes.
... | 90 | 292 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_pred(self, bboxes, bbox_num, im_shape, scale_factor):
if self.export_eb:
# enable rcnn models for edgeboard hw to skip the following postprocess.
... |
2,363 | def _signal_zone_update(self):
async_dispatcher_send(self.hass, f"{SIGNAL_ZONE_UPDATE}-{self._zone.zone_id}")
| Signal a zone update.
Whenever the underlying library does an action against
a zone, the data for the zone is updated.
Update a single zone.
| 25 | 4 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _signal_zone_update(self):
async_dispatcher_send(self.hass, f"{SIGNAL_ZONE_UPDATE}-{self._zone.zone_id}")
```
###Assistant : Signal a zone update.
... |
2,364 | def test_asymmetric_error(quantile):
n_samples = 10_000
rng = np.random.RandomState(42)
# take care that X @ coef + intercept > 0
X = np.concatenate(
(
np.abs(rng.randn(n_samples)[:, None]),
-rng.randint(2, size=(n_samples, 1)),
),
axis=1,
)
i... | Test quantile regression for asymmetric distributed targets. | 7 | 133 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_asymmetric_error(quantile):
n_samples = 10_000
rng = np.random.RandomState(42)
# take care that X @ coef + intercept > 0
X = np.concatenate(
(
... |
2,365 | def update(self) -> None:
with self.lock:
# Fetch valid stop information once
if not self._origin:
stops = self._pygtfs.stops_by_id(self.origin)
if not stops:
self._available = False
_LOGGER.warning("Origin ... | Get the latest data from GTFS and update the states. | 10 | 259 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def update(self) -> None:
with self.lock:
# Fetch valid stop information once
if not self._origin:
stops = self._pygtfs.stops_by_id(s... |
2,366 | async def test_carbon_monoxide_sensor_read_state(hass, utcnow):
helper = await setup_test_component(hass, create_carbon_monoxide_sensor_service)
await helper.async_update(
ServicesTypes.CARBON_MONOXIDE_SENSOR,
{CharacteristicsTypes.CARBON_MONOXIDE_DETECTED: 0},
)
state = await help... | Test that we can read the state of a HomeKit contact accessory. | 12 | 41 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_carbon_monoxide_sensor_read_state(hass, utcnow):
helper = await setup_test_component(hass, create_carbon_monoxide_sensor_service)
await helper.async_update(
... |
2,367 | def save_config(self) -> TritonArtifact:
device = self.device
if self.inference_stage != PREDICTOR:
device = "cpu"
self.config = TritonConfig(
self.full_model_name,
self.input_features,
self.output_features,
self.max_batch_size... | Save the Triton config.
Return the appropriate artifact.
| 8 | 52 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def save_config(self) -> TritonArtifact:
device = self.device
if self.inference_stage != PREDICTOR:
device = "cpu"
self.config = TritonConfig(
... |
2,368 | def test_unknown_device(self) -> None:
url = "/_synapse/admin/v2/users/%s/devices/unknown_device" % urllib.parse.quote(
self.other_user
)
channel = self.make_request(
"GET",
url,
access_token=self.admin_user_tok,
)
self.a... |
Tests that a lookup for a device that does not exist returns either 404 or 200.
| 16 | 50 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_unknown_device(self) -> None:
url = "/_synapse/admin/v2/users/%s/devices/unknown_device" % urllib.parse.quote(
self.other_user
)
channe... |
2,369 | def complete_code(accelerator, model, tokenizer, dataloader, n_tasks, batch_size=20, **gen_kwargs):
gen_token_dict = defaultdict(list) # dict of list of generated tokens
for step, batch in tqdm(enumerate(dataloader)):
with torch.no_grad():
gen_kwargs["stopping_criteria"][0].start_lengt... | Generate multiple codes for each task in the dataset. This function leverage accelerator to distribute
the processing to multiple GPUs.
dataloader, a wrapper around a TokenizeDataset objectm is supposed to send all the prompts from
the evalution dataset to the modelm as the following:
[p_0_0, p_0_1, ...... | 207 | 96 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def complete_code(accelerator, model, tokenizer, dataloader, n_tasks, batch_size=20, **gen_kwargs):
gen_token_dict = defaultdict(list) # dict of list of generated tokens
for st... |
2,370 | def get_status(start_date, end_date):
if not end_date:
return "Active"
start_date = getdate(start_date)
end_date = getdate(end_date)
now_date = getdate(nowdate())
return "Active" if start_date <= now_date <= end_date else "Inactive"
|
Get a Contract's status based on the start, current and end dates
Args:
start_date (str): The start date of the contract
end_date (str): The end date of the contract
Returns:
str: 'Active' if within range, otherwise 'Inactive'
| 37 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_status(start_date, end_date):
if not end_date:
return "Active"
start_date = getdate(start_date)
end_date = getdate(end_date)
now_date = getdate(nowdate())
return "Active"... |
2,371 | def calc_position(self, s):
x = self.sx.calc_position(s)
y = self.sy.calc_position(s)
return x, y
|
calc position
Parameters
----------
s : float
distance from the start point. if `s` is outside the data point's
range, return None.
Returns
-------
x : float
x position for given s.
y : float
y position fo... | 40 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def calc_position(self, s):
x = self.sx.calc_position(s)
y = self.sy.calc_position(s)
return x, y
```
###Assistant :
calc position
... |
2,372 | def push(self, exit):
# We use an unbound method rather than a bound method to follow
# the standard lookup behaviour for special methods.
_cb_type = type(exit)
try:
exit_method = _cb_type.__exit__
except AttributeError:
# Not a context manager, ... | Registers a callback with the standard __exit__ method signature.
Can suppress exceptions the same way __exit__ method can.
Also accepts any object with an __exit__ method (registering a call
to the method instead of the object itself).
| 37 | 55 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def push(self, exit):
# We use an unbound method rather than a bound method to follow
# the standard lookup behaviour for special methods.
_cb_type = type(ex... |
2,373 | async def async_media_play(self) -> None:
if self._status["state"] == "pause":
await self._client.pause(0)
else:
await self._client.play()
| Service to send the MPD the command for play/pause. | 9 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def async_media_play(self) -> None:
if self._status["state"] == "pause":
await self._client.pause(0)
else:
await self._client.play()
... |
2,374 | def download_datev_csv(filters):
if isinstance(filters, str):
filters = json.loads(filters)
validate(filters)
company = filters.get("company")
fiscal_year = get_fiscal_year(date=filters.get("from_date"), company=company)
filters["fiscal_year_start"] = fiscal_year[1]
# set chart of accounts used
coa = frap... |
Provide accounting entries for download in DATEV format.
Validate the filters, get the data, produce the CSV file and provide it for
download. Can be called like this:
GET /api/method/erpnext.regional.report.datev.datev.download_datev_csv
Arguments / Params:
filters -- dict of filters to be passed to the sql ... | 45 | 109 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def download_datev_csv(filters):
if isinstance(filters, str):
filters = json.loads(filters)
validate(filters)
company = filters.get("company")
fiscal_year = get_fiscal_year(date=fi... |
2,375 | def taggedsent_to_conll(sentence):
for (i, (word, tag)) in enumerate(sentence, start=1):
input_str = [str(i), word, "_", tag, tag, "_", "0", "a", "_", "_"]
input_str = "\t".join(input_str) + "\n"
yield input_str
|
A module to convert a single POS tagged sentence into CONLL format.
>>> from nltk import word_tokenize, pos_tag
>>> text = "This is a foobar sentence."
>>> for line in taggedsent_to_conll(pos_tag(word_tokenize(text))): # doctest: +NORMALIZE_WHITESPACE
... print(line, end="")
1 This _ DT D... | 121 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def taggedsent_to_conll(sentence):
for (i, (word, tag)) in enumerate(sentence, start=1):
input_str = [str(i), word, "_", tag, tag, "_", "0", "a", "_", "_"]
input_str... |
2,376 | def get_system_encoding():
try:
encoding = locale.getdefaultlocale()[1] or "ascii"
codecs.lookup(encoding)
except Exception:
encoding = "ascii"
return encoding
DEFAULT_LOCALE_ENCODING = get_system_encoding()
|
The encoding of the default system locale. Fallback to 'ascii' if the
#encoding is unsupported by Python or could not be determined. See tickets
#10335 and #5846.
| 27 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_system_encoding():
try:
encoding = locale.getdefaultlocale()[1] or "ascii"
codecs.lookup(encoding)
except Exception:
encoding = "ascii"
retur... |
2,377 | def get_menu_item(self):
if self.modeladmin_instances:
submenu = Menu(items=self.get_submenu_items())
return GroupMenuItem(self, self.get_menu_order(), submenu)
|
Utilised by Wagtail's 'register_menu_item' hook to create a menu
for this group with a submenu linking to listing pages for any
associated ModelAdmin instances
| 24 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_menu_item(self):
if self.modeladmin_instances:
submenu = Menu(items=self.get_submenu_items())
return GroupMenuItem(self, self.get_menu_order(... |
2,378 | def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath):
path, transform = self._get_text_path_transform(
x, y, s, prop, angle, ismath)
color = gc.get_rgb()
gc.set_linewidth(0.0)
self.draw_path(gc, path, transform, rgbFace=color)
|
Draw the text by converting them to paths using `.TextToPath`.
Parameters
----------
x : float
The x location of the text in display coords.
y : float
The y location of the text baseline in display coords.
s : str
The text to be conve... | 78 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath):
path, transform = self._get_text_path_transform(
x, y, s, prop, angle, ismath)
color = gc... |
2,379 | def __call__(self, match_quality_matrix):
assert match_quality_matrix.dim() == 2
if match_quality_matrix.numel() == 0:
default_matches = match_quality_matrix.new_full((match_quality_matrix.size(1),), 0, dtype=torch.int64)
# When no gt boxes exist, we define IOU = 0 and t... |
Args:
match_quality_matrix (Tensor[float]): an MxN tensor, containing the pairwise quality between M ground-truth elements and N predicted
elements. All elements must be >= 0 (due to the us of `torch.nonzero` for selecting indices in :meth:`set_low_quality_matches_`).
Return... | 69 | 128 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __call__(self, match_quality_matrix):
assert match_quality_matrix.dim() == 2
if match_quality_matrix.numel() == 0:
default_matches = match_quality_ma... |
2,380 | def ismemberdescriptor(object):
return isinstance(object, types.MemberDescriptorType)
else:
# Other implementations | Return true if the object is a member descriptor.
Member descriptors are specialized descriptors defined in extension
modules. | 18 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def ismemberdescriptor(object):
return isinstance(object, types.MemberDescriptorType)
else:
# Other implementations
```
###Assistant : Return true if the obj... |
2,381 | def pandas_dtype_to_arrow_c(dtype) -> str:
if isinstance(dtype, pandas.CategoricalDtype):
return ArrowCTypes.INT64
elif dtype == np.dtype("O"):
return ArrowCTypes.STRING
format_str = getattr(ArrowCTypes, dtype.name.upper(), None)
if format_str is not None:
return format_str... |
Represent pandas `dtype` as a format string in Apache Arrow C notation.
Parameters
----------
dtype : np.dtype
Datatype of pandas DataFrame to represent.
Returns
-------
str
Format string in Apache Arrow C notation of the given `dtype`.
| 37 | 62 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def pandas_dtype_to_arrow_c(dtype) -> str:
if isinstance(dtype, pandas.CategoricalDtype):
return ArrowCTypes.INT64
elif dtype == np.dtype("O"):
return ArrowCType... |
2,382 | def is_file_like(obj) -> bool:
if not (hasattr(obj, "read") or hasattr(obj, "write")):
return False
return bool(hasattr(obj, "__iter__"))
|
Check if the object is a file-like object.
For objects to be considered file-like, they must
be an iterator AND have either a `read` and/or `write`
method as an attribute.
Note: file-like objects must be iterable, but
iterable objects need not be file-like.
Parameters
----------
... | 76 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def is_file_like(obj) -> bool:
if not (hasattr(obj, "read") or hasattr(obj, "write")):
return False
return bool(hasattr(obj, "__iter__"))
```
###Assistant... |
2,383 | def update(self) -> Union[SourceRead, DestinationRead, ConnectionRead]:
return self._create_or_update(self._update_fn, self.update_payload)
| Public function to update the resource on the remote Airbyte instance.
Returns:
Union[SourceRead, DestinationRead, ConnectionRead]: The updated resource.
| 18 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def update(self) -> Union[SourceRead, DestinationRead, ConnectionRead]:
return self._create_or_update(self._update_fn, self.update_payload)
```
###Assistant : P... |
2,384 | def test_callback_session(self) -> None:
request = Mock(spec=["args", "getCookie", "cookies"])
# Missing cookie
request.args = {}
request.getCookie.return_value = None
self.get_success(self.handler.handle_oidc_callback(request))
self.assertRenderedError("missing... | The callback verifies the session presence and validity | 8 | 90 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_callback_session(self) -> None:
request = Mock(spec=["args", "getCookie", "cookies"])
# Missing cookie
request.args = {}
request.getCookie.... |
2,385 | def _create_repo_url(self) -> str:
url_components = urllib.parse.urlparse(self.repository_url)
if url_components.scheme == "https" and self.credentials is not None:
repo_url = url_components.netloc + url_components.path
updated_components = url_components._replace(
... | Format the URL provided to the `git clone` command.
For private repos: https://<oauth-key>@github.com/<username>/<repo>.git
All other repos should be the same as `self.repository`.
| 22 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _create_repo_url(self) -> str:
url_components = urllib.parse.urlparse(self.repository_url)
if url_components.scheme == "https" and self.credentials is not None:
... |
2,386 | def test_lookup_with_dynamic_value(self):
modeladmin = DepartmentFilterDynamicValueBookAdmin(Book, site)
|
Ensure SimpleListFilter can access self.value() inside the lookup.
| 8 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_lookup_with_dynamic_value(self):
modeladmin = DepartmentFilterDynamicValueBookAdmin(Book, site)
```
###Assistant :
Ensure SimpleListFilter can... |
2,387 | def test_batch_encode_dynamic_overflowing(self):
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
tokenizer = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name}, {tokenizer.__... |
When calling batch_encode with multiple sequence it can returns different number of
overflowing encoding for each sequence:
[
Sequence 1: [Encoding 1, Encoding 2],
Sequence 2: [Encoding 1],
Sequence 3: [Encoding 1, Encoding 2, ... Encoding N]
]
This... | 51 | 144 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_batch_encode_dynamic_overflowing(self):
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
tokenizer = self.rust_tokenizer_class.from_pretr... |
2,388 | def deserialize(config, custom_objects=None):
# loss_scale_optimizer has a direct dependency of optimizer, import here
# rather than top to avoid the cyclic dependency.
from keras.mixed_precision import (
loss_scale_optimizer,
) # pylint: disable=g-import-not-at-top
all_classes = {
... | Inverse of the `serialize` function.
Args:
config: Optimizer configuration dictionary.
custom_objects: Optional dictionary mapping names (strings) to custom
objects (classes and functions) to be considered during deserialization.
Returns:
A Keras Optimizer instance.
| 32 | 106 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def deserialize(config, custom_objects=None):
# loss_scale_optimizer has a direct dependency of optimizer, import here
# rather than top to avoid the cyclic dependency.
from... |
2,389 | def commutes_with(self, other):
a = self.array_form
b = other.array_form
return _af_commutes_with(a, b)
|
Checks if the elements are commuting.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> a = Permutation([1, 4, 3, 0, 2, 5])
>>> b = Permutation([0, 1, 2, 3, 4, 5])
>>> a.commutes_with(b)
True
>>> b = Permutation([2, 3, 5, 4, ... | 46 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def commutes_with(self, other):
a = self.array_form
b = other.array_form
return _af_commutes_with(a, b)
```
###Assistant :
Checks if th... |
2,390 | def get_all_styles():
yield from STYLE_MAP
for name, _ in find_plugin_styles():
yield name
| Return a generator for all styles by name,
both builtin and plugin. | 12 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_all_styles():
yield from STYLE_MAP
for name, _ in find_plugin_styles():
yield name
```
###Assistant : Return a generator for all styles by name,
... |
2,391 | def lift(cooccurrence):
diag_rows, diag_cols = _get_row_and_column_matrix(cooccurrence.diagonal())
with np.errstate(invalid="ignore", divide="ignore"):
result = cooccurrence / (diag_rows * diag_cols)
return np.array(result)
| Helper method to calculate the Lift of a matrix of
co-occurrences. In comparison with basic co-occurrence and Jaccard
similarity, lift favours discoverability and serendipity, as
opposed to co-occurrence that favours the most popular items, and
Jaccard that is a compromise between the two.
Args:
... | 63 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def lift(cooccurrence):
diag_rows, diag_cols = _get_row_and_column_matrix(cooccurrence.diagonal())
with np.errstate(invalid="ignore", divide="ignore"):
result = cooccu... |
2,392 | def update(self, props):
return self._update_props(
props, "{cls.__name__!r} object has no property {prop_name!r}")
|
Update this artist's properties from the dict *props*.
Parameters
----------
props : dict
| 13 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def update(self, props):
return self._update_props(
props, "{cls.__name__!r} object has no property {prop_name!r}")
```
###Assistant :
Upda... |
2,393 | def new_workers_size(self):
remote_resources = ray.available_resources()
max_remote_workers = self._max_workers
new_remote_workers = min(remote_resources.get("CPU", 0), max_remote_workers)
if self._use_gpu:
new_remote_workers = min(remote_resources.get("GPU", 0), new... | Returns number of workers to create based on available resources. | 10 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def new_workers_size(self):
remote_resources = ray.available_resources()
max_remote_workers = self._max_workers
new_remote_workers = min(remote_resources.get... |
2,394 | def setmonitor(self, enable=True):
# type: (bool) -> bool
# We must reset the monitor cache
if enable:
res = self.setmode('monitor')
else:
res = self.setmode('managed')
if not res:
log_runtime.error("Npcap WlanHelper returned with an e... | Alias for setmode('monitor') or setmode('managed')
Only available with Npcap | 9 | 50 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def setmonitor(self, enable=True):
# type: (bool) -> bool
# We must reset the monitor cache
if enable:
res = self.setmode('monitor')
else... |
2,395 | def _rotated_rect_with_max_area(h, w, angle):
angle = math.radians(angle)
width_is_longer = w >= h
side_long, side_short = (w, h) if width_is_longer else (h, w)
# since the solutions for angle, -angle and 180-angle are all the same,
# it is sufficient to look at the fi... |
Given a rectangle of size wxh that has been rotated by 'angle' (in
degrees), computes the width and height of the largest possible
axis-aligned rectangle (maximal area) within the rotated rectangle.
Code from: https://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black... | 34 | 195 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _rotated_rect_with_max_area(h, w, angle):
angle = math.radians(angle)
width_is_longer = w >= h
side_long, side_short = (w, h) if width_is_longer else (h... |
2,396 | def using(_other, **kwargs):
gt_kwargs = {}
if 'state' in kwargs:
s = kwargs.pop('state')
if isinstance(s, (list, tuple)):
gt_kwargs['stack'] = s
else:
gt_kwargs['stack'] = ('root', s)
if _other is this: |
Callback that processes the match with a different lexer.
The keyword arguments are forwarded to the lexer, except `state` which
is handled separately.
`state` specifies the state that the new lexer will start in, and can
be an enumerable such as ('root', 'inline', 'string') or a simple
strin... | 70 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def using(_other, **kwargs):
gt_kwargs = {}
if 'state' in kwargs:
s = kwargs.pop('state')
if isinstance(s, (list, tuple)):
gt_kwargs['stack'] = s
... |
2,397 | def test_unset_document_storage_path(self):
self.assertEqual(Document.objects.filter(storage_path=None).count(), 5)
bulk_edit.set_storage_path(
[self.doc1.id],
self.sp1.id,
)
self.assertEqual(Document.objects.filter(storage_path=None).count(), 4)
... |
GIVEN:
- 4 documents without defined storage path
- 1 document with a defined storage
WHEN:
- Bulk edit called to remove storage path from 1 document
THEN:
- Single document storage path removed
| 34 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_unset_document_storage_path(self):
self.assertEqual(Document.objects.filter(storage_path=None).count(), 5)
bulk_edit.set_storage_path(
[self.do... |
2,398 | def test_with_spinner(self):
function_with_spinner()
self.assertFalse(self.forward_msg_queue.is_empty())
| If the show_spinner flag is set, there should be one element in the
report queue.
| 15 | 4 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_with_spinner(self):
function_with_spinner()
self.assertFalse(self.forward_msg_queue.is_empty())
```
###Assistant : If the show_spinner flag is ... |
2,399 | def test_update_device_too_long_display_name(self) -> None:
# Set iniital display name.
update = {"display_name": "new display"}
self.get_success(
self.handler.update_device(
self.other_user, self.other_user_device_id, update
)
)
... |
Update a device with a display name that is invalid (too long).
| 12 | 82 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_update_device_too_long_display_name(self) -> None:
# Set iniital display name.
update = {"display_name": "new display"}
self.get_success(
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.