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
500
def set_aspect(self, aspect, adjustable=None, anchor=None, share=False): if cbook._str_equal(aspect, 'equal'): aspect = 1 if not cbook._str_equal(aspect, 'auto'): aspect = float(aspect) # raise ValueError if necessary if aspect<0: raise Value...
Set the aspect ratio of the axes scaling, i.e. y/x-scale. Parameters ---------- aspect : {'auto', 'equal'} or float Possible values: - 'auto': fill the position rectangle with data. - 'equal': same as ``aspect=1``, i.e. same scaling for x and y. ...
219
77
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): if cbook._str_equal(aspect, 'equal'): aspect = 1 if not cbook._str_equal(aspect,...
501
def test_pk_attributes(self): # pk can be used as a substitute for the primary key. # The primary key can be accessed via the pk property on the model. e = Employee.objects.get(pk=123) self.assertEqual(e.pk, 123) # Or we can use the real attribute name for the primary ke...
pk and attribute name are available on the model No default id attribute is added
15
59
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_pk_attributes(self): # pk can be used as a substitute for the primary key. # The primary key can be accessed via the pk property on the model. e = E...
502
async def __aenter__(self): if self._closed: # httpx.AsyncClient does not allow reuse so we will not either. raise RuntimeError( "The client cannot be started again after closing. " "Retrieve a new client with `get_client()` instead." ...
Start the client. If the client is already started, this will raise an exception. If the client is already closed, this will raise an exception. Use a new client instance instead.
31
95
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def __aenter__(self): if self._closed: # httpx.AsyncClient does not allow reuse so we will not either. raise RuntimeError( "The...
503
def training_iteration(self) -> ResultDict: # Sample n batches from n workers. new_sample_batches = synchronous_parallel_sample( worker_set=self.workers, concat=False ) for batch in new_sample_batches: # Update counters. self._counters[NUM_EN...
QMIX training iteration function. - Sample n MultiAgentBatches from n workers synchronously. - Store new samples in the replay buffer. - Sample one training MultiAgentBatch from the replay buffer. - Learn on the training batch. - Update the target network every `target_network_u...
61
224
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def training_iteration(self) -> ResultDict: # Sample n batches from n workers. new_sample_batches = synchronous_parallel_sample( worker_set=self.workers,...
504
def _announce() -> None: current_version = get_package_version() tag_name = f"v{current_version}" click.echo( f ) if "rc" in tag_name: click.echo( ) else: click.echo( ) @cli.command() @click.option("--gh-token", envvar=[...
Generate markdown to announce the release. Hi everyone. Synapse {current_version} has just been released. [notes](https://github.com/matrix-org/synapse/releases/tag/{tag_name}) | \ [docker](https://hub.docker.com/r/matrixdotorg/synapse/tags?name={tag_name}) | \ [debs](https://packages.matrix.org/debian/) | \ [pypi](ht...
72
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _announce() -> None: current_version = get_package_version() tag_name = f"v{current_version}" click.echo( f ) if "rc" in tag_name: click.echo(...
505
def update(self, value=None, visible=None): if not self._widget_was_created(): # if widget hasn't been created yet, then don't allow return if value is not None: self._TKOut.output.delete('1.0', tk.END) self._TKOut.output.insert(tk.END, value) if vi...
Changes some of the settings for the Output Element. Must call `Window.Read` or `Window.Finalize` prior Changes will not be visible in your window until you call window.read or window.refresh. If you change visibility, your element may MOVE. If you want it to remain stationary, use the "layou...
94
45
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def update(self, value=None, visible=None): if not self._widget_was_created(): # if widget hasn't been created yet, then don't allow return if value is...
506
def example(self): result = getattr(self, "_example", None) if result is None: # No example batch was found, so get one from the `.train` dataset result = next(iter(self.train)) # And cache it for next time self._example = result return re...
Get and cache an example batch of `inputs, labels` for plotting.
11
39
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def example(self): result = getattr(self, "_example", None) if result is None: # No example batch was found, so get one from the `.train` dataset ...
507
def unit_attname(cls, unit_str): lower = unit_str.lower() if unit_str in cls.UNITS: return unit_str elif lower in cls.UNITS: return lower elif lower in cls.LALIAS: return cls.LALIAS[lower] else: raise Exception( ...
Retrieve the unit attribute name for the given unit string. For example, if the given unit string is 'metre', return 'm'. Raise an exception if an attribute cannot be found.
30
39
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def unit_attname(cls, unit_str): lower = unit_str.lower() if unit_str in cls.UNITS: return unit_str elif lower in cls.UNITS: return l...
508
def test_dont_import_tf_error(): # Do not import tf for testing purposes. os.environ["RLLIB_TEST_NO_TF_IMPORT"] = "1" config = ppo.PPOConfig().environment("CartPole-v1") for _ in framework_iterator(config, frameworks=("tf", "tf2")): with pytest.raises(ImportError, match="However, no instal...
Check error being thrown, if tf not installed but configured.
10
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_dont_import_tf_error(): # Do not import tf for testing purposes. os.environ["RLLIB_TEST_NO_TF_IMPORT"] = "1" config = ppo.PPOConfig().environment("CartPole-v1") ...
509
def _current(self): if self._hmac: return self._hmac else: h = self._outer.copy() h.update(self._inner.digest()) return h
Return a hash object for the current state. To be used only internally with digest() and hexdigest().
17
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _current(self): if self._hmac: return self._hmac else: h = self._outer.copy() h.update(self._inner.digest()) retu...
510
def delete_links_from_desktop_icons(report): desktop_icons = frappe.db.get_values("Desktop Icon", {"_report": report}, ["name"]) for desktop_icon in desktop_icons: frappe.delete_doc("Desktop Icon", desktop_icon[0])
Check for one or multiple Desktop Icons and delete
9
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def delete_links_from_desktop_icons(report): desktop_icons = frappe.db.get_values("Desktop Icon", {"_report": report}, ["name"]) for desktop_icon in desktop_icons: frappe.delete_doc("D...
511
def get_bboxes_list(end2end_result, structure_master_result): # end2end end2end_xyxy_list = [] end2end_xywh_list = [] for end2end_item in end2end_result: src_bbox = end2end_item['bbox'] end2end_xyxy_list.append(src_bbox) xywh_bbox = xyxy2xywh(src_bbox) end2end_xywh_l...
This function is use to convert end2end results and structure master results to List of xyxy bbox format and List of xywh bbox format :param end2end_result: bbox's format is xyxy :param structure_master_result: bbox's format is xywh :return: 4 kind list of bbox ()
43
64
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_bboxes_list(end2end_result, structure_master_result): # end2end end2end_xyxy_list = [] end2end_xywh_list = [] for end2end_item in end2end_result: src_bbo...
512
def autoname_elements() -> None: for name, var in sys._getframe().f_back.f_locals.items(): if isinstance(var, ParserElement) and not var.customName: var.set_name(name) dbl_quoted_string = Combine( Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"' ).set_name("string ...
Utility to simplify mass-naming of parser elements, for generating railroad diagram with named subdiagrams.
14
134
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def autoname_elements() -> None: for name, var in sys._getframe().f_back.f_locals.items(): if isinstance(var, ParserElement) and not var.customName: var.set_name...
513
def test_valid_zero_ops_doesnt_require_backend_dispatch_key(self) -> None: yaml_str = # External codegen on a yaml file with no operators is effectively a no-op, # so there's no reason to parse the backend self.assert_success_from_gen_backend_stubs(yaml_str)
\ backend: BAD_XLA cpp_namespace: torch_xla supported:
6
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_valid_zero_ops_doesnt_require_backend_dispatch_key(self) -> None: yaml_str = # External codegen on a yaml file with no operators is effectively a no-op, # s...
514
async def test_pseudo_remote_peas_topologies(gateway, head, worker): worker_port = random_port() head_port = random_port() port_expose = random_port() graph_description = '{"start-gateway": ["pod0"], "pod0": ["end-gateway"]}' if head == 'remote': pods_addresses = f'{{"pod0": ["{HOST}:{h...
g(l)-h(l)-w(l) - works g(l)-h(l)-w(r) - works - head connects to worker via localhost g(l)-h(r)-w(r) - works - head (inside docker) connects to worker via dockerhost g(l)-h(r)-w(l) - doesn't work remote head need remote worker g(r)-... - doesn't work, as distributed parser not enabled for gateway ...
50
132
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_pseudo_remote_peas_topologies(gateway, head, worker): worker_port = random_port() head_port = random_port() port_expose = random_port() graph_description ...
515
async def async_wait_start_success(self): import asyncio _timeout = self.args.timeout_ready if _timeout <= 0: _timeout = None else: _timeout /= 1e3 timeout_ns = 1e9 * _timeout if _timeout else None now = time.time_ns() while time...
Wait for the `Pea` to start successfully in a non-blocking manner
11
50
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def async_wait_start_success(self): import asyncio _timeout = self.args.timeout_ready if _timeout <= 0: _timeout = None else: ...
516
def set_fontsize(self, s=None): if s is None: s = mpl.rcParams["legend.fontsize"] self.prop = FontProperties(size=s) self.stale = True
Set the fontsize in points. If *s* is not given, reset to :rc:`legend.fontsize`.
13
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_fontsize(self, s=None): if s is None: s = mpl.rcParams["legend.fontsize"] self.prop = FontProperties(size=s) self.stale = True ...
517
def get_next(self, timeout=None): if not self.has_next(): raise StopIteration("No more results to get") if self._next_return_index >= self._next_task_index: raise ValueError( "It is not allowed to call get_next() after " "get_next_unordered()." ...
Returns the next pending result in order. This returns the next result produced by submit(), blocking for up to the specified timeout until it is available. Returns: The next result. Raises: TimeoutError if the timeout is reached. Examples: ...
51
71
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_next(self, timeout=None): if not self.has_next(): raise StopIteration("No more results to get") if self._next_return_index >= self._next_task_ind...
518
def expand_egg_links(self) -> None: prefixes = [ Path(prefix) for prefix in self.base_paths["libdirs"].split(os.pathsep) if vistir.path.is_in_path(prefix, self.prefix.as_posix()) ] for loc in prefixes: if not loc.exists(): ...
Expand paths specified in egg-link files to prevent pip errors during reinstall
12
44
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def expand_egg_links(self) -> None: prefixes = [ Path(prefix) for prefix in self.base_paths["libdirs"].split(os.pathsep) if vistir.path.i...
519
def test_page_with_og(self) -> None: html = b parser = OpenGraphParser(html, "text/html; charset=UTF-8") result = parser.extract_data() self.assertEqual(result.title, "The Rock") self.assertEqual(result.description, "The Rock film")
<html> <head> <meta property="og:title" content="The Rock" /> <meta property="og:type" content="video.movie" /> <meta property="og:url" content="http://www.imdb.com/title/tt0117500/" /> <meta property="og:image" content="http://ia.media-imdb.com/images/rock.jpg" /> ...
27
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_page_with_og(self) -> None: html = b parser = OpenGraphParser(html, "text/html; charset=UTF-8") result = parser.extract_data() self.assertEqual(resu...
520
def is_rational_function(self, *syms): if self in _illegal: return False if syms: syms = set(map(sympify, syms)) else: syms = self.free_symbols if not syms: return True return self._eval_is_rational_function(syms)...
Test whether function is a ratio of two polynomials in the given symbols, syms. When syms is not given, all free symbols will be used. The rational function does not have to be in expanded or in any kind of canonical form. This function returns False for expressions that are "r...
182
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_rational_function(self, *syms): if self in _illegal: return False if syms: syms = set(map(sympify, syms)) else: s...
521
def reduce_alg_num(self, a): elt = self.ZK.parent.element_from_alg_num(a) red = self.reduce_element(elt) return a.field_element(list(reversed(red.QQ_col.flat())))
Reduce an :py:class:`~.AlgebraicNumber` to a "small representative" modulo this prime ideal. Parameters ========== elt : :py:class:`~.AlgebraicNumber` The element to be reduced. Returns ======= :py:class:`~.AlgebraicNumber` The...
33
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def reduce_alg_num(self, a): elt = self.ZK.parent.element_from_alg_num(a) red = self.reduce_element(elt) return a.field_element(list(reversed(red.QQ_col.flat...
522
def _auto_joiner(self, short_results, input_mapping, is_dict=False): concat_results = [] elem_type = {} if is_dict else [] for k, vs in input_mapping.items(): single_results = elem_type for v in vs: if len(single_results) == 0: ...
Join the short results automatically and generate the final results to match with the user inputs. Args: short_results (List[dict] / List[List[str]] / List[str]): input raw texts. input_mapping (dict): cutting length. is_dict (bool): whether the element type is dict,...
51
79
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _auto_joiner(self, short_results, input_mapping, is_dict=False): concat_results = [] elem_type = {} if is_dict else [] for k, vs in input_mapping.items()...
523
def get_variable_names_from_ckpt(path_ckpt, use_ema=True): v_all = tf.train.list_variables(path_ckpt) # keep name only v_name_all = [x[0] for x in v_all] if use_ema: v_name_all = [x for x in v_name_all if "ExponentialMovingAverage" in x] else: v_name_all = [ x for ...
Get list of tensor names from checkpoint. Args: path_ckpt: str, path to the ckpt files use_ema: Bool, whether to use ExponentialMovingAverage result or not. Returns: List of variable names from checkpoint.
31
66
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_variable_names_from_ckpt(path_ckpt, use_ema=True): v_all = tf.train.list_variables(path_ckpt) # keep name only v_name_all = [x[0] for x in v_all] if use_ema: ...
524
def ode_order(expr, func): a = Wild('a', exclude=[func]) if expr.match(a): return 0 if isinstance(expr, Derivative): if expr.args[0] == func: return len(expr.variables) else: return max(ode_order(arg, func) for arg in expr.args[0].args) + len(expr.variab...
Returns the order of a given differential equation with respect to func. This function is implemented recursively. Examples ======== >>> from sympy import Function >>> from sympy.solvers.deutils import ode_order >>> from sympy.abc import x >>> f, g = map(Function, ['f', 'g']) ...
67
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def ode_order(expr, func): a = Wild('a', exclude=[func]) if expr.match(a): return 0 if isinstance(expr, Derivative): if expr.args[0] == func: re...
525
async def async_send_message(self, message, **kwargs): nextcord.VoiceClient.warn_nacl = False discord_bot = nextcord.Client() images = None embedding = None if ATTR_TARGET not in kwargs: _LOGGER.error("No target specified") return None d...
Login to Discord, send message to channel(s) and log out.
10
170
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def async_send_message(self, message, **kwargs): nextcord.VoiceClient.warn_nacl = False discord_bot = nextcord.Client() images = None embedding...
526
def rand_series_with_duplicate_datetimeindex() -> Series: dates = [ datetime(2000, 1, 2), datetime(2000, 1, 2), datetime(2000, 1, 2), datetime(2000, 1, 3), datetime(2000, 1, 3), datetime(2000, 1, 3), datetime(2000, 1, 4), datetime(2000, 1, 4), ...
Fixture for Series with a DatetimeIndex that has duplicates.
9
78
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def rand_series_with_duplicate_datetimeindex() -> Series: dates = [ datetime(2000, 1, 2), datetime(2000, 1, 2), datetime(2000, 1, 2), datetime(2000, ...
527
def get_major_minor_version(): # type: () -> str return "{}.{}".format(*sys.version_info)
Return the major-minor version of the current Python as a string, e.g. "3.7" or "3.10".
15
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_major_minor_version(): # type: () -> str return "{}.{}".format(*sys.version_info) ``` ###Assistant : Return the major-minor version of the current Pyt...
528
def test_ssd_head_loss(self): s = 300 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, }] cfg = Config( dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, ...
Tests ssd head loss when truth is empty and non-empty.
10
232
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_ssd_head_loss(self): s = 300 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, }] cfg = Config( ...
529
def _legacy_check(self) -> None: if self._min_size > 0 or self._arguments.extract_every_n != 1: logger.warning("This alignments file was generated with the legacy extraction method.") logger.warning("You should run this extraction job, but with 'min_size' set to 0 and " ...
Check whether the alignments file was created with the legacy extraction method. If so, force user to re-extract all faces if any options have been specified, otherwise raise the appropriate warnings and set the legacy options.
36
160
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _legacy_check(self) -> None: if self._min_size > 0 or self._arguments.extract_every_n != 1: logger.warning("This alignments file was generated with the legac...
530
def FisherZ(name, d1, d2): r return rv(name, FisherZDistribution, (d1, d2)) #------------------------------------------------------------------------------- # Frechet distribution ---------------------------------------------------------
Create a Continuous Random Variable with an Fisher's Z distribution. Explanation =========== The density of the Fisher's Z distribution is given by .. math:: f(x) := \frac{2d_1^{d_1/2} d_2^{d_2/2}} {\mathrm{B}(d_1/2, d_2/2)} \frac{e^{d_1z}}{\left(d_1e^{2z}+d_2\right)^{\le...
145
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def FisherZ(name, d1, d2): r return rv(name, FisherZDistribution, (d1, d2)) #------------------------------------------------------------------------------- # Frechet distribution ...
531
def find_batch_size(tensors): if isinstance(tensors, (list, tuple)): for t in tensors: result = find_batch_size(t) if result is not None: return result elif isinstance(tensors, Mapping): for key, value in tensors.items(): result = find_bat...
Find the first dimension of a tensor in a nested list/tuple/dict of tensors.
13
60
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def find_batch_size(tensors): if isinstance(tensors, (list, tuple)): for t in tensors: result = find_batch_size(t) if result is not None: ...
532
def post_process_segmentation(self, outputs, target_sizes, threshold=0.9, mask_threshold=0.5): out_logits, raw_masks = outputs.logits, outputs.pred_masks preds = []
Converts the output of [`DetrForSegmentation`] into image segmentation predictions. Only supports PyTorch. Parameters: outputs ([`DetrSegmentationOutput`]): Raw outputs of the model. target_sizes (`torch.Tensor` of shape `(batch_size, 2)` or `List[Tuple]` of len...
101
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def post_process_segmentation(self, outputs, target_sizes, threshold=0.9, mask_threshold=0.5): out_logits, raw_masks = outputs.logits, outputs.pred_masks preds = [] ...
533
def iterate_graycode(self, k): unranked_code = GrayCode.unrank(self.superset_size, (self.rank_gray + k) % self.cardinality) return Subset.subset_from_bitlist(self.superset, unranked_code)
Helper function used for prev_gray and next_gray. It performs ``k`` step overs to get the respective Gray codes. Examples ======== >>> from sympy.combinatorics import Subset >>> a = Subset([1, 2, 3], [1, 2, 3, 4]) >>> a.iterate_graycode(3).subset [1, 4]...
49
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def iterate_graycode(self, k): unranked_code = GrayCode.unrank(self.superset_size, (self.rank_gray + k) % self.cardinality) re...
534
def is_sequence_right_padded(mask): max_seq_length = tf.shape(mask)[1] count_of_true = tf.reduce_sum(tf.cast(mask, tf.int32), axis=1) right_padded_mask = tf.sequence_mask(count_of_true, maxlen=max_seq_length) return tf.reduce_all(tf.equal(mask, right_padded_mask))
Check the mask tensor and see if it right padded. For cuDNN kernel, it uses the sequence length param to skip the tailing timestep. If the data is left padded, or not a strict right padding (has masked value in the middle of the sequence), then cuDNN kernel won't be work properly in those cases. L...
135
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_sequence_right_padded(mask): max_seq_length = tf.shape(mask)[1] count_of_true = tf.reduce_sum(tf.cast(mask, tf.int32), axis=1) right_padded_mask = tf.sequence_mask(co...
535
def _send_event_over_federation(self) -> None: body = { "pdus": [ { "sender": self.user_id, "type": EventTypes.Message, "state_key": "", "content": {"body": "hello world", "msgtype": "m.text"}, ...
Send a dummy event over federation and check that the request succeeds.
12
49
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _send_event_over_federation(self) -> None: body = { "pdus": [ { "sender": self.user_id, "type": Event...
536
def _print_loss(self, loss): output = ", ".join([f"Loss {side}: {side_loss:.5f}" for side, side_loss in zip(("A", "B"), loss)]) timestamp = time.strftime("%H:%M:%S") output = f"[{timestamp}] [#{self._model.iterations:05d}] {output}" print(f"\r{output}...
Outputs the loss for the current iteration to the console. Parameters ---------- loss: list The loss for each side. List should contain 2 ``floats`` side "a" in position 0 and side "b" in position `.
35
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _print_loss(self, loss): output = ", ".join([f"Loss {side}: {side_loss:.5f}" for side, side_loss in zip(("A", "B"), loss)]) timestamp...
537
def itermonthdays2(self, year, month): for i, d in enumerate(self.itermonthdays(year, month), self.firstweekday): yield d, i % 7
Like itermonthdates(), but will yield (day number, weekday number) tuples. For days outside the specified month the day number is 0.
21
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def itermonthdays2(self, year, month): for i, d in enumerate(self.itermonthdays(year, month), self.firstweekday): yield d, i % 7 ``` ###Assistant : ...
538
def test_distance_function_return_none_if_invalid_state(hass): hass.states.async_set("test.object_2", "happy", {"latitude": 10}) tpl = template.Template("{{ distance(states.test.object_2) | round }}", hass) with pytest.raises(TemplateError): tpl.async_render()
Test distance function return None if invalid state.
8
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_distance_function_return_none_if_invalid_state(hass): hass.states.async_set("test.object_2", "happy", {"latitude": 10}) tpl = template.Template("{{ distance(states.test...
539
def Concatenate(self, parameters): return _concatenate_getitem(self, parameters) # 3.7-8 elif sys.version_info[:2] >= (3, 7):
Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a higher order function which adds, removes or transforms parameters of a callable. For example:: Callable[Concatenate[int, P], int] See PEP 612 for detailed information.
33
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def Concatenate(self, parameters): return _concatenate_getitem(self, parameters) # 3.7-8 elif sys.version_info[:2] >= (3, 7): ``` ###Assistant : Used in conjunct...
540
def compute_recall(result_neighbors, ground_truth_neighbors) -> float: assert len( result_neighbors.shape) == 2, "shape = [num_queries, neighbors_per_query]" assert len(ground_truth_neighbors.shape ) == 2, "shape = [num_queries, ground_truth_neighbors_per_query]" assert result_neighbors.shape...
Computes the recall of an approximate nearest neighbor search. Args: result_neighbors: int32 numpy array of the shape [num_queries, neighbors_per_query] where the values are the indices of the dataset. ground_truth_neighbors: int32 numpy array of with shape [num_queries, ground_truth_neighbors_pe...
49
55
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def compute_recall(result_neighbors, ground_truth_neighbors) -> float: assert len( result_neighbors.shape) == 2, "shape = [num_queries, neighbors_per_query]" assert len(ground_t...
541
def isocalendar(self) -> DataFrame: from pandas import DataFrame values = self._local_timestamps() sarray = fields.build_isocalendar_sarray(values) iso_calendar_df = DataFrame( sarray, columns=["year", "week", "day"], dtype="UInt32" ) if self._hasna:...
Returns a DataFrame with the year, week, and day calculated according to the ISO 8601 standard. .. versionadded:: 1.1.0 Returns ------- DataFrame with columns year, week and day See Also -------- Timestamp.isocalendar : Function ret...
108
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def isocalendar(self) -> DataFrame: from pandas import DataFrame values = self._local_timestamps() sarray = fields.build_isocalendar_sarray(values) ...
542
def putpixel(self, xy, value): if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) i...
Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P and PA images. Note that this method is relatively slow. For more ext...
81
71
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def putpixel(self, xy, value): if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value...
543
async def test_available_template_with_entities(hass): await setup.async_setup_component( hass, "switch", { "switch": { "platform": "template", "switches": { "test_template_switch": { **OPTIMISTIC_SW...
Test availability templates with values from other entities.
8
55
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_available_template_with_entities(hass): await setup.async_setup_component( hass, "switch", { "switch": { "platform...
544
def etfs_disc_command(sort=""): # Debug if cfg.DEBUG: logger.debug("etfs") df_etfs = wsj_model.etf_movers(sort, export=True) if df_etfs.empty: raise Exception("No available data found") df_etfs.set_index(" ", inplace=True) prfx = "Top" if sort == "active": pr...
Displays ETF's Top Gainers/Decliners, Most Active [Wall Street Journal]
9
247
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def etfs_disc_command(sort=""): # Debug if cfg.DEBUG: logger.debug("etfs") df_etfs = wsj_model.etf_movers(sort, export=True) if df_etfs.empty: raise E...
545
def get(self): logger = get_logger() logger.debug(f"ENTER::Partition.get::{self._identity}") if len(self.call_queue): self.drain_call_queue() result = ray.get(self.oid) logger.debug(f"EXIT::Partition.get::{self._identity}") return result
Get the object wrapped by this partition out of the Plasma store. Returns ------- pandas.DataFrame The object from the Plasma store.
21
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get(self): logger = get_logger() logger.debug(f"ENTER::Partition.get::{self._identity}") if len(self.call_queue): self.drain_call_queue() ...
546
def dag_bag_ext(): clear_db_runs() dag_bag = DagBag(dag_folder=DEV_NULL, include_examples=False) dag_0 = DAG("dag_0", start_date=DEFAULT_DATE, schedule_interval=None) task_a_0 = EmptyOperator(task_id="task_a_0", dag=dag_0) task_b_0 = ExternalTaskMarker( task_id="task_b_0", external_da...
Create a DagBag with DAGs looking like this. The dotted lines represent external dependencies set up using ExternalTaskMarker and ExternalTaskSensor. dag_0: task_a_0 >> task_b_0 | | dag_1: ---> task_a_1 >> task_b_1 ...
45
111
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def dag_bag_ext(): clear_db_runs() dag_bag = DagBag(dag_folder=DEV_NULL, include_examples=False) dag_0 = DAG("dag_0", start_date=DEFAULT_DATE, schedule_interval=None) ...
547
def test_constrained_layout3(): fig, axs = plt.subplots(2, 2, layout="constrained") for nn, ax in enumerate(axs.flat): pcm = example_pcolor(ax, fontsize=24) if nn == 3: pad = 0.08 else: pad = 0.02 # default fig.colorbar(pcm, ax=ax, pad=pad) @image...
Test constrained_layout for colorbars with subplots
6
34
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_constrained_layout3(): fig, axs = plt.subplots(2, 2, layout="constrained") for nn, ax in enumerate(axs.flat): pcm = example_pcolor(ax, fontsize=24) if ...
548
def indices(self) -> dict[Hashable, npt.NDArray[np.intp]]: return self.grouper.indices
Dict {group name -> group indices}.
6
7
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def indices(self) -> dict[Hashable, npt.NDArray[np.intp]]: return self.grouper.indices ``` ###Assistant : Dict {group name -> group indices}. ...
549
def get_hash(self, data, hasher=None): if hasher is None: hasher = self.hasher if hasher is None: hasher = hashlib.md5 prefix = '' else: hasher = getattr(hashlib, hasher) prefix = '%s=' % self.hasher digest = hasher(dat...
Get the hash of some data, using a particular hash algorithm, if specified. :param data: The data to be hashed. :type data: bytes :param hasher: The name of a hash implementation, supported by hashlib, or ``None``. Examples of valid values are ``'sha1'``,...
104
42
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_hash(self, data, hasher=None): if hasher is None: hasher = self.hasher if hasher is None: hasher = hashlib.md5 prefix = '...
550
def test_async_call_same_actor_multiple_times(self): actors = [Actor.remote(i, maybe_crash=False) for i in range(4)] manager = FaultTolerantActorManager(actors=actors) # 2 asynchronous call to actor 0. num_of_calls = manager.foreach_actor_async( lambda w: w.call(), ...
Test multiple asynchronous remote calls to the same actor.
9
63
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_async_call_same_actor_multiple_times(self): actors = [Actor.remote(i, maybe_crash=False) for i in range(4)] manager = FaultTolerantActorManager(actors=actor...
551
def _load(self): data = {} if not self._is_extract: if not self.have_alignments_file: return data data = super()._load() return data skip_existing = hasattr(self._args, 'skip_existing') and self._args.skip_existing skip_faces ...
Override the parent :func:`~lib.align.Alignments._load` to handle skip existing frames and faces on extract. If skip existing has been selected, existing alignments are loaded and returned to the calling script. Returns ------- dict Any alignments that have...
49
119
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _load(self): data = {} if not self._is_extract: if not self.have_alignments_file: return data data = super()._load() ...
552
def get_gtech() -> pd.DataFrame: return get_df( "https://finance.yahoo.com/screener/predefined/growth_technology_stocks" ) @log_start_end(log=logger)
Get technology stocks with revenue and earnings growth in excess of 25%. [Source: Yahoo Finance] Returns ------- pd.DataFrame Growth technology stocks
21
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_gtech() -> pd.DataFrame: return get_df( "https://finance.yahoo.com/screener/predefined/growth_technology_stocks" ) @log_start_end(log=logger) ``` #...
553
def test_bert2gpt2_summarization(self): model = EncoderDecoderModel.from_pretrained("patrickvonplaten/bert2gpt2-cnn_dailymail-fp16") model.to(torch_device) tokenizer_in = AutoTokenizer.from_pretrained("bert-base-cased") tokenizer_out = AutoTokenizer.from_pretrained("../gpt2") A...
(CNN)Sigma Alpha Epsilon is under fire for a video showing party-bound fraternity members singing a racist chant. SAE's national chapter suspended the students, but University of Oklahoma President David Boren took it a step further, saying the university's affiliation with the fraternity is permanently done. The news ...
403
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_bert2gpt2_summarization(self): model = EncoderDecoderModel.from_pretrained("patrickvonplaten/bert2gpt2-cnn_dailymail-fp16") model.to(torch_device) tokenizer...
554
def _get_builtin_permissions(opts): # noqa: D205, D212 perms = [] for action in opts.default_permissions: perms.append( ( get_permission_codename(action, opts), "Can %s %s" % (action, opts.verbose_name_raw), ) ) return perms
Return (codename, name) for all autogenerated permissions. By default, this is ('add', 'change', 'delete', 'view')
15
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_builtin_permissions(opts): # noqa: D205, D212 perms = [] for action in opts.default_permissions: perms.append( ( get_permission_cod...
555
def accumulate(self, model): self._do_sync() if self.sync_gradients: context = contextlib.nullcontext else: context = self.no_sync with context(model): yield
A context manager that will lightly wrap around and perform gradient accumulation automatically Args: model (`torch.nn.Module`): PyTorch Module that was prepared with `Accelerator.prepare`
23
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def accumulate(self, model): self._do_sync() if self.sync_gradients: context = contextlib.nullcontext else: context = self.no_sync ...
556
def get_attribute(value): attribute = Attribute() if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) attribute.append(token) if value and value[0] in ATTRIBUTE_ENDS: raise errors.HeaderParseError( "expected token but found '{}'".format(value)) t...
[CFWS] 1*attrtext [CFWS] This version of the BNF makes the CFWS explicit, and as usual we use a value terminal for the actual run of characters. The RFC equivalent of attrtext is the token characters, with the subtraction of '*', "'", and '%'. We include tab in the excluded set just as we do for toke...
56
48
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_attribute(value): attribute = Attribute() if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) attribute.append(token) if value and v...
557
def eval_to_file(modin_obj, pandas_obj, fn, extension, **fn_kwargs): with ensure_clean_dir() as dirname: unique_filename_modin = get_unique_filename( extension=extension, data_dir=dirname ) unique_filename_pandas = get_unique_filename( extension=extension, data_d...
Helper function to test `to_<extension>` methods. Args: modin_obj: Modin DataFrame or Series to test `to_<extension>` method. pandas_obj: Pandas DataFrame or Series to test `to_<extension>` method. fn: name of the method, that should be tested. extension: Extension of the test file....
40
82
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def eval_to_file(modin_obj, pandas_obj, fn, extension, **fn_kwargs): with ensure_clean_dir() as dirname: unique_filename_modin = get_unique_filename( extension=e...
558
def _is_matching_generic_foreign_key(self, field): return ( isinstance(field, GenericForeignKey) and field.ct_field == self.content_type_field_name and field.fk_field == self.object_id_field_name )
Return True if field is a GenericForeignKey whose content type and object id fields correspond to the equivalent attributes on this GenericRelation.
22
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _is_matching_generic_foreign_key(self, field): return ( isinstance(field, GenericForeignKey) and field.ct_field == self.content_type_field_name ...
559
def hashes_to_frame(self): if not self._hashes_to_frame: logger.debug("Generating hashes to frame") for frame_name, val in self._data.items(): for idx, face in enumerate(val["faces"]): self._hashes_to_frame.setdefault(face["hash"], {})[frame_n...
dict: The SHA1 hash of the face mapped to the frame(s) and face index within the frame that the hash corresponds to. The structure of the dictionary is: {**SHA1_hash** (`str`): {**filename** (`str`): **face_index** (`int`)}}. Notes ----- This method is depractated and exists p...
79
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def hashes_to_frame(self): if not self._hashes_to_frame: logger.debug("Generating hashes to frame") for frame_name, val in self._data.items(): ...
560
def _get_textdoc(self, index): assert self._opt is not None # FIXME we probably should do eliding here. See # qcommonstyle.cpp:viewItemDrawText # https://github.com/qutebrowser/qutebrowser/issues/118 text_option = QTextOption() if self._opt.features & QStyleOptio...
Create the QTextDocument of an item. Args: index: The QModelIndex of the item to draw.
15
90
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_textdoc(self, index): assert self._opt is not None # FIXME we probably should do eliding here. See # qcommonstyle.cpp:viewItemDrawText # htt...
561
def feed(self, *args): assert len(args) != 0 self.terminals = [] for fed_layer in args: if isinstance(fed_layer, str): try: fed_layer = self.layers[fed_layer] except KeyError: raise KeyError('Unknown lay...
Set the input(s) for the next operation by replacing the terminal nodes. The arguments can be either layer names or the actual layers.
23
34
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def feed(self, *args): assert len(args) != 0 self.terminals = [] for fed_layer in args: if isinstance(fed_layer, str): try: ...
562
def unpack_iterator_input(iterator): try: next_element = iterator.get_next() except tf.errors.OutOfRangeError: raise RuntimeError( "Your dataset iterator ran out of data; " "Make sure that your dataset can generate " "required number of samples." ...
Convert a dataset iterator to a tuple of tensors `x, y, sample_weights`. Args: iterator: Instance of a dataset iterator. Returns: Tuple of tensors `x, y, weights`. `y` and `weights` entry may be None.
33
101
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def unpack_iterator_input(iterator): try: next_element = iterator.get_next() except tf.errors.OutOfRangeError: raise RuntimeError( "Your dataset iter...
563
def mock_2x2x4_devices(one_device_per_chip): return mock_devices(2, 2, 4, 'TPU v4', one_device_per_chip)
Hard-coded reproduction of jax.devices() output on 2x2x4.
7
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def mock_2x2x4_devices(one_device_per_chip): return mock_devices(2, 2, 4, 'TPU v4', one_device_per_chip) ``` ###Assistant : Hard-coded reproduction of jax.devices() output...
564
def export_triton(model_path, output_path="model_repository", model_name="ludwig_model", model_version=1, **kwargs): logger.info(f"Model path: {model_path}") logger.info(f"Output path: {output_path}") logger.info(f"Model name: {model_name}") logger.info(f"Model version: {model_version}") logger...
Exports a model in torchscript format with config for Triton serving. # Inputs :param model_path: (str) filepath to pre-trained model. :param output_path: (str, default: `'model_repository'`) directory to store the triton models. :param model_name: (str, default: `'ludwig_model'`) save triton...
55
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def export_triton(model_path, output_path="model_repository", model_name="ludwig_model", model_version=1, **kwargs): logger.info(f"Model path: {model_path}") logger.info(f"Outpu...
565
def tags(self) -> Sequence[Tuple[str, str]]: tags_key_column = self._get_column_name(Columns.TAGS_KEY) tags_value_column = self._get_column_name(Columns.TAGS_VALUE) if tags_key_column in self._snuba_data and tags_value_column in self._snuba_data: keys = self._snuba_data[tag...
Tags property uses tags from snuba if loaded otherwise falls back to nodestore.
13
93
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def tags(self) -> Sequence[Tuple[str, str]]: tags_key_column = self._get_column_name(Columns.TAGS_KEY) tags_value_column = self._get_column_name(Columns.TAGS_VALUE) ...
566
def test_cable_validates_compatible_types(self): # An interface cannot be connected to a power port cable = Cable(a_terminations=[self.interface1, self.interface2], b_terminations=[self.interface3]) with self.assertRaises(ValidationError): cable.clean() # TODO: Remove t...
The clean method should have a check to ensure only compatible port types can be connected by a cable # A cable cannot connect a front port to its corresponding rear port #
33
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_cable_validates_compatible_types(self): # An interface cannot be connected to a power port cable = Cable(a_terminations=[self.interface1, self.interface2], ...
567
def save_model_to_hdf5(model, filepath, overwrite=True, include_optimizer=True): if h5py is None: raise ImportError( "`save_model()` using h5 format requires h5py. Could not " "import h5py." ) # TODO(psv) Add warning when we save models that contain non-serializabl...
Saves a model to a HDF5 file. The saved model contains: - the model's configuration (topology) - the model's weights - the model's optimizer's state (if any) Thus the saved model can be reinstantiated in the exact same state, without any of the code used for model definition or...
114
235
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def save_model_to_hdf5(model, filepath, overwrite=True, include_optimizer=True): if h5py is None: raise ImportError( "`save_model()` using h5 format requires h5...
568
def set(self, **kwargs) -> None: # nosec attributes = {} user_id = kwargs["user_id"] user = self.first(id_int=int(user_id)) if not user: raise UserNotFoundError for k, v in kwargs.items(): if k in user.__attr_searchable__: attrib...
Updates the information for the given user id. Args: user_id (str): unique id of the user in the database. email (str, optional): email of the user. Defaults to "". password (str, optional): password of the user. Defaults to "". role (int, optional): role of the ...
119
79
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set(self, **kwargs) -> None: # nosec attributes = {} user_id = kwargs["user_id"] user = self.first(id_int=int(user_id)) if not user: ...
569
def test_get_entity_and_validate_dependency_tree_of_a_single_entity_derived_metric(self): use_case_id = UseCaseKey.RELEASE_HEALTH expected_derived_metrics_entities = { SessionMRI.ALL.value: "metrics_counters", SessionMRI.ALL_USER.value: "metrics_sets", Sessio...
Tests that ensures that get_entity method works expected in the sense that: - Since it is the first function that is called by the query_builder, validation is applied there to ensure that if it is an instance of a SingleEntityDerivedMetric, then it is composed of only other SingleEntit...
64
62
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_get_entity_and_validate_dependency_tree_of_a_single_entity_derived_metric(self): use_case_id = UseCaseKey.RELEASE_HEALTH expected_derived_metrics_entities =...
570
def transform(self, X): check_is_fitted(self) X = self._validate_data(X, reset=False) X = X - self.mean_ U = ridge_regression( self.components_.T, X.T, self.ridge_alpha, solver="cholesky" ) return U
Least Squares projection of the data onto the sparse components. To avoid instability issues in case the system is under-determined, regularization can be applied (Ridge regression) via the `ridge_alpha` parameter. Note that Sparse PCA components orthogonality is not enforced as in PCA...
90
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def transform(self, X): check_is_fitted(self) X = self._validate_data(X, reset=False) X = X - self.mean_ U = ridge_regression( self.com...
571
def serialize_object(obj, extra=None): json_str = serialize('json', [obj]) print(json_str) data = json.loads(json_str)[0]['fields'] # Exclude any MPTTModel fields if issubclass(obj.__class__, MPTTModel): for field in ['level', 'lft', 'rght', 'tree_id']: data.pop(field) ...
Return a generic JSON representation of an object using Django's built-in serializer. (This is used for things like change logging, not the REST API.) Optionally include a dictionary to supplement the object data. A list of keys can be provided to exclude them from the returned dictionary. Private fields (...
56
117
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def serialize_object(obj, extra=None): json_str = serialize('json', [obj]) print(json_str) data = json.loads(json_str)[0]['fields'] # Exclude any MPTTModel fields i...
572
async def test_statistics_during_period(recorder_mock, hass, hass_ws_client, caplog): now = dt_util.utcnow() await async_setup_component(hass, "history", {}) client = await hass_ws_client() # Test the WS API works and issues a warning await client.send_json( { "id": 1, ...
Test history/statistics_during_period forwards to recorder.
5
112
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_statistics_during_period(recorder_mock, hass, hass_ws_client, caplog): now = dt_util.utcnow() await async_setup_component(hass, "history", {}) client = await ...
573
def queryset_chunks(self, qs, chunk_size=DEFAULT_CHUNK_SIZE): i = 0 while True: items = list(qs[i * chunk_size :][:chunk_size]) if not items: break yield items i += 1
Yield a queryset in chunks of at most ``chunk_size``. The chunk yielded will be a list, not a queryset. Iterating over the chunks is done in a transaction so that the order and count of items in the queryset remains stable.
41
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def queryset_chunks(self, qs, chunk_size=DEFAULT_CHUNK_SIZE): i = 0 while True: items = list(qs[i * chunk_size :][:chunk_size]) if not items:...
574
def flattened_having(self) -> List[Condition]: flattened: List[Condition] = [] boolean_conditions: List[BooleanCondition] = [] for condition in self.having: if isinstance(condition, Condition): flattened.append(condition) elif isinstance(conditio...
Return self.having as a flattened list ignoring boolean operators This is because self.having can have a mix of BooleanConditions and Conditions. And each BooleanCondition can in turn be a mix of either type.
33
45
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def flattened_having(self) -> List[Condition]: flattened: List[Condition] = [] boolean_conditions: List[BooleanCondition] = [] for condition in self.having:...
575
def _add_timedelta_arraylike(self, other): # overridden by PeriodArray if len(self) != len(other): raise ValueError("cannot add indices of unequal length") if isinstance(other, np.ndarray): # ndarray[timedelta64]; wrap in TimedeltaIndex for op from ...
Add a delta of a TimedeltaIndex Returns ------- Same type as self
12
64
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _add_timedelta_arraylike(self, other): # overridden by PeriodArray if len(self) != len(other): raise ValueError("cannot add indices of unequal lengt...
576
def _map_graph_network(inputs, outputs): # "depth" is number of layers between output Node and the Node. # Nodes are ordered from inputs -> outputs. nodes_in_decreasing_depth, layer_indices = _build_map(outputs) network_nodes = { _make_node_key(node.layer.name, node.layer._inbound_nodes.ind...
Validates a network's topology and gather its layers and nodes. Args: inputs: List of input tensors. outputs: List of outputs tensors. Returns: A tuple `(nodes, nodes_by_depth, layers, layers_by_depth)`. - nodes: list of Node instances. - nodes_by_depth: dict mapping ints (depth)...
74
488
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _map_graph_network(inputs, outputs): # "depth" is number of layers between output Node and the Node. # Nodes are ordered from inputs -> outputs. nodes_in_decreasing_dept...
577
def default_batch_format(self) -> Type: # noqa: E501 import pandas as pd import pyarrow as pa schema = self.schema() assert isinstance(schema, (type, PandasBlockSchema, pa.Schema)) if isinstance(schema, type): return list if isinstance(schema, (Pa...
Return this dataset's default batch format. The default batch format describes what batches of data look like. To learn more about batch formats, read :ref:`writing user-defined functions <transform_datasets_writing_udfs>`. Example: If your dataset represents a list of Pyt...
219
40
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def default_batch_format(self) -> Type: # noqa: E501 import pandas as pd import pyarrow as pa schema = self.schema() assert isinstance(schema, (typ...
578
def test_decision_tree_regressor_sample_weight_consistency(criterion): tree_params = dict(criterion=criterion) tree = DecisionTreeRegressor(**tree_params, random_state=42) for kind in ["zeros", "ones"]: check_sample_weights_invariance( "DecisionTreeRegressor_" + criterion, tree, kin...
Test that the impact of sample_weight is consistent.
8
159
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_decision_tree_regressor_sample_weight_consistency(criterion): tree_params = dict(criterion=criterion) tree = DecisionTreeRegressor(**tree_params, random_state=42) f...
579
def test_with_fk_to_field(self): response = self.client.get( reverse("admin:auth_user_changelist") + "?q=joe&%s=id" % TO_FIELD_VAR ) self.assertContains(response, "\n1 user\n") self.assertContains( response, '<input type="hidden" name="%s" val...
The to_field GET parameter is preserved when a search is performed. Refs #10918.
13
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_with_fk_to_field(self): response = self.client.get( reverse("admin:auth_user_changelist") + "?q=joe&%s=id" % TO_FIELD_VAR ) self.assertC...
580
def remove_module_load(state_dict): new_state_dict = OrderedDict() for k, v in state_dict.items(): new_state_dict[k[7:]] = v return new_state_dict
create new OrderedDict that does not contain `module.`
8
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def remove_module_load(state_dict): new_state_dict = OrderedDict() for k, v in state_dict.items(): new_state_dict[k[7:]] = v return new_state_dict ``` ###Assist...
581
def serving(self, inputs): output = self.call(inputs) return self.serving_output(output) LAYOUTLMV3_START_DOCSTRING = r LAYOUTLMV3_INPUTS_DOCSTRING = r @add_start_docstrings( "The bare LayoutLMv3 Model transformer outputting raw hidden-states without any specific head on top.", LA...
Method used for serving the model. Args: inputs (`Dict[str, tf.Tensor]`): The input of the saved model as a dictionary of tensors. This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the library impleme...
689
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def serving(self, inputs): output = self.call(inputs) return self.serving_output(output) LAYOUTLMV3_START_DOCSTRING = r LAYOUTLMV3_INPUTS_DOCSTRING = r @add_st...
582
def media_image_url(self): if self._table.active_track: return self._table.active_track.get_thumbnail_url(Track.ThumbnailSize.LARGE) return super().media_image_url
Return the URL for a thumbnail image of the current track.
11
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def media_image_url(self): if self._table.active_track: return self._table.active_track.get_thumbnail_url(Track.ThumbnailSize.LARGE) return super().med...
583
def test_fluctuating_ongoing_requests(delay_s): config = AutoscalingConfig( min_replicas=1, max_replicas=10, target_num_ongoing_requests_per_replica=50, upscale_delay_s=delay_s, downscale_delay_s=delay_s) policy = BasicAutoscalingPolicy(config) if delay_s > 0:...
Simulates a workload that switches between too many and too few ongoing requests.
13
107
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_fluctuating_ongoing_requests(delay_s): config = AutoscalingConfig( min_replicas=1, max_replicas=10, target_num_ongoing_requests_per_replica=50, ...
584
def librosa_pad_lr(x, fsize, fshift, pad_sides=1): assert pad_sides in (1, 2) # return int(fsize // 2) pad = (x.shape[0] // fshift + 1) * fshift - x.shape[0] if pad_sides == 1: return 0, pad else: return pad // 2, pad // 2 + pad % 2 # Conversions
compute right padding (final frame) or both sides padding (first and final frames)
13
47
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def librosa_pad_lr(x, fsize, fshift, pad_sides=1): assert pad_sides in (1, 2) # return int(fsize // 2) pad = (x.shape[0] // fshift + 1) * fshift - x.shape[0] if pad_side...
585
def setup_tpu(tpu_driver_version='tpu_driver-0.2'): global TPU_DRIVER_MODE if not TPU_DRIVER_MODE: colab_tpu_addr = os.environ['COLAB_TPU_ADDR'].split(':')[0] url = f'http://{colab_tpu_addr}:8475/requestversion/{tpu_driver_version}' requests.post(url) TPU_DRIVER_MODE = 1 # The following is re...
Sets up Colab to run on TPU. Note: make sure the Colab Runtime is set to Accelerator: TPU. Args ---- tpu_driver_version : (str) specify the version identifier for the tpu driver. Defaults to "tpu_driver-0.2", which can be used with jaxlib 0.3.20. Set to "tpu_driver_nightly" to use the nightly tpu driv...
51
37
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def setup_tpu(tpu_driver_version='tpu_driver-0.2'): global TPU_DRIVER_MODE if not TPU_DRIVER_MODE: colab_tpu_addr = os.environ['COLAB_TPU_ADDR'].split(':')[0] url = f'http://...
586
def test_timeout_lock(self): lock = self.get_success(self.store.try_acquire_lock("name", "key")) assert lock is not None self.get_success(lock.__aenter__()) # We simulate the process getting stuck by cancelling the looping call # that keeps the lock active. lo...
Test that we time out locks if they're not updated for ages
12
49
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_timeout_lock(self): lock = self.get_success(self.store.try_acquire_lock("name", "key")) assert lock is not None self.get_success(lock.__aenter__()...
587
def random_brightness(x, brightness_range, scale=True): if len(brightness_range) != 2: raise ValueError( "`brightness_range should be tuple or list of two floats. " "Received: %s" % (brightness_range,) ) u = np.random.uniform(brightness_range[0], brightness_range[1]...
Performs a random brightness shift. Deprecated: `tf.keras.preprocessing.image.random_brightness` does not operate on tensors and is not recommended for new code. Prefer `tf.keras.layers.RandomBrightness` which provides equivalent functionality as a preprocessing layer. For more information, see the tut...
90
33
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def random_brightness(x, brightness_range, scale=True): if len(brightness_range) != 2: raise ValueError( "`brightness_range should be tuple or list of two floats...
588
def test_check_loop_sync(caplog): hasync.check_loop() assert "Detected blocking call inside the event loop" not in caplog.text
Test check_loop does nothing when called from thread.
8
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_check_loop_sync(caplog): hasync.check_loop() assert "Detected blocking call inside the event loop" not in caplog.text ``` ###Assistant : Test check_loop d...
589
def update(self) -> bool: try: # Add or remove DeploymentReplica instances in self._replicas. # This should be the only place we adjust total number of replicas # we manage. running_replicas_changed = self._scale_deployment_replicas() # Chec...
Attempts to reconcile this deployment to match its goal state. This is an asynchronous call; it's expected to be called repeatedly. Also updates the internal DeploymentStatusInfo based on the current state of the system. Returns true if this deployment was successfully deleted. ...
42
70
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def update(self) -> bool: try: # Add or remove DeploymentReplica instances in self._replicas. # This should be the only place we adjust total number ...
590
def test_https_malformed_host(self): req = self._get_request(method="POST") req._is_secure_override = True req.META["HTTP_HOST"] = "@malformed" req.META["HTTP_REFERER"] = "https://www.evil.org/somepage" req.META["SERVER_PORT"] = "443" mw = CsrfViewMiddleware(toke...
CsrfViewMiddleware generates a 403 response if it receives an HTTPS request with a bad host.
15
48
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_https_malformed_host(self): req = self._get_request(method="POST") req._is_secure_override = True req.META["HTTP_HOST"] = "@malformed" req.M...
591
def stream_slices(self, **kwargs) -> Iterable[Optional[Mapping[str, Any]]]: # TODO: self.authenticator should optionally pull from self._session.auth customers_stream = Customers(authenticator=self._session.auth) for customer in customers_stream.read_records(sync_mode=SyncMode.full_refr...
This stream is sliced per `customer_id`. This has two implications: (1) State can be checkpointed after processing each slice (2) The other parameters (e.g. request_params, path) can be dependent on this slice. This allows us to pull data on a per customer_id basis, since that's what O...
48
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def stream_slices(self, **kwargs) -> Iterable[Optional[Mapping[str, Any]]]: # TODO: self.authenticator should optionally pull from self._session.auth customers_strea...
592
def ragged_assert_compatible_and_get_flat_values(values, mask=None): if isinstance(values, list): is_all_ragged = all(isinstance(rt, tf.RaggedTensor) for rt in values) is_any_ragged = any(isinstance(rt, tf.RaggedTensor) for rt in values) else: is_all_ragged = isinstance(values, tf.R...
If ragged, it checks the compatibility and then returns the flat_values. Note: If two tensors are dense, it does not check their compatibility. Note: Although two ragged tensors with different ragged ranks could have identical overall rank and dimension sizes and hence be compatible, ...
116
193
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def ragged_assert_compatible_and_get_flat_values(values, mask=None): if isinstance(values, list): is_all_ragged = all(isinstance(rt, tf.RaggedTensor) for rt in values) ...
593
def update_sandbox_args(self): if self.is_sandbox: host, port = HubIO.deploy_public_sandbox(self.args) self._sandbox_deployed = True self.first_pod_args.host = host self.first_pod_args.port = port if self.head_args: self.pod_ar...
Update args of all its pods based on the host and port returned by Hubble
15
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def update_sandbox_args(self): if self.is_sandbox: host, port = HubIO.deploy_public_sandbox(self.args) self._sandbox_deployed = True self...
594
def download_all(): for name in DATA_HUB: download(name) DATA_HUB['kaggle_house_train'] = ( DATA_URL + 'kaggle_house_pred_train.csv', '585e9cc93e70b39160e7921475f9bcd7d31219ce') DATA_HUB['kaggle_house_test'] = ( DATA_URL + 'kaggle_house_pred_test.csv', 'fa19780a7b011d9b009e8bff8e99922...
Download all files in the DATA_HUB. Defined in :numref:`sec_kaggle_house`
9
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def download_all(): for name in DATA_HUB: download(name) DATA_HUB['kaggle_house_train'] = ( DATA_URL + 'kaggle_house_pred_train.csv', '585e9cc93e70b39160e7921475f9b...
595
def generate_matches(self, nodes): r = {} if nodes and self.match(nodes[0], r): yield 1, r
Generator yielding all matches for this pattern. Default implementation for non-wildcard patterns.
12
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def generate_matches(self, nodes): r = {} if nodes and self.match(nodes[0], r): yield 1, r ``` ###Assistant : Generator yielding a...
596
def user_can_delete_obj(self, user, obj): perm_codename = self.get_perm_codename("delete") return self.user_has_specific_permission(user, perm_codename)
Return a boolean to indicate whether `user` is permitted to 'delete' a specific `self.model` instance.
15
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def user_can_delete_obj(self, user, obj): perm_codename = self.get_perm_codename("delete") return self.user_has_specific_permission(user, perm_codename) ```...
597
def _busy_indicator_trace(self, *args) -> None: logger.trace("Busy indicator trace: %s", args) # type: ignore if self._busy_tkvar.get(): self._start_busy_indicator() else: self._stop_busy_indicator()
Show or hide busy indicator based on whether the preview is updating. Parameters ---------- args: unused Required for tkinter event, but unused
22
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _busy_indicator_trace(self, *args) -> None: logger.trace("Busy indicator trace: %s", args) # type: ignore if self._busy_tkvar.get(): self._start_bus...
598
def _gen_html_string(self): self.html_string = _hilite_me( self.code_string, self.language, self.style, self.insert_line_no, "border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;", self.file_path, self....
Function to generate html string with code highlighted and stores in variable html_string.
13
41
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _gen_html_string(self): self.html_string = _hilite_me( self.code_string, self.language, self.style, self.insert_line_no, ...
599
def __getstate__(self): state = self.__dict__.copy() # remove the unpickleable RLock object state.pop("_cookies_lock") return state
Unlike a normal CookieJar, this class is pickleable.
8
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def __getstate__(self): state = self.__dict__.copy() # remove the unpickleable RLock object state.pop("_cookies_lock") return state ``` ...