code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def get_os_instances(): """ :return: all knows OS instance """ LOGGER.debug("OSInstanceService.get_os_instances") args = {'http_operation': 'GET', 'operation_path': ''} response = OSInstanceService.requester.call(args) ret = None if response.rc == 0: ...
:return: all knows OS instance
Below is the the instruction that describes the task: ### Input: :return: all knows OS instance ### Response: def get_os_instances(): """ :return: all knows OS instance """ LOGGER.debug("OSInstanceService.get_os_instances") args = {'http_operation': 'GET', 'operation_path': ...
def _decrypt(cipher, key, data, iv, padding): """ Decrypts AES/RC4/RC2/3DES/DES ciphertext :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: ...
Decrypts AES/RC4/RC2/3DES/DES ciphertext :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :param iv: The...
Below is the the instruction that describes the task: ### Input: Decrypts AES/RC4/RC2/3DES/DES ciphertext :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param dat...
def apply_substitutions(monomial, monomial_substitutions, pure=False): """Helper function to remove monomials from the basis.""" if is_number_type(monomial): return monomial original_monomial = monomial changed = True if not pure: substitutions = monomial_substitutions else: ...
Helper function to remove monomials from the basis.
Below is the the instruction that describes the task: ### Input: Helper function to remove monomials from the basis. ### Response: def apply_substitutions(monomial, monomial_substitutions, pure=False): """Helper function to remove monomials from the basis.""" if is_number_type(monomial): return mon...
def sequence_edit_distance(predictions, labels, weights_fn=common_layers.weights_nonzero): """Average edit distance, ignoring padding 0s. The score returned is the edit distance divided by the total length of reference truth and the weight returned is the tot...
Average edit distance, ignoring padding 0s. The score returned is the edit distance divided by the total length of reference truth and the weight returned is the total length of the truth. Args: predictions: Tensor of shape [`batch_size`, `length`, 1, `num_classes`] and type tf.float32 representing ...
Below is the the instruction that describes the task: ### Input: Average edit distance, ignoring padding 0s. The score returned is the edit distance divided by the total length of reference truth and the weight returned is the total length of the truth. Args: predictions: Tensor of shape [`batch_size`, ...
def sodium_add(a, b): """ Given a couple of *same-sized* byte sequences, interpreted as the little-endian representation of two unsigned integers, compute the modular addition of the represented values, in constant time for a given common length of the byte sequences. :param a: input bytes buff...
Given a couple of *same-sized* byte sequences, interpreted as the little-endian representation of two unsigned integers, compute the modular addition of the represented values, in constant time for a given common length of the byte sequences. :param a: input bytes buffer :type a: bytes :param b...
Below is the the instruction that describes the task: ### Input: Given a couple of *same-sized* byte sequences, interpreted as the little-endian representation of two unsigned integers, compute the modular addition of the represented values, in constant time for a given common length of the byte sequenc...
def _create_delta(self): """ This function creates the delta transition Args: startState (int): Initial state of automaton Results: int, func: A number indicating the total states, and the delta function """ states = self._read_transitions() ...
This function creates the delta transition Args: startState (int): Initial state of automaton Results: int, func: A number indicating the total states, and the delta function
Below is the the instruction that describes the task: ### Input: This function creates the delta transition Args: startState (int): Initial state of automaton Results: int, func: A number indicating the total states, and the delta function ### Response: def _create_delta(sel...
def created(self): """Union[datetime.datetime, None]: Datetime at which the dataset was created (:data:`None` until set from the server). """ creation_time = self._properties.get("creationTime") if creation_time is not None: # creation_time will be in milliseconds. ...
Union[datetime.datetime, None]: Datetime at which the dataset was created (:data:`None` until set from the server).
Below is the the instruction that describes the task: ### Input: Union[datetime.datetime, None]: Datetime at which the dataset was created (:data:`None` until set from the server). ### Response: def created(self): """Union[datetime.datetime, None]: Datetime at which the dataset was created ...
def resource_filename(package_or_requirement, resource_name): """ Similar to pkg_resources.resource_filename but if the resource it not found via pkg_resources it also looks in a predefined list of paths in order to find the resource :param package_or_requirement: the module in which the resource resid...
Similar to pkg_resources.resource_filename but if the resource it not found via pkg_resources it also looks in a predefined list of paths in order to find the resource :param package_or_requirement: the module in which the resource resides :param resource_name: the name of the resource :return: the pat...
Below is the the instruction that describes the task: ### Input: Similar to pkg_resources.resource_filename but if the resource it not found via pkg_resources it also looks in a predefined list of paths in order to find the resource :param package_or_requirement: the module in which the resource resides ...
async def get_offers(connection: Connection) -> dict: """ Retrieves all pending credential offers for a given connection. :param connection: A connection handle :return: A list of dictionary objects representing offers from a given connection. Example: credential = await ...
Retrieves all pending credential offers for a given connection. :param connection: A connection handle :return: A list of dictionary objects representing offers from a given connection. Example: credential = await Credential.create_with_msgid(source_id, connection, msg_id) offers...
Below is the the instruction that describes the task: ### Input: Retrieves all pending credential offers for a given connection. :param connection: A connection handle :return: A list of dictionary objects representing offers from a given connection. Example: credential = await Crede...
def _check_enclosing_characters(string, opener, closer): """ Makes sure that the enclosing characters for a definition set make sense 1) There is only one set 2) They are in the right order (opening, then closing) """ opener_count = string.count(opener) closer_count = string.count(closer) ...
Makes sure that the enclosing characters for a definition set make sense 1) There is only one set 2) They are in the right order (opening, then closing)
Below is the the instruction that describes the task: ### Input: Makes sure that the enclosing characters for a definition set make sense 1) There is only one set 2) They are in the right order (opening, then closing) ### Response: def _check_enclosing_characters(string, opener, closer): """ Makes ...
def str_append_hash(*args): """ Convert each argument to a lower case string, appended, then hash """ ret_hash = "" for i in args: ret_hash += str(i).lower() return hash(ret_hash)
Convert each argument to a lower case string, appended, then hash
Below is the the instruction that describes the task: ### Input: Convert each argument to a lower case string, appended, then hash ### Response: def str_append_hash(*args): """ Convert each argument to a lower case string, appended, then hash """ ret_hash = "" for i in args: ret_hash += str(i)....
def MSR(self, params): """ MSR Rspecial, Rj Copy the value of Rj to Rspecial Rspecial can be APSR, IPSR, or EPSR """ Rspecial, Rj = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) self.check_arguments(LR_or_general_purpose_registers=(Rj,), sp...
MSR Rspecial, Rj Copy the value of Rj to Rspecial Rspecial can be APSR, IPSR, or EPSR
Below is the the instruction that describes the task: ### Input: MSR Rspecial, Rj Copy the value of Rj to Rspecial Rspecial can be APSR, IPSR, or EPSR ### Response: def MSR(self, params): """ MSR Rspecial, Rj Copy the value of Rj to Rspecial Rspecial can be APSR, I...
def square_order_matrix(usl_list): """ Compute the ordering of a list of usls from each usl and return the matrix m s.t. for each u in usl_list at index i, [usl_list[j] for j in m[i, :]] is the list sorted by proximity from u. of the result :param usl_list: a list of usls :return: a (len(us...
Compute the ordering of a list of usls from each usl and return the matrix m s.t. for each u in usl_list at index i, [usl_list[j] for j in m[i, :]] is the list sorted by proximity from u. of the result :param usl_list: a list of usls :return: a (len(usl_list), len(usl_list)) np.array
Below is the the instruction that describes the task: ### Input: Compute the ordering of a list of usls from each usl and return the matrix m s.t. for each u in usl_list at index i, [usl_list[j] for j in m[i, :]] is the list sorted by proximity from u. of the result :param usl_list: a list of usls ...
def create(verbose): """Create tables.""" click.secho('Creating all tables!', fg='yellow', bold=True) with click.progressbar(_db.metadata.sorted_tables) as bar: for table in bar: if verbose: click.echo(' Creating table {0}'.format(table)) table.create(bind=_db...
Create tables.
Below is the the instruction that describes the task: ### Input: Create tables. ### Response: def create(verbose): """Create tables.""" click.secho('Creating all tables!', fg='yellow', bold=True) with click.progressbar(_db.metadata.sorted_tables) as bar: for table in bar: if verbose...
def _install_production_config(self): """ Download the production configuration and install it in the current directory. """ # We initiate the link to the production configuration. # It is not hard coded because this method is called only if we # are sure that th...
Download the production configuration and install it in the current directory.
Below is the the instruction that describes the task: ### Input: Download the production configuration and install it in the current directory. ### Response: def _install_production_config(self): """ Download the production configuration and install it in the current directory. ...
def page_view(url): """ Page view decorator. Put that around a state handler function in order to log a page view each time the handler gets called. :param url: simili-URL that you want to give to the state """ def decorator(func): @wraps(func) async def wrapper(self: Base...
Page view decorator. Put that around a state handler function in order to log a page view each time the handler gets called. :param url: simili-URL that you want to give to the state
Below is the the instruction that describes the task: ### Input: Page view decorator. Put that around a state handler function in order to log a page view each time the handler gets called. :param url: simili-URL that you want to give to the state ### Response: def page_view(url): """ Page vi...
def nodes(self, nodes): """Specify the set of nodes and associated data. Must include any nodes referenced in the edge list. :param nodes: Nodes and their attributes. :type point_size: Pandas dataframe :returns: Plotter. :rtype: Plotter. **Example** ...
Specify the set of nodes and associated data. Must include any nodes referenced in the edge list. :param nodes: Nodes and their attributes. :type point_size: Pandas dataframe :returns: Plotter. :rtype: Plotter. **Example** :: import graphi...
Below is the the instruction that describes the task: ### Input: Specify the set of nodes and associated data. Must include any nodes referenced in the edge list. :param nodes: Nodes and their attributes. :type point_size: Pandas dataframe :returns: Plotter. :rtype: Plotte...
def _emit_search_criteria(user_ids, job_ids, task_ids, labels): """Print the filters used to delete tasks. Use raw flags as arguments.""" print('Delete running jobs:') print(' user:') print(' %s\n' % user_ids) print(' job-id:') print(' %s\n' % job_ids) if task_ids: print(' task-id:') prin...
Print the filters used to delete tasks. Use raw flags as arguments.
Below is the the instruction that describes the task: ### Input: Print the filters used to delete tasks. Use raw flags as arguments. ### Response: def _emit_search_criteria(user_ids, job_ids, task_ids, labels): """Print the filters used to delete tasks. Use raw flags as arguments.""" print('Delete running jobs...
def get_repositories(self, project=None, include_links=None, include_all_urls=None, include_hidden=None): """GetRepositories. [Preview API] Retrieve git repositories. :param str project: Project ID or project name :param bool include_links: [optional] True to include reference links. The...
GetRepositories. [Preview API] Retrieve git repositories. :param str project: Project ID or project name :param bool include_links: [optional] True to include reference links. The default value is false. :param bool include_all_urls: [optional] True to include all remote URLs. The defaul...
Below is the the instruction that describes the task: ### Input: GetRepositories. [Preview API] Retrieve git repositories. :param str project: Project ID or project name :param bool include_links: [optional] True to include reference links. The default value is false. :param bool inc...
def assert_credentials_match(self, verifier, authc_token, account): """ :type verifier: authc_abcs.CredentialsVerifier :type authc_token: authc_abcs.AuthenticationToken :type account: account_abcs.Account :returns: account_abcs.Account :raises IncorrectCredentialsExcepti...
:type verifier: authc_abcs.CredentialsVerifier :type authc_token: authc_abcs.AuthenticationToken :type account: account_abcs.Account :returns: account_abcs.Account :raises IncorrectCredentialsException: when authentication fails, includin...
Below is the the instruction that describes the task: ### Input: :type verifier: authc_abcs.CredentialsVerifier :type authc_token: authc_abcs.AuthenticationToken :type account: account_abcs.Account :returns: account_abcs.Account :raises IncorrectCredentialsException: when authentic...
def get_channel_image(self, channel, img_size=300, skip_cache=False): """Get the logo for a channel""" from bs4 import BeautifulSoup from wikipedia.exceptions import PageError import re import wikipedia wikipedia.set_lang('fr') if not channel: _LOGGER...
Get the logo for a channel
Below is the the instruction that describes the task: ### Input: Get the logo for a channel ### Response: def get_channel_image(self, channel, img_size=300, skip_cache=False): """Get the logo for a channel""" from bs4 import BeautifulSoup from wikipedia.exceptions import PageError i...
def write_hex(fout, buf, offset, width=16): """Write the content of 'buf' out in a hexdump style Args: fout: file object to write to buf: the buffer to be pretty printed offset: the starting offset of the buffer width: how many bytes should be displayed per row """ skip...
Write the content of 'buf' out in a hexdump style Args: fout: file object to write to buf: the buffer to be pretty printed offset: the starting offset of the buffer width: how many bytes should be displayed per row
Below is the the instruction that describes the task: ### Input: Write the content of 'buf' out in a hexdump style Args: fout: file object to write to buf: the buffer to be pretty printed offset: the starting offset of the buffer width: how many bytes should be displayed per row...
def process(self, metric): """ Process a metric by sending it to TSDB """ entry = {'timestamp': metric.timestamp, 'value': metric.value, "tags": {}} entry["tags"]["hostname"] = metric.host if self.cleanMetrics: metric = MetricWrapper(metric, ...
Process a metric by sending it to TSDB
Below is the the instruction that describes the task: ### Input: Process a metric by sending it to TSDB ### Response: def process(self, metric): """ Process a metric by sending it to TSDB """ entry = {'timestamp': metric.timestamp, 'value': metric.value, "tags": {}}...
def _endswith(expr, pat): """ Return boolean sequence or scalar indicating whether each string in the sequence or scalar ends with passed pattern. Equivalent to str.endswith(). :param expr: :param pat: Character sequence :return: sequence or scalar """ return _string_op(expr, Endswith,...
Return boolean sequence or scalar indicating whether each string in the sequence or scalar ends with passed pattern. Equivalent to str.endswith(). :param expr: :param pat: Character sequence :return: sequence or scalar
Below is the the instruction that describes the task: ### Input: Return boolean sequence or scalar indicating whether each string in the sequence or scalar ends with passed pattern. Equivalent to str.endswith(). :param expr: :param pat: Character sequence :return: sequence or scalar ### Response: ...
def encode_type(primary_type, types): """ The type of a struct is encoded as name ‖ "(" ‖ member₁ ‖ "," ‖ member₂ ‖ "," ‖ … ‖ memberₙ ")" where each member is written as type ‖ " " ‖ name. """ # Getting the dependencies and sorting them alphabetically as per EIP712 deps = get_dependencies(primar...
The type of a struct is encoded as name ‖ "(" ‖ member₁ ‖ "," ‖ member₂ ‖ "," ‖ … ‖ memberₙ ")" where each member is written as type ‖ " " ‖ name.
Below is the the instruction that describes the task: ### Input: The type of a struct is encoded as name ‖ "(" ‖ member₁ ‖ "," ‖ member₂ ‖ "," ‖ … ‖ memberₙ ")" where each member is written as type ‖ " " ‖ name. ### Response: def encode_type(primary_type, types): """ The type of a struct is encoded as ...
def create(zone, brand, zonepath, force=False): ''' Create an in-memory configuration for the specified zone. zone : string name of zone brand : string brand name zonepath : string path of zone force : boolean overwrite configuration CLI Example: .. cod...
Create an in-memory configuration for the specified zone. zone : string name of zone brand : string brand name zonepath : string path of zone force : boolean overwrite configuration CLI Example: .. code-block:: bash salt '*' zonecfg.create deathscythe ...
Below is the the instruction that describes the task: ### Input: Create an in-memory configuration for the specified zone. zone : string name of zone brand : string brand name zonepath : string path of zone force : boolean overwrite configuration CLI Example: ...
def _delete_service_nwk(self, tenant_id, tenant_name, direc): """Function to delete the service in network in DCNM. """ net_dict = {} if direc == 'in': seg, vlan = self.get_in_seg_vlan(tenant_id) net_dict['part_name'] = None else: seg, vlan = self.get_...
Function to delete the service in network in DCNM.
Below is the the instruction that describes the task: ### Input: Function to delete the service in network in DCNM. ### Response: def _delete_service_nwk(self, tenant_id, tenant_name, direc): """Function to delete the service in network in DCNM. """ net_dict = {} if direc == 'in': ...
def parse_play_details(details): """Parses play details from play-by-play string and returns structured data. :details: detail string for play :returns: dictionary of play attributes """ # if input isn't a string, return None if not isinstance(details, basestring): return None ...
Parses play details from play-by-play string and returns structured data. :details: detail string for play :returns: dictionary of play attributes
Below is the the instruction that describes the task: ### Input: Parses play details from play-by-play string and returns structured data. :details: detail string for play :returns: dictionary of play attributes ### Response: def parse_play_details(details): """Parses play details from play-by-pla...
def close(self, destroy=False, sync=False): """Close PV, disconnecting any clients. :param bool destroy: Indicate "permanent" closure. Current clients will not see subsequent open(). :param bool sync: When block until any pending onLastDisconnect() is delivered (timeout applies). :para...
Close PV, disconnecting any clients. :param bool destroy: Indicate "permanent" closure. Current clients will not see subsequent open(). :param bool sync: When block until any pending onLastDisconnect() is delivered (timeout applies). :param float timeout: Applies only when sync=True. None for...
Below is the the instruction that describes the task: ### Input: Close PV, disconnecting any clients. :param bool destroy: Indicate "permanent" closure. Current clients will not see subsequent open(). :param bool sync: When block until any pending onLastDisconnect() is delivered (timeout applies)....
def sum(self, axis): """Sums all data along axis, returns d-1 dimensional histogram""" axis = self.get_axis_number(axis) if self.dimensions == 2: new_hist = Hist1d else: new_hist = Histdd return new_hist.from_histogram(np.sum(self.histogram, axis=axis), ...
Sums all data along axis, returns d-1 dimensional histogram
Below is the the instruction that describes the task: ### Input: Sums all data along axis, returns d-1 dimensional histogram ### Response: def sum(self, axis): """Sums all data along axis, returns d-1 dimensional histogram""" axis = self.get_axis_number(axis) if self.dimensions == 2: ...
def file_response(request, filepath, block=None, status_code=None, content_type=None, encoding=None, cache_control=None): """Utility for serving a local file Typical usage:: from pulsar.apps import wsgi class MyRouter(wsgi.Router): def get(self, request): ...
Utility for serving a local file Typical usage:: from pulsar.apps import wsgi class MyRouter(wsgi.Router): def get(self, request): return wsgi.file_response(request, "<filepath>") :param request: Wsgi request :param filepath: full path of file to serve :p...
Below is the the instruction that describes the task: ### Input: Utility for serving a local file Typical usage:: from pulsar.apps import wsgi class MyRouter(wsgi.Router): def get(self, request): return wsgi.file_response(request, "<filepath>") :param request...
def update_network(cx_str, network_id, ndex_cred=None): """Update an existing CX network on NDEx with new CX content. Parameters ---------- cx_str : str String containing the CX content. network_id : str UUID of the network on NDEx. ndex_cred : dict A dictionary with the...
Update an existing CX network on NDEx with new CX content. Parameters ---------- cx_str : str String containing the CX content. network_id : str UUID of the network on NDEx. ndex_cred : dict A dictionary with the following entries: 'user': NDEx user name 'pas...
Below is the the instruction that describes the task: ### Input: Update an existing CX network on NDEx with new CX content. Parameters ---------- cx_str : str String containing the CX content. network_id : str UUID of the network on NDEx. ndex_cred : dict A dictionary wi...
def parse_subject(content, reference_id=None, clean=True): """\ Parses and returns the subject of a cable. If the cable has no subject, an empty string is returned. `content` The cable's content. `reference_id` The (optional) reference id of the cable. Used for error msgs `c...
\ Parses and returns the subject of a cable. If the cable has no subject, an empty string is returned. `content` The cable's content. `reference_id` The (optional) reference id of the cable. Used for error msgs `clean` Indicates if classification prefixes like ``(S)`` sh...
Below is the the instruction that describes the task: ### Input: \ Parses and returns the subject of a cable. If the cable has no subject, an empty string is returned. `content` The cable's content. `reference_id` The (optional) reference id of the cable. Used for error msgs ...
def parse(fileobject, schema=None): """Parses a file object This functon parses a KML file object, and optionally validates it against a provided schema. """ if schema: # with validation parser = objectify.makeparser(schema = schema.schema, strip_cdata=False) return obj...
Parses a file object This functon parses a KML file object, and optionally validates it against a provided schema.
Below is the the instruction that describes the task: ### Input: Parses a file object This functon parses a KML file object, and optionally validates it against a provided schema. ### Response: def parse(fileobject, schema=None): """Parses a file object This functon parses a KML file obj...
def create_payment_card(cls, payment_card, **kwargs): """Create PaymentCard Create a new PaymentCard This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_payment_card(payment_card, async=Tru...
Create PaymentCard Create a new PaymentCard This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_payment_card(payment_card, async=True) >>> result = thread.get() :param async bool ...
Below is the the instruction that describes the task: ### Input: Create PaymentCard Create a new PaymentCard This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_payment_card(payment_card, async...
def _config(name, conf, default=None): ''' Return a value for 'name' from the config file options. If the 'name' is not in the config, the 'default' value is returned. This method converts unicode values to str type under python 2. ''' try: value = conf[name] except KeyError: ...
Return a value for 'name' from the config file options. If the 'name' is not in the config, the 'default' value is returned. This method converts unicode values to str type under python 2.
Below is the the instruction that describes the task: ### Input: Return a value for 'name' from the config file options. If the 'name' is not in the config, the 'default' value is returned. This method converts unicode values to str type under python 2. ### Response: def _config(name, conf, default=None): ...
def _convertEntities(self, match): """Used in a call to re.sub to replace HTML, XML, and numeric entities with the appropriate Unicode characters. If HTML entities are being converted, any unrecognized entities are escaped.""" x = match.group(1) if self.convertHTMLEntitie...
Used in a call to re.sub to replace HTML, XML, and numeric entities with the appropriate Unicode characters. If HTML entities are being converted, any unrecognized entities are escaped.
Below is the the instruction that describes the task: ### Input: Used in a call to re.sub to replace HTML, XML, and numeric entities with the appropriate Unicode characters. If HTML entities are being converted, any unrecognized entities are escaped. ### Response: def _convertEntities(self,...
def readinto(self, buf): """Zero-copy read directly into buffer.""" got = 0 vbuf = memoryview(buf) while got < len(buf): # next vol needed? if self._cur_avail == 0: if not self._open_next(): break # length for next ...
Zero-copy read directly into buffer.
Below is the the instruction that describes the task: ### Input: Zero-copy read directly into buffer. ### Response: def readinto(self, buf): """Zero-copy read directly into buffer.""" got = 0 vbuf = memoryview(buf) while got < len(buf): # next vol needed? if ...
def get_events(self, login=None, start_date=None, end_date=None, **kwargs): """Get a user's events. :param str login: User's login (Default: self._login) :param str start_date: Start date :param str end_date: To date :return: JSON """ _login = kwargs.get( ...
Get a user's events. :param str login: User's login (Default: self._login) :param str start_date: Start date :param str end_date: To date :return: JSON
Below is the the instruction that describes the task: ### Input: Get a user's events. :param str login: User's login (Default: self._login) :param str start_date: Start date :param str end_date: To date :return: JSON ### Response: def get_events(self, login=None, start_date=None, e...
def switch_to_plain_text(self): """Switch to plain text mode""" self.rich_help = False self.plain_text.show() self.rich_text.hide() self.plain_text_action.setChecked(True)
Switch to plain text mode
Below is the the instruction that describes the task: ### Input: Switch to plain text mode ### Response: def switch_to_plain_text(self): """Switch to plain text mode""" self.rich_help = False self.plain_text.show() self.rich_text.hide() self.plain_text_action.setChecked...
def plot_best(trace=None, data_train=None, data_test=None, samples=1000, burn=200, axs=None): """ Plot BEST significance analysis. Parameters ---------- trace : pymc3.sampling.BaseTrace, optional trace object as returned by model_best() If not passed, will run model_be...
Plot BEST significance analysis. Parameters ---------- trace : pymc3.sampling.BaseTrace, optional trace object as returned by model_best() If not passed, will run model_best(), for which data_train and data_test are required. data_train : pandas.Series, optional Returns ...
Below is the the instruction that describes the task: ### Input: Plot BEST significance analysis. Parameters ---------- trace : pymc3.sampling.BaseTrace, optional trace object as returned by model_best() If not passed, will run model_best(), for which data_train and data_test ar...
def GetNewEventId(self, event_time=None): """Return a unique Event ID string.""" if event_time is None: event_time = int(time.time() * 1e6) return "%s:%s:%s" % (event_time, socket.gethostname(), os.getpid())
Return a unique Event ID string.
Below is the the instruction that describes the task: ### Input: Return a unique Event ID string. ### Response: def GetNewEventId(self, event_time=None): """Return a unique Event ID string.""" if event_time is None: event_time = int(time.time() * 1e6) return "%s:%s:%s" % (event_time, socket.geth...
def replace(name, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', show_changes=True, ignore_if_mis...
r''' Maintain an edit in a file. .. versionadded:: 0.17.0 name Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be matched using Python's :py:func:`re.search`. .. note:: ...
Below is the the instruction that describes the task: ### Input: r''' Maintain an edit in a file. .. versionadded:: 0.17.0 name Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be match...
def uplink_receive(self, stanza): """Handle stanza received from the stream.""" with self.lock: if self.stanza_route: self.stanza_route.uplink_receive(stanza) else: logger.debug(u"Stanza dropped (no route): {0!r}".format(stanza))
Handle stanza received from the stream.
Below is the the instruction that describes the task: ### Input: Handle stanza received from the stream. ### Response: def uplink_receive(self, stanza): """Handle stanza received from the stream.""" with self.lock: if self.stanza_route: self.stanza_route.uplink_receive(s...
def upload_intercom_user(obj_id): """Creates or updates single user account on intercom""" UserModel = get_user_model() intercom_user = False instance = UserModel.objects.get(pk=obj_id) data = instance.get_intercom_data() if not getattr(settings, "SKIP_INTERCOM", False): try: ...
Creates or updates single user account on intercom
Below is the the instruction that describes the task: ### Input: Creates or updates single user account on intercom ### Response: def upload_intercom_user(obj_id): """Creates or updates single user account on intercom""" UserModel = get_user_model() intercom_user = False instance = UserModel.object...
async def get_users(self): """Get Tautulli users.""" cmd = 'get_users' url = self.base_url + cmd users = [] try: async with async_timeout.timeout(8, loop=self._loop): response = await self._session.get(url) logger("Status from Tautulli: " ...
Get Tautulli users.
Below is the the instruction that describes the task: ### Input: Get Tautulli users. ### Response: async def get_users(self): """Get Tautulli users.""" cmd = 'get_users' url = self.base_url + cmd users = [] try: async with async_timeout.timeout(8, loop=self._loop...
def kube_node_status_network_unavailable(self, metric, scraper_config): """ Whether the node is in a network unavailable state (legacy)""" service_check_name = scraper_config['namespace'] + '.node.network_unavailable' for sample in metric.samples: node_tag = self._label_to_tag("node"...
Whether the node is in a network unavailable state (legacy)
Below is the the instruction that describes the task: ### Input: Whether the node is in a network unavailable state (legacy) ### Response: def kube_node_status_network_unavailable(self, metric, scraper_config): """ Whether the node is in a network unavailable state (legacy)""" service_check_name = ...
def client_list(self, name=None, name_only=None, all_enrolled=None): """ Get list of clients. Uses GET to /clients interface. :Kwargs: * *name*: (str) If specified, returns the client information for this client only. * *name_only*: (bool) If true, returns only the names of...
Get list of clients. Uses GET to /clients interface. :Kwargs: * *name*: (str) If specified, returns the client information for this client only. * *name_only*: (bool) If true, returns only the names of the clients requested * *all_enrolled*: (bool) If true, will return all enroll...
Below is the the instruction that describes the task: ### Input: Get list of clients. Uses GET to /clients interface. :Kwargs: * *name*: (str) If specified, returns the client information for this client only. * *name_only*: (bool) If true, returns only the names of the clients request...
def defaults(self_): """ Return {parameter_name:parameter.default} for all non-constant Parameters. Note that a Parameter for which instantiate==True has its default instantiated. """ self = self_.self d = {} for param_name,param in self.param.obj...
Return {parameter_name:parameter.default} for all non-constant Parameters. Note that a Parameter for which instantiate==True has its default instantiated.
Below is the the instruction that describes the task: ### Input: Return {parameter_name:parameter.default} for all non-constant Parameters. Note that a Parameter for which instantiate==True has its default instantiated. ### Response: def defaults(self_): """ Return {paramet...
def refresh_balance(self): """ Recalculate self.balance and self.depth based on child node values. """ left_depth = self.left_node.depth if self.left_node else 0 right_depth = self.right_node.depth if self.right_node else 0 self.depth = 1 + max(left_depth, right_depth) ...
Recalculate self.balance and self.depth based on child node values.
Below is the the instruction that describes the task: ### Input: Recalculate self.balance and self.depth based on child node values. ### Response: def refresh_balance(self): """ Recalculate self.balance and self.depth based on child node values. """ left_depth = self.left_node.depth...
def _create_mirror(self, resource_type, resource_name, target_name, mirror_type, slave_resource_name, create_slave='no', remote_pool=None, rpo=None, remote_rpo=None, schedule=None, remote_schedule=None, activate_mirror='no')...
creates a mirror and returns a mirror object. resource_type must be 'vol' or 'cg', target name must be a valid target from target_list, mirror type must be 'sync' or 'async', slave_resource_name would be the slave_vol or slave_cg name
Below is the the instruction that describes the task: ### Input: creates a mirror and returns a mirror object. resource_type must be 'vol' or 'cg', target name must be a valid target from target_list, mirror type must be 'sync' or 'async', slave_resource_name woul...
def udp_messenger(domain_name, UDP_IP, UDP_PORT, sock_timeout, message): """Send UDP messages to usage tracker asynchronously This multiprocessing based messenger was written to overcome the limitations of signalling/terminating a thread that is blocked on a system call. This messenger is created as a ...
Send UDP messages to usage tracker asynchronously This multiprocessing based messenger was written to overcome the limitations of signalling/terminating a thread that is blocked on a system call. This messenger is created as a separate process, and initialized with 2 queues, to_send to receive messages...
Below is the the instruction that describes the task: ### Input: Send UDP messages to usage tracker asynchronously This multiprocessing based messenger was written to overcome the limitations of signalling/terminating a thread that is blocked on a system call. This messenger is created as a separate pr...
def __make_request(self, url, method, data, auth, cookies, headers, proxies, timeout, verify): """Execute a request with the given data. Args: url (str): The URL to call. method (str): The method (e.g. `get` or `post`). data (str): The data to call the URL with. ...
Execute a request with the given data. Args: url (str): The URL to call. method (str): The method (e.g. `get` or `post`). data (str): The data to call the URL with. auth (obj): The authentication class. cookies (obj): The cookie dict. head...
Below is the the instruction that describes the task: ### Input: Execute a request with the given data. Args: url (str): The URL to call. method (str): The method (e.g. `get` or `post`). data (str): The data to call the URL with. auth (obj): The authenticatio...
def launch_ipython(argv=None): """ Force usage of QtConsole under Windows """ from .linux import launch_ipython as _launch_ipython_linux os.environ = {str(k): str(v) for k,v in os.environ.items()} try: from qtconsole.qtconsoleapp import JupyterQtConsoleApp except ImportError: ...
Force usage of QtConsole under Windows
Below is the the instruction that describes the task: ### Input: Force usage of QtConsole under Windows ### Response: def launch_ipython(argv=None): """ Force usage of QtConsole under Windows """ from .linux import launch_ipython as _launch_ipython_linux os.environ = {str(k): str(v) for k,v in ...
def to_dense(self): """ Convert SparseSeries to a Series. Returns ------- s : Series """ return Series(self.values.to_dense(), index=self.index, name=self.name)
Convert SparseSeries to a Series. Returns ------- s : Series
Below is the the instruction that describes the task: ### Input: Convert SparseSeries to a Series. Returns ------- s : Series ### Response: def to_dense(self): """ Convert SparseSeries to a Series. Returns ------- s : Series """ retu...
def share(self, base=None, keys=None, by=None, **kwargs): """ Share the formatoptions of one plotter with all the others This method shares specified formatoptions from `base` with all the plotters in this instance. Parameters ---------- base: None, Plotter, xar...
Share the formatoptions of one plotter with all the others This method shares specified formatoptions from `base` with all the plotters in this instance. Parameters ---------- base: None, Plotter, xarray.DataArray, InteractiveList, or list of them The source of the ...
Below is the the instruction that describes the task: ### Input: Share the formatoptions of one plotter with all the others This method shares specified formatoptions from `base` with all the plotters in this instance. Parameters ---------- base: None, Plotter, xarray.DataA...
def is_injective(self): '''Returns True if the mapping is injective (1-to-1).''' codomain_residues = [v.to_pdb_residue_id for k, v in self.mapping.iteritems()] return(len(codomain_residues) == len(set(codomain_residues)))
Returns True if the mapping is injective (1-to-1).
Below is the the instruction that describes the task: ### Input: Returns True if the mapping is injective (1-to-1). ### Response: def is_injective(self): '''Returns True if the mapping is injective (1-to-1).''' codomain_residues = [v.to_pdb_residue_id for k, v in self.mapping.iteritems()] r...
def _load_cookie(self): """Loads HTTP Cookie from environ""" cookie = SimpleCookie(self._environ.get('HTTP_COOKIE')) vishnu_keys = [key for key in cookie.keys() if key == self._config.cookie_name] # no session was started yet if not vishnu_keys: return mors...
Loads HTTP Cookie from environ
Below is the the instruction that describes the task: ### Input: Loads HTTP Cookie from environ ### Response: def _load_cookie(self): """Loads HTTP Cookie from environ""" cookie = SimpleCookie(self._environ.get('HTTP_COOKIE')) vishnu_keys = [key for key in cookie.keys() if key == self._con...
def assignIfExists(opts, default=None, **kwargs): """ Helper for assigning object attributes from API responses. """ for opt in opts: if(opt in kwargs): return kwargs[opt] return default
Helper for assigning object attributes from API responses.
Below is the the instruction that describes the task: ### Input: Helper for assigning object attributes from API responses. ### Response: def assignIfExists(opts, default=None, **kwargs): """ Helper for assigning object attributes from API responses. """ for opt in opts: if(opt in kwargs): ...
def hset(self, key, field, value): """Sets `field` in the hash stored at `key` to `value`. If `key` does not exist, a new key holding a hash is created. If `field` already exists in the hash, it is overwritten. .. note:: **Time complexity**: always ``O(1)`` :param ...
Sets `field` in the hash stored at `key` to `value`. If `key` does not exist, a new key holding a hash is created. If `field` already exists in the hash, it is overwritten. .. note:: **Time complexity**: always ``O(1)`` :param key: The key of the hash :type key: :c...
Below is the the instruction that describes the task: ### Input: Sets `field` in the hash stored at `key` to `value`. If `key` does not exist, a new key holding a hash is created. If `field` already exists in the hash, it is overwritten. .. note:: **Time complexity**: always ``...
def mark_quality(self, start_time, length, qual_name): """Mark signal quality, only add the new ones. Parameters ---------- start_time : int start time in s of the epoch being scored. length : int duration in s of the epoch being scored. qual_name ...
Mark signal quality, only add the new ones. Parameters ---------- start_time : int start time in s of the epoch being scored. length : int duration in s of the epoch being scored. qual_name : str one of the stages defined in global stages.
Below is the the instruction that describes the task: ### Input: Mark signal quality, only add the new ones. Parameters ---------- start_time : int start time in s of the epoch being scored. length : int duration in s of the epoch being scored. qual_na...
def per_core_reservation(): """ returns True if the cluster is configured for reservations to be per core, False if it is per job """ per_core = apply_bparams(per_core_reserve_from_stream) if per_core: if per_core.upper() == "Y": return True else: return F...
returns True if the cluster is configured for reservations to be per core, False if it is per job
Below is the the instruction that describes the task: ### Input: returns True if the cluster is configured for reservations to be per core, False if it is per job ### Response: def per_core_reservation(): """ returns True if the cluster is configured for reservations to be per core, False if it is ...
def status_counter(self): """ Returns a :class:`Counter` object that counts the number of tasks with given status (use the string representation of the status as key). """ # Count the number of tasks with given status in each work. counter = self[0].status_counter ...
Returns a :class:`Counter` object that counts the number of tasks with given status (use the string representation of the status as key).
Below is the the instruction that describes the task: ### Input: Returns a :class:`Counter` object that counts the number of tasks with given status (use the string representation of the status as key). ### Response: def status_counter(self): """ Returns a :class:`Counter` object that count...
def status(self, value): """Set Query Status""" if value is not None: if not isinstance(value, QueryStatusType): raise AttributeError("%s action type is invalid in mdsol:Query." % (value,)) self._status = value
Set Query Status
Below is the the instruction that describes the task: ### Input: Set Query Status ### Response: def status(self, value): """Set Query Status""" if value is not None: if not isinstance(value, QueryStatusType): raise AttributeError("%s action type is invalid in mdsol:Query...
def kill(self, id, signal=signal.SIGTERM): """ Kill a job with given id :WARNING: beware of what u kill, if u killed redis for example core0 or coreX won't be reachable :param id: job id to kill """ args = { 'id': id, 'signal': int(signal), ...
Kill a job with given id :WARNING: beware of what u kill, if u killed redis for example core0 or coreX won't be reachable :param id: job id to kill
Below is the the instruction that describes the task: ### Input: Kill a job with given id :WARNING: beware of what u kill, if u killed redis for example core0 or coreX won't be reachable :param id: job id to kill ### Response: def kill(self, id, signal=signal.SIGTERM): """ Kill a ...
def to_raw_text(text, keep_whitespace=False, normalize_ascii=True): """ A generator to convert raw text segments, with xml, and other non-textual content to a list of words without any markup. Additionally dates are replaced by `7777` for normalization. Arguments --------- text: str, inp...
A generator to convert raw text segments, with xml, and other non-textual content to a list of words without any markup. Additionally dates are replaced by `7777` for normalization. Arguments --------- text: str, input text to tokenize, strip of markup. keep_whitespace : bool, should the ...
Below is the the instruction that describes the task: ### Input: A generator to convert raw text segments, with xml, and other non-textual content to a list of words without any markup. Additionally dates are replaced by `7777` for normalization. Arguments --------- text: str, input text to ...
def memory_usage(proc=-1, interval=.1, timeout=None, timestamps=False, include_children=False, max_usage=False, retval=False, stream=None): """ Return the memory usage of a process or piece of code Parameters ---------- proc : {int, string, tuple, subprocess.Popen}...
Return the memory usage of a process or piece of code Parameters ---------- proc : {int, string, tuple, subprocess.Popen}, optional The process to monitor. Can be given by an integer/string representing a PID, by a Popen object or by a tuple representing a Python function. The tuple...
Below is the the instruction that describes the task: ### Input: Return the memory usage of a process or piece of code Parameters ---------- proc : {int, string, tuple, subprocess.Popen}, optional The process to monitor. Can be given by an integer/string representing a PID, by a Popen o...
def main(): """ Wrapper for OGR """ parser = argparse.ArgumentParser( description='Command line interface to python-ontobio.golr library' """ Provides command line interface onto the ontobio.golr python library, a high level abstraction layer over Monarch and GO solr in...
Wrapper for OGR
Below is the the instruction that describes the task: ### Input: Wrapper for OGR ### Response: def main(): """ Wrapper for OGR """ parser = argparse.ArgumentParser( description='Command line interface to python-ontobio.golr library' """ Provides command line interface onto...
def load_covarfile(self, file, indices=[], names=[], sample_file=False): """Load covariate data from file. Unlike phenofiles, if we already have data, we keep it (that would be the sex covariate)""" # Clean up input in case we are given some empty values var_indices = [] for x ...
Load covariate data from file. Unlike phenofiles, if we already have data, we keep it (that would be the sex covariate)
Below is the the instruction that describes the task: ### Input: Load covariate data from file. Unlike phenofiles, if we already have data, we keep it (that would be the sex covariate) ### Response: def load_covarfile(self, file, indices=[], names=[], sample_file=False): """Load covariate data fro...
def load_asf(self, source, **kwargs): '''Load a skeleton definition from an ASF text file. Parameters ---------- source : str or file A filename or file-like object that contains text information describing a skeleton, in ASF format. ''' if hasatt...
Load a skeleton definition from an ASF text file. Parameters ---------- source : str or file A filename or file-like object that contains text information describing a skeleton, in ASF format.
Below is the the instruction that describes the task: ### Input: Load a skeleton definition from an ASF text file. Parameters ---------- source : str or file A filename or file-like object that contains text information describing a skeleton, in ASF format. ### Respo...
def connect(self, protocolFactory): """Starts a process and connect a protocol to it. """ deferred = self._startProcess() deferred.addCallback(self._connectRelay, protocolFactory) deferred.addCallback(self._startRelay) return deferred
Starts a process and connect a protocol to it.
Below is the the instruction that describes the task: ### Input: Starts a process and connect a protocol to it. ### Response: def connect(self, protocolFactory): """Starts a process and connect a protocol to it. """ deferred = self._startProcess() deferred.addCallback(self._connectR...
def luns(self): """Aggregator for ioclass_luns and ioclass_snapshots.""" lun_list, smp_list = [], [] if self.ioclass_luns: lun_list = map(lambda l: VNXLun(lun_id=l.lun_id, name=l.name, cli=self._cli), self.ioclass_luns) if self.iocl...
Aggregator for ioclass_luns and ioclass_snapshots.
Below is the the instruction that describes the task: ### Input: Aggregator for ioclass_luns and ioclass_snapshots. ### Response: def luns(self): """Aggregator for ioclass_luns and ioclass_snapshots.""" lun_list, smp_list = [], [] if self.ioclass_luns: lun_list = map(lambda l: V...
def deeplift_grad(module, grad_input, grad_output): """The backward hook which computes the deeplift gradient for an nn.Module """ # first, get the module type module_type = module.__class__.__name__ # first, check the module is supported if module_type in op_handler: if op_handler[m...
The backward hook which computes the deeplift gradient for an nn.Module
Below is the the instruction that describes the task: ### Input: The backward hook which computes the deeplift gradient for an nn.Module ### Response: def deeplift_grad(module, grad_input, grad_output): """The backward hook which computes the deeplift gradient for an nn.Module """ # first, get ...
def ok_check(function, *args, **kwargs): '''Ensure that the response body is OK''' req = function(*args, **kwargs) if req.content.lower() != 'ok': raise ClientException(req.content) return req.content
Ensure that the response body is OK
Below is the the instruction that describes the task: ### Input: Ensure that the response body is OK ### Response: def ok_check(function, *args, **kwargs): '''Ensure that the response body is OK''' req = function(*args, **kwargs) if req.content.lower() != 'ok': raise ClientException(req.content...
def MaxLikeInterval(self, percentage=90): """Returns the maximum-likelihood credible interval. If percentage=90, computes a 90% CI containing the values with the highest likelihoods. percentage: float between 0 and 100 Returns: list of values from the suite """ ...
Returns the maximum-likelihood credible interval. If percentage=90, computes a 90% CI containing the values with the highest likelihoods. percentage: float between 0 and 100 Returns: list of values from the suite
Below is the the instruction that describes the task: ### Input: Returns the maximum-likelihood credible interval. If percentage=90, computes a 90% CI containing the values with the highest likelihoods. percentage: float between 0 and 100 Returns: list of values from the suite ###...
def moresane(self, subregion=None, scale_count=None, sigma_level=4, loop_gain=0.1, tolerance=0.75, accuracy=1e-6, major_loop_miter=100, minor_loop_miter=30, all_on_gpu=False, decom_mode="ser", core_count=1, conv_device='cpu', conv_mode='linear', extraction_mode='cpu', enforce_positivit...
Primary method for wavelet analysis and subsequent deconvolution. INPUTS: subregion (default=None): Size, in pixels, of the central region to be analyzed and deconvolved. scale_count (default=None): Maximum scale to be considered - maximum scale considered during ...
Below is the the instruction that describes the task: ### Input: Primary method for wavelet analysis and subsequent deconvolution. INPUTS: subregion (default=None): Size, in pixels, of the central region to be analyzed and deconvolved. scale_count (default=None): M...
def _get_example_length(example): """Returns the maximum length between the example inputs and targets.""" length = tf.maximum(tf.shape(example[0])[0], tf.shape(example[1])[0]) return length
Returns the maximum length between the example inputs and targets.
Below is the the instruction that describes the task: ### Input: Returns the maximum length between the example inputs and targets. ### Response: def _get_example_length(example): """Returns the maximum length between the example inputs and targets.""" length = tf.maximum(tf.shape(example[0])[0], tf.shape(exam...
def add_receipt(self, block_header: BlockHeader, index_key: int, receipt: Receipt) -> Hash32: """ Adds the given receipt to the provided block header. Returns the updated `receipts_root` for updated block header. """ receipt_db = HexaryTrie(db=self.db, root_hash=block_header.rec...
Adds the given receipt to the provided block header. Returns the updated `receipts_root` for updated block header.
Below is the the instruction that describes the task: ### Input: Adds the given receipt to the provided block header. Returns the updated `receipts_root` for updated block header. ### Response: def add_receipt(self, block_header: BlockHeader, index_key: int, receipt: Receipt) -> Hash32: """ ...
def dct(input, K=13): """Convert log-power-spectrum to MFCC using the orthogonal DCT-II""" nframes, N = input.shape freqstep = numpy.pi / N cosmat = dctmat(N,K,freqstep) return numpy.dot(input, cosmat) * numpy.sqrt(2.0 / N)
Convert log-power-spectrum to MFCC using the orthogonal DCT-II
Below is the the instruction that describes the task: ### Input: Convert log-power-spectrum to MFCC using the orthogonal DCT-II ### Response: def dct(input, K=13): """Convert log-power-spectrum to MFCC using the orthogonal DCT-II""" nframes, N = input.shape freqstep = numpy.pi / N cosmat = dctmat(N...
def get_status(address=None): """ Check if the DbServer is up. :param address: pair (hostname, port) :returns: 'running' or 'not-running' """ address = address or (config.dbserver.host, DBSERVER_PORT) return 'running' if socket_ready(address) else 'not-running'
Check if the DbServer is up. :param address: pair (hostname, port) :returns: 'running' or 'not-running'
Below is the the instruction that describes the task: ### Input: Check if the DbServer is up. :param address: pair (hostname, port) :returns: 'running' or 'not-running' ### Response: def get_status(address=None): """ Check if the DbServer is up. :param address: pair (hostname, port) :retu...
def psd(t, y, pow2=False, window=None, rescale=False): """ Single-sided power spectral density, assuming real valued inputs. This goes through the numpy fourier transform process, assembling and returning (frequencies, psd) given time and signal data y. Note it is defined such that sum(psd)*d...
Single-sided power spectral density, assuming real valued inputs. This goes through the numpy fourier transform process, assembling and returning (frequencies, psd) given time and signal data y. Note it is defined such that sum(psd)*df, where df is the frequency spacing, is the variance of the or...
Below is the the instruction that describes the task: ### Input: Single-sided power spectral density, assuming real valued inputs. This goes through the numpy fourier transform process, assembling and returning (frequencies, psd) given time and signal data y. Note it is defined such that sum(psd)...
def do_work(self): """ Do work """ self._starttime = time.time() if not os.path.isdir(self._dir2): if self._maketarget: if self._verbose: self.log('Creating directory %s' % self._dir2) try: os.makedirs(self._di...
Do work
Below is the the instruction that describes the task: ### Input: Do work ### Response: def do_work(self): """ Do work """ self._starttime = time.time() if not os.path.isdir(self._dir2): if self._maketarget: if self._verbose: self.log('Creati...
def compute_min_distance(lng_rad, lat_rad, p0_lng, p0_lat, pm1_lng, pm1_lat, p1_lng, p1_lat): """ :param lng_rad: lng of px in radians :param lat_rad: lat of px in radians :param p0_lng: lng of p0 in radians :param p0_lat: lat of p0 in radians :param pm1_lng: lng of pm1 in radians :param pm1...
:param lng_rad: lng of px in radians :param lat_rad: lat of px in radians :param p0_lng: lng of p0 in radians :param p0_lat: lat of p0 in radians :param pm1_lng: lng of pm1 in radians :param pm1_lat: lat of pm1 in radians :param p1_lng: lng of p1 in radians :param p1_lat: lat of p1 in radian...
Below is the the instruction that describes the task: ### Input: :param lng_rad: lng of px in radians :param lat_rad: lat of px in radians :param p0_lng: lng of p0 in radians :param p0_lat: lat of p0 in radians :param pm1_lng: lng of pm1 in radians :param pm1_lat: lat of pm1 in radians :para...
def get_ccc_handle_from_uuid(self, uuid): """Utility function to retrieve the client characteristic configuration descriptor handle for a given characteristic. Args: uuid (str): a string containing the hex-encoded UUID Returns: None if an err...
Utility function to retrieve the client characteristic configuration descriptor handle for a given characteristic. Args: uuid (str): a string containing the hex-encoded UUID Returns: None if an error occurs, otherwise an integer handle.
Below is the the instruction that describes the task: ### Input: Utility function to retrieve the client characteristic configuration descriptor handle for a given characteristic. Args: uuid (str): a string containing the hex-encoded UUID Returns: ...
def do_o3(self, line): """Send a DirectOperate BinaryOutput (group 12) CommandSet to the Outstation. Command syntax is: o3""" self.application.send_direct_operate_command_set(opendnp3.CommandSet( [ opendnp3.WithIndex(opendnp3.ControlRelayOutputBlock(opendnp3.ControlCode.LATCH...
Send a DirectOperate BinaryOutput (group 12) CommandSet to the Outstation. Command syntax is: o3
Below is the the instruction that describes the task: ### Input: Send a DirectOperate BinaryOutput (group 12) CommandSet to the Outstation. Command syntax is: o3 ### Response: def do_o3(self, line): """Send a DirectOperate BinaryOutput (group 12) CommandSet to the Outstation. Command syntax is: o3""" ...
def _at_function(self, calculator, rule, scope, block): """ Implements @mixin and @function """ if not block.argument: raise SyntaxError("%s requires a function name (%s)" % (block.directive, rule.file_and_line)) funct, argspec_node = self._get_funct_def(rule, calcul...
Implements @mixin and @function
Below is the the instruction that describes the task: ### Input: Implements @mixin and @function ### Response: def _at_function(self, calculator, rule, scope, block): """ Implements @mixin and @function """ if not block.argument: raise SyntaxError("%s requires a function...
def capture_message(self, message, level=None): # type: (str, Optional[Any]) -> Optional[str] """Captures a message. The message is just a string. If no level is provided the default level is `info`. """ if self.client is None: return None if level is None: ...
Captures a message. The message is just a string. If no level is provided the default level is `info`.
Below is the the instruction that describes the task: ### Input: Captures a message. The message is just a string. If no level is provided the default level is `info`. ### Response: def capture_message(self, message, level=None): # type: (str, Optional[Any]) -> Optional[str] """Captures a...
def make_redirect_url(self, path_info, query_args=None, domain_part=None): """Creates a redirect URL. :internal: """ suffix = '' if query_args: suffix = '?' + self.encode_query_args(query_args) return str('%s://%s/%s%s' % ( self.url_scheme, ...
Creates a redirect URL. :internal:
Below is the the instruction that describes the task: ### Input: Creates a redirect URL. :internal: ### Response: def make_redirect_url(self, path_info, query_args=None, domain_part=None): """Creates a redirect URL. :internal: """ suffix = '' if query_args: ...
def command_max_delay(self, event=None): """ CPU burst max running time - self.runtime_cfg.max_delay """ try: max_delay = self.max_delay_var.get() except ValueError: max_delay = self.runtime_cfg.max_delay if max_delay < 0: max_delay = self.runtime_cfg...
CPU burst max running time - self.runtime_cfg.max_delay
Below is the the instruction that describes the task: ### Input: CPU burst max running time - self.runtime_cfg.max_delay ### Response: def command_max_delay(self, event=None): """ CPU burst max running time - self.runtime_cfg.max_delay """ try: max_delay = self.max_delay_var.get() ...
def solve_simple_captcha(self, pathfile=None, filedata=None, filename=None): """ Upload a image (from disk or a bytearray), and then block until the captcha has been solved. Return value is the captcha result. either pathfile OR filedata AND filename should be specified. Failure will result in a subclass ...
Upload a image (from disk or a bytearray), and then block until the captcha has been solved. Return value is the captcha result. either pathfile OR filedata AND filename should be specified. Failure will result in a subclass of WebRequest.CaptchaSolverFailure being thrown.
Below is the the instruction that describes the task: ### Input: Upload a image (from disk or a bytearray), and then block until the captcha has been solved. Return value is the captcha result. either pathfile OR filedata AND filename should be specified. Failure will result in a subclass of WebRequest.Ca...
def _resolve_variable(cls, config, substitution): """ :param config: :param substitution: :return: (is_resolved, resolved_variable) """ variable = substitution.variable try: return True, config.get(variable) except ConfigMissingException: ...
:param config: :param substitution: :return: (is_resolved, resolved_variable)
Below is the the instruction that describes the task: ### Input: :param config: :param substitution: :return: (is_resolved, resolved_variable) ### Response: def _resolve_variable(cls, config, substitution): """ :param config: :param substitution: :return: (is_resolve...
def is_alive(self, vhost='%2F'): """ Uses the aliveness-test API call to determine if the server is alive and the vhost is active. The broker (not this code) creates a queue and then sends/consumes a message from it. :param string vhost: There should be no real reason to ever ch...
Uses the aliveness-test API call to determine if the server is alive and the vhost is active. The broker (not this code) creates a queue and then sends/consumes a message from it. :param string vhost: There should be no real reason to ever change this from the default value, but it'...
Below is the the instruction that describes the task: ### Input: Uses the aliveness-test API call to determine if the server is alive and the vhost is active. The broker (not this code) creates a queue and then sends/consumes a message from it. :param string vhost: There should be no real r...
def free(self): """Release the results and connection lock from the TornadoSession object. This **must** be called after you finish processing the results from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or :py:meth:`TornadoSession.callproc <queries.TornadoSession.call...
Release the results and connection lock from the TornadoSession object. This **must** be called after you finish processing the results from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` or the conne...
Below is the the instruction that describes the task: ### Input: Release the results and connection lock from the TornadoSession object. This **must** be called after you finish processing the results from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or :py:meth:`TornadoSes...
def main(): '''Main entry point for the bioinfo CLI.''' args = docopt(__doc__, version=__version__) if 'bam_coverage' in args: bam_coverage(args['<reference>'], args['<alignments>'], int(args['<minmatch>']), min_mapq=int(args['--mapq'])...
Main entry point for the bioinfo CLI.
Below is the the instruction that describes the task: ### Input: Main entry point for the bioinfo CLI. ### Response: def main(): '''Main entry point for the bioinfo CLI.''' args = docopt(__doc__, version=__version__) if 'bam_coverage' in args: bam_coverage(args['<reference>'], ...
def get(cls, **kwargs): """Get a copy of the type from the cache and reconstruct it.""" data = cls._get(**kwargs) if data is None: new = cls() new.from_miss(**kwargs) return new return cls.deserialize(data)
Get a copy of the type from the cache and reconstruct it.
Below is the the instruction that describes the task: ### Input: Get a copy of the type from the cache and reconstruct it. ### Response: def get(cls, **kwargs): """Get a copy of the type from the cache and reconstruct it.""" data = cls._get(**kwargs) if data is None: new = cls(...
def kill(self, block=False, reason="unknown"): """ Forcefully kill all greenlets associated with this job """ current_greenletid = id(gevent.getcurrent()) trace = "Job killed: %s" % reason for greenlet, job in context._GLOBAL_CONTEXT["greenlets"].values(): greenletid = id(g...
Forcefully kill all greenlets associated with this job
Below is the the instruction that describes the task: ### Input: Forcefully kill all greenlets associated with this job ### Response: def kill(self, block=False, reason="unknown"): """ Forcefully kill all greenlets associated with this job """ current_greenletid = id(gevent.getcurrent()) ...
def pattern_to_str(pattern): """Convert regex pattern to string. If pattern is string it returns itself, if pattern is SRE_Pattern then return pattern attribute :param pattern: pattern object or string :return: str: pattern sttring """ if isinstance(pattern, str): return repr(patter...
Convert regex pattern to string. If pattern is string it returns itself, if pattern is SRE_Pattern then return pattern attribute :param pattern: pattern object or string :return: str: pattern sttring
Below is the the instruction that describes the task: ### Input: Convert regex pattern to string. If pattern is string it returns itself, if pattern is SRE_Pattern then return pattern attribute :param pattern: pattern object or string :return: str: pattern sttring ### Response: def pattern_to_str(...
def query(self, query, time_precision='s', chunked=False): """Query data into DataFrames. Returns a DataFrame for a single time series and a map for multiple time series with the time series as value and its name as key. :param time_precision: [Optional, default 's'] Either 's', 'm', '...
Query data into DataFrames. Returns a DataFrame for a single time series and a map for multiple time series with the time series as value and its name as key. :param time_precision: [Optional, default 's'] Either 's', 'm', 'ms' or 'u'. :param chunked: [Optional, default=Fal...
Below is the the instruction that describes the task: ### Input: Query data into DataFrames. Returns a DataFrame for a single time series and a map for multiple time series with the time series as value and its name as key. :param time_precision: [Optional, default 's'] Either 's', 'm', 'm...
def maker(args): """ %prog maker maker.gff3 genome.fasta Prepare EVM inputs by separating tracks from MAKER. """ from jcvi.formats.base import SetFile, FileShredder A, T, P = "ABINITIO_PREDICTION", "TRANSCRIPT", "PROTEIN" # Stores default weights and types Registry = {\ "maker"...
%prog maker maker.gff3 genome.fasta Prepare EVM inputs by separating tracks from MAKER.
Below is the the instruction that describes the task: ### Input: %prog maker maker.gff3 genome.fasta Prepare EVM inputs by separating tracks from MAKER. ### Response: def maker(args): """ %prog maker maker.gff3 genome.fasta Prepare EVM inputs by separating tracks from MAKER. """ from jcvi...
def delete_metric(name): """Remove the named metric""" with LOCK: old_metric = REGISTRY.pop(name, None) # look for the metric name in the tags and remove it for _, tags in py3comp.iteritems(TAGS): if name in tags: tags.remove(name) return old_metric
Remove the named metric
Below is the the instruction that describes the task: ### Input: Remove the named metric ### Response: def delete_metric(name): """Remove the named metric""" with LOCK: old_metric = REGISTRY.pop(name, None) # look for the metric name in the tags and remove it for _, tags in py3com...