code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _drop_axis(self, labels, axis, level=None, errors='raise'): """ Drop labels from specified axis. Used in the ``drop`` method internally. Parameters ---------- labels : single label or list-like axis : int or axis name level : int or level name, defaul...
Drop labels from specified axis. Used in the ``drop`` method internally. Parameters ---------- labels : single label or list-like axis : int or axis name level : int or level name, default None For MultiIndex errors : {'ignore', 'raise'}, default 'rai...
Below is the the instruction that describes the task: ### Input: Drop labels from specified axis. Used in the ``drop`` method internally. Parameters ---------- labels : single label or list-like axis : int or axis name level : int or level name, default None ...
def read_file(filename): """Read package file as text to get name and version""" # intentionally *not* adding an encoding option to open # see here: # https://github.com/pypa/virtualenv/issues/201#issuecomment-3145690 here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.joi...
Read package file as text to get name and version
Below is the the instruction that describes the task: ### Input: Read package file as text to get name and version ### Response: def read_file(filename): """Read package file as text to get name and version""" # intentionally *not* adding an encoding option to open # see here: # https://github.com/...
def validate(cls, mapper_spec): """Validates mapper spec and all mapper parameters. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid. """ if mapper_spec.input_reader_class() != cls: raise BadReaderPar...
Validates mapper spec and all mapper parameters. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid.
Below is the the instruction that describes the task: ### Input: Validates mapper spec and all mapper parameters. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid. ### Response: def validate(cls, mapper_spec): ...
def _add_zone(self, zone, name='', status=Zone.CLEAR, expander=False): """ Adds a zone to the internal zone list. :param zone: zone number :type zone: int :param name: human readable zone name :type name: string :param status: zone status :type status: in...
Adds a zone to the internal zone list. :param zone: zone number :type zone: int :param name: human readable zone name :type name: string :param status: zone status :type status: int
Below is the the instruction that describes the task: ### Input: Adds a zone to the internal zone list. :param zone: zone number :type zone: int :param name: human readable zone name :type name: string :param status: zone status :type status: int ### Response: def _...
def group_by_match(self, variant): ''' Given a variant, split the PileupCollection based on whether it the data supports the reference allele, the alternate allele, or neither. Parameters ---------- variant : Variant The variant. Must have fields 'locus', 're...
Given a variant, split the PileupCollection based on whether it the data supports the reference allele, the alternate allele, or neither. Parameters ---------- variant : Variant The variant. Must have fields 'locus', 'ref', and 'alt'. Returns ---------- ...
Below is the the instruction that describes the task: ### Input: Given a variant, split the PileupCollection based on whether it the data supports the reference allele, the alternate allele, or neither. Parameters ---------- variant : Variant The variant. Must have field...
def dec_decimal_to_sexegesimal( self, dec, delimiter=":"): """ *Convert a declination between decimal degrees and sexegesimal.* Precision should be respected. **Key Arguments:** - ``dec`` -- DEC in decimal degrees. Will try and convert to...
*Convert a declination between decimal degrees and sexegesimal.* Precision should be respected. **Key Arguments:** - ``dec`` -- DEC in decimal degrees. Will try and convert to float before performing calculation. - ``delimiter`` -- how to delimit the RA units. Default *:* ...
Below is the the instruction that describes the task: ### Input: *Convert a declination between decimal degrees and sexegesimal.* Precision should be respected. **Key Arguments:** - ``dec`` -- DEC in decimal degrees. Will try and convert to float before performing calculation. ...
def penalize_boundary_complexity(shp, w=20, mask=None, C=0.5): """Encourage the boundaries of an image to have less variation and of color C. Args: shp: shape of T("input") because this may not be known. w: width of boundary to penalize. Ignored if mask is set. mask: mask describing what area should be...
Encourage the boundaries of an image to have less variation and of color C. Args: shp: shape of T("input") because this may not be known. w: width of boundary to penalize. Ignored if mask is set. mask: mask describing what area should be penalized. Returns: Objective.
Below is the the instruction that describes the task: ### Input: Encourage the boundaries of an image to have less variation and of color C. Args: shp: shape of T("input") because this may not be known. w: width of boundary to penalize. Ignored if mask is set. mask: mask describing what area should b...
def _calc_sizes(self, cnv_file, items): """Retrieve target and antitarget bin sizes based on depth. Similar to CNVkit's do_autobin but tries to have a standard set of ranges (50bp intervals for target and 10kb intervals for antitarget). """ bp_per_bin = 100000 # same target as ...
Retrieve target and antitarget bin sizes based on depth. Similar to CNVkit's do_autobin but tries to have a standard set of ranges (50bp intervals for target and 10kb intervals for antitarget).
Below is the the instruction that describes the task: ### Input: Retrieve target and antitarget bin sizes based on depth. Similar to CNVkit's do_autobin but tries to have a standard set of ranges (50bp intervals for target and 10kb intervals for antitarget). ### Response: def _calc_sizes(self, cnv...
def to_timestamp(val): """ Takes a value that is either a Python date, datetime, or a string representation of a date/datetime value. Returns a standard Unix timestamp corresponding to that value. """ # If we're given a number, give it right back - it's already a timestamp. if isinstance(val...
Takes a value that is either a Python date, datetime, or a string representation of a date/datetime value. Returns a standard Unix timestamp corresponding to that value.
Below is the the instruction that describes the task: ### Input: Takes a value that is either a Python date, datetime, or a string representation of a date/datetime value. Returns a standard Unix timestamp corresponding to that value. ### Response: def to_timestamp(val): """ Takes a value that is e...
def setValues(nxG, nyG, iBeg, iEnd, jBeg, jEnd, data): """ Set setValues @param nxG number of global cells in x @param nyG number of global cells in y @param iBeg global starting index in x @param iEnd global ending index in x @param jBeg global starting index in y @param jEnd global end...
Set setValues @param nxG number of global cells in x @param nyG number of global cells in y @param iBeg global starting index in x @param iEnd global ending index in x @param jBeg global starting index in y @param jEnd global ending index in y @param data local array
Below is the the instruction that describes the task: ### Input: Set setValues @param nxG number of global cells in x @param nyG number of global cells in y @param iBeg global starting index in x @param iEnd global ending index in x @param jBeg global starting index in y @param jEnd global e...
def deconstruct(self, including_private: bool=False) -> bytes: """Return state of this FinTSClient instance as an opaque datablob. You should not use this object after calling this method. Information about the connection is implicitly retrieved from the bank and cached in the FinTSClie...
Return state of this FinTSClient instance as an opaque datablob. You should not use this object after calling this method. Information about the connection is implicitly retrieved from the bank and cached in the FinTSClient. This includes: system identifier, bank parameter data, user pa...
Below is the the instruction that describes the task: ### Input: Return state of this FinTSClient instance as an opaque datablob. You should not use this object after calling this method. Information about the connection is implicitly retrieved from the bank and cached in the FinTSClient. T...
def metric_delete(self, project, metric_name): """API call: delete a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric """ path = "projects/%s/metrics/%...
API call: delete a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric
Below is the the instruction that describes the task: ### Input: API call: delete a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric ### Response: def metric_delete(self,...
def export_default_probes(path, module_name = '', raise_errors = False): """ NOT IMPLEMENTED YET tries to instantiate all the instruments that are imported in /instruments/__init__.py and the probes of each instrument that could be instantiated into a .b26 file in the folder path Args: path:...
NOT IMPLEMENTED YET tries to instantiate all the instruments that are imported in /instruments/__init__.py and the probes of each instrument that could be instantiated into a .b26 file in the folder path Args: path: target path for .b26 files
Below is the the instruction that describes the task: ### Input: NOT IMPLEMENTED YET tries to instantiate all the instruments that are imported in /instruments/__init__.py and the probes of each instrument that could be instantiated into a .b26 file in the folder path Args: path: target path for...
def init_parsecmdline(argv=[]): """ Parse arguments from the command line :param argv: list of arguments """ # main argument parser parser = argparse.ArgumentParser(prog=PKG_NAME) # --version parser.add_argument('--version', action='version', version=version) # -c, --config <file_...
Parse arguments from the command line :param argv: list of arguments
Below is the the instruction that describes the task: ### Input: Parse arguments from the command line :param argv: list of arguments ### Response: def init_parsecmdline(argv=[]): """ Parse arguments from the command line :param argv: list of arguments """ # main argument parser parse...
def comment_magic(source, language='python', global_escape_flag=True): """Escape Jupyter magics with '# '""" parser = StringParser(language) next_is_magic = False for pos, line in enumerate(source): if not parser.is_quoted() and (next_is_magic or is_magic(line, language, global_escape_flag)): ...
Escape Jupyter magics with '#
Below is the the instruction that describes the task: ### Input: Escape Jupyter magics with '# ### Response: def comment_magic(source, language='python', global_escape_flag=True): """Escape Jupyter magics with '# '""" parser = StringParser(language) next_is_magic = False for pos, line in enumerate(...
def put(self, items, indexes=True): '''Adds feature collections to the store. This efficiently adds multiple FCs to the store. The iterable of ``items`` given should yield tuples of ``(content_id, FC)``. :param items: Iterable of ``(content_id, FC)``. :param [str] feature_names...
Adds feature collections to the store. This efficiently adds multiple FCs to the store. The iterable of ``items`` given should yield tuples of ``(content_id, FC)``. :param items: Iterable of ``(content_id, FC)``. :param [str] feature_names: A list of feature names to retrieve...
Below is the the instruction that describes the task: ### Input: Adds feature collections to the store. This efficiently adds multiple FCs to the store. The iterable of ``items`` given should yield tuples of ``(content_id, FC)``. :param items: Iterable of ``(content_id, FC)``. :par...
def _build_connection_args(self, klass): """Read connection args spec, exclude self from list of possible :param klass: Redis connection class. """ bases = [base for base in klass.__bases__ if base is not object] all_args = [] for cls in [klass] + bases: try:...
Read connection args spec, exclude self from list of possible :param klass: Redis connection class.
Below is the the instruction that describes the task: ### Input: Read connection args spec, exclude self from list of possible :param klass: Redis connection class. ### Response: def _build_connection_args(self, klass): """Read connection args spec, exclude self from list of possible :par...
def set_target_temperature(self, temperature, mode=config.SCHEDULE_HOLD): """ Updates the target temperature on the NuHeat API :param temperature: The desired temperature in NuHeat format :param permanent: Permanently hold the temperature. If set to False, the schedule will ...
Updates the target temperature on the NuHeat API :param temperature: The desired temperature in NuHeat format :param permanent: Permanently hold the temperature. If set to False, the schedule will resume at the next programmed event
Below is the the instruction that describes the task: ### Input: Updates the target temperature on the NuHeat API :param temperature: The desired temperature in NuHeat format :param permanent: Permanently hold the temperature. If set to False, the schedule will resume at t...
def surface_evaluate_cartesian_multi(surface, points): """Image for :meth`.Surface.evaluate_cartesian_multi` docstring.""" if NO_IMAGES: return ax = surface.plot(256) ax.plot( points[0, :], points[1, :], color="black", linestyle="None", marker="o" ) delta = 1.0 / 32.0 font_s...
Image for :meth`.Surface.evaluate_cartesian_multi` docstring.
Below is the the instruction that describes the task: ### Input: Image for :meth`.Surface.evaluate_cartesian_multi` docstring. ### Response: def surface_evaluate_cartesian_multi(surface, points): """Image for :meth`.Surface.evaluate_cartesian_multi` docstring.""" if NO_IMAGES: return ax = surf...
def _row_should_be_placed(self, row, position): """:return: whether to place this instruction""" placed_row = self._rows_in_grid.get(row) return placed_row is None or placed_row.y < position.y
:return: whether to place this instruction
Below is the the instruction that describes the task: ### Input: :return: whether to place this instruction ### Response: def _row_should_be_placed(self, row, position): """:return: whether to place this instruction""" placed_row = self._rows_in_grid.get(row) return placed_row is None or pl...
def correlation(P, obs1, obs2=None, times=[1], k=None): r"""Time-correlation for equilibrium experiment. Parameters ---------- P : (M, M) ndarray Transition matrix obs1 : (M,) ndarray Observable, represented as vector on state space obs2 : (M,) ndarray (optional) Second ...
r"""Time-correlation for equilibrium experiment. Parameters ---------- P : (M, M) ndarray Transition matrix obs1 : (M,) ndarray Observable, represented as vector on state space obs2 : (M,) ndarray (optional) Second observable, for cross-correlations times : list of int (...
Below is the the instruction that describes the task: ### Input: r"""Time-correlation for equilibrium experiment. Parameters ---------- P : (M, M) ndarray Transition matrix obs1 : (M,) ndarray Observable, represented as vector on state space obs2 : (M,) ndarray (optional) ...
def query(self): """ Builds the query for this quick filter. :return <orb.Query> """ output = Query() for column, op, plugin, editor in self._plugins: query = Query(column) if plugin.setupQuery(query, op, editor): ...
Builds the query for this quick filter. :return <orb.Query>
Below is the the instruction that describes the task: ### Input: Builds the query for this quick filter. :return <orb.Query> ### Response: def query(self): """ Builds the query for this quick filter. :return <orb.Query> """ output = ...
def discover(): """ Import all experiments listed in *_PLUGINS_REPORTS. Tests: >>> from benchbuild.settings import CFG >>> from benchbuild.reports import discover >>> import logging as lg >>> import sys >>> l = lg.getLogger('benchbuild') >>> l.setLevel(lg.DEB...
Import all experiments listed in *_PLUGINS_REPORTS. Tests: >>> from benchbuild.settings import CFG >>> from benchbuild.reports import discover >>> import logging as lg >>> import sys >>> l = lg.getLogger('benchbuild') >>> l.setLevel(lg.DEBUG) >>> l.handlers =...
Below is the the instruction that describes the task: ### Input: Import all experiments listed in *_PLUGINS_REPORTS. Tests: >>> from benchbuild.settings import CFG >>> from benchbuild.reports import discover >>> import logging as lg >>> import sys >>> l = lg.getLogger('b...
def remove_known_hosts(overcloud_ip): """For a given IP address remove SSH keys from the known_hosts file""" known_hosts = os.path.expanduser("~/.ssh/known_hosts") if os.path.exists(known_hosts): command = ['ssh-keygen', '-R', overcloud_ip, '-f', known_hosts] subprocess.check_call(command)
For a given IP address remove SSH keys from the known_hosts file
Below is the the instruction that describes the task: ### Input: For a given IP address remove SSH keys from the known_hosts file ### Response: def remove_known_hosts(overcloud_ip): """For a given IP address remove SSH keys from the known_hosts file""" known_hosts = os.path.expanduser("~/.ssh/known_hosts"...
def haslayer(self, cls): """Specific: NTPHeader().haslayer(NTP) should return True.""" if cls == "NTP": if isinstance(self, NTP): return True elif issubtype(cls, NTP): if isinstance(self, cls): return True return super(NTP, self).ha...
Specific: NTPHeader().haslayer(NTP) should return True.
Below is the the instruction that describes the task: ### Input: Specific: NTPHeader().haslayer(NTP) should return True. ### Response: def haslayer(self, cls): """Specific: NTPHeader().haslayer(NTP) should return True.""" if cls == "NTP": if isinstance(self, NTP): return...
def request_permission(cls, permissions): """ Requests permission and returns an future result that returns a boolean indicating if all the given permission were granted or denied. """ app = AndroidApplication.instance() f = app.create_future() def on_result(p...
Requests permission and returns an future result that returns a boolean indicating if all the given permission were granted or denied.
Below is the the instruction that describes the task: ### Input: Requests permission and returns an future result that returns a boolean indicating if all the given permission were granted or denied. ### Response: def request_permission(cls, permissions): """ Requests permission and returns an fut...
def find(self, name): """ Return a list of subset of VM that match the pattern name @param name (str): the vm name of the virtual machine @param name (Obj): the vm object that represent the virtual machine (can be Pro or Smart) @return (list): the subse...
Return a list of subset of VM that match the pattern name @param name (str): the vm name of the virtual machine @param name (Obj): the vm object that represent the virtual machine (can be Pro or Smart) @return (list): the subset containing the serach result.
Below is the the instruction that describes the task: ### Input: Return a list of subset of VM that match the pattern name @param name (str): the vm name of the virtual machine @param name (Obj): the vm object that represent the virtual machine (can be Pro or Smart) ...
def body_lines(self): """ Return a normalized list of lines from message's body. """ if not self.message.is_multipart(): body = self.message.get_payload(None, decode=True) else: _, _, body = self.message.as_string().partition("\n\n") if isinstance(body, bytes): ...
Return a normalized list of lines from message's body.
Below is the the instruction that describes the task: ### Input: Return a normalized list of lines from message's body. ### Response: def body_lines(self): """ Return a normalized list of lines from message's body. """ if not self.message.is_multipart(): body = self.message.get_payload(...
def setup_http_session(): """Sets the global HTTP settings, such as proxy and headers.""" if args.http_proxy: streamlink.set_option("http-proxy", args.http_proxy) if args.https_proxy: streamlink.set_option("https-proxy", args.https_proxy) if args.http_cookie: streamlink.set_opt...
Sets the global HTTP settings, such as proxy and headers.
Below is the the instruction that describes the task: ### Input: Sets the global HTTP settings, such as proxy and headers. ### Response: def setup_http_session(): """Sets the global HTTP settings, such as proxy and headers.""" if args.http_proxy: streamlink.set_option("http-proxy", args.http_proxy)...
def send_email(sender, receivers, subject, text=None, html=None, charset='utf-8', config=Injected): """Sends an email. :param sender: Sender as string or None for default got from config. :param receivers: String or array of recipients. :param subject: Subject. :param text: Plain text message. ...
Sends an email. :param sender: Sender as string or None for default got from config. :param receivers: String or array of recipients. :param subject: Subject. :param text: Plain text message. :param html: Html message. :param charset: Charset. :param config: Current configuration
Below is the the instruction that describes the task: ### Input: Sends an email. :param sender: Sender as string or None for default got from config. :param receivers: String or array of recipients. :param subject: Subject. :param text: Plain text message. :param html: Html message. :param ...
def fromISO8601TimeAndDate(klass, iso8601string, tzinfo=None): """Return a new Time instance from a string formated as in ISO 8601. If the given string contains no timezone, it is assumed to be in the timezone specified by the parameter `tzinfo`, or UTC if tzinfo is None. An input strin...
Return a new Time instance from a string formated as in ISO 8601. If the given string contains no timezone, it is assumed to be in the timezone specified by the parameter `tzinfo`, or UTC if tzinfo is None. An input string with an explicit timezone will always override tzinfo. If the g...
Below is the the instruction that describes the task: ### Input: Return a new Time instance from a string formated as in ISO 8601. If the given string contains no timezone, it is assumed to be in the timezone specified by the parameter `tzinfo`, or UTC if tzinfo is None. An input string wit...
def _read_tags_for_revset(self, spec): """ Return TaggedRevision for each tag/rev combination in the revset spec """ cmd = [ 'log', '--style', 'default', '--config', 'defaults.log=', '-r', spec] res = self._invoke(*cmd) header_pattern = re.compile(r'(?P<header>\w+?):\s+(?P<value>.*)') match_res = ma...
Return TaggedRevision for each tag/rev combination in the revset spec
Below is the the instruction that describes the task: ### Input: Return TaggedRevision for each tag/rev combination in the revset spec ### Response: def _read_tags_for_revset(self, spec): """ Return TaggedRevision for each tag/rev combination in the revset spec """ cmd = [ 'log', '--style', 'default', '...
def _plaintext_data_key(): ''' Return the configured KMS data key decrypted and encoded in urlsafe base64. Cache the result to minimize API calls to AWS. ''' response = getattr(_plaintext_data_key, 'response', None) cache_hit = response is not None if not cache_hit: response = _api_...
Return the configured KMS data key decrypted and encoded in urlsafe base64. Cache the result to minimize API calls to AWS.
Below is the the instruction that describes the task: ### Input: Return the configured KMS data key decrypted and encoded in urlsafe base64. Cache the result to minimize API calls to AWS. ### Response: def _plaintext_data_key(): ''' Return the configured KMS data key decrypted and encoded in urlsafe b...
def apply_cut(self, cut): """Return a cut version of this |Subsystem|. Args: cut (Cut): The cut to apply to this |Subsystem|. Returns: Subsystem: The cut subsystem. """ return Subsystem(self.network, self.state, self.node_indices, ...
Return a cut version of this |Subsystem|. Args: cut (Cut): The cut to apply to this |Subsystem|. Returns: Subsystem: The cut subsystem.
Below is the the instruction that describes the task: ### Input: Return a cut version of this |Subsystem|. Args: cut (Cut): The cut to apply to this |Subsystem|. Returns: Subsystem: The cut subsystem. ### Response: def apply_cut(self, cut): """Return a cut version ...
def new_event(event): """ Wrap a raw gRPC event in a friendlier containing class. This picks the appropriate class from one of PutEvent or DeleteEvent and returns a new instance. """ op_name = event.EventType.DESCRIPTOR.values_by_number[event.type].name if op_name == 'PUT': cls = Pu...
Wrap a raw gRPC event in a friendlier containing class. This picks the appropriate class from one of PutEvent or DeleteEvent and returns a new instance.
Below is the the instruction that describes the task: ### Input: Wrap a raw gRPC event in a friendlier containing class. This picks the appropriate class from one of PutEvent or DeleteEvent and returns a new instance. ### Response: def new_event(event): """ Wrap a raw gRPC event in a friendlier co...
def _codes_to_ints(self, codes): """ Transform combination(s) of uint64 in one uint64 (each), in a strictly monotonic way (i.e. respecting the lexicographic order of integer combinations): see BaseMultiIndexCodesEngine documentation. Parameters ---------- codes :...
Transform combination(s) of uint64 in one uint64 (each), in a strictly monotonic way (i.e. respecting the lexicographic order of integer combinations): see BaseMultiIndexCodesEngine documentation. Parameters ---------- codes : 1- or 2-dimensional array of dtype uint64 ...
Below is the the instruction that describes the task: ### Input: Transform combination(s) of uint64 in one uint64 (each), in a strictly monotonic way (i.e. respecting the lexicographic order of integer combinations): see BaseMultiIndexCodesEngine documentation. Parameters ----------...
def copy_meta_from(self, ido): """Copies vtki meta data onto this object from another object""" self._active_scalar_info = ido.active_scalar_info self._active_vectors_info = ido.active_vectors_info if hasattr(ido, '_textures'): self._textures = ido._textures
Copies vtki meta data onto this object from another object
Below is the the instruction that describes the task: ### Input: Copies vtki meta data onto this object from another object ### Response: def copy_meta_from(self, ido): """Copies vtki meta data onto this object from another object""" self._active_scalar_info = ido.active_scalar_info self._a...
def GetResourceIdOrFullNameFromLink(resource_link): """Gets resource id or full name from resource link. :param str resource_link: :return: The resource id or full name from the resource link. :rtype: str """ # For named based, the resource link is the full name if IsNameBased(reso...
Gets resource id or full name from resource link. :param str resource_link: :return: The resource id or full name from the resource link. :rtype: str
Below is the the instruction that describes the task: ### Input: Gets resource id or full name from resource link. :param str resource_link: :return: The resource id or full name from the resource link. :rtype: str ### Response: def GetResourceIdOrFullNameFromLink(resource_link): """Gets ...
def set_end(self,time,pass_to_command_line=True): """ Set the GPS end time of the analysis node by setting a --gps-end-time option to the node when it is executed. @param time: GPS end time of job. @bool pass_to_command_line: add gps-end-time as variable option. """ if pass_to_command_line: ...
Set the GPS end time of the analysis node by setting a --gps-end-time option to the node when it is executed. @param time: GPS end time of job. @bool pass_to_command_line: add gps-end-time as variable option.
Below is the the instruction that describes the task: ### Input: Set the GPS end time of the analysis node by setting a --gps-end-time option to the node when it is executed. @param time: GPS end time of job. @bool pass_to_command_line: add gps-end-time as variable option. ### Response: def set_end(sel...
def create_input(option, template_name, template_location="template"): '''create an input file using jinja2 by filling a template with the values from the option variable passed in.''' # restructure option list into jinja2 input format jinja2_input = {} for item in option: try: ...
create an input file using jinja2 by filling a template with the values from the option variable passed in.
Below is the the instruction that describes the task: ### Input: create an input file using jinja2 by filling a template with the values from the option variable passed in. ### Response: def create_input(option, template_name, template_location="template"): '''create an input file using jinja2 by filling ...
def _cutout_expnum(observation, sky_coord, radius): """ Get a cutout from an exposure based on the RA/DEC location. @param observation: The Observation object that contains the expusre number information. @type observation: Observation @param sky_coord: which RA/DEC is needed, @type sky_coord: ...
Get a cutout from an exposure based on the RA/DEC location. @param observation: The Observation object that contains the expusre number information. @type observation: Observation @param sky_coord: which RA/DEC is needed, @type sky_coord: SkyCoord @param radius: @type radius: Quantity @retu...
Below is the the instruction that describes the task: ### Input: Get a cutout from an exposure based on the RA/DEC location. @param observation: The Observation object that contains the expusre number information. @type observation: Observation @param sky_coord: which RA/DEC is needed, @type sky_coo...
def __get_keys(self, name='master', passphrase=None): ''' Returns a key object for a key in the pki-dir ''' path = os.path.join(self.opts['pki_dir'], name + '.pem') if not os.path.exists(path): log.info('Generating %s keys: %s', name, self....
Returns a key object for a key in the pki-dir
Below is the the instruction that describes the task: ### Input: Returns a key object for a key in the pki-dir ### Response: def __get_keys(self, name='master', passphrase=None): ''' Returns a key object for a key in the pki-dir ''' path = os.path.join(self.opts['pki_dir'], ...
def almost_hermitian(gate: Gate) -> bool: """Return true if gate tensor is (almost) Hermitian""" return np.allclose(asarray(gate.asoperator()), asarray(gate.H.asoperator()))
Return true if gate tensor is (almost) Hermitian
Below is the the instruction that describes the task: ### Input: Return true if gate tensor is (almost) Hermitian ### Response: def almost_hermitian(gate: Gate) -> bool: """Return true if gate tensor is (almost) Hermitian""" return np.allclose(asarray(gate.asoperator()), asarray(gate...
def cupy_wrapper(func): """A wrapper function that converts numpy ndarray arguments to cupy arrays, and convert any cupy arrays returned by the wrapped function into numpy ndarrays. """ @functools.wraps(func) def wrapped(*args, **kwargs): args = list(args) for n, a in enumerate(...
A wrapper function that converts numpy ndarray arguments to cupy arrays, and convert any cupy arrays returned by the wrapped function into numpy ndarrays.
Below is the the instruction that describes the task: ### Input: A wrapper function that converts numpy ndarray arguments to cupy arrays, and convert any cupy arrays returned by the wrapped function into numpy ndarrays. ### Response: def cupy_wrapper(func): """A wrapper function that converts numpy nda...
def setall(self, key, values): """Set more than one value for a given key. Replaces all the existing values for the given key with new values, removes extra values that are already set if we don't suply enough, and appends values to the end if there are not enough existing spots...
Set more than one value for a given key. Replaces all the existing values for the given key with new values, removes extra values that are already set if we don't suply enough, and appends values to the end if there are not enough existing spots. >>> m = MutableMultiMap...
Below is the the instruction that describes the task: ### Input: Set more than one value for a given key. Replaces all the existing values for the given key with new values, removes extra values that are already set if we don't suply enough, and appends values to the end if there ar...
def _next(self): """Get the next summary and present it.""" self.summaries.rotate(-1) current_summary = self.summaries[0] self._update_summary(current_summary)
Get the next summary and present it.
Below is the the instruction that describes the task: ### Input: Get the next summary and present it. ### Response: def _next(self): """Get the next summary and present it.""" self.summaries.rotate(-1) current_summary = self.summaries[0] self._update_summary(current_summary)
def addContentLen(self, content, len): """Append the extra substring to the node content. NOTE: In contrast to xmlNodeSetContentLen(), @content is supposed to be raw text, so unescaped XML special chars are allowed, entity references are not supported. """ libxml2mod.xmlNo...
Append the extra substring to the node content. NOTE: In contrast to xmlNodeSetContentLen(), @content is supposed to be raw text, so unescaped XML special chars are allowed, entity references are not supported.
Below is the the instruction that describes the task: ### Input: Append the extra substring to the node content. NOTE: In contrast to xmlNodeSetContentLen(), @content is supposed to be raw text, so unescaped XML special chars are allowed, entity references are not supported. ### Respo...
def _cli(): '''CLI interface''' parser = _argparse.ArgumentParser( description=''' Present the user with a simple CLI menu, and return the option chosen. The menu is presented via stderr. The output is printed to stdout for piping. '''.format(_VERSION), ...
CLI interface
Below is the the instruction that describes the task: ### Input: CLI interface ### Response: def _cli(): '''CLI interface''' parser = _argparse.ArgumentParser( description=''' Present the user with a simple CLI menu, and return the option chosen. The menu is presented via st...
def _select(self, event): """This is basically a proxy to trigger a pick event. This function is connected to either a mouse motion or mouse button event (see "self.enable") depending on "self.hover". If we're over a point, it fires a pick event. This probably seems bizarre, bu...
This is basically a proxy to trigger a pick event. This function is connected to either a mouse motion or mouse button event (see "self.enable") depending on "self.hover". If we're over a point, it fires a pick event. This probably seems bizarre, but it's required for hover mode (no mo...
Below is the the instruction that describes the task: ### Input: This is basically a proxy to trigger a pick event. This function is connected to either a mouse motion or mouse button event (see "self.enable") depending on "self.hover". If we're over a point, it fires a pick event. ...
def iterator_chain(variables: VarType, parent: str = None) -> Iterable[VarMatrix]: """This successively appends each element of an array to a single list of values. This takes a list of values and puts all the values generated for each element in the list into a single list of values. It uses the :func:`it...
This successively appends each element of an array to a single list of values. This takes a list of values and puts all the values generated for each element in the list into a single list of values. It uses the :func:`itertools.chain` function to achieve this. This function is particularly useful for spec...
Below is the the instruction that describes the task: ### Input: This successively appends each element of an array to a single list of values. This takes a list of values and puts all the values generated for each element in the list into a single list of values. It uses the :func:`itertools.chain` functi...
def run_scalpel(align_bams, items, ref_file, assoc_files, region=None, out_file=None): """Run Scalpel indel calling, either paired tumor/normal or germline calling. """ if region is None: message = ("A region must be provided for Scalpel") raise ValueError(message) if i...
Run Scalpel indel calling, either paired tumor/normal or germline calling.
Below is the the instruction that describes the task: ### Input: Run Scalpel indel calling, either paired tumor/normal or germline calling. ### Response: def run_scalpel(align_bams, items, ref_file, assoc_files, region=None, out_file=None): """Run Scalpel indel calling, either paired tumor/no...
def call_fset(self, obj, value) -> None: """Store the given custom value and call the setter function.""" vars(obj)[self.name] = self.fset(obj, value)
Store the given custom value and call the setter function.
Below is the the instruction that describes the task: ### Input: Store the given custom value and call the setter function. ### Response: def call_fset(self, obj, value) -> None: """Store the given custom value and call the setter function.""" vars(obj)[self.name] = self.fset(obj, value)
def delete(self, cascade=False): """ Deletes this playlist. """ if self.id: self.connection.post('delete_playlist', playlist_id=self.id, cascade=cascade) self.id = None
Deletes this playlist.
Below is the the instruction that describes the task: ### Input: Deletes this playlist. ### Response: def delete(self, cascade=False): """ Deletes this playlist. """ if self.id: self.connection.post('delete_playlist', playlist_id=self.id, cascade=cascade)...
def mount_volume(volume, device='/dev/xvdf', mountpoint='/mnt/data', fstype='ext4'): ''' Mount an EBS volume Args: volume (str): EBS volume ID device (str): default /dev/xvdf mountpoint (str): default /mnt/data fstype (str): default ext4 ''' _ec2().attach_volume(volu...
Mount an EBS volume Args: volume (str): EBS volume ID device (str): default /dev/xvdf mountpoint (str): default /mnt/data fstype (str): default ext4
Below is the the instruction that describes the task: ### Input: Mount an EBS volume Args: volume (str): EBS volume ID device (str): default /dev/xvdf mountpoint (str): default /mnt/data fstype (str): default ext4 ### Response: def mount_volume(volume, device='/dev/xvdf', mount...
def get_or_create_by_title(self, title): """ Fetch a title, if it exists. Create it if it doesn't. Returns a tuple with the object first, and then a boolean that indicates whether or not the object was created fresh. True means it's brand new. """ try: ...
Fetch a title, if it exists. Create it if it doesn't. Returns a tuple with the object first, and then a boolean that indicates whether or not the object was created fresh. True means it's brand new.
Below is the the instruction that describes the task: ### Input: Fetch a title, if it exists. Create it if it doesn't. Returns a tuple with the object first, and then a boolean that indicates whether or not the object was created fresh. True means it's brand new. ### Response: def get_or_c...
def find_hist2d_offset(filename, reference, refwcs=None, refnames=['ra', 'dec'], match_tolerance=5., chip_catalog=True, search_radius=15.0, min_match=10, classify=True): """Iteratively look for the best cross-match between the catalog and ref. Parameters ------...
Iteratively look for the best cross-match between the catalog and ref. Parameters ---------- filename : `~astropy.io.fits.HDUList` or str Single image to extract sources for matching to the external astrometric catalog. reference : str or `~astropy.table.Table` ...
Below is the the instruction that describes the task: ### Input: Iteratively look for the best cross-match between the catalog and ref. Parameters ---------- filename : `~astropy.io.fits.HDUList` or str Single image to extract sources for matching to the external astrometric...
def add(self, match, handler): """Register a handler with the Router. :param match: The first argument passed to the :meth:`match` method when checking against this handler. :param handler: A callable or :class:`Route` instance that will handle matching calls. If not a R...
Register a handler with the Router. :param match: The first argument passed to the :meth:`match` method when checking against this handler. :param handler: A callable or :class:`Route` instance that will handle matching calls. If not a Route instance, will be wrapped in one.
Below is the the instruction that describes the task: ### Input: Register a handler with the Router. :param match: The first argument passed to the :meth:`match` method when checking against this handler. :param handler: A callable or :class:`Route` instance that will handle ...
def derived_from_all(self, identities: List[QualName]) -> MutableSet[QualName]: """Return list of identities transitively derived from all `identity`.""" if not identities: return set() res = self.derived_from(identities[0]) for id in identities[1:]: res &= self.d...
Return list of identities transitively derived from all `identity`.
Below is the the instruction that describes the task: ### Input: Return list of identities transitively derived from all `identity`. ### Response: def derived_from_all(self, identities: List[QualName]) -> MutableSet[QualName]: """Return list of identities transitively derived from all `identity`.""" ...
def grasstruth(args): """ %prog grasstruth james-pan-grass.txt Prepare truth pairs for 4 grasses. """ p = OptionParser(grasstruth.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) james, = args fp = open(james) pairs = set() f...
%prog grasstruth james-pan-grass.txt Prepare truth pairs for 4 grasses.
Below is the the instruction that describes the task: ### Input: %prog grasstruth james-pan-grass.txt Prepare truth pairs for 4 grasses. ### Response: def grasstruth(args): """ %prog grasstruth james-pan-grass.txt Prepare truth pairs for 4 grasses. """ p = OptionParser(grasstruth.__doc__)...
def content_list(self, key, model): """Returns the list of content IDs for a given model. This method maps to https://github.com/exosite/docs/tree/master/provision#get---list-content-ids Args: key: The CIK or Token for the device model: """ path ...
Returns the list of content IDs for a given model. This method maps to https://github.com/exosite/docs/tree/master/provision#get---list-content-ids Args: key: The CIK or Token for the device model:
Below is the the instruction that describes the task: ### Input: Returns the list of content IDs for a given model. This method maps to https://github.com/exosite/docs/tree/master/provision#get---list-content-ids Args: key: The CIK or Token for the device model: ###...
def exerciseOptions(self, id, contract, exerciseAction, exerciseQuantity, account, override): """exerciseOptions(EClient self, TickerId id, Contract contract, int exerciseAction, int exerciseQuantity, IBString const & account, int override)""" return _swigibpy.EClient_exerciseOptions(self, id, contract,...
exerciseOptions(EClient self, TickerId id, Contract contract, int exerciseAction, int exerciseQuantity, IBString const & account, int override)
Below is the the instruction that describes the task: ### Input: exerciseOptions(EClient self, TickerId id, Contract contract, int exerciseAction, int exerciseQuantity, IBString const & account, int override) ### Response: def exerciseOptions(self, id, contract, exerciseAction, exerciseQuantity, account, override)...
def execute(self, fragment, pretty_format=True): """ Run or aggregate a query fragment Concat the fragment to any stored fragments. If they form a complete query, run it and return the result. If not, store them and return None. """ self.fragments = (self.fragme...
Run or aggregate a query fragment Concat the fragment to any stored fragments. If they form a complete query, run it and return the result. If not, store them and return None.
Below is the the instruction that describes the task: ### Input: Run or aggregate a query fragment Concat the fragment to any stored fragments. If they form a complete query, run it and return the result. If not, store them and return None. ### Response: def execute(self, fragment, pretty_...
def startup_walk_for_missed_files(self): """Check xlog and xlog_incoming directories for files that receivexlog has received but not yet compressed as well as the files we have compressed but not yet uploaded and process them.""" for site in self.config["backup_sites"]: compressed_xl...
Check xlog and xlog_incoming directories for files that receivexlog has received but not yet compressed as well as the files we have compressed but not yet uploaded and process them.
Below is the the instruction that describes the task: ### Input: Check xlog and xlog_incoming directories for files that receivexlog has received but not yet compressed as well as the files we have compressed but not yet uploaded and process them. ### Response: def startup_walk_for_missed_files(self): ...
def check_subprocess(cmd, source, outname): """Run the command to resize the video and remove the output file if the processing fails. """ logger = logging.getLogger(__name__) try: res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) exc...
Run the command to resize the video and remove the output file if the processing fails.
Below is the the instruction that describes the task: ### Input: Run the command to resize the video and remove the output file if the processing fails. ### Response: def check_subprocess(cmd, source, outname): """Run the command to resize the video and remove the output file if the processing fails. ...
def load_labware( self, labware_obj: Labware, location: types.DeckLocation) -> Labware: """ Specify the presence of a piece of labware on the OT2 deck. This function loads the labware specified by `labware` (previously loaded from a configuration file) to the location ...
Specify the presence of a piece of labware on the OT2 deck. This function loads the labware specified by `labware` (previously loaded from a configuration file) to the location specified by `location`. :param Labware labware: The labware object to load :param location: The slot...
Below is the the instruction that describes the task: ### Input: Specify the presence of a piece of labware on the OT2 deck. This function loads the labware specified by `labware` (previously loaded from a configuration file) to the location specified by `location`. :param Labware ...
def data(offset, bytes): """Return Data record. This constructs the full record, including the length information, the record type (0x00), the checksum, and the offset. @param offset load offset of first byte. @param bytes list of byte values to pack into record. @...
Return Data record. This constructs the full record, including the length information, the record type (0x00), the checksum, and the offset. @param offset load offset of first byte. @param bytes list of byte values to pack into record. @return String representation...
Below is the the instruction that describes the task: ### Input: Return Data record. This constructs the full record, including the length information, the record type (0x00), the checksum, and the offset. @param offset load offset of first byte. @param bytes list of byte value...
def show_menu(self, status_icon, button, activate_time): """Show the tray icon menu. """ menu = self.get_widget('tray-menu') menu.popup(None, None, None, Gtk.StatusIcon.position_menu, button, activate_time)
Show the tray icon menu.
Below is the the instruction that describes the task: ### Input: Show the tray icon menu. ### Response: def show_menu(self, status_icon, button, activate_time): """Show the tray icon menu. """ menu = self.get_widget('tray-menu') menu.popup(None, None, None, Gtk.StatusIcon.position_m...
def draw_hydrogen_bonds(self,color="black"): """For each bond that has been determined to be important, a line gets drawn. """ self.draw_hbonds="" if self.hbonds!=None: for bond in self.hbonds.hbonds_for_drawing: x = str((self.molecule.x_dim-self.molecule.molsize1)/2) y = str((self.molecule.y_dim-sel...
For each bond that has been determined to be important, a line gets drawn.
Below is the the instruction that describes the task: ### Input: For each bond that has been determined to be important, a line gets drawn. ### Response: def draw_hydrogen_bonds(self,color="black"): """For each bond that has been determined to be important, a line gets drawn. """ self.draw_hbonds="" if sel...
def vrrp_config(app, interface, config): """create an instance. returns EventVRRPConfigReply(instance.name, interface, config) on success. returns EventVRRPConfigReply(None, interface, config) on failure. """ config_request = vrrp_event.EventVRRPConfigRequest(interface, config) config_re...
create an instance. returns EventVRRPConfigReply(instance.name, interface, config) on success. returns EventVRRPConfigReply(None, interface, config) on failure.
Below is the the instruction that describes the task: ### Input: create an instance. returns EventVRRPConfigReply(instance.name, interface, config) on success. returns EventVRRPConfigReply(None, interface, config) on failure. ### Response: def vrrp_config(app, interface, config): """create an i...
def field_type_schema( field: Field, *, by_alias: bool, model_name_map: Dict[Type['main.BaseModel'], str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ Used by ``field_schema()``, you probably should be using that funct...
Used by ``field_schema()``, you probably should be using that function. Take a single ``field`` and generate the schema for its type only, not including additional information as title, etc. Also return additional schema definitions, from sub-models.
Below is the the instruction that describes the task: ### Input: Used by ``field_schema()``, you probably should be using that function. Take a single ``field`` and generate the schema for its type only, not including additional information as title, etc. Also return additional schema definitions, from sub...
def _delete(self, url, data, scope): """ Make a DELETE request using the session object to a Degreed endpoint. Args: url (str): The url to send a DELETE request to. data (str): The json encoded payload to DELETE. scope (str): Must be one of the scopes Degreed...
Make a DELETE request using the session object to a Degreed endpoint. Args: url (str): The url to send a DELETE request to. data (str): The json encoded payload to DELETE. scope (str): Must be one of the scopes Degreed expects: - `CONTENT_PROVIDER_SCO...
Below is the the instruction that describes the task: ### Input: Make a DELETE request using the session object to a Degreed endpoint. Args: url (str): The url to send a DELETE request to. data (str): The json encoded payload to DELETE. scope (str): Must be one of the sc...
def init_app(self, app): """Flask application initialization.""" self.init_config(app) app.cli.add_command(cmd) app.extensions['invenio-communities'] = self # Register the jinja do extension app.jinja_env.add_extension('jinja2.ext.do') self.register_signals(app)
Flask application initialization.
Below is the the instruction that describes the task: ### Input: Flask application initialization. ### Response: def init_app(self, app): """Flask application initialization.""" self.init_config(app) app.cli.add_command(cmd) app.extensions['invenio-communities'] = self # Reg...
def _step_decorator_args(self, decorator): """ Get the arguments passed to step decorators converted to python objects. """ args = decorator.children[3:-2] step = None if len(args) == 1: try: step = ast.literal_eval(args[0].get_code()) ...
Get the arguments passed to step decorators converted to python objects.
Below is the the instruction that describes the task: ### Input: Get the arguments passed to step decorators converted to python objects. ### Response: def _step_decorator_args(self, decorator): """ Get the arguments passed to step decorators converted to python objects. """...
def hex_from(val): """Returns hex string representation for a given value. :param bytes|str|unicode|int|long val: :rtype: bytes|str """ if isinstance(val, integer_types): hex_str = '%x' % val if len(hex_str) % 2: hex_str = '0' + hex_str return hex_str return...
Returns hex string representation for a given value. :param bytes|str|unicode|int|long val: :rtype: bytes|str
Below is the the instruction that describes the task: ### Input: Returns hex string representation for a given value. :param bytes|str|unicode|int|long val: :rtype: bytes|str ### Response: def hex_from(val): """Returns hex string representation for a given value. :param bytes|str|unicode|int|long...
def instantiate(self, params, auth=None): """ Allows you to fetch the map tiles of a created map :param params: The json with the styling info for the named map :param auth: The auth client :type params: dict :type auth: :class:`carto.auth.APIKeyAuthClient` :ret...
Allows you to fetch the map tiles of a created map :param params: The json with the styling info for the named map :param auth: The auth client :type params: dict :type auth: :class:`carto.auth.APIKeyAuthClient` :return: :raise: CartoException
Below is the the instruction that describes the task: ### Input: Allows you to fetch the map tiles of a created map :param params: The json with the styling info for the named map :param auth: The auth client :type params: dict :type auth: :class:`carto.auth.APIKeyAuthClient` ...
def require(self, key: str) -> str: """ Returns a configuration value by its given key. If it doesn't exist, an error is thrown. :param str key: The requested configuration key. :return: The configuration key's value. :rtype: str :raises ConfigMissingError: The configur...
Returns a configuration value by its given key. If it doesn't exist, an error is thrown. :param str key: The requested configuration key. :return: The configuration key's value. :rtype: str :raises ConfigMissingError: The configuration value did not exist.
Below is the the instruction that describes the task: ### Input: Returns a configuration value by its given key. If it doesn't exist, an error is thrown. :param str key: The requested configuration key. :return: The configuration key's value. :rtype: str :raises ConfigMissingError:...
def _handle_no_candidates(self): """ If we fail to find a good candidate we need to find something else. """ # since we've not found a good candidate we're should help this if self.dom is not None and len(self.dom): dom = prep_article(self.dom) dom = build...
If we fail to find a good candidate we need to find something else.
Below is the the instruction that describes the task: ### Input: If we fail to find a good candidate we need to find something else. ### Response: def _handle_no_candidates(self): """ If we fail to find a good candidate we need to find something else. """ # since we've not found a g...
def run(self): """ Run the command with supplied configuration """ device = self.model_config.torch_device() learner = Learner(device, self.model_factory.instantiate()) # All callbacks useful for learning callbacks = self.gather_callbacks() # Metrics to track through th...
Run the command with supplied configuration
Below is the the instruction that describes the task: ### Input: Run the command with supplied configuration ### Response: def run(self): """ Run the command with supplied configuration """ device = self.model_config.torch_device() learner = Learner(device, self.model_factory.instantiate())...
def cmap(rgbin, N=256): '''Input an array of rgb values to generate a colormap. :param rgbin: An [mx3] array, where m is the number of input color triplets which are interpolated between to make the colormap that is returned. hex values can be input instead, as [mx1] in single quotes with a #...
Input an array of rgb values to generate a colormap. :param rgbin: An [mx3] array, where m is the number of input color triplets which are interpolated between to make the colormap that is returned. hex values can be input instead, as [mx1] in single quotes with a #. :param N=10: The number o...
Below is the the instruction that describes the task: ### Input: Input an array of rgb values to generate a colormap. :param rgbin: An [mx3] array, where m is the number of input color triplets which are interpolated between to make the colormap that is returned. hex values can be input inste...
def add_io_hook(self, hook): """ Args: hook: This hook will be invoked for every incoming and outgoing CAN frame. Hook arguments: (direction, frame) See FRAME_DIRECTION_*, CANFrame. """ def proxy(*args): hook(*args) ...
Args: hook: This hook will be invoked for every incoming and outgoing CAN frame. Hook arguments: (direction, frame) See FRAME_DIRECTION_*, CANFrame.
Below is the the instruction that describes the task: ### Input: Args: hook: This hook will be invoked for every incoming and outgoing CAN frame. Hook arguments: (direction, frame) See FRAME_DIRECTION_*, CANFrame. ### Response: def add_io_hook(self, hook): ...
def to_dataset(self, dim=None, name=None): """Convert a DataArray to a Dataset. Parameters ---------- dim : str, optional Name of the dimension on this array along which to split this array into separate variables. If not provided, this array is converted ...
Convert a DataArray to a Dataset. Parameters ---------- dim : str, optional Name of the dimension on this array along which to split this array into separate variables. If not provided, this array is converted into a Dataset of one variable. name : st...
Below is the the instruction that describes the task: ### Input: Convert a DataArray to a Dataset. Parameters ---------- dim : str, optional Name of the dimension on this array along which to split this array into separate variables. If not provided, this array is co...
def is_broker_action_done(action, rid=None, unit=None): """Check whether broker action has completed yet. @param action: name of action to be performed @returns True if action complete otherwise False """ rdata = relation_get(rid, unit) or {} broker_rsp = rdata.get(get_broker_rsp_key()) if ...
Check whether broker action has completed yet. @param action: name of action to be performed @returns True if action complete otherwise False
Below is the the instruction that describes the task: ### Input: Check whether broker action has completed yet. @param action: name of action to be performed @returns True if action complete otherwise False ### Response: def is_broker_action_done(action, rid=None, unit=None): """Check whether broker a...
def from_base62(s): """ Convert a base62 String back into a number :param s: The base62 encoded String :return: The number encoded in the String (integer) """ result = 0 for c in s: if c not in BASE62_MAP: raise Exception('Invalid base64 string: %s' % s) result ...
Convert a base62 String back into a number :param s: The base62 encoded String :return: The number encoded in the String (integer)
Below is the the instruction that describes the task: ### Input: Convert a base62 String back into a number :param s: The base62 encoded String :return: The number encoded in the String (integer) ### Response: def from_base62(s): """ Convert a base62 String back into a number :param s: The base...
def simxAuxiliaryConsoleShow(clientID, consoleHandle, showState, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' return c_AuxiliaryConsoleShow(clientID, consoleHandle, showState, operationMode)
Please have a look at the function description/documentation in the V-REP user manual
Below is the the instruction that describes the task: ### Input: Please have a look at the function description/documentation in the V-REP user manual ### Response: def simxAuxiliaryConsoleShow(clientID, consoleHandle, showState, operationMode): ''' Please have a look at the function description/documentat...
def trunk_angles(nrn, neurite_type=NeuriteType.all): '''Calculates the angles between all the trunks of the neuron. The angles are defined on the x-y plane and the trees are sorted from the y axis and anticlock-wise. ''' vectors = trunk_vectors(nrn, neurite_type=neurite_type) # In order to avoid...
Calculates the angles between all the trunks of the neuron. The angles are defined on the x-y plane and the trees are sorted from the y axis and anticlock-wise.
Below is the the instruction that describes the task: ### Input: Calculates the angles between all the trunks of the neuron. The angles are defined on the x-y plane and the trees are sorted from the y axis and anticlock-wise. ### Response: def trunk_angles(nrn, neurite_type=NeuriteType.all): '''Calcula...
def operations(*operations): '''Decorator for marking Resource methods as HTTP operations. This decorator does a number of different things: - It transfer onto itself docstring and annotations from the decorated method, so as to be "transparent" with regards to introspection. - It tra...
Decorator for marking Resource methods as HTTP operations. This decorator does a number of different things: - It transfer onto itself docstring and annotations from the decorated method, so as to be "transparent" with regards to introspection. - It tranform the method so as to make it a ...
Below is the the instruction that describes the task: ### Input: Decorator for marking Resource methods as HTTP operations. This decorator does a number of different things: - It transfer onto itself docstring and annotations from the decorated method, so as to be "transparent" with regards t...
def permission_required(perm, fn=None, login_url=None, raise_exception=False, redirect_field_name=REDIRECT_FIELD_NAME): """ View decorator that checks for the given permissions before allowing the view to execute. Use it like this:: from django.shortcuts import get_object_or_404 from rules....
View decorator that checks for the given permissions before allowing the view to execute. Use it like this:: from django.shortcuts import get_object_or_404 from rules.contrib.views import permission_required from posts.models import Post def get_post_by_pk(request, post_id): ...
Below is the the instruction that describes the task: ### Input: View decorator that checks for the given permissions before allowing the view to execute. Use it like this:: from django.shortcuts import get_object_or_404 from rules.contrib.views import permission_required from posts.mod...
def get_id_head(self): ''' Returns the id of the target that is set as "head" @rtype: string @return: the target id (or None) of the head target ''' id_head = None for target_node in self: if target_node.is_head(): id_head = target_nod...
Returns the id of the target that is set as "head" @rtype: string @return: the target id (or None) of the head target
Below is the the instruction that describes the task: ### Input: Returns the id of the target that is set as "head" @rtype: string @return: the target id (or None) of the head target ### Response: def get_id_head(self): ''' Returns the id of the target that is set as "head" ...
def parse_parameters(self, parameters): """Parses and sets parameters in the model.""" self.parameters = [] for param_name, param_value in parameters.items(): p = Parameter(param_name, param_value) if p: self.parameters.append(p)
Parses and sets parameters in the model.
Below is the the instruction that describes the task: ### Input: Parses and sets parameters in the model. ### Response: def parse_parameters(self, parameters): """Parses and sets parameters in the model.""" self.parameters = [] for param_name, param_value in parameters.items(): ...
def cmode(self, channel, modes=''): """ Sets or gets the channel mode. Required arguments: * channel - Channel to set/get modes of. Optional arguments: * modes='' - Modes to set. If not specified return the modes of the channel. """ with self.l...
Sets or gets the channel mode. Required arguments: * channel - Channel to set/get modes of. Optional arguments: * modes='' - Modes to set. If not specified return the modes of the channel.
Below is the the instruction that describes the task: ### Input: Sets or gets the channel mode. Required arguments: * channel - Channel to set/get modes of. Optional arguments: * modes='' - Modes to set. If not specified return the modes of the channel. ### Response: def...
def kwargs_only(func): """ Make a function only accept keyword arguments. This can be dropped in Python 3 in lieu of: def foo(*, bar=default): """ if hasattr(inspect, 'signature'): # pragma: no cover # Python 3 signature = inspect.signature(func) first_arg_name = lis...
Make a function only accept keyword arguments. This can be dropped in Python 3 in lieu of: def foo(*, bar=default):
Below is the the instruction that describes the task: ### Input: Make a function only accept keyword arguments. This can be dropped in Python 3 in lieu of: def foo(*, bar=default): ### Response: def kwargs_only(func): """ Make a function only accept keyword arguments. This can be dropped in...
def _make_module_refnode(self, builder, fromdocname, name, contnode): """Helper function to generate new xref node based on current environment. """ # Get additional info for modules. docname, synopsis, platform, deprecated = self.data['modules'][name] title = name ...
Helper function to generate new xref node based on current environment.
Below is the the instruction that describes the task: ### Input: Helper function to generate new xref node based on current environment. ### Response: def _make_module_refnode(self, builder, fromdocname, name, contnode): """Helper function to generate new xref node based on current environm...
def _build_pyramid(self, image, levels): """ Returns a list of reduced-size images, from smallest to original size """ pyramid = [image] for l in range(levels-1): if any(x < 20 for x in pyramid[-1].shape[:2]): break pyramid.append(cv2.pyrDown(pyramid[-1]))...
Returns a list of reduced-size images, from smallest to original size
Below is the the instruction that describes the task: ### Input: Returns a list of reduced-size images, from smallest to original size ### Response: def _build_pyramid(self, image, levels): """ Returns a list of reduced-size images, from smallest to original size """ pyramid = [image] for l...
def make_plot(self): """Generate the plot from time series and arguments """ plot = Plot(figsize=self.figsize, dpi=self.dpi) ax = plot.gca(xscale='auto-gps') # handle user specified plot labels if self.args.legend: nlegargs = len(self.args.legend[0]) ...
Generate the plot from time series and arguments
Below is the the instruction that describes the task: ### Input: Generate the plot from time series and arguments ### Response: def make_plot(self): """Generate the plot from time series and arguments """ plot = Plot(figsize=self.figsize, dpi=self.dpi) ax = plot.gca(xscale='auto-gps...
def update_hosting_device_status(self, context, host, status_info): """Report status changes for hosting devices. :param context: contains user information :param host: originator of callback :param status_info: Dictionary with list of hosting device ids for each type of hos...
Report status changes for hosting devices. :param context: contains user information :param host: originator of callback :param status_info: Dictionary with list of hosting device ids for each type of hosting device status to be updated i.e.:: { ...
Below is the the instruction that describes the task: ### Input: Report status changes for hosting devices. :param context: contains user information :param host: originator of callback :param status_info: Dictionary with list of hosting device ids for each type of hosting devic...
def _send_command(self, command, raw_text=False): """ Wrapper for NX-API show method. Allows more code sharing between NX-API and SSH. """ return self.device.show(command, raw_text=raw_text)
Wrapper for NX-API show method. Allows more code sharing between NX-API and SSH.
Below is the the instruction that describes the task: ### Input: Wrapper for NX-API show method. Allows more code sharing between NX-API and SSH. ### Response: def _send_command(self, command, raw_text=False): """ Wrapper for NX-API show method. Allows more code sharing between NX...
def reset(self): """Reset the estimates of mean and variance. Resets the full state of this class. Returns: Operation. """ with tf.name_scope(self._name + '/reset'): return tf.group( self._count.assign(0), self._mean.assign(tf.zeros_like(self._mean)), self...
Reset the estimates of mean and variance. Resets the full state of this class. Returns: Operation.
Below is the the instruction that describes the task: ### Input: Reset the estimates of mean and variance. Resets the full state of this class. Returns: Operation. ### Response: def reset(self): """Reset the estimates of mean and variance. Resets the full state of this class. Returns:...
def resolves_for(self, session): """ Returns whether this query resolves for the given session. Args: session (Session): The session for which this query should be executed. Returns: bool: Whether this query resolves. """ if self.url: ...
Returns whether this query resolves for the given session. Args: session (Session): The session for which this query should be executed. Returns: bool: Whether this query resolves.
Below is the the instruction that describes the task: ### Input: Returns whether this query resolves for the given session. Args: session (Session): The session for which this query should be executed. Returns: bool: Whether this query resolves. ### Response: def resolves_...
def _move_agent(self, agent, direction, wrap_allowed=True): """ moves agent 'agent' in 'direction' """ x,y = agent.coords['x'], agent.coords['y'] print('moving agent ', agent.name, 'to x,y=', direction, 'wrap_allowed = ', wrap_allowed) agent.coords['x'] = x + direction[0]...
moves agent 'agent' in 'direction'
Below is the the instruction that describes the task: ### Input: moves agent 'agent' in 'direction' ### Response: def _move_agent(self, agent, direction, wrap_allowed=True): """ moves agent 'agent' in 'direction' """ x,y = agent.coords['x'], agent.coords['y'] print('moving a...
def peer_store(key, value, relation_name='cluster'): """Store the key/value pair on the named peer relation `relation_name`.""" cluster_rels = relation_ids(relation_name) if len(cluster_rels) > 0: cluster_rid = cluster_rels[0] relation_set(relation_id=cluster_rid, relati...
Store the key/value pair on the named peer relation `relation_name`.
Below is the the instruction that describes the task: ### Input: Store the key/value pair on the named peer relation `relation_name`. ### Response: def peer_store(key, value, relation_name='cluster'): """Store the key/value pair on the named peer relation `relation_name`.""" cluster_rels = relation_ids(rel...