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,900
def _pi_coeff(arg, cycles=1): r arg = sympify(arg) if arg is pi: return S.One elif not arg: return S.Zero elif arg.is_Mul: cx = arg.coeff(pi) if cx: c, x = cx.as_coeff_Mul() # pi is not included as coeff if c.is_Float: # recast...
When arg is a Number times $\pi$ (e.g. $3\pi/2$) then return the Number normalized to be in the range $[0, 2]$, else `None`. When an even multiple of $\pi$ is encountered, if it is multiplying something with known parity then the multiple is returned as 0 otherwise as 2. Examples ========...
98
122
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _pi_coeff(arg, cycles=1): r arg = sympify(arg) if arg is pi: return S.One elif not arg: return S.Zero elif arg.is_Mul: cx = arg.coeff(pi) ...
1,901
async def async_test_still(hass, info) -> tuple[dict[str, str], str | None]: fmt = None if not (url := info.get(CONF_STILL_IMAGE_URL)): return {}, None if not isinstance(url, template_helper.Template) and url: url = cv.template(url) url.hass = hass try: url = url.asy...
Verify that the still image is valid before we create an entity.
12
63
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def async_test_still(hass, info) -> tuple[dict[str, str], str | None]: fmt = None if not (url := info.get(CONF_STILL_IMAGE_URL)): return {}, None if not isinst...
1,902
def normalize(self, a): a = _convert_other(a, raiseit=True) return a.normalize(context=self)
normalize reduces an operand to its simplest form. Essentially a plus operation with all trailing zeros removed from the result. >>> ExtendedContext.normalize(Decimal('2.1')) Decimal('2.1') >>> ExtendedContext.normalize(Decimal('-2.0')) Decimal('-2') >>> Extende...
41
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def normalize(self, a): a = _convert_other(a, raiseit=True) return a.normalize(context=self) ``` ###Assistant : normalize reduces an operand to its simp...
1,903
def get_tables(self) -> StatusResponse: query = result = self.native_query(query) df = result.data_frame df = df[['TABLE_NAME' 'TABLE_TYPE']] result.data_frame = df.rename(columns={'TABLE_NAME': 'table_name', 'TABLE_TYPE': 'table_type'}) return result
Return list of entities that will be accessible as tables. Returns: HandlerResponse SELECT * FROM INFORMATION_SCHEMA.TABLES
16
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_tables(self) -> StatusResponse: query = result = self.native_query(query) df = result.data_frame df = df[['TABLE_NAME' 'TABLE_TYPE']] ...
1,904
def get_expected_values(self, image_inputs, batched=False): if not batched: image = image_inputs[0] if isinstance(image, Image.Image): w, h = image.size else: h, w = image.shape[1], image.shape[2] scale = self.size / min(w,...
This function computes the expected height and width when providing images to ViltFeatureExtractor, assuming do_resize is set to True with a scalar size and size_divisor.
25
131
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_expected_values(self, image_inputs, batched=False): if not batched: image = image_inputs[0] if isinstance(image, Image.Image): ...
1,905
def preprocss_testing_data(self, data): num_augs = len(data[0]['img']) batch_size = len(data) aug_batch_imgs = [] aug_batch_data_samples = [] # adjust `images` and `data_samples` to a list of list # outer list is test-time augmentation and inter list # ...
Process input data during training and testing phases. Args: data (list[dict]): The data to be processed, which comes from dataloader. The list indicate the batch dimension. Each dict contains these keys: - `img` (list[Tensor]): Image tensor with dif...
123
90
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def preprocss_testing_data(self, data): num_augs = len(data[0]['img']) batch_size = len(data) aug_batch_imgs = [] aug_batch_data_samples = [] ...
1,906
def list_templates() -> List[pathlib.Path]: return (pathlib.Path(__file__).parent / "templates").glob("*.html.j2")
List the available HTML templates. Returns: List[pathlib.Path]: A list of files with .html.j2 extensions inside ./templates/
16
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def list_templates() -> List[pathlib.Path]: return (pathlib.Path(__file__).parent / "templates").glob("*.html.j2") ``` ###Assistant : List the available HTML te...
1,907
def usable_pip_file(path): # type: (t.Optional[str]) -> bool return bool(path) and os.path.exists(path) and bool(os.path.getsize(path)) # Cryptography
Return True if the specified pip file is usable, otherwise False.
11
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def usable_pip_file(path): # type: (t.Optional[str]) -> bool return bool(path) and os.path.exists(path) and bool(os.path.getsize(path)) # Cryptography ``` ###Assist...
1,908
def binary_accuracy(y_true, y_pred, threshold=0.5): y_pred = tf.convert_to_tensor(y_pred) threshold = tf.cast(threshold, y_pred.dtype) y_pred = tf.cast(y_pred > threshold, y_pred.dtype) return backend.mean(tf.equal(y_true, y_pred), axis=-1) @keras_export('keras.metrics.categorical_accuracy') @tf.__internal...
Calculates how often predictions match binary labels. Standalone usage: >>> y_true = [[1], [1], [0], [0]] >>> y_pred = [[1], [1], [0], [0]] >>> m = tf.keras.metrics.binary_accuracy(y_true, y_pred) >>> assert m.shape == (4,) >>> m.numpy() array([1., 1., 1., 1.], dtype=float32) Args: y_true: Ground ...
86
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def binary_accuracy(y_true, y_pred, threshold=0.5): y_pred = tf.convert_to_tensor(y_pred) threshold = tf.cast(threshold, y_pred.dtype) y_pred = tf.cast(y_pred > threshold, y_pred.dt...
1,909
def _object2proto(self) -> SyftOblvClient_PB: return SyftOblvClient_PB( token=self.token, oblivious_user_id=self.oblivious_user_id, cookies=self.cookies, headers=self.headers, timeout=self.timeout, verify_ssl=self.verify_ssl, ...
Returns a protobuf serialization of self. As a requirement of all objects which inherit from Serializable, this method transforms the current object into the corresponding Protobuf object so that it can be further serialized. :return: returns a protobuf object :rtype: SyftOblvCli...
68
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _object2proto(self) -> SyftOblvClient_PB: return SyftOblvClient_PB( token=self.token, oblivious_user_id=self.oblivious_user_id, cooki...
1,910
def test_bulk_handle_digest_email_skips_deactivated_users(self) -> None: realm = get_realm("zulip") hamlet = self.example_user("hamlet") user_ids = list( UserProfile.objects.filter(is_bot=False, realm=realm).values_list("id", flat=True) ) do_deactivate_user(...
A user id may be added to the queue before the user is deactivated. In such a case, the function responsible for sending the email should correctly skip them.
29
50
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_bulk_handle_digest_email_skips_deactivated_users(self) -> None: realm = get_realm("zulip") hamlet = self.example_user("hamlet") user_ids = list( ...
1,911
def test_driver_4(): args_list = [ 'tests/tests.csv', '-is', ',', '-target', 'class', '-g', '1', '-p', '2', '-cv', '3', '-s', '42', '-config', 'TPOT light', '-v', '3' ...
Assert that the tpot_driver() in TPOT driver outputs normal result with verbosity = 3.
14
62
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_driver_4(): args_list = [ 'tests/tests.csv', '-is', ',', '-target', 'class', '-g', '1', '-p'...
1,912
async def test_set_avatar(self) -> None: handler = self.hs.get_sso_handler() # Create a new user to set avatar for reg_handler = self.hs.get_registration_handler() user_id = self.get_success(reg_handler.register_user(approved=True)) self.assertTrue( self.ge...
Tests successfully setting the avatar of a newly created user
10
55
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_set_avatar(self) -> None: handler = self.hs.get_sso_handler() # Create a new user to set avatar for reg_handler = self.hs.get_registration_ha...
1,913
def tune_decorated(api_key_file): tuner = tune.Tuner( decorated_train_function, tune_config=tune.TuneConfig( metric="loss", mode="min", ), param_space={ "mean": tune.grid_search([1, 2, 3, 4, 5]), "sd": tune.uniform(0.2, 0.8), ...
Example for using the @wandb_mixin decorator with the function API
10
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def tune_decorated(api_key_file): tuner = tune.Tuner( decorated_train_function, tune_config=tune.TuneConfig( metric="loss", mode="min", ...
1,914
def format_usage(self, usage): # type: (str) -> str msg = "\nUsage: {}\n".format(self.indent_lines(textwrap.dedent(usage), " ")) return msg
Ensure there is only one newline between usage and the first heading if there is no description.
17
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def format_usage(self, usage): # type: (str) -> str msg = "\nUsage: {}\n".format(self.indent_lines(textwrap.dedent(usage), " ")) return msg ``` ...
1,915
def from_index_summation(expr, first_index=None, last_index=None, dimensions=None): r from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix first_indices = [] ...
Parse expression of matrices with explicitly summed indices into a matrix expression without indices, if possible. This transformation expressed in mathematical notation: `\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}` Optional parameter ``first_...
133
35
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def from_index_summation(expr, first_index=None, last_index=None, dimensions=None): r from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_arra...
1,916
def get_views(self): q = f"SHOW FULL TABLES IN {self.database} WHERE TABLE_TYPE LIKE 'VIEW';" result = self.native_query(q) return result
Get more information about specific database views
7
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_views(self): q = f"SHOW FULL TABLES IN {self.database} WHERE TABLE_TYPE LIKE 'VIEW';" result = self.native_query(q) return result ``` ##...
1,917
def _mac(model, obs, h): B, n_agents = obs.size(0), obs.size(1) if not isinstance(obs, dict): obs = {"obs": obs} obs_agents_as_batches = {k: _drop_agent_dim(v) for k, v in obs.items()} h_flat = [s.reshape([B * n_agents, -1]) for s in h] q_flat, h_flat = model(obs_agents_as_batches, h_fl...
Forward pass of the multi-agent controller. Args: model: TorchModelV2 class obs: Tensor of shape [B, n_agents, obs_size] h: List of tensors of shape [B, n_agents, h_size] Returns: q_vals: Tensor of shape [B, n_agents, n_actions] h: Tensor of shape [B, n_agents, h_size] ...
41
55
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _mac(model, obs, h): B, n_agents = obs.size(0), obs.size(1) if not isinstance(obs, dict): obs = {"obs": obs} obs_agents_as_batches = {k: _drop_agent_dim(v) for k...
1,918
def _get_count(self): has_meta = all(val is not None for val in self._alignments.video_meta_data.values()) retval = len(self._alignments.video_meta_data["pts_time"]) if has_meta else None logger.debug("Frame count from alignments file: (has_meta: %s, %s", has_meta, retval) retur...
If the alignments file has been run through the manual tool, then it will hold video meta information, meaning that the count of frames in the alignment file can be relied on to be accurate. Returns ------- int or ``None`` For video input which contain video meta-data i...
65
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_count(self): has_meta = all(val is not None for val in self._alignments.video_meta_data.values()) retval = len(self._alignments.video_meta_data["pts_time"])...
1,919
def test_sparse1_with_non_sparse_components(): fit_then_transform( sparse1_paratial_1h.todense(), sparse1, categorical_features=[True, False] )
Test fit_transform a sparse matrix with specifying categorical_features.
8
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_sparse1_with_non_sparse_components(): fit_then_transform( sparse1_paratial_1h.todense(), sparse1, categorical_features=[True, False] ) ...
1,920
def test_mod_gen_f77(capfd, hello_world_f90, monkeypatch): MNAME = "hi" foutl = get_io_paths(hello_world_f90, mname=MNAME) ipath = foutl.f90inp monkeypatch.setattr(sys, "argv", f'f2py {ipath} -m {MNAME}'.split()) with util.switchdir(ipath.parent): f2pycli() # Always generate C modu...
Checks the generation of files based on a module name CLI :: -m
13
41
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_mod_gen_f77(capfd, hello_world_f90, monkeypatch): MNAME = "hi" foutl = get_io_paths(hello_world_f90, mname=MNAME) ipath = foutl.f90inp monkeypatch.setattr(sys, ...
1,921
def delegate(args, host_state, exclude, require): # type: (CommonConfig, HostState, t.List[str], t.List[str]) -> None assert isinstance(args, EnvironmentConfig) with delegation_context(args, host_state): if isinstance(args, TestConfig): args.metadata.ci_provider = get_ci_provider().co...
Delegate execution of ansible-test to another environment.
7
51
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def delegate(args, host_state, exclude, require): # type: (CommonConfig, HostState, t.List[str], t.List[str]) -> None assert isinstance(args, EnvironmentConfig) with delegatio...
1,922
def require_torch_non_multi_gpu(test_case): if not is_torch_available(): return unittest.skip("test requires PyTorch")(test_case) import torch return unittest.skipUnless(torch.cuda.device_count() < 2, "test requires 0 or 1 GPU")(test_case)
Decorator marking a test that requires 0 or 1 GPU setup (in PyTorch).
13
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def require_torch_non_multi_gpu(test_case): if not is_torch_available(): return unittest.skip("test requires PyTorch")(test_case) import torch return unittest.skip...
1,923
def _ReturnKeyHandler(self, event): # if the element is disabled, ignore the event if self.Disabled: return MyForm = self.ParentForm button_element = self._FindReturnKeyBoundButton(MyForm) if button_element is not None: button_element.ButtonCallB...
Internal callback for the ENTER / RETURN key. Results in calling the ButtonCallBack for element that has the return key bound to it, just as if button was clicked. :param event: :type event:
33
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _ReturnKeyHandler(self, event): # if the element is disabled, ignore the event if self.Disabled: return MyForm = self.ParentForm but...
1,924
def uint64_frame(): return DataFrame( {"A": np.arange(3), "B": [2**63, 2**63 + 5, 2**63 + 10]}, dtype=np.uint64 ) @pytest.fixture
Fixture for DataFrame with uint64 values Columns are ['A', 'B']
10
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def uint64_frame(): return DataFrame( {"A": np.arange(3), "B": [2**63, 2**63 + 5, 2**63 + 10]}, dtype=np.uint64 ) @pytest.fixture ``` ###Assistant : F...
1,925
def test_null_annotation(self): book = Book.objects.annotate( no_value=Value(None, output_field=IntegerField()) ).first() self.assertIsNone(book.no_value)
Annotating None onto a model round-trips
6
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_null_annotation(self): book = Book.objects.annotate( no_value=Value(None, output_field=IntegerField()) ).first() self.assertIsNone(book....
1,926
def icosahedral_graph(create_using=None): description = [ "adjacencylist", "Platonic Icosahedral Graph", 12, [ [2, 6, 8, 9, 12], [3, 6, 7, 9], [4, 7, 9, 10], [5, 7, 10, 11], [6, 7, 11, 12], [7, 12], ...
Returns the Platonic Icosahedral graph. The icosahedral graph has 12 nodes and 30 edges. It is a Platonic graph whose nodes have the connectivity of the icosahedron. It is undirected, regular and Hamiltonian [1]_. Parameters ---------- create_using : NetworkX graph constructor, optional (...
73
51
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def icosahedral_graph(create_using=None): description = [ "adjacencylist", "Platonic Icosahedral Graph", 12, [ [2, 6, 8, 9, 12], ...
1,927
def evaluate(model, criterion, metric, data_loader): model.eval() metric.reset() losses = [] for batch in tqdm(data_loader): input_ids, token_type_ids, position_ids, masks, ent_label, spo_label = batch max_batch_len = input_ids.shape[-1] ent_mask = paddle.unsqueeze(masks, ax...
Given a dataset, it evals model and compute the metric. Args: model(obj:`paddle.nn.Layer`): A model to classify texts. dataloader(obj:`paddle.io.DataLoader`): The dataset loader which generates batches. criterion(`paddle.nn.functional`): It can compute the loss. metric(obj:`padd...
34
93
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def evaluate(model, criterion, metric, data_loader): model.eval() metric.reset() losses = [] for batch in tqdm(data_loader): input_ids, token_type_ids, position_...
1,928
def get_fields(self, include_parents=True, include_hidden=False): if include_parents is False: include_parents = PROXY_PARENTS return self._get_fields( include_parents=include_parents, include_hidden=include_hidden )
Return a list of fields associated to the model. By default, include forward and reverse fields, fields derived from inheritance, but not hidden fields. The returned fields can be changed using the parameters: - include_parents: include fields derived from inheritance - include...
53
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_fields(self, include_parents=True, include_hidden=False): if include_parents is False: include_parents = PROXY_PARENTS return self._get_fields( ...
1,929
def _key_to_file(self, session_key=None): if session_key is None: session_key = self._get_or_create_session_key() # Make sure we're not vulnerable to directory traversal. Session keys # should always be md5s, so they should never contain directory # components. ...
Get the file associated with this session key.
8
48
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _key_to_file(self, session_key=None): if session_key is None: session_key = self._get_or_create_session_key() # Make sure we're not vulnerable to di...
1,930
def check_against_chunks(self, chunks): # type: (Iterator[bytes]) -> None gots = {} for hash_name in self._allowed.keys(): try: gots[hash_name] = hashlib.new(hash_name) except (ValueError, TypeError): raise InstallationError(f"Unkn...
Check good hashes against ones built from iterable of chunks of data. Raise HashMismatch if none match.
17
47
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_against_chunks(self, chunks): # type: (Iterator[bytes]) -> None gots = {} for hash_name in self._allowed.keys(): try: g...
1,931
def _expand_onehot_labels(labels, label_weights, label_channels, ignore_index): bin_labels = labels.new_full((labels.size(0), label_channels), 0) valid_mask = (labels >= 0) & (labels != ignore_index) inds = torch.nonzero( valid_mask & (labels < label_channels), as_tuple=False) if inds.nume...
Expand onehot labels to match the size of prediction.
9
61
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _expand_onehot_labels(labels, label_weights, label_channels, ignore_index): bin_labels = labels.new_full((labels.size(0), label_channels), 0) valid_mask = (labels >= 0) & (l...
1,932
def test_sequence_input_types(self, input_type): if not tf.executing_eagerly(): self.skipTest("Improved checking is only present in data_adapter.") xy_function, x_function = self._make_sequence_input_functions( input_type ) fit_kwargs, evaluate_kwargs, p...
Ensure that namedtuples and tuples are plumbed identically.
8
55
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_sequence_input_types(self, input_type): if not tf.executing_eagerly(): self.skipTest("Improved checking is only present in data_adapter.") xy_f...
1,933
def get_stock_value_on(warehouse=None, posting_date=None, item_code=None): if not posting_date: posting_date = nowdate() values, condition = [posting_date], "" if warehouse: lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is_group"]) if is_group: values.extend([lft, rgt]...
SELECT item_code, stock_value, name, warehouse FROM `tabStock Ledger Entry` sle WHERE posting_date <= %s {0} and is_cancelled = 0 ORDER BY timestamp(posting_date, posting_time) DESC, creation DESC
26
100
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_stock_value_on(warehouse=None, posting_date=None, item_code=None): if not posting_date: posting_date = nowdate() values, condition = [posting_date], "" if warehouse: lft, r...
1,934
def _is_installed_rpm(name): log.debug(f"_is_installed_rpm '{name}'") cmd = ["/usr/bin/rpm", "-q", name] return __salt__["cmd.retcode"](cmd) == 0
Returns True if the rpm package is installed. Otherwise returns False.
11
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _is_installed_rpm(name): log.debug(f"_is_installed_rpm '{name}'") cmd = ["/usr/bin/rpm", "-q", name] return __salt__["cmd.retcode"](cmd) == 0 ``` ###Assist...
1,935
def iter_tree_files(root, on_error=None, follow_links=None): if on_error is not None and not callable(on_error): raise TypeError("on_error:{!r} is not callable.".format(on_error)) if follow_links is None: follow_links = True for entry in _iter_tree_entries_next(os.path.abspath(root), '', {}, on_error, follow...
Walks the specified directory for all files. *root* (:class:`str`) is the root directory to search for files. *on_error* (:class:`~collections.abc.Callable` or :data:`None`) optionally is the error handler for file-system exceptions. It will be called with the exception (:exc:`OSError`). Reraise the exception t...
90
45
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def iter_tree_files(root, on_error=None, follow_links=None): if on_error is not None and not callable(on_error): raise TypeError("on_error:{!r} is not callable.".format(on_error)) if ...
1,936
def _get_url_from_path(path, name): # type: (str, str) -> Optional[str] if _looks_like_path(name) and os.path.isdir(path): if is_installable_dir(path): return path_to_url(path) raise InstallationError( f"Directory {name!r} is not installable. Neither 'setup.py' " ...
First, it checks whether a provided path is an installable directory (e.g. it has a setup.py). If it is, returns the path. If false, check if the path is an archive file (such as a .whl). The function checks if the path is a file. If false, if the path has an @, it will treat it as a PEP 440 URL r...
67
100
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_url_from_path(path, name): # type: (str, str) -> Optional[str] if _looks_like_path(name) and os.path.isdir(path): if is_installable_dir(path): retur...
1,937
def test_install_fileset_with_bff_extension(): installp_call = MagicMock(return_value={"retcode": 0, "stdout": ""}) fileset_pkg_name = ( "/cecc/repos/aix72/TL3/BASE/installp/ppc/bos.rte.printers_7.2.2.0.bff" ) list_pkgs_mock = MagicMock( side_effect=[{"bos.rte.printers": "7.1.6.0"},...
Test install of fileset with bff extension
7
61
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_install_fileset_with_bff_extension(): installp_call = MagicMock(return_value={"retcode": 0, "stdout": ""}) fileset_pkg_name = ( "/cecc/repos/aix72/TL3/BASE/inst...
1,938
def is_user_in_allow_list(block_list): return frappe.session.user in frappe.db.sql_list( , block_list, )
select allow_user from `tabLeave Block List Allow` where parent=%s
9
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_user_in_allow_list(block_list): return frappe.session.user in frappe.db.sql_list( , block_list, ) ``` ###Assistant : select allow_user from `tabLeave Block List A...
1,939
def test_normalization(push_channel): types = { "list": list, } msgs = [ {"list": tuple([1, 2, 3])}, ] for msg in msgs: ret = push_channel.send(msg, timeout=5, tries=1) for key, value in ret["load"].items(): assert types[key] == type(value)
Since we use msgpack, we need to test that list types are converted to lists
15
34
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_normalization(push_channel): types = { "list": list, } msgs = [ {"list": tuple([1, 2, 3])}, ] for msg in msgs: ret = push_channel.se...
1,940
def to_perioddelta(self, freq) -> TimedeltaArray: # Deprecaation GH#34853 warnings.warn( "to_perioddelta is deprecated and will be removed in a " "future version. " "Use `dtindex - dtindex.to_period(freq).to_timestamp()` instead.", FutureWarning, ...
Calculate deltas between self values and self converted to Periods at a freq. Used for vectorized offsets. Parameters ---------- freq : Period frequency Returns ------- TimedeltaArray/Index
26
73
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def to_perioddelta(self, freq) -> TimedeltaArray: # Deprecaation GH#34853 warnings.warn( "to_perioddelta is deprecated and will be removed in a " ...
1,941
def set(self, components): if len(components) > 0: self.__components = components else: raise Exception("please give any vector")
input: new components changes the components of the vector. replace the components with newer one.
15
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set(self, components): if len(components) > 0: self.__components = components else: raise Exception("please give any vector") ``...
1,942
def get_best_result(self) -> Optional[Tuple[Union[int, str], Module, Dict[str, Dict[str, Tensor]], Optional[float], List[Dict]]]: if self._best_task_id is not None: compact_model = torch.load(Path(self._log_dir_root, 'best_result', 'model.pth')) compact_model_masks = torch.load(...
Returns ------- Optional[Tuple[int, Module, Dict[str, Dict[str, Tensor]], float, List[Dict]]] If self._best_task_id is not None, return best task id, best compact model, masks on the compact model, score, config list used in this task.
33
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_best_result(self) -> Optional[Tuple[Union[int, str], Module, Dict[str, Dict[str, Tensor]], Optional[float], List[Dict]]]: if self._best_task_id is not None: ...
1,943
def set_variation_by_axes(self, axes): try: self.font.setvaraxes(axes) except AttributeError as e: msg = "FreeType 2.9.1 or greater is required" raise NotImplementedError(msg) from e
:param axes: A list of values for each axis. :exception OSError: If the font is not a variation font.
19
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_variation_by_axes(self, axes): try: self.font.setvaraxes(axes) except AttributeError as e: msg = "FreeType 2.9.1 or greater is requir...
1,944
def dispatch_line(self, frame): if self.stop_here(frame) or self.break_here(frame): self.user_line(frame) if self.quitting: raise BdbQuit return self.trace_dispatch
Invoke user function and return trace function for line event. If the debugger stops on the current line, invoke self.user_line(). Raise BdbQuit if self.quitting is set. Return self.trace_dispatch to continue tracing in this scope.
34
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def dispatch_line(self, frame): if self.stop_here(frame) or self.break_here(frame): self.user_line(frame) if self.quitting: raise BdbQuit ret...
1,945
def clear(self) -> None: self._in_blocks.clear() self._snapshot_blocks = None self._snapshot_stats = None # We're erasing the snapshot, so put all stages into the "after snapshot" # bucket. self._stages_after_snapshot = ( self._stages_before_snapshot ...
Clear all cached block references of this plan, including input blocks. This will render the plan un-executable unless the root is a LazyBlockList.
23
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def clear(self) -> None: self._in_blocks.clear() self._snapshot_blocks = None self._snapshot_stats = None # We're erasing the snapshot, so put all st...
1,946
def _global_clustering(self, X=None): clusterer = self.n_clusters centroids = self.subcluster_centers_ compute_labels = (X is not None) and self.compute_labels # Preprocessing for the global clustering. not_enough_centroids = False if isinstance(clusterer, Integ...
Global clustering for the subclusters obtained after fitting
8
131
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _global_clustering(self, X=None): clusterer = self.n_clusters centroids = self.subcluster_centers_ compute_labels = (X is not None) and self.compute_labe...
1,947
def test_prefill_form_backcompat(extras, expected): mock_form = mock.Mock() mock_form.data = {"conn_id": "test", "extra": json.dumps(extras), "conn_type": "test"} cmv = ConnectionModelView() cmv.extra_fields = ['extra__test__my_param'] # this is set by `lazy_add_provider_discovered_options_to_...
When populating custom fields in the connection form we should first check for the non-prefixed value (since prefixes in extra are deprecated) and then fallback to the prefixed value. Either way, the field is known internally to the model view as the prefixed value.
44
41
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_prefill_form_backcompat(extras, expected): mock_form = mock.Mock() mock_form.data = {"conn_id": "test", "extra": json.dumps(extras), "conn_type": "test"} cmv = Conn...
1,948
def tokenize_query(query): result = defaultdict(list) query_params = defaultdict(list) tokens = split_query_into_tokens(query) for token in tokens: if token.upper() in ["OR", "AND"] or token.strip("()") == "": continue state = "query" for idx, char in enumerate(...
Tokenizes a standard Sentry search query. Example: >>> query = 'is:resolved foo bar tag:value' >>> tokenize_query(query) { 'is': ['resolved'], 'query': ['foo', 'bar'], 'tag': ['value'], } Has a companion implementation in static/app/utils/tokenizeSearch.tsx
31
98
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def tokenize_query(query): result = defaultdict(list) query_params = defaultdict(list) tokens = split_query_into_tokens(query) for token in tokens: if token.uppe...
1,949
def save_model(model, filepath, overwrite=True, save_format=None, **kwargs): save_format = get_save_format(filepath, save_format) if save_format not in ("keras", "tf", "h5", "keras_v3"): raise ValueError( "Unknown `save_format` argument. Expected one of " "'keras', 'tf', or ...
Saves a model as a TensorFlow SavedModel or HDF5 file. See the [Serialization and Saving guide]( https://keras.io/guides/serialization_and_saving/) for details. Args: model: Keras model instance to be saved. filepath: `str` or `pathlib.Path` object. Path where to save the model. ...
472
110
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def save_model(model, filepath, overwrite=True, save_format=None, **kwargs): save_format = get_save_format(filepath, save_format) if save_format not in ("keras", "tf", "h5", "ke...
1,950
def test_random_spanning_tree_additive_small(): pytest.importorskip("numpy") edges = { (0, 1): 1, (0, 2): 1, (0, 5): 3, (1, 2): 2, (1, 4): 3, (2, 3): 3, (5, 3): 4, (5, 4): 5, (4, 3): 4, } # Build the graph G = nx.Graph() ...
Sample a single spanning tree from the additive method.
9
78
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_random_spanning_tree_additive_small(): pytest.importorskip("numpy") edges = { (0, 1): 1, (0, 2): 1, (0, 5): 3, (1, 2): 2, (1, 4...
1,951
def sequence_loss(flow_preds, flow_gt, valid_flow_mask, gamma=0.8, max_flow=400): if gamma > 1: raise ValueError(f"Gamma should be < 1, got {gamma}.") # exlude invalid pixels and extremely large diplacements flow_norm = torch.sum(flow_gt**2, dim=1).sqrt() valid_flow_mask = valid_flow_mask...
Loss function defined over sequence of flow predictions
8
86
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def sequence_loss(flow_preds, flow_gt, valid_flow_mask, gamma=0.8, max_flow=400): if gamma > 1: raise ValueError(f"Gamma should be < 1, got {gamma}.") # exlude invalid...
1,952
def booleans_processing(config, **kwargs): final_booleans = {} if tf.executing_eagerly(): final_booleans["output_attentions"] = ( kwargs["output_attentions"] if kwargs["output_attentions"] is not None else config.output_attentions ) final_booleans["output_hidden_states"...
Process the input booleans of each model in order to be sure they are compliant with the execution mode (eager or graph) Args: config ([`PretrainedConfig`]): The config of the running model. **kwargs: The boolean parameters Returns: A dictionary with th...
45
108
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def booleans_processing(config, **kwargs): final_booleans = {} if tf.executing_eagerly(): final_booleans["output_attentions"] = ( kwargs["output_attentions"...
1,953
def test_dagrun_root_fail_unfinished(self): # TODO: this should live in test_dagrun.py # Run both the failed and successful tasks dag_id = 'test_dagrun_states_root_fail_unfinished' dag = self.dagbag.get_dag(dag_id) dr = dag.create_dagrun( run_type=DagRunType....
DagRuns with one unfinished and one failed root task -> RUNNING
11
84
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_dagrun_root_fail_unfinished(self): # TODO: this should live in test_dagrun.py # Run both the failed and successful tasks dag_id = 'test_dagrun_state...
1,954
def _get_call_args(backend_name, data, args, kwargs): if isinstance(data, ABCSeries): arg_def = [ ("kind", "line"), ("ax", None), ("figsize", None), ("use_index", True), ("title", None), ("grid",...
This function makes calls to this accessor `__call__` method compatible with the previous `SeriesPlotMethods.__call__` and `DataFramePlotMethods.__call__`. Those had slightly different signatures, since `DataFramePlotMethods` accepted `x` and `y` parameters.
28
266
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_call_args(backend_name, data, args, kwargs): if isinstance(data, ABCSeries): arg_def = [ ("kind", "line"), ("ax", None),...
1,955
async def test_ahas_key(self): await cache.aset("hello1", "goodbye1") self.assertIs(await cache.ahas_key("hello1"), False) self.assertIs(await cache.ahas_key("goodbye1"), False)
ahas_key() doesn't ever return True for the dummy cache backend.
10
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_ahas_key(self): await cache.aset("hello1", "goodbye1") self.assertIs(await cache.ahas_key("hello1"), False) self.assertIs(await cache.ahas_key...
1,956
def min_temp(self) -> float: if self.temperature_unit == UnitOfTemperature.CELSIUS: return TEMP_MIN return TEMP_MIN_F
Return the minimum temperature supported by the device.
8
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def min_temp(self) -> float: if self.temperature_unit == UnitOfTemperature.CELSIUS: return TEMP_MIN return TEMP_MIN_F ``` ###Assistant : Ret...
1,957
def nseries(self, x=None, x0=0, n=6, dir='+', logx=None, cdir=0): if x and x not in self.free_symbols: return self if x is None or x0 or dir != '+': # {see XPOS above} or (x.is_positive == x.is_negative == None): return self.series(x, x0, n, dir, cdir=cdir) else...
Wrapper to _eval_nseries if assumptions allow, else to series. If x is given, x0 is 0, dir='+', and self has x, then _eval_nseries is called. This calculates "n" terms in the innermost expressions and then builds up the final series just by "cross-multiplying" everything out. ...
294
49
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def nseries(self, x=None, x0=0, n=6, dir='+', logx=None, cdir=0): if x and x not in self.free_symbols: return self if x is None or x0 or dir != '+': # {...
1,958
def test_getitem_error(self, exception): container = self.Container(exception("failure")) with pytest.raises(validate.ValidationError) as cm: validate.validate(validate.get("foo", default="default"), container) assert_validationerror(cm.value, )
ValidationError(GetItemSchema): Could not get key 'foo' from object Container Context: failure
11
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_getitem_error(self, exception): container = self.Container(exception("failure")) with pytest.raises(validate.ValidationError) as cm: validate.validate(va...
1,959
def num_base_priors(self) -> List[int]: return [1 for _ in range(len(self.strides))]
list[int]: The number of priors (points) at a point on the feature grid
13
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def num_base_priors(self) -> List[int]: return [1 for _ in range(len(self.strides))] ``` ###Assistant : list[int]: The number of priors (points) at a point ...
1,960
def test_logentry_change_message_localized_datetime_input(self): post_data = { "site": self.site.pk, "title": "Changed", "hist": "Some content", "created_0": "12/03/2008", "created_1": "11:54", } with translation.override("fr")...
Localized date/time inputs shouldn't affect changed form data detection.
9
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_logentry_change_message_localized_datetime_input(self): post_data = { "site": self.site.pk, "title": "Changed", "hist": "Some co...
1,961
def _cleanup_code(code): return code # Nothing to do here # language=PythonVerboseRegExp _call_function_bytecode = bytecode_regex( rb ) else: # Starting with python 3.11, the bytecode is peppered with CACHE instructions (which dis module conveniently hides # unless show_caches=True...
# Matches `global_function('some', 'constant', 'arguments')`. # Load the global function. In code with >256 of names, this may require extended name references. ((?:`EXTENDED_ARG`.)* (?:`LOAD_NAME`|`LOAD_GLOBAL`|`LOAD_FAST`).) # For foo.bar.whizz(), the above is the 'foo', be...
94
66
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _cleanup_code(code): return code # Nothing to do here # language=PythonVerboseRegExp _call_function_bytecode = bytecode_regex( rb ) else: # Starting wit...
1,962
def filemode(mode): perm = [] for table in filemode_table: for bit, char in table: if mode & bit == bit: perm.append(char) break else: perm.append("-") return "".join(perm)
Convert a file's mode to a string of the form -rwxrwxrwx. Used by TarFile.list()
14
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def filemode(mode): perm = [] for table in filemode_table: for bit, char in table: if mode & bit == bit: perm.append(char) br...
1,963
def filter_2d(x, k, gain=1, data_format='NCHW', impl='cuda'): r k = _setup_kernel(k) * gain p = k.shape[0] - 1 return _simple_upfirdn_2d(x, k, pad0=(p+1)//2, pad1=p//2, data_format=data_format, impl=impl) #----------------------------------------------------------------------------
Filter a batch of 2D images with the given FIR filter. Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]` and filters each image with the given filter. The filter is normalized so that if the input pixels are constant, they will be scaled by the specified `gain`. Pixels outside ...
130
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def filter_2d(x, k, gain=1, data_format='NCHW', impl='cuda'): r k = _setup_kernel(k) * gain p = k.shape[0] - 1 return _simple_upfirdn_2d(x, k, pad0=(p+1)//2, pad1=p//2, data...
1,964
def execute(): frappe.reload_doctype("Pricing Rule") currency = frappe.db.get_default("currency") for doc in frappe.get_all("Pricing Rule", fields=["company", "name"]): if doc.company: currency = frappe.get_cached_value("Company", doc.company, "default_currency") frappe.db.sql( , (currency, doc.name) )...
update `tabPricing Rule` set currency = %s where name = %s
11
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def execute(): frappe.reload_doctype("Pricing Rule") currency = frappe.db.get_default("currency") for doc in frappe.get_all("Pricing Rule", fields=["company", "name"]): if doc.company:...
1,965
def forward(self, x, mask=None): B_, N, C = x.shape qkv = self.qkv(x).reshape((B_, N, 3, self.num_heads, C // self.num_heads)).transpose((2, 0, 3, 1, 4)) q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) q = q * self.scale attn = (q...
Args: x: input features with shape of (num_windows*B, N, C) mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
21
131
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def forward(self, x, mask=None): B_, N, C = x.shape qkv = self.qkv(x).reshape((B_, N, 3, self.num_heads, C // self.num_heads)).transpose((2, 0, 3, 1, 4)) q, ...
1,966
def test_join_rules_invite(self): creator = "@creator:example.com" pleb = "@joiner:example.com" auth_events = { ("m.room.create", ""): _create_event(RoomVersions.V6, creator), ("m.room.member", creator): _join_event(RoomVersions.V6, creator), ("m.roo...
Test joining an invite only room.
6
154
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_join_rules_invite(self): creator = "@creator:example.com" pleb = "@joiner:example.com" auth_events = { ("m.room.create", ""): _create_e...
1,967
def validate_onboarding(data): logging.info(f"Validating onboarding data {data}") messages = data['outputs']['messages'] if len(messages) == 0: return False status_message = messages[-2] if status_message is None: return False submitted_data = status_message.get('data') ...
Check the contents of the data to ensure they are valid.
11
53
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def validate_onboarding(data): logging.info(f"Validating onboarding data {data}") messages = data['outputs']['messages'] if len(messages) == 0: return False stat...
1,968
async def test_async_track_entity_registry_updated_event_with_empty_list(hass): unsub_single = async_track_entity_registry_updated_event( hass, [], ha.callback(lambda event: None) ) unsub_single2 = async_track_entity_registry_updated_event( hass, [], ha.callback(lambda event: None) ...
Test async_track_entity_registry_updated_event passing an empty list of entities.
8
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_async_track_entity_registry_updated_event_with_empty_list(hass): unsub_single = async_track_entity_registry_updated_event( hass, [], ha.callback(lambda event:...
1,969
def generate_self_signed_tls_certs(): try: from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography....
Create self-signed key/cert pair for testing. This method requires the library ``cryptography`` be installed.
14
167
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def generate_self_signed_tls_certs(): try: from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.pr...
1,970
def print_help(self): has_ticker_start = "[unvl]" if not self.ticker else "" has_ticker_end = "[/unvl]" if not self.ticker else "" help_text = f console.print(text=help_text, menu="Stocks - Government")
Print help [src][QuiverQuant][/src] [info]Explore:[/info][cmds] lasttrades last trades topbuys show most purchased stocks topsells show most sold stocks lastcontracts show last government contracts given out qtrcontracts quarterly government contracts analysis topl...
71
25
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 = "[unvl]" if not self.ticker else "" has_ticker_end = "[/unvl]" if not self.ticker else "" help_text = f cons...
1,971
def get_item_warehouse_projected_qty(items_to_consider): item_warehouse_projected_qty = {} for item_code, warehouse, projected_qty in frappe.db.sql( .format( ", ".join(["%s"] * len(items_to_consider)) ), items_to_consider, ): if item_code not in item_warehouse_projected_qty: item_warehouse_projected_...
select item_code, warehouse, projected_qty from tabBin where item_code in ({0}) and (warehouse != "" and warehouse is not null)
19
60
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_item_warehouse_projected_qty(items_to_consider): item_warehouse_projected_qty = {} for item_code, warehouse, projected_qty in frappe.db.sql( .format( ", ".join(["%s"] * len(i...
1,972
def _collect_type_vars(types, typevar_types=None): if typevar_types is None: typevar_types = typing.TypeVar tvars = [] for t in types: if ( isinstance(t, typevar_types) and t not in tvars and not _is_unpack(t) ): tvars.append(t) ...
Collect all type variable contained in types in order of first appearance (lexicographic order). For example:: _collect_type_vars((T, List[S, T])) == (T, S)
22
132
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _collect_type_vars(types, typevar_types=None): if typevar_types is None: typevar_types = typing.TypeVar tvars = [] for t in types: if ( isins...
1,973
def from_dataframe(df, allow_copy=True): if isinstance(df, pd.DataFrame): return df if not hasattr(df, "__dataframe__"): raise ValueError("`df` does not support __dataframe__") return _from_dataframe(df.__dataframe__(allow_copy=allow_copy))
Build a ``pd.DataFrame`` from any DataFrame supporting the interchange protocol. Parameters ---------- df : DataFrameXchg Object supporting the exchange protocol, i.e. `__dataframe__` method. allow_copy : bool, default: True Whether to allow copying the memory to perform the conver...
48
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def from_dataframe(df, allow_copy=True): if isinstance(df, pd.DataFrame): return df if not hasattr(df, "__dataframe__"): raise ValueError("`df` does not support...
1,974
def parse_wheel(wheel_zip, name): # type: (ZipFile, str) -> Tuple[str, Message] try: info_dir = wheel_dist_info_dir(wheel_zip, name) metadata = wheel_metadata(wheel_zip, info_dir) version = wheel_version(metadata) except UnsupportedWheel as e: raise UnsupportedWheel("{} ...
Extract information from the provided wheel, ensuring it meets basic standards. Returns the name of the .dist-info directory and the parsed WHEEL metadata.
23
39
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def parse_wheel(wheel_zip, name): # type: (ZipFile, str) -> Tuple[str, Message] try: info_dir = wheel_dist_info_dir(wheel_zip, name) metadata = wheel_metadata(wh...
1,975
def style_docstrings_in_code(code, max_len=119): # fmt: off splits = code.split('\"\"\"') splits = [ (s if i % 2 == 0 or _re_doc_ignore.search(splits[i - 1]) is not None else style_docstring(s, max_len=max_len)) for i, s in enumerate(splits) ] black_errors = "\n\n".join([s[1] fo...
Style all docstrings in some code. Args: code (`str`): The code in which we want to style the docstrings. max_len (`int`): The maximum number of characters per line. Returns: `Tuple[str, str]`: A tuple with the clean code and the black errors (if any)
43
70
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def style_docstrings_in_code(code, max_len=119): # fmt: off splits = code.split('\"\"\"') splits = [ (s if i % 2 == 0 or _re_doc_ignore.search(splits[i - 1]) is not ...
1,976
def check_version_info(cluster_metadata): cluster_version_info = ( cluster_metadata["ray_version"], cluster_metadata["python_version"], ) version_info = compute_version_info() if version_info != cluster_version_info: node_ip_address = ray._private.services.get_node_ip_addres...
Check if the Python and Ray versions stored in GCS matches this process. Args: cluster_metadata: Ray cluster metadata from GCS. Raises: Exception: An exception is raised if there is a version mismatch.
32
73
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_version_info(cluster_metadata): cluster_version_info = ( cluster_metadata["ray_version"], cluster_metadata["python_version"], ) version_info = comp...
1,977
def get_console() -> "Console": global _console if _console is None: from .console import Console _console = Console() return _console
Get a global :class:`~rich.console.Console` instance. This function is used when Rich requires a Console, and hasn't been explicitly given one. Returns: Console: A console instance.
25
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_console() -> "Console": global _console if _console is None: from .console import Console _console = Console() return _console ``` ##...
1,978
def is_hash_allowed(self, hashes): # type: (Optional[Hashes]) -> bool if hashes is None or not self.has_hash: return False # Assert non-None so mypy knows self.hash_name and self.hash are str. assert self.hash_name is not None assert self.hash is not None ...
Return True if the link has a hash and it is allowed.
12
52
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_hash_allowed(self, hashes): # type: (Optional[Hashes]) -> bool if hashes is None or not self.has_hash: return False # Assert non-None so m...
1,979
def coverage_error(y_true, y_score, *, sample_weight=None): y_true = check_array(y_true, ensure_2d=True) y_score = check_array(y_score, ensure_2d=True) check_consistent_length(y_true, y_score, sample_weight) y_type = type_of_target(y_true, input_name="y_true") if y_type != "multilabel-indicato...
Coverage error measure. Compute how far we need to go through the ranked scores to cover all true labels. The best value is equal to the average number of labels in ``y_true`` per sample. Ties in ``y_scores`` are broken by giving maximal rank that would have been assigned to all tied values. ...
179
60
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def coverage_error(y_true, y_score, *, sample_weight=None): y_true = check_array(y_true, ensure_2d=True) y_score = check_array(y_score, ensure_2d=True) check_consistent_leng...
1,980
def total_predict_batches(self) -> int: return sum(self.trainer.num_predict_batches)
The total number of prediction batches, which may change from epoch to epoch. Use this to set the total number of iterations in the progress bar. Can return ``inf`` if the predict dataloader is of infinite size.
37
6
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def total_predict_batches(self) -> int: return sum(self.trainer.num_predict_batches) ``` ###Assistant : The total number of prediction batches, which may change...
1,981
def shape(self) -> Dict[str, Tuple[int]]: self._check_values_type() return {k: dataset.shape for k, dataset in self.items()}
Shape of each split of the dataset (number of columns, number of rows). Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.shape {'test': (1066, 2), 'train': (8530, 2), 'validation': (1066, 2)} ```
36
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def shape(self) -> Dict[str, Tuple[int]]: self._check_values_type() return {k: dataset.shape for k, dataset in self.items()} ``` ###Assistant : Shape of...
1,982
def is_torch_support_available(self) -> bool: if is_torch_available(): from transformers.file_utils import torch_version return torch_version >= self.torch_onnx_minimum_version else: return False
The minimum PyTorch version required to export the model. Returns: `bool`: Whether the installed version of PyTorch is compatible with the model.
22
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_torch_support_available(self) -> bool: if is_torch_available(): from transformers.file_utils import torch_version return torch_version >= sel...
1,983
def check_connection(self, logger, config) -> Tuple[bool, any]: auth_header = TokenAuthenticator(token=config["api_key"]).get_auth_header() ping_url = ORB_API_BASE_URL + "ping" ping_response = requests.get(ping_url, headers=auth_header) try: ping_response.raise_for_s...
Makes a request to the /ping endpoint, which validates that the authentication credentials are appropriate. API Docs: https://docs.withorb.com/reference/ping
18
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_connection(self, logger, config) -> Tuple[bool, any]: auth_header = TokenAuthenticator(token=config["api_key"]).get_auth_header() ping_url = ORB_API_BASE_U...
1,984
def add_items_upsert(self, content_type_pk, indexers): compiler = InsertQuery(IndexEntry).get_compiler(connection=self.connection) title_sql = [] autocomplete_sql = [] body_sql = [] data_params = [] for indexer in indexers: data_params.extend((content_type_pk...
INSERT INTO %s (content_type_id, object_id, title, autocomplete, body, title_norm) (VALUES %s) ON CONFLICT (content_type_id, object_id) DO UPDATE SET title = EXCLUDED.title, title_norm = 1.0, aut...
30
112
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def add_items_upsert(self, content_type_pk, indexers): compiler = InsertQuery(IndexEntry).get_compiler(connection=self.connection) title_sql = [] autocomplete_sql = [...
1,985
def test_already_created_plus_written_results(indexer, indexer_cache) -> None: org_id = 1234 raw_indexer = indexer indexer = CachingIndexer(indexer_cache, indexer) v0 = raw_indexer.record(use_case_id, org_id, "v1.2.0") v1 = raw_indexer.record(use_case_id, org_id, "v1.2.1") v2 = raw_indexe...
Test that we correctly combine db read results with db write results for the same organization.
16
108
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_already_created_plus_written_results(indexer, indexer_cache) -> None: org_id = 1234 raw_indexer = indexer indexer = CachingIndexer(indexer_cache, indexer) v0 ...
1,986
def compiler_fixup(compiler_so, cc_args): stripArch = stripSysroot = False compiler_so = list(compiler_so) if not _supports_universal_builds(): # OSX before 10.4.0, these don't support -arch and -isysroot at # all. stripArch = stripSysroot = True else: stripArch = ...
This function will strip '-isysroot PATH' and '-arch ARCH' from the compile flags if the user has specified one them in extra_compile_flags. This is needed because '-arch ARCH' adds another architecture to the build, without a way to remove an architecture. Furthermore GCC will barf if multiple '-...
51
268
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def compiler_fixup(compiler_so, cc_args): stripArch = stripSysroot = False compiler_so = list(compiler_so) if not _supports_universal_builds(): # OSX before 10.4.0...
1,987
def test_copy_page_with_excluded_parental_and_child_relations(self): try: # modify excluded fields for this test EventPage.exclude_fields_in_copy = [ "advert_placements", "categories", "signup_link", ] # s...
Test that a page will be copied with parental and child relations removed if excluded.
15
197
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_copy_page_with_excluded_parental_and_child_relations(self): try: # modify excluded fields for this test EventPage.exclude_fields_in_copy = ...
1,988
def test_app_model_in_list_body_class(self): response = self.client.get(reverse("admin:admin_views_section_changelist")) self.assertContains(response, '<body class=" app-admin_views model-section ')
Ensure app and model tag are correctly read by change_list template
11
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_app_model_in_list_body_class(self): response = self.client.get(reverse("admin:admin_views_section_changelist")) self.assertContains(response, '<body class="...
1,989
def version_parts(best=False): # type: (bool) -> Tuple[str, str, str] return _distro.version_parts(best)
Return the version of the current OS distribution as a tuple ``(major, minor, build_number)`` with items as follows: * ``major``: The result of :func:`distro.major_version`. * ``minor``: The result of :func:`distro.minor_version`. * ``build_number``: The result of :func:`distro.build_number`....
47
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def version_parts(best=False): # type: (bool) -> Tuple[str, str, str] return _distro.version_parts(best) ``` ###Assistant : Return the version of the current ...
1,990
def check_status(self): status = { 'success': False } try: con = self.__connect() with closing(con) as con: #TODO: best way to check con.connected ? status['success'] = True except Exception as e: ...
Check the connection of the SQL Server database :return: success status and error message if error occurs
17
42
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_status(self): status = { 'success': False } try: con = self.__connect() with closing(con) as con: ...
1,991
def model_from_config(config, custom_objects=None): if isinstance(config, list): raise TypeError( "`model_from_config` expects a dictionary, not a list. " f"Received: config={config}. Did you meant to use " "`Sequential.from_config(config)`?" ) from keras...
Instantiates a Keras model from its config. Usage: ``` # for a Functional API model tf.keras.Model().from_config(model.get_config()) # for a Sequential model tf.keras.Sequential().from_config(model.get_config()) ``` Args: config: Configuration dictionary. custom_object...
57
37
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def model_from_config(config, custom_objects=None): if isinstance(config, list): raise TypeError( "`model_from_config` expects a dictionary, not a list. " ...
1,992
def test_golden_path(self): with self.assertNumQueries(0): result = self.page.cached_content_type self.assertEqual(result, ContentType.objects.get(id=self.page.content_type_id))
The return value should match the value you'd get if fetching the ContentType from the database, and shouldn't trigger any database queries when the ContentType is already in memory.
29
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_golden_path(self): with self.assertNumQueries(0): result = self.page.cached_content_type self.assertEqual(result, ContentType.objects.get(id=sel...
1,993
def fold_function_name(function_name): parts = function_name.split(".") if len(parts) == 1: return function_name tail = parts.pop() grouped = [list(g) for _, g in groupby(parts)]
Fold multiple consecutive occurences of the same property name into a single group, excluding the last component. foo | foo foo.foo | foo.foo foo.foo.foo | {foo#2}.foo bar.foo.foo | bar.foo.foo bar.foo.foo.foo | bar.{foo#2}.foo bar.foo.foo.onError | bar.{foo#2}.onError bar.bar.bar.foo....
41
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def fold_function_name(function_name): parts = function_name.split(".") if len(parts) == 1: return function_name tail = parts.pop() grouped = [list(g) for _, ...
1,994
def _laplace_rule_exp(f, t, s, doit=True, **hints): hints.pop('simplify', True) a = Wild('a', exclude=[t]) y = Wild('y') z = Wild('z') k, func = f.as_independent(t, as_Add=False) ma1 = func.match(exp(y)*z) if ma1: ma2 = ma1[y].collect(t).match(a*t) if ma2: d...
This internal helper function tries to transform a product containing the `exp` function and returns `None` if it cannot do it.
21
73
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _laplace_rule_exp(f, t, s, doit=True, **hints): hints.pop('simplify', True) a = Wild('a', exclude=[t]) y = Wild('y') z = Wild('z') k, func = f.as_independent(t,...
1,995
def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar): for i in xrange(startpos, len(line)): if line[i] == startchar: depth += 1 elif line[i] == endchar: depth -= 1 if depth == 0: return (i + 1, 0) return (-1, depth)
Find the position just after the matching endchar. Args: line: a CleansedLines line. startpos: start searching at this position. depth: nesting level at startpos. startchar: expression opening character. endchar: expression closing character. Returns: On finding matching endchar: (index ju...
52
37
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar): for i in xrange(startpos, len(line)): if line[i] == startchar: depth += 1 elif line[i] == endchar...
1,996
def test_toy_example_collapse_points(): rng = np.random.RandomState(42) input_dim = 5 two_points = rng.randn(2, input_dim) X = np.vstack([two_points, two_points.mean(axis=0)[np.newaxis, :]]) y = [0, 0, 1]
Test on a toy example of three points that should collapse We build a simple example: two points from the same class and a point from a different class in the middle of them. On this simple example, the new (transformed) points should all collapse into one single point. Indeed, the objective is 2/(1 + ...
83
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_toy_example_collapse_points(): rng = np.random.RandomState(42) input_dim = 5 two_points = rng.randn(2, input_dim) X = np.vstack([two_points, two_points.mean(axi...
1,997
def _get_string_indexer_log_records(caplog): return [ ( rec.message, { k: v for k, v in rec.__dict__.items() if k in ( "string_type", "is_global_quota", "n...
Get all log records and relevant extra arguments for easy snapshotting.
11
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_string_indexer_log_records(caplog): return [ ( rec.message, { k: v for k, v in rec.__dict__.items() ...
1,998
async def test_registered_pin_required(hass, user_form): with patch(MOCK_API_CONNECT, return_value=True), patch( MOCK_API_DEVICE_REGISTERED, new_callable=PropertyMock ) as mock_device_registered, patch(MOCK_API_IS_PIN_REQUIRED, return_value=True): mock_device_registered.return_value = True ...
Test if the device is already registered and PIN required.
10
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_registered_pin_required(hass, user_form): with patch(MOCK_API_CONNECT, return_value=True), patch( MOCK_API_DEVICE_REGISTERED, new_callable=PropertyMock ) ...
1,999
def test_send_push_multiple_workers(self): http_client_mock1 = Mock(spec_set=["post_json_get_json"]) http_client_mock1.post_json_get_json.side_effect = ( lambda *_, **__: defer.succeed({}) ) self.make_worker_hs( "synapse.app.generic_worker", ...
Test that registration works when using sharded pusher workers.
9
133
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_send_push_multiple_workers(self): http_client_mock1 = Mock(spec_set=["post_json_get_json"]) http_client_mock1.post_json_get_json.side_effect = ( ...