Unnamed: 0
int64
0
2.93k
code
stringlengths
101
62.2k
docs
stringlengths
51
10.7k
doc_len
int64
4
1.74k
words
int64
4
4.82k
lang
stringclasses
1 value
prompt
stringlengths
320
71.2k
2,500
def check_result_same(results, pipeline_results, check_keys): for key in check_keys: if results.get(key, None) is None: continue if isinstance(results[key], (BitmapMasks, PolygonMasks)): assert_allclose(pipeline_results[key].to_ndarray(), resu...
Check whether the ``pipeline_results`` is the same with the predefined ``results``. Args: results (dict): Predefined results which should be the standard output of the transform pipeline. pipeline_results (dict): Results processed by the transform pipeline. check...
46
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_result_same(results, pipeline_results, check_keys): for key in check_keys: if results.get(key, None) is None: continue if isinstance(results[ke...
2,501
def get_rasa_sdk_version() -> Text: dependencies_filename = "pyproject.toml" toml_data = toml.load(project_root() / dependencies_filename) try: sdk_version = toml_data["tool"]["poetry"]["dependencies"]["rasa-sdk"] return sdk_version[1:].strip() except AttributeError: raise ...
Find out what the referenced version of the Rasa SDK is.
11
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_rasa_sdk_version() -> Text: dependencies_filename = "pyproject.toml" toml_data = toml.load(project_root() / dependencies_filename) try: sdk_version = toml_d...
2,502
def test_update_omitted_version(self) -> None: version = self.get_success( self.handler.create_version( self.local_user, { "algorithm": "m.megolm_backup.v1", "auth_data": "first_version_auth_data", }, ...
Check that the update succeeds if the version is missing from the body
13
68
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_update_omitted_version(self) -> None: version = self.get_success( self.handler.create_version( self.local_user, { ...
2,503
def parameter_value(self, other, u, v=None): from sympy.geometry.point import Point if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if not isinstance(other, Point): raise ValueError("other must be a point") if ot...
Return the parameter(s) corresponding to the given point. Examples ======== >>> from sympy import pi, Plane >>> from sympy.abc import t, u, v >>> p = Plane((2, 0, 0), (0, 0, 1), (0, 1, 0)) By default, the parameter value returned defines a point that is a dista...
139
104
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def parameter_value(self, other, u, v=None): from sympy.geometry.point import Point if not isinstance(other, GeometryEntity): other = Point(other, dim=se...
2,504
def orthographic_projection(X, camera): camera = camera.reshape((-1, 1, 3)) X_trans = X[:, :, :2] + camera[:, :, 1:] shape = paddle.shape(X_trans) X_2d = (camera[:, :, 0] * X_trans.reshape((shape[0], -1))).reshape(shape) return X_2d @register
Perform orthographic projection of 3D points X using the camera parameters Args: X: size = [B, N, 3] camera: size = [B, 3] Returns: Projected 2D points -- size = [B, N, 2]
33
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def orthographic_projection(X, camera): camera = camera.reshape((-1, 1, 3)) X_trans = X[:, :, :2] + camera[:, :, 1:] shape = paddle.shape(X_trans) X_2d = (camera[:, :, 0...
2,505
def _load_state_id(self, state_id): remote_calls = [ worker.load_state_stream.remote(state_id) for worker in self.remote_workers ] return remote_calls
Loads the object with id `state_id` to all workers.
9
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _load_state_id(self, state_id): remote_calls = [ worker.load_state_stream.remote(state_id) for worker in self.remote_workers ] return remote_...
2,506
def __new__(cls, p1, pt=None, angle=None, **kwargs): p1 = Point(p1, dim=2) if pt is not None and angle is None: try: p2 = Point(pt, dim=2) except (NotImplementedError, TypeError, ValueError): raise ValueError(filldedent()) if p1 == p2: ...
The 2nd argument was not a valid Point; if it was meant to be an angle it should be given with keyword "angle".
23
210
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def __new__(cls, p1, pt=None, angle=None, **kwargs): p1 = Point(p1, dim=2) if pt is not None and angle is None: try: p2 = Point(pt, dim=2) ...
2,507
def delegate_command(args, host_state, exclude, require): # type: (EnvironmentConfig, HostState, t.List[str], t.List[str]) -> None con = host_state.controller_profile.get_origin_controller_connection() working_directory = host_state.controller_profile.get_working_directory() host_delegation = not isin...
Delegate execution based on the provided host state.
8
231
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def delegate_command(args, host_state, exclude, require): # type: (EnvironmentConfig, HostState, t.List[str], t.List[str]) -> None con = host_state.controller_profile.get_origin_co...
2,508
def test_in_predicate_requires_an_iterable(tmp_path, engine, filter_value): path = tmp_path / "gh_8720_pandas.parquet" df = pd.DataFrame( {"A": [1, 2, 3, 4], "B": [1, 1, 2, 2]}, ) df.to_parquet(path, engine=engine) with pytest.raises(TypeError, match="Value of 'in' filter"): dd....
Regression test for https://github.com/dask/dask/issues/8720
4
75
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_in_predicate_requires_an_iterable(tmp_path, engine, filter_value): path = tmp_path / "gh_8720_pandas.parquet" df = pd.DataFrame( {"A": [1, 2, 3, 4], "B": [1, 1,...
2,509
def only_targets(self, target_type): # type: (t.Type[THostConfig]) -> t.List[THostConfig] if not self.targets: raise Exception('There must be one or more targets.') assert type_guard(self.targets, target_type) return t.cast(t.List[THostConfig], self.targets)
Return a list of target host configurations. Requires that there are one or more targets, all the specified type.
19
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def only_targets(self, target_type): # type: (t.Type[THostConfig]) -> t.List[THostConfig] if not self.targets: raise Exception('There must be one or more target...
2,510
def _get_animated_artists(self): return tuple([a for ax_ in self.ax.get_figure().get_axes() for a in ax_.get_children() if a.get_animated() and a not in self.artists])
Convenience method to get all animated artists of a figure, except those already present in self.artists. 'z_order' is ignored.
19
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_animated_artists(self): return tuple([a for ax_ in self.ax.get_figure().get_axes() for a in ax_.get_children() if a.get_...
2,511
def new_gridlines(self, ax): gridlines = GridlinesCollection( None, transform=ax.transData, colors=mpl.rcParams['grid.color'], linestyles=mpl.rcParams['grid.linestyle'], linewidths=mpl.rcParams['grid.linewidth']) ax._set_artist_props(gridlines) gridli...
Create and return a new GridlineCollection instance. *which* : "major" or "minor" *axis* : "both", "x" or "y"
18
35
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def new_gridlines(self, ax): gridlines = GridlinesCollection( None, transform=ax.transData, colors=mpl.rcParams['grid.color'], linestyles=mpl.rcParam...
2,512
def duplicates_removed(it, already_seen=()): lst = [] seen = set() for i in it: if i in seen or i in already_seen: continue lst.append(i) seen.add(i) return lst
Returns a list with duplicates removed from the iterable `it`. Order is preserved.
13
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def duplicates_removed(it, already_seen=()): lst = [] seen = set() for i in it: if i in seen or i in already_seen: continue lst.append(i) ...
2,513
def masked_all(shape, dtype=float): a = masked_array(np.empty(shape, dtype), mask=np.ones(shape, make_mask_descr(dtype))) return a
Empty masked array with all elements masked. Return an empty masked array of the given shape and dtype, where all the data are masked. Parameters ---------- shape : int or tuple of ints Shape of the required MaskedArray, e.g., ``(2, 3)`` or ``2``. dtype : dtype, optional D...
136
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def masked_all(shape, dtype=float): a = masked_array(np.empty(shape, dtype), mask=np.ones(shape, make_mask_descr(dtype))) return a ``` ###Assi...
2,514
def closeness_centrality(G, u=None, distance=None, wf_improved=True): r if G.is_directed(): G = G.reverse() # create a reversed graph view if distance is not None: # use Dijkstra's algorithm with specified attribute as edge weight path_length = functools.partial( nx.sin...
Compute closeness centrality for nodes. Closeness centrality [1]_ of a node `u` is the reciprocal of the average shortest path distance to `u` over all `n-1` reachable nodes. .. math:: C(u) = \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)}, where `d(v, u)` is the shortest-path distance between `v` an...
467
125
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def closeness_centrality(G, u=None, distance=None, wf_improved=True): r if G.is_directed(): G = G.reverse() # create a reversed graph view if distance is not None: ...
2,515
async def _remove_old_push_actions_that_have_rotated(self) -> None: # We want to clear out anything that is older than a day that *has* already # been rotated. rotated_upto_stream_ordering = await self.db_pool.simple_select_one_onecol( table="event_push_summary_stream_order...
Clear out old push actions that have been summarised.
9
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def _remove_old_push_actions_that_have_rotated(self) -> None: # We want to clear out anything that is older than a day that *has* already # been rotated. ...
2,516
def test_indent(): multiline_string = indented_multiline_string = assert indented_multiline_string == _indent(multiline_string, 4)
Assert that indenting a multiline string by 4 spaces prepends 4 spaces before each new line.test test1 test2 test3 test test1 test2 test3
23
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_indent(): multiline_string = indented_multiline_string = assert indented_multiline_string == _indent(multiline_string, 4) ``` ###Assistant : Asser...
2,517
def update_inputs_outputs_dims(model, input_dims, output_dims): # type: (ModelProto, Dict[Text, List[Any]], Dict[Text, List[Any]]) -> ModelProto dim_param_set = set() # type: Set[Text]
This function updates the dimension sizes of the model's inputs and outputs to the values provided in input_dims and output_dims. if the dim value provided is negative, a unique dim_param will be set for that dimension. Example. if we have the following shape for inputs and outputs: ...
102
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def update_inputs_outputs_dims(model, input_dims, output_dims): # type: (ModelProto, Dict[Text, List[Any]], Dict[Text, List[Any]]) -> ModelProto dim_param_set = set() # type: Set[...
2,518
def get_aliased_columns(aliased_columns, model_alias, targets, mode=None): for col in targets: if mode == 'input': if str(col.parts[0]) != model_alias and col.alias is not None: aliased_columns[aliased_columns.index(col.parts[-1])] = str(col.alias) if mode == 'outpu...
This method assumes mdb_sql will alert if there are two columns with the same alias
15
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_aliased_columns(aliased_columns, model_alias, targets, mode=None): for col in targets: if mode == 'input': if str(col.parts[0]) != model_alias and col.al...
2,519
def get_model_urls(app_label, model_name): paths = [] # Retrieve registered views for this model try: views = registry['views'][app_label][model_name] except KeyError: # No views have been registered for this model views = [] for view in views: # Import the vie...
Return a list of URL paths for detail views registered to the given model. Args: app_label: App/plugin name model_name: Model name
21
66
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_model_urls(app_label, model_name): paths = [] # Retrieve registered views for this model try: views = registry['views'][app_label][model_name] except Ke...
2,520
def head(self, url, **kwargs): r kwargs.setdefault("allow_redirects", False) return self.request("HEAD", url, **kwargs)
Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
24
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def head(self, url, **kwargs): r kwargs.setdefault("allow_redirects", False) return self.request("HEAD", url, **kwargs) ``` ###Assistant : Sends a HEAD ...
2,521
async def get_and_submit_flow_runs(self) -> List[FlowRun]: if not self.started: raise RuntimeError("Agent is not started. Use `async with OrionAgent()...`") self.logger.debug("Checking for flow runs...") submittable_runs = await self.client.read_flow_runs( sort...
Queries for scheduled flow runs and submits them for execution in parallel
12
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def get_and_submit_flow_runs(self) -> List[FlowRun]: if not self.started: raise RuntimeError("Agent is not started. Use `async with OrionAgent()...`") ...
2,522
def get_quoted_string(value): quoted_string = QuotedString() if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) quoted_string.append(token) token, value = get_bare_quoted_string(value) quoted_string.append(token) if value and value[0] in CFWS_LEADER: to...
quoted-string = [CFWS] <bare-quoted-string> [CFWS] 'bare-quoted-string' is an intermediate class defined by this parser and not by the RFC grammar. It is the quoted string without any attached CFWS.
29
35
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_quoted_string(value): quoted_string = QuotedString() if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) quoted_string.append(token) ...
2,523
def test_defined_keyword_exist_in_schema(self, keyword, discovered_catalog): schemas_errors = [] for stream_name, stream in discovered_catalog.items(): check_result = find_keyword_schema(stream.json_schema, key=keyword) if check_result: schemas_errors.app...
Checking for the presence of not allowed keywords within each json schema
12
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_defined_keyword_exist_in_schema(self, keyword, discovered_catalog): schemas_errors = [] for stream_name, stream in discovered_catalog.items(): c...
2,524
def normalize_path_patterns(patterns): patterns = [os.path.normcase(p) for p in patterns] dir_suffixes = {"%s*" % path_sep for path_sep in {"/", os.sep}} norm_patterns = [] for pattern in patterns: for dir_suffix in dir_suffixes: if pattern.endswith(dir_suffix): ...
Normalize an iterable of glob style patterns based on OS.
10
39
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def normalize_path_patterns(patterns): patterns = [os.path.normcase(p) for p in patterns] dir_suffixes = {"%s*" % path_sep for path_sep in {"/", os.sep}} norm_patterns = [] ...
2,525
def get_protobuf_schema() -> GeneratedProtocolMessageType: return ErrorResponseMessage_PB
Return the type of protobuf object which stores a class of this type As a part of serialization and deserialization, we need the ability to lookup the protobuf object type directly from the object type. This static method allows us to do this. Importantly, this method is also used to cre...
112
6
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_protobuf_schema() -> GeneratedProtocolMessageType: return ErrorResponseMessage_PB ``` ###Assistant : Return the type of protobuf object which stores a ...
2,526
def test_remote_media_cache_retention(self) -> None: # Advance 31 days (in seconds) self.reactor.advance(31 * 24 * 60 * 60) # Check that media has been correctly purged. # Local media should be unaffected. # Remote media accessed <30 days ago should still exist. ...
Tests that entries from the remote media cache that have not been accessed recently is purged, while local media is unaffected.
21
59
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_remote_media_cache_retention(self) -> None: # Advance 31 days (in seconds) self.reactor.advance(31 * 24 * 60 * 60) # Check that media has been corr...
2,527
def setmodulation(self, modu): # type: (int) -> bool # According to https://nmap.org/npcap/guide/npcap-devguide.html#npcap-feature-dot11 # noqa: E501 self._check_npcap_requirement() _modus = { 0: "dsss", 1: "fhss", 2: "irbaseband", ...
Set the interface modulation. It can be: - 0: dsss - 1: fhss - 2: irbaseband - 3: ofdm - 4: hrdss - 5: erp - 6: ht - 7: vht - 8: ihv - 9: mimo-ofdm - 10: mimo-ofdm - the value directly ...
48
54
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def setmodulation(self, modu): # type: (int) -> bool # According to https://nmap.org/npcap/guide/npcap-devguide.html#npcap-feature-dot11 # noqa: E501 self._...
2,528
def _on_connection_error(self, connection, exception): log.error("Failed to connect", exc_info=True)
Invoked by pika when connection on connection error :param connection: :param exception: :return:
13
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _on_connection_error(self, connection, exception): log.error("Failed to connect", exc_info=True) ``` ###Assistant : Invoked by pika when connection...
2,529
def is_monotonic_decreasing(self) -> bool: # monotonic decreasing if and only if reverse is monotonic increasing return self[::-1].is_monotonic_increasing
Return a boolean if the values are equal or decreasing.
10
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_monotonic_decreasing(self) -> bool: # monotonic decreasing if and only if reverse is monotonic increasing return self[::-1].is_monotonic_increasing `...
2,530
def test_sends_assignment_notification(self): url = f"/api/0/issues/{self.group.id}/" with self.tasks(): response = self.client.put(url, format="json", data={"assignedTo": self.user.username}) assert response.status_code == 200, response.content msg = mail.outbox[0...
Test that an email AND Slack notification are sent with the expected values when an issue is assigned.
18
70
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_sends_assignment_notification(self): url = f"/api/0/issues/{self.group.id}/" with self.tasks(): response = self.client.put(url, format="json", ...
2,531
def _ask_default(self, default=''): self.prompt_output.write('Please enter the default value as valid Python.') if default: self.prompt_output.write( f"Accept the default '{default}' by pressing 'Enter' or " f"provide another value." ) ...
Prompt for a default value. The ``default`` argument allows providing a custom default value (as a string) which will be shown to the user and used as the return value if the user doesn't provide any other input.
38
119
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _ask_default(self, default=''): self.prompt_output.write('Please enter the default value as valid Python.') if default: self.prompt_output.write( ...
2,532
def reset_modules(self) -> None: self.modules = {} self.update_modules() self.parse_modules()
Reset the loaded modules list. This is called from cleanup to clear temporarily loaded modules.
15
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def reset_modules(self) -> None: self.modules = {} self.update_modules() self.parse_modules() ``` ###Assistant : Reset the loaded modules list. ...
2,533
def test_ddppo_compilation(self): config = ppo.ddppo.DEFAULT_CONFIG.copy() config["num_gpus_per_worker"] = 0 num_iterations = 2 for _ in framework_iterator(config, frameworks="torch"): trainer = ppo.ddppo.DDPPOTrainer(config=config, env="CartPole-v0") fo...
Test whether a DDPPOTrainer can be built with both frameworks.
10
56
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_ddppo_compilation(self): config = ppo.ddppo.DEFAULT_CONFIG.copy() config["num_gpus_per_worker"] = 0 num_iterations = 2 for _ in framework_i...
2,534
def log_cosh(y_true, y_pred): y_pred = tf.convert_to_tensor(y_pred) y_true = tf.cast(y_true, y_pred.dtype) def _logcosh(x): return x + tf.math.softplus(-2. * x) - tf.cast( tf.math.log(2.), x.dtype) return backend.mean(_logcosh(y_pred - y_true), axis=-1) @keras_export('keras.metrics.categorica...
Logarithm of the hyperbolic cosine of the prediction error. `log(cosh(x))` is approximately equal to `(x ** 2) / 2` for small `x` and to `abs(x) - log(2)` for large `x`. This means that 'logcosh' works mostly like the mean squared error, but will not be so strongly affected by the occasional wildly incorrect p...
131
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def log_cosh(y_true, y_pred): y_pred = tf.convert_to_tensor(y_pred) y_true = tf.cast(y_true, y_pred.dtype) def _logcosh(x): return x + tf.math.softplus(-2. * x) - tf.cast( ...
2,535
def make_predict_function(self, force=False): if self.predict_function is not None and not force: return self.predict_function
Creates a function that executes one step of inference. This method can be overridden to support custom inference logic. This method is called by `Model.predict` and `Model.predict_on_batch`. Typically, this method directly controls `tf.function` and `tf.distribute.Strategy` settings, ...
110
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def make_predict_function(self, force=False): if self.predict_function is not None and not force: return self.predict_function ``` ###Assistant : Cr...
2,536
def fit(self, X, y, **fit_params): self._validate_params() return self._fit(X, y, **fit_params)
Fit the RFE model and then the underlying estimator on the selected features. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. y : array-like of shape (n_samples,) The target values. **fi...
58
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def fit(self, X, y, **fit_params): self._validate_params() return self._fit(X, y, **fit_params) ``` ###Assistant : Fit the RFE model and then the underl...
2,537
def test_invalid_number_selection_fails(): number_string = "99999999" result = get_first_menu_and_fail(number_string) lines = result.stdout.splitlines() # Strange string addition are due to coloring, I believe assert lines[-1] == f"\x1b[31mInvalid selection {number_string}\x1b[0m" assert re...
We need to make sure that if we give an invalid number that the CLI will exit.
17
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_invalid_number_selection_fails(): number_string = "99999999" result = get_first_menu_and_fail(number_string) lines = result.stdout.splitlines() # Strange string...
2,538
def filldedent(s, w=70, **kwargs): return '\n' + fill(dedent(str(s)).strip('\n'), width=w, **kwargs)
Strips leading and trailing empty lines from a copy of ``s``, then dedents, fills and returns it. Empty line stripping serves to deal with docstrings like this one that start with a newline after the initial triple quote, inserting an empty line at the beginning of the string. Additional keyw...
61
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def filldedent(s, w=70, **kwargs): return '\n' + fill(dedent(str(s)).strip('\n'), width=w, **kwargs) ``` ###Assistant : Strips leading and trailing empty lines fr...
2,539
def in1d(ar1, ar2, assume_unique=False, invert=False, kind=None): # Ravel both arrays, behavior for the first array could be different ar1 = np.asarray(ar1).ravel() ar2 = np.asarray(ar2).ravel() # Ensure that iteration through object arrays yields size-1 arrays if ar2.dtype == object: ...
Test whether each element of a 1-D array is also present in a second array. Returns a boolean array the same length as `ar1` that is True where an element of `ar1` is in `ar2` and False otherwise. We recommend using :func:`isin` instead of `in1d` for new code. Parameters ---------- ar1 :...
485
528
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def in1d(ar1, ar2, assume_unique=False, invert=False, kind=None): # Ravel both arrays, behavior for the first array could be different ar1 = np.asarray(ar1).ravel() ar2 = np...
2,540
def test_devices(self) -> None: # Login in as the user self._get_token() # Check that we don't see a new device in our devices list channel = self.make_request( "GET", "devices", b"{}", access_token=self.other_user_tok ) self.assertEqual(HTTPStatus.O...
Tests that logging in as a user doesn't create a new device for them.
14
50
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_devices(self) -> None: # Login in as the user self._get_token() # Check that we don't see a new device in our devices list channel = self.m...
2,541
def in_ipython() -> bool: try: eval('__IPYTHON__') except NameError: return False else: # pragma: no cover return True
Check whether we're in an ipython environment, including jupyter notebooks.
10
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def in_ipython() -> bool: try: eval('__IPYTHON__') except NameError: return False else: # pragma: no cover return True ``` ###Assistant...
2,542
def test_stroptions_deprecated_internal_subset(): with pytest.raises(ValueError, match="deprecated options must be a subset"): StrOptions({"a", "b", "c"}, deprecated={"a", "d"}) with pytest.raises(ValueError, match="internal options must be a subset"): StrOptions({"a", "b", "c"}, internal=...
Check that the deprecated and internal parameters must be subsets of options.
12
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_stroptions_deprecated_internal_subset(): with pytest.raises(ValueError, match="deprecated options must be a subset"): StrOptions({"a", "b", "c"}, deprecated={"a", "...
2,543
def test_change_view_without_object_change_permission(self): change_url = reverse("admin9:admin_views_article_change", args=(self.a1.pk,)) self.client.force_login(self.viewuser) response = self.client.get(change_url) self.assertEqual(response.context["title"], "View article") ...
The object should be read-only if the user has permission to view it and change objects of that type but not to change the current object.
26
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_change_view_without_object_change_permission(self): change_url = reverse("admin9:admin_views_article_change", args=(self.a1.pk,)) self.client.force_login(se...
2,544
def __getattr__(name): import warnings if name in __deprecated_num_index_names: warnings.warn( f"pandas.{name} is deprecated " "and will be removed from pandas in a future version. " "Use pandas.Index with the appropriate dtype instead.", FutureWarning, ...
pandas - a powerful data analysis and manipulation library for Python ===================================================================== **pandas** is a Python package providing fast, flexible, and expressive data structures designed to make working with "relational" or "labeled" data both easy and intuitive. It a...
289
355
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def __getattr__(name): import warnings if name in __deprecated_num_index_names: warnings.warn( f"pandas.{name} is deprecated " "and will be removed f...
2,545
def readlink(path, canonicalize=False): path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError("Path to link must be absolute.") if not os.path.islink(path): raise SaltInvocationError("A valid link was not specified.") if canonicalize: retur...
.. versionadded:: 2014.1.0 Return the path that a symlink points to If canonicalize is set to True, then it return the final target CLI Example: .. code-block:: bash salt '*' file.readlink /path/to/link
32
33
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def readlink(path, canonicalize=False): path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError("Path to link must be absolute.") if ...
2,546
def warns_deprecated_sympy(): with warns(SymPyDeprecationWarning): yield @contextlib.contextmanager
Shorthand for ``warns(SymPyDeprecationWarning)`` This is the recommended way to test that ``SymPyDeprecationWarning`` is emitted for deprecated features in SymPy. To test for other warnings use ``warns``. To suppress warnings without asserting that they are emitted use ``ignore_warnings``. .....
143
6
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def warns_deprecated_sympy(): with warns(SymPyDeprecationWarning): yield @contextlib.contextmanager ``` ###Assistant : Shorthand for ``warns(SymPyDeprecati...
2,547
def assert_array_equal(x, y, err_msg='', verbose=True, *, strict=False): __tracebackhide__ = True # Hide traceback for py.test assert_array_compare(operator.__eq__, x, y, err_msg=err_msg, verbose=verbose, header='Arrays are not equal', strict=strict)
Raises an AssertionError if two array_like objects are not equal. Given two array_like objects, check that the shape is equal and all elements of these objects are equal (but see the Notes for the special handling of a scalar). An exception is raised at shape mismatch or conflicting values. In con...
461
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def assert_array_equal(x, y, err_msg='', verbose=True, *, strict=False): __tracebackhide__ = True # Hide traceback for py.test assert_array_compare(operator.__eq__, x, y, err_m...
2,548
def update_from_data_x(self, x, ignore=None): x = np.ravel(x) self.update_from_data_xy(np.column_stack([x, np.ones(x.size)]), ignore=ignore, updatey=False)
Update the x-bounds of the `Bbox` based on the passed in data. After updating, the bounds will have positive *width*, and *x0* will be the minimal value. Parameters ---------- x : `~numpy.ndarray` Array of x-values. ignore : bool, optional ...
69
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def update_from_data_x(self, x, ignore=None): x = np.ravel(x) self.update_from_data_xy(np.column_stack([x, np.ones(x.size)]), ignore...
2,549
def test_https_malformed_referer(self): malformed_referer_msg = "Referer checking failed - Referer is malformed." req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_REFERER"] = "http://http://www.example.com/" mw = CsrfViewMiddleware(...
A POST HTTPS request with a bad referer is rejected.
10
157
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_https_malformed_referer(self): malformed_referer_msg = "Referer checking failed - Referer is malformed." req = self._get_POST_request_with_token() r...
2,550
def test_missing_cpp_namespace(self) -> None: yaml_str = output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline(output_error, )
\ backend: XLA supported: - absYou must provide a value for "cpp_namespace"
12
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_missing_cpp_namespace(self) -> None: yaml_str = output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline(output_error, ) ...
2,551
def single_source_dijkstra_path_length(G, source, cutoff=None, weight="weight"): return multi_source_dijkstra_path_length(G, {source}, cutoff=cutoff, weight=weight)
Find shortest weighted path lengths in G from a source node. Compute the shortest path length between source and all other reachable nodes for a weighted graph. Parameters ---------- G : NetworkX graph source : node label Starting node for path cutoff : integer or float, optional...
289
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def single_source_dijkstra_path_length(G, source, cutoff=None, weight="weight"): return multi_source_dijkstra_path_length(G, {source}, cutoff=cutoff, weight=weight) ``` ...
2,552
def print_help(self): has_ticker_start = "" if self.ticker else "[unvl]" has_ticker_end = "" if self.ticker else "[/unvl]" help_text = f console.print(text=help_text, menu="Stocks - Behavioural Analysis")
[cmds] load load a specific stock ticker for analysis [param]Ticker: [/param]{self.ticker.upper() or None} {has_ticker_start} [src][Finbrain][/src] headlines sentiment from 15+ major news headlines [src][Finnhub][/src] stats sentiment stats including comparison with sector{has_ticker_...
205
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def print_help(self): has_ticker_start = "" if self.ticker else "[unvl]" has_ticker_end = "" if self.ticker else "[/unvl]" help_text = f console.print(text=he...
2,553
def iterate_instructions(code_object): # The arg extension the EXTENDED_ARG opcode represents is automatically handled by get_instructions() but the # instruction is left in. Get rid of it to make subsequent parsing easier/safer. yield from (i for i in get_instructions(code_object) if i.opname != "EXTE...
Delivers the byte-code instructions as a continuous stream. Yields `dis.Instruction`. After each code-block (`co_code`), `None` is yielded to mark the end of the block and to interrupt the steam.
29
75
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def iterate_instructions(code_object): # The arg extension the EXTENDED_ARG opcode represents is automatically handled by get_instructions() but the # instruction is left in. Ge...
2,554
def fit(self) -> ResultGrid: if not self._is_ray_client: try: return self._local_tuner.fit() except Exception as e: raise TuneError( f"Tune run failed. " f'Please use tuner = Tuner.restore("' ...
Executes hyperparameter tuning job as configured and returns result. Failure handling: For the kind of exception that happens during the execution of a trial, one may inspect it together with stacktrace through the returned result grid. See ``ResultGrid`` for reference. Each trial may f...
112
61
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def fit(self) -> ResultGrid: if not self._is_ray_client: try: return self._local_tuner.fit() except Exception as e: ...
2,555
def _handle_coordinator_update(self) -> None: self._refresh() super()._handle_coordinator_update()
Handle updated data from the coordinator. Tests fails without this method.
11
6
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _handle_coordinator_update(self) -> None: self._refresh() super()._handle_coordinator_update() ``` ###Assistant : Handle updated data from ...
2,556
def _skew_1d(self, column, bias=True, nan_policy="propagate"): # import depends on scipy, not installed by default from dask.array import stats as da_stats if pd.Int64Dtype.is_dtype(column._meta_nonempty): column = column.astype("f8") if not np.issubdtype(column.dt...
1D version of the skew calculation. Uses the array version from da.stats in case we are passing in a single series
21
67
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _skew_1d(self, column, bias=True, nan_policy="propagate"): # import depends on scipy, not installed by default from dask.array import stats as da_stats ...
2,557
def test_device_classes_aligned(): for device_class in NumberDeviceClass: assert hasattr(SensorDeviceClass, device_class.name) assert getattr(SensorDeviceClass, device_class.name).value == device_class.value
Make sure all number device classes are also available in SensorDeviceClass.
11
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_device_classes_aligned(): for device_class in NumberDeviceClass: assert hasattr(SensorDeviceClass, device_class.name) assert getattr(SensorDeviceClass, dev...
2,558
def intersection_all(graphs): R = None for i, G in enumerate(graphs): G_nodes_set = set(G.nodes) G_edges_set = set(G.edges(keys=True) if G.is_multigraph() else G.edges()) if i == 0: # create new graph R = G.__class__() node_intersection = G_nodes...
Returns a new graph that contains only the nodes and the edges that exist in all graphs. Parameters ---------- graphs : iterable Iterable of NetworkX graphs Returns ------- R : A new graph with the same type as the first graph in list Raises ------ ValueError If ...
68
73
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def intersection_all(graphs): R = None for i, G in enumerate(graphs): G_nodes_set = set(G.nodes) G_edges_set = set(G.edges(keys=True) if G.is_multigraph() else ...
2,559
def _looks_like_red_hat_scheme() -> bool: from distutils.command.install import install from distutils.dist import Distribution cmd: Any = install(Distribution()) cmd.finalize_options() return ( cmd.exec_prefix == f"{os.path.normpath(sys.exec_prefix)}/local" and cmd.prefix == f...
Red Hat patches ``sys.prefix`` and ``sys.exec_prefix``. Red Hat's ``00251-change-user-install-location.patch`` changes the install command's ``prefix`` and ``exec_prefix`` to append ``"/local"``. This is (fortunately?) done quite unconditionally, so we create a default command object without any config...
38
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _looks_like_red_hat_scheme() -> bool: from distutils.command.install import install from distutils.dist import Distribution cmd: Any = install(Distribution()) cmd.f...
2,560
def _create_sql_query(self) -> str: escaper = ParamEscaper() maybe_with = "" if self._encryption is not None or self._credential is not None: maybe_encryption = "" if self._encryption is not None: maybe_encryption = self._generate_options("ENCRYPTION", esc...
COPY INTO {self._table_name} FROM {location} FILEFORMAT = {self._file_format} {validation}{files_or_pattern}{format_options}{copy_options}
9
184
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _create_sql_query(self) -> str: escaper = ParamEscaper() maybe_with = "" if self._encryption is not None or self._credential is not None: maybe_encryp...
2,561
def predict(self, x, **kwargs): proba = self.model.predict(x, **kwargs) if proba.shape[-1] > 1: classes = proba.argmax(axis=-1) else: classes = (proba > 0.5).astype("int32") return self.classes_[classes]
Returns the class predictions for the given test data. Args: x: array-like, shape `(n_samples, n_features)` Test samples where `n_samples` is the number of samples and `n_features` is the number of features. **kwargs: dictionary arguments ...
48
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def predict(self, x, **kwargs): proba = self.model.predict(x, **kwargs) if proba.shape[-1] > 1: classes = proba.argmax(axis=-1) else: ...
2,562
def resize_image_type0(self, img): limit_side_len = self.max_side_len h, w, _ = img.shape # limit the max side if max(h, w) > limit_side_len: if h > w: ratio = float(limit_side_len) / h else: ratio = float(limit_side_len) ...
resize image to a size multiple of 32 which is required by the network args: img(array): array with shape [h, w, c] return(tuple): img, (ratio_h, ratio_w)
26
106
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def resize_image_type0(self, img): limit_side_len = self.max_side_len h, w, _ = img.shape # limit the max side if max(h, w) > limit_side_len: ...
2,563
def metrics(self): metrics = [] if self._is_compiled: # TODO(omalleyt): Track `LossesContainer` and `MetricsContainer` objects # so that attr names are not load-bearing. if self.compiled_loss is not None: metrics += self.compiled_loss.metrics ...
Returns the model's metrics added using `compile()`, `add_metric()` APIs. Note: Metrics passed to `compile()` are available only after a `keras.Model` has been trained/evaluated on actual data. Examples: >>> inputs = tf.keras.layers.Input(shape=(3,)) >>> outputs = tf.keras.lay...
128
48
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def metrics(self): metrics = [] if self._is_compiled: # TODO(omalleyt): Track `LossesContainer` and `MetricsContainer` objects # so that attr...
2,564
def set_level(request, level): if not hasattr(request, "_messages"): return False request._messages.level = level return True
Set the minimum level of messages to be recorded, and return ``True`` if the level was recorded successfully. If set to ``None``, use the default level (see the get_level() function).
30
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_level(request, level): if not hasattr(request, "_messages"): return False request._messages.level = level return True ``` ###Assistant : S...
2,565
def all_pairs_lowest_common_ancestor(G, pairs=None): if not nx.is_directed_acyclic_graph(G): raise nx.NetworkXError("LCA only defined on directed acyclic graphs.") if len(G) == 0: raise nx.NetworkXPointlessConcept("LCA meaningless on null graphs.") if pairs is None: pairs = com...
Return the lowest common ancestor of all pairs or the provided pairs Parameters ---------- G : NetworkX directed graph pairs : iterable of pairs of nodes, optional (default: all pairs) The pairs of nodes of interest. If None, will find the LCA of all pairs of nodes. Yields ---...
208
92
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def all_pairs_lowest_common_ancestor(G, pairs=None): if not nx.is_directed_acyclic_graph(G): raise nx.NetworkXError("LCA only defined on directed acyclic graphs.") if le...
2,566
async def test_is_pickleable_after_start(self, task_runner): task_runner.client_kwargs["set_as_default"] = True
The task_runner must be picklable as it is attached to `PrefectFuture` objects Reimplemented to set Dask client as default to allow unpickling
22
7
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_is_pickleable_after_start(self, task_runner): task_runner.client_kwargs["set_as_default"] = True ``` ###Assistant : The task_runner must ...
2,567
def _add_callback_signalsafe(self, handle): self._add_callback(handle) self._write_to_self()
Like _add_callback() but called from a signal handler.
8
5
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _add_callback_signalsafe(self, handle): self._add_callback(handle) self._write_to_self() ``` ###Assistant : Like _add_callback() but called from a s...
2,568
def get_local_ffmpeg() -> Optional[Path]: ffmpeg_path = Path( get_spotdl_path(), "ffmpeg" + ".exe" if platform.system() == "Windows" else "" ) if ffmpeg_path.is_file(): return ffmpeg_path return None
Get local ffmpeg binary path or None if not found.
10
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_local_ffmpeg() -> Optional[Path]: ffmpeg_path = Path( get_spotdl_path(), "ffmpeg" + ".exe" if platform.system() == "Windows" else "" ) if ffmpeg_path.is_fi...
2,569
def _render_cmd(cmd, cwd, template, saltenv=None, pillarenv=None, pillar_override=None): if saltenv is None: saltenv = __opts__.get("saltenv", "base") if not template: return (cmd, cwd) # render the path as a template using path_template_engine as the engine if template not in salt...
If template is a valid template engine, process the cmd and cwd through that engine.
15
88
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _render_cmd(cmd, cwd, template, saltenv=None, pillarenv=None, pillar_override=None): if saltenv is None: saltenv = __opts__.get("saltenv", "base") if not template: ...
2,570
def test_windows_1252(self) -> None: html = b tree = decode_body(html, "http://example.com/test.html") og = parse_html_to_open_graph(tree, "http://example.com/test.html") self.assertEqual(og, {"og:title": "ó", "og:description": "Some text."})
A body which uses cp1252, but doesn't declare that. <html> <head><title>\xf3</title></head> <body> Some text. </body> </html>
16
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_windows_1252(self) -> None: html = b tree = decode_body(html, "http://example.com/test.html") og = parse_html_to_open_graph(tree, "http://example.co...
2,571
def square_root(value, default=_SENTINEL): try: return math.sqrt(float(value)) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("sqrt", value) return default
Filter and function to get square root of the value.
10
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def square_root(value, default=_SENTINEL): try: return math.sqrt(float(value)) except (ValueError, TypeError): if default is _SENTINEL: raise_no_defa...
2,572
async def test_track_task_functions(event_loop): hass = ha.HomeAssistant() try: assert hass._track_task hass.async_stop_track_tasks() assert not hass._track_task hass.async_track_tasks() assert hass._track_task finally: await hass.async_stop()
Test function to start/stop track task and initial state.
9
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_track_task_functions(event_loop): hass = ha.HomeAssistant() try: assert hass._track_task hass.async_stop_track_tasks() assert not hass._t...
2,573
def media_position_updated_at(self) -> datetime | None: if self._device.movie.play_status in KALEIDESCAPE_PLAYING_STATES: return utcnow() return None
When was the position of the current playing media valid.
10
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def media_position_updated_at(self) -> datetime | None: if self._device.movie.play_status in KALEIDESCAPE_PLAYING_STATES: return utcnow() return None ...
2,574
def write(self, data): if not isinstance(data, (bytes, bytearray, memoryview)): raise TypeError(f"data: expecting a bytes-like instance, " f"got {type(data).__name__}") if not data: return self._ssl_protocol._write_appdata(data)
Write some data bytes to the transport. This does not block; it buffers the data and arranges for it to be sent out asynchronously.
24
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def write(self, data): if not isinstance(data, (bytes, bytearray, memoryview)): raise TypeError(f"data: expecting a bytes-like instance, " ...
2,575
def _extract_color_tags(self): tags = re.finditer( r'<color\s+col="([^"]+)"(\s+offset="([^"]+)")?>(.+?)</color>', self.original_text, re.S, ) colormap = [] for tag in tags: start = self._count_real_chars(self.original_text[: tag.s...
Used to determine which parts (if any) of the string should be formatted with a custom color. Removes the ``<color>`` tag, as it is not part of Pango's markup and would cause an error. Note: Using the ``<color>`` tags is deprecated. As soon as the legacy syntax is gone, this function w...
54
73
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _extract_color_tags(self): tags = re.finditer( r'<color\s+col="([^"]+)"(\s+offset="([^"]+)")?>(.+?)</color>', self.original_text, re....
2,576
def write_readme(self, file_path, parametric_eq_peqs=None, fixed_band_eq_peq=None): file_path = os.path.abspath(file_path) dir_path = os.path.dirname(file_path) model = self.name # Write model s = '# {}\n'.format(model) s += 'See [usage instructions](https://git...
Writes README.md with picture and Equalizer APO settings.
8
239
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def write_readme(self, file_path, parametric_eq_peqs=None, fixed_band_eq_peq=None): file_path = os.path.abspath(file_path) dir_path = os.path.dirname(file_path) ...
2,577
def _get_execution_environment(): if os.environ.get("CI", "False").lower() == "true": execution_env = "ci" elif "google.colab" in sys.modules: execution_env = "colab" elif "KUBERNETES_SERVICE_HOST" in os.environ: execution_env = "kubernetes" elif HAYSTACK_DOCKER_CONTAINER in...
Identifies the execution environment that Haystack is running in. Options are: colab notebook, kubernetes, CPU/GPU docker container, test environment, jupyter notebook, python script
23
59
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_execution_environment(): if os.environ.get("CI", "False").lower() == "true": execution_env = "ci" elif "google.colab" in sys.modules: execution_env = "c...
2,578
def _ensure_html_response(url, session): # type: (str, PipSession) -> None scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url) if scheme not in {'http', 'https'}: raise _NotHTTP() resp = session.head(url, allow_redirects=True) raise_for_status(resp) _ensure_html_hea...
Send a HEAD request to the URL, and ensure the response contains HTML. Raises `_NotHTTP` if the URL is not available for a HEAD request, or `_NotHTML` if the content type is not text/html.
34
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _ensure_html_response(url, session): # type: (str, PipSession) -> None scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url) if scheme not in {'http', 'http...
2,579
def _parse_item(self) -> Optional[Tuple[Optional[Key], Item]]: self.mark() with self._state as state: while True: c = self._current if c == "\n": # Found a newline; Return all whitespace found up to this point. ...
Attempts to parse the next item and returns it, along with its key if the item is value-like.
18
120
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _parse_item(self) -> Optional[Tuple[Optional[Key], Item]]: self.mark() with self._state as state: while True: c = self._current ...
2,580
def _xreplace(self, rule): if self in rule: return rule[self], True elif rule: rule = self._dedupe_indices_in_rule(rule) args = [] changed = False for a in self.args: _xreplace = getattr(a, '_xreplace', None) ...
Helper for xreplace. Tracks whether a replacement actually occurred. Given that the rule has entries {old:new, ...}, this handles the fact that if a dummy index in new is the same as an index in self, the dummy index in new must be renamed.
44
55
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _xreplace(self, rule): if self in rule: return rule[self], True elif rule: rule = self._dedupe_indices_in_rule(rule) args = [...
2,581
async def async_turn_on(self) -> None: await self._client.play() await self._update_playlists(no_throttle=True)
Service to send the MPD the command to start playing.
10
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def async_turn_on(self) -> None: await self._client.play() await self._update_playlists(no_throttle=True) ``` ###Assistant : Service to send the M...
2,582
def _build_network_on_replica(model, mode, inputs=None, targets=None): # Need to do imports here since we run into a circular dependency error. from keras import models # pylint: disable=g-import-not-at-top from keras.engine import sequential # pylint: disable=g-import-not-at-top # We rely on th...
Build an updated model on replicas. We create a new Keras model while sharing the variables from the old graph. Building a new sub-graph is required since the original keras model creates placeholders for the input and the output that are not accessible till we call iterator.get_next() inside the step_...
163
122
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _build_network_on_replica(model, mode, inputs=None, targets=None): # Need to do imports here since we run into a circular dependency error. from keras import models # pylin...
2,583
def can_jit_compile(warn=False): if platform.system() == "Darwin" and "arm" in platform.processor().lower(): if warn: logging.warning( "Tensorflow is not compiled with XLA on Mac M1 Arm processors, " "so cannot set `jit_compile` to True." ) ...
Returns True if TensorFlow XLA is available for the platform.
10
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def can_jit_compile(warn=False): if platform.system() == "Darwin" and "arm" in platform.processor().lower(): if warn: logging.warning( "Tensorflo...
2,584
def __setstate__(self, state) -> None: # TODO (sven): Validate that our config and the config in state are compatible. # For example, the model architectures may differ. # Also, what should the behavior be if e.g. some training parameter # (e.g. lr) changed? if hasat...
Sets the algorithm to the provided state. Args: state: The state dict to restore this Algorithm instance to. `state` may have been returned by a call to an Algorithm's `__getstate__()` method.
31
165
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def __setstate__(self, state) -> None: # TODO (sven): Validate that our config and the config in state are compatible. # For example, the model architectures may di...
2,585
def test_http2_client_aborts(tctx, stream, when, how): server = Placeholder(Server) flow = Placeholder(HTTPFlow) playbook, cff = start_h2_client(tctx) resp = Placeholder(bytes)
Test handling of the case where a client aborts during request or response transmission. If the client aborts the request transmission, we must trigger an error hook, if the client disconnects during response transmission, no error hook is triggered.
39
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_http2_client_aborts(tctx, stream, when, how): server = Placeholder(Server) flow = Placeholder(HTTPFlow) playbook, cff = start_h2_client(tctx) resp = Placeholder...
2,586
def get_changelist_instance(self, request): list_display = self.get_list_display(request) list_display_links = self.get_list_display_links(request, list_display) # Add the action checkboxes if any actions are available. if self.get_actions(request): list_display = ["...
Return a `ChangeList` instance based on `request`. May raise `IncorrectLookupParameters`.
10
49
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_changelist_instance(self, request): list_display = self.get_list_display(request) list_display_links = self.get_list_display_links(request, list_display) ...
2,587
def _use_cholesky(u, m, n, params): a, b, c = params _, N = u.shape x = c * (u.T.conj() @ u) + jnp.eye(N, dtype=jnp.dtype(u)) # Pads the lower-right corner with the identity matrix to prevent the Cholesky # decomposition from failing due to the matrix not being PSD if padded with # zeros. x = _mask(x, ...
QDWH iteration using Cholesky decomposition. Args: u: a matrix, with static (padded) shape M x N m, n: the dynamic shape of the matrix, where m <= M and n <= N. params: the QDWH parameters.
36
103
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _use_cholesky(u, m, n, params): a, b, c = params _, N = u.shape x = c * (u.T.conj() @ u) + jnp.eye(N, dtype=jnp.dtype(u)) # Pads the lower-right corner with the identity matri...
2,588
def piecewise_integrate(self, x, **kwargs): from sympy.integrals import integrate return self.func(*[(integrate(e, x, **kwargs), c) for e, c in self.args])
Return the Piecewise with each expression being replaced with its antiderivative. To obtain a continuous antiderivative, use the :func:`~.integrate` function or method. Examples ======== >>> from sympy import Piecewise >>> from sympy.abc import x >>> p = Piecewi...
135
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def piecewise_integrate(self, x, **kwargs): from sympy.integrals import integrate return self.func(*[(integrate(e, x, **kwargs), c) for e, c in self.args]) ...
2,589
def check_send_to_ereader(entry): formats = list() book_formats = list() if len(entry.data): for ele in iter(entry.data): if ele.uncompressed_size < config.mail_size: formats.append(ele.format) if 'EPUB' in formats: book_formats.append({'format': ...
returns all available book formats for sending to E-Reader
9
114
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_send_to_ereader(entry): formats = list() book_formats = list() if len(entry.data): for ele in iter(entry.data): if ele.uncompressed_size < conf...
2,590
def Multinomial(syms, n, *p): if not isinstance(p[0], list): p = (list(p), ) return multivariate_rv(MultinomialDistribution, syms, n, p[0]) #------------------------------------------------------------------------------- # Negative Multinomial Distribution -----------------------------------------...
Creates a discrete random variable with Multinomial Distribution. The density of the said distribution can be found at [1]. Parameters ========== n : Positive integer Represents number of trials p : List of event probabilites Must be in the range of [0, 1] Returns ==...
117
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def Multinomial(syms, n, *p): if not isinstance(p[0], list): p = (list(p), ) return multivariate_rv(MultinomialDistribution, syms, n, p[0]) #---------------------------...
2,591
def psi_n(n, x, m, omega): # sympify arguments n, x, m, omega = map(S, [n, x, m, omega]) nu = m * omega / hbar # normalization coefficient C = (nu/pi)**Rational(1, 4) * sqrt(1/(2**n*factorial(n))) return C * exp(-nu* x**2 /2) * hermite(n, sqrt(nu)*x)
Returns the wavefunction psi_{n} for the One-dimensional harmonic oscillator. Parameters ========== n : the "nodal" quantum number. Corresponds to the number of nodes in the wavefunction. ``n >= 0`` x : x coordinate. m : Mass of the particle. omega : ...
66
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def psi_n(n, x, m, omega): # sympify arguments n, x, m, omega = map(S, [n, x, m, omega]) nu = m * omega / hbar # normalization coefficient C = (nu/pi)**Rational(1, ...
2,592
def getsourcefile(object): filename = getfile(object) all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:] all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:] if any(filename.endswith(s) for s in all_bytecode_suffixes): filename = (os.path.splitext(...
Return the filename that can be used to locate an object's source. Return None if no way can be identified to get the source.
24
85
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def getsourcefile(object): filename = getfile(object) all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:] all_bytecode_suffixes += importlib.machinery.OPT...
2,593
def module_repr(self, module): warnings.warn("importlib.abc.Loader.module_repr() is deprecated and " "slated for removal in Python 3.12", DeprecationWarning) # The exception will cause ModuleType.__repr__ to ignore this method. raise NotImplementedError
Return a module's repr. Used by the module type when the method does not raise NotImplementedError. This method is deprecated.
20
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def module_repr(self, module): warnings.warn("importlib.abc.Loader.module_repr() is deprecated and " "slated for removal in Python 3.12", DeprecationWa...
2,594
def test_need_validated_email(self): with self.assertRaises(SynapseError) as cm: self.get_success_or_raise( self.hs.get_pusherpool().add_or_update_pusher( user_id=self.user_id, access_token=self.token_id, kind="emai...
Test that we can only add an email pusher if the user has validated their email.
16
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_need_validated_email(self): with self.assertRaises(SynapseError) as cm: self.get_success_or_raise( self.hs.get_pusherpool().add_or_updat...
2,595
def test_get_existing_comments(self): doc = Document.objects.create( title="test", mime_type="application/pdf", content="this is a document which will have comments!", ) comment = Comment.objects.create( comment="This is a comment.", ...
GIVEN: - A document with a single comment WHEN: - API reuqest for document comments is made THEN: - The associated comment is returned
24
64
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_get_existing_comments(self): doc = Document.objects.create( title="test", mime_type="application/pdf", content="this is a docume...
2,596
def collate_full_clips(batch): max_mel_length = max([b[0].shape[1] for b in batch]) if len(batch) > 1 else batch[0][0].shape[1] max_audio_length = max([b[1].shape[0] for b in batch]) if len(batch) > 1 else batch[0][1].shape[0] mels = torch.zeros([len(batch), batch[0][0].shape[0], max_m...
This is used in tune_wavegrad.py. It pads sequences to the max length.
12
62
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def collate_full_clips(batch): max_mel_length = max([b[0].shape[1] for b in batch]) if len(batch) > 1 else batch[0][0].shape[1] max_audio_length = max([b[1].shape[0]...
2,597
def feature_test(self, name, force_flags=None, macros=[]): if force_flags is None: force_flags = self.feature_flags(name) self.dist_log( "testing feature '%s' with flags (%s)" % ( name, ' '.join(force_flags) )) # Each CPU feature must have C ...
Test a certain CPU feature against the compiler through its own check file. Parameters ---------- name : str Supported CPU feature name. force_flags : list or None, optional If None(default), the returned flags from `feature_flags()` ...
50
81
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def feature_test(self, name, force_flags=None, macros=[]): if force_flags is None: force_flags = self.feature_flags(name) self.dist_log( "te...
2,598
def get_file_path(self) -> str: if self.file_name is None: raise ValueError("Must specify file for SVGMobject") return get_full_vector_image_path(self.file_name)
Search for an existing file based on the specified file name.
11
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_file_path(self) -> str: if self.file_name is None: raise ValueError("Must specify file for SVGMobject") return get_full_vector_image_path(self.fi...
2,599
def default_config(self) -> Dict[str, Any]: base = super().default_config() base["redis"] = {"enabled": True} return base
Overrides the default config to enable Redis. Even if the test only uses make_worker_hs, the main process needs Redis enabled otherwise it won't create a Fake Redis server to listen on the Redis port and accept fake TCP connections.
39
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def default_config(self) -> Dict[str, Any]: base = super().default_config() base["redis"] = {"enabled": True} return base ``` ###Assistant : ...