code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def read_sql( sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None, ): """ Read SQL query or database table into a DataFrame. Args: sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed o...
Read SQL query or database table into a DataFrame. Args: sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed or a table name. con: SQLAlchemy connectable (engine/connection) or database string URI or DBAPI2 connection (fallback mode) index_col: Column(s) to...
Below is the the instruction that describes the task: ### Input: Read SQL query or database table into a DataFrame. Args: sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed or a table name. con: SQLAlchemy connectable (engine/connection) or database string URI...
def get_cql_models(app, connection=None, keyspace=None): """ :param app: django models module :param connection: connection name :param keyspace: keyspace :return: list of all cassandra.cqlengine.Model within app that should be synced to keyspace. """ from .models import DjangoCassandraM...
:param app: django models module :param connection: connection name :param keyspace: keyspace :return: list of all cassandra.cqlengine.Model within app that should be synced to keyspace.
Below is the the instruction that describes the task: ### Input: :param app: django models module :param connection: connection name :param keyspace: keyspace :return: list of all cassandra.cqlengine.Model within app that should be synced to keyspace. ### Response: def get_cql_models(app, connectio...
def process(self, msg, kwargs): """Process the logging message and keyword arguments passed in to a logging call to insert contextual information. :param str msg: The message to process :param dict kwargs: The kwargs to append :rtype: (str, dict) """ kwargs['ext...
Process the logging message and keyword arguments passed in to a logging call to insert contextual information. :param str msg: The message to process :param dict kwargs: The kwargs to append :rtype: (str, dict)
Below is the the instruction that describes the task: ### Input: Process the logging message and keyword arguments passed in to a logging call to insert contextual information. :param str msg: The message to process :param dict kwargs: The kwargs to append :rtype: (str, dict) ### Re...
def _dereference_args(pipeline_name, args, kwargs): """Dereference a Pipeline's arguments that are slots, validating them. Each argument value passed in is assumed to be a dictionary with the format: {'type': 'value', 'value': 'serializable'} # A resolved value. {'type': 'slot', 'slot_key': 'str() on a db...
Dereference a Pipeline's arguments that are slots, validating them. Each argument value passed in is assumed to be a dictionary with the format: {'type': 'value', 'value': 'serializable'} # A resolved value. {'type': 'slot', 'slot_key': 'str() on a db.Key'} # A pending Slot. Args: pipeline_name: The...
Below is the the instruction that describes the task: ### Input: Dereference a Pipeline's arguments that are slots, validating them. Each argument value passed in is assumed to be a dictionary with the format: {'type': 'value', 'value': 'serializable'} # A resolved value. {'type': 'slot', 'slot_key': 's...
def remove(self, elem): """ Return new deque with first element from left equal to elem removed. If no such element is found a ValueError is raised. >>> pdeque([2, 1, 2]).remove(2) pdeque([1, 2]) """ try: return PDeque(self._left_list.remove(elem), se...
Return new deque with first element from left equal to elem removed. If no such element is found a ValueError is raised. >>> pdeque([2, 1, 2]).remove(2) pdeque([1, 2])
Below is the the instruction that describes the task: ### Input: Return new deque with first element from left equal to elem removed. If no such element is found a ValueError is raised. >>> pdeque([2, 1, 2]).remove(2) pdeque([1, 2]) ### Response: def remove(self, elem): """ ...
def remove(self, item): """Remove either an unparsed argument string or an argument object. :param Union[str,Arg] item: Item to remove >>> arguments = TexArgs([RArg('arg0'), '[arg2]', '{arg3}']) >>> arguments.remove('{arg0}') >>> len(arguments) 2 >>> arguments[0...
Remove either an unparsed argument string or an argument object. :param Union[str,Arg] item: Item to remove >>> arguments = TexArgs([RArg('arg0'), '[arg2]', '{arg3}']) >>> arguments.remove('{arg0}') >>> len(arguments) 2 >>> arguments[0] OArg('arg2')
Below is the the instruction that describes the task: ### Input: Remove either an unparsed argument string or an argument object. :param Union[str,Arg] item: Item to remove >>> arguments = TexArgs([RArg('arg0'), '[arg2]', '{arg3}']) >>> arguments.remove('{arg0}') >>> len(arguments)...
def encipher_shift(plaintext, plain_vocab, shift): """Encrypt plain text with a single shift layer. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. shift (Integer): number of shift, shift to the right if shift is...
Encrypt plain text with a single shift layer. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. shift (Integer): number of shift, shift to the right if shift is positive. Returns: ciphertext (list of Strings): ...
Below is the the instruction that describes the task: ### Input: Encrypt plain text with a single shift layer. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. shift (Integer): number of shift, shift to the righ...
def export(self, class_name, method_name, export_data=False, export_dir='.', export_filename='data.json', export_append_checksum=False, **kwargs): """ Port a trained estimator to the syntax of a chosen programming language. Parameters ---------- :pa...
Port a trained estimator to the syntax of a chosen programming language. Parameters ---------- :param class_name : string The name of the class in the returned result. :param method_name : string The name of the method in the returned result. :param expor...
Below is the the instruction that describes the task: ### Input: Port a trained estimator to the syntax of a chosen programming language. Parameters ---------- :param class_name : string The name of the class in the returned result. :param method_name : string ...
def init_modules(self): ''' Initialize all modules consecutively''' for module_id, module_cfg in self._module_cfgs.items(): if module_id in self._modules or module_id in self._tx_module_groups: if module_id in self._modules: module_id_str = "module " + mod...
Initialize all modules consecutively
Below is the the instruction that describes the task: ### Input: Initialize all modules consecutively ### Response: def init_modules(self): ''' Initialize all modules consecutively''' for module_id, module_cfg in self._module_cfgs.items(): if module_id in self._modules or module_id in s...
def _load_model(self, dct): """Load a serialized PyPhi model. The object is memoized for reuse elsewhere in the object graph. """ classname, version, _ = _pop_metadata(dct) _check_version(version) cls = self._models[classname] # Use `from_json` if available ...
Load a serialized PyPhi model. The object is memoized for reuse elsewhere in the object graph.
Below is the the instruction that describes the task: ### Input: Load a serialized PyPhi model. The object is memoized for reuse elsewhere in the object graph. ### Response: def _load_model(self, dct): """Load a serialized PyPhi model. The object is memoized for reuse elsewhere in the obj...
def _extract_member(self, tarinfo, targetpath, set_attrs=True): """Extract the TarInfo object tarinfo to a physical file called targetpath. """ # Fetch the TarInfo object for the given name # and build the destination pathname, replacing # forward slashes to platform s...
Extract the TarInfo object tarinfo to a physical file called targetpath.
Below is the the instruction that describes the task: ### Input: Extract the TarInfo object tarinfo to a physical file called targetpath. ### Response: def _extract_member(self, tarinfo, targetpath, set_attrs=True): """Extract the TarInfo object tarinfo to a physical file called targe...
def reset_namespace(self, namespace=None, params=None): """ Will delete and recreate specified namespace args: namespace(str): Namespace to reset params(dict): params used to reset the namespace """ log = logging.getLogger("%s.%s" % (self.log_name, ...
Will delete and recreate specified namespace args: namespace(str): Namespace to reset params(dict): params used to reset the namespace
Below is the the instruction that describes the task: ### Input: Will delete and recreate specified namespace args: namespace(str): Namespace to reset params(dict): params used to reset the namespace ### Response: def reset_namespace(self, namespace=None, params=None): """ ...
def run(self, in_batches): """Run shell operator synchronously to eat `in_batches` :param in_batches: `tuple` of batches to process """ if len(in_batches) != len(self._batcmd.batch_to_file_s): BaseShellOperator._rm_process_input_tmpfiles(self._batcmd.batch_to_file_s) # [tod...
Run shell operator synchronously to eat `in_batches` :param in_batches: `tuple` of batches to process
Below is the the instruction that describes the task: ### Input: Run shell operator synchronously to eat `in_batches` :param in_batches: `tuple` of batches to process ### Response: def run(self, in_batches): """Run shell operator synchronously to eat `in_batches` :param in_batches: `tuple...
def _get_initial_rnn_and_grammar_state(self, question: Dict[str, torch.LongTensor], table: Dict[str, torch.LongTensor], world: List[WikiTablesWorld], ...
Encodes the question and table, computes a linking between the two, and constructs an initial RnnStatelet and LambdaGrammarStatelet for each batch instance to pass to the decoder. We take ``outputs`` as a parameter here and `modify` it, adding things that we want to visualize in a demo.
Below is the the instruction that describes the task: ### Input: Encodes the question and table, computes a linking between the two, and constructs an initial RnnStatelet and LambdaGrammarStatelet for each batch instance to pass to the decoder. We take ``outputs`` as a parameter here and `m...
def flush(self, file=str()): """ Flushes the updated file content to the given *file*. .. note:: Overwrites an existing file. :param str file: name and location of the file. Default is the original file. """ if file: Path(file).write_bytes(self._cache) ...
Flushes the updated file content to the given *file*. .. note:: Overwrites an existing file. :param str file: name and location of the file. Default is the original file.
Below is the the instruction that describes the task: ### Input: Flushes the updated file content to the given *file*. .. note:: Overwrites an existing file. :param str file: name and location of the file. Default is the original file. ### Response: def flush(self, file=str()): ...
def from_environ(cls, environ=os.environ): """Constructs a _PipelineContext from the task queue environment.""" base_path, unused = (environ['PATH_INFO'].rsplit('/', 1) + [''])[:2] return cls( environ['HTTP_X_APPENGINE_TASKNAME'], environ['HTTP_X_APPENGINE_QUEUENAME'], base_path)
Constructs a _PipelineContext from the task queue environment.
Below is the the instruction that describes the task: ### Input: Constructs a _PipelineContext from the task queue environment. ### Response: def from_environ(cls, environ=os.environ): """Constructs a _PipelineContext from the task queue environment.""" base_path, unused = (environ['PATH_INFO'].rsplit('/',...
def Input_setIgnoreInputEvents(self, ignore): """ Function path: Input.setIgnoreInputEvents Domain: Input Method name: setIgnoreInputEvents Parameters: Required arguments: 'ignore' (type: boolean) -> Ignores input events processing when set to true. No return value. Description: Ignore...
Function path: Input.setIgnoreInputEvents Domain: Input Method name: setIgnoreInputEvents Parameters: Required arguments: 'ignore' (type: boolean) -> Ignores input events processing when set to true. No return value. Description: Ignores input events (useful while auditing page).
Below is the the instruction that describes the task: ### Input: Function path: Input.setIgnoreInputEvents Domain: Input Method name: setIgnoreInputEvents Parameters: Required arguments: 'ignore' (type: boolean) -> Ignores input events processing when set to true. No return value. Desc...
def AdjustDescriptor(self, fields): """Payload-aware metadata processor.""" for f in fields: if f.name == "args_rdf_name": f.name = "payload_type" if f.name == "args": f.name = "payload" return fields
Payload-aware metadata processor.
Below is the the instruction that describes the task: ### Input: Payload-aware metadata processor. ### Response: def AdjustDescriptor(self, fields): """Payload-aware metadata processor.""" for f in fields: if f.name == "args_rdf_name": f.name = "payload_type" if f.name == "args": ...
def feature_parser(uni_feature, word_surface): # type: (text_type, text_type) -> Tuple[Tuple[text_type, text_type, text_type], text_type] """ Parse the POS feature output by Mecab :param uni_feature unicode: :return ( (pos1, pos2, pos3), word_stem ): """ list_feature_items = uni_feature.spli...
Parse the POS feature output by Mecab :param uni_feature unicode: :return ( (pos1, pos2, pos3), word_stem ):
Below is the the instruction that describes the task: ### Input: Parse the POS feature output by Mecab :param uni_feature unicode: :return ( (pos1, pos2, pos3), word_stem ): ### Response: def feature_parser(uni_feature, word_surface): # type: (text_type, text_type) -> Tuple[Tuple[text_type, text_type, ...
def dragEnterEvent(self, event): """Allow user to drag files""" if mimedata2url(event.mimeData()): event.accept() else: event.ignore()
Allow user to drag files
Below is the the instruction that describes the task: ### Input: Allow user to drag files ### Response: def dragEnterEvent(self, event): """Allow user to drag files""" if mimedata2url(event.mimeData()): event.accept() else: event.ignore()
def route(self, request, response): """Processes every request. Directs control flow to the appropriate HTTP/1.1 method. """ # Ensure that we're allowed to use this HTTP method. self.require_http_allowed_method(request) # Retrieve the function corresponding to this HTTP...
Processes every request. Directs control flow to the appropriate HTTP/1.1 method.
Below is the the instruction that describes the task: ### Input: Processes every request. Directs control flow to the appropriate HTTP/1.1 method. ### Response: def route(self, request, response): """Processes every request. Directs control flow to the appropriate HTTP/1.1 method. ...
def save(self): """Either create or persist changes on this object back to the One Codex server.""" check_bind(self) creating = self.id is None if creating and not self.__class__._has_schema_method("create"): raise MethodNotSupported("{} do not support creating.".format(self...
Either create or persist changes on this object back to the One Codex server.
Below is the the instruction that describes the task: ### Input: Either create or persist changes on this object back to the One Codex server. ### Response: def save(self): """Either create or persist changes on this object back to the One Codex server.""" check_bind(self) creating = self....
def _fix_namespace(self): """Internal helper to fix the namespace. This is called to ensure that for queries without an explicit namespace, the namespace used by async calls is the one in effect at the time the async call is made, not the one in effect when the the request is actually generated. ...
Internal helper to fix the namespace. This is called to ensure that for queries without an explicit namespace, the namespace used by async calls is the one in effect at the time the async call is made, not the one in effect when the the request is actually generated.
Below is the the instruction that describes the task: ### Input: Internal helper to fix the namespace. This is called to ensure that for queries without an explicit namespace, the namespace used by async calls is the one in effect at the time the async call is made, not the one in effect when the t...
def add_gateway_router(self, router, body=None): """Adds an external network gateway to the specified router.""" return self.put((self.router_path % router), body={'router': {'external_gateway_info': body}})
Adds an external network gateway to the specified router.
Below is the the instruction that describes the task: ### Input: Adds an external network gateway to the specified router. ### Response: def add_gateway_router(self, router, body=None): """Adds an external network gateway to the specified router.""" return self.put((self.router_path % router), ...
def _check_submodule_status(root, submodules): """check submodule status Has three return values: 'missing' - submodules are absent 'unclean' - submodules have unstaged changes 'clean' - all submodules are up to date """ if hasattr(sys, "frozen"): # frozen via py2exe or similar, don...
check submodule status Has three return values: 'missing' - submodules are absent 'unclean' - submodules have unstaged changes 'clean' - all submodules are up to date
Below is the the instruction that describes the task: ### Input: check submodule status Has three return values: 'missing' - submodules are absent 'unclean' - submodules have unstaged changes 'clean' - all submodules are up to date ### Response: def _check_submodule_status(root, submodules): ""...
def get_port_for_process(self, pid): """Allocates and returns port for pid or 0 if none could be allocated.""" if not self._port_queue: raise RuntimeError('No ports being managed.') # Avoid an infinite loop if all ports are currently assigned. check_count = 0 max_por...
Allocates and returns port for pid or 0 if none could be allocated.
Below is the the instruction that describes the task: ### Input: Allocates and returns port for pid or 0 if none could be allocated. ### Response: def get_port_for_process(self, pid): """Allocates and returns port for pid or 0 if none could be allocated.""" if not self._port_queue: rais...
def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options, files): """Uploads the base files (and if necessary, the current ones as well).""" def UploadFile(filename, file_id, content, is_binary, status, is_base): """Uploads a file to the server.""" set_status("uploading " + filen...
Uploads the base files (and if necessary, the current ones as well).
Below is the the instruction that describes the task: ### Input: Uploads the base files (and if necessary, the current ones as well). ### Response: def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options, files): """Uploads the base files (and if necessary, the current ones as well)...
def __entropy(data): '''Compute entropy of the flattened data set (e.g. a density distribution).''' # normalize and convert to float data = data/float(numpy.sum(data)) # for each grey-value g with a probability p(g) = 0, the entropy is defined as 0, therefore we remove these values and also flatten the ...
Compute entropy of the flattened data set (e.g. a density distribution).
Below is the the instruction that describes the task: ### Input: Compute entropy of the flattened data set (e.g. a density distribution). ### Response: def __entropy(data): '''Compute entropy of the flattened data set (e.g. a density distribution).''' # normalize and convert to float data = data/float(...
def sudo_remove_dirtree(dir_name): """Removes directory tree as a superuser. Args: dir_name: name of the directory to remove. This function is necessary to cleanup directories created from inside a Docker, since they usually written as a root, thus have to be removed as a root. """ try: subproce...
Removes directory tree as a superuser. Args: dir_name: name of the directory to remove. This function is necessary to cleanup directories created from inside a Docker, since they usually written as a root, thus have to be removed as a root.
Below is the the instruction that describes the task: ### Input: Removes directory tree as a superuser. Args: dir_name: name of the directory to remove. This function is necessary to cleanup directories created from inside a Docker, since they usually written as a root, thus have to be removed as a ro...
def valid_remainder(cntxt: Context, n: Node, matchables: RDFGraph, S: ShExJ.Shape) -> bool: """ Let **outs** be the arcsOut in remainder: `outs = remainder ∩ arcsOut(G, n)`. Let **matchables** be the triples in outs whose predicate appears in a TripleConstraint in `expression`. If `expression` is absen...
Let **outs** be the arcsOut in remainder: `outs = remainder ∩ arcsOut(G, n)`. Let **matchables** be the triples in outs whose predicate appears in a TripleConstraint in `expression`. If `expression` is absent, matchables = Ø (the empty set). * There is no triple in **matchables** which matches a TripleCon...
Below is the the instruction that describes the task: ### Input: Let **outs** be the arcsOut in remainder: `outs = remainder ∩ arcsOut(G, n)`. Let **matchables** be the triples in outs whose predicate appears in a TripleConstraint in `expression`. If `expression` is absent, matchables = Ø (the empty set). ...
def scanFolderForRegexp(folder = None, listRegexp = None, recursive = False, verbosity=1, logFolder= "./logs"): ''' [Optionally] recursive method to scan the files in a given folder. :param folder: the folder to be scanned. :param listRegexp: listRegexp is an array of <RegexpObject>. :param recursive: when T...
[Optionally] recursive method to scan the files in a given folder. :param folder: the folder to be scanned. :param listRegexp: listRegexp is an array of <RegexpObject>. :param recursive: when True, it performs a recursive search on the subfolders. :return: a list of the available objects containing the expre...
Below is the the instruction that describes the task: ### Input: [Optionally] recursive method to scan the files in a given folder. :param folder: the folder to be scanned. :param listRegexp: listRegexp is an array of <RegexpObject>. :param recursive: when True, it performs a recursive search on the subfolde...
def export_metadata(self, fields=None, forms=None, format='json', df_kwargs=None): """ Export the project's metadata Parameters ---------- fields : list Limit exported metadata to these fields forms : list Limit exported metadata to th...
Export the project's metadata Parameters ---------- fields : list Limit exported metadata to these fields forms : list Limit exported metadata to these forms format : (``'json'``), ``'csv'``, ``'xml'``, ``'df'`` Return the metadata in native o...
Below is the the instruction that describes the task: ### Input: Export the project's metadata Parameters ---------- fields : list Limit exported metadata to these fields forms : list Limit exported metadata to these forms format : (``'json'``), ``'cs...
def get_template_as_json(template_id, **kwargs): """ Get a template (including attribute and dataset definitions) as a JSON string. This is just a wrapper around the get_template_as_dict function. """ user_id = kwargs['user_id'] return json.dumps(get_template_as_dict(template_id, user_id...
Get a template (including attribute and dataset definitions) as a JSON string. This is just a wrapper around the get_template_as_dict function.
Below is the the instruction that describes the task: ### Input: Get a template (including attribute and dataset definitions) as a JSON string. This is just a wrapper around the get_template_as_dict function. ### Response: def get_template_as_json(template_id, **kwargs): """ Get a template (inc...
def getParser(): "Creates and returns the argparse parser object." # text epilog =""" examples: %(prog)s -e example.nii grid.nii 10 Generates an empty image with the same attributes as example.nii, overlays it with a regular grid of width 10 voxels and saves it as grid.nii. %(prog)s -e examp...
Creates and returns the argparse parser object.
Below is the the instruction that describes the task: ### Input: Creates and returns the argparse parser object. ### Response: def getParser(): "Creates and returns the argparse parser object." # text epilog =""" examples: %(prog)s -e example.nii grid.nii 10 Generates an empty image with the sa...
def get_recurring_bill_by_subscription(self, subscription_id): """ Consulta de las facturas que están pagadas o pendientes por pagar. Se puede consultar por cliente, por suscripción o por rango de fechas. Args: subscription_id: Returns: """ params =...
Consulta de las facturas que están pagadas o pendientes por pagar. Se puede consultar por cliente, por suscripción o por rango de fechas. Args: subscription_id: Returns:
Below is the the instruction that describes the task: ### Input: Consulta de las facturas que están pagadas o pendientes por pagar. Se puede consultar por cliente, por suscripción o por rango de fechas. Args: subscription_id: Returns: ### Response: def get_recurring_bill_by_su...
def _from_dict(cls, _dict): """Initialize a AlignedElement object from a json dictionary.""" args = {} if 'element_pair' in _dict: args['element_pair'] = [ ElementPair._from_dict(x) for x in (_dict.get('element_pair')) ] if 'identical_text' in _dic...
Initialize a AlignedElement object from a json dictionary.
Below is the the instruction that describes the task: ### Input: Initialize a AlignedElement object from a json dictionary. ### Response: def _from_dict(cls, _dict): """Initialize a AlignedElement object from a json dictionary.""" args = {} if 'element_pair' in _dict: args['elem...
def grouped_mappings(self,id): """ return all mappings for a node, grouped by ID prefix """ g = self.get_xref_graph() m = {} for n in g.neighbors(id): [prefix, local] = n.split(':') if prefix not in m: m[prefix] = [] m[p...
return all mappings for a node, grouped by ID prefix
Below is the the instruction that describes the task: ### Input: return all mappings for a node, grouped by ID prefix ### Response: def grouped_mappings(self,id): """ return all mappings for a node, grouped by ID prefix """ g = self.get_xref_graph() m = {} for n in g...
def safe_service(attr, default_value=None): '''A **method** decorator for creating safe services. Given an attribute name, this returns a decorator for creating safe services. Namely, if a service that is not yet available is requested (like a database connection), then ``safe_service`` will log an...
A **method** decorator for creating safe services. Given an attribute name, this returns a decorator for creating safe services. Namely, if a service that is not yet available is requested (like a database connection), then ``safe_service`` will log any errors and set the given attribute to ``default_v...
Below is the the instruction that describes the task: ### Input: A **method** decorator for creating safe services. Given an attribute name, this returns a decorator for creating safe services. Namely, if a service that is not yet available is requested (like a database connection), then ``safe_service...
def serializeType(self, hdlType: HdlType) -> str: """ :see: doc of method on parent class """ def createTmpVar(suggestedName, dtype): raise NotImplementedError( "Can not seraialize hdl type %r into" "ipcore format" % (hdlType)) return...
:see: doc of method on parent class
Below is the the instruction that describes the task: ### Input: :see: doc of method on parent class ### Response: def serializeType(self, hdlType: HdlType) -> str: """ :see: doc of method on parent class """ def createTmpVar(suggestedName, dtype): raise NotImplementedE...
def transformToNative(self): """ Transform this object into a custom VBase subclass. transformToNative should always return a representation of this object. It may do so by modifying self in place then returning self, or by creating a new object. """ if self.isN...
Transform this object into a custom VBase subclass. transformToNative should always return a representation of this object. It may do so by modifying self in place then returning self, or by creating a new object.
Below is the the instruction that describes the task: ### Input: Transform this object into a custom VBase subclass. transformToNative should always return a representation of this object. It may do so by modifying self in place then returning self, or by creating a new object. ### Response...
def postcmd(self, stop, line): ''' Exit cmd cleanly. ''' self.color_prompt() return Cmd.postcmd(self, stop, line)
Exit cmd cleanly.
Below is the the instruction that describes the task: ### Input: Exit cmd cleanly. ### Response: def postcmd(self, stop, line): ''' Exit cmd cleanly. ''' self.color_prompt() return Cmd.postcmd(self, stop, line)
def get_param_list_for_prediction(model_obj, replicates): """ Create the `param_list` argument for use with `model_obj.predict`. Parameters ---------- model_obj : an instance of an MNDC object. Should have the following attributes: `['ind_var_names', 'intercept_names', 'shape_names'...
Create the `param_list` argument for use with `model_obj.predict`. Parameters ---------- model_obj : an instance of an MNDC object. Should have the following attributes: `['ind_var_names', 'intercept_names', 'shape_names', 'nest_names']`. This model should have already undergone a c...
Below is the the instruction that describes the task: ### Input: Create the `param_list` argument for use with `model_obj.predict`. Parameters ---------- model_obj : an instance of an MNDC object. Should have the following attributes: `['ind_var_names', 'intercept_names', 'shape_names',...
def add_edge(self, name1, name2, **attr): ''' API: add_edge(self, name1, name2, **attr) Description: Adds edge to the graph. Sets edge attributes using attr argument. Input: name1: Name of the source node (if directed). name2: Name of the sink node (if dir...
API: add_edge(self, name1, name2, **attr) Description: Adds edge to the graph. Sets edge attributes using attr argument. Input: name1: Name of the source node (if directed). name2: Name of the sink node (if directed). attr: Edge attributes. Pre: ...
Below is the the instruction that describes the task: ### Input: API: add_edge(self, name1, name2, **attr) Description: Adds edge to the graph. Sets edge attributes using attr argument. Input: name1: Name of the source node (if directed). name2: Name of the sink node ...
def send_music(self, user_id, url, hq_url, thumb_media_id, title=None, description=None, account=None): """ 发送音乐消息 详情请参考 http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param url:...
发送音乐消息 详情请参考 http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param url: 音乐链接 :param hq_url: 高品质音乐链接,wifi环境优先使用该链接播放音乐 :param thumb_media_id: 缩略图的媒体ID。 可以通过 :func:`upload_media` 上传。 :param ti...
Below is the the instruction that describes the task: ### Input: 发送音乐消息 详情请参考 http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param url: 音乐链接 :param hq_url: 高品质音乐链接,wifi环境优先使用该链接播放音乐 :param thum...
def delete_simple_httpauth_read_api( request, database_name, collection_name, slug): """Delete Simple PublicReadAPI""" ss = get_object_or_404(HTTPAuthReadAPI, database_name=database_name, collection_name=collection_name, slug=slug) ss.delete() m...
Delete Simple PublicReadAPI
Below is the the instruction that describes the task: ### Input: Delete Simple PublicReadAPI ### Response: def delete_simple_httpauth_read_api( request, database_name, collection_name, slug): """Delete Simple PublicReadAPI""" ss = get_object_or_404(HTTPAuthReadAPI, database_...
def config_shortcut(action, context, name, parent): """ Create a Shortcut namedtuple for a widget The data contained in this tuple will be registered in our shortcuts preferences page """ keystr = get_shortcut(context, name) qsc = QShortcut(QKeySequence(keystr), parent, action) qsc....
Create a Shortcut namedtuple for a widget The data contained in this tuple will be registered in our shortcuts preferences page
Below is the the instruction that describes the task: ### Input: Create a Shortcut namedtuple for a widget The data contained in this tuple will be registered in our shortcuts preferences page ### Response: def config_shortcut(action, context, name, parent): """ Create a Shortcut namedtuple fo...
def disable_all_breakpoints(self): """ Disables all breakpoints in all processes. @see: disable_code_breakpoint, disable_page_breakpoint, disable_hardware_breakpoint """ # disable code breakpoints for (pid, bp) in self.get_all_code_br...
Disables all breakpoints in all processes. @see: disable_code_breakpoint, disable_page_breakpoint, disable_hardware_breakpoint
Below is the the instruction that describes the task: ### Input: Disables all breakpoints in all processes. @see: disable_code_breakpoint, disable_page_breakpoint, disable_hardware_breakpoint ### Response: def disable_all_breakpoints(self): """ Disables ...
def insert_system_path(opts, paths): ''' Inserts path into python path taking into consideration 'root_dir' option. ''' if isinstance(paths, six.string_types): paths = [paths] for path in paths: path_options = {'path': path, 'root_dir': opts['root_dir']} prepend_root_dir(path...
Inserts path into python path taking into consideration 'root_dir' option.
Below is the the instruction that describes the task: ### Input: Inserts path into python path taking into consideration 'root_dir' option. ### Response: def insert_system_path(opts, paths): ''' Inserts path into python path taking into consideration 'root_dir' option. ''' if isinstance(paths, six....
def khatri_rao(matrices): """Khatri-Rao product of a list of matrices. Parameters ---------- matrices : list of ndarray Returns ------- khatri_rao_product: matrix of shape ``(prod(n_i), m)`` where ``prod(n_i) = prod([m.shape[0] for m in matrices])`` i.e. the product of the ...
Khatri-Rao product of a list of matrices. Parameters ---------- matrices : list of ndarray Returns ------- khatri_rao_product: matrix of shape ``(prod(n_i), m)`` where ``prod(n_i) = prod([m.shape[0] for m in matrices])`` i.e. the product of the number of rows of all the matrice...
Below is the the instruction that describes the task: ### Input: Khatri-Rao product of a list of matrices. Parameters ---------- matrices : list of ndarray Returns ------- khatri_rao_product: matrix of shape ``(prod(n_i), m)`` where ``prod(n_i) = prod([m.shape[0] for m in matrices]...
def remnant_mass(eta, ns_g_mass, ns_sequence, chi, incl, shift): """ Function that determines the remnant disk mass of an NS-BH system using the fit to numerical-relativity results discussed in Foucart PRD 86, 124007 (2012). Parameters ----------- eta: float the symmetric mass ratio...
Function that determines the remnant disk mass of an NS-BH system using the fit to numerical-relativity results discussed in Foucart PRD 86, 124007 (2012). Parameters ----------- eta: float the symmetric mass ratio of the binary ns_g_mass: float NS gravitational mass (in solar m...
Below is the the instruction that describes the task: ### Input: Function that determines the remnant disk mass of an NS-BH system using the fit to numerical-relativity results discussed in Foucart PRD 86, 124007 (2012). Parameters ----------- eta: float the symmetric mass ratio of the ...
def get_qset(self, queryset, q): """Performs filtering against the default queryset returned by mongoengine. """ if self.mongoadmin.search_fields and q: params = {} for field in self.mongoadmin.search_fields: if field == 'id': ...
Performs filtering against the default queryset returned by mongoengine.
Below is the the instruction that describes the task: ### Input: Performs filtering against the default queryset returned by mongoengine. ### Response: def get_qset(self, queryset, q): """Performs filtering against the default queryset returned by mongoengine. """ if...
def execute_api_request(self): """ Execute the request and return json data as a dict :return: data dict """ if not self.auth.check_auth(): raise Exception('Authentification needed or API not available with your type of connection') if self.auth.is_authentifie...
Execute the request and return json data as a dict :return: data dict
Below is the the instruction that describes the task: ### Input: Execute the request and return json data as a dict :return: data dict ### Response: def execute_api_request(self): """ Execute the request and return json data as a dict :return: data dict """ if not se...
def save_token(self): """ Saves the token dict in the store :return bool: Success / Failure """ if self.token is None: raise ValueError('You have to set the "token" first.') try: # set token will overwrite previous data self.doc_ref.se...
Saves the token dict in the store :return bool: Success / Failure
Below is the the instruction that describes the task: ### Input: Saves the token dict in the store :return bool: Success / Failure ### Response: def save_token(self): """ Saves the token dict in the store :return bool: Success / Failure """ if self.token is None: ...
def pathconf(path, os_name=os.name, isdir_fnc=os.path.isdir, pathconf_fnc=getattr(os, 'pathconf', None), pathconf_names=getattr(os, 'pathconf_names', ())): ''' Get all pathconf variables for given path. :param path: absolute fs path :type path: str ...
Get all pathconf variables for given path. :param path: absolute fs path :type path: str :returns: dictionary containing pathconf keys and their values (both str) :rtype: dict
Below is the the instruction that describes the task: ### Input: Get all pathconf variables for given path. :param path: absolute fs path :type path: str :returns: dictionary containing pathconf keys and their values (both str) :rtype: dict ### Response: def pathconf(path, os_name=os....
def closed(self, error=None): """ Notify the application that the connection has been closed. :param error: The exception which has caused the connection to be closed. If the connection has been closed due to an EOF, pass ``None``. """ ...
Notify the application that the connection has been closed. :param error: The exception which has caused the connection to be closed. If the connection has been closed due to an EOF, pass ``None``.
Below is the the instruction that describes the task: ### Input: Notify the application that the connection has been closed. :param error: The exception which has caused the connection to be closed. If the connection has been closed due to an EOF, pass ``None``....
def is_configured(self, project, **kwargs): """ Check if plugin is configured. """ params = self.get_option return bool(params('server_host', project) and params('server_port', project))
Check if plugin is configured.
Below is the the instruction that describes the task: ### Input: Check if plugin is configured. ### Response: def is_configured(self, project, **kwargs): """ Check if plugin is configured. """ params = self.get_option return bool(params('server_host', project) and params('se...
def register(self, name, func): """ Register a new callback.\ When the name/id is not found\ a new hook is created under its name,\ meaning the hook is usually created by\ the first registered callback :param str name: Hook name :param callable func: A fu...
Register a new callback.\ When the name/id is not found\ a new hook is created under its name,\ meaning the hook is usually created by\ the first registered callback :param str name: Hook name :param callable func: A func reference (callback)
Below is the the instruction that describes the task: ### Input: Register a new callback.\ When the name/id is not found\ a new hook is created under its name,\ meaning the hook is usually created by\ the first registered callback :param str name: Hook name :param ca...
def stringify_summary(summary): """ stringify summary, in order to dump json file and generate html report. """ for index, suite_summary in enumerate(summary["details"]): if not suite_summary.get("name"): suite_summary["name"] = "testcase {}".format(index) for record in suite_s...
stringify summary, in order to dump json file and generate html report.
Below is the the instruction that describes the task: ### Input: stringify summary, in order to dump json file and generate html report. ### Response: def stringify_summary(summary): """ stringify summary, in order to dump json file and generate html report. """ for index, suite_summary in enumerate(su...
def gdalwarp(src, dst, options): """ a simple wrapper for :osgeo:func:`gdal.Warp` Parameters ---------- src: str, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset` the input data set dst: str the output data set options: dict additional parameters passed t...
a simple wrapper for :osgeo:func:`gdal.Warp` Parameters ---------- src: str, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset` the input data set dst: str the output data set options: dict additional parameters passed to gdal.Warp; see :osgeo:func:`gdal.WarpOption...
Below is the the instruction that describes the task: ### Input: a simple wrapper for :osgeo:func:`gdal.Warp` Parameters ---------- src: str, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset` the input data set dst: str the output data set options: dict additi...
def present(name, uid=None, gid=None, usergroup=None, groups=None, optional_groups=None, remove_groups=True, home=None, createhome=True, password=None, hash_password=False, enforce_passwor...
Ensure that the named user is present with the specified properties name The name of the user to manage uid The user id to assign. If not specified, and the user does not exist, then the next available uid will be assigned. gid The id of the default group to assign to the ...
Below is the the instruction that describes the task: ### Input: Ensure that the named user is present with the specified properties name The name of the user to manage uid The user id to assign. If not specified, and the user does not exist, then the next available uid will be ass...
def marshal(self, o, use_value_list=False): """ Packages the return from a parser for easy use in a rule. """ if o is None: return elif isinstance(o, dict): if use_value_list: for k, v in o.items(): o[k] = [v] ...
Packages the return from a parser for easy use in a rule.
Below is the the instruction that describes the task: ### Input: Packages the return from a parser for easy use in a rule. ### Response: def marshal(self, o, use_value_list=False): """ Packages the return from a parser for easy use in a rule. """ if o is None: return ...
def namedb_get_all_namespace_ids( cur ): """ Get a list of all READY namespace IDs. """ query = "SELECT namespace_id FROM namespaces WHERE op = ?;" args = (NAMESPACE_READY,) namespace_rows = namedb_query_execute( cur, query, args ) ret = [] for namespace_row in namespace_rows: ...
Get a list of all READY namespace IDs.
Below is the the instruction that describes the task: ### Input: Get a list of all READY namespace IDs. ### Response: def namedb_get_all_namespace_ids( cur ): """ Get a list of all READY namespace IDs. """ query = "SELECT namespace_id FROM namespaces WHERE op = ?;" args = (NAMESPACE_READY,) ...
def glob(cls, files=None): ''' Glob a pattern or a list of pattern static storage relative(s). ''' files = files or [] if isinstance(files, str): files = os.path.normpath(files) matches = lambda path: matches_patterns(path, [files]) return [pat...
Glob a pattern or a list of pattern static storage relative(s).
Below is the the instruction that describes the task: ### Input: Glob a pattern or a list of pattern static storage relative(s). ### Response: def glob(cls, files=None): ''' Glob a pattern or a list of pattern static storage relative(s). ''' files = files or [] if isinstance...
def _get_compressed_vlan_list(self, pvlan_ids): """Generate a compressed vlan list ready for XML using a vlan set. Sample Use Case: Input vlan set: -------------- 1 - s = set([11, 50, 25, 30, 15, 16, 3, 8, 2, 1]) 2 - s = set([87, 11, 50, 25, 30, 15, 16, 3, 8, 2, 1, 88])...
Generate a compressed vlan list ready for XML using a vlan set. Sample Use Case: Input vlan set: -------------- 1 - s = set([11, 50, 25, 30, 15, 16, 3, 8, 2, 1]) 2 - s = set([87, 11, 50, 25, 30, 15, 16, 3, 8, 2, 1, 88]) Returned compressed XML list: -----------...
Below is the the instruction that describes the task: ### Input: Generate a compressed vlan list ready for XML using a vlan set. Sample Use Case: Input vlan set: -------------- 1 - s = set([11, 50, 25, 30, 15, 16, 3, 8, 2, 1]) 2 - s = set([87, 11, 50, 25, 30, 15, 16, 3, 8, ...
def convert_node_labels_to_integers(G, first_label=0, ordering="default", label_attribute=None): """Return a copy of the graph G with the nodes relabeled with integers. Parameters ---------- G : graph A NetworkX graph first_label : int, optional (default=...
Return a copy of the graph G with the nodes relabeled with integers. Parameters ---------- G : graph A NetworkX graph first_label : int, optional (default=0) An integer specifying the offset in numbering nodes. The n new integer labels are numbered first_label, ..., n-1+first_labe...
Below is the the instruction that describes the task: ### Input: Return a copy of the graph G with the nodes relabeled with integers. Parameters ---------- G : graph A NetworkX graph first_label : int, optional (default=0) An integer specifying the offset in numbering nodes. T...
def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> ''' cmd = '/usr/sbin/svcadm enable {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False)
Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name>
Below is the the instruction that describes the task: ### Input: Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> ### Response: def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: ...
def remove_quotes(self, value): """ Remove any surrounding quotes from a value and unescape any contained quotes of that type. """ # beware the empty string if not value: return value if value[0] == value[-1] == '"': return value[1:-1].rep...
Remove any surrounding quotes from a value and unescape any contained quotes of that type.
Below is the the instruction that describes the task: ### Input: Remove any surrounding quotes from a value and unescape any contained quotes of that type. ### Response: def remove_quotes(self, value): """ Remove any surrounding quotes from a value and unescape any contained quotes ...
def collect_metrics(): """ Register the decorated function to run for the collect_metrics hook. """ def _register(action): handler = Handler.get(action) handler.add_predicate(partial(_restricted_hook, 'collect-metrics')) return action return _register
Register the decorated function to run for the collect_metrics hook.
Below is the the instruction that describes the task: ### Input: Register the decorated function to run for the collect_metrics hook. ### Response: def collect_metrics(): """ Register the decorated function to run for the collect_metrics hook. """ def _register(action): handler = Handler.ge...
def from_passwd(uid_min=None, uid_max=None): """Create collection from locally discovered data, e.g. /etc/passwd.""" import pwd users = Users(oktypes=User) passwd_list = pwd.getpwall() if not uid_min: uid_min = UID_MIN if not uid_max: uid_max = UID...
Create collection from locally discovered data, e.g. /etc/passwd.
Below is the the instruction that describes the task: ### Input: Create collection from locally discovered data, e.g. /etc/passwd. ### Response: def from_passwd(uid_min=None, uid_max=None): """Create collection from locally discovered data, e.g. /etc/passwd.""" import pwd users = Users(okty...
def add_file(self, filename): """ Read and adds given file's content to data array that will be used to generate output :param filename File name to add :type str or unicode """ with (open(filename, 'rb')) as f: data = f.read() # below won't handle th...
Read and adds given file's content to data array that will be used to generate output :param filename File name to add :type str or unicode
Below is the the instruction that describes the task: ### Input: Read and adds given file's content to data array that will be used to generate output :param filename File name to add :type str or unicode ### Response: def add_file(self, filename): """ Read and adds given file's co...
def run_setup(setup_script, args): """Run a distutils setup script, sandboxed in its directory""" setup_dir = os.path.abspath(os.path.dirname(setup_script)) with setup_context(setup_dir): try: sys.argv[:] = [setup_script]+list(args) sys.path.insert(0, setup_dir) #...
Run a distutils setup script, sandboxed in its directory
Below is the the instruction that describes the task: ### Input: Run a distutils setup script, sandboxed in its directory ### Response: def run_setup(setup_script, args): """Run a distutils setup script, sandboxed in its directory""" setup_dir = os.path.abspath(os.path.dirname(setup_script)) with setup...
def build_from_path(package, path, dry_run=False, env='default', outfilename=DEFAULT_BUILDFILE): """ Compile a Quilt data package from a build file. Path can be a directory, in which case the build file will be generated automatically. """ team, owner, pkg, subpath = parse_package(package, allow_sub...
Compile a Quilt data package from a build file. Path can be a directory, in which case the build file will be generated automatically.
Below is the the instruction that describes the task: ### Input: Compile a Quilt data package from a build file. Path can be a directory, in which case the build file will be generated automatically. ### Response: def build_from_path(package, path, dry_run=False, env='default', outfilename=DEFAULT_BUILDFILE): ...
def update(self, y, exogenous=None, maxiter=None, **kwargs): """Update an ARIMA or auto-ARIMA as well as any necessary transformers Passes the newly observed values through the appropriate endog transformations, and the exogenous array through the exog transformers (updating where neces...
Update an ARIMA or auto-ARIMA as well as any necessary transformers Passes the newly observed values through the appropriate endog transformations, and the exogenous array through the exog transformers (updating where necessary) before finally updating the ARIMA model. Parameters ...
Below is the the instruction that describes the task: ### Input: Update an ARIMA or auto-ARIMA as well as any necessary transformers Passes the newly observed values through the appropriate endog transformations, and the exogenous array through the exog transformers (updating where necessar...
def iter(self, start=0, count=1000): """ @start: #int cursor start position @stop: #int cursor stop position @count: #int buffer limit -> yields all of the items in the list """ cursor = '0' _loads = self._loads stop = start + count wh...
@start: #int cursor start position @stop: #int cursor stop position @count: #int buffer limit -> yields all of the items in the list
Below is the the instruction that describes the task: ### Input: @start: #int cursor start position @stop: #int cursor stop position @count: #int buffer limit -> yields all of the items in the list ### Response: def iter(self, start=0, count=1000): """ @start: #int curs...
def get_domains(self): """ Retrieves the domains of the users from elastic. """ search = User.search() search.aggs.bucket('domains', 'terms', field='domain', order={'_count': 'desc'}, size=100) response = search.execute() return [entry.key for entry in respons...
Retrieves the domains of the users from elastic.
Below is the the instruction that describes the task: ### Input: Retrieves the domains of the users from elastic. ### Response: def get_domains(self): """ Retrieves the domains of the users from elastic. """ search = User.search() search.aggs.bucket('domains', 'terms', f...
def from_shapely(geometry, label=None): """ Create a MultiPolygon from a Shapely MultiPolygon, a Shapely Polygon or a Shapely GeometryCollection. This also creates all necessary Polygons contained by this MultiPolygon. Parameters ---------- geometry : shapely.geometry.M...
Create a MultiPolygon from a Shapely MultiPolygon, a Shapely Polygon or a Shapely GeometryCollection. This also creates all necessary Polygons contained by this MultiPolygon. Parameters ---------- geometry : shapely.geometry.MultiPolygon or shapely.geometry.Polygon\ ...
Below is the the instruction that describes the task: ### Input: Create a MultiPolygon from a Shapely MultiPolygon, a Shapely Polygon or a Shapely GeometryCollection. This also creates all necessary Polygons contained by this MultiPolygon. Parameters ---------- geometry : shapely.g...
def search_user(current): """ Search users for adding to a public room or creating one to one direct messaging .. code-block:: python # request: { 'view':'_zops_search_user', 'query': string, } # res...
Search users for adding to a public room or creating one to one direct messaging .. code-block:: python # request: { 'view':'_zops_search_user', 'query': string, } # response: { '...
Below is the the instruction that describes the task: ### Input: Search users for adding to a public room or creating one to one direct messaging .. code-block:: python # request: { 'view':'_zops_search_user', 'query': string, ...
def basicauth(self, realm = b'all', nofail = False): "Try to get the basic authorize info, return (username, password) if succeeded, return 401 otherwise" if b'authorization' in self.headerdict: auth = self.headerdict[b'authorization'] auth_pair = auth.split(b' ', 1) ...
Try to get the basic authorize info, return (username, password) if succeeded, return 401 otherwise
Below is the the instruction that describes the task: ### Input: Try to get the basic authorize info, return (username, password) if succeeded, return 401 otherwise ### Response: def basicauth(self, realm = b'all', nofail = False): "Try to get the basic authorize info, return (username, password) if succee...
def loadings(self): """Loadings = eigenvectors times sqrt(eigenvalues).""" loadings = self.v[:, : self.keep] * np.sqrt(self.eigenvalues) cols = ["PC%s" % i for i in range(1, self.keep + 1)] loadings = pd.DataFrame( loadings, columns=cols, index=self.feature_names ...
Loadings = eigenvectors times sqrt(eigenvalues).
Below is the the instruction that describes the task: ### Input: Loadings = eigenvectors times sqrt(eigenvalues). ### Response: def loadings(self): """Loadings = eigenvectors times sqrt(eigenvalues).""" loadings = self.v[:, : self.keep] * np.sqrt(self.eigenvalues) cols = ["PC%s" % i for ...
def conductorcmd_push(engine_name, project_name, services, **kwargs): """ Push images to a registry """ username = kwargs.pop('username') password = kwargs.pop('password') email = kwargs.pop('email') url = kwargs.pop('url') namespace = kwargs.pop('namespace') tag = kwargs.pop('tag') conf...
Push images to a registry
Below is the the instruction that describes the task: ### Input: Push images to a registry ### Response: def conductorcmd_push(engine_name, project_name, services, **kwargs): """ Push images to a registry """ username = kwargs.pop('username') password = kwargs.pop('password') email = kwargs.pop('em...
def crc32(self, data): """ Calculate a ZIP 32-bit CRC from data in memory. Origin code by Johann E. Klasek, j AT klasek at """ data_address = 0x1000 # position of the test data self.cpu.memory.load(data_address, data) # write test data into RAM self.cpu.index_x.s...
Calculate a ZIP 32-bit CRC from data in memory. Origin code by Johann E. Klasek, j AT klasek at
Below is the the instruction that describes the task: ### Input: Calculate a ZIP 32-bit CRC from data in memory. Origin code by Johann E. Klasek, j AT klasek at ### Response: def crc32(self, data): """ Calculate a ZIP 32-bit CRC from data in memory. Origin code by Johann E. Klasek, ...
def digest(self): """Terminate the message-digest computation and return digest. Return the digest of the strings passed to the update() method so far. This is a 16-byte string which may contain non-ASCII characters, including null bytes. """ H0 = self.H0 H1 = s...
Terminate the message-digest computation and return digest. Return the digest of the strings passed to the update() method so far. This is a 16-byte string which may contain non-ASCII characters, including null bytes.
Below is the the instruction that describes the task: ### Input: Terminate the message-digest computation and return digest. Return the digest of the strings passed to the update() method so far. This is a 16-byte string which may contain non-ASCII characters, including null bytes. ### Resp...
def check_if_exiftool_is_already_installed(): """Requirements This function will check if Exiftool is installed on your system Return: True if Exiftool is Installed False if not """ result = 1; command = ["exiftool", "-ver"] with open(os.devnull, "w") as fnull: res...
Requirements This function will check if Exiftool is installed on your system Return: True if Exiftool is Installed False if not
Below is the the instruction that describes the task: ### Input: Requirements This function will check if Exiftool is installed on your system Return: True if Exiftool is Installed False if not ### Response: def check_if_exiftool_is_already_installed(): """Requirements This funct...
def similarity(self, other): """Calculate similarity based on best matching permutation of items.""" # Select the longer list as the basis for comparison if len(self.items) > len(other.items): first, second = self, other else: first, second = other, self i...
Calculate similarity based on best matching permutation of items.
Below is the the instruction that describes the task: ### Input: Calculate similarity based on best matching permutation of items. ### Response: def similarity(self, other): """Calculate similarity based on best matching permutation of items.""" # Select the longer list as the basis for comparison ...
def _readline_insert(self, char, echo, insptr, line): """Deal properly with inserted chars in a line.""" if not self._readline_do_echo(echo): return # Write out the remainder of the line self.write(char + ''.join(line[insptr:])) # Cursor Left to the current insert poi...
Deal properly with inserted chars in a line.
Below is the the instruction that describes the task: ### Input: Deal properly with inserted chars in a line. ### Response: def _readline_insert(self, char, echo, insptr, line): """Deal properly with inserted chars in a line.""" if not self._readline_do_echo(echo): return # Writ...
def urlparams(url_, hash=None, **query): """Add a fragment and/or query paramaters to a URL. New query params will be appended to exising parameters, except duplicate names, which will be replaced. """ url = urlparse.urlparse(url_) fragment = hash if hash is not None else url.fragment # Us...
Add a fragment and/or query paramaters to a URL. New query params will be appended to exising parameters, except duplicate names, which will be replaced.
Below is the the instruction that describes the task: ### Input: Add a fragment and/or query paramaters to a URL. New query params will be appended to exising parameters, except duplicate names, which will be replaced. ### Response: def urlparams(url_, hash=None, **query): """Add a fragment and/or que...
def _send(self, message): """ Private method for send one message. :param SmsMessage message: SmsMessage class instance. :returns: True if message is sended else False :rtype: bool """ params = { 'V': SMSPUBLI_API_VERSION, 'UN': SMSPUBLI...
Private method for send one message. :param SmsMessage message: SmsMessage class instance. :returns: True if message is sended else False :rtype: bool
Below is the the instruction that describes the task: ### Input: Private method for send one message. :param SmsMessage message: SmsMessage class instance. :returns: True if message is sended else False :rtype: bool ### Response: def _send(self, message): """ Private method...
def run_and_exit(command_class): '''A shortcut for reading from sys.argv and exiting the interpreter''' cmd = command_class(sys.argv[1:]) if cmd.error: print('error: {0}'.format(cmd.error)) sys.exit(1) else: sys.exit(cmd.run())
A shortcut for reading from sys.argv and exiting the interpreter
Below is the the instruction that describes the task: ### Input: A shortcut for reading from sys.argv and exiting the interpreter ### Response: def run_and_exit(command_class): '''A shortcut for reading from sys.argv and exiting the interpreter''' cmd = command_class(sys.argv[1:]) if cmd.error: ...
def read(self, address, size, force=False): """ Read a stream of potentially symbolic bytes from a potentially symbolic address :param address: Where to read from :param size: How many bytes :param force: Whether to ignore permissions :rtype: list """ ...
Read a stream of potentially symbolic bytes from a potentially symbolic address :param address: Where to read from :param size: How many bytes :param force: Whether to ignore permissions :rtype: list
Below is the the instruction that describes the task: ### Input: Read a stream of potentially symbolic bytes from a potentially symbolic address :param address: Where to read from :param size: How many bytes :param force: Whether to ignore permissions :rtype: list ### Respon...
def get_parameters_off_value(self): """ Return the string associated to the parameters_off :rtype: string """ if self.parameters_off_value == None: params = self.CM.get_type_list(self.parameters_off) self.parameters_off_value = '({})'.format(' '.j...
Return the string associated to the parameters_off :rtype: string
Below is the the instruction that describes the task: ### Input: Return the string associated to the parameters_off :rtype: string ### Response: def get_parameters_off_value(self): """ Return the string associated to the parameters_off :rtype: string """ ...
def reduceByKey(self, func, numPartitions=None): """ Return a new DStream by applying reduceByKey to each RDD. """ if numPartitions is None: numPartitions = self._sc.defaultParallelism return self.combineByKey(lambda x: x, func, func, numPartitions)
Return a new DStream by applying reduceByKey to each RDD.
Below is the the instruction that describes the task: ### Input: Return a new DStream by applying reduceByKey to each RDD. ### Response: def reduceByKey(self, func, numPartitions=None): """ Return a new DStream by applying reduceByKey to each RDD. """ if numPartitions is None: ...
def escribir(dic, formato, contraer_fechas=False): "Genera una cadena dado un formato y un diccionario de claves/valores" linea = " " * sum([fmt[1] for fmt in formato]) comienzo = 1 for fmt in formato: clave, longitud, tipo = fmt[0:3] try: dec = (len(fmt)>3 and isinstance(fmt...
Genera una cadena dado un formato y un diccionario de claves/valores
Below is the the instruction that describes the task: ### Input: Genera una cadena dado un formato y un diccionario de claves/valores ### Response: def escribir(dic, formato, contraer_fechas=False): "Genera una cadena dado un formato y un diccionario de claves/valores" linea = " " * sum([fmt[1] for fmt in ...
def moments_XXXY(X, Y, remove_mean=False, symmetrize=False, weights=None, modify_data=False, sparse_mode='auto', sparse_tol=0.0, column_selection=None, diag_only=False): """ Computes the first two unnormalized moments of X and Y If symmetrize is False, computes .. math: ...
Computes the first two unnormalized moments of X and Y If symmetrize is False, computes .. math: s_x &=& \sum_t x_t s_y &=& \sum_t y_t C_XX &=& X^\top X C_XY &=& X^\top Y If symmetrize is True, computes .. math: s_x = s_y &=& \frac{1}{2} \sum_t(x_t + y_t) ...
Below is the the instruction that describes the task: ### Input: Computes the first two unnormalized moments of X and Y If symmetrize is False, computes .. math: s_x &=& \sum_t x_t s_y &=& \sum_t y_t C_XX &=& X^\top X C_XY &=& X^\top Y If symmetrize is True, computes...
def add_ignore(self, depend): """Adds dependencies to ignore.""" try: self._add_child(self.ignore, self.ignore_set, depend) except TypeError as e: e = e.args[0] if SCons.Util.is_List(e): s = list(map(str, e)) else: s...
Adds dependencies to ignore.
Below is the the instruction that describes the task: ### Input: Adds dependencies to ignore. ### Response: def add_ignore(self, depend): """Adds dependencies to ignore.""" try: self._add_child(self.ignore, self.ignore_set, depend) except TypeError as e: e = e.args[0...
def describe_api_key(apiKey, region=None, key=None, keyid=None, profile=None): ''' Gets info about the given api key CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_key apigw_api_key ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, p...
Gets info about the given api key CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_key apigw_api_key
Below is the the instruction that describes the task: ### Input: Gets info about the given api key CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_key apigw_api_key ### Response: def describe_api_key(apiKey, region=None, key=None, keyid=None, profile=None): ''' ...
def addLabel(self, start, end, labelName): """ Add the label labelName to each record with record ROWID in range from ``start`` to ``end``, noninclusive of end. This will recalculate all points from end to the last record stored in the internal cache of this classifier. :param start: (int) sta...
Add the label labelName to each record with record ROWID in range from ``start`` to ``end``, noninclusive of end. This will recalculate all points from end to the last record stored in the internal cache of this classifier. :param start: (int) start index :param end: (int) end index (noninclusive...
Below is the the instruction that describes the task: ### Input: Add the label labelName to each record with record ROWID in range from ``start`` to ``end``, noninclusive of end. This will recalculate all points from end to the last record stored in the internal cache of this classifier. :param st...
def announcement_approved_email(request, obj, req): """Email the requested teachers and submitter whenever an administrator approves an announcement request. obj: the Announcement object req: the AnnouncementRequest object """ if not settings.PRODUCTION: logger.debug("Not in productio...
Email the requested teachers and submitter whenever an administrator approves an announcement request. obj: the Announcement object req: the AnnouncementRequest object
Below is the the instruction that describes the task: ### Input: Email the requested teachers and submitter whenever an administrator approves an announcement request. obj: the Announcement object req: the AnnouncementRequest object ### Response: def announcement_approved_email(request, obj, req): ...
def from_array(array): """ Deserialize a new InlineQueryResultCachedAudio from a given dictionary. :return: new InlineQueryResultCachedAudio instance. :rtype: InlineQueryResultCachedAudio """ if array is None or not array: return None # end if ...
Deserialize a new InlineQueryResultCachedAudio from a given dictionary. :return: new InlineQueryResultCachedAudio instance. :rtype: InlineQueryResultCachedAudio
Below is the the instruction that describes the task: ### Input: Deserialize a new InlineQueryResultCachedAudio from a given dictionary. :return: new InlineQueryResultCachedAudio instance. :rtype: InlineQueryResultCachedAudio ### Response: def from_array(array): """ Deserialize a n...
def end_output (self, **kwargs): """Finish graph output, and print end of checking info as xml comment.""" self.xml_endtag(u"graph") self.xml_endtag(u"GraphXML") self.xml_end_output() self.close_fileoutput()
Finish graph output, and print end of checking info as xml comment.
Below is the the instruction that describes the task: ### Input: Finish graph output, and print end of checking info as xml comment. ### Response: def end_output (self, **kwargs): """Finish graph output, and print end of checking info as xml comment.""" self.xml_endtag(u"graph") ...
def get_size(conn, vm_): ''' Return the VM's size object ''' sizes = conn.list_sizes() vm_size = config.get_cloud_config_value('size', vm_, __opts__) if not vm_size: return sizes[0] for size in sizes: if vm_size and str(vm_size) in (str(size.id), str(size.name)): # pylint: ...
Return the VM's size object
Below is the the instruction that describes the task: ### Input: Return the VM's size object ### Response: def get_size(conn, vm_): ''' Return the VM's size object ''' sizes = conn.list_sizes() vm_size = config.get_cloud_config_value('size', vm_, __opts__) if not vm_size: return siz...