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,400
def test_poisson_vs_mse(): rng = np.random.RandomState(42) n_train, n_test, n_features = 500, 500, 10 X = datasets.make_low_rank_matrix( n_samples=n_train + n_test, n_features=n_features, random_state=rng ) # We create a log-linear Poisson model and downscale coef as it will get # ...
Test that random forest with poisson criterion performs better than mse for a poisson target. There is a similar test for DecisionTreeRegressor.
22
247
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_poisson_vs_mse(): rng = np.random.RandomState(42) n_train, n_test, n_features = 500, 500, 10 X = datasets.make_low_rank_matrix( n_samples=n_train + n_test, ...
1,401
def _external_caller_info(): frame = inspect.currentframe() caller = frame levels = 0 while caller.f_code.co_filename == __file__: caller = caller.f_back levels += 1 return { "lineno": caller.f_lineno, "filename": os.path.basename(caller.f_code.co_filename), ...
Get the info from the caller frame. Used to override the logging function and line number with the correct ones. See the comment on _patched_makeRecord for more info.
28
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _external_caller_info(): frame = inspect.currentframe() caller = frame levels = 0 while caller.f_code.co_filename == __file__: caller = caller.f_back ...
1,402
def _try_restart_fedora(self) -> None: try: util.run_script(['systemctl', 'restart', 'httpd']) except errors.SubprocessError as err: raise errors.MisconfigurationError(str(err)) # Finish with actual config check to see if systemctl restart helped super(...
Tries to restart httpd using systemctl to generate the self signed key pair.
13
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _try_restart_fedora(self) -> None: try: util.run_script(['systemctl', 'restart', 'httpd']) except errors.SubprocessError as err: raise e...
1,403
async def sock_accept(self, sock): base_events._check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be non-blocking") fut = self.create_future() self._sock_accept(fut, sock) return await fut
Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of t...
55
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def sock_accept(self, sock): base_events._check_ssl_socket(sock) if self._debug and sock.gettimeout() != 0: raise ValueError("the socket must be no...
1,404
def test_state(self, api, state): stream = AdsInsights( api=api, start_date=datetime(2010, 1, 1), end_date=datetime(2011, 1, 1), ) assert stream.state == {} stream.state = state actual_state = stream.state actual_state["slice...
State setter/getter should work with all combinations
7
37
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_state(self, api, state): stream = AdsInsights( api=api, start_date=datetime(2010, 1, 1), end_date=datetime(2011, 1, 1), ...
1,405
def get_snql_query(self) -> None: raise NotImplementedError("get_snql_query cannot be implemented for MetricsQueryBuilder")
Because metrics table queries need to make multiple requests per metric type this function cannot be inmplemented see run_query
19
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_snql_query(self) -> None: raise NotImplementedError("get_snql_query cannot be implemented for MetricsQueryBuilder") ``` ###Assistant : Because metrics t...
1,406
def _validate(self, params): remote_worker_stats = [w.validate.remote(**params) for w in self.remote_workers] return remote_worker_stats
Runs validation for each worker. Returns results as promises.
9
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _validate(self, params): remote_worker_stats = [w.validate.remote(**params) for w in self.remote_workers] return remote_worker_stats ``` ###Assistan...
1,407
def set_aspect(self, aspect, adjustable=None, anchor=None, share=False): _api.check_in_list(('auto', 'equal', 'equalxy', 'equalyz', 'equalxz'), aspect=aspect) super().set_aspect( aspect='auto', adjustable=adjustable, anchor=anchor, share=share) if...
Set the aspect ratios. Parameters ---------- aspect : {'auto', 'equal', 'equalxy', 'equalxz', 'equalyz'} Possible values: ========= ================================================== value description ========= ================...
195
94
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_aspect(self, aspect, adjustable=None, anchor=None, share=False): _api.check_in_list(('auto', 'equal', 'equalxy', 'equalyz', 'equalxz'), as...
1,408
def __getattr__(cls, name): if _is_dunder(name): raise AttributeError(name) try: return cls._member_map_[name] except KeyError: raise AttributeError(name) from None
Return the enum member matching `name` We use __getattr__ instead of descriptors or inserting into the enum class' __dict__ in order to support `name` and `value` being both properties for enum members (which live in the class' __dict__) and enum members themselves.
42
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def __getattr__(cls, name): if _is_dunder(name): raise AttributeError(name) try: return cls._member_map_[name] except KeyError: ...
1,409
def test_n_clusters(n_clusters): rng = np.random.RandomState(0) X = rng.rand(10, 2) bisect_means = BisectingKMeans(n_clusters=n_clusters, random_state=0) bisect_means.fit(X) assert_array_equal(np.unique(bisect_means.labels_), np.arange(n_clusters))
Test if resulting labels are in range [0, n_clusters - 1].
11
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_n_clusters(n_clusters): rng = np.random.RandomState(0) X = rng.rand(10, 2) bisect_means = BisectingKMeans(n_clusters=n_clusters, random_state=0) bisect_means....
1,410
def test_nested_ungrouped_nav(self): nav_cfg = [ {'Home': 'index.md'}, {'Contact': 'about/contact.md'}, {'License Title': 'about/sub/license.md'}, ] expected = dedent( ) cfg = load_config(nav=nav_cfg, site_url='http://example.com/'...
Page(title='Home', url='/') Page(title='Contact', url='/about/contact/') Page(title='License Title', url='/about/sub/license/')
7
46
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_nested_ungrouped_nav(self): nav_cfg = [ {'Home': 'index.md'}, {'Contact': 'about/contact.md'}, {'License Title': 'about/sub/license.md'},...
1,411
def _get_log_file_names(self, name, unique=False): if unique: log_stdout = self._make_inc_temp( suffix=".out", prefix=name, directory_name=self._logs_dir ) log_stderr = self._make_inc_temp( suffix=".err", prefix=name, directory_name=s...
Generate partially randomized filenames for log files. Args: name (str): descriptive string for this log file. unique (bool): if true, a counter will be attached to `name` to ensure the returned filename is not already used. Returns: A tuple of two f...
47
32
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_log_file_names(self, name, unique=False): if unique: log_stdout = self._make_inc_temp( suffix=".out", prefix=name, directory_name=self....
1,412
def yeardayscalendar(self, year, width=3): months = [ self.monthdayscalendar(year, i) for i in range(January, January+12) ] return [months[i:i+width] for i in range(0, len(months), width) ]
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero.
28
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def yeardayscalendar(self, year, width=3): months = [ self.monthdayscalendar(year, i) for i in range(January, January+12) ] return [m...
1,413
def test_simplelistfilter_without_parameter(self): modeladmin = DecadeFilterBookAdminWithoutParameter(Book, site) request = self.request_factory.get("/", {}) request.user = self.alfred msg = "The list filter 'DecadeListFilterWithoutParameter' does not specify a 'parameter_name'....
Any SimpleListFilter must define a parameter_name.
6
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_simplelistfilter_without_parameter(self): modeladmin = DecadeFilterBookAdminWithoutParameter(Book, site) request = self.request_factory.get("/", {}) ...
1,414
def from_session_or_email(cls, request, organization, email, instance=None, logger=None): invite_token, invite_member_id = get_invite_details(request) try: if invite_token and invite_member_id: om = OrganizationMember.objects.get(token=invite_token, id=invite_member...
Initializes the ApiInviteHelper by locating the pending organization member via the currently set pending invite details in the session, or via the passed email if no cookie is currently set.
30
54
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def from_session_or_email(cls, request, organization, email, instance=None, logger=None): invite_token, invite_member_id = get_invite_details(request) try: ...
1,415
async def test_multiple_bleak_scanner_instances(hass): install_multiple_bleak_catcher() instance = bleak.BleakScanner() assert isinstance(instance, HaBleakScannerWrapper) uninstall_multiple_bleak_catcher() with patch("bleak.get_platform_scanner_backend_type"): instance = bleak.Bleak...
Test creating multiple BleakScanners without an integration.
7
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_multiple_bleak_scanner_instances(hass): install_multiple_bleak_catcher() instance = bleak.BleakScanner() assert isinstance(instance, HaBleakScannerWrapper) ...
1,416
def highlight_string(value, highlight, trim_pre=None, trim_post=None, trim_placeholder='...'): # Split value on highlight string try: pre, match, post = re.split(fr'({highlight})', value, maxsplit=1, flags=re.IGNORECASE) except ValueError: # Match not found return escape(value) ...
Highlight a string within a string and optionally trim the pre/post portions of the original string.
16
59
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def highlight_string(value, highlight, trim_pre=None, trim_post=None, trim_placeholder='...'): # Split value on highlight string try: pre, match, post = re.split(fr'({hi...
1,417
def node_table(self): self._check_connected() node_table = self.global_state_accessor.get_node_table() results = [] for node_info_item in node_table: item = gcs_utils.GcsNodeInfo.FromString(node_info_item) node_info = { "NodeID": ray._pr...
Fetch and parse the Gcs node info table. Returns: Information about the node in the cluster.
16
63
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def node_table(self): self._check_connected() node_table = self.global_state_accessor.get_node_table() results = [] for node_info_item in node_tabl...
1,418
def vocabulary_size(self): if tf.executing_eagerly(): return ( int(self.lookup_table.size().numpy()) + self._token_start_index() ) else: return self.lookup_table.size() + self._token_start_index()
Gets the current size of the layer's vocabulary. Returns: The integer size of the vocabulary, including optional mask and oov indices.
21
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def vocabulary_size(self): if tf.executing_eagerly(): return ( int(self.lookup_table.size().numpy()) + self._token_start_index() ...
1,419
def test_version_with_invalid_names(): lslpp_mydog_out = ver_chk = MagicMock(return_value={"retcode": 1, "stdout": lslpp_mydog_out}) with patch.dict(aixpkg.__grains__, {"osarch": "PowerPC_POWER8"}), patch.dict( aixpkg.__salt__, {"cmd.run_all": ver_chk}, ): versions_checke...
test version of packages lslpp: Fileset mydog not installed. State codes: A -- Applied. B -- Broken. C -- Committed. E -- EFIX Locked. O -- Obsolete. (partially migrated to newer version) ? -- Inconsistent State...Run lppchk -v. Type codes: F -- Installp Fileset P -- Product C -- Compone...
61
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_version_with_invalid_names(): lslpp_mydog_out = ver_chk = MagicMock(return_value={"retcode": 1, "stdout": lslpp_mydog_out}) with patch.dict(aixpkg.__grains__, {"...
1,420
def test_mapped_literal_length_increase_adds_additional_ti(dag_maker, session): with dag_maker(session=session) as dag:
Test that when the length of mapped literal increases, additional ti is added
13
7
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_mapped_literal_length_increase_adds_additional_ti(dag_maker, session): with dag_maker(session=session) as dag: ``` ###Assistant : Test that when the length of...
1,421
def test_installed_without_username(self): # Remove username to simulate privacy mode del self.user_data_from_bitbucket["principal"]["username"] response = self.client.post(self.path, data=self.user_data_from_bitbucket) assert response.status_code == 200 integration = ...
Test a user (not team) installation where the user has hidden their username from public view
16
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_installed_without_username(self): # Remove username to simulate privacy mode del self.user_data_from_bitbucket["principal"]["username"] response =...
1,422
def _command_display(self, command): build_tabs = getattr(self, f"_{command}_tabs") build_tabs()
Build the relevant command specific tabs based on the incoming Faceswap command. Parameters ---------- command: str The Faceswap command that is being executed
23
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _command_display(self, command): build_tabs = getattr(self, f"_{command}_tabs") build_tabs() ``` ###Assistant : Build the relevant command specific...
1,423
def itermerged(self): for key in self: val = self._container[key.lower()] yield val[0], ", ".join(val[1:])
Iterate over all headers, merging duplicate ones together.
8
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def itermerged(self): for key in self: val = self._container[key.lower()] yield val[0], ", ".join(val[1:]) ``` ###Assistant : Iterate ov...
1,424
def get_file_from_path(self, path): return self.src_paths.get(os.path.normpath(path))
Return a File instance with File.src_path equal to path.
9
5
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_file_from_path(self, path): return self.src_paths.get(os.path.normpath(path)) ``` ###Assistant : Return a File instance with File.src_path equal to path...
1,425
def sleepdeprived(request): module = request.node.get_closest_marker( "sleepdeprived_patched_module").args[0] old_sleep, module.sleep = module.sleep, noop try: yield finally: module.sleep = old_sleep # Taken from # http://bitbucket.org/runeh/snippets/src/tip/missing_module...
Mock sleep method in patched module to do nothing. Example: >>> import time >>> @pytest.mark.sleepdeprived_patched_module(time) >>> def test_foo(self, sleepdeprived): >>> pass
21
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def sleepdeprived(request): module = request.node.get_closest_marker( "sleepdeprived_patched_module").args[0] old_sleep, module.sleep = module.sleep, noop try: ...
1,426
def _set_mouse_bindings(self) -> None: logger.debug("Binding mouse events") if system() == "Linux": self._canvas.tag_bind(self._canvas.image_id, "<Button-4>", self._on_bound_zoom) self._canvas.tag_bind(self._canvas.image_id, "<Button-5>", self._on_bound_zoom) els...
Set the mouse bindings for interacting with the preview image Mousewheel: Zoom in and out Mouse click: Move image
19
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _set_mouse_bindings(self) -> None: logger.debug("Binding mouse events") if system() == "Linux": self._canvas.tag_bind(self._canvas.image_id, "<Button...
1,427
async def test_create_area_with_id_already_in_use(registry): area1 = registry.async_create("mock") updated_area1 = registry.async_update(area1.id, name="New Name") assert updated_area1.id == area1.id area2 = registry.async_create("mock") assert area2.id == "mock_2"
Make sure that we can't create an area with a name already in use.
14
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_create_area_with_id_already_in_use(registry): area1 = registry.async_create("mock") updated_area1 = registry.async_update(area1.id, name="New Name") assert u...
1,428
def forward(self, *args, **kwargs): labels = kwargs.pop('labels', None) pooled, encoded = super(ErnieModelForSequenceClassification, self).forward(*args, **kwargs) hidden = self.dropout(pooled) logits = self.classifier(hidden) if labels is not None: if len(l...
Args: labels (optional, `Variable` of shape [batch_size]): ground truth label id for each sentence Returns: loss (`Variable` of shape []): Cross entropy loss mean over batch if labels not set, returns None logits (`Vari...
42
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def forward(self, *args, **kwargs): labels = kwargs.pop('labels', None) pooled, encoded = super(ErnieModelForSequenceClassification, self).forward(*args, **kwargs) ...
1,429
def _get_project(self, name): raise NotImplementedError('Please implement in the subclass')
For a given project, get a dictionary mapping available versions to Distribution instances. This should be implemented in subclasses. If called from a locate() request, self.matcher will be set to a matcher for the requirement to satisfy, otherwise it will be None.
42
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_project(self, name): raise NotImplementedError('Please implement in the subclass') ``` ###Assistant : For a given project, get a dictionary ma...
1,430
def test_pickle_empty(self): arr = np.array([]).reshape(999999, 0) pk_dmp = pickle.dumps(arr) pk_load = pickle.loads(pk_dmp) assert pk_load.size == 0
Checking if an empty array pickled and un-pickled will not cause a segmentation fault
14
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_pickle_empty(self): arr = np.array([]).reshape(999999, 0) pk_dmp = pickle.dumps(arr) pk_load = pickle.loads(pk_dmp) assert pk_load.size == ...
1,431
def get_semantics(cls, kwargs, semantics=None): # TODO this should be get_variables since we have included x and y if semantics is None: semantics = cls.semantics variables = {} for key, val in kwargs.items(): if key in semantics and val is not None: ...
Subset a dictionary arguments with known semantic variables.
8
46
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_semantics(cls, kwargs, semantics=None): # TODO this should be get_variables since we have included x and y if semantics is None: semantics = cls....
1,432
def convert_deps_to_pip(deps, project=None, r=True, include_index=True): from pipenv.vendor.requirementslib.models.requirements import Requirement dependencies = [] for dep_name, dep in deps.items(): if project: project.clear_pipfile_cache() indexes = getattr(project, "pipf...
"Converts a Pipfile-formatted dependency to a pip-formatted one.
8
72
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def convert_deps_to_pip(deps, project=None, r=True, include_index=True): from pipenv.vendor.requirementslib.models.requirements import Requirement dependencies = [] for dep...
1,433
def handle_trial_end(self, data): hyper_params = nni.load(data['hyper_params']) if self.is_created_in_previous_exp(hyper_params['parameter_id']): # The end of the recovered trial is ignored return self._handle_trial_end(hyper_params['parameter_id']) if da...
Parameters ---------- data: dict() it has three keys: trial_job_id, event, hyper_params trial_job_id: the id generated by training service event: the job's state hyper_params: the hyperparameters (a string) generated and returned by tuner
32
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def handle_trial_end(self, data): hyper_params = nni.load(data['hyper_params']) if self.is_created_in_previous_exp(hyper_params['parameter_id']): # The e...
1,434
def _copy_future_state(source, dest): assert source.done() if dest.cancelled(): return assert not dest.done() if source.cancelled(): dest.cancel() else: exception = source.exception() if exception is not None: dest.set_exception(_convert_future_exc(ex...
Internal helper to copy state from another Future. The other Future may be a concurrent.futures.Future.
15
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _copy_future_state(source, dest): assert source.done() if dest.cancelled(): return assert not dest.done() if source.cancelled(): dest.cancel() el...
1,435
def test_get_feature_names_invalid_dtypes(names, dtypes): pd = pytest.importorskip("pandas") X = pd.DataFrame([[1, 2], [4, 5], [5, 6]], columns=names) msg = re.escape( "Feature names only support names that are all strings. " f"Got feature names with dtypes: {dtypes}." ) with p...
Get feature names errors when the feature names have mixed dtypes
11
41
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_get_feature_names_invalid_dtypes(names, dtypes): pd = pytest.importorskip("pandas") X = pd.DataFrame([[1, 2], [4, 5], [5, 6]], columns=names) msg = re.escape( ...
1,436
def lookup(address, port, s): # We may get an ipv4-mapped ipv6 address here, e.g. ::ffff:127.0.0.1. # Those still appear as "127.0.0.1" in the table, so we need to strip the prefix. address = re.sub(r"^::ffff:(?=\d+.\d+.\d+.\d+$)", "", address) s = s.decode() # ALL tcp 192.168.1.13:57474 -> 23...
Parse the pfctl state output s, to look up the destination host matching the client (address, port). Returns an (address, port) tuple, or None.
24
133
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def lookup(address, port, s): # We may get an ipv4-mapped ipv6 address here, e.g. ::ffff:127.0.0.1. # Those still appear as "127.0.0.1" in the table, so we need to strip the pre...
1,437
def _hydrate_rules(cls, project_id, rules, type=OwnerRuleType.OWNERSHIP_RULE.value): owners = [owner for rule in rules for owner in rule.owners] actors = { key: val for key, val in resolve_actors({owner for owner in owners}, project_id).items() if val ...
Get the last matching rule to take the most precedence.
10
51
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _hydrate_rules(cls, project_id, rules, type=OwnerRuleType.OWNERSHIP_RULE.value): owners = [owner for rule in rules for owner in rule.owners] actors = { ...
1,438
def activate(self) -> str: load_kube_config_from_dict( config_dict=self.config, context=self.context, ) return self.current_context()
Convenience method for activating the k8s config stored in an instance of this block Returns current_context for sanity check
19
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def activate(self) -> str: load_kube_config_from_dict( config_dict=self.config, context=self.context, ) return self.current_context(...
1,439
def as_coeff_add(self, *deps) -> tuple[Expr, tuple[Expr, ...]]: if deps: if not self.has_free(*deps): return self, tuple() return S.Zero, (self,)
Return the tuple (c, args) where self is written as an Add, ``a``. c should be a Rational added to any terms of the Add that are independent of deps. args should be a tuple of all other terms of ``a``; args is empty if self is a Number or if self is independent of deps (when given). ...
195
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def as_coeff_add(self, *deps) -> tuple[Expr, tuple[Expr, ...]]: if deps: if not self.has_free(*deps): return self, tuple() return S.Zero,...
1,440
def create_github_url(url): repo_only_url = re.compile( r"https:\/\/github\.com\/[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}\/[a-zA-Z0-9]+$" ) re_branch = re.compile("/(tree|blob)/(.+?)/") # Check if the given url is a url to a GitHub repo. If it is, tell the # user to use 'git clone' to dow...
From the given url, produce a URL that is compatible with Github's REST API. Can handle blob or tree paths.
20
112
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def create_github_url(url): repo_only_url = re.compile( r"https:\/\/github\.com\/[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}\/[a-zA-Z0-9]+$" ) re_branch = re.compile("/(tr...
1,441
def homogeneity_score(labels_true, labels_pred): return homogeneity_completeness_v_measure(labels_true, labels_pred)[0]
Homogeneity metric of a cluster labeling given a ground truth. A clustering result satisfies homogeneity if all of its clusters contain only data points which are members of a single class. This metric is independent of the absolute values of the labels: a permutation of the class or cluster label val...
263
6
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def homogeneity_score(labels_true, labels_pred): return homogeneity_completeness_v_measure(labels_true, labels_pred)[0] ``` ###Assistant : Homogeneity metric of a clus...
1,442
def dup_chebyshevt(n, K): if n < 1: return [K.one] m2, m1 = [K.one], [K.one, K.zero] for i in range(2, n+1): m2, m1 = m1, dup_sub(dup_mul_ground(dup_lshift(m1, 1, K), K(2), K), m2, K) return m1
Low-level implementation of Chebyshev polynomials of the first kind.
9
33
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def dup_chebyshevt(n, K): if n < 1: return [K.one] m2, m1 = [K.one], [K.one, K.zero] for i in range(2, n+1): m2, m1 = m1, dup_sub(dup_mul_ground(dup_lshift(m...
1,443
def get_markdown_toc(markdown_source): md = markdown.Markdown(extensions=['toc']) md.convert(markdown_source) return md.toc_tokens
Return TOC generated by Markdown parser from Markdown source text.
10
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_markdown_toc(markdown_source): md = markdown.Markdown(extensions=['toc']) md.convert(markdown_source) return md.toc_tokens ``` ###Assistant : Return TO...
1,444
def get_value_data_from_instance(self, instance): return { "id": instance.pk, "edit_url": AdminURLFinder().get_edit_url(instance), }
Given a model instance, return a value that we can pass to both the server-side template and the client-side rendering code (via telepath) that contains all the information needed for display. Typically this is a dict of id, title etc; it must be JSON-serialisable.
44
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_value_data_from_instance(self, instance): return { "id": instance.pk, "edit_url": AdminURLFinder().get_edit_url(instance), } ...
1,445
def set_options(icon=None, button_color=None, element_size=(None, None), button_element_size=(None, None), margins=(None, None), element_padding=(None, None), auto_size_text=None, auto_size_buttons=None, font=None, border_width=None, slider_border_width=None, slider_relie...
:param icon: Can be either a filename or Base64 value. For Windows if filename, it MUST be ICO format. For Linux, must NOT be ICO. Most portable is to use a Base64 of a PNG file. This works universally across all OS's :type icon: bytes | str :param but...
889
4,824
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_options(icon=None, button_color=None, element_size=(None, None), button_element_size=(None, None), margins=(None, None), element_padding=(None, None),...
1,446
def find_module(module, path=None, imp=None): if imp is None: imp = import_module with cwd_in_path(): try: return imp(module) except ImportError: # Raise a more specific error if the problem is that one of the # dot-separated segments of the modul...
Version of :func:`imp.find_module` supporting dots.
5
84
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def find_module(module, path=None, imp=None): if imp is None: imp = import_module with cwd_in_path(): try: return imp(module) except ImportEr...
1,447
def get_ffmpeg_path() -> Optional[Path]: # Check if ffmpeg is installed global_ffmpeg = shutil.which("ffmpeg") if global_ffmpeg: return Path(global_ffmpeg) # Get local ffmpeg path return get_local_ffmpeg()
Get path to global ffmpeg binary or a local ffmpeg binary. Or None if not found.
16
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_ffmpeg_path() -> Optional[Path]: # Check if ffmpeg is installed global_ffmpeg = shutil.which("ffmpeg") if global_ffmpeg: return Path(global_ffmpeg) # G...
1,448
def __call__(self, inputs, state, scope=None): return self._call_wrapped_cell( inputs, state, cell_call_fn=self.cell.__call__, scope=scope )
Runs the RNN cell step computation. We assume that the wrapped RNNCell is being built within its `__call__` method. We directly use the wrapped cell's `__call__` in the overridden wrapper `__call__` method. This allows to use the wrapped cell and the non-wrapped cell equivalently ...
102
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def __call__(self, inputs, state, scope=None): return self._call_wrapped_cell( inputs, state, cell_call_fn=self.cell.__call__, scope=scope ) ```...
1,449
def get_kurtosis(self) -> pd.DataFrame: vals = list() for period in portfolio_helper.PERIODS: vals.append( [ round( scipy.stats.kurtosis( portfolio_helper.filter_df_by_period(self.returns, period...
Class method that retrieves kurtosis for portfolio and benchmark selected Returns ------- pd.DataFrame DataFrame with kurtosis for portfolio and benchmark for different periods
23
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_kurtosis(self) -> pd.DataFrame: vals = list() for period in portfolio_helper.PERIODS: vals.append( [ round( ...
1,450
def _save_model(self, epoch, batch, logs): logs = logs or {} if ( isinstance(self.save_freq, int) or self.epochs_since_last_save >= self.period ): # Block only when saving interval is reached. logs = tf_utils.sync_to_numpy_or_python_type(...
Saves the model. Args: epoch: the epoch this iteration is in. batch: the batch this iteration is in. `None` if the `save_freq` is set to `epoch`. logs: the `logs` dict passed in to `on_batch_end` or `on_epoch_end`.
36
230
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _save_model(self, epoch, batch, logs): logs = logs or {} if ( isinstance(self.save_freq, int) or self.epochs_since_last_save >= self.per...
1,451
def steiner_tree(G, terminal_nodes, weight="weight", method=None): r if method is None: import warnings msg = ( "steiner_tree will change default method from 'kou' to 'mehlhorn'" "in version 3.2.\nSet the `method` kwarg to remove this warning." ) warnings...
Return an approximation to the minimum Steiner tree of a graph. The minimum Steiner tree of `G` w.r.t a set of `terminal_nodes` (also *S*) is a tree within `G` that spans those nodes and has minimum size (sum of edge weights) among all such trees. The approximation algorithm is specified with the `met...
366
102
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def steiner_tree(G, terminal_nodes, weight="weight", method=None): r if method is None: import warnings msg = ( "steiner_tree will change default method ...
1,452
def find_object(self, queryset, request): if "id" in request.GET: return queryset.get(id=request.GET["id"])
Override this to implement more find methods.
7
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def find_object(self, queryset, request): if "id" in request.GET: return queryset.get(id=request.GET["id"]) ``` ###Assistant : Override thi...
1,453
def _maybe_infer_dtype_type(element): tipo = None if hasattr(element, "dtype"): tipo = element.dtype elif is_list_like(element): element = np.asarray(element) tipo = element.dtype return tipo
Try to infer an object's dtype, for use in arithmetic ops. Uses `element.dtype` if that's available. Objects implementing the iterator protocol are cast to a NumPy array, and from there the array's type is used. Parameters ---------- element : object Possibly has a `.dtype` attrib...
70
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _maybe_infer_dtype_type(element): tipo = None if hasattr(element, "dtype"): tipo = element.dtype elif is_list_like(element): element = np.asarray(element...
1,454
def test_create_api_message_special(): request = get_new_request("Alexa.PowerController", "TurnOn") directive_header = request["directive"]["header"] directive_header.pop("correlationToken") directive = messages.AlexaDirective(request) msg = directive.response("testName", "testNameSpace")._res...
Create an API message response of a request with non defaults.
11
59
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_create_api_message_special(): request = get_new_request("Alexa.PowerController", "TurnOn") directive_header = request["directive"]["header"] directive_header.pop("c...
1,455
def tearDown(self): r del self.model_fp16 del self.model_8bit gc.collect() torch.cuda.empty_cache()
TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
27
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def tearDown(self): r del self.model_fp16 del self.model_8bit gc.collect() torch.cuda.empty_cache() ``` ###Assistant : TearDown...
1,456
def test_pagination_from_sync_and_messages(self): channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "A") self.assertEquals(200, channel.code, channel.json_body) annotation_id = channel.json_body["event_id"] # Send an event after the relation events. s...
Pagination tokens from /sync and /messages can be used to paginate /relations.
12
226
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_pagination_from_sync_and_messages(self): channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "A") self.assertEquals(200, channel.code, cha...
1,457
def download(self, url_or_urls): url_or_urls = map_nested(self._download, url_or_urls, map_tuple=True) return url_or_urls
Download given url(s). Args: url_or_urls: url or `list`/`dict` of urls to download and extract. Each url is a `str`. Returns: downloaded_path(s): `str`, The downloaded paths matching the given input url_or_urls. Example: ```py ...
37
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def download(self, url_or_urls): url_or_urls = map_nested(self._download, url_or_urls, map_tuple=True) return url_or_urls ``` ###Assistant : Download gi...
1,458
def draw_gaussian(image, point, sigma): # Check if the gaussian is inside point[0] = round(point[0], 2) point[1] = round(point[1], 2) ul = [math.floor(point[0] - 7.5 * sigma), math.floor(point[1] - 7.5 * sigma)] br = [math.floor(point[0] + 7.5 * sigma), math.floor(point[1] + 7.5 * sigma)] ...
Draw gaussian circle at a point in an image. Args: image (np.array): An image of shape (H, W) point (np.array): The center point of the guassian circle sigma (float): Standard deviation of the gaussian kernel Returns: np.array: The image with the drawn gaussian.
43
148
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def draw_gaussian(image, point, sigma): # Check if the gaussian is inside point[0] = round(point[0], 2) point[1] = round(point[1], 2) ul = [math.floor(point[0] - 7.5 * ...
1,459
def setdefault(self, key, default=None): if key in self: return self[key] self[key] = default return default
Insert key with a value of default if key is not in the dictionary. Return the value for key if key is in the dictionary, else default.
27
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def setdefault(self, key, default=None): if key in self: return self[key] self[key] = default return default ``` ###Assistant : Inse...
1,460
def current_year(context): context["current_year"] = datetime.datetime.now().year return context
Add the current year to the context, so it can be used for the copyright note, or other places where it is needed.
23
7
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def current_year(context): context["current_year"] = datetime.datetime.now().year return context ``` ###Assistant : Add the current year to the...
1,461
def fileformatparser_map(self) -> Mapping[str, type]: return { "csv": CsvParser, "parquet": ParquetParser, } # TODO: make these user configurable in spec.json ab_additional_col = "_ab_additional_properties" ab_last_mod_col = "_ab_source_file_last_modified" ...
Mapping where every key is equal 'filetype' and values are corresponding parser classes.
13
37
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def fileformatparser_map(self) -> Mapping[str, type]: return { "csv": CsvParser, "parquet": ParquetParser, } # TODO: make these user con...
1,462
def pivot_table(self, index=None, columns=None, values=None, aggfunc="mean"): from dask.dataframe.reshape import pivot_table return pivot_table( self, index=index, columns=columns, values=values, aggfunc=aggfunc )
Create a spreadsheet-style pivot table as a DataFrame. Target ``columns`` must have category dtype to infer result's ``columns``. ``index``, ``columns``, ``values`` and ``aggfunc`` must be all scalar. Parameters ---------- values : scalar column to aggregate...
61
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def pivot_table(self, index=None, columns=None, values=None, aggfunc="mean"): from dask.dataframe.reshape import pivot_table return pivot_table( self, i...
1,463
def test_multi_trial_reuse_with_failing(ray_start_4_cpus_extra): os.environ["TUNE_MAX_PENDING_TRIALS_PG"] = "2" register_trainable("foo2", MyResettableClass) [trial1, trial2, trial3, trial4] = tune.run( "foo2", config={ "fail": tune.grid_search([False, True, False, False])...
Test that failing trial's actors are not reused. - 2 trials can run at the same time - Trial 1 succeeds, trial 2 fails - Trial 3 will be scheduled after trial 2 failed, so won't reuse actor - Trial 4 will be scheduled after trial 1 succeeded, so will reuse actor
52
42
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_multi_trial_reuse_with_failing(ray_start_4_cpus_extra): os.environ["TUNE_MAX_PENDING_TRIALS_PG"] = "2" register_trainable("foo2", MyResettableClass) [trial1, tria...
1,464
def dispatch(self, request, *args, **kwargs): page_id = kwargs.get("page_id") if not get_forms_for_user(self.request.user).filter(id=page_id).exists(): raise PermissionDenied self.page = get_object_or_404(Page, id=page_id).specific self.submissions = self.get_quer...
Check permissions, set the page and submissions, handle delete
9
32
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def dispatch(self, request, *args, **kwargs): page_id = kwargs.get("page_id") if not get_forms_for_user(self.request.user).filter(id=page_id).exists(): ...
1,465
def _prior_bpd(self, x_start): batch_size = x_start.shape[0] t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t) kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logv...
Get the prior KL term for the variational lower-bound, measured in bits-per-dim. This term can't be optimized, as it only depends on the encoder. :param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element.
48
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _prior_bpd(self, x_start): batch_size = x_start.shape[0] t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_lo...
1,466
def test_rolling_non_monotonic(method, expected): # Based on an example found in computation.rst use_expanding = [True, False, True, False, True, True, True, True] df = DataFrame({"values": np.arange(len(use_expanding)) ** 2})
Make sure the (rare) branch of non-monotonic indices is covered by a test. output from 1.1.3 is assumed to be the expected output. Output of sum/mean has manually been verified. GH 36933.
32
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_rolling_non_monotonic(method, expected): # Based on an example found in computation.rst use_expanding = [True, False, True, False, True, True, True, True] df = Data...
1,467
def clip(self, min=None, max=None): from dask.array.ufunc import clip return clip(self, min, max)
Return an array whose values are limited to ``[min, max]``. One of max or min must be given. Refer to :func:`dask.array.clip` for full documentation. See Also -------- dask.array.clip : equivalent function
31
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def clip(self, min=None, max=None): from dask.array.ufunc import clip return clip(self, min, max) ``` ###Assistant : Return an array whose values are l...
1,468
def _floor_std(self, std): r original_tensor = std.clone().detach() std = torch.clamp(std, min=self.std_floor) if torch.any(original_tensor != std): print( "[*] Standard deviation was floored! The model is preventing overfitting, nothing serious to worry about...
It clamps the standard deviation to not to go below some level This removes the problem when the model tries to cheat for higher likelihoods by converting one of the gaussians to a point mass. Args: std (float Tensor): tensor containing the standard deviation to be
46
34
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _floor_std(self, std): r original_tensor = std.clone().detach() std = torch.clamp(std, min=self.std_floor) if torch.any(original_tensor != std): ...
1,469
def asXML(self, doctag=None, namedItemsOnly=False, indent="", formatted=True): nl = "\n" out = [] namedItems = dict((v[1], k) for (k, vlist) in self.__tokdict.items() for v in vlist) nextLevelIndent = indent + " " # collapse out indents if for...
(Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
19
175
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def asXML(self, doctag=None, namedItemsOnly=False, indent="", formatted=True): nl = "\n" out = [] namedItems = dict((v[1], k) for (k, vlist) in self.__tokdic...
1,470
def times_seen_with_pending(self) -> int: return self.times_seen + self.times_seen_pending
Returns `times_seen` with any additional pending updates from `buffers` added on. This value must be set first.
17
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def times_seen_with_pending(self) -> int: return self.times_seen + self.times_seen_pending ``` ###Assistant : Returns `times_seen` with any additional ...
1,471
def test_api_create_storage_path(self): response = self.client.post( self.ENDPOINT, json.dumps( { "name": "A storage path", "path": "Somewhere/{asn}", }, ), content_type="application/...
GIVEN: - API request to create a storage paths WHEN: - API is called THEN: - Correct HTTP response - New storage path is created
25
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_api_create_storage_path(self): response = self.client.post( self.ENDPOINT, json.dumps( { "name": "A stor...
1,472
def test_set_all_ask_for_prompts_true_from_post(self, post, organization, inventory, org_admin): r = post( url=reverse('api:workflow_job_template_list'), data=dict( name='workflow that tests ask_for prompts', organization=organization.id, ...
Tests behaviour and values of ask_for_* fields on WFJT via POST
11
63
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_set_all_ask_for_prompts_true_from_post(self, post, organization, inventory, org_admin): r = post( url=reverse('api:workflow_job_template_list'), ...
1,473
def get_used_memory(): # Try to accurately figure out the memory usage if we are in a docker # container. docker_usage = None # For cgroups v1: memory_usage_filename = "/sys/fs/cgroup/memory/memory.stat" # For cgroups v2: memory_usage_filename_v2 = "/sys/fs/cgroup/memory.current" if...
Return the currently used system memory in bytes Returns: The total amount of used memory
15
60
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_used_memory(): # Try to accurately figure out the memory usage if we are in a docker # container. docker_usage = None # For cgroups v1: memory_usage_filename...
1,474
def pack_x_y_sample_weight(x, y=None, sample_weight=None): if y is None: # For single x-input, we do no tuple wrapping since in this case # there is no ambiguity. This also makes NumPy and Dataset # consistent in that the user does not have to wrap their Dataset # data in an unn...
Packs user-provided data into a tuple. This is a convenience utility for packing data into the tuple formats that `Model.fit` uses. Standalone usage: >>> x = tf.ones((10, 1)) >>> data = tf.keras.utils.pack_x_y_sample_weight(x) >>> isinstance(data, tf.Tensor) True >>> y = tf.ones((10, ...
83
71
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def pack_x_y_sample_weight(x, y=None, sample_weight=None): if y is None: # For single x-input, we do no tuple wrapping since in this case # there is no ambiguity. Th...
1,475
def test_glm_regression_vstacked_X(solver, fit_intercept, glm_dataset): model, X, y, _, coef_with_intercept, coef_without_intercept, alpha = glm_dataset n_samples, n_features = X.shape params = dict( alpha=alpha, fit_intercept=fit_intercept, # solver=solver, # only lbfgs availa...
Test that GLM converges for all solvers to correct solution on vstacked data. We work with a simple constructed data set with known solution. Fit on [X] with alpha is the same as fit on [X], [y] [X], [y] with 1 * alpha. It is the same alpha as the average los...
64
91
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_glm_regression_vstacked_X(solver, fit_intercept, glm_dataset): model, X, y, _, coef_with_intercept, coef_without_intercept, alpha = glm_dataset n_samples, n_features = ...
1,476
def deprecate_data(): sympy_deprecation_warning( , deprecated_since_version="1.4", active_deprecations_target="deprecated-tensorindextype-attrs", stacklevel=4, )
The data attribute of TensorIndexType is deprecated. Use The replace_with_arrays() method instead.
12
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def deprecate_data(): sympy_deprecation_warning( , deprecated_since_version="1.4", active_deprecations_target="deprecated-tensorindextype-attrs", stacklev...
1,477
def fit(self, X, y=None): self._validate_params() X = self._check_input(X, reset=True) if self.check_inverse and not (self.func is None or self.inverse_func is None): self._check_inverse_transform(X) return self
Fit transformer by checking X. If ``validate`` is ``True``, ``X`` will be checked. Parameters ---------- X : array-like, shape (n_samples, n_features) Input array. y : Ignored Not used, present here for API consistency by convention. Returns ...
43
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def fit(self, X, y=None): self._validate_params() X = self._check_input(X, reset=True) if self.check_inverse and not (self.func is None or self.inverse_func ...
1,478
def styleof(expr, styles=default_styles): style = {} for typ, sty in styles: if isinstance(expr, typ): style.update(sty) return style
Merge style dictionaries in order Examples ======== >>> from sympy import Symbol, Basic, Expr, S >>> from sympy.printing.dot import styleof >>> styles = [(Basic, {'color': 'blue', 'shape': 'ellipse'}), ... (Expr, {'color': 'black'})] >>> styleof(Basic(S(1)), styles) {'colo...
57
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def styleof(expr, styles=default_styles): style = {} for typ, sty in styles: if isinstance(expr, typ): style.update(sty) return style ``` #...
1,479
def execute(filters=None): columns = [ {"fieldname": "creation_date", "label": _("Date"), "fieldtype": "Date", "width": 300}, { "fieldname": "first_response_time", "fieldtype": "Duration", "label": _("First Response Time"), "width": 300, }, ] data = frappe.db.sql( , (filters.from_date, filters...
SELECT date(creation) as creation_date, avg(first_response_time) as avg_response_time FROM tabIssue WHERE date(creation) between %s and %s and first_response_time > 0 GROUP BY creation_date ORDER BY creation_date desc
26
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def execute(filters=None): columns = [ {"fieldname": "creation_date", "label": _("Date"), "fieldtype": "Date", "width": 300}, { "fieldname": "first_response_time", "fieldtype": "D...
1,480
def choose_parent(self, new_node, near_inds): if not near_inds: return None # search nearest cost in near_inds costs = [] for i in near_inds: near_node = self.node_list[i] t_node = self.steer(near_node, new_node) if t_node and sel...
Computes the cheapest point to new_node contained in the list near_inds and set such a node as the parent of new_node. Arguments: -------- new_node, Node randomly generated node with a path from its neared point There are n...
65
74
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def choose_parent(self, new_node, near_inds): if not near_inds: return None # search nearest cost in near_inds costs = [] for i in near_...
1,481
def test_a3c_compilation(self): config = a3c.DEFAULT_CONFIG.copy() config["num_workers"] = 2 config["num_envs_per_worker"] = 2 num_iterations = 1 # Test against all frameworks. for _ in framework_iterator(config, with_eager_tracing=True): for env in...
Test whether an A3CTrainer can be built with both frameworks.
10
54
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_a3c_compilation(self): config = a3c.DEFAULT_CONFIG.copy() config["num_workers"] = 2 config["num_envs_per_worker"] = 2 num_iterations = 1 ...
1,482
def extract(self, member, path="", set_attrs=True): self._check("r") if isinstance(member, str): tarinfo = self.getmember(member) else: tarinfo = member # Prepare the link target for makelink(). if tarinfo.islnk(): tarinfo._link_targ...
Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member' may be a filename or a TarInfo object. You can specify a different directory using `path'. File attributes (owner, mt...
52
76
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def extract(self, member, path="", set_attrs=True): self._check("r") if isinstance(member, str): tarinfo = self.getmember(member) else: ...
1,483
def test_artist_from_string(): artist = Artist.from_search_term("artist:gorillaz") assert artist.name == "Gorillaz" assert artist.url == "http://open.spotify.com/artist/3AA28KZvwAUcZuOKwyblJQ" assert len(artist.urls) > 1
Test if Artist class can be initialized from string.
9
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_artist_from_string(): artist = Artist.from_search_term("artist:gorillaz") assert artist.name == "Gorillaz" assert artist.url == "http://open.spotify.com/artist/3A...
1,484
def reset(self): # custom_info is used for episodic reports and tensorboard logging self.custom_info["Invalid"] = 0 self.custom_info["Hold"] = 0 self.custom_info["Unknown"] = 0 self.custom_info["pnl_factor"] = 0 self.custom_info["duration_factor"] = 0 sel...
Reset is called at the beginning of every episode
9
117
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def reset(self): # custom_info is used for episodic reports and tensorboard logging self.custom_info["Invalid"] = 0 self.custom_info["Hold"] = 0 self...
1,485
def get_ordered_to_be_billed_data(args): doctype, party = args.get("doctype"), args.get("party") child_tab = doctype + " Item" precision = ( get_field_precision( frappe.get_meta(child_tab).get_field("billed_amt"), currency=get_default_currency() ) or 2 ) project_field = get_project_field(doctype, party) ...
Select `{parent_tab}`.name, `{parent_tab}`.{date_field}, `{parent_tab}`.{party}, `{parent_tab}`.{party}_name, `{child_tab}`.item_code, `{child_tab}`.base_amount, (`{child_tab}`.billed_amt * ifnull(`{parent_tab}`.conversion_rate, 1)), (`{child_tab}`.base_rate * ifnull(`{child_tab}`.returned_qty, 0))...
70
44
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_ordered_to_be_billed_data(args): doctype, party = args.get("doctype"), args.get("party") child_tab = doctype + " Item" precision = ( get_field_precision( frappe.get_meta(chil...
1,486
def get_staged_trial(self): # TODO(xwjiang): This method should consider `self._cached_actor_pg`. for trial in self._staged_trials: if self._pg_manager.has_ready(trial): return trial return None
Get a trial whose placement group was successfully staged. Can also return None if no trial is available. Returns: Trial object or None.
23
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_staged_trial(self): # TODO(xwjiang): This method should consider `self._cached_actor_pg`. for trial in self._staged_trials: if self._pg_manager.h...
1,487
def register(cls, func, squeeze_self=False, **kwargs): return super().register( Resampler.build_resample(func, squeeze_self), fn_name=func.__name__, **kwargs )
Build function that do fallback to pandas and aggregate resampled data. Parameters ---------- func : callable Aggregation function to execute under resampled frame. squeeze_self : bool, default: False Whether or not to squeeze frame before resampling. ...
70
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def register(cls, func, squeeze_self=False, **kwargs): return super().register( Resampler.build_resample(func, squeeze_self), fn_name=func.__name__, ...
1,488
def aggregate(self, *args, **kwargs): if self.query.distinct_fields: raise NotImplementedError("aggregate() + distinct(fields) not implemented.") self._validate_values_are_expressions( (*args, *kwargs.values()), method_name="aggregate" ) for arg in args: ...
Return a dictionary containing the calculations (aggregation) over the current queryset. If args is present the expression is passed as a kwarg using the Aggregate object's default alias.
28
117
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def aggregate(self, *args, **kwargs): if self.query.distinct_fields: raise NotImplementedError("aggregate() + distinct(fields) not implemented.") self._v...
1,489
def _detect_bytelen_from_str(s): # type: (str) -> int assert len(s) >= 2 tmp_len = len(s) i = 1 while orb(s[i]) & 0x80 > 0: i += 1 assert i < tmp_len, 'EINVAL: s: out-of-bound read: unfinished AbstractUVarIntField detected' # noqa: E501 ...
_detect_bytelen_from_str returns the length of the machine representation of an AbstractUVarIntField starting at the beginning of s and which is assumed to expand over multiple bytes (value > _max_prefix_value). :param str s: the string to parse. It is assumed that it is a multib...
56
51
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _detect_bytelen_from_str(s): # type: (str) -> int assert len(s) >= 2 tmp_len = len(s) i = 1 while orb(s[i]) & 0x80 > 0: i +=...
1,490
def get_gl_entries(voucher_type, voucher_no): return frappe.db.sql( , (voucher_type, voucher_no), as_dict=1, )
select account, debit, credit, cost_center, is_cancelled from `tabGL Entry` where voucher_type=%s and voucher_no=%s order by account desc
17
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_gl_entries(voucher_type, voucher_no): return frappe.db.sql( , (voucher_type, voucher_no), as_dict=1, ) ``` ###Assistant : select account, debit, credit, cost_ce...
1,491
def random_normal(mean=0.0, std=1.0, shape=None, dev=None, f=None): return _cur_framework(f=f).random_normal(mean, std, shape, dev)
Draws samples from a normal distribution. :param mean: The mean of the normal distribution to sample from. Default is 0. :type mean: float :param std: The standard deviation of the normal distribution to sample from. Default is 1. :type std: float :param shape: Output shape. If the given shape...
111
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def random_normal(mean=0.0, std=1.0, shape=None, dev=None, f=None): return _cur_framework(f=f).random_normal(mean, std, shape, dev) ``` ###Assistant : Draws sampl...
1,492
def get_font_preamble(cls): font_preamble, command = cls._get_font_preamble_and_command() return font_preamble
Return a string containing font configuration for the tex preamble.
10
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_font_preamble(cls): font_preamble, command = cls._get_font_preamble_and_command() return font_preamble ``` ###Assistant : Return a stri...
1,493
def do_test_explorations(config, dummy_obs, prev_a=None, expected_mean_action=None): # Test all frameworks. for _ in framework_iterator(config): print(f"Algorithm={config.algo_class}") # Test for both the default Agent's exploration AND the `Random` # exploration class. fo...
Calls an Agent's `compute_actions` with different `explore` options.
8
147
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def do_test_explorations(config, dummy_obs, prev_a=None, expected_mean_action=None): # Test all frameworks. for _ in framework_iterator(config): print(f"Algorithm={conf...
1,494
def exit_with_success(message, **kwargs): kwargs.setdefault("style", "green") app.console.print(message, **kwargs) raise typer.Exit(0)
Utility to print a stylized success message and exit with a zero code
13
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def exit_with_success(message, **kwargs): kwargs.setdefault("style", "green") app.console.print(message, **kwargs) raise typer.Exit(0) ``` ###Assistant : U...
1,495
def get_keywords() -> Dict[str, str]: # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "$Format:%d$" git_f...
Get the keywords needed to look up the version information.
10
61
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_keywords() -> Dict[str, str]: # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # e...
1,496
def take(outname, inname, chunks, index, itemsize, axis=0): from .core import PerformanceWarning plan = slicing_plan(chunks[axis], index) if len(plan) >= len(chunks[axis]) * 10: factor = math.ceil(len(plan) / len(chunks[axis])) warnings.warn( "Slicing with an out-of-order ...
Index array with an iterable of index Handles a single index by a single list Mimics ``np.take`` >>> from pprint import pprint >>> chunks, dsk = take('y', 'x', [(20, 20, 20, 20)], [5, 1, 47, 3], 8, axis=0) >>> chunks ((2, 1, 1),) >>> pprint(dsk) # doctest: +ELLIPSIS {('y', 0): (<fun...
191
299
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def take(outname, inname, chunks, index, itemsize, axis=0): from .core import PerformanceWarning plan = slicing_plan(chunks[axis], index) if len(plan) >= len(chunks[axis]) ...
1,497
def test_multidb(self): ContentType.objects.clear_cache() with self.assertNumQueries(0, using="default"), self.assertNumQueries( 1, using="other" ): ContentType.objects.get_for_model(Author)
When using multiple databases, ContentType.objects.get_for_model() uses db_for_read().
7
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_multidb(self): ContentType.objects.clear_cache() with self.assertNumQueries(0, using="default"), self.assertNumQueries( 1, using="other" ...
1,498
def get_engle_granger_two_step_cointegration_test(y, x): warnings.simplefilter(action="ignore", category=FutureWarning) long_run_ols = sm.OLS(y, sm.add_constant(x)) warnings.simplefilter(action="default", category=FutureWarning) long_run_ols_fit = long_run_ols.fit() c, gamma = long_run_ols_fi...
Estimates long-run and short-run cointegration relationship for series y and x and apply the two-step Engle & Granger test for cointegration. Uses a 2-step process to first estimate coefficients for the long-run relationship y_t = c + gamma * x_t + z_t and then the short-term relationship, ...
315
103
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_engle_granger_two_step_cointegration_test(y, x): warnings.simplefilter(action="ignore", category=FutureWarning) long_run_ols = sm.OLS(y, sm.add_constant(x)) warnings...
1,499
def test_deterministic_order_for_unordered_model(self): superuser = self._create_superuser("superuser") for counter in range(1, 51): UnorderedObject.objects.create(id=counter, bool=True)
The primary key is used in the ordering of the changelist's results to guarantee a deterministic order, even when the model doesn't have any default ordering defined (#17198).
28
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_deterministic_order_for_unordered_model(self): superuser = self._create_superuser("superuser") for counter in range(1, 51): UnorderedObject.obj...