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 |
|---|---|---|---|---|---|---|
1,500 | async def read_settings() -> prefect.settings.Settings:
return prefect.settings.get_current_settings().with_obfuscated_secrets()
@router.get("/version") |
Get the current Orion settings.
Secret setting values will be obfuscated.
| 11 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def read_settings() -> prefect.settings.Settings:
return prefect.settings.get_current_settings().with_obfuscated_secrets()
@router.get("/version")
```
###Assista... |
1,501 | def map_overlap(self, func, depth, boundary=None, trim=True, **kwargs):
from dask.array.overlap import map_overlap
return map_overlap(
func, self, depth=depth, boundary=boundary, trim=trim, **kwargs
)
| Map a function over blocks of the array with some overlap
We share neighboring zones between blocks of the array, then map a
function, then trim away the neighboring strips.
Note that this function will attempt to automatically determine the output
array type before computing it, pleas... | 435 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def map_overlap(self, func, depth, boundary=None, trim=True, **kwargs):
from dask.array.overlap import map_overlap
return map_overlap(
func, self, depth... |
1,502 | def _flush(self):
# Raise an Exception if the value is being changed in read mode.
if not self._write:
raise GDALException(
"Raster needs to be opened in write mode to change values."
)
capi.flush_ds(self._ptr)
|
Flush all data from memory into the source file if it exists.
The data that needs flushing are geotransforms, coordinate systems,
nodata_values and pixel values. This function will be called
automatically wherever it is needed.
| 35 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _flush(self):
# Raise an Exception if the value is being changed in read mode.
if not self._write:
raise GDALException(
"Raster needs... |
1,503 | def _round(self, places, rounding):
if places <= 0:
raise ValueError("argument should be at least 1 in _round")
if self._is_special or not self:
return Decimal(self)
ans = self._rescale(self.adjusted()+1-places, rounding)
# it can happen that the rescale ... | Round a nonzero, nonspecial Decimal to a fixed number of
significant figures, using the given rounding mode.
Infinities, NaNs and zeros are returned unaltered.
This operation is quiet: it raises no flags, and uses no
information from the context.
| 39 | 82 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _round(self, places, rounding):
if places <= 0:
raise ValueError("argument should be at least 1 in _round")
if self._is_special or not self:
... |
1,504 | def is_redirect(self):
return "location" in self.headers and self.status_code in REDIRECT_STATI
| True if this Response is a well-formed HTTP redirect that could have
been processed automatically (by :meth:`Session.resolve_redirects`).
| 17 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def is_redirect(self):
return "location" in self.headers and self.status_code in REDIRECT_STATI
```
###Assistant : True if this Response is a well-formed HTTP r... |
1,505 | def write_eqapo_graphic_eq(self, file_path, normalize=True):
file_path = os.path.abspath(file_path)
s = self.eqapo_graphic_eq(normalize=normalize)
with open(file_path, 'w', encoding='utf-8') as f:
f.write(s)
return s
| Writes equalization graph to a file as Equalizer APO config. | 10 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def write_eqapo_graphic_eq(self, file_path, normalize=True):
file_path = os.path.abspath(file_path)
s = self.eqapo_graphic_eq(normalize=normalize)
with open(... |
1,506 | def test_export_pipeline_6():
pipeline_string = (
'DecisionTreeClassifier(SelectPercentile(input_matrix, SelectPercentile__percentile=20),'
'DecisionTreeClassifier__criterion=gini, DecisionTreeClassifier__max_depth=8,'
'DecisionTreeClassifier__min_samples_leaf=5, DecisionTreeClassifier... | Assert that exported_pipeline() generated a compile source file with random_state and data_file_path.import numpy as np
import pandas as pd
from sklearn.feature_selection import SelectPercentile, f_classif
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.tree ... | 102 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_export_pipeline_6():
pipeline_string = (
'DecisionTreeClassifier(SelectPercentile(input_matrix, SelectPercentile__percentile=20),'
'DecisionTreeClassifier_... |
1,507 | def _check_edge_connectivity(G):
# Construct the auxiliary graph that can be used to make each k-cc or k-sub
aux_graph = EdgeComponentAuxGraph.construct(G)
# memoize the local connectivity in this graph
memo = {}
for k in it.count(1):
# Test "local" k-edge-components and k-edge-subgra... |
Helper - generates all k-edge-components using the aux graph. Checks the
both local and subgraph edge connectivity of each cc. Also checks that
alternate methods of computing the k-edge-ccs generate the same result.
| 33 | 275 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _check_edge_connectivity(G):
# Construct the auxiliary graph that can be used to make each k-cc or k-sub
aux_graph = EdgeComponentAuxGraph.construct(G)
# memoize the lo... |
1,508 | def test_sequence_name_length_limits_flush(self):
# A full flush is expensive to the full test, so we dig into the
# internals to generate the likely offending SQL and run it manually
# Some convenience aliases
VLM = VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
... |
Sequence resetting as part of a flush with model with long name and
long pk name doesn't error (#8901).
| 19 | 53 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_sequence_name_length_limits_flush(self):
# A full flush is expensive to the full test, so we dig into the
# internals to generate the likely offending SQL a... |
1,509 | def test_delete_media(self) -> None:
download_resource = self.media_repo.children[b"download"]
upload_resource = self.media_repo.children[b"upload"]
# Upload some media into the room
response = self.helper.upload_media(
upload_resource,
SMALL_PNG,
... |
Tests that delete a media is successfully
| 7 | 159 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_delete_media(self) -> None:
download_resource = self.media_repo.children[b"download"]
upload_resource = self.media_repo.children[b"upload"]
# Uplo... |
1,510 | def load_data_for_viz(load_type, model_file_statistics, **kwargs):
supported_load_types = dict(
load_json=load_json,
load_from_file=partial(
load_from_file, dtype=kwargs.get("dtype", int), ground_truth_split=kwargs.get("ground_truth_split", 2)
),
)
loader = supported... | Load model file data in to list of .
:param load_type: type of the data loader to be used.
:param model_file_statistics: JSON file or list of json files containing any
model experiment stats.
:return List of training statistics loaded as json objects.
| 42 | 40 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def load_data_for_viz(load_type, model_file_statistics, **kwargs):
supported_load_types = dict(
load_json=load_json,
load_from_file=partial(
load_from_fi... |
1,511 | def scan_vocab(self, corpus_iterable=None, corpus_file=None, progress_per=100000, trim_rule=None):
logger.info("collecting all words and their counts")
if corpus_file is not None:
corpus_iterable = TaggedLineDocument(corpus_file)
total_words, corpus_count = self._scan_vocab... | Create the model's vocabulary: a mapping from unique words in the corpus to their frequency count.
Parameters
----------
documents : iterable of :class:`~gensim.models.doc2vec.TaggedDocument`, optional
The tagged documents used to create the vocabulary. Their tags can be either str ... | 218 | 52 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def scan_vocab(self, corpus_iterable=None, corpus_file=None, progress_per=100000, trim_rule=None):
logger.info("collecting all words and their counts")
if corpus_fil... |
1,512 | def _parse_command_opts(self, parser, args):
# late import because of mutual dependence between these modules
from distutils.cmd import Command
# Pull the current command from the head of the command line
command = args[0]
if not command_re.match(command):
r... | Parse the command-line options for a single command.
'parser' must be a FancyGetopt instance; 'args' must be the list
of arguments, starting with the current command (whose options
we are about to parse). Returns a new version of 'args' with
the next command at the front of the list; wi... | 75 | 337 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _parse_command_opts(self, parser, args):
# late import because of mutual dependence between these modules
from distutils.cmd import Command
# Pull the c... |
1,513 | def interval(self, confidence=None, *args, **kwds):
# This function was originally written with parameter `alpha`, but
# `alpha` is also the name of a shape parameter of two distributions.
# This block allows the function to accept both `alpha` and its
# replacement `confidence`... | Confidence interval with equal areas around the median.
.. deprecated:: 1.9.0
Parameter `alpha` is replaced by parameter `confidence` to avoid
name collisions with the shape parameter `alpha` of some
distributions. Parameter `alpha` will be removed in the second
rele... | 128 | 213 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def interval(self, confidence=None, *args, **kwds):
# This function was originally written with parameter `alpha`, but
# `alpha` is also the name of a shape paramete... |
1,514 | def __call__(self) -> bool:
for meta in tqdm(self._face_alignments,
desc="Updating Alignments File from PNG Header",
leave=False):
src = meta["source"]
alignment = meta["alignments"]
if not any(alignment.get(key, {}) ... | Parse through the face data updating any entries in the alignments file.
Returns
-------
bool
``True`` if any alignment information was updated otherwise ``False``
| 24 | 80 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __call__(self) -> bool:
for meta in tqdm(self._face_alignments,
desc="Updating Alignments File from PNG Header",
leave=... |
1,515 | def test_dynamic_path(self):
doc = Document.objects.create(
title="does not matter",
created=timezone.make_aware(datetime.datetime(2020, 6, 25, 7, 36, 51, 153)),
mime_type="application/pdf",
pk=2,
checksum="2",
storage_path=Storage... |
GIVEN:
- A document with a defined storage path
WHEN:
- the filename is generated for the document
THEN:
- the generated filename uses the defined storage path for the document
| 31 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_dynamic_path(self):
doc = Document.objects.create(
title="does not matter",
created=timezone.make_aware(datetime.datetime(2020, 6, 25, 7, 36... |
1,516 | async def follower_loop(self):
try:
await self._connect_to_leaders()
except Exception as e:
logger.error("Exception occurred in follower loop: ")
logger.exception(e)
|
Main follower coroutine
This starts all of the leader connection coros
| 11 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def follower_loop(self):
try:
await self._connect_to_leaders()
except Exception as e:
logger.error("Exception occurred in follower loop... |
1,517 | def test_launcher_ensures_stdio(self):
from kitty.constants import kitty_exe
import subprocess
exe = kitty_exe()
cp = subprocess.run([exe, '+runpy', ])
self.assertEqual(cp.returncode, 0)
| \
import os, sys
if sys.stdin:
os.close(sys.stdin.fileno())
if sys.stdout:
os.close(sys.stdout.fileno())
if sys.stderr:
os.close(sys.stderr.fileno())
os.execlp('kitty', 'kitty', '+runpy', 'import sys; raise SystemExit(1 if sys.stdout is None or sys.stdin is None or sys.stderr is None else 0)')
| 34 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_launcher_ensures_stdio(self):
from kitty.constants import kitty_exe
import subprocess
exe = kitty_exe()
cp = subprocess.run([exe, '+runpy', ])
... |
1,518 | def test_interface_label_count_mismatch(self):
bad_interface_data = {
'device': self.device.pk,
'name': 'eth[0-9]',
'label': 'Interface[0-1]',
'type': InterfaceTypeChoices.TYPE_1GE_GBIC,
}
form = InterfaceCreateForm(bad_interface_data)
... |
Check that attempting to generate a differing number of names and labels results in a validation error.
| 17 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_interface_label_count_mismatch(self):
bad_interface_data = {
'device': self.device.pk,
'name': 'eth[0-9]',
'label': 'Interface[0... |
1,519 | def power_transform(X, method="yeo-johnson", *, standardize=True, copy=True):
pt = PowerTransformer(method=method, standardize=standardize, copy=copy)
return pt.fit_transform(X)
| Parametric, monotonic transformation to make data more Gaussian-like.
Power transforms are a family of parametric, monotonic transformations
that are applied to make data more Gaussian-like. This is useful for
modeling issues related to heteroscedasticity (non-constant variance),
or other situations wh... | 421 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def power_transform(X, method="yeo-johnson", *, standardize=True, copy=True):
pt = PowerTransformer(method=method, standardize=standardize, copy=copy)
return pt.fit_transform(X)... |
1,520 | def desargues_graph(create_using=None):
G = LCF_graph(20, [5, -5, 9, -9], 5, create_using)
G.name = "Desargues Graph"
return G
|
Returns the Desargues Graph
The Desargues Graph is a non-planar, distance-transitive cubic graph
with 20 nodes and 30 edges [1]_.
It is a symmetric graph. It can be represented in LCF notation
as [5,-5,9,-9]^5 [2]_.
Parameters
----------
create_using : NetworkX graph constructor, opti... | 77 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def desargues_graph(create_using=None):
G = LCF_graph(20, [5, -5, 9, -9], 5, create_using)
G.name = "Desargues Graph"
return G
```
###Assistant :
Returns ... |
1,521 | def get_output_feature_jsonschema():
output_feature_types = sorted(list(output_type_registry.keys()))
return {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"type": {"type": "string", "enum":... | This function returns a JSON schema structured to only requires a `type` key and then conditionally applies
a corresponding output feature's field constraints.
Returns: JSON Schema
| 26 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_output_feature_jsonschema():
output_feature_types = sorted(list(output_type_registry.keys()))
return {
"type": "array",
"items": {
"type": "o... |
1,522 | def greet(str):
return str
with gr.Blocks() as demo:
with gr.Row():
text1 = gr.component("textarea")
text2 = gr.TextArea()
text3 = gr.templates.TextArea()
text1.change(greet, text1, text2)
text2.change(greet, text2, text3)
text3.change(greet, text3, text1)
... |
You can make use of str shortcuts you use in Interface within Blocks as well.
Interface shortcut example:
Interface(greet, "textarea", "textarea")
You can use
1. gr.component()
2. gr.templates.Template()
3. gr.Template()
All the templates are listed in gradio/templates.py
... | 37 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def greet(str):
return str
with gr.Blocks() as demo:
with gr.Row():
text1 = gr.component("textarea")
text2 = gr.TextArea()
text3 = gr.templ... |
1,523 | def _impute_values(self, features):
if self.verbosity > 1:
print("Imputing missing values in feature set")
if self._fitted_imputer is None:
self._fitted_imputer = SimpleImputer(strategy="median")
self._fitted_imputer.fit(features)
return self._fitte... | Impute missing values in a feature set.
Parameters
----------
features: array-like {n_samples, n_features}
A feature matrix
Returns
-------
array-like {n_samples, n_features}
| 21 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _impute_values(self, features):
if self.verbosity > 1:
print("Imputing missing values in feature set")
if self._fitted_imputer is None:
... |
1,524 | def get_current_site(request):
# Import is inside the function because its point is to avoid importing the
# Site models when django.contrib.sites isn't installed.
if apps.is_installed("django.contrib.sites"):
from .models import Site
return Site.objects.get_current(request)
else:
... |
Check if contrib.sites is installed and return either the current
``Site`` object or a ``RequestSite`` object based on the request.
| 20 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_current_site(request):
# Import is inside the function because its point is to avoid importing the
# Site models when django.contrib.sites isn't installed.
if apps.i... |
1,525 | def get_scripts(use_names=False):
scripts = OrderedDict()
# Iterate through all modules within the scripts path. These are the user-created files in which reports are
# defined.
for importer, module_name, _ in pkgutil.iter_modules([settings.SCRIPTS_ROOT]):
# Remove cached module to ensure c... |
Return a dict of dicts mapping all scripts to their modules. Set use_names to True to use each module's human-
defined name in place of the actual module name.
| 29 | 103 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_scripts(use_names=False):
scripts = OrderedDict()
# Iterate through all modules within the scripts path. These are the user-created files in which reports are
# defi... |
1,526 | def render(self, template_name, extra_context=None):
if extra_context is None:
extra_context = {}
elif not isinstance(extra_context, dict):
raise TypeError("extra_context must be a dictionary")
return get_template(template_name).render({**self.context, **extra_c... |
Convenience method for rendering the specified Django template using the default context data. An additional
context dictionary may be passed as `extra_context`.
| 22 | 24 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def render(self, template_name, extra_context=None):
if extra_context is None:
extra_context = {}
elif not isinstance(extra_context, dict):
r... |
1,527 | def preprocess_input(x, data_format=None):
return x
@keras_export("keras.applications.mobilenet_v3.decode_predictions") | A placeholder method for backward compatibility.
The preprocessing logic has been included in the mobilenet_v3 model
implementation. Users are no longer required to call this method to
normalize the input data. This method does nothing and only kept as a
placeholder to align the API surface between old... | 95 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def preprocess_input(x, data_format=None):
return x
@keras_export("keras.applications.mobilenet_v3.decode_predictions")
```
###Assistant : A placeholder method for bac... |
1,528 | def message_level_tag(message):
return MESSAGE_TAGS.get(message.level)
@register.simple_tag |
Return the tag for this message's level as defined in
django.contrib.messages.constants.DEFAULT_TAGS, ignoring the project-level
MESSAGE_TAGS setting (which end-users might customise).
| 20 | 5 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def message_level_tag(message):
return MESSAGE_TAGS.get(message.level)
@register.simple_tag
```
###Assistant :
Return the tag for this message's level as defined ... |
1,529 | def _check_reg_targets(y_true, y_pred, multioutput, dtype="numeric"):
check_consistent_length(y_true, y_pred)
y_true = check_array(y_true, ensure_2d=False, dtype=dtype)
y_pred = check_array(y_pred, ensure_2d=False, dtype=dtype)
if y_true.ndim == 1:
y_true = y_true.reshape((-1, 1))
if ... | Check that y_true and y_pred belong to the same regression task.
Parameters
----------
y_true : array-like
y_pred : array-like
multioutput : array-like or string in ['raw_values', uniform_average',
'variance_weighted'] or None
None is accepted due to backward compatibility of r2_s... | 124 | 141 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _check_reg_targets(y_true, y_pred, multioutput, dtype="numeric"):
check_consistent_length(y_true, y_pred)
y_true = check_array(y_true, ensure_2d=False, dtype=dtype)
y_pr... |
1,530 | def bind(self, *args, **kwargs) -> Union[ClassNode, FunctionNode]:
copied_self = copy(self)
copied_self._func_or_class = "dummpy.module"
schema_shell = deployment_to_schema(copied_self)
if inspect.isfunction(self._func_or_class):
return FunctionNode(
... | Bind the provided arguments and return a class or function node.
The returned bound deployment can be deployed or bound to other
deployments to create a deployment graph.
| 28 | 73 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def bind(self, *args, **kwargs) -> Union[ClassNode, FunctionNode]:
copied_self = copy(self)
copied_self._func_or_class = "dummpy.module"
schema_shell = depl... |
1,531 | def _obtain_mask(cls, detected_face, mask_type):
mask = detected_face.mask.get(mask_type)
if not mask:
return None
if mask.stored_centering != "face":
face = AlignedFace(detected_face.landmarks_xy)
mask.set_sub_crop(face.pose.offset[mask.stored_center... | Obtain the mask for the correct "face" centering that is used in the thumbnail display.
Parameters
-----------
detected_face: :class:`lib.align.DetectedFace`
The Detected Face object to obtain the mask for
mask_type: str
The type of mask to obtain
Retur... | 54 | 24 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _obtain_mask(cls, detected_face, mask_type):
mask = detected_face.mask.get(mask_type)
if not mask:
return None
if mask.stored_centering != "f... |
1,532 | def forward(self, input, mask=None):
forward_input, backward_input = paddle.chunk(input, chunks=2, axis=2)
# elementwise-sum forward_x and backward_x
# Shape: (batch_size, max_seq_len, hidden_size)
h = paddle.add_n([forward_input, backward_input])
# Shape: (batch_size, h... |
Args:
input (paddle.Tensor) of shape (batch, seq_len, input_size): Tensor containing the features of the input sequence.
mask (paddle.Tensor) of shape (batch, seq_len) :
Tensor is a bool tensor, whose each element identifies whether the input word id is pad token or not.... | 45 | 104 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def forward(self, input, mask=None):
forward_input, backward_input = paddle.chunk(input, chunks=2, axis=2)
# elementwise-sum forward_x and backward_x
# Shape... |
1,533 | def simple_test(self, feats, img_metas, **kwargs):
all_cls_scores, all_mask_preds = self(feats, img_metas)
mask_cls_results = all_cls_scores[-1]
mask_pred_results = all_mask_preds[-1]
# upsample masks
img_shape = img_metas[0]['batch_input_shape']
mask_pred_resul... | Test without augmentaton.
Args:
feats (list[Tensor]): Multi-level features from the
upstream network, each is a 4D-tensor.
img_metas (list[dict]): List of image information.
Returns:
tuple: A tuple contains two tensors.
- mask_cls_result... | 55 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def simple_test(self, feats, img_metas, **kwargs):
all_cls_scores, all_mask_preds = self(feats, img_metas)
mask_cls_results = all_cls_scores[-1]
mask_pred_re... |
1,534 | def _format_list(self, extracted_list):
Colors = self.Colors
list = []
for ind, (filename, lineno, name, line) in enumerate(extracted_list):
normalCol, nameCol, fileCol, lineCol = (
# Emphasize the last entry
(Colors.normalEm, Colors.nameEm, ... | Format a list of traceback entry tuples for printing.
Given a list of tuples as returned by extract_tb() or
extract_stack(), return a list of strings ready for printing.
Each string in the resulting list corresponds to the item with the
same index in the argument list. Each string ends... | 75 | 76 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _format_list(self, extracted_list):
Colors = self.Colors
list = []
for ind, (filename, lineno, name, line) in enumerate(extracted_list):
nor... |
1,535 | def euler_equations(L, funcs=(), vars=()):
r
funcs = tuple(funcs) if iterable(funcs) else (funcs,)
if not funcs:
funcs = tuple(L.atoms(Function))
else:
for f in funcs:
if not isinstance(f, Function):
raise TypeError('Function expected, got: %s' % f)
var... |
Find the Euler-Lagrange equations [1]_ for a given Lagrangian.
Parameters
==========
L : Expr
The Lagrangian that should be a function of the functions listed
in the second argument and their derivatives.
For example, in the case of two functions `f(x,y)`, `g(x,y)` and
... | 224 | 146 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def euler_equations(L, funcs=(), vars=()):
r
funcs = tuple(funcs) if iterable(funcs) else (funcs,)
if not funcs:
funcs = tuple(L.atoms(Function))
else:
for ... |
1,536 | def delay_update(self, skip_if_already_set=False, **kwargs):
for key, value in kwargs.items():
if key in self.extra_update_fields and skip_if_already_set:
continue
elif key in self.extra_update_fields and key in ('job_explanation', 'result_traceback'):
... | Stash fields that should be saved along with the job status change | 12 | 65 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def delay_update(self, skip_if_already_set=False, **kwargs):
for key, value in kwargs.items():
if key in self.extra_update_fields and skip_if_already_set:
... |
1,537 | def adjacent_tmp_file(path, **kwargs):
# type: (str, **Any) -> Iterator[BinaryIO]
with NamedTemporaryFile(
delete=False,
dir=os.path.dirname(path),
prefix=os.path.basename(path),
suffix=".tmp",
**kwargs,
) as f:
result = cast(BinaryIO, f)
try:
... | Return a file-like object pointing to a tmp file next to path.
The file is created securely and is ensured to be written to disk
after the context reaches its end.
kwargs will be passed to tempfile.NamedTemporaryFile to control
the way the temporary file will be opened.
| 47 | 68 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def adjacent_tmp_file(path, **kwargs):
# type: (str, **Any) -> Iterator[BinaryIO]
with NamedTemporaryFile(
delete=False,
dir=os.path.dirname(path),
prefi... |
1,538 | def _lsb_release_info(self):
# type: () -> Dict[str, str]
if not self.include_lsb:
return {}
with open(os.devnull, "wb") as devnull:
try:
cmd = ("lsb_release", "-a")
stdout = subprocess.check_output(cmd, stderr=devnull)
... |
Get the information items from the lsb_release command output.
Returns:
A dictionary containing all information items.
| 16 | 45 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _lsb_release_info(self):
# type: () -> Dict[str, str]
if not self.include_lsb:
return {}
with open(os.devnull, "wb") as devnull:
... |
1,539 | def as_dict(self) -> Dict[Text, Any]:
serializable_graph_schema: Dict[Text, Dict[Text, Any]] = {"nodes": {}}
for node_name, node in self.nodes.items():
serializable = dataclasses.asdict(node)
# Classes are not JSON serializable (surprise)
serializable["uses"... | Returns graph schema in a serializable format.
Returns:
The graph schema in a format which can be dumped as JSON or other formats.
| 23 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def as_dict(self) -> Dict[Text, Any]:
serializable_graph_schema: Dict[Text, Dict[Text, Any]] = {"nodes": {}}
for node_name, node in self.nodes.items():
s... |
1,540 | def _create_project_state(self, with_applied_migrations=False):
state = ProjectState(real_apps=self.loader.unmigrated_apps)
if with_applied_migrations:
# Create the forwards plan Django would follow on an empty database
full_plan = self.migration_plan(
se... |
Create a project state including all the applications without
migrations and applied migrations if with_applied_migrations=True.
| 15 | 52 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _create_project_state(self, with_applied_migrations=False):
state = ProjectState(real_apps=self.loader.unmigrated_apps)
if with_applied_migrations:
#... |
1,541 | def revoke(state, task_id, terminate=False, signal=None, **kwargs):
# pylint: disable=redefined-outer-name
# XXX Note that this redefines `terminate`:
# Outside of this scope that is a function.
# supports list argument since 3.1
task_ids, task_id = set(maybe_list(task_id) or []), None
... | Revoke task by task id (or list of ids).
Keyword Arguments:
terminate (bool): Also terminate the process if the task is active.
signal (str): Name of signal to use for terminate (e.g., ``KILL``).
| 33 | 58 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def revoke(state, task_id, terminate=False, signal=None, **kwargs):
# pylint: disable=redefined-outer-name
# XXX Note that this redefines `terminate`:
# Outside of this ... |
1,542 | def inplace_swap_row_csc(X, m, n):
for t in [m, n]:
if isinstance(t, np.ndarray):
raise TypeError("m and n should be valid integers")
if m < 0:
m += X.shape[0]
if n < 0:
n += X.shape[0]
m_mask = X.indices == m
X.indices[X.indices == n] = m
X.indices[m_m... | Swap two rows of a CSC matrix in-place.
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
Matrix whose two rows are to be swapped. It should be of
CSC format.
m : int
Index of the row of X to be swapped.
n : int
Index of the row of X to be sw... | 56 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def inplace_swap_row_csc(X, m, n):
for t in [m, n]:
if isinstance(t, np.ndarray):
raise TypeError("m and n should be valid integers")
if m < 0:
m +=... |
1,543 | def test_render_empty_table(self):
block = TableBlock()
result = block.render(
{
"first_row_is_table_header": False,
"first_col_is_header": False,
"data": [[None, None, None], [None, None, None], [None, None, None]],
}
... |
An empty table should render okay.
<table>
<tbody>
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td></tr>
</tbody>
</table>
... | 13 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_render_empty_table(self):
block = TableBlock()
result = block.render(
{
"first_row_is_table_header": False,
"fir... |
1,544 | def rot_axis3(theta):
ct = cos(theta)
st = sin(theta)
lil = ((ct, st, 0),
(-st, ct, 0),
(0, 0, 1))
return Matrix(lil)
| Returns a rotation matrix for a rotation of theta (in radians) about
the 3-axis.
Examples
========
>>> from sympy import pi, rot_axis3
A rotation of pi/3 (60 degrees):
>>> theta = pi/3
>>> rot_axis3(theta)
Matrix([
[ 1/2, sqrt(3)/2, 0],
[-sqrt(3)/2, 1/2, 0],
[... | 100 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def rot_axis3(theta):
ct = cos(theta)
st = sin(theta)
lil = ((ct, st, 0),
(-st, ct, 0),
(0, 0, 1))
return Matrix(lil)
```
###Assistan... |
1,545 | def current(self):
rv = self._current or '0'
if not isinstance(rv, str):
rv = bin(rv)[2:]
return rv.rjust(self.n, '0')
|
Returns the currently referenced Gray code as a bit string.
Examples
========
>>> from sympy.combinatorics import GrayCode
>>> GrayCode(3, start='100').current
'100'
| 21 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def current(self):
rv = self._current or '0'
if not isinstance(rv, str):
rv = bin(rv)[2:]
return rv.rjust(self.n, '0')
```
###Assist... |
1,546 | def upsample_conv_2d(x, w, k=None, factor=2, gain=1):
assert isinstance(factor, int) and factor >= 1
# Check weight shape.
assert len(w.shape) == 4
convH = w.shape[2]
convW = w.shape[3]
inC = w.shape[1]
assert convW == convH
# Setup filter kernel.
if k is None:
k = [... | Fused `upsample_2d()` followed by `tf.nn.conv2d()`.
Padding is performed only once at the beginning, not between the
operations.
The fused op is considerably more efficient than performing the same
calculation
using standard TensorFlow ops. It supports gradients of arbitrary order.
Args:
... | 139 | 210 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def upsample_conv_2d(x, w, k=None, factor=2, gain=1):
assert isinstance(factor, int) and factor >= 1
# Check weight shape.
assert len(w.shape) == 4
convH = w.shape[2]
... |
1,547 | def read(self, size=None):
if size is None:
t = []
while True:
buf = self._read(self.bufsize)
if not buf:
break
t.append(buf)
buf = "".join(t)
else:
buf = self._read(size)
... | Return the next size number of bytes from the stream.
If size is not defined, return all bytes of the stream
up to EOF.
| 24 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def read(self, size=None):
if size is None:
t = []
while True:
buf = self._read(self.bufsize)
if not buf:
... |
1,548 | def state(self) -> Mapping[str, Any]:
if self._cursor_value:
return {
self.cursor_field: self._cursor_value,
"include_deleted": self._include_deleted,
}
return {}
| State getter, get current state and serialize it to emmit Airbyte STATE message | 13 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def state(self) -> Mapping[str, Any]:
if self._cursor_value:
return {
self.cursor_field: self._cursor_value,
"include_deleted": s... |
1,549 | def set_task_factory(self, factory):
if factory is not None and not callable(factory):
raise TypeError('task factory must be a callable or None')
self._task_factory = factory
| Set a task factory that will be used by loop.create_task().
If factory is None the default task factory will be set.
If factory is a callable, it should have a signature matching
'(loop, coro)', where 'loop' will be a reference to the active
event loop, 'coro' will be a coroutine objec... | 57 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_task_factory(self, factory):
if factory is not None and not callable(factory):
raise TypeError('task factory must be a callable or None')
self._t... |
1,550 | def date(self) -> npt.NDArray[np.object_]:
# If the Timestamps have a timezone that is not UTC,
# convert them into their i8 representation while
# keeping their timezone and not using UTC
timestamps = self._local_timestamps()
return ints_to_pydatetime(timestamps, box="... |
Returns numpy array of python :class:`datetime.date` objects.
Namely, the date part of Timestamps without time and
timezone information.
| 18 | 37 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def date(self) -> npt.NDArray[np.object_]:
# If the Timestamps have a timezone that is not UTC,
# convert them into their i8 representation while
# keeping t... |
1,551 | def apply_transparency(self):
if self.mode != "P" or "transparency" not in self.info:
return
from . import ImagePalette
palette = self.getpalette("RGBA")
transparency = self.info["transparency"]
if isinstance(transparency, bytes):
for i, alpha i... |
If a P mode image has a "transparency" key in the info dictionary,
remove the key and apply the transparency to the palette instead.
| 24 | 54 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def apply_transparency(self):
if self.mode != "P" or "transparency" not in self.info:
return
from . import ImagePalette
palette = self.getpalet... |
1,552 | def get_frontend_app_asset_url(module, key):
args = (settings.STATIC_FRONTEND_APP_URL.rstrip("/"), module, key.lstrip("/"))
return "{}/{}/{}".format(*args)
|
Returns an asset URL that is unversioned. These assets should have a
`Cache-Control: max-age=0, must-revalidate` so that clients must validate with the origin
server before using their locally cached asset.
Example:
{% frontend_app_asset_url 'sentry' 'sentry.css' %}
=> "/_static/dist/sent... | 38 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_frontend_app_asset_url(module, key):
args = (settings.STATIC_FRONTEND_APP_URL.rstrip("/"), module, key.lstrip("/"))
return "{}/{}/{}".format(*args)
```
##... |
1,553 | def tridiagonal_solve(dl, d, du, b):
r
if dl.ndim != 1 or d.ndim != 1 or du.ndim != 1:
raise ValueError('dl, d and du must be vectors')
if dl.shape != d.shape or d.shape != du.shape:
raise ValueError(
f'dl={dl.shape}, d={d.shape} and du={du.shape} must all be `[m]`')
if b.ndim != 2:
raise ... | Computes the solution of a tridiagonal linear system.
This function computes the solution of a tridiagonal linear system:
.. math::
A . X = B
Args:
dl: The lower diagonal of A: ``dl[i] := A[i, i-1]`` for i in ``[0,m)``.
Note that ``dl[0] = 0``.
d: The middle diagnoal of A: ``d[i] := A[i, i]`... | 91 | 139 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def tridiagonal_solve(dl, d, du, b):
r
if dl.ndim != 1 or d.ndim != 1 or du.ndim != 1:
raise ValueError('dl, d and du must be vectors')
if dl.shape != d.shape or d.shape != du.sha... |
1,554 | def _get_dependency_info() -> dict[str, JSONSerializable]:
deps = [
"pandas",
# required
"numpy",
"pytz",
"dateutil",
# install / build,
"setuptools",
"pip",
"Cython",
# test
"pytest",
"hypothesis",
# docs
... |
Returns dependency information as a JSON serializable dictionary.
| 8 | 72 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_dependency_info() -> dict[str, JSONSerializable]:
deps = [
"pandas",
# required
"numpy",
"pytz",
"dateutil",
# install / bui... |
1,555 | def execute():
company_list = frappe.get_all("Company", filters={"country": "Germany"})
for company in company_list:
party_account_list = frappe.get_all(
"Party Account",
filters={"company": company.name},
fields=["name", "account", "debtor_creditor_number"],
)
for party_account in party_account_lis... | Move account number into the new custom field debtor_creditor_number.
German companies used to use a dedicated payable/receivable account for
every party to mimick party accounts in the external accounting software
"DATEV". This is no longer necessary. The reference ID for DATEV will be
stored in a new custom fiel... | 50 | 60 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def execute():
company_list = frappe.get_all("Company", filters={"country": "Germany"})
for company in company_list:
party_account_list = frappe.get_all(
"Party Account",
filter... |
1,556 | def compute_or_load(self, wav_file):
pitch_file = self.create_pitch_file_path(wav_file, self.cache_path)
if not os.path.exists(pitch_file):
pitch = self._compute_and_save_pitch(self.ap, wav_file, pitch_file)
else:
pitch = np.load(pitch_file)
return pitch.... |
compute pitch and return a numpy array of pitch values
| 10 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def compute_or_load(self, wav_file):
pitch_file = self.create_pitch_file_path(wav_file, self.cache_path)
if not os.path.exists(pitch_file):
pitch = self.... |
1,557 | def check_output(self, want, got, optionflags):
# Handle the common case first, for efficiency:
# if they're string-identical, always return true.
if got == want:
return True
# TODO parse integers as well ?
# Parse floats and compare them. If some of the par... |
Return True iff the actual output from an example (`got`)
matches the expected output (`want`). These strings are
always considered to match if they are identical; but
depending on what option flags the test runner is using,
several non-exact match types are also possible. See... | 55 | 272 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def check_output(self, want, got, optionflags):
# Handle the common case first, for efficiency:
# if they're string-identical, always return true.
if got == ... |
1,558 | def start(self, workflow_state, user=None):
task_state = self.get_task_state_class()(workflow_state=workflow_state)
task_state.status = TaskState.STATUS_IN_PROGRESS
task_state.page_revision = workflow_state.page.get_latest_revision()
task_state.task = self
task_state.sav... | Start this task on the provided workflow state by creating an instance of TaskState | 14 | 24 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def start(self, workflow_state, user=None):
task_state = self.get_task_state_class()(workflow_state=workflow_state)
task_state.status = TaskState.STATUS_IN_PROGRESS
... |
1,559 | def get_datev_csv(data, filters, csv_class):
empty_df = pd.DataFrame(columns=csv_class.COLUMNS)
data_df = pd.DataFrame.from_records(data)
result = empty_df.append(data_df, sort=True)
if csv_class.DATA_CATEGORY == DataCategory.TRANSACTIONS:
result["Belegdatum"] = pd.to_datetime(result["Belegdatum"])
result["... |
Fill in missing columns and return a CSV in DATEV Format.
For automatic processing, DATEV requires the first line of the CSV file to
hold meta data such as the length of account numbers oder the category of
the data.
Arguments:
data -- array of dictionaries
filters -- dict
csv_class -- defines DATA_CATEGORY,... | 56 | 155 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_datev_csv(data, filters, csv_class):
empty_df = pd.DataFrame(columns=csv_class.COLUMNS)
data_df = pd.DataFrame.from_records(data)
result = empty_df.append(data_df, sort=True)
... |
1,560 | def CircularSymplecticEnsemble(sym, dim):
sym, dim = _symbol_converter(sym), _sympify(dim)
model = CircularSymplecticEnsembleModel(sym, dim)
rmp = RandomMatrixPSpace(sym, model=model)
return RandomMatrixSymbol(sym, dim, dim, pspace=rmp)
|
Represents Circular Symplectic Ensembles.
Examples
========
>>> from sympy.stats import CircularSymplecticEnsemble as CSE
>>> from sympy.stats import joint_eigen_distribution
>>> C = CSE('S', 1)
>>> joint_eigen_distribution(C)
Lambda(t[1], Product(Abs(exp(I*t[_j]) - exp(I*t[_k]))**4, ... | 69 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def CircularSymplecticEnsemble(sym, dim):
sym, dim = _symbol_converter(sym), _sympify(dim)
model = CircularSymplecticEnsembleModel(sym, dim)
rmp = RandomMatrixPSpace(sym, mo... |
1,561 | def _executor_config_comparator(x, y):
try:
return x == y
except AttributeError:
return False
|
The TaskInstance.executor_config attribute is a pickled object that may contain
kubernetes objects. If the installed library version has changed since the
object was originally pickled, due to the underlying ``__eq__`` method on these
objects (which converts them to JSON), we may encounter attribute e... | 53 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _executor_config_comparator(x, y):
try:
return x == y
except AttributeError:
return False
```
###Assistant :
The TaskInstance.executor_con... |
1,562 | def test_color_temperature_to_rgbww():
# Coldest color temperature -> only cold channel enabled
assert color_util.color_temperature_to_rgbww(6535, 255, 2000, 6535) == (
0,
0,
0,
255,
0,
)
assert color_util.color_temperature_to_rgbww(6535, 128, 2000, 6535) == ... | Test color temp to warm, cold conversion.
Temperature values must be in mireds
Home Assistant uses rgbcw for rgbww
| 19 | 112 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_color_temperature_to_rgbww():
# Coldest color temperature -> only cold channel enabled
assert color_util.color_temperature_to_rgbww(6535, 255, 2000, 6535) == (
... |
1,563 | def test_set_page_config_first(self):
fake_enqueue = lambda msg: None
ctx = ScriptRunContext(
"TestSessionID",
fake_enqueue,
"",
SessionState(),
UploadedFileManager(),
)
ctx.on_script_start()
markdown_msg = F... | st.set_page_config must be called before other st commands
when the script has been marked as started | 16 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_set_page_config_first(self):
fake_enqueue = lambda msg: None
ctx = ScriptRunContext(
"TestSessionID",
fake_enqueue,
"",... |
1,564 | def set_vars(self) -> None:
tk_vars = super().set_vars()
smoothgraph = tk.DoubleVar()
smoothgraph.set(0.900)
tk_vars["smoothgraph"] = smoothgraph
raw_var = tk.BooleanVar()
raw_var.set(True)
tk_vars["raw_data"] = raw_var
smooth_var = tk.BooleanV... | Add graphing specific variables to the default variables.
Overrides original method.
Returns
-------
dict
The variable names with their corresponding tkinter variable
| 22 | 38 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_vars(self) -> None:
tk_vars = super().set_vars()
smoothgraph = tk.DoubleVar()
smoothgraph.set(0.900)
tk_vars["smoothgraph"] = smoothgraph
... |
1,565 | def _configure_kubernetes_library_client(self) -> None:
# TODO: Investigate returning a configured client so calls on other threads
# will not invalidate the config needed here
# if a k8s cluster block is provided to the flow runner, use that
if self.cluster_config:
... |
Set the correct kubernetes client configuration.
WARNING: This action is not threadsafe and may override the configuration
specified by another `KubernetesJob` instance.
| 22 | 82 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _configure_kubernetes_library_client(self) -> None:
# TODO: Investigate returning a configured client so calls on other threads
# will not invalidate the c... |
1,566 | def test_runs_alert_rule_action_creator(self, mock_alert_rule_action_creator):
self.login_as(user=self.user)
project = self.create_project()
self.create_sentry_app(
name="Pied Piper",
organization=project.organization,
schema={"elements": [self.crea... |
Ensures that Sentry Apps with schema forms (UI components)
receive a payload when an alert rule is created with them.
| 20 | 116 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_runs_alert_rule_action_creator(self, mock_alert_rule_action_creator):
self.login_as(user=self.user)
project = self.create_project()
self.create_se... |
1,567 | def _determine_interval(self) -> int:
intervals = {"default": self._max_interval}
for device in self._devices.values():
# Max interval if no location
if device.location is None:
continue
current_zone = run_callback_threadsafe(
... | Calculate new interval between two API fetch (in minutes). | 9 | 199 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _determine_interval(self) -> int:
intervals = {"default": self._max_interval}
for device in self._devices.values():
# Max interval if no location
... |
1,568 | def prepare_cookies(self, cookies):
if isinstance(cookies, cookielib.CookieJar):
self._cookies = cookies
else:
self._cookies = cookiejar_from_dict(cookies)
cookie_header = get_cookie_header(self._cookies, self)
if cookie_header is not None:
s... | Prepares the given HTTP cookie data.
This function eventually generates a ``Cookie`` header from the
given cookies using cookielib. Due to cookielib's design, the header
will not be regenerated if it already exists, meaning this function
can only be called once for the life of the
... | 66 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def prepare_cookies(self, cookies):
if isinstance(cookies, cookielib.CookieJar):
self._cookies = cookies
else:
self._cookies = cookiejar_from... |
1,569 | def wait_for_contains_text(self, selector, text, timeout=None):
return self._wait_for(
method=contains_text,
args=(selector, text),
timeout=timeout,
msg=f"text -> {text} not found inside element within {timeout or self._wait_timeout}s",
)
| Explicit wait until the element's text contains the expected `text`.
timeout if not set, equals to the fixture's `wait_timeout`
shortcut to `WebDriverWait` with customized `contains_text`
condition.
| 26 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def wait_for_contains_text(self, selector, text, timeout=None):
return self._wait_for(
method=contains_text,
args=(selector, text),
timeo... |
1,570 | def remove_member(self, label):
if label not in list(self._members):
raise ValueError("No such member exists in the Truss")
else:
self._nodes_occupied.pop(tuple([self._members[label][0], self._members[label][1]]))
self._nodes_occupied.pop(tuple([self._member... |
This method removes a member from the given truss.
Parameters
==========
label: String or Symbol
The label for the member to be removed.
Examples
========
>>> from sympy.physics.continuum_mechanics.truss import Truss
>>> t = Truss()
... | 79 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def remove_member(self, label):
if label not in list(self._members):
raise ValueError("No such member exists in the Truss")
else:
self._node... |
1,571 | def _create_mock_app_session(*args, **kwargs):
mock_id = mock.PropertyMock(
return_value="mock_id:%s" % ServerTestCase._next_session_id
)
ServerTestCase._next_session_id += 1
mock_session = mock.MagicMock(AppSession, autospec=True, *args, **kwargs)
type(mock... | Create a mock AppSession. Each mocked instance will have
its own unique ID. | 13 | 24 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _create_mock_app_session(*args, **kwargs):
mock_id = mock.PropertyMock(
return_value="mock_id:%s" % ServerTestCase._next_session_id
)
ServerT... |
1,572 | def taggedsents_to_conll(sentences):
for sentence in sentences:
yield from taggedsent_to_conll(sentence)
yield "\n\n"
######################################################################
# { Test Suites
######################################################################
|
A module to convert the a POS tagged document stream
(i.e. list of list of tuples, a list of sentences) and yield lines
in CONLL format. This module yields one line per word and two newlines
for end of sentence.
>>> from nltk import word_tokenize, sent_tokenize, pos_tag
>>> text = "This is a f... | 204 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def taggedsents_to_conll(sentences):
for sentence in sentences:
yield from taggedsent_to_conll(sentence)
yield "\n\n"
#############################################... |
1,573 | def _get_input_shape(self):
arch = self.config["enc_architecture"]
enforce_size = _MODEL_MAPPING[arch].get("enforce_for_weights", False)
default_size = _MODEL_MAPPING[arch]["default_size"]
scaling = self.config["enc_scaling"] / 100
min_size = _MODEL_MAPPING[arch].get("m... | Obtain the input shape for the model.
Input shape is calculated from the selected Encoder's input size, scaled to the user
selected Input Scaling, rounded down to the nearest 16 pixels.
Notes
-----
Some models (NasNet) require the input size to be of a certain dimension if loa... | 73 | 82 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_input_shape(self):
arch = self.config["enc_architecture"]
enforce_size = _MODEL_MAPPING[arch].get("enforce_for_weights", False)
default_size = _MODE... |
1,574 | def get_form_options(self):
options = {}
if not getattr(self.widget_overrides, "is_original_method", False):
warn(
"The `widget_overrides` method (on %r) is deprecated; "
"these should be returned from `get_form_options` as a "
"`widg... |
Return a dictionary of attributes such as 'fields', 'formsets' and 'widgets'
which should be incorporated into the form class definition to generate a form
that this EditHandler can use.
This will only be called after binding to a model (i.e. self.model is available).
| 43 | 148 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_form_options(self):
options = {}
if not getattr(self.widget_overrides, "is_original_method", False):
warn(
"The `widget_override... |
1,575 | def evaluate_links(self, link_evaluator, links):
# type: (LinkEvaluator, Iterable[Link]) -> List[InstallationCandidate]
candidates = []
for link in self._sort_links(links):
candidate = self.get_install_candidate(link_evaluator, link)
if candidate is not None:
... |
Convert links that are candidates to InstallationCandidate objects.
| 8 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def evaluate_links(self, link_evaluator, links):
# type: (LinkEvaluator, Iterable[Link]) -> List[InstallationCandidate]
candidates = []
for link in self._sor... |
1,576 | def columnarize(self):
if len(self.columns) != 1 or (
len(self.index) == 1 and self.index[0] == MODIN_UNNAMED_SERIES_LABEL
):
return self.transpose()
return self
|
Transpose this QueryCompiler if it has a single row but multiple columns.
This method should be called for QueryCompilers representing a Series object,
i.e. ``self.is_series_like()`` should be True.
Returns
-------
BaseQueryCompiler
Transposed new QueryComp... | 36 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def columnarize(self):
if len(self.columns) != 1 or (
len(self.index) == 1 and self.index[0] == MODIN_UNNAMED_SERIES_LABEL
):
return self.tra... |
1,577 | def get_formatted_file_tags(self):
# type: () -> List[str]
return sorted(str(tag) for tag in self.file_tags)
| Return the wheel's tags as a sorted list of strings. | 10 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_formatted_file_tags(self):
# type: () -> List[str]
return sorted(str(tag) for tag in self.file_tags)
```
###Assistant : Return the wheel's tags ... |
1,578 | def test_python_render():
syntax = Panel.fit(
Syntax(
CODE,
lexer="python",
line_numbers=True,
line_range=(2, 10),
theme="monokai",
code_width=60,
word_wrap=True,
),
padding=0,
)
rendered_syntax = ren... | Iterate and generate a tuple with a flag for first \x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[48;2;39;40;34m \x1b[0m\x1b[38;2;230;219;116;48;2;39;40;34mand last value. | 15 | 85 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_python_render():
syntax = Panel.fit(
Syntax(
CODE,
lexer="python",
line_numbers=True,
line_range=(2, 10),
the... |
1,579 | def test_state_changes_during_period_multiple_entities_single_test(hass_recorder):
hass = hass_recorder()
start = dt_util.utcnow()
test_entites = {f"sensor.{i}": str(i) for i in range(30)}
for entity_id, value in test_entites.items():
hass.states.set(entity_id, value)
wait_recording_do... | Test state change during period with multiple entities in the same test.
This test ensures the sqlalchemy query cache does not
generate incorrect results.
| 24 | 73 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_state_changes_during_period_multiple_entities_single_test(hass_recorder):
hass = hass_recorder()
start = dt_util.utcnow()
test_entites = {f"sensor.{i}": str(i) for ... |
1,580 | def O(self): # NOQA: E743, E741
if self._no_timezone_or_datetime_is_ambiguous_or_imaginary:
return ""
seconds = self.Z()
sign = "-" if seconds < 0 else "+"
seconds = abs(seconds)
return "%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60)
|
Difference to Greenwich time in hours; e.g. '+0200', '-0430'.
If timezone information is not available, return an empty string.
| 19 | 37 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def O(self): # NOQA: E743, E741
if self._no_timezone_or_datetime_is_ambiguous_or_imaginary:
return ""
seconds = self.Z()
sign = "-" if seconds ... |
1,581 | def convert_mem_str_to_bytes(mem_str):
# If there is no suffix, the memory sourced from the request is in bytes
if mem_str.isdigit():
return int(mem_str)
conversions = {
'Ei': lambda x: x * 2**60,
'E': lambda x: x * 10**18,
'Pi': lambda x: x * 2**50,
'P': lambda... | Convert string with suffix indicating units to memory in bytes (base 2)
Useful for dealing with memory setting that may be expressed in units compatible with
kubernetes.
See https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#meaning-of-memory
| 29 | 155 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def convert_mem_str_to_bytes(mem_str):
# If there is no suffix, the memory sourced from the request is in bytes
if mem_str.isdigit():
return int(mem_str)
conversion... |
1,582 | def sync_status_outbound(self, external_issue, is_resolved, project_id, **kwargs):
client = self.get_client()
jira_issue = client.get_issue(external_issue.key)
jira_project = jira_issue["fields"]["project"]
try:
external_project = IntegrationExternalProject.objects.... |
Propagate a sentry issue's status to a linked issue's status.
| 10 | 103 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def sync_status_outbound(self, external_issue, is_resolved, project_id, **kwargs):
client = self.get_client()
jira_issue = client.get_issue(external_issue.key)
... |
1,583 | def _sci(self, im):
_api.check_isinstance(
(mpl.contour.ContourSet, mcoll.Collection, mimage.AxesImage),
im=im)
if isinstance(im, mpl.contour.ContourSet):
if im.collections[0] not in self._children:
raise ValueError("ContourSet must be in curr... |
Set the current image.
This image will be the target of colormap functions like
``pyplot.viridis``, and other functions such as `~.pyplot.clim`. The
current image is an attribute of the current Axes.
| 31 | 44 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _sci(self, im):
_api.check_isinstance(
(mpl.contour.ContourSet, mcoll.Collection, mimage.AxesImage),
im=im)
if isinstance(im, mpl.contour... |
1,584 | def __dask_postpersist__(self) -> tuple[PostPersistCallable, tuple]:
raise NotImplementedError("Inheriting class must implement this method.")
| Rebuilder function and optional arguments to contruct a persisted collection.
Returns
-------
PostPersistCallable
Callable that rebuilds the collection. The signature
should be
``rebuild(dsk: Mapping, *args: Any, rename: Mapping[str, str] | None)``.
... | 98 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __dask_postpersist__(self) -> tuple[PostPersistCallable, tuple]:
raise NotImplementedError("Inheriting class must implement this method.")
```
###Assistant ... |
1,585 | def execute():
for doctype in ("Sales Order Item", "Bin"):
frappe.reload_doctype(doctype)
repost_for = frappe.db.sql()
for item_code, warehouse in repost_for:
if not (item_code and warehouse):
continue
update_bin_qty(item_code, warehouse, {
"reserved_qty": get_reserved_qty(item_code, warehouse)
})
... |
select
distinct item_code, warehouse
from
(
(
select distinct item_code, warehouse
from `tabSales Order Item` where docstatus=1
) UNION (
select distinct item_code, warehouse
from `tabPacked Item` where docstatus=1 and parenttype='Sales Order'
)
) so_item
where
exis... | 62 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def execute():
for doctype in ("Sales Order Item", "Bin"):
frappe.reload_doctype(doctype)
repost_for = frappe.db.sql()
for item_code, warehouse in repost_for:
if not (item_code and ... |
1,586 | def rename_group_tables_reverse(apps, schema_editor):
Group = apps.get_model("auth", "Group")
schema_editor.alter_db_table(
Group,
"account_group",
"auth_group",
)
PermissionGroup = Group.permissions.through
schema_editor.alter_db_table(
PermissionGroup,
"acco... |
ALTER TABLE account_group RENAME CONSTRAINT account_group_pkey
TO auth_group_pkey;
ALTER TABLE account_group RENAME CONSTRAINT account_group_name_key
TO auth_group_name_key;
ALTER INDEX IF EXISTS account_group_name_034e9f3f_like
RENAME TO auth_group_name_a6ea08ec_like;
ALTER TABLE auth_group_permissions... | 138 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def rename_group_tables_reverse(apps, schema_editor):
Group = apps.get_model("auth", "Group")
schema_editor.alter_db_table(
Group,
"account_group",
"auth_grou... |
1,587 | def test_session_is_accessed(self):
response = self.client.get("/auth_processor_attr_access/")
self.assertContains(response, "Session accessed")
|
The session is accessed if the auth context processor
is used and relevant attributes accessed.
| 15 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_session_is_accessed(self):
response = self.client.get("/auth_processor_attr_access/")
self.assertContains(response, "Session accessed")
```
###... |
1,588 | def _find_vc2017():
root = os.environ.get("ProgramFiles(x86)") or os.environ.get("ProgramFiles")
if not root:
return None, None
try:
path = subprocess.check_output([
os.path.join(root, "Microsoft Visual Studio", "Installer", "vswhere.exe"),
"-latest",
... | Returns "15, path" based on the result of invoking vswhere.exe
If no install is found, returns "None, None"
The version is returned to avoid unnecessarily changing the function
result. It may be ignored when the path is not None.
If vswhere.exe is not available, by definition, VS 2017 is not
insta... | 51 | 71 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _find_vc2017():
root = os.environ.get("ProgramFiles(x86)") or os.environ.get("ProgramFiles")
if not root:
return None, None
try:
path = subprocess.check... |
1,589 | def save_attributes_to_hdf5_group(group, name, data):
# Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
# because in that case even chunking the array would not make the saving
# possible.
bad_attributes = [x for x in data if len(x) > HDF5_OBJECT_HEADER_LIMIT]
# Expectin... | Saves attributes (data) of the specified name into the HDF5 group.
This method deals with an inherent problem of HDF5 file which is not
able to store data larger than HDF5_OBJECT_HEADER_LIMIT bytes.
Args:
group: A pointer to a HDF5 group.
name: A name of the attributes to save.
dat... | 65 | 127 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def save_attributes_to_hdf5_group(group, name, data):
# Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
# because in that case even chunking the array wou... |
1,590 | def dispatch_hook(cls, _pkt=None, *args, **kargs):
if _pkt is not None:
plen = len(_pkt)
if plen >= 2:
byte0, byte1 = struct.unpack("BB", _pkt[:2])
s = kargs.get("tls_session", None)
if byte0 not in _tls_type or byte1 != 3: # Unkn... |
If the TLS class was called on raw SSLv2 data, we want to return an
SSLv2 record instance. We acknowledge the risk of SSLv2 packets with a
msglen of 0x1403, 0x1503, 0x1603 or 0x1703 which will never be casted
as SSLv2 records but TLS ones instead, but hey, we can't be held
respo... | 57 | 165 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def dispatch_hook(cls, _pkt=None, *args, **kargs):
if _pkt is not None:
plen = len(_pkt)
if plen >= 2:
byte0, byte1 = struct.unpack("... |
1,591 | def get_leave_period(from_date, to_date, company):
leave_period = frappe.db.sql(
,
{"from_date": from_date, "to_date": to_date, "company": company},
as_dict=1,
)
if leave_period:
return leave_period
|
select name, from_date, to_date
from `tabLeave Period`
where company=%(company)s and is_active=1
and (from_date between %(from_date)s and %(to_date)s
or to_date between %(from_date)s and %(to_date)s
or (from_date < %(from_date)s and to_date > %(to_date)s))
| 31 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_leave_period(from_date, to_date, company):
leave_period = frappe.db.sql(
,
{"from_date": from_date, "to_date": to_date, "company": company},
as_dict=1,
)
if leave_period:
... |
1,592 | def rows(self) -> Iterator[Dict[str, TensorType]]:
# Do we add seq_lens=[1] to each row?
seq_lens = None if self.get(SampleBatch.SEQ_LENS) is None else np.array([1])
self_as_dict = {k: v for k, v in self.items()}
for i in range(self.count):
yield tree.map_structur... | Returns an iterator over data rows, i.e. dicts with column values.
Note that if `seq_lens` is set in self, we set it to [1] in the rows.
Yields:
The column values of the row in this iteration.
Examples:
>>> batch = SampleBatch({
... "a": [1, 2, 3],
... | 82 | 49 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def rows(self) -> Iterator[Dict[str, TensorType]]:
# Do we add seq_lens=[1] to each row?
seq_lens = None if self.get(SampleBatch.SEQ_LENS) is None else np.array([1]... |
1,593 | def _dedup_weights(self, weights):
output, seen_ids = [], set()
for w in weights:
if id(w) not in seen_ids:
output.append(w)
# Track the Variable's identity to avoid __eq__ issues.
seen_ids.add(id(w))
return output
# Save... | Dedupe weights while maintaining order as much as possible. | 9 | 38 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _dedup_weights(self, weights):
output, seen_ids = [], set()
for w in weights:
if id(w) not in seen_ids:
output.append(w)
... |
1,594 | def ancestors_with_self(self) -> list[DOMNode]:
nodes: list[MessagePump | None] = []
add_node = nodes.append
node: MessagePump | None = self
while node is not None:
add_node(node)
node = node._parent
return cast("list[DOMNode]", nodes)
| list[DOMNode]: A list of Nodes by tracing a path all the way back to App.
Note: This is inclusive of ``self``.
| 21 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def ancestors_with_self(self) -> list[DOMNode]:
nodes: list[MessagePump | None] = []
add_node = nodes.append
node: MessagePump | None = self
while no... |
1,595 | def function_converter(self) -> Mapping[str, fields.MetricsFunction]:
resolve_metric_id = {
"name": "metric_id",
"fn": lambda args: self.resolve_metric(args["column"]),
}
function_converter = {
function.name: function
for function in [
... | While the final functions in clickhouse must have their -Merge combinators in order to function, we don't
need to add them here since snuba has a FunctionMapper that will add it for us. Basically it turns expressions
like quantiles(0.9)(value) into quantilesMerge(0.9)(percentiles)
Make sure to u... | 68 | 747 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def function_converter(self) -> Mapping[str, fields.MetricsFunction]:
resolve_metric_id = {
"name": "metric_id",
"fn": lambda args: self.resolve_metr... |
1,596 | def copyUsedDLLs(source_dir, dist_dir, standalone_entry_points):
# This is terribly complex, because we check the list of used DLLs
# trying to avoid duplicates, and detecting errors with them not
# being binary identical, so we can report them. And then of course
# we also need to handle OS specifics.
... | Colliding DLL names for %s, checking identity of \
'%s' <-> '%s'.\
Ignoring non-identical DLLs for '%s'.
%s used by:
%s
different from
%s used by
%s | 27 | 477 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def copyUsedDLLs(source_dir, dist_dir, standalone_entry_points):
# This is terribly complex, because we check the list of used DLLs
# trying to avoid duplicates, and detecting errors... |
1,597 | def _laplace_rule_diff(f, t, s, doit=True, **hints):
hints.pop('simplify', True)
a = Wild('a', exclude=[t])
y = Wild('y')
n = Wild('n', exclude=[t])
g = WildFunction('g', nargs=1)
ma1 = f.match(a*Derivative(g, (t, n)))
if ma1 and ma1[g].args[0] == t and ma1[n].is_integer:
debug(... |
This internal helper function tries to transform an expression containing
a derivative of an undefined function and returns `None` if it cannot
do it.
| 24 | 81 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _laplace_rule_diff(f, t, s, doit=True, **hints):
hints.pop('simplify', True)
a = Wild('a', exclude=[t])
y = Wild('y')
n = Wild('n', exclude=[t])
g = WildFunction... |
1,598 | def _check_flag(user, flag, attributes, user_flags_settings):
new_flag = False
is_role_key = "is_%s_role" % (flag)
is_attr_key = "is_%s_attr" % (flag)
is_value_key = "is_%s_value" % (flag)
remove_setting = "remove_%ss" % (flag)
# Check to see if we are respecting a role and, if so, does ou... |
Helper function to set the is_superuser is_system_auditor flags for the SAML adapter
Returns the new flag and whether or not it changed the flag
| 24 | 374 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _check_flag(user, flag, attributes, user_flags_settings):
new_flag = False
is_role_key = "is_%s_role" % (flag)
is_attr_key = "is_%s_attr" % (flag)
is_value_key = "is... |
1,599 | def test_get_backfill_points_in_room(self):
setup_info = self._setup_room_for_backfill_tests()
room_id = setup_info.room_id
backfill_points = self.get_success(
self.store.get_backfill_points_in_room(room_id)
)
backfill_event_ids = [backfill_point[0] for back... |
Test to make sure we get some backfill points
| 9 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_get_backfill_points_in_room(self):
setup_info = self._setup_room_for_backfill_tests()
room_id = setup_info.room_id
backfill_points = self.get_succe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.