code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def rm_token(opts, tok): ''' Remove token from the store. :param opts: Salt master config options :param tok: Token to remove :returns: Empty dict if successful. None if failed. ''' t_path = os.path.join(opts['token_dir'], tok) try: os.remove(t_path) return {} except...
Remove token from the store. :param opts: Salt master config options :param tok: Token to remove :returns: Empty dict if successful. None if failed.
Below is the the instruction that describes the task: ### Input: Remove token from the store. :param opts: Salt master config options :param tok: Token to remove :returns: Empty dict if successful. None if failed. ### Response: def rm_token(opts, tok): ''' Remove token from the store. :pa...
def drawBackground( self, painter, opt, rect, brush ): """ Make sure the background extends to 0 for the first item. :param painter | <QtGui.QPainter> rect | <QtCore.QRect> brush | <QtGui.QBrush> """ if not brush:...
Make sure the background extends to 0 for the first item. :param painter | <QtGui.QPainter> rect | <QtCore.QRect> brush | <QtGui.QBrush>
Below is the the instruction that describes the task: ### Input: Make sure the background extends to 0 for the first item. :param painter | <QtGui.QPainter> rect | <QtCore.QRect> brush | <QtGui.QBrush> ### Response: def drawBackground( self, pa...
def random_digit_or_empty(self): """ Returns a random digit/number between 0 and 9 or an empty string. """ if self.generator.random.randint(0, 1): return self.generator.random.randint(0, 9) else: return ''
Returns a random digit/number between 0 and 9 or an empty string.
Below is the the instruction that describes the task: ### Input: Returns a random digit/number between 0 and 9 or an empty string. ### Response: def random_digit_or_empty(self): """ Returns a random digit/number between 0 and 9 or an empty string. """ if self.generat...
def get_distinct_segments(self, left_offset = 0, right_offset = 0, sequence_length = None): '''Returns a list of segments (pairs of start and end positions) based on the loop definitions. The returned segments merge overlapping loops e.g. if the loops file contains sections 32-40, 23-30, 28-33, and ...
Returns a list of segments (pairs of start and end positions) based on the loop definitions. The returned segments merge overlapping loops e.g. if the loops file contains sections 32-40, 23-30, 28-33, and 43-46 then the returned segments will be [(23, 40), (43, 46)]. This may not be ...
Below is the the instruction that describes the task: ### Input: Returns a list of segments (pairs of start and end positions) based on the loop definitions. The returned segments merge overlapping loops e.g. if the loops file contains sections 32-40, 23-30, 28-33, and 43-46 then the returned ...
def set_edges(self, name: str, a: np.ndarray, b: np.ndarray, w: np.ndarray, *, axis: int) -> None: """ **DEPRECATED** - Use `ds.row_graphs[name] = g` or `ds.col_graphs[name] = g` instead """ deprecated("'set_edges' is deprecated. Use 'ds.row_graphs[name] = g' or 'ds.col_graphs[name] = g' instead") try: g =...
**DEPRECATED** - Use `ds.row_graphs[name] = g` or `ds.col_graphs[name] = g` instead
Below is the the instruction that describes the task: ### Input: **DEPRECATED** - Use `ds.row_graphs[name] = g` or `ds.col_graphs[name] = g` instead ### Response: def set_edges(self, name: str, a: np.ndarray, b: np.ndarray, w: np.ndarray, *, axis: int) -> None: """ **DEPRECATED** - Use `ds.row_graphs[name] = g...
def _validate_checksum(self, buffer): """Validate the buffer response against the checksum. When reading the serial interface, data will come back in a raw format with an included checksum process. :returns: bool """ self._log.debug("Validating the buffer") if l...
Validate the buffer response against the checksum. When reading the serial interface, data will come back in a raw format with an included checksum process. :returns: bool
Below is the the instruction that describes the task: ### Input: Validate the buffer response against the checksum. When reading the serial interface, data will come back in a raw format with an included checksum process. :returns: bool ### Response: def _validate_checksum(self, buffer): ...
def _mergedict(a, b): """Recusively merge the 2 dicts. Destructive on argument 'a'. """ for p, d1 in b.items(): if p in a: if not isinstance(d1, dict): continue _mergedict(a[p], d1) else: a[p] = d1 return a
Recusively merge the 2 dicts. Destructive on argument 'a'.
Below is the the instruction that describes the task: ### Input: Recusively merge the 2 dicts. Destructive on argument 'a'. ### Response: def _mergedict(a, b): """Recusively merge the 2 dicts. Destructive on argument 'a'. """ for p, d1 in b.items(): if p in a: if not isins...
def slicenet_middle(inputs_encoded, targets, target_space_emb, mask, hparams): """Middle part of slicenet, connecting encoder and decoder.""" def norm_fn(x, name): with tf.variable_scope(name, default_name="norm"): return common_layers.apply_norm(x, hparams.norm_type, hparams.hidden_size, ...
Middle part of slicenet, connecting encoder and decoder.
Below is the the instruction that describes the task: ### Input: Middle part of slicenet, connecting encoder and decoder. ### Response: def slicenet_middle(inputs_encoded, targets, target_space_emb, mask, hparams): """Middle part of slicenet, connecting encoder and decoder.""" def norm_fn(x, name): with t...
def _get_file_stream(self, total_content_length, content_type, filename=None, content_length=None): """Called to get a stream for the file upload. This must provide a file-like class with `read()`, `readline()` and `seek()` methods that is both writeable and readable. ...
Called to get a stream for the file upload. This must provide a file-like class with `read()`, `readline()` and `seek()` methods that is both writeable and readable. The default implementation returns a temporary file if the total content length is higher than 500KB. Because many brow...
Below is the the instruction that describes the task: ### Input: Called to get a stream for the file upload. This must provide a file-like class with `read()`, `readline()` and `seek()` methods that is both writeable and readable. The default implementation returns a temporary file if the ...
def update_user(self, username, profile, owner_privkey): """ Update profile_hash on blockchain """ url = self.base_url + "/users/" + username + "/update" owner_pubkey = get_pubkey_from_privkey(owner_privkey) payload = { 'profile': profile, '...
Update profile_hash on blockchain
Below is the the instruction that describes the task: ### Input: Update profile_hash on blockchain ### Response: def update_user(self, username, profile, owner_privkey): """ Update profile_hash on blockchain """ url = self.base_url + "/users/" + username + "/update" ow...
def update(self, id, **dict): '''Update a given item with the passed data.''' if not self._item_path: raise AttributeError('update is not available for %s' % self._item_name) target = (self._update_path or self._item_path) % id payload = json.dumps({self._item_type:dict}) ...
Update a given item with the passed data.
Below is the the instruction that describes the task: ### Input: Update a given item with the passed data. ### Response: def update(self, id, **dict): '''Update a given item with the passed data.''' if not self._item_path: raise AttributeError('update is not available for %s' % self._it...
def _bell(self): u'''ring the bell if requested.''' if self.bell_style == u'none': pass elif self.bell_style == u'visible': raise NotImplementedError(u"Bellstyle visible is not implemented yet.") elif self.bell_style == u'audible': self.console.bell() ...
u'''ring the bell if requested.
Below is the the instruction that describes the task: ### Input: u'''ring the bell if requested. ### Response: def _bell(self): u'''ring the bell if requested.''' if self.bell_style == u'none': pass elif self.bell_style == u'visible': raise NotImplementedError(u"Bell...
def _read_http_header(self, header): """Read HTTP/1.* header. Structure of HTTP/1.* header [RFC 7230]: start-line :==: request-line / status-line request-line :==: method SP request-target SP HTTP-version CRLF status-line :==: HTTP-version SP sta...
Read HTTP/1.* header. Structure of HTTP/1.* header [RFC 7230]: start-line :==: request-line / status-line request-line :==: method SP request-target SP HTTP-version CRLF status-line :==: HTTP-version SP status-code SP reason-phrase CRLF heade...
Below is the the instruction that describes the task: ### Input: Read HTTP/1.* header. Structure of HTTP/1.* header [RFC 7230]: start-line :==: request-line / status-line request-line :==: method SP request-target SP HTTP-version CRLF status-line :==: ...
def _get_block(self): """Just read a single block from your current location in _fh""" b = self._fh.read(4) # get block size bytes #print self._fh.tell() if not b: raise StopIteration block_size = struct.unpack('<i',b)[0] return self._fh.read(block_size)
Just read a single block from your current location in _fh
Below is the the instruction that describes the task: ### Input: Just read a single block from your current location in _fh ### Response: def _get_block(self): """Just read a single block from your current location in _fh""" b = self._fh.read(4) # get block size bytes #print self._fh.tell() if not ...
def response_minify(self, response): """ minify response html to decrease traffic """ if response.content_type == u'text/html; charset=utf-8': endpoint = request.endpoint or '' view_func = current_app.view_functions.get(endpoint, None) name = ( ...
minify response html to decrease traffic
Below is the the instruction that describes the task: ### Input: minify response html to decrease traffic ### Response: def response_minify(self, response): """ minify response html to decrease traffic """ if response.content_type == u'text/html; charset=utf-8': endpoin...
def _simulate(self, nreps, admix=None, Ns=500000, gen=20): """ Enter a baba.Tree object in which the 'tree' attribute (newick derived tree) has edge lengths in units of generations. You can use the 'gen' parameter to multiply branch lengths by a constant. Parameters: ----------- nreps: ...
Enter a baba.Tree object in which the 'tree' attribute (newick derived tree) has edge lengths in units of generations. You can use the 'gen' parameter to multiply branch lengths by a constant. Parameters: ----------- nreps: (int) Number of reps (loci) to simulate under the demographic s...
Below is the the instruction that describes the task: ### Input: Enter a baba.Tree object in which the 'tree' attribute (newick derived tree) has edge lengths in units of generations. You can use the 'gen' parameter to multiply branch lengths by a constant. Parameters: ----------- nreps: (i...
def quote_completions(self, completions, cword_prequote, last_wordbreak_pos): """ If the word under the cursor started with a quote (as indicated by a nonempty ``cword_prequote``), escapes occurrences of that quote character in the completions, and adds the quote to the beginning of each complet...
If the word under the cursor started with a quote (as indicated by a nonempty ``cword_prequote``), escapes occurrences of that quote character in the completions, and adds the quote to the beginning of each completion. Otherwise, escapes all characters that bash splits words on (``COMP_WORDBREAKS``), an...
Below is the the instruction that describes the task: ### Input: If the word under the cursor started with a quote (as indicated by a nonempty ``cword_prequote``), escapes occurrences of that quote character in the completions, and adds the quote to the beginning of each completion. Otherwise, escap...
def ensure_all_alt_ids_have_a_nest(nest_spec, list_elements, all_ids): """ Ensures that the alternative id's in `nest_spec` are all associated with a nest. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings tha...
Ensures that the alternative id's in `nest_spec` are all associated with a nest. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoti...
Below is the the instruction that describes the task: ### Input: Ensures that the alternative id's in `nest_spec` are all associated with a nest. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the n...
def load_raw(raw_pickle_file): """ Load a pickle file of raw recordings. Parameters ---------- raw_pickle_file : str Path to a pickle file which contains raw recordings. Returns ------- dict The loaded pickle file. """ with open(raw_pickle_file, 'rb') as f: ...
Load a pickle file of raw recordings. Parameters ---------- raw_pickle_file : str Path to a pickle file which contains raw recordings. Returns ------- dict The loaded pickle file.
Below is the the instruction that describes the task: ### Input: Load a pickle file of raw recordings. Parameters ---------- raw_pickle_file : str Path to a pickle file which contains raw recordings. Returns ------- dict The loaded pickle file. ### Response: def load_raw(r...
def routing_tree_to_tables(routes, net_keys): """Convert a set of :py:class:`~rig.place_and_route.routing_tree.RoutingTree` s into a per-chip set of routing tables. .. warning:: A :py:exc:`rig.routing_table.MultisourceRouteError` will be raised if entries with identical keys and masks b...
Convert a set of :py:class:`~rig.place_and_route.routing_tree.RoutingTree` s into a per-chip set of routing tables. .. warning:: A :py:exc:`rig.routing_table.MultisourceRouteError` will be raised if entries with identical keys and masks but with differing routes are generated. This ...
Below is the the instruction that describes the task: ### Input: Convert a set of :py:class:`~rig.place_and_route.routing_tree.RoutingTree` s into a per-chip set of routing tables. .. warning:: A :py:exc:`rig.routing_table.MultisourceRouteError` will be raised if entries with identical ...
def _schedule_log_parsing(job, job_logs, result): """Kick off the initial task that parses the log data. log_data is a list of job log objects and the result for that job """ # importing here to avoid an import loop from treeherder.log_parser.tasks import parse_logs task_types = { "er...
Kick off the initial task that parses the log data. log_data is a list of job log objects and the result for that job
Below is the the instruction that describes the task: ### Input: Kick off the initial task that parses the log data. log_data is a list of job log objects and the result for that job ### Response: def _schedule_log_parsing(job, job_logs, result): """Kick off the initial task that parses the log data. ...
def auto(self): """Returns the highest whole-number unit.""" if self._value >= 1099511627776: return self.TiB, 'TiB' if self._value >= 1073741824: return self.GiB, 'GiB' if self._value >= 1048576: return self.MiB, 'MiB' if self._value >= 1024: ...
Returns the highest whole-number unit.
Below is the the instruction that describes the task: ### Input: Returns the highest whole-number unit. ### Response: def auto(self): """Returns the highest whole-number unit.""" if self._value >= 1099511627776: return self.TiB, 'TiB' if self._value >= 1073741824: re...
def async_update(self, event): """New event for light. Check that state is part of event. Signal that light has updated state. """ self.update_attr(event.get('state', {})) super().async_update(event)
New event for light. Check that state is part of event. Signal that light has updated state.
Below is the the instruction that describes the task: ### Input: New event for light. Check that state is part of event. Signal that light has updated state. ### Response: def async_update(self, event): """New event for light. Check that state is part of event. Signal that...
def rotate(self): '''Move the first address to the last position.''' item = self._address_infos.pop(0) self._address_infos.append(item)
Move the first address to the last position.
Below is the the instruction that describes the task: ### Input: Move the first address to the last position. ### Response: def rotate(self): '''Move the first address to the last position.''' item = self._address_infos.pop(0) self._address_infos.append(item)
def ip_addresses_from_xff(value: str) -> List[str]: """ Returns a list of IP addresses (as strings), given the value of an HTTP ``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header. Args: value: the value of an HTTP ``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDE...
Returns a list of IP addresses (as strings), given the value of an HTTP ``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header. Args: value: the value of an HTTP ``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header Returns: a list of IP address as st...
Below is the the instruction that describes the task: ### Input: Returns a list of IP addresses (as strings), given the value of an HTTP ``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header. Args: value: the value of an HTTP ``X-Forwarded-For`` (or ``WSGI HTTP_X_FOR...
def flush(self): """Ensure all logging output has been flushed.""" if self.shutdown: return self.flush_buffers(force=True) self.queue.put(FLUSH_MARKER) self.queue.join()
Ensure all logging output has been flushed.
Below is the the instruction that describes the task: ### Input: Ensure all logging output has been flushed. ### Response: def flush(self): """Ensure all logging output has been flushed.""" if self.shutdown: return self.flush_buffers(force=True) self.queue.put(FLUSH_MARK...
def get_doctypes(self, default_doctypes=None): """Returns the doctypes (or mapping type names) to use.""" doctypes = self.type.get_mapping_type_name() if isinstance(doctypes, six.string_types): doctypes = [doctypes] return super(S, self).get_doctypes(default_doctypes=doctypes...
Returns the doctypes (or mapping type names) to use.
Below is the the instruction that describes the task: ### Input: Returns the doctypes (or mapping type names) to use. ### Response: def get_doctypes(self, default_doctypes=None): """Returns the doctypes (or mapping type names) to use.""" doctypes = self.type.get_mapping_type_name() if isins...
def _queryset_iterator(qs): """ Override default iterator to wrap returned items in a publishing sanity-checker "booby trap" to lazily raise an exception if DRAFT items are mistakenly returned and mis-used in a public context where only PUBLISHED items should be used. This booby trap is added w...
Override default iterator to wrap returned items in a publishing sanity-checker "booby trap" to lazily raise an exception if DRAFT items are mistakenly returned and mis-used in a public context where only PUBLISHED items should be used. This booby trap is added when all of: - the publishing middle...
Below is the the instruction that describes the task: ### Input: Override default iterator to wrap returned items in a publishing sanity-checker "booby trap" to lazily raise an exception if DRAFT items are mistakenly returned and mis-used in a public context where only PUBLISHED items should be used. ...
def imbound(clspatch, *args, **kwargs): """ :param clspatch: :param args: :param kwargs: :return: """ # todo : add example c = kwargs.pop('color', kwargs.get('edgecolor', None)) kwargs.update(facecolor='none', edgecolor=c) return impatch(clspatch, *args, **kwargs)
:param clspatch: :param args: :param kwargs: :return:
Below is the the instruction that describes the task: ### Input: :param clspatch: :param args: :param kwargs: :return: ### Response: def imbound(clspatch, *args, **kwargs): """ :param clspatch: :param args: :param kwargs: :return: """ # todo : add example c = kwargs.pop...
def parse_arguments(args): '''Parse arguments from the command line''' parser = argparse.ArgumentParser(description='Convert JAMS to .lab files') parser.add_argument('-c', '--comma-separated', dest='csv', action='store_true', ...
Parse arguments from the command line
Below is the the instruction that describes the task: ### Input: Parse arguments from the command line ### Response: def parse_arguments(args): '''Parse arguments from the command line''' parser = argparse.ArgumentParser(description='Convert JAMS to .lab files') parser.add_argument('-c', ...
def polar_direction_xyz(self): """ get current polar direction in Roche (xyz) coordinates """ return mesh.spin_in_roche(self.polar_direction_uvw, self.true_anom, self.elongan, self.eincl).astype(float)
get current polar direction in Roche (xyz) coordinates
Below is the the instruction that describes the task: ### Input: get current polar direction in Roche (xyz) coordinates ### Response: def polar_direction_xyz(self): """ get current polar direction in Roche (xyz) coordinates """ return mesh.spin_in_roche(self.polar_direction_uvw, ...
def decrypt(self, k, a, iv, e, t): """ Decrypt accoriding to the selected encryption and hashing functions. :param k: Encryption key (optional) :param a: Additional Authenticated Data :param iv: Initialization Vector :param e: Ciphertext :param t: Authentication T...
Decrypt accoriding to the selected encryption and hashing functions. :param k: Encryption key (optional) :param a: Additional Authenticated Data :param iv: Initialization Vector :param e: Ciphertext :param t: Authentication Tag Returns plaintext or raises an erro...
Below is the the instruction that describes the task: ### Input: Decrypt accoriding to the selected encryption and hashing functions. :param k: Encryption key (optional) :param a: Additional Authenticated Data :param iv: Initialization Vector :param e: Ciphertext :par...
def do_register(self, arg): """ [~thread] r - print(the value of all registers [~thread] r <register> - print(the value of a register [~thread] r <register>=<value> - change the value of a register [~thread] register - print(the value of all registers [~thread] register <...
[~thread] r - print(the value of all registers [~thread] r <register> - print(the value of a register [~thread] r <register>=<value> - change the value of a register [~thread] register - print(the value of all registers [~thread] register <register> - print(the value of a register ...
Below is the the instruction that describes the task: ### Input: [~thread] r - print(the value of all registers [~thread] r <register> - print(the value of a register [~thread] r <register>=<value> - change the value of a register [~thread] register - print(the value of all registers ...
def main(*argv): """ main driver of program """ try: url = str(argv[0]) arcgisSH = ArcGISTokenSecurityHandler() if arcgisSH.valid == False: arcpy.AddError(arcgisSH.message) return fl = FeatureLayer( url=url, securityHandler=arcgisS...
main driver of program
Below is the the instruction that describes the task: ### Input: main driver of program ### Response: def main(*argv): """ main driver of program """ try: url = str(argv[0]) arcgisSH = ArcGISTokenSecurityHandler() if arcgisSH.valid == False: arcpy.AddError(arcgisSH.mess...
def union(self, *dstreams): """ Create a unified DStream from multiple DStreams of the same type and same slide duration. """ if not dstreams: raise ValueError("should have at least one DStream to union") if len(dstreams) == 1: return dstreams[0] ...
Create a unified DStream from multiple DStreams of the same type and same slide duration.
Below is the the instruction that describes the task: ### Input: Create a unified DStream from multiple DStreams of the same type and same slide duration. ### Response: def union(self, *dstreams): """ Create a unified DStream from multiple DStreams of the same type and same slide du...
def initialize_dual(neural_net_params_object, init_dual_file=None, random_init_variance=0.01, init_nu=200.0): """Function to initialize the dual variables of the class. Args: neural_net_params_object: Object with the neural net weights, biases and types init_dual_file: Path to fil...
Function to initialize the dual variables of the class. Args: neural_net_params_object: Object with the neural net weights, biases and types init_dual_file: Path to file containing dual variables, if the path is empty, perform random initialization Expects numpy dictionary with lambda...
Below is the the instruction that describes the task: ### Input: Function to initialize the dual variables of the class. Args: neural_net_params_object: Object with the neural net weights, biases and types init_dual_file: Path to file containing dual variables, if the path is empty, perform r...
def del_edge(self, edge): """ Remove an edge from the graph. @type edge: tuple @param edge: Edge. """ u, v = edge self.node_neighbors[u].remove(v) self.del_edge_labeling((u, v)) if (u != v): self.node_neighbors[v].remove(u) ...
Remove an edge from the graph. @type edge: tuple @param edge: Edge.
Below is the the instruction that describes the task: ### Input: Remove an edge from the graph. @type edge: tuple @param edge: Edge. ### Response: def del_edge(self, edge): """ Remove an edge from the graph. @type edge: tuple @param edge: Edge. """ ...
def discretize_soil_profile(sp, incs=None, target=1.0): """ Splits the soil profile into slices and stores as dictionary :param sp: SoilProfile :param incs: array_like, increments of depth to use for each layer :param target: target depth increment size :return: dict """ if incs is Non...
Splits the soil profile into slices and stores as dictionary :param sp: SoilProfile :param incs: array_like, increments of depth to use for each layer :param target: target depth increment size :return: dict
Below is the the instruction that describes the task: ### Input: Splits the soil profile into slices and stores as dictionary :param sp: SoilProfile :param incs: array_like, increments of depth to use for each layer :param target: target depth increment size :return: dict ### Response: def discret...
def _check_valid_data(self, data): """Checks that the given data is a uint8 array with one or three channels. Parameters ---------- data : :obj:`numpy.ndarray` The data to check. Raises ------ ValueError If the data is invalid. ...
Checks that the given data is a uint8 array with one or three channels. Parameters ---------- data : :obj:`numpy.ndarray` The data to check. Raises ------ ValueError If the data is invalid.
Below is the the instruction that describes the task: ### Input: Checks that the given data is a uint8 array with one or three channels. Parameters ---------- data : :obj:`numpy.ndarray` The data to check. Raises ------ ValueError If ...
def get_object(cls, api_token, image_id_or_slug): """ Class method that will return an Image object by ID or slug. This method is used to validate the type of the image. If it is a number, it will be considered as an Image ID, instead if it is a string, it will c...
Class method that will return an Image object by ID or slug. This method is used to validate the type of the image. If it is a number, it will be considered as an Image ID, instead if it is a string, it will considered as slug.
Below is the the instruction that describes the task: ### Input: Class method that will return an Image object by ID or slug. This method is used to validate the type of the image. If it is a number, it will be considered as an Image ID, instead if it is a string, it will consid...
def render(self, compress=False): """Return a rendered representation of the color. If `compress` is true, the shortest possible representation is used; otherwise, named colors are rendered as names and all others are rendered as hex (or with the rgba function). """ if ...
Return a rendered representation of the color. If `compress` is true, the shortest possible representation is used; otherwise, named colors are rendered as names and all others are rendered as hex (or with the rgba function).
Below is the the instruction that describes the task: ### Input: Return a rendered representation of the color. If `compress` is true, the shortest possible representation is used; otherwise, named colors are rendered as names and all others are rendered as hex (or with the rgba function). ...
def get_record(self, msg_id): """Get a specific Task Record, by msg_id.""" cursor = self._db.execute("""SELECT * FROM %s WHERE msg_id==?"""%self.table, (msg_id,)) line = cursor.fetchone() if line is None: raise KeyError("No such msg: %r"%msg_id) return self._list_to_d...
Get a specific Task Record, by msg_id.
Below is the the instruction that describes the task: ### Input: Get a specific Task Record, by msg_id. ### Response: def get_record(self, msg_id): """Get a specific Task Record, by msg_id.""" cursor = self._db.execute("""SELECT * FROM %s WHERE msg_id==?"""%self.table, (msg_id,)) line = cur...
def parse_contact(self): """Parse a top level contact expression, these consist of a name expression a special char and an email expression. The characters found in a name and email expression are returned. """ self.parse_whitespace() name = self.parse_name() # parse a ...
Parse a top level contact expression, these consist of a name expression a special char and an email expression. The characters found in a name and email expression are returned.
Below is the the instruction that describes the task: ### Input: Parse a top level contact expression, these consist of a name expression a special char and an email expression. The characters found in a name and email expression are returned. ### Response: def parse_contact(self): """Pars...
def ensembl_to_kegg(organism,kegg_db): """ Looks up KEGG mappings of KEGG ids to ensembl ids :param organism: an organisms as listed in organismsKEGG() :param kegg_db: a matching KEGG db as reported in databasesKEGG :returns: a Pandas dataframe of with 'KEGGid' and 'ENSid'. """ print("KEG...
Looks up KEGG mappings of KEGG ids to ensembl ids :param organism: an organisms as listed in organismsKEGG() :param kegg_db: a matching KEGG db as reported in databasesKEGG :returns: a Pandas dataframe of with 'KEGGid' and 'ENSid'.
Below is the the instruction that describes the task: ### Input: Looks up KEGG mappings of KEGG ids to ensembl ids :param organism: an organisms as listed in organismsKEGG() :param kegg_db: a matching KEGG db as reported in databasesKEGG :returns: a Pandas dataframe of with 'KEGGid' and 'ENSid'. ### R...
def generate_one(self): """Generate a single element. Returns ------- element An element from the domain. Examples ------- >>> generator = RepellentGenerator(['a', 'b']) >>> gen_item = generator.generate_one() >>> gen_ite...
Generate a single element. Returns ------- element An element from the domain. Examples ------- >>> generator = RepellentGenerator(['a', 'b']) >>> gen_item = generator.generate_one() >>> gen_item in ['a', 'b'] True
Below is the the instruction that describes the task: ### Input: Generate a single element. Returns ------- element An element from the domain. Examples ------- >>> generator = RepellentGenerator(['a', 'b']) >>> gen_item = generator....
def get_channel_info(self): """ Returns the first data row from Channel.csv """ csv_filename = get_metadata_file_path(channeldir=self.channeldir, filename=self.channelinfo) csv_lines = _read_csv_lines(csv_filename) dict_reader = csv.DictReader(csv_lines) channel_c...
Returns the first data row from Channel.csv
Below is the the instruction that describes the task: ### Input: Returns the first data row from Channel.csv ### Response: def get_channel_info(self): """ Returns the first data row from Channel.csv """ csv_filename = get_metadata_file_path(channeldir=self.channeldir, filename=self....
def respond_to_SIGTERM(signal_number, frame, target=None): """ these classes are instrumented to respond to a KeyboardInterrupt by cleanly shutting down. This function, when given as a handler to for a SIGTERM event, will make the program respond to a SIGTERM as neatly as it responds to ^C. This f...
these classes are instrumented to respond to a KeyboardInterrupt by cleanly shutting down. This function, when given as a handler to for a SIGTERM event, will make the program respond to a SIGTERM as neatly as it responds to ^C. This function is used in registering a signal handler from the signal ...
Below is the the instruction that describes the task: ### Input: these classes are instrumented to respond to a KeyboardInterrupt by cleanly shutting down. This function, when given as a handler to for a SIGTERM event, will make the program respond to a SIGTERM as neatly as it responds to ^C. This...
def deauth(self): """ Resets authentication info. Calls stop_crypto() if RFID is in auth state """ self.method = None self.key = None self.last_auth = None if self.debug: print("Changing auth key and method to None") if self.rfid.authed: ...
Resets authentication info. Calls stop_crypto() if RFID is in auth state
Below is the the instruction that describes the task: ### Input: Resets authentication info. Calls stop_crypto() if RFID is in auth state ### Response: def deauth(self): """ Resets authentication info. Calls stop_crypto() if RFID is in auth state """ self.method = None self....
def get_checker_executable(name): """Return checker executable in the form of a list of arguments for subprocess.Popen""" if programs.is_program_installed(name): # Checker is properly installed return [name] else: path1 = programs.python_script_exists(package=None, ...
Return checker executable in the form of a list of arguments for subprocess.Popen
Below is the the instruction that describes the task: ### Input: Return checker executable in the form of a list of arguments for subprocess.Popen ### Response: def get_checker_executable(name): """Return checker executable in the form of a list of arguments for subprocess.Popen""" if programs....
def get_client_premaster_secret(self, password_hash, server_public, client_private, common_secret): """S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int """...
S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int
Below is the the instruction that describes the task: ### Input: S = (B - (k * g^x)) ^ (a + (u * x)) % N :param int server_public: :param int password_hash: :param int client_private: :param int common_secret: :rtype: int ### Response: def get_client_premaster_secret(self, ...
def decode_chain_list(in_bytes): """Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN :param in_bytes: the input bytes :return the decoded list of strings""" tot_strings = len(in_bytes) // mmtf.utils.constants.CHAIN_LEN out_strings = [] for i in range(tot_str...
Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN :param in_bytes: the input bytes :return the decoded list of strings
Below is the the instruction that describes the task: ### Input: Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN :param in_bytes: the input bytes :return the decoded list of strings ### Response: def decode_chain_list(in_bytes): """Convert a list of bytes to a lis...
def unpack(cls, rawpacket): """Instantiate `Packet` from binary string. :param rawpacket: TSIP pkt in binary format. :type rawpacket: String. `rawpacket` must already have framing (DLE...DLE/ETX) removed and byte stuffing reversed. """ structs_ = g...
Instantiate `Packet` from binary string. :param rawpacket: TSIP pkt in binary format. :type rawpacket: String. `rawpacket` must already have framing (DLE...DLE/ETX) removed and byte stuffing reversed.
Below is the the instruction that describes the task: ### Input: Instantiate `Packet` from binary string. :param rawpacket: TSIP pkt in binary format. :type rawpacket: String. `rawpacket` must already have framing (DLE...DLE/ETX) removed and byte stuffing reversed. ### ...
def is_op(call, op): """ :param call: The specific operator instance (a method call) :param op: The the operator we are testing against :return: isinstance(call, op), but faster """ try: return call.id == op.id except Exception as e: return False
:param call: The specific operator instance (a method call) :param op: The the operator we are testing against :return: isinstance(call, op), but faster
Below is the the instruction that describes the task: ### Input: :param call: The specific operator instance (a method call) :param op: The the operator we are testing against :return: isinstance(call, op), but faster ### Response: def is_op(call, op): """ :param call: The specific operator instanc...
def add_script_sequence(self): """ creates a script sequence based on the script iterator type selected and the selected scripts and sends it to the tree self.tree_loaded """ def empty_tree(tree_model): # COMMENT_ME def add_children_to_list(item, somelis...
creates a script sequence based on the script iterator type selected and the selected scripts and sends it to the tree self.tree_loaded
Below is the the instruction that describes the task: ### Input: creates a script sequence based on the script iterator type selected and the selected scripts and sends it to the tree self.tree_loaded ### Response: def add_script_sequence(self): """ creates a script sequence based on the sc...
def est_gaba_conc(self): """ Estimate gaba concentration based on equation adapted from Sanacora 1999, p1045 Ref: Sanacora, G., Mason, G. F., Rothman, D. L., Behar, K. L., Hyder, F., Petroff, O. A., ... & Krystal, J. H. (1999). Reduced cortical $\gamma$-aminobutyric acid...
Estimate gaba concentration based on equation adapted from Sanacora 1999, p1045 Ref: Sanacora, G., Mason, G. F., Rothman, D. L., Behar, K. L., Hyder, F., Petroff, O. A., ... & Krystal, J. H. (1999). Reduced cortical $\gamma$-aminobutyric acid levels in depressed patients determined by ...
Below is the the instruction that describes the task: ### Input: Estimate gaba concentration based on equation adapted from Sanacora 1999, p1045 Ref: Sanacora, G., Mason, G. F., Rothman, D. L., Behar, K. L., Hyder, F., Petroff, O. A., ... & Krystal, J. H. (1999). Reduced cortical $\...
def checker(func: Callable) -> Callable: """ A decorator that will convert AssertionErrors into CiVerificationError. :param func: A function that will raise AssertionError :return: The given function wrapped to raise a CiVerificationError on AssertionError """ def func_wrapper(*args, **kwa...
A decorator that will convert AssertionErrors into CiVerificationError. :param func: A function that will raise AssertionError :return: The given function wrapped to raise a CiVerificationError on AssertionError
Below is the the instruction that describes the task: ### Input: A decorator that will convert AssertionErrors into CiVerificationError. :param func: A function that will raise AssertionError :return: The given function wrapped to raise a CiVerificationError on AssertionError ### Response: def checker...
def sort_by_name(infile, outfile): '''Sorts input sequence file by sort -d -k1,1, writes sorted output file.''' seqs = {} file_to_dict(infile, seqs) #seqs = list(seqs.values()) #seqs.sort() fout = utils.open_file_write(outfile) for name in sorted(seqs): print(seqs[name], file=fout) ...
Sorts input sequence file by sort -d -k1,1, writes sorted output file.
Below is the the instruction that describes the task: ### Input: Sorts input sequence file by sort -d -k1,1, writes sorted output file. ### Response: def sort_by_name(infile, outfile): '''Sorts input sequence file by sort -d -k1,1, writes sorted output file.''' seqs = {} file_to_dict(infile, seqs) ...
def handle_cable(cable, handler, standalone=True): """\ Emits event from the provided `cable` to the handler. `cable` A cable object. `handler` A ICableHandler instance. `standalone` Indicates if a `start` and `end` event should be issued (default: ``True``). ...
\ Emits event from the provided `cable` to the handler. `cable` A cable object. `handler` A ICableHandler instance. `standalone` Indicates if a `start` and `end` event should be issued (default: ``True``). If `standalone` is set to ``False``, no ``handler.start()...
Below is the the instruction that describes the task: ### Input: \ Emits event from the provided `cable` to the handler. `cable` A cable object. `handler` A ICableHandler instance. `standalone` Indicates if a `start` and `end` event should be issued (default: ``True`...
def create_network(batch_size, update_freq): """Create a linear regression network for performing SVRG optimization. :return: an instance of mx.io.NDArrayIter :return: an instance of mx.mod.svrgmodule for performing SVRG optimization """ head = '%(asctime)-15s %(message)s' logging.basicConfig(le...
Create a linear regression network for performing SVRG optimization. :return: an instance of mx.io.NDArrayIter :return: an instance of mx.mod.svrgmodule for performing SVRG optimization
Below is the the instruction that describes the task: ### Input: Create a linear regression network for performing SVRG optimization. :return: an instance of mx.io.NDArrayIter :return: an instance of mx.mod.svrgmodule for performing SVRG optimization ### Response: def create_network(batch_size, update_freq...
def _complete_task(self, task_name, **kwargs): """ Marks this task as completed. Kwargs are stored in the run log. """ logger.debug('Job {0} marking task {1} as completed'.format(self.name, task_name)) self.run_log['tasks'][task_name] = kwargs for node in self.downstream(task_name, sel...
Marks this task as completed. Kwargs are stored in the run log.
Below is the the instruction that describes the task: ### Input: Marks this task as completed. Kwargs are stored in the run log. ### Response: def _complete_task(self, task_name, **kwargs): """ Marks this task as completed. Kwargs are stored in the run log. """ logger.debug('Job {0} marking task {...
def create_ps_command(ps_command, force_ps32=False, dont_obfs=False): amsi_bypass = """[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} try{ [Ref].Assembly.GetType('Sys'+'tem.Man'+'agement.Aut'+'omation.Am'+'siUt'+'ils').GetField('am'+'siIni'+'tFailed', 'NonP'+'ublic,Sta'+'tic').SetValue($n...
if is_powershell_installed(): temp = tempfile.NamedTemporaryFile(prefix='cme_', suffix='.ps1', dir='/tmp') temp.write(command) temp.read() encoding_types = [1,2,3,4,5,6] while True: ...
Below is the the instruction that describes the task: ### Input: if is_powershell_installed(): temp = tempfile.NamedTemporaryFile(prefix='cme_', suffix='.ps1', dir='/tmp') temp.write(command) temp.read() ...
def run(generate_pks, show_pks, host, port, uri): """Connect sandman to <URI> and start the API server/admin interface.""" app.config['SQLALCHEMY_DATABASE_URI'] = uri app.config['SANDMAN_GENERATE_PKS'] = generate_pks app.config['SANDMAN_SHOW_PKS'] = show_pks app.config['SERVER_HOST'] = host ...
Connect sandman to <URI> and start the API server/admin interface.
Below is the the instruction that describes the task: ### Input: Connect sandman to <URI> and start the API server/admin interface. ### Response: def run(generate_pks, show_pks, host, port, uri): """Connect sandman to <URI> and start the API server/admin interface.""" app.config['SQLALCHEMY_DATABAS...
def add_to_filemenu(): """Add Pyblish to file-menu .. note:: We're going a bit hacky here, probably due to my lack of understanding for `evalDeferred` or `executeDeferred`, so if you can think of a better solution, feel free to edit. """ if hasattr(cmds, 'about') and not cmds.about(ba...
Add Pyblish to file-menu .. note:: We're going a bit hacky here, probably due to my lack of understanding for `evalDeferred` or `executeDeferred`, so if you can think of a better solution, feel free to edit.
Below is the the instruction that describes the task: ### Input: Add Pyblish to file-menu .. note:: We're going a bit hacky here, probably due to my lack of understanding for `evalDeferred` or `executeDeferred`, so if you can think of a better solution, feel free to edit. ### Response: def add...
def _run_server(self, multiprocessing): """Use server multiprocessing to extract PCAP files.""" if not self._flag_m: raise UnsupportedCall(f"Extractor(engine={self._exeng})' has no attribute '_run_server'") if not self._flag_q: self._flag_q = True warnings.wa...
Use server multiprocessing to extract PCAP files.
Below is the the instruction that describes the task: ### Input: Use server multiprocessing to extract PCAP files. ### Response: def _run_server(self, multiprocessing): """Use server multiprocessing to extract PCAP files.""" if not self._flag_m: raise UnsupportedCall(f"Extractor(engine=...
def _should_really_index(self, instance): """Return True if according to should_index the object should be indexed.""" if self._should_index_is_method: is_method = inspect.ismethod(self.should_index) try: count_args = len(inspect.signature(self.should_index).param...
Return True if according to should_index the object should be indexed.
Below is the the instruction that describes the task: ### Input: Return True if according to should_index the object should be indexed. ### Response: def _should_really_index(self, instance): """Return True if according to should_index the object should be indexed.""" if self._should_index_is_metho...
def fit_lines(self, window=1500, break_thresh=1500): """ Fits lines to pitch contours. :param window: size of each chunk to which linear equation is to be fit (in milliseconds). To keep it simple, hop is chosen to be one third of the window. :param break_thresh: If there is sile...
Fits lines to pitch contours. :param window: size of each chunk to which linear equation is to be fit (in milliseconds). To keep it simple, hop is chosen to be one third of the window. :param break_thresh: If there is silence beyond this limit (in milliseconds), the contour will be brok...
Below is the the instruction that describes the task: ### Input: Fits lines to pitch contours. :param window: size of each chunk to which linear equation is to be fit (in milliseconds). To keep it simple, hop is chosen to be one third of the window. :param break_thresh: If there is silence ...
def headerData(self, section, orientation, role=Qt.DisplayRole): """Qt Override.""" if role == Qt.TextAlignmentRole: if orientation == Qt.Horizontal: return to_qvariant(int(Qt.AlignHCenter | Qt.AlignVCenter)) return to_qvariant(int(Qt.AlignRight | Qt.AlignVCe...
Qt Override.
Below is the the instruction that describes the task: ### Input: Qt Override. ### Response: def headerData(self, section, orientation, role=Qt.DisplayRole): """Qt Override.""" if role == Qt.TextAlignmentRole: if orientation == Qt.Horizontal: return to_qvariant(int(Qt...
def downsample_grid(a, b, samples, ret_idx=False): """Content-based downsampling for faster visualization The arrays `a` and `b` make up a 2D scatter plot with high and low density values. This method takes out points at indices with high density. Parameters ---------- a, b: 1d ndarrays ...
Content-based downsampling for faster visualization The arrays `a` and `b` make up a 2D scatter plot with high and low density values. This method takes out points at indices with high density. Parameters ---------- a, b: 1d ndarrays The input arrays to downsample samples: int ...
Below is the the instruction that describes the task: ### Input: Content-based downsampling for faster visualization The arrays `a` and `b` make up a 2D scatter plot with high and low density values. This method takes out points at indices with high density. Parameters ---------- a, b: 1d ...
def upload_data(job, master_ip, inputs, hdfs_name, upload_name, spark_on_toil): """ Upload file hdfsName from hdfs to s3 """ if mock_mode(): truncate_file(master_ip, hdfs_name, spark_on_toil) log.info("Uploading output BAM %s to %s.", hdfs_name, upload_name) call_conductor(job, master_...
Upload file hdfsName from hdfs to s3
Below is the the instruction that describes the task: ### Input: Upload file hdfsName from hdfs to s3 ### Response: def upload_data(job, master_ip, inputs, hdfs_name, upload_name, spark_on_toil): """ Upload file hdfsName from hdfs to s3 """ if mock_mode(): truncate_file(master_ip, hdfs_nam...
def removeChildren(self, children): ''' removeChildren - Remove multiple child AdvancedTags. @see removeChild @return list<AdvancedTag/None> - A list of all tags removed in same order as passed. Item is "None" if it was not attached to this node, and thus wa...
removeChildren - Remove multiple child AdvancedTags. @see removeChild @return list<AdvancedTag/None> - A list of all tags removed in same order as passed. Item is "None" if it was not attached to this node, and thus was not removed.
Below is the the instruction that describes the task: ### Input: removeChildren - Remove multiple child AdvancedTags. @see removeChild @return list<AdvancedTag/None> - A list of all tags removed in same order as passed. Item is "None" if it was not attached to this node, an...
def single_input(self, body): """single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE""" loc = None if body != []: loc = body[0].loc return ast.Interactive(body=body, loc=loc)
single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
Below is the the instruction that describes the task: ### Input: single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE ### Response: def single_input(self, body): """single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE""" loc = None if body != []: loc = body[0].loc ...
def rcts(self, command, *args, **kwargs): '''General function for applying a rolling R function to a timeserie''' cls = self.__class__ name = kwargs.pop('name','') date = kwargs.pop('date',None) data = kwargs.pop('data',None) kwargs.pop('bycolumn',None) ts ...
General function for applying a rolling R function to a timeserie
Below is the the instruction that describes the task: ### Input: General function for applying a rolling R function to a timeserie ### Response: def rcts(self, command, *args, **kwargs): '''General function for applying a rolling R function to a timeserie''' cls = self.__class__ name = k...
def verify_path(self, mold_id_path): """ Lookup and verify path. """ try: path = self.lookup_path(mold_id_path) if not exists(path): raise KeyError except KeyError: raise_os_error(ENOENT) return path
Lookup and verify path.
Below is the the instruction that describes the task: ### Input: Lookup and verify path. ### Response: def verify_path(self, mold_id_path): """ Lookup and verify path. """ try: path = self.lookup_path(mold_id_path) if not exists(path): raise ...
def fetch_output(self, path, name, working_directory, action_type, output_type): """ Fetch (transfer, copy, etc...) an output from the remote Pulsar server. **Parameters** path : str Local path of the dataset. name : str Remote name of file (i.e. path re...
Fetch (transfer, copy, etc...) an output from the remote Pulsar server. **Parameters** path : str Local path of the dataset. name : str Remote name of file (i.e. path relative to remote staging output or working directory). working_directory : str ...
Below is the the instruction that describes the task: ### Input: Fetch (transfer, copy, etc...) an output from the remote Pulsar server. **Parameters** path : str Local path of the dataset. name : str Remote name of file (i.e. path relative to remote staging output ...
def show_page_courses(self, url, course_id): """ Show page. Retrieve the content of a wiki page """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - P...
Show page. Retrieve the content of a wiki page
Below is the the instruction that describes the task: ### Input: Show page. Retrieve the content of a wiki page ### Response: def show_page_courses(self, url, course_id): """ Show page. Retrieve the content of a wiki page """ path = {} data = {} ...
def put_edit(self, f, *args, **kwds): """ Defer an edit to run on the EditQueue. :param callable f: The function to be called :param tuple args: Positional arguments to the function :param tuple kwds: Keyword arguments to the function :throws queue.Full: if the queue is ...
Defer an edit to run on the EditQueue. :param callable f: The function to be called :param tuple args: Positional arguments to the function :param tuple kwds: Keyword arguments to the function :throws queue.Full: if the queue is full
Below is the the instruction that describes the task: ### Input: Defer an edit to run on the EditQueue. :param callable f: The function to be called :param tuple args: Positional arguments to the function :param tuple kwds: Keyword arguments to the function :throws queue.Full: if th...
def convert_attrs_to_lowercase(obj: Any, attrs: Iterable[str]) -> None: """ Converts the specified attributes of an object to lower case, modifying the object in place. """ for a in attrs: value = getattr(obj, a) if value is None: continue setattr(obj, a, value.lo...
Converts the specified attributes of an object to lower case, modifying the object in place.
Below is the the instruction that describes the task: ### Input: Converts the specified attributes of an object to lower case, modifying the object in place. ### Response: def convert_attrs_to_lowercase(obj: Any, attrs: Iterable[str]) -> None: """ Converts the specified attributes of an object to lower...
def adjust_hue(im, hout=0.66, is_offset=True, is_clip=True, is_random=False): """Adjust hue of an RGB image. This is a convenience method that converts an RGB image to float representation, converts it to HSV, add an offset to the hue channel, converts back to RGB and then back to the original data type. F...
Adjust hue of an RGB image. This is a convenience method that converts an RGB image to float representation, converts it to HSV, add an offset to the hue channel, converts back to RGB and then back to the original data type. For TF, see `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/...
Below is the the instruction that describes the task: ### Input: Adjust hue of an RGB image. This is a convenience method that converts an RGB image to float representation, converts it to HSV, add an offset to the hue channel, converts back to RGB and then back to the original data type. For TF, see `tf.i...
def get_mcc(self, ip): ''' Get mcc ''' rec = self.get_all(ip) return rec and rec.mcc
Get mcc
Below is the the instruction that describes the task: ### Input: Get mcc ### Response: def get_mcc(self, ip): ''' Get mcc ''' rec = self.get_all(ip) return rec and rec.mcc
def upload_data(self, file_or_str, chunk_size=analyzere.upload_chunk_size, poll_interval=analyzere.upload_poll_interval, upload_callback=lambda x: None, commit_callback=lambda x: None): """ Accepts a file-like object or string and uploads it. F...
Accepts a file-like object or string and uploads it. Files are automatically uploaded in chunks. The default chunk size is 16MiB and can be overwritten by specifying the number of bytes in the ``chunk_size`` variable. Accepts an optional poll_interval for temporarily overriding the ...
Below is the the instruction that describes the task: ### Input: Accepts a file-like object or string and uploads it. Files are automatically uploaded in chunks. The default chunk size is 16MiB and can be overwritten by specifying the number of bytes in the ``chunk_size`` variable. A...
def unpublish(namespace, name, version, registry=None): ''' Try to unpublish a recently published version. Return any errors that occur. ''' registry = registry or Registry_Base_URL url = '%s/%s/%s/versions/%s' % ( registry, namespace, name, version ) he...
Try to unpublish a recently published version. Return any errors that occur.
Below is the the instruction that describes the task: ### Input: Try to unpublish a recently published version. Return any errors that occur. ### Response: def unpublish(namespace, name, version, registry=None): ''' Try to unpublish a recently published version. Return any errors that occur. ...
def load_map(map, src_file, output_dir, scale=1, cache_dir=None, datasources_cfg=None, user_styles=[], verbose=False): """ Apply a stylesheet source file to a given mapnik Map instance, like mapnik.load_map(). Parameters: map: Instance of mapnik.Map. sr...
Apply a stylesheet source file to a given mapnik Map instance, like mapnik.load_map(). Parameters: map: Instance of mapnik.Map. src_file: Location of stylesheet .mml file. Can be relative path, absolute path, or fully-qualified URL o...
Below is the the instruction that describes the task: ### Input: Apply a stylesheet source file to a given mapnik Map instance, like mapnik.load_map(). Parameters: map: Instance of mapnik.Map. src_file: Location of stylesheet .mml file. Can ...
def parser(scope, usage=''): """ Generates a default parser for the inputted scope. :param scope | <dict> || <module> usage | <str> callable | <str> :return <OptionParser> """ subcmds = [] for cmd in commands(scope): subcmds.ap...
Generates a default parser for the inputted scope. :param scope | <dict> || <module> usage | <str> callable | <str> :return <OptionParser>
Below is the the instruction that describes the task: ### Input: Generates a default parser for the inputted scope. :param scope | <dict> || <module> usage | <str> callable | <str> :return <OptionParser> ### Response: def parser(scope, usage=''): ...
def parse_result(self, data): """ Returns a YHSM_GeneratedAEAD instance, or throws pyhsm.exception.YHSM_CommandFailed. """ # typedef struct { # uint8_t nonce[YSM_AEAD_NONCE_SIZE]; // Nonce (publicId for Yubikey AEADs) # uint32_t keyHandle; // Key handl...
Returns a YHSM_GeneratedAEAD instance, or throws pyhsm.exception.YHSM_CommandFailed.
Below is the the instruction that describes the task: ### Input: Returns a YHSM_GeneratedAEAD instance, or throws pyhsm.exception.YHSM_CommandFailed. ### Response: def parse_result(self, data): """ Returns a YHSM_GeneratedAEAD instance, or throws pyhsm.exception.YHSM_CommandFailed. """ ...
def str_transmission_rate(self): """Returns a tuple of human readable transmission rates in bytes.""" upstream, downstream = self.transmission_rate return ( fritztools.format_num(upstream), fritztools.format_num(downstream) )
Returns a tuple of human readable transmission rates in bytes.
Below is the the instruction that describes the task: ### Input: Returns a tuple of human readable transmission rates in bytes. ### Response: def str_transmission_rate(self): """Returns a tuple of human readable transmission rates in bytes.""" upstream, downstream = self.transmission_rate r...
def _derive_temporalnetwork(self, f, i, tag, params, confounds_exist, confound_files): """ Funciton called by TenetoBIDS.derive_temporalnetwork for concurrent processing. """ data = load_tabular_file(f, index_col=True, header=True) fs, _ = drop_bids_suffix(f) save_name, ...
Funciton called by TenetoBIDS.derive_temporalnetwork for concurrent processing.
Below is the the instruction that describes the task: ### Input: Funciton called by TenetoBIDS.derive_temporalnetwork for concurrent processing. ### Response: def _derive_temporalnetwork(self, f, i, tag, params, confounds_exist, confound_files): """ Funciton called by TenetoBIDS.derive_temporalnetw...
def _post_query(self, **query_dict): """Perform a POST query against Solr and return the response as a Python dict.""" param_dict = query_dict.copy() return self._send_query(do_post=True, **param_dict)
Perform a POST query against Solr and return the response as a Python dict.
Below is the the instruction that describes the task: ### Input: Perform a POST query against Solr and return the response as a Python dict. ### Response: def _post_query(self, **query_dict): """Perform a POST query against Solr and return the response as a Python dict.""" param_dic...
def exec_python_rc(*args, **kwargs): """ Wrap running python script in a subprocess. Return exit code of the invoked command. """ cmdargs, kwargs = __wrap_python(args, kwargs) return exec_command_rc(*cmdargs, **kwargs)
Wrap running python script in a subprocess. Return exit code of the invoked command.
Below is the the instruction that describes the task: ### Input: Wrap running python script in a subprocess. Return exit code of the invoked command. ### Response: def exec_python_rc(*args, **kwargs): """ Wrap running python script in a subprocess. Return exit code of the invoked command. """...
def reset_tip_tracking(self): """ Resets the :any:`Pipette` tip tracking, "refilling" the tip racks """ self.current_tip(None) self.tip_rack_iter = iter([]) if self.has_tip_rack(): iterables = self.tip_racks if self.channels > 1: ...
Resets the :any:`Pipette` tip tracking, "refilling" the tip racks
Below is the the instruction that describes the task: ### Input: Resets the :any:`Pipette` tip tracking, "refilling" the tip racks ### Response: def reset_tip_tracking(self): """ Resets the :any:`Pipette` tip tracking, "refilling" the tip racks """ self.current_tip(None) sel...
def getplan(self, size="150", axes=None, padding=None): """ Identify a plan for chunking values along each dimension. Generates an ndarray with the size (in number of elements) of chunks in each dimension. If provided, will estimate chunks for only a subset of axes, leaving all ...
Identify a plan for chunking values along each dimension. Generates an ndarray with the size (in number of elements) of chunks in each dimension. If provided, will estimate chunks for only a subset of axes, leaving all others to the full size of the axis. Parameters ---------- ...
Below is the the instruction that describes the task: ### Input: Identify a plan for chunking values along each dimension. Generates an ndarray with the size (in number of elements) of chunks in each dimension. If provided, will estimate chunks for only a subset of axes, leaving all others ...
def merge_dicts(dicts, deepcopy=False): """Merges dicts In case of key conflicts, the value kept will be from the latter dictionary in the list of dictionaries :param dicts: [dict, ...] :param deepcopy: deepcopy items within dicts """ assert isinstance(dicts, list) and all(isinstance(d, di...
Merges dicts In case of key conflicts, the value kept will be from the latter dictionary in the list of dictionaries :param dicts: [dict, ...] :param deepcopy: deepcopy items within dicts
Below is the the instruction that describes the task: ### Input: Merges dicts In case of key conflicts, the value kept will be from the latter dictionary in the list of dictionaries :param dicts: [dict, ...] :param deepcopy: deepcopy items within dicts ### Response: def merge_dicts(dicts, deepcop...
def to_interval_values(self): '''Extract observation data in a `mir_eval`-friendly format. Returns ------- intervals : np.ndarray [shape=(n, 2), dtype=float] Start- and end-times of all valued intervals `intervals[i, :] = [time[i], time[i] + duration[i]]` ...
Extract observation data in a `mir_eval`-friendly format. Returns ------- intervals : np.ndarray [shape=(n, 2), dtype=float] Start- and end-times of all valued intervals `intervals[i, :] = [time[i], time[i] + duration[i]]` labels : list List view of...
Below is the the instruction that describes the task: ### Input: Extract observation data in a `mir_eval`-friendly format. Returns ------- intervals : np.ndarray [shape=(n, 2), dtype=float] Start- and end-times of all valued intervals `intervals[i, :] = [time[i], ti...
def is_measure(self): """Return true if the colum is a dimension""" from ambry.valuetype.core import ROLE return self.role == ROLE.MEASURE
Return true if the colum is a dimension
Below is the the instruction that describes the task: ### Input: Return true if the colum is a dimension ### Response: def is_measure(self): """Return true if the colum is a dimension""" from ambry.valuetype.core import ROLE return self.role == ROLE.MEASURE
def _fix_history_sequence(self, df, table): """ fix out-of-sequence ticks/bars """ # remove "Unnamed: x" columns cols = df.columns[df.columns.str.startswith('Unnamed:')].tolist() df.drop(cols, axis=1, inplace=True) # remove future dates df['datetime'] = pd.to_datetime(d...
fix out-of-sequence ticks/bars
Below is the the instruction that describes the task: ### Input: fix out-of-sequence ticks/bars ### Response: def _fix_history_sequence(self, df, table): """ fix out-of-sequence ticks/bars """ # remove "Unnamed: x" columns cols = df.columns[df.columns.str.startswith('Unnamed:')].tolist() ...
def strip_br(s): r""" Strip the trailing html linebreak character (<BR />) from a string or sequence of strings A sequence of strings is assumed to be a row in a CSV/TSV file or words from a line of text so only the last element in a sequence is "stripped" >>> strip_br(' Title <BR> ') ' Title' ...
r""" Strip the trailing html linebreak character (<BR />) from a string or sequence of strings A sequence of strings is assumed to be a row in a CSV/TSV file or words from a line of text so only the last element in a sequence is "stripped" >>> strip_br(' Title <BR> ') ' Title' >>> strip_br(list(ra...
Below is the the instruction that describes the task: ### Input: r""" Strip the trailing html linebreak character (<BR />) from a string or sequence of strings A sequence of strings is assumed to be a row in a CSV/TSV file or words from a line of text so only the last element in a sequence is "stripped" ...
def fftp(wave, npoints=None, indep_min=None, indep_max=None, unwrap=True, rad=True): r""" Return the phase of the Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** ...
r""" Return the phase of the Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector ...
Below is the the instruction that describes the task: ### Input: r""" Return the phase of the Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less ...
def norm(table): """ fit to normal distribution """ print('# norm dist is broken', file=sys.stderr) exit() from matplotlib.pyplot import hist as hist t = [] for i in table: t.append(np.ndarray.tolist(hist(i, bins = len(i), normed = True)[0])) return t
fit to normal distribution
Below is the the instruction that describes the task: ### Input: fit to normal distribution ### Response: def norm(table): """ fit to normal distribution """ print('# norm dist is broken', file=sys.stderr) exit() from matplotlib.pyplot import hist as hist t = [] for i in table: ...
def char_width(char): """ Get the display length of a unicode character. """ if ord(char) < 128: return 1 elif unicodedata.east_asian_width(char) in ('F', 'W'): return 2 elif unicodedata.category(char) in ('Mn',): return 0 else: return 1
Get the display length of a unicode character.
Below is the the instruction that describes the task: ### Input: Get the display length of a unicode character. ### Response: def char_width(char): """ Get the display length of a unicode character. """ if ord(char) < 128: return 1 elif unicodedata.east_asian_width(char) in ('F', 'W'): ...
def most_similar_catchments(self, subject_catchment, similarity_dist_function, records_limit=500, include_subject_catchment='auto'): """ Return a list of catchments sorted by hydrological similarity defined by `similarity_distance_function` :param subject_catchme...
Return a list of catchments sorted by hydrological similarity defined by `similarity_distance_function` :param subject_catchment: subject catchment to find similar catchments for :type subject_catchment: :class:`floodestimation.entities.Catchment` :param similarity_dist_function: a method retur...
Below is the the instruction that describes the task: ### Input: Return a list of catchments sorted by hydrological similarity defined by `similarity_distance_function` :param subject_catchment: subject catchment to find similar catchments for :type subject_catchment: :class:`floodestimation.entiti...
def __draw_constant_line(self, value_label_style): "Draw a constant line on the y-axis with the label" value, label, style = value_label_style start = self.transform_output_coordinates((0, value))[1] stop = self.graph_width path = etree.SubElement(self.graph, 'path', { 'd': 'M 0 %(start)s h%(stop)s' % loca...
Draw a constant line on the y-axis with the label
Below is the the instruction that describes the task: ### Input: Draw a constant line on the y-axis with the label ### Response: def __draw_constant_line(self, value_label_style): "Draw a constant line on the y-axis with the label" value, label, style = value_label_style start = self.transform_output_coordin...