code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def module_del(self, key): """ Deregister from python module change events. """ if key in self._module_event_map: del self._module_event_map[key] if key in self._watch_modules.names: self._watch_modules.remove(key)
Deregister from python module change events.
Below is the the instruction that describes the task: ### Input: Deregister from python module change events. ### Response: def module_del(self, key): """ Deregister from python module change events. """ if key in self._module_event_map: del self._module_event_map[key] ...
def create_epochs(data, events_onsets, sampling_rate=1000, duration=1, onset=0, index=None): """ Epoching a dataframe. Parameters ---------- data : pandas.DataFrame Data*time. events_onsets : list A list of event onsets indices. sampling_rate : int Sampling rate (sam...
Epoching a dataframe. Parameters ---------- data : pandas.DataFrame Data*time. events_onsets : list A list of event onsets indices. sampling_rate : int Sampling rate (samples/second). duration : int or list Duration(s) of each epoch(s) (in seconds). onset : i...
Below is the the instruction that describes the task: ### Input: Epoching a dataframe. Parameters ---------- data : pandas.DataFrame Data*time. events_onsets : list A list of event onsets indices. sampling_rate : int Sampling rate (samples/second). duration : int or ...
def pad(data, length): """This function returns a padded version of the input data to the given length. this function will shorten the given data to the length specified if necessary. post-condition: len(data) = length :param data: the data byte array to pad :param length: the...
This function returns a padded version of the input data to the given length. this function will shorten the given data to the length specified if necessary. post-condition: len(data) = length :param data: the data byte array to pad :param length: the length to pad the array to
Below is the the instruction that describes the task: ### Input: This function returns a padded version of the input data to the given length. this function will shorten the given data to the length specified if necessary. post-condition: len(data) = length :param data: the data byte arra...
def process_exception(self, request, exception): """Report exceptions from requests via Exreporter. """ gc = GithubCredentials( user=settings.EXREPORTER_GITHUB_USER, repo=settings.EXREPORTER_GITHUB_REPO, auth_token=settings.EXREPORTER_GITHUB_AUTH_TOKEN) ...
Report exceptions from requests via Exreporter.
Below is the the instruction that describes the task: ### Input: Report exceptions from requests via Exreporter. ### Response: def process_exception(self, request, exception): """Report exceptions from requests via Exreporter. """ gc = GithubCredentials( user=settings.EXREPORTER...
def execute(sql, args=None, key='default'): """It is used for update, delete records. :param sql string: the sql stamtement like 'select * from %s' :param args list: Wen set None, will use dbi execute(sql), else dbi execute(sql, args), the args keep the original rules, it shuld be tuple or lis...
It is used for update, delete records. :param sql string: the sql stamtement like 'select * from %s' :param args list: Wen set None, will use dbi execute(sql), else dbi execute(sql, args), the args keep the original rules, it shuld be tuple or list of list :param key: a key for your dabtabase ...
Below is the the instruction that describes the task: ### Input: It is used for update, delete records. :param sql string: the sql stamtement like 'select * from %s' :param args list: Wen set None, will use dbi execute(sql), else dbi execute(sql, args), the args keep the original rules, it shu...
def error_view(template_dir=None): """ Create the Error view Must be instantiated import error_view ErrorView = error_view() :param template_dir: The directory containing the view pages :return: """ if not template_dir: template_dir = "Pylot/Error" template_page = "%s/...
Create the Error view Must be instantiated import error_view ErrorView = error_view() :param template_dir: The directory containing the view pages :return:
Below is the the instruction that describes the task: ### Input: Create the Error view Must be instantiated import error_view ErrorView = error_view() :param template_dir: The directory containing the view pages :return: ### Response: def error_view(template_dir=None): """ Create the ...
def halfmax_points(self): """Get the bandpass' half-maximum wavelengths. These can be used to compute a representative bandwidth, or for display purposes. Unlike calc_halfmax_points(), this function will use a cached value if available. """ t = self.registry._halfmaxes....
Get the bandpass' half-maximum wavelengths. These can be used to compute a representative bandwidth, or for display purposes. Unlike calc_halfmax_points(), this function will use a cached value if available.
Below is the the instruction that describes the task: ### Input: Get the bandpass' half-maximum wavelengths. These can be used to compute a representative bandwidth, or for display purposes. Unlike calc_halfmax_points(), this function will use a cached value if available. ### Response: def...
def fit_transform(self, X, u=None): """Fit X into an embedded space and return that transformed output. Inputs ---------- X : array, shape (n_samples, n_features). X contains a sample per row. Returns ------- embedding : array, shape (n_samples, n_compone...
Fit X into an embedded space and return that transformed output. Inputs ---------- X : array, shape (n_samples, n_features). X contains a sample per row. Returns ------- embedding : array, shape (n_samples, n_components) Embedding of the training data...
Below is the the instruction that describes the task: ### Input: Fit X into an embedded space and return that transformed output. Inputs ---------- X : array, shape (n_samples, n_features). X contains a sample per row. Returns ------- embedding : array, shape...
def debugDumpOneNode(self, output, depth): """Dumps debug information for the element node, it is not recursive """ libxml2mod.xmlDebugDumpOneNode(output, self._o, depth)
Dumps debug information for the element node, it is not recursive
Below is the the instruction that describes the task: ### Input: Dumps debug information for the element node, it is not recursive ### Response: def debugDumpOneNode(self, output, depth): """Dumps debug information for the element node, it is not recursive """ libxml2mod.xmlDe...
def wait_until_finished(self): """ Sleeps until all the processors are done. """ for file_path, processor in self._processors.items(): while not processor.done: time.sleep(0.1)
Sleeps until all the processors are done.
Below is the the instruction that describes the task: ### Input: Sleeps until all the processors are done. ### Response: def wait_until_finished(self): """ Sleeps until all the processors are done. """ for file_path, processor in self._processors.items(): while not proce...
def pil_image(self): """Return a PIL image from the current image. """ channels, fill_value = self._finalize() if self.is_empty(): return Pil.new(self.mode, (0, 0)) if self.mode == "L": if fill_value is not None: img = Pil.fromarray(chann...
Return a PIL image from the current image.
Below is the the instruction that describes the task: ### Input: Return a PIL image from the current image. ### Response: def pil_image(self): """Return a PIL image from the current image. """ channels, fill_value = self._finalize() if self.is_empty(): return Pil.new(se...
def _read_field(self): ''' Read a single byte for field type, then read the value. ''' ftype = self._input[self._pos] self._pos += 1 reader = self.field_type_map.get(ftype) if reader: return reader(self) raise Reader.FieldError('Unknown field...
Read a single byte for field type, then read the value.
Below is the the instruction that describes the task: ### Input: Read a single byte for field type, then read the value. ### Response: def _read_field(self): ''' Read a single byte for field type, then read the value. ''' ftype = self._input[self._pos] self._pos += 1 ...
async def mail( self, sender: str, options: Iterable[str] = None, timeout: DefaultNumType = _default, ) -> SMTPResponse: """ Send an SMTP MAIL command, which specifies the message sender and begins a new mail transfer session ("envelope"). :raises SMT...
Send an SMTP MAIL command, which specifies the message sender and begins a new mail transfer session ("envelope"). :raises SMTPSenderRefused: on unexpected server response code
Below is the the instruction that describes the task: ### Input: Send an SMTP MAIL command, which specifies the message sender and begins a new mail transfer session ("envelope"). :raises SMTPSenderRefused: on unexpected server response code ### Response: async def mail( self, send...
def before_request(self, f): """Like :meth:`Flask.before_request` but for a blueprint. This function is only executed before each request that is handled by a function of that blueprint. """ self.record_once(lambda s: s.app.before_request_funcs .setdefault(self.name,...
Like :meth:`Flask.before_request` but for a blueprint. This function is only executed before each request that is handled by a function of that blueprint.
Below is the the instruction that describes the task: ### Input: Like :meth:`Flask.before_request` but for a blueprint. This function is only executed before each request that is handled by a function of that blueprint. ### Response: def before_request(self, f): """Like :meth:`Flask.before...
def write_hier_all(self, out=sys.stdout, len_dash=1, max_depth=None, num_child=None, short_prt=False): """Write hierarchy for all GO Terms in obo file.""" # Print: [biological_process, molecular_function, and cellular_component] for go_id in ['GO:0008150', 'GO:0003674', 'GO...
Write hierarchy for all GO Terms in obo file.
Below is the the instruction that describes the task: ### Input: Write hierarchy for all GO Terms in obo file. ### Response: def write_hier_all(self, out=sys.stdout, len_dash=1, max_depth=None, num_child=None, short_prt=False): """Write hierarchy for all GO Terms in obo file.""" ...
def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: ...
Return a set of ip addrs active tcp connections
Below is the the instruction that describes the task: ### Input: Return a set of ip addrs active tcp connections ### Response: def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is...
def transaction_id(self, transaction_id): """ Sets the transaction_id of this AdditionalRecipientReceivable. The ID of the transaction that the additional recipient receivable was applied to. :param transaction_id: The transaction_id of this AdditionalRecipientReceivable. :type:...
Sets the transaction_id of this AdditionalRecipientReceivable. The ID of the transaction that the additional recipient receivable was applied to. :param transaction_id: The transaction_id of this AdditionalRecipientReceivable. :type: str
Below is the the instruction that describes the task: ### Input: Sets the transaction_id of this AdditionalRecipientReceivable. The ID of the transaction that the additional recipient receivable was applied to. :param transaction_id: The transaction_id of this AdditionalRecipientReceivable. ...
def parse_help_text(self, file_path): ''' Load of list of commands and descriptions from a file. ''' with open(file_path) as f: lines = f.readlines() # Parse commands and descriptions, which are separated by a multi-space # (any sequence of two or more space characters in a ...
Load of list of commands and descriptions from a file.
Below is the the instruction that describes the task: ### Input: Load of list of commands and descriptions from a file. ### Response: def parse_help_text(self, file_path): ''' Load of list of commands and descriptions from a file. ''' with open(file_path) as f: lines = f.readlines() ...
def getWorkerInfo(dataTask): """Returns the total execution time and task quantity by worker""" workertime = [] workertasks = [] for fichier, vals in dataTask.items(): if hasattr(vals, 'values'): #workers_names.append(fichier) # Data from worker totaltime = su...
Returns the total execution time and task quantity by worker
Below is the the instruction that describes the task: ### Input: Returns the total execution time and task quantity by worker ### Response: def getWorkerInfo(dataTask): """Returns the total execution time and task quantity by worker""" workertime = [] workertasks = [] for fichier, vals in dataTask....
def rollback(self): """Implementation of NAPALM method rollback.""" commands = [] commands.append('configure replace flash:rollback-0') commands.append('write memory') self.device.run_commands(commands)
Implementation of NAPALM method rollback.
Below is the the instruction that describes the task: ### Input: Implementation of NAPALM method rollback. ### Response: def rollback(self): """Implementation of NAPALM method rollback.""" commands = [] commands.append('configure replace flash:rollback-0') commands.append('write mem...
def update_J(self): """Updates J, JTJ, and internal counters.""" self.calc_J() # np.dot(j, j.T) is slightly faster but 2x as much mem step = np.ceil(1e-2 * self.J.shape[1]).astype('int') # 1% more mem... self.JTJ = low_mem_sq(self.J, step=step) #copies still, since J is ...
Updates J, JTJ, and internal counters.
Below is the the instruction that describes the task: ### Input: Updates J, JTJ, and internal counters. ### Response: def update_J(self): """Updates J, JTJ, and internal counters.""" self.calc_J() # np.dot(j, j.T) is slightly faster but 2x as much mem step = np.ceil(1e-2 * self.J.sh...
def _set_config(self, config=None): """Set this component's initial configuration""" if not config: config = {} try: # pprint(self.configschema) self.config = self.componentmodel(config) # self.log("Config schema:", lvl=critical) # ppr...
Set this component's initial configuration
Below is the the instruction that describes the task: ### Input: Set this component's initial configuration ### Response: def _set_config(self, config=None): """Set this component's initial configuration""" if not config: config = {} try: # pprint(self.configschema)...
def _extract_match(self, candidate, offset): """Attempts to extract a match from a candidate string. Arguments: candidate -- The candidate text that might contain a phone number. offset -- The offset of candidate within self.text Returns the match found, None if none can be foun...
Attempts to extract a match from a candidate string. Arguments: candidate -- The candidate text that might contain a phone number. offset -- The offset of candidate within self.text Returns the match found, None if none can be found
Below is the the instruction that describes the task: ### Input: Attempts to extract a match from a candidate string. Arguments: candidate -- The candidate text that might contain a phone number. offset -- The offset of candidate within self.text Returns the match found, None if non...
def updateRules( self ): """ Updates the query line items to match the latest rule options. """ terms = sorted(self._rules.keys()) for child in self.lineWidgets(): child.setTerms(terms)
Updates the query line items to match the latest rule options.
Below is the the instruction that describes the task: ### Input: Updates the query line items to match the latest rule options. ### Response: def updateRules( self ): """ Updates the query line items to match the latest rule options. """ terms = sorted(self._rules.keys()) fo...
def is_ancestor_of_repository(self, id_, repository_id): """Tests if an ``Id`` is an ancestor of a repository. arg: id (osid.id.Id): an ``Id`` arg: repository_id (osid.id.Id): the Id of a repository return: (boolean) - ``true`` if this ``id`` is an ancestor of ``re...
Tests if an ``Id`` is an ancestor of a repository. arg: id (osid.id.Id): an ``Id`` arg: repository_id (osid.id.Id): the Id of a repository return: (boolean) - ``true`` if this ``id`` is an ancestor of ``repository_id,`` ``false`` otherwise raise: NotFound - ``rep...
Below is the the instruction that describes the task: ### Input: Tests if an ``Id`` is an ancestor of a repository. arg: id (osid.id.Id): an ``Id`` arg: repository_id (osid.id.Id): the Id of a repository return: (boolean) - ``true`` if this ``id`` is an ancestor of ``r...
def changed(self, filename='.md5', glob=None): """Are any of the files matched by ``glob`` changed? """ if glob is not None: filename += '.glob-' + ''.join(ch.lower() for ch in glob if ch.isalpha()) return changed(self, filename, glo...
Are any of the files matched by ``glob`` changed?
Below is the the instruction that describes the task: ### Input: Are any of the files matched by ``glob`` changed? ### Response: def changed(self, filename='.md5', glob=None): """Are any of the files matched by ``glob`` changed? """ if glob is not None: filename += '.glob-' + ''...
def deserialize(cls, assoc_s): """ Parse an association as stored by serialize(). inverse of serialize @param assoc_s: Association as serialized by serialize() @type assoc_s: str @return: instance of this class """ pairs = kvform.kvToSeq(assoc_s, str...
Parse an association as stored by serialize(). inverse of serialize @param assoc_s: Association as serialized by serialize() @type assoc_s: str @return: instance of this class
Below is the the instruction that describes the task: ### Input: Parse an association as stored by serialize(). inverse of serialize @param assoc_s: Association as serialized by serialize() @type assoc_s: str @return: instance of this class ### Response: def deserialize(cls, a...
def _printer(self, *out, **kws): """Generic print function.""" flush = kws.pop('flush', True) fileh = kws.pop('file', self.writer) sep = kws.pop('sep', ' ') end = kws.pop('sep', '\n') print(*out, file=fileh, sep=sep, end=end) if flush: fileh.flush()
Generic print function.
Below is the the instruction that describes the task: ### Input: Generic print function. ### Response: def _printer(self, *out, **kws): """Generic print function.""" flush = kws.pop('flush', True) fileh = kws.pop('file', self.writer) sep = kws.pop('sep', ' ') end = kws.pop('...
def to_dict(self, properties=None): """Return a dictionary containing Substance data. If the properties parameter is not specified, everything except cids and aids is included. This is because the aids and cids properties each require an extra request to retrieve. :param properties: (o...
Return a dictionary containing Substance data. If the properties parameter is not specified, everything except cids and aids is included. This is because the aids and cids properties each require an extra request to retrieve. :param properties: (optional) A list of the desired properties.
Below is the the instruction that describes the task: ### Input: Return a dictionary containing Substance data. If the properties parameter is not specified, everything except cids and aids is included. This is because the aids and cids properties each require an extra request to retrieve. ...
def create_pswd_change(self, body): """Create password change ticket. Args: body (dict): Please see: https://auth0.com/docs/api/v2#!/Tickets/post_password_change """ return self.client.post(self._url('password-change'), data=body)
Create password change ticket. Args: body (dict): Please see: https://auth0.com/docs/api/v2#!/Tickets/post_password_change
Below is the the instruction that describes the task: ### Input: Create password change ticket. Args: body (dict): Please see: https://auth0.com/docs/api/v2#!/Tickets/post_password_change ### Response: def create_pswd_change(self, body): """Create password change ticket. Args:...
def get_num_processors(): """ Return number of online processor cores. """ # try different strategies and use first one that succeeeds try: return os.cpu_count() # Py3 only except AttributeError: pass try: import multiprocessing return multiprocessing.cpu_cou...
Return number of online processor cores.
Below is the the instruction that describes the task: ### Input: Return number of online processor cores. ### Response: def get_num_processors(): """ Return number of online processor cores. """ # try different strategies and use first one that succeeeds try: return os.cpu_count() # Py...
def directory(self, query, **kwargs): """Search by users or channels on all server.""" if isinstance(query, dict): query = str(query).replace("'", '"') return self.__call_api_get('directory', query=query, kwargs=kwargs)
Search by users or channels on all server.
Below is the the instruction that describes the task: ### Input: Search by users or channels on all server. ### Response: def directory(self, query, **kwargs): """Search by users or channels on all server.""" if isinstance(query, dict): query = str(query).replace("'", '"') retu...
def __GetServiceVersionDescription(protocol, server, port, path, sslContext): """ Private method that returns a root from an ElementTree describing the API versions supported by the specified server. The result will be vimServiceVersions.xml if it exists, otherwise vimService.wsdl if it exists, otherwise N...
Private method that returns a root from an ElementTree describing the API versions supported by the specified server. The result will be vimServiceVersions.xml if it exists, otherwise vimService.wsdl if it exists, otherwise None. @param protocol: What protocol to use for the connection (e.g. https or http). ...
Below is the the instruction that describes the task: ### Input: Private method that returns a root from an ElementTree describing the API versions supported by the specified server. The result will be vimServiceVersions.xml if it exists, otherwise vimService.wsdl if it exists, otherwise None. @param pro...
def enable_eye_dome_lighting(self): """Enable eye dome lighting (EDL)""" if hasattr(self, 'edl_pass'): return self # create the basic VTK render steps basic_passes = vtk.vtkRenderStepsPass() # blur the resulting image # The blur delegates rendering the unblure...
Enable eye dome lighting (EDL)
Below is the the instruction that describes the task: ### Input: Enable eye dome lighting (EDL) ### Response: def enable_eye_dome_lighting(self): """Enable eye dome lighting (EDL)""" if hasattr(self, 'edl_pass'): return self # create the basic VTK render steps basic_pass...
def handle_cd_command(arg): """Handles a `cd` shell command by calling python's os.chdir.""" CD_CMD = 'cd' tokens = arg.split(CD_CMD + ' ') directory = tokens[-1] if len(tokens) > 1 else None if not directory: return False, "No folder name was provided." try: os.chdir(directory) ...
Handles a `cd` shell command by calling python's os.chdir.
Below is the the instruction that describes the task: ### Input: Handles a `cd` shell command by calling python's os.chdir. ### Response: def handle_cd_command(arg): """Handles a `cd` shell command by calling python's os.chdir.""" CD_CMD = 'cd' tokens = arg.split(CD_CMD + ' ') directory = tokens[-1...
def delete_record(self, record): """ Permanently removes record from table. """ try: self.session.delete(record) self.session.commit() except Exception as e: self.session.rollback() raise ProgrammingError(e) finally: ...
Permanently removes record from table.
Below is the the instruction that describes the task: ### Input: Permanently removes record from table. ### Response: def delete_record(self, record): """ Permanently removes record from table. """ try: self.session.delete(record) self.session.commit() ...
def build_image_path(self, src): """\ This method will take an image path and build out the absolute path to that image * using the initial url we crawled so we can find a link to the image if they use relative urls like ../myimage.jpg """ o = urlparse...
\ This method will take an image path and build out the absolute path to that image * using the initial url we crawled so we can find a link to the image if they use relative urls like ../myimage.jpg
Below is the the instruction that describes the task: ### Input: \ This method will take an image path and build out the absolute path to that image * using the initial url we crawled so we can find a link to the image if they use relative urls like ../myimage.jpg ### Res...
def get_level(self, level=2): """Get all nodes that are exactly this far away.""" if level == 1: for child in self.children.values(): yield child else: for child in self.children.values(): for node in child.get_level(level-1): yield node
Get all nodes that are exactly this far away.
Below is the the instruction that describes the task: ### Input: Get all nodes that are exactly this far away. ### Response: def get_level(self, level=2): """Get all nodes that are exactly this far away.""" if level == 1: for child in self.children.values(): yield child else: ...
def _allocate_output(self, windows, shape): """ Allocate an output array whose rows should be passed to `self.compute`. The resulting array must have a shape of ``shape``. If we have standard outputs (i.e. self.outputs is NotSpecified), the default is an empty ndarray whose dty...
Allocate an output array whose rows should be passed to `self.compute`. The resulting array must have a shape of ``shape``. If we have standard outputs (i.e. self.outputs is NotSpecified), the default is an empty ndarray whose dtype is ``self.dtype``. If we have an outputs tuple, the ...
Below is the the instruction that describes the task: ### Input: Allocate an output array whose rows should be passed to `self.compute`. The resulting array must have a shape of ``shape``. If we have standard outputs (i.e. self.outputs is NotSpecified), the default is an empty ndarray whos...
def get_token(self): """ Method to retrieve an auth token. The cached global token is looked up and returned if it exists. If it is `None` a new one is requested and returned. Returns: Simplenote API token as string """ if self.token == None: se...
Method to retrieve an auth token. The cached global token is looked up and returned if it exists. If it is `None` a new one is requested and returned. Returns: Simplenote API token as string
Below is the the instruction that describes the task: ### Input: Method to retrieve an auth token. The cached global token is looked up and returned if it exists. If it is `None` a new one is requested and returned. Returns: Simplenote API token as string ### Response: def get...
def id_token_jwt_grant(request, token_uri, assertion): """Implements the JWT Profile for OAuth 2.0 Authorization Grants, but requests an OpenID Connect ID Token instead of an access token. This is a variant on the standard JWT Profile that is currently unique to Google. This was added for the benefit o...
Implements the JWT Profile for OAuth 2.0 Authorization Grants, but requests an OpenID Connect ID Token instead of an access token. This is a variant on the standard JWT Profile that is currently unique to Google. This was added for the benefit of authenticating to services that require ID Tokens instea...
Below is the the instruction that describes the task: ### Input: Implements the JWT Profile for OAuth 2.0 Authorization Grants, but requests an OpenID Connect ID Token instead of an access token. This is a variant on the standard JWT Profile that is currently unique to Google. This was added for the be...
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_2_0): """ Read the data stream and decode the AttributeReference structure into its parts. Args: input_buffer (stream): A data stream containing encoded object data, supporting a read method. ...
Read the data stream and decode the AttributeReference structure into its parts. Args: input_buffer (stream): A data stream containing encoded object data, supporting a read method. kmip_version (enum): A KMIPVersion enumeration defining the KMIP ...
Below is the the instruction that describes the task: ### Input: Read the data stream and decode the AttributeReference structure into its parts. Args: input_buffer (stream): A data stream containing encoded object data, supporting a read method. kmip_version...
def fix_report(self, report, errors="drop", prefer="before"): """Perform utc assignment on all readings in a report. The returned report will have all reading timestamps in UTC. This only works on SignedListReport objects. Note that the report should typically have previously been adde...
Perform utc assignment on all readings in a report. The returned report will have all reading timestamps in UTC. This only works on SignedListReport objects. Note that the report should typically have previously been added to the UTC assigner using add_report or no reference points fro...
Below is the the instruction that describes the task: ### Input: Perform utc assignment on all readings in a report. The returned report will have all reading timestamps in UTC. This only works on SignedListReport objects. Note that the report should typically have previously been added to...
def _get(self, name, interval, config, timestamp, **kws): ''' Get the interval. ''' i_bucket = config['i_calc'].to_bucket(timestamp) fetch = kws.get('fetch') process_row = kws.get('process_row') or self._process_row rval = OrderedDict() if fetch: data = fetch( self._client.connect...
Get the interval.
Below is the the instruction that describes the task: ### Input: Get the interval. ### Response: def _get(self, name, interval, config, timestamp, **kws): ''' Get the interval. ''' i_bucket = config['i_calc'].to_bucket(timestamp) fetch = kws.get('fetch') process_row = kws.get('process_row')...
def parse_session_token(response_headers): """ Extracts session token from response headers and parses :param dict response_headers: :return: A dictionary of partition id to session lsn for given collection :rtype: dict """ # extract sessio...
Extracts session token from response headers and parses :param dict response_headers: :return: A dictionary of partition id to session lsn for given collection :rtype: dict
Below is the the instruction that describes the task: ### Input: Extracts session token from response headers and parses :param dict response_headers: :return: A dictionary of partition id to session lsn for given collection :rtype: dict ### Response: def parse_se...
def is_ordered_mapping(obj): """Checks whether given object is an ordered mapping, e.g. a :class:`OrderedDict`. :return: ``True`` if argument is an ordered mapping, ``False`` otherwise """ if not (is_mapping(obj) and hasattr(obj, '__reversed__')): return False # PyPy has a bug where the...
Checks whether given object is an ordered mapping, e.g. a :class:`OrderedDict`. :return: ``True`` if argument is an ordered mapping, ``False`` otherwise
Below is the the instruction that describes the task: ### Input: Checks whether given object is an ordered mapping, e.g. a :class:`OrderedDict`. :return: ``True`` if argument is an ordered mapping, ``False`` otherwise ### Response: def is_ordered_mapping(obj): """Checks whether given object is an order...
def records(self, name): """ Get a list of all domain records for the given domain name Parameters ---------- name: str domain name """ if self.get(name): return DomainRecords(self.api, name)
Get a list of all domain records for the given domain name Parameters ---------- name: str domain name
Below is the the instruction that describes the task: ### Input: Get a list of all domain records for the given domain name Parameters ---------- name: str domain name ### Response: def records(self, name): """ Get a list of all domain records for the given doma...
def add_mavlink_packet(self, msg): '''add data to the graph''' mtype = msg.get_type() if mtype not in self.msg_types: return for i in range(len(self.fields)): if mtype not in self.field_types[i]: continue f = self.fields[i] ...
add data to the graph
Below is the the instruction that describes the task: ### Input: add data to the graph ### Response: def add_mavlink_packet(self, msg): '''add data to the graph''' mtype = msg.get_type() if mtype not in self.msg_types: return for i in range(len(self.fields)): ...
def setup(): """Walk the user though the Wallace setup.""" # Create the Wallace config file if it does not already exist. config_name = ".wallaceconfig" config_path = os.path.join(os.path.expanduser("~"), config_name) if os.path.isfile(config_path): log("Wallace config file already exists."...
Walk the user though the Wallace setup.
Below is the the instruction that describes the task: ### Input: Walk the user though the Wallace setup. ### Response: def setup(): """Walk the user though the Wallace setup.""" # Create the Wallace config file if it does not already exist. config_name = ".wallaceconfig" config_path = os.path.join(...
def path_exists(self, dest, weight=None): """Return whether there is a path leading from me to ``dest``. With ``weight``, only consider edges that have a stat by the given name. Raise ``ValueError`` if ``dest`` is not a node in my character or the name of one. """ ...
Return whether there is a path leading from me to ``dest``. With ``weight``, only consider edges that have a stat by the given name. Raise ``ValueError`` if ``dest`` is not a node in my character or the name of one.
Below is the the instruction that describes the task: ### Input: Return whether there is a path leading from me to ``dest``. With ``weight``, only consider edges that have a stat by the given name. Raise ``ValueError`` if ``dest`` is not a node in my character or the name of one. #...
def register_animation(self, animation_class): """Add a new animation""" self.state.animationClasses.append(animation_class) return len(self.state.animationClasses) - 1
Add a new animation
Below is the the instruction that describes the task: ### Input: Add a new animation ### Response: def register_animation(self, animation_class): """Add a new animation""" self.state.animationClasses.append(animation_class) return len(self.state.animationClasses) - 1
def git_clean(ctx): """ Delete all files untracked by git. :param ctx: Context object. :return: None. """ # Get command parts cmd_part_s = [ # Program path 'git', # Clean untracked files 'clean', # Remove all untracked files '-x', ...
Delete all files untracked by git. :param ctx: Context object. :return: None.
Below is the the instruction that describes the task: ### Input: Delete all files untracked by git. :param ctx: Context object. :return: None. ### Response: def git_clean(ctx): """ Delete all files untracked by git. :param ctx: Context object. :return: None. """ # Get command pa...
def p_pragma(self, p): 'pragma : LPAREN TIMES ID TIMES RPAREN' p[0] = Pragma(PragmaEntry(p[3], lineno=p.lineno(1)), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
pragma : LPAREN TIMES ID TIMES RPAREN
Below is the the instruction that describes the task: ### Input: pragma : LPAREN TIMES ID TIMES RPAREN ### Response: def p_pragma(self, p): 'pragma : LPAREN TIMES ID TIMES RPAREN' p[0] = Pragma(PragmaEntry(p[3], lineno=p.lineno(1)), lineno=p.lineno(1)) p.set_lineno(0, ...
def form_valid(self, form): """ Praise be, someone has spammed us. """ form.send_email(to=self.to_addr) return super(EmailView, self).form_valid(form)
Praise be, someone has spammed us.
Below is the the instruction that describes the task: ### Input: Praise be, someone has spammed us. ### Response: def form_valid(self, form): """ Praise be, someone has spammed us. """ form.send_email(to=self.to_addr) return super(EmailView, self).form_valid(form)
def _connect_command(self): ''' Generates a JSON string with the params to be used when sending CONNECT to the server. ->> CONNECT {"lang": "python3"} ''' options = { "verbose": self.options["verbose"], "pedantic": self.options["pedantic"], ...
Generates a JSON string with the params to be used when sending CONNECT to the server. ->> CONNECT {"lang": "python3"}
Below is the the instruction that describes the task: ### Input: Generates a JSON string with the params to be used when sending CONNECT to the server. ->> CONNECT {"lang": "python3"} ### Response: def _connect_command(self): ''' Generates a JSON string with the params to be used...
def group_dict(self, group: str) -> Dict[str, Any]: """The names and values of options in a group. Useful for copying options into Application settings:: from tornado.options import define, parse_command_line, options define('template_path', group='application') de...
The names and values of options in a group. Useful for copying options into Application settings:: from tornado.options import define, parse_command_line, options define('template_path', group='application') define('static_path', group='application') parse_com...
Below is the the instruction that describes the task: ### Input: The names and values of options in a group. Useful for copying options into Application settings:: from tornado.options import define, parse_command_line, options define('template_path', group='application') ...
def end(self): """End the roaster control process via thread signal. This simply sends an exit signal to the thread, and shuts it down. In order to stop monitoring, call the `set_monitor` method with false. :returns: None """ self._process.shutdown() self._roast...
End the roaster control process via thread signal. This simply sends an exit signal to the thread, and shuts it down. In order to stop monitoring, call the `set_monitor` method with false. :returns: None
Below is the the instruction that describes the task: ### Input: End the roaster control process via thread signal. This simply sends an exit signal to the thread, and shuts it down. In order to stop monitoring, call the `set_monitor` method with false. :returns: None ### Response: def en...
def add_job(self, job_name, job_id=None): """ Create a new, empty Job. """ logger.debug('Creating a new job named {0}'.format(job_name)) if not self._name_is_available(job_name): raise DagobahError('name %s is not available' % job_name) if not job_id: job_id = se...
Create a new, empty Job.
Below is the the instruction that describes the task: ### Input: Create a new, empty Job. ### Response: def add_job(self, job_name, job_id=None): """ Create a new, empty Job. """ logger.debug('Creating a new job named {0}'.format(job_name)) if not self._name_is_available(job_name): ...
def decode(self, s, _w=WHITESPACE.match): """Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) """ obj, end = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if end != len(s): raise JSONDeco...
Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document)
Below is the the instruction that describes the task: ### Input: Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) ### Response: def decode(self, s, _w=WHITESPACE.match): """Return the Python representation of ``s`` (a ``str`` or ``unicode`` ...
def dokent(data, NN): """ gets Kent parameters for data Parameters ___________________ data : nested pairs of [Dec,Inc] NN : normalization NN is the number of data for Kent ellipse NN is 1 for Kent ellipses of bootstrapped mean directions Return kpars dictionary keys ...
gets Kent parameters for data Parameters ___________________ data : nested pairs of [Dec,Inc] NN : normalization NN is the number of data for Kent ellipse NN is 1 for Kent ellipses of bootstrapped mean directions Return kpars dictionary keys dec : mean declination ...
Below is the the instruction that describes the task: ### Input: gets Kent parameters for data Parameters ___________________ data : nested pairs of [Dec,Inc] NN : normalization NN is the number of data for Kent ellipse NN is 1 for Kent ellipses of bootstrapped mean directions ...
def is_available(self, rtdc_ds, verbose=False): """Check whether the feature is available Parameters ---------- rtdc_ds: instance of RTDCBase The dataset to check availability for Returns ------- available: bool `True`, if feature can be ...
Check whether the feature is available Parameters ---------- rtdc_ds: instance of RTDCBase The dataset to check availability for Returns ------- available: bool `True`, if feature can be computed with `compute` Notes ----- ...
Below is the the instruction that describes the task: ### Input: Check whether the feature is available Parameters ---------- rtdc_ds: instance of RTDCBase The dataset to check availability for Returns ------- available: bool `True`, if featu...
def html(tag): """Return sequence of start and end regex patterns for simple HTML tag""" return (HTML_START.format(tag=tag), HTML_END.format(tag=tag))
Return sequence of start and end regex patterns for simple HTML tag
Below is the the instruction that describes the task: ### Input: Return sequence of start and end regex patterns for simple HTML tag ### Response: def html(tag): """Return sequence of start and end regex patterns for simple HTML tag""" return (HTML_START.format(tag=tag), HTML_END.format(tag=tag))
def create_CAG_with_indicators(input, output, filename="CAG_with_indicators.pdf"): """ Create a CAG with mapped indicators """ with open(input, "rb") as f: G = pickle.load(f) G.map_concepts_to_indicators(min_temporal_res="month") G.set_indicator("UN/events/weather/precipitation", "Historical Ave...
Create a CAG with mapped indicators
Below is the the instruction that describes the task: ### Input: Create a CAG with mapped indicators ### Response: def create_CAG_with_indicators(input, output, filename="CAG_with_indicators.pdf"): """ Create a CAG with mapped indicators """ with open(input, "rb") as f: G = pickle.load(f) G.map...
def dec2dms(x): """ Convert decimal degrees into a sexagessimal string in degrees. Parameters ---------- x : float Angle in degrees Returns ------- dms : string String of format [+-]DD:MM:SS.SS or XX:XX:XX.XX if x is not finite. """ if not np.isfinite(x)...
Convert decimal degrees into a sexagessimal string in degrees. Parameters ---------- x : float Angle in degrees Returns ------- dms : string String of format [+-]DD:MM:SS.SS or XX:XX:XX.XX if x is not finite.
Below is the the instruction that describes the task: ### Input: Convert decimal degrees into a sexagessimal string in degrees. Parameters ---------- x : float Angle in degrees Returns ------- dms : string String of format [+-]DD:MM:SS.SS or XX:XX:XX.XX if x is not ...
def resolve_pid(fetched_pid): """Retrieve the real PID given a fetched PID. :param pid: fetched PID to resolve. """ return PersistentIdentifier.get( pid_type=fetched_pid.pid_type, pid_value=fetched_pid.pid_value, pid_provider=fetched_pid.provider.pid_provider )
Retrieve the real PID given a fetched PID. :param pid: fetched PID to resolve.
Below is the the instruction that describes the task: ### Input: Retrieve the real PID given a fetched PID. :param pid: fetched PID to resolve. ### Response: def resolve_pid(fetched_pid): """Retrieve the real PID given a fetched PID. :param pid: fetched PID to resolve. """ return PersistentId...
def execute_command(self, command): """Execute a command Args: command (str) Returns: process (object) """ self.runner.info_log("Executing command: %s" % command) process = Popen( command, stdout=open(os.devnull,...
Execute a command Args: command (str) Returns: process (object)
Below is the the instruction that describes the task: ### Input: Execute a command Args: command (str) Returns: process (object) ### Response: def execute_command(self, command): """Execute a command Args: command (str) Returns: ...
def now(self, when=None): """Set the current value to the correct tuple based on the seconds since the epoch. If 'when' is not provided, get the current time from the task manager. """ if when is None: when = _TaskManager().get_time() tup = time.localtime(whe...
Set the current value to the correct tuple based on the seconds since the epoch. If 'when' is not provided, get the current time from the task manager.
Below is the the instruction that describes the task: ### Input: Set the current value to the correct tuple based on the seconds since the epoch. If 'when' is not provided, get the current time from the task manager. ### Response: def now(self, when=None): """Set the current value to the c...
def delete_policy_version(policyName, policyVersionId, region=None, key=None, keyid=None, profile=None): ''' Given a policy name and version, delete it. Returns {deleted: true} if the policy version was deleted and returns {deleted: false} if the policy version was not deleted. CLI Exa...
Given a policy name and version, delete it. Returns {deleted: true} if the policy version was deleted and returns {deleted: false} if the policy version was not deleted. CLI Example: .. code-block:: bash salt myminion boto_iot.delete_policy_version mypolicy version
Below is the the instruction that describes the task: ### Input: Given a policy name and version, delete it. Returns {deleted: true} if the policy version was deleted and returns {deleted: false} if the policy version was not deleted. CLI Example: .. code-block:: bash salt myminion boto_...
def has_wrap_around_links(self, minimum_working=0.9): """Test if a machine has wrap-around connections installed. Since the Machine object does not explicitly define whether a machine has wrap-around links they must be tested for directly. This test performs a "fuzzy" test on the number...
Test if a machine has wrap-around connections installed. Since the Machine object does not explicitly define whether a machine has wrap-around links they must be tested for directly. This test performs a "fuzzy" test on the number of wrap-around links which are working to determine if w...
Below is the the instruction that describes the task: ### Input: Test if a machine has wrap-around connections installed. Since the Machine object does not explicitly define whether a machine has wrap-around links they must be tested for directly. This test performs a "fuzzy" test on the nu...
def is_time_older(self): """ Check if the current time is older than the one in the database. """ if ( self._authorization() and self.is_in_database() and int( PyFunceble.INTERN["whois_db"][PyFunceble.INTERN["file_to_test"]][ ...
Check if the current time is older than the one in the database.
Below is the the instruction that describes the task: ### Input: Check if the current time is older than the one in the database. ### Response: def is_time_older(self): """ Check if the current time is older than the one in the database. """ if ( self._authorization() ...
def avg_grads(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. The inner ...
Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. The inner list is over the gradient c...
Below is the the instruction that describes the task: ### Input: Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is o...
def present( name, user=None, fingerprint=None, key=None, port=None, enc=None, config=None, hash_known_hosts=True, timeout=5, fingerprint_hash_type=None): ''' Verifies that the specified host is known by the specified user On m...
Verifies that the specified host is known by the specified user On many systems, specifically those running with openssh 4 or older, the ``enc`` option must be set, only openssh 5 and above can detect the key type. name The name of the remote host (e.g. "github.com") Note that only a s...
Below is the the instruction that describes the task: ### Input: Verifies that the specified host is known by the specified user On many systems, specifically those running with openssh 4 or older, the ``enc`` option must be set, only openssh 5 and above can detect the key type. name The n...
def _process_files(self, record_id, data): """Snapshot bucket and add files in record during first publishing.""" if self.files: assert not self.files.bucket.locked self.files.bucket.locked = True snapshot = self.files.bucket.snapshot(lock=True) data['_fil...
Snapshot bucket and add files in record during first publishing.
Below is the the instruction that describes the task: ### Input: Snapshot bucket and add files in record during first publishing. ### Response: def _process_files(self, record_id, data): """Snapshot bucket and add files in record during first publishing.""" if self.files: assert not sel...
def key(self): """ Example:: /browse/homes/ca/ -> ca /browse/homes/ca/los-angeles-county/ -> los-angeles-county /browse/homes/ca/los-angeles-county/91001/ -> 91001 /browse/homes/ca/los-angeles-county/91001/tola-ave_5038895/ -> tola-ave_5038895 :r...
Example:: /browse/homes/ca/ -> ca /browse/homes/ca/los-angeles-county/ -> los-angeles-county /browse/homes/ca/los-angeles-county/91001/ -> 91001 /browse/homes/ca/los-angeles-county/91001/tola-ave_5038895/ -> tola-ave_5038895 :return:
Below is the the instruction that describes the task: ### Input: Example:: /browse/homes/ca/ -> ca /browse/homes/ca/los-angeles-county/ -> los-angeles-county /browse/homes/ca/los-angeles-county/91001/ -> 91001 /browse/homes/ca/los-angeles-county/91001/tola-ave_503889...
def count(cls, *criterion, **kwargs): """Returns a count of the instances meeting the specified filter criterion and kwargs. Examples: >>> User.count() 500 >>> User.count(country="India") 300 >>> User.count(User.age > 50, country="I...
Returns a count of the instances meeting the specified filter criterion and kwargs. Examples: >>> User.count() 500 >>> User.count(country="India") 300 >>> User.count(User.age > 50, country="India") 39
Below is the the instruction that describes the task: ### Input: Returns a count of the instances meeting the specified filter criterion and kwargs. Examples: >>> User.count() 500 >>> User.count(country="India") 300 >>> User.count(User....
def get_changes(self, checks=None, imports=None, resources=None, task_handle=taskhandle.NullTaskHandle()): """Get the changes needed by this restructuring `resources` can be a list of `rope.base.resources.File`\s to apply the restructuring on. If `None`, the restructuring w...
Get the changes needed by this restructuring `resources` can be a list of `rope.base.resources.File`\s to apply the restructuring on. If `None`, the restructuring will be applied to all python files. `checks` argument has been deprecated. Use the `args` argument of the constr...
Below is the the instruction that describes the task: ### Input: Get the changes needed by this restructuring `resources` can be a list of `rope.base.resources.File`\s to apply the restructuring on. If `None`, the restructuring will be applied to all python files. `checks` argumen...
def from_xyz(x, y, z, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CIE-XYZ values. Parameters: :x: The Red component value [0...1] :y: The Green component value [0...1] :z: The Blue component value [0...1] :alpha: The col...
Create a new instance based on the specifed CIE-XYZ values. Parameters: :x: The Red component value [0...1] :y: The Green component value [0...1] :z: The Blue component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: ...
Below is the the instruction that describes the task: ### Input: Create a new instance based on the specifed CIE-XYZ values. Parameters: :x: The Red component value [0...1] :y: The Green component value [0...1] :z: The Blue component value [0...1] :alpha: ...
def read(self): "Connect to the feedback service and read all data." log.msg('APNSService read (connecting)') try: server, port = ((FEEDBACK_SERVER_SANDBOX_HOSTNAME if self.environment == 'sandbox' else FEEDBACK_SERVER_HOSTNAME), FEEDBACK_SERVER_PORT) ...
Connect to the feedback service and read all data.
Below is the the instruction that describes the task: ### Input: Connect to the feedback service and read all data. ### Response: def read(self): "Connect to the feedback service and read all data." log.msg('APNSService read (connecting)') try: server, port = ((FEEDBACK_SERVER_SANDBOX_HOSTNAME ...
def wait_for_tasks(self, tasks): """Given the service instance si and tasks, it returns after all the tasks are complete """ property_collector = self.service_instance.RetrieveContent().propertyCollector task_list = [str(task) for task in tasks] # Create filter obj_...
Given the service instance si and tasks, it returns after all the tasks are complete
Below is the the instruction that describes the task: ### Input: Given the service instance si and tasks, it returns after all the tasks are complete ### Response: def wait_for_tasks(self, tasks): """Given the service instance si and tasks, it returns after all the tasks are complete "...
def explorev2(self, datasource_type, datasource_id): """Deprecated endpoint, here for backward compatibility of urls""" return redirect(url_for( 'Superset.explore', datasource_type=datasource_type, datasource_id=datasource_id, **request.args))
Deprecated endpoint, here for backward compatibility of urls
Below is the the instruction that describes the task: ### Input: Deprecated endpoint, here for backward compatibility of urls ### Response: def explorev2(self, datasource_type, datasource_id): """Deprecated endpoint, here for backward compatibility of urls""" return redirect(url_for( 'S...
def stop_trace(self, frame=None): """Stop tracing from here""" self.tracing = False self.full = False frame = frame or sys._getframe().f_back while frame: del frame.f_trace frame = frame.f_back sys.settrace(None) log.info('Stopping trace')
Stop tracing from here
Below is the the instruction that describes the task: ### Input: Stop tracing from here ### Response: def stop_trace(self, frame=None): """Stop tracing from here""" self.tracing = False self.full = False frame = frame or sys._getframe().f_back while frame: del fr...
def _rebuffer(self): """ (very internal) refill the repeat buffer """ results = [] exceptions = [] for i in xrange(self.stride): try: results.append(self.iterable.next()) exceptions.append(False) except Exception, ex...
(very internal) refill the repeat buffer
Below is the the instruction that describes the task: ### Input: (very internal) refill the repeat buffer ### Response: def _rebuffer(self): """ (very internal) refill the repeat buffer """ results = [] exceptions = [] for i in xrange(self.stride): try: ...
def commit(self): """ commit the injections desired, overwriting any previous injections in the file. """ self.logger.debug("Starting injections...") self.logger.debug("Injections dict is:") self.logger.debug(self.inject_dict) self.logger.debug("Clear list is:") self.logg...
commit the injections desired, overwriting any previous injections in the file.
Below is the the instruction that describes the task: ### Input: commit the injections desired, overwriting any previous injections in the file. ### Response: def commit(self): """ commit the injections desired, overwriting any previous injections in the file. """ self.logger.debug("Starting inject...
def create(message_type, priority=0): """Create a ProtocolMessage.""" message = protobuf.ProtocolMessage() message.type = message_type message.priority = priority return message
Create a ProtocolMessage.
Below is the the instruction that describes the task: ### Input: Create a ProtocolMessage. ### Response: def create(message_type, priority=0): """Create a ProtocolMessage.""" message = protobuf.ProtocolMessage() message.type = message_type message.priority = priority return message
def commitLine(self, line) : """Commits a line making it ready to be streamed to a file and saves the current buffer if needed. If no stream is active, raises a ValueError""" if self.streamBuffer is None : raise ValueError("Commit lines is only for when you are streaming to a file") self.streamBuffer.append(l...
Commits a line making it ready to be streamed to a file and saves the current buffer if needed. If no stream is active, raises a ValueError
Below is the the instruction that describes the task: ### Input: Commits a line making it ready to be streamed to a file and saves the current buffer if needed. If no stream is active, raises a ValueError ### Response: def commitLine(self, line) : """Commits a line making it ready to be streamed to a file and sa...
def querypath(self, block, path): """An XPath-like interface to `query`.""" class BadPath(Exception): """Bad path exception thrown when path cannot be found.""" pass results = self.query(block) ROOT, SEP, WORD, FINAL = six.moves.range(4) # pylint: di...
An XPath-like interface to `query`.
Below is the the instruction that describes the task: ### Input: An XPath-like interface to `query`. ### Response: def querypath(self, block, path): """An XPath-like interface to `query`.""" class BadPath(Exception): """Bad path exception thrown when path cannot be found.""" ...
def get_domain_home_from_url(url): """ parse url for domain and homepage :param url: the req url :type url: str :return: (homepage, domain) :rtype: """ p = parse.urlparse(url) if p.netloc: return '{}://{}'.format(p.scheme, p.netloc), p.netloc else: return '', ''
parse url for domain and homepage :param url: the req url :type url: str :return: (homepage, domain) :rtype:
Below is the the instruction that describes the task: ### Input: parse url for domain and homepage :param url: the req url :type url: str :return: (homepage, domain) :rtype: ### Response: def get_domain_home_from_url(url): """ parse url for domain and homepage :param url: the req url ...
def input_to_fastq( self, input_file, sample_name, paired_end, fastq_folder, output_file=None, multiclass=False): """ Builds a command to convert input file to fastq, for various inputs. Takes either .bam, .fastq.gz, or .fastq input and returns commands that will create ...
Builds a command to convert input file to fastq, for various inputs. Takes either .bam, .fastq.gz, or .fastq input and returns commands that will create the .fastq file, regardless of input type. This is useful to made your pipeline easily accept any of these input types seamlessly, sta...
Below is the the instruction that describes the task: ### Input: Builds a command to convert input file to fastq, for various inputs. Takes either .bam, .fastq.gz, or .fastq input and returns commands that will create the .fastq file, regardless of input type. This is useful to made your pi...
def to_header(self, span_context): """Convert a SpanContext object to header string. :type span_context: :class:`~opencensus.trace.span_context.SpanContext` :param span_context: SpanContext object. :rtype: str :returns: A trace context header string in google cloud ...
Convert a SpanContext object to header string. :type span_context: :class:`~opencensus.trace.span_context.SpanContext` :param span_context: SpanContext object. :rtype: str :returns: A trace context header string in google cloud format.
Below is the the instruction that describes the task: ### Input: Convert a SpanContext object to header string. :type span_context: :class:`~opencensus.trace.span_context.SpanContext` :param span_context: SpanContext object. :rtype: str :returns: A trace context header ...
def get_text(revision, strip=True): """Extract the text from a revision. Args: revision: a string strip: a boolean Returns: a string """ # text start tag looks like "<text ..otherstuff>" start_pos = revision.find("<text") assert start_pos != -1 end_tag_pos = revision.find(">", start_pos) ...
Extract the text from a revision. Args: revision: a string strip: a boolean Returns: a string
Below is the the instruction that describes the task: ### Input: Extract the text from a revision. Args: revision: a string strip: a boolean Returns: a string ### Response: def get_text(revision, strip=True): """Extract the text from a revision. Args: revision: a string strip: a bool...
def get_work_spec(self, work_spec_name): '''Get the dictionary defining some work spec.''' with self.registry.lock(identifier=self.worker_id) as session: return session.get(WORK_SPECS, work_spec_name)
Get the dictionary defining some work spec.
Below is the the instruction that describes the task: ### Input: Get the dictionary defining some work spec. ### Response: def get_work_spec(self, work_spec_name): '''Get the dictionary defining some work spec.''' with self.registry.lock(identifier=self.worker_id) as session: return ses...
def setCurrency( self, currency ): """ Sets the currency for this widget. :param currency | <str> """ self._currency = currency self.setValue(self.value())
Sets the currency for this widget. :param currency | <str>
Below is the the instruction that describes the task: ### Input: Sets the currency for this widget. :param currency | <str> ### Response: def setCurrency( self, currency ): """ Sets the currency for this widget. :param currency | <str> """ ...
def top_sentences (kernel, path): """ determine distance for each sentence """ key_sent = {} i = 0 if isinstance(path, str): path = json_iter(path) for meta in path: graf = meta["graf"] tagged_sent = [WordNode._make(x) for x in graf] text = " ".join([w.raw f...
determine distance for each sentence
Below is the the instruction that describes the task: ### Input: determine distance for each sentence ### Response: def top_sentences (kernel, path): """ determine distance for each sentence """ key_sent = {} i = 0 if isinstance(path, str): path = json_iter(path) for meta in p...
def sjoiner(inbox, s=None, join=""): """ String joins input with indices in s. Arguments: - s(sequence) [default: ``None``] ``tuple`` or ``list`` of indices of the elements which will be joined. - join(``str``) [default: ``""``] String which will join the elements of the inbo...
String joins input with indices in s. Arguments: - s(sequence) [default: ``None``] ``tuple`` or ``list`` of indices of the elements which will be joined. - join(``str``) [default: ``""``] String which will join the elements of the inbox i.e. ``join.join()``.
Below is the the instruction that describes the task: ### Input: String joins input with indices in s. Arguments: - s(sequence) [default: ``None``] ``tuple`` or ``list`` of indices of the elements which will be joined. - join(``str``) [default: ``""``] String which will join the elements o...
def ls(url='http://localhost:8080/manager', timeout=180): ''' list all the deployed webapps url : http://localhost:8080/manager the URL of the server manager webapp timeout : 180 timeout for HTTP request CLI Examples: .. code-block:: bash salt '*' tomcat.ls sa...
list all the deployed webapps url : http://localhost:8080/manager the URL of the server manager webapp timeout : 180 timeout for HTTP request CLI Examples: .. code-block:: bash salt '*' tomcat.ls salt '*' tomcat.ls http://localhost:8080/manager
Below is the the instruction that describes the task: ### Input: list all the deployed webapps url : http://localhost:8080/manager the URL of the server manager webapp timeout : 180 timeout for HTTP request CLI Examples: .. code-block:: bash salt '*' tomcat.ls sal...
def get_zone(): ''' Get current timezone (i.e. America/Denver) Returns: str: Timezone in unix format Raises: CommandExecutionError: If timezone could not be gathered CLI Example: .. code-block:: bash salt '*' timezone.get_zone ''' cmd = ['tzutil', '/g'] r...
Get current timezone (i.e. America/Denver) Returns: str: Timezone in unix format Raises: CommandExecutionError: If timezone could not be gathered CLI Example: .. code-block:: bash salt '*' timezone.get_zone
Below is the the instruction that describes the task: ### Input: Get current timezone (i.e. America/Denver) Returns: str: Timezone in unix format Raises: CommandExecutionError: If timezone could not be gathered CLI Example: .. code-block:: bash salt '*' timezone.get_zone...
def run_symmetrized_readout(self, program: Program, trials: int) -> np.ndarray: """ Run a quil program in such a way that the readout error is made collectively symmetric This means the probability of a bitstring ``b`` being mistaken for a bitstring ``c`` is the same as the probability ...
Run a quil program in such a way that the readout error is made collectively symmetric This means the probability of a bitstring ``b`` being mistaken for a bitstring ``c`` is the same as the probability of ``not(b)`` being mistaken for ``not(c)`` A more general symmetrization would guarantee t...
Below is the the instruction that describes the task: ### Input: Run a quil program in such a way that the readout error is made collectively symmetric This means the probability of a bitstring ``b`` being mistaken for a bitstring ``c`` is the same as the probability of ``not(b)`` being mistaken fo...
def execute(self, target, source, env, executor=None): """Execute a command action. This will handle lists of commands as well as individual commands, because construction variable substitution may turn a single "command" into a list. This means that this class can actually han...
Execute a command action. This will handle lists of commands as well as individual commands, because construction variable substitution may turn a single "command" into a list. This means that this class can actually handle lists of commands, even though that's not how we use it ...
Below is the the instruction that describes the task: ### Input: Execute a command action. This will handle lists of commands as well as individual commands, because construction variable substitution may turn a single "command" into a list. This means that this class can actually ...
def diff_summary(self, old, new, rel_path=None): """ Provides a summarized output of a diff between two revisions (file, change type, file type) """ full_url_or_path = self.__url_or_path if rel_path is not None: full_url_or_path += '/' + rel_path resul...
Provides a summarized output of a diff between two revisions (file, change type, file type)
Below is the the instruction that describes the task: ### Input: Provides a summarized output of a diff between two revisions (file, change type, file type) ### Response: def diff_summary(self, old, new, rel_path=None): """ Provides a summarized output of a diff between two revisions ...
def energy_upperbound(self, spins): """A formula for an upper bound on the energy of Theta with spins fixed. Args: spins (dict): Spin values for a subset of the variables in Theta. Returns: Formula that upper bounds the energy with spins fixed. """ subt...
A formula for an upper bound on the energy of Theta with spins fixed. Args: spins (dict): Spin values for a subset of the variables in Theta. Returns: Formula that upper bounds the energy with spins fixed.
Below is the the instruction that describes the task: ### Input: A formula for an upper bound on the energy of Theta with spins fixed. Args: spins (dict): Spin values for a subset of the variables in Theta. Returns: Formula that upper bounds the energy with spins fixed. ###...