code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _get_vcap_services(vcap_services=None): """Retrieves the VCAP Services information from the `ConfigParams.VCAP_SERVICES` field in the config object. If `vcap_services` is not specified, it takes the information from VCAP_SERVICES environment variable. Args: vcap_services (str): Try to parse as ...
Retrieves the VCAP Services information from the `ConfigParams.VCAP_SERVICES` field in the config object. If `vcap_services` is not specified, it takes the information from VCAP_SERVICES environment variable. Args: vcap_services (str): Try to parse as a JSON string, otherwise, try open it as a file. ...
Below is the the instruction that describes the task: ### Input: Retrieves the VCAP Services information from the `ConfigParams.VCAP_SERVICES` field in the config object. If `vcap_services` is not specified, it takes the information from VCAP_SERVICES environment variable. Args: vcap_services (str)...
def _parse_args(): """Parse and return command line arguments.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=_CliFormatter) parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose output.') fb_group = parser.ad...
Parse and return command line arguments.
Below is the the instruction that describes the task: ### Input: Parse and return command line arguments. ### Response: def _parse_args(): """Parse and return command line arguments.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=_CliFormatter) parser.add_argu...
def _union_with_dsis(self, dsis): """ Union with another DiscreteStridedIntervalSet. :param dsis: :return: """ copied = self.copy() for a in dsis._si_set: copied = copied.union(a) if isinstance(copied, DiscreteStridedIntervalSet): ...
Union with another DiscreteStridedIntervalSet. :param dsis: :return:
Below is the the instruction that describes the task: ### Input: Union with another DiscreteStridedIntervalSet. :param dsis: :return: ### Response: def _union_with_dsis(self, dsis): """ Union with another DiscreteStridedIntervalSet. :param dsis: :return: ""...
def silent(duration=1000, frame_rate=11025): """ Creates an AudioSegment object of the specified duration/frame_rate filled with digital silence. :param duration: The duration of the returned object in ms. :param frame_rate: The samples per second of the returned object. :returns: AudioSegment obje...
Creates an AudioSegment object of the specified duration/frame_rate filled with digital silence. :param duration: The duration of the returned object in ms. :param frame_rate: The samples per second of the returned object. :returns: AudioSegment object filled with pure digital silence.
Below is the the instruction that describes the task: ### Input: Creates an AudioSegment object of the specified duration/frame_rate filled with digital silence. :param duration: The duration of the returned object in ms. :param frame_rate: The samples per second of the returned object. :returns: Audio...
def get_attrs_by_path(self, field_path, stop_first=False): """ It returns list of values looked up by field path. Field path is dot-formatted string path: ``parent_field.child_field``. :param field_path: field path. It allows ``*`` as wildcard. :type field_path: list or None. ...
It returns list of values looked up by field path. Field path is dot-formatted string path: ``parent_field.child_field``. :param field_path: field path. It allows ``*`` as wildcard. :type field_path: list or None. :param stop_first: Stop iteration on first value looked up. Default: Fals...
Below is the the instruction that describes the task: ### Input: It returns list of values looked up by field path. Field path is dot-formatted string path: ``parent_field.child_field``. :param field_path: field path. It allows ``*`` as wildcard. :type field_path: list or None. :par...
def three_sum(array): """ :param array: List[int] :return: Set[ Tuple[int, int, int] ] """ res = set() array.sort() for i in range(len(array) - 2): if i > 0 and array[i] == array[i - 1]: continue l, r = i + 1, len(array) - 1 while l < r: s = ar...
:param array: List[int] :return: Set[ Tuple[int, int, int] ]
Below is the the instruction that describes the task: ### Input: :param array: List[int] :return: Set[ Tuple[int, int, int] ] ### Response: def three_sum(array): """ :param array: List[int] :return: Set[ Tuple[int, int, int] ] """ res = set() array.sort() for i in range(len(array) -...
def search_response(self, request): """ creates a key from the request and searches the cache with it :param request: :return CacheElement: returns None if there's a cache miss """ logger.debug("Cache Search Response") if self.cache.is_empty() is True: ...
creates a key from the request and searches the cache with it :param request: :return CacheElement: returns None if there's a cache miss
Below is the the instruction that describes the task: ### Input: creates a key from the request and searches the cache with it :param request: :return CacheElement: returns None if there's a cache miss ### Response: def search_response(self, request): """ creates a key from the req...
def isUserCert(self, name): ''' Checks if a user certificate exists. Args: name (str): The name of the user keypair. Examples: Check if the user cert "myuser" exists: exists = cdir.isUserCert('myuser') Returns: bool: True if...
Checks if a user certificate exists. Args: name (str): The name of the user keypair. Examples: Check if the user cert "myuser" exists: exists = cdir.isUserCert('myuser') Returns: bool: True if the certificate is present, False otherwise.
Below is the the instruction that describes the task: ### Input: Checks if a user certificate exists. Args: name (str): The name of the user keypair. Examples: Check if the user cert "myuser" exists: exists = cdir.isUserCert('myuser') Returns: ...
def check_apartment_number(self, token): """ Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out, because it has a lot of false positives. """ apartment_regexes = [r'#\w+ & \w+', '#\w+ rm \w+', "#\w+-\w", r'apt ...
Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out, because it has a lot of false positives.
Below is the the instruction that describes the task: ### Input: Finds apartment, unit, #, etc, regardless of spot in string. This needs to come after everything else has been ruled out, because it has a lot of false positives. ### Response: def check_apartment_number(self, token): """ Find...
def video_bitwise_bottom(x, model_hparams, vocab_size): """Bottom transformation for embedding video bitwise.""" pixel_embedding_size = 64 inputs = x with tf.variable_scope("video_modality_bitwise", reuse=tf.AUTO_REUSE): common_layers.summarize_video(inputs, "bottom") # Embed bitwise. assert vocab_s...
Bottom transformation for embedding video bitwise.
Below is the the instruction that describes the task: ### Input: Bottom transformation for embedding video bitwise. ### Response: def video_bitwise_bottom(x, model_hparams, vocab_size): """Bottom transformation for embedding video bitwise.""" pixel_embedding_size = 64 inputs = x with tf.variable_scope("vid...
def _build_loop(self, lexer): """Build saveframe loop. :param lexer: instance of lexical analyzer. :type lexer: :func:`~nmrstarlib.bmrblex.bmrblex` :return: Fields and values of the loop. :rtype: :py:class:`tuple` """ fields = [] values = [] toke...
Build saveframe loop. :param lexer: instance of lexical analyzer. :type lexer: :func:`~nmrstarlib.bmrblex.bmrblex` :return: Fields and values of the loop. :rtype: :py:class:`tuple`
Below is the the instruction that describes the task: ### Input: Build saveframe loop. :param lexer: instance of lexical analyzer. :type lexer: :func:`~nmrstarlib.bmrblex.bmrblex` :return: Fields and values of the loop. :rtype: :py:class:`tuple` ### Response: def _build_loop(self, ...
def find_packages(path: str) -> List[str]: """ A better version of find_packages than what setuptools offers This function needs to be deterministic. :param path: :return: """ ret = [] for root, _dir, files in os.walk(path): if '__init__.py' in files: ret.append(root....
A better version of find_packages than what setuptools offers This function needs to be deterministic. :param path: :return:
Below is the the instruction that describes the task: ### Input: A better version of find_packages than what setuptools offers This function needs to be deterministic. :param path: :return: ### Response: def find_packages(path: str) -> List[str]: """ A better version of find_packages than what ...
def list_remote(local_root): """Get remote branch/tag latest SHAs. :raise GitError: When git ls-remote fails. :param str local_root: Local path to git root directory. :return: List of tuples containing strings. Each tuple is sha, name, kind. :rtype: list """ command = ['git', 'ls-remote',...
Get remote branch/tag latest SHAs. :raise GitError: When git ls-remote fails. :param str local_root: Local path to git root directory. :return: List of tuples containing strings. Each tuple is sha, name, kind. :rtype: list
Below is the the instruction that describes the task: ### Input: Get remote branch/tag latest SHAs. :raise GitError: When git ls-remote fails. :param str local_root: Local path to git root directory. :return: List of tuples containing strings. Each tuple is sha, name, kind. :rtype: list ### Respo...
def read(self, size=-1): """Read data from RAW file. Args: size: Number of bytes to read as integer. Actual number of bytes read is always equal to size unless EOF is reached. If size is negative or unspecified, read the entire file. Returns: data read as str. Raises: ...
Read data from RAW file. Args: size: Number of bytes to read as integer. Actual number of bytes read is always equal to size unless EOF is reached. If size is negative or unspecified, read the entire file. Returns: data read as str. Raises: IOError: When this buffer is c...
Below is the the instruction that describes the task: ### Input: Read data from RAW file. Args: size: Number of bytes to read as integer. Actual number of bytes read is always equal to size unless EOF is reached. If size is negative or unspecified, read the entire file. Returns: ...
def register(linter): """required method to auto register this checker""" linter.register_checker(BasicErrorChecker(linter)) linter.register_checker(BasicChecker(linter)) linter.register_checker(NameChecker(linter)) linter.register_checker(DocStringChecker(linter)) linter.register_checker(PassCh...
required method to auto register this checker
Below is the the instruction that describes the task: ### Input: required method to auto register this checker ### Response: def register(linter): """required method to auto register this checker""" linter.register_checker(BasicErrorChecker(linter)) linter.register_checker(BasicChecker(linter)) lin...
def view_structure(self, only_chains=None, opacity=1.0, recolor=False, gui=False): """Use NGLviewer to display a structure in a Jupyter notebook Args: only_chains (str, list): Chain ID or IDs to display opacity (float): Opacity of the structure recolor (bool): If str...
Use NGLviewer to display a structure in a Jupyter notebook Args: only_chains (str, list): Chain ID or IDs to display opacity (float): Opacity of the structure recolor (bool): If structure should be cleaned and recolored to silver gui (bool): If the NGLview GUI sh...
Below is the the instruction that describes the task: ### Input: Use NGLviewer to display a structure in a Jupyter notebook Args: only_chains (str, list): Chain ID or IDs to display opacity (float): Opacity of the structure recolor (bool): If structure should be cleaned ...
def _len_tube(Flow, Diam, HeadLoss, conc_chem, temp, en_chem, KMinor): """Length of tube required to get desired head loss at maximum flow based on the Hagen-Poiseuille equation.""" num1 = pc.gravity.magnitude * HeadLoss * np.pi * (Diam**4) denom1 = 128 * viscosity_kinematic_chem(conc_chem, temp, en_che...
Length of tube required to get desired head loss at maximum flow based on the Hagen-Poiseuille equation.
Below is the the instruction that describes the task: ### Input: Length of tube required to get desired head loss at maximum flow based on the Hagen-Poiseuille equation. ### Response: def _len_tube(Flow, Diam, HeadLoss, conc_chem, temp, en_chem, KMinor): """Length of tube required to get desired head loss ...
def get(self, index, id, fields=None, doc_type=EsConst.ALL_VALUES, **query_params): """ Retrieve specific record by id `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html>`_ :param index: the index name to query :param id: the id of the record :...
Retrieve specific record by id `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html>`_ :param index: the index name to query :param id: the id of the record :param fields: the fields you what to fetch from the record (str separated by comma's) :param doc...
Below is the the instruction that describes the task: ### Input: Retrieve specific record by id `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html>`_ :param index: the index name to query :param id: the id of the record :param fields: the fields you what t...
def pair_visual(*args, **kwargs): """Deprecation wrapper""" warnings.warn("`pair_visual` has moved to `cleverhans.plot.pyplot_image`. " "cleverhans.utils.pair_visual may be removed on or after " "2019-04-24.") from cleverhans.plot.pyplot_image import pair_visual as new_pair_visual ...
Deprecation wrapper
Below is the the instruction that describes the task: ### Input: Deprecation wrapper ### Response: def pair_visual(*args, **kwargs): """Deprecation wrapper""" warnings.warn("`pair_visual` has moved to `cleverhans.plot.pyplot_image`. " "cleverhans.utils.pair_visual may be removed on or after " ...
def _HandleHomepage(self, request): """Renders GRR home page by rendering base.html Jinja template.""" _ = request env = jinja2.Environment( loader=jinja2.FileSystemLoader(config.CONFIG["AdminUI.template_root"]), autoescape=True) create_time = psutil.Process(os.getpid()).create_time()...
Renders GRR home page by rendering base.html Jinja template.
Below is the the instruction that describes the task: ### Input: Renders GRR home page by rendering base.html Jinja template. ### Response: def _HandleHomepage(self, request): """Renders GRR home page by rendering base.html Jinja template.""" _ = request env = jinja2.Environment( loader=jinja...
def environment_schedule_unset(self, name): """Schedules unsetting (removing) an environment variable when creating the next guest process. This affects the :py:func:`IGuestSession.environment_changes` attribute. in name of type str Name of the environment variable to unse...
Schedules unsetting (removing) an environment variable when creating the next guest process. This affects the :py:func:`IGuestSession.environment_changes` attribute. in name of type str Name of the environment variable to unset. This cannot be empty nor can it contain...
Below is the the instruction that describes the task: ### Input: Schedules unsetting (removing) an environment variable when creating the next guest process. This affects the :py:func:`IGuestSession.environment_changes` attribute. in name of type str Name of the environment va...
def write_lock(self): """Context manager that grants a write lock. Will wait until no active readers. Blocks readers after acquiring. Guaranteed for locks to be processed in fair order (FIFO). Raises a ``RuntimeError`` if an active reader attempts to acquire a lock. ""...
Context manager that grants a write lock. Will wait until no active readers. Blocks readers after acquiring. Guaranteed for locks to be processed in fair order (FIFO). Raises a ``RuntimeError`` if an active reader attempts to acquire a lock.
Below is the the instruction that describes the task: ### Input: Context manager that grants a write lock. Will wait until no active readers. Blocks readers after acquiring. Guaranteed for locks to be processed in fair order (FIFO). Raises a ``RuntimeError`` if an active reader attempts t...
def list_cache_subnet_groups(name=None, region=None, key=None, keyid=None, profile=None): ''' Return a list of all cache subnet group names CLI example:: salt myminion boto_elasticache.list_subnet_groups region=us-east-1 ''' return [g['CacheSubnetGroupName'] fo...
Return a list of all cache subnet group names CLI example:: salt myminion boto_elasticache.list_subnet_groups region=us-east-1
Below is the the instruction that describes the task: ### Input: Return a list of all cache subnet group names CLI example:: salt myminion boto_elasticache.list_subnet_groups region=us-east-1 ### Response: def list_cache_subnet_groups(name=None, region=None, key=None, key...
def create_mongo_db(database_name, collection_name, initial_document): """Create a new database and collection by inserting one document.""" response_dict = {} try: mongodb_client_url = getattr(settings, 'MONGODB_CLIENT', 'mongodb://localhost:27017/') mc = Mo...
Create a new database and collection by inserting one document.
Below is the the instruction that describes the task: ### Input: Create a new database and collection by inserting one document. ### Response: def create_mongo_db(database_name, collection_name, initial_document): """Create a new database and collection by inserting one document.""" response_dict = {} ...
def from_learner(cls, learn: Learner, ds_type:DatasetType=DatasetType.Valid): "Create an instance of `ClassificationInterpretation`" preds = learn.get_preds(ds_type=ds_type, with_loss=True) return cls(learn, *preds)
Create an instance of `ClassificationInterpretation`
Below is the the instruction that describes the task: ### Input: Create an instance of `ClassificationInterpretation` ### Response: def from_learner(cls, learn: Learner, ds_type:DatasetType=DatasetType.Valid): "Create an instance of `ClassificationInterpretation`" preds = learn.get_preds(ds_type=d...
def update_entity(self, entity, agent=None, metadata=None): """ Updates the specified entity's values with the supplied parameters. """ body = {} if agent: body["agent_id"] = utils.get_id(agent) if metadata: body["metadata"] = metadata if b...
Updates the specified entity's values with the supplied parameters.
Below is the the instruction that describes the task: ### Input: Updates the specified entity's values with the supplied parameters. ### Response: def update_entity(self, entity, agent=None, metadata=None): """ Updates the specified entity's values with the supplied parameters. """ ...
def filter_defragment(self, threshold, mode='include', filt=True, samples=None, subset=None): """ Remove 'fragments' from the calculated filter Parameters ---------- threshold : int Contiguous data regions that contain this number or fewer points are cons...
Remove 'fragments' from the calculated filter Parameters ---------- threshold : int Contiguous data regions that contain this number or fewer points are considered 'fragments' mode : str Specifies wither to 'include' or 'exclude' the identified ...
Below is the the instruction that describes the task: ### Input: Remove 'fragments' from the calculated filter Parameters ---------- threshold : int Contiguous data regions that contain this number or fewer points are considered 'fragments' mode : str ...
def deregisterevent(self, event_name): """ Remove callback of registered event @param event_name: Event name in at-spi format. @type event_name: string @return: 1 if registration was successful, 0 if not. @rtype: integer """ if event_name in self._pollE...
Remove callback of registered event @param event_name: Event name in at-spi format. @type event_name: string @return: 1 if registration was successful, 0 if not. @rtype: integer
Below is the the instruction that describes the task: ### Input: Remove callback of registered event @param event_name: Event name in at-spi format. @type event_name: string @return: 1 if registration was successful, 0 if not. @rtype: integer ### Response: def deregisterevent(self...
def get_carrier_concentration(self): """ gives the carrier concentration (in cm^-3) Returns a dictionary {temp:[]} with an array of carrier concentration (in cm^-3) at each temperature The array relates to each step of electron chemical potential """ ...
gives the carrier concentration (in cm^-3) Returns a dictionary {temp:[]} with an array of carrier concentration (in cm^-3) at each temperature The array relates to each step of electron chemical potential
Below is the the instruction that describes the task: ### Input: gives the carrier concentration (in cm^-3) Returns a dictionary {temp:[]} with an array of carrier concentration (in cm^-3) at each temperature The array relates to each step of electron chemical potential ...
def _page(q, chunk=1000): """ Quick utility to page a query, 1000 items at a time. We need this so we don't OOM (out of memory) ourselves loading the world. """ offset = 0 while True: r = False for elem in q.limit(chunk).offset(offset): r = True yield elem ...
Quick utility to page a query, 1000 items at a time. We need this so we don't OOM (out of memory) ourselves loading the world.
Below is the the instruction that describes the task: ### Input: Quick utility to page a query, 1000 items at a time. We need this so we don't OOM (out of memory) ourselves loading the world. ### Response: def _page(q, chunk=1000): """ Quick utility to page a query, 1000 items at a time. We need this s...
def permissions(self, addr, permissions=None): """ Retrieve the permissions of the page at address `addr`. :param addr: address to get the page permissions :param permissions: Integer or BVV to optionally set page permissions to :return: AST representing the pe...
Retrieve the permissions of the page at address `addr`. :param addr: address to get the page permissions :param permissions: Integer or BVV to optionally set page permissions to :return: AST representing the permissions on the page
Below is the the instruction that describes the task: ### Input: Retrieve the permissions of the page at address `addr`. :param addr: address to get the page permissions :param permissions: Integer or BVV to optionally set page permissions to :return: AST representing the ...
def commit_channel(self, channel_id): """ commit_channel: commits channel to Kolibri Studio Args: channel_id (str): channel's id on Kolibri Studio Returns: channel id and link to uploadedchannel """ payload = { "channel_id":channel_id, ...
commit_channel: commits channel to Kolibri Studio Args: channel_id (str): channel's id on Kolibri Studio Returns: channel id and link to uploadedchannel
Below is the the instruction that describes the task: ### Input: commit_channel: commits channel to Kolibri Studio Args: channel_id (str): channel's id on Kolibri Studio Returns: channel id and link to uploadedchannel ### Response: def commit_channel(self, channel_id): ...
def send_msg_to_clients(client_ids, msg, error=False): """Send message to all clients""" if error: stream = "stderr" else: stream = "stdout" response = [{"message": None, "type": "console", "payload": msg, "stream": stream}] for client_id in client_ids: logger.info("emiting...
Send message to all clients
Below is the the instruction that describes the task: ### Input: Send message to all clients ### Response: def send_msg_to_clients(client_ids, msg, error=False): """Send message to all clients""" if error: stream = "stderr" else: stream = "stdout" response = [{"message": None, "typ...
def getAllowedInstruments(self): """Returns the allowed instruments for this analysis, either if the instrument was assigned directly (by using "Allows instrument entry of results") or indirectly via Method (by using "Allows manual entry of results") in Analysis Service edit view. ...
Returns the allowed instruments for this analysis, either if the instrument was assigned directly (by using "Allows instrument entry of results") or indirectly via Method (by using "Allows manual entry of results") in Analysis Service edit view. :return: A list of instruments allowed for...
Below is the the instruction that describes the task: ### Input: Returns the allowed instruments for this analysis, either if the instrument was assigned directly (by using "Allows instrument entry of results") or indirectly via Method (by using "Allows manual entry of results") in Analysis ...
def normalize_rgb(r, g, b, a): """Transform a rgb[a] color to #hex[a]. """ r = int(r, 10) g = int(g, 10) b = int(b, 10) if a: a = float(a) * 256 if r > 255 or g > 255 or b > 255 or (a and a > 255): return None color = '#%02x%02x%02x' % (r, g, b) if a: color +=...
Transform a rgb[a] color to #hex[a].
Below is the the instruction that describes the task: ### Input: Transform a rgb[a] color to #hex[a]. ### Response: def normalize_rgb(r, g, b, a): """Transform a rgb[a] color to #hex[a]. """ r = int(r, 10) g = int(g, 10) b = int(b, 10) if a: a = float(a) * 256 if r > 255 or g > ...
def close(self): """ Unclaim the PEP node and unregister the registered features. It is not necessary to call close if this claim is managed by :class:`~aioxmpp.pep.register_pep_node`. """ if self._closed: return self._closed = True self._pep...
Unclaim the PEP node and unregister the registered features. It is not necessary to call close if this claim is managed by :class:`~aioxmpp.pep.register_pep_node`.
Below is the the instruction that describes the task: ### Input: Unclaim the PEP node and unregister the registered features. It is not necessary to call close if this claim is managed by :class:`~aioxmpp.pep.register_pep_node`. ### Response: def close(self): """ Unclaim the PEP no...
def incrementSub(self, amount=1): """ Increments the sub-progress bar by amount. """ self._subProgressBar.setValue(self.subValue() + amount) QApplication.instance().processEvents()
Increments the sub-progress bar by amount.
Below is the the instruction that describes the task: ### Input: Increments the sub-progress bar by amount. ### Response: def incrementSub(self, amount=1): """ Increments the sub-progress bar by amount. """ self._subProgressBar.setValue(self.subValue() + amount) QApplicatio...
def get_frames_singleimage(self): """ Get current left and right frames from a single image, by splitting the image in half. """ frame = self.captures[0].read()[1] height, width, colors = frame.shape left_frame = frame[:, :width/2, :] right_frame = frame[:...
Get current left and right frames from a single image, by splitting the image in half.
Below is the the instruction that describes the task: ### Input: Get current left and right frames from a single image, by splitting the image in half. ### Response: def get_frames_singleimage(self): """ Get current left and right frames from a single image, by splitting the image i...
def weight_from_comm(self, v, comm): """ The total number of edges (or sum of weights) to node ``v`` from community ``comm``. See Also -------- :func:`~VertexPartition.MutableVertexPartition.weight_to_comm` """ return _c_leiden._MutableVertexPartition_weight_from_comm(self._partition, v, co...
The total number of edges (or sum of weights) to node ``v`` from community ``comm``. See Also -------- :func:`~VertexPartition.MutableVertexPartition.weight_to_comm`
Below is the the instruction that describes the task: ### Input: The total number of edges (or sum of weights) to node ``v`` from community ``comm``. See Also -------- :func:`~VertexPartition.MutableVertexPartition.weight_to_comm` ### Response: def weight_from_comm(self, v, comm): """ The tota...
def _compile_schema(self, schema): """ Compile another schema """ assert self.matcher == schema.matcher self.name = schema.name self.compiled_type = schema.compiled_type return schema.compiled
Compile another schema
Below is the the instruction that describes the task: ### Input: Compile another schema ### Response: def _compile_schema(self, schema): """ Compile another schema """ assert self.matcher == schema.matcher self.name = schema.name self.compiled_type = schema.compiled_type r...
def register_result(self, job, skip_sanity_checks=False): """ function to register the result of a job This function is called from HB_master, don't call this from your script. """ if self.is_finished: raise RuntimeError("This HB iteration is finished, you can't register more results!") config_id = ...
function to register the result of a job This function is called from HB_master, don't call this from your script.
Below is the the instruction that describes the task: ### Input: function to register the result of a job This function is called from HB_master, don't call this from your script. ### Response: def register_result(self, job, skip_sanity_checks=False): """ function to register the result of a job This f...
def run(self, rapid_namelist_file=""): """ Run RAPID program and generate file based on inputs This will generate your rapid_namelist file and run RAPID from wherever you call this script (your working directory). Parameters ---------- rapid_namelist_file: str, o...
Run RAPID program and generate file based on inputs This will generate your rapid_namelist file and run RAPID from wherever you call this script (your working directory). Parameters ---------- rapid_namelist_file: str, optional Path of namelist file to use in the sim...
Below is the the instruction that describes the task: ### Input: Run RAPID program and generate file based on inputs This will generate your rapid_namelist file and run RAPID from wherever you call this script (your working directory). Parameters ---------- rapid_namelist_fi...
def publish(self, event_type, events): """Publish events.""" assert event_type in self.events current_queues.queues['stats-{}'.format(event_type)].publish(events)
Publish events.
Below is the the instruction that describes the task: ### Input: Publish events. ### Response: def publish(self, event_type, events): """Publish events.""" assert event_type in self.events current_queues.queues['stats-{}'.format(event_type)].publish(events)
def _SkipGroup(buffer, pos, end): """Skip sub-group. Returns the new position.""" while 1: (tag_bytes, pos) = ReadTag(buffer, pos) new_pos = SkipField(buffer, pos, end, tag_bytes) if new_pos == -1: return pos pos = new_pos
Skip sub-group. Returns the new position.
Below is the the instruction that describes the task: ### Input: Skip sub-group. Returns the new position. ### Response: def _SkipGroup(buffer, pos, end): """Skip sub-group. Returns the new position.""" while 1: (tag_bytes, pos) = ReadTag(buffer, pos) new_pos = SkipField(buffer, pos, end, tag_bytes)...
def read(afile): """Read a file into setup""" the_relative_file = os.path.join(HERE, afile) with codecs.open(the_relative_file, 'r', 'utf-8') as opened_file: content = filter_out_test_code(opened_file) content = "".join(list(content)) return content
Read a file into setup
Below is the the instruction that describes the task: ### Input: Read a file into setup ### Response: def read(afile): """Read a file into setup""" the_relative_file = os.path.join(HERE, afile) with codecs.open(the_relative_file, 'r', 'utf-8') as opened_file: content = filter_out_test_code(open...
def _get_host_details(self): """Get the system details.""" # Assuming only one system present as part of collection, # as we are dealing with iLO's here. status, headers, system = self._rest_get('/rest/v1/Systems/1') if status < 300: stype = self._get_type(system) ...
Get the system details.
Below is the the instruction that describes the task: ### Input: Get the system details. ### Response: def _get_host_details(self): """Get the system details.""" # Assuming only one system present as part of collection, # as we are dealing with iLO's here. status, headers, system = ...
def authenticate(self): """ Handles authentication, and persists the X-APPLE-WEB-KB cookie so that subsequent logins will not cause additional e-mails from Apple. """ logger.info("Authenticating as %s", self.user['apple_id']) data = dict(self.user) # We authent...
Handles authentication, and persists the X-APPLE-WEB-KB cookie so that subsequent logins will not cause additional e-mails from Apple.
Below is the the instruction that describes the task: ### Input: Handles authentication, and persists the X-APPLE-WEB-KB cookie so that subsequent logins will not cause additional e-mails from Apple. ### Response: def authenticate(self): """ Handles authentication, and persists the X-APPLE-...
def to_html(self, table_width=5): """Write the program information to HTML code, which can be saved, printed and brought to the gym. Parameters ---------- table_width The table with of the HTML code. Returns ------- string HTML co...
Write the program information to HTML code, which can be saved, printed and brought to the gym. Parameters ---------- table_width The table with of the HTML code. Returns ------- string HTML code.
Below is the the instruction that describes the task: ### Input: Write the program information to HTML code, which can be saved, printed and brought to the gym. Parameters ---------- table_width The table with of the HTML code. Returns ------- st...
def open_external_editor(filename=None, sql=None): """Open external editor, wait for the user to type in their query, return the query. :return: list with one tuple, query as first element. """ message = None filename = filename.strip().split(' ', 1)[0] if filename else None sql = sql or '...
Open external editor, wait for the user to type in their query, return the query. :return: list with one tuple, query as first element.
Below is the the instruction that describes the task: ### Input: Open external editor, wait for the user to type in their query, return the query. :return: list with one tuple, query as first element. ### Response: def open_external_editor(filename=None, sql=None): """Open external editor, wait for the...
def load_blind(self, item): """Load blind from JSON.""" blind = Blind.from_config(self.pyvlx, item) self.add(blind)
Load blind from JSON.
Below is the the instruction that describes the task: ### Input: Load blind from JSON. ### Response: def load_blind(self, item): """Load blind from JSON.""" blind = Blind.from_config(self.pyvlx, item) self.add(blind)
def set_scalebar_for_all(self, row_column_list=None, location='lower right'): """Show marker area scale for subplots. :param row_column_list: a list containing (row, column) tuples to specify the subplots, or None to indicate *all* subplots. :param locat...
Show marker area scale for subplots. :param row_column_list: a list containing (row, column) tuples to specify the subplots, or None to indicate *all* subplots. :param location: the location of the label inside the plot. May be one of 'center', 'upper right', 'lower right', 'up...
Below is the the instruction that describes the task: ### Input: Show marker area scale for subplots. :param row_column_list: a list containing (row, column) tuples to specify the subplots, or None to indicate *all* subplots. :param location: the location of the label inside the plot. ...
def endStep(self,key): """ Record the end time for the step. If key==None, simply record ptime as end time for class to represent the overall runtime since the initialization of the class. """ ptime = _ptime() if key is not None: self.steps[key]['end'...
Record the end time for the step. If key==None, simply record ptime as end time for class to represent the overall runtime since the initialization of the class.
Below is the the instruction that describes the task: ### Input: Record the end time for the step. If key==None, simply record ptime as end time for class to represent the overall runtime since the initialization of the class. ### Response: def endStep(self,key): """ Record the end...
def get_new_addresses( self, index=0, count=1, security_level=AddressGenerator.DEFAULT_SECURITY_LEVEL, checksum=False, ): # type: (int, Optional[int], int, bool) -> dict """ Generates one or more new addresses from the seed. ...
Generates one or more new addresses from the seed. :param index: The key index of the first new address to generate (must be >= 1). :param count: Number of addresses to generate (must be >= 1). .. tip:: This is more efficient than callin...
Below is the the instruction that describes the task: ### Input: Generates one or more new addresses from the seed. :param index: The key index of the first new address to generate (must be >= 1). :param count: Number of addresses to generate (must be >= 1). ...
def uridefrag(uristring): """Remove an existing fragment component from a URI reference string. """ if isinstance(uristring, bytes): parts = uristring.partition(b'#') else: parts = uristring.partition(u'#') return DefragResult(parts[0], parts[2] if parts[1] else None)
Remove an existing fragment component from a URI reference string.
Below is the the instruction that describes the task: ### Input: Remove an existing fragment component from a URI reference string. ### Response: def uridefrag(uristring): """Remove an existing fragment component from a URI reference string. """ if isinstance(uristring, bytes): parts = uristri...
def route(vertices_resources, nets, machine, constraints, placements, allocations={}, core_resource=Cores, radius=20): """Routing algorithm based on Neighbour Exploring Routing (NER). Algorithm refrence: J. Navaridas et al. SpiNNaker: Enhanced multicast routing, Parallel Computing (2014). htt...
Routing algorithm based on Neighbour Exploring Routing (NER). Algorithm refrence: J. Navaridas et al. SpiNNaker: Enhanced multicast routing, Parallel Computing (2014). http://dx.doi.org/10.1016/j.parco.2015.01.002 This algorithm attempts to use NER to generate routing trees for all nets and routes...
Below is the the instruction that describes the task: ### Input: Routing algorithm based on Neighbour Exploring Routing (NER). Algorithm refrence: J. Navaridas et al. SpiNNaker: Enhanced multicast routing, Parallel Computing (2014). http://dx.doi.org/10.1016/j.parco.2015.01.002 This algorithm atte...
def facts(self, **kwargs): """Get all facts of this node. Additional arguments may also be specified that will be passed to the query function. """ return self.__api.facts(query=EqualsOperator("certname", self.name), **kwargs)
Get all facts of this node. Additional arguments may also be specified that will be passed to the query function.
Below is the the instruction that describes the task: ### Input: Get all facts of this node. Additional arguments may also be specified that will be passed to the query function. ### Response: def facts(self, **kwargs): """Get all facts of this node. Additional arguments may also be specifi...
def system(cmd, data=None): ''' pipes the output of a program ''' import subprocess s = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) out, err = s.communicate(data) return out.decode('utf8')
pipes the output of a program
Below is the the instruction that describes the task: ### Input: pipes the output of a program ### Response: def system(cmd, data=None): ''' pipes the output of a program ''' import subprocess s = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) out, err = s.communicate(...
def load_pricing_adjustments(self, columns, dts, assets): """ Returns ------- adjustments : list[dict[int -> Adjustment]] A list, where each element corresponds to the `columns`, of mappings from index to adjustment objects to apply at that index. """ ...
Returns ------- adjustments : list[dict[int -> Adjustment]] A list, where each element corresponds to the `columns`, of mappings from index to adjustment objects to apply at that index.
Below is the the instruction that describes the task: ### Input: Returns ------- adjustments : list[dict[int -> Adjustment]] A list, where each element corresponds to the `columns`, of mappings from index to adjustment objects to apply at that index. ### Response: def load_p...
def get_region_vcf(self, case_obj, chrom=None, start=None, end=None, gene_obj=None, variant_type='clinical', category='snv', rank_threshold=None): """Produce a reduced vcf with variants from the specified coordinates This is used for the alignment viewer....
Produce a reduced vcf with variants from the specified coordinates This is used for the alignment viewer. Args: case_obj(dict): A case from the scout database variant_type(str): 'clinical' or 'research'. Default: 'clinical' category(str): 'snv' or 'sv'. Default: '...
Below is the the instruction that describes the task: ### Input: Produce a reduced vcf with variants from the specified coordinates This is used for the alignment viewer. Args: case_obj(dict): A case from the scout database variant_type(str): 'clinical' or 'research'. Def...
def request(self, endpoint): """Perform a request for the APIRequest instance 'endpoint'. Parameters ---------- endpoint : APIRequest The endpoint parameter contains an instance of an APIRequest containing the endpoint, method and optionally other parameters ...
Perform a request for the APIRequest instance 'endpoint'. Parameters ---------- endpoint : APIRequest The endpoint parameter contains an instance of an APIRequest containing the endpoint, method and optionally other parameters or body data. Raises ...
Below is the the instruction that describes the task: ### Input: Perform a request for the APIRequest instance 'endpoint'. Parameters ---------- endpoint : APIRequest The endpoint parameter contains an instance of an APIRequest containing the endpoint, method and opt...
def tweet(tweet_text_func): ''' A decorator to make a function Tweet Parameters - `tweet_text_func` is a function that takes no parameters and returns a tweetable string For example:: @tweet def total_deposits_this_week(): # ... @tweet def not_an_inte...
A decorator to make a function Tweet Parameters - `tweet_text_func` is a function that takes no parameters and returns a tweetable string For example:: @tweet def total_deposits_this_week(): # ... @tweet def not_an_interesting_tweet(): return 'Thi...
Below is the the instruction that describes the task: ### Input: A decorator to make a function Tweet Parameters - `tweet_text_func` is a function that takes no parameters and returns a tweetable string For example:: @tweet def total_deposits_this_week(): # ... @...
def add_char(self, char): """ Process the next character of input through the translation finite state maching (FSM). There are two possible states, buffer pending and not pending, but those are hidden behind the ``.flush()`` method which must be called at the end of text to ensu...
Process the next character of input through the translation finite state maching (FSM). There are two possible states, buffer pending and not pending, but those are hidden behind the ``.flush()`` method which must be called at the end of text to ensure any pending ``<w:t>`` element is wr...
Below is the the instruction that describes the task: ### Input: Process the next character of input through the translation finite state maching (FSM). There are two possible states, buffer pending and not pending, but those are hidden behind the ``.flush()`` method which must be called at ...
def pipeline(stages, run=True, stride=1, chunksize=None): r""" Data analysis pipeline. Constructs a data analysis :class:`Pipeline <pyemma.coordinates.pipelines.Pipeline>` and parametrizes it (unless prevented). If this function takes too long, consider loading data in memory. Alternatively if the ...
r""" Data analysis pipeline. Constructs a data analysis :class:`Pipeline <pyemma.coordinates.pipelines.Pipeline>` and parametrizes it (unless prevented). If this function takes too long, consider loading data in memory. Alternatively if the data is to large to be loaded into memory make use of the ...
Below is the the instruction that describes the task: ### Input: r""" Data analysis pipeline. Constructs a data analysis :class:`Pipeline <pyemma.coordinates.pipelines.Pipeline>` and parametrizes it (unless prevented). If this function takes too long, consider loading data in memory. Alternatively ...
def _det_inference(self): """ Internal method for determining the inference method """ # 2 random effects with complete design -> gp2KronSum # TODO: add check for low-rankness, use GP3KronSumLR and GP2KronSumLR when possible if (self.n_randEffs==2) and (~sp.isnan(self.Y)....
Internal method for determining the inference method
Below is the the instruction that describes the task: ### Input: Internal method for determining the inference method ### Response: def _det_inference(self): """ Internal method for determining the inference method """ # 2 random effects with complete design -> gp2KronSum # ...
def getLocalDeformationEnergy(self, bp, complexDna, freeDnaFrames=None, boundDnaFrames=None, helical=False, unit='kT', which='all', outFile=None): r"""Deformation energy of the input DNA using local elastic properties The deformation energy of a base-step/s for probe D...
r"""Deformation energy of the input DNA using local elastic properties The deformation energy of a base-step/s for probe DNA object with reference to the same base-step/s DNA present in the current DNA object. The deformation free energy is calculated using elastic matrix as follows ....
Below is the the instruction that describes the task: ### Input: r"""Deformation energy of the input DNA using local elastic properties The deformation energy of a base-step/s for probe DNA object with reference to the same base-step/s DNA present in the current DNA object. The deformation...
def prep_db_parallel(samples, parallel_fn): """Prepares gemini databases in parallel, handling jointly called populations. """ batch_groups, singles, out_retrieve, extras = _group_by_batches(samples, _has_variant_calls) to_process = [] has_batches = False for (name, caller), info in batch_groups...
Prepares gemini databases in parallel, handling jointly called populations.
Below is the the instruction that describes the task: ### Input: Prepares gemini databases in parallel, handling jointly called populations. ### Response: def prep_db_parallel(samples, parallel_fn): """Prepares gemini databases in parallel, handling jointly called populations. """ batch_groups, singles...
def get_assessment_ids(self): """Gets the Ids of any assessments associated with this activity. return: (osid.id.IdList) - list of assessment Ids raise: IllegalState - is_assessment_based_activity() is false compliance: mandatory - This method must be implemented. """ ...
Gets the Ids of any assessments associated with this activity. return: (osid.id.IdList) - list of assessment Ids raise: IllegalState - is_assessment_based_activity() is false compliance: mandatory - This method must be implemented.
Below is the the instruction that describes the task: ### Input: Gets the Ids of any assessments associated with this activity. return: (osid.id.IdList) - list of assessment Ids raise: IllegalState - is_assessment_based_activity() is false compliance: mandatory - This method must be implem...
def preview(src_path): ''' Generates a preview of src_path in the requested format. :returns: A list of preview paths, one for each page. ''' previews = [] if sketch.is_sketchfile(src_path): previews = sketch.preview(src_path) if not previews: previews = quicklook.preview(src_path) previews = [...
Generates a preview of src_path in the requested format. :returns: A list of preview paths, one for each page.
Below is the the instruction that describes the task: ### Input: Generates a preview of src_path in the requested format. :returns: A list of preview paths, one for each page. ### Response: def preview(src_path): ''' Generates a preview of src_path in the requested format. :returns: A list of preview paths, ...
def parse_rpm_output(output, tags=None, separator=';'): """ Parse output of the rpm query. :param output: list, decoded output (str) from the rpm subprocess :param tags: list, str fields used for query output :return: list, dicts describing each rpm package """ if tags is None: tag...
Parse output of the rpm query. :param output: list, decoded output (str) from the rpm subprocess :param tags: list, str fields used for query output :return: list, dicts describing each rpm package
Below is the the instruction that describes the task: ### Input: Parse output of the rpm query. :param output: list, decoded output (str) from the rpm subprocess :param tags: list, str fields used for query output :return: list, dicts describing each rpm package ### Response: def parse_rpm_output(outp...
async def delete(self, device, remove=True): """ Detach the loop device. :param device: device object, block device path or mount path :param bool remove: whether to unmount the partition etc. :returns: whether the loop device is deleted """ device = self._find_d...
Detach the loop device. :param device: device object, block device path or mount path :param bool remove: whether to unmount the partition etc. :returns: whether the loop device is deleted
Below is the the instruction that describes the task: ### Input: Detach the loop device. :param device: device object, block device path or mount path :param bool remove: whether to unmount the partition etc. :returns: whether the loop device is deleted ### Response: async def delete(self,...
def add_link(self, rel, target, wrap=False, **kwargs): """Adds a link to the document. This method adds a link to the given ``target`` to the document with the given ``rel``. If one or more links are already present for that link relationship type, the new link will be added to the exis...
Adds a link to the document. This method adds a link to the given ``target`` to the document with the given ``rel``. If one or more links are already present for that link relationship type, the new link will be added to the existing links for that link relationship type. Unlik...
Below is the the instruction that describes the task: ### Input: Adds a link to the document. This method adds a link to the given ``target`` to the document with the given ``rel``. If one or more links are already present for that link relationship type, the new link will be added to the e...
def byte_adaptor(fbuffer): """ provides py3 compatibility by converting byte based file stream to string based file stream Arguments: fbuffer: file like objects containing bytes Returns: string buffer """ if six.PY3: strings = fbuffer.read().decode('latin-1') fb...
provides py3 compatibility by converting byte based file stream to string based file stream Arguments: fbuffer: file like objects containing bytes Returns: string buffer
Below is the the instruction that describes the task: ### Input: provides py3 compatibility by converting byte based file stream to string based file stream Arguments: fbuffer: file like objects containing bytes Returns: string buffer ### Response: def byte_adaptor(fbuffer): """ p...
def list_by_instance(self, instance_id): """Gets security groups of an instance. :returns: List of SecurityGroup objects associated with the instance """ ports = port_list(self.request, device_id=instance_id) sg_ids = [] for p in ports: sg_ids += p.security_g...
Gets security groups of an instance. :returns: List of SecurityGroup objects associated with the instance
Below is the the instruction that describes the task: ### Input: Gets security groups of an instance. :returns: List of SecurityGroup objects associated with the instance ### Response: def list_by_instance(self, instance_id): """Gets security groups of an instance. :returns: List of Secur...
def add_doc(self, doc): """ Simple dict of {'name': '@filename.pdf'}""" if isinstance(doc, HelloDoc) and doc.validate(): self.docs.append(doc) else: if not doc.validate(): raise Exception("HelloDoc Errors %s" % (doc.errors,)) else: ...
Simple dict of {'name': '@filename.pdf'}
Below is the the instruction that describes the task: ### Input: Simple dict of {'name': '@filename.pdf'} ### Response: def add_doc(self, doc): """ Simple dict of {'name': '@filename.pdf'}""" if isinstance(doc, HelloDoc) and doc.validate(): self.docs.append(doc) else: ...
def open_acqdata(filename, user='unknown', filemode='w-'): """Opens and returns the correct AcquisitionData object according to filename extention. Supported extentions: * .hdf5, .h5 for sparkle data * .pst, .raw for batlab data. Both the .pst and .raw file must be co-located and share the same base fi...
Opens and returns the correct AcquisitionData object according to filename extention. Supported extentions: * .hdf5, .h5 for sparkle data * .pst, .raw for batlab data. Both the .pst and .raw file must be co-located and share the same base file name, but only one should be provided to this function ...
Below is the the instruction that describes the task: ### Input: Opens and returns the correct AcquisitionData object according to filename extention. Supported extentions: * .hdf5, .h5 for sparkle data * .pst, .raw for batlab data. Both the .pst and .raw file must be co-located and share the same base...
def compute_rotsym(self, threshold=1e-3*angstrom): """Compute the rotational symmetry number. Optional argument: | ``threshold`` -- only when a rotation results in an rmsd below the given threshold, the rotation is considered to transform the ...
Compute the rotational symmetry number. Optional argument: | ``threshold`` -- only when a rotation results in an rmsd below the given threshold, the rotation is considered to transform the molecule onto itself.
Below is the the instruction that describes the task: ### Input: Compute the rotational symmetry number. Optional argument: | ``threshold`` -- only when a rotation results in an rmsd below the given threshold, the rotation is considered to transform the ...
def build_global(self, global_node): """parse `global` section, and return the config.Global Args: global_node (TreeNode): `global` section treenode Returns: config.Global: an object """ config_block_lines = self.__build_config_block( globa...
parse `global` section, and return the config.Global Args: global_node (TreeNode): `global` section treenode Returns: config.Global: an object
Below is the the instruction that describes the task: ### Input: parse `global` section, and return the config.Global Args: global_node (TreeNode): `global` section treenode Returns: config.Global: an object ### Response: def build_global(self, global_node): """p...
def upload(self, filepaths, enable_matching=False, transcode_quality='320k', delete_on_success=False): """Upload local songs to Google Music. Parameters: filepaths (list or str): Filepath(s) to upload. enable_matching (bool): If ``True`` attempt to use `scan and match <http://support.google.com/googlepl...
Upload local songs to Google Music. Parameters: filepaths (list or str): Filepath(s) to upload. enable_matching (bool): If ``True`` attempt to use `scan and match <http://support.google.com/googleplay/bin/answer.py?hl=en&answer=2920799&topic=2450455>`__. This requieres ffmpeg or avconv. transcode_...
Below is the the instruction that describes the task: ### Input: Upload local songs to Google Music. Parameters: filepaths (list or str): Filepath(s) to upload. enable_matching (bool): If ``True`` attempt to use `scan and match <http://support.google.com/googleplay/bin/answer.py?hl=en&answer=2920799&t...
def _switch_charset_list(characters, target=''): ''' Switches the character set of a list. If a character does not have an equivalent in the target script (e.g. ヹ when converting to hiragana), the original character is kept. ''' # Copy the list to avoid modifying the existing one. characters...
Switches the character set of a list. If a character does not have an equivalent in the target script (e.g. ヹ when converting to hiragana), the original character is kept.
Below is the the instruction that describes the task: ### Input: Switches the character set of a list. If a character does not have an equivalent in the target script (e.g. ヹ when converting to hiragana), the original character is kept. ### Response: def _switch_charset_list(characters, target=''): '''...
def get_plot(self, subplot=False, width=None, height=None, xmin=-6., xmax=6., yscale=1, colours=None, plot_total=True, legend_on=True, num_columns=2, legend_frame_on=False, legend_cutoff=3, xlabel='Energy (eV)', ylabel='Arb. units', zero_to_efermi=True...
Get a :obj:`matplotlib.pyplot` object of the density of states. Args: subplot (:obj:`bool`, optional): Plot the density of states for each element on separate subplots. Defaults to ``False``. width (:obj:`float`, optional): The width of the plot. height (:obj...
Below is the the instruction that describes the task: ### Input: Get a :obj:`matplotlib.pyplot` object of the density of states. Args: subplot (:obj:`bool`, optional): Plot the density of states for each element on separate subplots. Defaults to ``False``. width (:ob...
def strip_context_items(self, a_string): """Strip PaloAlto-specific output. PaloAlto will also put a configuration context: [edit] This method removes those lines. """ strings_to_strip = [r"\[edit.*\]"] response_list = a_string.split(self.RESPONSE_RETURN) ...
Strip PaloAlto-specific output. PaloAlto will also put a configuration context: [edit] This method removes those lines.
Below is the the instruction that describes the task: ### Input: Strip PaloAlto-specific output. PaloAlto will also put a configuration context: [edit] This method removes those lines. ### Response: def strip_context_items(self, a_string): """Strip PaloAlto-specific output. ...
def find_packages(path): """ Find all java files matching the "*Package.java" pattern within the given enaml package directory relative to the java source path. """ matches = [] root = join(path, 'src', 'main', 'java') for folder, dirnames, filenames in os.walk(root): ...
Find all java files matching the "*Package.java" pattern within the given enaml package directory relative to the java source path.
Below is the the instruction that describes the task: ### Input: Find all java files matching the "*Package.java" pattern within the given enaml package directory relative to the java source path. ### Response: def find_packages(path): """ Find all java files matching the "*Package.java" pattern wi...
def train(sess, loss, x_train, y_train, init_all=False, evaluate=None, feed=None, args=None, rng=None, var_list=None, fprop_args=None, optimizer=None, devices=None, x_batch_preprocessor=None, use_ema=False, ema_decay=.998, run_canary=None, loss_threshold=1e5, dataset_tr...
Run (optionally multi-replica, synchronous) training to minimize `loss` :param sess: TF session to use when training the graph :param loss: tensor, the loss to minimize :param x_train: numpy array with training inputs or tf Dataset :param y_train: numpy array with training outputs or tf Dataset :param init_al...
Below is the the instruction that describes the task: ### Input: Run (optionally multi-replica, synchronous) training to minimize `loss` :param sess: TF session to use when training the graph :param loss: tensor, the loss to minimize :param x_train: numpy array with training inputs or tf Dataset :param y_tr...
def export(self, path, column_names=None, byteorder="=", shuffle=False, selection=False, progress=None, virtual=False, sort=None, ascending=True): """Exports the DataFrame to a file written with arrow :param DataFrameLocal df: DataFrame to export :param str path: path for file :param li...
Exports the DataFrame to a file written with arrow :param DataFrameLocal df: DataFrame to export :param str path: path for file :param lis[str] column_names: list of column names to export or None for all columns :param str byteorder: = for native, < for little endian and > for big endi...
Below is the the instruction that describes the task: ### Input: Exports the DataFrame to a file written with arrow :param DataFrameLocal df: DataFrame to export :param str path: path for file :param lis[str] column_names: list of column names to export or None for all columns :para...
def save(self): """ Send out a password reset if the provided data is valid. If the provided email address exists and is verified, a reset email is sent to the address. Returns: The password reset token if it was returned and ``None`` otherwise. ...
Send out a password reset if the provided data is valid. If the provided email address exists and is verified, a reset email is sent to the address. Returns: The password reset token if it was returned and ``None`` otherwise.
Below is the the instruction that describes the task: ### Input: Send out a password reset if the provided data is valid. If the provided email address exists and is verified, a reset email is sent to the address. Returns: The password reset token if it was returned and ``None`...
def process(self, metrics, config): """Processes metrics. This method is called by the Snap deamon during the process phase of the execution of a Snap workflow. Examples of processing metrics include applying filtering, max, min, average functions as well as adding additional c...
Processes metrics. This method is called by the Snap deamon during the process phase of the execution of a Snap workflow. Examples of processing metrics include applying filtering, max, min, average functions as well as adding additional context to the metrics to name just a few. ...
Below is the the instruction that describes the task: ### Input: Processes metrics. This method is called by the Snap deamon during the process phase of the execution of a Snap workflow. Examples of processing metrics include applying filtering, max, min, average functions as well as ...
def getAsKmlPngAnimation(self, session, projectFile=None, path=None, documentName=None, colorRamp=None, alpha=1.0, noDataValue=0, drawOrder=0, cellSize=None, resampleMethod='NearestNeighbour'): """ Retrieve the WMS dataset as a PNG time stamped KMZ Args: ...
Retrieve the WMS dataset as a PNG time stamped KMZ Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database. projectFile(:class:`gsshapy.orm.ProjectFile`): Project file object for the GSSHA project to which the WMS dataset belong...
Below is the the instruction that describes the task: ### Input: Retrieve the WMS dataset as a PNG time stamped KMZ Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database. projectFile(:class:`gsshapy.orm.ProjectFile`): Proj...
def get_usertag(email, *tags): """Get buglists by usertags. Parameters ---------- email : str tags : tuple of strings If tags are given the dictionary is limited to the matching tags, if no tags are given all available tags are returned. Returns ------- mapping : dict ...
Get buglists by usertags. Parameters ---------- email : str tags : tuple of strings If tags are given the dictionary is limited to the matching tags, if no tags are given all available tags are returned. Returns ------- mapping : dict a mapping of usertag -> buglist
Below is the the instruction that describes the task: ### Input: Get buglists by usertags. Parameters ---------- email : str tags : tuple of strings If tags are given the dictionary is limited to the matching tags, if no tags are given all available tags are returned. Returns ...
def rpc_fix_code_with_yapf(self, source, directory): """Formats Python code to conform to the PEP 8 style guide. """ source = get_source(source) return fix_code_with_yapf(source, directory)
Formats Python code to conform to the PEP 8 style guide.
Below is the the instruction that describes the task: ### Input: Formats Python code to conform to the PEP 8 style guide. ### Response: def rpc_fix_code_with_yapf(self, source, directory): """Formats Python code to conform to the PEP 8 style guide. """ source = get_source(source) r...
def stop(self): """ Stop all threads and modules of the client. :return: """ super(BitfinexWSS, self).stop() log.info("BitfinexWSS.stop(): Stopping client..") log.info("BitfinexWSS.stop(): Joining receiver thread..") try: self.receiver_thread...
Stop all threads and modules of the client. :return:
Below is the the instruction that describes the task: ### Input: Stop all threads and modules of the client. :return: ### Response: def stop(self): """ Stop all threads and modules of the client. :return: """ super(BitfinexWSS, self).stop() log.info("Bitfine...
def boto_fix_security_token_in_profile(self, connect_args): ''' monkey patch for boto issue boto/boto#2100 ''' profile = 'profile ' + self.boto_profile if boto.config.has_option(profile, 'aws_security_token'): connect_args['security_token'] = boto.config.get(profile, 'aws_security_to...
monkey patch for boto issue boto/boto#2100
Below is the the instruction that describes the task: ### Input: monkey patch for boto issue boto/boto#2100 ### Response: def boto_fix_security_token_in_profile(self, connect_args): ''' monkey patch for boto issue boto/boto#2100 ''' profile = 'profile ' + self.boto_profile if boto.config.ha...
def to_df(self, varnames=None, ranefs=False, transformed=False, chains=None): ''' Returns the MCMC samples in a nice, neat pandas DataFrame with all MCMC chains concatenated. Args: varnames (list): List of variable names to include; if None (def...
Returns the MCMC samples in a nice, neat pandas DataFrame with all MCMC chains concatenated. Args: varnames (list): List of variable names to include; if None (default), all eligible variables are included. ranefs (bool): Whether or not to include random effects ...
Below is the the instruction that describes the task: ### Input: Returns the MCMC samples in a nice, neat pandas DataFrame with all MCMC chains concatenated. Args: varnames (list): List of variable names to include; if None (default), all eligible variables are included....
def gen_hot_url(hot_index, page=1): """拼接 首页热门文章 URL Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ------- str 热门文章分类的url """ ...
拼接 首页热门文章 URL Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ------- str 热门文章分类的url
Below is the the instruction that describes the task: ### Input: 拼接 首页热门文章 URL Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ------- str 热门文...
def diff_lorenz(value_array, sigma, beta, rho): """The Lorenz attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param sigma: Constant attractor parameter :param beta: FConstant attractor parameter :param rho: Constant attractor parameter ...
The Lorenz attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param sigma: Constant attractor parameter :param beta: FConstant attractor parameter :param rho: Constant attractor parameter :return: 3d array of the Lorenz system evaluated at `va...
Below is the the instruction that describes the task: ### Input: The Lorenz attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param sigma: Constant attractor parameter :param beta: FConstant attractor parameter :param rho: Constant attractor p...
def strict_parse(cls, query_str, *specs, extra_parameters=True): """ Parse query and return :class:`.WStrictURIQuery` object :param query_str: query component of URI to parse :param specs: list of parameters specifications :param extra_parameters: whether parameters that was not specified in "specs" are allowe...
Parse query and return :class:`.WStrictURIQuery` object :param query_str: query component of URI to parse :param specs: list of parameters specifications :param extra_parameters: whether parameters that was not specified in "specs" are allowed :return: WStrictURIQuery
Below is the the instruction that describes the task: ### Input: Parse query and return :class:`.WStrictURIQuery` object :param query_str: query component of URI to parse :param specs: list of parameters specifications :param extra_parameters: whether parameters that was not specified in "specs" are allowed ...
def get_directory_relative_to_git_root(directory: str): """ Gets the path to the given directory relative to the git repository root in which it is a subdirectory. :param directory: the directory within a git repository :return: the path to the directory relative to the git repository root """ r...
Gets the path to the given directory relative to the git repository root in which it is a subdirectory. :param directory: the directory within a git repository :return: the path to the directory relative to the git repository root
Below is the the instruction that describes the task: ### Input: Gets the path to the given directory relative to the git repository root in which it is a subdirectory. :param directory: the directory within a git repository :return: the path to the directory relative to the git repository root ### Response...
def do_banner(self, arg, arguments): """ :: Usage: banner [-c CHAR] [-n WIDTH] [-i INDENT] [-r COLOR] TEXT Arguments: TEXT The text message from which to create the banner CHAR The character for the frame. WID...
:: Usage: banner [-c CHAR] [-n WIDTH] [-i INDENT] [-r COLOR] TEXT Arguments: TEXT The text message from which to create the banner CHAR The character for the frame. WIDTH Width of the banner INDENT indentatio...
Below is the the instruction that describes the task: ### Input: :: Usage: banner [-c CHAR] [-n WIDTH] [-i INDENT] [-r COLOR] TEXT Arguments: TEXT The text message from which to create the banner CHAR The character for the frame. ...
def set_grads(params, params_with_grad): """ Copies gradients from param_with_grad to params :param params: dst parameters :param params_with_grad: src parameters """ for param, param_w_grad in zip(params, params_with_grad): if param.grad is None: ...
Copies gradients from param_with_grad to params :param params: dst parameters :param params_with_grad: src parameters
Below is the the instruction that describes the task: ### Input: Copies gradients from param_with_grad to params :param params: dst parameters :param params_with_grad: src parameters ### Response: def set_grads(params, params_with_grad): """ Copies gradients from param_with_grad to...
def bind(self, database): """Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. """ self._database = database ...
Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed.
Below is the the instruction that describes the task: ### Input: Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. ### Response: def bind...
def quantile(self, q=0.5, interpolation='linear'): """ Return value at the given quantile. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) 0 <= q <= 1, the quantile(s) to compute. interpolation : {'linear', 'lower', 'higher', 'midpoi...
Return value at the given quantile. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) 0 <= q <= 1, the quantile(s) to compute. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} .. versionadded:: 0.18.0 This ...
Below is the the instruction that describes the task: ### Input: Return value at the given quantile. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) 0 <= q <= 1, the quantile(s) to compute. interpolation : {'linear', 'lower', 'higher', 'midpoint...