code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _restore_backup(self): """Restore the specified database.""" input_filename, input_file = self._get_backup_file(database=self.database_name, servername=self.servername) self.logger.info("Restoring backup for database '%s' and server ...
Restore the specified database.
Below is the the instruction that describes the task: ### Input: Restore the specified database. ### Response: def _restore_backup(self): """Restore the specified database.""" input_filename, input_file = self._get_backup_file(database=self.database_name, ...
def set_debug(self, status): """Control the logging state.""" if status: self.logger.setLevel('DEBUG') else: self.logger.setLevel('INFO')
Control the logging state.
Below is the the instruction that describes the task: ### Input: Control the logging state. ### Response: def set_debug(self, status): """Control the logging state.""" if status: self.logger.setLevel('DEBUG') else: self.logger.setLevel('INFO')
def osu_run1(data_set='osu_run1', sample_every=4): """Ohio State University's Run1 motion capture data set.""" path = os.path.join(data_path, data_set) if not data_available(data_set): import zipfile download_data(data_set) zip = zipfile.ZipFile(os.path.join(data_path, data_set, 'run...
Ohio State University's Run1 motion capture data set.
Below is the the instruction that describes the task: ### Input: Ohio State University's Run1 motion capture data set. ### Response: def osu_run1(data_set='osu_run1', sample_every=4): """Ohio State University's Run1 motion capture data set.""" path = os.path.join(data_path, data_set) if not data_availa...
def connection_from_url(url, **kw): """ Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must...
Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must include the scheme. Port is optional. :par...
Below is the the instruction that describes the task: ### Input: Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute...
def main( context: click.core.Context, method: str, request_type: str, id: Any, send: str ) -> None: """ Create a JSON-RPC request. """ exit_status = 0 # Extract the jsonrpc arguments positional = [a for a in context.args if "=" not in a] named = {a.split("=")[0]: a.split("=")[1] for a i...
Create a JSON-RPC request.
Below is the the instruction that describes the task: ### Input: Create a JSON-RPC request. ### Response: def main( context: click.core.Context, method: str, request_type: str, id: Any, send: str ) -> None: """ Create a JSON-RPC request. """ exit_status = 0 # Extract the jsonrpc arguments ...
def unpack(self, value): """Unpack the parameter using its kattype. Parameters ---------- packed_value : str The unescaped KATCP string to unpack. Returns ------- value : object The unpacked value. """ # Wrap errors in Fa...
Unpack the parameter using its kattype. Parameters ---------- packed_value : str The unescaped KATCP string to unpack. Returns ------- value : object The unpacked value.
Below is the the instruction that describes the task: ### Input: Unpack the parameter using its kattype. Parameters ---------- packed_value : str The unescaped KATCP string to unpack. Returns ------- value : object The unpacked value. ### Res...
def parse_py_tree(self, pytree): """Parse the given Python package tree. :param str pytree: The absolute path to the Python tree which is to be parsed. :rtype: dict :returns: A two-tuple. The first element is a dict where each key is the path of a parsed Python module (relat...
Parse the given Python package tree. :param str pytree: The absolute path to the Python tree which is to be parsed. :rtype: dict :returns: A two-tuple. The first element is a dict where each key is the path of a parsed Python module (relative to the Python tree) and its value is the...
Below is the the instruction that describes the task: ### Input: Parse the given Python package tree. :param str pytree: The absolute path to the Python tree which is to be parsed. :rtype: dict :returns: A two-tuple. The first element is a dict where each key is the path of a parsed ...
def histograms(self, analytes=None, bins=25, logy=False, filt=False, colourful=True): """ Plot histograms of analytes. Parameters ---------- analytes : optional, array_like or str The analyte(s) to plot. Defaults to all analytes. bins : int...
Plot histograms of analytes. Parameters ---------- analytes : optional, array_like or str The analyte(s) to plot. Defaults to all analytes. bins : int The number of bins in each histogram (default = 25) logy : bool If true, y axis is a log sca...
Below is the the instruction that describes the task: ### Input: Plot histograms of analytes. Parameters ---------- analytes : optional, array_like or str The analyte(s) to plot. Defaults to all analytes. bins : int The number of bins in each histogram (defau...
def register_function(scope=None, as_property=False, name=None): """Decorator to register a new function with vaex. Example: >>> import vaex >>> df = vaex.example() >>> @vaex.register_function() >>> def invert(x): >>> return 1/x >>> df.x.invert() >>> import numpy as np >>...
Decorator to register a new function with vaex. Example: >>> import vaex >>> df = vaex.example() >>> @vaex.register_function() >>> def invert(x): >>> return 1/x >>> df.x.invert() >>> import numpy as np >>> df = vaex.from_arrays(departure=np.arange('2015-01-01', '2015-12-05', ...
Below is the the instruction that describes the task: ### Input: Decorator to register a new function with vaex. Example: >>> import vaex >>> df = vaex.example() >>> @vaex.register_function() >>> def invert(x): >>> return 1/x >>> df.x.invert() >>> import numpy as np >>> d...
def check_cv(self, y): """Resolve which cross validation strategy is used.""" y_arr = None if self.stratified: # Try to convert y to numpy for sklearn's check_cv; if conversion # doesn't work, still try. try: y_arr = to_numpy(y) exc...
Resolve which cross validation strategy is used.
Below is the the instruction that describes the task: ### Input: Resolve which cross validation strategy is used. ### Response: def check_cv(self, y): """Resolve which cross validation strategy is used.""" y_arr = None if self.stratified: # Try to convert y to numpy for sklearn'...
def version(self, pretty=False, best=False): """ Return the version of the OS distribution, as a string. For details, see :func:`distro.version`. """ versions = [ self.os_release_attr('version_id'), self.lsb_release_attr('release'), self.distr...
Return the version of the OS distribution, as a string. For details, see :func:`distro.version`.
Below is the the instruction that describes the task: ### Input: Return the version of the OS distribution, as a string. For details, see :func:`distro.version`. ### Response: def version(self, pretty=False, best=False): """ Return the version of the OS distribution, as a string. ...
def _wave(self): """Return a wave.Wave_read instance from the ``wave`` module.""" try: return wave.open(StringIO(self.contents)) except wave.Error, err: err.message += "\nInvalid wave file: %s" % self err.args = (err.message,) raise
Return a wave.Wave_read instance from the ``wave`` module.
Below is the the instruction that describes the task: ### Input: Return a wave.Wave_read instance from the ``wave`` module. ### Response: def _wave(self): """Return a wave.Wave_read instance from the ``wave`` module.""" try: return wave.open(StringIO(self.contents)) except wave....
def align_yaxis_np(axes): """Align zeros of the two axes, zooming them out by same ratio""" axes = np.array(axes) extrema = np.array([ax.get_ylim() for ax in axes]) # reset for divide by zero issues for i in range(len(extrema)): if np.isclose(extrema[i, 0], 0.0): extrema[i, 0] =...
Align zeros of the two axes, zooming them out by same ratio
Below is the the instruction that describes the task: ### Input: Align zeros of the two axes, zooming them out by same ratio ### Response: def align_yaxis_np(axes): """Align zeros of the two axes, zooming them out by same ratio""" axes = np.array(axes) extrema = np.array([ax.get_ylim() for ax in axes])...
def from_aid(cls, aid): """Retrieve the Assay record for the specified AID. :param int aid: The PubChem Assay Identifier (AID). """ record = json.loads(request(aid, 'aid', 'assay', 'description').read().decode())['PC_AssayContainer'][0] return cls(record)
Retrieve the Assay record for the specified AID. :param int aid: The PubChem Assay Identifier (AID).
Below is the the instruction that describes the task: ### Input: Retrieve the Assay record for the specified AID. :param int aid: The PubChem Assay Identifier (AID). ### Response: def from_aid(cls, aid): """Retrieve the Assay record for the specified AID. :param int aid: The PubChem Assay...
def riseset(self, crd, ev="5deg"): """This will give the rise/set times of a source. It needs the position in the frame, and a time. If the latter is not set, the current time will be used. :param crd: a direction measure :param ev: the elevation limit as a quantity or string ...
This will give the rise/set times of a source. It needs the position in the frame, and a time. If the latter is not set, the current time will be used. :param crd: a direction measure :param ev: the elevation limit as a quantity or string :returns: The returned value is a `dict`...
Below is the the instruction that describes the task: ### Input: This will give the rise/set times of a source. It needs the position in the frame, and a time. If the latter is not set, the current time will be used. :param crd: a direction measure :param ev: the elevation limit as ...
def load_from_data(self, data, with_undefined=False): """Load index structure. :param with_undefined: Load undefined keys as well :type with_undefined: bool """ if with_undefined: defined_values, undefined_values = data else: defined_values = dat...
Load index structure. :param with_undefined: Load undefined keys as well :type with_undefined: bool
Below is the the instruction that describes the task: ### Input: Load index structure. :param with_undefined: Load undefined keys as well :type with_undefined: bool ### Response: def load_from_data(self, data, with_undefined=False): """Load index structure. :param with_undefined: ...
def _create_object(self, data, request): """ Create a python object from the given data. This will use ``self.factory`` object's ``create()`` function to create the data. If no factory is defined, this will simply return the same data that was given. """ if req...
Create a python object from the given data. This will use ``self.factory`` object's ``create()`` function to create the data. If no factory is defined, this will simply return the same data that was given.
Below is the the instruction that describes the task: ### Input: Create a python object from the given data. This will use ``self.factory`` object's ``create()`` function to create the data. If no factory is defined, this will simply return the same data that was given. ### Respons...
def opened(self, *args): """Initiates communication with the remote controlled device. :param args: """ self._serial_open = True self.log("Opened: ", args, lvl=debug) self._send_command(b'l,1') # Saying hello, shortly self.log("Turning off engine, pump and neut...
Initiates communication with the remote controlled device. :param args:
Below is the the instruction that describes the task: ### Input: Initiates communication with the remote controlled device. :param args: ### Response: def opened(self, *args): """Initiates communication with the remote controlled device. :param args: """ self._serial_open ...
def delete(self, uri, force=False, timeout=-1, custom_headers=None): """Deletes current resource. Args: force: Flag to delete the resource forcefully, default is False. timeout: Timeout in seconds. custom_headers: Allows to set custom http headers. """ ...
Deletes current resource. Args: force: Flag to delete the resource forcefully, default is False. timeout: Timeout in seconds. custom_headers: Allows to set custom http headers.
Below is the the instruction that describes the task: ### Input: Deletes current resource. Args: force: Flag to delete the resource forcefully, default is False. timeout: Timeout in seconds. custom_headers: Allows to set custom http headers. ### Response: def delete(sel...
async def stepper_config(self, steps_per_revolution, stepper_pins): """ Configure stepper motor prior to operation. This is a FirmataPlus feature. :param steps_per_revolution: number of steps per motor revolution :param stepper_pins: a list of control pin numbers - either 4 or ...
Configure stepper motor prior to operation. This is a FirmataPlus feature. :param steps_per_revolution: number of steps per motor revolution :param stepper_pins: a list of control pin numbers - either 4 or 2 :returns: No return value.
Below is the the instruction that describes the task: ### Input: Configure stepper motor prior to operation. This is a FirmataPlus feature. :param steps_per_revolution: number of steps per motor revolution :param stepper_pins: a list of control pin numbers - either 4 or 2 :returns...
def setCurrentIndex(self, index): """ Sets the current item to the item at the inputed index. :param index | <int> """ if self._currentIndex == index: return self._currentIndex = index self.currentIndexChanged.emit(index) for i, item in...
Sets the current item to the item at the inputed index. :param index | <int>
Below is the the instruction that describes the task: ### Input: Sets the current item to the item at the inputed index. :param index | <int> ### Response: def setCurrentIndex(self, index): """ Sets the current item to the item at the inputed index. :param index | <int> ...
def from_config(config, kwargs=None): """ Creates a solver from a specification dict. """ return util.get_object( obj=config, predefined=tensorforce.core.optimizers.solvers.solvers, kwargs=kwargs )
Creates a solver from a specification dict.
Below is the the instruction that describes the task: ### Input: Creates a solver from a specification dict. ### Response: def from_config(config, kwargs=None): """ Creates a solver from a specification dict. """ return util.get_object( obj=config, predefined...
def _set_pip_ssl(anaconda_dir): """Set PIP SSL certificate to installed conda certificate to avoid SSL errors """ if anaconda_dir: cert_file = os.path.join(anaconda_dir, "ssl", "cert.pem") if os.path.exists(cert_file): os.environ["PIP_CERT"] = cert_file
Set PIP SSL certificate to installed conda certificate to avoid SSL errors
Below is the the instruction that describes the task: ### Input: Set PIP SSL certificate to installed conda certificate to avoid SSL errors ### Response: def _set_pip_ssl(anaconda_dir): """Set PIP SSL certificate to installed conda certificate to avoid SSL errors """ if anaconda_dir: cert_file ...
def import_bill(data, standalone_votes, categorizer): """ insert or update a bill data - raw bill JSON standalone_votes - votes scraped separately categorizer - SubjectCategorizer (None - no categorization) """ abbr = data[settings.LEVEL_FIELD] # clean up bill_ids d...
insert or update a bill data - raw bill JSON standalone_votes - votes scraped separately categorizer - SubjectCategorizer (None - no categorization)
Below is the the instruction that describes the task: ### Input: insert or update a bill data - raw bill JSON standalone_votes - votes scraped separately categorizer - SubjectCategorizer (None - no categorization) ### Response: def import_bill(data, standalone_votes, categorizer): """ ...
def _clause(self, pt: parsing.ParserTree) -> [ast.stmt]: """Normalize a test expression into a statements list. Statements list are returned as-is. Expression is packaged as: if not expr: return False """ if isinstance(pt, list): return pt ...
Normalize a test expression into a statements list. Statements list are returned as-is. Expression is packaged as: if not expr: return False
Below is the the instruction that describes the task: ### Input: Normalize a test expression into a statements list. Statements list are returned as-is. Expression is packaged as: if not expr: return False ### Response: def _clause(self, pt: parsing.ParserTree) -> [ast.stmt]: ...
def _check_hash_view(self): """ Return infohash if view name refers to a single item, else None. """ infohash = None if self.viewname.startswith('#'): infohash = self.viewname[1:] elif len(self.viewname) == 40: try: int(self.viewname, 16) ...
Return infohash if view name refers to a single item, else None.
Below is the the instruction that describes the task: ### Input: Return infohash if view name refers to a single item, else None. ### Response: def _check_hash_view(self): """ Return infohash if view name refers to a single item, else None. """ infohash = None if self.viewname.start...
def executemany(self, query, args): """Run several data against one query PyMySQL can execute bulkinsert for query like 'INSERT ... VALUES (%s)'. In other form of queries, just run :meth:`execute` many times. """ if not args: return m = RE_INSERT_VALUES.matc...
Run several data against one query PyMySQL can execute bulkinsert for query like 'INSERT ... VALUES (%s)'. In other form of queries, just run :meth:`execute` many times.
Below is the the instruction that describes the task: ### Input: Run several data against one query PyMySQL can execute bulkinsert for query like 'INSERT ... VALUES (%s)'. In other form of queries, just run :meth:`execute` many times. ### Response: def executemany(self, query, args): """Ru...
def hurst_rs(data, nvals=None, fit="RANSAC", debug_plot=False, debug_data=False, plot_file=None, corrected=True, unbiased=True): """ Calculates the Hurst exponent by a standard rescaled range (R/S) approach. Explanation of Hurst exponent: The Hurst exponent is a measure for the "long-term memory...
Calculates the Hurst exponent by a standard rescaled range (R/S) approach. Explanation of Hurst exponent: The Hurst exponent is a measure for the "long-term memory" of a time series, meaning the long statistical dependencies in the data that do not originate from cycles. It originates from H.E. Hurs...
Below is the the instruction that describes the task: ### Input: Calculates the Hurst exponent by a standard rescaled range (R/S) approach. Explanation of Hurst exponent: The Hurst exponent is a measure for the "long-term memory" of a time series, meaning the long statistical dependencies in the data tha...
def wrap(self, data, many): """Wrap response in envelope.""" if not many: return data else: data = {'contents': data} bucket = self.context.get('bucket') if bucket: data.update(BucketSchema().dump(bucket).data) return da...
Wrap response in envelope.
Below is the the instruction that describes the task: ### Input: Wrap response in envelope. ### Response: def wrap(self, data, many): """Wrap response in envelope.""" if not many: return data else: data = {'contents': data} bucket = self.context.get('buck...
def remove(name, path): ''' Removes installed alternative for defined <name> and <path> or fallback to default alternative, if some defined before. name is the master name for this link group (e.g. pager) path is the location of one of the alternative target files. ...
Removes installed alternative for defined <name> and <path> or fallback to default alternative, if some defined before. name is the master name for this link group (e.g. pager) path is the location of one of the alternative target files. (e.g. /usr/bin/less)
Below is the the instruction that describes the task: ### Input: Removes installed alternative for defined <name> and <path> or fallback to default alternative, if some defined before. name is the master name for this link group (e.g. pager) path is the location of one of the a...
def remove_field(self, model, field): """Ran when a field is removed from a model.""" for keys in self._iterate_uniqueness_keys(field): self._drop_hstore_unique( model, field, keys )
Ran when a field is removed from a model.
Below is the the instruction that describes the task: ### Input: Ran when a field is removed from a model. ### Response: def remove_field(self, model, field): """Ran when a field is removed from a model.""" for keys in self._iterate_uniqueness_keys(field): self._drop_hstore_unique( ...
def tree(): """Return a tree of tuples representing the logger layout. Each tuple looks like ``('logger-name', <Logger>, [...])`` where the third element is a list of zero or more child tuples that share the same layout. """ root = ('', logging.root, []) nodes = {} items = list(logging...
Return a tree of tuples representing the logger layout. Each tuple looks like ``('logger-name', <Logger>, [...])`` where the third element is a list of zero or more child tuples that share the same layout.
Below is the the instruction that describes the task: ### Input: Return a tree of tuples representing the logger layout. Each tuple looks like ``('logger-name', <Logger>, [...])`` where the third element is a list of zero or more child tuples that share the same layout. ### Response: def tree(): "...
def safe_decode(s): """Safely decodes a binary string to unicode""" if isinstance(s, unicode): return s elif isinstance(s, bytes): return s.decode(defenc, 'surrogateescape') elif s is not None: raise TypeError('Expected bytes or text, but got %r' % (s,))
Safely decodes a binary string to unicode
Below is the the instruction that describes the task: ### Input: Safely decodes a binary string to unicode ### Response: def safe_decode(s): """Safely decodes a binary string to unicode""" if isinstance(s, unicode): return s elif isinstance(s, bytes): return s.decode(defenc, 'surrogatee...
def add_manager_view(request): ''' View to add a new manager position. Restricted to superadmins and presidents. ''' form = ManagerForm(request.POST or None) if form.is_valid(): manager = form.save() messages.add_message(request, messages.SUCCESS, MESSAGES['MANAG...
View to add a new manager position. Restricted to superadmins and presidents.
Below is the the instruction that describes the task: ### Input: View to add a new manager position. Restricted to superadmins and presidents. ### Response: def add_manager_view(request): ''' View to add a new manager position. Restricted to superadmins and presidents. ''' form = ManagerForm(request.POST o...
def ElemMatch(q, *conditions): """ The ElemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. """ new_condition = {} for condition in conditions: deep_merge(condition.to_dict(), new_condition) return ...
The ElemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
Below is the the instruction that describes the task: ### Input: The ElemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. ### Response: def ElemMatch(q, *conditions): """ The ElemMatch operator matches documents that c...
def mesh_multiplane(mesh, plane_origin, plane_normal, heights): """ A utility function for slicing a mesh by multiple parallel planes, which caches the dot product operation. Parameters ------------- mesh : trimesh.Trimesh Geom...
A utility function for slicing a mesh by multiple parallel planes, which caches the dot product operation. Parameters ------------- mesh : trimesh.Trimesh Geometry to be sliced by planes plane_normal : (3,) float Normal vector of plane plane_origin : (3,) float Point on ...
Below is the the instruction that describes the task: ### Input: A utility function for slicing a mesh by multiple parallel planes, which caches the dot product operation. Parameters ------------- mesh : trimesh.Trimesh Geometry to be sliced by planes plane_normal : (3,) float N...
def set(self, agent_id, name=None, description=None, redirect_domain=None, logo_media_id=None, report_location_flag=0, is_report_user=True, is_report_enter=True): """ 设置应用 https://work.weixin.qq.com/a...
设置应用 https://work.weixin.qq.com/api/doc#90000/90135/90228 :param agent_id: 企业应用的id :param name: 企业应用名称,长度不超过32个utf8字符 :param description: 企业应用详情,长度为4至120个utf8字符 :param redirect_domain: 企业应用可信域名。注意:域名需通过所有权校验,否则jssdk功能将受限,此时返回错误码85005 :param logo_media_id: 企业应用头像的mediaid,...
Below is the the instruction that describes the task: ### Input: 设置应用 https://work.weixin.qq.com/api/doc#90000/90135/90228 :param agent_id: 企业应用的id :param name: 企业应用名称,长度不超过32个utf8字符 :param description: 企业应用详情,长度为4至120个utf8字符 :param redirect_domain: 企业应用可信域名。注意:域名需通过所有权校验,否则...
def _activate(self): """Activate the application (bringing menus and windows forward).""" ra = AppKit.NSRunningApplication app = ra.runningApplicationWithProcessIdentifier_( self._getPid()) # NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps # =...
Activate the application (bringing menus and windows forward).
Below is the the instruction that describes the task: ### Input: Activate the application (bringing menus and windows forward). ### Response: def _activate(self): """Activate the application (bringing menus and windows forward).""" ra = AppKit.NSRunningApplication app = ra.runningApplicatio...
def calculate_top_down_likelihood(tree, character, frequencies, sf, kappa=None, model=F81): """ Calculates the top-down likelihood for the given tree. The likelihood for each node is stored in the corresponding feature, given by get_personalised_feature_name(feature, TD_LH). To calculate the top-do...
Calculates the top-down likelihood for the given tree. The likelihood for each node is stored in the corresponding feature, given by get_personalised_feature_name(feature, TD_LH). To calculate the top-down likelihood of a node, we assume that the tree is rooted in this node and combine the likelihoods ...
Below is the the instruction that describes the task: ### Input: Calculates the top-down likelihood for the given tree. The likelihood for each node is stored in the corresponding feature, given by get_personalised_feature_name(feature, TD_LH). To calculate the top-down likelihood of a node, we assume ...
def parse(self, valstr): # type: (bytes) -> None ''' A method to parse an El Torito Entry out of a string. Parameters: valstr - The string to parse the El Torito Entry out of. Returns: Nothing. ''' if self._initialized: raise pycdlib...
A method to parse an El Torito Entry out of a string. Parameters: valstr - The string to parse the El Torito Entry out of. Returns: Nothing.
Below is the the instruction that describes the task: ### Input: A method to parse an El Torito Entry out of a string. Parameters: valstr - The string to parse the El Torito Entry out of. Returns: Nothing. ### Response: def parse(self, valstr): # type: (bytes) -> None ...
def writeGenerator(self, gen): """ Iterates over a generator object and encodes all that is returned. """ n = getattr(gen, 'next') while True: try: self.writeElement(n()) except StopIteration: break
Iterates over a generator object and encodes all that is returned.
Below is the the instruction that describes the task: ### Input: Iterates over a generator object and encodes all that is returned. ### Response: def writeGenerator(self, gen): """ Iterates over a generator object and encodes all that is returned. """ n = getattr(gen, 'next') ...
def errors_handler(self, *custom_filters, exception=None, run_task=None, **kwargs): """ Decorator for errors handler :param exception: you can make handler for specific errors type :param run_task: run callback in task (no wait results) :return: """ def decorato...
Decorator for errors handler :param exception: you can make handler for specific errors type :param run_task: run callback in task (no wait results) :return:
Below is the the instruction that describes the task: ### Input: Decorator for errors handler :param exception: you can make handler for specific errors type :param run_task: run callback in task (no wait results) :return: ### Response: def errors_handler(self, *custom_filters, exception=N...
def submit(self, func, *args, **kwargs): """Submit a function for serialized execution on sqs """ self.op_sequence += 1 self.sqs.send_message( QueueUrl=self.map_queue, MessageBody=utils.dumps({'args': args, 'kwargs': kwargs}), MessageAttributes={ ...
Submit a function for serialized execution on sqs
Below is the the instruction that describes the task: ### Input: Submit a function for serialized execution on sqs ### Response: def submit(self, func, *args, **kwargs): """Submit a function for serialized execution on sqs """ self.op_sequence += 1 self.sqs.send_message( ...
def disable_event(self, event_type, mechanism): """Disables notification of the specified event type(s) via the specified mechanism(s). :param event_type: Logical event identifier. :param mechanism: Specifies event handling mechanisms to be disabled. (Constants.VI_QUEU...
Disables notification of the specified event type(s) via the specified mechanism(s). :param event_type: Logical event identifier. :param mechanism: Specifies event handling mechanisms to be disabled. (Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR, .VI_ALL_MECH)
Below is the the instruction that describes the task: ### Input: Disables notification of the specified event type(s) via the specified mechanism(s). :param event_type: Logical event identifier. :param mechanism: Specifies event handling mechanisms to be disabled. (Constan...
def relaxedEMDS(X0, N, d, C, b, KE, print_out=False, lamda=10): """ Find the set of points from an edge kernel with geometric constraints, using convex rank relaxation. """ E = C.shape[1] X = Variable((E, E), PSD=True) constraints = [C[i, :] * X == b[i] for i in range(C.shape[0])] obj = Minimi...
Find the set of points from an edge kernel with geometric constraints, using convex rank relaxation.
Below is the the instruction that describes the task: ### Input: Find the set of points from an edge kernel with geometric constraints, using convex rank relaxation. ### Response: def relaxedEMDS(X0, N, d, C, b, KE, print_out=False, lamda=10): """ Find the set of points from an edge kernel with geometric const...
def set_zone_order(self, zone_ids): """ reorder zones per the passed in list :param zone_ids: :return: """ reordered_zones = [] current_zone_ids = [z['id'] for z in self.my_osid_object_form._my_map['zones']] if set(zone_ids) != set(current_zone_ids): r...
reorder zones per the passed in list :param zone_ids: :return:
Below is the the instruction that describes the task: ### Input: reorder zones per the passed in list :param zone_ids: :return: ### Response: def set_zone_order(self, zone_ids): """ reorder zones per the passed in list :param zone_ids: :return: """ reordered_...
def iter_traceback_frames(tb): """ Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable. """ # Some versions of celery have hacked traceback objects that might # miss tb_frame. while tb and hasattr(tb, 'tb_frame'): ...
Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable.
Below is the the instruction that describes the task: ### Input: Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable. ### Response: def iter_traceback_frames(tb): """ Given a traceback object, it will iterate over all frames th...
def get_swagger_operation(self, context=default_context): """ get the swagger_schema operation representation. """ consumes = produces = context.contenttype_serializers.keys() parameters = get_swagger_parameters(self.parameters, context) responses = { "400": R...
get the swagger_schema operation representation.
Below is the the instruction that describes the task: ### Input: get the swagger_schema operation representation. ### Response: def get_swagger_operation(self, context=default_context): """ get the swagger_schema operation representation. """ consumes = produces = context.contenttyp...
def update_list_function(self, list_name, list_func): """ Modifies/overwrites an existing list function in the locally cached DesignDocument indexes dictionary. :param str list_name: Name used to identify the list function. :param str list_func: Javascript list function. ...
Modifies/overwrites an existing list function in the locally cached DesignDocument indexes dictionary. :param str list_name: Name used to identify the list function. :param str list_func: Javascript list function.
Below is the the instruction that describes the task: ### Input: Modifies/overwrites an existing list function in the locally cached DesignDocument indexes dictionary. :param str list_name: Name used to identify the list function. :param str list_func: Javascript list function. ### Response...
def run_simulation(self): """Runs the complete simulation""" print('Starting simulations...') for i in range(self.num_trials): print('---Trial {}---'.format(i)) self.run_trial(i) print('Simulation completed.')
Runs the complete simulation
Below is the the instruction that describes the task: ### Input: Runs the complete simulation ### Response: def run_simulation(self): """Runs the complete simulation""" print('Starting simulations...') for i in range(self.num_trials): print('---Trial {}---'.format(i)) ...
def remove(image): """Remove an image to the GUI img library.""" path = os.path.join(IMG_DIR, image) if os.path.isfile(path): os.remove(path)
Remove an image to the GUI img library.
Below is the the instruction that describes the task: ### Input: Remove an image to the GUI img library. ### Response: def remove(image): """Remove an image to the GUI img library.""" path = os.path.join(IMG_DIR, image) if os.path.isfile(path): os.remove(path)
def create_request_url(self, interface, method, version, parameters): """Create the URL to submit to the Steam Web API interface: Steam Web API interface containing methods. method: The method to call. version: The version of the method. paramters: Parameters to supply to the me...
Create the URL to submit to the Steam Web API interface: Steam Web API interface containing methods. method: The method to call. version: The version of the method. paramters: Parameters to supply to the method.
Below is the the instruction that describes the task: ### Input: Create the URL to submit to the Steam Web API interface: Steam Web API interface containing methods. method: The method to call. version: The version of the method. paramters: Parameters to supply to the method. ### Re...
def add(self, files, items): """ Add a list of files with a reference to a list of objects. """ if isinstance(files, (str, bytes)): files = iter([files]) for pathname in files: try: values = self._filemap[pathname] except KeyErr...
Add a list of files with a reference to a list of objects.
Below is the the instruction that describes the task: ### Input: Add a list of files with a reference to a list of objects. ### Response: def add(self, files, items): """ Add a list of files with a reference to a list of objects. """ if isinstance(files, (str, bytes)): f...
def parse_args(self, ctx, args): """Check if the first argument is an existing command.""" if args and args[0] in self.commands: args.insert(0, '') super(OptionalGroup, self).parse_args(ctx, args)
Check if the first argument is an existing command.
Below is the the instruction that describes the task: ### Input: Check if the first argument is an existing command. ### Response: def parse_args(self, ctx, args): """Check if the first argument is an existing command.""" if args and args[0] in self.commands: args.insert(0, '') ...
def import_object(path): """Import an object given its fully qualified name.""" spl = path.split('.') if len(spl) == 1: return importlib.import_module(path) # avoid last part for the moment cls = spl[-1] mods = '.'.join(spl[:-1]) mm = importlib.import_module(mods) # try to get t...
Import an object given its fully qualified name.
Below is the the instruction that describes the task: ### Input: Import an object given its fully qualified name. ### Response: def import_object(path): """Import an object given its fully qualified name.""" spl = path.split('.') if len(spl) == 1: return importlib.import_module(path) # avoi...
def setDragTable(self, table): """ Sets the table that will be linked with the drag query for this record. This information will be added to the drag & drop information when this record is dragged from the tree and will be set into the application/x-table format for mime da...
Sets the table that will be linked with the drag query for this record. This information will be added to the drag & drop information when this record is dragged from the tree and will be set into the application/x-table format for mime data. :sa setDragQuery, XTreeWid...
Below is the the instruction that describes the task: ### Input: Sets the table that will be linked with the drag query for this record. This information will be added to the drag & drop information when this record is dragged from the tree and will be set into the application/x-table fo...
def remove_peer_from_bgp_speaker(self, speaker_id, body=None): """Removes a peer from BGP speaker.""" return self.put((self.bgp_speaker_path % speaker_id) + "/remove_bgp_peer", body=body)
Removes a peer from BGP speaker.
Below is the the instruction that describes the task: ### Input: Removes a peer from BGP speaker. ### Response: def remove_peer_from_bgp_speaker(self, speaker_id, body=None): """Removes a peer from BGP speaker.""" return self.put((self.bgp_speaker_path % speaker_id) + "/remo...
def _set_desire_distance(self, v, load=False): """ Setter method for desire_distance, mapped from YANG variable /interface/fc_port/desire_distance (desire-distance-type) If this variable is read-only (config: false) in the source YANG file, then _set_desire_distance is considered as a private method...
Setter method for desire_distance, mapped from YANG variable /interface/fc_port/desire_distance (desire-distance-type) If this variable is read-only (config: false) in the source YANG file, then _set_desire_distance is considered as a private method. Backends looking to populate this variable should do ...
Below is the the instruction that describes the task: ### Input: Setter method for desire_distance, mapped from YANG variable /interface/fc_port/desire_distance (desire-distance-type) If this variable is read-only (config: false) in the source YANG file, then _set_desire_distance is considered as a private ...
def root_hash(self): """Returns the root hash of this tree. (Only re-computed on change.)""" if self.__root_hash is None: self.__root_hash = ( self.__hasher._hash_fold(self.__hashes) if self.__hashes else self.__hasher.hash_empty()) return self.__root_...
Returns the root hash of this tree. (Only re-computed on change.)
Below is the the instruction that describes the task: ### Input: Returns the root hash of this tree. (Only re-computed on change.) ### Response: def root_hash(self): """Returns the root hash of this tree. (Only re-computed on change.)""" if self.__root_hash is None: self.__root_hash = (...
def check_version(current_version: str): """ Check periodically for a new release """ app_version = parse_version(current_version) while True: try: _do_check_version(app_version) except requests.exceptions.HTTPError as herr: click.secho('Error while checking for versi...
Check periodically for a new release
Below is the the instruction that describes the task: ### Input: Check periodically for a new release ### Response: def check_version(current_version: str): """ Check periodically for a new release """ app_version = parse_version(current_version) while True: try: _do_check_version(a...
def _copy_and_clean_up_expectations_from_indexes( self, match_indexes, discard_result_format_kwargs=True, discard_include_configs_kwargs=True, discard_catch_exceptions_kwargs=True, ): """Copies and cleans all expectations provided by their index in DataAsset._expectat...
Copies and cleans all expectations provided by their index in DataAsset._expectations_config.expectations. Applies the _copy_and_clean_up_expectation method to multiple expectations, provided by their index in \ `DataAsset,_expectations_config.expectations`. Returns a list of the copied and clean...
Below is the the instruction that describes the task: ### Input: Copies and cleans all expectations provided by their index in DataAsset._expectations_config.expectations. Applies the _copy_and_clean_up_expectation method to multiple expectations, provided by their index in \ `DataAsset,_expe...
def get_perm_codename(perm, fail_silently=True): """ Get permission codename from permission-string. Examples -------- >>> get_perm_codename('app_label.codename_model') 'codename_model' >>> get_perm_codename('app_label.codename') 'codename' >>> get_perm_codename('codename_model') ...
Get permission codename from permission-string. Examples -------- >>> get_perm_codename('app_label.codename_model') 'codename_model' >>> get_perm_codename('app_label.codename') 'codename' >>> get_perm_codename('codename_model') 'codename_model' >>> get_perm_codename('codename') ...
Below is the the instruction that describes the task: ### Input: Get permission codename from permission-string. Examples -------- >>> get_perm_codename('app_label.codename_model') 'codename_model' >>> get_perm_codename('app_label.codename') 'codename' >>> get_perm_codename('codename_mo...
def get_files(dir_name): """Simple directory walker""" return [(os.path.join('.', d), [os.path.join(d, f) for f in files]) for d, _, files in os.walk(dir_name)]
Simple directory walker
Below is the the instruction that describes the task: ### Input: Simple directory walker ### Response: def get_files(dir_name): """Simple directory walker""" return [(os.path.join('.', d), [os.path.join(d, f) for f in files]) for d, _, files in os.walk(dir_name)]
def fix_e712(self, result): """Fix (trivial case of) comparison with boolean.""" (line_index, offset, target) = get_index_offset_contents(result, self.source) # Handle very easy "not" special cases. if re.match(r'^\s*if [\...
Fix (trivial case of) comparison with boolean.
Below is the the instruction that describes the task: ### Input: Fix (trivial case of) comparison with boolean. ### Response: def fix_e712(self, result): """Fix (trivial case of) comparison with boolean.""" (line_index, offset, target) = get_index_offset_contents(result, ...
def field_cache_to_index_pattern(self, field_cache): """Return a .kibana index-pattern doc_type""" mapping_dict = {} mapping_dict['customFormats'] = "{}" mapping_dict['title'] = self.index_pattern # now post the data into .kibana mapping_dict['fields'] = json.dumps(field_...
Return a .kibana index-pattern doc_type
Below is the the instruction that describes the task: ### Input: Return a .kibana index-pattern doc_type ### Response: def field_cache_to_index_pattern(self, field_cache): """Return a .kibana index-pattern doc_type""" mapping_dict = {} mapping_dict['customFormats'] = "{}" mapping_di...
def _validate_ports(reactor, ports): """ Internal helper for Onion services. Validates an incoming list of port mappings and returns a list of strings suitable for passing to other onion-services functions. Accepts 3 different ways of specifying ports: - list of ints: each int is the public ...
Internal helper for Onion services. Validates an incoming list of port mappings and returns a list of strings suitable for passing to other onion-services functions. Accepts 3 different ways of specifying ports: - list of ints: each int is the public port, local port random - list of 2-tuples ...
Below is the the instruction that describes the task: ### Input: Internal helper for Onion services. Validates an incoming list of port mappings and returns a list of strings suitable for passing to other onion-services functions. Accepts 3 different ways of specifying ports: - list of ints: eac...
def save_list(self, list_name, emails): """ Upload a list. The list import job is queued and will happen shortly after the API request. http://docs.sailthru.com/api/list @param list: list name @param emails: List of email values or comma separated string """ data ...
Upload a list. The list import job is queued and will happen shortly after the API request. http://docs.sailthru.com/api/list @param list: list name @param emails: List of email values or comma separated string
Below is the the instruction that describes the task: ### Input: Upload a list. The list import job is queued and will happen shortly after the API request. http://docs.sailthru.com/api/list @param list: list name @param emails: List of email values or comma separated string ### Response: d...
def expected_record(self, node): """ Constructs the provenance record that would be saved in the given node if the pipeline was run on the current state of the repository Parameters ---------- node : arcana.repository.tree.TreeNode A node of the Tree represen...
Constructs the provenance record that would be saved in the given node if the pipeline was run on the current state of the repository Parameters ---------- node : arcana.repository.tree.TreeNode A node of the Tree representation of the study data stored in the re...
Below is the the instruction that describes the task: ### Input: Constructs the provenance record that would be saved in the given node if the pipeline was run on the current state of the repository Parameters ---------- node : arcana.repository.tree.TreeNode A node of t...
def generate_simple_chemical_query(self, name=None, chemical_formula=None, property_name=None, property_value=None, property_min=None, property_max=None, property_units=None, reference_doi=None, include_datasets=[], exclude_datasets=[], from_...
This method generates a :class:`PifSystemReturningQuery` object using the supplied arguments. All arguments that accept lists have logical OR's on the queries that they generate. This means that, for example, simple_chemical_search(name=['A', 'B']) will match records that have name equal to 'A' ...
Below is the the instruction that describes the task: ### Input: This method generates a :class:`PifSystemReturningQuery` object using the supplied arguments. All arguments that accept lists have logical OR's on the queries that they generate. This means that, for example, simple_chemical_search(nam...
def giving_up(self, message): """ Called when a message has been received where ``msg.attempts > max_tries`` This is useful to subclass and override to perform a task (such as writing to disk, etc.) :param message: the :class:`nsq.Message` received """ logger.warning('[...
Called when a message has been received where ``msg.attempts > max_tries`` This is useful to subclass and override to perform a task (such as writing to disk, etc.) :param message: the :class:`nsq.Message` received
Below is the the instruction that describes the task: ### Input: Called when a message has been received where ``msg.attempts > max_tries`` This is useful to subclass and override to perform a task (such as writing to disk, etc.) :param message: the :class:`nsq.Message` received ### Response: def...
def save(self, *args, **kwargs): """ This method autogenerates the auto_generated_description field """ # Cache basic data self.cache_data() # Ensure slug doesn't change if self.id is not None: db_company = Company.objects.get(id=self.id) ...
This method autogenerates the auto_generated_description field
Below is the the instruction that describes the task: ### Input: This method autogenerates the auto_generated_description field ### Response: def save(self, *args, **kwargs): """ This method autogenerates the auto_generated_description field """ # Cache basic data self.cach...
def create_arguments(primary, pyfunction, call_node, scope): """A factory for creating `Arguments`""" args = list(call_node.args) args.extend(call_node.keywords) called = call_node.func # XXX: Handle constructors if _is_method_call(primary, pyfunction) and \ isinstance(called, ast.Attribu...
A factory for creating `Arguments`
Below is the the instruction that describes the task: ### Input: A factory for creating `Arguments` ### Response: def create_arguments(primary, pyfunction, call_node, scope): """A factory for creating `Arguments`""" args = list(call_node.args) args.extend(call_node.keywords) called = call_node.func...
def _set_vrf(self, v, load=False): """ Setter method for vrf, mapped from YANG variable /nas/server_ip/vrf (list) If this variable is read-only (config: false) in the source YANG file, then _set_vrf is considered as a private method. Backends looking to populate this variable should do so via ca...
Setter method for vrf, mapped from YANG variable /nas/server_ip/vrf (list) If this variable is read-only (config: false) in the source YANG file, then _set_vrf is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_vrf() directly.
Below is the the instruction that describes the task: ### Input: Setter method for vrf, mapped from YANG variable /nas/server_ip/vrf (list) If this variable is read-only (config: false) in the source YANG file, then _set_vrf is considered as a private method. Backends looking to populate this variable s...
def detect_mobile(view): """View Decorator that adds a "mobile" attribute to the request which is True or False depending on whether the request should be considered to come from a small-screen device such as a phone or a PDA""" @wraps(view) def detected(request, *args, **kwargs): Mob...
View Decorator that adds a "mobile" attribute to the request which is True or False depending on whether the request should be considered to come from a small-screen device such as a phone or a PDA
Below is the the instruction that describes the task: ### Input: View Decorator that adds a "mobile" attribute to the request which is True or False depending on whether the request should be considered to come from a small-screen device such as a phone or a PDA ### Response: def detect_mobile(view):...
def prepare_build_dir(self): '''Ensure that a build dir exists for the recipe. This same single dir will be used for building all different archs.''' self.build_dir = self.get_build_dir() self.common_dir = self.get_common_dir() copy_files(join(self.bootstrap_dir, 'build'), self.b...
Ensure that a build dir exists for the recipe. This same single dir will be used for building all different archs.
Below is the the instruction that describes the task: ### Input: Ensure that a build dir exists for the recipe. This same single dir will be used for building all different archs. ### Response: def prepare_build_dir(self): '''Ensure that a build dir exists for the recipe. This same single d...
def int_to_array(i, length=2): """Convert an length byte integer to an array of bytes.""" res = [] for dummy in range(0, length): res.append(i & 0xff) i = i >> 8 return reversed(res)
Convert an length byte integer to an array of bytes.
Below is the the instruction that describes the task: ### Input: Convert an length byte integer to an array of bytes. ### Response: def int_to_array(i, length=2): """Convert an length byte integer to an array of bytes.""" res = [] for dummy in range(0, length): res.append(i & 0xff) i = ...
def create_upload_and_chunk_url(self, project_id, path_data, hash_data, remote_filename=None, storage_provider_id=None): """ Create an non-chunked upload that returns upload id and upload url. This type of upload doesn't allow additional upload urls. For singl...
Create an non-chunked upload that returns upload id and upload url. This type of upload doesn't allow additional upload urls. For single chunk files this method is more efficient than create_upload/create_file_chunk_url. :param project_id: str: uuid of the project :param path_data: PathD...
Below is the the instruction that describes the task: ### Input: Create an non-chunked upload that returns upload id and upload url. This type of upload doesn't allow additional upload urls. For single chunk files this method is more efficient than create_upload/create_file_chunk_url. :param...
def apply(self, strain, detector_name, f_lower=None, distance_scale=1, simulation_ids=None, inj_filter_rejector=None): """Add injections (as seen by a particular detector) to a time series. Parameters ---------- strain : TimeSeries Time series to inject signals...
Add injections (as seen by a particular detector) to a time series. Parameters ---------- strain : TimeSeries Time series to inject signals into, of type float32 or float64. detector_name : string Name of the detector used for projecting injections. f_low...
Below is the the instruction that describes the task: ### Input: Add injections (as seen by a particular detector) to a time series. Parameters ---------- strain : TimeSeries Time series to inject signals into, of type float32 or float64. detector_name : string ...
def getElementText(self, node, preserve_ws=None): """Return the text value of an xml element node. Leading and trailing whitespace is stripped from the value unless the preserve_ws flag is passed with a true value.""" result = [] for child in node.childNodes: no...
Return the text value of an xml element node. Leading and trailing whitespace is stripped from the value unless the preserve_ws flag is passed with a true value.
Below is the the instruction that describes the task: ### Input: Return the text value of an xml element node. Leading and trailing whitespace is stripped from the value unless the preserve_ws flag is passed with a true value. ### Response: def getElementText(self, node, preserve_ws=None): ...
def set_device_offset(self, x_offset, y_offset): """ Sets an offset that is added to the device coordinates determined by the CTM when drawing to surface. One use case for this method is when we want to create a :class:`Surface` that redirects drawing for a portion of an onscreen...
Sets an offset that is added to the device coordinates determined by the CTM when drawing to surface. One use case for this method is when we want to create a :class:`Surface` that redirects drawing for a portion of an onscreen surface to an offscreen surface in a way that is ...
Below is the the instruction that describes the task: ### Input: Sets an offset that is added to the device coordinates determined by the CTM when drawing to surface. One use case for this method is when we want to create a :class:`Surface` that redirects drawing for a portion of an ...
def tb_h_file_creation(target, source, env): """Compile tilebus file into only .h files corresponding to config variables for inclusion in a library""" files = [str(x) for x in source] try: desc = TBDescriptor(files) except pyparsing.ParseException as e: raise BuildError("Could not par...
Compile tilebus file into only .h files corresponding to config variables for inclusion in a library
Below is the the instruction that describes the task: ### Input: Compile tilebus file into only .h files corresponding to config variables for inclusion in a library ### Response: def tb_h_file_creation(target, source, env): """Compile tilebus file into only .h files corresponding to config variables for inclu...
def start(self): """ Start all the processes """ Global.LOGGER.info("starting the flow manager") self._start_actions() self._start_message_fetcher() Global.LOGGER.debug("flow manager started")
Start all the processes
Below is the the instruction that describes the task: ### Input: Start all the processes ### Response: def start(self): """ Start all the processes """ Global.LOGGER.info("starting the flow manager") self._start_actions() self._start_message_fetcher() Global....
def mesh2fc(script, all_visible_layers=False): """Transfer mesh colors to face colors Args: script: the FilterScript object or script filename to write the filter to. all_visible_layers (bool): If true the color mapping is applied to all the meshes """ filter_xml = ''.join([...
Transfer mesh colors to face colors Args: script: the FilterScript object or script filename to write the filter to. all_visible_layers (bool): If true the color mapping is applied to all the meshes
Below is the the instruction that describes the task: ### Input: Transfer mesh colors to face colors Args: script: the FilterScript object or script filename to write the filter to. all_visible_layers (bool): If true the color mapping is applied to all the meshes ### Response: def ...
def allck(): ''' 檢查所有股票買賣點,剔除$10以下、成交量小於1000張的股票。 ''' for i in twseno().allstockno: a = goristock.goristock(i) try: if a.stock_vol[-1] > 1000*1000 and a.raw_data[-1] > 10: #a.goback(3) ## 倒退天數 ck4m(a) except: pass
檢查所有股票買賣點,剔除$10以下、成交量小於1000張的股票。
Below is the the instruction that describes the task: ### Input: 檢查所有股票買賣點,剔除$10以下、成交量小於1000張的股票。 ### Response: def allck(): ''' 檢查所有股票買賣點,剔除$10以下、成交量小於1000張的股票。 ''' for i in twseno().allstockno: a = goristock.goristock(i) try: if a.stock_vol[-1] > 1000*1000 and a.raw_data[-1] > 10: #a.go...
def set_start(self,t): """ Override the GPS start time (and set the duration) of this ScienceSegment. @param t: new GPS start time. """ self.__dur += self.__start - t self.__start = t
Override the GPS start time (and set the duration) of this ScienceSegment. @param t: new GPS start time.
Below is the the instruction that describes the task: ### Input: Override the GPS start time (and set the duration) of this ScienceSegment. @param t: new GPS start time. ### Response: def set_start(self,t): """ Override the GPS start time (and set the duration) of this ScienceSegment. @param t: new...
async def load_variant(self, elem_type, params=None, elem=None, wrapped=None, obj=None): """ Loads variant type from the reader. Supports both wrapped and raw variant. :param elem_type: :param params: :param elem: :param wrapped: :param obj: :retu...
Loads variant type from the reader. Supports both wrapped and raw variant. :param elem_type: :param params: :param elem: :param wrapped: :param obj: :return:
Below is the the instruction that describes the task: ### Input: Loads variant type from the reader. Supports both wrapped and raw variant. :param elem_type: :param params: :param elem: :param wrapped: :param obj: :return: ### Response: async def load_varian...
def cutout(vol, requested_bbox, steps, channel_slice=slice(None), parallel=1, shared_memory_location=None, output_to_shared_memory=False): """Cutout a requested bounding box from storage and return it as a numpy array.""" global fs_lock cloudpath_bbox = requested_bbox.expand_to_chunk_size(vol.underlying, offs...
Cutout a requested bounding box from storage and return it as a numpy array.
Below is the the instruction that describes the task: ### Input: Cutout a requested bounding box from storage and return it as a numpy array. ### Response: def cutout(vol, requested_bbox, steps, channel_slice=slice(None), parallel=1, shared_memory_location=None, output_to_shared_memory=False): """Cutout a req...
def make_clean_visible_from_raw(_html, tag_replacement_char=' '): '''Takes an HTML-like Unicode (or UTF-8 encoded) string as input and returns a Unicode string with all tags replaced by whitespace. In particular, all Unicode characters inside HTML are replaced with a single whitespace character. Th...
Takes an HTML-like Unicode (or UTF-8 encoded) string as input and returns a Unicode string with all tags replaced by whitespace. In particular, all Unicode characters inside HTML are replaced with a single whitespace character. This *does* detect comments, style, script, link tags and replaces them...
Below is the the instruction that describes the task: ### Input: Takes an HTML-like Unicode (or UTF-8 encoded) string as input and returns a Unicode string with all tags replaced by whitespace. In particular, all Unicode characters inside HTML are replaced with a single whitespace character. This *...
def sas_interconnect_types(self): """ Gets the SasInterconnectTypes API client. Returns: SasInterconnectTypes: """ if not self.__sas_interconnect_types: self.__sas_interconnect_types = SasInterconnectTypes(self.__connection) return self.__sas_inte...
Gets the SasInterconnectTypes API client. Returns: SasInterconnectTypes:
Below is the the instruction that describes the task: ### Input: Gets the SasInterconnectTypes API client. Returns: SasInterconnectTypes: ### Response: def sas_interconnect_types(self): """ Gets the SasInterconnectTypes API client. Returns: SasInterconnectT...
async def _write(self, path, data, *, flags=None, cas=None, acquire=None, release=None): """Sets the key to the given value. Returns: bool: ``True`` on success """ if not isinstance(data, bytes): raise ValueError("value must be bytes") ...
Sets the key to the given value. Returns: bool: ``True`` on success
Below is the the instruction that describes the task: ### Input: Sets the key to the given value. Returns: bool: ``True`` on success ### Response: async def _write(self, path, data, *, flags=None, cas=None, acquire=None, release=None): """Sets the key to the given ...
def get_listing(path): """ Returns the list of files and directories in a path. Prepents a ".." (parent directory link) if path is not current dir. """ if path != ".": listing = sorted(['..'] + os.listdir(path)) else: listing = sorted(os.listdir(path)) return listing
Returns the list of files and directories in a path. Prepents a ".." (parent directory link) if path is not current dir.
Below is the the instruction that describes the task: ### Input: Returns the list of files and directories in a path. Prepents a ".." (parent directory link) if path is not current dir. ### Response: def get_listing(path): """ Returns the list of files and directories in a path. Prepents a ".." (parent dir...
def meta(self, file_list, **kwargs): """获得文件(s)的metainfo :param file_list: 文件路径列表,如 ['/aaa.txt'] :type file_list: list :return: requests.Response .. note :: 示例 * 文件不存在 {"errno":12,"info":[{"errno":-9}],"request_id":3294861771} ...
获得文件(s)的metainfo :param file_list: 文件路径列表,如 ['/aaa.txt'] :type file_list: list :return: requests.Response .. note :: 示例 * 文件不存在 {"errno":12,"info":[{"errno":-9}],"request_id":3294861771} * 文件存在 { "errno"...
Below is the the instruction that describes the task: ### Input: 获得文件(s)的metainfo :param file_list: 文件路径列表,如 ['/aaa.txt'] :type file_list: list :return: requests.Response .. note :: 示例 * 文件不存在 {"errno":12,"info":[{"errno":-9}],"request_id":...
def segments(self, using=None, **kwargs): """ Provide low level segments information that a Lucene index (shard level) is built with. Any additional keyword arguments will be passed to ``Elasticsearch.indices.segments`` unchanged. """ return self._get_connection(...
Provide low level segments information that a Lucene index (shard level) is built with. Any additional keyword arguments will be passed to ``Elasticsearch.indices.segments`` unchanged.
Below is the the instruction that describes the task: ### Input: Provide low level segments information that a Lucene index (shard level) is built with. Any additional keyword arguments will be passed to ``Elasticsearch.indices.segments`` unchanged. ### Response: def segments(self, using=N...
def process_hive(vargs): """ Main Hive.co path. """ artist_url = vargs['artist_url'] if 'hive.co' in artist_url: mc_url = artist_url else: mc_url = 'https://www.hive.co/downloads/download/' + artist_url filenames = scrape_hive_url(mc_url, num_tracks=vargs['num_tracks'], fo...
Main Hive.co path.
Below is the the instruction that describes the task: ### Input: Main Hive.co path. ### Response: def process_hive(vargs): """ Main Hive.co path. """ artist_url = vargs['artist_url'] if 'hive.co' in artist_url: mc_url = artist_url else: mc_url = 'https://www.hive.co/downlo...
def get_list_filter(self, request): """ Adds the period filter to the filters list. :param request: Current request. :return: Iterable of filters. """ original = super(TrackedLiveAdmin, self).get_list_filter(request) return original + type(original)([PeriodFilter...
Adds the period filter to the filters list. :param request: Current request. :return: Iterable of filters.
Below is the the instruction that describes the task: ### Input: Adds the period filter to the filters list. :param request: Current request. :return: Iterable of filters. ### Response: def get_list_filter(self, request): """ Adds the period filter to the filters list. :para...
def assign_properties(thing): """Assign properties to an object. When creating something via a post request (e.g. a node), you can pass the properties of the object in the request. This function gets those values from the request and fills in the relevant columns of the table. """ for p in rang...
Assign properties to an object. When creating something via a post request (e.g. a node), you can pass the properties of the object in the request. This function gets those values from the request and fills in the relevant columns of the table.
Below is the the instruction that describes the task: ### Input: Assign properties to an object. When creating something via a post request (e.g. a node), you can pass the properties of the object in the request. This function gets those values from the request and fills in the relevant columns of the ...
def import_classes(name, currmodule): # type: (unicode, unicode) -> Any """Import a class using its fully-qualified *name*.""" target = None # import class or module using currmodule if currmodule: target = try_import(currmodule + '.' + name) # import class or module without currmodule...
Import a class using its fully-qualified *name*.
Below is the the instruction that describes the task: ### Input: Import a class using its fully-qualified *name*. ### Response: def import_classes(name, currmodule): # type: (unicode, unicode) -> Any """Import a class using its fully-qualified *name*.""" target = None # import class or module usin...
def restrict_bond_dict(self, bond_dict): """Restrict a bond dictionary to self. Args: bond_dict (dict): Look into :meth:`~chemcoord.Cartesian.get_bonds`, to see examples for a bond_dict. Returns: bond dictionary """ return {j: bond_dict[j...
Restrict a bond dictionary to self. Args: bond_dict (dict): Look into :meth:`~chemcoord.Cartesian.get_bonds`, to see examples for a bond_dict. Returns: bond dictionary
Below is the the instruction that describes the task: ### Input: Restrict a bond dictionary to self. Args: bond_dict (dict): Look into :meth:`~chemcoord.Cartesian.get_bonds`, to see examples for a bond_dict. Returns: bond dictionary ### Response: def restri...
def _traverse_tree(tree, path): """Traverses the permission tree, returning the permission at given permission path.""" path_steps = (step for step in path.split('.') if step != '') # Special handling for first step, because the first step isn't under 'objects' first_step = path_steps.ne...
Traverses the permission tree, returning the permission at given permission path.
Below is the the instruction that describes the task: ### Input: Traverses the permission tree, returning the permission at given permission path. ### Response: def _traverse_tree(tree, path): """Traverses the permission tree, returning the permission at given permission path.""" path_steps = (step...
def get(self, field): """ Returns the value of a user field. :param str field: The name of the user field. :returns: str -- the value """ if field in ('username', 'uuid', 'app_data'): return self.data[field] else: return self.d...
Returns the value of a user field. :param str field: The name of the user field. :returns: str -- the value
Below is the the instruction that describes the task: ### Input: Returns the value of a user field. :param str field: The name of the user field. :returns: str -- the value ### Response: def get(self, field): """ Returns the value of a user field. :param str fi...