code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def evalop(op,left,right): "this takes evaluated left and right (i.e. values not expressions)" if op in ('=','!=','>','<'): return threevl.ThreeVL.compare(op,left,right) elif op in ('+','-','*','/'): # todo: does arithmetic require threevl? if op=='/': raise NotImplementedError('todo: spec about int/float div...
this takes evaluated left and right (i.e. values not expressions)
Below is the the instruction that describes the task: ### Input: this takes evaluated left and right (i.e. values not expressions) ### Response: def evalop(op,left,right): "this takes evaluated left and right (i.e. values not expressions)" if op in ('=','!=','>','<'): return threevl.ThreeVL.compare(op,left,rig...
def move_edge_source(self, edge_id, node_a, node_b): """Moves an edge originating from node_a so that it originates from node_b.""" # Grab the edge edge = self.get_edge(edge_id) # Alter the vertices edge['vertices'] = (node_b, edge['vertices'][1]) # Remove the edge from...
Moves an edge originating from node_a so that it originates from node_b.
Below is the the instruction that describes the task: ### Input: Moves an edge originating from node_a so that it originates from node_b. ### Response: def move_edge_source(self, edge_id, node_a, node_b): """Moves an edge originating from node_a so that it originates from node_b.""" # Grab the edge...
def gen_matches(self, word): """Generate a sequence of possible completions for ``word``. :param word: the word to complete """ if word.startswith("$"): for match in self.gen_variable_completions(word, os.environ): yield match else: head,...
Generate a sequence of possible completions for ``word``. :param word: the word to complete
Below is the the instruction that describes the task: ### Input: Generate a sequence of possible completions for ``word``. :param word: the word to complete ### Response: def gen_matches(self, word): """Generate a sequence of possible completions for ``word``. :param word: the word to com...
def get_function_from_settings(settings_key): """Gets a function from the string path defined in a settings file. Example: # my_app/my_file.py def some_function(): # do something pass # settings.py SOME_FUNCTION = 'my_app.my_file.some_function' > get_function_from_setting...
Gets a function from the string path defined in a settings file. Example: # my_app/my_file.py def some_function(): # do something pass # settings.py SOME_FUNCTION = 'my_app.my_file.some_function' > get_function_from_settings('SOME_FUNCTION') <function my_app.my_file.some_...
Below is the the instruction that describes the task: ### Input: Gets a function from the string path defined in a settings file. Example: # my_app/my_file.py def some_function(): # do something pass # settings.py SOME_FUNCTION = 'my_app.my_file.some_function' > get_funct...
def update_build_configuration_sets(self, id, **kwargs): """ This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): ...
This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.update_build_co...
Below is the the instruction that describes the task: ### Input: This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> ...
def divConn (self, preCellsTags, postCellsTags, connParam): from .. import sim ''' Generates connections between all pre and post-syn cells based on probability values''' if sim.cfg.verbose: print('Generating set of divergent connections (rule: %s) ...' % (connParam['label'])) # get list of param...
Generates connections between all pre and post-syn cells based on probability values
Below is the the instruction that describes the task: ### Input: Generates connections between all pre and post-syn cells based on probability values ### Response: def divConn (self, preCellsTags, postCellsTags, connParam): from .. import sim ''' Generates connections between all pre and post-syn cells ba...
def _fetch_features(self): """ Retrieves a new page of features from Geopedia """ if self.next_page_url is None: return response = get_json(self.next_page_url, post_values=self.query, headers=self.gpd_session.session_headers) self.features.extend(response['features'...
Retrieves a new page of features from Geopedia
Below is the the instruction that describes the task: ### Input: Retrieves a new page of features from Geopedia ### Response: def _fetch_features(self): """ Retrieves a new page of features from Geopedia """ if self.next_page_url is None: return response = get_json(self...
def getDatastream(self, pid, dsID, asOfDateTime=None, validateChecksum=False): """Get information about a single datastream on a Fedora object; optionally, get information for the version of the datastream as of a particular date time. :param pid: object pid :param dsID: datastream id ...
Get information about a single datastream on a Fedora object; optionally, get information for the version of the datastream as of a particular date time. :param pid: object pid :param dsID: datastream id :param asOfDateTime: optional datetime; ``must`` be a non-naive datetime ...
Below is the the instruction that describes the task: ### Input: Get information about a single datastream on a Fedora object; optionally, get information for the version of the datastream as of a particular date time. :param pid: object pid :param dsID: datastream id :param asOfDat...
def process_node(e): """ Process a node element entry into a dict suitable for going into a Pandas DataFrame. Parameters ---------- e : dict individual node element in downloaded OSM json Returns ------- node : dict """ node = {'id': e['id'], 'lat': e['...
Process a node element entry into a dict suitable for going into a Pandas DataFrame. Parameters ---------- e : dict individual node element in downloaded OSM json Returns ------- node : dict
Below is the the instruction that describes the task: ### Input: Process a node element entry into a dict suitable for going into a Pandas DataFrame. Parameters ---------- e : dict individual node element in downloaded OSM json Returns ------- node : dict ### Response: def pro...
def send_refactor_request(self, ref_type, ref_params, ref_options): """Send a refactor request to the Ensime server. The `ref_params` field will always have a field `type`. """ request = { "typehint": ref_type, "procId": self.refactor_id, "params": re...
Send a refactor request to the Ensime server. The `ref_params` field will always have a field `type`.
Below is the the instruction that describes the task: ### Input: Send a refactor request to the Ensime server. The `ref_params` field will always have a field `type`. ### Response: def send_refactor_request(self, ref_type, ref_params, ref_options): """Send a refactor request to the Ensime server. ...
def scan(self): """ Scan source and grab tokens. """ self.pre_scan() token = None end = len(self.source) while self.pos < end: best_pat = None best_pat_len = 0 # Check patterns for p, regexp in self.patterns: m ...
Scan source and grab tokens.
Below is the the instruction that describes the task: ### Input: Scan source and grab tokens. ### Response: def scan(self): """ Scan source and grab tokens. """ self.pre_scan() token = None end = len(self.source) while self.pos < end: best_pat = None ...
def encode_many(chord_labels, reduce_extended_chords=False): """Translate a set of chord labels to numerical representations for sane evaluation. Parameters ---------- chord_labels : list Set of chord labels to encode. reduce_extended_chords : bool Whether to map the upper voici...
Translate a set of chord labels to numerical representations for sane evaluation. Parameters ---------- chord_labels : list Set of chord labels to encode. reduce_extended_chords : bool Whether to map the upper voicings of extended chords (9's, 11's, 13's) to semitone extensi...
Below is the the instruction that describes the task: ### Input: Translate a set of chord labels to numerical representations for sane evaluation. Parameters ---------- chord_labels : list Set of chord labels to encode. reduce_extended_chords : bool Whether to map the upper voic...
def fromtextindex(index_or_dirname, indexname=None, docnum_field=None): """ Extract all documents from a Whoosh index. E.g.:: >>> import petl as etl >>> import os >>> # set up an index and load some documents via the Whoosh API ... from whoosh.index import create_in >>> ...
Extract all documents from a Whoosh index. E.g.:: >>> import petl as etl >>> import os >>> # set up an index and load some documents via the Whoosh API ... from whoosh.index import create_in >>> from whoosh.fields import * >>> schema = Schema(title=TEXT(stored=True), pat...
Below is the the instruction that describes the task: ### Input: Extract all documents from a Whoosh index. E.g.:: >>> import petl as etl >>> import os >>> # set up an index and load some documents via the Whoosh API ... from whoosh.index import create_in >>> from whoosh.fie...
def install(): ''' Install weboob system-wide ''' tmp_weboob_dir = '/tmp/weboob' # Check that the directory does not already exists while (os.path.exists(tmp_weboob_dir)): tmp_weboob_dir += '1' # Clone the repository print 'Fetching sources in temporary dir {}'.format(tmp_w...
Install weboob system-wide
Below is the the instruction that describes the task: ### Input: Install weboob system-wide ### Response: def install(): ''' Install weboob system-wide ''' tmp_weboob_dir = '/tmp/weboob' # Check that the directory does not already exists while (os.path.exists(tmp_weboob_dir)): ...
def get_automations(self, refresh=False, generic_type=None): """Get all automations.""" if refresh or self._automations is None: if self._automations is None: # Set up the device libraries self._automations = {} _LOGGER.info("Updating all automati...
Get all automations.
Below is the the instruction that describes the task: ### Input: Get all automations. ### Response: def get_automations(self, refresh=False, generic_type=None): """Get all automations.""" if refresh or self._automations is None: if self._automations is None: # Set up the...
def edit_permissions(self): """Creates the view used to edit permissions. To create the view, data in the following format is passed to the UI in the objects field: .. code-block:: python { "type": "tree-toggle", "action": "set_permission", ...
Creates the view used to edit permissions. To create the view, data in the following format is passed to the UI in the objects field: .. code-block:: python { "type": "tree-toggle", "action": "set_permission", "tree": [ ...
Below is the the instruction that describes the task: ### Input: Creates the view used to edit permissions. To create the view, data in the following format is passed to the UI in the objects field: .. code-block:: python { "type": "tree-toggle", ...
def get_transform(self, map_from='visual', map_to='render'): """Return a transform mapping between any two coordinate systems. Parameters ---------- map_from : str The starting coordinate system to map from. Must be one of: visual, scene, document, canvas...
Return a transform mapping between any two coordinate systems. Parameters ---------- map_from : str The starting coordinate system to map from. Must be one of: visual, scene, document, canvas, framebuffer, or render. map_to : str The ending co...
Below is the the instruction that describes the task: ### Input: Return a transform mapping between any two coordinate systems. Parameters ---------- map_from : str The starting coordinate system to map from. Must be one of: visual, scene, document, canvas, f...
def emit(self, signal, value=None, gather=False): """Emits a signal, causing all slot methods connected with the signal to be called (optionally w/ related value) signal: the name of the signal to emit, must be defined in the classes 'signals' list. value: the value to pass to all connect...
Emits a signal, causing all slot methods connected with the signal to be called (optionally w/ related value) signal: the name of the signal to emit, must be defined in the classes 'signals' list. value: the value to pass to all connected slot methods. gather: if set, causes emit to re...
Below is the the instruction that describes the task: ### Input: Emits a signal, causing all slot methods connected with the signal to be called (optionally w/ related value) signal: the name of the signal to emit, must be defined in the classes 'signals' list. value: the value to pass to all...
def _validate_plan_base( new_plan, base_plan, is_partition_subset=True, allow_rf_change=False, ): """Validate if given plan is valid comparing with given base-plan. Validate following assertions: - Partition-check: New partition-set should be subset of base-partition set - Replica-count...
Validate if given plan is valid comparing with given base-plan. Validate following assertions: - Partition-check: New partition-set should be subset of base-partition set - Replica-count check: Replication-factor for each partition remains same - Broker-check: New broker-set should be subset of base br...
Below is the the instruction that describes the task: ### Input: Validate if given plan is valid comparing with given base-plan. Validate following assertions: - Partition-check: New partition-set should be subset of base-partition set - Replica-count check: Replication-factor for each partition remain...
def add_efac(psr, efac=1.0, flagid=None, flags=None, seed=None): """Add nominal TOA errors, multiplied by `efac` factor. Optionally take a pseudorandom-number-generator seed.""" if seed is not None: N.random.seed(seed) # default efacvec efacvec = N.ones(psr.nobs) # check that efac...
Add nominal TOA errors, multiplied by `efac` factor. Optionally take a pseudorandom-number-generator seed.
Below is the the instruction that describes the task: ### Input: Add nominal TOA errors, multiplied by `efac` factor. Optionally take a pseudorandom-number-generator seed. ### Response: def add_efac(psr, efac=1.0, flagid=None, flags=None, seed=None): """Add nominal TOA errors, multiplied by `efac` factor. ...
def __create_tcp_top(self, packet): """ witch the complete packet set top header """ length = len(packet) top = pack('<HHI', const.MACHINE_PREPARE_DATA_1, const.MACHINE_PREPARE_DATA_2, length) return top + packet
witch the complete packet set top header
Below is the the instruction that describes the task: ### Input: witch the complete packet set top header ### Response: def __create_tcp_top(self, packet): """ witch the complete packet set top header """ length = len(packet) top = pack('<HHI', const.MACHINE_PREPARE_DATA_1, ...
def render_template(self, template, **kwargs): """ Use this method on your own endpoints, will pass the extra_args to the templates. :param template: The template relative path :param kwargs: arguments to be passed to the template """ kwargs["base...
Use this method on your own endpoints, will pass the extra_args to the templates. :param template: The template relative path :param kwargs: arguments to be passed to the template
Below is the the instruction that describes the task: ### Input: Use this method on your own endpoints, will pass the extra_args to the templates. :param template: The template relative path :param kwargs: arguments to be passed to the template ### Response: def render_template...
def set_seamless_mode(self, enabled): """Enables or disables seamless guest display rendering (seamless desktop integration) mode. Calling this method has no effect if :py:func:`IGuest.get_facility_status` with facility @c Seamless does not return @c Active. in enabled...
Enables or disables seamless guest display rendering (seamless desktop integration) mode. Calling this method has no effect if :py:func:`IGuest.get_facility_status` with facility @c Seamless does not return @c Active. in enabled of type bool
Below is the the instruction that describes the task: ### Input: Enables or disables seamless guest display rendering (seamless desktop integration) mode. Calling this method has no effect if :py:func:`IGuest.get_facility_status` with facility @c Seamless does not return @c Active....
def _parse_api_value_list(self, values): """Return a list field compatible with the API.""" try: return [v.to_api() for v in values] # Not models except AttributeError: return list(values)
Return a list field compatible with the API.
Below is the the instruction that describes the task: ### Input: Return a list field compatible with the API. ### Response: def _parse_api_value_list(self, values): """Return a list field compatible with the API.""" try: return [v.to_api() for v in values] # Not models e...
def remove(self, member): """Remove a member from the archive.""" # Make sure we have an info object if isinstance(member, ZipInfo): # 'member' is already an info object zinfo = member else: # Get info object for name zinfo = self.getinfo(m...
Remove a member from the archive.
Below is the the instruction that describes the task: ### Input: Remove a member from the archive. ### Response: def remove(self, member): """Remove a member from the archive.""" # Make sure we have an info object if isinstance(member, ZipInfo): # 'member' is already an info obj...
def _remove_empty_pars(pars, pars_oi, dims_oi): """ Remove parameters that are actually empty. For example, the parameter y would be removed with the following model code: transformed data { int n; n <- 0; } parameters { real y[n]; } Parameters ---------- pars: iterable of str ...
Remove parameters that are actually empty. For example, the parameter y would be removed with the following model code: transformed data { int n; n <- 0; } parameters { real y[n]; } Parameters ---------- pars: iterable of str pars_oi: list of str dims_oi: list of list of int ...
Below is the the instruction that describes the task: ### Input: Remove parameters that are actually empty. For example, the parameter y would be removed with the following model code: transformed data { int n; n <- 0; } parameters { real y[n]; } Parameters ---------- pars: iterabl...
def heightmap_lerp_hm( hm1: np.ndarray, hm2: np.ndarray, hm3: np.ndarray, coef: float ) -> None: """Perform linear interpolation between two heightmaps storing the result in ``hm3``. This is the same as doing ``hm3[:] = hm1[:] + (hm2[:] - hm1[:]) * coef`` Args: hm1 (numpy.ndarray): The fir...
Perform linear interpolation between two heightmaps storing the result in ``hm3``. This is the same as doing ``hm3[:] = hm1[:] + (hm2[:] - hm1[:]) * coef`` Args: hm1 (numpy.ndarray): The first heightmap. hm2 (numpy.ndarray): The second heightmap to add to the first. hm3 (numpy.ndar...
Below is the the instruction that describes the task: ### Input: Perform linear interpolation between two heightmaps storing the result in ``hm3``. This is the same as doing ``hm3[:] = hm1[:] + (hm2[:] - hm1[:]) * coef`` Args: hm1 (numpy.ndarray): The first heightmap. hm2 (numpy.ndarra...
def sell_close(id_or_ins, amount, price=None, style=None, close_today=False): """ 平买仓 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] :param int amount: 下单手数 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主...
平买仓 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] :param int amount: 下单手数 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class...
Below is the the instruction that describes the task: ### Input: 平买仓 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] :param int amount: 下单手数 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 ...
def _new_import(self, import_name): """ Starts a new import. Args: import_name(str): A relative import in the dot syntax (e.g. "first.second.expressions") """ # Import can't be used if meta-model is loaded from string assert self.root_path is ...
Starts a new import. Args: import_name(str): A relative import in the dot syntax (e.g. "first.second.expressions")
Below is the the instruction that describes the task: ### Input: Starts a new import. Args: import_name(str): A relative import in the dot syntax (e.g. "first.second.expressions") ### Response: def _new_import(self, import_name): """ Starts a new import. ...
def _raw(s): """Get raw representation of s, truncating if too long.""" if isinstance(s, list): s = "\n".join(_raw(item) for item in s) if s == EOF: return "EOF" s = repr(s) # Get raw representation of string s = s[1:-1] # Strip away quotation marks if len(s) > 15: s...
Get raw representation of s, truncating if too long.
Below is the the instruction that describes the task: ### Input: Get raw representation of s, truncating if too long. ### Response: def _raw(s): """Get raw representation of s, truncating if too long.""" if isinstance(s, list): s = "\n".join(_raw(item) for item in s) if s == EOF: retu...
def bufferoutput(self): """ Buffer the whole output until write EOF or flushed. """ new_stream = Stream(writebufferlimit=None) if self._sendHeaders: # An extra copy self.container.subroutine(new_stream.copy_to(self.outputstream, self.container, buffering=F...
Buffer the whole output until write EOF or flushed.
Below is the the instruction that describes the task: ### Input: Buffer the whole output until write EOF or flushed. ### Response: def bufferoutput(self): """ Buffer the whole output until write EOF or flushed. """ new_stream = Stream(writebufferlimit=None) if self._sendHead...
def merkle(hashes, func=_merkle_hash256): """Convert an iterable of hashes or hashable objects into a binary tree, construct the interior values using a passed-in constructor or compression function, and return the root value of the tree. The default compressor is the hash256 function, resulting in root...
Convert an iterable of hashes or hashable objects into a binary tree, construct the interior values using a passed-in constructor or compression function, and return the root value of the tree. The default compressor is the hash256 function, resulting in root-hash for the entire tree.
Below is the the instruction that describes the task: ### Input: Convert an iterable of hashes or hashable objects into a binary tree, construct the interior values using a passed-in constructor or compression function, and return the root value of the tree. The default compressor is the hash256 functio...
def get_environment(self): ''' Return a dictionary representing the environment variables used to set the proxy settings. ''' env = {} if self.http: env['http_proxy'] = env['HTTP_PROXY'] = self.http if self.https: env['https_proxy'] = env['...
Return a dictionary representing the environment variables used to set the proxy settings.
Below is the the instruction that describes the task: ### Input: Return a dictionary representing the environment variables used to set the proxy settings. ### Response: def get_environment(self): ''' Return a dictionary representing the environment variables used to set the proxy s...
def _get_window_labels(self, window): """Returns the mapping between sliding window points and their contigs, and the x-axis position of contig Parameters ---------- window : int Size of the window. Returns ------- xbars : list Th...
Returns the mapping between sliding window points and their contigs, and the x-axis position of contig Parameters ---------- window : int Size of the window. Returns ------- xbars : list The x-axis position of the ending for each contig. ...
Below is the the instruction that describes the task: ### Input: Returns the mapping between sliding window points and their contigs, and the x-axis position of contig Parameters ---------- window : int Size of the window. Returns ------- xbars :...
def _get(self, url, method, host): """Get a request handler based on the URL of the request, or raises an error. Internal method for caching. :param url: request URL :param method: request method :return: handler, arguments, keyword arguments """ url = unquote(h...
Get a request handler based on the URL of the request, or raises an error. Internal method for caching. :param url: request URL :param method: request method :return: handler, arguments, keyword arguments
Below is the the instruction that describes the task: ### Input: Get a request handler based on the URL of the request, or raises an error. Internal method for caching. :param url: request URL :param method: request method :return: handler, arguments, keyword arguments ### Response...
def setup(self, environ): '''Called once to setup the list of wsgi middleware.''' json_handler = Root().putSubHandler('calc', Calculator()) middleware = wsgi.Router('/', post=json_handler, accept_content_types=JSON_CONTENT_TYPES) response = [wsgi.GZipMidd...
Called once to setup the list of wsgi middleware.
Below is the the instruction that describes the task: ### Input: Called once to setup the list of wsgi middleware. ### Response: def setup(self, environ): '''Called once to setup the list of wsgi middleware.''' json_handler = Root().putSubHandler('calc', Calculator()) middleware = wsgi.Rout...
def add_observer( self, callable_, entity_type=None, action=None, entity_id=None, predicate=None): """Register an "on-model-change" callback Once the model is connected, ``callable_`` will be called each time the model changes. ``callable_`` should be Awaitable a...
Register an "on-model-change" callback Once the model is connected, ``callable_`` will be called each time the model changes. ``callable_`` should be Awaitable and accept the following positional arguments: delta - An instance of :class:`juju.delta.EntityDelta` cont...
Below is the the instruction that describes the task: ### Input: Register an "on-model-change" callback Once the model is connected, ``callable_`` will be called each time the model changes. ``callable_`` should be Awaitable and accept the following positional arguments: delta ...
def extend(self, items): """ Adds @items to the end of the list -> #int length of list after operation """ if items: if self.serialized: items = list(map(self._dumps, items)) self._client.rpush(self.key_prefix, *items)
Adds @items to the end of the list -> #int length of list after operation
Below is the the instruction that describes the task: ### Input: Adds @items to the end of the list -> #int length of list after operation ### Response: def extend(self, items): """ Adds @items to the end of the list -> #int length of list after operation """ if item...
def BAR(w_F, w_R, DeltaF=0.0, compute_uncertainty=True, uncertainty_method='BAR',maximum_iterations=500, relative_tolerance=1.0e-12, verbose=False, method='false-position', iterated_solution=True): """Compute free energy difference using the Bennett acceptance ratio (BAR) method. Parameters ---------- ...
Compute free energy difference using the Bennett acceptance ratio (BAR) method. Parameters ---------- w_F : np.ndarray w_F[t] is the forward work value from snapshot t. t = 0...(T_F-1) Length T_F is deduced from vector. w_R : np.ndarray w_R[t] is the reverse work value from sna...
Below is the the instruction that describes the task: ### Input: Compute free energy difference using the Bennett acceptance ratio (BAR) method. Parameters ---------- w_F : np.ndarray w_F[t] is the forward work value from snapshot t. t = 0...(T_F-1) Length T_F is deduced from vector. ...
def create_from_response_pdu(resp_pdu, req_pdu): """ Create instance from response PDU. Response PDU is required together with the number of registers read. :param resp_pdu: Byte array with request PDU. :param quantity: Number of coils read. :return: Instance of :class:`ReadCoi...
Create instance from response PDU. Response PDU is required together with the number of registers read. :param resp_pdu: Byte array with request PDU. :param quantity: Number of coils read. :return: Instance of :class:`ReadCoils`.
Below is the the instruction that describes the task: ### Input: Create instance from response PDU. Response PDU is required together with the number of registers read. :param resp_pdu: Byte array with request PDU. :param quantity: Number of coils read. :return: Instance of :class:...
def gridLog(**kw): """Send GLRecord, Distributed Logging Utilities If the scheme is passed as a keyword parameter the value is expected to be a callable function that takes 2 parameters: url, outputStr GRIDLOG_ON -- turn grid logging on GRIDLOG_DEST -- provide URL destination """ impo...
Send GLRecord, Distributed Logging Utilities If the scheme is passed as a keyword parameter the value is expected to be a callable function that takes 2 parameters: url, outputStr GRIDLOG_ON -- turn grid logging on GRIDLOG_DEST -- provide URL destination
Below is the the instruction that describes the task: ### Input: Send GLRecord, Distributed Logging Utilities If the scheme is passed as a keyword parameter the value is expected to be a callable function that takes 2 parameters: url, outputStr GRIDLOG_ON -- turn grid logging on GRIDLOG_DEST ...
def _get(self, components, picker, **params): """Generic get which handles call to api and setting of results Return: Results object""" url = '/'.join((self.base,) + components) headers = {"Authorization": "Token token=" + self._token} params['page'] = params.get('page') or sel...
Generic get which handles call to api and setting of results Return: Results object
Below is the the instruction that describes the task: ### Input: Generic get which handles call to api and setting of results Return: Results object ### Response: def _get(self, components, picker, **params): """Generic get which handles call to api and setting of results Return: Results ob...
def get_instance(): """Return an instance of Client.""" global _instances user_agents = _config['user-agents'] user_agent = user_agents[ random.randint(0, len(user_agents) - 1) ] if len(user_agents) > 0 else DEFAULT_UA instance_key = user_agent try: instance = _instances[i...
Return an instance of Client.
Below is the the instruction that describes the task: ### Input: Return an instance of Client. ### Response: def get_instance(): """Return an instance of Client.""" global _instances user_agents = _config['user-agents'] user_agent = user_agents[ random.randint(0, len(user_agents) - 1) ...
def get_allowance(self, asset_name: str, from_address: str, to_address: str, is_full: bool = False) -> str: """ This interface is used to get the the allowance from transfer-from account to transfer-to account in current network. :param asset_name: :param from_address: a base58 ...
This interface is used to get the the allowance from transfer-from account to transfer-to account in current network. :param asset_name: :param from_address: a base58 encoded account address. :param to_address: a base58 encoded account address. :param is_full: :return: t...
Below is the the instruction that describes the task: ### Input: This interface is used to get the the allowance from transfer-from account to transfer-to account in current network. :param asset_name: :param from_address: a base58 encoded account address. :param to_address: a base5...
def violin_or_box_plot(df, y, figformat, path, y_name, title=None, plot="violin", log=False, palette=None): """Create a violin or boxplot from the received DataFrame. The x-axis should be divided based on the 'dataset' column, the y-axis is specified in the arguments """ comp...
Create a violin or boxplot from the received DataFrame. The x-axis should be divided based on the 'dataset' column, the y-axis is specified in the arguments
Below is the the instruction that describes the task: ### Input: Create a violin or boxplot from the received DataFrame. The x-axis should be divided based on the 'dataset' column, the y-axis is specified in the arguments ### Response: def violin_or_box_plot(df, y, figformat, path, y_name, ...
def get_raw(tree): """Get the exact words in lowercase in the tree object. Args: tree (Tree): Parsed tree structure Returns: Resulting string of tree ``(Ex: "The red car")`` """ if isinstance(tree, Tree): words = [] for child in tree: words.append(get...
Get the exact words in lowercase in the tree object. Args: tree (Tree): Parsed tree structure Returns: Resulting string of tree ``(Ex: "The red car")``
Below is the the instruction that describes the task: ### Input: Get the exact words in lowercase in the tree object. Args: tree (Tree): Parsed tree structure Returns: Resulting string of tree ``(Ex: "The red car")`` ### Response: def get_raw(tree): """Get the exact words in lowerc...
def position_rates(self): '''List of position rates for linear degrees of freedom.''' return [self.ode_obj.getPositionRate(i) for i in range(self.LDOF)]
List of position rates for linear degrees of freedom.
Below is the the instruction that describes the task: ### Input: List of position rates for linear degrees of freedom. ### Response: def position_rates(self): '''List of position rates for linear degrees of freedom.''' return [self.ode_obj.getPositionRate(i) for i in range(self.LDOF)]
def get_emitter(self, name: str) -> Callable[[Event], Event]: """Gets and emitter for a named event. Parameters ---------- name : The name of the event he requested emitter will emit. Users may provide their own named events by requesting an emitter with this fun...
Gets and emitter for a named event. Parameters ---------- name : The name of the event he requested emitter will emit. Users may provide their own named events by requesting an emitter with this function, but should do so with caution as it makes time much mo...
Below is the the instruction that describes the task: ### Input: Gets and emitter for a named event. Parameters ---------- name : The name of the event he requested emitter will emit. Users may provide their own named events by requesting an emitter with this functio...
def find_gene_knockout_reactions(cobra_model, gene_list, compiled_gene_reaction_rules=None): """identify reactions which will be disabled when the genes are knocked out cobra_model: :class:`~cobra.core.Model.Model` gene_list: iterable of :class:`~cobra.core.Gene.Gene` ...
identify reactions which will be disabled when the genes are knocked out cobra_model: :class:`~cobra.core.Model.Model` gene_list: iterable of :class:`~cobra.core.Gene.Gene` compiled_gene_reaction_rules: dict of {reaction_id: compiled_string} If provided, this gives pre-compiled gene_reaction_rule...
Below is the the instruction that describes the task: ### Input: identify reactions which will be disabled when the genes are knocked out cobra_model: :class:`~cobra.core.Model.Model` gene_list: iterable of :class:`~cobra.core.Gene.Gene` compiled_gene_reaction_rules: dict of {reaction_id: compiled_st...
def do_action(self, action, objects): """Performs the workflow transition passed in and returns the list of objects that have been successfully transitioned """ transitioned = [] ActionHandlerPool.get_instance().queue_pool() for obj in objects: obj = api.get_o...
Performs the workflow transition passed in and returns the list of objects that have been successfully transitioned
Below is the the instruction that describes the task: ### Input: Performs the workflow transition passed in and returns the list of objects that have been successfully transitioned ### Response: def do_action(self, action, objects): """Performs the workflow transition passed in and returns the list...
def main(): """CLI entrypoint for scaling policy creation""" logging.basicConfig(format=LOGGING_FORMAT) log = logging.getLogger(__name__) parser = argparse.ArgumentParser() add_debug(parser) add_app(parser) add_properties(parser) add_env(parser) add_region(parser) args = parser....
CLI entrypoint for scaling policy creation
Below is the the instruction that describes the task: ### Input: CLI entrypoint for scaling policy creation ### Response: def main(): """CLI entrypoint for scaling policy creation""" logging.basicConfig(format=LOGGING_FORMAT) log = logging.getLogger(__name__) parser = argparse.ArgumentParser() ...
def revert(self, request, queryset): """ Admin action to revert a configuration back to the selected value """ if queryset.count() != 1: self.message_user(request, _("Please select a single configuration to revert to.")) return target = queryset[0] ...
Admin action to revert a configuration back to the selected value
Below is the the instruction that describes the task: ### Input: Admin action to revert a configuration back to the selected value ### Response: def revert(self, request, queryset): """ Admin action to revert a configuration back to the selected value """ if queryset.count() != 1: ...
def dumps(module, cls=PVLEncoder, **kwargs): """Serialize ``module`` as a pvl module formated byte string. :param module: a ```PVLModule``` or ```dict``` like object to serialize :param cls: the encoder class used to serialize the pvl module. You may use the default ``PVLEncoder`` class or provide...
Serialize ``module`` as a pvl module formated byte string. :param module: a ```PVLModule``` or ```dict``` like object to serialize :param cls: the encoder class used to serialize the pvl module. You may use the default ``PVLEncoder`` class or provided encoder formats such as the ```IsisCubeLab...
Below is the the instruction that describes the task: ### Input: Serialize ``module`` as a pvl module formated byte string. :param module: a ```PVLModule``` or ```dict``` like object to serialize :param cls: the encoder class used to serialize the pvl module. You may use the default ``PVLEncoder``...
def workflow_start(obj, queue, keep_data, name, workflow_args): """ Send a workflow to the queue. \b NAME: The name of the workflow that should be started. WORKFLOW_ARGS: Workflow arguments in the form key1=value1 key2=value2. """ try: start_workflow(name=name, co...
Send a workflow to the queue. \b NAME: The name of the workflow that should be started. WORKFLOW_ARGS: Workflow arguments in the form key1=value1 key2=value2.
Below is the the instruction that describes the task: ### Input: Send a workflow to the queue. \b NAME: The name of the workflow that should be started. WORKFLOW_ARGS: Workflow arguments in the form key1=value1 key2=value2. ### Response: def workflow_start(obj, queue, keep_data, name, workflow_args): ...
def set_group_name(self, group, old_name, new_name): """ Group was renamed. """ lgroup = self._get_group(old_name) rename(lgroup, database=self._database, cn=new_name)
Group was renamed.
Below is the the instruction that describes the task: ### Input: Group was renamed. ### Response: def set_group_name(self, group, old_name, new_name): """ Group was renamed. """ lgroup = self._get_group(old_name) rename(lgroup, database=self._database, cn=new_name)
def fail(self, message, param=None, ctx=None): """Helper method to fail with an invalid value message.""" raise BadParameter(message, ctx=ctx, param=param)
Helper method to fail with an invalid value message.
Below is the the instruction that describes the task: ### Input: Helper method to fail with an invalid value message. ### Response: def fail(self, message, param=None, ctx=None): """Helper method to fail with an invalid value message.""" raise BadParameter(message, ctx=ctx, param=param)
def get_next(self): """Return next iteration time related to loop time""" return self.loop_time + (self.croniter.get_next(float) - self.time)
Return next iteration time related to loop time
Below is the the instruction that describes the task: ### Input: Return next iteration time related to loop time ### Response: def get_next(self): """Return next iteration time related to loop time""" return self.loop_time + (self.croniter.get_next(float) - self.time)
def load(cls, path, base=None): '''Either load a path and return a shovel object or return None''' obj = cls() obj.read(path, base) return obj
Either load a path and return a shovel object or return None
Below is the the instruction that describes the task: ### Input: Either load a path and return a shovel object or return None ### Response: def load(cls, path, base=None): '''Either load a path and return a shovel object or return None''' obj = cls() obj.read(path, base) return obj
def governor(self, dep_type, node): """ Registers a node as governing this node :param dep_type: The dependency type :type dep_type: str :param node: :return: self, provides fluent interface :rtype: corenlp_xml.dependencies.DependencyNode """ se...
Registers a node as governing this node :param dep_type: The dependency type :type dep_type: str :param node: :return: self, provides fluent interface :rtype: corenlp_xml.dependencies.DependencyNode
Below is the the instruction that describes the task: ### Input: Registers a node as governing this node :param dep_type: The dependency type :type dep_type: str :param node: :return: self, provides fluent interface :rtype: corenlp_xml.dependencies.DependencyNode ### Respon...
def check_json(code): """Yield errors.""" try: json.loads(code) except ValueError as exception: message = '{}'.format(exception) line_number = 0 found = re.search(r': line\s+([0-9]+)[^:]*$', message) if found: line_number = int(found.group(1)) yi...
Yield errors.
Below is the the instruction that describes the task: ### Input: Yield errors. ### Response: def check_json(code): """Yield errors.""" try: json.loads(code) except ValueError as exception: message = '{}'.format(exception) line_number = 0 found = re.search(r': line\s+([0...
def fetch_url(src, dst): """ Fetch file from URL src and save it to dst. """ # we do not use the nicer sys.version_info.major # for compatibility with Python < 2.7 if sys.version_info[0] > 2: import urllib.request class URLopener(urllib.request.FancyURLopener): def h...
Fetch file from URL src and save it to dst.
Below is the the instruction that describes the task: ### Input: Fetch file from URL src and save it to dst. ### Response: def fetch_url(src, dst): """ Fetch file from URL src and save it to dst. """ # we do not use the nicer sys.version_info.major # for compatibility with Python < 2.7 if s...
def flatten(self): """Create a flattened version by putting output first and then states.""" ls = [self.output] ls.extend(self.state) return ls
Create a flattened version by putting output first and then states.
Below is the the instruction that describes the task: ### Input: Create a flattened version by putting output first and then states. ### Response: def flatten(self): """Create a flattened version by putting output first and then states.""" ls = [self.output] ls.extend(self.state) return ls
def _request(self, proxy, timeout): """ Returns WPToolsRequest object """ return request.WPToolsRequest(self.flags['silent'], self.flags['verbose'], proxy, timeout)
Returns WPToolsRequest object
Below is the the instruction that describes the task: ### Input: Returns WPToolsRequest object ### Response: def _request(self, proxy, timeout): """ Returns WPToolsRequest object """ return request.WPToolsRequest(self.flags['silent'], self.flags...
def new_build(py_ver: PyVer): """Job for building/caching different docker images""" cache_file = f'app_{py_ver.name}.tar' cache_path = f'{cache_dir}/{cache_file}' cache_key = f'v3-{py_ver.name}-{{{{ .Branch }}}}' template = yaml.safe_load(f""" machine: image: 'circleci/classic:201710-02' ...
Job for building/caching different docker images
Below is the the instruction that describes the task: ### Input: Job for building/caching different docker images ### Response: def new_build(py_ver: PyVer): """Job for building/caching different docker images""" cache_file = f'app_{py_ver.name}.tar' cache_path = f'{cache_dir}/{cache_file}' cache_k...
def launch_modules_with_names(modules_with_names, module_args={}, kill_before_launch=True): '''launch module.main functions in another process''' processes = [] if kill_before_launch: for module_name, name in modules_with_names: kill_module(name) for module_name, name in modules_with...
launch module.main functions in another process
Below is the the instruction that describes the task: ### Input: launch module.main functions in another process ### Response: def launch_modules_with_names(modules_with_names, module_args={}, kill_before_launch=True): '''launch module.main functions in another process''' processes = [] if kill_before_...
def _ignore_class_scope(self, node): """ Return True if the node is in a local class scope, as an assignment. :param node: Node considered :type node: astroid.Node :return: True if the node is in a local class scope, as an assignment. False otherwise. :rtype: bool ...
Return True if the node is in a local class scope, as an assignment. :param node: Node considered :type node: astroid.Node :return: True if the node is in a local class scope, as an assignment. False otherwise. :rtype: bool
Below is the the instruction that describes the task: ### Input: Return True if the node is in a local class scope, as an assignment. :param node: Node considered :type node: astroid.Node :return: True if the node is in a local class scope, as an assignment. False otherwise. :rtype:...
def export_ply(filename, cutout, level=0): """ Converts a dense annotation to a .PLY, using Marching Cubes (PyMCubes). Arguments: filename (str): The filename to write out to cutout (numpy.ndarray): The dense annotation level (int): The level at which to run mcubes Returns: ...
Converts a dense annotation to a .PLY, using Marching Cubes (PyMCubes). Arguments: filename (str): The filename to write out to cutout (numpy.ndarray): The dense annotation level (int): The level at which to run mcubes Returns: boolean success
Below is the the instruction that describes the task: ### Input: Converts a dense annotation to a .PLY, using Marching Cubes (PyMCubes). Arguments: filename (str): The filename to write out to cutout (numpy.ndarray): The dense annotation level (int): The level at which to run mcubes ...
def readBatchTupleQuotes(self, symbols, start, end): ''' read batch quotes as tuple to save memory ''' if end is None: end=sys.maxint ret={} session=self.getReadSession()() try: symbolChunks=splitListEqually(symbols, 100) ...
read batch quotes as tuple to save memory
Below is the the instruction that describes the task: ### Input: read batch quotes as tuple to save memory ### Response: def readBatchTupleQuotes(self, symbols, start, end): ''' read batch quotes as tuple to save memory ''' if end is None: end=sys.maxint ...
def authorize(self, role): """Check permission""" resource, action = parse_request() roles = self.meta.get("$roles", {}) message = "%s can't access %s.%s" % (role, resource, action) try: if action not in roles[role][resource]: abort(403, "PermissionDen...
Check permission
Below is the the instruction that describes the task: ### Input: Check permission ### Response: def authorize(self, role): """Check permission""" resource, action = parse_request() roles = self.meta.get("$roles", {}) message = "%s can't access %s.%s" % (role, resource, action) ...
def check_number_available(self, id_environment, num_vlan, id_vlan): """Checking if environment has a number vlan available :param id_environment: Identifier of environment :param num_vlan: Vlan number :param id_vlan: Vlan indentifier (False if inserting a vlan) :return: True i...
Checking if environment has a number vlan available :param id_environment: Identifier of environment :param num_vlan: Vlan number :param id_vlan: Vlan indentifier (False if inserting a vlan) :return: True is has number available, False if hasn't :raise AmbienteNaoExisteError: ...
Below is the the instruction that describes the task: ### Input: Checking if environment has a number vlan available :param id_environment: Identifier of environment :param num_vlan: Vlan number :param id_vlan: Vlan indentifier (False if inserting a vlan) :return: True is has numbe...
def read_zipfile(self, encoding='utf8'): """ READ FIRST FILE IN ZIP FILE :param encoding: :return: STRING """ from zipfile import ZipFile with ZipFile(self.abspath) as zipped: for num, zip_name in enumerate(zipped.namelist()): return zi...
READ FIRST FILE IN ZIP FILE :param encoding: :return: STRING
Below is the the instruction that describes the task: ### Input: READ FIRST FILE IN ZIP FILE :param encoding: :return: STRING ### Response: def read_zipfile(self, encoding='utf8'): """ READ FIRST FILE IN ZIP FILE :param encoding: :return: STRING """ f...
def get_parents(docgraph, child_node, strict=True): """Return a list of parent nodes that dominate this child. In a 'syntax tree' a node never has more than one parent node dominating it. To enforce this, set strict=True. Parameters ---------- docgraph : DiscourseDocumentGraph a docume...
Return a list of parent nodes that dominate this child. In a 'syntax tree' a node never has more than one parent node dominating it. To enforce this, set strict=True. Parameters ---------- docgraph : DiscourseDocumentGraph a document graph strict : bool If True, raise a ValueEr...
Below is the the instruction that describes the task: ### Input: Return a list of parent nodes that dominate this child. In a 'syntax tree' a node never has more than one parent node dominating it. To enforce this, set strict=True. Parameters ---------- docgraph : DiscourseDocumentGraph ...
def _K(self, R): """Return numpy array from K1 up to and including Kn. (eqn. 5)""" return self._ns * self._N / R / self._sin_alpha
Return numpy array from K1 up to and including Kn. (eqn. 5)
Below is the the instruction that describes the task: ### Input: Return numpy array from K1 up to and including Kn. (eqn. 5) ### Response: def _K(self, R): """Return numpy array from K1 up to and including Kn. (eqn. 5)""" return self._ns * self._N / R / self._sin_alpha
def new_keypair(key, value, ambig, unambig): """ Check new keypair against existing unambiguous dict :param key: of pair :param value: of pair :param ambig: set of keys with ambig decoding :param unambig: set of keys with unambig decoding :return: """ if key in ambig: return...
Check new keypair against existing unambiguous dict :param key: of pair :param value: of pair :param ambig: set of keys with ambig decoding :param unambig: set of keys with unambig decoding :return:
Below is the the instruction that describes the task: ### Input: Check new keypair against existing unambiguous dict :param key: of pair :param value: of pair :param ambig: set of keys with ambig decoding :param unambig: set of keys with unambig decoding :return: ### Response: def new_keypair(...
def _merge_hash(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None """Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.""" if not parser.values.hashes: parser.values.hashes = {} # type: ignore try: ...
Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.
Below is the the instruction that describes the task: ### Input: Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name. ### Response: def _merge_hash(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None """Given a value spell...
def first(iterable = None, *, name = None, metric = call_default): """Measure time elapsed to produce first item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric """ if iterable is None: return _first_decorator(name, me...
Measure time elapsed to produce first item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric
Below is the the instruction that describes the task: ### Input: Measure time elapsed to produce first item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric ### Response: def first(iterable = None, *, name = None, metric = call_defaul...
def hurst_compare_nvals(data, nvals=None): """ Creates a plot that compares the results of different choices for nvals for the function hurst_rs. Args: data (array-like of float): the input data from which the hurst exponent should be estimated Kwargs: nvals (array of int): a manually se...
Creates a plot that compares the results of different choices for nvals for the function hurst_rs. Args: data (array-like of float): the input data from which the hurst exponent should be estimated Kwargs: nvals (array of int): a manually selected value for the nvals parameter that should be...
Below is the the instruction that describes the task: ### Input: Creates a plot that compares the results of different choices for nvals for the function hurst_rs. Args: data (array-like of float): the input data from which the hurst exponent should be estimated Kwargs: nvals (array of int): ...
def _publish_daemon(self, log_queue=None): ''' Bind to the interface specified in the configuration file ''' salt.utils.process.appendproctitle(self.__class__.__name__) if log_queue: salt.log.setup.set_multiprocessing_logging_queue(log_queue) salt.log.setu...
Bind to the interface specified in the configuration file
Below is the the instruction that describes the task: ### Input: Bind to the interface specified in the configuration file ### Response: def _publish_daemon(self, log_queue=None): ''' Bind to the interface specified in the configuration file ''' salt.utils.process.appendproctitle(se...
def setDirection( self, direction ): """ Sets the direction for this widget to the inputed direction. :param direction | <XPopupWidget.Direction> """ if ( direction == XPopupWidget.Direction.North ): self.setAnchor(XPopupWidget.Anchor.TopCenter) ...
Sets the direction for this widget to the inputed direction. :param direction | <XPopupWidget.Direction>
Below is the the instruction that describes the task: ### Input: Sets the direction for this widget to the inputed direction. :param direction | <XPopupWidget.Direction> ### Response: def setDirection( self, direction ): """ Sets the direction for this widget to the inpute...
def constant(interval=1): """Generator for constant intervals. Args: interval: A constant value to yield or an iterable of such values. """ try: itr = iter(interval) except TypeError: itr = itertools.repeat(interval) for val in itr: yield val
Generator for constant intervals. Args: interval: A constant value to yield or an iterable of such values.
Below is the the instruction that describes the task: ### Input: Generator for constant intervals. Args: interval: A constant value to yield or an iterable of such values. ### Response: def constant(interval=1): """Generator for constant intervals. Args: interval: A constant value to ...
def _cmp_fstruct(self, s1, s2, frac_tol, mask): """ Returns true if a matching exists between s2 and s2 under frac_tol. s2 should be a subset of s1 """ if len(s2) > len(s1): raise ValueError("s1 must be larger than s2") if mask.shape != (len(s2), len(s1)): ...
Returns true if a matching exists between s2 and s2 under frac_tol. s2 should be a subset of s1
Below is the the instruction that describes the task: ### Input: Returns true if a matching exists between s2 and s2 under frac_tol. s2 should be a subset of s1 ### Response: def _cmp_fstruct(self, s1, s2, frac_tol, mask): """ Returns true if a matching exists between s2 and s2 unde...
def finalize_options(self): """Post-process options.""" if self.test: print("V%s will publish to the test.pypi.org" % version) elif self.release: print("V%s will publish to the pypi.org" % version)
Post-process options.
Below is the the instruction that describes the task: ### Input: Post-process options. ### Response: def finalize_options(self): """Post-process options.""" if self.test: print("V%s will publish to the test.pypi.org" % version) elif self.release: print("V%s will publ...
def _get_next(self): """Executes the next iteration of the PRNG evolution process, and returns the result """ self.state = PRNG_A * self.state % PRNG_M return self.state
Executes the next iteration of the PRNG evolution process, and returns the result
Below is the the instruction that describes the task: ### Input: Executes the next iteration of the PRNG evolution process, and returns the result ### Response: def _get_next(self): """Executes the next iteration of the PRNG evolution process, and returns the result """ sel...
def _calculateOverlap(self, inputVector): """ This function determines each column's overlap with the current input vector. The overlap of a column is the number of synapses for that column that are connected (permanence value is greater than '_synPermConnected') to input bits which are turned on. T...
This function determines each column's overlap with the current input vector. The overlap of a column is the number of synapses for that column that are connected (permanence value is greater than '_synPermConnected') to input bits which are turned on. The implementation takes advantage of the SparseBin...
Below is the the instruction that describes the task: ### Input: This function determines each column's overlap with the current input vector. The overlap of a column is the number of synapses for that column that are connected (permanence value is greater than '_synPermConnected') to input bits which a...
def recent_activity(self, user_id): """Recent activity (actions) for a given user""" M = models # noqa if request.args.get('limit'): limit = int(request.args.get('limit')) else: limit = 1000 qry = ( db.session.query(M.Log, M.Dashboard, M.Sli...
Recent activity (actions) for a given user
Below is the the instruction that describes the task: ### Input: Recent activity (actions) for a given user ### Response: def recent_activity(self, user_id): """Recent activity (actions) for a given user""" M = models # noqa if request.args.get('limit'): limit = int(request.ar...
def set_ss_value(tag, value): """ Setter for data that also work with implicit transfersyntax :param value: the value to set on the tag :param tag: the tag to read """ if tag.VR == 'OB' or tag.VR == 'UN': value = struct.pack('h', value) tag.value = value
Setter for data that also work with implicit transfersyntax :param value: the value to set on the tag :param tag: the tag to read
Below is the the instruction that describes the task: ### Input: Setter for data that also work with implicit transfersyntax :param value: the value to set on the tag :param tag: the tag to read ### Response: def set_ss_value(tag, value): """ Setter for data that also work with implicit transfersy...
def getRenderers(filename): """For a given DP, returns a list of renderer ids giving the renderers that support the source file type""" global available_renderers renderers = [] for rdrid, (renderer, module) in available_renderers.items(): try: priority = renderer.canRender(filen...
For a given DP, returns a list of renderer ids giving the renderers that support the source file type
Below is the the instruction that describes the task: ### Input: For a given DP, returns a list of renderer ids giving the renderers that support the source file type ### Response: def getRenderers(filename): """For a given DP, returns a list of renderer ids giving the renderers that support the source...
def _send_request(self, request): """Establishes connection and returns http response based off of request. :param request: HTTPRequest object :type request: :class:`tincan.http_request.HTTPRequest` :returns: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse` ...
Establishes connection and returns http response based off of request. :param request: HTTPRequest object :type request: :class:`tincan.http_request.HTTPRequest` :returns: LRS Response object :rtype: :class:`tincan.lrs_response.LRSResponse`
Below is the the instruction that describes the task: ### Input: Establishes connection and returns http response based off of request. :param request: HTTPRequest object :type request: :class:`tincan.http_request.HTTPRequest` :returns: LRS Response object :rtype: :class:`tincan.lrs...
def read(self, entity=None, attrs=None, ignore=None, params=None): """Do not read the ``account_password`` attribute. Work around a bug. For more information, see `Bugzilla #1243036 <https://bugzilla.redhat.com/show_bug.cgi?id=1243036>`_. """ if attrs is None: attrs...
Do not read the ``account_password`` attribute. Work around a bug. For more information, see `Bugzilla #1243036 <https://bugzilla.redhat.com/show_bug.cgi?id=1243036>`_.
Below is the the instruction that describes the task: ### Input: Do not read the ``account_password`` attribute. Work around a bug. For more information, see `Bugzilla #1243036 <https://bugzilla.redhat.com/show_bug.cgi?id=1243036>`_. ### Response: def read(self, entity=None, attrs=None, ignore=Non...
def send_frame(self, frame): """ Sends a frame to the other end of the connection. """ self._sendbuf += self._send_streamify(frame) self._sendbuf_event.set()
Sends a frame to the other end of the connection.
Below is the the instruction that describes the task: ### Input: Sends a frame to the other end of the connection. ### Response: def send_frame(self, frame): """ Sends a frame to the other end of the connection. """ self._sendbuf += self._send_streamify(frame) self._sendbuf...
def tempo_account_delete_customer_by_id(self, customer_id=1): """ Delete an Attribute. Caller must have Manage Account Permission. Attribute can be a Category or Customer. :param customer_id: id of Customer record :return: Customer info """ url = 'rest/tempo-accounts/1/cu...
Delete an Attribute. Caller must have Manage Account Permission. Attribute can be a Category or Customer. :param customer_id: id of Customer record :return: Customer info
Below is the the instruction that describes the task: ### Input: Delete an Attribute. Caller must have Manage Account Permission. Attribute can be a Category or Customer. :param customer_id: id of Customer record :return: Customer info ### Response: def tempo_account_delete_customer_by_id(self, cus...
async def set_setback_temp(self, sb_temp, timeout=OTGW_DEFAULT_TIMEOUT): """ Configure the setback temperature to use in combination with GPIO functions HOME (5) and AWAY (6). Return the new setback temperature, or None on failure. This method is a coroutine """ ...
Configure the setback temperature to use in combination with GPIO functions HOME (5) and AWAY (6). Return the new setback temperature, or None on failure. This method is a coroutine
Below is the the instruction that describes the task: ### Input: Configure the setback temperature to use in combination with GPIO functions HOME (5) and AWAY (6). Return the new setback temperature, or None on failure. This method is a coroutine ### Response: async def set_setback_temp(se...
def to_dict(self): # cls, self): """Convert Docpie into a JSONlizable dict. Use it in this way: pie = Docpie(__doc__) json.dumps(pie.convert_2_dict()) Note the `extra` info will be lost if you costomize that, because a function is not JSONlizable. You can use `...
Convert Docpie into a JSONlizable dict. Use it in this way: pie = Docpie(__doc__) json.dumps(pie.convert_2_dict()) Note the `extra` info will be lost if you costomize that, because a function is not JSONlizable. You can use `set_config(extra={...})` to set it back.
Below is the the instruction that describes the task: ### Input: Convert Docpie into a JSONlizable dict. Use it in this way: pie = Docpie(__doc__) json.dumps(pie.convert_2_dict()) Note the `extra` info will be lost if you costomize that, because a function is not JSONlizabl...
def _quit(self, *args): """ quit crash """ self.logger.warn('Bye!') sys.exit(self.exit())
quit crash
Below is the the instruction that describes the task: ### Input: quit crash ### Response: def _quit(self, *args): """ quit crash """ self.logger.warn('Bye!') sys.exit(self.exit())
def get_or_add_media_part(self, media): """Return a |MediaPart| object containing the media in *media*. If this package already contains a media part for the same bytestream, that instance is returned, otherwise a new media part is created. """ media_part = self._find_by...
Return a |MediaPart| object containing the media in *media*. If this package already contains a media part for the same bytestream, that instance is returned, otherwise a new media part is created.
Below is the the instruction that describes the task: ### Input: Return a |MediaPart| object containing the media in *media*. If this package already contains a media part for the same bytestream, that instance is returned, otherwise a new media part is created. ### Response: def get_or_ad...
def read_file(filename: PathLike = "experiment.yml") -> Dict[str, Any]: """Read and parse yaml file.""" logger.debug("Input file: %s", filename) with open(filename, "r") as stream: structure = yaml.safe_load(stream) return structure
Read and parse yaml file.
Below is the the instruction that describes the task: ### Input: Read and parse yaml file. ### Response: def read_file(filename: PathLike = "experiment.yml") -> Dict[str, Any]: """Read and parse yaml file.""" logger.debug("Input file: %s", filename) with open(filename, "r") as stream: structur...
def __push_params(self, tid, params): """ Remembers the arguments tuple for the last call to the hooked function from this thread. @type tid: int @param tid: Thread global ID. @type params: tuple( arg, arg, arg... ) @param params: Tuple of arguments. "...
Remembers the arguments tuple for the last call to the hooked function from this thread. @type tid: int @param tid: Thread global ID. @type params: tuple( arg, arg, arg... ) @param params: Tuple of arguments.
Below is the the instruction that describes the task: ### Input: Remembers the arguments tuple for the last call to the hooked function from this thread. @type tid: int @param tid: Thread global ID. @type params: tuple( arg, arg, arg... ) @param params: Tuple of arguments...
def get_popular_decks(self, **params: keys): """Get a list of most queried decks \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the ...
Get a list of most queried decks \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the response \*\*max: Optional[int] = None ...
Below is the the instruction that describes the task: ### Input: Get a list of most queried decks \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional[list] = None Filter which keys should be excluded from the...
def edit_message_text(text, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, disable_web_page_preview=None, reply_markup=None, **kwargs): """ Use this method to edit text messages sent by the bot or via the bot (for inline bots). :param text: New text of the mes...
Use this method to edit text messages sent by the bot or via the bot (for inline bots). :param text: New text of the message :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) the target channel (in the format @channeluse...
Below is the the instruction that describes the task: ### Input: Use this method to edit text messages sent by the bot or via the bot (for inline bots). :param text: New text of the message :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channeluserna...
def append_vobject(self, vcard, filename=None): """Appends an address to the Abook addressbook vcard -- vCard to append filename -- unused return the new UID of the appended vcard """ book = ConfigParser(default_section='format') with self._lock: book....
Appends an address to the Abook addressbook vcard -- vCard to append filename -- unused return the new UID of the appended vcard
Below is the the instruction that describes the task: ### Input: Appends an address to the Abook addressbook vcard -- vCard to append filename -- unused return the new UID of the appended vcard ### Response: def append_vobject(self, vcard, filename=None): """Appends an address to th...