code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def namedb_get_num_names( cur, current_block, include_expired=False ): """ Get the number of names that exist at the current block """ unexpired_query = "" unexpired_args = () if not include_expired: # count all names, including expired ones unexpired_query, unexpired_args = nam...
Get the number of names that exist at the current block
Below is the the instruction that describes the task: ### Input: Get the number of names that exist at the current block ### Response: def namedb_get_num_names( cur, current_block, include_expired=False ): """ Get the number of names that exist at the current block """ unexpired_query = "" unex...
def hse_output(pdb_file, file_type): """ The solvent exposure of an amino acid residue is important for analyzing, understanding and predicting aspects of protein structure and function [73]. A residue's solvent exposure can be classified as four categories: exposed, partly exposed, buried and deepl...
The solvent exposure of an amino acid residue is important for analyzing, understanding and predicting aspects of protein structure and function [73]. A residue's solvent exposure can be classified as four categories: exposed, partly exposed, buried and deeply buried residues. Hamelryck et al. [73] establi...
Below is the the instruction that describes the task: ### Input: The solvent exposure of an amino acid residue is important for analyzing, understanding and predicting aspects of protein structure and function [73]. A residue's solvent exposure can be classified as four categories: exposed, partly exposed, ...
def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False, validating=True): """Return UIDs of the selected services """ service_uids = form.get("uids", []) return service_uids, {}
Return UIDs of the selected services
Below is the the instruction that describes the task: ### Input: Return UIDs of the selected services ### Response: def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False, validating=True): """Return UIDs of the selected services """ s...
def update(self, dt): """ Responsabilities: Updates game engine each tick Copies new stats into labels """ for key, value in self.labels.iteritems(): str_val = str(int(self.stats[key])) self.msgs[key][0].element.text = self.labels[key] + st...
Responsabilities: Updates game engine each tick Copies new stats into labels
Below is the the instruction that describes the task: ### Input: Responsabilities: Updates game engine each tick Copies new stats into labels ### Response: def update(self, dt): """ Responsabilities: Updates game engine each tick Copies new stats into...
def lmax(self): r"""Largest eigenvalue of the graph Laplacian. Can be exactly computed by :func:`compute_fourier_basis` or approximated by :func:`estimate_lmax`. """ if self._lmax is None: self.logger.warning('The largest eigenvalue G.lmax is not ' ...
r"""Largest eigenvalue of the graph Laplacian. Can be exactly computed by :func:`compute_fourier_basis` or approximated by :func:`estimate_lmax`.
Below is the the instruction that describes the task: ### Input: r"""Largest eigenvalue of the graph Laplacian. Can be exactly computed by :func:`compute_fourier_basis` or approximated by :func:`estimate_lmax`. ### Response: def lmax(self): r"""Largest eigenvalue of the graph Laplacian. ...
def _get_range_dimension_key(self, base_key: Key, start_time: datetime, end_time: datetime, count: int = 0) -> List[Tuple[Key, Any]]: """ Returns the list of items from the...
Returns the list of items from the store based on the given time range or count. This is used when the key being used is a DIMENSION key.
Below is the the instruction that describes the task: ### Input: Returns the list of items from the store based on the given time range or count. This is used when the key being used is a DIMENSION key. ### Response: def _get_range_dimension_key(self, base_key: Key, ...
def ToMicroseconds(self): """Converts a Duration to microseconds.""" micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND) return self.seconds * _MICROS_PER_SECOND + micros
Converts a Duration to microseconds.
Below is the the instruction that describes the task: ### Input: Converts a Duration to microseconds. ### Response: def ToMicroseconds(self): """Converts a Duration to microseconds.""" micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND) return self.seconds * _MICROS_PER_SECOND + micros
def remove_node(self, node): """ Removes node from circle and rebuild it. """ try: self._nodes.remove(node) del self._weights[node] except (KeyError, ValueError): pass self._hashring = dict() self._sorted_keys = [] ...
Removes node from circle and rebuild it.
Below is the the instruction that describes the task: ### Input: Removes node from circle and rebuild it. ### Response: def remove_node(self, node): """ Removes node from circle and rebuild it. """ try: self._nodes.remove(node) del self._weights[node] ...
def _read_marcxml(xml): """ Read MARC XML or OAI file, convert, add namespace and return XML in required format with all necessities. Args: xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. Returns: obj: Required XML parsed with ``lxml.etr...
Read MARC XML or OAI file, convert, add namespace and return XML in required format with all necessities. Args: xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. Returns: obj: Required XML parsed with ``lxml.etree``.
Below is the the instruction that describes the task: ### Input: Read MARC XML or OAI file, convert, add namespace and return XML in required format with all necessities. Args: xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. Returns: obj: Re...
def weakref_proxy(obj): """returns either a weakref.proxy for the object, or if object is already a proxy, returns itself.""" if type(obj) in weakref.ProxyTypes: return obj else: return weakref.proxy(obj)
returns either a weakref.proxy for the object, or if object is already a proxy, returns itself.
Below is the the instruction that describes the task: ### Input: returns either a weakref.proxy for the object, or if object is already a proxy, returns itself. ### Response: def weakref_proxy(obj): """returns either a weakref.proxy for the object, or if object is already a proxy, returns itself.""" ...
def fetch(opts): """ Create a local mirror of one or more resources. """ resources = _load(opts.resources, opts.output_dir) if opts.all: opts.resource_names = ALL reporthook = None if opts.quiet else lambda name: print('Fetching {}...'.format(name)) if opts.verbose: backend.V...
Create a local mirror of one or more resources.
Below is the the instruction that describes the task: ### Input: Create a local mirror of one or more resources. ### Response: def fetch(opts): """ Create a local mirror of one or more resources. """ resources = _load(opts.resources, opts.output_dir) if opts.all: opts.resource_names = A...
def call_purge_doc(cls, kb_app, sphinx_app: Sphinx, sphinx_env: BuildEnvironment, docname: str): """ On env-purge-doc, do callbacks """ for callback in EventAction.get_callbacks(kb_app, SphinxEvent.EPD): callback(kb_app, sphinx_app, sphinx_env, ...
On env-purge-doc, do callbacks
Below is the the instruction that describes the task: ### Input: On env-purge-doc, do callbacks ### Response: def call_purge_doc(cls, kb_app, sphinx_app: Sphinx, sphinx_env: BuildEnvironment, docname: str): """ On env-purge-doc, do callbacks """ for ca...
def status_charge(): ''' Return battery charge CLI Example: .. code-block:: bash salt '*' apcups.status_charge ''' data = status() if 'BCHARGE' in data: charge = data['BCHARGE'].split() if charge[1].lower() == 'percent': return float(charge[0]) ret...
Return battery charge CLI Example: .. code-block:: bash salt '*' apcups.status_charge
Below is the the instruction that describes the task: ### Input: Return battery charge CLI Example: .. code-block:: bash salt '*' apcups.status_charge ### Response: def status_charge(): ''' Return battery charge CLI Example: .. code-block:: bash salt '*' apcups.status_...
def __normalize_grades(self): """ Adjust the grades list. If a grade has been set, set All to false """ if 'grades' in self and self['grades']['All'] is True: for grade in self['grades']: if grade != 'All' and self['grades'][grade] is True: ...
Adjust the grades list. If a grade has been set, set All to false
Below is the the instruction that describes the task: ### Input: Adjust the grades list. If a grade has been set, set All to false ### Response: def __normalize_grades(self): """ Adjust the grades list. If a grade has been set, set All to false """ if 'grades' in se...
def PopupGetFolder(message, default_path='', no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folder=None): ...
Display popup with text entry field and browse button. Browse for folder :param message: :param default_path: :param no_window: :param size: :param button_color: :param background_color: :param text_color: :param icon: :param font: :param no_titlebar: :param grab_anywhere: ...
Below is the the instruction that describes the task: ### Input: Display popup with text entry field and browse button. Browse for folder :param message: :param default_path: :param no_window: :param size: :param button_color: :param background_color: :param text_color: :param icon: ...
def needs_ssh(hostname, _socket=None): """ Obtains remote hostname of the socket and cuts off the domain part of its FQDN. """ if hostname.lower() in ['localhost', '127.0.0.1', '127.0.1.1']: return False _socket = _socket or socket fqdn = _socket.getfqdn() if hostname == fqdn: ...
Obtains remote hostname of the socket and cuts off the domain part of its FQDN.
Below is the the instruction that describes the task: ### Input: Obtains remote hostname of the socket and cuts off the domain part of its FQDN. ### Response: def needs_ssh(hostname, _socket=None): """ Obtains remote hostname of the socket and cuts off the domain part of its FQDN. """ if ho...
def _convert_fancy(self, field): """Convert to a list (sep != None) and convert list elements.""" if self.sep is False: x = self._convert_singlet(field) else: x = tuple([self._convert_singlet(s) for s in field.split(self.sep)]) if len(x) == 0: ...
Convert to a list (sep != None) and convert list elements.
Below is the the instruction that describes the task: ### Input: Convert to a list (sep != None) and convert list elements. ### Response: def _convert_fancy(self, field): """Convert to a list (sep != None) and convert list elements.""" if self.sep is False: x = self._convert_singlet(fie...
def parse_script(output_script): """ Parses an output and returns the payload if the output matches the right pattern for a marker output, or None otherwise. :param CScript output_script: The output script to be parsed. :return: The marker output payload if the output fits the p...
Parses an output and returns the payload if the output matches the right pattern for a marker output, or None otherwise. :param CScript output_script: The output script to be parsed. :return: The marker output payload if the output fits the pattern, None otherwise. :rtype: bytes
Below is the the instruction that describes the task: ### Input: Parses an output and returns the payload if the output matches the right pattern for a marker output, or None otherwise. :param CScript output_script: The output script to be parsed. :return: The marker output payload if the o...
def get_comment_object(self): """ Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object (i.e. ``user...
Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object (i.e. ``user`` or ``ip_address``).
Below is the the instruction that describes the task: ### Input: Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object ...
def output_touch(self): """ensure the ./swhlab/ folder exists.""" if not os.path.exists(self.outFolder): self.log.debug("creating %s",self.outFolder) os.mkdir(self.outFolder)
ensure the ./swhlab/ folder exists.
Below is the the instruction that describes the task: ### Input: ensure the ./swhlab/ folder exists. ### Response: def output_touch(self): """ensure the ./swhlab/ folder exists.""" if not os.path.exists(self.outFolder): self.log.debug("creating %s",self.outFolder) os.mkdir(s...
def upgrade(): """Upgrade database.""" op.create_table( 'pidstore_pid', sa.Column('created', sa.DateTime(), nullable=False), sa.Column('updated', sa.DateTime(), nullable=False), sa.Column('id', sa.Integer(), nullable=False), sa.Column('pid_type', sa.String(length=6), null...
Upgrade database.
Below is the the instruction that describes the task: ### Input: Upgrade database. ### Response: def upgrade(): """Upgrade database.""" op.create_table( 'pidstore_pid', sa.Column('created', sa.DateTime(), nullable=False), sa.Column('updated', sa.DateTime(), nullable=False), ...
def _xy2hash(x, y, dim): """Convert (x, y) to hashcode. Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 Pure python implementation. Parameters: x: int x value of point [0, dim) in dim x dim coord system y: int ...
Convert (x, y) to hashcode. Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 Pure python implementation. Parameters: x: int x value of point [0, dim) in dim x dim coord system y: int y value of point [0, dim) ...
Below is the the instruction that describes the task: ### Input: Convert (x, y) to hashcode. Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 Pure python implementation. Parameters: x: int x value of point [0, dim) in di...
def cov_params(self, r_matrix=None, column=None, scale=None, cov_p=None, other=None): """ Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will ...
Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar. Parameters ---------- r_...
Below is the the instruction that describes the task: ### Input: Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to ...
def convert(txt, src_fmt, tgt_fmt, single=True, **kwargs): """ Convert a textual representation of \*MRS from one the src_fmt representation to the tgt_fmt representation. By default, only read and convert a single \*MRS object (e.g. for `mrx` this starts at <mrs> and not <mrs-list>), but changing t...
Convert a textual representation of \*MRS from one the src_fmt representation to the tgt_fmt representation. By default, only read and convert a single \*MRS object (e.g. for `mrx` this starts at <mrs> and not <mrs-list>), but changing the `mode` argument to `corpus` (alternatively: `list`) reads and co...
Below is the the instruction that describes the task: ### Input: Convert a textual representation of \*MRS from one the src_fmt representation to the tgt_fmt representation. By default, only read and convert a single \*MRS object (e.g. for `mrx` this starts at <mrs> and not <mrs-list>), but changing the...
def table(self, table): """ Modify a table on the schema. :param table: The table """ try: blueprint = self._create_blueprint(table) yield blueprint except Exception as e: raise try: self._build(blueprint) ...
Modify a table on the schema. :param table: The table
Below is the the instruction that describes the task: ### Input: Modify a table on the schema. :param table: The table ### Response: def table(self, table): """ Modify a table on the schema. :param table: The table """ try: blueprint = self._create_blue...
def frets_to_NoteContainer(self, fingering): """Convert a list such as returned by find_fret to a NoteContainer.""" res = [] for (string, fret) in enumerate(fingering): if fret is not None: res.append(self.get_Note(string, fret)) return NoteContainer(res)
Convert a list such as returned by find_fret to a NoteContainer.
Below is the the instruction that describes the task: ### Input: Convert a list such as returned by find_fret to a NoteContainer. ### Response: def frets_to_NoteContainer(self, fingering): """Convert a list such as returned by find_fret to a NoteContainer.""" res = [] for (string, fret) in...
def _deriv_logaddexp2(x1, x2): """The derivative of f(x, y) = log2(2^x + 2^y)""" y1 = np.exp2(x1) y2 = np.exp2(x2) df_dx1 = y1 / (y1 + y2) df_dx2 = y2 / (y1 + y2) return np.vstack([df_dx1, df_dx2]).T
The derivative of f(x, y) = log2(2^x + 2^y)
Below is the the instruction that describes the task: ### Input: The derivative of f(x, y) = log2(2^x + 2^y) ### Response: def _deriv_logaddexp2(x1, x2): """The derivative of f(x, y) = log2(2^x + 2^y)""" y1 = np.exp2(x1) y2 = np.exp2(x2) df_dx1 = y1 / (y1 + y2) df_dx2 = y2 / (y1 + y2) retur...
def get_viz(self, force=False): """Creates :py:class:viz.BaseViz object from the url_params_multidict. :return: object of the 'viz_type' type that is taken from the url_params_multidict or self.params. :rtype: :py:class:viz.BaseViz """ slice_params = json.loads(self....
Creates :py:class:viz.BaseViz object from the url_params_multidict. :return: object of the 'viz_type' type that is taken from the url_params_multidict or self.params. :rtype: :py:class:viz.BaseViz
Below is the the instruction that describes the task: ### Input: Creates :py:class:viz.BaseViz object from the url_params_multidict. :return: object of the 'viz_type' type that is taken from the url_params_multidict or self.params. :rtype: :py:class:viz.BaseViz ### Response: def get_vi...
def get_font_files(): """Returns a list of all font files we could find Returned as a list of dir/files tuples:: get_font_files() -> {'FontName': '/abs/FontName.ttf', ...] For example:: >>> fonts = get_font_files() >>> 'NotoSans-Bold' in fonts True >>> fonts['Noto...
Returns a list of all font files we could find Returned as a list of dir/files tuples:: get_font_files() -> {'FontName': '/abs/FontName.ttf', ...] For example:: >>> fonts = get_font_files() >>> 'NotoSans-Bold' in fonts True >>> fonts['NotoSans-Bold'].endswith('/NotoSa...
Below is the the instruction that describes the task: ### Input: Returns a list of all font files we could find Returned as a list of dir/files tuples:: get_font_files() -> {'FontName': '/abs/FontName.ttf', ...] For example:: >>> fonts = get_font_files() >>> 'NotoSans-Bold' in fo...
def visit_FunctionDef(self, node: ast.FunctionDef) -> Optional[ast.AST]: """Eliminate dead code from function bodies.""" new_node = self.generic_visit(node) assert isinstance(new_node, ast.FunctionDef) return ast.copy_location( ast.FunctionDef( name=new_node.n...
Eliminate dead code from function bodies.
Below is the the instruction that describes the task: ### Input: Eliminate dead code from function bodies. ### Response: def visit_FunctionDef(self, node: ast.FunctionDef) -> Optional[ast.AST]: """Eliminate dead code from function bodies.""" new_node = self.generic_visit(node) assert isinst...
def configure_logging(level=logging.DEBUG): '''Configures the root logger for command line applications. A stream handler will be added to the logger that directs messages to the standard error stream. By default, *no* messages will be filtered out: set a higher level on derived/child loggers to a...
Configures the root logger for command line applications. A stream handler will be added to the logger that directs messages to the standard error stream. By default, *no* messages will be filtered out: set a higher level on derived/child loggers to achieve filtering. Warning ------- Logg...
Below is the the instruction that describes the task: ### Input: Configures the root logger for command line applications. A stream handler will be added to the logger that directs messages to the standard error stream. By default, *no* messages will be filtered out: set a higher level on derived/...
def remove_user(self, name): """Remove a user from kubeconfig. """ user = self.get_user(name) users = self.get_users() users.remove(user)
Remove a user from kubeconfig.
Below is the the instruction that describes the task: ### Input: Remove a user from kubeconfig. ### Response: def remove_user(self, name): """Remove a user from kubeconfig. """ user = self.get_user(name) users = self.get_users() users.remove(user)
def get_old_options(cli, image): """ Returns Dockerfile values for CMD and Entrypoint """ return { 'cmd': dockerapi.inspect_config(cli, image, 'Cmd'), 'entrypoint': dockerapi.inspect_config(cli, image, 'Entrypoint'), }
Returns Dockerfile values for CMD and Entrypoint
Below is the the instruction that describes the task: ### Input: Returns Dockerfile values for CMD and Entrypoint ### Response: def get_old_options(cli, image): """ Returns Dockerfile values for CMD and Entrypoint """ return { 'cmd': dockerapi.inspect_config(cli, image, 'Cmd'), 'entrypo...
def _get_kernel_data(self, nmr_samples, thinning, return_output): """Get the kernel data we will input to the MCMC sampler. This sets the items: * data: the pointer to the user provided data * method_data: the data specific to the MCMC method * nmr_iterations: the number of ite...
Get the kernel data we will input to the MCMC sampler. This sets the items: * data: the pointer to the user provided data * method_data: the data specific to the MCMC method * nmr_iterations: the number of iterations to sample * iteration_offset: the current sample index, that ...
Below is the the instruction that describes the task: ### Input: Get the kernel data we will input to the MCMC sampler. This sets the items: * data: the pointer to the user provided data * method_data: the data specific to the MCMC method * nmr_iterations: the number of iterations ...
def queue_raw_jobs(queue, params_list, **kwargs): """ Queue some jobs on a raw queue """ from .queue import Queue queue_obj = Queue(queue) queue_obj.enqueue_raw_jobs(params_list, **kwargs)
Queue some jobs on a raw queue
Below is the the instruction that describes the task: ### Input: Queue some jobs on a raw queue ### Response: def queue_raw_jobs(queue, params_list, **kwargs): """ Queue some jobs on a raw queue """ from .queue import Queue queue_obj = Queue(queue) queue_obj.enqueue_raw_jobs(params_list, **kwargs)
def _transition_loop(self): """Execute all queued transitions step by step.""" while self._transitions: start = time.time() for transition in self._transitions: transition.step() if transition.finished: self._transitions.remove(...
Execute all queued transitions step by step.
Below is the the instruction that describes the task: ### Input: Execute all queued transitions step by step. ### Response: def _transition_loop(self): """Execute all queued transitions step by step.""" while self._transitions: start = time.time() for transition in self._tra...
def blue(self, memo=None): """ Constructs a BlueDispatcher out of the current object. :param memo: A dictionary to cache Blueprints. :type memo: dict[T,schedula.utils.blue.Blueprint] :return: A BlueDispatcher of the current object. :rtype: schedu...
Constructs a BlueDispatcher out of the current object. :param memo: A dictionary to cache Blueprints. :type memo: dict[T,schedula.utils.blue.Blueprint] :return: A BlueDispatcher of the current object. :rtype: schedula.utils.blue.BlueDispatcher
Below is the the instruction that describes the task: ### Input: Constructs a BlueDispatcher out of the current object. :param memo: A dictionary to cache Blueprints. :type memo: dict[T,schedula.utils.blue.Blueprint] :return: A BlueDispatcher of the current object. ...
def mimic_user_input( args: List[str], source_challenge_response: List[Tuple[SubprocSource, str, Union[str, SubprocCommand]]], line_terminators: List[str] = None, print_stdout: bool = False, ...
r""" Run an external command. Pretend to be a human by sending text to the subcommand (responses) when the external command sends us triggers (challenges). This is a bit nasty. Args: args: command-line arguments source_challenge_response: list of tuples of the format ``(cha...
Below is the the instruction that describes the task: ### Input: r""" Run an external command. Pretend to be a human by sending text to the subcommand (responses) when the external command sends us triggers (challenges). This is a bit nasty. Args: args: command-line arguments ...
def leaveoneout(self): """Train & Test using leave one out""" traintestfile = self.fileprefix + '.train' options = "-F " + self.format + " " + self.timbloptions + " -t leave_one_out" if sys.version < '3': self.api = timblapi.TimblAPI(b(options), b"") else: ...
Train & Test using leave one out
Below is the the instruction that describes the task: ### Input: Train & Test using leave one out ### Response: def leaveoneout(self): """Train & Test using leave one out""" traintestfile = self.fileprefix + '.train' options = "-F " + self.format + " " + self.timbloptions + " -t leave_one_...
def object(self, infotype, key): "Return the encoding, idletime, or refcount about the key" redisent = self.redises[self._getnodenamefor(key) + '_slave'] return getattr(redisent, 'object')(infotype, key)
Return the encoding, idletime, or refcount about the key
Below is the the instruction that describes the task: ### Input: Return the encoding, idletime, or refcount about the key ### Response: def object(self, infotype, key): "Return the encoding, idletime, or refcount about the key" redisent = self.redises[self._getnodenamefor(key) + '_slave'] r...
def set_uploaded(self, files_uploaded): """ set_uploaded: records progress after uploading files Args: files_uploaded ([str]): list of files that have been successfully uploaded Returns: None """ self.files_uploaded = files_uploaded self.__record_progress(Status.U...
set_uploaded: records progress after uploading files Args: files_uploaded ([str]): list of files that have been successfully uploaded Returns: None
Below is the the instruction that describes the task: ### Input: set_uploaded: records progress after uploading files Args: files_uploaded ([str]): list of files that have been successfully uploaded Returns: None ### Response: def set_uploaded(self, files_uploaded): """ set_uploaded...
def json_2_cluster(json_obj): """ transform json from Ariane server to local object :param json_obj: json from Ariane Server :return: transformed cluster """ LOGGER.debug("Cluster.json_2_cluster") return Cluster( cid=json_obj['clusterID'], ...
transform json from Ariane server to local object :param json_obj: json from Ariane Server :return: transformed cluster
Below is the the instruction that describes the task: ### Input: transform json from Ariane server to local object :param json_obj: json from Ariane Server :return: transformed cluster ### Response: def json_2_cluster(json_obj): """ transform json from Ariane server to local object ...
def checkValidCell(self, index): """Asks the model if the value at *index* is valid See :meth:`isFieldValid<sparkle.stim.auto_parameter_model.AutoParameterModel.isFieldValid>` """ col = index.column() row = index.row() return self.model.isFieldValid(row, self._headers[in...
Asks the model if the value at *index* is valid See :meth:`isFieldValid<sparkle.stim.auto_parameter_model.AutoParameterModel.isFieldValid>`
Below is the the instruction that describes the task: ### Input: Asks the model if the value at *index* is valid See :meth:`isFieldValid<sparkle.stim.auto_parameter_model.AutoParameterModel.isFieldValid>` ### Response: def checkValidCell(self, index): """Asks the model if the value at *index* is v...
def load_v4_tools(): """ Load Gromacs 4.x tools automatically using some heuristic. Tries to load tools (1) in configured tool groups (2) and fails back to automatic detection from ``GMXBIN`` (3) then to a prefilled list. Also load any extra tool configured in ``~/.gromacswrapper.cfg`` :return: ...
Load Gromacs 4.x tools automatically using some heuristic. Tries to load tools (1) in configured tool groups (2) and fails back to automatic detection from ``GMXBIN`` (3) then to a prefilled list. Also load any extra tool configured in ``~/.gromacswrapper.cfg`` :return: dict mapping tool names to Gr...
Below is the the instruction that describes the task: ### Input: Load Gromacs 4.x tools automatically using some heuristic. Tries to load tools (1) in configured tool groups (2) and fails back to automatic detection from ``GMXBIN`` (3) then to a prefilled list. Also load any extra tool configured in ...
def add_args_kwargs(func): """Add Args and Kwargs This wrapper adds support for additional arguments and keyword arguments to any callable function Parameters ---------- func : function Callable function Returns ------- function wrapper """ @wraps(func) def w...
Add Args and Kwargs This wrapper adds support for additional arguments and keyword arguments to any callable function Parameters ---------- func : function Callable function Returns ------- function wrapper
Below is the the instruction that describes the task: ### Input: Add Args and Kwargs This wrapper adds support for additional arguments and keyword arguments to any callable function Parameters ---------- func : function Callable function Returns ------- function wrapper #...
def handle(self, *args, **options): """Run do_index_command on each specified index and log the output.""" for index in options.pop("indexes"): data = {} try: data = self.do_index_command(index, **options) except TransportError as ex: l...
Run do_index_command on each specified index and log the output.
Below is the the instruction that describes the task: ### Input: Run do_index_command on each specified index and log the output. ### Response: def handle(self, *args, **options): """Run do_index_command on each specified index and log the output.""" for index in options.pop("indexes"): ...
def make_interactive_tree(matrix=None,labels=None): '''make interactive tree will return complete html for an interactive tree :param title: a title for the plot, if not defined, will be left out. ''' from scipy.cluster.hierarchy import ( dendrogram, linkage, to_tree ) ...
make interactive tree will return complete html for an interactive tree :param title: a title for the plot, if not defined, will be left out.
Below is the the instruction that describes the task: ### Input: make interactive tree will return complete html for an interactive tree :param title: a title for the plot, if not defined, will be left out. ### Response: def make_interactive_tree(matrix=None,labels=None): '''make interactive tree will retu...
def seqs_from_file(filename, exit_on_err=False, return_qual=False): """Extract sequences from a file Name: seqs_from_file Author(s): Martin C F Thomsen Date: 18 Jul 2013 Description: Iterator which extract sequence data from the input file Args: filename: string which...
Extract sequences from a file Name: seqs_from_file Author(s): Martin C F Thomsen Date: 18 Jul 2013 Description: Iterator which extract sequence data from the input file Args: filename: string which contain a path to the input file Supported Formats: fasta, fastq...
Below is the the instruction that describes the task: ### Input: Extract sequences from a file Name: seqs_from_file Author(s): Martin C F Thomsen Date: 18 Jul 2013 Description: Iterator which extract sequence data from the input file Args: filename: string which cont...
def all(self, timeout=None, max_concurrency=64, auto_batch=True): """Fanout to all hosts. Works otherwise exactly like :meth:`fanout`. Example:: with cluster.all() as client: client.flushdb() """ return self.fanout('all', timeout=timeout, ...
Fanout to all hosts. Works otherwise exactly like :meth:`fanout`. Example:: with cluster.all() as client: client.flushdb()
Below is the the instruction that describes the task: ### Input: Fanout to all hosts. Works otherwise exactly like :meth:`fanout`. Example:: with cluster.all() as client: client.flushdb() ### Response: def all(self, timeout=None, max_concurrency=64, auto_batch=True): ...
def user_data(self, access_token, *args, **kwargs): """Load user data from OAuth Profile Google App Engine App""" url = GOOGLE_APPENGINE_PROFILE_V1 auth = self.oauth_auth(access_token) return self.get_json(url, auth=auth, params=auth )
Load user data from OAuth Profile Google App Engine App
Below is the the instruction that describes the task: ### Input: Load user data from OAuth Profile Google App Engine App ### Response: def user_data(self, access_token, *args, **kwargs): """Load user data from OAuth Profile Google App Engine App""" url = GOOGLE_APPENGINE_PROFILE_V1 auth = s...
def submit_status_external_cmd(cmd_file, status_file): ''' Submits the status lines in the status_file to Nagios' external cmd file. ''' try: with open(cmd_file, 'a') as cmd_file: cmd_file.write(status_file.read()) except IOError: exit("Fatal error: Unable to write to Nagios external command file ...
Submits the status lines in the status_file to Nagios' external cmd file.
Below is the the instruction that describes the task: ### Input: Submits the status lines in the status_file to Nagios' external cmd file. ### Response: def submit_status_external_cmd(cmd_file, status_file): ''' Submits the status lines in the status_file to Nagios' external cmd file. ''' try: with open(...
def getMetadata(L): """ Get metadata from a LiPD data in memory | Example | m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"]) :param dict L: One LiPD record :return dict d: LiPD record (metadata only) """ _l = {} try: # Create a copy. Do not affect the original d...
Get metadata from a LiPD data in memory | Example | m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"]) :param dict L: One LiPD record :return dict d: LiPD record (metadata only)
Below is the the instruction that describes the task: ### Input: Get metadata from a LiPD data in memory | Example | m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"]) :param dict L: One LiPD record :return dict d: LiPD record (metadata only) ### Response: def getMetadata(L): """ ...
def add_extension(self, extension): """ Specify a broadway extension to initialise .. code-block:: python factory = Factory() factory.add_extension('broadway_sqlalchemy') :param extension: import path to extension :type extension: str """ ...
Specify a broadway extension to initialise .. code-block:: python factory = Factory() factory.add_extension('broadway_sqlalchemy') :param extension: import path to extension :type extension: str
Below is the the instruction that describes the task: ### Input: Specify a broadway extension to initialise .. code-block:: python factory = Factory() factory.add_extension('broadway_sqlalchemy') :param extension: import path to extension :type extension: str ### ...
def fill_cache(self): """Fill the cache with new data from the sensor.""" _LOGGER.debug('Filling cache with new sensor data.') try: firmware_version = self.firmware_version() except BluetoothBackendException: # If a sensor doesn't work, wait 5 minutes before retry...
Fill the cache with new data from the sensor.
Below is the the instruction that describes the task: ### Input: Fill the cache with new data from the sensor. ### Response: def fill_cache(self): """Fill the cache with new data from the sensor.""" _LOGGER.debug('Filling cache with new sensor data.') try: firmware_version = sel...
def bootstrap(nside, rand, nbar, *data): """ This function will bootstrap data based on the sky coverage of rand. It is different from bootstrap in the traditional sense, but for correlation functions it gives the correct answer with less computation. nbar : number density of rand, used to ...
This function will bootstrap data based on the sky coverage of rand. It is different from bootstrap in the traditional sense, but for correlation functions it gives the correct answer with less computation. nbar : number density of rand, used to estimate the effective area of a pixel n...
Below is the the instruction that describes the task: ### Input: This function will bootstrap data based on the sky coverage of rand. It is different from bootstrap in the traditional sense, but for correlation functions it gives the correct answer with less computation. nbar : number densi...
def DeleteOldCronJobRuns(self, cutoff_timestamp): """Deletes cron job runs for a given job id.""" deleted = 0 for run in list(itervalues(self.cronjob_runs)): if run.timestamp < cutoff_timestamp: del self.cronjob_runs[(run.cron_job_id, run.run_id)] deleted += 1 return deleted
Deletes cron job runs for a given job id.
Below is the the instruction that describes the task: ### Input: Deletes cron job runs for a given job id. ### Response: def DeleteOldCronJobRuns(self, cutoff_timestamp): """Deletes cron job runs for a given job id.""" deleted = 0 for run in list(itervalues(self.cronjob_runs)): if run.timestamp <...
def get_file(self, hash_list): """ Returns the path of the file - but verifies that the hash is actually present. """ assert len(hash_list) == 1 self._check_hashes(hash_list) return self.object_path(hash_list[0])
Returns the path of the file - but verifies that the hash is actually present.
Below is the the instruction that describes the task: ### Input: Returns the path of the file - but verifies that the hash is actually present. ### Response: def get_file(self, hash_list): """ Returns the path of the file - but verifies that the hash is actually present. """ assert ...
def get_status(self, response, finished=False): """Given the stdout from the command returned by :meth:`cmd_status`, return one of the status code defined in :mod:`clusterjob.status`""" status_pos = 0 for line in response.split("\n"): if line.startswith('JOBID'): ...
Given the stdout from the command returned by :meth:`cmd_status`, return one of the status code defined in :mod:`clusterjob.status`
Below is the the instruction that describes the task: ### Input: Given the stdout from the command returned by :meth:`cmd_status`, return one of the status code defined in :mod:`clusterjob.status` ### Response: def get_status(self, response, finished=False): """Given the stdout from the command ret...
def read_tags(fh, byteorder, offsetsize, tagnames, customtags=None, maxifds=None): """Read tags from chain of IFDs and return as list of dicts. The file handle position must be at a valid IFD header. """ if offsetsize == 4: offsetformat = byteorder+'I' tagnosize = 2 ...
Read tags from chain of IFDs and return as list of dicts. The file handle position must be at a valid IFD header.
Below is the the instruction that describes the task: ### Input: Read tags from chain of IFDs and return as list of dicts. The file handle position must be at a valid IFD header. ### Response: def read_tags(fh, byteorder, offsetsize, tagnames, customtags=None, maxifds=None): """Read tags fro...
def canonicalize_clusters(clusters: DefaultDict[int, List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]: """ The CONLL 2012 data includes 2 annotated spans which are identical, but have different ids. This checks all clusters for spans which are identical, and if it finds any, merges the clusters co...
The CONLL 2012 data includes 2 annotated spans which are identical, but have different ids. This checks all clusters for spans which are identical, and if it finds any, merges the clusters containing the identical spans.
Below is the the instruction that describes the task: ### Input: The CONLL 2012 data includes 2 annotated spans which are identical, but have different ids. This checks all clusters for spans which are identical, and if it finds any, merges the clusters containing the identical spans. ### Response: def...
def Field( dagster_type, default_value=FIELD_NO_DEFAULT_PROVIDED, is_optional=INFER_OPTIONAL_COMPOSITE_FIELD, is_secret=False, description=None, ): ''' The schema for configuration data that describes the type, optionality, defaults, and description. Args: dagster_type (DagsterT...
The schema for configuration data that describes the type, optionality, defaults, and description. Args: dagster_type (DagsterType): A ``DagsterType`` describing the schema of this field, ie `Dict({'example': Field(String)})` default_value (Any): A default value to use that ...
Below is the the instruction that describes the task: ### Input: The schema for configuration data that describes the type, optionality, defaults, and description. Args: dagster_type (DagsterType): A ``DagsterType`` describing the schema of this field, ie `Dict({'example': Field(String)})` ...
def get(self, *keys: str, default: Any = NOT_SET) -> Any: """ Returns values from the settings in the order of keys, the first value encountered is used. Example: >>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2}) >>> settings.get("one") 1 >>> settings.get("one", "...
Returns values from the settings in the order of keys, the first value encountered is used. Example: >>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2}) >>> settings.get("one") 1 >>> settings.get("one", "two") 1 >>> settings.get("two", "one") 2 ...
Below is the the instruction that describes the task: ### Input: Returns values from the settings in the order of keys, the first value encountered is used. Example: >>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2}) >>> settings.get("one") 1 >>> settings.get("one", "t...
def index(self, val, start=None, stop=None): """ Return the smallest *k* such that L[k] == val and i <= k < j`. Raises ValueError if *val* is not present. *stop* defaults to the end of the list. *start* defaults to the beginning. Negative indices are supported, as for slice ind...
Return the smallest *k* such that L[k] == val and i <= k < j`. Raises ValueError if *val* is not present. *stop* defaults to the end of the list. *start* defaults to the beginning. Negative indices are supported, as for slice indices.
Below is the the instruction that describes the task: ### Input: Return the smallest *k* such that L[k] == val and i <= k < j`. Raises ValueError if *val* is not present. *stop* defaults to the end of the list. *start* defaults to the beginning. Negative indices are supported, as for slice...
def handle_line(self, line): """Handle incoming string data one line at a time.""" if not self.gateway.can_log: _LOGGER.debug('Receiving %s', line) self.gateway.add_job(self.gateway.logic, line)
Handle incoming string data one line at a time.
Below is the the instruction that describes the task: ### Input: Handle incoming string data one line at a time. ### Response: def handle_line(self, line): """Handle incoming string data one line at a time.""" if not self.gateway.can_log: _LOGGER.debug('Receiving %s', line) self...
def register(self, x, graph=False): """Register a function as being part of an API, then returns the original function.""" if graph: # This function must comply to the "graph" API interface, meaning it can bahave like bonobo.run. from inspect import signature parame...
Register a function as being part of an API, then returns the original function.
Below is the the instruction that describes the task: ### Input: Register a function as being part of an API, then returns the original function. ### Response: def register(self, x, graph=False): """Register a function as being part of an API, then returns the original function.""" if graph: ...
def _write_to_log(self, s, truncate=False): """Writes the given output to the log file, appending unless `truncate` is True.""" # if truncate is True, set write mode to truncate with open(self._logfile, 'w' if truncate else 'a') as fp: fp.writelines((to_text(s) if six.PY2 else to_tex...
Writes the given output to the log file, appending unless `truncate` is True.
Below is the the instruction that describes the task: ### Input: Writes the given output to the log file, appending unless `truncate` is True. ### Response: def _write_to_log(self, s, truncate=False): """Writes the given output to the log file, appending unless `truncate` is True.""" # if truncate ...
def convert(model, input_features, output_features): """Convert a DictVectorizer model to the protobuf spec. Parameters ---------- model: DictVectorizer A fitted DictVectorizer model. input_features: str Name of the input column. output_features: str Name of the output...
Convert a DictVectorizer model to the protobuf spec. Parameters ---------- model: DictVectorizer A fitted DictVectorizer model. input_features: str Name of the input column. output_features: str Name of the output column. Returns ------- model_spec: An object ...
Below is the the instruction that describes the task: ### Input: Convert a DictVectorizer model to the protobuf spec. Parameters ---------- model: DictVectorizer A fitted DictVectorizer model. input_features: str Name of the input column. output_features: str Name of t...
def prepare_for_build(self): '''Prepare the build. ''' assert(self.target is not None) if hasattr(self.target, '_build_prepared'): return self.info('Preparing build') self.info('Check requirements for {0}'.format(self.targetname)) self.target.check_r...
Prepare the build.
Below is the the instruction that describes the task: ### Input: Prepare the build. ### Response: def prepare_for_build(self): '''Prepare the build. ''' assert(self.target is not None) if hasattr(self.target, '_build_prepared'): return self.info('Preparing build...
def map_across_full_axis(self, axis, map_func): """Applies `map_func` to every partition. Note: This method should be used in the case that `map_func` relies on some global information about the axis. Args: axis: The axis to perform the map across (0 - index, 1 - column...
Applies `map_func` to every partition. Note: This method should be used in the case that `map_func` relies on some global information about the axis. Args: axis: The axis to perform the map across (0 - index, 1 - columns). map_func: The function to apply. R...
Below is the the instruction that describes the task: ### Input: Applies `map_func` to every partition. Note: This method should be used in the case that `map_func` relies on some global information about the axis. Args: axis: The axis to perform the map across (0 - index, ...
def markov_blanket(y, mean, scale, shape, skewness): """ Markov blanket for the Exponential distribution Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the Exponential distribution ...
Markov blanket for the Exponential distribution Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the Exponential distribution scale : float scale parameter for the Exponential dis...
Below is the the instruction that describes the task: ### Input: Markov blanket for the Exponential distribution Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the Exponential distribution ...
def check_recovery(working_dir): """ Do we need to recover on start-up? """ recovery_start_block, recovery_end_block = get_recovery_range(working_dir) if recovery_start_block is not None and recovery_end_block is not None: local_current_block = virtualchain_hooks.get_last_block(working_dir) ...
Do we need to recover on start-up?
Below is the the instruction that describes the task: ### Input: Do we need to recover on start-up? ### Response: def check_recovery(working_dir): """ Do we need to recover on start-up? """ recovery_start_block, recovery_end_block = get_recovery_range(working_dir) if recovery_start_block is not...
def run_out_of_sample_mds(boot_collection, ref_collection, ref_distance_matrix, index, dimensions, task=_fast_geo, rooted=False, **kwargs): """ index = index of the locus the bootstrap sample corresponds to - only important if using recalc=True in kwargs """ fit = np.empty((len(boot_collecti...
index = index of the locus the bootstrap sample corresponds to - only important if using recalc=True in kwargs
Below is the the instruction that describes the task: ### Input: index = index of the locus the bootstrap sample corresponds to - only important if using recalc=True in kwargs ### Response: def run_out_of_sample_mds(boot_collection, ref_collection, ref_distance_matrix, index, dimensions, task=_fast_geo...
def set_patient_medhx_flag(self, patient_id, medhx_status): """ invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :param patient_id :param medhx_status - Field in EEHR expects U, G, or D. SP defaults to Null and erro...
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :param patient_id :param medhx_status - Field in EEHR expects U, G, or D. SP defaults to Null and errors out if included. U=Unknown G=Granted D=Declined :ret...
Below is the the instruction that describes the task: ### Input: invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :param patient_id :param medhx_status - Field in EEHR expects U, G, or D. SP defaults to Null and errors out if included. U=Unkn...
def alias_assessment_taken(self, assessment_taken_id, alias_id): """Adds an ``Id`` to an ``AssessmentTaken`` for the purpose of creating compatibility. The primary ``Id`` of the ``AssessmentTaken`` is determined by the provider. The new ``Id`` is an alias to the primary ``Id``. If the a...
Adds an ``Id`` to an ``AssessmentTaken`` for the purpose of creating compatibility. The primary ``Id`` of the ``AssessmentTaken`` is determined by the provider. The new ``Id`` is an alias to the primary ``Id``. If the alias is a pointer to another assessment taken, it is reassigned to t...
Below is the the instruction that describes the task: ### Input: Adds an ``Id`` to an ``AssessmentTaken`` for the purpose of creating compatibility. The primary ``Id`` of the ``AssessmentTaken`` is determined by the provider. The new ``Id`` is an alias to the primary ``Id``. If the alias is...
def check_state(self, state): """ Check if the specific function is reached with certain arguments :param angr.SimState state: The state to check :return: True if the function is reached with certain arguments, False otherwise. :rtype: bool """ if state.addr == ...
Check if the specific function is reached with certain arguments :param angr.SimState state: The state to check :return: True if the function is reached with certain arguments, False otherwise. :rtype: bool
Below is the the instruction that describes the task: ### Input: Check if the specific function is reached with certain arguments :param angr.SimState state: The state to check :return: True if the function is reached with certain arguments, False otherwise. :rtype: bool ### Response: def ...
def CBO_Gamma(self, **kwargs): ''' Returns the strain-shifted Gamma-valley conduction band offset (CBO), assuming the strain affects all conduction band valleys equally. ''' return (self.unstrained.CBO_Gamma(**kwargs) + self.CBO_strain_shift(**kwargs))
Returns the strain-shifted Gamma-valley conduction band offset (CBO), assuming the strain affects all conduction band valleys equally.
Below is the the instruction that describes the task: ### Input: Returns the strain-shifted Gamma-valley conduction band offset (CBO), assuming the strain affects all conduction band valleys equally. ### Response: def CBO_Gamma(self, **kwargs): ''' Returns the strain-shifted Gamma-valley co...
def get_fieldsets(self, *args, **kwargs): """Re-order fields""" result = super(EventAdmin, self).get_fieldsets(*args, **kwargs) result = list(result) fields = list(result[0][1]['fields']) for name in ('content', 'start', 'end', 'repeat', 'repeat_until', \ 'external_li...
Re-order fields
Below is the the instruction that describes the task: ### Input: Re-order fields ### Response: def get_fieldsets(self, *args, **kwargs): """Re-order fields""" result = super(EventAdmin, self).get_fieldsets(*args, **kwargs) result = list(result) fields = list(result[0][1]['fields']) ...
def UploadAccount(self, hash_algorithm, hash_key, accounts): """Uploads multiple accounts to Gitkit server. Args: hash_algorithm: string, algorithm to hash password. hash_key: string, base64-encoded key of the algorithm. accounts: array of accounts to be uploaded. Returns: Response...
Uploads multiple accounts to Gitkit server. Args: hash_algorithm: string, algorithm to hash password. hash_key: string, base64-encoded key of the algorithm. accounts: array of accounts to be uploaded. Returns: Response of the API.
Below is the the instruction that describes the task: ### Input: Uploads multiple accounts to Gitkit server. Args: hash_algorithm: string, algorithm to hash password. hash_key: string, base64-encoded key of the algorithm. accounts: array of accounts to be uploaded. Returns: Respons...
def from_Composition(composition, width=80): """Convert a mingus.containers.Composition to an ASCII tablature string. Automatically add an header based on the title, subtitle, author, e-mail and description attributes. An extra description of the piece can also be given. Tunings can be set by usin...
Convert a mingus.containers.Composition to an ASCII tablature string. Automatically add an header based on the title, subtitle, author, e-mail and description attributes. An extra description of the piece can also be given. Tunings can be set by using the Track.instrument.tuning or Track.tuning at...
Below is the the instruction that describes the task: ### Input: Convert a mingus.containers.Composition to an ASCII tablature string. Automatically add an header based on the title, subtitle, author, e-mail and description attributes. An extra description of the piece can also be given. Tunings c...
def enumeration(values, converter=str, default=''): """Return an enumeration string based on the given values. The following four examples show the standard output of function |enumeration|: >>> from hydpy.core.objecttools import enumeration >>> enumeration(('text', 3, [])) 'text, 3, and []' ...
Return an enumeration string based on the given values. The following four examples show the standard output of function |enumeration|: >>> from hydpy.core.objecttools import enumeration >>> enumeration(('text', 3, [])) 'text, 3, and []' >>> enumeration(('text', 3)) 'text and 3' >>> en...
Below is the the instruction that describes the task: ### Input: Return an enumeration string based on the given values. The following four examples show the standard output of function |enumeration|: >>> from hydpy.core.objecttools import enumeration >>> enumeration(('text', 3, [])) 'text, 3,...
def map(self, func): """ Process all data with given function. The scheme of function should be x,y -> x,y. """ if self._train_set: self._train_set = map(func, self._train_set) if self._valid_set: self._valid_set = map(func, self._valid_set) ...
Process all data with given function. The scheme of function should be x,y -> x,y.
Below is the the instruction that describes the task: ### Input: Process all data with given function. The scheme of function should be x,y -> x,y. ### Response: def map(self, func): """ Process all data with given function. The scheme of function should be x,y -> x,y. """ ...
def populate_unique_identifiers(self, metamodel): ''' Populate a *metamodel* with class unique identifiers previously encountered from input. ''' for stmt in self.statements: if isinstance(stmt, CreateUniqueStmt): metamodel.define_unique_identifier(stm...
Populate a *metamodel* with class unique identifiers previously encountered from input.
Below is the the instruction that describes the task: ### Input: Populate a *metamodel* with class unique identifiers previously encountered from input. ### Response: def populate_unique_identifiers(self, metamodel): ''' Populate a *metamodel* with class unique identifiers previously ...
def notify_user( self, msg, level="error", rate_limit=None, module_name="", icon=None, title="py3status", ): """ Display notification to user via i3-nagbar or send-notify We also make sure to log anything to keep trace of it. N...
Display notification to user via i3-nagbar or send-notify We also make sure to log anything to keep trace of it. NOTE: Message should end with a '.' for consistency.
Below is the the instruction that describes the task: ### Input: Display notification to user via i3-nagbar or send-notify We also make sure to log anything to keep trace of it. NOTE: Message should end with a '.' for consistency. ### Response: def notify_user( self, msg, l...
def adjustMinimumWidth( self ): """ Updates the minimum width for this menu based on the font metrics \ for its title (if its shown). This method is called automatically \ when the menu is shown. """ if not self.showTitle(): return metrics = ...
Updates the minimum width for this menu based on the font metrics \ for its title (if its shown). This method is called automatically \ when the menu is shown.
Below is the the instruction that describes the task: ### Input: Updates the minimum width for this menu based on the font metrics \ for its title (if its shown). This method is called automatically \ when the menu is shown. ### Response: def adjustMinimumWidth( self ): """ Updates...
def fetch_all_images(self, type=None, private=None): # pylint: disable=redefined-builtin r""" Returns a generator that yields all of the images available to the account :param type: the type of images to fetch: ``"distribution"``, ``"application"``, or all (`None`); ...
r""" Returns a generator that yields all of the images available to the account :param type: the type of images to fetch: ``"distribution"``, ``"application"``, or all (`None`); default: `None` :type type: string or None :param bool private: whether to only return th...
Below is the the instruction that describes the task: ### Input: r""" Returns a generator that yields all of the images available to the account :param type: the type of images to fetch: ``"distribution"``, ``"application"``, or all (`None`); default: `None` :type type: ...
def status(name, sig=None): ''' Return the status for a service via s6, return pid if running CLI Example: .. code-block:: bash salt '*' s6.status <service name> ''' cmd = 's6-svstat {0}'.format(_service_path(name)) out = __salt__['cmd.run_stdout'](cmd) try: pid = re.s...
Return the status for a service via s6, return pid if running CLI Example: .. code-block:: bash salt '*' s6.status <service name>
Below is the the instruction that describes the task: ### Input: Return the status for a service via s6, return pid if running CLI Example: .. code-block:: bash salt '*' s6.status <service name> ### Response: def status(name, sig=None): ''' Return the status for a service via s6, return ...
def _queueMouseButton(self, coord, mouseButton, modFlags, clickCount=1, dest_coord=None): """Private method to handle generic mouse button clicking. Parameters: coord (x, y) to click, mouseButton (e.g., kCGMouseButtonLeft), modFlags set (int) Option...
Private method to handle generic mouse button clicking. Parameters: coord (x, y) to click, mouseButton (e.g., kCGMouseButtonLeft), modFlags set (int) Optional: clickCount (default 1; set to 2 for double-click; 3 for triple-click on host) Returns: None
Below is the the instruction that describes the task: ### Input: Private method to handle generic mouse button clicking. Parameters: coord (x, y) to click, mouseButton (e.g., kCGMouseButtonLeft), modFlags set (int) Optional: clickCount (default 1; set to 2 for double-click; 3 fo...
def stableSlugId(): """Returns a closure which can be used to generate stable slugIds. Stable slugIds can be used in a graph to specify task IDs in multiple places without regenerating them, e.g. taskId, requires, etc. """ _cache = {} def closure(name): if name not in _cache: ...
Returns a closure which can be used to generate stable slugIds. Stable slugIds can be used in a graph to specify task IDs in multiple places without regenerating them, e.g. taskId, requires, etc.
Below is the the instruction that describes the task: ### Input: Returns a closure which can be used to generate stable slugIds. Stable slugIds can be used in a graph to specify task IDs in multiple places without regenerating them, e.g. taskId, requires, etc. ### Response: def stableSlugId(): """Retur...
def calc_support(self, items): """ Returns a support for items. Arguments: items -- Items as an iterable object (eg. ['A', 'B']). """ # Empty items is supported by all transactions. if not items: return 1.0 # Empty transactions supports n...
Returns a support for items. Arguments: items -- Items as an iterable object (eg. ['A', 'B']).
Below is the the instruction that describes the task: ### Input: Returns a support for items. Arguments: items -- Items as an iterable object (eg. ['A', 'B']). ### Response: def calc_support(self, items): """ Returns a support for items. Arguments: items --...
def delete_collection_namespaced_stateful_set(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_stateful_set # noqa: E501 delete collection of StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request...
delete_collection_namespaced_stateful_set # noqa: E501 delete collection of StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_stateful_set(nam...
Below is the the instruction that describes the task: ### Input: delete_collection_namespaced_stateful_set # noqa: E501 delete collection of StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
def to_8bit(self): """ Convert to 8-bit color :return: Color8Bit instance """ h, s, v = colorsys.rgb_to_hsv(*self.scale(1)) # Check if the color is a shade of grey if s * v < 0.3: if v < 0.3: return Color8Bit(Color8Bit.BLACK, False) ...
Convert to 8-bit color :return: Color8Bit instance
Below is the the instruction that describes the task: ### Input: Convert to 8-bit color :return: Color8Bit instance ### Response: def to_8bit(self): """ Convert to 8-bit color :return: Color8Bit instance """ h, s, v = colorsys.rgb_to_hsv(*self.scale(1)) # Che...
def find_existing_record(env, zone_id, dns_name, check_key=None, check_value=None): """Check if a specific DNS record exists. Args: env (str): Deployment environment. zone_id (str): Route53 zone id. dns_name (str): FQDN of application's dns entry to add/update. check_key(str): K...
Check if a specific DNS record exists. Args: env (str): Deployment environment. zone_id (str): Route53 zone id. dns_name (str): FQDN of application's dns entry to add/update. check_key(str): Key to look for in record. Example: "Type" check_value(str): Value to look for with ...
Below is the the instruction that describes the task: ### Input: Check if a specific DNS record exists. Args: env (str): Deployment environment. zone_id (str): Route53 zone id. dns_name (str): FQDN of application's dns entry to add/update. check_key(str): Key to look for in reco...
def add_section(self, ino, sector_count, load_seg, media_name, system_type, efi, bootable): # type: (inode.Inode, int, int, str, int, bool, bool) -> None ''' A method to add an section header and entry to this Boot Catalog. Parameters: ino - The Inode object...
A method to add an section header and entry to this Boot Catalog. Parameters: ino - The Inode object to associate with the new Entry. sector_count - The number of sectors to assign to the new Entry. load_seg - The load segment address of the boot image. media_name - The name...
Below is the the instruction that describes the task: ### Input: A method to add an section header and entry to this Boot Catalog. Parameters: ino - The Inode object to associate with the new Entry. sector_count - The number of sectors to assign to the new Entry. load_seg - The l...
def rel_humid_from_db_wb(db_temp, wet_bulb, b_press=101325): """Relative Humidity (%) at db_temp(C), wet_bulb (C), and Pressure b_press (Pa). """ # Calculate saturation pressure. p_ws = saturated_vapor_pressure(db_temp + 273.15) p_ws_wb = saturated_vapor_pressure(wet_bulb + 273.15) # calculate p...
Relative Humidity (%) at db_temp(C), wet_bulb (C), and Pressure b_press (Pa).
Below is the the instruction that describes the task: ### Input: Relative Humidity (%) at db_temp(C), wet_bulb (C), and Pressure b_press (Pa). ### Response: def rel_humid_from_db_wb(db_temp, wet_bulb, b_press=101325): """Relative Humidity (%) at db_temp(C), wet_bulb (C), and Pressure b_press (Pa). """ ...
def a_alpha_and_derivatives(self, T, full=True, quick=True): r'''Method to calculate `a_alpha` and its first and second derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Uses the set values of `T...
r'''Method to calculate `a_alpha` and its first and second derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Uses the set values of `Tc`, `omega`, and `a`. Because of its similarity for ...
Below is the the instruction that describes the task: ### Input: r'''Method to calculate `a_alpha` and its first and second derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Uses the set values of `T...
def showinfo(self): ''' 總覽顯示 ''' print 'money:',self.money print 'store:',self.store print 'avgprice:',self.avgprice
總覽顯示
Below is the the instruction that describes the task: ### Input: 總覽顯示 ### Response: def showinfo(self): ''' 總覽顯示 ''' print 'money:',self.money print 'store:',self.store print 'avgprice:',self.avgprice
def open_process(cls, cmd, **kwargs): """Opens a process object via subprocess.Popen(). :param string|list cmd: A list or string representing the command to run. :param **kwargs: Additional kwargs to pass through to subprocess.Popen. :return: A `subprocess.Popen` object. :raises: `Executor.Executab...
Opens a process object via subprocess.Popen(). :param string|list cmd: A list or string representing the command to run. :param **kwargs: Additional kwargs to pass through to subprocess.Popen. :return: A `subprocess.Popen` object. :raises: `Executor.ExecutableNotFound` when the executable requested to ...
Below is the the instruction that describes the task: ### Input: Opens a process object via subprocess.Popen(). :param string|list cmd: A list or string representing the command to run. :param **kwargs: Additional kwargs to pass through to subprocess.Popen. :return: A `subprocess.Popen` object. :ra...
def checkpath(path_, verbose=VERYVERBOSE, n=None, info=VERYVERBOSE): r""" verbose wrapper around ``os.path.exists`` Returns: true if ``path_`` exists on the filesystem show only the top `n` directories Args: path_ (str): path string verbose (bool): verbosity flag(default = ...
r""" verbose wrapper around ``os.path.exists`` Returns: true if ``path_`` exists on the filesystem show only the top `n` directories Args: path_ (str): path string verbose (bool): verbosity flag(default = False) n (int): (default = None) info (bool): (default =...
Below is the the instruction that describes the task: ### Input: r""" verbose wrapper around ``os.path.exists`` Returns: true if ``path_`` exists on the filesystem show only the top `n` directories Args: path_ (str): path string verbose (bool): verbosity flag(default = Fals...
def dropna(df, nonnull_rows=100, nonnull_cols=50, nanstrs=('nan', 'NaN', ''), nullstr=''): """Drop columns/rows with too many NaNs and replace NaNs in columns of strings with '' >>> df = pd.DataFrame([['nan',np.nan,'str'],[np.nan,0.1,'and'],[2.0,None,np.nan]]) >>> dropna(df) Empty DataFrame Columns...
Drop columns/rows with too many NaNs and replace NaNs in columns of strings with '' >>> df = pd.DataFrame([['nan',np.nan,'str'],[np.nan,0.1,'and'],[2.0,None,np.nan]]) >>> dropna(df) Empty DataFrame Columns: [] Index: [] >>> dropna(df, nonnull_cols=0, nonnull_rows=0) 0 1 2 0 ...
Below is the the instruction that describes the task: ### Input: Drop columns/rows with too many NaNs and replace NaNs in columns of strings with '' >>> df = pd.DataFrame([['nan',np.nan,'str'],[np.nan,0.1,'and'],[2.0,None,np.nan]]) >>> dropna(df) Empty DataFrame Columns: [] Index: [] >>> dr...
def add_text(orig, dc, img, text=None): """Add text to an image using the pydecorate package. All the features of pydecorate's ``add_text`` are available. See documentation of :doc:`pydecorate:index` for more info. """ LOG.info("Add text to image.") dc.add_text(**text) arr = da.from_arra...
Add text to an image using the pydecorate package. All the features of pydecorate's ``add_text`` are available. See documentation of :doc:`pydecorate:index` for more info.
Below is the the instruction that describes the task: ### Input: Add text to an image using the pydecorate package. All the features of pydecorate's ``add_text`` are available. See documentation of :doc:`pydecorate:index` for more info. ### Response: def add_text(orig, dc, img, text=None): """Add text...