code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def get_meas_los(self, user_lo_config): """Embed default meas LO frequencies from backend and format them to list object. If configured lo frequency is the same as default, this method returns `None`. Args: user_lo_config (LoConfig): A dictionary of LOs to format. Returns: ...
Embed default meas LO frequencies from backend and format them to list object. If configured lo frequency is the same as default, this method returns `None`. Args: user_lo_config (LoConfig): A dictionary of LOs to format. Returns: list: A list of meas LOs. Rais...
Below is the the instruction that describes the task: ### Input: Embed default meas LO frequencies from backend and format them to list object. If configured lo frequency is the same as default, this method returns `None`. Args: user_lo_config (LoConfig): A dictionary of LOs to format. ...
def cmd_log(self, reopen=False, rotate=False): """Allows managing of uWSGI log related stuff :param bool reopen: Reopen log file. Could be required after third party rotation. :param bool rotate: Trigger built-in log rotation. """ cmd = b'' if reopen: cmd +...
Allows managing of uWSGI log related stuff :param bool reopen: Reopen log file. Could be required after third party rotation. :param bool rotate: Trigger built-in log rotation.
Below is the the instruction that describes the task: ### Input: Allows managing of uWSGI log related stuff :param bool reopen: Reopen log file. Could be required after third party rotation. :param bool rotate: Trigger built-in log rotation. ### Response: def cmd_log(self, reopen=False, rotate=Fal...
def random_pairs_with_replacement(n, shape, random_state=None): """make random record pairs""" if not isinstance(random_state, np.random.RandomState): random_state = np.random.RandomState(random_state) n_max = max_pairs(shape) if n_max <= 0: raise ValueError('n_max must be larger than...
make random record pairs
Below is the the instruction that describes the task: ### Input: make random record pairs ### Response: def random_pairs_with_replacement(n, shape, random_state=None): """make random record pairs""" if not isinstance(random_state, np.random.RandomState): random_state = np.random.RandomState(random...
def invert(self, invert=True): """Inverts all the channels of a image according to *invert*. If invert is a tuple or a list, elementwise invertion is performed, otherwise all channels are inverted if *invert* is true (default). Note: 'Inverting' means that black becomes white, and vice-versa, n...
Inverts all the channels of a image according to *invert*. If invert is a tuple or a list, elementwise invertion is performed, otherwise all channels are inverted if *invert* is true (default). Note: 'Inverting' means that black becomes white, and vice-versa, not that the values are negated !
Below is the the instruction that describes the task: ### Input: Inverts all the channels of a image according to *invert*. If invert is a tuple or a list, elementwise invertion is performed, otherwise all channels are inverted if *invert* is true (default). Note: 'Inverting' means that black becom...
def execute(self, timeout=None): """Execute all currently queued batch commands""" logger.debug(' > Batch API request (length %s)' % len(self._commands)) auth = self._build_http_auth() headers = self._build_request_headers() logger.debug('\tbatch headers: %s' % headers) ...
Execute all currently queued batch commands
Below is the the instruction that describes the task: ### Input: Execute all currently queued batch commands ### Response: def execute(self, timeout=None): """Execute all currently queued batch commands""" logger.debug(' > Batch API request (length %s)' % len(self._commands)) auth = self._...
def get(self): """ *get the ebook object* **Return:** - ``ebook`` **Usage:** See class docstring for usage """ self.log.debug('starting the ``get`` method') if self.format == "epub": if self.urlOrPath[:4] == "http" or self.u...
*get the ebook object* **Return:** - ``ebook`` **Usage:** See class docstring for usage
Below is the the instruction that describes the task: ### Input: *get the ebook object* **Return:** - ``ebook`` **Usage:** See class docstring for usage ### Response: def get(self): """ *get the ebook object* **Return:** - ``ebook`` ...
def handle_class(signature_node, module, object_name, cache): """ Styles ``autoclass`` entries. Adds ``abstract`` prefix to abstract classes. """ class_ = getattr(module, object_name, None) if class_ is None: return if class_ not in cache: cache[class_] = {} attribut...
Styles ``autoclass`` entries. Adds ``abstract`` prefix to abstract classes.
Below is the the instruction that describes the task: ### Input: Styles ``autoclass`` entries. Adds ``abstract`` prefix to abstract classes. ### Response: def handle_class(signature_node, module, object_name, cache): """ Styles ``autoclass`` entries. Adds ``abstract`` prefix to abstract classes. ...
def mulmod(computation: BaseComputation) -> None: """ Modulo Multiplication """ left, right, mod = computation.stack_pop(num_items=3, type_hint=constants.UINT256) if mod == 0: result = 0 else: result = (left * right) % mod computation.stack_push(result)
Modulo Multiplication
Below is the the instruction that describes the task: ### Input: Modulo Multiplication ### Response: def mulmod(computation: BaseComputation) -> None: """ Modulo Multiplication """ left, right, mod = computation.stack_pop(num_items=3, type_hint=constants.UINT256) if mod == 0: result = ...
def init_volumes(self, single=None, only_mount=None, skip_mount=None, swallow_exceptions=True): """Detects volumes (as volume system or as single volume) in all disks and yields the volumes. This calls :func:`Disk.init_volumes` on all disks and should be called after :func:`mount_disks`. :rtype...
Detects volumes (as volume system or as single volume) in all disks and yields the volumes. This calls :func:`Disk.init_volumes` on all disks and should be called after :func:`mount_disks`. :rtype: generator
Below is the the instruction that describes the task: ### Input: Detects volumes (as volume system or as single volume) in all disks and yields the volumes. This calls :func:`Disk.init_volumes` on all disks and should be called after :func:`mount_disks`. :rtype: generator ### Response: def init_vo...
def num_or_str(x): """The argument is a string; convert to a number if possible, or strip it. >>> num_or_str('42') 42 >>> num_or_str(' 42x ') '42x' """ if isnumber(x): return x try: return int(x) except ValueError: try: return float(x) except Value...
The argument is a string; convert to a number if possible, or strip it. >>> num_or_str('42') 42 >>> num_or_str(' 42x ') '42x'
Below is the the instruction that describes the task: ### Input: The argument is a string; convert to a number if possible, or strip it. >>> num_or_str('42') 42 >>> num_or_str(' 42x ') '42x' ### Response: def num_or_str(x): """The argument is a string; convert to a number if possible, or strip ...
def run(self): """Redirects messages until a shutdown message is received.""" while True: if not self.task_socket.poll(-1): continue msg = self.task_socket.recv_multipart() msg_type = msg[1] if self.debug: self.stats.appen...
Redirects messages until a shutdown message is received.
Below is the the instruction that describes the task: ### Input: Redirects messages until a shutdown message is received. ### Response: def run(self): """Redirects messages until a shutdown message is received.""" while True: if not self.task_socket.poll(-1): continue ...
async def set_config(cls, name: str, value): """Set a configuration value in MAAS. Consult your MAAS server for recognised settings. Alternatively, use the pre-canned functions also defined on this object. """ return await cls._handler.set_config(name=[name], value=[value])
Set a configuration value in MAAS. Consult your MAAS server for recognised settings. Alternatively, use the pre-canned functions also defined on this object.
Below is the the instruction that describes the task: ### Input: Set a configuration value in MAAS. Consult your MAAS server for recognised settings. Alternatively, use the pre-canned functions also defined on this object. ### Response: async def set_config(cls, name: str, value): """Set a...
def is_java_project(self): """ Indicates if the project's main binary is a Java Archive. """ if self._is_java_project is None: self._is_java_project = isinstance(self.arch, ArchSoot) return self._is_java_project
Indicates if the project's main binary is a Java Archive.
Below is the the instruction that describes the task: ### Input: Indicates if the project's main binary is a Java Archive. ### Response: def is_java_project(self): """ Indicates if the project's main binary is a Java Archive. """ if self._is_java_project is None: self._i...
def to_instants_dataframe(self, sql_ctx): """ Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time. This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column is a key form one of the rows in the TimeSeriesRDD. """ ...
Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time. This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column is a key form one of the rows in the TimeSeriesRDD.
Below is the the instruction that describes the task: ### Input: Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time. This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column is a key form one of the rows in the TimeSeriesRDD. ### R...
def summary(dataset_uri, format): """Report summary information about a dataset.""" dataset = dtoolcore.DataSet.from_uri(dataset_uri) creator_username = dataset._admin_metadata["creator_username"] frozen_at = dataset._admin_metadata["frozen_at"] num_items = len(dataset.identifiers) tot_size = su...
Report summary information about a dataset.
Below is the the instruction that describes the task: ### Input: Report summary information about a dataset. ### Response: def summary(dataset_uri, format): """Report summary information about a dataset.""" dataset = dtoolcore.DataSet.from_uri(dataset_uri) creator_username = dataset._admin_metadata["cr...
def validate_file(file_type, file_path): """ Validates a file against a schema Parameters ---------- file_type : str Type of file to read. May be 'component', 'element', 'table', or 'references' file_path: Full path to the file to be validated Raises ------ RuntimeE...
Validates a file against a schema Parameters ---------- file_type : str Type of file to read. May be 'component', 'element', 'table', or 'references' file_path: Full path to the file to be validated Raises ------ RuntimeError If the file_type is not valid (and/or a ...
Below is the the instruction that describes the task: ### Input: Validates a file against a schema Parameters ---------- file_type : str Type of file to read. May be 'component', 'element', 'table', or 'references' file_path: Full path to the file to be validated Raises ---...
def kld(d1, d2): """Return the Kullback-Leibler Divergence (KLD) between two distributions. Args: d1 (np.ndarray): The first distribution. d2 (np.ndarray): The second distribution. Returns: float: The KLD of ``d1`` from ``d2``. """ d1, d2 = flatten(d1), flatten(d2) retu...
Return the Kullback-Leibler Divergence (KLD) between two distributions. Args: d1 (np.ndarray): The first distribution. d2 (np.ndarray): The second distribution. Returns: float: The KLD of ``d1`` from ``d2``.
Below is the the instruction that describes the task: ### Input: Return the Kullback-Leibler Divergence (KLD) between two distributions. Args: d1 (np.ndarray): The first distribution. d2 (np.ndarray): The second distribution. Returns: float: The KLD of ``d1`` from ``d2``. ### Respo...
def cmd_tool(args=None): """ Command line tool for plotting and viewing info on guppi raw files """ from argparse import ArgumentParser parser = ArgumentParser(description="Command line utility for creating spectra from GuppiRaw files.") parser.add_argument('filename', type=str, help='Name of file to...
Command line tool for plotting and viewing info on guppi raw files
Below is the the instruction that describes the task: ### Input: Command line tool for plotting and viewing info on guppi raw files ### Response: def cmd_tool(args=None): """ Command line tool for plotting and viewing info on guppi raw files """ from argparse import ArgumentParser parser = ArgumentPa...
def run(self): # type: () -> bool """ Run all linters and report results. Returns: bool: **True** if all checks were successful, **False** otherwise. """ with util.timed_block() as t: files = self._collect_files() log.info("Collected <33>{} <32>f...
Run all linters and report results. Returns: bool: **True** if all checks were successful, **False** otherwise.
Below is the the instruction that describes the task: ### Input: Run all linters and report results. Returns: bool: **True** if all checks were successful, **False** otherwise. ### Response: def run(self): # type: () -> bool """ Run all linters and report results. Retu...
def get_os_version_package(pkg, fatal=True): '''Derive OpenStack version number from an installed package.''' codename = get_os_codename_package(pkg, fatal=fatal) if not codename: return None if 'swift' in pkg: vers_map = SWIFT_CODENAMES for cname, version in six.iteritems(vers...
Derive OpenStack version number from an installed package.
Below is the the instruction that describes the task: ### Input: Derive OpenStack version number from an installed package. ### Response: def get_os_version_package(pkg, fatal=True): '''Derive OpenStack version number from an installed package.''' codename = get_os_codename_package(pkg, fatal=fatal) i...
def _release_info(jsn,VERSION): """Gives information about a particular package version.""" try: release_point = jsn['releases'][VERSION][0] except KeyError: print "\033[91m\033[1mError: Release not found." exit(1) python_version = release_point['python_version'] filename = release_point['filename'] md5 = r...
Gives information about a particular package version.
Below is the the instruction that describes the task: ### Input: Gives information about a particular package version. ### Response: def _release_info(jsn,VERSION): """Gives information about a particular package version.""" try: release_point = jsn['releases'][VERSION][0] except KeyError: print "\033[91m\0...
def _parse_qualimap_globals_inregion(table): """Retrieve metrics from the global targeted region table. """ out = {} for row in table.find_all("tr"): col, val = [x.text for x in row.find_all("td")] if col == "Mapped reads": out.update(_parse_num_pct("%s (in regions)" % col, v...
Retrieve metrics from the global targeted region table.
Below is the the instruction that describes the task: ### Input: Retrieve metrics from the global targeted region table. ### Response: def _parse_qualimap_globals_inregion(table): """Retrieve metrics from the global targeted region table. """ out = {} for row in table.find_all("tr"): col, v...
def modularity_louvain_und(W, gamma=1, hierarchy=False, seed=None): ''' The optimal community structure is a subdivision of the network into nonoverlapping groups of nodes in a way that maximizes the number of within-group edges, and minimizes the number of between-group edges. The modularity is a s...
The optimal community structure is a subdivision of the network into nonoverlapping groups of nodes in a way that maximizes the number of within-group edges, and minimizes the number of between-group edges. The modularity is a statistic that quantifies the degree to which the network may be subdivided i...
Below is the the instruction that describes the task: ### Input: The optimal community structure is a subdivision of the network into nonoverlapping groups of nodes in a way that maximizes the number of within-group edges, and minimizes the number of between-group edges. The modularity is a statistic th...
def visible_fields(self): """ Returns the reduced set of visible fields to output from the form. This method respects the provided ``fields`` configuration _and_ exlcudes all fields from the ``exclude`` configuration. If no ``fields`` where provided when configuring this fields...
Returns the reduced set of visible fields to output from the form. This method respects the provided ``fields`` configuration _and_ exlcudes all fields from the ``exclude`` configuration. If no ``fields`` where provided when configuring this fieldset, all visible fields minus the exclu...
Below is the the instruction that describes the task: ### Input: Returns the reduced set of visible fields to output from the form. This method respects the provided ``fields`` configuration _and_ exlcudes all fields from the ``exclude`` configuration. If no ``fields`` where provided when ...
def map_to_openapi_type(self, *args): """Decorator to set mapping for custom fields. ``*args`` can be: - a pair of the form ``(type, format)`` - a core marshmallow field type (in which case we reuse that type's mapping) """ if len(args) == 1 and args[0] in self.field_ma...
Decorator to set mapping for custom fields. ``*args`` can be: - a pair of the form ``(type, format)`` - a core marshmallow field type (in which case we reuse that type's mapping)
Below is the the instruction that describes the task: ### Input: Decorator to set mapping for custom fields. ``*args`` can be: - a pair of the form ``(type, format)`` - a core marshmallow field type (in which case we reuse that type's mapping) ### Response: def map_to_openapi_type(self, *...
def calc_hamiltonian(self, mass, omega_array): """ Calculates the standard (pot+kin) Hamiltonian of your system. Parameters ---------- mass : float The mass of the particle in kg omega_array : array array which represents omega at every po...
Calculates the standard (pot+kin) Hamiltonian of your system. Parameters ---------- mass : float The mass of the particle in kg omega_array : array array which represents omega at every point in your time trace and should therefore have the sa...
Below is the the instruction that describes the task: ### Input: Calculates the standard (pot+kin) Hamiltonian of your system. Parameters ---------- mass : float The mass of the particle in kg omega_array : array array which represents omega at every ...
def addKeyword(self, keyword, weight): """ add a relevant keyword to the topic page @param keyword: keyword or phrase to be added @param weight: importance of the provided keyword (typically in range 1 - 50) """ assert isinstance(weight, (float, int)), "weight value has t...
add a relevant keyword to the topic page @param keyword: keyword or phrase to be added @param weight: importance of the provided keyword (typically in range 1 - 50)
Below is the the instruction that describes the task: ### Input: add a relevant keyword to the topic page @param keyword: keyword or phrase to be added @param weight: importance of the provided keyword (typically in range 1 - 50) ### Response: def addKeyword(self, keyword, weight): """ ...
def get_ordered_entries(self, queryset=False): """ Custom ordering. First we get the average views and rating for the categories's entries. Second we created a rank by multiplying both. Last, we sort categories by this rank from top to bottom. Example: - Cat_1 ...
Custom ordering. First we get the average views and rating for the categories's entries. Second we created a rank by multiplying both. Last, we sort categories by this rank from top to bottom. Example: - Cat_1 - Entry_1 (500 Views, Rating 2) - Entry_2 (200 Views,...
Below is the the instruction that describes the task: ### Input: Custom ordering. First we get the average views and rating for the categories's entries. Second we created a rank by multiplying both. Last, we sort categories by this rank from top to bottom. Example: - Cat_1 ...
def broadcast(self, fromUserId, objectName, content, pushContent=None, pushData=None, os=None): """ 发送广播消息方法(发送消息给一个应用下的所有注册用户,如用户未在线会对满足条件(绑定手机终端)的用户发送 Push 信息,单条消息最大 128k,会话类型为 SYSTEM。每小时只能发送 1 ...
发送广播消息方法(发送消息给一个应用下的所有注册用户,如用户未在线会对满足条件(绑定手机终端)的用户发送 Push 信息,单条消息最大 128k,会话类型为 SYSTEM。每小时只能发送 1 次,每天最多发送 3 次。) 方法 @param fromUserId:发送人用户 Id。(必传) @param txtMessage:文本消息。 @param pushContent:定义显示的 Push 内容,如果 objectName 为融云内置消息类型时,则发送后用户一定会收到 Push 信息. 如果为自定义消息,则 pushContent 为自定义消息显示的 Push 内容,如果不...
Below is the the instruction that describes the task: ### Input: 发送广播消息方法(发送消息给一个应用下的所有注册用户,如用户未在线会对满足条件(绑定手机终端)的用户发送 Push 信息,单条消息最大 128k,会话类型为 SYSTEM。每小时只能发送 1 次,每天最多发送 3 次。) 方法 @param fromUserId:发送人用户 Id。(必传) @param txtMessage:文本消息。 @param pushContent:定义显示的 Push 内容,如果 objectName 为融云内置消息...
def delete_untagged(collector, **kwargs): """Find the untagged images and remove them""" configuration = collector.configuration docker_api = configuration["harpoon"].docker_api images = docker_api.images() found = False for image in images: if image["RepoTags"] == ["<none>:<none>"]: ...
Find the untagged images and remove them
Below is the the instruction that describes the task: ### Input: Find the untagged images and remove them ### Response: def delete_untagged(collector, **kwargs): """Find the untagged images and remove them""" configuration = collector.configuration docker_api = configuration["harpoon"].docker_api i...
def _get_site_class(self, vs30, mmi_mean): """ Return site class flag for: Class E - Very Soft Soil vs30 < 180 Class D - Deep or Soft Soil vs30 >= 180 and vs30 <= 360 Class C - Shallow Soil vs30 > 360 and vs30 <= 760 Class B - Rock vs3...
Return site class flag for: Class E - Very Soft Soil vs30 < 180 Class D - Deep or Soft Soil vs30 >= 180 and vs30 <= 360 Class C - Shallow Soil vs30 > 360 and vs30 <= 760 Class B - Rock vs30 > 760 and vs30 <= 1500 Class A - Strong Rock ...
Below is the the instruction that describes the task: ### Input: Return site class flag for: Class E - Very Soft Soil vs30 < 180 Class D - Deep or Soft Soil vs30 >= 180 and vs30 <= 360 Class C - Shallow Soil vs30 > 360 and vs30 <= 760 Class B - Rock ...
def make_report(self, outcome): """Make report in form of two notebooks. Use nbdime diff-web to present the difference between reference cells and test cells. """ failures = self.getreports('failed') if not failures: return for rep in failures: ...
Make report in form of two notebooks. Use nbdime diff-web to present the difference between reference cells and test cells.
Below is the the instruction that describes the task: ### Input: Make report in form of two notebooks. Use nbdime diff-web to present the difference between reference cells and test cells. ### Response: def make_report(self, outcome): """Make report in form of two notebooks. Use n...
def currentpath(self) -> str: """Absolute path of the current working directory. >>> from hydpy.core.filetools import FileManager >>> filemanager = FileManager() >>> filemanager.BASEDIR = 'basename' >>> filemanager.projectdir = 'projectname' >>> from hydpy import repr_, ...
Absolute path of the current working directory. >>> from hydpy.core.filetools import FileManager >>> filemanager = FileManager() >>> filemanager.BASEDIR = 'basename' >>> filemanager.projectdir = 'projectname' >>> from hydpy import repr_, TestIO >>> with TestIO(): ...
Below is the the instruction that describes the task: ### Input: Absolute path of the current working directory. >>> from hydpy.core.filetools import FileManager >>> filemanager = FileManager() >>> filemanager.BASEDIR = 'basename' >>> filemanager.projectdir = 'projectname' >...
def from_analysis_period(cls, analysis_period, clearness=1, daylight_savings_indicator='No'): """"Initialize a OriginalClearSkyCondition from an analysis_period""" _check_analysis_period(analysis_period) return cls(analysis_period.st_month, analysis_period.st_day, cl...
Initialize a OriginalClearSkyCondition from an analysis_period
Below is the the instruction that describes the task: ### Input: Initialize a OriginalClearSkyCondition from an analysis_period ### Response: def from_analysis_period(cls, analysis_period, clearness=1, daylight_savings_indicator='No'): """"Initialize a OriginalClearSkyCondition...
def parse_model_table_file(path, f): """Parse a file as a list of model reactions Yields reactions IDs. Path can be given as a string or a context. """ for line in f: line, _, comment = line.partition('#') line = line.strip() if line == '': continue yield l...
Parse a file as a list of model reactions Yields reactions IDs. Path can be given as a string or a context.
Below is the the instruction that describes the task: ### Input: Parse a file as a list of model reactions Yields reactions IDs. Path can be given as a string or a context. ### Response: def parse_model_table_file(path, f): """Parse a file as a list of model reactions Yields reactions IDs. Path can b...
async def get_entry(config, url): """ Given an entry URL, return the entry Arguments: config -- the configuration url -- the URL of the entry Returns: 3-tuple of (current, previous, updated) """ previous = config.cache.get( 'entry', url, schema_version=SCHEMA_VERSION) if conf...
Given an entry URL, return the entry Arguments: config -- the configuration url -- the URL of the entry Returns: 3-tuple of (current, previous, updated)
Below is the the instruction that describes the task: ### Input: Given an entry URL, return the entry Arguments: config -- the configuration url -- the URL of the entry Returns: 3-tuple of (current, previous, updated) ### Response: async def get_entry(config, url): """ Given an entry URL, re...
def _stellingwerf_pdm_worker(task): ''' This is a parallel worker for the function below. Parameters ---------- task : tuple This is of the form below:: task[0] = times task[1] = mags task[2] = errs task[3] = frequency task[4] = ...
This is a parallel worker for the function below. Parameters ---------- task : tuple This is of the form below:: task[0] = times task[1] = mags task[2] = errs task[3] = frequency task[4] = binsize task[5] = minbin Return...
Below is the the instruction that describes the task: ### Input: This is a parallel worker for the function below. Parameters ---------- task : tuple This is of the form below:: task[0] = times task[1] = mags task[2] = errs task[3] = frequency ...
def _init_params_default(self): """ Internal method for default parameter initialization """ # if there are some nan -> mean impute Yimp = self.Y.copy() Inan = sp.isnan(Yimp) Yimp[Inan] = Yimp[~Inan].mean() if self.P==1: C = sp.array([[Yimp.var()]]) ...
Internal method for default parameter initialization
Below is the the instruction that describes the task: ### Input: Internal method for default parameter initialization ### Response: def _init_params_default(self): """ Internal method for default parameter initialization """ # if there are some nan -> mean impute Yimp = self...
def get_shape(kind='line',x=None,y=None,x0=None,y0=None,x1=None,y1=None,span=0,color='red',dash='solid',width=1, fillcolor=None,fill=False,opacity=1,xref='x',yref='y'): """ Returns a plotly shape Parameters: ----------- kind : string Shape kind line rect circle x : float x values for the ...
Returns a plotly shape Parameters: ----------- kind : string Shape kind line rect circle x : float x values for the shape. This assumes x0=x1 x0 : float x0 value for the shape x1 : float x1 value for the shape y : float y values for the shape. This assumes y0=y1 y0 : floa...
Below is the the instruction that describes the task: ### Input: Returns a plotly shape Parameters: ----------- kind : string Shape kind line rect circle x : float x values for the shape. This assumes x0=x1 x0 : float x0 value for the shape x1 : float x1 value for the shape y...
def saml_provider_absent(name, region=None, key=None, keyid=None, profile=None): ''' .. versionadded:: 2016.11.0 Ensure the SAML provider with the specified name is absent. name (string) The name of the SAML provider. saml_metadata_document (string) The xml document of the SAML pr...
.. versionadded:: 2016.11.0 Ensure the SAML provider with the specified name is absent. name (string) The name of the SAML provider. saml_metadata_document (string) The xml document of the SAML provider. region (string) Region to connect to. key (string) Secret k...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2016.11.0 Ensure the SAML provider with the specified name is absent. name (string) The name of the SAML provider. saml_metadata_document (string) The xml document of the SAML provider. region (str...
def redirect_to_assignment_override_for_group(self, group_id, assignment_id): """ Redirect to the assignment override for a group. Responds with a redirect to the override for the given group, if any (404 otherwise). """ path = {} data = {} param...
Redirect to the assignment override for a group. Responds with a redirect to the override for the given group, if any (404 otherwise).
Below is the the instruction that describes the task: ### Input: Redirect to the assignment override for a group. Responds with a redirect to the override for the given group, if any (404 otherwise). ### Response: def redirect_to_assignment_override_for_group(self, group_id, assignment_id): ...
def mouse_click(self, widget, event=None): """Implements shift- and control-key handling features for mouse button press events explicit The method is implements a fully defined mouse pattern to use shift- and control-key for multi-selection in a TreeView and a ListStore as model. It avoid pr...
Implements shift- and control-key handling features for mouse button press events explicit The method is implements a fully defined mouse pattern to use shift- and control-key for multi-selection in a TreeView and a ListStore as model. It avoid problems caused by special renderer types like the text ...
Below is the the instruction that describes the task: ### Input: Implements shift- and control-key handling features for mouse button press events explicit The method is implements a fully defined mouse pattern to use shift- and control-key for multi-selection in a TreeView and a ListStore as mod...
def collection(self, collection_id): """Create a sub-collection underneath the current document. Args: collection_id (str): The sub-collection identifier (sometimes referred to as the "kind"). Returns: ~.firestore_v1beta1.collection.CollectionReference: ...
Create a sub-collection underneath the current document. Args: collection_id (str): The sub-collection identifier (sometimes referred to as the "kind"). Returns: ~.firestore_v1beta1.collection.CollectionReference: The child collection.
Below is the the instruction that describes the task: ### Input: Create a sub-collection underneath the current document. Args: collection_id (str): The sub-collection identifier (sometimes referred to as the "kind"). Returns: ~.firestore_v1beta1.collection....
def shutdown(self, msg, args): """Causes the bot to gracefully shutdown.""" self.log.info("Received shutdown from %s", msg.user.username) self._bot.runnable = False return "Shutting down..."
Causes the bot to gracefully shutdown.
Below is the the instruction that describes the task: ### Input: Causes the bot to gracefully shutdown. ### Response: def shutdown(self, msg, args): """Causes the bot to gracefully shutdown.""" self.log.info("Received shutdown from %s", msg.user.username) self._bot.runnable = False ...
def printImportedNames(self): """Produce a report of imported names.""" for module in self.listModules(): print("%s:" % module.modname) print(" %s" % "\n ".join(imp.name for imp in module.imported_names))
Produce a report of imported names.
Below is the the instruction that describes the task: ### Input: Produce a report of imported names. ### Response: def printImportedNames(self): """Produce a report of imported names.""" for module in self.listModules(): print("%s:" % module.modname) print(" %s" % "\n ".jo...
def with_arg_count(self, count): """Set the last call to expect an exact argument count. I.E.:: >>> auth = Fake('auth').provides('login').with_arg_count(2) >>> auth.login('joe_user') # forgot password Traceback (most recent call last): ... As...
Set the last call to expect an exact argument count. I.E.:: >>> auth = Fake('auth').provides('login').with_arg_count(2) >>> auth.login('joe_user') # forgot password Traceback (most recent call last): ... AssertionError: fake:auth.login() was called w...
Below is the the instruction that describes the task: ### Input: Set the last call to expect an exact argument count. I.E.:: >>> auth = Fake('auth').provides('login').with_arg_count(2) >>> auth.login('joe_user') # forgot password Traceback (most recent call last): ...
def trigger(cls, streams): """ Given a list of streams, collect all the stream parameters into a dictionary and pass it to the union set of subscribers. Passing multiple streams at once to trigger can be useful when a subscriber may be set multiple times across streams but only ...
Given a list of streams, collect all the stream parameters into a dictionary and pass it to the union set of subscribers. Passing multiple streams at once to trigger can be useful when a subscriber may be set multiple times across streams but only needs to be called once.
Below is the the instruction that describes the task: ### Input: Given a list of streams, collect all the stream parameters into a dictionary and pass it to the union set of subscribers. Passing multiple streams at once to trigger can be useful when a subscriber may be set multiple times ac...
def mdr_conditional_entropy(X, Y, labels, base=2): """Calculates the MDR conditional entropy, H(XY|labels), in the given base MDR conditional entropy is calculated by combining variables X and Y into a single MDR model then calculating the entropy of the resulting model's predictions conditional on the pro...
Calculates the MDR conditional entropy, H(XY|labels), in the given base MDR conditional entropy is calculated by combining variables X and Y into a single MDR model then calculating the entropy of the resulting model's predictions conditional on the provided labels. Parameters ---------- X: array-...
Below is the the instruction that describes the task: ### Input: Calculates the MDR conditional entropy, H(XY|labels), in the given base MDR conditional entropy is calculated by combining variables X and Y into a single MDR model then calculating the entropy of the resulting model's predictions conditional...
def fragment6(pkt, fragSize): """ Performs fragmentation of an IPv6 packet. Provided packet ('pkt') must already contain an IPv6ExtHdrFragment() class. 'fragSize' argument is the expected maximum size of fragments (MTU). The list of packets is returned. If packet does not contain an IPv6ExtHdrFragm...
Performs fragmentation of an IPv6 packet. Provided packet ('pkt') must already contain an IPv6ExtHdrFragment() class. 'fragSize' argument is the expected maximum size of fragments (MTU). The list of packets is returned. If packet does not contain an IPv6ExtHdrFragment class, it is returned in result li...
Below is the the instruction that describes the task: ### Input: Performs fragmentation of an IPv6 packet. Provided packet ('pkt') must already contain an IPv6ExtHdrFragment() class. 'fragSize' argument is the expected maximum size of fragments (MTU). The list of packets is returned. If packet does not...
def add_to_results(self, data, label, results): """ responsible for updating the running `results` variable with the data from this queryset/serializer combo """ raise NotImplementedError( '{} must specify how to add data to the running results tally ' 'by...
responsible for updating the running `results` variable with the data from this queryset/serializer combo
Below is the the instruction that describes the task: ### Input: responsible for updating the running `results` variable with the data from this queryset/serializer combo ### Response: def add_to_results(self, data, label, results): """ responsible for updating the running `results` variabl...
def MeetsConditions(knowledge_base, source): """Check conditions on the source.""" source_conditions_met = True os_conditions = ConvertSupportedOSToConditions(source) if os_conditions: source.conditions.append(os_conditions) for condition in source.conditions: source_conditions_met &= artifact_utils.C...
Check conditions on the source.
Below is the the instruction that describes the task: ### Input: Check conditions on the source. ### Response: def MeetsConditions(knowledge_base, source): """Check conditions on the source.""" source_conditions_met = True os_conditions = ConvertSupportedOSToConditions(source) if os_conditions: source....
def voxel_count(dset,p=None,positive_only=False,mask=None,ROI=None): ''' returns the number of non-zero voxels :p: threshold the dataset at the given *p*-value, then count :positive_only: only count positive values :mask: count within the given mask :ROI: only use the...
returns the number of non-zero voxels :p: threshold the dataset at the given *p*-value, then count :positive_only: only count positive values :mask: count within the given mask :ROI: only use the ROI with the given value (or list of values) within the mask ...
Below is the the instruction that describes the task: ### Input: returns the number of non-zero voxels :p: threshold the dataset at the given *p*-value, then count :positive_only: only count positive values :mask: count within the given mask :ROI: only use the ROI wit...
def poll_integration_information_for_waiting_integration_alerts(): """poll_integration_information_for_waiting_integration_alerts.""" if not polling_integration_alerts: return logger.debug("Polling information for waiting integration alerts") for integration_alert in polling_integration_alerts...
poll_integration_information_for_waiting_integration_alerts.
Below is the the instruction that describes the task: ### Input: poll_integration_information_for_waiting_integration_alerts. ### Response: def poll_integration_information_for_waiting_integration_alerts(): """poll_integration_information_for_waiting_integration_alerts.""" if not polling_integration_alerts...
def _get_bucket_region(self, bucket_name): """ Get region based on the bucket name. :param bucket_name: Bucket name for which region will be fetched. :return: Region of bucket name. """ # Region set in constructor, return right here. if self._region: ...
Get region based on the bucket name. :param bucket_name: Bucket name for which region will be fetched. :return: Region of bucket name.
Below is the the instruction that describes the task: ### Input: Get region based on the bucket name. :param bucket_name: Bucket name for which region will be fetched. :return: Region of bucket name. ### Response: def _get_bucket_region(self, bucket_name): """ Get region based on t...
def snapshots(): ''' List current description snapshots. CLI Example: .. code-block:: bash salt myminion inspector.snapshots ''' try: return _("collector").Inspector(cachedir=__opts__['cachedir'], piddir=os.path.dirname(__opts__['pidfile...
List current description snapshots. CLI Example: .. code-block:: bash salt myminion inspector.snapshots
Below is the the instruction that describes the task: ### Input: List current description snapshots. CLI Example: .. code-block:: bash salt myminion inspector.snapshots ### Response: def snapshots(): ''' List current description snapshots. CLI Example: .. code-block:: bash ...
def htmlFormat(output, pathParts = (), statDict = None, query = None): """Formats as HTML, writing to the given object.""" statDict = statDict or scales.getStats() if query: statDict = runQuery(statDict, query) _htmlRenderDict(pathParts, statDict, output)
Formats as HTML, writing to the given object.
Below is the the instruction that describes the task: ### Input: Formats as HTML, writing to the given object. ### Response: def htmlFormat(output, pathParts = (), statDict = None, query = None): """Formats as HTML, writing to the given object.""" statDict = statDict or scales.getStats() if query: statDi...
def area_uri(self, area_uuid): """ Return the URI for an Upload Area :param area_uuid: UUID of area for which we want URI :return: Upload Area URI object :rtype: UploadAreaURI :raises UploadException: if area does not exist """ if area_uuid not in self.are...
Return the URI for an Upload Area :param area_uuid: UUID of area for which we want URI :return: Upload Area URI object :rtype: UploadAreaURI :raises UploadException: if area does not exist
Below is the the instruction that describes the task: ### Input: Return the URI for an Upload Area :param area_uuid: UUID of area for which we want URI :return: Upload Area URI object :rtype: UploadAreaURI :raises UploadException: if area does not exist ### Response: def area_uri(se...
def kill_log_monitor(self, check_alive=True): """Kill the log monitor. Args: check_alive (bool): Raise an exception if the process was already dead. """ self._kill_process_type( ray_constants.PROCESS_TYPE_LOG_MONITOR, check_alive=check_alive)
Kill the log monitor. Args: check_alive (bool): Raise an exception if the process was already dead.
Below is the the instruction that describes the task: ### Input: Kill the log monitor. Args: check_alive (bool): Raise an exception if the process was already dead. ### Response: def kill_log_monitor(self, check_alive=True): """Kill the log monitor. Args: ...
def write_temp_file(text=""): """Create a new temporary file and write some initial text to it. :param text: the text to write to the temp file :type text: str :returns: the file name of the newly created temp file :rtype: str """ with NamedTemporaryFile(mode='w+t', suffix='.yml', delete=F...
Create a new temporary file and write some initial text to it. :param text: the text to write to the temp file :type text: str :returns: the file name of the newly created temp file :rtype: str
Below is the the instruction that describes the task: ### Input: Create a new temporary file and write some initial text to it. :param text: the text to write to the temp file :type text: str :returns: the file name of the newly created temp file :rtype: str ### Response: def write_temp_file(text=...
def create_aaaa_record(self, name, values, ttl=60, weight=None, region=None, set_identifier=None): """ Creates an AAAA record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings...
Creates an AAAA record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record (in seconds). :keyword int weight: *For weighted record sets ...
Below is the the instruction that describes the task: ### Input: Creates an AAAA record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record ...
def get_graph_by_ids(self, network_ids: List[int]) -> BELGraph: """Get a combine BEL Graph from a list of network identifiers.""" if len(network_ids) == 1: return self.get_graph_by_id(network_ids[0]) log.debug('getting graph by identifiers: %s', network_ids) graphs = self.ge...
Get a combine BEL Graph from a list of network identifiers.
Below is the the instruction that describes the task: ### Input: Get a combine BEL Graph from a list of network identifiers. ### Response: def get_graph_by_ids(self, network_ids: List[int]) -> BELGraph: """Get a combine BEL Graph from a list of network identifiers.""" if len(network_ids) == 1: ...
def kremove(self, key, value=None): """Removes the given key/value from all elements. If value is not specified, the whole key is removed. If value is not None and the key is present but with a different value, or if the key is not present, silently passes. """ for item i...
Removes the given key/value from all elements. If value is not specified, the whole key is removed. If value is not None and the key is present but with a different value, or if the key is not present, silently passes.
Below is the the instruction that describes the task: ### Input: Removes the given key/value from all elements. If value is not specified, the whole key is removed. If value is not None and the key is present but with a different value, or if the key is not present, silently passes. ### Resp...
def sasl_mechanism(name, secure, preference = 50): """Class decorator generator for `ClientAuthenticator` or `ServerAuthenticator` subclasses. Adds the class to the pyxmpp.sasl mechanism registry. :Parameters: - `name`: SASL mechanism name - `secure`: if the mechanims can be considered ...
Class decorator generator for `ClientAuthenticator` or `ServerAuthenticator` subclasses. Adds the class to the pyxmpp.sasl mechanism registry. :Parameters: - `name`: SASL mechanism name - `secure`: if the mechanims can be considered secure - `True` if it can be used over plain-tex...
Below is the the instruction that describes the task: ### Input: Class decorator generator for `ClientAuthenticator` or `ServerAuthenticator` subclasses. Adds the class to the pyxmpp.sasl mechanism registry. :Parameters: - `name`: SASL mechanism name - `secure`: if the mechanims can be ...
def show_stories(self, raw=False, limit=None): """Returns list of item ids of latest Show HN stories Args: limit (int): specifies the number of stories to be returned. raw (bool): Flag to indicate whether to transform all objects into raw json. Returns: ...
Returns list of item ids of latest Show HN stories Args: limit (int): specifies the number of stories to be returned. raw (bool): Flag to indicate whether to transform all objects into raw json. Returns: `list` object containing ids of Show HN storie...
Below is the the instruction that describes the task: ### Input: Returns list of item ids of latest Show HN stories Args: limit (int): specifies the number of stories to be returned. raw (bool): Flag to indicate whether to transform all objects into raw json. ...
def burstColumn(self, column, columnMatchingSegments, prevActiveCells, prevWinnerCells, learn): """ Activates all of the cells in an unpredicted active column, chooses a winner cell, and, if learning is turned on, learns on one segment, growing a new segment if necessary. @param c...
Activates all of the cells in an unpredicted active column, chooses a winner cell, and, if learning is turned on, learns on one segment, growing a new segment if necessary. @param column (int) Index of bursting column. @param columnMatchingSegments (iter) Matching segments in this column, or N...
Below is the the instruction that describes the task: ### Input: Activates all of the cells in an unpredicted active column, chooses a winner cell, and, if learning is turned on, learns on one segment, growing a new segment if necessary. @param column (int) Index of bursting column. @param col...
def get_provider(vm_=None): ''' Extract the provider name from vm ''' if vm_ is None: provider = __active_provider_name__ or 'ec2' else: provider = vm_.get('provider', 'ec2') if ':' in provider: prov_comps = provider.split(':') provider = prov_comps[0] return...
Extract the provider name from vm
Below is the the instruction that describes the task: ### Input: Extract the provider name from vm ### Response: def get_provider(vm_=None): ''' Extract the provider name from vm ''' if vm_ is None: provider = __active_provider_name__ or 'ec2' else: provider = vm_.get('provider'...
def add_note(self, note): """Add a note to the selected tracks. Everything container.Track supports in __add__ is accepted. """ for n in self.selected_tracks: self.tracks[n] + note
Add a note to the selected tracks. Everything container.Track supports in __add__ is accepted.
Below is the the instruction that describes the task: ### Input: Add a note to the selected tracks. Everything container.Track supports in __add__ is accepted. ### Response: def add_note(self, note): """Add a note to the selected tracks. Everything container.Track supports in __add__ is a...
def getTaskInfo(self, task_id, **kwargs): """ Load all information about a task and return a custom Task class. Calls "getTaskInfo" XML-RPC (with request=True to get the full information.) :param task_id: ``int``, for example 12345 :returns: deferred that when fired ret...
Load all information about a task and return a custom Task class. Calls "getTaskInfo" XML-RPC (with request=True to get the full information.) :param task_id: ``int``, for example 12345 :returns: deferred that when fired returns a Task (Munch, dict-like) object repres...
Below is the the instruction that describes the task: ### Input: Load all information about a task and return a custom Task class. Calls "getTaskInfo" XML-RPC (with request=True to get the full information.) :param task_id: ``int``, for example 12345 :returns: deferred that when fi...
def attr(*args, **kwargs): ''' Set attributes on the current active tag context ''' ctx = dom_tag._with_contexts[_get_thread_context()] if ctx and ctx[-1]: dicts = args + (kwargs,) for d in dicts: for attr, value in d.items(): ctx[-1].tag.set_attribute(*dom_tag.clean_pair(attr, value)) ...
Set attributes on the current active tag context
Below is the the instruction that describes the task: ### Input: Set attributes on the current active tag context ### Response: def attr(*args, **kwargs): ''' Set attributes on the current active tag context ''' ctx = dom_tag._with_contexts[_get_thread_context()] if ctx and ctx[-1]: dicts = args + (k...
def write_summary_cnts_goobjs(self, goobjs): """Write summary of level and depth counts for active GO Terms.""" cnts = self.get_cnts_levels_depths_recs(goobjs) self._write_summary_cnts(cnts)
Write summary of level and depth counts for active GO Terms.
Below is the the instruction that describes the task: ### Input: Write summary of level and depth counts for active GO Terms. ### Response: def write_summary_cnts_goobjs(self, goobjs): """Write summary of level and depth counts for active GO Terms.""" cnts = self.get_cnts_levels_depths_recs(goobjs)...
def edit_message_live_location(latitude, longitude, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None, **kwargs): """ Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A locati...
Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message was sent by the bot, the edited Message is returne...
Below is the the instruction that describes the task: ### Input: Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if ...
def destroy_iam(app='', env='dev', **_): """Destroy IAM Resources. Args: app (str): Spinnaker Application name. env (str): Deployment environment, i.e. dev, stage, prod. Returns: True upon successful completion. """ session = boto3.Session(profile_name=env) client = ses...
Destroy IAM Resources. Args: app (str): Spinnaker Application name. env (str): Deployment environment, i.e. dev, stage, prod. Returns: True upon successful completion.
Below is the the instruction that describes the task: ### Input: Destroy IAM Resources. Args: app (str): Spinnaker Application name. env (str): Deployment environment, i.e. dev, stage, prod. Returns: True upon successful completion. ### Response: def destroy_iam(app='', env='dev',...
def convertAndMake(converter, handler): """Convert with location.""" def convertAction(loc, value): return handler(loc, converter(value)) return convertAction
Convert with location.
Below is the the instruction that describes the task: ### Input: Convert with location. ### Response: def convertAndMake(converter, handler): """Convert with location.""" def convertAction(loc, value): return handler(loc, converter(value)) return convertAction
def _offset_to_min(utc_offset): ''' Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ''' match = re.match(r"^([+-])?(\d\d)(\d\d)$",...
Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively.
Below is the the instruction that describes the task: ### Input: Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ### Response: def _offset_to...
def resume(self, trigger_duration=0): """Resumes pulse capture after an optional trigger pulse.""" if trigger_duration != 0: self._mq.send("t%d" % trigger_duration, True, type=1) else: self._mq.send("r", True, type=1) self._paused = False
Resumes pulse capture after an optional trigger pulse.
Below is the the instruction that describes the task: ### Input: Resumes pulse capture after an optional trigger pulse. ### Response: def resume(self, trigger_duration=0): """Resumes pulse capture after an optional trigger pulse.""" if trigger_duration != 0: self._mq.send("t%d" % trigge...
def add(self, data, name=None): ''' Appends a new column of data to the data source. Args: data (seq) : new data to add name (str, optional) : column name to use. If not supplied, generate a name of the form "Series ####" Returns: str: the c...
Appends a new column of data to the data source. Args: data (seq) : new data to add name (str, optional) : column name to use. If not supplied, generate a name of the form "Series ####" Returns: str: the column name used
Below is the the instruction that describes the task: ### Input: Appends a new column of data to the data source. Args: data (seq) : new data to add name (str, optional) : column name to use. If not supplied, generate a name of the form "Series ####" Returns...
def iterate_presentation_files(path=None, excludes=None, includes=None): """Iterates the repository presentation files relative to 'path', not including themes. Note that 'includes' take priority.""" # Defaults if includes is None: includes = [] if excludes is None: excludes = [] ...
Iterates the repository presentation files relative to 'path', not including themes. Note that 'includes' take priority.
Below is the the instruction that describes the task: ### Input: Iterates the repository presentation files relative to 'path', not including themes. Note that 'includes' take priority. ### Response: def iterate_presentation_files(path=None, excludes=None, includes=None): """Iterates the repository present...
def prop_symbols(x): "Return a list of all propositional symbols in x." if not isinstance(x, Expr): return [] elif is_prop_symbol(x.op): return [x] else: return list(set(symbol for arg in x.args for symbol in prop_symbols(arg)))
Return a list of all propositional symbols in x.
Below is the the instruction that describes the task: ### Input: Return a list of all propositional symbols in x. ### Response: def prop_symbols(x): "Return a list of all propositional symbols in x." if not isinstance(x, Expr): return [] elif is_prop_symbol(x.op): return [x] else: ...
def getPaths(urlOrPaths): ''' Determines if the given URL in urlOrPaths is a URL or a file or directory. If it's a directory, it walks the directory and then finds all file paths in it, and ads them too. If it's a file, it adds it to the paths. If it's a URL it just adds it to the path. :param urlOr...
Determines if the given URL in urlOrPaths is a URL or a file or directory. If it's a directory, it walks the directory and then finds all file paths in it, and ads them too. If it's a file, it adds it to the paths. If it's a URL it just adds it to the path. :param urlOrPaths: the url or path to be scanned ...
Below is the the instruction that describes the task: ### Input: Determines if the given URL in urlOrPaths is a URL or a file or directory. If it's a directory, it walks the directory and then finds all file paths in it, and ads them too. If it's a file, it adds it to the paths. If it's a URL it just adds i...
def read_lua_file(dotted_module, path=None, context=None): '''Load lua script from the stdnet/lib/lua directory''' path = path or DEFAULT_LUA_PATH bits = dotted_module.split('.') bits[-1] += '.lua' name = os.path.join(path, *bits) with open(name) as f: data = f.read() if cont...
Load lua script from the stdnet/lib/lua directory
Below is the the instruction that describes the task: ### Input: Load lua script from the stdnet/lib/lua directory ### Response: def read_lua_file(dotted_module, path=None, context=None): '''Load lua script from the stdnet/lib/lua directory''' path = path or DEFAULT_LUA_PATH bits = dotted_module.spl...
def view_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/views#show-view" api_path = "/api/v2/views/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/views#show-view
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/core/views#show-view ### Response: def view_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/views#show-view" api_path = "/api/v2/views/{id}.json" api_path...
def _keep_this(self, name): """Return True if there are to be no modifications to name.""" for keep_name in self.keep: if name == keep_name: return True return False
Return True if there are to be no modifications to name.
Below is the the instruction that describes the task: ### Input: Return True if there are to be no modifications to name. ### Response: def _keep_this(self, name): """Return True if there are to be no modifications to name.""" for keep_name in self.keep: if name == keep_name: ...
def make_caption(self, caption): """Adds/Substitutes the table's caption.""" if not hasattr(self, "caption"): self(caption=Caption()) return self.caption.empty()(caption)
Adds/Substitutes the table's caption.
Below is the the instruction that describes the task: ### Input: Adds/Substitutes the table's caption. ### Response: def make_caption(self, caption): """Adds/Substitutes the table's caption.""" if not hasattr(self, "caption"): self(caption=Caption()) return self.caption.empty()(...
def send_location(self, peer: Peer, latitude: float, longitude: float, reply: int=None, on_success: callable=None, reply_markup: botapi.ReplyMarkup=None): """ Send location to peer. :param peer: Peer to send message to. :param latitude: Latitude of the location. ...
Send location to peer. :param peer: Peer to send message to. :param latitude: Latitude of the location. :param longitude: Longitude of the location. :param reply: Message object or message_id to reply to. :param on_success: Callback to call when call is complete. :type r...
Below is the the instruction that describes the task: ### Input: Send location to peer. :param peer: Peer to send message to. :param latitude: Latitude of the location. :param longitude: Longitude of the location. :param reply: Message object or message_id to reply to. :param...
def tisbod(ref, body, et): """ Return a 6x6 matrix that transforms states in inertial coordinates to states in body-equator-and-prime-meridian coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tisbod_c.html :param ref: ID of inertial reference frame to transform from. :type ...
Return a 6x6 matrix that transforms states in inertial coordinates to states in body-equator-and-prime-meridian coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tisbod_c.html :param ref: ID of inertial reference frame to transform from. :type ref: str :param body: ID code of bo...
Below is the the instruction that describes the task: ### Input: Return a 6x6 matrix that transforms states in inertial coordinates to states in body-equator-and-prime-meridian coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tisbod_c.html :param ref: ID of inertial reference frame...
def load(obj, env=None, silent=None, key=None): """Reads and loads in to "settings" a single key or all keys from vault :param obj: the settings instance :param env: settings env default='DYNACONF' :param silent: if errors should raise :param key: if defined load a single key, else load all in env ...
Reads and loads in to "settings" a single key or all keys from vault :param obj: the settings instance :param env: settings env default='DYNACONF' :param silent: if errors should raise :param key: if defined load a single key, else load all in env :return: None
Below is the the instruction that describes the task: ### Input: Reads and loads in to "settings" a single key or all keys from vault :param obj: the settings instance :param env: settings env default='DYNACONF' :param silent: if errors should raise :param key: if defined load a single key, else lo...
def __copyfile(source, destination): """Copy data and mode bits ("cp source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bool: True if the operation...
Copy data and mode bits ("cp source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bool: True if the operation is successful, False otherwise.
Below is the the instruction that describes the task: ### Input: Copy data and mode bits ("cp source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bo...
def find_session(self, session_name): """Finds guest sessions by their friendly name and returns an interface array with all found guest sessions. in session_name of type str The session's friendly name to find. Wildcards like ? and * are allowed. return sessions of type :c...
Finds guest sessions by their friendly name and returns an interface array with all found guest sessions. in session_name of type str The session's friendly name to find. Wildcards like ? and * are allowed. return sessions of type :class:`IGuestSession` Array with all g...
Below is the the instruction that describes the task: ### Input: Finds guest sessions by their friendly name and returns an interface array with all found guest sessions. in session_name of type str The session's friendly name to find. Wildcards like ? and * are allowed. return...
def get_posix(self, i): """Get POSIX.""" index = i.index value = ['['] try: c = next(i) if c != ':': raise ValueError('Not a valid property!') else: value.append(c) c = next(i) if c == '^...
Get POSIX.
Below is the the instruction that describes the task: ### Input: Get POSIX. ### Response: def get_posix(self, i): """Get POSIX.""" index = i.index value = ['['] try: c = next(i) if c != ':': raise ValueError('Not a valid property!') ...
def pad_sentences(sentences, padding_word="</s>"): """Pads all sentences to the same length. The length is defined by the longest sentence. Returns padded sentences. """ sequence_length = max(len(x) for x in sentences) padded_sentences = [] for i, sentence in enumerate(sentences): num_pa...
Pads all sentences to the same length. The length is defined by the longest sentence. Returns padded sentences.
Below is the the instruction that describes the task: ### Input: Pads all sentences to the same length. The length is defined by the longest sentence. Returns padded sentences. ### Response: def pad_sentences(sentences, padding_word="</s>"): """Pads all sentences to the same length. The length is defined b...
def EMetaclass(cls): """Class decorator for creating PyEcore metaclass.""" superclass = cls.__bases__ if not issubclass(cls, EObject): sclasslist = list(superclass) if object in superclass: index = sclasslist.index(object) sclasslist.insert(index, EObject) ...
Class decorator for creating PyEcore metaclass.
Below is the the instruction that describes the task: ### Input: Class decorator for creating PyEcore metaclass. ### Response: def EMetaclass(cls): """Class decorator for creating PyEcore metaclass.""" superclass = cls.__bases__ if not issubclass(cls, EObject): sclasslist = list(superclass) ...
def export_dse_home_in_dse_env_sh(self): ''' Due to the way CCM lays out files, separating the repository from the node(s) confs, the `dse-env.sh` script of each node needs to have its DSE_HOME var set and exported. Since DSE 4.5.x, the stock `dse-env.sh` file includes a commente...
Due to the way CCM lays out files, separating the repository from the node(s) confs, the `dse-env.sh` script of each node needs to have its DSE_HOME var set and exported. Since DSE 4.5.x, the stock `dse-env.sh` file includes a commented-out place to do exactly this, intended for installe...
Below is the the instruction that describes the task: ### Input: Due to the way CCM lays out files, separating the repository from the node(s) confs, the `dse-env.sh` script of each node needs to have its DSE_HOME var set and exported. Since DSE 4.5.x, the stock `dse-env.sh` file includes a ...
def postprocess(self): """Submit a postprocessing script after collation""" assert self.postscript envmod.setup() envmod.module('load', 'pbs') cmd = 'qsub {script}'.format(script=self.postscript) cmd = shlex.split(cmd) rc = sp.call(cmd) assert rc == 0, '...
Submit a postprocessing script after collation
Below is the the instruction that describes the task: ### Input: Submit a postprocessing script after collation ### Response: def postprocess(self): """Submit a postprocessing script after collation""" assert self.postscript envmod.setup() envmod.module('load', 'pbs') cmd =...
def check_support_ucannet(cls, hw_info_ex): """ Checks whether the module supports the usage of USB-CANnetwork driver. :param HardwareInfoEx hw_info_ex: Extended hardware information structure (see method :meth:`get_hardware_info`). :return: True when the module does support...
Checks whether the module supports the usage of USB-CANnetwork driver. :param HardwareInfoEx hw_info_ex: Extended hardware information structure (see method :meth:`get_hardware_info`). :return: True when the module does support the usage of the USB-CANnetwork driver, otherwise False. ...
Below is the the instruction that describes the task: ### Input: Checks whether the module supports the usage of USB-CANnetwork driver. :param HardwareInfoEx hw_info_ex: Extended hardware information structure (see method :meth:`get_hardware_info`). :return: True when the module does su...
def img2ascii(img_path, ascii_path, ascii_char="*", pad=0): """Convert an image to ascii art text. Suppose we have an image like that: .. image:: images/rabbit.png :align: left Put some codes:: >>> from weatherlab.math.img2waveform import img2ascii >>> img2ascii(r"testdata\im...
Convert an image to ascii art text. Suppose we have an image like that: .. image:: images/rabbit.png :align: left Put some codes:: >>> from weatherlab.math.img2waveform import img2ascii >>> img2ascii(r"testdata\img2waveform\rabbit.png", ... r"testdata\img2wavef...
Below is the the instruction that describes the task: ### Input: Convert an image to ascii art text. Suppose we have an image like that: .. image:: images/rabbit.png :align: left Put some codes:: >>> from weatherlab.math.img2waveform import img2ascii >>> img2ascii(r"testdata\...
def verifies( self, hash, signature ): """Verify that signature is a valid signature of hash. Return True if the signature is valid. """ # From X9.62 J.3.1. G = self.generator n = G.order() r = signature.r s = signature.s if r < 1 or r > n-1: return False if s < 1 or s > n-1: r...
Verify that signature is a valid signature of hash. Return True if the signature is valid.
Below is the the instruction that describes the task: ### Input: Verify that signature is a valid signature of hash. Return True if the signature is valid. ### Response: def verifies( self, hash, signature ): """Verify that signature is a valid signature of hash. Return True if the signature is valid. ...
def _detect_start_end(true_values): """From ndarray of bool values, return intervals of True values. Parameters ---------- true_values : ndarray (dtype='bool') array with bool values Returns ------- ndarray (dtype='int') N x 2 matrix with starting and ending times. """ ...
From ndarray of bool values, return intervals of True values. Parameters ---------- true_values : ndarray (dtype='bool') array with bool values Returns ------- ndarray (dtype='int') N x 2 matrix with starting and ending times.
Below is the the instruction that describes the task: ### Input: From ndarray of bool values, return intervals of True values. Parameters ---------- true_values : ndarray (dtype='bool') array with bool values Returns ------- ndarray (dtype='int') N x 2 matrix with starting ...
def isPythonFile(filename): """Return True if filename points to a Python file.""" if filename.endswith('.py'): return True # Avoid obvious Emacs backup files if filename.endswith("~"): return False max_bytes = 128 try: with open(filename, 'rb') as f: text ...
Return True if filename points to a Python file.
Below is the the instruction that describes the task: ### Input: Return True if filename points to a Python file. ### Response: def isPythonFile(filename): """Return True if filename points to a Python file.""" if filename.endswith('.py'): return True # Avoid obvious Emacs backup files if ...
def reftrack_status_data(rt, role): """Return the data for the status :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the status :rtype: de...
Return the data for the status :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the status :rtype: depending on role :raises: None
Below is the the instruction that describes the task: ### Input: Return the data for the status :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for...
def needs_encode(obj): ''' >>> from re import compile >>> atomics = (True, 1, 1.0, '', None, compile(''), datetime.now(), b'') >>> any(needs_encode(i) for i in atomics) False >>> needs_encode([1, 2, 3]) False >>> needs_encode([]) False >>> needs_encode([1, [2, 3]]) False ...
>>> from re import compile >>> atomics = (True, 1, 1.0, '', None, compile(''), datetime.now(), b'') >>> any(needs_encode(i) for i in atomics) False >>> needs_encode([1, 2, 3]) False >>> needs_encode([]) False >>> needs_encode([1, [2, 3]]) False >>> needs_encode({}) False ...
Below is the the instruction that describes the task: ### Input: >>> from re import compile >>> atomics = (True, 1, 1.0, '', None, compile(''), datetime.now(), b'') >>> any(needs_encode(i) for i in atomics) False >>> needs_encode([1, 2, 3]) False >>> needs_encode([]) False >>> needs_...