code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def delete(block_id): """Processing block detail resource.""" _url = get_root_url() try: DB.delete_processing_block(block_id) response = dict(message='Deleted block', id='{}'.format(block_id), links=dict(list='{}/processing-blocks'.format(_url)...
Processing block detail resource.
Below is the the instruction that describes the task: ### Input: Processing block detail resource. ### Response: def delete(block_id): """Processing block detail resource.""" _url = get_root_url() try: DB.delete_processing_block(block_id) response = dict(message='Deleted block', ...
def total_stored(self, wanted, slots=None): """ Calculates the total number of items of that type in the current window or given slot range. Args: wanted: function(Slot) or Slot or itemID or (itemID, metadata) """ if slots is None: slots = self.wi...
Calculates the total number of items of that type in the current window or given slot range. Args: wanted: function(Slot) or Slot or itemID or (itemID, metadata)
Below is the the instruction that describes the task: ### Input: Calculates the total number of items of that type in the current window or given slot range. Args: wanted: function(Slot) or Slot or itemID or (itemID, metadata) ### Response: def total_stored(self, wanted, slots=None): ...
def select_entry(self, core_element_id, by_cursor=True): """Selects the row entry belonging to the given core_element_id by cursor or tree selection""" for row_num, element_row in enumerate(self.list_store): # Compare data port ids if element_row[self.ID_STORAGE_ID] == core_eleme...
Selects the row entry belonging to the given core_element_id by cursor or tree selection
Below is the the instruction that describes the task: ### Input: Selects the row entry belonging to the given core_element_id by cursor or tree selection ### Response: def select_entry(self, core_element_id, by_cursor=True): """Selects the row entry belonging to the given core_element_id by cursor or tree ...
def get_activities_for_objective(self, objective_id=None): """Gets the activities for the given objective. In plenary mode, the returned list contains all of the activities mapped to the objective Id or an error results if an Id in the supplied list is not found or inaccessible. Otherwis...
Gets the activities for the given objective. In plenary mode, the returned list contains all of the activities mapped to the objective Id or an error results if an Id in the supplied list is not found or inaccessible. Otherwise, inaccessible Activities may be omitted from the list and ma...
Below is the the instruction that describes the task: ### Input: Gets the activities for the given objective. In plenary mode, the returned list contains all of the activities mapped to the objective Id or an error results if an Id in the supplied list is not found or inaccessible. Otherwise...
def get_broadcast_date(pid): """Take BBC pid (string); extract and return broadcast date as string.""" print("Extracting first broadcast date...") broadcast_etree = open_listing_page(pid + '/broadcasts.inc') original_broadcast_date, = broadcast_etree.xpath( '(//div[@class="grid__inner"]//div' ...
Take BBC pid (string); extract and return broadcast date as string.
Below is the the instruction that describes the task: ### Input: Take BBC pid (string); extract and return broadcast date as string. ### Response: def get_broadcast_date(pid): """Take BBC pid (string); extract and return broadcast date as string.""" print("Extracting first broadcast date...") broadcast...
def seek(self, timestamp): """Seek to a given timestamp in the current track, specified in the format of HH:MM:SS or H:MM:SS. Raises: ValueError: if the given timestamp is invalid. """ if not re.match(r'^[0-9][0-9]?:[0-9][0-9]:[0-9][0-9]$', timestamp): ra...
Seek to a given timestamp in the current track, specified in the format of HH:MM:SS or H:MM:SS. Raises: ValueError: if the given timestamp is invalid.
Below is the the instruction that describes the task: ### Input: Seek to a given timestamp in the current track, specified in the format of HH:MM:SS or H:MM:SS. Raises: ValueError: if the given timestamp is invalid. ### Response: def seek(self, timestamp): """Seek to a given ti...
def stream_fastq_full(fastq, threads): """Generator for returning metrics extracted from fastq. Extract from a fastq file: -readname -average and median quality -read_lenght """ logging.info("Nanoget: Starting to collect full metrics from plain fastq file.") inputfastq = handle_compress...
Generator for returning metrics extracted from fastq. Extract from a fastq file: -readname -average and median quality -read_lenght
Below is the the instruction that describes the task: ### Input: Generator for returning metrics extracted from fastq. Extract from a fastq file: -readname -average and median quality -read_lenght ### Response: def stream_fastq_full(fastq, threads): """Generator for returning metrics extracted...
def expand_recurring(number, repeat=5): """ Expands a recurring pattern within a number. Args: number(tuple): the number to process in the form: (int, int, int, ... ".", ... , int int int) repeat: the number of times to expand the pattern. Returns: The ori...
Expands a recurring pattern within a number. Args: number(tuple): the number to process in the form: (int, int, int, ... ".", ... , int int int) repeat: the number of times to expand the pattern. Returns: The original number with recurring pattern expanded. E...
Below is the the instruction that describes the task: ### Input: Expands a recurring pattern within a number. Args: number(tuple): the number to process in the form: (int, int, int, ... ".", ... , int int int) repeat: the number of times to expand the pattern. Returns: ...
def is_revision_chain_placeholder(pid): """For replicas, the PIDs referenced in revision chains are reserved for use by other replicas.""" return d1_gmn.app.models.ReplicaRevisionChainReference.objects.filter( pid__did=pid ).exists()
For replicas, the PIDs referenced in revision chains are reserved for use by other replicas.
Below is the the instruction that describes the task: ### Input: For replicas, the PIDs referenced in revision chains are reserved for use by other replicas. ### Response: def is_revision_chain_placeholder(pid): """For replicas, the PIDs referenced in revision chains are reserved for use by other repli...
def update_ports(self, ports, id_or_uri, timeout=-1): """ Updates the interconnect ports. Args: id_or_uri: Can be either the interconnect id or the interconnect uri. ports (list): Ports to update. timeout: Timeout in seconds. Wait for task completion by defau...
Updates the interconnect ports. Args: id_or_uri: Can be either the interconnect id or the interconnect uri. ports (list): Ports to update. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; i...
Below is the the instruction that describes the task: ### Input: Updates the interconnect ports. Args: id_or_uri: Can be either the interconnect id or the interconnect uri. ports (list): Ports to update. timeout: Timeout in seconds. Wait for task completion by default. T...
def qs_from_dict(qsdict, prefix=""): ''' Same as dict_from_qs, but in reverse i.e. {"period": {"di": {}, "fhr": {}}} => "period.di,period.fhr" ''' prefix = prefix + '.' if prefix else "" def descend(qsd): for key, val in sorted(qsd.items()): if val: yield qs_...
Same as dict_from_qs, but in reverse i.e. {"period": {"di": {}, "fhr": {}}} => "period.di,period.fhr"
Below is the the instruction that describes the task: ### Input: Same as dict_from_qs, but in reverse i.e. {"period": {"di": {}, "fhr": {}}} => "period.di,period.fhr" ### Response: def qs_from_dict(qsdict, prefix=""): ''' Same as dict_from_qs, but in reverse i.e. {"period": {"di": {}, "fhr": {}...
def plot_transaction_rate_heterogeneity( model, suptitle="Heterogeneity in Transaction Rate", xlabel="Transaction Rate", ylabel="Density", suptitle_fontsize=14, **kwargs ): """ Plot the estimated gamma distribution of lambda (customers' propensities to purchase). Parameters ----...
Plot the estimated gamma distribution of lambda (customers' propensities to purchase). Parameters ---------- model: lifetimes model A fitted lifetimes model, for now only for BG/NBD suptitle: str, optional Figure suptitle xlabel: str, optional Figure xlabel ylabel: str, ...
Below is the the instruction that describes the task: ### Input: Plot the estimated gamma distribution of lambda (customers' propensities to purchase). Parameters ---------- model: lifetimes model A fitted lifetimes model, for now only for BG/NBD suptitle: str, optional Figure supti...
def Ctrl(cls, key): """ 在指定元素上执行ctrl组合键事件 @note: key event -> control + key @param key: 如'X' """ element = cls._element() element.send_keys(Keys.CONTROL, key)
在指定元素上执行ctrl组合键事件 @note: key event -> control + key @param key: 如'X'
Below is the the instruction that describes the task: ### Input: 在指定元素上执行ctrl组合键事件 @note: key event -> control + key @param key: 如'X' ### Response: def Ctrl(cls, key): """ 在指定元素上执行ctrl组合键事件 @note: key event -> control + key @param key: 如'X' """ ele...
def connect(self): '''Connect to S3 storage''' try: if S3Handler.S3_KEYS: self.s3 = BotoClient(self.opt, S3Handler.S3_KEYS[0], S3Handler.S3_KEYS[1]) else: self.s3 = BotoClient(self.opt) except Exception as e: raise RetryFailure('Unable to connect to s3: %s' % e)
Connect to S3 storage
Below is the the instruction that describes the task: ### Input: Connect to S3 storage ### Response: def connect(self): '''Connect to S3 storage''' try: if S3Handler.S3_KEYS: self.s3 = BotoClient(self.opt, S3Handler.S3_KEYS[0], S3Handler.S3_KEYS[1]) else: self.s3 = BotoClient(se...
def internal_energy(self, t, structure=None): """ Phonon contribution to the internal energy at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/mol-c. A mol-c is the abbreviation of a mole-cell, that is, the number of Av...
Phonon contribution to the internal energy at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/mol-c. A mol-c is the abbreviation of a mole-cell, that is, the number of Avogadro times the atoms in a unit cell. To compare with experimenta...
Below is the the instruction that describes the task: ### Input: Phonon contribution to the internal energy at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/mol-c. A mol-c is the abbreviation of a mole-cell, that is, the number of...
def parse_raid(rule): ''' Parse the raid line ''' parser = argparse.ArgumentParser() rules = shlex.split(rule) rules.pop(0) partitions = [] newrules = [] for count in range(0, len(rules)): if count == 0: newrules.append(rules[count]) continue ...
Parse the raid line
Below is the the instruction that describes the task: ### Input: Parse the raid line ### Response: def parse_raid(rule): ''' Parse the raid line ''' parser = argparse.ArgumentParser() rules = shlex.split(rule) rules.pop(0) partitions = [] newrules = [] for count in range(0, len...
def reverse_whois(self, query, exclude=[], scope='current', mode=None, **kwargs): """List of one or more terms to search for in the Whois record, as a Python list or separated with the pipe character ( | ). """ return self._results('reverse-whois', '/v1/reverse-whois', terms=delimited...
List of one or more terms to search for in the Whois record, as a Python list or separated with the pipe character ( | ).
Below is the the instruction that describes the task: ### Input: List of one or more terms to search for in the Whois record, as a Python list or separated with the pipe character ( | ). ### Response: def reverse_whois(self, query, exclude=[], scope='current', mode=None, **kwargs): """List of on...
def render_files(self, root=None): """ Render the file path as accordions """ if root is None: tmp = os.environ.get('TMP') root = sys.path[1 if tmp and tmp in sys.path else 0] items = [] for filename in os.listdir(root): # for subdirname in di...
Render the file path as accordions
Below is the the instruction that describes the task: ### Input: Render the file path as accordions ### Response: def render_files(self, root=None): """ Render the file path as accordions """ if root is None: tmp = os.environ.get('TMP') root = sys.path[1 if tmp and ...
def org_update(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /org-xxxx/update API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2Fupdate """ return DXHTTPRequest('/%s/update' % object_id, input_para...
Invokes the /org-xxxx/update API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2Fupdate
Below is the the instruction that describes the task: ### Input: Invokes the /org-xxxx/update API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2Fupdate ### Response: def org_update(object_id, input_params={}, always_retry=True, **kwargs...
def upload_file(self, local_path, remote_path): """ Upload a file from the local filesystem to the remote host :type local_path: str :param local_path: path of local file to upload :type remote_path: str :param remote_path: destination path of upload on remote host ...
Upload a file from the local filesystem to the remote host :type local_path: str :param local_path: path of local file to upload :type remote_path: str :param remote_path: destination path of upload on remote host
Below is the the instruction that describes the task: ### Input: Upload a file from the local filesystem to the remote host :type local_path: str :param local_path: path of local file to upload :type remote_path: str :param remote_path: destination path of upload on remote host ### ...
def get_all_related_many_to_many_objects(opts): """ Django 1.8 changed meta api, see docstr in compat.get_all_related_objects() :param opts: Options instance :return: list of many-to-many relations """ if django.VERSION < (1, 9): return opts.get_all_related_many_to_many_objects() el...
Django 1.8 changed meta api, see docstr in compat.get_all_related_objects() :param opts: Options instance :return: list of many-to-many relations
Below is the the instruction that describes the task: ### Input: Django 1.8 changed meta api, see docstr in compat.get_all_related_objects() :param opts: Options instance :return: list of many-to-many relations ### Response: def get_all_related_many_to_many_objects(opts): """ Django 1.8 changed me...
def fold_columns_to_rows(df, levels_from=2): """ Take a levels from the columns and fold down into the row index. This destroys the existing index; existing rows will appear as columns under the new column index :param df: :param levels_from: The level (inclusive) from which column index will b...
Take a levels from the columns and fold down into the row index. This destroys the existing index; existing rows will appear as columns under the new column index :param df: :param levels_from: The level (inclusive) from which column index will be folded :return:
Below is the the instruction that describes the task: ### Input: Take a levels from the columns and fold down into the row index. This destroys the existing index; existing rows will appear as columns under the new column index :param df: :param levels_from: The level (inclusive) from which column ...
def update_energy(self, bypass_check=False): """Fetch updated energy information about devices""" for outlet in self.outlets: outlet.update_energy(bypass_check)
Fetch updated energy information about devices
Below is the the instruction that describes the task: ### Input: Fetch updated energy information about devices ### Response: def update_energy(self, bypass_check=False): """Fetch updated energy information about devices""" for outlet in self.outlets: outlet.update_energy(bypass_check)
def mesh(**kwargs): """ Create parameters for a new mesh dataset. Generally, this will be used as an input to the kind argument in :meth:`phoebe.frontend.bundle.Bundle.add_dataset` :parameter **kwargs: defaults for the values of any of the parameters :return: a :class:`phoebe.parameters.parame...
Create parameters for a new mesh dataset. Generally, this will be used as an input to the kind argument in :meth:`phoebe.frontend.bundle.Bundle.add_dataset` :parameter **kwargs: defaults for the values of any of the parameters :return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly ...
Below is the the instruction that describes the task: ### Input: Create parameters for a new mesh dataset. Generally, this will be used as an input to the kind argument in :meth:`phoebe.frontend.bundle.Bundle.add_dataset` :parameter **kwargs: defaults for the values of any of the parameters :retur...
def reads(paths, filename='data.h5', options=None, **keywords): """ Reads data from an HDF5 file (high level). High level function to read one or more pieces of data from an HDF5 file located at the paths specified in `paths` into Python types. Each path is specified as a POSIX style path where the dat...
Reads data from an HDF5 file (high level). High level function to read one or more pieces of data from an HDF5 file located at the paths specified in `paths` into Python types. Each path is specified as a POSIX style path where the data to read is located. There are various options that can be use...
Below is the the instruction that describes the task: ### Input: Reads data from an HDF5 file (high level). High level function to read one or more pieces of data from an HDF5 file located at the paths specified in `paths` into Python types. Each path is specified as a POSIX style path where the data ...
def register(self, model_alias, code='general', name=None, order=None, display_filter=None): """ Register new tab :param model_alias: :param code: :param name: :param order: :return: """ model_alias = self.get_model_alias(model_alias) def...
Register new tab :param model_alias: :param code: :param name: :param order: :return:
Below is the the instruction that describes the task: ### Input: Register new tab :param model_alias: :param code: :param name: :param order: :return: ### Response: def register(self, model_alias, code='general', name=None, order=None, display_filter=None): """ ...
def ops_to_words(item): """Translate requirement specification to words.""" unsupp_ops = ["~=", "==="] # Ordered for "pleasant" word specification supp_ops = [">=", ">", "==", "<=", "<", "!="] tokens = sorted(item.split(","), reverse=True) actual_tokens = [] for req in tokens: for o...
Translate requirement specification to words.
Below is the the instruction that describes the task: ### Input: Translate requirement specification to words. ### Response: def ops_to_words(item): """Translate requirement specification to words.""" unsupp_ops = ["~=", "==="] # Ordered for "pleasant" word specification supp_ops = [">=", ">", "==...
def error(self, i: int=None) -> str: """ Returns an error message """ head = "[" + colors.red("error") + "]" if i is not None: head = str(i) + " " + head return head
Returns an error message
Below is the the instruction that describes the task: ### Input: Returns an error message ### Response: def error(self, i: int=None) -> str: """ Returns an error message """ head = "[" + colors.red("error") + "]" if i is not None: head = str(i) + " " + head ...
def anoteElements(ax, anotelist, showAccName=False, efilter=None, textypos=None, **kwargs): """ annotate elements to axes :param ax: matplotlib axes object :param anotelist: element annotation object list :param showAccName: tag name for accelerator tubes? defaul...
annotate elements to axes :param ax: matplotlib axes object :param anotelist: element annotation object list :param showAccName: tag name for accelerator tubes? default is False, show acceleration band type, e.g. 'S', 'C', 'X', or for '[S,C,X]D' for cavi...
Below is the the instruction that describes the task: ### Input: annotate elements to axes :param ax: matplotlib axes object :param anotelist: element annotation object list :param showAccName: tag name for accelerator tubes? default is False, show a...
def palette_image(self): """ PIL weird interface for making a paletted image: create an image which already has the palette, and use that in Image.quantize. This function returns this palette image. """ if self.pimage is None: palette = [] for i in range(s...
PIL weird interface for making a paletted image: create an image which already has the palette, and use that in Image.quantize. This function returns this palette image.
Below is the the instruction that describes the task: ### Input: PIL weird interface for making a paletted image: create an image which already has the palette, and use that in Image.quantize. This function returns this palette image. ### Response: def palette_image(self): """ PIL w...
def visit_console_html(self, node): """Generate HTML for the console directive.""" if self.builder.name in ('djangohtml', 'json') and node['win_console_text']: # Put a mark on the document object signaling the fact the directive # has been used on it. self.document._console_directive_use...
Generate HTML for the console directive.
Below is the the instruction that describes the task: ### Input: Generate HTML for the console directive. ### Response: def visit_console_html(self, node): """Generate HTML for the console directive.""" if self.builder.name in ('djangohtml', 'json') and node['win_console_text']: # Put a mark on the...
def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btr...
Make a filesystem using the appropriate module .. versionadded:: Beryllium
Below is the the instruction that describes the task: ### Input: Make a filesystem using the appropriate module .. versionadded:: Beryllium ### Response: def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts...
def random_indexes(max_index, subset_size=None, seed=None, rng=None): """ random unrepeated indicies Args: max_index (?): subset_size (None): (default = None) seed (None): (default = None) rng (RandomState): random number generator(default = None) Returns: ?: subst...
random unrepeated indicies Args: max_index (?): subset_size (None): (default = None) seed (None): (default = None) rng (RandomState): random number generator(default = None) Returns: ?: subst CommandLine: python -m utool.util_numpy --exec-random_indexes ...
Below is the the instruction that describes the task: ### Input: random unrepeated indicies Args: max_index (?): subset_size (None): (default = None) seed (None): (default = None) rng (RandomState): random number generator(default = None) Returns: ?: subst Com...
def parse_expression(expression: str) -> Tuple[Set[str], List[CompositeAxis]]: """ Parses an indexing expression (for a single tensor). Checks uniqueness of names, checks usage of '...' (allowed only once) Returns set of all used identifiers and a list of axis groups """ identifiers = set() ...
Parses an indexing expression (for a single tensor). Checks uniqueness of names, checks usage of '...' (allowed only once) Returns set of all used identifiers and a list of axis groups
Below is the the instruction that describes the task: ### Input: Parses an indexing expression (for a single tensor). Checks uniqueness of names, checks usage of '...' (allowed only once) Returns set of all used identifiers and a list of axis groups ### Response: def parse_expression(expression: str) -> Tu...
def invokeCompletionIfAvailable(self, requestedByUser=False): """Invoke completion, if available. Called after text has been typed in qpart Returns True, if invoked """ if self._qpart.completionEnabled and self._wordSet is not None: wordBeforeCursor = self._wordBeforeCursor()...
Invoke completion, if available. Called after text has been typed in qpart Returns True, if invoked
Below is the the instruction that describes the task: ### Input: Invoke completion, if available. Called after text has been typed in qpart Returns True, if invoked ### Response: def invokeCompletionIfAvailable(self, requestedByUser=False): """Invoke completion, if available. Called after text has ...
def _set_request_cache_if_django_cache_hit(key, django_cached_response): """ Sets the value in the request cache if the django cached response was a hit. Args: key (string) django_cached_response (CachedResponse) """ if django_cached_response.is_found: ...
Sets the value in the request cache if the django cached response was a hit. Args: key (string) django_cached_response (CachedResponse)
Below is the the instruction that describes the task: ### Input: Sets the value in the request cache if the django cached response was a hit. Args: key (string) django_cached_response (CachedResponse) ### Response: def _set_request_cache_if_django_cache_hit(key, django_cached_respo...
def to_json(self): """Outputs the entire graph.""" res_dict = {} def gen_dep_edge(node, edge, dep_tgt, aliases): return { 'target': dep_tgt.address.spec, 'dependency_type': self._edge_type(node.concrete_target, edge, dep_tgt), 'products_used': len(edge.products_used), ...
Outputs the entire graph.
Below is the the instruction that describes the task: ### Input: Outputs the entire graph. ### Response: def to_json(self): """Outputs the entire graph.""" res_dict = {} def gen_dep_edge(node, edge, dep_tgt, aliases): return { 'target': dep_tgt.address.spec, 'dependency_type': se...
def run_transaction(self, command_list, do_commit=True): '''This can be used to stage multiple commands and roll back the transaction if an error occurs. This is useful if you want to remove multiple records in multiple tables for one entity but do not want the deletion to occur if the e...
This can be used to stage multiple commands and roll back the transaction if an error occurs. This is useful if you want to remove multiple records in multiple tables for one entity but do not want the deletion to occur if the entity is tied to table not specified in the list of commands. Perfor...
Below is the the instruction that describes the task: ### Input: This can be used to stage multiple commands and roll back the transaction if an error occurs. This is useful if you want to remove multiple records in multiple tables for one entity but do not want the deletion to occur if the ...
def _serialize_value(self, value): """ Called by :py:meth:`._serialize` to serialise an individual value. """ if isinstance(value, (list, tuple, set)): return [self._serialize_value(v) for v in value] elif isinstance(value, dict): return dict([(k, self._se...
Called by :py:meth:`._serialize` to serialise an individual value.
Below is the the instruction that describes the task: ### Input: Called by :py:meth:`._serialize` to serialise an individual value. ### Response: def _serialize_value(self, value): """ Called by :py:meth:`._serialize` to serialise an individual value. """ if isinstance(value, (list,...
def latcyl(radius, lon, lat): """ Convert from latitudinal coordinates to cylindrical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latcyl_c.html :param radius: Distance of a point from the origin. :type radius: :param lon: Angle of the point from the XZ plane in radians...
Convert from latitudinal coordinates to cylindrical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latcyl_c.html :param radius: Distance of a point from the origin. :type radius: :param lon: Angle of the point from the XZ plane in radians. :param lat: Angle of the point from ...
Below is the the instruction that describes the task: ### Input: Convert from latitudinal coordinates to cylindrical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latcyl_c.html :param radius: Distance of a point from the origin. :type radius: :param lon: Angle of the point f...
def _pull_out_perm_rhs(rest, rhs, out_port, in_port): """Similar to :func:`_pull_out_perm_lhs` but on the RHS of a series product self-feedback.""" in_im, rhs_red = rhs._factor_rhs(in_port) return (Feedback.create( SeriesProduct.create(*rest), out_port=out_port, in_port=i...
Similar to :func:`_pull_out_perm_lhs` but on the RHS of a series product self-feedback.
Below is the the instruction that describes the task: ### Input: Similar to :func:`_pull_out_perm_lhs` but on the RHS of a series product self-feedback. ### Response: def _pull_out_perm_rhs(rest, rhs, out_port, in_port): """Similar to :func:`_pull_out_perm_lhs` but on the RHS of a series product self-f...
def postinit(self, value, conversion=None, format_spec=None): """Do some setup after initialisation. :param value: The value to be formatted into the string. :type value: NodeNG :param conversion: The type of formatting to be applied to the value. :type conversion: int or None ...
Do some setup after initialisation. :param value: The value to be formatted into the string. :type value: NodeNG :param conversion: The type of formatting to be applied to the value. :type conversion: int or None :param format_spec: The formatting to be applied to the value. ...
Below is the the instruction that describes the task: ### Input: Do some setup after initialisation. :param value: The value to be formatted into the string. :type value: NodeNG :param conversion: The type of formatting to be applied to the value. :type conversion: int or None ...
def spiro_image(R, r, r_, resolution=2*PI/1000, spins=50, size=[32, 32]): '''Create image with given Spirograph parameters using numpy and scipy. ''' x, y = give_dots(200, r, r_, spins=20) xy = np.array([x, y]).T xy = np.array(np.around(xy), dtype=np.int64) xy = xy[(xy[:, 0] >= -250) & (xy[:, 1]...
Create image with given Spirograph parameters using numpy and scipy.
Below is the the instruction that describes the task: ### Input: Create image with given Spirograph parameters using numpy and scipy. ### Response: def spiro_image(R, r, r_, resolution=2*PI/1000, spins=50, size=[32, 32]): '''Create image with given Spirograph parameters using numpy and scipy. ''' x, y ...
def match(self, pattern, context=None): """ This method returns a (possibly empty) list of strings that match the regular expression ``pattern`` provided. You can also provide a ``context`` as described above. This method calls ``choices`` to get a list of all possible ...
This method returns a (possibly empty) list of strings that match the regular expression ``pattern`` provided. You can also provide a ``context`` as described above. This method calls ``choices`` to get a list of all possible choices and then filters the list by performing a regular ...
Below is the the instruction that describes the task: ### Input: This method returns a (possibly empty) list of strings that match the regular expression ``pattern`` provided. You can also provide a ``context`` as described above. This method calls ``choices`` to get a list of all possible...
def get_formset(self, request, obj=None, **kwargs): """ Default user to the current version owner. """ data = super().get_formset(request, obj, **kwargs) if obj: data.form.base_fields['user'].initial = request.user.id return data
Default user to the current version owner.
Below is the the instruction that describes the task: ### Input: Default user to the current version owner. ### Response: def get_formset(self, request, obj=None, **kwargs): """ Default user to the current version owner. """ data = super().get_formset(request, obj, **kwargs) if obj: ...
def r_q_send(self, msg_dict): """Send message dicts through r_q, and throw explicit errors for pickle problems""" # Check whether msg_dict can be pickled... no_pickle_keys = self.invalid_dict_pickle_keys(msg_dict) if no_pickle_keys == []: self.r_q.put(msg_dict) ...
Send message dicts through r_q, and throw explicit errors for pickle problems
Below is the the instruction that describes the task: ### Input: Send message dicts through r_q, and throw explicit errors for pickle problems ### Response: def r_q_send(self, msg_dict): """Send message dicts through r_q, and throw explicit errors for pickle problems""" # Check w...
def assert_not_equal(first, second, msg_fmt="{msg}"): """Fail if first equals second, as determined by the '==' operator. >>> assert_not_equal(5, 8) >>> assert_not_equal(-7, -7.0) Traceback (most recent call last): ... AssertionError: -7 == -7.0 The following msg_fmt arguments are supp...
Fail if first equals second, as determined by the '==' operator. >>> assert_not_equal(5, 8) >>> assert_not_equal(-7, -7.0) Traceback (most recent call last): ... AssertionError: -7 == -7.0 The following msg_fmt arguments are supported: * msg - the default error message * first - th...
Below is the the instruction that describes the task: ### Input: Fail if first equals second, as determined by the '==' operator. >>> assert_not_equal(5, 8) >>> assert_not_equal(-7, -7.0) Traceback (most recent call last): ... AssertionError: -7 == -7.0 The following msg_fmt arguments ...
def guest_stop(self, userid, **kwargs): """Power off VM.""" requestData = "PowerVM " + userid + " off" if 'timeout' in kwargs.keys() and kwargs['timeout']: requestData += ' --maxwait ' + str(kwargs['timeout']) if 'poll_interval' in kwargs.keys() and kwargs['poll_interval']: ...
Power off VM.
Below is the the instruction that describes the task: ### Input: Power off VM. ### Response: def guest_stop(self, userid, **kwargs): """Power off VM.""" requestData = "PowerVM " + userid + " off" if 'timeout' in kwargs.keys() and kwargs['timeout']: requestData += ' --maxwait ' ...
def from_irc(self, irc_nickname=None, irc_password=None): ''' Connect to the IRC channel and find all servers presently connected. Slow; takes 30+ seconds but authoritative and current. OBSOLETE. ''' if have_bottom: from .findall import IrcListen...
Connect to the IRC channel and find all servers presently connected. Slow; takes 30+ seconds but authoritative and current. OBSOLETE.
Below is the the instruction that describes the task: ### Input: Connect to the IRC channel and find all servers presently connected. Slow; takes 30+ seconds but authoritative and current. OBSOLETE. ### Response: def from_irc(self, irc_nickname=None, irc_password=None): ''' ...
def register_frontend_media(request, media): """ Add a :class:`~django.forms.Media` class to the current request. This will be rendered by the ``render_plugin_media`` template tag. """ if not hasattr(request, '_fluent_contents_frontend_media'): request._fluent_contents_frontend_media = Media...
Add a :class:`~django.forms.Media` class to the current request. This will be rendered by the ``render_plugin_media`` template tag.
Below is the the instruction that describes the task: ### Input: Add a :class:`~django.forms.Media` class to the current request. This will be rendered by the ``render_plugin_media`` template tag. ### Response: def register_frontend_media(request, media): """ Add a :class:`~django.forms.Media` class to...
def _parse_call_args(self,*args,**kwargs): """Helper function to parse the arguments to the __call__ and related functions, return [6,nobj] array of frequencies (:3) and angles (3:)""" interp= kwargs.get('interp',self._useInterp) if len(args) == 5: raise IOError("Must specify...
Helper function to parse the arguments to the __call__ and related functions, return [6,nobj] array of frequencies (:3) and angles (3:)
Below is the the instruction that describes the task: ### Input: Helper function to parse the arguments to the __call__ and related functions, return [6,nobj] array of frequencies (:3) and angles (3:) ### Response: def _parse_call_args(self,*args,**kwargs): """Helper function to parse the arguments...
def change_node_subscriptions(self, jid, node, subscriptions_to_set): """ Update the subscriptions at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param subscr...
Update the subscriptions at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param subscriptions_to_set: The subscriptions to set at the node. :type subscriptions_to_set: ...
Below is the the instruction that describes the task: ### Input: Update the subscriptions at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param subscriptions_to_set: The s...
def image_preprocessing(image_buffer, bbox, train, thread_id=0): """Decode and preprocess one image for evaluation or training. Args: image_buffer: JPEG encoded string Tensor bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates a...
Decode and preprocess one image for evaluation or training. Args: image_buffer: JPEG encoded string Tensor bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. train: boolean ...
Below is the the instruction that describes the task: ### Input: Decode and preprocess one image for evaluation or training. Args: image_buffer: JPEG encoded string Tensor bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates ar...
def __create_url_node_for_content(self, content, content_type, url=None, modification_time=None): """ Creates the required <url> node for the sitemap xml. :param content: the content class to handle :type content: pelican.contents.Content | None :param content_type: the type of t...
Creates the required <url> node for the sitemap xml. :param content: the content class to handle :type content: pelican.contents.Content | None :param content_type: the type of the given content to match settings.EXTENDED_SITEMAP_PLUGIN :type content_type; str :param url; if give...
Below is the the instruction that describes the task: ### Input: Creates the required <url> node for the sitemap xml. :param content: the content class to handle :type content: pelican.contents.Content | None :param content_type: the type of the given content to match settings.EXTENDED_SITEM...
def _nextSequence(cls, name=None): """Return a new sequence number for insertion in self._sqlTable. Note that if your sequences are not named tablename_primarykey_seq (ie. for table 'blapp' with primary key 'john_id', sequence name blapp_john_id_seq) you must give the full se...
Return a new sequence number for insertion in self._sqlTable. Note that if your sequences are not named tablename_primarykey_seq (ie. for table 'blapp' with primary key 'john_id', sequence name blapp_john_id_seq) you must give the full sequence name as an optional argument to _nextSe...
Below is the the instruction that describes the task: ### Input: Return a new sequence number for insertion in self._sqlTable. Note that if your sequences are not named tablename_primarykey_seq (ie. for table 'blapp' with primary key 'john_id', sequence name blapp_john_id_seq) you must g...
def from_time( year=None, month=None, day=None, hours=None, minutes=None, seconds=None, microseconds=None, timezone=None ): """Convenience wrapper to take a series of date/time elements and return a WMI time of the form `yyyymmddHHMMSS.mmmmmm+UUU`. All elements may be int, string or omitted altogether. ...
Convenience wrapper to take a series of date/time elements and return a WMI time of the form `yyyymmddHHMMSS.mmmmmm+UUU`. All elements may be int, string or omitted altogether. If omitted, they will be replaced in the output string by a series of stars of the appropriate length. :param year: The year el...
Below is the the instruction that describes the task: ### Input: Convenience wrapper to take a series of date/time elements and return a WMI time of the form `yyyymmddHHMMSS.mmmmmm+UUU`. All elements may be int, string or omitted altogether. If omitted, they will be replaced in the output string by a se...
def normalizeGlyphHeight(value): """ Normalizes glyph height. * **value** must be a :ref:`type-int-float`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)): raise TypeError("Glyph height must be an :ref:`type-int-float`, not " ...
Normalizes glyph height. * **value** must be a :ref:`type-int-float`. * Returned value is the same type as the input value.
Below is the the instruction that describes the task: ### Input: Normalizes glyph height. * **value** must be a :ref:`type-int-float`. * Returned value is the same type as the input value. ### Response: def normalizeGlyphHeight(value): """ Normalizes glyph height. * **value** must be a :ref:`...
def input(self, input, song): """Input callback, handles key presses """ try: cmd = getattr(self, self.CMD_MAP[input][1]) except (IndexError, KeyError): return self.screen.print_error( "Invalid command {!r}!".format(input)) cmd(song)
Input callback, handles key presses
Below is the the instruction that describes the task: ### Input: Input callback, handles key presses ### Response: def input(self, input, song): """Input callback, handles key presses """ try: cmd = getattr(self, self.CMD_MAP[input][1]) except (IndexError, KeyError): ...
def run_process(self, slug, inputs): """Run a new process from a running process.""" def export_files(value): """Export input files of spawned process.""" if isinstance(value, str) and os.path.isfile(value): # TODO: Use the protocol to export files and get the ...
Run a new process from a running process.
Below is the the instruction that describes the task: ### Input: Run a new process from a running process. ### Response: def run_process(self, slug, inputs): """Run a new process from a running process.""" def export_files(value): """Export input files of spawned process.""" ...
def run_pipes(executable, input_path, output_path, more_args=None, properties=None, force_pydoop_submitter=False, hadoop_conf_dir=None, logger=None, keep_streams=False): """ Run a pipes command. ``more_args`` (after setting input/output path) and ``properties`` are passed to...
Run a pipes command. ``more_args`` (after setting input/output path) and ``properties`` are passed to :func:`run_cmd`. If not specified otherwise, this function sets the properties ``mapreduce.pipes.isjavarecordreader`` and ``mapreduce.pipes.isjavarecordwriter`` to ``"true"``. This function w...
Below is the the instruction that describes the task: ### Input: Run a pipes command. ``more_args`` (after setting input/output path) and ``properties`` are passed to :func:`run_cmd`. If not specified otherwise, this function sets the properties ``mapreduce.pipes.isjavarecordreader`` and ``map...
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_lldp_pdu_received(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail") config = get_lldp_neighbor_detail output = ET.SubElement(...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_lldp_neighbor_detail_output_lldp_neighbor_detail_lldp_pdu_received(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_lldp_neighbor_detail = ET.Eleme...
def get_schedule(self, ehr_username, start_date, changed_since, include_pix, other_user='All', end_date='', appointment_types=None, status_filter='All'): """ invokes TouchWorksMagicConstants.ACTION_GET_SCHEDULE action :return: JSON r...
invokes TouchWorksMagicConstants.ACTION_GET_SCHEDULE action :return: JSON response
Below is the the instruction that describes the task: ### Input: invokes TouchWorksMagicConstants.ACTION_GET_SCHEDULE action :return: JSON response ### Response: def get_schedule(self, ehr_username, start_date, changed_since, include_pix, other_user='All', end_date...
def get_last_modified_datetime(dir_path=os.path.dirname(__file__)): """Return datetime object of latest change in kerncraft module directory.""" max_mtime = 0 for root, dirs, files in os.walk(dir_path): for f in files: p = os.path.join(root, f) try: max_mtime ...
Return datetime object of latest change in kerncraft module directory.
Below is the the instruction that describes the task: ### Input: Return datetime object of latest change in kerncraft module directory. ### Response: def get_last_modified_datetime(dir_path=os.path.dirname(__file__)): """Return datetime object of latest change in kerncraft module directory.""" max_mtime = ...
def data_cifar10(train_start=0, train_end=50000, test_start=0, test_end=10000): """ Preprocess CIFAR10 dataset :return: """ # These values are specific to CIFAR10 img_rows = 32 img_cols = 32 nb_classes = 10 # the data, shuffled and split between train and test sets (x_train, y_train), (x_test, y_...
Preprocess CIFAR10 dataset :return:
Below is the the instruction that describes the task: ### Input: Preprocess CIFAR10 dataset :return: ### Response: def data_cifar10(train_start=0, train_end=50000, test_start=0, test_end=10000): """ Preprocess CIFAR10 dataset :return: """ # These values are specific to CIFAR10 img_rows = 32 img_c...
def to_size(value, convert_to_human=True): ''' Convert python int (bytes) to zfs size NOTE: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/pyzfs/common/util.py#114 ''' value = from_size(value) if value is None: value = 'none' if isinstance(value, Number) and value > 10...
Convert python int (bytes) to zfs size NOTE: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/pyzfs/common/util.py#114
Below is the the instruction that describes the task: ### Input: Convert python int (bytes) to zfs size NOTE: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/pyzfs/common/util.py#114 ### Response: def to_size(value, convert_to_human=True): ''' Convert python int (bytes) to zfs size NO...
def address_to_scripthash(address: str) -> UInt160: """Just a helper method""" AddressVersion = 23 # fixed at this point data = b58decode(address) if len(data) != 25: raise ValueError('Not correct Address, wrong length.') if data[0] != AddressVersion: raise ValueError('Not correct C...
Just a helper method
Below is the the instruction that describes the task: ### Input: Just a helper method ### Response: def address_to_scripthash(address: str) -> UInt160: """Just a helper method""" AddressVersion = 23 # fixed at this point data = b58decode(address) if len(data) != 25: raise ValueError('Not c...
def remove_cable_distributor(self, cable_dist): """Removes a cable distributor from _cable_distributors if existing""" if cable_dist in self.cable_distributors() and isinstance(cable_dist, MVCableDistributorDing0): # remove fr...
Removes a cable distributor from _cable_distributors if existing
Below is the the instruction that describes the task: ### Input: Removes a cable distributor from _cable_distributors if existing ### Response: def remove_cable_distributor(self, cable_dist): """Removes a cable distributor from _cable_distributors if existing""" if cable_dist in self.cable_distribu...
def kappa_statistic(self): r"""Return κ statistic. The κ statistic is defined as: :math:`\kappa = \frac{accuracy - random~ accuracy} {1 - random~ accuracy}` The κ statistic compares the performance of the classifier relative to the performance of a random classifier. :m...
r"""Return κ statistic. The κ statistic is defined as: :math:`\kappa = \frac{accuracy - random~ accuracy} {1 - random~ accuracy}` The κ statistic compares the performance of the classifier relative to the performance of a random classifier. :math:`\kappa` = 0 indicates ...
Below is the the instruction that describes the task: ### Input: r"""Return κ statistic. The κ statistic is defined as: :math:`\kappa = \frac{accuracy - random~ accuracy} {1 - random~ accuracy}` The κ statistic compares the performance of the classifier relative to the perf...
def percentile(values, percent): """ PERCENTILE WITH INTERPOLATION RETURN VALUE AT, OR ABOVE, percentile OF THE VALUES snagged from http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/ """ N = sorted(values) if not N: return None k = (len(N) - 1) * pe...
PERCENTILE WITH INTERPOLATION RETURN VALUE AT, OR ABOVE, percentile OF THE VALUES snagged from http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/
Below is the the instruction that describes the task: ### Input: PERCENTILE WITH INTERPOLATION RETURN VALUE AT, OR ABOVE, percentile OF THE VALUES snagged from http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/ ### Response: def percentile(values, percent): """ PERCEN...
def get_comments_content_object(parser, token): """ Get a limited set of comments for a given object. Defaults to a limit of 5. Setting the limit to -1 disables limiting. usage: {% get_comments_content_object for form_object as variable_name %} """ keywords = token.contents.split() ...
Get a limited set of comments for a given object. Defaults to a limit of 5. Setting the limit to -1 disables limiting. usage: {% get_comments_content_object for form_object as variable_name %}
Below is the the instruction that describes the task: ### Input: Get a limited set of comments for a given object. Defaults to a limit of 5. Setting the limit to -1 disables limiting. usage: {% get_comments_content_object for form_object as variable_name %} ### Response: def get_comments_content_...
def get_open_orders(self, market=None): """ Get all orders that you currently have opened. A specific market can be requested. Endpoint: 1.1 /market/getopenorders 2.0 /key/market/getopenorders :param market: String literal for the market (ie. BTC-LTC) :t...
Get all orders that you currently have opened. A specific market can be requested. Endpoint: 1.1 /market/getopenorders 2.0 /key/market/getopenorders :param market: String literal for the market (ie. BTC-LTC) :type market: str :return: Open orders info in JSON ...
Below is the the instruction that describes the task: ### Input: Get all orders that you currently have opened. A specific market can be requested. Endpoint: 1.1 /market/getopenorders 2.0 /key/market/getopenorders :param market: String literal for the market (ie. BTC-LTC) ...
def create_markdown_cell(block): """Create a markdown cell from a block.""" kwargs = {'cell_type': block['type'], 'source': block['content']} markdown_cell = nbbase.new_markdown_cell(**kwargs) return markdown_cell
Create a markdown cell from a block.
Below is the the instruction that describes the task: ### Input: Create a markdown cell from a block. ### Response: def create_markdown_cell(block): """Create a markdown cell from a block.""" kwargs = {'cell_type': block['type'], 'source': block['content']} markdown_cell =...
def clusterQueues(self): """ Return a dict of queues in cluster and servers running them """ servers = yield self.getClusterServers() queues = {} for sname in servers: qs = yield self.get('rhumba.server.%s.queues' % sname) uuid = yield self.get('rhumba.s...
Return a dict of queues in cluster and servers running them
Below is the the instruction that describes the task: ### Input: Return a dict of queues in cluster and servers running them ### Response: def clusterQueues(self): """ Return a dict of queues in cluster and servers running them """ servers = yield self.getClusterServers() queues = ...
def parse_from_array(arr): """ Parse 2d array into synonym set Every array inside arr is considered a set of synonyms """ syn_set = SynonymSet() for synonyms in arr: _set = set() for synonym in synonyms: _set.add(synonym) syn_set.add_set(_set) return s...
Parse 2d array into synonym set Every array inside arr is considered a set of synonyms
Below is the the instruction that describes the task: ### Input: Parse 2d array into synonym set Every array inside arr is considered a set of synonyms ### Response: def parse_from_array(arr): """ Parse 2d array into synonym set Every array inside arr is considered a set of synonyms """ syn...
def fetch_all_messages(self, conn, directory, readonly): """ Fetches all messages at @conn from @directory. Params: conn IMAP4_SSL connection directory The IMAP directory to look for readonly readonly mode, true or false Return...
Fetches all messages at @conn from @directory. Params: conn IMAP4_SSL connection directory The IMAP directory to look for readonly readonly mode, true or false Returns: List of subject-body tuples
Below is the the instruction that describes the task: ### Input: Fetches all messages at @conn from @directory. Params: conn IMAP4_SSL connection directory The IMAP directory to look for readonly readonly mode, true or false Return...
def save_files(self, nodes): """ Saves user defined files using give nodes. :param nodes: Nodes. :type nodes: list :return: Method success. :rtype: bool """ metrics = {"Opened": 0, "Cached": 0} for node in nodes: file = node.file ...
Saves user defined files using give nodes. :param nodes: Nodes. :type nodes: list :return: Method success. :rtype: bool
Below is the the instruction that describes the task: ### Input: Saves user defined files using give nodes. :param nodes: Nodes. :type nodes: list :return: Method success. :rtype: bool ### Response: def save_files(self, nodes): """ Saves user defined files using giv...
def ext_pillar(minion_id, pillar, **kwargs): ''' Obtain the Pillar data from **reclass** for the given ``minion_id``. ''' # If reclass is installed, __virtual__ put it onto the search path, so we # don't need to protect against ImportError: # pylint: disable=3rd-party-module-not-gated from ...
Obtain the Pillar data from **reclass** for the given ``minion_id``.
Below is the the instruction that describes the task: ### Input: Obtain the Pillar data from **reclass** for the given ``minion_id``. ### Response: def ext_pillar(minion_id, pillar, **kwargs): ''' Obtain the Pillar data from **reclass** for the given ``minion_id``. ''' # If reclass is installed, _...
def namedbuffer(buffer_name, fields_spec): # noqa (ignore ciclomatic complexity) """ Class factory, returns a class to wrap a buffer instance and expose the data as fields. The field spec specifies how many bytes should be used for a field and what is the encoding / decoding function. """ # py...
Class factory, returns a class to wrap a buffer instance and expose the data as fields. The field spec specifies how many bytes should be used for a field and what is the encoding / decoding function.
Below is the the instruction that describes the task: ### Input: Class factory, returns a class to wrap a buffer instance and expose the data as fields. The field spec specifies how many bytes should be used for a field and what is the encoding / decoding function. ### Response: def namedbuffer(buffer...
def input_yn(conf_mess): """Print Confirmation Message and Get Y/N response from user.""" ui_erase_ln() ui_print(conf_mess) with term.cbreak(): input_flush() val = input_by_key() return bool(val.lower() == 'y')
Print Confirmation Message and Get Y/N response from user.
Below is the the instruction that describes the task: ### Input: Print Confirmation Message and Get Y/N response from user. ### Response: def input_yn(conf_mess): """Print Confirmation Message and Get Y/N response from user.""" ui_erase_ln() ui_print(conf_mess) with term.cbreak(): input_flu...
def get_domain(self): """ :returns: opposite vertices of the bounding prism for this object. :rtype: ndarray([min], [max]) """ if self.domain is None: return np.array([self.points.min(axis=0), self.points.max(axis=0)]...
:returns: opposite vertices of the bounding prism for this object. :rtype: ndarray([min], [max])
Below is the the instruction that describes the task: ### Input: :returns: opposite vertices of the bounding prism for this object. :rtype: ndarray([min], [max]) ### Response: def get_domain(self): """ :returns: opposite vertices of the bounding prism for this ...
def check_query(state, query, error_msg=None, expand_msg=None): """Run arbitrary queries against to the DB connection to verify the database state. For queries that do not return any output (INSERTs, UPDATEs, ...), you cannot use functions like ``check_col()`` and ``is_equal()`` to verify the query result....
Run arbitrary queries against to the DB connection to verify the database state. For queries that do not return any output (INSERTs, UPDATEs, ...), you cannot use functions like ``check_col()`` and ``is_equal()`` to verify the query result. ``check_query()`` will rerun the solution query in the transactio...
Below is the the instruction that describes the task: ### Input: Run arbitrary queries against to the DB connection to verify the database state. For queries that do not return any output (INSERTs, UPDATEs, ...), you cannot use functions like ``check_col()`` and ``is_equal()`` to verify the query result. ...
def fixed_string(self, data=None): """ The fixed string is used to identify a particular Yubikey device. The fixed string is referred to as the 'Token Identifier' in OATH-HOTP mode. The length of the fixed string can be set between 0 and 16 bytes. Tip: This can also be used to...
The fixed string is used to identify a particular Yubikey device. The fixed string is referred to as the 'Token Identifier' in OATH-HOTP mode. The length of the fixed string can be set between 0 and 16 bytes. Tip: This can also be used to extend the length of a static password.
Below is the the instruction that describes the task: ### Input: The fixed string is used to identify a particular Yubikey device. The fixed string is referred to as the 'Token Identifier' in OATH-HOTP mode. The length of the fixed string can be set between 0 and 16 bytes. Tip: This can a...
def path_regex(self): """Return the regex for the path to the build folder.""" try: path = '%s/' % urljoin(self.monthly_build_list_regex, self.builds[self.build_index]) if self.application in APPLICATIONS_MULTI_LOCALE \ and s...
Return the regex for the path to the build folder.
Below is the the instruction that describes the task: ### Input: Return the regex for the path to the build folder. ### Response: def path_regex(self): """Return the regex for the path to the build folder.""" try: path = '%s/' % urljoin(self.monthly_build_list_regex, ...
def get_F_y(fname='binzegger_connectivity_table.json', y=['p23']): ''' Extract frequency of occurrences of those cell types that are modeled. The data set contains cell types that are not modeled (TCs etc.) The returned percentages are renormalized onto modeled cell-types, i.e. they sum up to 1 ''...
Extract frequency of occurrences of those cell types that are modeled. The data set contains cell types that are not modeled (TCs etc.) The returned percentages are renormalized onto modeled cell-types, i.e. they sum up to 1
Below is the the instruction that describes the task: ### Input: Extract frequency of occurrences of those cell types that are modeled. The data set contains cell types that are not modeled (TCs etc.) The returned percentages are renormalized onto modeled cell-types, i.e. they sum up to 1 ### Response: def...
def open_package(locals=None, dr=None): """Try to open a package with the metatab_doc variable, which is set when a Notebook is run as a resource. If that does not exist, try the local _packages directory""" if locals is None: locals = caller_locals() try: # Running in a package build...
Try to open a package with the metatab_doc variable, which is set when a Notebook is run as a resource. If that does not exist, try the local _packages directory
Below is the the instruction that describes the task: ### Input: Try to open a package with the metatab_doc variable, which is set when a Notebook is run as a resource. If that does not exist, try the local _packages directory ### Response: def open_package(locals=None, dr=None): """Try to open a package w...
def custom_callback(self, view_func): """ Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. """ @wraps(view_func) def decorated(*args, **kwargs): plainreturn, dat...
Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server.
Below is the the instruction that describes the task: ### Input: Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. ### Response: def custom_callback(self, view_func): """ Wrapper function to us...
def save_data_files(vr, bs, prefix=None, directory=None): """Write the band structure data files to disk. Args: vs (`Vasprun`): Pymatgen `Vasprun` object. bs (`BandStructureSymmLine`): Calculated band structure. prefix (`str`, optional): Prefix for data file. directory (`str`, o...
Write the band structure data files to disk. Args: vs (`Vasprun`): Pymatgen `Vasprun` object. bs (`BandStructureSymmLine`): Calculated band structure. prefix (`str`, optional): Prefix for data file. directory (`str`, optional): Directory in which to save the data. Returns: ...
Below is the the instruction that describes the task: ### Input: Write the band structure data files to disk. Args: vs (`Vasprun`): Pymatgen `Vasprun` object. bs (`BandStructureSymmLine`): Calculated band structure. prefix (`str`, optional): Prefix for data file. directory (`str...
def plot_rebit_prior(prior, rebit_axes=REBIT_AXES, n_samples=2000, true_state=None, true_size=250, force_mean=None, legend=True, mean_color_index=2 ): """ Plots rebit states drawn from a given prior. :param qinfer.tomography.DensityOperatorDistribution prior: Distributio...
Plots rebit states drawn from a given prior. :param qinfer.tomography.DensityOperatorDistribution prior: Distribution over rebit states to plot. :param list rebit_axes: List containing indices for the :math:`x` and :math:`z` axes. :param int n_samples: Number of samples to draw from the ...
Below is the the instruction that describes the task: ### Input: Plots rebit states drawn from a given prior. :param qinfer.tomography.DensityOperatorDistribution prior: Distribution over rebit states to plot. :param list rebit_axes: List containing indices for the :math:`x` and :math:`z` a...
def nearest_overlap(self, overlap, bins): """Return nearest overlap/crop factor based on number of bins""" bins_overlap = overlap * bins if bins_overlap % 2 != 0: bins_overlap = math.ceil(bins_overlap / 2) * 2 overlap = bins_overlap / bins logger.warning('numb...
Return nearest overlap/crop factor based on number of bins
Below is the the instruction that describes the task: ### Input: Return nearest overlap/crop factor based on number of bins ### Response: def nearest_overlap(self, overlap, bins): """Return nearest overlap/crop factor based on number of bins""" bins_overlap = overlap * bins if bins_overlap ...
def ft2file(self, **kwargs): """ return the name of the input ft2 file list """ kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['data_time'] = kwargs.get( 'data_time', self.dataset(**kwargs)) self._replace_none(kwargs_copy) ...
return the name of the input ft2 file list
Below is the the instruction that describes the task: ### Input: return the name of the input ft2 file list ### Response: def ft2file(self, **kwargs): """ return the name of the input ft2 file list """ kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_c...
def _get_parseable_methods(cls): """Return all methods of cls that are parseable i.e. have been decorated by '@create_parser'. Args: cls: the class currently being decorated Note: classmethods will not be included as they can only be referenced once the class has been defined ...
Return all methods of cls that are parseable i.e. have been decorated by '@create_parser'. Args: cls: the class currently being decorated Note: classmethods will not be included as they can only be referenced once the class has been defined Returns: a 2-tuple with the p...
Below is the the instruction that describes the task: ### Input: Return all methods of cls that are parseable i.e. have been decorated by '@create_parser'. Args: cls: the class currently being decorated Note: classmethods will not be included as they can only be referenced once ...
def p_namespace(self, p): """namespace : KEYWORD ID NL | KEYWORD ID NL INDENT docsection DEDENT""" if p[1] == 'namespace': doc = None if len(p) > 4: doc = p[5] p[0] = AstNamespace( self.path, p.lineno(1), p.lexpos(1...
namespace : KEYWORD ID NL | KEYWORD ID NL INDENT docsection DEDENT
Below is the the instruction that describes the task: ### Input: namespace : KEYWORD ID NL | KEYWORD ID NL INDENT docsection DEDENT ### Response: def p_namespace(self, p): """namespace : KEYWORD ID NL | KEYWORD ID NL INDENT docsection DEDENT""" if p[1] == '...
def write_block_data(self, address, register, value): """ SMBus Block Write: i2c_smbus_write_block_data() ================================================ The opposite of the Block Read command, this writes up to 32 bytes to a device, to a designated register that is specified ...
SMBus Block Write: i2c_smbus_write_block_data() ================================================ The opposite of the Block Read command, this writes up to 32 bytes to a device, to a designated register that is specified through the Comm byte. The amount of data is specified in the Coun...
Below is the the instruction that describes the task: ### Input: SMBus Block Write: i2c_smbus_write_block_data() ================================================ The opposite of the Block Read command, this writes up to 32 bytes to a device, to a designated register that is specified throu...
def generate(self): """Generates a particle using the creator function. Notes ----- Position and speed are uniformly randomly seeded within allowed bounds. The particle also has speed limit settings taken from global values. Returns ------- partic...
Generates a particle using the creator function. Notes ----- Position and speed are uniformly randomly seeded within allowed bounds. The particle also has speed limit settings taken from global values. Returns ------- particle object
Below is the the instruction that describes the task: ### Input: Generates a particle using the creator function. Notes ----- Position and speed are uniformly randomly seeded within allowed bounds. The particle also has speed limit settings taken from global values. ...
def _recurse(data, obj): """Iterates over all children of the current object, gathers the contents contributing to the resulting PGFPlots file, and returns those. """ content = _ContentManager() for child in obj.get_children(): # Some patches are Spines, too; skip those entirely. # S...
Iterates over all children of the current object, gathers the contents contributing to the resulting PGFPlots file, and returns those.
Below is the the instruction that describes the task: ### Input: Iterates over all children of the current object, gathers the contents contributing to the resulting PGFPlots file, and returns those. ### Response: def _recurse(data, obj): """Iterates over all children of the current object, gathers the con...
def is_in_range(self, values, unit=None, raise_exception=True): """Check if a list of values is within physically/mathematically possible range. Args: values: A list of values. unit: The unit of the values. If not specified, the default metric unit will be assum...
Check if a list of values is within physically/mathematically possible range. Args: values: A list of values. unit: The unit of the values. If not specified, the default metric unit will be assumed. raise_exception: Set to True to raise an exception if not i...
Below is the the instruction that describes the task: ### Input: Check if a list of values is within physically/mathematically possible range. Args: values: A list of values. unit: The unit of the values. If not specified, the default metric unit will be assumed. ...
def user( state, host, name, present=True, home=None, shell=None, group=None, groups=None, public_keys=None, delete_keys=False, ensure_home=True, system=False, uid=None, ): ''' Add/remove/update system users & their ssh `authorized_keys`. + name: name of the user to ensure + present: wh...
Add/remove/update system users & their ssh `authorized_keys`. + name: name of the user to ensure + present: whether this user should exist + home: the users home directory + shell: the users shell + group: the users primary group + groups: the users secondary groups + public_keys: list of p...
Below is the the instruction that describes the task: ### Input: Add/remove/update system users & their ssh `authorized_keys`. + name: name of the user to ensure + present: whether this user should exist + home: the users home directory + shell: the users shell + group: the users primary group ...
def factory(cls, registry): """Returns a dynamic MetricsHandler class tied to the passed registry. """ # This implementation relies on MetricsHandler.registry # (defined above and defaulted to REGISTRY). # As we have unicode_literals, we need to create a str() ...
Returns a dynamic MetricsHandler class tied to the passed registry.
Below is the the instruction that describes the task: ### Input: Returns a dynamic MetricsHandler class tied to the passed registry. ### Response: def factory(cls, registry): """Returns a dynamic MetricsHandler class tied to the passed registry. """ # This implementati...
def _reorderForPreference(themeList, preferredThemeName): """ Re-order the input themeList according to the preferred theme. Returns None. """ for theme in themeList: if preferredThemeName == theme.themeName: themeList.remove(theme) themeList.insert(0, theme) ...
Re-order the input themeList according to the preferred theme. Returns None.
Below is the the instruction that describes the task: ### Input: Re-order the input themeList according to the preferred theme. Returns None. ### Response: def _reorderForPreference(themeList, preferredThemeName): """ Re-order the input themeList according to the preferred theme. Returns None. ...
def page_sequence(n_sheets: int, one_based: bool = True) -> List[int]: """ Generates the final page sequence from the starting number of sheets. """ n_pages = calc_n_virtual_pages(n_sheets) assert n_pages % 4 == 0 half_n_pages = n_pages // 2 firsthalf = list(range(half_n_pages)) secondha...
Generates the final page sequence from the starting number of sheets.
Below is the the instruction that describes the task: ### Input: Generates the final page sequence from the starting number of sheets. ### Response: def page_sequence(n_sheets: int, one_based: bool = True) -> List[int]: """ Generates the final page sequence from the starting number of sheets. """ n...