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,200
def replaceHTMLEntity(t): return _htmlEntityMap.get(t.entity) # it's easy to get these comment structures wrong - they're very common, so may as well make them available cStyleComment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + '*/').setName("C style comment") "Comment of the form ``/* ... */``" htmlComment =...
Helper parser action to replace common HTML entities with their special characters(Deprecated) Predefined expression of 1 or more printable words or quoted strings, separated by commas. This expression is deprecated in favor of :class:`pyparsing_common.comma_separated_list`.
34
141
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def replaceHTMLEntity(t): return _htmlEntityMap.get(t.entity) # it's easy to get these comment structures wrong - they're very common, so may as well make them available cStyleComm...
1,201
def read_csv_with_nan(path, nan_percent=0.0): df = pd.read_csv(path) if nan_percent > 0: num_rows = len(df) for col in df.columns: for row in random.sample(range(num_rows), int(round(nan_percent * num_rows))): df[col].iloc[row] = np.nan return df
Converts `nan_percent` of samples in each row of the CSV at `path` to NaNs.
14
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def read_csv_with_nan(path, nan_percent=0.0): df = pd.read_csv(path) if nan_percent > 0: num_rows = len(df) for col in df.columns: for row in random....
1,202
def _upsample_2d(self, x, w=None, k=None, factor=2, gain=1): assert isinstance(factor, int) and factor >= 1 # Setup filter kernel. if k is None: k = [1] * factor # setup kernel k = np.asarray(k, dtype=np.float32) if k.ndim == 1: k = np....
Fused `upsample_2d()` followed by `Conv2d()`. Args: Padding is performed only once at the beginning, not between the operations. The fused op is considerably more efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of arbitrary: order. ...
139
219
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _upsample_2d(self, x, w=None, k=None, factor=2, gain=1): assert isinstance(factor, int) and factor >= 1 # Setup filter kernel. if k is None: ...
1,203
def get_network_names(self) -> t.Optional[t.List[str]]: if self.networks is None: return None return sorted(self.networks)
Return a list of the network names the container is attached to.
12
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_network_names(self) -> t.Optional[t.List[str]]: if self.networks is None: return None return sorted(self.networks) ``` ###Assistant...
1,204
def get_delivered_items_cost(): dn_items = frappe.db.sql( , as_dict=1, ) si_items = frappe.db.sql( , as_dict=1, ) dn_item_map = {} for item in dn_items: dn_item_map.setdefault(item.project, item.amount) for item in si_items: dn_item_map.setdefault(item.project, item.amount) return dn_item_map
select dn.project, sum(dn_item.base_net_amount) as amount from `tabDelivery Note` dn, `tabDelivery Note Item` dn_item where dn.name = dn_item.parent and dn.docstatus = 1 and ifnull(dn.project, '') != '' group by dn.projectselect si.project, sum(si_item.base_net_amount) as amount from `tabSales Invoice` si, `tab...
65
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_delivered_items_cost(): dn_items = frappe.db.sql( , as_dict=1, ) si_items = frappe.db.sql( , as_dict=1, ) dn_item_map = {} for item in dn_items: dn_item_map.setdefa...
1,205
def __new__(cls, *args, **kw_args): is_canon_bp = kw_args.get('is_canon_bp', False) args = list(map(_sympify, args)) free = [get_free_indices(arg) for arg in args] free = set(itertools.chain(*free)) #flatten free newargs = [] for arg in args: dum_thi...
If the internal dummy indices in one arg conflict with the free indices of the remaining args, we need to rename those internal dummy indices.
25
186
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def __new__(cls, *args, **kw_args): is_canon_bp = kw_args.get('is_canon_bp', False) args = list(map(_sympify, args)) free = [get_free_indices(arg) for arg i...
1,206
def test_context_for_crash_rate_alert(self): status = TriggerStatus.ACTIVE incident = self.create_incident() alert_rule = self.create_alert_rule( aggregate="percentage(sessions_crashed, sessions) AS _crash_rate_alert_aggregate" ) alert_rule_trigger = self.cre...
Test that ensures the metric name for Crash rate alerts excludes the alias
13
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_context_for_crash_rate_alert(self): status = TriggerStatus.ACTIVE incident = self.create_incident() alert_rule = self.create_alert_rule( ...
1,207
def get_template(self, template_name, skip=None): tried = [] for origin in self.get_template_sources(template_name): if skip is not None and origin in skip: tried.append((origin, "Skipped to avoid recursion")) continue try: ...
Call self.get_template_sources() and return a Template object for the first template matching template_name. If skip is provided, ignore template origins in skip. This is used to avoid recursion during template extending.
31
49
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_template(self, template_name, skip=None): tried = [] for origin in self.get_template_sources(template_name): if skip is not None and origin in s...
1,208
def from_config(cls, config): if "learning_rate" in config: if isinstance(config["learning_rate"], dict): config["learning_rate"] = learning_rate_schedule.deserialize( config["learning_rate"] ) return cls(**config) base_optimizer...
Creates an optimizer from its config. This method is the reverse of `get_config`, capable of instantiating the same optimizer from the config dictionary. Args: config: A Python dictionary, typically the output of get_config. Returns: An optimizer instance. ...
306
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def from_config(cls, config): if "learning_rate" in config: if isinstance(config["learning_rate"], dict): config["learning_rate"] = learning_rate...
1,209
def close(self): # When application exit, system shuts down all handlers by # calling close method. Here we check if logger is already # closed to prevent uploading the log to remote storage multiple # times when `logging.shutdown` is called. if self.closed: ...
Close and upload local log file to remote storage S3.
10
92
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def close(self): # When application exit, system shuts down all handlers by # calling close method. Here we check if logger is already # closed to prevent up...
1,210
def safestring_in_template_exception(request): template = Template('{% extends "<script>alert(1);</script>" %}') try: template.render(Context()) except Exception: return technical_500_response(request, *sys.exc_info())
Trigger an exception in the template machinery which causes a SafeString to be inserted as args[0] of the Exception.
19
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def safestring_in_template_exception(request): template = Template('{% extends "<script>alert(1);</script>" %}') try: template.render(Context()) except Exception: ...
1,211
async def test_unique_id_in_progress(hass, manager): mock_integration(hass, MockModule("comp")) mock_entity_platform(hass, "config_flow.comp", None)
Test that we abort if there is already a flow in progress with same unique id.
16
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_unique_id_in_progress(hass, manager): mock_integration(hass, MockModule("comp")) mock_entity_platform(hass, "config_flow.comp", None) ``` ###Assistan...
1,212
def test_simple(self) -> None: event_factory = self.hs.get_event_builder_factory() bob = "@creator:test" alice = "@alice:test" room_id = "!room:test" # Ensure that we have a rooms entry so that we generate the chain index. self.get_success( self.sto...
Test that the example in `docs/auth_chain_difference_algorithm.md` works.
7
338
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_simple(self) -> None: event_factory = self.hs.get_event_builder_factory() bob = "@creator:test" alice = "@alice:test" room_id = "!room:test...
1,213
async def _do_retry(self, func, attempts=3) -> Any: # pylint: disable=no-self-use exception = None for attempt in range(1, attempts + 1): _LOGGER.debug("Attempt %s of %s", attempt, attempts) try: return await func() except Exception as...
Retry a function call. Withings' API occasionally and incorrectly throws errors. Retrying the call tends to work.
17
69
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def _do_retry(self, func, attempts=3) -> Any: # pylint: disable=no-self-use exception = None for attempt in range(1, attempts + 1): _LOGGER...
1,214
def refactor_doctest(self, block, lineno, indent, filename): try: tree = self.parse_block(block, lineno, indent) except Exception as err: if self.logger.isEnabledFor(logging.DEBUG): for line in block: self.log_debug("Source: %s", line....
Refactors one doctest. A doctest is given as a block of lines, the first of which starts with ">>>" (possibly indented), while the remaining lines start with "..." (identically indented).
30
97
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def refactor_doctest(self, block, lineno, indent, filename): try: tree = self.parse_block(block, lineno, indent) except Exception as err: if ...
1,215
def get_tables(self, dataset_id) -> Response: client = self.connect() result = client.list_tables(dataset_id) return result
Get a list with all of the tabels in BigQuery
10
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_tables(self, dataset_id) -> Response: client = self.connect() result = client.list_tables(dataset_id) return result ``` ###Assistant : ...
1,216
def mac_set_relative_dylib_deps(libname, distname): from macholib import util from macholib.MachO import MachO # Ignore bootloader; otherwise PyInstaller fails with exception like # 'ValueError: total_size > low_offset (288 > 0)' if os.path.basename(libname) in _BOOTLOADER_FNAMES: ret...
On Mac OS set relative paths to dynamic library dependencies of `libname`. Relative paths allow to avoid using environment variable DYLD_LIBRARY_PATH. There are known some issues with DYLD_LIBRARY_PATH. Relative paths is more flexible mechanism. Current location of dependent libraries is derived from...
120
76
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def mac_set_relative_dylib_deps(libname, distname): from macholib import util from macholib.MachO import MachO # Ignore bootloader; otherwise PyInstaller fails with except...
1,217
def get_v2_optimizer(name, **kwargs): try: return _V2_OPTIMIZER_MAP[name](**kwargs) except KeyError: raise ValueError( "Could not find requested v2 optimizer: {}\nValid choices: {}".format( name, list(_V2_OPTIMIZER_MAP.keys()) ) )
Get the v2 optimizer requested. This is only necessary until v2 are the default, as we are testing in Eager, and Eager + v1 optimizers fail tests. When we are in v2, the strings alone should be sufficient, and this mapping can theoretically be removed. Args: name: string name of Keras v2 optimiz...
75
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_v2_optimizer(name, **kwargs): try: return _V2_OPTIMIZER_MAP[name](**kwargs) except KeyError: raise ValueError( "Could not find requested v2 o...
1,218
def _prefix_from_ip_int(cls, ip_int): trailing_zeroes = _count_righthand_zero_bits(ip_int, cls._max_prefixlen) prefixlen = cls._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = (1 << prefixle...
Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones
32
52
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _prefix_from_ip_int(cls, ip_int): trailing_zeroes = _count_righthand_zero_bits(ip_int, cls._max_prefixlen) p...
1,219
def batch_has_learnable_example(self, examples): for eg in examples: for ent in eg.predicted.ents: candidates = list(self.get_candidates(self.kb, ent)) if candidates: return True return False
Check if a batch contains a learnable example. If one isn't present, then the update step needs to be skipped.
20
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def batch_has_learnable_example(self, examples): for eg in examples: for ent in eg.predicted.ents: candidates = list(self.get_candidates(self.kb...
1,220
def get_delayed_update_fields(self): self.extra_update_fields['emitted_events'] = self.event_ct if 'got an unexpected keyword argument' in self.extra_update_fields.get('result_traceback', ''): self.delay_update(result_traceback=ANSIBLE_RUNNER_NEEDS_UPDATE_MESSAGE) return sel...
Return finalized dict of all fields that should be saved along with the job status change
16
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_delayed_update_fields(self): self.extra_update_fields['emitted_events'] = self.event_ct if 'got an unexpected keyword argument' in self.extra_update_fields.g...
1,221
def get_checks_result(warning_id=None): checks_result = checks.run_checks() if warning_id: return [ warning for warning in checks_result if warning.id == warning_id] return checks_result
Run Django checks on any with the 'search' tag used when registering the check
14
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_checks_result(warning_id=None): checks_result = checks.run_checks() if warning_id: return [ warning for warning in ...
1,222
def use_bottleneck_cb(key) -> None: from pandas.core import nanops nanops.set_use_bottleneck(cf.get_option(key)) use_numexpr_doc =
: bool Use the numexpr library to accelerate computation if it is installed, the default is True Valid values: False,True
20
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def use_bottleneck_cb(key) -> None: from pandas.core import nanops nanops.set_use_bottleneck(cf.get_option(key)) use_numexpr_doc = ``` ###Assistant : : bool Us...
1,223
def test_repeated_column_labels(self, datapath): # GH 13923, 25772 msg = with pytest.raises(ValueError, match=msg): read_stata( datapath("io", "data", "stata", "stata15.dta"), convert_categoricals=True, )
Value labels for column ethnicsn are not unique. These cannot be converted to pandas categoricals. Either read the file with `convert_categoricals` set to False or use the low level interface in `StataReader` to separately read the values and the value_labels. The repeated labels are:\n-+\nwolof
44
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_repeated_column_labels(self, datapath): # GH 13923, 25772 msg = with pytest.raises(ValueError, match=msg): read_stata( datapath(...
1,224
def string_width_in_pixels(cls, font, string): # if no windows have been created (there is no hidden master root to rely on) then temporarily make a window so the measurement can happen if Window.NumOpenWindows == 0: root = tk.Tk() else: root = None siz...
Get the with of the supplied string in pixels for the font being passed in. If an error occurs, 0 will be returned :param font: specifies the font family, size, etc. Tuple or Single string format 'name size styles'. Styles: italic * roman bold normal underline overstrike, to be measured ...
76
70
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def string_width_in_pixels(cls, font, string): # if no windows have been created (there is no hidden master root to rely on) then temporarily make a window so the measureme...
1,225
def model_call_inputs(model, keep_original_batch_size=False): input_specs = model.save_spec(dynamic_batch=not keep_original_batch_size) if input_specs is None: return None, None input_specs = _enforce_names_consistency(input_specs) return input_specs
Inspect model to get its input signature. The model's input signature is a list with a single (possibly-nested) object. This is due to the Keras-enforced restriction that tensor inputs must be passed in as the first argument. For example, a model with input {'feature1': <Tensor>, 'feature2': <Tensor>}...
119
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def model_call_inputs(model, keep_original_batch_size=False): input_specs = model.save_spec(dynamic_batch=not keep_original_batch_size) if input_specs is None: return No...
1,226
def _getSubDirectoryFolders(self, module, sub_dirs): module_dir = module.getCompileTimeDirectory() file_list = [] data_dirs = [os.path.join(module_dir, subdir) for subdir in sub_dirs] # Gather the full file list, probably makes no sense to include bytecode files file_...
Get dirnames in given subdirs of the module. Notes: All dirnames in folders below one of the sub_dirs are recursively retrieved and returned shortened to begin with the string of subdir. Args: module: module object sub_dirs: sub folder name(s) - tuple ...
46
139
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _getSubDirectoryFolders(self, module, sub_dirs): module_dir = module.getCompileTimeDirectory() file_list = [] data_dirs = [os.path.join(module_dir, sub...
1,227
def test_orderby_percentile_with_many_fields_one_entity_no_data(self): for metric in [ TransactionMRI.MEASUREMENTS_FCP.value, "transaction", ]: perf_indexer_record(self.organization.id, metric) response = self.get_success_response( self.or...
Test that ensures that when metrics data is available then an empty response is returned gracefully
16
33
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_orderby_percentile_with_many_fields_one_entity_no_data(self): for metric in [ TransactionMRI.MEASUREMENTS_FCP.value, "transaction", ...
1,228
def _add_save_button(self) -> None: logger.debug("Adding save button") button = tk.Button(self, text="Save", cursor="hand2", command=lambda: self.save_var.set(True)) button.pack(side=tk.LEFT) logger...
Add a save button for saving out original preview
9
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _add_save_button(self) -> None: logger.debug("Adding save button") button = tk.Button(self, text="Save", cu...
1,229
def temporary_environ_defaults(**kwargs): old_env = os.environ.copy() try: for var in kwargs: # TODO: Consider warning on conflicts os.environ.setdefault(var, str(kwargs[var])) yield {var: os.environ[var] for var in kwargs} finally: for var in kwargs: ...
Temporarily override default values in os.environ. Yields a dictionary of the key/value pairs matching the provided keys.
17
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def temporary_environ_defaults(**kwargs): old_env = os.environ.copy() try: for var in kwargs: # TODO: Consider warning on conflicts os.environ.s...
1,230
def test_same_entity_multiple_metric_ids_missing_data(self, mocked_derived_metrics): mocked_derived_metrics.return_value = MOCKED_DERIVED_METRICS_2 _indexer_record(self.organization.id, "metric_foo_doe") self.store_session( self.build_session( project_id=self...
Test when not requested metrics have data in the dataset
10
53
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_same_entity_multiple_metric_ids_missing_data(self, mocked_derived_metrics): mocked_derived_metrics.return_value = MOCKED_DERIVED_METRICS_2 _indexer_record(s...
1,231
def _align_matrices(x, y): x_matrix = _to_matrix(x) y_matrix = _to_matrix(y) x_shape = x_matrix.shape y_shape = y_matrix.shape if y_shape[1] != x_shape[1]: # dimensions do not match. raise ValueError( "The outermost dimensions of the input tensors should match. " ...
Aligns x and y tensors to allow computations over pairs of their rows.
13
62
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _align_matrices(x, y): x_matrix = _to_matrix(x) y_matrix = _to_matrix(y) x_shape = x_matrix.shape y_shape = y_matrix.shape if y_shape[1] != x_shape[1]: # dimens...
1,232
def test_prune_gap_if_dummy_local(self): body = self.helper.send(self.room_id, body="Test", tok=self.token) body = self.helper.send_event( self.room_id, type=EventTypes.Dummy, content={}, tok=self.token ) local_message_event_id = body["event_id"] self.asser...
Test that we don't drop extremities after a gap when the previous extremity is a local dummy event and points to local events.
23
131
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_prune_gap_if_dummy_local(self): body = self.helper.send(self.room_id, body="Test", tok=self.token) body = self.helper.send_event( self.room_id...
1,233
def _reset_layer_losses(parent_layer): losses_dict = {} for layer in utils.list_all_layers_and_sublayers(parent_layer): losses_dict[layer] = { 'losses': layer._losses[:], 'eager_losses': layer._eager_losses[:] } with utils.no_automatic_dependency_tracking_scope(layer): layer._lo...
Resets losses of layer and its sublayers, and returns original losses.
11
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _reset_layer_losses(parent_layer): losses_dict = {} for layer in utils.list_all_layers_and_sublayers(parent_layer): losses_dict[layer] = { 'losses': layer._losses[:], ...
1,234
def test_result_list_editable_html(self): new_parent = Parent.objects.create(name="parent") new_child = Child.objects.create(name="name", parent=new_parent) request = self.factory.get("/child/") request.user = self.superuser m = ChildAdmin(Child, custom_site) # ...
Regression tests for #11791: Inclusion tag result_list generates a table and this checks that the items are nested within the table element tags. Also a regression test for #13599, verifies that hidden fields when list_editable is enabled are rendered in a div outside the ...
45
139
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_result_list_editable_html(self): new_parent = Parent.objects.create(name="parent") new_child = Child.objects.create(name="name", parent=new_parent) ...
1,235
def test_title_column(self): root_page = Page.objects.filter(depth=2).first() blog = Site.objects.create( hostname="blog.example.com", site_name="My blog", root_page=root_page ) gallery = Site.objects.create( hostname="gallery.example.com", site_name="My gallery",...
<table class="listing"> <thead> <tr><th>Hostname</th><th>Site name</th></tr> </thead> <tbody> <tr> <td class="title"> <div class="title-wrapper"> ...
37
51
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_title_column(self): root_page = Page.objects.filter(depth=2).first() blog = Site.objects.create( hostname="blog.example.com", site_name="My blog", root_p...
1,236
def _clean_text(self, text): output = [] for char in text: cp = ord(char) if cp == 0 or cp == 0xFFFD or _is_control(char): continue if _is_whitespace(char): output.append(" ") else: output.append(cha...
Performs invalid character removal and whitespace cleanup on text.
9
32
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _clean_text(self, text): output = [] for char in text: cp = ord(char) if cp == 0 or cp == 0xFFFD or _is_control(char): co...
1,237
def call_candle(self, other_args): if self.symbol: parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="candle", description=, ) ns_parser = pa...
Process candle commandDisplay chart for loaded coin. You can specify currency vs which you want to show chart and also number of days to get data for.
27
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def call_candle(self, other_args): if self.symbol: parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.Arg...
1,238
async def test_load_values_when_added_to_hass(hass): config = { "binary_sensor": { "name": "Test_Binary", "platform": "bayesian", "unique_id": "3b4c9563-5e84-4167-8fe7-8f507e796d72", "device_class": "connectivity", "observations": [ ...
Test that sensor initializes with observations of relevant entities.
9
72
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_load_values_when_added_to_hass(hass): config = { "binary_sensor": { "name": "Test_Binary", "platform": "bayesian", "uniqu...
1,239
def test_copy_with_target_credential(self): expression = "col1, col2" op = DatabricksCopyIntoOperator( file_location=COPY_FILE_LOCATION, file_format='CSV', table_name='test', task_id=TASK_ID, expression_list=expression, storage_cred...
COPY INTO test WITH (CREDENTIAL abc) FROM (SELECT {expression} FROM '{COPY_FILE_LOCATION}' WITH (CREDENTIAL (AZURE_SAS_TOKEN = 'abc') )) FILEFORMAT = CSV
20
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_copy_with_target_credential(self): expression = "col1, col2" op = DatabricksCopyIntoOperator( file_location=COPY_FILE_LOCATION, file_format='...
1,240
def show_actual_vendor_versions(vendor_txt_versions): # type: (Dict[str, str]) -> None for module_name, expected_version in vendor_txt_versions.items(): extra_message = '' actual_version = get_vendor_version_from_module(module_name) if not actual_version: extra_message =...
Log the actual version and print extra info if there is a conflict or if the actual version could not be imported.
22
58
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def show_actual_vendor_versions(vendor_txt_versions): # type: (Dict[str, str]) -> None for module_name, expected_version in vendor_txt_versions.items(): extra_message = ...
1,241
def escape_rfc3986(s): if sys.version_info < (3, 0) and isinstance(s, compat_str): s = s.encode('utf-8') # ensure unicode: after quoting, it can always be converted return compat_str(compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]"))
Escape non-ASCII characters as suggested by RFC 3986
8
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def escape_rfc3986(s): if sys.version_info < (3, 0) and isinstance(s, compat_str): s = s.encode('utf-8') # ensure unicode: after quoting, it can always be converted ...
1,242
def call_social(self, other_args): parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="social", description=, ) ns_parser = parse_known_args_and_warn( parser, other_ar...
Process social commandShows social media corresponding to loaded coin. You can find there name of telegram channel, urls to twitter, reddit, bitcointalk, facebook and discord.
25
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def call_social(self, other_args): parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, ...
1,243
def test_ignores_different_group(self): url = reverse( "sentry-api-0-project-event-details", kwargs={ "event_id": self.next_transaction_event.event_id, "project_slug": self.next_transaction_event.project.slug, "organization_slug": ...
Test that a different group's events aren't attributed to the one that was passed
14
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_ignores_different_group(self): url = reverse( "sentry-api-0-project-event-details", kwargs={ "event_id": self.next_transacti...
1,244
def _dedupe_indices(new, exclude, index_structure): inds_self = set(exclude) dums_new = set(get_dummy_indices(new)) conflicts = dums_new.intersection(inds_self) if len(conflicts) == 0: return None inds_self.update(dums_new) self_args_free =...
exclude: set new: TensExpr index_structure: _IndexStructure (required to generate new dummy indices) If ``new`` has any dummy indices that are in ``exclude``, return a version of new with those indices replaced. If no replacements are needed, return None ...
63
67
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _dedupe_indices(new, exclude, index_structure): inds_self = set(exclude) dums_new = set(get_dummy_indices(new)) conflicts = dums_new.intersection(inds_s...
1,245
def get_window_extent(self, renderer=None): # make sure the location is updated so that transforms etc are correct: self._adjust_location() bb = super().get_window_extent(renderer=renderer) if self.axis is None or not self.axis.get_visible(): return bb bboxes...
Return the window extent of the spines in display space, including padding for ticks (but not their labels) See Also -------- matplotlib.axes.Axes.get_tightbbox matplotlib.axes.Axes.get_window_extent
23
174
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_window_extent(self, renderer=None): # make sure the location is updated so that transforms etc are correct: self._adjust_location() bb = super().get_...
1,246
def apply_support(self, location, type): if location not in self._node_labels: raise ValueError("Support must be added on a known node") else: self._supports[location] = type if type == "pinned": self._loads['R_'+str(location)+'_x']= [] ...
This method adds a pinned or roller support at a particular node Parameters ========== location: String or Symbol Label of the Node at which support is added. type: String Type of the support being provided at the node. Examples ======...
66
41
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def apply_support(self, location, type): if location not in self._node_labels: raise ValueError("Support must be added on a known node") else: ...
1,247
def timers(self) -> list[dict[str, Any]]: return [ { "enabled": timer.enabled, "cron": timer.cron, "next_schedule": as_utc(timer.next_schedule), } for timer in self.coordinator.data.timers ]
Get the list of added timers of the vacuum cleaner.
10
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def timers(self) -> list[dict[str, Any]]: return [ { "enabled": timer.enabled, "cron": timer.cron, "next_schedule...
1,248
def plot_avg_pitch(pitch, chars, fig_size=(30, 10), output_fig=False): old_fig_size = plt.rcParams["figure.figsize"] if fig_size is not None: plt.rcParams["figure.figsize"] = fig_size fig, ax = plt.subplots() x = np.array(range(len(chars))) my_xticks = [c for c in chars] plt.xtick...
Plot pitch curves on top of the input characters. Args: pitch (np.array): Pitch values. chars (str): Characters to place to the x-axis. Shapes: pitch: :math:`(T,)`
25
51
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def plot_avg_pitch(pitch, chars, fig_size=(30, 10), output_fig=False): old_fig_size = plt.rcParams["figure.figsize"] if fig_size is not None: plt.rcParams["figure.figsiz...
1,249
def composite(nth): n = as_int(nth) if n < 1: raise ValueError("nth must be a positive integer; composite(1) == 4") composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18] if n <= 10: return composite_arr[n - 1] a, b = 4, sieve._list[-1] if n <= b - primepi(b) - 1: whi...
Return the nth composite number, with the composite numbers indexed as composite(1) = 4, composite(2) = 6, etc.... Examples ======== >>> from sympy import composite >>> composite(36) 52 >>> composite(1) 4 >>> composite(17737) 20000 ...
87
170
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def composite(nth): n = as_int(nth) if n < 1: raise ValueError("nth must be a positive integer; composite(1) == 4") composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, ...
1,250
def histogram2d(x, y, bins=10, range=None, density=None, weights=None): from numpy import histogramdd if len(x) != len(y): raise ValueError('x and y must have the same length.') try: N = len(bins) except TypeError: N = 1 if N != 1 and N != 2: xedges = yedges =...
Compute the bi-dimensional histogram of two data samples. Parameters ---------- x : array_like, shape (N,) An array containing the x coordinates of the points to be histogrammed. y : array_like, shape (N,) An array containing the y coordinates of the points to be hi...
747
64
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def histogram2d(x, y, bins=10, range=None, density=None, weights=None): from numpy import histogramdd if len(x) != len(y): raise ValueError('x and y must have the same ...
1,251
def available(self) -> bool: return self._device is not None and self._device.profile_device.available
Device is available when we have a connection to it.
10
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def available(self) -> bool: return self._device is not None and self._device.profile_device.available ``` ###Assistant : Device is available when we have a con...
1,252
def _get_input_from_iterator(iterator, model): next_element = iterator.get_next() # `len(nest.flatten(x))` is going to not count empty elements such as {}. # len(nest.flatten([[0,1,2], {}])) is 3 and not 4. The `next_element` is # going to get flattened in `_prepare_feed_values` to work around t...
Get elements from the iterator and verify the input shape and type.
12
115
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_input_from_iterator(iterator, model): next_element = iterator.get_next() # `len(nest.flatten(x))` is going to not count empty elements such as {}. # len(nest.flatt...
1,253
def inner(a, b): return (a, b) @array_function_from_c_func_and_dispatcher(_multiarray_umath.where)
inner(a, b, /) Inner product of two arrays. Ordinary inner product of vectors for 1-D arrays (without complex conjugation), in higher dimensions a sum product over the last axes. Parameters ---------- a, b : array_like If `a` and `b` are nonscalar, their last dimensions must matc...
260
7
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def inner(a, b): return (a, b) @array_function_from_c_func_and_dispatcher(_multiarray_umath.where) ``` ###Assistant : inner(a, b, /) Inner product of two arr...
1,254
def contains(self, mouseevent): inside, info = self._default_contains(mouseevent) if inside is not None: return inside, info if not self.get_visible(): return False, {} pickradius = ( float(self._picker) if isinstance(self._picke...
Test whether the mouse event occurred in the collection. Returns ``bool, dict(ind=itemlist)``, where every item in itemlist contains the event.
20
135
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def contains(self, mouseevent): inside, info = self._default_contains(mouseevent) if inside is not None: return inside, info if not self.get_vis...
1,255
def deployments(self) -> List[Dict]: return [ { 'name': self.name, 'head_host': self.head_host, 'head_port_in': self.head_port_in, } ]
Get deployments of the deployment. The BaseDeployment just gives one deployment. :return: list of deployments
15
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def deployments(self) -> List[Dict]: return [ { 'name': self.name, 'head_host': self.head_host, 'head_port_in': s...
1,256
def parse_content_disposition(reply): is_inline = True filename = None content_disposition_header = b'Content-Disposition' # First check if the Content-Disposition header has a filename # attribute. if reply.hasRawHeader(content_disposition_header): # We use the unsafe variant of th...
Parse a content_disposition header. Args: reply: The QNetworkReply to get a filename for. Return: A (is_inline, filename) tuple.
18
100
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def parse_content_disposition(reply): is_inline = True filename = None content_disposition_header = b'Content-Disposition' # First check if the Content-Disposition heade...
1,257
def _get_categorical_mapping(self, scale, data): levels = categorical_order(data, scale.order) n = len(levels) values = scale.values if isinstance(values, dict): self._check_dict_entries(levels, values) # TODO where to ensure that dict values have consis...
Define mapping as lookup in list of discrete color values.
10
124
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_categorical_mapping(self, scale, data): levels = categorical_order(data, scale.order) n = len(levels) values = scale.values if isinstance(v...
1,258
def minorlocator(self, loc): self._long_axis().set_minor_locator(loc) self._minorlocator = loc
Set minor locator being used for colorbar
7
7
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def minorlocator(self, loc): self._long_axis().set_minor_locator(loc) self._minorlocator = loc ``` ###Assistant : Set minor locator being used ...
1,259
def test_process_datetime_to_timestamp_freeze_time(time_zone, hass): hass.config.set_time_zone(time_zone) utc_now = dt_util.utcnow() with freeze_time(utc_now): epoch = utc_now.timestamp() assert process_datetime_to_timestamp(dt_util.utcnow()) == epoch now = dt_util.now() ...
Test we can handle processing database datatimes to timestamps. This test freezes time to make sure everything matches.
18
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_process_datetime_to_timestamp_freeze_time(time_zone, hass): hass.config.set_time_zone(time_zone) utc_now = dt_util.utcnow() with freeze_time(utc_now): epoch...
1,260
def _spatially_filter(self) -> np.ndarray: logger.debug("Spatially Filter") assert self._shapes_model is not None landmarks_norm = self._normalized["landmarks"] # Convert to matrix form landmarks_norm_table = np.reshape(landmarks_norm, [68 * 2, landmarks_norm.shape[2]])....
interpret the shapes using our shape model (project and reconstruct) Returns ------- :class:`numpy.ndarray` The filtered landmarks in original coordinate space
20
68
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _spatially_filter(self) -> np.ndarray: logger.debug("Spatially Filter") assert self._shapes_model is not None landmarks_norm = self._normalized["landmark...
1,261
def letter_form(self): return tuple(flatten([(i,)*j if j > 0 else (-i,)*(-j) for i, j in self.array_form]))
The letter representation of a ``FreeGroupElement`` is a tuple of generator symbols, with each entry corresponding to a group generator. Inverses of the generators are represented by negative generator symbols. Examples ======== >>> from sympy.combinatorics imp...
76
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def letter_form(self): return tuple(flatten([(i,)*j if j > 0 else (-i,)*(-j) for i, j in self.array_form])) ``` ###Assistant : The ...
1,262
def _handle_default_message(self, type, data): logger.debug(f"Received message from Leader of type {type}: {data}")
Default leader message handler, just logs it. We should never have to run this unless the leader sends us some weird message.
22
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _handle_default_message(self, type, data): logger.debug(f"Received message from Leader of type {type}: {data}") ``` ###Assistant : Default leader m...
1,263
def export_probs(self) -> dict[str, Any]: result = {} for module in self.nas_modules: try: result.update(module.export_probs(memo=result)) except NotImplementedError: warnings.warn( 'Some super-modules you have used did...
Export the probability of every choice in the search space got chosen. .. note:: If such method of some modules is not implemented, they will be simply ignored. Returns ------- dict In most cases, keys are names of ``nas_modules`` suffixed with ``/`` and choice nam...
55
37
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def export_probs(self) -> dict[str, Any]: result = {} for module in self.nas_modules: try: result.update(module.export_probs(memo=result)...
1,264
def debounce_update_release_health_data(organization, project_ids): # Figure out which projects need to get updates from the snuba. should_update = {} cache_keys = ["debounce-health:%d" % id for id in project_ids] cache_data = cache.get_many(cache_keys) for project_id, cache_key in zip(project_...
This causes a flush of snuba health data to the postgres tables once per minute for the given projects.
19
265
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def debounce_update_release_health_data(organization, project_ids): # Figure out which projects need to get updates from the snuba. should_update = {} cache_keys = ["debounc...
1,265
def show_code(co, *, file=None): print(code_info(co), file=file) _Instruction = collections.namedtuple("_Instruction", "opname opcode arg argval argrepr offset starts_line is_jump_target") _Instruction.opname.__doc__ = "Human readable name for operation" _Instruction.opcode.__doc__ = "Numeric code for o...
Print details of methods, functions, or code to *file*. If *file* is not provided, the output is printed on stdout.
20
96
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def show_code(co, *, file=None): print(code_info(co), file=file) _Instruction = collections.namedtuple("_Instruction", "opname opcode arg argval argrepr offset starts_line is_...
1,266
def set_cmap(cmap): cmap = colormaps[cmap] rc('image', cmap=cmap.name) im = gci() if im is not None: im.set_cmap(cmap) @_copy_docstring_and_deprecators(matplotlib.image.imread)
Set the default colormap, and applies it to the current image if any. Parameters ---------- cmap : `~matplotlib.colors.Colormap` or str A colormap instance or the name of a registered colormap. See Also -------- colormaps matplotlib.cm.register_cmap matplotlib.cm.get_cmap ...
36
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_cmap(cmap): cmap = colormaps[cmap] rc('image', cmap=cmap.name) im = gci() if im is not None: im.set_cmap(cmap) @_copy_docstring_and_deprecators(matpl...
1,267
def completion_item_focus(self, which, history=False): if history: if (self._cmd.text() == ':' or self._cmd.history.is_browsing() or not self._active): if which == 'next': self._cmd.command_history_next() return ...
Shift the focus of the completion menu to another item. Args: which: 'next', 'prev', 'next-category', 'prev-category', 'next-page', or 'prev-page'. history: Navigate through command history if no text was typed.
29
114
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def completion_item_focus(self, which, history=False): if history: if (self._cmd.text() == ':' or self._cmd.history.is_browsing() or not self...
1,268
def _background_extract(self, output_folder, progress_queue): _io = dict(saver=ImagesSaver(get_folder(output_folder), as_bytes=True), loader=ImagesLoader(self._input_location, count=self._alignments.frames_count)) for frame_idx, (filename, image) in enumerate(_io["loader"].l...
Perform the background extraction in a thread so GUI doesn't become unresponsive. Parameters ---------- output_folder: str The location to save the output faces to progress_queue: :class:`queue.Queue` The queue to place incremental counts to for updating the GUI...
39
65
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _background_extract(self, output_folder, progress_queue): _io = dict(saver=ImagesSaver(get_folder(output_folder), as_bytes=True), loader=ImagesLoader(...
1,269
def test_multi_part_language(self, m): m.return_value = ["chi_sim", "eng"] msgs = check_default_language_available(None) self.assertEqual(len(msgs), 0)
GIVEN: - An OCR language which is multi part (ie chi-sim) - The language is correctly formatted WHEN: - Installed packages are checked THEN: - No errors are reported
29
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_multi_part_language(self, m): m.return_value = ["chi_sim", "eng"] msgs = check_default_language_available(None) self.assertEqual(len(msgs), 0) ...
1,270
def finished_callback(self, runner_obj): event_data = { 'event': 'EOF', 'final_counter': self.event_ct, 'guid': self.guid, } event_data.setdefault(self.event_data_key, self.instance.id) self.dispatcher.dispatch(event_data)
Ansible runner callback triggered on finished run
7
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def finished_callback(self, runner_obj): event_data = { 'event': 'EOF', 'final_counter': self.event_ct, 'guid': self.guid, } ...
1,271
def test_anonymize_gql_operation_response_with_fragment_spread(gql_operation_factory): query = result = {"data": "result"} sensitive_fields = {"Product": {"name"}} operation_result = gql_operation_factory(query, result=result) anonymize_gql_operation_response(operation_result, sensitive_fields) ...
fragment ProductFragment on Product { id name } query products($first: Int){ products(channel: "channel-pln", first:$first){ edges{ node{ ... ProductFragment variants { variantName: name } } } } ...
27
33
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_anonymize_gql_operation_response_with_fragment_spread(gql_operation_factory): query = result = {"data": "result"} sensitive_fields = {"Product": {"name"}} operation...
1,272
def complete_bipartite_graph(n1, n2, create_using=None): G = nx.empty_graph(0, create_using) if G.is_directed(): raise nx.NetworkXError("Directed Graph not supported") n1, top = n1 n2, bottom = n2 if isinstance(n1, numbers.Integral) and isinstance(n2, numbers.Integral): bottom ...
Returns the complete bipartite graph `K_{n_1,n_2}`. The graph is composed of two partitions with nodes 0 to (n1 - 1) in the first and nodes n1 to (n1 + n2 - 1) in the second. Each node in the first is connected to each node in the second. Parameters ---------- n1, n2 : integer or iterable cont...
166
74
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def complete_bipartite_graph(n1, n2, create_using=None): G = nx.empty_graph(0, create_using) if G.is_directed(): raise nx.NetworkXError("Directed Graph not supported") ...
1,273
def shutdown(self, callback=None): if self._state == _UNWRAPPED: raise RuntimeError('no security layer present') if self._state == _SHUTDOWN: raise RuntimeError('shutdown in progress') assert self._state in (_WRAPPED, _DO_HANDSHAKE) self._state = _SHUTDOW...
Start the SSL shutdown sequence. Return a list of ssldata. A ssldata element is a list of buffers The optional *callback* argument can be used to install a callback that will be called when the shutdown is complete. The callback will be called without arguments.
45
45
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def shutdown(self, callback=None): if self._state == _UNWRAPPED: raise RuntimeError('no security layer present') if self._state == _SHUTDOWN: ...
1,274
def preferred_ip(vm_, ips): proto = config.get_cloud_config_value( "protocol", vm_, __opts__, default="ipv4", search_global=False ) family = socket.AF_INET if proto == "ipv6": family = socket.AF_INET6 for ip in ips: ignore_ip = ignore_cidr(vm_, ip) if ignore_ip:...
Return either an 'ipv4' (default) or 'ipv6' address depending on 'protocol' option. The list of 'ipv4' IPs is filtered by ignore_cidr() to remove any unreachable private addresses.
27
46
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def preferred_ip(vm_, ips): proto = config.get_cloud_config_value( "protocol", vm_, __opts__, default="ipv4", search_global=False ) family = socket.AF_INET if p...
1,275
def get_parent_account(doctype, txt, searchfield, start, page_len, filters): return frappe.db.sql( % ("%s", searchfield, "%s", "%s", "%s"), (filters["company"], "%%%s%%" % txt, page_len, start), as_list=1, )
select name from tabAccount where is_group = 1 and docstatus != 2 and company = %s and %s like %s order by name limit %s offset %s
27
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_parent_account(doctype, txt, searchfield, start, page_len, filters): return frappe.db.sql( % ("%s", searchfield, "%s", "%s", "%s"), (filters["company"], "%%%s%%" % txt, page_...
1,276
def exact_laplacian_kernel(x, y, stddev): r x_aligned, y_aligned = _align_matrices(x, y) diff_l1_norm = tf.reduce_sum(tf.abs(tf.subtract(x_aligned, y_aligned)), 2) return tf.exp(-diff_l1_norm / stddev)
Computes exact Laplacian kernel value(s) for tensors x and y using stddev. The Laplacian kernel for vectors u, v is defined as follows: K(u, v) = exp(-||u-v|| / stddev) where the norm is the l1-norm. x, y can be either vectors or matrices. If they are vectors, they must have the same dimension. If...
195
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def exact_laplacian_kernel(x, y, stddev): r x_aligned, y_aligned = _align_matrices(x, y) diff_l1_norm = tf.reduce_sum(tf.abs(tf.subtract(x_aligned, y_aligned)), 2) return tf....
1,277
def transform(self, X): check_is_fitted(self) if self.n_neighbors is not None: distances, indices = self.nbrs_.kneighbors(X, return_distance=True) else: distances, indices = self.nbrs_.radius_neighbors(X, return_distance=True) # Create the graph of short...
Transform X. This is implemented by linking the points X into the graph of geodesic distances of the training data. First the `n_neighbors` nearest neighbors of X are found in the training data, and from these the shortest geodesic distances from each point in X to each point in ...
118
93
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) if self.n_neighbors is not None: distances, indices = self.nbrs_.kneighbors(X, return_distance=True) ...
1,278
def generate_config_style_dict(self) -> dict[str, str]: keys_converting_dict = { "fill": ("color", "fill_color"), "fill-opacity": ("opacity", "fill_opacity"), "stroke": ("color", "stroke_color"), "stroke-opacity": ("opacity", "stroke_opacity"), ...
Generate a dictionary holding the default style information.
8
48
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def generate_config_style_dict(self) -> dict[str, str]: keys_converting_dict = { "fill": ("color", "fill_color"), "fill-opacity": ("opacity", "fill_o...
1,279
def get_variables(self): # type: () -> t.Dict[str, t.Union[str, t.List[str]]] return dict( bootstrap_type=self.bootstrap_type, controller='yes' if self.controller else '', python_versions=self.python_versions, ssh_key_type=self.ssh_key.KEY_TYPE, ...
The variables to template in the bootstrapping script.
8
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_variables(self): # type: () -> t.Dict[str, t.Union[str, t.List[str]]] return dict( bootstrap_type=self.bootstrap_type, controller='yes' if s...
1,280
def _create_pseudo_member_(cls, value): pseudo_member = cls._value2member_map_.get(value, None) if pseudo_member is None: # verify all bits are accounted for _, extra_flags = _decompose(cls, value) if extra_flags: raise ValueError("%r is not a...
Create a composite member iff value contains only members.
9
71
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _create_pseudo_member_(cls, value): pseudo_member = cls._value2member_map_.get(value, None) if pseudo_member is None: # verify all bits are accounted...
1,281
def _identify_infrequent(self, category_count, n_samples, col_idx): if isinstance(self.min_frequency, numbers.Integral): infrequent_mask = category_count < self.min_frequency elif isinstance(self.min_frequency, numbers.Real): min_frequency_abs = n_samples * self.min_freq...
Compute the infrequent indices. Parameters ---------- category_count : ndarray of shape (n_cardinality,) Category counts. n_samples : int Number of samples. col_idx : int Index of the current category. Only used for the error message. ...
55
78
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _identify_infrequent(self, category_count, n_samples, col_idx): if isinstance(self.min_frequency, numbers.Integral): infrequent_mask = category_count < self....
1,282
def get_conn(self) -> container_v1.ClusterManagerClient: if self._client is None: credentials = self._get_credentials() self._client = container_v1.ClusterManagerClient(credentials=credentials, client_info=CLIENT_INFO) return self._client # To preserve backward comp...
Returns ClusterManagerCLinet object. :rtype: google.cloud.container_v1.ClusterManagerClient
5
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_conn(self) -> container_v1.ClusterManagerClient: if self._client is None: credentials = self._get_credentials() self._client = container_v1.C...
1,283
def iscoroutinefunction(func): return (inspect.iscoroutinefunction(func) or getattr(func, '_is_coroutine', None) is _is_coroutine) # Prioritize native coroutine check to speed-up # asyncio.iscoroutine. _COROUTINE_TYPES = (types.CoroutineType, types.GeneratorType, collections.a...
Return True if func is a decorated coroutine function.
9
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def iscoroutinefunction(func): return (inspect.iscoroutinefunction(func) or getattr(func, '_is_coroutine', None) is _is_coroutine) # Prioritize native coroutine check ...
1,284
async def async_load(self) -> _T | None: if self._load_task is None: self._load_task = self.hass.async_create_task(self._async_load()) return await self._load_task
Load data. If the expected version and minor version do not match the given versions, the migrate function will be invoked with migrate_func(version, minor_version, config). Will ensure that when a call comes in while another one is in progress, the second call will wait and return the...
52
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def async_load(self) -> _T | None: if self._load_task is None: self._load_task = self.hass.async_create_task(self._async_load()) return await self...
1,285
def extra_state_attributes(self) -> dict[str, Any] | None: data = super().extra_state_attributes or {} last_user = self.vera_device.get_last_user_alert() if last_user is not None: data[ATTR_LAST_USER_NAME] = last_user[1] data[ATTR_LOW_BATTERY] = self.vera_device.ge...
Who unlocked the lock and did a low battery alert fire. Reports on the previous poll cycle. changed_by_name is a string like 'Bob'. low_battery is 1 if an alert fired, 0 otherwise.
32
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def extra_state_attributes(self) -> dict[str, Any] | None: data = super().extra_state_attributes or {} last_user = self.vera_device.get_last_user_alert() if...
1,286
def magic(self, arg_s): warnings.warn( "`magic(...)` is deprecated since IPython 0.13 (warning added in " "8.1), use run_line_magic(magic_name, parameter_s).", DeprecationWarning, stacklevel=2, ) # TODO: should we issue a loud deprecation ...
DEPRECATED Deprecated since IPython 0.13 (warning added in 8.1), use run_line_magic(magic_name, parameter_s). Call a magic function by name. Input: a string containing the name of the magic function to call and any additional arguments to be passed to the magic. ...
92
51
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def magic(self, arg_s): warnings.warn( "`magic(...)` is deprecated since IPython 0.13 (warning added in " "8.1), use run_line_magic(magic_name, param...
1,287
def create_command(name, **kwargs): # type: (str, **Any) -> Command module_path, class_name, summary = commands_dict[name] module = importlib.import_module(module_path) command_class = getattr(module, class_name) command = command_class(name=name, summary=summary, **kwargs) return command ...
Create an instance of the Command class with the given name.
11
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def create_command(name, **kwargs): # type: (str, **Any) -> Command module_path, class_name, summary = commands_dict[name] module = importlib.import_module(module_path) ...
1,288
def to_pandas_refs(self) -> List[ObjectRef["pandas.DataFrame"]]: block_to_df = cached_remote_fn(_block_to_df) return [block_to_df.remote(block) for block in self._blocks.get_blocks()]
Convert this dataset into a distributed set of Pandas dataframes. This is only supported for datasets convertible to Arrow records. This function induces a copy of the data. For zero-copy access to the underlying data, consider using ``.to_arrow()`` or ``.get_internal_block_refs()``. ...
57
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def to_pandas_refs(self) -> List[ObjectRef["pandas.DataFrame"]]: block_to_df = cached_remote_fn(_block_to_df) return [block_to_df.remote(block) for block in self._b...
1,289
def hsplit(ary, indices_or_sections): if _nx.ndim(ary) == 0: raise ValueError('hsplit only works on arrays of 1 or more dimensions') if ary.ndim > 1: return split(ary, indices_or_sections, 1) else: return split(ary, indices_or_sections, 0) @array_function_dispatch(_hvdsplit_di...
Split an array into multiple sub-arrays horizontally (column-wise). Please refer to the `split` documentation. `hsplit` is equivalent to `split` with ``axis=1``, the array is always split along the second axis except for 1-D arrays, where it is split at ``axis=0``. See Also -------- spli...
203
32
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def hsplit(ary, indices_or_sections): if _nx.ndim(ary) == 0: raise ValueError('hsplit only works on arrays of 1 or more dimensions') if ary.ndim > 1: return spli...
1,290
def get_points_earned(self): def get_returned_amount(): returned_amount = frappe.db.sql( , self.name, ) return abs(flt(returned_amount[0][0])) if returned_amount else 0 lp_details = get_loyalty_program_details_with_points( self.customer, company=self.company, loyalty_program=self.loyalty_program, ...
select sum(grand_total) from `tabSales Invoice` where docstatus=1 and is_return=1 and ifnull(return_against, '')=%s
12
59
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_points_earned(self): def get_returned_amount(): returned_amount = frappe.db.sql( , self.name, ) return abs(flt(returned_amount[0][0])) if returned_amount else 0 lp_det...
1,291
def _get_kernel(self) -> plaidml.tile.Value: coords = np.arange(self._filter_size, dtype="float32") coords -= (self._filter_size - 1) / 2. kernel = np.square(coords) kernel *= -0.5 / np.square(self._filter_sigma) kernel = np.reshape(kernel, (1, -1)) + np.reshape(kernel,...
Obtain the base kernel for performing depthwise convolution. Returns ------- :class:`plaidml.tile.Value` The gaussian kernel based on selected size and sigma
20
49
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_kernel(self) -> plaidml.tile.Value: coords = np.arange(self._filter_size, dtype="float32") coords -= (self._filter_size - 1) / 2. kernel = np.squar...
1,292
def test_default_default(self): block = blocks.ListBlock(blocks.CharBlock(default='chocolate')) self.assertEqual(list(block.get_default()), ['chocolate']) block.set_name('test_shoppinglistblock') js_args = ListBlockAdapter().js_args(block) self.assertEqual(js_args[2], ...
if no explicit 'default' is set on the ListBlock, it should fall back on a single instance of the child block in its default state.
25
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_default_default(self): block = blocks.ListBlock(blocks.CharBlock(default='chocolate')) self.assertEqual(list(block.get_default()), ['chocolate']) ...
1,293
def convert_empty_str_key(self) -> None: if self.namespaces and "" in self.namespaces.keys(): self.namespaces[None] = self.namespaces.pop("", "default")
Replace zero-length string in `namespaces`. This method will replace '' with None to align to `lxml` requirement that empty string prefixes are not allowed.
24
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def convert_empty_str_key(self) -> None: if self.namespaces and "" in self.namespaces.keys(): self.namespaces[None] = self.namespaces.pop("", "default") ...
1,294
def test_get_with_custom_key_using_default_key(self): # Generate signature signature = generate_signature(self.image.id, "fill-800x600") # Get the image response = self.client.get( reverse( "wagtailimages_serve_custom_key", args=(sign...
Test that that the key can be changed on the view This tests that the default key no longer works when the key is changed on the view
28
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_get_with_custom_key_using_default_key(self): # Generate signature signature = generate_signature(self.image.id, "fill-800x600") # Get the image ...
1,295
async def test_timeouts_do_not_hide_crashes(self, flow_run, orion_client): started = anyio.Event()
Since timeouts capture anyio cancellations, we want to ensure that something still ends up in a 'Crashed' state if it is cancelled independently from our timeout cancellation.
27
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_timeouts_do_not_hide_crashes(self, flow_run, orion_client): started = anyio.Event() ``` ###Assistant : Since timeouts capture anyio canc...
1,296
def test_enable_disable_conflict_with_config(): nlp = English() nlp.add_pipe("tagger") nlp.add_pipe("senter") nlp.add_pipe("sentencizer") with make_tempdir() as tmp_dir: nlp.to_disk(tmp_dir) # Expected to fail, as config and arguments conflict. with pytest.raises(ValueE...
Test conflict between enable/disable w.r.t. `nlp.disabled` set in the config.
10
72
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_enable_disable_conflict_with_config(): nlp = English() nlp.add_pipe("tagger") nlp.add_pipe("senter") nlp.add_pipe("sentencizer") with make_tempdir() as tmp...
1,297
async def test_logs_streaming(job_manager): stream_logs_script = stream_logs_cmd = f'python -c "{stream_logs_script}"' job_id = await job_manager.submit_job(entrypoint=stream_logs_cmd) await async_wait_for_condition( lambda: "STREAMED" in job_manager.get_job_logs(job_id) ) job_...
Test that logs are streamed during the job, not just at the end. import time print('STREAMED') while True: time.sleep(1)
19
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_logs_streaming(job_manager): stream_logs_script = stream_logs_cmd = f'python -c "{stream_logs_script}"' job_id = await job_manager.submit_job(entrypoint=s...
1,298
def _train_no_recompute(n_steps): img_dim, n_channels, batch_size = 256, 1, 4 x, y = _get_dummy_data(img_dim, n_channels, batch_size) model = _get_big_cnn_model( img_dim, n_channels, num_partitions=3, blocks_per_partition=2 ) optimizer = optimizers.SGD() losses = [] tr_vars = mo...
Trains a single large model without gradient checkpointing.
8
60
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _train_no_recompute(n_steps): img_dim, n_channels, batch_size = 256, 1, 4 x, y = _get_dummy_data(img_dim, n_channels, batch_size) model = _get_big_cnn_model( img...
1,299
def _make_replica_execution_function(model, mode): if mode == ModeKeys.TRAIN: func = model.train_on_batch elif mode == ModeKeys.TEST: func = model.test_on_batch else:
A single step of the distributed execution on a replica.
10
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _make_replica_execution_function(model, mode): if mode == ModeKeys.TRAIN: func = model.train_on_batch elif mode == ModeKeys.TEST: func = model.test_on_batch ...