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,700 | def progress(self, msg):
if self.paras.verbose:
sys.stdout.write("\033[K") # Clear line
print('[{}] {}'.format(human_format(self.step), msg), end='\r')
| Verbose function for updating progress on stdout (do not include newline) | 11 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def progress(self, msg):
if self.paras.verbose:
sys.stdout.write("\033[K") # Clear line
print('[{}] {}'.format(human_format(self.step), msg), end='\... |
1,701 | def test_customize_compiler_before_get_config_vars(self):
# Issue #21923: test that a Distribution compiler
# instance can be called without an explicit call to
# get_config_vars().
with open(TESTFN, 'w') as f:
f.writelines(textwrap.dedent())
p = subprocess.Popen([str... | \
from distutils.core import Distribution
config = Distribution().get_command_obj('config')
# try_compile may pass or it may fail if no compiler
# is found but it should not raise an exception.
rc = config.try_compile('int x;')
... | 33 | 46 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_customize_compiler_before_get_config_vars(self):
# Issue #21923: test that a Distribution compiler
# instance can be called without an explicit call to
# get... |
1,702 | def siren_platform_only():
with patch(
"homeassistant.components.zha.PLATFORMS",
(
Platform.DEVICE_TRACKER,
Platform.NUMBER,
Platform.SENSOR,
Platform.SELECT,
Platform.SIREN,
),
):
yield
@pytest.fixture | Only setup the siren and required base platforms to speed up tests. | 12 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def siren_platform_only():
with patch(
"homeassistant.components.zha.PLATFORMS",
(
Platform.DEVICE_TRACKER,
Platform.NUMBER,
Plat... |
1,703 | def test_maybe_send_server_notice_when_alerting_suppressed_room_blocked(self):
self._rlsn._auth.check_auth_blocking = Mock(
return_value=make_awaitable(None),
side_effect=ResourceLimitError(
403, "foo", limit_type=LimitBlockingTypes.MONTHLY_ACTIVE_USER
... |
When the room is already in a blocked state, test that when alerting
is suppressed that the room is returned to an unblocked state.
| 24 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_maybe_send_server_notice_when_alerting_suppressed_room_blocked(self):
self._rlsn._auth.check_auth_blocking = Mock(
return_value=make_awaitable(None),
... |
1,704 | def test_send(event_listener, salt_master, salt_minion, salt_call_cli):
event_tag = random_string("salt/test/event/")
data = {"event.fire": "just test it!!!!"}
start_time = time.time()
ret = salt_call_cli.run(
"event.send",
event_tag,
data=data,
with_grains=True,
... |
Test sending an event to the master event bus
| 9 | 79 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_send(event_listener, salt_master, salt_minion, salt_call_cli):
event_tag = random_string("salt/test/event/")
data = {"event.fire": "just test it!!!!"}
start_time = ... |
1,705 | def _check_tree_and_avals(what, tree1, avals1, tree2, avals2):
if tree1 != tree2:
raise TypeError(
f"{what} must have same type structure, got {tree1} and {tree2}.")
if not all(_map(core.typematch, avals1, avals2)):
diff = tree_map(_show_diff, tree_unflatten(tree1, avals1),
tr... | Raises TypeError if (tree1, avals1) does not match (tree2, avals2).
Corresponding `tree` and `avals` must match in the sense that the number of
leaves in `tree` must be equal to the length of `avals`. `what` will be
prepended to details of the mismatch in TypeError.
| 45 | 41 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _check_tree_and_avals(what, tree1, avals1, tree2, avals2):
if tree1 != tree2:
raise TypeError(
f"{what} must have same type structure, got {tree1} and {tree2}.")
if no... |
1,706 | def test_load_global_local_flag_config(self):
global_config =
local_config =
global_config_path = "/mock/home/folder/.streamlit/config.toml"
local_config_path = os.path.join(os.getcwd(), ".streamlit/config.toml")
global_open = mock_open(read_data=global_config)
... | Test that CLI flags have higher priority than both
~/.streamlit/config.toml and $CWD/.streamlit/config.toml at parse time.
[theme]
base = "dark"
font = "sans serif"
textColor = "#FFFFFF"
[theme]
base = "light"
font = "serif"
| 33 | 70 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_load_global_local_flag_config(self):
global_config =
local_config =
global_config_path = "/mock/home/folder/.streamlit/config.toml"
loc... |
1,707 | def get_valid_filename(name):
s = str(name).strip().replace(" ", "_")
s = re.sub(r"(?u)[^-\w.]", "", s)
if s in {"", ".", ".."}:
raise SuspiciousFileOperation("Could not derive file name from '%s'" % name)
return s
@keep_lazy_text |
Return the given string converted to a string that can be used for a clean
filename. Remove leading and trailing spaces; convert other spaces to
underscores; and remove anything that is not an alphanumeric, dash,
underscore, or dot.
>>> get_valid_filename("john's portrait in 2004.jpg")
'johns_p... | 44 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_valid_filename(name):
s = str(name).strip().replace(" ", "_")
s = re.sub(r"(?u)[^-\w.]", "", s)
if s in {"", ".", ".."}:
raise SuspiciousFileOperation("Could... |
1,708 | def test_no_duplicates_for_m2m_in_list_filter(self):
blues = Genre.objects.create(name="Blues")
band = Band.objects.create(name="B.B. King Review", nr_of_members=11)
band.genres.add(blues)
band.genres.add(blues)
m = BandAdmin(Band, custom_site)
request = self.f... |
Regression test for #13902: When using a ManyToMany in list_filter,
results shouldn't appear more than once. Basic ManyToMany.
| 18 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_no_duplicates_for_m2m_in_list_filter(self):
blues = Genre.objects.create(name="Blues")
band = Band.objects.create(name="B.B. King Review", nr_of_members=11)... |
1,709 | def add_flex_arithmetic_methods(cls) -> None:
flex_arith_method, flex_comp_method = _get_method_wrappers(cls)
new_methods = _create_methods(cls, flex_arith_method, flex_comp_method)
new_methods.update(
{
"multiply": new_methods["mul"],
"subtract": new_methods["sub"],
... |
Adds the full suite of flex arithmetic methods (``pow``, ``mul``, ``add``)
to the class.
Parameters
----------
cls : class
flex methods will be defined and pinned to this class
| 29 | 45 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def add_flex_arithmetic_methods(cls) -> None:
flex_arith_method, flex_comp_method = _get_method_wrappers(cls)
new_methods = _create_methods(cls, flex_arith_method, flex_comp_met... |
1,710 | def get_collected_keypoint(self):
output = []
for tracker_id in self.id_to_pop:
output.append([tracker_id, self.keypoint_saver[tracker_id]])
del (self.keypoint_saver[tracker_id])
self.flag_to_pop = False
self.id_to_pop.clear()
return output
|
Output (List): List of keypoint results for Action Recognition task, where
the format of each element is [tracker_id, KeyPointSequence of tracker_id]
| 21 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_collected_keypoint(self):
output = []
for tracker_id in self.id_to_pop:
output.append([tracker_id, self.keypoint_saver[tracker_id]])
... |
1,711 | def get_course_schedule_events(start, end, filters=None):
from frappe.desk.calendar import get_event_conditions
conditions = get_event_conditions("Course Schedule", filters)
data = frappe.db.sql(.format(conditions=conditions), {
"start": start,
"end": end
}, as_dict=True, update={"allDay": 0})
return d... | Returns events for Course Schedule Calendar view rendering.
:param start: Start date-time.
:param end: End date-time.
:param filters: Filters (JSON).
select name, course, color,
timestamp(schedule_date, from_time) as from_time,
timestamp(schedule_date, to_time) as to_time,
room, student_group, 0 as 'allDa... | 49 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_course_schedule_events(start, end, filters=None):
from frappe.desk.calendar import get_event_conditions
conditions = get_event_conditions("Course Schedule", filters)
data = fra... |
1,712 | def check_keys_split(self, decoded) -> None:
bad_keys = set(decoded.keys()).difference(set(self._split_keys))
if bad_keys:
bad_keys_joined = ", ".join(bad_keys)
raise ValueError(f"JSON data had unexpected key(s): {bad_keys_joined}")
|
Checks that dict has only the appropriate keys for orient='split'.
| 10 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def check_keys_split(self, decoded) -> None:
bad_keys = set(decoded.keys()).difference(set(self._split_keys))
if bad_keys:
bad_keys_joined = ", ".join(ba... |
1,713 | def adapt_datetimefield_value(self, value):
if value is None:
return None
# Expression values are adapted by the database.
if hasattr(value, "resolve_expression"):
return value
# cx_Oracle doesn't support tz-aware datetimes
if timezone.is_aware... |
Transform a datetime value to an object compatible with what is expected
by the backend driver for datetime columns.
If naive datetime is passed assumes that is in UTC. Normally Django
models.DateTimeField makes sure that if USE_TZ is True passed datetime
is timezone aware.
... | 44 | 53 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def adapt_datetimefield_value(self, value):
if value is None:
return None
# Expression values are adapted by the database.
if hasattr(value, "r... |
1,714 | def __pow__(a, b):
if isinstance(b, numbers.Rational):
if b.denominator == 1:
power = b.numerator
if power >= 0:
return Fraction(a._numerator ** power,
a._denominator ** power,
... | a ** b
If b is not an integer, the result will be a float or complex
since roots are generally irrational. If b is an integer, the
result will be rational.
| 32 | 67 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __pow__(a, b):
if isinstance(b, numbers.Rational):
if b.denominator == 1:
power = b.numerator
if power >= 0:
... |
1,715 | def fit(self, X, y, sample_weight=None):
self._validate_params()
super().fit(X, y, sample_weight=sample_weight)
return self
| Fit Ridge regression model with cv.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Training data. If using GCV, will be cast to float64
if necessary.
y : ndarray of shape (n_samples,) or (n_samples, n_targets)
Target values. Will ... | 118 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def fit(self, X, y, sample_weight=None):
self._validate_params()
super().fit(X, y, sample_weight=sample_weight)
return self
```
###Assistant :... |
1,716 | def calc_position(self, x):
if x < self.x[0]:
return None
elif x > self.x[-1]:
return None
i = self.__search_index(x)
dx = x - self.x[i]
position = self.a[i] + self.b[i] * dx + \
self.c[i] * dx ** 2.0 + self.d[i] * dx ** 3.0
... |
Calc `y` position for given `x`.
if `x` is outside the data point's `x` range, return None.
Returns
-------
y : float
y position for given x.
| 27 | 45 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def calc_position(self, x):
if x < self.x[0]:
return None
elif x > self.x[-1]:
return None
i = self.__search_index(x)
dx = x... |
1,717 | def get_daily_sector_prices(start_date, end_date) -> dict:
# sector ticker information
sp500_tickers = {
"S&P 500 Materials (Sector)": "^SP500-15",
"S&P 500 Industrials (Sector)": "^SP500-20",
"S&P 500 Consumer Discretionary (Sector)": "^SP500-25",
"S&P 500 Consumer Staples ... |
fetches daily sector prices for S&P500 for a fixed time period
Parameters
----------
start_date : str ('yyyy-mm-dd') or datetime.date
start date for fetching data
end_date : str ('yyyy-mm-dd') or datetime.date
end date for fetching data
Returns
-------
sp500_tickers_da... | 48 | 133 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_daily_sector_prices(start_date, end_date) -> dict:
# sector ticker information
sp500_tickers = {
"S&P 500 Materials (Sector)": "^SP500-15",
"S&P 500 Indu... |
1,718 | def get_unpositioned_tip(self, tip_shape=None, tip_length=None):
from manim.mobject.geometry.tips import ArrowTriangleFilledTip
if tip_shape is None:
tip_shape = ArrowTriangleFilledTip
if tip_length is None:
tip_length = self.get_default_tip_length()
col... |
Returns a tip that has been stylistically configured,
but has not yet been given a position in space.
| 18 | 38 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_unpositioned_tip(self, tip_shape=None, tip_length=None):
from manim.mobject.geometry.tips import ArrowTriangleFilledTip
if tip_shape is None:
ti... |
1,719 | def test_parse_due_date_without_timezone_uses_offset():
data: DueDate = {
"date": "2022-02-02T14:00:00",
"is_recurring": False,
"lang": "en",
"string": "Feb 2 2:00 PM",
"timezone": None,
}
actual = _parse_due_date(data, timezone_offset=-8)
assert datetime(202... | Test due date uses user local timezone offset when it has no timezone. | 13 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_parse_due_date_without_timezone_uses_offset():
data: DueDate = {
"date": "2022-02-02T14:00:00",
"is_recurring": False,
"lang": "en",
"string... |
1,720 | def serving_output(self, output):
hidden_states = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attentions = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
return TFBaseModelOutput(
last_hidden_state=outpu... | TFHubert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC). | 14 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def serving_output(self, output):
hidden_states = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attentions = tf.convert_to_tensor(o... |
1,721 | def _unique_np(values, return_inverse=False, return_counts=False):
uniques = np.unique(
values, return_inverse=return_inverse, return_counts=return_counts
)
inverse, counts = None, None
if return_counts:
*uniques, counts = uniques
if return_inverse:
*uniques, inverse ... | Helper function to find unique values for numpy arrays that correctly
accounts for nans. See `_unique` documentation for details. | 19 | 111 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _unique_np(values, return_inverse=False, return_counts=False):
uniques = np.unique(
values, return_inverse=return_inverse, return_counts=return_counts
)
inverse... |
1,722 | def switch_to_live(self) -> None:
self.logbook_run.event_cache.clear()
self.logbook_run.context_lookup.clear()
| Switch to live stream.
Clear caches so we can reduce memory pressure.
| 12 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def switch_to_live(self) -> None:
self.logbook_run.event_cache.clear()
self.logbook_run.context_lookup.clear()
```
###Assistant : Switch to live stream.... |
1,723 | def require_comet_ml(test_case):
return unittest.skipUnless(is_comet_ml_available(), "test requires comet_ml")(test_case)
|
Decorator marking a test that requires comet_ml installed. These tests are skipped when comet_ml isn't installed
| 16 | 7 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def require_comet_ml(test_case):
return unittest.skipUnless(is_comet_ml_available(), "test requires comet_ml")(test_case)
```
###Assistant :
Decorator marking a t... |
1,724 | def triggered_id(self):
component_id = None
if self.triggered:
prop_id = self.triggered_prop_ids.first()
component_id = self.triggered_prop_ids[prop_id]
return component_id
|
Returns the component id (str or dict) of the Input component that triggered the callback.
Note - use `triggered_prop_ids` if you need both the component id and the prop that triggered the callback or if
multiple Inputs triggered the callback.
Example usage:
`if "btn-1" == ctx... | 47 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def triggered_id(self):
component_id = None
if self.triggered:
prop_id = self.triggered_prop_ids.first()
component_id = self.triggered_prop_i... |
1,725 | def _solve_W(self, X, H, max_iter):
avg = np.sqrt(X.mean() / self._n_components)
W = np.full((X.shape[0], self._n_components), avg, dtype=X.dtype)
W_buffer = W.copy()
# Get scaled regularization terms. Done for each minibatch to take into account
# variable sizes of min... | Minimize the objective function w.r.t W.
Update W with H being fixed, until convergence. This is the heart
of `transform` but it's also used during `fit` when doing fresh restarts.
| 30 | 80 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _solve_W(self, X, H, max_iter):
avg = np.sqrt(X.mean() / self._n_components)
W = np.full((X.shape[0], self._n_components), avg, dtype=X.dtype)
W_buffer =... |
1,726 | def convert_bbox_to_z(bbox):
w = bbox[2] - bbox[0]
h = bbox[3] - bbox[1]
x = bbox[0] + w / 2.
y = bbox[1] + h / 2.
s = w * h # scale is just area
r = w / float(h + 1e-6)
return np.array([x, y, s, r]).reshape((4, 1))
|
Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form
[x,y,s,r] where x,y is the centre of the box and s is the scale/area and r is
the aspect ratio
| 34 | 49 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def convert_bbox_to_z(bbox):
w = bbox[2] - bbox[0]
h = bbox[3] - bbox[1]
x = bbox[0] + w / 2.
y = bbox[1] + h / 2.
s = w * h # scale is just area
r = w / float(... |
1,727 | def remove_whitespace(string, leading=False, trailing=False):
# Remove any leading new line characters along with any surrounding white space
if leading:
string = re.sub(r'^\s*\n+\s*', '', string)
# Remove any trailing new line characters along with any surrounding white space
if trailing:... | Remove white space from a string.
Args:
string(str): The string to remove white space from.
leading(bool, optional): Remove leading new lines when True.
trailing(bool, optional): Remove trailing new lines when False.
Returns:
str: The input string with new line characters removed... | 166 | 82 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def remove_whitespace(string, leading=False, trailing=False):
# Remove any leading new line characters along with any surrounding white space
if leading:
string = re.sub... |
1,728 | def selectionChanged(self, selected, deselected):
if not self._active:
return
super().selectionChanged(selected, deselected)
indexes = selected.indexes()
if not indexes:
return
data = str(self._model().data(indexes[0]))
self.selection_chan... | Extend selectionChanged to call completers selection_changed. | 6 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def selectionChanged(self, selected, deselected):
if not self._active:
return
super().selectionChanged(selected, deselected)
indexes = selected.i... |
1,729 | def __mul__(self, other):
newlist = [v for v in self.args]
other = sympify(other)
for i, v in enumerate(newlist):
newlist[i] = (other * newlist[i][0], newlist[i][1])
return Vector(newlist)
| Multiplies the Vector by a sympifyable expression.
Parameters
==========
other : Sympifyable
The scalar to multiply this Vector with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy import Symbol
>>> N = ... | 50 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __mul__(self, other):
newlist = [v for v in self.args]
other = sympify(other)
for i, v in enumerate(newlist):
newlist[i] = (other * newlist[... |
1,730 | def to_dict(self) -> Dict:
return serve_application_to_schema(self._deployments.values()).dict()
| Returns this Application's deployments as a dictionary.
This dictionary adheres to the Serve REST API schema. It can be deployed
via the Serve REST API.
Returns:
Dict: The Application's deployments formatted in a dictionary.
| 34 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def to_dict(self) -> Dict:
return serve_application_to_schema(self._deployments.values()).dict()
```
###Assistant : Returns this Application's deployments as a... |
1,731 | def get_shift_details(shift_type_name, for_timestamp=None):
if not shift_type_name:
return None
if not for_timestamp:
for_timestamp = now_datetime()
shift_type = frappe.get_doc('Shift Type', shift_type_name)
shift_actual_start = shift_type.start_time - timedelta(minutes=shift_type.begin_check_in_before_shift... | Returns Shift Details which contain some additional information as described below.
'shift_details' contains the following keys:
'shift_type' - Object of DocType Shift Type,
'start_datetime' - Date and Time of shift start on given date,
'end_datetime' - Date and Time of shift end on given da... | 88 | 149 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_shift_details(shift_type_name, for_timestamp=None):
if not shift_type_name:
return None
if not for_timestamp:
for_timestamp = now_datetime()
shift_type = frappe.get_doc('Sh... |
1,732 | def subprocess_run_helper(func, *args, timeout, extra_env=None):
target = func.__name__
module = func.__module__
proc = subprocess.run(
[sys.executable,
"-c",
f"from {module} import {target}; {target}()",
*args],
env={**os.environ, "SOURCE_DATE_EPOCH": "0", **... |
Run a function in a sub-process.
Parameters
----------
func : function
The function to be run. It must be in a module that is importable.
*args : str
Any additional command line arguments to be passed in
the first argument to ``subprocess.run``.
extra_env : dict[str, s... | 56 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def subprocess_run_helper(func, *args, timeout, extra_env=None):
target = func.__name__
module = func.__module__
proc = subprocess.run(
[sys.executable,
"-c... |
1,733 | def add_preheated_app_session(self) -> None:
session = self._create_or_reuse_app_session(ws=None)
session.handle_rerun_script_request(is_preheat=True)
| Register a fake browser with the server and run the script.
This is used to start running the user's script even before the first
browser connects.
| 26 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def add_preheated_app_session(self) -> None:
session = self._create_or_reuse_app_session(ws=None)
session.handle_rerun_script_request(is_preheat=True)
```
... |
1,734 | def score(self, testing_features, testing_target):
if self.fitted_pipeline_ is None:
raise RuntimeError(
"A pipeline has not yet been optimized. Please call fit() first."
)
testing_features, testing_target = self._check_dataset(
testing_featu... | Return the score on the given testing data using the user-specified scoring function.
Parameters
----------
testing_features: array-like {n_samples, n_features}
Feature matrix of the testing set
testing_target: array-like {n_samples}
List of class labels for pred... | 47 | 88 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def score(self, testing_features, testing_target):
if self.fitted_pipeline_ is None:
raise RuntimeError(
"A pipeline has not yet been optimized. ... |
1,735 | def test_as_dict():
expected = {
LENGTH: UnitOfLength.KILOMETERS,
WIND_SPEED: UnitOfSpeed.METERS_PER_SECOND,
TEMPERATURE: UnitOfTemperature.CELSIUS,
VOLUME: UnitOfVolume.LITERS,
MASS: UnitOfMass.GRAMS,
PRESSURE: UnitOfPressure.PA,
ACCUMULATED_PRECIPITATIO... | Test that the as_dict() method returns the expected dictionary. | 9 | 24 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_as_dict():
expected = {
LENGTH: UnitOfLength.KILOMETERS,
WIND_SPEED: UnitOfSpeed.METERS_PER_SECOND,
TEMPERATURE: UnitOfTemperature.CELSIUS,
... |
1,736 | def _get_inputs(self):
logger.debug("Getting inputs")
if len(self.input_shape) == 3:
input_shapes = [self.input_shape, self.input_shape]
else:
input_shapes = self.input_shape
inputs = [Input(shape=shape, name=f"face_in_{side}")
for side,... | Obtain the standardized inputs for the model.
The inputs will be returned for the "A" and "B" sides in the shape as defined by
:attr:`input_shape`.
Returns
-------
list
A list of :class:`keras.layers.Input` tensors. This will be a list of 2 tensors (one
... | 49 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_inputs(self):
logger.debug("Getting inputs")
if len(self.input_shape) == 3:
input_shapes = [self.input_shape, self.input_shape]
else:
... |
1,737 | def collect_units_install() -> t.List[PipInstall]:
requirements_paths = [] # type: t.List[t.Tuple[str, str]]
constraints_paths = [] # type: t.List[t.Tuple[str, str]]
path = os.path.join(data_context().content.unit_path, 'requirements.txt')
requirements_paths.append((data_context().content.root, ... | Return details necessary for the specified units pip install(s). | 9 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def collect_units_install() -> t.List[PipInstall]:
requirements_paths = [] # type: t.List[t.Tuple[str, str]]
constraints_paths = [] # type: t.List[t.Tuple[str, str]]
path... |
1,738 | def forward(self, features, **kwargs):
x = features[:, 0, :] # take <s> token (equiv. to [CLS])
x = self.dropout(x)
x = self.dense(x)
x = ACT2FN[self.config.hidden_act](x)
x = self.dropout(x)
x = self.out_proj(x)
return x
@add_start_docstrings(
,
YOSO_S... | YOSO Model transformer with a sequence classification/regression head on top (a linear layer on top of
the pooled output) e.g. for GLUE tasks. | 23 | 37 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def forward(self, features, **kwargs):
x = features[:, 0, :] # take <s> token (equiv. to [CLS])
x = self.dropout(x)
x = self.dense(x)
x = ACT2FN[self.config.... |
1,739 | def delete_batch(self, pk_list, using):
# number of objects deleted
num_deleted = 0
field = self.get_meta().pk
for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):
self.clear_where()
self.add_filter(
f"{field.attname}__in",
... |
Set up and execute delete queries for all the objects in pk_list.
More than one physical query may be executed if there are a
lot of values in pk_list.
| 29 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def delete_batch(self, pk_list, using):
# number of objects deleted
num_deleted = 0
field = self.get_meta().pk
for offset in range(0, len(pk_list), G... |
1,740 | def generate_ansible_coverage_config() -> str:
coverage_config =
return coverage_config
| Generate code coverage configuration for Ansible tests.
[run]
branch = True
concurrency = multiprocessing
parallel = True
omit =
*/python*/dist-packages/*
*/python*/site-packages/*
*/python*/distutils/*
*/pyshared/*
*/pytest
*/AnsiballZ_*.py
*/test/results/*
| 26 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def generate_ansible_coverage_config() -> str:
coverage_config =
return coverage_config
```
###Assistant : Generate code coverage configuration for Ansible tests... |
1,741 | def get_allowed_roles_to_invite(self):
return [
r
for r in organization_roles.get_all()
if r.priority <= organization_roles.get(self.role).priority
]
|
Return a list of roles which that member could invite
Must check if member member has member:admin first before checking
| 20 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_allowed_roles_to_invite(self):
return [
r
for r in organization_roles.get_all()
if r.priority <= organization_roles.get(self.role... |
1,742 | def search_space_spec(self) -> Dict[str, ParameterSpec]:
raise NotImplementedError()
|
Space specification (sample points).
Mapping from spec name to ParameterSpec. The names in choices should be in the same format of export.
For example: ::
{"layer1": ParameterSpec(values=["conv", "pool"])}
| 28 | 7 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def search_space_spec(self) -> Dict[str, ParameterSpec]:
raise NotImplementedError()
```
###Assistant :
Space specification (sample points).
Ma... |
1,743 | def test_context_as_admin(self) -> None:
# Create a room. We're not part of it.
user_id = self.register_user("test", "test")
user_tok = self.login("test", "test")
room_id = self.helper.create_room_as(user_id, tok=user_tok)
# Populate the room with events.
event... |
Test that, as admin, we can find the context of an event without having joined the room.
| 17 | 132 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_context_as_admin(self) -> None:
# Create a room. We're not part of it.
user_id = self.register_user("test", "test")
user_tok = self.login("test", "... |
1,744 | def marginal_std(self, t):
return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
|
Compute sigma_t of a given continuous-time label t in [0, T].
| 11 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def marginal_std(self, t):
return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t)))
```
###Assistant :
Compute sigma_t of a given contin... |
1,745 | def for_request(cls, request):
attr_name = cls.get_cache_attr_name()
if hasattr(request, attr_name):
return getattr(request, attr_name)
site = Site.find_for_request(request)
site_settings = cls.for_site(site)
# to allow more efficient page url generation
... |
Get or create an instance of this model for the request,
and cache the result on the request for faster repeat access.
| 22 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def for_request(cls, request):
attr_name = cls.get_cache_attr_name()
if hasattr(request, attr_name):
return getattr(request, attr_name)
site = Si... |
1,746 | def _enable_ocsp_stapling(self, ssl_vhost, unused_options):
min_apache_ver = (2, 3, 3)
if self.get_version() < min_apache_ver:
raise errors.PluginError(
"Unable to set OCSP directives.\n"
"Apache version is below 2.3.3.")
if "socache_shmcb_mo... | Enables OCSP Stapling
In OCSP, each client (e.g. browser) would have to query the
OCSP Responder to validate that the site certificate was not revoked.
Enabling OCSP Stapling, would allow the web-server to query the OCSP
Responder, and staple its response to the offered certificate dur... | 107 | 108 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _enable_ocsp_stapling(self, ssl_vhost, unused_options):
min_apache_ver = (2, 3, 3)
if self.get_version() < min_apache_ver:
raise errors.PluginError(
... |
1,747 | def make_regional_gl_entries(gl_entries, doc):
country = frappe.get_cached_value("Company", doc.company, "country")
if country != "United Arab Emirates":
return gl_entries
if doc.reverse_charge == "Y":
tax_accounts = get_tax_accounts(doc.company)
for tax in doc.get("taxes"):
if tax.category not in ("Tot... | Hooked to make_regional_gl_entries in Purchase Invoice.It appends the region specific general ledger entries to the list of GL Entries. | 19 | 44 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def make_regional_gl_entries(gl_entries, doc):
country = frappe.get_cached_value("Company", doc.company, "country")
if country != "United Arab Emirates":
return gl_entries
if doc.re... |
1,748 | def private_param(param):
return pytest.param(
*param,
marks=pytest.mark.skipif(
not _run_private_tests,
reason="Skipping: this test is marked private, set RUN_PRIVATE=1 in your environment to run",
),
)
| Wrap param to mark it as private, meaning it requires credentials to run.
Private tests are skipped by default. Set the RUN_PRIVATE environment variable to a truth value to run them.
| 31 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def private_param(param):
return pytest.param(
*param,
marks=pytest.mark.skipif(
not _run_private_tests,
reason="Skipping: this test is marke... |
1,749 | def minimal_d_separator(G, u, v):
if not nx.is_directed_acyclic_graph(G):
raise nx.NetworkXError("graph should be directed acyclic")
union_uv = {u, v}
if any(n not in G.nodes for n in union_uv):
raise nx.NodeNotFound("one or more specified nodes not found in the graph")
# first c... | Compute a minimal d-separating set between 'u' and 'v'.
A d-separating set in a DAG is a set of nodes that blocks all paths
between the two nodes, 'u' and 'v'. This function
constructs a d-separating set that is "minimal", meaning it is the smallest
d-separating set for 'u' and 'v'. This is not necessa... | 306 | 108 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def minimal_d_separator(G, u, v):
if not nx.is_directed_acyclic_graph(G):
raise nx.NetworkXError("graph should be directed acyclic")
union_uv = {u, v}
if any(n not... |
1,750 | def _change_alignment_for_a_line(self, alignment, line_no):
self.lines[1][line_no] = alignment
if self.lines[1][line_no] == "center":
self[line_no].move_to(
np.array([self.get_center()[0], self[line_no].get_center()[1], 0]),
)
elif self.lines[1][l... | Function to change one line's alignment to a specific value.
Parameters
----------
alignment : :class:`str`
Defines the alignment of paragraph. Possible values are "left", "right", "center".
line_no : :class:`int`
Defines the line number for which we want to set ... | 41 | 50 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _change_alignment_for_a_line(self, alignment, line_no):
self.lines[1][line_no] = alignment
if self.lines[1][line_no] == "center":
self[line_no].move_... |
1,751 | def test_rejoin_forgotten_by_user(self) -> None:
self.helper.join(self.room_id, user=self.bob, tok=self.bob_token)
self.helper.leave(self.room_id, user=self.alice, tok=self.alice_token)
self.get_success(self.handler.forget(self.alice_ID, self.room_id))
self.assertTrue(
... | Test that a user that has forgotten a room can do a re-join.
The room was not forgotten from the local server.
One local user is still member of the room. | 31 | 51 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_rejoin_forgotten_by_user(self) -> None:
self.helper.join(self.room_id, user=self.bob, tok=self.bob_token)
self.helper.leave(self.room_id, user=self.alice, ... |
1,752 | def std_call(func):
if os.name == "nt":
return lwingdal[func]
else:
return lgdal[func]
# #### Version-information functions. ####
# Return GDAL library version information with the given key.
_version_info = std_call("GDALVersionInfo")
_version_info.argtypes = [c_char_p]
_version_info.re... |
Return the correct STDCALL function for certain OSR routines on Win32
platforms.
| 12 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def std_call(func):
if os.name == "nt":
return lwingdal[func]
else:
return lgdal[func]
# #### Version-information functions. ####
# Return GDAL library versio... |
1,753 | def __getitem__(self, key):
use_func = key.startswith(self.prefix)
if use_func:
key = key[len(self.prefix) :]
value = super().__getitem__(key)
if use_func:
return self.func(value)
return value
|
Retrieve the real value after stripping the prefix string (if
present). If the prefix is present, pass the value through self.func
before returning, otherwise return the raw value.
| 28 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __getitem__(self, key):
use_func = key.startswith(self.prefix)
if use_func:
key = key[len(self.prefix) :]
value = super().__getitem__(key)
... |
1,754 | def not_enough_open_files() -> bool:
try:
import resource
except ImportError:
# resource limits is not a concept on all systems, notably Windows
return False
soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
return soft_limit < 512 or hard_limit < 512
|
The current process does not currently allow enough open files for this test.
You can increase the number of open files with `ulimit -n 512`.
| 25 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def not_enough_open_files() -> bool:
try:
import resource
except ImportError:
# resource limits is not a concept on all systems, notably Windows
return F... |
1,755 | def configure(self, request):
# Save ordering preference
if request.user.is_authenticated:
table_name = self.__class__.__name__
if self.prefixed_order_by_field in request.GET:
# If an ordering has been specified as a query parameter, save it as the
... |
Configure the table for a specific request context. This performs pagination and records
the user's preferred ordering logic.
| 18 | 79 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def configure(self, request):
# Save ordering preference
if request.user.is_authenticated:
table_name = self.__class__.__name__
if self.prefi... |
1,756 | def _shard_arg(arg, devices, arg_indices):
if isinstance(arg, ShardedDeviceArray) and arg_indices == arg.indices:
# The shard_arg_handlers allow an extensible set of types to be sharded, but
# inline handling for ShardedDeviceArray as a special case for performance
# NOTE: we compare indices instead of... | Returns a list of size len(devices) containing per-device buffers.
For the C++ pmap path, we fallback to Python (this function) to shard
arguments that are not supported by the C++ `ShardArg`.
Arrgs:
arg: The Python argument.
devices: The list of devices to shard over.
arg_indices: A list of `len(de... | 56 | 75 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _shard_arg(arg, devices, arg_indices):
if isinstance(arg, ShardedDeviceArray) and arg_indices == arg.indices:
# The shard_arg_handlers allow an extensible set of types to be sha... |
1,757 | def test_rect(self):
n3x3 = coord_net_spec(ks=3, stride=1, pad=0)
n5x5 = coord_net_spec(ks=5, stride=2, pad=10)
n3x5 = coord_net_spec(ks=[3, 5], stride=[1, 2], pad=[0, 10])
ax_3x3, a_3x3, b_3x3 = coord_map_from_to(n3x3.deconv, n3x3.data)
ax_5x5, a_5x5, b_5x5 = coord_map_... |
Anisotropic mapping is equivalent to its isotropic parts.
| 8 | 51 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_rect(self):
n3x3 = coord_net_spec(ks=3, stride=1, pad=0)
n5x5 = coord_net_spec(ks=5, stride=2, pad=10)
n3x5 = coord_net_spec(ks=[3, 5], stride=[1, 2... |
1,758 | def test_get_page_url_when_for_settings_fetched_via_for_site(self):
self._create_importantpages_object()
settings = ImportantPages.for_site(self.default_site)
# Force site root paths query beforehand
self.default_site.root_page._get_site_root_paths()
for page_fk_field... | ImportantPages.for_site() cannot make the settings object
request-aware, so things are a little less efficient, and the
URLs returned will not be site-relative | 22 | 102 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_get_page_url_when_for_settings_fetched_via_for_site(self):
self._create_importantpages_object()
settings = ImportantPages.for_site(self.default_site)
... |
1,759 | def test_send_receipts_with_backoff(self):
mock_send_transaction = (
self.hs.get_federation_transport_client().send_transaction
)
mock_send_transaction.return_value = make_awaitable({})
sender = self.hs.get_federation_sender()
receipt = ReadReceipt(
... | Send two receipts in quick succession; the second should be flushed, but
only after 20ms | 15 | 119 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_send_receipts_with_backoff(self):
mock_send_transaction = (
self.hs.get_federation_transport_client().send_transaction
)
mock_send_trans... |
1,760 | def process_frame(self, processable_frame, processing_task):
frame = processable_frame.frame
token = None
cache = self.cache
sourcemaps = self.sourcemaps
all_errors = []
sourcemap_applied = False
# can't demangle if there's no filename or line number pr... |
Attempt to demangle the given frame.
| 6 | 857 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def process_frame(self, processable_frame, processing_task):
frame = processable_frame.frame
token = None
cache = self.cache
sourcemaps = self.sourc... |
1,761 | def validate_csv(headers, fields, required_fields):
# Validate provided column headers
is_update = False
for field, to_field in headers.items():
if field == "id":
is_update = True
continue
if field not in fields:
raise forms.ValidationError(f'Unexpect... |
Validate that parsed csv data conforms to the object's available fields. Raise validation errors
if parsed csv data contains invalid headers or does not contain required headers.
| 27 | 95 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def validate_csv(headers, fields, required_fields):
# Validate provided column headers
is_update = False
for field, to_field in headers.items():
if field == "id":
... |
1,762 | def bernoulli_poly(n, x=None, polys=False):
return appell_poly(n, [[1], [1, QQ(-1,2)]], QQ(1,2),
lambda p, i: p * QQ(1<<(i-1), 1-(1<<i)), QQ, x, polys)
@public | Generates the Bernoulli polynomial of degree `n` in `x`.
Parameters
==========
n : int
Degree of the polynomial.
x : optional
polys : bool, optional
If True, return a Poly, otherwise (default) return an expression.
| 35 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def bernoulli_poly(n, x=None, polys=False):
return appell_poly(n, [[1], [1, QQ(-1,2)]], QQ(1,2),
lambda p, i: p * QQ(1<<(i-1), 1-(1<<i)), QQ, x, polys)
@public
... |
1,763 | def test_calculate_max_drawdown_abs(values, relative, result, result_rel):
dates = [Arrow(2020, 1, 1).shift(days=i) for i in range(len(values))]
df = DataFrame(zip(values, dates), columns=['profit_abs', 'open_date'])
# sort by profit and reset index
df = df.sort_values('profit_abs').reset_index(dr... |
Test case from issue https://github.com/freqtrade/freqtrade/issues/6655
[1000, 500, 1000, 11000, 10000] # absolute results
[1000, 50%, 0%, 0%, ~9%] # Relative drawdowns
| 21 | 91 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_calculate_max_drawdown_abs(values, relative, result, result_rel):
dates = [Arrow(2020, 1, 1).shift(days=i) for i in range(len(values))]
df = DataFrame(zip(values, date... |
1,764 | def testOnCheckpointUnavailableAttribute(self):
checkpoint_manager = self.checkpoint_manager(keep_checkpoints_num=1)
no_attr_checkpoint = Checkpoint(Checkpoint.PERSISTENT, 0, {})
with patch.object(logger, "error") as log_error_mock:
checkpoint_manager.on_checkpoint(no_attr_... |
Tests that an error is logged when the associated result of the
checkpoint has no checkpoint score attribute.
| 18 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def testOnCheckpointUnavailableAttribute(self):
checkpoint_manager = self.checkpoint_manager(keep_checkpoints_num=1)
no_attr_checkpoint = Checkpoint(Checkpoint.PERS... |
1,765 | def subscription_app_status_changed_webhook(subscription_webhook):
return subscription_webhook(
APP_STATUS_CHANGED_SUBSCRIPTION_QUERY,
WebhookEventAsyncType.APP_STATUS_CHANGED,
)
CATEGORY_CREATED_SUBSCRIPTION_QUERY =
@pytest.fixture |
subscription{
event{
...on CategoryCreated{
category{
id
}
}
}
}
| 10 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def subscription_app_status_changed_webhook(subscription_webhook):
return subscription_webhook(
APP_STATUS_CHANGED_SUBSCRIPTION_QUERY,
WebhookEventAsyncType.APP_STATUS_CH... |
1,766 | def binary_op(self, op, right_frame, join_type="outer"):
left_parts, right_parts, joined_index, row_lengths = self._copartition(
0, right_frame, join_type, sort=True
)
# unwrap list returned by `copartition`.
right_parts = right_parts[0]
new_frame = self._par... |
Perform an operation that requires joining with another Modin DataFrame.
Parameters
----------
op : callable
Function to apply after the join.
right_frame : PandasDataframe
Modin DataFrame to join with.
join_type : str, default: "outer"
... | 45 | 49 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def binary_op(self, op, right_frame, join_type="outer"):
left_parts, right_parts, joined_index, row_lengths = self._copartition(
0, right_frame, join_type, sort=... |
1,767 | def rc_file(fname, *, use_default_template=True):
# Deprecation warnings were already handled in rc_params_from_file, no need
# to reemit them here.
with _api.suppress_matplotlib_deprecation_warning():
from .style.core import STYLE_BLACKLIST
rc_from_file = rc_params_from_file(
... |
Update `.rcParams` from file.
Style-blacklisted `.rcParams` (defined in
``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
Parameters
----------
fname : str or path-like
A file with Matplotlib rc settings.
use_default_template : bool
If True, initialize with defa... | 58 | 42 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def rc_file(fname, *, use_default_template=True):
# Deprecation warnings were already handled in rc_params_from_file, no need
# to reemit them here.
with _api.suppress_matpl... |
1,768 | def create_gloo_context(rank, world_size):
context = pygloo.rendezvous.Context(rank, world_size)
return context
| Create a GLOO context using GLOO APIs.
Args:
rank: the rank of this process.
world_size: the number of processes of this collective group.
Returns:
context (pygloo.Context): a GLOO context.
| 29 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def create_gloo_context(rank, world_size):
context = pygloo.rendezvous.Context(rank, world_size)
return context
```
###Assistant : Create a GLOO context using GLOO... |
1,769 | def require_bitsandbytes(test_case):
if not is_bitsandbytes_available():
return unittest.skip("test requires bnb")(test_case)
else:
return test_case
|
Decorator for bits and bytes (bnb) dependency
| 7 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def require_bitsandbytes(test_case):
if not is_bitsandbytes_available():
return unittest.skip("test requires bnb")(test_case)
else:
return test_case
``... |
1,770 | def copy_func(f) -> Callable:
g = types.FunctionType(
f.__code__,
f.__globals__,
name=f.__name__,
argdefs=f.__defaults__,
closure=f.__closure__,
)
g = functools.update_wrapper(g, f)
g.__kwdefaults__ = f.__kwdefaults__
return g
| Copies the contents and attributes of the entered function. Based on https://stackoverflow.com/a/13503277
Parameters
----------
f: Callable
Function to be copied
Returns
-------
g: Callable
New function
| 26 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def copy_func(f) -> Callable:
g = types.FunctionType(
f.__code__,
f.__globals__,
name=f.__name__,
argdefs=f.__defaults__,
closure=f.__closure... |
1,771 | def evaluate(self, expr, context):
if isinstance(expr, string_types):
if expr[0] in '\'"':
result = expr[1:-1]
else:
if expr not in context:
raise SyntaxError('unknown variable: %s' % expr)
result = context[expr... |
Evaluate a marker expression returned by the :func:`parse_requirement`
function in the specified context.
| 13 | 123 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def evaluate(self, expr, context):
if isinstance(expr, string_types):
if expr[0] in '\'"':
result = expr[1:-1]
else:
... |
1,772 | def track_tf_optimizer(tf_optimizer):
if tf.executing_eagerly():
return
optimizers = _GRAPH_TF_OPTIMIZERS[None]
optimizers.add(tf_optimizer)
@keras_export("keras.__internal__.backend.track_variable", v1=[]) | Tracks the given TF optimizer for initialization of its variables. | 10 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def track_tf_optimizer(tf_optimizer):
if tf.executing_eagerly():
return
optimizers = _GRAPH_TF_OPTIMIZERS[None]
optimizers.add(tf_optimizer)
@keras_export("keras._... |
1,773 | def _galois_group_degree_5(T, max_tries=30, randomize=False):
r
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.named_groups import (
CyclicGroup, DihedralGroup, AlternatingGroup, SymmetricGroup
)
# The ideas here are all the same as in the degree-4 method.... |
Compute the Galois group of a polynomial of degree 5, following Alg 6.3.9
of Cohen.
References
==========
.. [1] Cohen, H. *A Course in Computational Algebraic Number Theory*.
| 28 | 247 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _galois_group_degree_5(T, max_tries=30, randomize=False):
r
from sympy.combinatorics.permutations import Permutation
from sympy.combinatorics.named_groups import (
Cy... |
1,774 | def error(self, message):
self.print_usage(_sys.stderr)
args = {'prog': self.prog, 'message': message}
self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
| error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception.
| 33 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def error(self, message):
self.print_usage(_sys.stderr)
args = {'prog': self.prog, 'message': message}
self.exit(2, _('%(prog)s: error: %(message)s\n') % arg... |
1,775 | def preprocess_input(x, data_format=None): # pylint: disable=unused-argument
return x
@keras_export("keras.applications.regnet.decode_predictions") | A placeholder method for backward compatibility.
The preprocessing logic has been included in the regnet 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 and n... | 95 | 9 | 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): # pylint: disable=unused-argument
return x
@keras_export("keras.applications.regnet.decode_predictions")
```
###Assistant :... |
1,776 | def test_edit_post(self):
# Send request
response = self.client.post(
reverse("wagtaildocs:edit_multiple", args=(self.doc.id,)),
{
"doc-%d-%s" % (self.doc.id, field): data
for field, data in self.edit_post_data.items()
},
... |
This tests that a POST request to the edit view edits the document
| 13 | 46 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_edit_post(self):
# Send request
response = self.client.post(
reverse("wagtaildocs:edit_multiple", args=(self.doc.id,)),
{
... |
1,777 | def test_message_hiding(qtbot, view):
with qtbot.wait_signal(view._clear_timer.timeout):
view.show_message(message.MessageInfo(usertypes.MessageLevel.info, 'test'))
assert not view._messages
| Messages should be hidden after the timer times out. | 9 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_message_hiding(qtbot, view):
with qtbot.wait_signal(view._clear_timer.timeout):
view.show_message(message.MessageInfo(usertypes.MessageLevel.info, 'test'))
asse... |
1,778 | def test_avatar_allowed_mime_type_per_room(self):
self._setup_local_files(
{
"good": {"mimetype": "image/png"},
"bad": {"mimetype": "application/octet-stream"},
}
)
room_id = self.helper.create_room_as(tok=self.owner_tok)
... | Tests that the MIME type whitelist for avatars is enforced when updating a
per-room profile.
| 15 | 48 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_avatar_allowed_mime_type_per_room(self):
self._setup_local_files(
{
"good": {"mimetype": "image/png"},
"bad": {"mimetype... |
1,779 | def container_name(self) -> t.Optional[str]:
return self.state.get('container_name')
| Return the stored container name, if any, otherwise None. | 9 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def container_name(self) -> t.Optional[str]:
return self.state.get('container_name')
```
###Assistant : Return the stored container name, if any, otherwise None... |
1,780 | def get_scorer(scoring):
if isinstance(scoring, str):
try:
scorer = copy.deepcopy(_SCORERS[scoring])
except KeyError:
raise ValueError(
"%r is not a valid scoring value. "
"Use sklearn.metrics.get_scorer_names() "
"to get v... | Get a scorer from string.
Read more in the :ref:`User Guide <scoring_parameter>`.
:func:`~sklearn.metrics.get_scorer_names` can be used to retrieve the names
of all available scorers.
Parameters
----------
scoring : str or callable
Scoring method as string. If callable it is returned a... | 78 | 37 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_scorer(scoring):
if isinstance(scoring, str):
try:
scorer = copy.deepcopy(_SCORERS[scoring])
except KeyError:
raise ValueError(
... |
1,781 | def fit(self, X, y):
X, y = self._validate_data(
X, y, ensure_min_samples=2, dtype=[np.float64, np.float32]
)
self.classes_ = unique_labels(y)
n_samples, _ = X.shape
n_classes = len(self.classes_)
if n_samples == n_classes:
raise ValueErr... | Fit the Linear Discriminant Analysis model.
.. versionchanged:: 0.19
*store_covariance* has been moved to main constructor.
.. versionchanged:: 0.19
*tol* has been moved to main constructor.
Parameters
----------
X : array-like of shape (n_sam... | 52 | 249 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def fit(self, X, y):
X, y = self._validate_data(
X, y, ensure_min_samples=2, dtype=[np.float64, np.float32]
)
self.classes_ = unique_labels(y)
... |
1,782 | def test_pr_opened_with_multiple_reviewers(self) -> None:
expected_topic = "sandbox / PR #6 sample_file: Add sample_file.txt."
expected_message =
self.check_webhook(
"pull_request_opened_with_multiple_reviewers", expected_topic, expected_message
)
| [hypro999](http://139.59.64.214:7990/users/hypro999) opened [PR #6](http://139.59.64.214:7990/projects/SBOX/repos/sandbox/pull-requests/6) from `master` to `master` (assigned to [sougo](http://139.59.64.214:7990/users/sougo), [zura](http://139.59.64.214:7990/users/zura) and [shimura](http://139.59.64.214:7990/users/shi... | 25 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_pr_opened_with_multiple_reviewers(self) -> None:
expected_topic = "sandbox / PR #6 sample_file: Add sample_file.txt."
expected_message =
self.check_webhook(... |
1,783 | def make_grouping_by_key(schema, source, default=None):
return map_grouping(lambda s: source.get(s, default), schema)
|
Create a grouping from a schema by using the schema's scalar values to look up
items in the provided source object.
:param schema: A grouping of potential keys in source
:param source: Dict-like object to use to look up scalar grouping value using
scalar grouping values as keys
:param defa... | 66 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def make_grouping_by_key(schema, source, default=None):
return map_grouping(lambda s: source.get(s, default), schema)
```
###Assistant :
Create a grouping from a ... |
1,784 | def taxicab_distance(self, p):
s, p = Point._normalize_dimension(self, Point(p))
return Add(*(abs(a - b) for a, b in zip(s, p)))
| The Taxicab Distance from self to point p.
Returns the sum of the horizontal and vertical distances to point p.
Parameters
==========
p : Point
Returns
=======
taxicab_distance : The sum of the horizontal
and vertical distances to point p.
Se... | 62 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def taxicab_distance(self, p):
s, p = Point._normalize_dimension(self, Point(p))
return Add(*(abs(a - b) for a, b in zip(s, p)))
```
###Assistant : The ... |
1,785 | def cosine_similarity(y_true, y_pred, axis=-1):
y_true = tf.linalg.l2_normalize(y_true, axis=axis)
y_pred = tf.linalg.l2_normalize(y_pred, axis=axis)
return tf.reduce_sum(y_true * y_pred, axis=axis)
| Computes the cosine similarity between labels and predictions.
Args:
y_true: The ground truth values.
y_pred: The prediction values.
axis: (Optional) Defaults to -1. The dimension along which the cosine
similarity is computed.
Returns:
Cosine similarity value.
| 36 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def cosine_similarity(y_true, y_pred, axis=-1):
y_true = tf.linalg.l2_normalize(y_true, axis=axis)
y_pred = tf.linalg.l2_normalize(y_pred, axis=axis)
return tf.reduce_sum(y_true * y... |
1,786 | def rotate(self, theta):
a = math.cos(theta)
b = math.sin(theta)
mtx = self._mtx
# Operating and assigning one scalar at a time is much faster.
(xx, xy, x0), (yx, yy, y0), _ = mtx.tolist()
# mtx = [[a -b 0], [b a 0], [0 0 1]] * mtx
mtx[0, 0] = a * xx - b ... |
Add a rotation (in radians) to this transform in place.
Returns *self*, so this method can easily be chained with more
calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
and :meth:`scale`.
| 28 | 110 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def rotate(self, theta):
a = math.cos(theta)
b = math.sin(theta)
mtx = self._mtx
# Operating and assigning one scalar at a time is much faster.
... |
1,787 | def call_load(self, other_args):
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="load",
description=,
)
parser.add_argument(
"-c",
"--coin",
... | Process load command.Load crypto currency to perform analysis on.
Yahoo Finance is used as default source.
Other sources can be used such as 'ccxt' or 'cg' with --source.
If you select 'ccxt', you can then select any exchange with --exchange.
You can also select a specifi... | 49 | 198 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def call_load(self, other_args):
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
... |
1,788 | def render_markdown(value):
schemes = '|'.join(get_config().ALLOWED_URL_SCHEMES)
# Strip HTML tags
value = strip_tags(value)
# Sanitize Markdown links
pattern = fr'\[([^\]]+)\]\((?!({schemes})).*:(.+)\)'
value = re.sub(pattern, '[\\1](\\3)', value, flags=re.IGNORECASE)
# Sanitize Mar... |
Render a string as Markdown. This filter is invoked as "markdown":
{{ md_source_text|markdown }}
| 14 | 72 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def render_markdown(value):
schemes = '|'.join(get_config().ALLOWED_URL_SCHEMES)
# Strip HTML tags
value = strip_tags(value)
# Sanitize Markdown links
pattern = fr... |
1,789 | def _try_breadth_first(tasks, user):
tasks = tasks.annotate(annotations_count=Count('annotations'))
max_annotations_count = tasks.aggregate(Max('annotations_count'))['annotations_count__max']
if max_annotations_count == 0:
# there is no any labeled tasks found
return
# find any ta... | Try to find tasks with maximum amount of annotations, since we are trying to label tasks as fast as possible
| 20 | 62 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _try_breadth_first(tasks, user):
tasks = tasks.annotate(annotations_count=Count('annotations'))
max_annotations_count = tasks.aggregate(Max('annotations_count'))['annotatio... |
1,790 | def test_pad_batch_dynamic_max(self):
view_requirements = {
"state_in_0": ViewRequirement(
"state_out_0",
shift=[-1],
used_for_training=False,
used_for_compute_actions=True,
batch_repeat_value=1,
)
... | Test pad_batch_to_sequences_of_same_size when dynamic_max = True | 6 | 66 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_pad_batch_dynamic_max(self):
view_requirements = {
"state_in_0": ViewRequirement(
"state_out_0",
shift=[-1],
... |
1,791 | def sensors_fans():
ret = collections.defaultdict(list)
basenames = glob.glob('/sys/class/hwmon/hwmon*/fan*_*')
if not basenames:
# CentOS has an intermediate /device directory:
# https://github.com/giampaolo/psutil/issues/971
basenames = glob.glob('/sys/class/hwmon/hwmon*/devic... | Return hardware fans info (for CPU and other peripherals) as a
dict including hardware label and current speed.
Implementation notes:
- /sys/class/hwmon looks like the most recent interface to
retrieve this info, and this implementation relies on it
only (old distros will probably use something... | 54 | 61 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def sensors_fans():
ret = collections.defaultdict(list)
basenames = glob.glob('/sys/class/hwmon/hwmon*/fan*_*')
if not basenames:
# CentOS has an intermediate /devic... |
1,792 | def factory(cls, loader):
cls.__check_eager_loader(loader)
return lambda *args, **kwargs: cls(loader(*args, **kwargs))
| Construct a callable which returns the eager loader made lazy. | 10 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def factory(cls, loader):
cls.__check_eager_loader(loader)
return lambda *args, **kwargs: cls(loader(*args, **kwargs))
```
###Assistant : Construct a ca... |
1,793 | def test_table_block_caption_render(self):
value = {
"table_caption": "caption",
"first_row_is_table_header": False,
"first_col_is_header": False,
"data": [
["Test 1", "Test 2", "Test 3"],
[None, None, None],
... |
Test a generic render with caption.
<table>
<caption>caption</caption>
<tbody>
<tr><td>Test 1</td><td>Test 2</td><td>Test 3</td></tr>
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td><... | 17 | 40 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_table_block_caption_render(self):
value = {
"table_caption": "caption",
"first_row_is_table_header": False,
"first_col_is_header... |
1,794 | def stream_config_without_start_date():
return {
"client_id": "fake_client_id",
"client_secret": "fake_client_secret",
"refresh_token": "fake_refresh_token",
"is_sandbox": False,
"wait_timeout": 15,
}
| Generates streams settings for REST logic without start_date | 8 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def stream_config_without_start_date():
return {
"client_id": "fake_client_id",
"client_secret": "fake_client_secret",
"refresh_token": "fake_refresh_token",... |
1,795 | async def relay(self):
while True:
message = await self.queue.get()
try:
await self.send(message)
self.queue.task_done()
except RuntimeError:
# The connection was closed, just exit the task
return
|
Relay messages from the channel's queue and send them out. This is started
as a task.
| 16 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def relay(self):
while True:
message = await self.queue.get()
try:
await self.send(message)
self.queue.task_don... |
1,796 | def q_sample(self, x_start, t, noise=None):
if noise is None:
# noise = th.randn_like(x_start)
noise = paddle.randn(x_start.shape, x_start.dtype)
assert noise.shape == x_start.shape
return (_extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_star... |
Diffuse the data for a given number of diffusion steps.
In other words, sample from q(x_t | x_0).
:param x_start: the initial data batch.
:param t: the number of diffusion steps (minus 1). Here, 0 means one step.
:param noise: if specified, the split-out normal noise.
... | 52 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def q_sample(self, x_start, t, noise=None):
if noise is None:
# noise = th.randn_like(x_start)
noise = paddle.randn(x_start.shape, x_start.dtype)
... |
1,797 | def get_views(self):
query = f"SELECT * FROM information_schema.views WHERE table_schema NOT IN ('information_schema', 'pg_catalog')"
result = self.run_native_query(query)
return result
|
List all views in PostgreSQL without the system views information_schema and pg_catalog
| 12 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_views(self):
query = f"SELECT * FROM information_schema.views WHERE table_schema NOT IN ('information_schema', 'pg_catalog')"
result = self.run_native_query(... |
1,798 | def verify_ogr_field(self, ogr_field, model_field):
if isinstance(ogr_field, OFTString) and isinstance(
model_field, (models.CharField, models.TextField)
):
if self.encoding and ogr_field.value is not None:
# The encoding for OGR data sources may be speci... |
Verify if the OGR Field contents are acceptable to the model field. If
they are, return the verified value, otherwise raise an exception.
| 23 | 274 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def verify_ogr_field(self, ogr_field, model_field):
if isinstance(ogr_field, OFTString) and isinstance(
model_field, (models.CharField, models.TextField)
... |
1,799 | def get_streamer():
if 'JINA_STREAMER_ARGS' in os.environ:
args_dict = json.loads(os.environ['JINA_STREAMER_ARGS'])
return GatewayStreamer(**args_dict)
else:
raise OSError('JINA_STREAMER_ARGS environment variable is not set')
|
Return a streamer object based on the current environment context.
The streamer object is contructed using runtime arguments stored in the `JINA_STREAMER_ARGS` environment variable.
If this method is used outside a Jina context (process not controlled/orchestrated by jina), this method will
... | 58 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_streamer():
if 'JINA_STREAMER_ARGS' in os.environ:
args_dict = json.loads(os.environ['JINA_STREAMER_ARGS'])
return GatewayStreamer(**args_dic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.