code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def group_by_count(iterable: List[Any], count: int, default_value: Any) -> List[List[Any]]: """ Takes a list and groups it into sublists of size ``count``, using ``default_value`` to pad the list at the end if the list is not divisable by ``count``. For example: >>> group_by_count([1, 2, 3, 4, 5, 6...
Takes a list and groups it into sublists of size ``count``, using ``default_value`` to pad the list at the end if the list is not divisable by ``count``. For example: >>> group_by_count([1, 2, 3, 4, 5, 6, 7], 3, 0) [[1, 2, 3], [4, 5, 6], [7, 0, 0]] This is a short method, but it's complicated and ...
Below is the the instruction that describes the task: ### Input: Takes a list and groups it into sublists of size ``count``, using ``default_value`` to pad the list at the end if the list is not divisable by ``count``. For example: >>> group_by_count([1, 2, 3, 4, 5, 6, 7], 3, 0) [[1, 2, 3], [4, 5, ...
def _maybe_run_callbacks(self, latest_block): """ Run the callbacks if there is at least one new block. The callbacks are executed only if there is a new block, otherwise the filters may try to poll for an inexisting block number and the Ethereum client can return an JSON-RPC error. ...
Run the callbacks if there is at least one new block. The callbacks are executed only if there is a new block, otherwise the filters may try to poll for an inexisting block number and the Ethereum client can return an JSON-RPC error.
Below is the the instruction that describes the task: ### Input: Run the callbacks if there is at least one new block. The callbacks are executed only if there is a new block, otherwise the filters may try to poll for an inexisting block number and the Ethereum client can return an JSON-RPC...
def write_classifier(self, clf): """ Writes classifier object to pickle file """ with open(os.path.join(self.repopath, 'classifier.pkl'), 'w') as fp: pickle.dump(clf, fp)
Writes classifier object to pickle file
Below is the the instruction that describes the task: ### Input: Writes classifier object to pickle file ### Response: def write_classifier(self, clf): """ Writes classifier object to pickle file """ with open(os.path.join(self.repopath, 'classifier.pkl'), 'w') as fp: pickle.dump(clf, ...
def _check_bam_contigs(in_bam, ref_file, config): """Ensure a pre-aligned BAM file matches the expected reference genome. """ # GATK allows chromosome M to be in multiple locations, skip checking it allowed_outoforder = ["chrM", "MT"] ref_contigs = [c.name for c in ref.file_contigs(ref_file, config)...
Ensure a pre-aligned BAM file matches the expected reference genome.
Below is the the instruction that describes the task: ### Input: Ensure a pre-aligned BAM file matches the expected reference genome. ### Response: def _check_bam_contigs(in_bam, ref_file, config): """Ensure a pre-aligned BAM file matches the expected reference genome. """ # GATK allows chromosome M to...
def delete_cache_settings(self, service_id, version_number, name): """Delete a specific cache settings object.""" content = self._fetch("/service/%s/version/%d/cache_settings/%s" % (service_id, version_number, name), method="DELETE") return self._status(content)
Delete a specific cache settings object.
Below is the the instruction that describes the task: ### Input: Delete a specific cache settings object. ### Response: def delete_cache_settings(self, service_id, version_number, name): """Delete a specific cache settings object.""" content = self._fetch("/service/%s/version/%d/cache_settings/%s" % (service_i...
def is_dir(self, follow_symlinks=True): """ Return True if this entry is a directory or a symbolic link pointing to a directory; return False if the entry is or points to any other kind of file, or if it doesn’t exist anymore. The result is cached on the os.DirEntry object. ...
Return True if this entry is a directory or a symbolic link pointing to a directory; return False if the entry is or points to any other kind of file, or if it doesn’t exist anymore. The result is cached on the os.DirEntry object. Args: follow_symlinks (bool): Follow symlin...
Below is the the instruction that describes the task: ### Input: Return True if this entry is a directory or a symbolic link pointing to a directory; return False if the entry is or points to any other kind of file, or if it doesn’t exist anymore. The result is cached on the os.DirEntry obj...
def _set_other(self): """Sets other specific sections""" # manage not setting if not mandatory for numpy if self.dst.style['in'] == 'numpydoc': if self.docs['in']['raw'] is not None: self.docs['out']['post'] = self.dst.numpydoc.get_raw_not_managed(self.docs['in']['raw...
Sets other specific sections
Below is the the instruction that describes the task: ### Input: Sets other specific sections ### Response: def _set_other(self): """Sets other specific sections""" # manage not setting if not mandatory for numpy if self.dst.style['in'] == 'numpydoc': if self.docs['in']['raw'] i...
def calculate_between_class_scatter_matrix(X, y): """Calculates the Between-Class Scatter matrix Parameters: ----------- X : array-like, shape (m, n) - the samples y : array-like, shape (m, ) - the class labels Returns: -------- between_class_scatter_matrix : array-like, shape (n, ...
Calculates the Between-Class Scatter matrix Parameters: ----------- X : array-like, shape (m, n) - the samples y : array-like, shape (m, ) - the class labels Returns: -------- between_class_scatter_matrix : array-like, shape (n, n)
Below is the the instruction that describes the task: ### Input: Calculates the Between-Class Scatter matrix Parameters: ----------- X : array-like, shape (m, n) - the samples y : array-like, shape (m, ) - the class labels Returns: -------- between_class_scatter_matrix : array-like...
def get_blast2(pdb_id, chain_id='A', output_form='HTML'): '''Alternative way to look up BLAST for a given PDB ID. This function is a wrapper for get_raw_blast and parse_blast Parameters ---------- pdb_id : string A 4 character string giving a pdb entry of interest chain_id : string ...
Alternative way to look up BLAST for a given PDB ID. This function is a wrapper for get_raw_blast and parse_blast Parameters ---------- pdb_id : string A 4 character string giving a pdb entry of interest chain_id : string A single character designating the chain ID of interest ...
Below is the the instruction that describes the task: ### Input: Alternative way to look up BLAST for a given PDB ID. This function is a wrapper for get_raw_blast and parse_blast Parameters ---------- pdb_id : string A 4 character string giving a pdb entry of interest chain_id : string...
def setContextNode(self, node): """Set the current node of an xpathContext """ if node is None: node__o = None else: node__o = node._o libxml2mod.xmlXPathSetContextNode(self._o, node__o)
Set the current node of an xpathContext
Below is the the instruction that describes the task: ### Input: Set the current node of an xpathContext ### Response: def setContextNode(self, node): """Set the current node of an xpathContext """ if node is None: node__o = None else: node__o = node._o libxml2mod.xmlXPathSetContext...
def suggest_accumulation_rate(chron): """From core age-depth data, suggest mean accumulation rate (cm/y) """ # Follow's Bacon's method @ Bacon.R ln 30 - 44 # Suggested round vals. sugg = np.tile([1, 2, 5], (4, 1)) * np.reshape(np.repeat([0.1, 1.0, 10, 100], 3), (4, 3)) # Get ballpark accumulatio...
From core age-depth data, suggest mean accumulation rate (cm/y)
Below is the the instruction that describes the task: ### Input: From core age-depth data, suggest mean accumulation rate (cm/y) ### Response: def suggest_accumulation_rate(chron): """From core age-depth data, suggest mean accumulation rate (cm/y) """ # Follow's Bacon's method @ Bacon.R ln 30 - 44 ...
def _parse(partial_dt): """ parse a partial datetime object to a complete datetime object """ dt = None try: if isinstance(partial_dt, datetime): dt = partial_dt if isinstance(partial_dt, date): dt = _combine_date_time(partial_dt, time(0, 0, 0)) if isi...
parse a partial datetime object to a complete datetime object
Below is the the instruction that describes the task: ### Input: parse a partial datetime object to a complete datetime object ### Response: def _parse(partial_dt): """ parse a partial datetime object to a complete datetime object """ dt = None try: if isinstance(partial_dt, datetime): ...
def advance(self, myDateTime): """ Advances to the next value and returns an appropriate value for the given time. :param myDateTime: (datetime) when to fetch the value for :return: (float|int) value for given time """ if self.getTime() == myDateTime: out = self.next() # Someti...
Advances to the next value and returns an appropriate value for the given time. :param myDateTime: (datetime) when to fetch the value for :return: (float|int) value for given time
Below is the the instruction that describes the task: ### Input: Advances to the next value and returns an appropriate value for the given time. :param myDateTime: (datetime) when to fetch the value for :return: (float|int) value for given time ### Response: def advance(self, myDateTime): """ ...
def set_pipeline(self, pipeline): """ Specify the pipeline. See get_pipeline_alternatives to see what are avaialble. Input should be a string. """ self.add_history(inspect.stack()[0][3], locals(), 1) if not os.path.exists(self.BIDS_dir + '/derivatives/' + pipeline): p...
Specify the pipeline. See get_pipeline_alternatives to see what are avaialble. Input should be a string.
Below is the the instruction that describes the task: ### Input: Specify the pipeline. See get_pipeline_alternatives to see what are avaialble. Input should be a string. ### Response: def set_pipeline(self, pipeline): """ Specify the pipeline. See get_pipeline_alternatives to see what are avaialble...
def wallet_export(self, wallet): """ Return a json representation of **wallet** :param wallet: Wallet to export :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.wallet_export(wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F") ...
Return a json representation of **wallet** :param wallet: Wallet to export :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.wallet_export(wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F") { "0000000000000000000000000000000...
Below is the the instruction that describes the task: ### Input: Return a json representation of **wallet** :param wallet: Wallet to export :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.wallet_export(wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A...
def word_tokenize(text, stopwords=_stopwords, ngrams=None, min_length=0, ignore_numeric=True): """ Parses the given text and yields tokens which represent words within the given text. Tokens are assumed to be divided by any form of whitespace character. """ if ngrams is None: ngrams = 1 ...
Parses the given text and yields tokens which represent words within the given text. Tokens are assumed to be divided by any form of whitespace character.
Below is the the instruction that describes the task: ### Input: Parses the given text and yields tokens which represent words within the given text. Tokens are assumed to be divided by any form of whitespace character. ### Response: def word_tokenize(text, stopwords=_stopwords, ngrams=None, min_length=0, ...
def delete_compliance_task(self, id): '''**Description** Delete the compliance task with the given id **Arguments** - id: the id of the compliance task to delete ''' res = requests.delete(self.url + '/api/complianceTasks/{}'.format(id), headers=self.hdrs, verify=...
**Description** Delete the compliance task with the given id **Arguments** - id: the id of the compliance task to delete
Below is the the instruction that describes the task: ### Input: **Description** Delete the compliance task with the given id **Arguments** - id: the id of the compliance task to delete ### Response: def delete_compliance_task(self, id): '''**Description** Delet...
def cluster_assignments(self): """ Return an array of cluster assignments corresponding to the most recent set of instances clustered. :return: the cluster assignments :rtype: ndarray """ array = javabridge.call(self.jobject, "getClusterAssignments", "()[D") if a...
Return an array of cluster assignments corresponding to the most recent set of instances clustered. :return: the cluster assignments :rtype: ndarray
Below is the the instruction that describes the task: ### Input: Return an array of cluster assignments corresponding to the most recent set of instances clustered. :return: the cluster assignments :rtype: ndarray ### Response: def cluster_assignments(self): """ Return an array of ...
def deleteProfile(self, profile): """ Removes a profile from the persistent settings """ profGroupName = self.profileGroupName(profile) logger.debug("Resetting profile settings: {}".format(profGroupName)) settings = QtCore.QSettings() settings.remove(profGroupName)
Removes a profile from the persistent settings
Below is the the instruction that describes the task: ### Input: Removes a profile from the persistent settings ### Response: def deleteProfile(self, profile): """ Removes a profile from the persistent settings """ profGroupName = self.profileGroupName(profile) logger.debug("Resetti...
def same_color(self, objects: Set[Object]) -> Set[Object]: """ Filters the set of objects, and returns those objects whose color is the most frequent color in the initial set of objects, if the highest frequency is greater than 1, or an empty set otherwise. This is an unusual na...
Filters the set of objects, and returns those objects whose color is the most frequent color in the initial set of objects, if the highest frequency is greater than 1, or an empty set otherwise. This is an unusual name for what the method does, but just as ``blue`` filters objects to th...
Below is the the instruction that describes the task: ### Input: Filters the set of objects, and returns those objects whose color is the most frequent color in the initial set of objects, if the highest frequency is greater than 1, or an empty set otherwise. This is an unusual name for wha...
def append(self, record): """ Adds the passed +record+ to satisfy the query. Only intended to be used in conjunction with associations (i.e. do not use if self.record is None). Intended use case (DO THIS): post.comments.append(comment) NOT THIS: Query(...
Adds the passed +record+ to satisfy the query. Only intended to be used in conjunction with associations (i.e. do not use if self.record is None). Intended use case (DO THIS): post.comments.append(comment) NOT THIS: Query(Post).where(content="foo").append(post)
Below is the the instruction that describes the task: ### Input: Adds the passed +record+ to satisfy the query. Only intended to be used in conjunction with associations (i.e. do not use if self.record is None). Intended use case (DO THIS): post.comments.append(comment) NO...
def p_statement_draw3_attr(p): """ statement : DRAW attr_list expr COMMA expr COMMA expr """ p[0] = make_sentence('DRAW3', make_typecast(TYPE.integer, p[3], p.lineno(4)), make_typecast(TYPE.integer, p[5], p.lineno(6)), make_typecast(...
statement : DRAW attr_list expr COMMA expr COMMA expr
Below is the the instruction that describes the task: ### Input: statement : DRAW attr_list expr COMMA expr COMMA expr ### Response: def p_statement_draw3_attr(p): """ statement : DRAW attr_list expr COMMA expr COMMA expr """ p[0] = make_sentence('DRAW3', make_typecast(TYPE.int...
def save_colormap(self, name=None): """ Saves the colormap with the specified name. None means use internal name. (See get_name()) """ if name == None: name = self.get_name() if name == "" or not type(name)==str: return "Error: invalid name." # get the colormaps ...
Saves the colormap with the specified name. None means use internal name. (See get_name())
Below is the the instruction that describes the task: ### Input: Saves the colormap with the specified name. None means use internal name. (See get_name()) ### Response: def save_colormap(self, name=None): """ Saves the colormap with the specified name. None means use internal name....
def sanitize(self): ''' Check if the current settings conform to the LISP specifications and fix them where possible. ''' super(EncapsulatedControlMessage, self).sanitize() # S: This is the Security bit. When set to 1 the following # authentication information w...
Check if the current settings conform to the LISP specifications and fix them where possible.
Below is the the instruction that describes the task: ### Input: Check if the current settings conform to the LISP specifications and fix them where possible. ### Response: def sanitize(self): ''' Check if the current settings conform to the LISP specifications and fix them where po...
def registered(self, driver, executorInfo, frameworkInfo, agentInfo): """ Invoked once the executor driver has been able to successfully connect with Mesos. """ # Get the ID we have been assigned, if we have it self.id = executorInfo.executor_id.get('value', None) ...
Invoked once the executor driver has been able to successfully connect with Mesos.
Below is the the instruction that describes the task: ### Input: Invoked once the executor driver has been able to successfully connect with Mesos. ### Response: def registered(self, driver, executorInfo, frameworkInfo, agentInfo): """ Invoked once the executor driver has been able to successfully ...
def get_umbrella_sampling_data(ntherm=11, us_fc=20.0, us_length=500, md_length=1000, nmd=20): """ Continuous MCMC process in an asymmetric double well potential using umbrella sampling. Parameters ---------- ntherm: int, optional, default=11 Number of umbrella states. us_fc: double, opt...
Continuous MCMC process in an asymmetric double well potential using umbrella sampling. Parameters ---------- ntherm: int, optional, default=11 Number of umbrella states. us_fc: double, optional, default=20.0 Force constant in kT/length^2 for each umbrella. us_length: int, optional,...
Below is the the instruction that describes the task: ### Input: Continuous MCMC process in an asymmetric double well potential using umbrella sampling. Parameters ---------- ntherm: int, optional, default=11 Number of umbrella states. us_fc: double, optional, default=20.0 Force con...
def get(self, obj_id): """ Get a document or a page using its ID Won't instantiate them if they are not yet available """ if BasicPage.PAGE_ID_SEPARATOR in obj_id: (docid, page_nb) = obj_id.split(BasicPage.PAGE_ID_SEPARATOR) page_nb = int(page_nb) ...
Get a document or a page using its ID Won't instantiate them if they are not yet available
Below is the the instruction that describes the task: ### Input: Get a document or a page using its ID Won't instantiate them if they are not yet available ### Response: def get(self, obj_id): """ Get a document or a page using its ID Won't instantiate them if they are not yet avail...
def default_loader(obj, defaults=None): """Loads default settings and check if there are overridings exported as environment variables""" defaults = defaults or {} default_settings_values = { key: value for key, value in default_settings.__dict__.items() # noqa if key.isupper() ...
Loads default settings and check if there are overridings exported as environment variables
Below is the the instruction that describes the task: ### Input: Loads default settings and check if there are overridings exported as environment variables ### Response: def default_loader(obj, defaults=None): """Loads default settings and check if there are overridings exported as environment variabl...
def __parse_enrollments(self, user): """Parse user enrollments""" enrollments = [] for company in user['companies']: name = company['company_name'] org = self._organizations.get(name, None) if not org: org = Organization(name=name) ...
Parse user enrollments
Below is the the instruction that describes the task: ### Input: Parse user enrollments ### Response: def __parse_enrollments(self, user): """Parse user enrollments""" enrollments = [] for company in user['companies']: name = company['company_name'] org = self._or...
def classifyParameters(self): """Return (arguments, options, outputs) tuple. Together, the three lists contain all parameters (recursively fetched from all parameter groups), classified into optional parameters, required ones (with an index), and simple output parameters (that w...
Return (arguments, options, outputs) tuple. Together, the three lists contain all parameters (recursively fetched from all parameter groups), classified into optional parameters, required ones (with an index), and simple output parameters (that would get written to a file using ...
Below is the the instruction that describes the task: ### Input: Return (arguments, options, outputs) tuple. Together, the three lists contain all parameters (recursively fetched from all parameter groups), classified into optional parameters, required ones (with an index), and simple outpu...
def columnNameAt( self, index ): """ Returns the name of the column at the inputed index. :param index | <int> :return <str> """ columns = self.columns() if ( 0 <= index and index < len(columns) ): return columns[index] ...
Returns the name of the column at the inputed index. :param index | <int> :return <str>
Below is the the instruction that describes the task: ### Input: Returns the name of the column at the inputed index. :param index | <int> :return <str> ### Response: def columnNameAt( self, index ): """ Returns the name of the column at the inputed index....
def overlapping_spheres(shape: List[int], radius: int, porosity: float, iter_max: int = 10, tol: float = 0.01): r""" Generate a packing of overlapping mono-disperse spheres Parameters ---------- shape : list The size of the image to generate in [Nx, Ny, Nz] where Ni ...
r""" Generate a packing of overlapping mono-disperse spheres Parameters ---------- shape : list The size of the image to generate in [Nx, Ny, Nz] where Ni is the number of voxels in the i-th direction. radius : scalar The radius of spheres in the packing. porosity : sc...
Below is the the instruction that describes the task: ### Input: r""" Generate a packing of overlapping mono-disperse spheres Parameters ---------- shape : list The size of the image to generate in [Nx, Ny, Nz] where Ni is the number of voxels in the i-th direction. radius : sc...
def is_sqlatype_binary(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type a binary type? """ # Several binary types inherit internally from _Binary, making that the # easiest to check. coltype = _coltype_to_typeengine(coltype) # noinspection PyProtectedMemb...
Is the SQLAlchemy column type a binary type?
Below is the the instruction that describes the task: ### Input: Is the SQLAlchemy column type a binary type? ### Response: def is_sqlatype_binary(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type a binary type? """ # Several binary types inherit internally from ...
def ped_parser(self, family_info): """ Parse .ped formatted family info. Add all family info to the parser object Arguments: family_info (iterator): An iterator with family info """ for line in family_info: # Che...
Parse .ped formatted family info. Add all family info to the parser object Arguments: family_info (iterator): An iterator with family info
Below is the the instruction that describes the task: ### Input: Parse .ped formatted family info. Add all family info to the parser object Arguments: family_info (iterator): An iterator with family info ### Response: def ped_parser(self, family_info): """ ...
def parse_header(header): """ Convert a list of the form `['fieldname:fieldtype:fieldsize',...]` into a numpy composite dtype. The parser understands headers generated by :func:`openquake.commonlib.writers.build_header`. Here is an example: >>> parse_header(['PGA:float32', 'PGV', 'avg:float32:2...
Convert a list of the form `['fieldname:fieldtype:fieldsize',...]` into a numpy composite dtype. The parser understands headers generated by :func:`openquake.commonlib.writers.build_header`. Here is an example: >>> parse_header(['PGA:float32', 'PGV', 'avg:float32:2']) (['PGA', 'PGV', 'avg'], dtype(...
Below is the the instruction that describes the task: ### Input: Convert a list of the form `['fieldname:fieldtype:fieldsize',...]` into a numpy composite dtype. The parser understands headers generated by :func:`openquake.commonlib.writers.build_header`. Here is an example: >>> parse_header(['PGA:...
def initialize_plot(self, data=None, ax=None, make_plot=True, clear=False, draw=False, remove=False, priority=None): """ Initialize the plot for a data array Parameters ---------- data: InteractiveArray or ArrayList, optional Data object that ...
Initialize the plot for a data array Parameters ---------- data: InteractiveArray or ArrayList, optional Data object that shall be visualized. - If not None and `plot` is True, the given data is visualized. - If None and the :attr:`data` attribute is not Non...
Below is the the instruction that describes the task: ### Input: Initialize the plot for a data array Parameters ---------- data: InteractiveArray or ArrayList, optional Data object that shall be visualized. - If not None and `plot` is True, the given data is visual...
def calcparams_desoto(effective_irradiance, temp_cell, alpha_sc, a_ref, I_L_ref, I_o_ref, R_sh_ref, R_s, EgRef=1.121, dEgdT=-0.0002677, irrad_ref=1000, temp_ref=25): ''' Calculates five parameter values for the single diode equation at effect...
Calculates five parameter values for the single diode equation at effective irradiance and cell temperature using the De Soto et al. model described in [1]. The five values returned by calcparams_desoto can be used by singlediode to calculate an IV curve. Parameters ---------- effective_irradia...
Below is the the instruction that describes the task: ### Input: Calculates five parameter values for the single diode equation at effective irradiance and cell temperature using the De Soto et al. model described in [1]. The five values returned by calcparams_desoto can be used by singlediode to calcul...
async def update_flags(self, messages: Sequence[MessageT], flag_set: FrozenSet[Flag], mode: FlagOp) -> None: """Update the permanent flags of each messages. Args: messages: The message objects. flag_set: The set of flags for the update operation. ...
Update the permanent flags of each messages. Args: messages: The message objects. flag_set: The set of flags for the update operation. flag_op: The mode to change the flags.
Below is the the instruction that describes the task: ### Input: Update the permanent flags of each messages. Args: messages: The message objects. flag_set: The set of flags for the update operation. flag_op: The mode to change the flags. ### Response: async def update_...
def output_notebook(inline=True, logo=False): """ Load the notebook extension Parameters ---------- inline : boolean (optional) Whether to inline JS code or load it from a CDN logo : boolean (optional) Whether to show the logo(s) """ try: import hvplot except...
Load the notebook extension Parameters ---------- inline : boolean (optional) Whether to inline JS code or load it from a CDN logo : boolean (optional) Whether to show the logo(s)
Below is the the instruction that describes the task: ### Input: Load the notebook extension Parameters ---------- inline : boolean (optional) Whether to inline JS code or load it from a CDN logo : boolean (optional) Whether to show the logo(s) ### Response: def output_notebook(inl...
def dec2dms(dec): """ ADW: This should really be replaced by astropy """ DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. dec = float(dec) sign = np.copysign(1.0,dec) fdeg = np.abs(dec) deg = int(fdeg) fminute = (fdeg - deg)*MINUTE minute = int(fminute) ...
ADW: This should really be replaced by astropy
Below is the the instruction that describes the task: ### Input: ADW: This should really be replaced by astropy ### Response: def dec2dms(dec): """ ADW: This should really be replaced by astropy """ DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. dec = float(dec) sign = np...
def positionlesscrop(self,x,y,sheet_coord_system): """ Return the correct slice for a weights/mask matrix at this ConnectionField's location on the sheet (i.e. for getting the correct submatrix of the weights or mask in case the unit is near the edge of the sheet). """ ...
Return the correct slice for a weights/mask matrix at this ConnectionField's location on the sheet (i.e. for getting the correct submatrix of the weights or mask in case the unit is near the edge of the sheet).
Below is the the instruction that describes the task: ### Input: Return the correct slice for a weights/mask matrix at this ConnectionField's location on the sheet (i.e. for getting the correct submatrix of the weights or mask in case the unit is near the edge of the sheet). ### Response: d...
def timestamp_YmdHMS(value): """Convert timestamp string to time in seconds since epoch. Timestamps strings like '20130618120000' are able to be converted by this function. Args: value: A timestamp string in the format '%Y%m%d%H%M%S'. Returns: The time in seconds since epoch as an...
Convert timestamp string to time in seconds since epoch. Timestamps strings like '20130618120000' are able to be converted by this function. Args: value: A timestamp string in the format '%Y%m%d%H%M%S'. Returns: The time in seconds since epoch as an integer. Raises: Value...
Below is the the instruction that describes the task: ### Input: Convert timestamp string to time in seconds since epoch. Timestamps strings like '20130618120000' are able to be converted by this function. Args: value: A timestamp string in the format '%Y%m%d%H%M%S'. Returns: The ...
def create_secret_link(self, title, description=None, expires_at=None): """Create a secret link from request.""" self.link = SecretLink.create( title, self.receiver, extra_data=dict(recid=self.recid), description=description, expires_at=expires...
Create a secret link from request.
Below is the the instruction that describes the task: ### Input: Create a secret link from request. ### Response: def create_secret_link(self, title, description=None, expires_at=None): """Create a secret link from request.""" self.link = SecretLink.create( title, self.recei...
def _handle_ticker(self, ts, chan_id, data): """ Adds received ticker data to self.tickers dict, filed under its channel id. :param ts: timestamp, declares when data was received by the client :param chan_id: int, channel id :param data: tuple or list of data received via...
Adds received ticker data to self.tickers dict, filed under its channel id. :param ts: timestamp, declares when data was received by the client :param chan_id: int, channel id :param data: tuple or list of data received via wss :return:
Below is the the instruction that describes the task: ### Input: Adds received ticker data to self.tickers dict, filed under its channel id. :param ts: timestamp, declares when data was received by the client :param chan_id: int, channel id :param data: tuple or list of data received...
def ensure_alt_ids_in_nest_spec_are_ints(nest_spec, list_elements): """ Ensures that the alternative id's in `nest_spec` are integers. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of ...
Ensures that the alternative id's in `nest_spec` are integers. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternati...
Below is the the instruction that describes the task: ### Input: Ensures that the alternative id's in `nest_spec` are integers. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. ...
def subontology(self, minimal=False): """ Generates a sub-ontology based on associations """ return self.ontology.subontology(self.objects, minimal=minimal)
Generates a sub-ontology based on associations
Below is the the instruction that describes the task: ### Input: Generates a sub-ontology based on associations ### Response: def subontology(self, minimal=False): """ Generates a sub-ontology based on associations """ return self.ontology.subontology(self.objects, minimal=minimal)
def load_all(stream): """ Parse all YAML documents in a stream and produce corresponding YAMLDict objects. """ loader = YAMLDictLoader(stream) try: while loader.check_data(): yield loader.get_data() finally: loader.dispose()
Parse all YAML documents in a stream and produce corresponding YAMLDict objects.
Below is the the instruction that describes the task: ### Input: Parse all YAML documents in a stream and produce corresponding YAMLDict objects. ### Response: def load_all(stream): """ Parse all YAML documents in a stream and produce corresponding YAMLDict objects. """ loader = YAMLDictLoa...
def connect(self, interface=None): """Connect to the USB for the hottop. Attempt to discover the USB port used for the Hottop and then form a connection using the serial library. :returns: bool :raises SerialConnectionError: """ if self._simulate: re...
Connect to the USB for the hottop. Attempt to discover the USB port used for the Hottop and then form a connection using the serial library. :returns: bool :raises SerialConnectionError:
Below is the the instruction that describes the task: ### Input: Connect to the USB for the hottop. Attempt to discover the USB port used for the Hottop and then form a connection using the serial library. :returns: bool :raises SerialConnectionError: ### Response: def connect(sel...
def regex_query(expression): """Apply regular expression to result of expression.""" def _regex(index, expression=expression): """Return store key for documents that satisfy expression.""" pattern = re.compile(expression) return [ store_key for value, store_keys ...
Apply regular expression to result of expression.
Below is the the instruction that describes the task: ### Input: Apply regular expression to result of expression. ### Response: def regex_query(expression): """Apply regular expression to result of expression.""" def _regex(index, expression=expression): """Return store key for documents that sati...
def create_schema(self, connection): """ Will create the schema in the database """ if '.' not in self.table: return query = 'CREATE SCHEMA IF NOT EXISTS {schema_name};'.format(schema_name=self.table.split('.')[0]) connection.cursor().execute(query)
Will create the schema in the database
Below is the the instruction that describes the task: ### Input: Will create the schema in the database ### Response: def create_schema(self, connection): """ Will create the schema in the database """ if '.' not in self.table: return query = 'CREATE SCHEMA IF N...
def _numeric_summary(arg, exact_nunique=False, prefix=None): """ Compute a set of summary metrics from the input numeric value expression Parameters ---------- arg : numeric value expression exact_nunique : boolean, default False prefix : string, default None String prefix for metric ...
Compute a set of summary metrics from the input numeric value expression Parameters ---------- arg : numeric value expression exact_nunique : boolean, default False prefix : string, default None String prefix for metric names Returns ------- summary : (count, # nulls, min, max, s...
Below is the the instruction that describes the task: ### Input: Compute a set of summary metrics from the input numeric value expression Parameters ---------- arg : numeric value expression exact_nunique : boolean, default False prefix : string, default None String prefix for metric name...
def update_positions(tree, positions): """Updates the tree with new positions""" for step, pos in zip(tree.findall('step'), positions): for key in sorted(pos): value = pos.get(key) if key.endswith("-rel"): abs_key = key[:key.index("-rel")] if valu...
Updates the tree with new positions
Below is the the instruction that describes the task: ### Input: Updates the tree with new positions ### Response: def update_positions(tree, positions): """Updates the tree with new positions""" for step, pos in zip(tree.findall('step'), positions): for key in sorted(pos): value = pos...
def has_operator_manifest(self): """ Check if Dockerfile sets the operator manifest label :return: bool """ dockerfile = df_parser(self.workflow.builder.df_path, workflow=self.workflow) labels = Labels(dockerfile.labels) try: _, operator_label = label...
Check if Dockerfile sets the operator manifest label :return: bool
Below is the the instruction that describes the task: ### Input: Check if Dockerfile sets the operator manifest label :return: bool ### Response: def has_operator_manifest(self): """ Check if Dockerfile sets the operator manifest label :return: bool """ dockerfile ...
def set_iomem(self, iomem): """ Set I/O memory size for this router. :param iomem: I/O memory size """ yield from self._hypervisor.send('c3600 set_iomem "{name}" {size}'.format(name=self._name, size=iomem)) log.info('Router "{name}" [{id}]: I/O memory updated from {old...
Set I/O memory size for this router. :param iomem: I/O memory size
Below is the the instruction that describes the task: ### Input: Set I/O memory size for this router. :param iomem: I/O memory size ### Response: def set_iomem(self, iomem): """ Set I/O memory size for this router. :param iomem: I/O memory size """ yield from self...
def save(self): """ Save the project configuration This method dumps the configuration for each project and the project paths (see the :attr:`all_projects` attribute) to the hard drive """ project_paths = OrderedDict() for project, d in OrderedDict(self).items():...
Save the project configuration This method dumps the configuration for each project and the project paths (see the :attr:`all_projects` attribute) to the hard drive
Below is the the instruction that describes the task: ### Input: Save the project configuration This method dumps the configuration for each project and the project paths (see the :attr:`all_projects` attribute) to the hard drive ### Response: def save(self): """ Save the project c...
def _attach(self, instruction, qargs, cargs): """DEPRECATED after 0.8""" self.append(instruction, qargs, cargs)
DEPRECATED after 0.8
Below is the the instruction that describes the task: ### Input: DEPRECATED after 0.8 ### Response: def _attach(self, instruction, qargs, cargs): """DEPRECATED after 0.8""" self.append(instruction, qargs, cargs)
def get_list_subtasks(client, list_id, completed=False): ''' Gets subtasks for the list with given ID ''' params = { 'list_id' : int(list_id), 'completed' : completed, } response = client.authenticated_request(client.api.Endpoints.SUBTASKS, params=params) return respo...
Gets subtasks for the list with given ID
Below is the the instruction that describes the task: ### Input: Gets subtasks for the list with given ID ### Response: def get_list_subtasks(client, list_id, completed=False): ''' Gets subtasks for the list with given ID ''' params = { 'list_id' : int(list_id), 'completed' : comple...
def disconnect_async(self, conn_id, callback): """Asynchronously disconnect from a device that has previously been connected Args: conn_id (int): a unique identifier for this connection on the DeviceManager that owns this adapter. callback (callable): A function ...
Asynchronously disconnect from a device that has previously been connected Args: conn_id (int): a unique identifier for this connection on the DeviceManager that owns this adapter. callback (callable): A function called as callback(conn_id, adapter_id, success, failure_r...
Below is the the instruction that describes the task: ### Input: Asynchronously disconnect from a device that has previously been connected Args: conn_id (int): a unique identifier for this connection on the DeviceManager that owns this adapter. callback (callable): ...
def predict_normal_binding(job, binding_result, transgened_files, allele, peplen, univ_options, mhc_options): """ Predict the binding score for the normal counterparts of the peptides in mhc_dict and then return the results in a properly formatted structure. :param str bindin...
Predict the binding score for the normal counterparts of the peptides in mhc_dict and then return the results in a properly formatted structure. :param str binding_result: The results from running predict_mhci_binding or predict_mhcii_binding on a single allele :param dict transgened_files: A di...
Below is the the instruction that describes the task: ### Input: Predict the binding score for the normal counterparts of the peptides in mhc_dict and then return the results in a properly formatted structure. :param str binding_result: The results from running predict_mhci_binding or predict_mh...
def compute_tab_title(self, vte): """Abbreviate and cut vte terminal title when necessary """ vte_title = vte.get_window_title() or _("Terminal") try: current_directory = vte.get_current_directory() if self.abbreviate and vte_title.endswith(current_directory): ...
Abbreviate and cut vte terminal title when necessary
Below is the the instruction that describes the task: ### Input: Abbreviate and cut vte terminal title when necessary ### Response: def compute_tab_title(self, vte): """Abbreviate and cut vte terminal title when necessary """ vte_title = vte.get_window_title() or _("Terminal") try: ...
def get(self, timeout=10): """get() -> {'id': 32-byte-md5, 'body': msg-body}""" req = self.req({'op': 'GET', 'timeout': timeout}) if req.status_code != 200: return None result = req.json() if result.get('status') != 'ok': return False return result
get() -> {'id': 32-byte-md5, 'body': msg-body}
Below is the the instruction that describes the task: ### Input: get() -> {'id': 32-byte-md5, 'body': msg-body} ### Response: def get(self, timeout=10): """get() -> {'id': 32-byte-md5, 'body': msg-body}""" req = self.req({'op': 'GET', 'timeout': timeout}) if req.status_code != 200: ...
def make_avro_schema(i, # type: List[Any] loader # type: Loader ): # type: (...) -> Names """ All in one convenience function. Call make_avro() and make_avro_schema_from_avro() separately if you need the intermediate result for diagnostic output. ...
All in one convenience function. Call make_avro() and make_avro_schema_from_avro() separately if you need the intermediate result for diagnostic output.
Below is the the instruction that describes the task: ### Input: All in one convenience function. Call make_avro() and make_avro_schema_from_avro() separately if you need the intermediate result for diagnostic output. ### Response: def make_avro_schema(i, # type: List[Any] loa...
def durationSeconds(self): """ Returns the runtime duration of the video stream as a floating point number of seconds. Returns 0.0 if not a video stream. """ f=0.0 if self.isVideo() or self.isAudio(): if self.__dict__['duration']: try: ...
Returns the runtime duration of the video stream as a floating point number of seconds. Returns 0.0 if not a video stream.
Below is the the instruction that describes the task: ### Input: Returns the runtime duration of the video stream as a floating point number of seconds. Returns 0.0 if not a video stream. ### Response: def durationSeconds(self): """ Returns the runtime duration of the video stream as a floa...
def increment(self, size: int): '''Increment the number of files downloaded. Args: size: The size of the file ''' assert size >= 0, size self.files += 1 self.size += size self.bandwidth_meter.feed(size)
Increment the number of files downloaded. Args: size: The size of the file
Below is the the instruction that describes the task: ### Input: Increment the number of files downloaded. Args: size: The size of the file ### Response: def increment(self, size: int): '''Increment the number of files downloaded. Args: size: The size of the file ...
def _build_settings(config_data): """ Build the django CMS settings dictionary :param config_data: configuration data """ spacer = ' ' text = [] vars = get_settings() vars.MIDDLEWARE_CLASSES.insert(0, vars.APPHOOK_RELOAD_MIDDLEWARE_CLASS) processors = vars.TEMPLATE_CONTEXT_PROC...
Build the django CMS settings dictionary :param config_data: configuration data
Below is the the instruction that describes the task: ### Input: Build the django CMS settings dictionary :param config_data: configuration data ### Response: def _build_settings(config_data): """ Build the django CMS settings dictionary :param config_data: configuration data """ spacer =...
def saturate_colors(colors, amount): """Saturate all colors.""" if amount and float(amount) <= 1.0: for i, _ in enumerate(colors): if i not in [0, 7, 8, 15]: colors[i] = util.saturate_color(colors[i], float(amount)) return colors
Saturate all colors.
Below is the the instruction that describes the task: ### Input: Saturate all colors. ### Response: def saturate_colors(colors, amount): """Saturate all colors.""" if amount and float(amount) <= 1.0: for i, _ in enumerate(colors): if i not in [0, 7, 8, 15]: colors[i] = u...
def owner(*paths, **kwargs): # pylint: disable=unused-argument ''' Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dic...
Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dictionary of file/package name pairs will be returned. If the file is not...
Below is the the instruction that describes the task: ### Input: Return the name of the package that owns the file. Multiple file paths can be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single path is passed, a string will be returned, and if multiple paths are passed, a dictionary...
def parse_css(self, css): """ Parse a css style sheet into the CSS object. For the moment this will only work for very simple css documents. It works by using regular expression matching css syntax. This is not bullet proof. """ rulesets = self.ruleset_re.finda...
Parse a css style sheet into the CSS object. For the moment this will only work for very simple css documents. It works by using regular expression matching css syntax. This is not bullet proof.
Below is the the instruction that describes the task: ### Input: Parse a css style sheet into the CSS object. For the moment this will only work for very simple css documents. It works by using regular expression matching css syntax. This is not bullet proof. ### Response: def parse_css(...
def _set_mpls_traffic_bypasses(self, v, load=False): """ Setter method for mpls_traffic_bypasses, mapped from YANG variable /telemetry/profile/mpls_traffic_bypass/mpls_traffic_bypasses (list) If this variable is read-only (config: false) in the source YANG file, then _set_mpls_traffic_bypasses is consid...
Setter method for mpls_traffic_bypasses, mapped from YANG variable /telemetry/profile/mpls_traffic_bypass/mpls_traffic_bypasses (list) If this variable is read-only (config: false) in the source YANG file, then _set_mpls_traffic_bypasses is considered as a private method. Backends looking to populate this v...
Below is the the instruction that describes the task: ### Input: Setter method for mpls_traffic_bypasses, mapped from YANG variable /telemetry/profile/mpls_traffic_bypass/mpls_traffic_bypasses (list) If this variable is read-only (config: false) in the source YANG file, then _set_mpls_traffic_bypasses is co...
def check_configuration(self, file_path, test_program, custom_args): """Checks if configuration is ok.""" # checking filepath if not os.path.isdir(file_path): raise InvalidFilePath("INVALID CONFIGURATION: file path %s is not a directory" % os.path.abspath(file_path) ...
Checks if configuration is ok.
Below is the the instruction that describes the task: ### Input: Checks if configuration is ok. ### Response: def check_configuration(self, file_path, test_program, custom_args): """Checks if configuration is ok.""" # checking filepath if not os.path.isdir(file_path): raise Inva...
def _chunk_report_(bytes_so_far, total_size, initial_size, t_0): """Show downloading percentage. :param int bytes_so_far: number of downloaded bytes :param int total_size: total size of the file (may be 0/None, depending on download method). :param int t_0: the time in seconds (as returned by t...
Show downloading percentage. :param int bytes_so_far: number of downloaded bytes :param int total_size: total size of the file (may be 0/None, depending on download method). :param int t_0: the time in seconds (as returned by time.time()) at which the download was resumed / started. :pa...
Below is the the instruction that describes the task: ### Input: Show downloading percentage. :param int bytes_so_far: number of downloaded bytes :param int total_size: total size of the file (may be 0/None, depending on download method). :param int t_0: the time in seconds (as returned by time...
def checkOnline(self, userId): """ 检查用户在线状态 方法 方法 @param userId:用户 Id,最大长度 64 字节。是用户在 App 中的唯一标识码,必须保证在同一个 App 内不重复,重复的用户 Id 将被当作是同一用户。(必传) @return code:返回码,200 为正常。 @return status:在线状态,1为在线,0为不在线。 @return errorMessage:错误信息。 """ desc = { "nam...
检查用户在线状态 方法 方法 @param userId:用户 Id,最大长度 64 字节。是用户在 App 中的唯一标识码,必须保证在同一个 App 内不重复,重复的用户 Id 将被当作是同一用户。(必传) @return code:返回码,200 为正常。 @return status:在线状态,1为在线,0为不在线。 @return errorMessage:错误信息。
Below is the the instruction that describes the task: ### Input: 检查用户在线状态 方法 方法 @param userId:用户 Id,最大长度 64 字节。是用户在 App 中的唯一标识码,必须保证在同一个 App 内不重复,重复的用户 Id 将被当作是同一用户。(必传) @return code:返回码,200 为正常。 @return status:在线状态,1为在线,0为不在线。 @return errorMessage:错误信息。 ### Response: def checkO...
def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of ar...
Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_siz...
Below is the the instruction that describes the task: ### Input: Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. ...
def init_running_properties(self): """ Initialize the running_properties. Each instance have own property. :return: None """ for prop, entry in list(self.__class__.running_properties.items()): val = entry.default # Make a copy of the value for com...
Initialize the running_properties. Each instance have own property. :return: None
Below is the the instruction that describes the task: ### Input: Initialize the running_properties. Each instance have own property. :return: None ### Response: def init_running_properties(self): """ Initialize the running_properties. Each instance have own property. ...
def shrink(self): """ Calculate the Constant-Correlation covariance matrix. :return: shrunk sample covariance matrix :rtype: np.ndarray """ x = np.nan_to_num(self.X.values) # de-mean returns t, n = np.shape(x) meanx = x.mean(axis=0) x = x...
Calculate the Constant-Correlation covariance matrix. :return: shrunk sample covariance matrix :rtype: np.ndarray
Below is the the instruction that describes the task: ### Input: Calculate the Constant-Correlation covariance matrix. :return: shrunk sample covariance matrix :rtype: np.ndarray ### Response: def shrink(self): """ Calculate the Constant-Correlation covariance matrix. :ret...
def save(self, data, xparent=None): """ Parses the element from XML to Python. :param data | <variant> xparent | <xml.etree.ElementTree.Element> || None :return <xml.etree.ElementTree.Element> """ if xparent is not None: ...
Parses the element from XML to Python. :param data | <variant> xparent | <xml.etree.ElementTree.Element> || None :return <xml.etree.ElementTree.Element>
Below is the the instruction that describes the task: ### Input: Parses the element from XML to Python. :param data | <variant> xparent | <xml.etree.ElementTree.Element> || None :return <xml.etree.ElementTree.Element> ### Response: def save(self, da...
def stop(self): """ Stop the node process. """ if self._wrapper_telnet_server: self._wrapper_telnet_server.close() yield from self._wrapper_telnet_server.wait_closed() self.status = "stopped"
Stop the node process.
Below is the the instruction that describes the task: ### Input: Stop the node process. ### Response: def stop(self): """ Stop the node process. """ if self._wrapper_telnet_server: self._wrapper_telnet_server.close() yield from self._wrapper_telnet_server.wai...
def create_issue(self, request, group, form_data, **kwargs): """ Creates the issue on the remote service and returns an issue ID. """ instance = self.get_option('instance', group.project) project = ( form_data.get('project') or self.get_option('default_pro...
Creates the issue on the remote service and returns an issue ID.
Below is the the instruction that describes the task: ### Input: Creates the issue on the remote service and returns an issue ID. ### Response: def create_issue(self, request, group, form_data, **kwargs): """ Creates the issue on the remote service and returns an issue ID. """ insta...
def dispatch_on(*dispatch_args): """ Factory of decorators turning a function into a generic function dispatching on the given arguments. """ assert dispatch_args, 'No dispatch args passed' dispatch_str = '(%s,)' % ', '.join(dispatch_args) def check(arguments, wrong=operator.ne, msg=''): ...
Factory of decorators turning a function into a generic function dispatching on the given arguments.
Below is the the instruction that describes the task: ### Input: Factory of decorators turning a function into a generic function dispatching on the given arguments. ### Response: def dispatch_on(*dispatch_args): """ Factory of decorators turning a function into a generic function dispatching on th...
def wave_interp_option(obj): r""" Validate if an object is a :ref:`WaveInterpOption` pseudo-type object. :param obj: Object :type obj: any :raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The token \*[argument_name]\* is replaced by the name of the argument the contr...
r""" Validate if an object is a :ref:`WaveInterpOption` pseudo-type object. :param obj: Object :type obj: any :raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The token \*[argument_name]\* is replaced by the name of the argument the contract is attached to :rtype: N...
Below is the the instruction that describes the task: ### Input: r""" Validate if an object is a :ref:`WaveInterpOption` pseudo-type object. :param obj: Object :type obj: any :raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The token \*[argument_name]\* is replaced by the...
def plot_energy( data, kind="kde", bfmi=True, figsize=None, legend=True, fill_alpha=(1, 0.75), fill_color=("C0", "C5"), bw=4.5, textsize=None, fill_kwargs=None, plot_kwargs=None, ax=None, ): """Plot energy transition distribution and marginal energy distribution in HM...
Plot energy transition distribution and marginal energy distribution in HMC algorithms. This may help to diagnose poor exploration by gradient-based algorithms like HMC or NUTS. Parameters ---------- data : xarray dataset, or object that can be converted (must represent `sample_stats` and h...
Below is the the instruction that describes the task: ### Input: Plot energy transition distribution and marginal energy distribution in HMC algorithms. This may help to diagnose poor exploration by gradient-based algorithms like HMC or NUTS. Parameters ---------- data : xarray dataset, or object ...
def importalma(asdm, ms): """Convert an ALMA low-level ASDM dataset to Measurement Set format. asdm (str) The path to the input ASDM dataset. ms (str) The path to the output MS dataset. This implementation automatically infers the value of the "tbuff" parameter. Example:: f...
Convert an ALMA low-level ASDM dataset to Measurement Set format. asdm (str) The path to the input ASDM dataset. ms (str) The path to the output MS dataset. This implementation automatically infers the value of the "tbuff" parameter. Example:: from pwkit.environments.casa impor...
Below is the the instruction that describes the task: ### Input: Convert an ALMA low-level ASDM dataset to Measurement Set format. asdm (str) The path to the input ASDM dataset. ms (str) The path to the output MS dataset. This implementation automatically infers the value of the "tbuff" ...
def fpsInformation(self,args): '''fps command''' invalidStr = 'Invalid number of arguments. Usage horizon-fps set <fps> or horizon-fps get. Set fps to zero to get unrestricted framerate.' if len(args)>0: if args[0] == "get": '''Get the current framerate.''' ...
fps command
Below is the the instruction that describes the task: ### Input: fps command ### Response: def fpsInformation(self,args): '''fps command''' invalidStr = 'Invalid number of arguments. Usage horizon-fps set <fps> or horizon-fps get. Set fps to zero to get unrestricted framerate.' if len(args)...
def reload_using_spawn_exit(self): """ Spawn a subprocess and exit the current process. :return: None. """ # Create command parts cmd_parts = [sys.executable] + sys.argv # Get env dict copy env_copy = os.environ.copy() # Spawn subpro...
Spawn a subprocess and exit the current process. :return: None.
Below is the the instruction that describes the task: ### Input: Spawn a subprocess and exit the current process. :return: None. ### Response: def reload_using_spawn_exit(self): """ Spawn a subprocess and exit the current process. :return: None. """...
def c(self, *args, **kwargs): """ Takes a single argument or keyword argument, and returns the specified column. If the argument (or keyword argument) is an integer, return the n'th column, otherwise return the column based on key. If no arguments are supplied, simply ...
Takes a single argument or keyword argument, and returns the specified column. If the argument (or keyword argument) is an integer, return the n'th column, otherwise return the column based on key. If no arguments are supplied, simply print the column information.
Below is the the instruction that describes the task: ### Input: Takes a single argument or keyword argument, and returns the specified column. If the argument (or keyword argument) is an integer, return the n'th column, otherwise return the column based on key. If no arguments ar...
def uploads(self): """returns an object to work with the site uploads""" if self._resources is None: self.__init() if "uploads" in self._resources: url = self._url + "/uploads" return _uploads.Uploads(url=url, securityHandle...
returns an object to work with the site uploads
Below is the the instruction that describes the task: ### Input: returns an object to work with the site uploads ### Response: def uploads(self): """returns an object to work with the site uploads""" if self._resources is None: self.__init() if "uploads" in self._resources: ...
def _generate_typevars(self): # type: () -> None """ Creates type variables that are used by the type signatures for _process_custom_annotations. """ self.emit("T = TypeVar('T', bound=bb.AnnotationType)") self.emit("U = TypeVar('U')") self.import_tracker._...
Creates type variables that are used by the type signatures for _process_custom_annotations.
Below is the the instruction that describes the task: ### Input: Creates type variables that are used by the type signatures for _process_custom_annotations. ### Response: def _generate_typevars(self): # type: () -> None """ Creates type variables that are used by the type signature...
def join(L, keycols=None, nullvals=None, renamer=None, returnrenaming=False, Names=None): """ Combine two or more numpy ndarray with structured dtype on common key column(s). Merge a list (or dictionary) of numpy ndarray with structured dtype, given by `L`, on key columns listed in `keyc...
Combine two or more numpy ndarray with structured dtype on common key column(s). Merge a list (or dictionary) of numpy ndarray with structured dtype, given by `L`, on key columns listed in `keycols`. This function is actually a wrapper for :func:`tabular.spreadsheet.strictjoin`. The ``stric...
Below is the the instruction that describes the task: ### Input: Combine two or more numpy ndarray with structured dtype on common key column(s). Merge a list (or dictionary) of numpy ndarray with structured dtype, given by `L`, on key columns listed in `keycols`. This function is actually a wrap...
def _update_u(u, W): """ Update the threat points if it not feasible in the new W, by the minimum of new feasible payoffs. Parameters ---------- u : ndarray(float, ndim=1) The threat points. W : ndarray(float, ndim=1) The points that construct the feasible payoff convex hul...
Update the threat points if it not feasible in the new W, by the minimum of new feasible payoffs. Parameters ---------- u : ndarray(float, ndim=1) The threat points. W : ndarray(float, ndim=1) The points that construct the feasible payoff convex hull. Returns ------- u...
Below is the the instruction that describes the task: ### Input: Update the threat points if it not feasible in the new W, by the minimum of new feasible payoffs. Parameters ---------- u : ndarray(float, ndim=1) The threat points. W : ndarray(float, ndim=1) The points that cons...
def like(self, photo_id): """ Like a photo on behalf of the logged-in user. This requires the 'write_likes' scope. Note: This action is idempotent; sending the POST request to a single photo multiple times has no additional effect. :param photo_id [string]: The photo’s ...
Like a photo on behalf of the logged-in user. This requires the 'write_likes' scope. Note: This action is idempotent; sending the POST request to a single photo multiple times has no additional effect. :param photo_id [string]: The photo’s ID. Required. :return: [Photo]: The Un...
Below is the the instruction that describes the task: ### Input: Like a photo on behalf of the logged-in user. This requires the 'write_likes' scope. Note: This action is idempotent; sending the POST request to a single photo multiple times has no additional effect. :param photo_id...
def nfc(ctx, enable, disable, enable_all, disable_all, list, lock_code, force): """ Enable or disable applications over NFC. """ if not (list or enable_all or enable or disable_all or disable): ctx.fail('No configuration options chosen.') if enable_all: enable = APPLICATION.__membe...
Enable or disable applications over NFC.
Below is the the instruction that describes the task: ### Input: Enable or disable applications over NFC. ### Response: def nfc(ctx, enable, disable, enable_all, disable_all, list, lock_code, force): """ Enable or disable applications over NFC. """ if not (list or enable_all or enable or disable_a...
def write(self, buf): """Write bytes to the sink (if currently playing). """ buf = align_buf(buf, self._sample_width) buf = normalize_audio_buffer(buf, self.volume_percentage) return self._sink.write(buf)
Write bytes to the sink (if currently playing).
Below is the the instruction that describes the task: ### Input: Write bytes to the sink (if currently playing). ### Response: def write(self, buf): """Write bytes to the sink (if currently playing). """ buf = align_buf(buf, self._sample_width) buf = normalize_audio_buffer(buf, self...
def create_topic(self, topic): """Create a topic.""" nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/create', fields={'topic': topic})
Create a topic.
Below is the the instruction that describes the task: ### Input: Create a topic. ### Response: def create_topic(self, topic): """Create a topic.""" nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/create', fields={'topic': topic})
def instantiate_config(config): '''setup the config and load external modules This updates 'config' as follows: * All paths are replaced with absolute paths * A hash and JSON dump of the config are stored in the config * If 'pythonpath' is in the config, it is added to sys.path * If 'setup_mod...
setup the config and load external modules This updates 'config' as follows: * All paths are replaced with absolute paths * A hash and JSON dump of the config are stored in the config * If 'pythonpath' is in the config, it is added to sys.path * If 'setup_modules' is in the config, all modules nam...
Below is the the instruction that describes the task: ### Input: setup the config and load external modules This updates 'config' as follows: * All paths are replaced with absolute paths * A hash and JSON dump of the config are stored in the config * If 'pythonpath' is in the config, it is added t...
def export_ply(mesh, encoding='binary', vertex_normal=None): """ Export a mesh in the PLY format. Parameters ---------- mesh : Trimesh object encoding : ['ascii'|'binary_little_endian'] vertex_normal : include vertex normals Returns ---------- expo...
Export a mesh in the PLY format. Parameters ---------- mesh : Trimesh object encoding : ['ascii'|'binary_little_endian'] vertex_normal : include vertex normals Returns ---------- export : bytes of result
Below is the the instruction that describes the task: ### Input: Export a mesh in the PLY format. Parameters ---------- mesh : Trimesh object encoding : ['ascii'|'binary_little_endian'] vertex_normal : include vertex normals Returns ---------- export : bytes of result ### Response:...
def post(self): """token生成流程: >1. 首先使用用户名和密码去签定身份返回True/False >2. 如果True接着获取用户可公开数据 >3. 之后生成JWT 具体业务流程自由定义,比如可以保存token到redis中,设置ttl过期时间。 """ #1. username = request.form.get("username") password = request.form.get("password") exipres = 7200...
token生成流程: >1. 首先使用用户名和密码去签定身份返回True/False >2. 如果True接着获取用户可公开数据 >3. 之后生成JWT 具体业务流程自由定义,比如可以保存token到redis中,设置ttl过期时间。
Below is the the instruction that describes the task: ### Input: token生成流程: >1. 首先使用用户名和密码去签定身份返回True/False >2. 如果True接着获取用户可公开数据 >3. 之后生成JWT 具体业务流程自由定义,比如可以保存token到redis中,设置ttl过期时间。 ### Response: def post(self): """token生成流程: >1. 首先使用用户名和密码去签定身份返回True/False ...
def wait_for_master_to_start(single_master): ''' Wait for a nomad master to start ''' i = 0 while True: try: r = requests.get("http://%s:4646/v1/status/leader" % single_master) if r.status_code == 200: break except: Log.debug(sys.exc_info()[0]) Log.info("Waiting for clu...
Wait for a nomad master to start
Below is the the instruction that describes the task: ### Input: Wait for a nomad master to start ### Response: def wait_for_master_to_start(single_master): ''' Wait for a nomad master to start ''' i = 0 while True: try: r = requests.get("http://%s:4646/v1/status/leader" % single_master) ...
def save(self, *args, **kwargs): """ Updates name """ self.name = str(self.company.name) + " --- " + str(self.person) super(Executive, self).save(*args, **kwargs)
Updates name
Below is the the instruction that describes the task: ### Input: Updates name ### Response: def save(self, *args, **kwargs): """ Updates name """ self.name = str(self.company.name) + " --- " + str(self.person) super(Executive, self).save(*args, **kwargs)
def filter_record(self, record): """ Filter a single record """ quality_scores = record.letter_annotations['phred_quality'] mean_score = mean(quality_scores) if mean_score >= self.min_mean_score: return record else: raise FailedFilter(mean...
Filter a single record
Below is the the instruction that describes the task: ### Input: Filter a single record ### Response: def filter_record(self, record): """ Filter a single record """ quality_scores = record.letter_annotations['phred_quality'] mean_score = mean(quality_scores) if mea...
def _get_flatchoices(self): """ Redefine standard method. Return constants themselves instead of their names for right rendering in admin's 'change_list' view, if field is present in 'list_display' attribute of model's admin. """ return [ (self.to_pyt...
Redefine standard method. Return constants themselves instead of their names for right rendering in admin's 'change_list' view, if field is present in 'list_display' attribute of model's admin.
Below is the the instruction that describes the task: ### Input: Redefine standard method. Return constants themselves instead of their names for right rendering in admin's 'change_list' view, if field is present in 'list_display' attribute of model's admin. ### Response: def _get_flatchoi...