code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def register_value_producer(self, value_name: str, source: Callable[..., pd.DataFrame]=None, preferred_combiner: Callable=replace_combiner, preferred_post_processor: Callable[..., pd.DataFrame]=None) -> Pipeline: """Marks a ``Callable`` as the prod...
Marks a ``Callable`` as the producer of a named value. Parameters ---------- value_name : The name of the new dynamic value pipeline. source : A callable source for the dynamic value pipeline. preferred_combiner : A strategy for combining the ...
Below is the the instruction that describes the task: ### Input: Marks a ``Callable`` as the producer of a named value. Parameters ---------- value_name : The name of the new dynamic value pipeline. source : A callable source for the dynamic value pipeline. ...
def list_address(self, domain): " Get the list of addresses of a single domain." try: response = self.get('/REST/ARecord/%s/%s' % ( self.zone, domain)) except self.NotFoundError: return [] # Return a generator with the addresses. addresse...
Get the list of addresses of a single domain.
Below is the the instruction that describes the task: ### Input: Get the list of addresses of a single domain. ### Response: def list_address(self, domain): " Get the list of addresses of a single domain." try: response = self.get('/REST/ARecord/%s/%s' % ( self.zone, do...
def get_all_tags(self): """ This method returns a list of all tags. """ data = self.get_data("tags") return [ Tag(token=self.token, **tag) for tag in data['tags'] ]
This method returns a list of all tags.
Below is the the instruction that describes the task: ### Input: This method returns a list of all tags. ### Response: def get_all_tags(self): """ This method returns a list of all tags. """ data = self.get_data("tags") return [ Tag(token=self.token, **tag) f...
def AIC(data, model, params=None, corrected=True): """ Akaike Information Criteria given data and a model Parameters ---------- {0} {1} params : int Number of parameters in the model. If None, calculated from model object. corrected : bool If True, calculates the...
Akaike Information Criteria given data and a model Parameters ---------- {0} {1} params : int Number of parameters in the model. If None, calculated from model object. corrected : bool If True, calculates the small-sample size correct AICC. Default True. Returns ...
Below is the the instruction that describes the task: ### Input: Akaike Information Criteria given data and a model Parameters ---------- {0} {1} params : int Number of parameters in the model. If None, calculated from model object. corrected : bool If True, calculat...
def update_bgp_peer(self, bgp_peer_id, body=None): """Update a BGP peer.""" return self.put(self.bgp_peer_path % bgp_peer_id, body=body)
Update a BGP peer.
Below is the the instruction that describes the task: ### Input: Update a BGP peer. ### Response: def update_bgp_peer(self, bgp_peer_id, body=None): """Update a BGP peer.""" return self.put(self.bgp_peer_path % bgp_peer_id, body=body)
def fenceloader(self): '''fence loader by sysid''' if not self.target_system in self.fenceloader_by_sysid: self.fenceloader_by_sysid[self.target_system] = mavwp.MAVFenceLoader() return self.fenceloader_by_sysid[self.target_system]
fence loader by sysid
Below is the the instruction that describes the task: ### Input: fence loader by sysid ### Response: def fenceloader(self): '''fence loader by sysid''' if not self.target_system in self.fenceloader_by_sysid: self.fenceloader_by_sysid[self.target_system] = mavwp.MAVFenceLoader() ...
def compare_field_caches(self, replica, original): """Verify original is subset of replica""" if original is None: original = [] if replica is None: replica = [] self.pr_dbg("Comparing orig with %s fields to replica with %s fields" % (len(origi...
Verify original is subset of replica
Below is the the instruction that describes the task: ### Input: Verify original is subset of replica ### Response: def compare_field_caches(self, replica, original): """Verify original is subset of replica""" if original is None: original = [] if replica is None: re...
def _compute_term2(self, C, mag, rrup): """ This computes the term f2 in equation 32, page 1021 """ c78_factor = (C['c7'] * np.exp(C['c8'] * mag)) ** 2 R = np.sqrt(rrup ** 2 + c78_factor) return C['c4'] * np.log(R) + (C['c5'] + C['c6'] * mag) * rrup
This computes the term f2 in equation 32, page 1021
Below is the the instruction that describes the task: ### Input: This computes the term f2 in equation 32, page 1021 ### Response: def _compute_term2(self, C, mag, rrup): """ This computes the term f2 in equation 32, page 1021 """ c78_factor = (C['c7'] * np.exp(C['c8'] * mag)) ** 2 ...
def _solve_location(self, req, dut_req_len, idx): """ Helper function for resolving the location for a resource. :param req: Requirements dictionary :param dut_req_len: Amount of required resources :param idx: index, integer :return: Nothing, modifies req object ...
Helper function for resolving the location for a resource. :param req: Requirements dictionary :param dut_req_len: Amount of required resources :param idx: index, integer :return: Nothing, modifies req object
Below is the the instruction that describes the task: ### Input: Helper function for resolving the location for a resource. :param req: Requirements dictionary :param dut_req_len: Amount of required resources :param idx: index, integer :return: Nothing, modifies req object ### Respo...
def get_quad_by_id(self, mosaic, quad_id): '''Get a quad response for a specific mosaic and quad. :param mosaic dict: A mosaic representation from the API :param quad_id str: A quad id (typically <xcoord>-<ycoord>) :returns: :py:Class:`planet.api.models.JSON` :raises planet.api....
Get a quad response for a specific mosaic and quad. :param mosaic dict: A mosaic representation from the API :param quad_id str: A quad id (typically <xcoord>-<ycoord>) :returns: :py:Class:`planet.api.models.JSON` :raises planet.api.exceptions.APIException: On API error.
Below is the the instruction that describes the task: ### Input: Get a quad response for a specific mosaic and quad. :param mosaic dict: A mosaic representation from the API :param quad_id str: A quad id (typically <xcoord>-<ycoord>) :returns: :py:Class:`planet.api.models.JSON` :rai...
def register_shortcuts(self): ''' .. versionchanged:: 0.14 Add keyboard shortcuts to set neighbouring electrode states based on directional input using ``<Control>`` key plus the corresponding direction (e.g., ``<Control>Up``) ''' def control_protocol(...
.. versionchanged:: 0.14 Add keyboard shortcuts to set neighbouring electrode states based on directional input using ``<Control>`` key plus the corresponding direction (e.g., ``<Control>Up``)
Below is the the instruction that describes the task: ### Input: .. versionchanged:: 0.14 Add keyboard shortcuts to set neighbouring electrode states based on directional input using ``<Control>`` key plus the corresponding direction (e.g., ``<Control>Up``) ### Response: def reg...
def query_columns(conn, query, name=None): """Lightweight query to retrieve column list of select query. Notes ----- Strongly urged to specify a cursor name for performance. """ with conn.cursor(name) as cursor: cursor.itersize = 1 cursor.execute(query) cursor.fetchmany...
Lightweight query to retrieve column list of select query. Notes ----- Strongly urged to specify a cursor name for performance.
Below is the the instruction that describes the task: ### Input: Lightweight query to retrieve column list of select query. Notes ----- Strongly urged to specify a cursor name for performance. ### Response: def query_columns(conn, query, name=None): """Lightweight query to retrieve column list of ...
def error2str(e): """returns the formatted stacktrace of the exception `e`. :param BaseException e: an exception to format into str :rtype: str """ out = StringIO() traceback.print_exception(None, e, e.__traceback__, file=out) out.seek(0) return out.read()
returns the formatted stacktrace of the exception `e`. :param BaseException e: an exception to format into str :rtype: str
Below is the the instruction that describes the task: ### Input: returns the formatted stacktrace of the exception `e`. :param BaseException e: an exception to format into str :rtype: str ### Response: def error2str(e): """returns the formatted stacktrace of the exception `e`. :param BaseExceptio...
def to_seconds(value, strict=True, force_int=True): """ converts duration value to integer seconds strict=True (by default) raises StrictnessError if either hours, minutes or seconds in duration value exceed allowed values """ if isinstance(value, int): return value # assuming it's sec...
converts duration value to integer seconds strict=True (by default) raises StrictnessError if either hours, minutes or seconds in duration value exceed allowed values
Below is the the instruction that describes the task: ### Input: converts duration value to integer seconds strict=True (by default) raises StrictnessError if either hours, minutes or seconds in duration value exceed allowed values ### Response: def to_seconds(value, strict=True, force_int=True): """ ...
def post_ext_init(state): """Setup blueprint.""" app = state.app app.config.setdefault( 'OAUTHCLIENT_SITENAME', app.config.get('THEME_SITENAME', 'Invenio')) app.config.setdefault( 'OAUTHCLIENT_BASE_TEMPLATE', app.config.get('BASE_TEMPLATE', 'inveni...
Setup blueprint.
Below is the the instruction that describes the task: ### Input: Setup blueprint. ### Response: def post_ext_init(state): """Setup blueprint.""" app = state.app app.config.setdefault( 'OAUTHCLIENT_SITENAME', app.config.get('THEME_SITENAME', 'Invenio')) app.config.setdefault( ...
def google_analytics(parser, token): """ Google Analytics tracking template tag. Renders Javascript code to track page visits. You must supply your website property ID (as a string) in the ``GOOGLE_ANALYTICS_PROPERTY_ID`` setting. """ bits = token.split_contents() if len(bits) > 1: ...
Google Analytics tracking template tag. Renders Javascript code to track page visits. You must supply your website property ID (as a string) in the ``GOOGLE_ANALYTICS_PROPERTY_ID`` setting.
Below is the the instruction that describes the task: ### Input: Google Analytics tracking template tag. Renders Javascript code to track page visits. You must supply your website property ID (as a string) in the ``GOOGLE_ANALYTICS_PROPERTY_ID`` setting. ### Response: def google_analytics(parser, tok...
def _read_function(ctx: ReaderContext) -> llist.List: """Read a function reader macro from the input stream.""" if ctx.is_in_anon_fn: raise SyntaxError(f"Nested #() definitions not allowed") with ctx.in_anon_fn(): form = _read_list(ctx) arg_set = set() def arg_suffix(arg_num): ...
Read a function reader macro from the input stream.
Below is the the instruction that describes the task: ### Input: Read a function reader macro from the input stream. ### Response: def _read_function(ctx: ReaderContext) -> llist.List: """Read a function reader macro from the input stream.""" if ctx.is_in_anon_fn: raise SyntaxError(f"Nested #() def...
def smartypants(text): """ Transforms sequences of characters into HTML entities. =================================== ===================== ========= Markdown HTML Result =================================== ===================== ========= ``'s``...
Transforms sequences of characters into HTML entities. =================================== ===================== ========= Markdown HTML Result =================================== ===================== ========= ``'s`` (s, t, m, d, re, ll, ve) &rsq...
Below is the the instruction that describes the task: ### Input: Transforms sequences of characters into HTML entities. =================================== ===================== ========= Markdown HTML Result =================================== =========...
def add_alt_text(self, alt_text): """Adds an alt_text. arg: alt_text (displayText): the new alt_text raise: InvalidArgument - ``alt_text`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``alt_text`` is ``null`` *compliance:...
Adds an alt_text. arg: alt_text (displayText): the new alt_text raise: InvalidArgument - ``alt_text`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``alt_text`` is ``null`` *compliance: mandatory -- This method must be implemented...
Below is the the instruction that describes the task: ### Input: Adds an alt_text. arg: alt_text (displayText): the new alt_text raise: InvalidArgument - ``alt_text`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``alt_text`` is ``nul...
def text_with_newlines(text, line_length=78, newline='\n'): '''Return text with a `newline` inserted after each `line_length` char. Return `text` unchanged if line_length == 0. ''' if line_length > 0: if len(text) <= line_length: return text else: return newline....
Return text with a `newline` inserted after each `line_length` char. Return `text` unchanged if line_length == 0.
Below is the the instruction that describes the task: ### Input: Return text with a `newline` inserted after each `line_length` char. Return `text` unchanged if line_length == 0. ### Response: def text_with_newlines(text, line_length=78, newline='\n'): '''Return text with a `newline` inserted after each `...
def do_connect(self, arg): ''' Connect to the arm. ''' if self.arm.is_connected(): print(self.style.error('Error: ', 'Arm is already connected.')) else: try: port = self.arm.connect() print(self.style.success('Success: ', ...
Connect to the arm.
Below is the the instruction that describes the task: ### Input: Connect to the arm. ### Response: def do_connect(self, arg): ''' Connect to the arm. ''' if self.arm.is_connected(): print(self.style.error('Error: ', 'Arm is already connected.')) else: try: ...
def update(self, *args, **kw): ''' Update the dictionary with items and names:: (items, names, **kw) (dict, names, **kw) (MIDict, names, **kw) Optional positional argument ``names`` is only allowed when ``self.indices`` is empty (no indices are set y...
Update the dictionary with items and names:: (items, names, **kw) (dict, names, **kw) (MIDict, names, **kw) Optional positional argument ``names`` is only allowed when ``self.indices`` is empty (no indices are set yet).
Below is the the instruction that describes the task: ### Input: Update the dictionary with items and names:: (items, names, **kw) (dict, names, **kw) (MIDict, names, **kw) Optional positional argument ``names`` is only allowed when ``self.indices`` is empty (no...
def key_type(key, host=None, port=None, db=None, password=None): ''' Get redis key type CLI Example: .. code-block:: bash salt '*' redis.type foo ''' server = _connect(host, port, db, password) return server.type(key)
Get redis key type CLI Example: .. code-block:: bash salt '*' redis.type foo
Below is the the instruction that describes the task: ### Input: Get redis key type CLI Example: .. code-block:: bash salt '*' redis.type foo ### Response: def key_type(key, host=None, port=None, db=None, password=None): ''' Get redis key type CLI Example: .. code-block:: bash ...
def _conan_user_home(self, conan, in_workdir=False): """Create the CONAN_USER_HOME for this task fingerprint and initialize the Conan remotes. See https://docs.conan.io/en/latest/reference/commands/consumer/config.html#conan-config-install for docs on configuring remotes. """ # This argument is exp...
Create the CONAN_USER_HOME for this task fingerprint and initialize the Conan remotes. See https://docs.conan.io/en/latest/reference/commands/consumer/config.html#conan-config-install for docs on configuring remotes.
Below is the the instruction that describes the task: ### Input: Create the CONAN_USER_HOME for this task fingerprint and initialize the Conan remotes. See https://docs.conan.io/en/latest/reference/commands/consumer/config.html#conan-config-install for docs on configuring remotes. ### Response: def _conan...
def prior_prediction(self): """get a dict of prior prediction variances Returns ------- prior_prediction : dict dictionary of prediction name, prior variance pairs """ if self.__prior_prediction is not None: return self.__prior_prediction ...
get a dict of prior prediction variances Returns ------- prior_prediction : dict dictionary of prediction name, prior variance pairs
Below is the the instruction that describes the task: ### Input: get a dict of prior prediction variances Returns ------- prior_prediction : dict dictionary of prediction name, prior variance pairs ### Response: def prior_prediction(self): """get a dict of prior predict...
def ifar(self, coinc_stat): """Return the far that would be associated with the coincident given. """ n = self.coincs.num_greater(coinc_stat) return self.background_time / lal.YRJUL_SI / (n + 1)
Return the far that would be associated with the coincident given.
Below is the the instruction that describes the task: ### Input: Return the far that would be associated with the coincident given. ### Response: def ifar(self, coinc_stat): """Return the far that would be associated with the coincident given. """ n = self.coincs.num_greater(coinc_stat) ...
def get_typelist(self): """ This collects all avaliable types and applies include/exclude filters """ typelist = [] # convert type list into arrays if strings if isinstance(self.config['type_include'], basestring): self.config['type_include'] = self.config['t...
This collects all avaliable types and applies include/exclude filters
Below is the the instruction that describes the task: ### Input: This collects all avaliable types and applies include/exclude filters ### Response: def get_typelist(self): """ This collects all avaliable types and applies include/exclude filters """ typelist = [] # convert...
def add_profile(self, namespace, key, value, force=False): """ Add profile information to this node at the DAX level """ try: entry = dax.Profile(namespace, key, value) self._dax_node.addProfile(entry) except dax.DuplicateError: if force: ...
Add profile information to this node at the DAX level
Below is the the instruction that describes the task: ### Input: Add profile information to this node at the DAX level ### Response: def add_profile(self, namespace, key, value, force=False): """ Add profile information to this node at the DAX level """ try: entry = dax.Profile(...
def _import_module(module_name, warn=True, prefix='_py_', ignore='_'): """Try import all public attributes from module into global namespace. Existing attributes with name clashes are renamed with prefix. Attributes starting with underscore are ignored by default. Return True on successful import. ...
Try import all public attributes from module into global namespace. Existing attributes with name clashes are renamed with prefix. Attributes starting with underscore are ignored by default. Return True on successful import.
Below is the the instruction that describes the task: ### Input: Try import all public attributes from module into global namespace. Existing attributes with name clashes are renamed with prefix. Attributes starting with underscore are ignored by default. Return True on successful import. ### Response...
def multipublish_tcp(self, topic, messages, **kwargs): """Use :meth:`NsqdTCPClient.multipublish` instead. .. deprecated:: 1.0.0 """ return self.__tcp_client.multipublish(topic, messages, **kwargs)
Use :meth:`NsqdTCPClient.multipublish` instead. .. deprecated:: 1.0.0
Below is the the instruction that describes the task: ### Input: Use :meth:`NsqdTCPClient.multipublish` instead. .. deprecated:: 1.0.0 ### Response: def multipublish_tcp(self, topic, messages, **kwargs): """Use :meth:`NsqdTCPClient.multipublish` instead. .. deprecated:: 1.0.0 """ ...
def angular_error(self, axis_length): """ The angular error for an in-plane axis of given length (either a PCA major axis or an intermediate direction). """ hyp_axes = self.method(self) return N.arctan2(hyp_axes[-1],axis_length)
The angular error for an in-plane axis of given length (either a PCA major axis or an intermediate direction).
Below is the the instruction that describes the task: ### Input: The angular error for an in-plane axis of given length (either a PCA major axis or an intermediate direction). ### Response: def angular_error(self, axis_length): """ The angular error for an in-plane axis of g...
def get_argument(self, name, default=None, strip=True): """ Returns the value of the argument with the given name. If default is not provided, returns ``None`` If the argument appears in the url more than once, we return the last value. The returned value is always unicode ...
Returns the value of the argument with the given name. If default is not provided, returns ``None`` If the argument appears in the url more than once, we return the last value. The returned value is always unicode
Below is the the instruction that describes the task: ### Input: Returns the value of the argument with the given name. If default is not provided, returns ``None`` If the argument appears in the url more than once, we return the last value. The returned value is always unicode ### Respon...
def _init_tools(self, element, callbacks=[]): """ Processes the list of tools to be supplied to the plot. """ tooltips, hover_opts = self._hover_opts(element) tooltips = [(ttp.pprint_label, '@{%s}' % util.dimension_sanitizer(ttp.name)) if isinstance(ttp, Dimen...
Processes the list of tools to be supplied to the plot.
Below is the the instruction that describes the task: ### Input: Processes the list of tools to be supplied to the plot. ### Response: def _init_tools(self, element, callbacks=[]): """ Processes the list of tools to be supplied to the plot. """ tooltips, hover_opts = self._hover_opt...
def get_queryset(self, request): """ Make special filtering by user's permissions. """ if not request.user.has_perm('zinnia.can_view_all'): queryset = self.model.objects.filter(authors__pk=request.user.pk) else: queryset = super(EntryAdmin, self).get_query...
Make special filtering by user's permissions.
Below is the the instruction that describes the task: ### Input: Make special filtering by user's permissions. ### Response: def get_queryset(self, request): """ Make special filtering by user's permissions. """ if not request.user.has_perm('zinnia.can_view_all'): querys...
def schedule_retry(self, config): """Schedule a retry""" raise self.retry(countdown=config.get('SAILTHRU_RETRY_SECONDS'), max_retries=config.get('SAILTHRU_RETRY_ATTEMPTS'))
Schedule a retry
Below is the the instruction that describes the task: ### Input: Schedule a retry ### Response: def schedule_retry(self, config): """Schedule a retry""" raise self.retry(countdown=config.get('SAILTHRU_RETRY_SECONDS'), max_retries=config.get('SAILTHRU_RETRY_ATTEMPTS'))
def filename_to_task_id(fname): """Map filename to the task id that created it assuming 1k tasks.""" # This matches the order and size in WikisumBase.out_filepaths fname = os.path.basename(fname) shard_id_increment = { "train": 0, "dev": 800, "test": 900, } parts = fname.split("-") split...
Map filename to the task id that created it assuming 1k tasks.
Below is the the instruction that describes the task: ### Input: Map filename to the task id that created it assuming 1k tasks. ### Response: def filename_to_task_id(fname): """Map filename to the task id that created it assuming 1k tasks.""" # This matches the order and size in WikisumBase.out_filepaths fna...
def pois_from_address(address, distance, amenities=None): """ Get OSM points of Interests within some distance north, south, east, and west of an address. Parameters ---------- address : string the address to geocode to a lat-long point distance : numeric distance in meters ...
Get OSM points of Interests within some distance north, south, east, and west of an address. Parameters ---------- address : string the address to geocode to a lat-long point distance : numeric distance in meters amenities : list List of amenities that will be used for f...
Below is the the instruction that describes the task: ### Input: Get OSM points of Interests within some distance north, south, east, and west of an address. Parameters ---------- address : string the address to geocode to a lat-long point distance : numeric distance in meters ...
def add_dnc( self, obj_id, channel='email', reason=MANUAL, channel_id=None, comments='via API' ): """ Adds Do Not Contact :param obj_id: int :param channel: str :param reason: str :param channel_id: int :param c...
Adds Do Not Contact :param obj_id: int :param channel: str :param reason: str :param channel_id: int :param comments: str :return: dict|str
Below is the the instruction that describes the task: ### Input: Adds Do Not Contact :param obj_id: int :param channel: str :param reason: str :param channel_id: int :param comments: str :return: dict|str ### Response: def add_dnc( self, obj_id, ...
def render_heading(self, token): """ Overrides super().render_heading; stores rendered heading first, then returns it. """ rendered = super().render_heading(token) content = self.parse_rendered_heading(rendered) if not (self.omit_title and token.level == 1 ...
Overrides super().render_heading; stores rendered heading first, then returns it.
Below is the the instruction that describes the task: ### Input: Overrides super().render_heading; stores rendered heading first, then returns it. ### Response: def render_heading(self, token): """ Overrides super().render_heading; stores rendered heading first, then returns it. ...
def bifurcated_extend(self, corpus, max_size): """Replaces the results with those n-grams that contain any of the original n-grams, and that represent points at which an n-gram is a constituent of multiple larger n-grams with a lower label count. :param corpus: corpus of works t...
Replaces the results with those n-grams that contain any of the original n-grams, and that represent points at which an n-gram is a constituent of multiple larger n-grams with a lower label count. :param corpus: corpus of works to which results belong :type corpus: `Corpus` ...
Below is the the instruction that describes the task: ### Input: Replaces the results with those n-grams that contain any of the original n-grams, and that represent points at which an n-gram is a constituent of multiple larger n-grams with a lower label count. :param corpus: corpus...
def load_schema(schema_path): """Prepare the api specification for request and response validation. :returns: a mapping from :class:`RequestMatcher` to :class:`ValidatorMap` for every operation in the api specification. :rtype: dict """ with open(schema_path, 'r') as schema_file: sc...
Prepare the api specification for request and response validation. :returns: a mapping from :class:`RequestMatcher` to :class:`ValidatorMap` for every operation in the api specification. :rtype: dict
Below is the the instruction that describes the task: ### Input: Prepare the api specification for request and response validation. :returns: a mapping from :class:`RequestMatcher` to :class:`ValidatorMap` for every operation in the api specification. :rtype: dict ### Response: def load_schema(sch...
def minimise(routing_table, target_length): """Reduce the size of a routing table by merging together entries where possible and by removing any remaining default routes. .. warning:: The input routing table *must* also include entries which could be removed and replaced by default routing...
Reduce the size of a routing table by merging together entries where possible and by removing any remaining default routes. .. warning:: The input routing table *must* also include entries which could be removed and replaced by default routing. .. warning:: It is assumed that the...
Below is the the instruction that describes the task: ### Input: Reduce the size of a routing table by merging together entries where possible and by removing any remaining default routes. .. warning:: The input routing table *must* also include entries which could be removed and replaced ...
def trace_function(module, function, tracer=tracer): """ Traces given module function using given tracer. :param module: Module of the function. :type module: object :param function: Function to trace. :type function: object :param tracer: Tracer. :type tracer: object :return: Defin...
Traces given module function using given tracer. :param module: Module of the function. :type module: object :param function: Function to trace. :type function: object :param tracer: Tracer. :type tracer: object :return: Definition success. :rtype: bool
Below is the the instruction that describes the task: ### Input: Traces given module function using given tracer. :param module: Module of the function. :type module: object :param function: Function to trace. :type function: object :param tracer: Tracer. :type tracer: object :return: D...
def tmp_file_path(self): """ :return: :rtype: str """ return os.path.normpath(os.path.join( TMP_DIR, self.filename ))
:return: :rtype: str
Below is the the instruction that describes the task: ### Input: :return: :rtype: str ### Response: def tmp_file_path(self): """ :return: :rtype: str """ return os.path.normpath(os.path.join( TMP_DIR, self.filename ))
def show_system_monitor_output_switch_status_switch_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_system_monitor = ET.Element("show_system_monitor") config = show_system_monitor output = ET.SubElement(show_system_monitor, "output") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def show_system_monitor_output_switch_status_switch_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_system_monitor = ET.Element("show_system_monitor...
def str_to_obj(cls, file_path=None, text='', columns=None, remove_empty_rows=True, key_on=None, row_columns=None, deliminator='\t', eval_cells=True): """ This will convert text file or text to a seaborn table and return it :param file_path: str of th...
This will convert text file or text to a seaborn table and return it :param file_path: str of the path to the file :param text: str of the csv text :param columns: list of str of columns to use :param row_columns: list of str of columns in data but not to use :param remov...
Below is the the instruction that describes the task: ### Input: This will convert text file or text to a seaborn table and return it :param file_path: str of the path to the file :param text: str of the csv text :param columns: list of str of columns to use :param row_column...
def number_range_inclusive(min, max, type=float): """ Return a value check function which raises a ValueError if the supplied value when cast as `type` is less than `min` or greater than `max`. """ def checker(v): if type(v) < min or type(v) > max: raise ValueError(v) retur...
Return a value check function which raises a ValueError if the supplied value when cast as `type` is less than `min` or greater than `max`.
Below is the the instruction that describes the task: ### Input: Return a value check function which raises a ValueError if the supplied value when cast as `type` is less than `min` or greater than `max`. ### Response: def number_range_inclusive(min, max, type=float): """ Return a value check function ...
def get_objective_lookup_session(self): """Gets the OsidSession associated with the objective lookup service. return: (osid.learning.ObjectiveLookupSession) - an ObjectiveLookupSession raise: OperationFailed - unable to complete request raise: Unimplemented - s...
Gets the OsidSession associated with the objective lookup service. return: (osid.learning.ObjectiveLookupSession) - an ObjectiveLookupSession raise: OperationFailed - unable to complete request raise: Unimplemented - supports_objective_lookup() is false complia...
Below is the the instruction that describes the task: ### Input: Gets the OsidSession associated with the objective lookup service. return: (osid.learning.ObjectiveLookupSession) - an ObjectiveLookupSession raise: OperationFailed - unable to complete request raise: ...
def save_driver_script(driver, script_save=None): # noqa: E501 """Save a script Save a script # noqa: E501 :param driver: The driver to use for the request. ie. github :type driver: str :param script_save: The data needed to save this script :type script_save: dict | bytes :rtype: Respon...
Save a script Save a script # noqa: E501 :param driver: The driver to use for the request. ie. github :type driver: str :param script_save: The data needed to save this script :type script_save: dict | bytes :rtype: Response
Below is the the instruction that describes the task: ### Input: Save a script Save a script # noqa: E501 :param driver: The driver to use for the request. ie. github :type driver: str :param script_save: The data needed to save this script :type script_save: dict | bytes :rtype: Response...
async def connect_model(self, model_name=None): """Connect to a model by name. If either controller or model parts of the name are empty, the current controller and/or model will be used. :param str model: <controller>:<model> """ try: controller_name, model...
Connect to a model by name. If either controller or model parts of the name are empty, the current controller and/or model will be used. :param str model: <controller>:<model>
Below is the the instruction that describes the task: ### Input: Connect to a model by name. If either controller or model parts of the name are empty, the current controller and/or model will be used. :param str model: <controller>:<model> ### Response: async def connect_model(self, model...
def _parse_domain_caps(caps): ''' Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :p...
Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the given emulator binary :param arch: return the capabilities for the...
Below is the the instruction that describes the task: ### Input: Parse the XML document of domain capabilities into a structure. Return the domain capabilities given an emulator, architecture, machine or virtualization type. .. versionadded:: 2019.2.0 :param emulator: return the capabilities for the g...
def init(): """Initialize the pipeline in maya so everything works Init environment and load plugins. This also creates the initial Jukebox Menu entry. :returns: None :rtype: None :raises: None """ main.init_environment() pluginpath = os.pathsep.join((os.environ.get('JUKEBOX_PLUGIN...
Initialize the pipeline in maya so everything works Init environment and load plugins. This also creates the initial Jukebox Menu entry. :returns: None :rtype: None :raises: None
Below is the the instruction that describes the task: ### Input: Initialize the pipeline in maya so everything works Init environment and load plugins. This also creates the initial Jukebox Menu entry. :returns: None :rtype: None :raises: None ### Response: def init(): """Initialize the p...
def cmdline(argv=sys.argv[1:]): """ Script for rebasing a text file """ parser = ArgumentParser( description='Rebase a text from his stop words') parser.add_argument('language', help='The language used to rebase') parser.add_argument('source', help='Text file to rebase') options = pa...
Script for rebasing a text file
Below is the the instruction that describes the task: ### Input: Script for rebasing a text file ### Response: def cmdline(argv=sys.argv[1:]): """ Script for rebasing a text file """ parser = ArgumentParser( description='Rebase a text from his stop words') parser.add_argument('language'...
def merge_all(rasters, roi=None, dest_resolution=None, merge_strategy=MergeStrategy.UNION, shape=None, ul_corner=None, crs=None, pixel_strategy=PixelStrategy.FIRST, resampling=Resampling.nearest): """Merge a list of rasters, cropping by a region of interest. There are cases that t...
Merge a list of rasters, cropping by a region of interest. There are cases that the roi is not precise enough for this cases one can use, the upper left corner the shape and crs to precisely define the roi. When roi is provided the ul_corner, shape and crs are ignored
Below is the the instruction that describes the task: ### Input: Merge a list of rasters, cropping by a region of interest. There are cases that the roi is not precise enough for this cases one can use, the upper left corner the shape and crs to precisely define the roi. When roi is provided th...
def parse_response(self, raw): """ Format the requested data model into a dictionary of DataFrames and a criteria map DataFrame. Take data returned by a requests.get call to Earthref. Parameters ---------- raw: 'requests.models.Response' Returns ...
Format the requested data model into a dictionary of DataFrames and a criteria map DataFrame. Take data returned by a requests.get call to Earthref. Parameters ---------- raw: 'requests.models.Response' Returns --------- data_model : dictionary of DataFr...
Below is the the instruction that describes the task: ### Input: Format the requested data model into a dictionary of DataFrames and a criteria map DataFrame. Take data returned by a requests.get call to Earthref. Parameters ---------- raw: 'requests.models.Response' ...
def Process(self, fs_msg, context): """Processes a single fleetspeak message.""" try: if fs_msg.message_type == "GrrMessage": grr_message = rdf_flows.GrrMessage.FromSerializedString( fs_msg.data.value) self._ProcessGRRMessages(fs_msg.source.client_id, [grr_message]) elif ...
Processes a single fleetspeak message.
Below is the the instruction that describes the task: ### Input: Processes a single fleetspeak message. ### Response: def Process(self, fs_msg, context): """Processes a single fleetspeak message.""" try: if fs_msg.message_type == "GrrMessage": grr_message = rdf_flows.GrrMessage.FromSerialized...
def set_disk0(self, disk0): """ Sets the size (MB) for PCMCIA disk0. :param disk0: disk0 size (integer) """ yield from self._hypervisor.send('vm set_disk0 "{name}" {disk0}'.format(name=self._name, disk0=disk0)) log.info('Router "{name}" [{id}]: disk0 updated from {old_...
Sets the size (MB) for PCMCIA disk0. :param disk0: disk0 size (integer)
Below is the the instruction that describes the task: ### Input: Sets the size (MB) for PCMCIA disk0. :param disk0: disk0 size (integer) ### Response: def set_disk0(self, disk0): """ Sets the size (MB) for PCMCIA disk0. :param disk0: disk0 size (integer) """ yield...
def _required_attribute(element, name, default): """ Add attribute with default value to element if it doesn't already exist. """ if element.get(name) is None: element.set(name, default)
Add attribute with default value to element if it doesn't already exist.
Below is the the instruction that describes the task: ### Input: Add attribute with default value to element if it doesn't already exist. ### Response: def _required_attribute(element, name, default): """ Add attribute with default value to element if it doesn't already exist. """ if element.get(na...
def eval_upto(self, e, n, cast_to=None, **kwargs): """ Evaluate an expression, using the solver if necessary. Returns primitives as specified by the `cast_to` parameter. Only certain primitives are supported, check the implementation of `_cast_to` to see which ones. :param e: the expres...
Evaluate an expression, using the solver if necessary. Returns primitives as specified by the `cast_to` parameter. Only certain primitives are supported, check the implementation of `_cast_to` to see which ones. :param e: the expression :param n: the number of desired solutions :param e...
Below is the the instruction that describes the task: ### Input: Evaluate an expression, using the solver if necessary. Returns primitives as specified by the `cast_to` parameter. Only certain primitives are supported, check the implementation of `_cast_to` to see which ones. :param e: the expressi...
def _wfdb_fmt(bit_res, single_fmt=True): """ Return the most suitable wfdb format(s) to use given signal resolutions. Parameters ---------- bit_res : int, or list The resolution of the signal, or a list of resolutions, in bits. single_fmt : bool, optional Whether to return t...
Return the most suitable wfdb format(s) to use given signal resolutions. Parameters ---------- bit_res : int, or list The resolution of the signal, or a list of resolutions, in bits. single_fmt : bool, optional Whether to return the format for the maximum resolution signal. Ret...
Below is the the instruction that describes the task: ### Input: Return the most suitable wfdb format(s) to use given signal resolutions. Parameters ---------- bit_res : int, or list The resolution of the signal, or a list of resolutions, in bits. single_fmt : bool, optional Whe...
def _set_mpls_reopt_lsp(self, v, load=False): """ Setter method for mpls_reopt_lsp, mapped from YANG variable /brocade_mpls_rpc/mpls_reopt_lsp (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_mpls_reopt_lsp is considered as a private method. Backends looking to ...
Setter method for mpls_reopt_lsp, mapped from YANG variable /brocade_mpls_rpc/mpls_reopt_lsp (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_mpls_reopt_lsp is considered as a private method. Backends looking to populate this variable should do so via calling thisOb...
Below is the the instruction that describes the task: ### Input: Setter method for mpls_reopt_lsp, mapped from YANG variable /brocade_mpls_rpc/mpls_reopt_lsp (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_mpls_reopt_lsp is considered as a private method. Backends ...
def _evaluate(self,x): ''' Returns the level of the function at each value in x as the minimum among all of the functions. Only called internally by HARKinterpolator1D.__call__. ''' if _isscalar(x): y = np.nanmin([f(x) for f in self.functions]) else: ...
Returns the level of the function at each value in x as the minimum among all of the functions. Only called internally by HARKinterpolator1D.__call__.
Below is the the instruction that describes the task: ### Input: Returns the level of the function at each value in x as the minimum among all of the functions. Only called internally by HARKinterpolator1D.__call__. ### Response: def _evaluate(self,x): ''' Returns the level of the function...
def get_creation_time(self): """stub""" ct = self.my_osid_object._my_map['creationTime'] return DateTime(ct.year, ct.month, ct.day, ct.hour, ct.minute, ct.second, ...
stub
Below is the the instruction that describes the task: ### Input: stub ### Response: def get_creation_time(self): """stub""" ct = self.my_osid_object._my_map['creationTime'] return DateTime(ct.year, ct.month, ct.day, ct....
def _cartesian_to_spherical(cls, coord, center): """Cartesian to Spherical conversion .. warning:: The spherical form is equatorial, not zenithal """ x, y, z, vx, vy, vz = coord r = np.linalg.norm(coord[:3]) phi = arcsin(z / r) theta = arctan2(y, x) r_do...
Cartesian to Spherical conversion .. warning:: The spherical form is equatorial, not zenithal
Below is the the instruction that describes the task: ### Input: Cartesian to Spherical conversion .. warning:: The spherical form is equatorial, not zenithal ### Response: def _cartesian_to_spherical(cls, coord, center): """Cartesian to Spherical conversion .. warning:: The spherical for...
def p_cpf_list(self, p): '''cpf_list : cpf_list cpf_def | empty''' if p[1] is None: p[0] = [] else: p[1].append(p[2]) p[0] = p[1]
cpf_list : cpf_list cpf_def | empty
Below is the the instruction that describes the task: ### Input: cpf_list : cpf_list cpf_def | empty ### Response: def p_cpf_list(self, p): '''cpf_list : cpf_list cpf_def | empty''' if p[1] is None: p[0] = [] else: p[1].append(...
def _compute(self, inputs, outputs): """ Run one iteration of SPRegion's compute """ #if self.topDownMode and (not 'topDownIn' in inputs): # raise RuntimeError("The input topDownIn must be linked in if " # "topDownMode is True") if self._sfdr is None: raise Runti...
Run one iteration of SPRegion's compute
Below is the the instruction that describes the task: ### Input: Run one iteration of SPRegion's compute ### Response: def _compute(self, inputs, outputs): """ Run one iteration of SPRegion's compute """ #if self.topDownMode and (not 'topDownIn' in inputs): # raise RuntimeError("The input top...
def connectTo(self, remoteRouteName): """ Set the name of the route which will be added to outgoing boxes. """ self.remoteRouteName = remoteRouteName # This route must not be started before its router is started. If # sender is None, then the router is not started. When...
Set the name of the route which will be added to outgoing boxes.
Below is the the instruction that describes the task: ### Input: Set the name of the route which will be added to outgoing boxes. ### Response: def connectTo(self, remoteRouteName): """ Set the name of the route which will be added to outgoing boxes. """ self.remoteRouteName = remot...
def cmd(self): """ Determine the final CMD instruction, if any, in the final build stage. CMDs from earlier stages are ignored. :return: value of final stage CMD instruction """ value = None for insndesc in self.structure: if insndesc['instruction'] ==...
Determine the final CMD instruction, if any, in the final build stage. CMDs from earlier stages are ignored. :return: value of final stage CMD instruction
Below is the the instruction that describes the task: ### Input: Determine the final CMD instruction, if any, in the final build stage. CMDs from earlier stages are ignored. :return: value of final stage CMD instruction ### Response: def cmd(self): """ Determine the final CMD instru...
def t_quotedvar_ENCAPSED_AND_WHITESPACE(t): r'( [^"\\${] | \\(.|\n) | \$(?![A-Za-z_{]) | \{(?!\$) )+' t.lexer.lineno += t.value.count("\n") t.lexer.pop_state() return t
r'( [^"\\${] | \\(.|\n) | \$(?![A-Za-z_{]) | \{(?!\$) )+
Below is the the instruction that describes the task: ### Input: r'( [^"\\${] | \\(.|\n) | \$(?![A-Za-z_{]) | \{(?!\$) )+ ### Response: def t_quotedvar_ENCAPSED_AND_WHITESPACE(t): r'( [^"\\${] | \\(.|\n) | \$(?![A-Za-z_{]) | \{(?!\$) )+' t.lexer.lineno += t.value.count("\n") t.lexer.pop_state() ret...
def checksum_chain(self): """ Returns a list of checksums joined with "::". """ checksums = [] for certificate in self.certificates: checksums.append(certificate.checksum) return "::".join(checksums)
Returns a list of checksums joined with "::".
Below is the the instruction that describes the task: ### Input: Returns a list of checksums joined with "::". ### Response: def checksum_chain(self): """ Returns a list of checksums joined with "::". """ checksums = [] for certificate in self.certificates: chec...
def setActivations(self, value): """ Sets all activations to the value of the argument. Value should be in the range [0,1]. """ #if self.verify and not self.activationSet == 0: # raise LayerError, \ # ('Activation flag not reset. Activations may have been set ...
Sets all activations to the value of the argument. Value should be in the range [0,1].
Below is the the instruction that describes the task: ### Input: Sets all activations to the value of the argument. Value should be in the range [0,1]. ### Response: def setActivations(self, value): """ Sets all activations to the value of the argument. Value should be in the range [0,1]. "...
def log(db, job_id, timestamp, level, process, message): """ Write a log record in the database. :param db: a :class:`openquake.server.dbapi.Db` instance :param job_id: a job ID :param timestamp: timestamp to store in the log record :param level: logging level to...
Write a log record in the database. :param db: a :class:`openquake.server.dbapi.Db` instance :param job_id: a job ID :param timestamp: timestamp to store in the log record :param level: logging level to store in the log record :param process: process ID to st...
Below is the the instruction that describes the task: ### Input: Write a log record in the database. :param db: a :class:`openquake.server.dbapi.Db` instance :param job_id: a job ID :param timestamp: timestamp to store in the log record :param level: logging level to...
def plot_slnp(fignum, SiteRec, datablock, key): """ plots lines and planes on a great circle with alpha 95 and mean deprecated (used in pmagplotlib) """ # make the stereonet plt.figure(num=fignum) plot_net(fignum) s = SiteRec['er_site_name'] # # plot on the data # coord = SiteRec['sit...
plots lines and planes on a great circle with alpha 95 and mean deprecated (used in pmagplotlib)
Below is the the instruction that describes the task: ### Input: plots lines and planes on a great circle with alpha 95 and mean deprecated (used in pmagplotlib) ### Response: def plot_slnp(fignum, SiteRec, datablock, key): """ plots lines and planes on a great circle with alpha 95 and mean depre...
def host_from_uri(uri): """Extract hostname and port from URI. Will use default port for HTTP and HTTPS if none is present in the URI. """ default_ports = { 'HTTP': '80', 'HTTPS': '443', } sch, netloc, path, par, query, fra = urlparse(uri) if ':' in netloc: netloc, ...
Extract hostname and port from URI. Will use default port for HTTP and HTTPS if none is present in the URI.
Below is the the instruction that describes the task: ### Input: Extract hostname and port from URI. Will use default port for HTTP and HTTPS if none is present in the URI. ### Response: def host_from_uri(uri): """Extract hostname and port from URI. Will use default port for HTTP and HTTPS if none is...
def CropObservations(env): """" Crops the visual observations of an environment so that they only contain the game screen. Removes anything outside the game that usually belongs to universe (browser borders and so on). """ if env.spec.tags.get('flashgames', False): spec = runtime_spec('flash...
Crops the visual observations of an environment so that they only contain the game screen. Removes anything outside the game that usually belongs to universe (browser borders and so on).
Below is the the instruction that describes the task: ### Input: Crops the visual observations of an environment so that they only contain the game screen. Removes anything outside the game that usually belongs to universe (browser borders and so on). ### Response: def CropObservations(env): """" Crops...
def combining_goal(state): """ Check if two Cubies are combined on the U face. """ ((corner, edge), (L, U, F, D, R, B)) = state if "U" not in corner or "U" not in edge: return False if set(edge).issubset(set(corner)): return True elif set(edge.facings.keys()).issu...
Check if two Cubies are combined on the U face.
Below is the the instruction that describes the task: ### Input: Check if two Cubies are combined on the U face. ### Response: def combining_goal(state): """ Check if two Cubies are combined on the U face. """ ((corner, edge), (L, U, F, D, R, B)) = state if "U" not in corner...
def get(self, name, default="", parent_search=False, multikeys_search=False, __settings_temp=None, __rank_recursion=0): """ Récupération d'une configuration le paramètre ```name``` peut être soit un nom ou un chemin vers la valeur (séparateur /) ```parent_search``` est le boolean qui indique si on doi...
Récupération d'une configuration le paramètre ```name``` peut être soit un nom ou un chemin vers la valeur (séparateur /) ```parent_search``` est le boolean qui indique si on doit chercher la valeur dans la hiérarchie plus haute. Si la chaîne "/document/host/val" retourne None, on recherche dans "/doc...
Below is the the instruction that describes the task: ### Input: Récupération d'une configuration le paramètre ```name``` peut être soit un nom ou un chemin vers la valeur (séparateur /) ```parent_search``` est le boolean qui indique si on doit chercher la valeur dans la hiérarchie plus haute. Si la ...
def list_kubernetes_roles(self, mount_point='kubernetes'): """GET /auth/<mount_point>/role?list=true :param mount_point: The "path" the k8s auth backend was mounted on. Vault currently defaults to "kubernetes". :type mount_point: str. :return: Parsed JSON response from the list roles GE...
GET /auth/<mount_point>/role?list=true :param mount_point: The "path" the k8s auth backend was mounted on. Vault currently defaults to "kubernetes". :type mount_point: str. :return: Parsed JSON response from the list roles GET request. :rtype: dict.
Below is the the instruction that describes the task: ### Input: GET /auth/<mount_point>/role?list=true :param mount_point: The "path" the k8s auth backend was mounted on. Vault currently defaults to "kubernetes". :type mount_point: str. :return: Parsed JSON response from the list roles GET...
def _i2c_idle(self): """Set I2C signals to idle state with SCL and SDA at a high value. Must be called within a transaction start/end. """ self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.HIGH}, write=False) self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
Set I2C signals to idle state with SCL and SDA at a high value. Must be called within a transaction start/end.
Below is the the instruction that describes the task: ### Input: Set I2C signals to idle state with SCL and SDA at a high value. Must be called within a transaction start/end. ### Response: def _i2c_idle(self): """Set I2C signals to idle state with SCL and SDA at a high value. Must be calle...
def indx_table(node_dict, tbl_mode=False): """Print Table for dict=formatted list conditionally include numbers.""" nt = PrettyTable() nt.header = False nt.padding_width = 2 nt.border = False clr_num = C_TI + "NUM" clr_name = C_TI + "NAME" clr_state = "STATE" + C_NORM t_lu = {True: [...
Print Table for dict=formatted list conditionally include numbers.
Below is the the instruction that describes the task: ### Input: Print Table for dict=formatted list conditionally include numbers. ### Response: def indx_table(node_dict, tbl_mode=False): """Print Table for dict=formatted list conditionally include numbers.""" nt = PrettyTable() nt.header = False ...
def _fastfood_show(args): """Run on `fastfood show`.""" template_pack = pack.TemplatePack(args.template_pack) if args.stencil_set: stencil_set = template_pack.load_stencil_set(args.stencil_set) print("Stencil Set %s:" % args.stencil_set) print(' Stencils:') for stencil in st...
Run on `fastfood show`.
Below is the the instruction that describes the task: ### Input: Run on `fastfood show`. ### Response: def _fastfood_show(args): """Run on `fastfood show`.""" template_pack = pack.TemplatePack(args.template_pack) if args.stencil_set: stencil_set = template_pack.load_stencil_set(args.stencil_set...
def pivot_by_group( df, variable, value, new_columns, groups, id_cols=None ): """ Pivot a dataframe by group of variables --- ### Parameters *mandatory :* * `variable` (*str*): name of the column used to create the groups. * `value` (*str*):...
Pivot a dataframe by group of variables --- ### Parameters *mandatory :* * `variable` (*str*): name of the column used to create the groups. * `value` (*str*): name of the column containing the value to fill the pivoted df. * `new_columns` (*list of str*): names of the new columns. * `gro...
Below is the the instruction that describes the task: ### Input: Pivot a dataframe by group of variables --- ### Parameters *mandatory :* * `variable` (*str*): name of the column used to create the groups. * `value` (*str*): name of the column containing the value to fill the pivoted df. ...
def POST_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ """ Edit a task """ if not id_checker(taskid) or not id_checker(courseid): raise Exception("Invalid course/task id") course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False) data...
Edit a task
Below is the the instruction that describes the task: ### Input: Edit a task ### Response: def POST_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ """ Edit a task """ if not id_checker(taskid) or not id_checker(courseid): raise Exception("Invalid course/task id") ...
def parse_tstv_summary(self): """ Create the HTML for the TsTv summary plot. """ self.vcftools_tstv_summary = dict() for f in self.find_log_files('vcftools/tstv_summary', filehandles=True): d = {} for line in f['f'].readlines()[1:]: # don't add the header line (first row...
Create the HTML for the TsTv summary plot.
Below is the the instruction that describes the task: ### Input: Create the HTML for the TsTv summary plot. ### Response: def parse_tstv_summary(self): """ Create the HTML for the TsTv summary plot. """ self.vcftools_tstv_summary = dict() for f in self.find_log_files('vcftools/tstv_summary...
def accept_quality(accept, default=1): """Separates out the quality score from the accepted content_type""" quality = default if accept and ";" in accept: accept, rest = accept.split(";", 1) accept_quality = RE_ACCEPT_QUALITY.search(rest) if accept_quality: quality = floa...
Separates out the quality score from the accepted content_type
Below is the the instruction that describes the task: ### Input: Separates out the quality score from the accepted content_type ### Response: def accept_quality(accept, default=1): """Separates out the quality score from the accepted content_type""" quality = default if accept and ";" in accept: ...
def build_span_analyzer(document, vec): """ Return an analyzer and the preprocessed doc. Analyzer will yield pairs of spans and feature, where spans are pairs of indices into the preprocessed doc. The idea here is to do minimal preprocessing so that we can still recover the same features as sklearn ...
Return an analyzer and the preprocessed doc. Analyzer will yield pairs of spans and feature, where spans are pairs of indices into the preprocessed doc. The idea here is to do minimal preprocessing so that we can still recover the same features as sklearn vectorizers, but with spans, that will allow us ...
Below is the the instruction that describes the task: ### Input: Return an analyzer and the preprocessed doc. Analyzer will yield pairs of spans and feature, where spans are pairs of indices into the preprocessed doc. The idea here is to do minimal preprocessing so that we can still recover the same fea...
def put(self, key, value, minutes): """ Store an item in the cache for a given number of minutes. :param key: The cache key :type key: str :param value: The cache value :type value: mixed :param minutes: The lifetime in minutes of the cached value :type...
Store an item in the cache for a given number of minutes. :param key: The cache key :type key: str :param value: The cache value :type value: mixed :param minutes: The lifetime in minutes of the cached value :type minutes: int
Below is the the instruction that describes the task: ### Input: Store an item in the cache for a given number of minutes. :param key: The cache key :type key: str :param value: The cache value :type value: mixed :param minutes: The lifetime in minutes of the cached value ...
def can_create_objective_bank_with_record_types(self, objective_bank_record_types): """Tests if this user can create a single ``ObjectiveBank`` using the desired record types. While ``LearningManager.getObjectiveBankRecordTypes()`` can be used to examine which records are supported, this method...
Tests if this user can create a single ``ObjectiveBank`` using the desired record types. While ``LearningManager.getObjectiveBankRecordTypes()`` can be used to examine which records are supported, this method tests which record(s) are required for creating a specific ``ObjectiveBank``. ...
Below is the the instruction that describes the task: ### Input: Tests if this user can create a single ``ObjectiveBank`` using the desired record types. While ``LearningManager.getObjectiveBankRecordTypes()`` can be used to examine which records are supported, this method tests which recor...
def show(self, format='png', as_data=False): '''Returns an Image object of the current surface. Used for displaying output in Jupyter notebooks. Adapted from the cairo-jupyter project.''' from io import BytesIO b = BytesIO() if format == 'png': from IPython.display...
Returns an Image object of the current surface. Used for displaying output in Jupyter notebooks. Adapted from the cairo-jupyter project.
Below is the the instruction that describes the task: ### Input: Returns an Image object of the current surface. Used for displaying output in Jupyter notebooks. Adapted from the cairo-jupyter project. ### Response: def show(self, format='png', as_data=False): '''Returns an Image object of the curr...
def range_is_obj(rng, rdfclass): """ Test to see if range for the class should be an object or a litteral """ if rng == 'rdfs_Literal': return False if hasattr(rdfclass, rng): mod_class = getattr(rdfclass, rng) for item in mod_class.cls_defs['rdf_type']: try: ...
Test to see if range for the class should be an object or a litteral
Below is the the instruction that describes the task: ### Input: Test to see if range for the class should be an object or a litteral ### Response: def range_is_obj(rng, rdfclass): """ Test to see if range for the class should be an object or a litteral """ if rng == 'rdfs_Literal': ret...
def _translate_sext(self, oprnd1, oprnd2, oprnd3): """Return a formula representation of a SEXT instruction. """ assert oprnd1.size and oprnd3.size op1_var = self._translate_src_oprnd(oprnd1) op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3) if oprnd3.size > ...
Return a formula representation of a SEXT instruction.
Below is the the instruction that describes the task: ### Input: Return a formula representation of a SEXT instruction. ### Response: def _translate_sext(self, oprnd1, oprnd2, oprnd3): """Return a formula representation of a SEXT instruction. """ assert oprnd1.size and oprnd3.size ...
def prune_tour(self, tour, cpus): """ Test deleting each contig and check the delta_score; tour here must be an array of ints. """ while True: tour_score, = self.evaluate_tour_M(tour) logging.debug("Starting score: {}".format(tour_score)) active_sizes ...
Test deleting each contig and check the delta_score; tour here must be an array of ints.
Below is the the instruction that describes the task: ### Input: Test deleting each contig and check the delta_score; tour here must be an array of ints. ### Response: def prune_tour(self, tour, cpus): """ Test deleting each contig and check the delta_score; tour here must be an array of in...
def log_errors(f, self, *args, **kwargs): """decorator to log unhandled exceptions raised in a method. For use wrapping on_recv callbacks, so that exceptions do not cause the stream to be closed. """ try: return f(self, *args, **kwargs) except Exception: self.log.error("Unca...
decorator to log unhandled exceptions raised in a method. For use wrapping on_recv callbacks, so that exceptions do not cause the stream to be closed.
Below is the the instruction that describes the task: ### Input: decorator to log unhandled exceptions raised in a method. For use wrapping on_recv callbacks, so that exceptions do not cause the stream to be closed. ### Response: def log_errors(f, self, *args, **kwargs): """decorator to log unhand...
def _set_task_uuid(self, dependencies): """Adds universally unique user ids (UUID) to each task of the workflow. :param dependencies: The list of dependencies between tasks defining the computational graph :type dependencies: list(Dependency) :return: A dictionary mapping UUID to d...
Adds universally unique user ids (UUID) to each task of the workflow. :param dependencies: The list of dependencies between tasks defining the computational graph :type dependencies: list(Dependency) :return: A dictionary mapping UUID to dependencies :rtype: dict(str: Dependency)
Below is the the instruction that describes the task: ### Input: Adds universally unique user ids (UUID) to each task of the workflow. :param dependencies: The list of dependencies between tasks defining the computational graph :type dependencies: list(Dependency) :return: A dictionary ...
def send_keys(key_string): """ sends the text or keys to the active application using shell Note, that the imp module shows deprecation warning. Examples: shell.SendKeys("^a") # CTRL+A shell.SendKeys("{DELETE}") # Delete key shell.SendKeys("hello this is a lot of text with a //"...
sends the text or keys to the active application using shell Note, that the imp module shows deprecation warning. Examples: shell.SendKeys("^a") # CTRL+A shell.SendKeys("{DELETE}") # Delete key shell.SendKeys("hello this is a lot of text with a //")
Below is the the instruction that describes the task: ### Input: sends the text or keys to the active application using shell Note, that the imp module shows deprecation warning. Examples: shell.SendKeys("^a") # CTRL+A shell.SendKeys("{DELETE}") # Delete key shell.SendKeys("hello th...
def download(self, resource_id): """Update the request URI to download the document for this resource. Args: resource_id (integer): The group id. """ self.resource_id(str(resource_id)) self._request_uri = '{}/download'.format(self._request_uri)
Update the request URI to download the document for this resource. Args: resource_id (integer): The group id.
Below is the the instruction that describes the task: ### Input: Update the request URI to download the document for this resource. Args: resource_id (integer): The group id. ### Response: def download(self, resource_id): """Update the request URI to download the document for this reso...
def queryAll(self, *args, **kwargs): """ Returns a :class:`Deferred` object which will have its callback invoked with a :class:`BatchedView` when the results are complete. Parameters follow conventions of :meth:`~couchbase.bucket.Bucket.query`. Example:: d = ...
Returns a :class:`Deferred` object which will have its callback invoked with a :class:`BatchedView` when the results are complete. Parameters follow conventions of :meth:`~couchbase.bucket.Bucket.query`. Example:: d = cb.queryAll("beer", "brewery_beers") def on_all...
Below is the the instruction that describes the task: ### Input: Returns a :class:`Deferred` object which will have its callback invoked with a :class:`BatchedView` when the results are complete. Parameters follow conventions of :meth:`~couchbase.bucket.Bucket.query`. Example:: ...
def getInterval(self, alpha): """ Evaluate the interval corresponding to a C.L. of (1-alpha)%. Parameters ---------- alpha : limit confidence level. """ dlnl = twosided_cl_to_dlnl(1.0 - alpha) lo_lim = self.getDeltaLogLike(dlnl, upper=False) hi_lim = self...
Evaluate the interval corresponding to a C.L. of (1-alpha)%. Parameters ---------- alpha : limit confidence level.
Below is the the instruction that describes the task: ### Input: Evaluate the interval corresponding to a C.L. of (1-alpha)%. Parameters ---------- alpha : limit confidence level. ### Response: def getInterval(self, alpha): """ Evaluate the interval corresponding to a C.L. of (1-al...
def get_series(self, series): """ Returns a census series API handler. """ if series == "acs1": return self.census.acs1dp elif series == "acs5": return self.census.acs5 elif series == "sf1": return self.census.sf1 elif series ==...
Returns a census series API handler.
Below is the the instruction that describes the task: ### Input: Returns a census series API handler. ### Response: def get_series(self, series): """ Returns a census series API handler. """ if series == "acs1": return self.census.acs1dp elif series == "acs5": ...
def as_text(self, max_rows=0, sep=" | "): """Format table as text.""" if not max_rows or max_rows > self.num_rows: max_rows = self.num_rows omitted = max(0, self.num_rows - max_rows) labels = self._columns.keys() fmts = self._get_column_formatters(max_rows, False) ...
Format table as text.
Below is the the instruction that describes the task: ### Input: Format table as text. ### Response: def as_text(self, max_rows=0, sep=" | "): """Format table as text.""" if not max_rows or max_rows > self.num_rows: max_rows = self.num_rows omitted = max(0, self.num_rows - max_r...