code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def initial(self, request, *args, **kwargs): """Disallow users other than the user whose email is being reset.""" email = request.data.get('email') if request.user.is_authenticated() and email != request.user.email: raise PermissionDenied() return super(ResendConfirmationEma...
Disallow users other than the user whose email is being reset.
Below is the the instruction that describes the task: ### Input: Disallow users other than the user whose email is being reset. ### Response: def initial(self, request, *args, **kwargs): """Disallow users other than the user whose email is being reset.""" email = request.data.get('email') i...
def go_to_history(self, index): """ Go to this item in the history. """ if index < len(self._working_lines): self.working_index = index self.cursor_position = len(self.text)
Go to this item in the history.
Below is the the instruction that describes the task: ### Input: Go to this item in the history. ### Response: def go_to_history(self, index): """ Go to this item in the history. """ if index < len(self._working_lines): self.working_index = index self.cursor_...
def _spikes_per_cluster(spike_clusters, spike_ids=None): """Return a dictionary {cluster: list_of_spikes}.""" if spike_clusters is None or not len(spike_clusters): return {} if spike_ids is None: spike_ids = np.arange(len(spike_clusters)).astype(np.int64) # NOTE: this sort method is stab...
Return a dictionary {cluster: list_of_spikes}.
Below is the the instruction that describes the task: ### Input: Return a dictionary {cluster: list_of_spikes}. ### Response: def _spikes_per_cluster(spike_clusters, spike_ids=None): """Return a dictionary {cluster: list_of_spikes}.""" if spike_clusters is None or not len(spike_clusters): return {}...
def handle(self, pkt, raddress, rport): "Handle an initial WRQ packet as a server." log.debug("In TftpStateServerRecvWRQ.handle") sendoack = self.serverInitial(pkt, raddress, rport) path = self.full_path if self.context.upload_open: f = self.context.upload_open(path, ...
Handle an initial WRQ packet as a server.
Below is the the instruction that describes the task: ### Input: Handle an initial WRQ packet as a server. ### Response: def handle(self, pkt, raddress, rport): "Handle an initial WRQ packet as a server." log.debug("In TftpStateServerRecvWRQ.handle") sendoack = self.serverInitial(pkt, raddr...
def wait_msg(self, event, timeout=None, raises=None): """Wait for a message, similiar to :meth:`.wait_event` :param event: :class:`.EMsg' or job id :param timeout: seconds to wait before timeout :type timeout: :class:`int` :param raises: On timeout when ``False` returns :class:`...
Wait for a message, similiar to :meth:`.wait_event` :param event: :class:`.EMsg' or job id :param timeout: seconds to wait before timeout :type timeout: :class:`int` :param raises: On timeout when ``False` returns :class:`None`, else raise :class:`gevent.Timeout` :type raises: :...
Below is the the instruction that describes the task: ### Input: Wait for a message, similiar to :meth:`.wait_event` :param event: :class:`.EMsg' or job id :param timeout: seconds to wait before timeout :type timeout: :class:`int` :param raises: On timeout when ``False` returns :cla...
def evpn_prefix_add(self, route_type, route_dist, esi=0, ethernet_tag_id=None, mac_addr=None, ip_addr=None, ip_prefix=None, gw_ip_addr=None, vni=None, next_hop=None, tunnel_type=None, pmsi_tunnel_type=None, redundancy_mode=N...
This method adds a new EVPN route to be advertised. ``route_type`` specifies one of the EVPN route type name. This parameter must be one of the following. - EVPN_ETH_AUTO_DISCOVERY = 'eth_ad' - EVPN_MAC_IP_ADV_ROUTE = 'mac_ip_adv' - EVPN_MULTICAST_ETAG_ROUTE = 'multicast_...
Below is the the instruction that describes the task: ### Input: This method adds a new EVPN route to be advertised. ``route_type`` specifies one of the EVPN route type name. This parameter must be one of the following. - EVPN_ETH_AUTO_DISCOVERY = 'eth_ad' - EVPN_MAC_IP_ADV_ROUTE...
def windowed(a, windowsize, stepsize=None, dopad=False): """ Parameters a - the input array to restructure into overlapping windows windowsize - the size of each window of samples stepsize - the number of samples to shift the window each step. If not speci...
Parameters a - the input array to restructure into overlapping windows windowsize - the size of each window of samples stepsize - the number of samples to shift the window each step. If not specified, this defaults to windowsize dopad - If false (defa...
Below is the the instruction that describes the task: ### Input: Parameters a - the input array to restructure into overlapping windows windowsize - the size of each window of samples stepsize - the number of samples to shift the window each step. If not speci...
def get_props_from_doc(self, cls, id, doc): """ Pull out the properties from this document Returns the class, the properties in a hash, and the id if provided as a tuple :return: (cls, props, id) """ obj_node = doc.getElementsByTagName('object')[0] if not cls: ...
Pull out the properties from this document Returns the class, the properties in a hash, and the id if provided as a tuple :return: (cls, props, id)
Below is the the instruction that describes the task: ### Input: Pull out the properties from this document Returns the class, the properties in a hash, and the id if provided as a tuple :return: (cls, props, id) ### Response: def get_props_from_doc(self, cls, id, doc): """ Pull out...
def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''...
Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats
Below is the the instruction that describes the task: ### Input: Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ###...
def _construct(self): """ Construct a control dependence graph. This implementation is based on figure 6 of paper An Efficient Method of Computing Static Single Assignment Form by Ron Cytron, etc. """ self._acyclic_cfg = self._cfg.copy() # TODO: Cycle-removing i...
Construct a control dependence graph. This implementation is based on figure 6 of paper An Efficient Method of Computing Static Single Assignment Form by Ron Cytron, etc.
Below is the the instruction that describes the task: ### Input: Construct a control dependence graph. This implementation is based on figure 6 of paper An Efficient Method of Computing Static Single Assignment Form by Ron Cytron, etc. ### Response: def _construct(self): """ Constr...
def __update_order_seed(self, optic_descriptor, neighbors_descriptors, order_seed): """! @brief Update sorted list of reachable objects (from core-object) that should be processed using neighbors of core-object. @param[in] optic_descriptor (optics_descriptor): Core-object whose neig...
! @brief Update sorted list of reachable objects (from core-object) that should be processed using neighbors of core-object. @param[in] optic_descriptor (optics_descriptor): Core-object whose neighbors should be analysed. @param[in] neighbors_descriptors (list): List of neighbors of...
Below is the the instruction that describes the task: ### Input: ! @brief Update sorted list of reachable objects (from core-object) that should be processed using neighbors of core-object. @param[in] optic_descriptor (optics_descriptor): Core-object whose neighbors should be analysed. ...
def load_ccd_data_from_fits(image_path, pixel_scale, image_hdu=0, resized_ccd_shape=None, resized_ccd_origin_pixels=None, resized_ccd_origin_arcsec=None, psf_path=None, psf_hdu=0, resized_psf_shape=None, renormalize_psf=True, ...
Factory for loading the ccd data from .fits files, as well as computing properties like the noise-map, exposure-time map, etc. from the ccd-data. This factory also includes a number of routines for converting the ccd-data from units not supported by PyAutoLens \ (e.g. adus, electrons) to electrons per seco...
Below is the the instruction that describes the task: ### Input: Factory for loading the ccd data from .fits files, as well as computing properties like the noise-map, exposure-time map, etc. from the ccd-data. This factory also includes a number of routines for converting the ccd-data from units not suppo...
def dimensions(self): """Returns terminal dimensions Don't save this information for long periods of time because the user might resize their terminal. :return: Returns ``(width, height)``. If there's no terminal to be found, we'll just return ``(79, 40)``. ""...
Returns terminal dimensions Don't save this information for long periods of time because the user might resize their terminal. :return: Returns ``(width, height)``. If there's no terminal to be found, we'll just return ``(79, 40)``.
Below is the the instruction that describes the task: ### Input: Returns terminal dimensions Don't save this information for long periods of time because the user might resize their terminal. :return: Returns ``(width, height)``. If there's no terminal to be found, we'll ...
def get(self, k, d=None): """Override dict.get() to title-case keys.""" return super(HeaderDict, self).get(k.title(), d)
Override dict.get() to title-case keys.
Below is the the instruction that describes the task: ### Input: Override dict.get() to title-case keys. ### Response: def get(self, k, d=None): """Override dict.get() to title-case keys.""" return super(HeaderDict, self).get(k.title(), d)
def genl_register_family(ops): """Register Generic Netlink family and associated commands. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L164 Registers the specified Generic Netlink family definition together with all associated commands. After registration, received Generic Netlin...
Register Generic Netlink family and associated commands. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L164 Registers the specified Generic Netlink family definition together with all associated commands. After registration, received Generic Netlink messages can be passed to genl_handl...
Below is the the instruction that describes the task: ### Input: Register Generic Netlink family and associated commands. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L164 Registers the specified Generic Netlink family definition together with all associated commands. After registrati...
def get_post_file(self, hdr, f_in, clen, post, files): """Reads from a multipart/form-data.""" lens = { 'clen': clen, 'push': [], } prefix = "boundary=" if not hdr.startswith(prefix): return None boundary = hdr[len(prefix):].strip().enc...
Reads from a multipart/form-data.
Below is the the instruction that describes the task: ### Input: Reads from a multipart/form-data. ### Response: def get_post_file(self, hdr, f_in, clen, post, files): """Reads from a multipart/form-data.""" lens = { 'clen': clen, 'push': [], } prefix = "boun...
def dissociate(self, c, context, hm, pool_id): """Remove a pool association, and the healthmonitor if its the last one""" self._dissociate(c, context, hm, pool_id) pools = hm.get("pools", []) if not any(p for p in pools if p.get("pool_id") != pool_id): self._delete_unused(c,...
Remove a pool association, and the healthmonitor if its the last one
Below is the the instruction that describes the task: ### Input: Remove a pool association, and the healthmonitor if its the last one ### Response: def dissociate(self, c, context, hm, pool_id): """Remove a pool association, and the healthmonitor if its the last one""" self._dissociate(c, context,...
def revdocs2reverts(rev_docs, radius=defaults.RADIUS, use_sha1=False, resort=False, verbose=False): """ Converts a sequence of page-partitioned revision documents into a sequence of reverts. :Params: rev_docs : `iterable` ( `dict` ) a page-partitioned sequence of...
Converts a sequence of page-partitioned revision documents into a sequence of reverts. :Params: rev_docs : `iterable` ( `dict` ) a page-partitioned sequence of revision documents radius : `int` The maximum number of revisions that a revert can reference. use_sha1...
Below is the the instruction that describes the task: ### Input: Converts a sequence of page-partitioned revision documents into a sequence of reverts. :Params: rev_docs : `iterable` ( `dict` ) a page-partitioned sequence of revision documents radius : `int` The maxi...
def check(self, radl): """Check the features in this network.""" SIMPLE_FEATURES = { "host": (str, None), "credentials.username": (str, None), "credentials.password": (str, None), "credentials.private_key": (str, None) } self.check_simple(...
Check the features in this network.
Below is the the instruction that describes the task: ### Input: Check the features in this network. ### Response: def check(self, radl): """Check the features in this network.""" SIMPLE_FEATURES = { "host": (str, None), "credentials.username": (str, None), "cre...
def _find_root_dir(path, spor_dir): """Search for a spor repo containing `path`. This searches for `spor_dir` in directories dominating `path`. If a directory containing `spor_dir` is found, then that directory is returned as a `pathlib.Path`. Returns: The dominating directory containing `spor_dir...
Search for a spor repo containing `path`. This searches for `spor_dir` in directories dominating `path`. If a directory containing `spor_dir` is found, then that directory is returned as a `pathlib.Path`. Returns: The dominating directory containing `spor_dir` as a `pathlib.Path`. Raises: ...
Below is the the instruction that describes the task: ### Input: Search for a spor repo containing `path`. This searches for `spor_dir` in directories dominating `path`. If a directory containing `spor_dir` is found, then that directory is returned as a `pathlib.Path`. Returns: The dominating dire...
def registerEventHandlers(self): """ Registers the up and down handlers. Also registers a scheduled function every 60th of a second, causing pyglet to redraw your window with 60fps. """ # Crouch/fly down self.peng.keybinds.add(self.peng.cfg["controls.controls.cro...
Registers the up and down handlers. Also registers a scheduled function every 60th of a second, causing pyglet to redraw your window with 60fps.
Below is the the instruction that describes the task: ### Input: Registers the up and down handlers. Also registers a scheduled function every 60th of a second, causing pyglet to redraw your window with 60fps. ### Response: def registerEventHandlers(self): """ Registers the up and ...
def setup_sudo_access(plugin): """ Injects a `run_root` method into the provided plugin instance that forks a shell command using sudo. Used for command plugin needs. `plugin` ``Plugin`` instance. """ def run_root(self, command): """ Executes a shell command as root...
Injects a `run_root` method into the provided plugin instance that forks a shell command using sudo. Used for command plugin needs. `plugin` ``Plugin`` instance.
Below is the the instruction that describes the task: ### Input: Injects a `run_root` method into the provided plugin instance that forks a shell command using sudo. Used for command plugin needs. `plugin` ``Plugin`` instance. ### Response: def setup_sudo_access(plugin): """ Inject...
def namespaced_function(function, global_dict, defaults=None, preserve_context=False): ''' Redefine (clone) a function under a different globals() namespace scope preserve_context: Allow keeping the context taken from orignal namespace, and extend it with globals() taken from ...
Redefine (clone) a function under a different globals() namespace scope preserve_context: Allow keeping the context taken from orignal namespace, and extend it with globals() taken from new targetted namespace.
Below is the the instruction that describes the task: ### Input: Redefine (clone) a function under a different globals() namespace scope preserve_context: Allow keeping the context taken from orignal namespace, and extend it with globals() taken from new targetted namesp...
def add_client(self, user_id=None): """ Adds current instance to public or private channel. If user_id is specified it will be added to the private channel, If user_id is not specified it will be added to the public one instead. """ if user_id is None: # gener...
Adds current instance to public or private channel. If user_id is specified it will be added to the private channel, If user_id is not specified it will be added to the public one instead.
Below is the the instruction that describes the task: ### Input: Adds current instance to public or private channel. If user_id is specified it will be added to the private channel, If user_id is not specified it will be added to the public one instead. ### Response: def add_client(self, user_id=No...
def _connect(self, sock, addr, timeout): """Start watching the socket for it to be writtable.""" if self.connection: raise SocketClientConnectedError() if self.connector: raise SocketClientConnectingError() self.connect_deferred = Deferred(self.loop) sel...
Start watching the socket for it to be writtable.
Below is the the instruction that describes the task: ### Input: Start watching the socket for it to be writtable. ### Response: def _connect(self, sock, addr, timeout): """Start watching the socket for it to be writtable.""" if self.connection: raise SocketClientConnectedError() ...
def stop(self): """Stop the current timer if there is one and cancel the async call.""" if self._timer: self._timer.stop() self._timer.deleteLater()
Stop the current timer if there is one and cancel the async call.
Below is the the instruction that describes the task: ### Input: Stop the current timer if there is one and cancel the async call. ### Response: def stop(self): """Stop the current timer if there is one and cancel the async call.""" if self._timer: self._timer.stop() self._t...
def _threeDdot_simple(M,a): "Return Ma, where M is a 3x3 transformation matrix, for each pixel" result = np.empty(a.shape,dtype=a.dtype) for i in range(a.shape[0]): for j in range(a.shape[1]): A = np.array([a[i,j,0],a[i,j,1],a[i,j,2]]).reshape((3,1)) L = np.dot(M,A) ...
Return Ma, where M is a 3x3 transformation matrix, for each pixel
Below is the the instruction that describes the task: ### Input: Return Ma, where M is a 3x3 transformation matrix, for each pixel ### Response: def _threeDdot_simple(M,a): "Return Ma, where M is a 3x3 transformation matrix, for each pixel" result = np.empty(a.shape,dtype=a.dtype) for i in range(a.sh...
def do_bd(self, arg): """ [~process] bd <address> - disable a code breakpoint [~thread] bd <address> - disable a hardware breakpoint [~process] bd <address-address> - disable a memory breakpoint [~process] bd <address> <size> - disable a memory breakpoint """ toke...
[~process] bd <address> - disable a code breakpoint [~thread] bd <address> - disable a hardware breakpoint [~process] bd <address-address> - disable a memory breakpoint [~process] bd <address> <size> - disable a memory breakpoint
Below is the the instruction that describes the task: ### Input: [~process] bd <address> - disable a code breakpoint [~thread] bd <address> - disable a hardware breakpoint [~process] bd <address-address> - disable a memory breakpoint [~process] bd <address> <size> - disable a memory breakpoi...
def delete(self, project_id): ''' Deletes a project by id Args: project_id: The project id to delete Returns: Nothing ''' self.logger.debug('Deleting project by id: ' + project_id) url = '%(base_url)s/%(project_id)s' % { 'ba...
Deletes a project by id Args: project_id: The project id to delete Returns: Nothing
Below is the the instruction that describes the task: ### Input: Deletes a project by id Args: project_id: The project id to delete Returns: Nothing ### Response: def delete(self, project_id): ''' Deletes a project by id Args: projec...
def coerce(cls, key, value): "Convert plain dictionaries to MutableDict." if not isinstance(value, MutableDict): if isinstance(value, dict): return MutableDict(value) # this call will raise ValueError return Mutable.coerce(key, value) else: ...
Convert plain dictionaries to MutableDict.
Below is the the instruction that describes the task: ### Input: Convert plain dictionaries to MutableDict. ### Response: def coerce(cls, key, value): "Convert plain dictionaries to MutableDict." if not isinstance(value, MutableDict): if isinstance(value, dict): return ...
def rotate(self, pitch, roll, yaw): """ Rotate the gimbal to a specific vector. .. code-block:: python #Point the gimbal straight down vehicle.gimbal.rotate(-90, 0, 0) :param pitch: Gimbal pitch in degrees relative to the vehicle (see diagram for :ref:`attitude...
Rotate the gimbal to a specific vector. .. code-block:: python #Point the gimbal straight down vehicle.gimbal.rotate(-90, 0, 0) :param pitch: Gimbal pitch in degrees relative to the vehicle (see diagram for :ref:`attitude <figure_attitude>`). A value of 0 represent...
Below is the the instruction that describes the task: ### Input: Rotate the gimbal to a specific vector. .. code-block:: python #Point the gimbal straight down vehicle.gimbal.rotate(-90, 0, 0) :param pitch: Gimbal pitch in degrees relative to the vehicle (see diagram for :...
def processFlat(self): """Main process for flat segmentation. Returns ------- est_idxs : np.array(N) Estimated times for the segment boundaries in frame indeces. est_labels : np.array(N-1) Estimated labels for the segments. """ # Preprocess...
Main process for flat segmentation. Returns ------- est_idxs : np.array(N) Estimated times for the segment boundaries in frame indeces. est_labels : np.array(N-1) Estimated labels for the segments.
Below is the the instruction that describes the task: ### Input: Main process for flat segmentation. Returns ------- est_idxs : np.array(N) Estimated times for the segment boundaries in frame indeces. est_labels : np.array(N-1) Estimated labels for the segment...
def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') ...
Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data stru...
Below is the the instruction that describes the task: ### Input: Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') ...
def dilate_obs(self, dilation_radius): """ Use a dilation filter to grow positive observation areas by a specified number of grid points :param dilation_radius: Number of times to dilate the grid. :return: """ for s in self.size_thresholds: self.dilated_obs[s...
Use a dilation filter to grow positive observation areas by a specified number of grid points :param dilation_radius: Number of times to dilate the grid. :return:
Below is the the instruction that describes the task: ### Input: Use a dilation filter to grow positive observation areas by a specified number of grid points :param dilation_radius: Number of times to dilate the grid. :return: ### Response: def dilate_obs(self, dilation_radius): """ ...
def shlex_split(s, sep): """Split a character on the given set of characters. Example:: >>> shlex_split('foo,bar', ', ') ['foo', 'bar'] >>> shlex_split('foo\\\\,bar1', ',') # escape a separator ['foo,bar1'] >>> shlex_split('"foo,bar", bla', ', ') ['foo,bar', 'b...
Split a character on the given set of characters. Example:: >>> shlex_split('foo,bar', ', ') ['foo', 'bar'] >>> shlex_split('foo\\\\,bar1', ',') # escape a separator ['foo,bar1'] >>> shlex_split('"foo,bar", bla', ', ') ['foo,bar', 'bla'] >>> shlex_split('fo...
Below is the the instruction that describes the task: ### Input: Split a character on the given set of characters. Example:: >>> shlex_split('foo,bar', ', ') ['foo', 'bar'] >>> shlex_split('foo\\\\,bar1', ',') # escape a separator ['foo,bar1'] >>> shlex_split('"foo,bar...
def loadmat(filename, meta=False): """Load data from MAT-file: data = loadmat(filename, meta=False) The filename argument is either a string with the filename, or a file like object. The returned parameter ``data`` is a dict with the variables found in the MAT file. Call ``loadmat`` with...
Load data from MAT-file: data = loadmat(filename, meta=False) The filename argument is either a string with the filename, or a file like object. The returned parameter ``data`` is a dict with the variables found in the MAT file. Call ``loadmat`` with parameter meta=True to include meta data,...
Below is the the instruction that describes the task: ### Input: Load data from MAT-file: data = loadmat(filename, meta=False) The filename argument is either a string with the filename, or a file like object. The returned parameter ``data`` is a dict with the variables found in the MAT file....
def magic_help(self, line): """ Print out the help for magics Usage: Call help with no arguments to list all magics, or call it with a magic to print out it's help info. `%help` or `%help run """ line = line.strip() if not line: ...
Print out the help for magics Usage: Call help with no arguments to list all magics, or call it with a magic to print out it's help info. `%help` or `%help run
Below is the the instruction that describes the task: ### Input: Print out the help for magics Usage: Call help with no arguments to list all magics, or call it with a magic to print out it's help info. `%help` or `%help run ### Response: def magic_help(self, line)...
def mergeSplitsOnInterfaces(root: LNode): """ collect all split/concatenation nodes and group them by target interface """ for ch in root.children: if ch.children: mergeSplitsOnInterfaces(ch) ctx = MergeSplitsOnInterfacesCtx() for ch in root.children: srcPorts = None...
collect all split/concatenation nodes and group them by target interface
Below is the the instruction that describes the task: ### Input: collect all split/concatenation nodes and group them by target interface ### Response: def mergeSplitsOnInterfaces(root: LNode): """ collect all split/concatenation nodes and group them by target interface """ for ch in root.children:...
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given translation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) An...
Transform an image using an Affine transform with the given translation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns -------...
Below is the the instruction that describes the task: ### Input: Transform an image using an Affine transform with the given translation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) ...
def set_value(self, key, value): """ Set key value to the file. The fuction will be make the key and value to dictinary formate. If its exist then it will update the current new key value to the file. Arg: key : cache key value : cache value """ ...
Set key value to the file. The fuction will be make the key and value to dictinary formate. If its exist then it will update the current new key value to the file. Arg: key : cache key value : cache value
Below is the the instruction that describes the task: ### Input: Set key value to the file. The fuction will be make the key and value to dictinary formate. If its exist then it will update the current new key value to the file. Arg: key : cache key value : cache val...
def _findSwiplLin(): """ This function uses several heuristics to guess where SWI-Prolog is installed in Linuxes. :returns: A tuple of (path to the swipl so, path to the resource file) :returns type: ({str, None}, {str, None}) """ # Maybe the exec is on path? (path, sw...
This function uses several heuristics to guess where SWI-Prolog is installed in Linuxes. :returns: A tuple of (path to the swipl so, path to the resource file) :returns type: ({str, None}, {str, None})
Below is the the instruction that describes the task: ### Input: This function uses several heuristics to guess where SWI-Prolog is installed in Linuxes. :returns: A tuple of (path to the swipl so, path to the resource file) :returns type: ({str, None}, {str, None}) ### Response: def ...
def get_headers(hide_env=True): """Returns headers dict from request context.""" headers = dict(request.headers.items()) if hide_env and ('show_env' not in request.args): for key in ENV_HEADERS: try: del headers[key] except KeyError: pass ...
Returns headers dict from request context.
Below is the the instruction that describes the task: ### Input: Returns headers dict from request context. ### Response: def get_headers(hide_env=True): """Returns headers dict from request context.""" headers = dict(request.headers.items()) if hide_env and ('show_env' not in request.args): ...
def ipv4_is_defined(address): """ The function for checking if an IPv4 address is defined (does not need to be resolved). Args: address (:obj:`str`): An IPv4 address. Returns: namedtuple: :is_defined (bool): True if given address is defined, otherwise False ...
The function for checking if an IPv4 address is defined (does not need to be resolved). Args: address (:obj:`str`): An IPv4 address. Returns: namedtuple: :is_defined (bool): True if given address is defined, otherwise False :ietf_name (str): IETF assignment nam...
Below is the the instruction that describes the task: ### Input: The function for checking if an IPv4 address is defined (does not need to be resolved). Args: address (:obj:`str`): An IPv4 address. Returns: namedtuple: :is_defined (bool): True if given address is defined, othe...
def _build_queryset( self, serializer=None, filters=None, queryset=None, requirements=None, extra_filters=None, disable_prefetches=False, ): """Build a queryset that pulls in all data required by this request. Handles nested prefetching of rel...
Build a queryset that pulls in all data required by this request. Handles nested prefetching of related data and deferring fields at the queryset level. Arguments: serializer: An optional serializer to use a base for the queryset. If no serializer is passed, the `ge...
Below is the the instruction that describes the task: ### Input: Build a queryset that pulls in all data required by this request. Handles nested prefetching of related data and deferring fields at the queryset level. Arguments: serializer: An optional serializer to use a base ...
def replace(name, repl, full_match=False): ''' Replace all instances of a string or full line in the running config name String to replace repl The replacement text full_match Whether `name` will match the full line or only a subset of the line. Defaults to False. ...
Replace all instances of a string or full line in the running config name String to replace repl The replacement text full_match Whether `name` will match the full line or only a subset of the line. Defaults to False. When False, .* is added around `name` for matching ...
Below is the the instruction that describes the task: ### Input: Replace all instances of a string or full line in the running config name String to replace repl The replacement text full_match Whether `name` will match the full line or only a subset of the line. Defau...
def libvlc_video_get_adjust_float(p_mi, option): '''Get float adjust option. @param p_mi: libvlc media player instance. @param option: adjust option to get, values of libvlc_video_adjust_option_t. @version: LibVLC 1.1.1 and later. ''' f = _Cfunctions.get('libvlc_video_get_adjust_float', None) or...
Get float adjust option. @param p_mi: libvlc media player instance. @param option: adjust option to get, values of libvlc_video_adjust_option_t. @version: LibVLC 1.1.1 and later.
Below is the the instruction that describes the task: ### Input: Get float adjust option. @param p_mi: libvlc media player instance. @param option: adjust option to get, values of libvlc_video_adjust_option_t. @version: LibVLC 1.1.1 and later. ### Response: def libvlc_video_get_adjust_float(p_mi, optio...
def register(full_name, email, password, lang=None, timezone=None): """Register a new Todoist account. :param full_name: The user's full name. :type full_name: str :param email: The user's email address. :type email: str :param password: The user's password. :type password: str :param l...
Register a new Todoist account. :param full_name: The user's full name. :type full_name: str :param email: The user's email address. :type email: str :param password: The user's password. :type password: str :param lang: The user's language. :type lang: str :param timezone: The user...
Below is the the instruction that describes the task: ### Input: Register a new Todoist account. :param full_name: The user's full name. :type full_name: str :param email: The user's email address. :type email: str :param password: The user's password. :type password: str :param lang: T...
def remove(self, obj): """ Removes a member from the collection. :param obj: Object to remove. Example: >>> mycollection.remove(pump.Person('bob@example.org')) """ activity = { "verb": "remove", "object": { "objectType": obj.o...
Removes a member from the collection. :param obj: Object to remove. Example: >>> mycollection.remove(pump.Person('bob@example.org'))
Below is the the instruction that describes the task: ### Input: Removes a member from the collection. :param obj: Object to remove. Example: >>> mycollection.remove(pump.Person('bob@example.org')) ### Response: def remove(self, obj): """ Removes a member from the collection. ...
def wait_for_event(event): """ Wraps a win32 event into a `Future` and wait for it. """ f = Future() def ready(): get_event_loop().remove_win32_handle(event) f.set_result(None) get_event_loop().add_win32_handle(event, ready) return f
Wraps a win32 event into a `Future` and wait for it.
Below is the the instruction that describes the task: ### Input: Wraps a win32 event into a `Future` and wait for it. ### Response: def wait_for_event(event): """ Wraps a win32 event into a `Future` and wait for it. """ f = Future() def ready(): get_event_loop().remove_win32_handle(even...
def partial_jinja_template(template_name, name='data', mimetype="text/html"): """ Partial render of jinja templates. This is useful if you want to re-render the template in the output middleware phase. These templates are rendered in a way that all undefined variables will be kept in the emplate in...
Partial render of jinja templates. This is useful if you want to re-render the template in the output middleware phase. These templates are rendered in a way that all undefined variables will be kept in the emplate intact.
Below is the the instruction that describes the task: ### Input: Partial render of jinja templates. This is useful if you want to re-render the template in the output middleware phase. These templates are rendered in a way that all undefined variables will be kept in the emplate intact. ### Response: ...
def err(r): """ Input: { return - return code error - error text } Output: Nothing; quits program """ import sys rc=r['return'] re=r['error'] out('Error: '+re) sys.exit(rc)
Input: { return - return code error - error text } Output: Nothing; quits program
Below is the the instruction that describes the task: ### Input: Input: { return - return code error - error text } Output: Nothing; quits program ### Response: def err(r): """ Input: { return - return code error - error text ...
def _MakeEnumValueDescriptor(self, value_proto, index): """Creates a enum value descriptor object from a enum value proto. Args: value_proto: The proto describing the enum value. index: The index of the enum value. Returns: An initialized EnumValueDescriptor object. """ return d...
Creates a enum value descriptor object from a enum value proto. Args: value_proto: The proto describing the enum value. index: The index of the enum value. Returns: An initialized EnumValueDescriptor object.
Below is the the instruction that describes the task: ### Input: Creates a enum value descriptor object from a enum value proto. Args: value_proto: The proto describing the enum value. index: The index of the enum value. Returns: An initialized EnumValueDescriptor object. ### Response: ...
def bulk_cursor_execute(self, bulk_cursor): """ Executes the bulk_cursor :param bulk_cursor: Cursor to perform bulk operations :type bulk_cursor: pymongo bulk cursor object :returns: pymongo bulk cursor object (for bulk operations) """ try: ...
Executes the bulk_cursor :param bulk_cursor: Cursor to perform bulk operations :type bulk_cursor: pymongo bulk cursor object :returns: pymongo bulk cursor object (for bulk operations)
Below is the the instruction that describes the task: ### Input: Executes the bulk_cursor :param bulk_cursor: Cursor to perform bulk operations :type bulk_cursor: pymongo bulk cursor object :returns: pymongo bulk cursor object (for bulk operations) ### Response: def bulk_curso...
def _create_session(self, test_connection=False): """ Create a consulate.session object, and query for its leader to ensure that the connection is made. :param test_connection: call .leader() to ensure that the connection is valid :type test_connection: bool ...
Create a consulate.session object, and query for its leader to ensure that the connection is made. :param test_connection: call .leader() to ensure that the connection is valid :type test_connection: bool :return consulate.Session instance
Below is the the instruction that describes the task: ### Input: Create a consulate.session object, and query for its leader to ensure that the connection is made. :param test_connection: call .leader() to ensure that the connection is valid :type test_connection: bool :...
def inference(self, kern_r, kern_c, Xr, Xc, Zr, Zc, likelihood, Y, qU_mean ,qU_var_r, qU_var_c): """ The SVI-VarDTC inference """ N, D, Mr, Mc, Qr, Qc = Y.shape[0], Y.shape[1], Zr.shape[0], Zc.shape[0], Zr.shape[1], Zc.shape[1] uncertain_inputs_r = isinstance(Xr, VariationalPos...
The SVI-VarDTC inference
Below is the the instruction that describes the task: ### Input: The SVI-VarDTC inference ### Response: def inference(self, kern_r, kern_c, Xr, Xc, Zr, Zc, likelihood, Y, qU_mean ,qU_var_r, qU_var_c): """ The SVI-VarDTC inference """ N, D, Mr, Mc, Qr, Qc = Y.shape[0], Y.shape[1], Z...
def uninstall(**kwargs): """Uninstall the current pre-commit hook.""" force = kwargs.get('force') restore_legacy = kwargs.get('restore_legacy') colorama.init(strip=kwargs.get('no_color')) git_dir = current_git_dir() if git_dir is None: output(NOT_GIT_REPO_MSG) exit(1) hoo...
Uninstall the current pre-commit hook.
Below is the the instruction that describes the task: ### Input: Uninstall the current pre-commit hook. ### Response: def uninstall(**kwargs): """Uninstall the current pre-commit hook.""" force = kwargs.get('force') restore_legacy = kwargs.get('restore_legacy') colorama.init(strip=kwargs.get('no_c...
def length_of_geographical_area_code(numobj): """Return length of the geographical area code for a number. Gets the length of the geographical area code from the PhoneNumber object passed in, so that clients could use it to split a national significant number into geographical area code and subscriber ...
Return length of the geographical area code for a number. Gets the length of the geographical area code from the PhoneNumber object passed in, so that clients could use it to split a national significant number into geographical area code and subscriber number. It works in such a way that the resultant...
Below is the the instruction that describes the task: ### Input: Return length of the geographical area code for a number. Gets the length of the geographical area code from the PhoneNumber object passed in, so that clients could use it to split a national significant number into geographical area code...
def _HuntObjectFromRow(self, row): """Generates a flow object from a database row.""" ( create_time, last_update_time, creator, duration_micros, client_rate, client_limit, hunt_state, hunt_state_comment, init_start_time, last_start_...
Generates a flow object from a database row.
Below is the the instruction that describes the task: ### Input: Generates a flow object from a database row. ### Response: def _HuntObjectFromRow(self, row): """Generates a flow object from a database row.""" ( create_time, last_update_time, creator, duration_micros, ...
def f2p_list(phrase, max_word_size=15, cutoff=3): """Convert a phrase from Finglish to Persian. phrase: The phrase to convert. max_word_size: Maximum size of the words to consider. Words larger than this will be kept unchanged. cutoff: The cut-off point. For each word, there could be many pos...
Convert a phrase from Finglish to Persian. phrase: The phrase to convert. max_word_size: Maximum size of the words to consider. Words larger than this will be kept unchanged. cutoff: The cut-off point. For each word, there could be many possibilities. By default 3 of these possibilities are consi...
Below is the the instruction that describes the task: ### Input: Convert a phrase from Finglish to Persian. phrase: The phrase to convert. max_word_size: Maximum size of the words to consider. Words larger than this will be kept unchanged. cutoff: The cut-off point. For each word, there could be ...
def handle_events(self): """ An event handler that processes events from stdin and calls the on_click function of the respective object. This function is run in another thread, so as to not stall the main thread. """ for event in sys.stdin: if event.startswith...
An event handler that processes events from stdin and calls the on_click function of the respective object. This function is run in another thread, so as to not stall the main thread.
Below is the the instruction that describes the task: ### Input: An event handler that processes events from stdin and calls the on_click function of the respective object. This function is run in another thread, so as to not stall the main thread. ### Response: def handle_events(self): """...
def struct2dict(struct): """convert a ctypes structure to a dictionary""" return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}
convert a ctypes structure to a dictionary
Below is the the instruction that describes the task: ### Input: convert a ctypes structure to a dictionary ### Response: def struct2dict(struct): """convert a ctypes structure to a dictionary""" return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}
def count(self): """Returns the number of bits set to True in the bit string. Usage: assert BitString('00110').count() == 2 Arguments: None Return: An int, the number of bits with value 1. """ result = 0 bits = self._bits while bi...
Returns the number of bits set to True in the bit string. Usage: assert BitString('00110').count() == 2 Arguments: None Return: An int, the number of bits with value 1.
Below is the the instruction that describes the task: ### Input: Returns the number of bits set to True in the bit string. Usage: assert BitString('00110').count() == 2 Arguments: None Return: An int, the number of bits with value 1. ### Response: def count(self): ...
def decrement(self, key, value=1): """ Decrement the value of an item in the cache. :param key: The cache key :type key: str :param value: The decrement value :type value: int :rtype: int or bool """ self._store.decrement(self.tagged_item_key(ke...
Decrement the value of an item in the cache. :param key: The cache key :type key: str :param value: The decrement value :type value: int :rtype: int or bool
Below is the the instruction that describes the task: ### Input: Decrement the value of an item in the cache. :param key: The cache key :type key: str :param value: The decrement value :type value: int :rtype: int or bool ### Response: def decrement(self, key, value=1): ...
def image_to_data(image, lang=None, config='', nice=0, output_type=Output.STRING): ''' Returns string containing box boundaries, confidences, and other information. Requires Tesseract 3.05+ ''' if get_tesseract_version() < '3.0...
Returns string containing box boundaries, confidences, and other information. Requires Tesseract 3.05+
Below is the the instruction that describes the task: ### Input: Returns string containing box boundaries, confidences, and other information. Requires Tesseract 3.05+ ### Response: def image_to_data(image, lang=None, config='', nice=0, ou...
def walk_train_dirs(root_dir: str) -> Iterable[Tuple[str, Iterable[str]]]: """ Modify os.walk with the following: - return only root_dir and sub-dirs - return only training sub-dirs - stop recursion at training dirs :param root_dir: root dir to be walked :return: generator of (r...
Modify os.walk with the following: - return only root_dir and sub-dirs - return only training sub-dirs - stop recursion at training dirs :param root_dir: root dir to be walked :return: generator of (root_dir, training sub-dirs) pairs
Below is the the instruction that describes the task: ### Input: Modify os.walk with the following: - return only root_dir and sub-dirs - return only training sub-dirs - stop recursion at training dirs :param root_dir: root dir to be walked :return: generator of (root_dir, training ...
def read(self, *args, **kwargs): """ read the buffer, passing named and non named arguments to the io.BufferedReader function. """ buf = io.BufferedReader.read(self, *args, **kwargs) self.increment(len(buf)) return buf
read the buffer, passing named and non named arguments to the io.BufferedReader function.
Below is the the instruction that describes the task: ### Input: read the buffer, passing named and non named arguments to the io.BufferedReader function. ### Response: def read(self, *args, **kwargs): """ read the buffer, passing named and non named arguments to the io.BufferedRead...
def patch(self, url, body="", headers={}, retry=True): """Execute an HTTP PATCH request and return a dict containing the response and the response status code. Keyword arguments: url -- The path to execute the result against, not including the API version or project ID, w...
Execute an HTTP PATCH request and return a dict containing the response and the response status code. Keyword arguments: url -- The path to execute the result against, not including the API version or project ID, with no leading /. Required. body -- A string or file objec...
Below is the the instruction that describes the task: ### Input: Execute an HTTP PATCH request and return a dict containing the response and the response status code. Keyword arguments: url -- The path to execute the result against, not including the API version or project ID...
def _got_request_exception(self, sender, exception, **extra): """ The signal handler for the got_request_exception signal. """ extra = self.summary_extra() extra['errno'] = 500 self.summary_logger.error(str(exception), extra=extra) g._has_exception = True
The signal handler for the got_request_exception signal.
Below is the the instruction that describes the task: ### Input: The signal handler for the got_request_exception signal. ### Response: def _got_request_exception(self, sender, exception, **extra): """ The signal handler for the got_request_exception signal. """ extra = self.summary...
def missing_datetimes(self, finite_datetimes): """ Override in subclasses to do bulk checks. Returns a sorted list. This is a conservative base implementation that brutally checks completeness, instance by instance. Inadvisable as it may be slow. """ return [d ...
Override in subclasses to do bulk checks. Returns a sorted list. This is a conservative base implementation that brutally checks completeness, instance by instance. Inadvisable as it may be slow.
Below is the the instruction that describes the task: ### Input: Override in subclasses to do bulk checks. Returns a sorted list. This is a conservative base implementation that brutally checks completeness, instance by instance. Inadvisable as it may be slow. ### Response: def missing_d...
def matchers_refresh(self): ''' Refresh the matchers ''' log.debug('Refreshing matchers.') self.matchers = salt.loader.matchers(self.opts)
Refresh the matchers
Below is the the instruction that describes the task: ### Input: Refresh the matchers ### Response: def matchers_refresh(self): ''' Refresh the matchers ''' log.debug('Refreshing matchers.') self.matchers = salt.loader.matchers(self.opts)
def author_preview_view(self, context): """ View for previewing contents in studio. """ children_contents = [] fragment = Fragment() for child_id in self.children: child = self.runtime.get_block(child_id) child_fragment = self._render_child_fragme...
View for previewing contents in studio.
Below is the the instruction that describes the task: ### Input: View for previewing contents in studio. ### Response: def author_preview_view(self, context): """ View for previewing contents in studio. """ children_contents = [] fragment = Fragment() for child_id i...
def geolocation_buses(network, session): """ If geopandas is installed: Use Geometries of buses x/y(lon/lat) and Polygons of Countries from RenpassGisParameterRegion in order to locate the buses Else: Use coordinats of buses to locate foreign buses, which is less accurate. Param...
If geopandas is installed: Use Geometries of buses x/y(lon/lat) and Polygons of Countries from RenpassGisParameterRegion in order to locate the buses Else: Use coordinats of buses to locate foreign buses, which is less accurate. Parameters ---------- network_etrago: : class: `e...
Below is the the instruction that describes the task: ### Input: If geopandas is installed: Use Geometries of buses x/y(lon/lat) and Polygons of Countries from RenpassGisParameterRegion in order to locate the buses Else: Use coordinats of buses to locate foreign buses, which is less accura...
def fetch(self, deputies, start_date, end_date): """ :param deputies: (pandas.DataFrame) a dataframe with deputies data :param date_start: (str) date in the format dd/mm/yyyy :param date_end: (str) date in the format dd/mm/yyyy """ log.debug("Fetching data for {} deputies...
:param deputies: (pandas.DataFrame) a dataframe with deputies data :param date_start: (str) date in the format dd/mm/yyyy :param date_end: (str) date in the format dd/mm/yyyy
Below is the the instruction that describes the task: ### Input: :param deputies: (pandas.DataFrame) a dataframe with deputies data :param date_start: (str) date in the format dd/mm/yyyy :param date_end: (str) date in the format dd/mm/yyyy ### Response: def fetch(self, deputies, start_date, end_dat...
def process(meta): """Saves metadata fields in global variables and returns a few computed fields.""" # pylint: disable=global-statement global capitalize global use_cleveref_default global plusname global starname global numbersections # Read in the metadata fields and do some che...
Saves metadata fields in global variables and returns a few computed fields.
Below is the the instruction that describes the task: ### Input: Saves metadata fields in global variables and returns a few computed fields. ### Response: def process(meta): """Saves metadata fields in global variables and returns a few computed fields.""" # pylint: disable=global-statement g...
def attach(domain, filename): '''Attach existing dataset to their harvest remote id before harvesting. The expected csv file format is the following: - a column with header "local" and the local IDs or slugs - a column with header "remote" and the remote IDs The delimiter should be ";". columns o...
Attach existing dataset to their harvest remote id before harvesting. The expected csv file format is the following: - a column with header "local" and the local IDs or slugs - a column with header "remote" and the remote IDs The delimiter should be ";". columns order and extras columns does not ...
Below is the the instruction that describes the task: ### Input: Attach existing dataset to their harvest remote id before harvesting. The expected csv file format is the following: - a column with header "local" and the local IDs or slugs - a column with header "remote" and the remote IDs The de...
def screen_to_latlon(self, x, y): """ Return the latitude and longitude corresponding to a screen point :param x: screen x :param y: screen y :return: latitude and longitude at x,y """ xtile = 1. * x / TILE_SIZE + self.xtile ytile = 1. * y / TILE_SIZE + se...
Return the latitude and longitude corresponding to a screen point :param x: screen x :param y: screen y :return: latitude and longitude at x,y
Below is the the instruction that describes the task: ### Input: Return the latitude and longitude corresponding to a screen point :param x: screen x :param y: screen y :return: latitude and longitude at x,y ### Response: def screen_to_latlon(self, x, y): """ Return the lati...
def consume_tickets(self, user): """ Consume all valid ``Ticket``s for a specified user. This is run when the user logs out to ensure all issued tickets are no longer valid for future authentication attempts. """ for ticket in self.filter(user=user, consumed__isnull=True,...
Consume all valid ``Ticket``s for a specified user. This is run when the user logs out to ensure all issued tickets are no longer valid for future authentication attempts.
Below is the the instruction that describes the task: ### Input: Consume all valid ``Ticket``s for a specified user. This is run when the user logs out to ensure all issued tickets are no longer valid for future authentication attempts. ### Response: def consume_tickets(self, user): """ ...
def setup(self, socket_type, complete_or_error_queue): """Setup the asyncio event loop. Args: socket_type (int from zmq.*): One of zmq.DEALER or zmq.ROUTER complete_or_error_queue (queue.Queue): A way to propagate errors back to the calling thread. Needed since t...
Setup the asyncio event loop. Args: socket_type (int from zmq.*): One of zmq.DEALER or zmq.ROUTER complete_or_error_queue (queue.Queue): A way to propagate errors back to the calling thread. Needed since this function is directly used in Thread. ...
Below is the the instruction that describes the task: ### Input: Setup the asyncio event loop. Args: socket_type (int from zmq.*): One of zmq.DEALER or zmq.ROUTER complete_or_error_queue (queue.Queue): A way to propagate errors back to the calling thread. Needed sinc...
def lines(fp): """ Read lines of UTF-8 from the file-like object given in ``fp``, making sure that when reading from STDIN, reads are at most line-buffered. UTF-8 decoding errors are handled silently. Invalid characters are replaced by U+FFFD REPLACEMENT CHARACTER. Line endings are normalised ...
Read lines of UTF-8 from the file-like object given in ``fp``, making sure that when reading from STDIN, reads are at most line-buffered. UTF-8 decoding errors are handled silently. Invalid characters are replaced by U+FFFD REPLACEMENT CHARACTER. Line endings are normalised to newlines by Python's uni...
Below is the the instruction that describes the task: ### Input: Read lines of UTF-8 from the file-like object given in ``fp``, making sure that when reading from STDIN, reads are at most line-buffered. UTF-8 decoding errors are handled silently. Invalid characters are replaced by U+FFFD REPLACEMENT CH...
def restrictCheckers(self, allowedMessages): """ Unregister useless checkers to speed up twistedchecker. @param allowedMessages: output messages allowed in twistedchecker """ uselessCheckers = self.findUselessCheckers(allowedMessages) # Unregister these checkers ...
Unregister useless checkers to speed up twistedchecker. @param allowedMessages: output messages allowed in twistedchecker
Below is the the instruction that describes the task: ### Input: Unregister useless checkers to speed up twistedchecker. @param allowedMessages: output messages allowed in twistedchecker ### Response: def restrictCheckers(self, allowedMessages): """ Unregister useless checkers to speed up ...
def set_flags(self): """ Set flags representing generation way accordingly - commkeys are client generated, app key is server generated. :return: """ offset = self.template['flagoffset']//8 # comm keys provided? self.tpl_buff = bytes_transform(self.tpl_buff, offs...
Set flags representing generation way accordingly - commkeys are client generated, app key is server generated. :return:
Below is the the instruction that describes the task: ### Input: Set flags representing generation way accordingly - commkeys are client generated, app key is server generated. :return: ### Response: def set_flags(self): """ Set flags representing generation way accordingly - commkeys are c...
def re_escape(pattern, chars=frozenset("()[]{}?*+|^$\\.-#")): ''' Escape all special regex characters in pattern. Logic taken from regex module. :param pattern: regex pattern to escape :type patterm: str :returns: escaped pattern :rtype: str ''' escape = '\\{}'.format return ''....
Escape all special regex characters in pattern. Logic taken from regex module. :param pattern: regex pattern to escape :type patterm: str :returns: escaped pattern :rtype: str
Below is the the instruction that describes the task: ### Input: Escape all special regex characters in pattern. Logic taken from regex module. :param pattern: regex pattern to escape :type patterm: str :returns: escaped pattern :rtype: str ### Response: def re_escape(pattern, chars=frozenset(...
def list(self, item, default=None, spliter=",", strip=True, mod=None): """ Return value of key as a list :param item: key of value to transform :param mod: function to map against list :param default: value to return if item does not exist :param spliter: character to split str ...
Return value of key as a list :param item: key of value to transform :param mod: function to map against list :param default: value to return if item does not exist :param spliter: character to split str on :param strip: clean the list with the `strip` :return: list of i...
Below is the the instruction that describes the task: ### Input: Return value of key as a list :param item: key of value to transform :param mod: function to map against list :param default: value to return if item does not exist :param spliter: character to split str on :pa...
def visit_unaryop(self, node): """check use of the non-existent ++ and -- operator operator""" if ( (node.op in "+-") and isinstance(node.operand, astroid.UnaryOp) and (node.operand.op == node.op) ): self.add_message("nonexistent-operator", node=no...
check use of the non-existent ++ and -- operator operator
Below is the the instruction that describes the task: ### Input: check use of the non-existent ++ and -- operator operator ### Response: def visit_unaryop(self, node): """check use of the non-existent ++ and -- operator operator""" if ( (node.op in "+-") and isinstance(node....
def read_orange(user_id, records_path, antennas_path=None, attributes_path=None, recharges_path=None, network=False, describe=True, warnings=True, errors=False): """ Load user records from a CSV file in *orange* format: ``call_record_type;basic_service;user_msisdn;call_partn...
Load user records from a CSV file in *orange* format: ``call_record_type;basic_service;user_msisdn;call_partner_identity;datetime;call_duration;longitude;latitude`` ``basic_service`` takes one of the following values: - 11: telephony; - 12: emergency calls; - 21: short message (in) - 22: shor...
Below is the the instruction that describes the task: ### Input: Load user records from a CSV file in *orange* format: ``call_record_type;basic_service;user_msisdn;call_partner_identity;datetime;call_duration;longitude;latitude`` ``basic_service`` takes one of the following values: - 11: telephony; ...
def from_reply(cls, state): """ Comptaibility layer for old :class:`SASLInterface` implementations. Accepts the follwing set of :class:`SASLState` or strings and maps the strings to :class:`SASLState` elements as follows: ``"challenge"`` :member:`SASLState...
Comptaibility layer for old :class:`SASLInterface` implementations. Accepts the follwing set of :class:`SASLState` or strings and maps the strings to :class:`SASLState` elements as follows: ``"challenge"`` :member:`SASLState.CHALLENGE` ``"failue"`` ...
Below is the the instruction that describes the task: ### Input: Comptaibility layer for old :class:`SASLInterface` implementations. Accepts the follwing set of :class:`SASLState` or strings and maps the strings to :class:`SASLState` elements as follows: ``"challenge"`` ...
def fletcher_checksum(data, offset): """ Fletcher Checksum -- Refer to RFC1008 calling with offset == _FLETCHER_CHECKSUM_VALIDATE will validate the checksum without modifying the buffer; a valid checksum returns 0. """ c0 = 0 c1 = 0 pos = 0 length = len(data) data = bytearray(da...
Fletcher Checksum -- Refer to RFC1008 calling with offset == _FLETCHER_CHECKSUM_VALIDATE will validate the checksum without modifying the buffer; a valid checksum returns 0.
Below is the the instruction that describes the task: ### Input: Fletcher Checksum -- Refer to RFC1008 calling with offset == _FLETCHER_CHECKSUM_VALIDATE will validate the checksum without modifying the buffer; a valid checksum returns 0. ### Response: def fletcher_checksum(data, offset): """ Flet...
def set(self, value): """ Update value of the option. Only possible for options with :py:attr:`readonly` set to `False`. If :py:attr:`type` is `choice`, the value must be one of the :py:attr:`choices`. If :py:attr:`type` is `range`, the value must be in the range describ...
Update value of the option. Only possible for options with :py:attr:`readonly` set to `False`. If :py:attr:`type` is `choice`, the value must be one of the :py:attr:`choices`. If :py:attr:`type` is `range`, the value must be in the range described by :py:attr:`range`. :...
Below is the the instruction that describes the task: ### Input: Update value of the option. Only possible for options with :py:attr:`readonly` set to `False`. If :py:attr:`type` is `choice`, the value must be one of the :py:attr:`choices`. If :py:attr:`type` is `range`, the value m...
def next(self): """Returns the next query result. :return: The next query result. :rtype: dict :raises StopIteration: If no more result is left. """ if self._has_finished: raise StopIteration if not len(self._buffer): ...
Returns the next query result. :return: The next query result. :rtype: dict :raises StopIteration: If no more result is left.
Below is the the instruction that describes the task: ### Input: Returns the next query result. :return: The next query result. :rtype: dict :raises StopIteration: If no more result is left. ### Response: def next(self): """Returns the next query result. ...
def _validate_logical_id(cls, logical_id): """Validates that the provided logical id is an alphanumeric string. :param str logical_id: the logical id to validate :returns: True if the logical id is valid :rtype: bool :raises TypeError: if the logical id is invalid """ ...
Validates that the provided logical id is an alphanumeric string. :param str logical_id: the logical id to validate :returns: True if the logical id is valid :rtype: bool :raises TypeError: if the logical id is invalid
Below is the the instruction that describes the task: ### Input: Validates that the provided logical id is an alphanumeric string. :param str logical_id: the logical id to validate :returns: True if the logical id is valid :rtype: bool :raises TypeError: if the logical id is invalid...
def get_report(self): """ describe the graph :returns: report :rtype: string """ ostr = '' ostr += "Nodes: "+str(len(self.__nodes.keys()))+"\n" ostr += "Edges: "+str(len(self.__edges.keys()))+"\n" return ostr
describe the graph :returns: report :rtype: string
Below is the the instruction that describes the task: ### Input: describe the graph :returns: report :rtype: string ### Response: def get_report(self): """ describe the graph :returns: report :rtype: string """ ostr = '' ostr += "Nodes: "+str(len(self.__nodes.keys()))+"\n" ost...
def delete_object(self, identifier, erase=False): """Delete the entry with given identifier in the database. Returns the handle for the deleted object or None if object identifier is unknown. If the read-only property of the object is set to true a ValueError is raised. Paramet...
Delete the entry with given identifier in the database. Returns the handle for the deleted object or None if object identifier is unknown. If the read-only property of the object is set to true a ValueError is raised. Parameters ---------- identifier : string ...
Below is the the instruction that describes the task: ### Input: Delete the entry with given identifier in the database. Returns the handle for the deleted object or None if object identifier is unknown. If the read-only property of the object is set to true a ValueError is raised. ...
def _proc_ellipse(self, tokens, filled): """ Returns the components of an ellipse. """ component = Ellipse(pen=self.pen, x_origin=tokens["x0"], y_origin=tokens["y0"], e_width=tokens["w"], e_h...
Returns the components of an ellipse.
Below is the the instruction that describes the task: ### Input: Returns the components of an ellipse. ### Response: def _proc_ellipse(self, tokens, filled): """ Returns the components of an ellipse. """ component = Ellipse(pen=self.pen, x_origin=tokens["x0"], ...
def requiv_to_pot_contact(requiv, q, sma, compno=1): """ TODO: add documentation """ return ConstraintParameter(requiv._bundle, "requiv_to_pot_contact({}, {}, {}, {})".format(_get_expr(requiv), _get_expr(q), _get_expr(sma), compno))
TODO: add documentation
Below is the the instruction that describes the task: ### Input: TODO: add documentation ### Response: def requiv_to_pot_contact(requiv, q, sma, compno=1): """ TODO: add documentation """ return ConstraintParameter(requiv._bundle, "requiv_to_pot_contact({}, {}, {}, {})".format(_get_expr(requiv), _g...
def _get_prm_file(file_name=None, search_order=None): """returns name of the prm file""" if file_name is not None: if os.path.isfile(file_name): return file_name else: logger.info("Could not find the prm-file") default_name = prms._prm_default_name prm_globtxt = ...
returns name of the prm file
Below is the the instruction that describes the task: ### Input: returns name of the prm file ### Response: def _get_prm_file(file_name=None, search_order=None): """returns name of the prm file""" if file_name is not None: if os.path.isfile(file_name): return file_name else: ...
def urls(cls, name_prefix=None): """ A convenience method for hooking up the URLs. This automatically adds a list & a detail endpoint to your URLconf. :param name_prefix: (Optional) A prefix for the URL's name (for resolving). The default is ``None``, which will autocreate ...
A convenience method for hooking up the URLs. This automatically adds a list & a detail endpoint to your URLconf. :param name_prefix: (Optional) A prefix for the URL's name (for resolving). The default is ``None``, which will autocreate a prefix based on the class name. Ex: ``B...
Below is the the instruction that describes the task: ### Input: A convenience method for hooking up the URLs. This automatically adds a list & a detail endpoint to your URLconf. :param name_prefix: (Optional) A prefix for the URL's name (for resolving). The default is ``None``, which ...
def dict_expand(o): """Expand keys in a dict with '.' in them into sub-dictionaries, e.g. {'a.b.c': 'foo'} ==> {'a': {'b': {'c': 'foo'}}} """ r = {} for k, v in o.items(): if isinstance(k, str): k = k.replace('$', '_') if "." in k:...
Expand keys in a dict with '.' in them into sub-dictionaries, e.g. {'a.b.c': 'foo'} ==> {'a': {'b': {'c': 'foo'}}}
Below is the the instruction that describes the task: ### Input: Expand keys in a dict with '.' in them into sub-dictionaries, e.g. {'a.b.c': 'foo'} ==> {'a': {'b': {'c': 'foo'}}} ### Response: def dict_expand(o): """Expand keys in a dict with '.' in them into sub-dictionaries, e.g...
def _unique_constrains(cls): """Get all (single column and multi column) unique constraints""" unique = [{c.name for c in u.columns} for u in cls.__table_args__ if isinstance(u, UniqueConstraint)] unique.extend({c.name} for c in cls.__table__.columns if c.unique) return...
Get all (single column and multi column) unique constraints
Below is the the instruction that describes the task: ### Input: Get all (single column and multi column) unique constraints ### Response: def _unique_constrains(cls): """Get all (single column and multi column) unique constraints""" unique = [{c.name for c in u.columns} for u in cls.__table_args__...
def _to_pixel_params(self, wcs, mode='all'): """ Convert the sky aperture parameters to those for a pixel aperture. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optiona...
Convert the sky aperture parameters to those for a pixel aperture. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, optional Whether to do the transformation including distorti...
Below is the the instruction that describes the task: ### Input: Convert the sky aperture parameters to those for a pixel aperture. Parameters ---------- wcs : `~astropy.wcs.WCS` The world coordinate system (WCS) transformation to use. mode : {'all', 'wcs'}, opt...
def rows(self, table, cols): ''' Fetches rows from the local cache or from the db if there's no cache. :param table: table name to select :cols: list of columns to select :return: list of rows :rtype: list ''' if self.orng_tables: ...
Fetches rows from the local cache or from the db if there's no cache. :param table: table name to select :cols: list of columns to select :return: list of rows :rtype: list
Below is the the instruction that describes the task: ### Input: Fetches rows from the local cache or from the db if there's no cache. :param table: table name to select :cols: list of columns to select :return: list of rows :rtype: list ### Response: def rows(self,...