code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def set_scrollregion(self, event=None): """ Set the scroll region on the canvas""" self.canvas.configure(scrollregion=self.canvas.bbox('all'))
Set the scroll region on the canvas
Below is the the instruction that describes the task: ### Input: Set the scroll region on the canvas ### Response: def set_scrollregion(self, event=None): """ Set the scroll region on the canvas""" self.canvas.configure(scrollregion=self.canvas.bbox('all'))
def cmd(self): """Returns the (last) saved command line. If the file was created from a run that resumed from a checkpoint, only the last command line used is returned. Returns ------- cmd : string The command line that created this InferenceFile. ""...
Returns the (last) saved command line. If the file was created from a run that resumed from a checkpoint, only the last command line used is returned. Returns ------- cmd : string The command line that created this InferenceFile.
Below is the the instruction that describes the task: ### Input: Returns the (last) saved command line. If the file was created from a run that resumed from a checkpoint, only the last command line used is returned. Returns ------- cmd : string The command line ...
def clear(self): # type: () -> None """Clears the entire scope.""" self._level = None self._fingerprint = None self._transaction = None self._user = None self._tags = {} # type: Dict[str, Any] self._contexts = {} # type: Dict[str, Dict] self._ex...
Clears the entire scope.
Below is the the instruction that describes the task: ### Input: Clears the entire scope. ### Response: def clear(self): # type: () -> None """Clears the entire scope.""" self._level = None self._fingerprint = None self._transaction = None self._user = None ...
def initialize(self, session_creator, session_init): """ Create the session and set `self.sess`. Call `self.initiailize_hooks()` Finalize the graph. It must be called after callbacks are setup. Args: session_creator (tf.train.SessionCreator): ses...
Create the session and set `self.sess`. Call `self.initiailize_hooks()` Finalize the graph. It must be called after callbacks are setup. Args: session_creator (tf.train.SessionCreator): session_init (sessinit.SessionInit):
Below is the the instruction that describes the task: ### Input: Create the session and set `self.sess`. Call `self.initiailize_hooks()` Finalize the graph. It must be called after callbacks are setup. Args: session_creator (tf.train.SessionCreator): session...
def _bfs_from_cluster_tree(tree, bfs_root): """ Perform a breadth first search on a tree in condensed tree format """ result = [] to_process = [bfs_root] while to_process: result.extend(to_process) to_process = tree['child'][np.in1d(tree['parent'], to_process)].tolist() re...
Perform a breadth first search on a tree in condensed tree format
Below is the the instruction that describes the task: ### Input: Perform a breadth first search on a tree in condensed tree format ### Response: def _bfs_from_cluster_tree(tree, bfs_root): """ Perform a breadth first search on a tree in condensed tree format """ result = [] to_process = [bfs_r...
def courses(self, request, enterprise_customer, pk=None): # pylint: disable=invalid-name """ Retrieve the list of courses contained within this catalog. Only courses with active course runs are returned. A course run is considered active if it is currently open for enrollment, or will ...
Retrieve the list of courses contained within this catalog. Only courses with active course runs are returned. A course run is considered active if it is currently open for enrollment, or will open in the future.
Below is the the instruction that describes the task: ### Input: Retrieve the list of courses contained within this catalog. Only courses with active course runs are returned. A course run is considered active if it is currently open for enrollment, or will open in the future. ### Response: def co...
def circ_rayleigh(alpha, w=None, d=None): """Rayleigh test for non-uniformity of circular data. Parameters ---------- alpha : np.array Sample of angles in radians. w : np.array Number of incidences in case of binned angle data. d : float Spacing (in radians) of bin cente...
Rayleigh test for non-uniformity of circular data. Parameters ---------- alpha : np.array Sample of angles in radians. w : np.array Number of incidences in case of binned angle data. d : float Spacing (in radians) of bin centers for binned data. If supplied, a correc...
Below is the the instruction that describes the task: ### Input: Rayleigh test for non-uniformity of circular data. Parameters ---------- alpha : np.array Sample of angles in radians. w : np.array Number of incidences in case of binned angle data. d : float Spacing (in r...
def request(key, features, query, timeout=5): """Make an API request :param string key: API key to use :param list features: features to request. It must be a subset of :data:`FEATURES` :param string query: query to send :param integer timeout: timeout of the request :returns: result of the API...
Make an API request :param string key: API key to use :param list features: features to request. It must be a subset of :data:`FEATURES` :param string query: query to send :param integer timeout: timeout of the request :returns: result of the API request :rtype: dict
Below is the the instruction that describes the task: ### Input: Make an API request :param string key: API key to use :param list features: features to request. It must be a subset of :data:`FEATURES` :param string query: query to send :param integer timeout: timeout of the request :returns: r...
def update_metadata(self, loadbalancer, metadata, node=None): """ Updates the existing metadata with the supplied dictionary. If 'node' is supplied, the metadata for that node is updated instead of for the load balancer. """ # Get the existing metadata md = self.g...
Updates the existing metadata with the supplied dictionary. If 'node' is supplied, the metadata for that node is updated instead of for the load balancer.
Below is the the instruction that describes the task: ### Input: Updates the existing metadata with the supplied dictionary. If 'node' is supplied, the metadata for that node is updated instead of for the load balancer. ### Response: def update_metadata(self, loadbalancer, metadata, node=None): ...
def scan_codes(code_types, image): """ Get *code_type* codes from a PIL Image. *code_type* can be any of zbar supported code type [#zbar_symbologies]_: - **EAN/UPC**: EAN-13 (`ean13`), UPC-A (`upca`), EAN-8 (`ean8`) and UPC-E (`upce`) - **Linear barcode**: Code 128 (`code128`), Code 93 (`code93`),...
Get *code_type* codes from a PIL Image. *code_type* can be any of zbar supported code type [#zbar_symbologies]_: - **EAN/UPC**: EAN-13 (`ean13`), UPC-A (`upca`), EAN-8 (`ean8`) and UPC-E (`upce`) - **Linear barcode**: Code 128 (`code128`), Code 93 (`code93`), Code 39 (`code39`), Interleaved 2 of 5 (`i25`)...
Below is the the instruction that describes the task: ### Input: Get *code_type* codes from a PIL Image. *code_type* can be any of zbar supported code type [#zbar_symbologies]_: - **EAN/UPC**: EAN-13 (`ean13`), UPC-A (`upca`), EAN-8 (`ean8`) and UPC-E (`upce`) - **Linear barcode**: Code 128 (`code128`...
def relocate(self, destination): """Configure the virtual environment for another path. Args: destination (str): The target path of the virtual environment. Note: This does not actually move the virtual environment. Is only rewrites the metadata required to ...
Configure the virtual environment for another path. Args: destination (str): The target path of the virtual environment. Note: This does not actually move the virtual environment. Is only rewrites the metadata required to support a move.
Below is the the instruction that describes the task: ### Input: Configure the virtual environment for another path. Args: destination (str): The target path of the virtual environment. Note: This does not actually move the virtual environment. Is only rewrites ...
def _resolve_looppart(parts, assign_path, context): """recursive function to resolve multiple assignments on loops""" assign_path = assign_path[:] index = assign_path.pop(0) for part in parts: if part is util.Uninferable: continue if not hasattr(part, "itered"): c...
recursive function to resolve multiple assignments on loops
Below is the the instruction that describes the task: ### Input: recursive function to resolve multiple assignments on loops ### Response: def _resolve_looppart(parts, assign_path, context): """recursive function to resolve multiple assignments on loops""" assign_path = assign_path[:] index = assign_pa...
def send(self, packet, mac_addr=broadcast_addr): """place sent packets directly into the reciever's queues (as if they are connected by wire)""" if self.keep_listening: if mac_addr == self.broadcast_addr: for addr, recv_queue in self.inq.items(): recv_queu...
place sent packets directly into the reciever's queues (as if they are connected by wire)
Below is the the instruction that describes the task: ### Input: place sent packets directly into the reciever's queues (as if they are connected by wire) ### Response: def send(self, packet, mac_addr=broadcast_addr): """place sent packets directly into the reciever's queues (as if they are connected by wi...
def _in_deferred_types(self, cls): """ Check if the given class is specified in the deferred type registry. Returns the printer from the registry if it exists, and None if the class is not in the registry. Successful matches will be moved to the regular type registry for future ...
Check if the given class is specified in the deferred type registry. Returns the printer from the registry if it exists, and None if the class is not in the registry. Successful matches will be moved to the regular type registry for future use.
Below is the the instruction that describes the task: ### Input: Check if the given class is specified in the deferred type registry. Returns the printer from the registry if it exists, and None if the class is not in the registry. Successful matches will be moved to the regular type regist...
def bind_switcher(cls): """ Bind the switch checkbox to functions for switching between types of inputs. """ def show_two_conspect(): cls.is_twoconspect = True # search by class for el in cls.two_conspect_el: el.style.display =...
Bind the switch checkbox to functions for switching between types of inputs.
Below is the the instruction that describes the task: ### Input: Bind the switch checkbox to functions for switching between types of inputs. ### Response: def bind_switcher(cls): """ Bind the switch checkbox to functions for switching between types of inputs. """ de...
def fromJSON(value): """loads the GP object from a JSON string """ j = json.loads(value) v = GPDataFile() if "defaultValue" in j: v.value = j['defaultValue'] else: v.value = j['value'] if 'paramName' in j: v.paramName = j['paramName'] ...
loads the GP object from a JSON string
Below is the the instruction that describes the task: ### Input: loads the GP object from a JSON string ### Response: def fromJSON(value): """loads the GP object from a JSON string """ j = json.loads(value) v = GPDataFile() if "defaultValue" in j: v.value = j['defaultVal...
def solve(self, solver_klass=None): """ Solves an optimal power flow and returns a results dictionary. """ # Start the clock. t0 = time() # Build an OPF model with variables and constraints. om = self._construct_opf_model(self.case) if om is None: ret...
Solves an optimal power flow and returns a results dictionary.
Below is the the instruction that describes the task: ### Input: Solves an optimal power flow and returns a results dictionary. ### Response: def solve(self, solver_klass=None): """ Solves an optimal power flow and returns a results dictionary. """ # Start the clock. t0 = time() ...
def delete(self, key): """Implementation of :meth:`~simplekv.KeyValueStore.delete`. If an exception occurs in either the cache or backing store, all are passing on. """ self._dstore.delete(key) self.cache.delete(key)
Implementation of :meth:`~simplekv.KeyValueStore.delete`. If an exception occurs in either the cache or backing store, all are passing on.
Below is the the instruction that describes the task: ### Input: Implementation of :meth:`~simplekv.KeyValueStore.delete`. If an exception occurs in either the cache or backing store, all are passing on. ### Response: def delete(self, key): """Implementation of :meth:`~simplekv.KeyValueSto...
def BinarySigmoid(self, func): ''' Currently, caffe2 does not support this function. ''' n = onnx.helper.make_node( 'HardSigmoid', func.input, func.output, alpha=1.0, beta=0.0 ) return [n]
Currently, caffe2 does not support this function.
Below is the the instruction that describes the task: ### Input: Currently, caffe2 does not support this function. ### Response: def BinarySigmoid(self, func): ''' Currently, caffe2 does not support this function. ''' n = onnx.helper.make_node( 'HardSigmoid', ...
def biasFromLocations(locs, preferOrigin=True): """ Find the vector that translates the whole system to the origin. """ dims = {} locs.sort() for l in locs: for d in l.keys(): if not d in dims: dims[d] = [] v = l[d] if type(v)==tup...
Find the vector that translates the whole system to the origin.
Below is the the instruction that describes the task: ### Input: Find the vector that translates the whole system to the origin. ### Response: def biasFromLocations(locs, preferOrigin=True): """ Find the vector that translates the whole system to the origin. """ dims = {} locs.sort() f...
def _proper_namespace(self, owner=None, app=None, sharing=None): """Produce a namespace sans wildcards for use in entity requests. This method tries to fill in the fields of the namespace which are `None` or wildcard (`'-'`) from the entity's namespace. If that fails, it uses the servic...
Produce a namespace sans wildcards for use in entity requests. This method tries to fill in the fields of the namespace which are `None` or wildcard (`'-'`) from the entity's namespace. If that fails, it uses the service's namespace. :param owner: :param app: :param sha...
Below is the the instruction that describes the task: ### Input: Produce a namespace sans wildcards for use in entity requests. This method tries to fill in the fields of the namespace which are `None` or wildcard (`'-'`) from the entity's namespace. If that fails, it uses the service's nam...
def deserialize_data(self, buffer=bytes(), byte_order=None): """ De-serializes the :attr:`data` object referenced by the `Pointer` field from the byte *buffer* by mapping the bytes to the :attr:`~Field.value` for each :class:`Field` in the :attr:`data` object in accordance with the decod...
De-serializes the :attr:`data` object referenced by the `Pointer` field from the byte *buffer* by mapping the bytes to the :attr:`~Field.value` for each :class:`Field` in the :attr:`data` object in accordance with the decoding *byte order* for the de-serialization and the decoding :attr:...
Below is the the instruction that describes the task: ### Input: De-serializes the :attr:`data` object referenced by the `Pointer` field from the byte *buffer* by mapping the bytes to the :attr:`~Field.value` for each :class:`Field` in the :attr:`data` object in accordance with the decoding ...
def update(self, stats, duration=3, cs_status=None, return_to_browser=False): """Update the screen. INPUT stats: Stats database to display duration: duration of the loop cs_status: "None": standalone or serv...
Update the screen. INPUT stats: Stats database to display duration: duration of the loop cs_status: "None": standalone or server mode "Connected": Client is connected to the server "Disconnected": Client is disconnected from the server return_...
Below is the the instruction that describes the task: ### Input: Update the screen. INPUT stats: Stats database to display duration: duration of the loop cs_status: "None": standalone or server mode "Connected": Client is connected to the server "...
def _final_redis_call(self, final_set, sort_options): """ The final redis call to obtain the values to return from the "final_set" with some sort options. """ conn = self.cls.get_connection() if sort_options is not None: # a sort, or values, call the SORT com...
The final redis call to obtain the values to return from the "final_set" with some sort options.
Below is the the instruction that describes the task: ### Input: The final redis call to obtain the values to return from the "final_set" with some sort options. ### Response: def _final_redis_call(self, final_set, sort_options): """ The final redis call to obtain the values to return from ...
def action_object(self, obj, **kwargs): """ Stream of most recent actions where obj is the action_object. Keyword arguments will be passed to Action.objects.filter """ check(obj) return obj.action_object_actions.public(**kwargs)
Stream of most recent actions where obj is the action_object. Keyword arguments will be passed to Action.objects.filter
Below is the the instruction that describes the task: ### Input: Stream of most recent actions where obj is the action_object. Keyword arguments will be passed to Action.objects.filter ### Response: def action_object(self, obj, **kwargs): """ Stream of most recent actions where obj is the a...
def ensure_loopback_device(path, size): ''' Ensure a loopback device exists for a given backing file path and size. If it a loopback device is not mapped to file, a new one will be created. TODO: Confirm size of found loopback device. :returns: str: Full path to the ensured loopback device (eg, /d...
Ensure a loopback device exists for a given backing file path and size. If it a loopback device is not mapped to file, a new one will be created. TODO: Confirm size of found loopback device. :returns: str: Full path to the ensured loopback device (eg, /dev/loop0)
Below is the the instruction that describes the task: ### Input: Ensure a loopback device exists for a given backing file path and size. If it a loopback device is not mapped to file, a new one will be created. TODO: Confirm size of found loopback device. :returns: str: Full path to the ensured loopba...
def _plot2d(plotfunc): """ Decorator for common 2d plotting logic Also adds the 2d plot method to class _PlotMethods """ commondoc = """ Parameters ---------- darray : DataArray Must be 2 dimensional, unless creating faceted plots x : string, optional Coordinate for ...
Decorator for common 2d plotting logic Also adds the 2d plot method to class _PlotMethods
Below is the the instruction that describes the task: ### Input: Decorator for common 2d plotting logic Also adds the 2d plot method to class _PlotMethods ### Response: def _plot2d(plotfunc): """ Decorator for common 2d plotting logic Also adds the 2d plot method to class _PlotMethods """ ...
def add_service(self, zconf, typ, name): """ Add a service to the collection. """ service = None tries = 0 _LOGGER.debug("add_service %s, %s", typ, name) while service is None and tries < 4: try: service = zconf.get_service_info(typ, name) ...
Add a service to the collection.
Below is the the instruction that describes the task: ### Input: Add a service to the collection. ### Response: def add_service(self, zconf, typ, name): """ Add a service to the collection. """ service = None tries = 0 _LOGGER.debug("add_service %s, %s", typ, name) while ser...
def _request(self, *args, **kwargs): # type (Any) -> Response """Make requests using configured :class:`requests.Session`. Any error details will be extracted to an :class:`HTTPError` which will contain relevant error details when printed.""" self._amend_request_kwargs(kwargs) ...
Make requests using configured :class:`requests.Session`. Any error details will be extracted to an :class:`HTTPError` which will contain relevant error details when printed.
Below is the the instruction that describes the task: ### Input: Make requests using configured :class:`requests.Session`. Any error details will be extracted to an :class:`HTTPError` which will contain relevant error details when printed. ### Response: def _request(self, *args, **kwargs): ...
def reduce_max(x, disable_positional_args=None, output_shape=None, reduced_dim=None, name=None): """Reduction on 1 or more axes. Args: x: a Tensor disable_positional_args: None output_shape: an optional Shape. Must be a subsequence of x.shape...
Reduction on 1 or more axes. Args: x: a Tensor disable_positional_args: None output_shape: an optional Shape. Must be a subsequence of x.shape. reduced_dim: an optional Dimension name: an optional string Returns: a Tensor
Below is the the instruction that describes the task: ### Input: Reduction on 1 or more axes. Args: x: a Tensor disable_positional_args: None output_shape: an optional Shape. Must be a subsequence of x.shape. reduced_dim: an optional Dimension name: an optional string Returns: a Tensor...
def reset(self): """ Stops the timer and resets its values to 0. """ self._elapsed = datetime.timedelta() self._delta = datetime.timedelta() self._starttime = datetime.datetime.now() self.refresh()
Stops the timer and resets its values to 0.
Below is the the instruction that describes the task: ### Input: Stops the timer and resets its values to 0. ### Response: def reset(self): """ Stops the timer and resets its values to 0. """ self._elapsed = datetime.timedelta() self._delta = datetime.timedelta() ...
def requestedFormat(request,acceptedFormat): """Return the response format requested by client Client could specify requested format using: (options are processed in this order) - `format` field in http request - `Accept` header in http request Example: ...
Return the response format requested by client Client could specify requested format using: (options are processed in this order) - `format` field in http request - `Accept` header in http request Example: chooseFormat(request, ['text/html','application/json'...
Below is the the instruction that describes the task: ### Input: Return the response format requested by client Client could specify requested format using: (options are processed in this order) - `format` field in http request - `Accept` header in http request Examp...
def clone(kwargs=None, call=None): ''' Clone a Linode. linode_id The ID of the Linode to clone. Required. datacenter_id The ID of the Datacenter where the Linode will be placed. Required. plan_id The ID of the plan (size) of the Linode. Required. CLI Example: .. ...
Clone a Linode. linode_id The ID of the Linode to clone. Required. datacenter_id The ID of the Datacenter where the Linode will be placed. Required. plan_id The ID of the plan (size) of the Linode. Required. CLI Example: .. code-block:: bash salt-cloud -f clone ...
Below is the the instruction that describes the task: ### Input: Clone a Linode. linode_id The ID of the Linode to clone. Required. datacenter_id The ID of the Datacenter where the Linode will be placed. Required. plan_id The ID of the plan (size) of the Linode. Required. ...
def database_remove_tags(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /database-xxxx/removeTags API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Tags#API-method%3A-%2Fclass-xxxx%2FremoveTags """ return DXHTTPRequest('/%s/removeTags' % o...
Invokes the /database-xxxx/removeTags API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Tags#API-method%3A-%2Fclass-xxxx%2FremoveTags
Below is the the instruction that describes the task: ### Input: Invokes the /database-xxxx/removeTags API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Tags#API-method%3A-%2Fclass-xxxx%2FremoveTags ### Response: def database_remove_tags(object_id, input_params={}, always_retr...
def mkpart(device, part_type, fs_type=None, start=None, end=None): ''' Make a part_type partition for filesystem fs_type, beginning at start and ending at end (by default in megabytes). part_type should be one of "primary", "logical", or "extended". CLI Examples: .. code-block:: bash ...
Make a part_type partition for filesystem fs_type, beginning at start and ending at end (by default in megabytes). part_type should be one of "primary", "logical", or "extended". CLI Examples: .. code-block:: bash salt '*' partition.mkpart /dev/sda primary fs_type=fat32 start=0 end=639 ...
Below is the the instruction that describes the task: ### Input: Make a part_type partition for filesystem fs_type, beginning at start and ending at end (by default in megabytes). part_type should be one of "primary", "logical", or "extended". CLI Examples: .. code-block:: bash salt '*' ...
def reset_term_stats(set_id, term_id, client_id, user_id, access_token): """Reset the stats of a term by deleting and re-creating it.""" found_sets = [user_set for user_set in get_user_sets(client_id, user_id) if user_set.set_id == set_id] if len(found_sets) != 1: raise ValueError(...
Reset the stats of a term by deleting and re-creating it.
Below is the the instruction that describes the task: ### Input: Reset the stats of a term by deleting and re-creating it. ### Response: def reset_term_stats(set_id, term_id, client_id, user_id, access_token): """Reset the stats of a term by deleting and re-creating it.""" found_sets = [user_set for user_s...
def error(self, argparser, target, message): """ This was used as part of the original non-recursive lookup for the target parser. """ warnings.warn( 'Runtime.error is deprecated and will be removed by calmjs-4.0.0', DeprecationWarning) details = ...
This was used as part of the original non-recursive lookup for the target parser.
Below is the the instruction that describes the task: ### Input: This was used as part of the original non-recursive lookup for the target parser. ### Response: def error(self, argparser, target, message): """ This was used as part of the original non-recursive lookup for the target...
def clean_up(files): '''clean up will delete a list of files, only if they exist ''' if not isinstance(files, list): files = [files] for f in files: if os.path.exists(f): bot.verbose3("Cleaning up %s" % f) os.remove(f)
clean up will delete a list of files, only if they exist
Below is the the instruction that describes the task: ### Input: clean up will delete a list of files, only if they exist ### Response: def clean_up(files): '''clean up will delete a list of files, only if they exist ''' if not isinstance(files, list): files = [files] for f in files: ...
def get_assembly_names(): """return list of available assemblies >>> assy_names = get_assembly_names() >>> 'GRCh37.p13' in assy_names True """ return [ n.replace(".json.gz", "") for n in pkg_resources.resource_listdir(__name__, _assy_dir) if n.endswith(".json.gz")...
return list of available assemblies >>> assy_names = get_assembly_names() >>> 'GRCh37.p13' in assy_names True
Below is the the instruction that describes the task: ### Input: return list of available assemblies >>> assy_names = get_assembly_names() >>> 'GRCh37.p13' in assy_names True ### Response: def get_assembly_names(): """return list of available assemblies >>> assy_names = get_assembly_...
def print_grains(self): ''' Print out the grains ''' grains = self.minion.opts.get('grains') or salt.loader.grains(self.opts) salt.output.display_output({'local': grains}, 'grains', self.opts)
Print out the grains
Below is the the instruction that describes the task: ### Input: Print out the grains ### Response: def print_grains(self): ''' Print out the grains ''' grains = self.minion.opts.get('grains') or salt.loader.grains(self.opts) salt.output.display_output({'local': grains}, 'gr...
def disassembler(co, lasti= -1): """Disassemble a code object. :param co: code object :param lasti: internal :yields: Instructions. """ code = co.co_code labels = dis.findlabels(code) linestarts = dict(dis.findlinestarts(co)) i = 0 extended_arg = 0 lineno = 0 ...
Disassemble a code object. :param co: code object :param lasti: internal :yields: Instructions.
Below is the the instruction that describes the task: ### Input: Disassemble a code object. :param co: code object :param lasti: internal :yields: Instructions. ### Response: def disassembler(co, lasti= -1): """Disassemble a code object. :param co: code object :param lasti: inte...
def validate_wrap(self, value): ''' Validates the type and length of ``value`` ''' if not isinstance(value, basestring): self._fail_validation_type(value, basestring) if self.max is not None and len(value) > self.max: self._fail_validation(value, 'Value too long (%d)' % l...
Validates the type and length of ``value``
Below is the the instruction that describes the task: ### Input: Validates the type and length of ``value`` ### Response: def validate_wrap(self, value): ''' Validates the type and length of ``value`` ''' if not isinstance(value, basestring): self._fail_validation_type(value, basestring...
def makeService(opt): """Return a service based on parsed command-line options :param opt: dict-like object. Relevant keys are config, messages, pid, frequency, threshold, killtime, minrestartdelay and maxrestartdelay :returns: service, {twisted.application.interfaces.IServi...
Return a service based on parsed command-line options :param opt: dict-like object. Relevant keys are config, messages, pid, frequency, threshold, killtime, minrestartdelay and maxrestartdelay :returns: service, {twisted.application.interfaces.IService}
Below is the the instruction that describes the task: ### Input: Return a service based on parsed command-line options :param opt: dict-like object. Relevant keys are config, messages, pid, frequency, threshold, killtime, minrestartdelay and maxrestartdelay :returns: service...
def finalize(self): """Disables redirection""" if self._original_steam is not None and self._redirection: sys.stdout = self._original_steam print('Disabled redirection of `stdout`.') self._redirection = False self._original_steam = None
Disables redirection
Below is the the instruction that describes the task: ### Input: Disables redirection ### Response: def finalize(self): """Disables redirection""" if self._original_steam is not None and self._redirection: sys.stdout = self._original_steam print('Disabled redirection of `std...
def forward_log_det_jacobian_fn(bijector): """Makes a function which applies a list of Bijectors' `log_det_jacobian`s.""" if not mcmc_util.is_list_like(bijector): bijector = [bijector] def fn(transformed_state_parts, event_ndims): return sum([ b.forward_log_det_jacobian(sp, event_ndims=e) ...
Makes a function which applies a list of Bijectors' `log_det_jacobian`s.
Below is the the instruction that describes the task: ### Input: Makes a function which applies a list of Bijectors' `log_det_jacobian`s. ### Response: def forward_log_det_jacobian_fn(bijector): """Makes a function which applies a list of Bijectors' `log_det_jacobian`s.""" if not mcmc_util.is_list_like(bijecto...
def decode_randomness(randomness: str) -> bytes: """ Decode the given Base32 encoded :class:`~str` instance to :class:`~bytes`. The given :class:`~str` are expected to represent the last 16 characters of a ULID, which are cryptographically secure random values. .. note:: This uses an optimized str...
Decode the given Base32 encoded :class:`~str` instance to :class:`~bytes`. The given :class:`~str` are expected to represent the last 16 characters of a ULID, which are cryptographically secure random values. .. note:: This uses an optimized strategy from the `NUlid` project for decoding ULID stri...
Below is the the instruction that describes the task: ### Input: Decode the given Base32 encoded :class:`~str` instance to :class:`~bytes`. The given :class:`~str` are expected to represent the last 16 characters of a ULID, which are cryptographically secure random values. .. note:: This uses an optim...
def uptodate(name, software=True, drivers=False, skip_hidden=False, skip_mandatory=False, skip_reboot=True, categories=None, severities=None,): ''' Ensure Microsoft Updates that match the passed criteria are installed. ...
Ensure Microsoft Updates that match the passed criteria are installed. Updates will be downloaded if needed. This state allows you to update a system without specifying a specific update to apply. All matching updates will be installed. Args: name (str): The name has no functional...
Below is the the instruction that describes the task: ### Input: Ensure Microsoft Updates that match the passed criteria are installed. Updates will be downloaded if needed. This state allows you to update a system without specifying a specific update to apply. All matching updates will be installed. ...
def _retrieve_config_xml(config_xml, saltenv): ''' Helper to cache the config XML and raise a CommandExecutionError if we fail to do so. If we successfully cache the file, return the cached path. ''' ret = __salt__['cp.cache_file'](config_xml, saltenv) if not ret: raise CommandExecution...
Helper to cache the config XML and raise a CommandExecutionError if we fail to do so. If we successfully cache the file, return the cached path.
Below is the the instruction that describes the task: ### Input: Helper to cache the config XML and raise a CommandExecutionError if we fail to do so. If we successfully cache the file, return the cached path. ### Response: def _retrieve_config_xml(config_xml, saltenv): ''' Helper to cache the config X...
def reconnect(self): """断线重连.""" self.closed = True self.connect() if self.debug: print("reconnect to {}".format((self.hostname, self.port)))
断线重连.
Below is the the instruction that describes the task: ### Input: 断线重连. ### Response: def reconnect(self): """断线重连.""" self.closed = True self.connect() if self.debug: print("reconnect to {}".format((self.hostname, self.port)))
def parse(self, contents): """Parse the document. :param contents: The text contents of the document. :rtype: a *generator* of tokenized text. """ i = 0 for text in contents.split(self.delim): if not len(text.strip()): continue wor...
Parse the document. :param contents: The text contents of the document. :rtype: a *generator* of tokenized text.
Below is the the instruction that describes the task: ### Input: Parse the document. :param contents: The text contents of the document. :rtype: a *generator* of tokenized text. ### Response: def parse(self, contents): """Parse the document. :param contents: The text contents of t...
def _dataset_line(args): """Implements the BigQuery dataset magic subcommand used to operate on datasets The supported syntax is: %bq datasets <command> <args> Commands: {list, create, delete} Args: args: the optional arguments following '%bq datasets command'. """ if args['command'] == 'list...
Implements the BigQuery dataset magic subcommand used to operate on datasets The supported syntax is: %bq datasets <command> <args> Commands: {list, create, delete} Args: args: the optional arguments following '%bq datasets command'.
Below is the the instruction that describes the task: ### Input: Implements the BigQuery dataset magic subcommand used to operate on datasets The supported syntax is: %bq datasets <command> <args> Commands: {list, create, delete} Args: args: the optional arguments following '%bq datasets comman...
def onThemeColor(self, color, item): """pass theme colors to bottom panel""" bconf = self.panel_bot.conf if item == 'grid': bconf.set_gridcolor(color) elif item == 'bg': bconf.set_bgcolor(color) elif item == 'frame': bconf.set_framecolor(color)...
pass theme colors to bottom panel
Below is the the instruction that describes the task: ### Input: pass theme colors to bottom panel ### Response: def onThemeColor(self, color, item): """pass theme colors to bottom panel""" bconf = self.panel_bot.conf if item == 'grid': bconf.set_gridcolor(color) elif it...
def from_dict(data, ctx): """ Instantiate a new QuoteHomeConversionFactors from a dict (generally from loading a JSON response). The data used to instantiate the QuoteHomeConversionFactors is a shallow copy of the dict passed in, with any complex child types instantiated appropri...
Instantiate a new QuoteHomeConversionFactors from a dict (generally from loading a JSON response). The data used to instantiate the QuoteHomeConversionFactors is a shallow copy of the dict passed in, with any complex child types instantiated appropriately.
Below is the the instruction that describes the task: ### Input: Instantiate a new QuoteHomeConversionFactors from a dict (generally from loading a JSON response). The data used to instantiate the QuoteHomeConversionFactors is a shallow copy of the dict passed in, with any complex child type...
def to_xdr_object(self): """Creates an XDR Operation object that represents this :class:`SetOptions`. """ def assert_option_array(x): if x is None: return [] if not isinstance(x, list): return [x] return x if ...
Creates an XDR Operation object that represents this :class:`SetOptions`.
Below is the the instruction that describes the task: ### Input: Creates an XDR Operation object that represents this :class:`SetOptions`. ### Response: def to_xdr_object(self): """Creates an XDR Operation object that represents this :class:`SetOptions`. """ def assert_opt...
def destroy(self): """Destroy an app and all its add-ons""" result = self._result( ["heroku", "apps:destroy", "--app", self.name, "--confirm", self.name] ) return result
Destroy an app and all its add-ons
Below is the the instruction that describes the task: ### Input: Destroy an app and all its add-ons ### Response: def destroy(self): """Destroy an app and all its add-ons""" result = self._result( ["heroku", "apps:destroy", "--app", self.name, "--confirm", self.name] ) r...
def set_logging(self, log_level=logging.ERROR, file_path_name=None): """ This function allows to change the logging backend, either output or file as backend It also allows to set the logging level (whether to display only critical/error/info/debug. for example:: yag = yagma...
This function allows to change the logging backend, either output or file as backend It also allows to set the logging level (whether to display only critical/error/info/debug. for example:: yag = yagmail.SMTP() yag.set_logging(yagmail.logging.DEBUG) # to see everything ...
Below is the the instruction that describes the task: ### Input: This function allows to change the logging backend, either output or file as backend It also allows to set the logging level (whether to display only critical/error/info/debug. for example:: yag = yagmail.SMTP() ...
def _previous(self): """Get the previous summary and present it.""" self.summaries.rotate() current_summary = self.summaries[0] self._update_summary(current_summary)
Get the previous summary and present it.
Below is the the instruction that describes the task: ### Input: Get the previous summary and present it. ### Response: def _previous(self): """Get the previous summary and present it.""" self.summaries.rotate() current_summary = self.summaries[0] self._update_summary(current_summar...
def _init_id2gos(assoc_fn): ##, no_top=False): """ Reads a gene id go term association file. The format of the file is as follows: AAR1 GO:0005575;GO:0003674;GO:0006970;GO:0006970;GO:0040029 AAR2 GO:0005575;GO:0003674;GO:0040029;GO:0009845 ACD5 GO:0005575;GO:0003674;GO:...
Reads a gene id go term association file. The format of the file is as follows: AAR1 GO:0005575;GO:0003674;GO:0006970;GO:0006970;GO:0040029 AAR2 GO:0005575;GO:0003674;GO:0040029;GO:0009845 ACD5 GO:0005575;GO:0003674;GO:0008219 ACL1 GO:0005575;GO:0003674;GO:0009965;GO:0010073 ...
Below is the the instruction that describes the task: ### Input: Reads a gene id go term association file. The format of the file is as follows: AAR1 GO:0005575;GO:0003674;GO:0006970;GO:0006970;GO:0040029 AAR2 GO:0005575;GO:0003674;GO:0040029;GO:0009845 ACD5 GO:0005575;GO:0003674;GO...
def request_args(self): ''' Returns the arguments passed with the request in a dictionary. Returns both URL resolved arguments and query string arguments. ''' kwargs = {} kwargs.update(self.request.match_info.items()) kwargs.update(self.request.query.items()) ...
Returns the arguments passed with the request in a dictionary. Returns both URL resolved arguments and query string arguments.
Below is the the instruction that describes the task: ### Input: Returns the arguments passed with the request in a dictionary. Returns both URL resolved arguments and query string arguments. ### Response: def request_args(self): ''' Returns the arguments passed with the request in a dictio...
def _batches(iterable, size): """ Take an iterator and yield its contents in groups of `size` items. """ sourceiter = iter(iterable) while True: try: batchiter = islice(sourceiter, size) yield chain([next(batchiter)], batchiter) except StopIteration: ...
Take an iterator and yield its contents in groups of `size` items.
Below is the the instruction that describes the task: ### Input: Take an iterator and yield its contents in groups of `size` items. ### Response: def _batches(iterable, size): """ Take an iterator and yield its contents in groups of `size` items. """ sourceiter = iter(iterable) while True: ...
def click(self, selector, btn=0): """ Click the targeted element. :param selector: A CSS3 selector to targeted element. :param btn: The number of mouse button. 0 - left button, 1 - middle button, 2 - right button """ return self.evalua...
Click the targeted element. :param selector: A CSS3 selector to targeted element. :param btn: The number of mouse button. 0 - left button, 1 - middle button, 2 - right button
Below is the the instruction that describes the task: ### Input: Click the targeted element. :param selector: A CSS3 selector to targeted element. :param btn: The number of mouse button. 0 - left button, 1 - middle button, 2 - right button ### Response: def clic...
def display_event(div, attributes=[]): """ Function to build a suitable CustomJS to display the current event in the div model. """ style = 'float: left; clear: left; font-size: 10pt' return CustomJS(args=dict(div=div), code=""" var attrs = %s; var args = []; for (var i =...
Function to build a suitable CustomJS to display the current event in the div model.
Below is the the instruction that describes the task: ### Input: Function to build a suitable CustomJS to display the current event in the div model. ### Response: def display_event(div, attributes=[]): """ Function to build a suitable CustomJS to display the current event in the div model. """...
def fitPlaneLSQ(XYZ): """Fit a plane to input point data using LSQ """ [rows,cols] = XYZ.shape G = np.ones((rows,3)) G[:,0] = XYZ[:,0] #X G[:,1] = XYZ[:,1] #Y Z = XYZ[:,2] coeff,resid,rank,s = np.linalg.lstsq(G,Z,rcond=None) return coeff
Fit a plane to input point data using LSQ
Below is the the instruction that describes the task: ### Input: Fit a plane to input point data using LSQ ### Response: def fitPlaneLSQ(XYZ): """Fit a plane to input point data using LSQ """ [rows,cols] = XYZ.shape G = np.ones((rows,3)) G[:,0] = XYZ[:,0] #X G[:,1] = XYZ[:,1] #Y Z = X...
def default_vrf_unicast_address_family(self, **kwargs): """Create default address family (ipv4/ipv6) under router bgp. Args: afi (str): Address family to configure. (ipv4, ipv6) rbridge_id (str): The rbridge ID of the device on which BGP will be con...
Create default address family (ipv4/ipv6) under router bgp. Args: afi (str): Address family to configure. (ipv4, ipv6) rbridge_id (str): The rbridge ID of the device on which BGP will be configured in a VCS fabric. delete (bool): Deletes the red...
Below is the the instruction that describes the task: ### Input: Create default address family (ipv4/ipv6) under router bgp. Args: afi (str): Address family to configure. (ipv4, ipv6) rbridge_id (str): The rbridge ID of the device on which BGP will be c...
def showActionToolTip(self): """ Shows the tool tip of the action that is currently being hovered over. :param action | <QAction> """ if ( not self.isVisible() ): return geom = self.actionGeometry(self._toolTipAction) pos ...
Shows the tool tip of the action that is currently being hovered over. :param action | <QAction>
Below is the the instruction that describes the task: ### Input: Shows the tool tip of the action that is currently being hovered over. :param action | <QAction> ### Response: def showActionToolTip(self): """ Shows the tool tip of the action that is currently being hovered ove...
def column_exists(cr, table, column): """ Check whether a certain column exists """ cr.execute( 'SELECT count(attname) FROM pg_attribute ' 'WHERE attrelid = ' '( SELECT oid FROM pg_class WHERE relname = %s ) ' 'AND attname = %s', (table, column)) return cr.fetchone()[...
Check whether a certain column exists
Below is the the instruction that describes the task: ### Input: Check whether a certain column exists ### Response: def column_exists(cr, table, column): """ Check whether a certain column exists """ cr.execute( 'SELECT count(attname) FROM pg_attribute ' 'WHERE attrelid = ' '( SELE...
def parse_file(self, filename: str, entry: str=None) -> parsing.Node: """Parse filename using the grammar""" self.from_string = False import os.path with open(filename, 'r') as f: self.parsed_stream(f.read(), os.path.abspath(filename)) if entry is None: en...
Parse filename using the grammar
Below is the the instruction that describes the task: ### Input: Parse filename using the grammar ### Response: def parse_file(self, filename: str, entry: str=None) -> parsing.Node: """Parse filename using the grammar""" self.from_string = False import os.path with open(filename, 'r...
def getState(self): """See comments in base class.""" return dict(_position = self._position, position = self.getPosition(), velocity = self._velocity, bestPosition = self._bestPosition, bestResult = self._bestResult)
See comments in base class.
Below is the the instruction that describes the task: ### Input: See comments in base class. ### Response: def getState(self): """See comments in base class.""" return dict(_position = self._position, position = self.getPosition(), velocity = self._velocity, ...
def humanize(number): """ Return a human-readable string for number. """ # units = ('bytes', 'KB', 'MB', 'GB', 'TB') # base = 1000 units = ('bytes', 'KiB', 'MiB', 'GiB', 'TiB') base = 1024 if number is None: return None pow = int(math.log(number, base)) if number > 0 else 0 pow =...
Return a human-readable string for number.
Below is the the instruction that describes the task: ### Input: Return a human-readable string for number. ### Response: def humanize(number): """ Return a human-readable string for number. """ # units = ('bytes', 'KB', 'MB', 'GB', 'TB') # base = 1000 units = ('bytes', 'KiB', 'MiB', 'GiB', 'TiB') ...
def get(path, objectType, user=None): ''' Get the ACL of an object. Will filter by user if one is provided. Args: path: The path to the object objectType: The type of object (FILE, DIRECTORY, REGISTRY) user: A user name to filter by Returns (dict): A dictionary containing the A...
Get the ACL of an object. Will filter by user if one is provided. Args: path: The path to the object objectType: The type of object (FILE, DIRECTORY, REGISTRY) user: A user name to filter by Returns (dict): A dictionary containing the ACL CLI Example: .. code-block:: bash ...
Below is the the instruction that describes the task: ### Input: Get the ACL of an object. Will filter by user if one is provided. Args: path: The path to the object objectType: The type of object (FILE, DIRECTORY, REGISTRY) user: A user name to filter by Returns (dict): A dictiona...
def _pyfftw_rfftn_empty_aligned(shape, axes, dtype, order='C', n=None): """Patched version of :func:`sporco.linalg.pyfftw_rfftn_empty_aligned`. """ ashp = list(shape) raxis = axes[-1] ashp[raxis] = ashp[raxis] // 2 + 1 cdtype = _complex_dtype(dtype) return cp.empty(ashp, cdtype, order)
Patched version of :func:`sporco.linalg.pyfftw_rfftn_empty_aligned`.
Below is the the instruction that describes the task: ### Input: Patched version of :func:`sporco.linalg.pyfftw_rfftn_empty_aligned`. ### Response: def _pyfftw_rfftn_empty_aligned(shape, axes, dtype, order='C', n=None): """Patched version of :func:`sporco.linalg.pyfftw_rfftn_empty_aligned`. """ ashp =...
def trim_prefix(text, nchr): """Trim characters off of the beginnings of text lines. Parameters ---------- text : str The text to be trimmed, with newlines (\n) separating lines nchr: int The number of spaces to trim off the beginning of a line if it starts with that many s...
Trim characters off of the beginnings of text lines. Parameters ---------- text : str The text to be trimmed, with newlines (\n) separating lines nchr: int The number of spaces to trim off the beginning of a line if it starts with that many spaces Returns ------- t...
Below is the the instruction that describes the task: ### Input: Trim characters off of the beginnings of text lines. Parameters ---------- text : str The text to be trimmed, with newlines (\n) separating lines nchr: int The number of spaces to trim off the beginning of a line if ...
def sync_local_to_changes(org, syncer, fetches, deleted_fetches, progress_callback=None): """ Sync local instances against iterators which return fetches of changed and deleted remote objects. :param * org: the org :param * syncer: the local model syncer :param * fetches: an iterator returning fetc...
Sync local instances against iterators which return fetches of changed and deleted remote objects. :param * org: the org :param * syncer: the local model syncer :param * fetches: an iterator returning fetches of modified remote objects :param * deleted_fetches: an iterator returning fetches of deleted ...
Below is the the instruction that describes the task: ### Input: Sync local instances against iterators which return fetches of changed and deleted remote objects. :param * org: the org :param * syncer: the local model syncer :param * fetches: an iterator returning fetches of modified remote objects ...
def get_socket(host, port, timeout=None): """ Return a socket. :param str host: the hostname to connect to :param int port: the port number to connect to :param timeout: if specified, set the socket timeout """ for res in getaddrinfo(host, port, 0, SOCK_STREAM): af, socktype, proto,...
Return a socket. :param str host: the hostname to connect to :param int port: the port number to connect to :param timeout: if specified, set the socket timeout
Below is the the instruction that describes the task: ### Input: Return a socket. :param str host: the hostname to connect to :param int port: the port number to connect to :param timeout: if specified, set the socket timeout ### Response: def get_socket(host, port, timeout=None): """ Return a...
def _grow(growth, walls, target, i, j, steps, new_steps, res): ''' fills [res] with [distance to next position where target == 1, x coord., y coord. of that position in target] using region growth i,j -> pixel position growth -> a work array, ne...
fills [res] with [distance to next position where target == 1, x coord., y coord. of that position in target] using region growth i,j -> pixel position growth -> a work array, needed to measure the distance steps, new_steps -> current and last posit...
Below is the the instruction that describes the task: ### Input: fills [res] with [distance to next position where target == 1, x coord., y coord. of that position in target] using region growth i,j -> pixel position growth -> a work array, needed to ...
def write_file( task: Task, filename: str, content: str, append: bool = False, dry_run: Optional[bool] = None, ) -> Result: """ Write contents to a file (locally) Arguments: dry_run: Whether to apply changes or not filename: file you want to write into content: c...
Write contents to a file (locally) Arguments: dry_run: Whether to apply changes or not filename: file you want to write into content: content you want to write append: whether you want to replace the contents or append to it Returns: Result object with the following att...
Below is the the instruction that describes the task: ### Input: Write contents to a file (locally) Arguments: dry_run: Whether to apply changes or not filename: file you want to write into content: content you want to write append: whether you want to replace the contents or ap...
def create_app(self, args): """创建应用 在指定区域创建一个新应用,所属应用为当前请求方。 Args: - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: - result 成功返回所创建的应用信息,若失败则返回None - ResponseInfo 请求的Response信息 """ url = '{0}/v3/apps'.form...
创建应用 在指定区域创建一个新应用,所属应用为当前请求方。 Args: - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: - result 成功返回所创建的应用信息,若失败则返回None - ResponseInfo 请求的Response信息
Below is the the instruction that describes the task: ### Input: 创建应用 在指定区域创建一个新应用,所属应用为当前请求方。 Args: - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: - result 成功返回所创建的应用信息,若失败则返回None - ResponseInfo 请求的Response信息 ### Response: ...
def build_response( self, status=NOT_SET, error="", data=None): """build_response :param status: status code :param error: error message :param data: dictionary to send back """ res_node = { "status": status, ...
build_response :param status: status code :param error: error message :param data: dictionary to send back
Below is the the instruction that describes the task: ### Input: build_response :param status: status code :param error: error message :param data: dictionary to send back ### Response: def build_response( self, status=NOT_SET, error="", data...
def _run_tumor_pindel_caller(align_bams, items, ref_file, assoc_files, region=None, out_file=None): """Detect indels with pindel in tumor/[normal] analysis. Only attempts to detect small insertion/deletions and not larger structural events. :param align_bam: (list) bam files ...
Detect indels with pindel in tumor/[normal] analysis. Only attempts to detect small insertion/deletions and not larger structural events. :param align_bam: (list) bam files :param items: (dict) information from yaml :param ref_file: (str) genome in fasta format :param assoc_file: (dict) files for an...
Below is the the instruction that describes the task: ### Input: Detect indels with pindel in tumor/[normal] analysis. Only attempts to detect small insertion/deletions and not larger structural events. :param align_bam: (list) bam files :param items: (dict) information from yaml :param ref_file: (s...
def _get_el_attributes(lxml_el, ns=None, nsmap=None): """Return the XML attributes of lxml ``Element`` instance lxml_el as a dict where namespaced attributes are represented via colon-delimiting and using snake case. """ attrs = {} for attr, val in lxml_el.items(): attr = _to_colon_ns(at...
Return the XML attributes of lxml ``Element`` instance lxml_el as a dict where namespaced attributes are represented via colon-delimiting and using snake case.
Below is the the instruction that describes the task: ### Input: Return the XML attributes of lxml ``Element`` instance lxml_el as a dict where namespaced attributes are represented via colon-delimiting and using snake case. ### Response: def _get_el_attributes(lxml_el, ns=None, nsmap=None): """Return ...
def put(self, resource, obj, operation_timeout=None, max_envelope_size=None, locale=None): """ resource can be a URL or a ResourceLocator """ headers = None return self.service.invoke(headers, obj)
resource can be a URL or a ResourceLocator
Below is the the instruction that describes the task: ### Input: resource can be a URL or a ResourceLocator ### Response: def put(self, resource, obj, operation_timeout=None, max_envelope_size=None, locale=None): """ resource can be a URL or a ResourceLocator """ headers...
def make_fileitem_username(file_owner, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/Username :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/Username' content_type = 'string' content = file_ow...
Create a node for FileItem/Username :return: A IndicatorItem represented as an Element node
Below is the the instruction that describes the task: ### Input: Create a node for FileItem/Username :return: A IndicatorItem represented as an Element node ### Response: def make_fileitem_username(file_owner, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/Usern...
def to_mesh(self): """ Return a copy of the Primitive object as a Trimesh object. """ result = Trimesh(vertices=self.vertices.copy(), faces=self.faces.copy(), face_normals=self.face_normals.copy(), process=False) ...
Return a copy of the Primitive object as a Trimesh object.
Below is the the instruction that describes the task: ### Input: Return a copy of the Primitive object as a Trimesh object. ### Response: def to_mesh(self): """ Return a copy of the Primitive object as a Trimesh object. """ result = Trimesh(vertices=self.vertices.copy(), ...
def json_encode(func): """ Decorator used to change the return value from PJFFactory.fuzzed, it makes the structure printable """ def func_wrapper(self, indent, utf8): if utf8: encoding = "\\x%02x" else: encoding = "\\u%04x" ...
Decorator used to change the return value from PJFFactory.fuzzed, it makes the structure printable
Below is the the instruction that describes the task: ### Input: Decorator used to change the return value from PJFFactory.fuzzed, it makes the structure printable ### Response: def json_encode(func): """ Decorator used to change the return value from PJFFactory.fuzzed, it makes the structure print...
def usage(self, callback=None, errback=None, **kwargs): """ Return the current usage information for this zone :rtype: dict :return: usage information """ stats = Stats(self.config) return stats.usage(zone=self.zone, callback=callback, errback=errback, ...
Return the current usage information for this zone :rtype: dict :return: usage information
Below is the the instruction that describes the task: ### Input: Return the current usage information for this zone :rtype: dict :return: usage information ### Response: def usage(self, callback=None, errback=None, **kwargs): """ Return the current usage information for this zone ...
def lose(): """Enables access to websites that are defined as 'distractors'""" changed = False with open(settings.HOSTS_FILE, "r") as hosts_file: new_file = [] in_block = False for line in hosts_file: if in_block: if line.strip() == settings.END_TOKEN: ...
Enables access to websites that are defined as 'distractors
Below is the the instruction that describes the task: ### Input: Enables access to websites that are defined as 'distractors ### Response: def lose(): """Enables access to websites that are defined as 'distractors'""" changed = False with open(settings.HOSTS_FILE, "r") as hosts_file: new_file =...
def items(self): "Returns all elements as a list in (key,value) format." return list(zip(list(self.keys()), list(self.values())))
Returns all elements as a list in (key,value) format.
Below is the the instruction that describes the task: ### Input: Returns all elements as a list in (key,value) format. ### Response: def items(self): "Returns all elements as a list in (key,value) format." return list(zip(list(self.keys()), list(self.values())))
def set_runtime_value_int(self, ihcid: int, value: int) -> bool: """ Set integer runtime value with re-authenticate if needed""" if self.client.set_runtime_value_int(ihcid, value): return True self.re_authenticate() return self.client.set_runtime_value_int(ihcid, value)
Set integer runtime value with re-authenticate if needed
Below is the the instruction that describes the task: ### Input: Set integer runtime value with re-authenticate if needed ### Response: def set_runtime_value_int(self, ihcid: int, value: int) -> bool: """ Set integer runtime value with re-authenticate if needed""" if self.client.set_runtime_value_i...
def refresh_pillar(**kwargs): ''' Signal the minion to refresh the pillar data. .. versionchanged:: Neon The ``async`` argument has been added. The default value is True. CLI Example: .. code-block:: bash salt '*' saltutil.refresh_pillar salt '*' saltutil.refresh_pillar a...
Signal the minion to refresh the pillar data. .. versionchanged:: Neon The ``async`` argument has been added. The default value is True. CLI Example: .. code-block:: bash salt '*' saltutil.refresh_pillar salt '*' saltutil.refresh_pillar async=False
Below is the the instruction that describes the task: ### Input: Signal the minion to refresh the pillar data. .. versionchanged:: Neon The ``async`` argument has been added. The default value is True. CLI Example: .. code-block:: bash salt '*' saltutil.refresh_pillar salt '*...
def compile(self, session=None): """ Before calling the standard compile function, check to see if the size of the data has changed and add parameters appropriately. This is necessary because the shape of the parameters depends on the shape of the data. """ if no...
Before calling the standard compile function, check to see if the size of the data has changed and add parameters appropriately. This is necessary because the shape of the parameters depends on the shape of the data.
Below is the the instruction that describes the task: ### Input: Before calling the standard compile function, check to see if the size of the data has changed and add parameters appropriately. This is necessary because the shape of the parameters depends on the shape of the data. ### Respo...
def merge_peptides(fns, ns): """Loops peptides from multiple files, fetches PSMs from sequence:PSM map, outputs correctly PSM mapped peptides""" peptides_to_map = reader.generate_peptides_multiple_fractions(fns, ns) psmmap = create_merge_psm_map(peptides_to_map, ns) peptides = reader.generate_peptid...
Loops peptides from multiple files, fetches PSMs from sequence:PSM map, outputs correctly PSM mapped peptides
Below is the the instruction that describes the task: ### Input: Loops peptides from multiple files, fetches PSMs from sequence:PSM map, outputs correctly PSM mapped peptides ### Response: def merge_peptides(fns, ns): """Loops peptides from multiple files, fetches PSMs from sequence:PSM map, outputs co...
def tofile(self, fobj, format): """Write data to hex or bin file. Preferred method over tobin or tohex. @param fobj file name or file-like object @param format file format ("hex" or "bin") """ if format == 'hex': self.write_hex_file(fobj) elif f...
Write data to hex or bin file. Preferred method over tobin or tohex. @param fobj file name or file-like object @param format file format ("hex" or "bin")
Below is the the instruction that describes the task: ### Input: Write data to hex or bin file. Preferred method over tobin or tohex. @param fobj file name or file-like object @param format file format ("hex" or "bin") ### Response: def tofile(self, fobj, format): """Write da...
def replace_strings_in_list(array_of_strigs, replace_with_strings): "A value in replace_with_strings can be either single string or list of strings" potentially_nested_list = [replace_with_strings.get(s) or s for s in array_of_strigs] return list(flatten(potentially_nested_list))
A value in replace_with_strings can be either single string or list of strings
Below is the the instruction that describes the task: ### Input: A value in replace_with_strings can be either single string or list of strings ### Response: def replace_strings_in_list(array_of_strigs, replace_with_strings): "A value in replace_with_strings can be either single string or list of strings" ...
def getParameterArrayCount(self, name, index): """Default implementation that return the length of the attribute. This default implementation goes hand in hand with :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getParameterArray`. If you override one of them in your subclass, you should probably ove...
Default implementation that return the length of the attribute. This default implementation goes hand in hand with :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getParameterArray`. If you override one of them in your subclass, you should probably override both of them. The implementation preven...
Below is the the instruction that describes the task: ### Input: Default implementation that return the length of the attribute. This default implementation goes hand in hand with :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getParameterArray`. If you override one of them in your subclass, you shou...
def sendPREMISEvent(webRoot, eventType, agentIdentifier, eventDetail, eventOutcome, eventOutcomeDetail=None, linkObjectList=[], eventDate=None, debug=False, eventIdentifier=None): """ A function to format an event to be uploaded and send it to a particular CODA server ...
A function to format an event to be uploaded and send it to a particular CODA server in order to register it
Below is the the instruction that describes the task: ### Input: A function to format an event to be uploaded and send it to a particular CODA server in order to register it ### Response: def sendPREMISEvent(webRoot, eventType, agentIdentifier, eventDetail, eventOutcome, eventOutcomeDetail=...
def to_string(self, verbose=0): """String representation.""" lines = [] app = lines.append app("<%s: %s>" % (self.__class__.__name__, self.basename)) app(" summary: " + self.summary.strip()) app(" number of valence electrons: %s" % self.Z_val) app(" maximum ang...
String representation.
Below is the the instruction that describes the task: ### Input: String representation. ### Response: def to_string(self, verbose=0): """String representation.""" lines = [] app = lines.append app("<%s: %s>" % (self.__class__.__name__, self.basename)) app(" summary: " + sel...
def scheduled_status_update(self, id, scheduled_at): """ Update the scheduled time of a scheduled status. New time must be at least 5 minutes into the future. Returns a `scheduled toot dict`_ """ scheduled_at = self.__consistent_isoformat_utc(scheduled_a...
Update the scheduled time of a scheduled status. New time must be at least 5 minutes into the future. Returns a `scheduled toot dict`_
Below is the the instruction that describes the task: ### Input: Update the scheduled time of a scheduled status. New time must be at least 5 minutes into the future. Returns a `scheduled toot dict`_ ### Response: def scheduled_status_update(self, id, scheduled_at): """ ...
def read_release_version(): """Read version information from VERSION file""" try: with open(VERSION_FILE, "r") as infile: version = str(infile.read().strip()) if len(version) == 0: version = None return version except IOError: return None
Read version information from VERSION file
Below is the the instruction that describes the task: ### Input: Read version information from VERSION file ### Response: def read_release_version(): """Read version information from VERSION file""" try: with open(VERSION_FILE, "r") as infile: version = str(infile.read().strip()) ...
def read_dirs(path, folder): ''' Fetches name of all files in path in long form, and labels associated by extrapolation of directory names. ''' lbls, fnames, all_lbls = [], [], [] full_path = os.path.join(path, folder) for lbl in sorted(os.listdir(full_path)): if lbl not in ('.ipynb_che...
Fetches name of all files in path in long form, and labels associated by extrapolation of directory names.
Below is the the instruction that describes the task: ### Input: Fetches name of all files in path in long form, and labels associated by extrapolation of directory names. ### Response: def read_dirs(path, folder): ''' Fetches name of all files in path in long form, and labels associated by extrapolation o...
def get_phonetic_info(self, lang): """For a specified language (lang), it returns the matrix and the vecto containing specifications of the characters. """ phonetic_data = self.all_phonetic_data if lang != LC_TA else self.tamil_phonetic_data phonetic_vectors = self.all_phonetic...
For a specified language (lang), it returns the matrix and the vecto containing specifications of the characters.
Below is the the instruction that describes the task: ### Input: For a specified language (lang), it returns the matrix and the vecto containing specifications of the characters. ### Response: def get_phonetic_info(self, lang): """For a specified language (lang), it returns the matrix and the vect...