code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def exists(self, using=None, **kwargs): """ Returns ``True`` if the index already exists in elasticsearch. Any additional keyword arguments will be passed to ``Elasticsearch.indices.exists`` unchanged. """ return self._get_connection(using).indices.exists(index=self._nam...
Returns ``True`` if the index already exists in elasticsearch. Any additional keyword arguments will be passed to ``Elasticsearch.indices.exists`` unchanged.
Below is the the instruction that describes the task: ### Input: Returns ``True`` if the index already exists in elasticsearch. Any additional keyword arguments will be passed to ``Elasticsearch.indices.exists`` unchanged. ### Response: def exists(self, using=None, **kwargs): """ R...
def select_columns(self, column_names): """ Selects all columns where the name of the column or the type of column is included in the column_names. An exception is raised if duplicate columns are selected i.e. sf.select_columns(['a','a']), or non-existent columns are selected. ...
Selects all columns where the name of the column or the type of column is included in the column_names. An exception is raised if duplicate columns are selected i.e. sf.select_columns(['a','a']), or non-existent columns are selected. Throws an exception for all other input types. ...
Below is the the instruction that describes the task: ### Input: Selects all columns where the name of the column or the type of column is included in the column_names. An exception is raised if duplicate columns are selected i.e. sf.select_columns(['a','a']), or non-existent columns are sel...
def eta_bar(msg, max_value): """Display an adaptive ETA / countdown bar with a message. Parameters ---------- msg: str Message to prefix countdown bar line with max_value: max_value The max number of progress bar steps/updates """ widgets = [ "{msg}:".format(msg=ms...
Display an adaptive ETA / countdown bar with a message. Parameters ---------- msg: str Message to prefix countdown bar line with max_value: max_value The max number of progress bar steps/updates
Below is the the instruction that describes the task: ### Input: Display an adaptive ETA / countdown bar with a message. Parameters ---------- msg: str Message to prefix countdown bar line with max_value: max_value The max number of progress bar steps/updates ### Response: def eta...
def StatEntryFromStat(stat, pathspec, ext_attrs = True): """Build a stat entry object from a given stat object. Args: stat: A `Stat` object. pathspec: A `PathSpec` from which `stat` was obtained. ext_attrs: Whether to include extended file attributes in the r...
Build a stat entry object from a given stat object. Args: stat: A `Stat` object. pathspec: A `PathSpec` from which `stat` was obtained. ext_attrs: Whether to include extended file attributes in the result. Returns: `StatEntry` object.
Below is the the instruction that describes the task: ### Input: Build a stat entry object from a given stat object. Args: stat: A `Stat` object. pathspec: A `PathSpec` from which `stat` was obtained. ext_attrs: Whether to include extended file attributes in the result. Returns: `StatEntry` ob...
def getRootIntfPort(port: LPort): """ :return: most top port which contains this port """ while True: if isinstance(port.parent, LNode): return port else: port = port.parent
:return: most top port which contains this port
Below is the the instruction that describes the task: ### Input: :return: most top port which contains this port ### Response: def getRootIntfPort(port: LPort): """ :return: most top port which contains this port """ while True: if isinstance(port.parent, LNode): return port ...
def update(self, path, node): '''Update the dict with a new color using a 'path' through the dict. You can either pass an existing path e.g. 'Scaffold.mutations' to override a color or part of the hierarchy or you can add a new leaf node or dict.''' assert(type(path) == type(self.name)) ...
Update the dict with a new color using a 'path' through the dict. You can either pass an existing path e.g. 'Scaffold.mutations' to override a color or part of the hierarchy or you can add a new leaf node or dict.
Below is the the instruction that describes the task: ### Input: Update the dict with a new color using a 'path' through the dict. You can either pass an existing path e.g. 'Scaffold.mutations' to override a color or part of the hierarchy or you can add a new leaf node or dict. ### Response: def update(...
def write_secret(path, **kwargs): ''' Set secret at the path in vault. The vault policy used must allow this. CLI Example: .. code-block:: bash salt '*' vault.write_secret "secret/my/secret" user="foo" password="bar" ''' log.debug('Writing vault secrets for %s at %s', __grains__['...
Set secret at the path in vault. The vault policy used must allow this. CLI Example: .. code-block:: bash salt '*' vault.write_secret "secret/my/secret" user="foo" password="bar"
Below is the the instruction that describes the task: ### Input: Set secret at the path in vault. The vault policy used must allow this. CLI Example: .. code-block:: bash salt '*' vault.write_secret "secret/my/secret" user="foo" password="bar" ### Response: def write_secret(path, **kwargs): ...
def take(self, indexer, axis=1, verify=True, convert=True): """ Take items along any axis. """ self._consolidate_inplace() indexer = (np.arange(indexer.start, indexer.stop, indexer.step, dtype='int64') if isinstance(indexer, slice) ...
Take items along any axis.
Below is the the instruction that describes the task: ### Input: Take items along any axis. ### Response: def take(self, indexer, axis=1, verify=True, convert=True): """ Take items along any axis. """ self._consolidate_inplace() indexer = (np.arange(indexer.start, indexer.st...
def provisions(ctx, provision, clear_existing, overwrite, list_provisions): """Install default provisioning data""" install_provisions(ctx, provision, clear_existing, overwrite, list_provisions)
Install default provisioning data
Below is the the instruction that describes the task: ### Input: Install default provisioning data ### Response: def provisions(ctx, provision, clear_existing, overwrite, list_provisions): """Install default provisioning data""" install_provisions(ctx, provision, clear_existing, overwrite, list_provisions...
def modelshift_weaksec(koi): """ Max secondary depth based on model-shift secondary test from Jeff Coughlin secondary metric: mod_depth_sec_dv * (1 + 3*mod_fred_dv / mod_sig_sec_dv) """ num = KOIDATA.ix[ku.koiname(koi), 'koi_tce_plnt_num'] if np.isnan(num): num = 1 kid = KOIDATA.ix[...
Max secondary depth based on model-shift secondary test from Jeff Coughlin secondary metric: mod_depth_sec_dv * (1 + 3*mod_fred_dv / mod_sig_sec_dv)
Below is the the instruction that describes the task: ### Input: Max secondary depth based on model-shift secondary test from Jeff Coughlin secondary metric: mod_depth_sec_dv * (1 + 3*mod_fred_dv / mod_sig_sec_dv) ### Response: def modelshift_weaksec(koi): """ Max secondary depth based on model-shift ...
def request( self, method_name: str, *args: Any, trim_log_values: bool = False, validate_against_schema: bool = True, id_generator: Optional[Iterator] = None, **kwargs: Any ) -> Response: """ Send a request by passing the method and arguments. ...
Send a request by passing the method and arguments. >>> client.request("cat", name="Yoko") <Response[1] Args: method_name: The remote procedure's method name. args: Positional arguments passed to the remote procedure. kwargs: Keyword arguments passed to the ...
Below is the the instruction that describes the task: ### Input: Send a request by passing the method and arguments. >>> client.request("cat", name="Yoko") <Response[1] Args: method_name: The remote procedure's method name. args: Positional arguments passed to the r...
def percentile_ranks(self, affinities, allele=None, alleles=None, throw=True): """ Return percentile ranks for the given ic50 affinities and alleles. The 'allele' and 'alleles' argument are as in the `predict` method. Specify one of these. Parameters ---------- ...
Return percentile ranks for the given ic50 affinities and alleles. The 'allele' and 'alleles' argument are as in the `predict` method. Specify one of these. Parameters ---------- affinities : sequence of float nM affinities allele : string alleles : ...
Below is the the instruction that describes the task: ### Input: Return percentile ranks for the given ic50 affinities and alleles. The 'allele' and 'alleles' argument are as in the `predict` method. Specify one of these. Parameters ---------- affinities : sequence of float...
def on_core_metadata_event(self, event): """Implementation of the core metadata-carrying Event proto callback. Args: event: An Event proto that contains core metadata about the debugged Session::Run() in its log_message.message field, as a JSON string. See the doc string of debug_data.Deb...
Implementation of the core metadata-carrying Event proto callback. Args: event: An Event proto that contains core metadata about the debugged Session::Run() in its log_message.message field, as a JSON string. See the doc string of debug_data.DebugDumpDir.core_metadata for details.
Below is the the instruction that describes the task: ### Input: Implementation of the core metadata-carrying Event proto callback. Args: event: An Event proto that contains core metadata about the debugged Session::Run() in its log_message.message field, as a JSON string. See the doc str...
def graphs(self): """Sorry for the black magic. The result is an object whose attributes are all the graphs found in graphs.py initialized with this instance as only argument.""" result = Dummy() for graph in graphs.__all__: cls = getattr(graphs, graph) se...
Sorry for the black magic. The result is an object whose attributes are all the graphs found in graphs.py initialized with this instance as only argument.
Below is the the instruction that describes the task: ### Input: Sorry for the black magic. The result is an object whose attributes are all the graphs found in graphs.py initialized with this instance as only argument. ### Response: def graphs(self): """Sorry for the black magic. The resul...
def get_media_metadata(self, item_id): """Get metadata for a media item. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's metadata, or `None` See also: The Sonos `getMediaMetadata API ...
Get metadata for a media item. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's metadata, or `None` See also: The Sonos `getMediaMetadata API <http://musicpartners.sonos.com/node/83>`_
Below is the the instruction that describes the task: ### Input: Get metadata for a media item. Args: item_id (str): The item for which metadata is required. Returns: ~collections.OrderedDict: The item's metadata, or `None` See also: The Sonos `getMedia...
def find_spec(self, fullname, path, target=None): '''finds the appropriate properties (spec) of a module, and sets its loader.''' if not path: path = [os.getcwd()] if "." in fullname: name = fullname.split(".")[-1] else: name = fullname ...
finds the appropriate properties (spec) of a module, and sets its loader.
Below is the the instruction that describes the task: ### Input: finds the appropriate properties (spec) of a module, and sets its loader. ### Response: def find_spec(self, fullname, path, target=None): '''finds the appropriate properties (spec) of a module, and sets its loader.''' ...
def load(*args, **kwargs): """Load an numpy.ndarray from a file stream. This works exactly like the usual `json.load()` function, but it uses our custom deserializer. """ kwargs.update(dict(object_hook=json_numpy_obj_hook)) return _json.load(*args, **kwargs)
Load an numpy.ndarray from a file stream. This works exactly like the usual `json.load()` function, but it uses our custom deserializer.
Below is the the instruction that describes the task: ### Input: Load an numpy.ndarray from a file stream. This works exactly like the usual `json.load()` function, but it uses our custom deserializer. ### Response: def load(*args, **kwargs): """Load an numpy.ndarray from a file stream. This work...
def format_t_into_dhms_format(timestamp): """ Convert an amount of second into day, hour, min and sec :param timestamp: seconds :type timestamp: int :return: 'Ad Bh Cm Ds' :rtype: str >>> format_t_into_dhms_format(456189) '5d 6h 43m 9s' >>> format_t_into_dhms_format(3600) '0d 1h 0...
Convert an amount of second into day, hour, min and sec :param timestamp: seconds :type timestamp: int :return: 'Ad Bh Cm Ds' :rtype: str >>> format_t_into_dhms_format(456189) '5d 6h 43m 9s' >>> format_t_into_dhms_format(3600) '0d 1h 0m 0s'
Below is the the instruction that describes the task: ### Input: Convert an amount of second into day, hour, min and sec :param timestamp: seconds :type timestamp: int :return: 'Ad Bh Cm Ds' :rtype: str >>> format_t_into_dhms_format(456189) '5d 6h 43m 9s' >>> format_t_into_dhms_format...
def reverse_index(self): """Move the cursor up one line in the same column. If the cursor is at the first line, create a new line at the top. """ top, bottom = self.margins or Margins(0, self.lines - 1) if self.cursor.y == top: # TODO: mark only the lines within margi...
Move the cursor up one line in the same column. If the cursor is at the first line, create a new line at the top.
Below is the the instruction that describes the task: ### Input: Move the cursor up one line in the same column. If the cursor is at the first line, create a new line at the top. ### Response: def reverse_index(self): """Move the cursor up one line in the same column. If the cursor is at th...
def _rr_new(self, rr_version, rr_name, rr_symlink_target, rr_relocated_child, rr_relocated, rr_relocated_parent, file_mode): # type: (str, bytes, bytes, bool, bool, bool, int) -> None ''' Internal method to add Rock Ridge to a Directory Record. Parameters: rr_ve...
Internal method to add Rock Ridge to a Directory Record. Parameters: rr_version - A string containing the version of Rock Ridge to use for this record. rr_name - The Rock Ridge name to associate with this directory record. rr_symlink_target - The target for the ...
Below is the the instruction that describes the task: ### Input: Internal method to add Rock Ridge to a Directory Record. Parameters: rr_version - A string containing the version of Rock Ridge to use for this record. rr_name - The Rock Ridge name to associate with th...
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_lldp_pdu_transmitted(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail") config = get_lldp_neighbor_detail output = ET.SubEleme...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_lldp_neighbor_detail_output_lldp_neighbor_detail_lldp_pdu_transmitted(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_lldp_neighbor_detail = ET.El...
def get_soap_locals(obj, Hpos, alp, bet, rCut=5.0, nMax=5, Lmax=5, crossOver=True, all_atomtypes=None, eta=1.0): """Get the RBF basis SOAP output for the given positions in a finite system. Args: obj(ase.Atoms): Atomic structure for which the SOAP output is calculated. Hpos: Positio...
Get the RBF basis SOAP output for the given positions in a finite system. Args: obj(ase.Atoms): Atomic structure for which the SOAP output is calculated. Hpos: Positions at which to calculate SOAP alp: Alphas bet: Betas rCut: Radial cutoff. nMax: Maximum ...
Below is the the instruction that describes the task: ### Input: Get the RBF basis SOAP output for the given positions in a finite system. Args: obj(ase.Atoms): Atomic structure for which the SOAP output is calculated. Hpos: Positions at which to calculate SOAP alp: Alphas ...
def on_create_view(self): """ Trigger the click """ d = self.declaration changed = not d.condition if changed: d.condition = True view = self.get_view() if changed: self.ready.set_result(True) return view
Trigger the click
Below is the the instruction that describes the task: ### Input: Trigger the click ### Response: def on_create_view(self): """ Trigger the click """ d = self.declaration changed = not d.condition if changed: d.condition = True view = self.get_view() ...
def finalize_options(self): """Finalizes the command's options. Args: self (CoverageCommand): the ``CoverageCommand`` instance Returns: ``None`` """ self.cwd = os.path.abspath(os.path.dirname(__file__)) self.test_dir = os.path.join(self.cwd, 'tests')
Finalizes the command's options. Args: self (CoverageCommand): the ``CoverageCommand`` instance Returns: ``None``
Below is the the instruction that describes the task: ### Input: Finalizes the command's options. Args: self (CoverageCommand): the ``CoverageCommand`` instance Returns: ``None`` ### Response: def finalize_options(self): """Finalizes the command's options. Arg...
def writable(self): """True if the Slot is writable.""" return bool(lib.EnvSlotWritableP(self._env, self._cls, self._name))
True if the Slot is writable.
Below is the the instruction that describes the task: ### Input: True if the Slot is writable. ### Response: def writable(self): """True if the Slot is writable.""" return bool(lib.EnvSlotWritableP(self._env, self._cls, self._name))
def get_adaptive_threshold(threshold_method, image, threshold, mask = None, adaptive_window_size = 10, **kwargs): """Given a global threshold, compute a threshold per pixel Break the image into blocks, computing the thres...
Given a global threshold, compute a threshold per pixel Break the image into blocks, computing the threshold per block. Afterwards, constrain the block threshold to .7 T < t < 1.5 T. Block sizes must be at least 50x50. Images > 500 x 500 get 10x10 blocks.
Below is the the instruction that describes the task: ### Input: Given a global threshold, compute a threshold per pixel Break the image into blocks, computing the threshold per block. Afterwards, constrain the block threshold to .7 T < t < 1.5 T. Block sizes must be at least 50x50. Images > 5...
def get_config(name, expand=False): """ Returns the config value that corresponds to *name*, which must have the format ``<section>[.<option>]``. When an option is given and *expand* is *True*, variables are expanded in the returned value. """ cfg = Config.instance() only_section = "." not i...
Returns the config value that corresponds to *name*, which must have the format ``<section>[.<option>]``. When an option is given and *expand* is *True*, variables are expanded in the returned value.
Below is the the instruction that describes the task: ### Input: Returns the config value that corresponds to *name*, which must have the format ``<section>[.<option>]``. When an option is given and *expand* is *True*, variables are expanded in the returned value. ### Response: def get_config(name, expand=...
def set_dry_run(xml_root, value=True): """Sets dry-run so records are not updated, only log file is produced.""" value_str = str(value).lower() assert value_str in ("true", "false") if xml_root.tag == "testsuites": _set_property(xml_root, "polarion-dry-run", value_str) elif xml_root.tag in (...
Sets dry-run so records are not updated, only log file is produced.
Below is the the instruction that describes the task: ### Input: Sets dry-run so records are not updated, only log file is produced. ### Response: def set_dry_run(xml_root, value=True): """Sets dry-run so records are not updated, only log file is produced.""" value_str = str(value).lower() assert value...
def unpack_bits( byte ): """Expand a bitfield into a 64-bit int (8 bool bytes).""" longbits = byte & (0x00000000000000ff) longbits = (longbits | (longbits<<28)) & (0x0000000f0000000f) longbits = (longbits | (longbits<<14)) & (0x0003000300030003) longbits = (longbits | (longbits<<7)) & (0x01010101010...
Expand a bitfield into a 64-bit int (8 bool bytes).
Below is the the instruction that describes the task: ### Input: Expand a bitfield into a 64-bit int (8 bool bytes). ### Response: def unpack_bits( byte ): """Expand a bitfield into a 64-bit int (8 bool bytes).""" longbits = byte & (0x00000000000000ff) longbits = (longbits | (longbits<<28)) & (0x000000...
def _create_resource_group(self, region, resource_group_name): """ Create resource group if it does not exist. """ resource_group_config = {'location': region} try: self.resource.resource_groups.create_or_update( resource_group_name, resource_group_co...
Create resource group if it does not exist.
Below is the the instruction that describes the task: ### Input: Create resource group if it does not exist. ### Response: def _create_resource_group(self, region, resource_group_name): """ Create resource group if it does not exist. """ resource_group_config = {'location': region} ...
def vnic_attached_to_network(nicspec, network, logger): """ Attach vNIC to Network. :param nicspec: <vim.vm.device.VirtualDeviceSpec> :param network: <vim network obj> :return: updated 'nicspec' """ if nicspec: if network_is_portgroup(network): ...
Attach vNIC to Network. :param nicspec: <vim.vm.device.VirtualDeviceSpec> :param network: <vim network obj> :return: updated 'nicspec'
Below is the the instruction that describes the task: ### Input: Attach vNIC to Network. :param nicspec: <vim.vm.device.VirtualDeviceSpec> :param network: <vim network obj> :return: updated 'nicspec' ### Response: def vnic_attached_to_network(nicspec, network, logger): """ A...
def generate(ast_tree: ast.Tree, model_name: str): """ :param ast_tree: AST to generate from :param model_name: class to generate :return: sympy source code for model """ component_ref = ast.ComponentRef.from_string(model_name) ast_tree_new = copy.deepcopy(ast_tree) ast_walker = TreeWalk...
:param ast_tree: AST to generate from :param model_name: class to generate :return: sympy source code for model
Below is the the instruction that describes the task: ### Input: :param ast_tree: AST to generate from :param model_name: class to generate :return: sympy source code for model ### Response: def generate(ast_tree: ast.Tree, model_name: str): """ :param ast_tree: AST to generate from :param mode...
def inject_config(self, config, from_args): """ :param config: :type config: list :param from_args: :type from_args: dict """ # First get required values from labelStore runtime = self._get_runtime() whitelist = self._get_whitelist() #Run introspection on the libraries to retriev...
:param config: :type config: list :param from_args: :type from_args: dict
Below is the the instruction that describes the task: ### Input: :param config: :type config: list :param from_args: :type from_args: dict ### Response: def inject_config(self, config, from_args): """ :param config: :type config: list :param from_args: :type from_args: dict """ ...
def init_logger(cls, log_level): """Initialize logger settings.""" logger = logging.getLogger("AutoMLBoard") handler = logging.StreamHandler() formatter = logging.Formatter("[%(levelname)s %(asctime)s] " "%(filename)s: %(lineno)d " ...
Initialize logger settings.
Below is the the instruction that describes the task: ### Input: Initialize logger settings. ### Response: def init_logger(cls, log_level): """Initialize logger settings.""" logger = logging.getLogger("AutoMLBoard") handler = logging.StreamHandler() formatter = logging.Formatter("[%...
def get_squeezenet(version, pretrained=False, ctx=cpu(), root=os.path.join(base.data_dir(), 'models'), **kwargs): r"""SqueezeNet model from the `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" <https://arxiv.org/abs/1602.07360>`_ paper. SqueezeNet 1.1 ...
r"""SqueezeNet model from the `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" <https://arxiv.org/abs/1602.07360>`_ paper. SqueezeNet 1.1 model from the `official SqueezeNet repo <https://github.com/DeepScale/SqueezeNet/tree/master/SqueezeNet_v1.1>`_. SqueezeNet 1.1 ...
Below is the the instruction that describes the task: ### Input: r"""SqueezeNet model from the `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" <https://arxiv.org/abs/1602.07360>`_ paper. SqueezeNet 1.1 model from the `official SqueezeNet repo <https://github.com/Dee...
def search(self, regex, flags=0): """ Run a regex test against a dict value (only substring string has to match). >>> Query().f1.search(r'^\w+$') :param regex: The regular expression to use for matching """ return self._generate_test( lambda value: r...
Run a regex test against a dict value (only substring string has to match). >>> Query().f1.search(r'^\w+$') :param regex: The regular expression to use for matching
Below is the the instruction that describes the task: ### Input: Run a regex test against a dict value (only substring string has to match). >>> Query().f1.search(r'^\w+$') :param regex: The regular expression to use for matching ### Response: def search(self, regex, flags=0): """...
def getStates(self, Corpnum, reciptNumList, UserID=None): """ 전송내역 요약정보 확인 args CorpNum : 팝빌회원 사업자번호 reciptNumList : 문자전송 접수번호 배열 UserID : 팝빌회원 아이디 return 전송정보 as list raise PopbillExcept...
전송내역 요약정보 확인 args CorpNum : 팝빌회원 사업자번호 reciptNumList : 문자전송 접수번호 배열 UserID : 팝빌회원 아이디 return 전송정보 as list raise PopbillException
Below is the the instruction that describes the task: ### Input: 전송내역 요약정보 확인 args CorpNum : 팝빌회원 사업자번호 reciptNumList : 문자전송 접수번호 배열 UserID : 팝빌회원 아이디 return 전송정보 as list raise PopbillExceptio...
def create(cls, service=None, endpoint=None, data=None, *args, **kwargs): """ Create an integration within the scope of an service. Make sure that they should reasonably be able to query with an service or endpoint that knows about an service. """ cls.validate(data) ...
Create an integration within the scope of an service. Make sure that they should reasonably be able to query with an service or endpoint that knows about an service.
Below is the the instruction that describes the task: ### Input: Create an integration within the scope of an service. Make sure that they should reasonably be able to query with an service or endpoint that knows about an service. ### Response: def create(cls, service=None, endpoint=None, data=Non...
def dump(self, dest_dir=None, to_local=1, from_local=0, archive=0, dump_fn=None, name=None, site=None, use_sudo=0, cleanup=1): """ Exports the target database to a single transportable file on the localhost, appropriate for loading using load(). """ r = self.local_renderer ...
Exports the target database to a single transportable file on the localhost, appropriate for loading using load().
Below is the the instruction that describes the task: ### Input: Exports the target database to a single transportable file on the localhost, appropriate for loading using load(). ### Response: def dump(self, dest_dir=None, to_local=1, from_local=0, archive=0, dump_fn=None, name=None, site=None, use_sudo=0...
def webex_teams_webhook_events(): """Processes incoming requests to the '/events' URI.""" if request.method == 'GET': return ("""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Webex Tea...
Processes incoming requests to the '/events' URI.
Below is the the instruction that describes the task: ### Input: Processes incoming requests to the '/events' URI. ### Response: def webex_teams_webhook_events(): """Processes incoming requests to the '/events' URI.""" if request.method == 'GET': return ("""<!DOCTYPE html> <html ...
def update_image_member(self, img_id, status): """ Updates the image whose ID is given with the status specified. This must be called by the user whose project_id is in the members for the image. If called by the owner of the image, an InvalidImageMember exception will be raised....
Updates the image whose ID is given with the status specified. This must be called by the user whose project_id is in the members for the image. If called by the owner of the image, an InvalidImageMember exception will be raised. Valid values for 'status' include: pending ...
Below is the the instruction that describes the task: ### Input: Updates the image whose ID is given with the status specified. This must be called by the user whose project_id is in the members for the image. If called by the owner of the image, an InvalidImageMember exception will be raise...
def reverse_transform(self, col): """Converts data back into original format. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame """ output = pd.DataFrame() new_name = '?' + self.col_name col.loc[col[new_name] == 0...
Converts data back into original format. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame
Below is the the instruction that describes the task: ### Input: Converts data back into original format. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame ### Response: def reverse_transform(self, col): """Converts data back into original f...
def solve_filter(expr, vars): """Filter values on the LHS by evaluating RHS with each value. Returns any LHS values for which RHS evaluates to a true value. """ lhs_values, _ = __solve_for_repeated(expr.lhs, vars) def lazy_filter(): for lhs_value in repeated.getvalues(lhs_values): ...
Filter values on the LHS by evaluating RHS with each value. Returns any LHS values for which RHS evaluates to a true value.
Below is the the instruction that describes the task: ### Input: Filter values on the LHS by evaluating RHS with each value. Returns any LHS values for which RHS evaluates to a true value. ### Response: def solve_filter(expr, vars): """Filter values on the LHS by evaluating RHS with each value. Retur...
def logarithmic_profile(wind_speed, wind_speed_height, hub_height, roughness_length, obstacle_height=0.0): r""" Calculates the wind speed at hub height using a logarithmic wind profile. The logarithmic height equation is used. There is the possibility of including the height of ...
r""" Calculates the wind speed at hub height using a logarithmic wind profile. The logarithmic height equation is used. There is the possibility of including the height of the surrounding obstacles in the calculation. This function is carried out when the parameter `wind_speed_model` of an instance...
Below is the the instruction that describes the task: ### Input: r""" Calculates the wind speed at hub height using a logarithmic wind profile. The logarithmic height equation is used. There is the possibility of including the height of the surrounding obstacles in the calculation. This function is...
def all_tables(self) -> List[str]: """ List of all known tables :return: """ return sorted([k for k in self.__dict__.keys() if k not in _I2B2Tables._funcs and not k.startswith("_")])
List of all known tables :return:
Below is the the instruction that describes the task: ### Input: List of all known tables :return: ### Response: def all_tables(self) -> List[str]: """ List of all known tables :return: """ return sorted([k for k in self.__dict__.keys() if k no...
def _elbv2_load_balancer(self, lookup): """ Args: lookup: the friendly name of the V2 elb to look up Returns: A dict with the load balancer description Raises: botocore.exceptions.ClientError: no such load-balancer """ client = EFAwsResolver.__CLIENTS['elbv2'] elbs = client...
Args: lookup: the friendly name of the V2 elb to look up Returns: A dict with the load balancer description Raises: botocore.exceptions.ClientError: no such load-balancer
Below is the the instruction that describes the task: ### Input: Args: lookup: the friendly name of the V2 elb to look up Returns: A dict with the load balancer description Raises: botocore.exceptions.ClientError: no such load-balancer ### Response: def _elbv2_load_balancer(self, lookup):...
def AddClient(self, client): """Adds a client to the index. Args: client: A VFSGRRClient record to add or update. """ client_id, keywords = self.AnalyzeClient(client) self.AddKeywordsForName(client_id, keywords)
Adds a client to the index. Args: client: A VFSGRRClient record to add or update.
Below is the the instruction that describes the task: ### Input: Adds a client to the index. Args: client: A VFSGRRClient record to add or update. ### Response: def AddClient(self, client): """Adds a client to the index. Args: client: A VFSGRRClient record to add or update. """ c...
def data_to_string(self): """Returns a UTF8 string with the QR Code's data""" # FIX-ME: if we don't add the BOM_UTF8 char, QtQR doesn't decode # correctly; but if we add it, mobile apps don't.- # Apparently is a zbar bug. if self.data_type == 'text': return BOM_UTF8 +...
Returns a UTF8 string with the QR Code's data
Below is the the instruction that describes the task: ### Input: Returns a UTF8 string with the QR Code's data ### Response: def data_to_string(self): """Returns a UTF8 string with the QR Code's data""" # FIX-ME: if we don't add the BOM_UTF8 char, QtQR doesn't decode # correctly; but if we ...
def restore(self, backup=None, delete_backup=False): """Restore the snapshot to the associated storage resource. :param backup: name of the backup snapshot :param delete_backup: Whether to delete the backup snap after a successful restore. """ resp ...
Restore the snapshot to the associated storage resource. :param backup: name of the backup snapshot :param delete_backup: Whether to delete the backup snap after a successful restore.
Below is the the instruction that describes the task: ### Input: Restore the snapshot to the associated storage resource. :param backup: name of the backup snapshot :param delete_backup: Whether to delete the backup snap after a successful restore. ### Response: def r...
def get_user_from_social_auth(tpa_provider, tpa_username): """ Find the LMS user from the LMS model `UserSocialAuth`. Arguments: tpa_provider (third_party_auth.provider): third party auth provider object tpa_username (str): Username returned by the third party auth """ user_social_...
Find the LMS user from the LMS model `UserSocialAuth`. Arguments: tpa_provider (third_party_auth.provider): third party auth provider object tpa_username (str): Username returned by the third party auth
Below is the the instruction that describes the task: ### Input: Find the LMS user from the LMS model `UserSocialAuth`. Arguments: tpa_provider (third_party_auth.provider): third party auth provider object tpa_username (str): Username returned by the third party auth ### Response: def get_user...
def clear_xcom_data(self, session=None): """ Clears all XCom data from the database for the task instance """ session.query(XCom).filter( XCom.dag_id == self.dag_id, XCom.task_id == self.task_id, XCom.execution_date == self.execution_date ).del...
Clears all XCom data from the database for the task instance
Below is the the instruction that describes the task: ### Input: Clears all XCom data from the database for the task instance ### Response: def clear_xcom_data(self, session=None): """ Clears all XCom data from the database for the task instance """ session.query(XCom).filter( ...
def lookup_prefix(self, prefix, timestamp=timestamp_now): """ Returns lookup data of a Prefix Args: prefix (string): Prefix of a Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: dict: Dictionary contai...
Returns lookup data of a Prefix Args: prefix (string): Prefix of a Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: dict: Dictionary containing the country specific data of the Prefix Raises: KeyE...
Below is the the instruction that describes the task: ### Input: Returns lookup data of a Prefix Args: prefix (string): Prefix of a Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: dict: Dictionary containing the ...
def parameters(self): """Return a list where each element contains the parameters for a task. """ parameters = [] for task in self.tasks: parameters.extend(task.parameters) return parameters
Return a list where each element contains the parameters for a task.
Below is the the instruction that describes the task: ### Input: Return a list where each element contains the parameters for a task. ### Response: def parameters(self): """Return a list where each element contains the parameters for a task. """ parameters = [] for task in self.task...
def from_isodatetime(value, strict=False): """Convert an ISO formatted datetime into a Date object. :param value: The ISO formatted datetime. :param strict: If value is ``None``, then if strict is ``True`` it returns the Date object of today, otherwise it returns ``None``. (Default: ``False...
Convert an ISO formatted datetime into a Date object. :param value: The ISO formatted datetime. :param strict: If value is ``None``, then if strict is ``True`` it returns the Date object of today, otherwise it returns ``None``. (Default: ``False``) :returns: The Date object or ``None``.
Below is the the instruction that describes the task: ### Input: Convert an ISO formatted datetime into a Date object. :param value: The ISO formatted datetime. :param strict: If value is ``None``, then if strict is ``True`` it returns the Date object of today, otherwise it returns ``None``. ...
def import_class(class_path): """imports and returns given class string. :param class_path: Class path as string :type class_path: str :returns: Class that has given path :rtype: class :Example: >>> import_class('collections.OrderedDict').__name__ 'OrderedDict' """ try: ...
imports and returns given class string. :param class_path: Class path as string :type class_path: str :returns: Class that has given path :rtype: class :Example: >>> import_class('collections.OrderedDict').__name__ 'OrderedDict'
Below is the the instruction that describes the task: ### Input: imports and returns given class string. :param class_path: Class path as string :type class_path: str :returns: Class that has given path :rtype: class :Example: >>> import_class('collections.OrderedDict').__name__ 'Ord...
def set_children(self, children): """Set children of the span block.""" if isinstance(children, tuple): self._children = list(children) else: self._children = [children] return self
Set children of the span block.
Below is the the instruction that describes the task: ### Input: Set children of the span block. ### Response: def set_children(self, children): """Set children of the span block.""" if isinstance(children, tuple): self._children = list(children) else: self._children...
def write_error(self, text): """Simulate stderr""" self.flush() self.write(text, flush=True, error=True) if get_debug_level(): STDERR.write(text)
Simulate stderr
Below is the the instruction that describes the task: ### Input: Simulate stderr ### Response: def write_error(self, text): """Simulate stderr""" self.flush() self.write(text, flush=True, error=True) if get_debug_level(): STDERR.write(text)
def _notifyDone(self): ''' Allow any other editatoms waiting on me to complete to resume ''' if self.notified: return self.doneevent.set() for buid in self.mybldgbuids: del self.allbldgbuids[buid] self.notified = True
Allow any other editatoms waiting on me to complete to resume
Below is the the instruction that describes the task: ### Input: Allow any other editatoms waiting on me to complete to resume ### Response: def _notifyDone(self): ''' Allow any other editatoms waiting on me to complete to resume ''' if self.notified: return sel...
def get_proxy(self, input_): """Gets a proxy. arg: input (osid.proxy.ProxyCondition): a proxy condition return: (osid.proxy.Proxy) - a proxy raise: NullArgument - ``input`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - au...
Gets a proxy. arg: input (osid.proxy.ProxyCondition): a proxy condition return: (osid.proxy.Proxy) - a proxy raise: NullArgument - ``input`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure raise: Unsu...
Below is the the instruction that describes the task: ### Input: Gets a proxy. arg: input (osid.proxy.ProxyCondition): a proxy condition return: (osid.proxy.Proxy) - a proxy raise: NullArgument - ``input`` is ``null`` raise: OperationFailed - unable to complete request ...
def __get_conn(self, flag_force_new=False, filename=None): """Returns connection to database. Tries to return existing connection, unless flag_force_new Args: flag_force_new: filename: Returns: sqlite3.Connection object **Note** this is a private method because...
Returns connection to database. Tries to return existing connection, unless flag_force_new Args: flag_force_new: filename: Returns: sqlite3.Connection object **Note** this is a private method because you can get a connection to any file, so it has to b...
Below is the the instruction that describes the task: ### Input: Returns connection to database. Tries to return existing connection, unless flag_force_new Args: flag_force_new: filename: Returns: sqlite3.Connection object **Note** this is a private method because ...
def percept(self, agent): "By default, agent perceives things within a default radius." return [self.thing_percept(thing, agent) for thing in self.things_near(agent.location)]
By default, agent perceives things within a default radius.
Below is the the instruction that describes the task: ### Input: By default, agent perceives things within a default radius. ### Response: def percept(self, agent): "By default, agent perceives things within a default radius." return [self.thing_percept(thing, agent) for thing in se...
def remove_objects(self, bucket_name, objects_iter): """ Removes multiple objects from a bucket. :param bucket_name: Bucket from which to remove objects :param objects_iter: A list, tuple or iterator that provides objects names to delete. :return: An iterator of MultiD...
Removes multiple objects from a bucket. :param bucket_name: Bucket from which to remove objects :param objects_iter: A list, tuple or iterator that provides objects names to delete. :return: An iterator of MultiDeleteError instances for each object that had a delete error.
Below is the the instruction that describes the task: ### Input: Removes multiple objects from a bucket. :param bucket_name: Bucket from which to remove objects :param objects_iter: A list, tuple or iterator that provides objects names to delete. :return: An iterator of MultiDelet...
def add_suggestions(self, *suggestions, **kwargs): """ Add suggestion terms to the AutoCompleter engine. Each suggestion has a score and string. If kwargs['increment'] is true and the terms are already in the server's dictionary, we increment their scores """ pipe = self.redis....
Add suggestion terms to the AutoCompleter engine. Each suggestion has a score and string. If kwargs['increment'] is true and the terms are already in the server's dictionary, we increment their scores
Below is the the instruction that describes the task: ### Input: Add suggestion terms to the AutoCompleter engine. Each suggestion has a score and string. If kwargs['increment'] is true and the terms are already in the server's dictionary, we increment their scores ### Response: def add_suggestions(self, ...
def _set_mip_policy(self, v, load=False): """ Setter method for mip_policy, mapped from YANG variable /protocol/cfm/domain_name/ma_name/cfm_ma_sub_commands/mip_policy (mip-policy-type) If this variable is read-only (config: false) in the source YANG file, then _set_mip_policy is considered as a private ...
Setter method for mip_policy, mapped from YANG variable /protocol/cfm/domain_name/ma_name/cfm_ma_sub_commands/mip_policy (mip-policy-type) If this variable is read-only (config: false) in the source YANG file, then _set_mip_policy is considered as a private method. Backends looking to populate this variable...
Below is the the instruction that describes the task: ### Input: Setter method for mip_policy, mapped from YANG variable /protocol/cfm/domain_name/ma_name/cfm_ma_sub_commands/mip_policy (mip-policy-type) If this variable is read-only (config: false) in the source YANG file, then _set_mip_policy is considere...
def generate_data(self, plot_data): """ Generate data to be used by this layer Parameters ---------- plot_data : dataframe ggplot object data """ # Each layer that does not have data gets a copy of # of the ggplot.data. If the has data it is r...
Generate data to be used by this layer Parameters ---------- plot_data : dataframe ggplot object data
Below is the the instruction that describes the task: ### Input: Generate data to be used by this layer Parameters ---------- plot_data : dataframe ggplot object data ### Response: def generate_data(self, plot_data): """ Generate data to be used by this layer ...
def calc_fft_with_PyCUDA(Signal): """ Calculates the FFT of the passed signal by using the scikit-cuda libary which relies on PyCUDA Parameters ---------- Signal : ndarray Signal to be transformed into Fourier space Returns ------- Signalfft : ndarray Array containi...
Calculates the FFT of the passed signal by using the scikit-cuda libary which relies on PyCUDA Parameters ---------- Signal : ndarray Signal to be transformed into Fourier space Returns ------- Signalfft : ndarray Array containing the signal's FFT
Below is the the instruction that describes the task: ### Input: Calculates the FFT of the passed signal by using the scikit-cuda libary which relies on PyCUDA Parameters ---------- Signal : ndarray Signal to be transformed into Fourier space Returns ------- Signalfft : ndarray...
def geocode( self, query, bbox=None, mapview=None, exactly_one=True, maxresults=None, pageinformation=None, language=None, additional_data=False, timeout=DEFAULT_SENTINEL ): """ Re...
Return a location point by address. This implementation supports only a subset of all available parameters. A list of all parameters of the pure REST API is available here: https://developer.here.com/documentation/geocoder/topics/resource-geocode.html :param str query: The address or q...
Below is the the instruction that describes the task: ### Input: Return a location point by address. This implementation supports only a subset of all available parameters. A list of all parameters of the pure REST API is available here: https://developer.here.com/documentation/geocoder/top...
def _fromJSON(cls, jsonobject): """Generates a new instance of :class:`maspy.core.MzmlScan` from a decoded JSON object (as generated by :func:`maspy.core.MzmlScan._reprJSON()`). :param jsonobject: decoded JSON object :returns: a new instance of :class:`MzmlScan` """ ...
Generates a new instance of :class:`maspy.core.MzmlScan` from a decoded JSON object (as generated by :func:`maspy.core.MzmlScan._reprJSON()`). :param jsonobject: decoded JSON object :returns: a new instance of :class:`MzmlScan`
Below is the the instruction that describes the task: ### Input: Generates a new instance of :class:`maspy.core.MzmlScan` from a decoded JSON object (as generated by :func:`maspy.core.MzmlScan._reprJSON()`). :param jsonobject: decoded JSON object :returns: a new instance of :class:...
def clip_to_seconds(m: Union[int, pd.Series]) -> Union[int, pd.Series]: """Clips UTC datetime in nanoseconds to seconds.""" return m // pd.Timedelta(1, unit='s').value
Clips UTC datetime in nanoseconds to seconds.
Below is the the instruction that describes the task: ### Input: Clips UTC datetime in nanoseconds to seconds. ### Response: def clip_to_seconds(m: Union[int, pd.Series]) -> Union[int, pd.Series]: """Clips UTC datetime in nanoseconds to seconds.""" return m // pd.Timedelta(1, unit='s').value
def context(self, size, placeholder=None, scope=None): """Returns this word in context, {size} words to the left, the current word, and {size} words to the right""" return self.leftcontext(size, placeholder,scope) + [self] + self.rightcontext(size, placeholder,scope)
Returns this word in context, {size} words to the left, the current word, and {size} words to the right
Below is the the instruction that describes the task: ### Input: Returns this word in context, {size} words to the left, the current word, and {size} words to the right ### Response: def context(self, size, placeholder=None, scope=None): """Returns this word in context, {size} words to the left, the curren...
def _render_image(self, spec, container_args, alt_text=None): """ Render an image specification into an <img> tag """ try: path, image_args, title = image.parse_image_spec(spec) except Exception as err: # pylint: disable=broad-except logger.exception("Got error on spec ...
Render an image specification into an <img> tag
Below is the the instruction that describes the task: ### Input: Render an image specification into an <img> tag ### Response: def _render_image(self, spec, container_args, alt_text=None): """ Render an image specification into an <img> tag """ try: path, image_args, title = image.pars...
def _guess_concat(data): """ Guess concat function from given data """ return { type(u''): u''.join, type(b''): concat_bytes, }.get(type(data), list)
Guess concat function from given data
Below is the the instruction that describes the task: ### Input: Guess concat function from given data ### Response: def _guess_concat(data): """ Guess concat function from given data """ return { type(u''): u''.join, type(b''): concat_bytes, }.get(type(data), list)
def logs(self): """Find the log directory and return all the logs sorted.""" if not self.parent.loaded: self.parent.load() logs = self.parent.p.logs_dir.flat_directories logs.sort(key=lambda x: x.mod_time) return logs
Find the log directory and return all the logs sorted.
Below is the the instruction that describes the task: ### Input: Find the log directory and return all the logs sorted. ### Response: def logs(self): """Find the log directory and return all the logs sorted.""" if not self.parent.loaded: self.parent.load() logs = self.parent.p.logs_dir.flat...
def get_grade_systems(self): """Gets the grade system list resulting from the search. return: (osid.grading.GradeSystemList) - the grade system list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.* """ if self.ret...
Gets the grade system list resulting from the search. return: (osid.grading.GradeSystemList) - the grade system list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Gets the grade system list resulting from the search. return: (osid.grading.GradeSystemList) - the grade system list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.* ###...
def canonical_request(self, method, path, content, timestamp): """Return the canonical request string.""" request = collections.OrderedDict([ ('Method', method.upper()), ('Hashed Path', path), ('X-Ops-Content-Hash', content), ('X-Ops-Timestamp', timestamp)...
Return the canonical request string.
Below is the the instruction that describes the task: ### Input: Return the canonical request string. ### Response: def canonical_request(self, method, path, content, timestamp): """Return the canonical request string.""" request = collections.OrderedDict([ ('Method', method.upper()), ...
def feature_extraction(self, algorithms): """Get a list of features. Every algorithm has to return the features as a list.""" assert type(algorithms) is list features = [] for algorithm in algorithms: new_features = algorithm(self) assert len(new_features...
Get a list of features. Every algorithm has to return the features as a list.
Below is the the instruction that describes the task: ### Input: Get a list of features. Every algorithm has to return the features as a list. ### Response: def feature_extraction(self, algorithms): """Get a list of features. Every algorithm has to return the features as a list.""" ...
def _exchange_refresh_tokens(self): 'Exchanges a refresh token for an access token' if self.token_cache is not None and 'refresh' in self.token_cache: # Attempt to use the refresh token to get a new access token. refresh_form = { 'grant_type': 'refresh_token', ...
Exchanges a refresh token for an access token
Below is the the instruction that describes the task: ### Input: Exchanges a refresh token for an access token ### Response: def _exchange_refresh_tokens(self): 'Exchanges a refresh token for an access token' if self.token_cache is not None and 'refresh' in self.token_cache: # Attempt t...
def _path2uri(self, dirpath): ''' Convert directory path to uri ''' relpath = dirpath.replace(self.root_path, self.package_name) if relpath.startswith(os.path.sep): relpath = relpath[1:] return relpath.replace(os.path.sep, '.')
Convert directory path to uri
Below is the the instruction that describes the task: ### Input: Convert directory path to uri ### Response: def _path2uri(self, dirpath): ''' Convert directory path to uri ''' relpath = dirpath.replace(self.root_path, self.package_name) if relpath.startswith(os.path.sep): relpa...
def check_collections_are_supported(saved_model_handler, supported): """Checks that SavedModelHandler only uses supported collections.""" for meta_graph in saved_model_handler.meta_graphs: used_collection_keys = set(meta_graph.collection_def.keys()) unsupported = used_collection_keys - supported if unsu...
Checks that SavedModelHandler only uses supported collections.
Below is the the instruction that describes the task: ### Input: Checks that SavedModelHandler only uses supported collections. ### Response: def check_collections_are_supported(saved_model_handler, supported): """Checks that SavedModelHandler only uses supported collections.""" for meta_graph in saved_model_h...
def symbols(self, *args, **kwargs): """Lookup multuple Equities as a list. Parameters ---------- *args : iterable[str] The ticker symbols to lookup. country_code : str or None, optional A country to limit symbol searches to. Returns ---...
Lookup multuple Equities as a list. Parameters ---------- *args : iterable[str] The ticker symbols to lookup. country_code : str or None, optional A country to limit symbol searches to. Returns ------- equities : list[Equity] ...
Below is the the instruction that describes the task: ### Input: Lookup multuple Equities as a list. Parameters ---------- *args : iterable[str] The ticker symbols to lookup. country_code : str or None, optional A country to limit symbol searches to. ...
def closed_paths(entities, vertices): """ Paths are lists of entity indices. We first generate vertex paths using graph cycle algorithms, and then convert them to entity paths. This will also change the ordering of entity.points in place so a path may be traversed without having to reverse the ...
Paths are lists of entity indices. We first generate vertex paths using graph cycle algorithms, and then convert them to entity paths. This will also change the ordering of entity.points in place so a path may be traversed without having to reverse the entity. Parameters ------------- enti...
Below is the the instruction that describes the task: ### Input: Paths are lists of entity indices. We first generate vertex paths using graph cycle algorithms, and then convert them to entity paths. This will also change the ordering of entity.points in place so a path may be traversed without hav...
def format_packet(command): """Format packet to be sent.""" frame_header = b"\xaa" verify = b"\x0b" send_delim = b"\xbb" return frame_header + command.ljust(17, b"\x00") + verify + send_delim
Format packet to be sent.
Below is the the instruction that describes the task: ### Input: Format packet to be sent. ### Response: def format_packet(command): """Format packet to be sent.""" frame_header = b"\xaa" verify = b"\x0b" send_delim = b"\xbb" return frame_header + command.ljust(17, b"\x00") ...
def xmoe2_v1_l4k_local_only(): """With sequence length 4096.""" hparams = xmoe2_v1_l4k() hparams.decoder_layers = [ "local_att" if l == "att" else l for l in hparams.decoder_layers] return hparams
With sequence length 4096.
Below is the the instruction that describes the task: ### Input: With sequence length 4096. ### Response: def xmoe2_v1_l4k_local_only(): """With sequence length 4096.""" hparams = xmoe2_v1_l4k() hparams.decoder_layers = [ "local_att" if l == "att" else l for l in hparams.decoder_layers] return hparam...
def hmget(self, hashkey, keys, *args): """Emulate hmget.""" redis_hash = self._get_hash(hashkey, 'HMGET') attributes = self._list_or_args(keys, args) return [redis_hash.get(self._encode(attribute)) for attribute in attributes]
Emulate hmget.
Below is the the instruction that describes the task: ### Input: Emulate hmget. ### Response: def hmget(self, hashkey, keys, *args): """Emulate hmget.""" redis_hash = self._get_hash(hashkey, 'HMGET') attributes = self._list_or_args(keys, args) return [redis_hash.get(self._encode(at...
def start(self, skip_choose=False, fixed_workspace_dir=None): """ Start the application. Looks for workspace_location persistent string. If it doesn't find it, uses a default workspace location. Then checks to see if that workspace exists. If not and if skip_cho...
Start the application. Looks for workspace_location persistent string. If it doesn't find it, uses a default workspace location. Then checks to see if that workspace exists. If not and if skip_choose has not been set to True, asks the user for a workspace location. User...
Below is the the instruction that describes the task: ### Input: Start the application. Looks for workspace_location persistent string. If it doesn't find it, uses a default workspace location. Then checks to see if that workspace exists. If not and if skip_choose has not been ...
def eval_objfn(self): """Compute components of objective function as well as total contribution to objective function. """ if self.opt['fEvalX']: rnn = np.sum(self.ss) else: rnn = sp.norm_nuclear(self.obfn_fvar()) rl1 = np.sum(np.abs(self.obfn_gva...
Compute components of objective function as well as total contribution to objective function.
Below is the the instruction that describes the task: ### Input: Compute components of objective function as well as total contribution to objective function. ### Response: def eval_objfn(self): """Compute components of objective function as well as total contribution to objective function....
def _query_for_individual_audio(self, run, tag, sample, index): """Builds a URL for accessing the specified audio. This should be kept in sync with _serve_audio_metadata. Note that the URL is *not* guaranteed to always return the same audio, since audio may be unloaded from the reservoir as new audio e...
Builds a URL for accessing the specified audio. This should be kept in sync with _serve_audio_metadata. Note that the URL is *not* guaranteed to always return the same audio, since audio may be unloaded from the reservoir as new audio entries come in. Args: run: The name of the run. tag: T...
Below is the the instruction that describes the task: ### Input: Builds a URL for accessing the specified audio. This should be kept in sync with _serve_audio_metadata. Note that the URL is *not* guaranteed to always return the same audio, since audio may be unloaded from the reservoir as new audio ent...
def parse_metric_family(self, response, scraper_config): """ Parse the MetricFamily from a valid requests.Response object to provide a MetricFamily object (see [0]) The text format uses iter_lines() generator. :param response: requests.Response :return: core.Metric """ ...
Parse the MetricFamily from a valid requests.Response object to provide a MetricFamily object (see [0]) The text format uses iter_lines() generator. :param response: requests.Response :return: core.Metric
Below is the the instruction that describes the task: ### Input: Parse the MetricFamily from a valid requests.Response object to provide a MetricFamily object (see [0]) The text format uses iter_lines() generator. :param response: requests.Response :return: core.Metric ### Response: def par...
def get_extended_summary(self, s, base=None): """Get the extended summary from a docstring This here is the extended summary Parameters ---------- s: str The docstring to use base: str or None A key under which the summary shall be stored in the ...
Get the extended summary from a docstring This here is the extended summary Parameters ---------- s: str The docstring to use base: str or None A key under which the summary shall be stored in the :attr:`params` attribute. If not None, the su...
Below is the the instruction that describes the task: ### Input: Get the extended summary from a docstring This here is the extended summary Parameters ---------- s: str The docstring to use base: str or None A key under which the summary shall be st...
def convert_meas(direction, Rec): """ converts measurments tables from magic 2 to 3 (direction=magic3) or from model 3 to 2.5 (direction=magic2) [not available] """ if direction == 'magic3': columns = meas_magic2_2_magic3_map MeasRec = {} for key in columns: if ke...
converts measurments tables from magic 2 to 3 (direction=magic3) or from model 3 to 2.5 (direction=magic2) [not available]
Below is the the instruction that describes the task: ### Input: converts measurments tables from magic 2 to 3 (direction=magic3) or from model 3 to 2.5 (direction=magic2) [not available] ### Response: def convert_meas(direction, Rec): """ converts measurments tables from magic 2 to 3 (direction=magic3...
def log_instantiation(LOGGER, classname, args, forbidden, with_date=False): ''' Log the instantiation of an object to the given logger. :LOGGER: A logger to log to. Please see module "logging". :classname: The name of the class that is being instantiated. :args: A dictionary of arguments pa...
Log the instantiation of an object to the given logger. :LOGGER: A logger to log to. Please see module "logging". :classname: The name of the class that is being instantiated. :args: A dictionary of arguments passed to the instantiation, which will be logged on debug level. :forbidden: ...
Below is the the instruction that describes the task: ### Input: Log the instantiation of an object to the given logger. :LOGGER: A logger to log to. Please see module "logging". :classname: The name of the class that is being instantiated. :args: A dictionary of arguments passed to the instant...
def listar_permissao(self, nome_equipamento, nome_interface): """List all VLANS having communication permission to trunk from a port in switch. Run script 'configurador'. :: The value of 'stdout' key of return dictionary can have a list of numbers or number intervals of VL...
List all VLANS having communication permission to trunk from a port in switch. Run script 'configurador'. :: The value of 'stdout' key of return dictionary can have a list of numbers or number intervals of VLAN´s, comma separated. Examples of possible returns of 'stdout' below: ...
Below is the the instruction that describes the task: ### Input: List all VLANS having communication permission to trunk from a port in switch. Run script 'configurador'. :: The value of 'stdout' key of return dictionary can have a list of numbers or number intervals of VLAN´s...
def load_ner_model(lang="en", version="2"): """Return a named entity extractor parameters for `lang` and of version `version` Args: lang (string): language code. version (string): version of the parameters to be used. """ src_dir = "ner{}".format(version) p = locate_resource(src_dir, lang) fh = _op...
Return a named entity extractor parameters for `lang` and of version `version` Args: lang (string): language code. version (string): version of the parameters to be used.
Below is the the instruction that describes the task: ### Input: Return a named entity extractor parameters for `lang` and of version `version` Args: lang (string): language code. version (string): version of the parameters to be used. ### Response: def load_ner_model(lang="en", version="2"): """Retur...
def run_false_positive_experiment_correlation(seed, num_neurons = 1, a = 32, dim = 4000, num_samples = 20000, ...
Run an experiment to test the false positive rate based on the correlation between bits. Correlation is measured as the average pairwise correlation between bits for each pattern in the data (across all of the data). To generate the results shown in the false positive vs. correlation figure, we used the param...
Below is the the instruction that describes the task: ### Input: Run an experiment to test the false positive rate based on the correlation between bits. Correlation is measured as the average pairwise correlation between bits for each pattern in the data (across all of the data). To generate the results sh...
def _tokenize(self, text): """Tokenizes a piece of text.""" text = self._clean_text(text) # This was added on November 1st, 2018 for the multilingual and Chinese # models. This is also applied to the English models now, but it doesn't # matter since the English models were not t...
Tokenizes a piece of text.
Below is the the instruction that describes the task: ### Input: Tokenizes a piece of text. ### Response: def _tokenize(self, text): """Tokenizes a piece of text.""" text = self._clean_text(text) # This was added on November 1st, 2018 for the multilingual and Chinese # models. This...
def getHostDetailsByIndex(self, index, lanInterfaceId=1, timeout=1): """Execute GetGenericHostEntry action to get detailed information's of a connected host. :param index: the index of the host :param int lanInterfaceId: the id of the LAN interface :param float timeout: the timeout to w...
Execute GetGenericHostEntry action to get detailed information's of a connected host. :param index: the index of the host :param int lanInterfaceId: the id of the LAN interface :param float timeout: the timeout to wait for the action to be executed :return: the detailed information's of...
Below is the the instruction that describes the task: ### Input: Execute GetGenericHostEntry action to get detailed information's of a connected host. :param index: the index of the host :param int lanInterfaceId: the id of the LAN interface :param float timeout: the timeout to wait for the...
def stationary_distribution(H, pi=None, P=None): """Computes the stationary distribution of a random walk on the given hypergraph using the iterative approach explained in the paper: Aurelien Ducournau, Alain Bretto, Random walks in directed hypergraphs and application to semi-supervised image segmentat...
Computes the stationary distribution of a random walk on the given hypergraph using the iterative approach explained in the paper: Aurelien Ducournau, Alain Bretto, Random walks in directed hypergraphs and application to semi-supervised image segmentation, Computer Vision and Image Understanding, Volume...
Below is the the instruction that describes the task: ### Input: Computes the stationary distribution of a random walk on the given hypergraph using the iterative approach explained in the paper: Aurelien Ducournau, Alain Bretto, Random walks in directed hypergraphs and application to semi-supervised im...
def load(package, prefix, offset=0, limit=1000): """ Load lines from the log file with pagination support. """ logs = package.all(LogFile, unicode(prefix)) logs = sorted(logs, key=lambda l: l.name, reverse=True) seen = 0 record = None tmp = tempfile.NamedTemporaryFile(suffix='.log') for log ...
Load lines from the log file with pagination support.
Below is the the instruction that describes the task: ### Input: Load lines from the log file with pagination support. ### Response: def load(package, prefix, offset=0, limit=1000): """ Load lines from the log file with pagination support. """ logs = package.all(LogFile, unicode(prefix)) logs = sorted(...
def _authenticate(self): """Determine the hosted zone id for the domain.""" try: hosted_zones = self.r53_client.list_hosted_zones_by_name()[ 'HostedZones' ] hosted_zone = next( hz for hz in hosted_zones if self.filter_zo...
Determine the hosted zone id for the domain.
Below is the the instruction that describes the task: ### Input: Determine the hosted zone id for the domain. ### Response: def _authenticate(self): """Determine the hosted zone id for the domain.""" try: hosted_zones = self.r53_client.list_hosted_zones_by_name()[ 'Hoste...
def rotate_capture_handler_log(self, name): ''' Force a rotation of a handler's log file Args: name: The name of the handler who's log file should be rotated. ''' for sc_key, sc in self._stream_capturers.iteritems(): for h in sc[0].capture_handler...
Force a rotation of a handler's log file Args: name: The name of the handler who's log file should be rotated.
Below is the the instruction that describes the task: ### Input: Force a rotation of a handler's log file Args: name: The name of the handler who's log file should be rotated. ### Response: def rotate_capture_handler_log(self, name): ''' Force a rotation of a handler's ...