code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def forward(node, analysis): """Perform a given analysis on all functions within an AST.""" if not isinstance(analysis, Forward): raise TypeError('not a valid forward analysis object') for succ in gast.walk(node): if isinstance(succ, gast.FunctionDef): cfg_obj = CFG.build_cfg(succ) analysis.vi...
Perform a given analysis on all functions within an AST.
Below is the the instruction that describes the task: ### Input: Perform a given analysis on all functions within an AST. ### Response: def forward(node, analysis): """Perform a given analysis on all functions within an AST.""" if not isinstance(analysis, Forward): raise TypeError('not a valid forward anal...
def _get_sr(name=None, session=None): ''' Get XEN sr (storage repo) object reference ''' if session is None: session = _get_session() srs = session.xenapi.SR.get_by_name_label(name) if len(srs) == 1: return srs[0] return None
Get XEN sr (storage repo) object reference
Below is the the instruction that describes the task: ### Input: Get XEN sr (storage repo) object reference ### Response: def _get_sr(name=None, session=None): ''' Get XEN sr (storage repo) object reference ''' if session is None: session = _get_session() srs = session.xenapi.SR.get_by_...
def get_raw_fixed_block(self, unbuffered=False): """Get the raw "fixed block" of settings and min/max data.""" if unbuffered or not self._fixed_block: self._fixed_block = self._read_fixed_block() return self._fixed_block
Get the raw "fixed block" of settings and min/max data.
Below is the the instruction that describes the task: ### Input: Get the raw "fixed block" of settings and min/max data. ### Response: def get_raw_fixed_block(self, unbuffered=False): """Get the raw "fixed block" of settings and min/max data.""" if unbuffered or not self._fixed_block: s...
def fit(self, x0=None, distribution='lognormal', n=None, **kwargs): '''Incomplete method to fit experimental values to a curve. It is very hard to get good initial guesses, which are really required for this. Differential evolution is promissing. This API is likely to change in the futur...
Incomplete method to fit experimental values to a curve. It is very hard to get good initial guesses, which are really required for this. Differential evolution is promissing. This API is likely to change in the future.
Below is the the instruction that describes the task: ### Input: Incomplete method to fit experimental values to a curve. It is very hard to get good initial guesses, which are really required for this. Differential evolution is promissing. This API is likely to change in the future. ### Res...
def save_report( self, name, address=True): """ Save Compare report in .comp (flat file format). :param name: filename :type name : str :param address: flag for address return :type address : bool :return: saving Status as dict...
Save Compare report in .comp (flat file format). :param name: filename :type name : str :param address: flag for address return :type address : bool :return: saving Status as dict {"Status":bool , "Message":str}
Below is the the instruction that describes the task: ### Input: Save Compare report in .comp (flat file format). :param name: filename :type name : str :param address: flag for address return :type address : bool :return: saving Status as dict {"Status":bool , "Message":str...
def unset_iscsi_info(self): """Disable iSCSI boot option in UEFI boot mode. :raises: IloCommandNotSupportedInBiosError, if the system is in the BIOS boot mode. """ if(self._is_boot_mode_uefi()): iscsi_info = {'iSCSIConnection': 'Disabled'} self._...
Disable iSCSI boot option in UEFI boot mode. :raises: IloCommandNotSupportedInBiosError, if the system is in the BIOS boot mode.
Below is the the instruction that describes the task: ### Input: Disable iSCSI boot option in UEFI boot mode. :raises: IloCommandNotSupportedInBiosError, if the system is in the BIOS boot mode. ### Response: def unset_iscsi_info(self): """Disable iSCSI boot option in UEFI boot mod...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'notice_id') and self.notice_id is not None: _dict['notice_id'] = self.notice_id if hasattr(self, 'created') and self.created is not None: _dict['created'] = da...
Return a json dictionary representing this model.
Below is the the instruction that describes the task: ### Input: Return a json dictionary representing this model. ### Response: def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'notice_id') and self.notice_id is not None: _...
def predict_proba(self, a, b, **kwargs): """Evaluate a pair using the IGCI model. :param a: Input variable 1D :param b: Input variable 1D :param kwargs: {refMeasure: Scaling method (gaussian, integral or None), estimator: method used to evaluate the pairs (entrop...
Evaluate a pair using the IGCI model. :param a: Input variable 1D :param b: Input variable 1D :param kwargs: {refMeasure: Scaling method (gaussian, integral or None), estimator: method used to evaluate the pairs (entropy or integral)} :return: Return value of the...
Below is the the instruction that describes the task: ### Input: Evaluate a pair using the IGCI model. :param a: Input variable 1D :param b: Input variable 1D :param kwargs: {refMeasure: Scaling method (gaussian, integral or None), estimator: method used to evaluate ...
def upload(self, file_path, dataset=None, public=False): """Use this function to upload data to Knoema dataset.""" upload_status = self.upload_file(file_path) err_msg = 'Dataset has not been uploaded to the remote host' if not upload_status.successful: msg = '{}, becau...
Use this function to upload data to Knoema dataset.
Below is the the instruction that describes the task: ### Input: Use this function to upload data to Knoema dataset. ### Response: def upload(self, file_path, dataset=None, public=False): """Use this function to upload data to Knoema dataset.""" upload_status = self.upload_file(file_path) ...
def do_scan_all(self, line): """Call ScanAllObjects. Command syntax is: scan_all""" self.application.master.ScanAllObjects(opendnp3.GroupVariationID(2, 1), opendnp3.TaskConfig().Default())
Call ScanAllObjects. Command syntax is: scan_all
Below is the the instruction that describes the task: ### Input: Call ScanAllObjects. Command syntax is: scan_all ### Response: def do_scan_all(self, line): """Call ScanAllObjects. Command syntax is: scan_all""" self.application.master.ScanAllObjects(opendnp3.GroupVariationID(2, 1), opendnp3.TaskCo...
def handle_connack(self): """Handle incoming CONNACK command.""" self.logger.info("CONNACK reveived") ret, flags = self.in_packet.read_byte() if ret != NC.ERR_SUCCESS: self.logger.error("error read byte") return ret # useful for v3.1.1 only ...
Handle incoming CONNACK command.
Below is the the instruction that describes the task: ### Input: Handle incoming CONNACK command. ### Response: def handle_connack(self): """Handle incoming CONNACK command.""" self.logger.info("CONNACK reveived") ret, flags = self.in_packet.read_byte() if ret != NC.ERR_SUCCESS: ...
def get_skos(self, id=None, uri=None, match=None): """ get the saved skos concept with given ID or via other methods... Note: it tries to guess what is being passed as above """ if not id and not uri and not match: return None if type(id) == type("string"):...
get the saved skos concept with given ID or via other methods... Note: it tries to guess what is being passed as above
Below is the the instruction that describes the task: ### Input: get the saved skos concept with given ID or via other methods... Note: it tries to guess what is being passed as above ### Response: def get_skos(self, id=None, uri=None, match=None): """ get the saved skos concept with given...
def fix(self, value=None): """ Fix all instances of this variable to a value if provided or to their current value otherwise. Args: value: value to be set. """ if value is None: self._impl.fix() else: self._impl.fix(value)
Fix all instances of this variable to a value if provided or to their current value otherwise. Args: value: value to be set.
Below is the the instruction that describes the task: ### Input: Fix all instances of this variable to a value if provided or to their current value otherwise. Args: value: value to be set. ### Response: def fix(self, value=None): """ Fix all instances of this variable ...
def __diff_dict(self, level, parents_ids=frozenset({}), print_as_attribute=False, override=False, override_t1=None, override_t2=None): """Difference of 2 dictionaries""" if override: ...
Difference of 2 dictionaries
Below is the the instruction that describes the task: ### Input: Difference of 2 dictionaries ### Response: def __diff_dict(self, level, parents_ids=frozenset({}), print_as_attribute=False, override=False, override_...
def _init_filename(self, filename=None, ext=None): """Initialize the current filename :attr:`FileUtils.real_filename` of the object. Bit of a hack. - The first invocation must have ``filename != None``; this will set a default filename with suffix :attr:`FileUtils.default_extension` ...
Initialize the current filename :attr:`FileUtils.real_filename` of the object. Bit of a hack. - The first invocation must have ``filename != None``; this will set a default filename with suffix :attr:`FileUtils.default_extension` unless another one was supplied. - Subseque...
Below is the the instruction that describes the task: ### Input: Initialize the current filename :attr:`FileUtils.real_filename` of the object. Bit of a hack. - The first invocation must have ``filename != None``; this will set a default filename with suffix :attr:`FileUtils.default_exte...
def _create_user_posts_table(self): """ Creates the table to store association info between user and blog posts. :return: """ with self._engine.begin() as conn: user_posts_table_name = self._table_name("user_posts") if not conn.dialect.has_table(co...
Creates the table to store association info between user and blog posts. :return:
Below is the the instruction that describes the task: ### Input: Creates the table to store association info between user and blog posts. :return: ### Response: def _create_user_posts_table(self): """ Creates the table to store association info between user and blog posts. ...
def signrawtransaction(self, rawtxhash, parent_tx_outputs=None, private_key=None): """signrawtransaction returns status and rawtxhash : rawtxhash - serialized transaction (hex) : parent_tx_outputs - outputs being spent by this transaction : private_key - a private key to sign this transa...
signrawtransaction returns status and rawtxhash : rawtxhash - serialized transaction (hex) : parent_tx_outputs - outputs being spent by this transaction : private_key - a private key to sign this transaction with
Below is the the instruction that describes the task: ### Input: signrawtransaction returns status and rawtxhash : rawtxhash - serialized transaction (hex) : parent_tx_outputs - outputs being spent by this transaction : private_key - a private key to sign this transaction with ### Response: ...
def metadata_matches(self, query={}): """ Returns key matches to metadata This will check every key in query for a matching key in metadata returning true if every key is in metadata. query without keys return false. Args: query(object): metadata for matchi...
Returns key matches to metadata This will check every key in query for a matching key in metadata returning true if every key is in metadata. query without keys return false. Args: query(object): metadata for matching Returns: bool: Tru...
Below is the the instruction that describes the task: ### Input: Returns key matches to metadata This will check every key in query for a matching key in metadata returning true if every key is in metadata. query without keys return false. Args: query(object): metadata...
def get_dag_params(self) -> Dict[str, Any]: """ Merges default config with dag config, sets dag_id, and extropolates dag_start_date :returns: dict of dag parameters """ try: dag_params: Dict[str, Any] = utils.merge_configs(self.dag_config, self.default_config) ...
Merges default config with dag config, sets dag_id, and extropolates dag_start_date :returns: dict of dag parameters
Below is the the instruction that describes the task: ### Input: Merges default config with dag config, sets dag_id, and extropolates dag_start_date :returns: dict of dag parameters ### Response: def get_dag_params(self) -> Dict[str, Any]: """ Merges default config with dag config, sets da...
def delete_file(self, fname, multiple, yes_to_all): """Delete file""" if multiple: buttons = QMessageBox.Yes|QMessageBox.YesToAll| \ QMessageBox.No|QMessageBox.Cancel else: buttons = QMessageBox.Yes|QMessageBox.No if yes_to_all is None...
Delete file
Below is the the instruction that describes the task: ### Input: Delete file ### Response: def delete_file(self, fname, multiple, yes_to_all): """Delete file""" if multiple: buttons = QMessageBox.Yes|QMessageBox.YesToAll| \ QMessageBox.No|QMessageBox.Cancel ...
def process_line(self, record): "Process a single record. This assumes only a single sample output." cleaned = [] for key in self.vcf_fields: out = self.process_column(key, getattr(record, key)) if isinstance(out, (list, tuple)): cleaned.extend(out) ...
Process a single record. This assumes only a single sample output.
Below is the the instruction that describes the task: ### Input: Process a single record. This assumes only a single sample output. ### Response: def process_line(self, record): "Process a single record. This assumes only a single sample output." cleaned = [] for key in self.vcf_fields: ...
async def available_ssids() -> List[Dict[str, Any]]: """ List the visible (broadcasting SSID) wireless networks. Returns a list of the SSIDs. They may contain spaces and should be escaped if later passed to a shell. """ fields = ['ssid', 'signal', 'active', 'security'] cmd = ['--terse', ...
List the visible (broadcasting SSID) wireless networks. Returns a list of the SSIDs. They may contain spaces and should be escaped if later passed to a shell.
Below is the the instruction that describes the task: ### Input: List the visible (broadcasting SSID) wireless networks. Returns a list of the SSIDs. They may contain spaces and should be escaped if later passed to a shell. ### Response: async def available_ssids() -> List[Dict[str, Any]]: """ List th...
def scopes(self, **kwargs): """Scopes associated to the team.""" return self._client.scopes(team=self.id, **kwargs)
Scopes associated to the team.
Below is the the instruction that describes the task: ### Input: Scopes associated to the team. ### Response: def scopes(self, **kwargs): """Scopes associated to the team.""" return self._client.scopes(team=self.id, **kwargs)
def head(self, n=None, **kwargs): """ Return the first n rows. Execute at once. :param n: :return: result frame :rtype: :class:`odps.df.backends.frame.ResultFrame` """ if n is None: n = options.display.max_rows return self._handle_delay_call('...
Return the first n rows. Execute at once. :param n: :return: result frame :rtype: :class:`odps.df.backends.frame.ResultFrame`
Below is the the instruction that describes the task: ### Input: Return the first n rows. Execute at once. :param n: :return: result frame :rtype: :class:`odps.df.backends.frame.ResultFrame` ### Response: def head(self, n=None, **kwargs): """ Return the first n rows. Execut...
def label_accuracy_score(label_trues, label_preds, n_class): """Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc """ hist = np.zeros((n_class, n_class)) for lt, lp in zip(label_trues, label_preds): hist += _fast_hist(lt.fla...
Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc
Below is the the instruction that describes the task: ### Input: Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc ### Response: def label_accuracy_score(label_trues, label_preds, n_class): """Returns accuracy score evaluation result. ...
def _create_filter_by(self): """Transform the json-server filter arguments to model-resource ones.""" filter_by = [] for name, values in request.args.copy().lists(): # copy.lists works in py2 and py3 if name not in _SKIPPED_ARGUMENTS: column = _re_column_name.search...
Transform the json-server filter arguments to model-resource ones.
Below is the the instruction that describes the task: ### Input: Transform the json-server filter arguments to model-resource ones. ### Response: def _create_filter_by(self): """Transform the json-server filter arguments to model-resource ones.""" filter_by = [] for name, values in request...
def search(self, ctype, level=None, category=None, assetId=None, defId=None, min_price=None, max_price=None, min_buy=None, max_buy=None, league=None, club=None, position=None, zone=None, nationality=None, rare=False, playStyle=None, start=0, page_size=itemsPerPage['transferM...
Prepare search request, send and return parsed data as a dict. :param ctype: [development / ? / ?] Card type. :param level: (optional) [?/?/gold] Card level. :param category: (optional) [fitness/?/?] Card category. :param assetId: (optional) Asset id. :param defId: (optional) De...
Below is the the instruction that describes the task: ### Input: Prepare search request, send and return parsed data as a dict. :param ctype: [development / ? / ?] Card type. :param level: (optional) [?/?/gold] Card level. :param category: (optional) [fitness/?/?] Card category. :pa...
def sde(self): """ Return the state space representation of the covariance. """ variance = float(self.variance.values) lengthscale = float(self.lengthscale) F = np.array(((-1.0/lengthscale,),)) L = np.array(((1.0,),)) Qc = np.array( ((2.0*variance/lengt...
Return the state space representation of the covariance.
Below is the the instruction that describes the task: ### Input: Return the state space representation of the covariance. ### Response: def sde(self): """ Return the state space representation of the covariance. """ variance = float(self.variance.values) lengthscale = float(...
def get_managers(self): """Get managers for the slave environments. """ if self._single_env: return None if not hasattr(self, '_managers'): self._managers = self.env.get_slave_managers() return self._managers
Get managers for the slave environments.
Below is the the instruction that describes the task: ### Input: Get managers for the slave environments. ### Response: def get_managers(self): """Get managers for the slave environments. """ if self._single_env: return None if not hasattr(self, '_managers'): ...
def _add_helpingmaterials(config, helping_file, helping_type): """Add helping materials to a project.""" try: project = find_project_by_short_name(config.project['short_name'], config.pbclient, config.all) ...
Add helping materials to a project.
Below is the the instruction that describes the task: ### Input: Add helping materials to a project. ### Response: def _add_helpingmaterials(config, helping_file, helping_type): """Add helping materials to a project.""" try: project = find_project_by_short_name(config.project['short_name'], ...
def decrypt_email(enc_email): """ The inverse of :func:`encrypt_email`. :param enc_email: The encrypted email address. """ aes = SimpleAES(flask.current_app.config["AES_KEY"]) return aes.decrypt(enc_email)
The inverse of :func:`encrypt_email`. :param enc_email: The encrypted email address.
Below is the the instruction that describes the task: ### Input: The inverse of :func:`encrypt_email`. :param enc_email: The encrypted email address. ### Response: def decrypt_email(enc_email): """ The inverse of :func:`encrypt_email`. :param enc_email: The encrypted email address...
def view_task_hazard(token, dstore): """ Display info about a given task. Here are a few examples of usage:: $ oq show task_hazard:0 # the fastest task $ oq show task_hazard:-1 # the slowest task """ tasks = set(dstore['task_info']) if 'source_data' not in dstore: return 'Missin...
Display info about a given task. Here are a few examples of usage:: $ oq show task_hazard:0 # the fastest task $ oq show task_hazard:-1 # the slowest task
Below is the the instruction that describes the task: ### Input: Display info about a given task. Here are a few examples of usage:: $ oq show task_hazard:0 # the fastest task $ oq show task_hazard:-1 # the slowest task ### Response: def view_task_hazard(token, dstore): """ Display info about ...
def optimal_marginal_branch_length(self, node, tol=1e-10): ''' calculate the marginal distribution of sequence states on both ends of the branch leading to node, Parameters ---------- node : PhyloTree.Clade TreeNode, attached to the branch. Returns ...
calculate the marginal distribution of sequence states on both ends of the branch leading to node, Parameters ---------- node : PhyloTree.Clade TreeNode, attached to the branch. Returns ------- branch_length : float branch length of the bra...
Below is the the instruction that describes the task: ### Input: calculate the marginal distribution of sequence states on both ends of the branch leading to node, Parameters ---------- node : PhyloTree.Clade TreeNode, attached to the branch. Returns ----...
def get_trap_definitions(): """Takes in no param as input to fetch SNMP TRAP definitions from HP IMC RESTFUL API :param None :return: object of type list containing the device asset details """ # checks to see if the imc credentials are already available if auth is None or url is None: s...
Takes in no param as input to fetch SNMP TRAP definitions from HP IMC RESTFUL API :param None :return: object of type list containing the device asset details
Below is the the instruction that describes the task: ### Input: Takes in no param as input to fetch SNMP TRAP definitions from HP IMC RESTFUL API :param None :return: object of type list containing the device asset details ### Response: def get_trap_definitions(): """Takes in no param as input to fetc...
def long_input(prompt='Multi-line input\n' + \ 'Enter EOF on a blank line to end ' + \ '(ctrl-D in *nix, ctrl-Z in windows)', maxlines = None, maxlength = None): """Get a multi-line string as input""" lines = [] print(prompt) lnum = 1 try: while True: ...
Get a multi-line string as input
Below is the the instruction that describes the task: ### Input: Get a multi-line string as input ### Response: def long_input(prompt='Multi-line input\n' + \ 'Enter EOF on a blank line to end ' + \ '(ctrl-D in *nix, ctrl-Z in windows)', maxlines = None, maxlength = None): """Get a mult...
def delete_notes(self, noteids): """Delete a note or notes :param noteids: The noteids to delete """ if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to th...
Delete a note or notes :param noteids: The noteids to delete
Below is the the instruction that describes the task: ### Input: Delete a note or notes :param noteids: The noteids to delete ### Response: def delete_notes(self, noteids): """Delete a note or notes :param noteids: The noteids to delete """ if self.standard_grant_type is...
def verify_subscription(request, ident): """ Verifies an unverified subscription and create or appends to an existing subscription. """ try: unverified = UnverifiedSubscription.objects.get(ident=ident) except UnverifiedSubscription.DoesNotExist: return respond('overseer/inva...
Verifies an unverified subscription and create or appends to an existing subscription.
Below is the the instruction that describes the task: ### Input: Verifies an unverified subscription and create or appends to an existing subscription. ### Response: def verify_subscription(request, ident): """ Verifies an unverified subscription and create or appends to an existing subscription. ...
def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not hav...
Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for
Below is the the instruction that describes the task: ### Input: Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Con...
def date_from_isoformat(isoformat_date): """Convert an ISO-8601 date into a `datetime.date` object. Argument: isoformat_date (str): a date in ISO-8601 format (YYYY-MM-DD) Returns: ~datetime.date: the object corresponding to the given ISO date. Raises: ValueError: when the date...
Convert an ISO-8601 date into a `datetime.date` object. Argument: isoformat_date (str): a date in ISO-8601 format (YYYY-MM-DD) Returns: ~datetime.date: the object corresponding to the given ISO date. Raises: ValueError: when the date could not be converted successfully. See A...
Below is the the instruction that describes the task: ### Input: Convert an ISO-8601 date into a `datetime.date` object. Argument: isoformat_date (str): a date in ISO-8601 format (YYYY-MM-DD) Returns: ~datetime.date: the object corresponding to the given ISO date. Raises: Valu...
def get_user(): """User information. .. note:: **Privacy note** A users IP address, user agent string, and user id (if logged in) is sent to a message queue, where it is stored for about 5 minutes. The information is used to: - Detect robot visits from the user agent string. ...
User information. .. note:: **Privacy note** A users IP address, user agent string, and user id (if logged in) is sent to a message queue, where it is stored for about 5 minutes. The information is used to: - Detect robot visits from the user agent string. - Generate an anonymi...
Below is the the instruction that describes the task: ### Input: User information. .. note:: **Privacy note** A users IP address, user agent string, and user id (if logged in) is sent to a message queue, where it is stored for about 5 minutes. The information is used to: - Detect ...
def dict_to_dataset(data, *, attrs=None, library=None, coords=None, dims=None): """Convert a dictionary of numpy arrays to an xarray.Dataset. Parameters ---------- data : dict[str] -> ndarray Data to convert. Keys are variable names. attrs : dict Json serializable metadata to attach...
Convert a dictionary of numpy arrays to an xarray.Dataset. Parameters ---------- data : dict[str] -> ndarray Data to convert. Keys are variable names. attrs : dict Json serializable metadata to attach to the dataset, in addition to defaults. library : module Library used for...
Below is the the instruction that describes the task: ### Input: Convert a dictionary of numpy arrays to an xarray.Dataset. Parameters ---------- data : dict[str] -> ndarray Data to convert. Keys are variable names. attrs : dict Json serializable metadata to attach to the dataset, i...
def transform_and_attach(self, image_list, func, show=True): """ Displays the transformed (combined) version of the cross-sections from each image, (same slice and dimension). So if you input n>=1 images, ...
Displays the transformed (combined) version of the cross-sections from each image, (same slice and dimension). So if you input n>=1 images, n slices are obtained from each image, which are passed to the func (callable) provided, and the result will be displayed in the corresponding c...
Below is the the instruction that describes the task: ### Input: Displays the transformed (combined) version of the cross-sections from each image, (same slice and dimension). So if you input n>=1 images, n slices are obtained from each image, which are passed to the func (callable) provided...
def group_update(auth=None, **kwargs): ''' Update a group CLI Example: .. code-block:: bash salt '*' keystoneng.group_update name=group1 description='new description' salt '*' keystoneng.group_create name=group2 domain_id=b62e76fbeeff4e8fb77073f591cf211e new_name=newgroupname ...
Update a group CLI Example: .. code-block:: bash salt '*' keystoneng.group_update name=group1 description='new description' salt '*' keystoneng.group_create name=group2 domain_id=b62e76fbeeff4e8fb77073f591cf211e new_name=newgroupname salt '*' keystoneng.group_create name=0e4febc2a5ab4...
Below is the the instruction that describes the task: ### Input: Update a group CLI Example: .. code-block:: bash salt '*' keystoneng.group_update name=group1 description='new description' salt '*' keystoneng.group_create name=group2 domain_id=b62e76fbeeff4e8fb77073f591cf211e new_name=new...
def list_actions(cls): """Get a list of exposed actions that are callable via the ``do_action()`` method.""" # Make sure these are always at the beginning of the list actions = ['start', 'stop', 'restart', 'status'] # Iterate over the instance attributes checking for actions that...
Get a list of exposed actions that are callable via the ``do_action()`` method.
Below is the the instruction that describes the task: ### Input: Get a list of exposed actions that are callable via the ``do_action()`` method. ### Response: def list_actions(cls): """Get a list of exposed actions that are callable via the ``do_action()`` method.""" # Make sure the...
def _updateMinDutyCycles(self): """ Updates the minimum duty cycles defining normal activity for a column. A column with activity duty cycle below this minimum threshold is boosted. """ if self._globalInhibition or self._inhibitionRadius > self._numInputs: self._updateMinDutyCyclesGlobal() ...
Updates the minimum duty cycles defining normal activity for a column. A column with activity duty cycle below this minimum threshold is boosted.
Below is the the instruction that describes the task: ### Input: Updates the minimum duty cycles defining normal activity for a column. A column with activity duty cycle below this minimum threshold is boosted. ### Response: def _updateMinDutyCycles(self): """ Updates the minimum duty cycles defining n...
def resolve(self, targets, compile_classpath, sources, javadoc, executor): """ This is the core function for coursier resolve. Validation strategy: 1. All targets are going through the `invalidated` to get fingerprinted in the target level. No cache is fetched at this stage because it is disabl...
This is the core function for coursier resolve. Validation strategy: 1. All targets are going through the `invalidated` to get fingerprinted in the target level. No cache is fetched at this stage because it is disabled. 2. Once each target is fingerprinted, we combine them into a `VersionedTargetSe...
Below is the the instruction that describes the task: ### Input: This is the core function for coursier resolve. Validation strategy: 1. All targets are going through the `invalidated` to get fingerprinted in the target level. No cache is fetched at this stage because it is disabled. 2. Once ea...
def valid_path(path): ''' Check if an entry in the class path exists as either a directory or a file ''' # check if the suffic of classpath suffix exists as directory if path.endswith('*'): Log.debug('Checking classpath entry suffix as directory: %s', path[:-1]) if os.path.isdir(path[:-1]): retu...
Check if an entry in the class path exists as either a directory or a file
Below is the the instruction that describes the task: ### Input: Check if an entry in the class path exists as either a directory or a file ### Response: def valid_path(path): ''' Check if an entry in the class path exists as either a directory or a file ''' # check if the suffic of classpath suffix exists...
async def fetchone(self): """ Fetch next row """ self._check_executed() row = await self._read_next() if row is None: return self._rownumber += 1 return row
Fetch next row
Below is the the instruction that describes the task: ### Input: Fetch next row ### Response: async def fetchone(self): """ Fetch next row """ self._check_executed() row = await self._read_next() if row is None: return self._rownumber += 1 return row
def load_module(self, fullname): """Load a module if its name starts with :code:`self.group` and is registered.""" if fullname in sys.modules: return sys.modules[fullname] end_name = fullname[len(self._group_with_dot):] for entry_point in iter_entry_points(group=self.group, n...
Load a module if its name starts with :code:`self.group` and is registered.
Below is the the instruction that describes the task: ### Input: Load a module if its name starts with :code:`self.group` and is registered. ### Response: def load_module(self, fullname): """Load a module if its name starts with :code:`self.group` and is registered.""" if fullname in sys.modules: ...
def circle(radius=None, center=None, **kwargs): """ Create a Path2D containing a single or multiple rectangles with the specified bounds. Parameters -------------- bounds : (2, 2) float, or (m, 2, 2) float Minimum XY, Maximum XY Returns ------------- rect : Path2D Path ...
Create a Path2D containing a single or multiple rectangles with the specified bounds. Parameters -------------- bounds : (2, 2) float, or (m, 2, 2) float Minimum XY, Maximum XY Returns ------------- rect : Path2D Path containing specified rectangles
Below is the the instruction that describes the task: ### Input: Create a Path2D containing a single or multiple rectangles with the specified bounds. Parameters -------------- bounds : (2, 2) float, or (m, 2, 2) float Minimum XY, Maximum XY Returns ------------- rect : Path2D ...
def _get_nailgun_client(self, jvm_options, classpath, stdout, stderr, stdin): """This (somewhat unfortunately) is the main entrypoint to this class via the Runner. It handles creation of the running nailgun server as well as creation of the client.""" classpath = self._nailgun_classpath + classpath n...
This (somewhat unfortunately) is the main entrypoint to this class via the Runner. It handles creation of the running nailgun server as well as creation of the client.
Below is the the instruction that describes the task: ### Input: This (somewhat unfortunately) is the main entrypoint to this class via the Runner. It handles creation of the running nailgun server as well as creation of the client. ### Response: def _get_nailgun_client(self, jvm_options, classpath, stdout,...
def readObject(self): """read object""" try: _, res = self._read_and_exec_opcode(ident=0) position_bak = self.object_stream.tell() the_rest = self.object_stream.read() if len(the_rest): log_error("Warning!!!!: Stream still has %s bytes left.\ Enable debug mode of logging to see ...
read object
Below is the the instruction that describes the task: ### Input: read object ### Response: def readObject(self): """read object""" try: _, res = self._read_and_exec_opcode(ident=0) position_bak = self.object_stream.tell() the_rest = self.object_stream.read() if len(the_rest): ...
def _get_environment_details(python_bin: str) -> list: """Get information about packages in environment where packages get installed.""" cmd = "{} -m pipdeptree --json".format(python_bin) output = run_command(cmd, is_json=True).stdout return [_create_entry(entry) for entry in output]
Get information about packages in environment where packages get installed.
Below is the the instruction that describes the task: ### Input: Get information about packages in environment where packages get installed. ### Response: def _get_environment_details(python_bin: str) -> list: """Get information about packages in environment where packages get installed.""" cmd = "{} -m pi...
def save_attrgetter(self, obj): """attrgetter serializer""" class Dummy(object): def __init__(self, attrs, index=None): self.attrs = attrs self.index = index def __getattribute__(self, item): attrs = object.__getattribute__(self, "a...
attrgetter serializer
Below is the the instruction that describes the task: ### Input: attrgetter serializer ### Response: def save_attrgetter(self, obj): """attrgetter serializer""" class Dummy(object): def __init__(self, attrs, index=None): self.attrs = attrs self.index = in...
def send_sci(self, operation, target, payload, reply=None, synchronous=None, sync_timeout=None, cache=None, allow_offline=None, wait_for_reconnect=None): """Send SCI request to 1 or more targets :param str operation: The operation is one of {send_message, update_firmware, disconnect, q...
Send SCI request to 1 or more targets :param str operation: The operation is one of {send_message, update_firmware, disconnect, query_firmware_targets, file_system, data_service, and reboot} :param target: The device(s) to be targeted with this request :type target: :class:`~.Target...
Below is the the instruction that describes the task: ### Input: Send SCI request to 1 or more targets :param str operation: The operation is one of {send_message, update_firmware, disconnect, query_firmware_targets, file_system, data_service, and reboot} :param target: The device(s) to...
def classificationgroup(self): """List with (subject group ID, number of documents)-tuples.""" path = ['author-profile', 'classificationgroup', 'classifications', 'classification'] out = [(item['$'], item['@frequency']) for item in listify(chained_get(self._json, p...
List with (subject group ID, number of documents)-tuples.
Below is the the instruction that describes the task: ### Input: List with (subject group ID, number of documents)-tuples. ### Response: def classificationgroup(self): """List with (subject group ID, number of documents)-tuples.""" path = ['author-profile', 'classificationgroup', 'classifications',...
def inject_instance(self, classkey=None, allow_override=False, verbose=VERBOSE_CLASS, strict=True): """ Injects an instance (self) of type (classkey) with all functions registered to (classkey) call this in the __init__ class function Args: self: the class instance ...
Injects an instance (self) of type (classkey) with all functions registered to (classkey) call this in the __init__ class function Args: self: the class instance classkey: key for a class, preferably the class type itself, but it doesnt have to be SeeAlso: make_cla...
Below is the the instruction that describes the task: ### Input: Injects an instance (self) of type (classkey) with all functions registered to (classkey) call this in the __init__ class function Args: self: the class instance classkey: key for a class, preferably the class type itself...
def _coords2vec(self, coords): """ Converts from sky coordinates to unit vectors. Before conversion to unit vectors, the coordiantes are transformed to the coordinate system used internally by the :obj:`UnstructuredDustMap`, which can be set during initialization of the class. ...
Converts from sky coordinates to unit vectors. Before conversion to unit vectors, the coordiantes are transformed to the coordinate system used internally by the :obj:`UnstructuredDustMap`, which can be set during initialization of the class. Args: coords (:obj:`astropy.coor...
Below is the the instruction that describes the task: ### Input: Converts from sky coordinates to unit vectors. Before conversion to unit vectors, the coordiantes are transformed to the coordinate system used internally by the :obj:`UnstructuredDustMap`, which can be set during initializatio...
def _make_request_to_broker(self, broker, requestId, request, **kwArgs): """Send a request to the specified broker.""" def _timeout_request(broker, requestId): """The time we allotted for the request expired, cancel it.""" try: # FIXME: This should be done by call...
Send a request to the specified broker.
Below is the the instruction that describes the task: ### Input: Send a request to the specified broker. ### Response: def _make_request_to_broker(self, broker, requestId, request, **kwArgs): """Send a request to the specified broker.""" def _timeout_request(broker, requestId): """The t...
def OnRemoveReaders(self, removedreaders): """Called when a reader is removed. Removes the reader from the smartcard readers tree.""" self.mutex.acquire() try: parentnode = self.root for readertoremove in removedreaders: (childReader, cookie) = sel...
Called when a reader is removed. Removes the reader from the smartcard readers tree.
Below is the the instruction that describes the task: ### Input: Called when a reader is removed. Removes the reader from the smartcard readers tree. ### Response: def OnRemoveReaders(self, removedreaders): """Called when a reader is removed. Removes the reader from the smartcard readers tr...
def _fusion_to_dsl(tokens) -> FusionBase: """Convert a PyParsing data dictionary to a PyBEL fusion data dictionary. :param tokens: A PyParsing data dictionary representing a fusion :type tokens: ParseResult """ func = tokens[FUNCTION] fusion_dsl = FUNC_TO_FUSION_DSL[func] member_dsl = FUNC_...
Convert a PyParsing data dictionary to a PyBEL fusion data dictionary. :param tokens: A PyParsing data dictionary representing a fusion :type tokens: ParseResult
Below is the the instruction that describes the task: ### Input: Convert a PyParsing data dictionary to a PyBEL fusion data dictionary. :param tokens: A PyParsing data dictionary representing a fusion :type tokens: ParseResult ### Response: def _fusion_to_dsl(tokens) -> FusionBase: """Convert a PyPars...
def _get_geocoding(self, key, location): """Lookup the Google geocoding API information for `key`""" url = self._location_query_base % quote_plus(key) if self.api_key: url += "&key=%s" % self.api_key data = self._read_from_url(url) response = json.loads(data) ...
Lookup the Google geocoding API information for `key`
Below is the the instruction that describes the task: ### Input: Lookup the Google geocoding API information for `key` ### Response: def _get_geocoding(self, key, location): """Lookup the Google geocoding API information for `key`""" url = self._location_query_base % quote_plus(key) if sel...
def kernels_list(self, **kwargs): # noqa: E501 """List kernels # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernels_list(async_req=True) >>> result = thread.get() ...
List kernels # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernels_list(async_req=True) >>> result = thread.get() :param async_req bool :param int page: Page numbe...
Below is the the instruction that describes the task: ### Input: List kernels # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernels_list(async_req=True) >>> result = thread.get...
def addslashes(s, escaped_chars=None): """Add slashes for given characters. Default is for ``\`` and ``'``. :param s: string :param escaped_chars: list of characters to prefix with a slash ``\`` :return: string with slashed characters :rtype: str :Example: >>> addslashes("'") "...
Add slashes for given characters. Default is for ``\`` and ``'``. :param s: string :param escaped_chars: list of characters to prefix with a slash ``\`` :return: string with slashed characters :rtype: str :Example: >>> addslashes("'") "\\'"
Below is the the instruction that describes the task: ### Input: Add slashes for given characters. Default is for ``\`` and ``'``. :param s: string :param escaped_chars: list of characters to prefix with a slash ``\`` :return: string with slashed characters :rtype: str :Example: >>> ad...
def submit(recaptcha_response_field, secret_key, remoteip, verify_server=VERIFY_SERVER): """ Submits a reCAPTCHA request for verification. Returns RecaptchaResponse for the request recaptcha_response_field -- The value from the form secret_key -- your reCAPTCHA secr...
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse for the request recaptcha_response_field -- The value from the form secret_key -- your reCAPTCHA secret key remoteip -- the user's ip address
Below is the the instruction that describes the task: ### Input: Submits a reCAPTCHA request for verification. Returns RecaptchaResponse for the request recaptcha_response_field -- The value from the form secret_key -- your reCAPTCHA secret key remoteip -- the user's ip address ### Response: def s...
def _connect_docker(spec): """ Return ContextService arguments for a Docker connection. """ return { 'method': 'docker', 'kwargs': { 'username': spec.remote_user(), 'container': spec.remote_addr(), 'python_path': spec.python_path(), 'connec...
Return ContextService arguments for a Docker connection.
Below is the the instruction that describes the task: ### Input: Return ContextService arguments for a Docker connection. ### Response: def _connect_docker(spec): """ Return ContextService arguments for a Docker connection. """ return { 'method': 'docker', 'kwargs': { 'u...
def form_invalid(self, form): '''Builds the JSON for the errors''' response = {self.errors_key: {}} response[self.non_field_errors_key] = form.non_field_errors() response.update(self.get_hidden_fields_errors(form)) for field in form.visible_fields(): if field.errors:...
Builds the JSON for the errors
Below is the the instruction that describes the task: ### Input: Builds the JSON for the errors ### Response: def form_invalid(self, form): '''Builds the JSON for the errors''' response = {self.errors_key: {}} response[self.non_field_errors_key] = form.non_field_errors() response.up...
def _extract_elements(self, tree, element_type): """ extracts all element of type `element_type from the `_ElementTree` representation of a SaltXML document and adds them to the corresponding `SaltDocument` attributes, i.e. `self.nodes`, `self.edges` and `self.layers`. P...
extracts all element of type `element_type from the `_ElementTree` representation of a SaltXML document and adds them to the corresponding `SaltDocument` attributes, i.e. `self.nodes`, `self.edges` and `self.layers`. Parameters ---------- tree : lxml.etree._ElementTree ...
Below is the the instruction that describes the task: ### Input: extracts all element of type `element_type from the `_ElementTree` representation of a SaltXML document and adds them to the corresponding `SaltDocument` attributes, i.e. `self.nodes`, `self.edges` and `self.layers`. P...
def get_gateway_id(self): """Return a unique id for the gateway.""" host, _ = self.server_address try: ip_address = ipaddress.ip_address(host) except ValueError: # Only hosts using ip address supports unique id. return None if ip_address.versio...
Return a unique id for the gateway.
Below is the the instruction that describes the task: ### Input: Return a unique id for the gateway. ### Response: def get_gateway_id(self): """Return a unique id for the gateway.""" host, _ = self.server_address try: ip_address = ipaddress.ip_address(host) except ValueE...
def from_pubkey(cls, pubkey, compressed=False, version=56, prefix=None): # Ensure this is a public key pubkey = PublicKey(pubkey) if compressed: pubkey = pubkey.compressed() else: pubkey = pubkey.uncompressed() """ Derive address using ``RIPEMD160(SHA256(...
Derive address using ``RIPEMD160(SHA256(x))``
Below is the the instruction that describes the task: ### Input: Derive address using ``RIPEMD160(SHA256(x))`` ### Response: def from_pubkey(cls, pubkey, compressed=False, version=56, prefix=None): # Ensure this is a public key pubkey = PublicKey(pubkey) if compressed: pubkey = ...
def add(self, variant, arch, image): """ Assign an :class:`.Image` object to variant and arch. :param variant: compose variant UID :type variant: str :param arch: compose architecture :type arch: str :param image: image :type image: :class:`....
Assign an :class:`.Image` object to variant and arch. :param variant: compose variant UID :type variant: str :param arch: compose architecture :type arch: str :param image: image :type image: :class:`.Image`
Below is the the instruction that describes the task: ### Input: Assign an :class:`.Image` object to variant and arch. :param variant: compose variant UID :type variant: str :param arch: compose architecture :type arch: str :param image: image :type image:...
def pipe_rename(context=None, _INPUT=None, conf=None, **kwargs): """An operator that renames or copies fields in the input source. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : { 'RULE': [ ...
An operator that renames or copies fields in the input source. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : { 'RULE': [ { 'op': {'value': 'rename or copy'}, ...
Below is the the instruction that describes the task: ### Input: An operator that renames or copies fields in the input source. Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : { 'RULE': [ ...
def dom_lt(graph): """Dominator algorithm from Lengauer-Tarjan""" def _dfs(v, n): semi[v] = n = n + 1 vertex[n] = label[v] = v ancestor[v] = 0 for w in graph.all_sucs(v): if not semi[w]: parent[w] = v n = _dfs(w, n) pred[w]...
Dominator algorithm from Lengauer-Tarjan
Below is the the instruction that describes the task: ### Input: Dominator algorithm from Lengauer-Tarjan ### Response: def dom_lt(graph): """Dominator algorithm from Lengauer-Tarjan""" def _dfs(v, n): semi[v] = n = n + 1 vertex[n] = label[v] = v ancestor[v] = 0 for w in gr...
def describe(name, tags=None, region=None, key=None, keyid=None, profile=None): ''' Return RDS instance details. CLI example:: salt myminion boto_rds.describe myrds ''' res = __salt__['boto_rds.exists'](name, tags, region, key, keyid, pro...
Return RDS instance details. CLI example:: salt myminion boto_rds.describe myrds
Below is the the instruction that describes the task: ### Input: Return RDS instance details. CLI example:: salt myminion boto_rds.describe myrds ### Response: def describe(name, tags=None, region=None, key=None, keyid=None, profile=None): ''' Return RDS instance details. CL...
def inference_q(self, next_action_arr): ''' Infernce Q-Value. Args: next_action_arr: `np.ndarray` of action. Returns: `np.ndarray` of Q-Values. ''' q_arr = next_action_arr.reshape((next_action_arr.shape[0], -1)) self._...
Infernce Q-Value. Args: next_action_arr: `np.ndarray` of action. Returns: `np.ndarray` of Q-Values.
Below is the the instruction that describes the task: ### Input: Infernce Q-Value. Args: next_action_arr: `np.ndarray` of action. Returns: `np.ndarray` of Q-Values. ### Response: def inference_q(self, next_action_arr): ''' Infernce Q-Val...
def format(args): """ %prog format oldagpfile newagpfile Reformat AGP file. --switch will replace the ids in the AGP file. """ from jcvi.formats.base import DictFile p = OptionParser(format.__doc__) p.add_option("--switchcomponent", help="Switch component id based on") ...
%prog format oldagpfile newagpfile Reformat AGP file. --switch will replace the ids in the AGP file.
Below is the the instruction that describes the task: ### Input: %prog format oldagpfile newagpfile Reformat AGP file. --switch will replace the ids in the AGP file. ### Response: def format(args): """ %prog format oldagpfile newagpfile Reformat AGP file. --switch will replace the ids in the AGP ...
def log(args, number=None, oneline=False, quiet=False): """Run a "git log ..." command, and return stdout args is anything which can be added after a normal "git log ..." it can be blank number, if true-ish, will be added as a "-n" option oneline, if true-ish, will add the "--oneline" option ...
Run a "git log ..." command, and return stdout args is anything which can be added after a normal "git log ..." it can be blank number, if true-ish, will be added as a "-n" option oneline, if true-ish, will add the "--oneline" option
Below is the the instruction that describes the task: ### Input: Run a "git log ..." command, and return stdout args is anything which can be added after a normal "git log ..." it can be blank number, if true-ish, will be added as a "-n" option oneline, if true-ish, will add the "--oneline" opt...
def y_subset(y, query=None, aux=None, subset=None, dropna=False, outcome='true', k=None, p=None, ascending=False, score='score', p_of='notnull'): """ Subset a model "y" dataframe Args: query: operates on y, or aux if present subset: takes a dataframe or index thereof and subsets...
Subset a model "y" dataframe Args: query: operates on y, or aux if present subset: takes a dataframe or index thereof and subsets to that dropna: means drop missing outcomes return: top k (count) or p (proportion) if specified p_of: specifies what the proportion is relative t...
Below is the the instruction that describes the task: ### Input: Subset a model "y" dataframe Args: query: operates on y, or aux if present subset: takes a dataframe or index thereof and subsets to that dropna: means drop missing outcomes return: top k (count) or p (proportion) i...
def toggle_settings( toolbar=False, nbname=False, hideprompt=False, kernellogo=False): """Toggle main notebook toolbar (e.g., buttons), filename, and kernel logo.""" toggle = '' if toolbar: toggle += 'div#maintoolbar {margin-left: 8px !important;}\n' toggle += '.toolbar.containe...
Toggle main notebook toolbar (e.g., buttons), filename, and kernel logo.
Below is the the instruction that describes the task: ### Input: Toggle main notebook toolbar (e.g., buttons), filename, and kernel logo. ### Response: def toggle_settings( toolbar=False, nbname=False, hideprompt=False, kernellogo=False): """Toggle main notebook toolbar (e.g., buttons), filename, ...
def setFontFamily(self, family): """ Sets the current font family to the inputed family. :param family | <str> """ self.blockSignals(True) self.editor().setFontFamily(family) self.blockSignals(False)
Sets the current font family to the inputed family. :param family | <str>
Below is the the instruction that describes the task: ### Input: Sets the current font family to the inputed family. :param family | <str> ### Response: def setFontFamily(self, family): """ Sets the current font family to the inputed family. :param ...
def wsgi(self, environ, start_response): """ The bottle WSGI-interface. """ try: environ['bottle.app'] = self request.bind(environ) response.bind() out = self._cast(self._handle(environ), request, response) # rfc2616 section 4.3 if ...
The bottle WSGI-interface.
Below is the the instruction that describes the task: ### Input: The bottle WSGI-interface. ### Response: def wsgi(self, environ, start_response): """ The bottle WSGI-interface. """ try: environ['bottle.app'] = self request.bind(environ) response.bind() ...
def init_account(self): """Setup a new GitHub account.""" ghuser = self.api.me() # Setup local access tokens to be used by the webhooks hook_token = ProviderToken.create_personal( 'github-webhook', self.user_id, scopes=['webhooks:event'], i...
Setup a new GitHub account.
Below is the the instruction that describes the task: ### Input: Setup a new GitHub account. ### Response: def init_account(self): """Setup a new GitHub account.""" ghuser = self.api.me() # Setup local access tokens to be used by the webhooks hook_token = ProviderToken.create_person...
def translate(srcCol, matching, replace): """A function translate any character in the `srcCol` by a character in `matching`. The characters in `replace` is corresponding to the characters in `matching`. The translate will happen when any character in the string matching with the character in the `match...
A function translate any character in the `srcCol` by a character in `matching`. The characters in `replace` is corresponding to the characters in `matching`. The translate will happen when any character in the string matching with the character in the `matching`. >>> spark.createDataFrame([('translate...
Below is the the instruction that describes the task: ### Input: A function translate any character in the `srcCol` by a character in `matching`. The characters in `replace` is corresponding to the characters in `matching`. The translate will happen when any character in the string matching with the charact...
def set_mesh(self, mesh, shift=None, is_time_reversal=True, is_mesh_symmetry=True, is_eigenvectors=False, is_gamma_center=False, run_immediately=True): """Phonon calculations on sampling mesh g...
Phonon calculations on sampling mesh grids Parameters ---------- mesh: array_like Mesh numbers along a, b, c axes. dtype='intc' shape=(3,) shift: array_like, optional, default None (no shift) Mesh shifts along a*, b*, c* axes with respect ...
Below is the the instruction that describes the task: ### Input: Phonon calculations on sampling mesh grids Parameters ---------- mesh: array_like Mesh numbers along a, b, c axes. dtype='intc' shape=(3,) shift: array_like, optional, default None (...
def table_formatter(self, dataframe, inc_header=1, inc_index=1): """Return a table formatter for the dataframe. Saves the user the need to import this class""" return TableFormatter(dataframe, inc_header=inc_header, inc_index=inc_index)
Return a table formatter for the dataframe. Saves the user the need to import this class
Below is the the instruction that describes the task: ### Input: Return a table formatter for the dataframe. Saves the user the need to import this class ### Response: def table_formatter(self, dataframe, inc_header=1, inc_index=1): """Return a table formatter for the dataframe. Saves the user the need to ...
def _prep_ssh( self, tgt, fun, arg=(), timeout=None, tgt_type='glob', kwarg=None, **kwargs): ''' Prepare the arguments ''' opts = copy.deepcopy(self.opts) opts.update(kwargs) i...
Prepare the arguments
Below is the the instruction that describes the task: ### Input: Prepare the arguments ### Response: def _prep_ssh( self, tgt, fun, arg=(), timeout=None, tgt_type='glob', kwarg=None, **kwargs): ''' Prepa...
def dump(self): """Print a formatted summary of the current solve state.""" from rez.utils.formatting import columnise rows = [] for i, phase in enumerate(self.phase_stack): rows.append((self._depth_label(i), phase.status, str(phase))) print "status: %s (%s)" % (sel...
Print a formatted summary of the current solve state.
Below is the the instruction that describes the task: ### Input: Print a formatted summary of the current solve state. ### Response: def dump(self): """Print a formatted summary of the current solve state.""" from rez.utils.formatting import columnise rows = [] for i, phase in enum...
def collation(self, collation): """Adds a :class:`~pymongo.collation.Collation` to this query. This option is only supported on MongoDB 3.4 and above. Raises :exc:`TypeError` if `collation` is not an instance of :class:`~pymongo.collation.Collation` or a ``dict``. Raises :exc:`...
Adds a :class:`~pymongo.collation.Collation` to this query. This option is only supported on MongoDB 3.4 and above. Raises :exc:`TypeError` if `collation` is not an instance of :class:`~pymongo.collation.Collation` or a ``dict``. Raises :exc:`~pymongo.errors.InvalidOperation` if this :...
Below is the the instruction that describes the task: ### Input: Adds a :class:`~pymongo.collation.Collation` to this query. This option is only supported on MongoDB 3.4 and above. Raises :exc:`TypeError` if `collation` is not an instance of :class:`~pymongo.collation.Collation` or a ``dic...
def gsea(data, gene_sets, cls, outdir='GSEA_', min_size=15, max_size=500, permutation_num=1000, weighted_score_type=1,permutation_type='gene_set', method='log2_ratio_of_classes', ascending=False, processes=1, figsize=(6.5,6), format='pdf', graph_num=20, no_plot=False, seed=None, verbose=False...
Run Gene Set Enrichment Analysis. :param data: Gene expression data table, Pandas DataFrame, gct file. :param gene_sets: Enrichr Library name or .gmt gene sets file or dict of gene sets. Same input with GSEA. :param cls: A list or a .cls file format required for GSEA. :param str outdir: Results output ...
Below is the the instruction that describes the task: ### Input: Run Gene Set Enrichment Analysis. :param data: Gene expression data table, Pandas DataFrame, gct file. :param gene_sets: Enrichr Library name or .gmt gene sets file or dict of gene sets. Same input with GSEA. :param cls: A list or a .cls ...
def linear_gradient(start_hex, finish_hex, n=10): """ Interpolates the color gradient between to hex colors """ s = hex2rgb(start_hex) f = hex2rgb(finish_hex) gradient = [s] for t in range(1, n): curr_vector = [int(s[j] + (float(t)/(n-1))*(f[j]-s[j])) for j in range(3)] gradi...
Interpolates the color gradient between to hex colors
Below is the the instruction that describes the task: ### Input: Interpolates the color gradient between to hex colors ### Response: def linear_gradient(start_hex, finish_hex, n=10): """ Interpolates the color gradient between to hex colors """ s = hex2rgb(start_hex) f = hex2rgb(finish_hex) ...
def prepare_mergetable_sql(self, precursor=False, isobaric=False, probability=False, fdr=False, pep=False): """Dynamically build SQL query to generate entries for the multi-set merged protein and peptide tables. E.g. SELECT g.gene_acc, pc.channel_name, pc.amount_p...
Dynamically build SQL query to generate entries for the multi-set merged protein and peptide tables. E.g. SELECT g.gene_acc, pc.channel_name, pc.amount_psms_name, giq.quantvalue giq.amount_psms gfdr.fdr FROM genes AS g JOIN biosets AS bs JOIN gene_tables AS gt ON ...
Below is the the instruction that describes the task: ### Input: Dynamically build SQL query to generate entries for the multi-set merged protein and peptide tables. E.g. SELECT g.gene_acc, pc.channel_name, pc.amount_psms_name, giq.quantvalue giq.amount_psms gfdr.fdr FROM gen...
def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 """ try: self.match(path_info, method="--") except MethodNotAllowed as e: return e.valid_methods except HTTPException: ...
Returns the valid methods that match for a given path. .. versionadded:: 0.7
Below is the the instruction that describes the task: ### Input: Returns the valid methods that match for a given path. .. versionadded:: 0.7 ### Response: def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 ""...
def info_community(self,teamid): '''Get comunity info using a ID''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/standings.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/teamInfo.phtml?ti...
Get comunity info using a ID
Below is the the instruction that describes the task: ### Input: Get comunity info using a ID ### Response: def info_community(self,teamid): '''Get comunity info using a ID''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/st...
def import_words_from_file(self, inputfile: str, is_diceware: bool) -> None: """Import words for the wordlist from a given file. The file can have a single column with words or be diceware-like (two columns). Keyword argumen...
Import words for the wordlist from a given file. The file can have a single column with words or be diceware-like (two columns). Keyword arguments: inputfile -- A string with the path to the wordlist file to load, or the value 'internal' to load the internal one. is_dic...
Below is the the instruction that describes the task: ### Input: Import words for the wordlist from a given file. The file can have a single column with words or be diceware-like (two columns). Keyword arguments: inputfile -- A string with the path to the wordlist file to load, or ...
def warn(self, message, *args, **kwargs): """Send email and syslog by default ... """ self._log(logging.WARNING, message, *args, **kwargs)
Send email and syslog by default ...
Below is the the instruction that describes the task: ### Input: Send email and syslog by default ... ### Response: def warn(self, message, *args, **kwargs): """Send email and syslog by default ... """ self._log(logging.WARNING, message, *args, **kwargs)
def add_pypiper_args(parser, groups=("pypiper", ), args=None, required=None, all_args=False): """ Use this to add standardized pypiper arguments to your python pipeline. There are two ways to use `add_pypiper_args`: by specifying argument groups, or by specifying individual argumen...
Use this to add standardized pypiper arguments to your python pipeline. There are two ways to use `add_pypiper_args`: by specifying argument groups, or by specifying individual arguments. Specifying argument groups will add multiple arguments to your parser; these convenient argument groupings make it ...
Below is the the instruction that describes the task: ### Input: Use this to add standardized pypiper arguments to your python pipeline. There are two ways to use `add_pypiper_args`: by specifying argument groups, or by specifying individual arguments. Specifying argument groups will add multiple argum...
def profile_args(_args): """Return args for v1, v2, or v3 structure. Args: _args (dict): The args section from the profile. Returns: dict: A collapsed version of the args dict. """ # TODO: clean this up in a way that works for both py2/3 if ( ...
Return args for v1, v2, or v3 structure. Args: _args (dict): The args section from the profile. Returns: dict: A collapsed version of the args dict.
Below is the the instruction that describes the task: ### Input: Return args for v1, v2, or v3 structure. Args: _args (dict): The args section from the profile. Returns: dict: A collapsed version of the args dict. ### Response: def profile_args(_args): """Return ar...
def to_projection(self): """ Promote this column expression to a table projection """ roots = self._root_tables() if len(roots) > 1: raise com.RelationError( 'Cannot convert array expression ' 'involving multiple base table references '...
Promote this column expression to a table projection
Below is the the instruction that describes the task: ### Input: Promote this column expression to a table projection ### Response: def to_projection(self): """ Promote this column expression to a table projection """ roots = self._root_tables() if len(roots) > 1: ...
def set_mag_offsets_encode(self, target_system, target_component, mag_ofs_x, mag_ofs_y, mag_ofs_z): ''' Deprecated. Use MAV_CMD_PREFLIGHT_SET_SENSOR_OFFSETS instead. Set the magnetometer offsets target_system : System ID (uint8_t) ...
Deprecated. Use MAV_CMD_PREFLIGHT_SET_SENSOR_OFFSETS instead. Set the magnetometer offsets target_system : System ID (uint8_t) target_component : Component ID (uint8_t) mag_ofs_x : magnetometer X offset (int16_t) ...
Below is the the instruction that describes the task: ### Input: Deprecated. Use MAV_CMD_PREFLIGHT_SET_SENSOR_OFFSETS instead. Set the magnetometer offsets target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ...
def pop_min(self): """ Remove the minimum value and return it. """ if self.root is NULL: raise KeyError("pop from an empty blackjack") self.root, value = self.root.delete_min() self._len -= 1 return value
Remove the minimum value and return it.
Below is the the instruction that describes the task: ### Input: Remove the minimum value and return it. ### Response: def pop_min(self): """ Remove the minimum value and return it. """ if self.root is NULL: raise KeyError("pop from an empty blackjack") self.ro...