code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def p_speed_conversion(self, p): 'speed : speed IN speed_unit' logger.debug('speed = speed %s in speed unit %s', p[1], p[3]) information_unit, duration = p[3] p[0] = '{0: {1}}'.format(p[1], '{0}/{1}'.format(information_unit, duration))
speed : speed IN speed_unit
Below is the the instruction that describes the task: ### Input: speed : speed IN speed_unit ### Response: def p_speed_conversion(self, p): 'speed : speed IN speed_unit' logger.debug('speed = speed %s in speed unit %s', p[1], p[3]) information_unit, duration = p[3] p[0] = '{0: {1}}'...
def surface(n_x=20,n_y=20): """ Returns a DataFrame with the required format for a surface plot Parameters: ----------- n_x : int Number of points along the X axis n_y : int Number of points along the Y axis """ x=[float(np.random.randint(0,100))] for i in range(n_x): x.append(x[:1][0]+np.random....
Returns a DataFrame with the required format for a surface plot Parameters: ----------- n_x : int Number of points along the X axis n_y : int Number of points along the Y axis
Below is the the instruction that describes the task: ### Input: Returns a DataFrame with the required format for a surface plot Parameters: ----------- n_x : int Number of points along the X axis n_y : int Number of points along the Y axis ### Response: def surface(n_x=20,n_y=20): """ Returns a D...
def _reshape_G(G): """From a correlation matrix of size nsrc X nsrc X nchan X nchan X filters_len X filters_len, creates a new one of size nsrc*nchan*filters_len X nsrc*nchan*filters_len""" G = np.moveaxis(G, (1, 3), (3, 4)) (nsrc, nchan, filters_len) = G.shape[0:3] G = np.reshape( G...
From a correlation matrix of size nsrc X nsrc X nchan X nchan X filters_len X filters_len, creates a new one of size nsrc*nchan*filters_len X nsrc*nchan*filters_len
Below is the the instruction that describes the task: ### Input: From a correlation matrix of size nsrc X nsrc X nchan X nchan X filters_len X filters_len, creates a new one of size nsrc*nchan*filters_len X nsrc*nchan*filters_len ### Response: def _reshape_G(G): """From a correlation matrix of size...
def _apply_over_vars_with_dim(func, self, dim=None, **kwargs): '''wrapper for datasets''' ds = type(self)(coords=self.coords, attrs=self.attrs) for name, var in self.data_vars.items(): if dim in var.dims: ds[name] = func(var, dim=dim, **kwargs) else: ds[name] = var ...
wrapper for datasets
Below is the the instruction that describes the task: ### Input: wrapper for datasets ### Response: def _apply_over_vars_with_dim(func, self, dim=None, **kwargs): '''wrapper for datasets''' ds = type(self)(coords=self.coords, attrs=self.attrs) for name, var in self.data_vars.items(): if dim i...
def heatmap_seaborn(dfr, outfilename=None, title=None, params=None): """Returns seaborn heatmap with cluster dendrograms. - dfr - pandas DataFrame with relevant data - outfilename - path to output file (indicates output format) """ # Decide on figure layout size: a minimum size is required for ...
Returns seaborn heatmap with cluster dendrograms. - dfr - pandas DataFrame with relevant data - outfilename - path to output file (indicates output format)
Below is the the instruction that describes the task: ### Input: Returns seaborn heatmap with cluster dendrograms. - dfr - pandas DataFrame with relevant data - outfilename - path to output file (indicates output format) ### Response: def heatmap_seaborn(dfr, outfilename=None, title=None, params=None): ...
def find_first_number(ll): """ Returns nr of first entry parseable to float in ll, None otherwise""" for nr, entry in enumerate(ll): try: float(entry) except (ValueError, TypeError) as e: pass else: return nr return None
Returns nr of first entry parseable to float in ll, None otherwise
Below is the the instruction that describes the task: ### Input: Returns nr of first entry parseable to float in ll, None otherwise ### Response: def find_first_number(ll): """ Returns nr of first entry parseable to float in ll, None otherwise""" for nr, entry in enumerate(ll): try: flo...
def check_perm(request): """ Check user permission. --- request_serializer: serializers.CheckPerm parameters: - name: user type: string required: true description: username paramType: query - name: perm type: string requir...
Check user permission. --- request_serializer: serializers.CheckPerm parameters: - name: user type: string required: true description: username paramType: query - name: perm type: string required: true description: permi...
Below is the the instruction that describes the task: ### Input: Check user permission. --- request_serializer: serializers.CheckPerm parameters: - name: user type: string required: true description: username paramType: query - name: perm ...
def get_script_header(script_text, executable=sys_executable, wininst=False): """Create a #! line, getting options (if any) from script_text""" from distutils.command.build_scripts import first_line_re # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern. if not isinstance(first_line_re.pat...
Create a #! line, getting options (if any) from script_text
Below is the the instruction that describes the task: ### Input: Create a #! line, getting options (if any) from script_text ### Response: def get_script_header(script_text, executable=sys_executable, wininst=False): """Create a #! line, getting options (if any) from script_text""" from distutils.command.b...
def cli(env, context_id, include): """List IPSEC VPN tunnel context details. Additional resources can be joined using multiple instances of the include option, for which the following choices are available. \b at: address translations is: internal subnets rs: remote subnets sr: statica...
List IPSEC VPN tunnel context details. Additional resources can be joined using multiple instances of the include option, for which the following choices are available. \b at: address translations is: internal subnets rs: remote subnets sr: statically routed subnets ss: service subnets
Below is the the instruction that describes the task: ### Input: List IPSEC VPN tunnel context details. Additional resources can be joined using multiple instances of the include option, for which the following choices are available. \b at: address translations is: internal subnets rs: rem...
def get_snaps_install_info_from_origin(snaps, src, mode='classic'): """Generate a dictionary of snap install information from origin @param snaps: List of snaps @param src: String of openstack-origin or source of the form snap:track/channel @param mode: String classic, devmode or jailmode @...
Generate a dictionary of snap install information from origin @param snaps: List of snaps @param src: String of openstack-origin or source of the form snap:track/channel @param mode: String classic, devmode or jailmode @returns: Dictionary of snaps with channels and modes
Below is the the instruction that describes the task: ### Input: Generate a dictionary of snap install information from origin @param snaps: List of snaps @param src: String of openstack-origin or source of the form snap:track/channel @param mode: String classic, devmode or jailmode @return...
def resource(url_prefix_or_resource_cls: Union[str, Type[Resource]], resource_cls: Optional[Type[Resource]] = None, *, member_param: Optional[str] = None, unique_member_param: Optional[str] = None, rules: Optional[Iterable[Union[Route, RouteGenerator]]] =...
This function is used to register a :class:`Resource`'s routes. Example usage:: routes = lambda: [ prefix('/api/v1', [ resource('/products', ProductResource), ]) ] Or with the optional prefix argument:: routes = lambda: [ resource('...
Below is the the instruction that describes the task: ### Input: This function is used to register a :class:`Resource`'s routes. Example usage:: routes = lambda: [ prefix('/api/v1', [ resource('/products', ProductResource), ]) ] Or with the optional...
def transfer(ctx, to, amount, asset, memo, account): """ Transfer assets """ pprint(ctx.peerplays.transfer(to, amount, asset, memo=memo, account=account))
Transfer assets
Below is the the instruction that describes the task: ### Input: Transfer assets ### Response: def transfer(ctx, to, amount, asset, memo, account): """ Transfer assets """ pprint(ctx.peerplays.transfer(to, amount, asset, memo=memo, account=account))
def write( self, mi_cmd_to_write, timeout_sec=DEFAULT_GDB_TIMEOUT_SEC, raise_error_on_timeout=True, read_response=True, ): """Write to gdb process. Block while parsing responses from gdb for a maximum of timeout_sec. Args: mi_cmd_to_write (str or ...
Write to gdb process. Block while parsing responses from gdb for a maximum of timeout_sec. Args: mi_cmd_to_write (str or list): String to write to gdb. If list, it is joined by newlines. timeout_sec (float): Maximum number of seconds to wait for response before exiting. Must be >= 0. ...
Below is the the instruction that describes the task: ### Input: Write to gdb process. Block while parsing responses from gdb for a maximum of timeout_sec. Args: mi_cmd_to_write (str or list): String to write to gdb. If list, it is joined by newlines. timeout_sec (float): Maximum nu...
def close(self): '''Close all the connections and clean up. This instance will not be usable after calling this method. ''' for key, pool in tuple(self._host_pools.items()): pool.close() del self._host_pools[key] del self._host_pool_waiters[key] ...
Close all the connections and clean up. This instance will not be usable after calling this method.
Below is the the instruction that describes the task: ### Input: Close all the connections and clean up. This instance will not be usable after calling this method. ### Response: def close(self): '''Close all the connections and clean up. This instance will not be usable after calling thi...
def add_hybrid_interface(ifindex, pvid, taggedvlans, untaggedvlans, auth, url, devip=None, devid=None): """ Function takes ifindex, pvid, tagged vlans untagged vlans as input values to add a hybrid port to a HPE Comware based switch. These functions only apply to HPE Comware based d...
Function takes ifindex, pvid, tagged vlans untagged vlans as input values to add a hybrid port to a HPE Comware based switch. These functions only apply to HPE Comware based devices. :param ifindex: str ifIndex value of target interface :param pvid: str 802.1q value (1-4094) of target VLAN :param tagged...
Below is the the instruction that describes the task: ### Input: Function takes ifindex, pvid, tagged vlans untagged vlans as input values to add a hybrid port to a HPE Comware based switch. These functions only apply to HPE Comware based devices. :param ifindex: str ifIndex value of target interface :p...
def getVariantAnnotationId(self, gaVariant, gaAnnotation): """ Produces a stringified compoundId representing a variant annotation. :param gaVariant: protocol.Variant :param gaAnnotation: protocol.VariantAnnotation :return: compoundId String """ md5 = s...
Produces a stringified compoundId representing a variant annotation. :param gaVariant: protocol.Variant :param gaAnnotation: protocol.VariantAnnotation :return: compoundId String
Below is the the instruction that describes the task: ### Input: Produces a stringified compoundId representing a variant annotation. :param gaVariant: protocol.Variant :param gaAnnotation: protocol.VariantAnnotation :return: compoundId String ### Response: def getVariantAnnotati...
def list( self, **kwargs ): """ Get a list of all Accounts authorized for the provided token. Args: Returns: v20.response.Response containing the results from submitting the request """ request = Request( 'GET', ...
Get a list of all Accounts authorized for the provided token. Args: Returns: v20.response.Response containing the results from submitting the request
Below is the the instruction that describes the task: ### Input: Get a list of all Accounts authorized for the provided token. Args: Returns: v20.response.Response containing the results from submitting the request ### Response: def list( self, **kwargs ...
def is_final(name, mro): """ Checks if `name` is a `final` object in the given `mro`. We need to check the mro because we need to directly go into the __dict__ of the classes. Because `final` objects are descriptor, we need to grab them _BEFORE_ the `__call__` is invoked. """ return any(isin...
Checks if `name` is a `final` object in the given `mro`. We need to check the mro because we need to directly go into the __dict__ of the classes. Because `final` objects are descriptor, we need to grab them _BEFORE_ the `__call__` is invoked.
Below is the the instruction that describes the task: ### Input: Checks if `name` is a `final` object in the given `mro`. We need to check the mro because we need to directly go into the __dict__ of the classes. Because `final` objects are descriptor, we need to grab them _BEFORE_ the `__call__` is invo...
def trim(network, pores=[], throats=[]): ''' Remove pores or throats from the network. Parameters ---------- network : OpenPNM Network Object The Network from which pores or throats should be removed pores (or throats) : array_like The indices of the of the pores or throats to ...
Remove pores or throats from the network. Parameters ---------- network : OpenPNM Network Object The Network from which pores or throats should be removed pores (or throats) : array_like The indices of the of the pores or throats to be removed from the network. Notes -...
Below is the the instruction that describes the task: ### Input: Remove pores or throats from the network. Parameters ---------- network : OpenPNM Network Object The Network from which pores or throats should be removed pores (or throats) : array_like The indices of the of the pore...
def _validate_auths(self, path, obj, app): """ make sure that apiKey and basicAuth are empty list in Operation object. """ errs = [] for k, v in six.iteritems(obj.authorizations or {}): if k not in app.raw.authorizations: errs.append('auth {0} not fou...
make sure that apiKey and basicAuth are empty list in Operation object.
Below is the the instruction that describes the task: ### Input: make sure that apiKey and basicAuth are empty list in Operation object. ### Response: def _validate_auths(self, path, obj, app): """ make sure that apiKey and basicAuth are empty list in Operation object. """ e...
def fork_connection(source, sink, source_lane, lane): """Makes the connection between a process and the first processes in the lanes to which it forks. The ``lane`` argument should correspond to the lane of the source process. For each lane in ``sink``, the lane counter will increase. Parameters ...
Makes the connection between a process and the first processes in the lanes to which it forks. The ``lane`` argument should correspond to the lane of the source process. For each lane in ``sink``, the lane counter will increase. Parameters ---------- source : str Name of the process th...
Below is the the instruction that describes the task: ### Input: Makes the connection between a process and the first processes in the lanes to which it forks. The ``lane`` argument should correspond to the lane of the source process. For each lane in ``sink``, the lane counter will increase. Para...
def all_edges_with_verts(self, v_indices, as_boolean=False): ''' returns all of the faces that contain at least one of the vertices in v_indices ''' included_vertices = np.zeros(self.v.shape[0], dtype=bool) included_vertices[v_indices] = True edges_with_verts = included_v...
returns all of the faces that contain at least one of the vertices in v_indices
Below is the the instruction that describes the task: ### Input: returns all of the faces that contain at least one of the vertices in v_indices ### Response: def all_edges_with_verts(self, v_indices, as_boolean=False): ''' returns all of the faces that contain at least one of the vertices in v_ind...
def fastMean(img, f=10, inplace=False): ''' for bigger ksizes it if often faster to resize an image rather than blur it... ''' s0,s1 = img.shape[:2] ss0 = int(round(s0/f)) ss1 = int(round(s1/f)) small = cv2.resize(img,(ss1,ss0), interpolation=cv2.INTER_AREA) #bigger ...
for bigger ksizes it if often faster to resize an image rather than blur it...
Below is the the instruction that describes the task: ### Input: for bigger ksizes it if often faster to resize an image rather than blur it... ### Response: def fastMean(img, f=10, inplace=False): ''' for bigger ksizes it if often faster to resize an image rather than blur it... ''' ...
def isSelfVerificationEnabled(self): """Returns if the user that submitted a result for this analysis must also be able to verify the result :returns: true or false """ bsve = self.bika_setup.getSelfVerificationEnabled() vs = self.getSelfVerification() return bsve...
Returns if the user that submitted a result for this analysis must also be able to verify the result :returns: true or false
Below is the the instruction that describes the task: ### Input: Returns if the user that submitted a result for this analysis must also be able to verify the result :returns: true or false ### Response: def isSelfVerificationEnabled(self): """Returns if the user that submitted a result for...
def ws_url(self): """websocket url matching the current request turns http[s]://host[:port] into ws[s]://host[:port] """ proto = self.request.protocol.replace('http', 'ws') host = self.application.ipython_app.websocket_host # default to config value if ho...
websocket url matching the current request turns http[s]://host[:port] into ws[s]://host[:port]
Below is the the instruction that describes the task: ### Input: websocket url matching the current request turns http[s]://host[:port] into ws[s]://host[:port] ### Response: def ws_url(self): """websocket url matching the current request turns http[s]://host[:port] into ...
def _references(self, i, sequence=False): """Handle references.""" value = '' c = next(i) if c == '\\': # \\ if sequence and self.bslash_abort: raise PathNameException value = c elif c == '/': # \/ if s...
Handle references.
Below is the the instruction that describes the task: ### Input: Handle references. ### Response: def _references(self, i, sequence=False): """Handle references.""" value = '' c = next(i) if c == '\\': # \\ if sequence and self.bslash_abort: ...
def show_clusters(data, clusters, noise=None): """! @brief Display CLIQUE clustering results. @param[in] data (list): Data that was used for clustering. @param[in] clusters (array_like): Clusters that were allocated by the algorithm. @param[in] noise (array_like): Noise th...
! @brief Display CLIQUE clustering results. @param[in] data (list): Data that was used for clustering. @param[in] clusters (array_like): Clusters that were allocated by the algorithm. @param[in] noise (array_like): Noise that were allocated by the algorithm.
Below is the the instruction that describes the task: ### Input: ! @brief Display CLIQUE clustering results. @param[in] data (list): Data that was used for clustering. @param[in] clusters (array_like): Clusters that were allocated by the algorithm. @param[in] noise (array_like)...
def transform_array(rot_mtx,vec_array): '''transform_array( matrix, vector_array ) -> vector_array ''' return map( lambda x,m=rot_mtx:transform(m,x), vec_array )
transform_array( matrix, vector_array ) -> vector_array
Below is the the instruction that describes the task: ### Input: transform_array( matrix, vector_array ) -> vector_array ### Response: def transform_array(rot_mtx,vec_array): '''transform_array( matrix, vector_array ) -> vector_array ''' return map( lambda x,m=rot_mtx:transform(m,x), vec_array )
def neutralize_variable(self, variable_name): """ Neutralizes an OpenFisca variable existing in the tax and benefit system. A neutralized variable always returns its default value when computed. Trying to set inputs for a neutralized variable has no effect except raising a warning. ...
Neutralizes an OpenFisca variable existing in the tax and benefit system. A neutralized variable always returns its default value when computed. Trying to set inputs for a neutralized variable has no effect except raising a warning.
Below is the the instruction that describes the task: ### Input: Neutralizes an OpenFisca variable existing in the tax and benefit system. A neutralized variable always returns its default value when computed. Trying to set inputs for a neutralized variable has no effect except raising a warning. ...
def _get_input_files(samples, base_dir, tx_out_dir): """Retrieve input files, keyed by sample and QC method name. Stages files into the work directory to ensure correct names for MultiQC sample assessment when running with CWL. """ in_files = collections.defaultdict(list) for data in samples: ...
Retrieve input files, keyed by sample and QC method name. Stages files into the work directory to ensure correct names for MultiQC sample assessment when running with CWL.
Below is the the instruction that describes the task: ### Input: Retrieve input files, keyed by sample and QC method name. Stages files into the work directory to ensure correct names for MultiQC sample assessment when running with CWL. ### Response: def _get_input_files(samples, base_dir, tx_out_dir): ...
def loadfile(self, filename, mode='replace', **options): """Mapped mpv loadfile command, see man mpv(1).""" self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
Mapped mpv loadfile command, see man mpv(1).
Below is the the instruction that describes the task: ### Input: Mapped mpv loadfile command, see man mpv(1). ### Response: def loadfile(self, filename, mode='replace', **options): """Mapped mpv loadfile command, see man mpv(1).""" self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode...
def list_actions(name, location='\\'): r''' List all actions that pertain to a task in the specified location. :param str name: The name of the task for which list actions. :param str location: A string value representing the location of the task from which to list actions. Default is '\\' whi...
r''' List all actions that pertain to a task in the specified location. :param str name: The name of the task for which list actions. :param str location: A string value representing the location of the task from which to list actions. Default is '\\' which is the root for the task schedul...
Below is the the instruction that describes the task: ### Input: r''' List all actions that pertain to a task in the specified location. :param str name: The name of the task for which list actions. :param str location: A string value representing the location of the task from which to list ac...
def marketOhlcDF(token='', version=''): '''Returns the official open and close for whole market. https://iexcloud.io/docs/api/#news 9:30am-5pm ET Mon-Fri Args: token (string); Access token version (string); API version Returns: DataFrame: result ''' x = marketOhlc(...
Returns the official open and close for whole market. https://iexcloud.io/docs/api/#news 9:30am-5pm ET Mon-Fri Args: token (string); Access token version (string); API version Returns: DataFrame: result
Below is the the instruction that describes the task: ### Input: Returns the official open and close for whole market. https://iexcloud.io/docs/api/#news 9:30am-5pm ET Mon-Fri Args: token (string); Access token version (string); API version Returns: DataFrame: result ### R...
def hash_of_signed_transaction(txn_obj): ''' Regenerate the hash of the signed transaction object. 1. Infer the chain ID from the signature 2. Strip out signature from transaction 3. Annotate the transaction with that ID, if available 4. Take the hash of the serialized, unsigned, chain-aware tr...
Regenerate the hash of the signed transaction object. 1. Infer the chain ID from the signature 2. Strip out signature from transaction 3. Annotate the transaction with that ID, if available 4. Take the hash of the serialized, unsigned, chain-aware transaction Chain ID inference and annotation is a...
Below is the the instruction that describes the task: ### Input: Regenerate the hash of the signed transaction object. 1. Infer the chain ID from the signature 2. Strip out signature from transaction 3. Annotate the transaction with that ID, if available 4. Take the hash of the serialized, unsigned...
def _formatExternalIdentifier(self, element, element_type): """ Formats a single external identifier for query """ if "http" not in element['database']: term = "{}:{}".format(element['database'], element['identifier']) namespaceTerm = self._toNamespaceURL(term) ...
Formats a single external identifier for query
Below is the the instruction that describes the task: ### Input: Formats a single external identifier for query ### Response: def _formatExternalIdentifier(self, element, element_type): """ Formats a single external identifier for query """ if "http" not in element['database']: ...
def openNotification(self): ''' Opens the notification shade. ''' # the tablet has a different Notification/Quick Settings bar depending on x w13 = self.device.display['width'] / 3 s = (w13, 0) e = (w13, self.device.display['height']/2) self.device.drag(s...
Opens the notification shade.
Below is the the instruction that describes the task: ### Input: Opens the notification shade. ### Response: def openNotification(self): ''' Opens the notification shade. ''' # the tablet has a different Notification/Quick Settings bar depending on x w13 = self.device.displ...
def do_peek(self, args): """Peek at the next 16 bytes in the stream:: Example: The peek command will display the next 16 hex bytes in the input stream:: pfp> peek 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 .PNG........IHDR """ ...
Peek at the next 16 bytes in the stream:: Example: The peek command will display the next 16 hex bytes in the input stream:: pfp> peek 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 .PNG........IHDR
Below is the the instruction that describes the task: ### Input: Peek at the next 16 bytes in the stream:: Example: The peek command will display the next 16 hex bytes in the input stream:: pfp> peek 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 .P...
def _forward(self, x_dot_parameters): """ Helper to calculate the forward weights. """ return forward(self._lattice, x_dot_parameters, self.state_machine.n_states)
Helper to calculate the forward weights.
Below is the the instruction that describes the task: ### Input: Helper to calculate the forward weights. ### Response: def _forward(self, x_dot_parameters): """ Helper to calculate the forward weights. """ return forward(self._lattice, x_dot_parameters, self.state_machine....
def logpdf_link(self, link_f, y, Y_metadata=None): """ Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = \\alpha_{i}\\log \\beta - \\log \\Gamma(\\alpha_{i}) + (\\alpha_{i} - 1)\\log y_{i} - \\beta y_{i}\\\\ \\alpha_{i} = \\beta y_{i} ...
Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = \\alpha_{i}\\log \\beta - \\log \\Gamma(\\alpha_{i}) + (\\alpha_{i} - 1)\\log y_{i} - \\beta y_{i}\\\\ \\alpha_{i} = \\beta y_{i} :param link_f: latent variables (link(f)) :type link_f: Nx1 a...
Below is the the instruction that describes the task: ### Input: Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = \\alpha_{i}\\log \\beta - \\log \\Gamma(\\alpha_{i}) + (\\alpha_{i} - 1)\\log y_{i} - \\beta y_{i}\\\\ \\alpha_{i} = \\beta y_{i} ...
def init(vcs): """Initialize the locking module for a repository """ path = os.path.join(vcs.private_dir(), 'locks') if not os.path.exists(path): os.mkdir(path)
Initialize the locking module for a repository
Below is the the instruction that describes the task: ### Input: Initialize the locking module for a repository ### Response: def init(vcs): """Initialize the locking module for a repository """ path = os.path.join(vcs.private_dir(), 'locks') if not os.path.exists(path): os.mkdir(path)
def shutdown(self): """关停当前连接. 用于主动关停连接,并清理一些任务,包括: + 取消监听任务 + 取消过期监控任务 + 取消其他还没执行完的任务 + 将流读写器都重置 """ self._handlertask.cancel() if self._timeout_handler: self._timeout_handler.cancel() self._transport = None self._st...
关停当前连接. 用于主动关停连接,并清理一些任务,包括: + 取消监听任务 + 取消过期监控任务 + 取消其他还没执行完的任务 + 将流读写器都重置
Below is the the instruction that describes the task: ### Input: 关停当前连接. 用于主动关停连接,并清理一些任务,包括: + 取消监听任务 + 取消过期监控任务 + 取消其他还没执行完的任务 + 将流读写器都重置 ### Response: def shutdown(self): """关停当前连接. 用于主动关停连接,并清理一些任务,包括: + 取消监听任务 + 取消过期监控任务 + 取消其他还...
def close(self): """Close port.""" os.close(self.in_d) os.close(self.out_d)
Close port.
Below is the the instruction that describes the task: ### Input: Close port. ### Response: def close(self): """Close port.""" os.close(self.in_d) os.close(self.out_d)
def plot_diagram(config, results, images_dir, out_filename): """Plot one diagram""" img_files = plot_temp_diagrams(config, results, images_dir) join_images(img_files, out_filename) for img_file in img_files: os.remove(img_file)
Plot one diagram
Below is the the instruction that describes the task: ### Input: Plot one diagram ### Response: def plot_diagram(config, results, images_dir, out_filename): """Plot one diagram""" img_files = plot_temp_diagrams(config, results, images_dir) join_images(img_files, out_filename) for img_file in img_fi...
def text_to_bytes_and_warn(label, obj): """ If ``obj`` is text, emit a warning that it should be bytes instead and try to convert it to bytes automatically. :param str label: The name of the parameter from which ``obj`` was taken (so a developer can easily find the source of the problem and cor...
If ``obj`` is text, emit a warning that it should be bytes instead and try to convert it to bytes automatically. :param str label: The name of the parameter from which ``obj`` was taken (so a developer can easily find the source of the problem and correct it). :return: If ``obj`` is the te...
Below is the the instruction that describes the task: ### Input: If ``obj`` is text, emit a warning that it should be bytes instead and try to convert it to bytes automatically. :param str label: The name of the parameter from which ``obj`` was taken (so a developer can easily find the source of th...
def tokenize(self, text, include_punc=True, **kwargs): """Return a list of word tokens. :param text: string of text. :param include_punc: (optional) whether to include punctuation as separate tokens. Default to True. """ return self.tokenizer.word_tokenize(text, inc...
Return a list of word tokens. :param text: string of text. :param include_punc: (optional) whether to include punctuation as separate tokens. Default to True.
Below is the the instruction that describes the task: ### Input: Return a list of word tokens. :param text: string of text. :param include_punc: (optional) whether to include punctuation as separate tokens. Default to True. ### Response: def tokenize(self, text, include_punc=True, **kw...
def rindex(self, sub, *args): ''' S.rindex(sub [,start [,end]]) -> int Like S.rfind() but raise ValueError when the substring is not found. ''' pos = self.rfind(sub, *args) if pos == -1: raise ValueError('substring not found')
S.rindex(sub [,start [,end]]) -> int Like S.rfind() but raise ValueError when the substring is not found.
Below is the the instruction that describes the task: ### Input: S.rindex(sub [,start [,end]]) -> int Like S.rfind() but raise ValueError when the substring is not found. ### Response: def rindex(self, sub, *args): ''' S.rindex(sub [,start [,end]]) -> int Like S.rfind() but raise ...
def stop(self, name): """Stop a service """ init = self._get_implementation(name) self._assert_service_installed(init, name) logger.info('Stopping service: %s...', name) init.stop()
Stop a service
Below is the the instruction that describes the task: ### Input: Stop a service ### Response: def stop(self, name): """Stop a service """ init = self._get_implementation(name) self._assert_service_installed(init, name) logger.info('Stopping service: %s...', name) ini...
def bind(mod_path, with_path=None): """ bind user variable to `_wrapped` .. note:: you don't need call this method by yourself. program will call it in `cliez.parser.parse` .. expection:: if path is not correct,will cause an `ImportError` ...
bind user variable to `_wrapped` .. note:: you don't need call this method by yourself. program will call it in `cliez.parser.parse` .. expection:: if path is not correct,will cause an `ImportError` :param str mod_path: module path, *use dot style,'mo...
Below is the the instruction that describes the task: ### Input: bind user variable to `_wrapped` .. note:: you don't need call this method by yourself. program will call it in `cliez.parser.parse` .. expection:: if path is not correct,will cause an `Import...
def find_providers(self, reqt): """ Find the distributions which can fulfill a requirement. :param reqt: The requirement. :type reqt: str :return: A set of distribution which can fulfill the requirement. """ matcher = self.get_matcher(reqt) name = matche...
Find the distributions which can fulfill a requirement. :param reqt: The requirement. :type reqt: str :return: A set of distribution which can fulfill the requirement.
Below is the the instruction that describes the task: ### Input: Find the distributions which can fulfill a requirement. :param reqt: The requirement. :type reqt: str :return: A set of distribution which can fulfill the requirement. ### Response: def find_providers(self, reqt): ""...
def load_obsdata(self, idx: int) -> None: """Load the next obs sequence value (of the given index).""" if self._obs_ramflag: self.obs[0] = self._obs_array[idx] elif self._obs_diskflag: raw = self._obs_file.read(8) self.obs[0] = struct.unpack('d', raw)
Load the next obs sequence value (of the given index).
Below is the the instruction that describes the task: ### Input: Load the next obs sequence value (of the given index). ### Response: def load_obsdata(self, idx: int) -> None: """Load the next obs sequence value (of the given index).""" if self._obs_ramflag: self.obs[0] = self._obs_arra...
def urls(self): """ Get all of the api endpoints. NOTE: only for django as of now. NOTE: urlpatterns are deprecated since Django1.8 :return list: urls """ from django.conf.urls import url urls = [ url(r'^$', self.documentation), url(r'^m...
Get all of the api endpoints. NOTE: only for django as of now. NOTE: urlpatterns are deprecated since Django1.8 :return list: urls
Below is the the instruction that describes the task: ### Input: Get all of the api endpoints. NOTE: only for django as of now. NOTE: urlpatterns are deprecated since Django1.8 :return list: urls ### Response: def urls(self): """ Get all of the api endpoints. NOTE: only f...
def blade_idrac(name, idrac_password=None, idrac_ipmi=None, idrac_ip=None, idrac_netmask=None, idrac_gateway=None, idrac_dnsname=None, idrac_dhcp=None): ''' Set parameters for iDRAC in a blade. :param idrac_password: Password to use to connect to the iDRACs d...
Set parameters for iDRAC in a blade. :param idrac_password: Password to use to connect to the iDRACs directly (idrac_ipmi and idrac_dnsname must be set directly on the iDRAC. They can't be set through the CMC. If this password is present, use it instead of the CMC password) :param idr...
Below is the the instruction that describes the task: ### Input: Set parameters for iDRAC in a blade. :param idrac_password: Password to use to connect to the iDRACs directly (idrac_ipmi and idrac_dnsname must be set directly on the iDRAC. They can't be set through the CMC. If this password i...
def upsert(path, value, create_parents=False, **kwargs): """ Create or replace a dictionary path. :param path: The path to modify :param value: The new value for the path. This should be a native Python object which can be encoded into JSON (the SDK will do the encoding for you). :p...
Create or replace a dictionary path. :param path: The path to modify :param value: The new value for the path. This should be a native Python object which can be encoded into JSON (the SDK will do the encoding for you). :param create_parents: Whether intermediate parents should be created. ...
Below is the the instruction that describes the task: ### Input: Create or replace a dictionary path. :param path: The path to modify :param value: The new value for the path. This should be a native Python object which can be encoded into JSON (the SDK will do the encoding for you). :p...
def add_cv_description(self, cv_id, lang_ref, description=None): """Add a description to a controlled vocabulary. :param str cv_id: Name of the controlled vocabulary to add the description. :param str lang_ref: Language reference. :param str description: Description, this ca...
Add a description to a controlled vocabulary. :param str cv_id: Name of the controlled vocabulary to add the description. :param str lang_ref: Language reference. :param str description: Description, this can be none. :throws KeyError: If there is no controlled vocabulary wi...
Below is the the instruction that describes the task: ### Input: Add a description to a controlled vocabulary. :param str cv_id: Name of the controlled vocabulary to add the description. :param str lang_ref: Language reference. :param str description: Description, this can be no...
def remove_router_from_hosting_device(self, context, hosting_device_id, router_id): """Remove the router from hosting device. After removal, the router will be non-hosted until there is update which leads to re-schedule or be added to another hosting de...
Remove the router from hosting device. After removal, the router will be non-hosted until there is update which leads to re-schedule or be added to another hosting device manually.
Below is the the instruction that describes the task: ### Input: Remove the router from hosting device. After removal, the router will be non-hosted until there is update which leads to re-schedule or be added to another hosting device manually. ### Response: def remove_router_from_hosting...
def _check_self_to_empty(self, stateid): """ Because of the optimization, the rule for empty states is missing A check takes place live Args: stateid (int): The state identifier Returns: bool: A true or false response """ x_term = stateid.r...
Because of the optimization, the rule for empty states is missing A check takes place live Args: stateid (int): The state identifier Returns: bool: A true or false response
Below is the the instruction that describes the task: ### Input: Because of the optimization, the rule for empty states is missing A check takes place live Args: stateid (int): The state identifier Returns: bool: A true or false response ### Response: def _check_self...
def _report_final_failure(self, err, flaky, name): """ Report that the test has failed too many times to pass at least min_passes times. By default, this means that the test has failed twice. :param err: Information about the test failure (from sys.exc_info()) ...
Report that the test has failed too many times to pass at least min_passes times. By default, this means that the test has failed twice. :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `trac...
Below is the the instruction that describes the task: ### Input: Report that the test has failed too many times to pass at least min_passes times. By default, this means that the test has failed twice. :param err: Information about the test failure (from sys.exc_info()) ...
def _safe_match_list(inner_type, argument_value): """Represent the list of "inner_type" objects in MATCH form.""" stripped_type = strip_non_null_from_type(inner_type) if isinstance(stripped_type, GraphQLList): raise GraphQLInvalidArgumentError(u'MATCH does not currently support nested lists, ' ...
Represent the list of "inner_type" objects in MATCH form.
Below is the the instruction that describes the task: ### Input: Represent the list of "inner_type" objects in MATCH form. ### Response: def _safe_match_list(inner_type, argument_value): """Represent the list of "inner_type" objects in MATCH form.""" stripped_type = strip_non_null_from_type(inner_type) ...
async def send(self, data): """ Add data to send queue. """ self.writer.write(data) await self.writer.drain()
Add data to send queue.
Below is the the instruction that describes the task: ### Input: Add data to send queue. ### Response: async def send(self, data): """ Add data to send queue. """ self.writer.write(data) await self.writer.drain()
def rgb2termhex(r: int, g: int, b: int) -> str: """ Convert an rgb value to the nearest hex value that matches a term code. The hex value will be one in `hex2term_map`. """ incs = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff] res = [] parts = r, g, b for part in parts: if (part < 0) or (...
Convert an rgb value to the nearest hex value that matches a term code. The hex value will be one in `hex2term_map`.
Below is the the instruction that describes the task: ### Input: Convert an rgb value to the nearest hex value that matches a term code. The hex value will be one in `hex2term_map`. ### Response: def rgb2termhex(r: int, g: int, b: int) -> str: """ Convert an rgb value to the nearest hex value that matc...
def update_fname_label(self): """Upadte file name label.""" filename = to_text_string(self.get_current_filename()) if len(filename) > 100: shorten_filename = u'...' + filename[-100:] else: shorten_filename = filename self.fname_label.setText(shorten...
Upadte file name label.
Below is the the instruction that describes the task: ### Input: Upadte file name label. ### Response: def update_fname_label(self): """Upadte file name label.""" filename = to_text_string(self.get_current_filename()) if len(filename) > 100: shorten_filename = u'...' + filen...
def strip_tashkeel(text): """Strip vowels from a text, include Shadda. The striped marks are : - FATHA, DAMMA, KASRA - SUKUN - SHADDA - FATHATAN, DAMMATAN, KASRATAN, , , . @param text: arabic text. @type text: unicode. @return: return a striped text. @rty...
Strip vowels from a text, include Shadda. The striped marks are : - FATHA, DAMMA, KASRA - SUKUN - SHADDA - FATHATAN, DAMMATAN, KASRATAN, , , . @param text: arabic text. @type text: unicode. @return: return a striped text. @rtype: unicode.
Below is the the instruction that describes the task: ### Input: Strip vowels from a text, include Shadda. The striped marks are : - FATHA, DAMMA, KASRA - SUKUN - SHADDA - FATHATAN, DAMMATAN, KASRATAN, , , . @param text: arabic text. @type text: unicode. @ret...
def read(device): """ Reads data from the specified device. :param device: the AlarmDecoder device :type device: :py:class:`~alarmdecoder.devices.Device` :returns: string """ response = None bytes_avail = bytes_available(device) if isinstance(de...
Reads data from the specified device. :param device: the AlarmDecoder device :type device: :py:class:`~alarmdecoder.devices.Device` :returns: string
Below is the the instruction that describes the task: ### Input: Reads data from the specified device. :param device: the AlarmDecoder device :type device: :py:class:`~alarmdecoder.devices.Device` :returns: string ### Response: def read(device): """ Reads data from the spe...
def emit(self, tup, stream=Stream.DEFAULT_STREAM_ID, anchors=None, direct_task=None, need_task_ids=False): """Emits a new tuple from this Bolt It is compatible with StreamParse API. :type tup: list or tuple :param tup: the new output Tuple to send from this bolt, should only...
Emits a new tuple from this Bolt It is compatible with StreamParse API. :type tup: list or tuple :param tup: the new output Tuple to send from this bolt, should only contain only serializable data. :type stream: str :param stream: the ID of the stream to emit this Tuple to. ...
Below is the the instruction that describes the task: ### Input: Emits a new tuple from this Bolt It is compatible with StreamParse API. :type tup: list or tuple :param tup: the new output Tuple to send from this bolt, should only contain only serializable data. :type stream: str ...
def get_contact(self, email): """Get Filemail contact based on email. :param email: address of contact :type email: ``str``, ``unicode`` :rtype: ``dict`` with contact information """ contacts = self.get_contacts() for contact in contacts: if contact[...
Get Filemail contact based on email. :param email: address of contact :type email: ``str``, ``unicode`` :rtype: ``dict`` with contact information
Below is the the instruction that describes the task: ### Input: Get Filemail contact based on email. :param email: address of contact :type email: ``str``, ``unicode`` :rtype: ``dict`` with contact information ### Response: def get_contact(self, email): """Get Filemail contact bas...
def differential_pressure_meter_dP(D, D2, P1, P2, C=None, meter_type=ISO_5167_ORIFICE): r'''Calculates either the non-recoverable pressure drop of a differential pressure flow meter based on the geometry of the meter, measured pressures of the meter, and for most models ...
r'''Calculates either the non-recoverable pressure drop of a differential pressure flow meter based on the geometry of the meter, measured pressures of the meter, and for most models the meter discharge coefficient. Parameters ---------- D : float Upstream internal pipe diameter, [m] ...
Below is the the instruction that describes the task: ### Input: r'''Calculates either the non-recoverable pressure drop of a differential pressure flow meter based on the geometry of the meter, measured pressures of the meter, and for most models the meter discharge coefficient. Parameters --...
def create_dump(): """ Create the grammar for the 'dump' statement """ dump = upkey("dump").setResultsName("action") return ( dump + upkey("schema") + Optional(Group(delimitedList(table)).setResultsName("tables")) )
Create the grammar for the 'dump' statement
Below is the the instruction that describes the task: ### Input: Create the grammar for the 'dump' statement ### Response: def create_dump(): """ Create the grammar for the 'dump' statement """ dump = upkey("dump").setResultsName("action") return ( dump + upkey("schema") + Optio...
def init_mpraw(mpv, npv): """Set a global variable as a multiprocessing RawArray in shared memory with a numpy array wrapper and initialise its value. Parameters ---------- mpv : string Name of global variable to set npv : ndarray Numpy array to use as initialiser for global variabl...
Set a global variable as a multiprocessing RawArray in shared memory with a numpy array wrapper and initialise its value. Parameters ---------- mpv : string Name of global variable to set npv : ndarray Numpy array to use as initialiser for global variable value
Below is the the instruction that describes the task: ### Input: Set a global variable as a multiprocessing RawArray in shared memory with a numpy array wrapper and initialise its value. Parameters ---------- mpv : string Name of global variable to set npv : ndarray Numpy array to u...
def limit_acceleration(self, accel): """Sets the acceleration limit on the Grizzly. The max value is 143. Units are change in pwm per millisecond. Internally, the pwm is in the range [-0x7f, 0x7f] or [-127, 127]. So in one millisecond the maximum acceleration limit possible is 127 - -127...
Sets the acceleration limit on the Grizzly. The max value is 143. Units are change in pwm per millisecond. Internally, the pwm is in the range [-0x7f, 0x7f] or [-127, 127]. So in one millisecond the maximum acceleration limit possible is 127 - -127 = 142. The internal default value is 4*...
Below is the the instruction that describes the task: ### Input: Sets the acceleration limit on the Grizzly. The max value is 143. Units are change in pwm per millisecond. Internally, the pwm is in the range [-0x7f, 0x7f] or [-127, 127]. So in one millisecond the maximum acceleration limit p...
def check_bin_existence(self, chi1_bin, chi2_bin): """ Given indices for bins in chi1 and chi2 space check that the bin exists in the object. If not add it. Also check for the existence of all bins within +/- self.bin_range_check and add if not present. Parameters ------...
Given indices for bins in chi1 and chi2 space check that the bin exists in the object. If not add it. Also check for the existence of all bins within +/- self.bin_range_check and add if not present. Parameters ----------- chi1_bin : int The index of the chi1_bin to c...
Below is the the instruction that describes the task: ### Input: Given indices for bins in chi1 and chi2 space check that the bin exists in the object. If not add it. Also check for the existence of all bins within +/- self.bin_range_check and add if not present. Parameters --------...
def _format_signature(self, signature, doc='', parameter='', parameter_doc='', color=_DEFAULT_TITLE_COLOR, is_python=False): """ Create HTML template for signature. This template will include indent after the method name, a highlight ...
Create HTML template for signature. This template will include indent after the method name, a highlight color for the active parameter and highlights for special chars.
Below is the the instruction that describes the task: ### Input: Create HTML template for signature. This template will include indent after the method name, a highlight color for the active parameter and highlights for special chars. ### Response: def _format_signature(self, signature, doc='',...
def add_parameters(self, traj): """Adds parameters and config from the `.ini` file to the trajectory""" if self.config_file: parameters = self._collect_section('parameters') for name in parameters: value = parameters[name] if not isinstance(value, ...
Adds parameters and config from the `.ini` file to the trajectory
Below is the the instruction that describes the task: ### Input: Adds parameters and config from the `.ini` file to the trajectory ### Response: def add_parameters(self, traj): """Adds parameters and config from the `.ini` file to the trajectory""" if self.config_file: parameters = self...
def upgrade(config, revision, **kwargs): """ Upgrade database. """ with alembic_lock( config.registry["sqlalchemy.engine"], config.alembic_config() ) as alembic_config: alembic.command.upgrade(alembic_config, revision, **kwargs)
Upgrade database.
Below is the the instruction that describes the task: ### Input: Upgrade database. ### Response: def upgrade(config, revision, **kwargs): """ Upgrade database. """ with alembic_lock( config.registry["sqlalchemy.engine"], config.alembic_config() ) as alembic_config: alembic.comma...
def StartGuiSession(self): """ Launches the UCSM GUI via specific UCS handle. """ from UcsBase import WriteUcsWarning, UcsUtils, UcsValidationException import urllib, tempfile, fileinput, os, subprocess, platform osSupport = ["Windows", "Linux", "Microsoft"] if platform.system() not in osSupport: raise U...
Launches the UCSM GUI via specific UCS handle.
Below is the the instruction that describes the task: ### Input: Launches the UCSM GUI via specific UCS handle. ### Response: def StartGuiSession(self): """ Launches the UCSM GUI via specific UCS handle. """ from UcsBase import WriteUcsWarning, UcsUtils, UcsValidationException import urllib, tempfile, filein...
def write_Composition(composition, filename, zip=False): """Create an XML file (or MXL if compressed) for a given composition.""" text = from_Composition(composition) if not zip: f = open(filename + '.xml', 'w') f.write(text) f.close() else: import zipfile import ...
Create an XML file (or MXL if compressed) for a given composition.
Below is the the instruction that describes the task: ### Input: Create an XML file (or MXL if compressed) for a given composition. ### Response: def write_Composition(composition, filename, zip=False): """Create an XML file (or MXL if compressed) for a given composition.""" text = from_Composition(composi...
def setConf(self, conf, type='simu'): """ set information for different type dict, :param conf: configuration information, str or dict :param type: simu, ctrl, misc """ if conf is None: return else: if isinstance(conf, str): conf =...
set information for different type dict, :param conf: configuration information, str or dict :param type: simu, ctrl, misc
Below is the the instruction that describes the task: ### Input: set information for different type dict, :param conf: configuration information, str or dict :param type: simu, ctrl, misc ### Response: def setConf(self, conf, type='simu'): """ set information for different type dict, ...
def stream(self, id, task, type, follow=False, offset=0, origin="start", plain=False): """ This endpoint streams a task's stderr/stdout logs. https://www.nomadproject.io/api/client.html#stream-logs arguments: - id: (str) allocation_id required - task: (str) ...
This endpoint streams a task's stderr/stdout logs. https://www.nomadproject.io/api/client.html#stream-logs arguments: - id: (str) allocation_id required - task: (str) name of the task inside the allocation to stream logs from - type: (str) Specifies th...
Below is the the instruction that describes the task: ### Input: This endpoint streams a task's stderr/stdout logs. https://www.nomadproject.io/api/client.html#stream-logs arguments: - id: (str) allocation_id required - task: (str) name of the task inside the al...
def send_message_sync( self, message: Message, sender: str = None, recipients: RecipientsType = None, mail_options: Iterable[str] = None, rcpt_options: Iterable[str] = None, timeout: DefaultNumType = _default, ) -> SendmailResponseType: """ Syn...
Synchronous version of :meth:`.send_message`. This method starts the event loop to connect, send the message, and disconnect.
Below is the the instruction that describes the task: ### Input: Synchronous version of :meth:`.send_message`. This method starts the event loop to connect, send the message, and disconnect. ### Response: def send_message_sync( self, message: Message, sender: str = None, rec...
def write_dockerfile(self, output_dir): """ Used only to write a Dockerfile that will NOT be built by docker-make """ if not os.path.exists(output_dir): os.makedirs(output_dir) lines = [] for istep, step in enumerate(self.steps): if istep == 0: ...
Used only to write a Dockerfile that will NOT be built by docker-make
Below is the the instruction that describes the task: ### Input: Used only to write a Dockerfile that will NOT be built by docker-make ### Response: def write_dockerfile(self, output_dir): """ Used only to write a Dockerfile that will NOT be built by docker-make """ if not os.path.exists(ou...
def CreateSessionStart(self): """Creates a session start. Returns: SessionStart: session start attribute container. """ session_start = SessionStart() session_start.artifact_filters = self.artifact_filters session_start.command_line_arguments = self.command_line_arguments session_star...
Creates a session start. Returns: SessionStart: session start attribute container.
Below is the the instruction that describes the task: ### Input: Creates a session start. Returns: SessionStart: session start attribute container. ### Response: def CreateSessionStart(self): """Creates a session start. Returns: SessionStart: session start attribute container. """ ...
def is_uniform(keys, axis=semantics.axis_default): """returns true if all keys have equal multiplicity""" index = as_index(keys, axis) return index.uniform
returns true if all keys have equal multiplicity
Below is the the instruction that describes the task: ### Input: returns true if all keys have equal multiplicity ### Response: def is_uniform(keys, axis=semantics.axis_default): """returns true if all keys have equal multiplicity""" index = as_index(keys, axis) return index.uniform
def make_backups(self, block_id): """ If we're doing backups on a regular basis, then carry them out here if it is time to do so. This method does nothing otherwise. Return None on success Abort on failure """ assert self.setup, "Not set up yet. Call .d...
If we're doing backups on a regular basis, then carry them out here if it is time to do so. This method does nothing otherwise. Return None on success Abort on failure
Below is the the instruction that describes the task: ### Input: If we're doing backups on a regular basis, then carry them out here if it is time to do so. This method does nothing otherwise. Return None on success Abort on failure ### Response: def make_backups(self, block_id): ...
def vote_up_idea(self, *args, **kwargs): """ :allowed_param: 'ideaId', 'myVote' (optional) """ kwargs.update({'headers': {'content-type':'application/json'}}) return bind_api( api=self, path='/ideas/{ideaId}/vote/up', method='POST', payload...
:allowed_param: 'ideaId', 'myVote' (optional)
Below is the the instruction that describes the task: ### Input: :allowed_param: 'ideaId', 'myVote' (optional) ### Response: def vote_up_idea(self, *args, **kwargs): """ :allowed_param: 'ideaId', 'myVote' (optional) """ kwargs.update({'headers': {'content-type':'application/json'}}) ...
def set_extension(self, name, value): """ Sets the value for an extension using a fully constructed asn1crypto.core.Asn1Value object. Normally this should not be needed, and the convenience attributes should be sufficient. See the definition of asn1crypto.ocsp.TBSRequestExtensio...
Sets the value for an extension using a fully constructed asn1crypto.core.Asn1Value object. Normally this should not be needed, and the convenience attributes should be sufficient. See the definition of asn1crypto.ocsp.TBSRequestExtension and asn1crypto.ocsp.RequestExtension to determin...
Below is the the instruction that describes the task: ### Input: Sets the value for an extension using a fully constructed asn1crypto.core.Asn1Value object. Normally this should not be needed, and the convenience attributes should be sufficient. See the definition of asn1crypto.ocsp.TBSRequ...
def list_available_work_units(self, work_spec_name, start=0, limit=None): """Get a dictionary of available work units for some work spec. The dictionary is from work unit name to work unit definiton. Only work units that have not been started, or units that were started but did not comp...
Get a dictionary of available work units for some work spec. The dictionary is from work unit name to work unit definiton. Only work units that have not been started, or units that were started but did not complete in a timely fashion, are included.
Below is the the instruction that describes the task: ### Input: Get a dictionary of available work units for some work spec. The dictionary is from work unit name to work unit definiton. Only work units that have not been started, or units that were started but did not complete in a timely...
def unescape(self, varname, value): """ Unescape `value`. """ f = self.unescape_funcs.get(varname) return f(value) if f else value
Unescape `value`.
Below is the the instruction that describes the task: ### Input: Unescape `value`. ### Response: def unescape(self, varname, value): """ Unescape `value`. """ f = self.unescape_funcs.get(varname) return f(value) if f else value
def serialize(self, tag): """Serialize tag and print it to the output.""" try: tag.serialize(self) except (AttributeError, TypeError): self.write(str(tag))
Serialize tag and print it to the output.
Below is the the instruction that describes the task: ### Input: Serialize tag and print it to the output. ### Response: def serialize(self, tag): """Serialize tag and print it to the output.""" try: tag.serialize(self) except (AttributeError, TypeError): self.write(...
def get_used_template(response): """ Get the template used in a TemplateResponse. This returns a tuple of "active choice, all choices" """ if not hasattr(response, 'template_name'): return None, None template = response.template_name if template is None: return None, None ...
Get the template used in a TemplateResponse. This returns a tuple of "active choice, all choices"
Below is the the instruction that describes the task: ### Input: Get the template used in a TemplateResponse. This returns a tuple of "active choice, all choices" ### Response: def get_used_template(response): """ Get the template used in a TemplateResponse. This returns a tuple of "active choice, ...
def find_all_output_in_range(self, ifo, currSeg, useSplitLists=False): """ Return all files that overlap the specified segment. """ if not useSplitLists: # Slower, but simpler method outFiles = [i for i in self if ifo in i.ifo_list] outFiles = [i for i...
Return all files that overlap the specified segment.
Below is the the instruction that describes the task: ### Input: Return all files that overlap the specified segment. ### Response: def find_all_output_in_range(self, ifo, currSeg, useSplitLists=False): """ Return all files that overlap the specified segment. """ if not useSplitList...
def _get_index_urls_locations(self, project_name): """Returns the locations found via self.index_urls Checks the url_name on the main (first in the list) index and use this url_name to produce all locations """ def mkurl_pypi_url(url): loc = posixpath.join(url, proj...
Returns the locations found via self.index_urls Checks the url_name on the main (first in the list) index and use this url_name to produce all locations
Below is the the instruction that describes the task: ### Input: Returns the locations found via self.index_urls Checks the url_name on the main (first in the list) index and use this url_name to produce all locations ### Response: def _get_index_urls_locations(self, project_name): """Retu...
def _lookup_user_data(self,*args,**kwargs): """ Generic function for looking up values in a user-specific dictionary. Use as follows:: _lookup_user_data('path','to','desired','value','in','dictionary', default = <default value>, ...
Generic function for looking up values in a user-specific dictionary. Use as follows:: _lookup_user_data('path','to','desired','value','in','dictionary', default = <default value>, data_kind = 'customization'/'saved_searches')
Below is the the instruction that describes the task: ### Input: Generic function for looking up values in a user-specific dictionary. Use as follows:: _lookup_user_data('path','to','desired','value','in','dictionary', default = <default value>, ...
def _update(self): """Emit dataChanged signal on all cells""" self.dataChanged.emit(self.createIndex(0, 0), self.createIndex( len(self.collection), len(self.header)))
Emit dataChanged signal on all cells
Below is the the instruction that describes the task: ### Input: Emit dataChanged signal on all cells ### Response: def _update(self): """Emit dataChanged signal on all cells""" self.dataChanged.emit(self.createIndex(0, 0), self.createIndex( len(self.collection), len(self.header)))
def disconnect_channel(self, destination_id): """ Disconnect a channel with destination_id. """ if destination_id in self._open_channels: try: self.send_message( destination_id, NS_CONNECTION, {MESSAGE_TYPE: TYPE_CLOSE, 'origin': {}}, ...
Disconnect a channel with destination_id.
Below is the the instruction that describes the task: ### Input: Disconnect a channel with destination_id. ### Response: def disconnect_channel(self, destination_id): """ Disconnect a channel with destination_id. """ if destination_id in self._open_channels: try: self.se...
def _return_container_objects(self): """Return a list of objects to delete. The return tuple will indicate if it was a userd efined list of objects as True of False. The list of objects is a list of dictionaries with the key being "container_object". :returns: tuple (`...
Return a list of objects to delete. The return tuple will indicate if it was a userd efined list of objects as True of False. The list of objects is a list of dictionaries with the key being "container_object". :returns: tuple (``bol``, ``list``)
Below is the the instruction that describes the task: ### Input: Return a list of objects to delete. The return tuple will indicate if it was a userd efined list of objects as True of False. The list of objects is a list of dictionaries with the key being "container_object". ...
def parse_bytes(field): ''' >>> parse_bytes('24B') 24.0 >>> parse_bytes('4MiB') 4194304.0 ''' if field[-1] in 'bB': field = field[:-1] try: for i, prefix in enumerate('KMGTPEZ'): if field.endswith(prefix + 'i'): factor = 2 ** (10 * (i + 1)) ...
>>> parse_bytes('24B') 24.0 >>> parse_bytes('4MiB') 4194304.0
Below is the the instruction that describes the task: ### Input: >>> parse_bytes('24B') 24.0 >>> parse_bytes('4MiB') 4194304.0 ### Response: def parse_bytes(field): ''' >>> parse_bytes('24B') 24.0 >>> parse_bytes('4MiB') 4194304.0 ''' if field[-1] in 'bB': field = fi...
def p_lvalue_one(self, p): 'lvalue : identifier' p[0] = Lvalue(p[1], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
lvalue : identifier
Below is the the instruction that describes the task: ### Input: lvalue : identifier ### Response: def p_lvalue_one(self, p): 'lvalue : identifier' p[0] = Lvalue(p[1], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
def _get_url(self, resource, item, sys_id=None): """Takes table and sys_id (if present), and returns a URL :param resource: API resource :param item: API resource item :param sys_id: Record sys_id :return: - url string """ url_str = '%(base_url)s/%(b...
Takes table and sys_id (if present), and returns a URL :param resource: API resource :param item: API resource item :param sys_id: Record sys_id :return: - url string
Below is the the instruction that describes the task: ### Input: Takes table and sys_id (if present), and returns a URL :param resource: API resource :param item: API resource item :param sys_id: Record sys_id :return: - url string ### Response: def _get_url(self, resou...
def gps_rtk_encode(self, time_last_baseline_ms, rtk_receiver_id, wn, tow, rtk_health, rtk_rate, nsats, baseline_coords_type, baseline_a_mm, baseline_b_mm, baseline_c_mm, accuracy, iar_num_hypotheses): ''' RTK GPS data. Gives information on the relative baseline calculation ...
RTK GPS data. Gives information on the relative baseline calculation the GPS is reporting time_last_baseline_ms : Time since boot of last baseline message received in ms. (uint32_t) rtk_receiver_id : Identification of connected RTK receiver. (uint8_t) ...
Below is the the instruction that describes the task: ### Input: RTK GPS data. Gives information on the relative baseline calculation the GPS is reporting time_last_baseline_ms : Time since boot of last baseline message received in ms. (uint32_t) rtk_receiver_...
def v_type_extension(ctx, stmt): """verify that the extension matches the extension definition""" (modulename, identifier) = stmt.keyword revision = stmt.i_extension_revision module = modulename_to_module(stmt.i_module, modulename, revision) if module is None: return if identifier not in...
verify that the extension matches the extension definition
Below is the the instruction that describes the task: ### Input: verify that the extension matches the extension definition ### Response: def v_type_extension(ctx, stmt): """verify that the extension matches the extension definition""" (modulename, identifier) = stmt.keyword revision = stmt.i_extension...
async def spawn_nodes(self, spawn_cmd, ports=None, **ssh_kwargs): """An alias for :meth:`creamas.ds.DistributedEnvironment.spawn_slaves`. """ return await self.spawn_slaves(spawn_cmd, ports=ports, **ssh_kwargs)
An alias for :meth:`creamas.ds.DistributedEnvironment.spawn_slaves`.
Below is the the instruction that describes the task: ### Input: An alias for :meth:`creamas.ds.DistributedEnvironment.spawn_slaves`. ### Response: async def spawn_nodes(self, spawn_cmd, ports=None, **ssh_kwargs): """An alias for :meth:`creamas.ds.DistributedEnvironment.spawn_slaves`. """ r...