code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def find(self, key): '''Get a shared variable for a parameter by name. Parameters ---------- key : str or int The name of the parameter to look up, or the index of the parameter in our parameter list. These are both dependent on the implementation of ...
Get a shared variable for a parameter by name. Parameters ---------- key : str or int The name of the parameter to look up, or the index of the parameter in our parameter list. These are both dependent on the implementation of the layer. Returns ...
Below is the the instruction that describes the task: ### Input: Get a shared variable for a parameter by name. Parameters ---------- key : str or int The name of the parameter to look up, or the index of the parameter in our parameter list. These are both dependent ...
def expected_value(self, feature=None, pstate=None, hstate=None, pstate_prob=None, hstate_prob=None): """ Determine the joint maximum likelihood estimate """ # Use the first feature by default if feature is None: feature = self.emission_name[0] # Will default...
Determine the joint maximum likelihood estimate
Below is the the instruction that describes the task: ### Input: Determine the joint maximum likelihood estimate ### Response: def expected_value(self, feature=None, pstate=None, hstate=None, pstate_prob=None, hstate_prob=None): """ Determine the joint maximum likelihood estimate """ ...
def _pys2col_widths(self, line): """Updates col_widths in code_array""" # Split with maxsplit 3 split_line = self._split_tidy(line) key = col, tab = self._get_key(*split_line[:2]) width = float(split_line[2]) shape = self.code_array.shape try: if co...
Updates col_widths in code_array
Below is the the instruction that describes the task: ### Input: Updates col_widths in code_array ### Response: def _pys2col_widths(self, line): """Updates col_widths in code_array""" # Split with maxsplit 3 split_line = self._split_tidy(line) key = col, tab = self._get_key(*split_...
def _do_to_py_ast(ctx: GeneratorContext, node: Do) -> GeneratedPyAST: """Return a Python AST Node for a `do` expression.""" assert node.op == NodeOp.DO assert not node.is_body body_ast = GeneratedPyAST.reduce( *map(partial(gen_py_ast, ctx), chain(node.statements, [node.ret])) ) fn_body...
Return a Python AST Node for a `do` expression.
Below is the the instruction that describes the task: ### Input: Return a Python AST Node for a `do` expression. ### Response: def _do_to_py_ast(ctx: GeneratorContext, node: Do) -> GeneratedPyAST: """Return a Python AST Node for a `do` expression.""" assert node.op == NodeOp.DO assert not node.is_body ...
def filter(self, twig=None, check_visible=True, check_default=True, **kwargs): """ Filter the ParameterSet based on the meta-tags of the Parameters and return another ParameterSet. Because another ParameterSet is returned, these filter calls are chainable. >>> b.filter(...
Filter the ParameterSet based on the meta-tags of the Parameters and return another ParameterSet. Because another ParameterSet is returned, these filter calls are chainable. >>> b.filter(context='component').filter(component='starA') :parameter str twig: (optional) the search ...
Below is the the instruction that describes the task: ### Input: Filter the ParameterSet based on the meta-tags of the Parameters and return another ParameterSet. Because another ParameterSet is returned, these filter calls are chainable. >>> b.filter(context='component').filter(co...
def histogram(x, edges, axis=None, extend_lower_interval=False, extend_upper_interval=False, dtype=None, name=None): """Count how often `x` falls in intervals defined by `edges`. Given `edges = [c0, ..., cK]`, defining intervals ...
Count how often `x` falls in intervals defined by `edges`. Given `edges = [c0, ..., cK]`, defining intervals `I0 = [c0, c1)`, `I1 = [c1, c2)`, ..., `I_{K-1} = [c_{K-1}, cK]`, This function counts how often `x` falls into each interval. Values of `x` outside of the intervals cause errors. Consider using `ex...
Below is the the instruction that describes the task: ### Input: Count how often `x` falls in intervals defined by `edges`. Given `edges = [c0, ..., cK]`, defining intervals `I0 = [c0, c1)`, `I1 = [c1, c2)`, ..., `I_{K-1} = [c_{K-1}, cK]`, This function counts how often `x` falls into each interval. Value...
def get_all_versions(self, headers=None, **params): """ A lower-level, version-aware method for listing contents of a bucket. This closely models the actual S3 API and requires you to manually handle the paging of results. For a higher-level method that handles the details of pa...
A lower-level, version-aware method for listing contents of a bucket. This closely models the actual S3 API and requires you to manually handle the paging of results. For a higher-level method that handles the details of paging for you, you can use the list method. :type max_ke...
Below is the the instruction that describes the task: ### Input: A lower-level, version-aware method for listing contents of a bucket. This closely models the actual S3 API and requires you to manually handle the paging of results. For a higher-level method that handles the details of pagin...
def strip_dots(value): """ Remove dots(if any) that mark calculated aesthetics Parameters ---------- value : object Aesthetic value. In most cases this will be a string but other types will pass through unmodified. Return ------ out : object Aesthetic value with...
Remove dots(if any) that mark calculated aesthetics Parameters ---------- value : object Aesthetic value. In most cases this will be a string but other types will pass through unmodified. Return ------ out : object Aesthetic value with the dots removed.
Below is the the instruction that describes the task: ### Input: Remove dots(if any) that mark calculated aesthetics Parameters ---------- value : object Aesthetic value. In most cases this will be a string but other types will pass through unmodified. Return ------ out : o...
def set_p0(self, samples_file=None, prior=None): """Sets the initial position of the walkers. Parameters ---------- samples_file : InferenceFile, optional If provided, use the last iteration in the given file for the starting positions. prior : JointDistr...
Sets the initial position of the walkers. Parameters ---------- samples_file : InferenceFile, optional If provided, use the last iteration in the given file for the starting positions. prior : JointDistribution, optional Use the given prior to set the...
Below is the the instruction that describes the task: ### Input: Sets the initial position of the walkers. Parameters ---------- samples_file : InferenceFile, optional If provided, use the last iteration in the given file for the starting positions. prior : J...
def toggle(self, event): """Toggles state to next bitmap""" if self.state < len(self.bitmap_list) - 1: self.state += 1 else: self.state = 0 self.SetBitmapLabel(self.bitmap_list[self.state]) try: event.Skip() except AttributeError: ...
Toggles state to next bitmap
Below is the the instruction that describes the task: ### Input: Toggles state to next bitmap ### Response: def toggle(self, event): """Toggles state to next bitmap""" if self.state < len(self.bitmap_list) - 1: self.state += 1 else: self.state = 0 self.SetB...
def main(): """ Main method """ # Options global args parser = argparse.ArgumentParser() parser.add_argument("-n", "--min_word_length", type=int, help="Minimum length for each word", default=3) parser.add_argument("-x", "--max_word_length", type=int, ...
Main method
Below is the the instruction that describes the task: ### Input: Main method ### Response: def main(): """ Main method """ # Options global args parser = argparse.ArgumentParser() parser.add_argument("-n", "--min_word_length", type=int, help="Minimum length ...
def _canonicalize_query(self, query): """ Transform the query dictionary to replace e.g. documents with __ref__ fields. """ def transform_query(q): if isinstance(q, dict): nq = {} for key,value in q.items(): nq[key] = tra...
Transform the query dictionary to replace e.g. documents with __ref__ fields.
Below is the the instruction that describes the task: ### Input: Transform the query dictionary to replace e.g. documents with __ref__ fields. ### Response: def _canonicalize_query(self, query): """ Transform the query dictionary to replace e.g. documents with __ref__ fields. """ ...
def fetch_items(self, path, payload): """Return the items from GitLab API using links pagination""" page = 0 # current page last_page = None # last page url_next = urijoin(self.base_url, GitLabClient.PROJECTS, self.owner + '%2F' + self.repository, path) logger.debug("Get GitL...
Return the items from GitLab API using links pagination
Below is the the instruction that describes the task: ### Input: Return the items from GitLab API using links pagination ### Response: def fetch_items(self, path, payload): """Return the items from GitLab API using links pagination""" page = 0 # current page last_page = None # last page ...
def rdfs_properties(rdf): """Perform RDFS subproperty inference. Add superproperties where subproperties have been used.""" # find out the subproperty mappings superprops = {} # key: property val: set([superprop1, superprop2..]) for s, o in rdf.subject_objects(RDFS.subPropertyOf): superpr...
Perform RDFS subproperty inference. Add superproperties where subproperties have been used.
Below is the the instruction that describes the task: ### Input: Perform RDFS subproperty inference. Add superproperties where subproperties have been used. ### Response: def rdfs_properties(rdf): """Perform RDFS subproperty inference. Add superproperties where subproperties have been used.""" #...
def is_suspended(order_book_id, count=1): """ 判断某只股票是否全天停牌。 :param str order_book_id: 某只股票的代码或股票代码,可传入单只股票的order_book_id, symbol :param int count: 回溯获取的数据个数。默认为当前能够获取到的最近的数据 :return: count为1时 `bool`; count>1时 `pandas.DataFrame` """ dt = Environment.get_instance().calendar_dt.date() or...
判断某只股票是否全天停牌。 :param str order_book_id: 某只股票的代码或股票代码,可传入单只股票的order_book_id, symbol :param int count: 回溯获取的数据个数。默认为当前能够获取到的最近的数据 :return: count为1时 `bool`; count>1时 `pandas.DataFrame`
Below is the the instruction that describes the task: ### Input: 判断某只股票是否全天停牌。 :param str order_book_id: 某只股票的代码或股票代码,可传入单只股票的order_book_id, symbol :param int count: 回溯获取的数据个数。默认为当前能够获取到的最近的数据 :return: count为1时 `bool`; count>1时 `pandas.DataFrame` ### Response: def is_suspended(order_book_id, count=1...
def vertical_line(self, x: Union[int, float], y1: Union[int, float], y2: Union[int, float], emphasize: bool = False ) -> None: """Adds a line from (x, y1) to (x, y2).""" y1, y2 = sorted([y1, y2]...
Adds a line from (x, y1) to (x, y2).
Below is the the instruction that describes the task: ### Input: Adds a line from (x, y1) to (x, y2). ### Response: def vertical_line(self, x: Union[int, float], y1: Union[int, float], y2: Union[int, float], emphasize: bool = F...
def runNetwork(network, writer): """Run the network and write output to writer. :param network: a Network instance to run :param writer: a csv.writer instance to write output to """ identityRegion = network.regions["identityRegion"] for i in xrange(_NUM_RECORDS): # Run the network for a single iterati...
Run the network and write output to writer. :param network: a Network instance to run :param writer: a csv.writer instance to write output to
Below is the the instruction that describes the task: ### Input: Run the network and write output to writer. :param network: a Network instance to run :param writer: a csv.writer instance to write output to ### Response: def runNetwork(network, writer): """Run the network and write output to writer. :par...
def analyze(self, M_c, T, X_L, X_D, seed, kernel_list=(), n_steps=1, c=(), r=(), max_iterations=-1, max_time=-1, do_diagnostics=False, diagnostics_every_N=1, ROW_CRP_ALPHA_GRID=(), COLUMN_CRP_ALPHA_GRID=(), S_GRID=(), MU_GRI...
Evolve the latent state by running MCMC transition kernels. :param seed: The random seed :type seed: int :param M_c: The column metadata :type M_c: dict :param T: The data table in mapped representation (all floats, generated by data_utils.read_data_objects) ...
Below is the the instruction that describes the task: ### Input: Evolve the latent state by running MCMC transition kernels. :param seed: The random seed :type seed: int :param M_c: The column metadata :type M_c: dict :param T: The data table in mapped representation (all fl...
def filtered_image(self, im): """Returns a filtered image after applying the Fourier-space filters""" q = np.fft.fftn(im) for k,v in self.filters: q[k] -= v return np.real(np.fft.ifftn(q))
Returns a filtered image after applying the Fourier-space filters
Below is the the instruction that describes the task: ### Input: Returns a filtered image after applying the Fourier-space filters ### Response: def filtered_image(self, im): """Returns a filtered image after applying the Fourier-space filters""" q = np.fft.fftn(im) for k,v in self.filters:...
def install(self, io_handler, module_name): """ Installs the bundle with the given module name """ bundle = self._context.install_bundle(module_name) io_handler.write_line("Bundle ID: {0}", bundle.get_bundle_id()) return bundle.get_bundle_id()
Installs the bundle with the given module name
Below is the the instruction that describes the task: ### Input: Installs the bundle with the given module name ### Response: def install(self, io_handler, module_name): """ Installs the bundle with the given module name """ bundle = self._context.install_bundle(module_name) ...
def tunnel(self, local_port, remote_port): """ Creates an SSH tunnel. """ r = self.local_renderer r.env.tunnel_local_port = local_port r.env.tunnel_remote_port = remote_port r.local(' ssh -i {key_filename} -L {tunnel_local_port}:localhost:{tunnel_remote_port} {use...
Creates an SSH tunnel.
Below is the the instruction that describes the task: ### Input: Creates an SSH tunnel. ### Response: def tunnel(self, local_port, remote_port): """ Creates an SSH tunnel. """ r = self.local_renderer r.env.tunnel_local_port = local_port r.env.tunnel_remote_port = rem...
def dumpRule(serviceCls, rule, prefix): """ Create an in-between representation of the rule, so we can eventually convert it to OpenAPIPathItem with OpenAPIOperation(s) """ rulePath = prefix + rule.rule rulePath = re.sub('/{2,}', '/', rulePath) cor = ConvertedRule( rulePath=rulePath...
Create an in-between representation of the rule, so we can eventually convert it to OpenAPIPathItem with OpenAPIOperation(s)
Below is the the instruction that describes the task: ### Input: Create an in-between representation of the rule, so we can eventually convert it to OpenAPIPathItem with OpenAPIOperation(s) ### Response: def dumpRule(serviceCls, rule, prefix): """ Create an in-between representation of the rule, so we can ...
def list_set(seq): """Similar to `list(set(seq))`, but maintains the order of `seq` while eliminating duplicates In general list(set(L)) will not have the same order as the original list. This is a list(set(L)) function that will preserve the order of L. Arguments: seq (iterable): list, tuple, o...
Similar to `list(set(seq))`, but maintains the order of `seq` while eliminating duplicates In general list(set(L)) will not have the same order as the original list. This is a list(set(L)) function that will preserve the order of L. Arguments: seq (iterable): list, tuple, or other iterable to be use...
Below is the the instruction that describes the task: ### Input: Similar to `list(set(seq))`, but maintains the order of `seq` while eliminating duplicates In general list(set(L)) will not have the same order as the original list. This is a list(set(L)) function that will preserve the order of L. Argu...
def send_raw_transaction(self, tx: Transaction, is_full: bool = False) -> str: """ This interface is used to send the transaction into the network. :param tx: Transaction object in ontology Python SDK. :param is_full: :return: a hexadecimal transaction hash value. """ ...
This interface is used to send the transaction into the network. :param tx: Transaction object in ontology Python SDK. :param is_full: :return: a hexadecimal transaction hash value.
Below is the the instruction that describes the task: ### Input: This interface is used to send the transaction into the network. :param tx: Transaction object in ontology Python SDK. :param is_full: :return: a hexadecimal transaction hash value. ### Response: def send_raw_transaction(self,...
def provStacks(self, offs, size): ''' Returns a stream of provenance stacks at the given offset ''' for _, iden in self.provseq.slice(offs, size): stack = self.getProvStack(iden) if stack is None: continue yield (iden, stack)
Returns a stream of provenance stacks at the given offset
Below is the the instruction that describes the task: ### Input: Returns a stream of provenance stacks at the given offset ### Response: def provStacks(self, offs, size): ''' Returns a stream of provenance stacks at the given offset ''' for _, iden in self.provseq.slice(offs, size):...
def rm(*components, **kwargs): """ Remove a file or directory. If path is a directory, this recursively removes the directory and any contents. Non-existent paths are silently ignored. Supports Unix style globbing by default (disable using glob=False). For details on globbing pattern expansion...
Remove a file or directory. If path is a directory, this recursively removes the directory and any contents. Non-existent paths are silently ignored. Supports Unix style globbing by default (disable using glob=False). For details on globbing pattern expansion, see: https://docs.python.org/2/l...
Below is the the instruction that describes the task: ### Input: Remove a file or directory. If path is a directory, this recursively removes the directory and any contents. Non-existent paths are silently ignored. Supports Unix style globbing by default (disable using glob=False). For details on ...
def start_worker(queues, config, *, name=None, celery_args=None, check_datastore=True): """ Start a worker process. Args: queues (list): List of queue names this worker accepts jobs from. config (Config): Reference to the configuration object from which the settings for the worker a...
Start a worker process. Args: queues (list): List of queue names this worker accepts jobs from. config (Config): Reference to the configuration object from which the settings for the worker are retrieved. name (string): Unique name for the worker. The hostname template variables...
Below is the the instruction that describes the task: ### Input: Start a worker process. Args: queues (list): List of queue names this worker accepts jobs from. config (Config): Reference to the configuration object from which the settings for the worker are retrieved. name ...
def _errmsg(self, error: "Err", tb: bool=False, i: int=None, msgformat: str="terminal") -> str: """ Get the error message """ if msgformat == "terminal": msg = self._headline(error, i) if error.ex is not None: msg += "\n" + "line " ...
Get the error message
Below is the the instruction that describes the task: ### Input: Get the error message ### Response: def _errmsg(self, error: "Err", tb: bool=False, i: int=None, msgformat: str="terminal") -> str: """ Get the error message """ if msgformat == "terminal": ...
def TakeWhile(self: dict, f): """ [ { 'self': [1, 2, 3, 4, 5], 'f': lambda x: x < 4, 'assert': lambda ret: list(ret) == [1, 2, 3] } ] """ if is_to_destruct(f): f = destruct_func(f) for e in self.items(): if not f(e): ...
[ { 'self': [1, 2, 3, 4, 5], 'f': lambda x: x < 4, 'assert': lambda ret: list(ret) == [1, 2, 3] } ]
Below is the the instruction that describes the task: ### Input: [ { 'self': [1, 2, 3, 4, 5], 'f': lambda x: x < 4, 'assert': lambda ret: list(ret) == [1, 2, 3] } ] ### Response: def TakeWhile(self: dict, f): """ [ { 'self': [1, ...
def connect(self): """Connects to the lutron controller.""" if self._connected or self.is_alive(): raise ConnectionExistsError("Already connected") # After starting the thread we wait for it to post us # an event signifying that connection is established. This # ensures that the caller only re...
Connects to the lutron controller.
Below is the the instruction that describes the task: ### Input: Connects to the lutron controller. ### Response: def connect(self): """Connects to the lutron controller.""" if self._connected or self.is_alive(): raise ConnectionExistsError("Already connected") # After starting the thread we wait...
def wrap(self, value): ''' Validate ``value`` and then use the document's class to wrap the value''' self.validate_wrap(value) return self.type.wrap(value)
Validate ``value`` and then use the document's class to wrap the value
Below is the the instruction that describes the task: ### Input: Validate ``value`` and then use the document's class to wrap the value ### Response: def wrap(self, value): ''' Validate ``value`` and then use the document's class to wrap the value''' self.validate_wrap(value...
def FileFinderOSFromClient(args): """This function expands paths from the args and returns related stat entries. Args: args: An `rdf_file_finder.FileFinderArgs` object. Yields: `rdf_paths.PathSpec` instances. """ stat_cache = filesystem.StatCache() opts = args.action.stat for path in GetExpand...
This function expands paths from the args and returns related stat entries. Args: args: An `rdf_file_finder.FileFinderArgs` object. Yields: `rdf_paths.PathSpec` instances.
Below is the the instruction that describes the task: ### Input: This function expands paths from the args and returns related stat entries. Args: args: An `rdf_file_finder.FileFinderArgs` object. Yields: `rdf_paths.PathSpec` instances. ### Response: def FileFinderOSFromClient(args): """This functi...
def _append_message(self, text, char_format): """ Parses text and executes parsed operations. """ self._cursor = self._text_edit.textCursor() operations = self._parser.parse_text(FormattedText(text, char_format)) for i, operation in enumerate(operations): try:...
Parses text and executes parsed operations.
Below is the the instruction that describes the task: ### Input: Parses text and executes parsed operations. ### Response: def _append_message(self, text, char_format): """ Parses text and executes parsed operations. """ self._cursor = self._text_edit.textCursor() operations...
def array(self, dtype=None): """An implementation of __array__()""" t = self._t # timestamp (12) through last enum (76) if 11 <= t < 77: dtype = dtypeof(self) a = numpy.empty(len(self), dtype) k2a(a, self) return a # table (98) if t == 98: if dtype is None...
An implementation of __array__()
Below is the the instruction that describes the task: ### Input: An implementation of __array__() ### Response: def array(self, dtype=None): """An implementation of __array__()""" t = self._t # timestamp (12) through last enum (76) if 11 <= t < 77: dtype = dtypeof(self) a = numpy.em...
def clear(self): ''' Reset the current HyperLogLog to empty. ''' self.reg = np.zeros((self.m,), dtype=np.int8)
Reset the current HyperLogLog to empty.
Below is the the instruction that describes the task: ### Input: Reset the current HyperLogLog to empty. ### Response: def clear(self): ''' Reset the current HyperLogLog to empty. ''' self.reg = np.zeros((self.m,), dtype=np.int8)
def get_ht_mcs(mcs): """http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/util.c?id=v3.17#n591. Positional arguments: mcs -- bytearray. Returns: Dict. """ answers = dict() max_rx_supp_data_rate = (mcs[10] & ((mcs[11] & 0x3) << 8)) tx_mcs_set_defined = not not (mcs[12] &...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/util.c?id=v3.17#n591. Positional arguments: mcs -- bytearray. Returns: Dict.
Below is the the instruction that describes the task: ### Input: http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/util.c?id=v3.17#n591. Positional arguments: mcs -- bytearray. Returns: Dict. ### Response: def get_ht_mcs(mcs): """http://git.kernel.org/cgit/linux/kernel/git/jberg/i...
def transformed_value(self, output_name=DEFAULT_OUTPUT): '''Returns transformed value either for DEFAULT_OUTPUT or for the output given as output_name. Returns None if execution result isn't a success. Reconstructs the pipeline context to materialize value. ''' check.str_param(o...
Returns transformed value either for DEFAULT_OUTPUT or for the output given as output_name. Returns None if execution result isn't a success. Reconstructs the pipeline context to materialize value.
Below is the the instruction that describes the task: ### Input: Returns transformed value either for DEFAULT_OUTPUT or for the output given as output_name. Returns None if execution result isn't a success. Reconstructs the pipeline context to materialize value. ### Response: def transformed_value...
def carry_in(value, carry, base): """ Add a carry digit to a number represented by ``value``. :param value: the value :type value: list of int :param int carry: the carry digit (>= 0) :param int base: the base (>= 2) :returns: carry-out and result :rtype...
Add a carry digit to a number represented by ``value``. :param value: the value :type value: list of int :param int carry: the carry digit (>= 0) :param int base: the base (>= 2) :returns: carry-out and result :rtype: tuple of int * (list of int) Complexity: O(len(val...
Below is the the instruction that describes the task: ### Input: Add a carry digit to a number represented by ``value``. :param value: the value :type value: list of int :param int carry: the carry digit (>= 0) :param int base: the base (>= 2) :returns: carry-out and result...
def screenshot(self, filename, scale=1.0, quality=100): '''take screenshot.''' result = self.server.screenshot(filename, scale, quality) if result: return result device_file = self.server.jsonrpc.takeScreenshot("screenshot.png", ...
take screenshot.
Below is the the instruction that describes the task: ### Input: take screenshot. ### Response: def screenshot(self, filename, scale=1.0, quality=100): '''take screenshot.''' result = self.server.screenshot(filename, scale, quality) if result: return result device_file ...
def eulerian_tour_directed(graph): """Eulerian tour on a directed graph :param graph: directed graph in listlist format, cannot be listdict :assumes: graph is eulerian :returns: eulerian cycle as a vertex list :complexity: `O(|V|+|E|)` """ P = [] Q = [0] R = [] succ ...
Eulerian tour on a directed graph :param graph: directed graph in listlist format, cannot be listdict :assumes: graph is eulerian :returns: eulerian cycle as a vertex list :complexity: `O(|V|+|E|)`
Below is the the instruction that describes the task: ### Input: Eulerian tour on a directed graph :param graph: directed graph in listlist format, cannot be listdict :assumes: graph is eulerian :returns: eulerian cycle as a vertex list :complexity: `O(|V|+|E|)` ### Response: def euler...
def With(self, context_manager, *body, **kwargs): """ **With** def With(context_manager, *body): **Arguments** * **context_manager**: a [context manager](https://docs.python.org/2/reference/datamodel.html#context-managers) object or valid expression from the DSL that returns a context manager. * ***body*...
**With** def With(context_manager, *body): **Arguments** * **context_manager**: a [context manager](https://docs.python.org/2/reference/datamodel.html#context-managers) object or valid expression from the DSL that returns a context manager. * ***body**: any valid expression of the DSL to be evaluated inside the ...
Below is the the instruction that describes the task: ### Input: **With** def With(context_manager, *body): **Arguments** * **context_manager**: a [context manager](https://docs.python.org/2/reference/datamodel.html#context-managers) object or valid expression from the DSL that returns a context manager. * *...
def allState(self, *args, **kwargs): """ List out the entire internal state This method is only for debugging the ec2-manager This method is ``experimental`` """ return self._makeApiCall(self.funcinfo["allState"], *args, **kwargs)
List out the entire internal state This method is only for debugging the ec2-manager This method is ``experimental``
Below is the the instruction that describes the task: ### Input: List out the entire internal state This method is only for debugging the ec2-manager This method is ``experimental`` ### Response: def allState(self, *args, **kwargs): """ List out the entire internal state ...
def to_exceptions(cls, errors): """ Convert the validation errors into ValidationFailure exc's Transform native schematics validation errors into a goldman ValidationFailure exception. :param errors: dict of errors in schematics format :return: list of V...
Convert the validation errors into ValidationFailure exc's Transform native schematics validation errors into a goldman ValidationFailure exception. :param errors: dict of errors in schematics format :return: list of ValidationFailure exception objects
Below is the the instruction that describes the task: ### Input: Convert the validation errors into ValidationFailure exc's Transform native schematics validation errors into a goldman ValidationFailure exception. :param errors: dict of errors in schematics format :retu...
def incomplete_alg(alg_str, input_color, position): """ Converts a string written in short algebraic form into an incomplete move. These incomplete moves do not have the initial location specified and therefore cannot be used to update the board. IN order to fully utilize incomplete move, it must be...
Converts a string written in short algebraic form into an incomplete move. These incomplete moves do not have the initial location specified and therefore cannot be used to update the board. IN order to fully utilize incomplete move, it must be run through ``make_legal()`` with the corresponding positio...
Below is the the instruction that describes the task: ### Input: Converts a string written in short algebraic form into an incomplete move. These incomplete moves do not have the initial location specified and therefore cannot be used to update the board. IN order to fully utilize incomplete move, it mu...
def get_transfer_operation(self, operation_name): """ Gets an transfer operation in Google Storage Transfer Service. :param operation_name: (Required) Name of the transfer operation. :type operation_name: str :return: transfer operation See: https://cloud...
Gets an transfer operation in Google Storage Transfer Service. :param operation_name: (Required) Name of the transfer operation. :type operation_name: str :return: transfer operation See: https://cloud.google.com/storage-transfer/docs/reference/rest/v1/Operation ...
Below is the the instruction that describes the task: ### Input: Gets an transfer operation in Google Storage Transfer Service. :param operation_name: (Required) Name of the transfer operation. :type operation_name: str :return: transfer operation See: https://cloud....
def write(self,output): """Writes the data to be output to the device buffer :param output: data to output :type output: numpy.ndarray """ w = c_int32() self.WriteAnalogF64(self.npoints, 0, 10.0, DAQmx_Val_GroupByChannel, output, w, No...
Writes the data to be output to the device buffer :param output: data to output :type output: numpy.ndarray
Below is the the instruction that describes the task: ### Input: Writes the data to be output to the device buffer :param output: data to output :type output: numpy.ndarray ### Response: def write(self,output): """Writes the data to be output to the device buffer :...
def process_hv_plots(widgets, plots): """ Temporary fix to patch HoloViews plot comms """ bokeh_plots = [] for plot in plots: if hasattr(plot, '_update_callbacks'): for subplot in plot.traverse(lambda x: x): subplot.comm = widgets.server_comm for c...
Temporary fix to patch HoloViews plot comms
Below is the the instruction that describes the task: ### Input: Temporary fix to patch HoloViews plot comms ### Response: def process_hv_plots(widgets, plots): """ Temporary fix to patch HoloViews plot comms """ bokeh_plots = [] for plot in plots: if hasattr(plot, '_update_callbacks'):...
def _normalize(self, string): ''' Returns a sanitized string. ''' string = super(VerbixFr, self)._normalize(string) string = string.replace('il; elle', 'il/elle') string = string.replace('ils; elles', 'ils/elles') string = string.strip() return string
Returns a sanitized string.
Below is the the instruction that describes the task: ### Input: Returns a sanitized string. ### Response: def _normalize(self, string): ''' Returns a sanitized string. ''' string = super(VerbixFr, self)._normalize(string) string = string.replace('il; elle', 'il/elle') string = string.replace('ils; elles'...
def get_branch(self, auth, username, repo_name, branch_name): """ Returns the branch with name ``branch_name`` in the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: use...
Returns the branch with name ``branch_name`` in the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository containing the branch :param str repo_name: n...
Below is the the instruction that describes the task: ### Input: Returns the branch with name ``branch_name`` in the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owne...
def _drop_indices(self): """Drops the database indices relating to n-grams.""" self._logger.info('Dropping database indices') self._conn.execute(constants.DROP_TEXTNGRAM_INDEX_SQL) self._logger.info('Finished dropping database indices')
Drops the database indices relating to n-grams.
Below is the the instruction that describes the task: ### Input: Drops the database indices relating to n-grams. ### Response: def _drop_indices(self): """Drops the database indices relating to n-grams.""" self._logger.info('Dropping database indices') self._conn.execute(constants.DROP_TEXT...
def is_sub_to_any_kind(self, *super_entity_kinds): """ Find all entities that have super_entities of any of the specified kinds """ if super_entity_kinds: # get the pks of the desired subs from the relationships table if len(super_entity_kinds) == 1: ...
Find all entities that have super_entities of any of the specified kinds
Below is the the instruction that describes the task: ### Input: Find all entities that have super_entities of any of the specified kinds ### Response: def is_sub_to_any_kind(self, *super_entity_kinds): """ Find all entities that have super_entities of any of the specified kinds """ ...
def percentile_doy(arr, window=5, per=.1): """Percentile value for each day of the year Return the climatological percentile over a moving window around each day of the year. Parameters ---------- arr : xarray.DataArray Input data. window : int Number of days around each day of the...
Percentile value for each day of the year Return the climatological percentile over a moving window around each day of the year. Parameters ---------- arr : xarray.DataArray Input data. window : int Number of days around each day of the year to include in the calculation. per : flo...
Below is the the instruction that describes the task: ### Input: Percentile value for each day of the year Return the climatological percentile over a moving window around each day of the year. Parameters ---------- arr : xarray.DataArray Input data. window : int Number of days aro...
def _getFieldsInDB(self, tablename): """get all the fields from a specific table""" SQL = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME="%s"' % tablename array_data = self.execQuery(SQL) return [x[0] for x in array_data]
get all the fields from a specific table
Below is the the instruction that describes the task: ### Input: get all the fields from a specific table ### Response: def _getFieldsInDB(self, tablename): """get all the fields from a specific table""" SQL = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME="%s"' % tablename array_data...
def main(): """Script entrypoint.""" # Parse the arguments parser = argparse.ArgumentParser( description='Convert MSBuild XML to JSON format') parser.add_argument( '-t', '--toolchain', help='The name of the toolchain', required=True) parser.add_argument( '-o', '--output', he...
Script entrypoint.
Below is the the instruction that describes the task: ### Input: Script entrypoint. ### Response: def main(): """Script entrypoint.""" # Parse the arguments parser = argparse.ArgumentParser( description='Convert MSBuild XML to JSON format') parser.add_argument( '-t', '--toolchain',...
def make_slack_blueprint( client_id=None, client_secret=None, scope=None, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, storage=None, ): """ Make a blueprint for authenticating with Slack using OAuth 2. This requires a clien...
Make a blueprint for authenticating with Slack using OAuth 2. This requires a client ID and client secret from Slack. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the variables :envvar:`SLACK_OAUTH_CLIENT_ID` and :envvar:`SLACK_OAUT...
Below is the the instruction that describes the task: ### Input: Make a blueprint for authenticating with Slack using OAuth 2. This requires a client ID and client secret from Slack. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the ...
def value_type(type_): """returns reference to `boost::shared_ptr` \ or `std::shared_ptr` value type""" if not smart_pointer_traits.is_smart_pointer(type_): raise TypeError( 'Type "%s" is not an instantiation of \ boost::shared_ptr or std::shared_ptr' ...
returns reference to `boost::shared_ptr` \ or `std::shared_ptr` value type
Below is the the instruction that describes the task: ### Input: returns reference to `boost::shared_ptr` \ or `std::shared_ptr` value type ### Response: def value_type(type_): """returns reference to `boost::shared_ptr` \ or `std::shared_ptr` value type""" if not smart_pointer_trai...
def refresh(self, nice_repr=True, **kwargs): """ :param nice_repr: Append the repr of a list containing the items that have been fetched to this point by the fetcher. :type nice_repr: bool :param kwargs: kwargs that should be passed to the fetcher when its ...
:param nice_repr: Append the repr of a list containing the items that have been fetched to this point by the fetcher. :type nice_repr: bool :param kwargs: kwargs that should be passed to the fetcher when its fetch method is called. These are merged with t...
Below is the the instruction that describes the task: ### Input: :param nice_repr: Append the repr of a list containing the items that have been fetched to this point by the fetcher. :type nice_repr: bool :param kwargs: kwargs that should be passed to the fetcher when its ...
def transform_audio(self, y): '''Compute the CQT with unwrapped phase Parameters ---------- y : np.ndarray The audio buffer Returns ------- data : dict data['mag'] : np.ndarray, shape=(n_frames, n_bins) CQT magnitude ...
Compute the CQT with unwrapped phase Parameters ---------- y : np.ndarray The audio buffer Returns ------- data : dict data['mag'] : np.ndarray, shape=(n_frames, n_bins) CQT magnitude data['dphase'] : np.ndarray, shap...
Below is the the instruction that describes the task: ### Input: Compute the CQT with unwrapped phase Parameters ---------- y : np.ndarray The audio buffer Returns ------- data : dict data['mag'] : np.ndarray, shape=(n_frames, n_bins) ...
def col_counts(col, weights=None, gap_chars='-.'): """Absolute counts of each residue type in a single column.""" cnt = defaultdict(float) for aa, wt in zip(col, weights): if aa not in gap_chars: cnt[aa] += wt return cnt
Absolute counts of each residue type in a single column.
Below is the the instruction that describes the task: ### Input: Absolute counts of each residue type in a single column. ### Response: def col_counts(col, weights=None, gap_chars='-.'): """Absolute counts of each residue type in a single column.""" cnt = defaultdict(float) for aa, wt in zip(col, weigh...
def audio_open(path, backends=None): """Open an audio file using a library that is available on this system. The optional `backends` parameter can be a list of audio file classes to try opening the file with. If it is not provided, `audio_open` tries all available backends. If you call this functio...
Open an audio file using a library that is available on this system. The optional `backends` parameter can be a list of audio file classes to try opening the file with. If it is not provided, `audio_open` tries all available backends. If you call this function many times, you can avoid the cost of ...
Below is the the instruction that describes the task: ### Input: Open an audio file using a library that is available on this system. The optional `backends` parameter can be a list of audio file classes to try opening the file with. If it is not provided, `audio_open` tries all available backends....
def where_terms_factorization_check(self, term_list): """ check for where terms if they are applicable Create a boolean array where `term_list` is true. A terms list has a [(col, operator, value), ..] construction. Eg. [('sales', '>', 2), ('state', 'in', ['IL', 'AR'])] :...
check for where terms if they are applicable Create a boolean array where `term_list` is true. A terms list has a [(col, operator, value), ..] construction. Eg. [('sales', '>', 2), ('state', 'in', ['IL', 'AR'])] :param term_list: :param outcols: :param limit: :pa...
Below is the the instruction that describes the task: ### Input: check for where terms if they are applicable Create a boolean array where `term_list` is true. A terms list has a [(col, operator, value), ..] construction. Eg. [('sales', '>', 2), ('state', 'in', ['IL', 'AR'])] :param...
def update_position(self): '''update position text''' state = self.state pos = self.mouse_pos newtext = '' alt = 0 if pos is not None: (lat,lon) = self.coordinates(pos.x, pos.y) newtext += 'Cursor: %f %f (%s)' % (lat, lon, mp_util.latlon_to_grid((l...
update position text
Below is the the instruction that describes the task: ### Input: update position text ### Response: def update_position(self): '''update position text''' state = self.state pos = self.mouse_pos newtext = '' alt = 0 if pos is not None: (lat,lon) = self.coo...
def _sliced_shape(shape, keys): """ Returns the shape that results from slicing an array of the given shape by the given keys. >>> _sliced_shape(shape=(52350, 70, 90, 180), ... keys=(np.newaxis, slice(None, 10), 3, ... slice(None), slice(2, 3))) (1, 10, 90,...
Returns the shape that results from slicing an array of the given shape by the given keys. >>> _sliced_shape(shape=(52350, 70, 90, 180), ... keys=(np.newaxis, slice(None, 10), 3, ... slice(None), slice(2, 3))) (1, 10, 90, 1)
Below is the the instruction that describes the task: ### Input: Returns the shape that results from slicing an array of the given shape by the given keys. >>> _sliced_shape(shape=(52350, 70, 90, 180), ... keys=(np.newaxis, slice(None, 10), 3, ... slice(None), slic...
def _tab_pressed(self): """ Called when the tab key is pressed. Returns whether to continue processing the event. """ # Perform tab completion if: # 1) The cursor is in the input buffer. # 2) There is a non-whitespace character before the cursor. text = self._...
Called when the tab key is pressed. Returns whether to continue processing the event.
Below is the the instruction that describes the task: ### Input: Called when the tab key is pressed. Returns whether to continue processing the event. ### Response: def _tab_pressed(self): """ Called when the tab key is pressed. Returns whether to continue processing the event. ...
def coordInImage(x_coord, y_coord, numPix, deltapix): """ checks whether image positions are within the pixel image in units of arcsec if not: remove it :param imcoord: image coordinate (in units of angels) [[x,y,delta,magnification][...]] :type imcoord: (n,4) numpy array :returns: image posit...
checks whether image positions are within the pixel image in units of arcsec if not: remove it :param imcoord: image coordinate (in units of angels) [[x,y,delta,magnification][...]] :type imcoord: (n,4) numpy array :returns: image positions within the pixel image
Below is the the instruction that describes the task: ### Input: checks whether image positions are within the pixel image in units of arcsec if not: remove it :param imcoord: image coordinate (in units of angels) [[x,y,delta,magnification][...]] :type imcoord: (n,4) numpy array :returns: image po...
def _update_dicts(name_scope, model_layer, input_to_in_layer, model_name_to_output, prev_node_name): """Updates input_to_in_layer, model_name_to_output, and prev_node_name based on the model_layer. Args: name_scope: a string representing...
Updates input_to_in_layer, model_name_to_output, and prev_node_name based on the model_layer. Args: name_scope: a string representing a scope name, similar to that of tf.name_scope. model_layer: a dict representing a Keras model configuration. input_to_in_layer: a dict mapping Keras.layers.Input to inb...
Below is the the instruction that describes the task: ### Input: Updates input_to_in_layer, model_name_to_output, and prev_node_name based on the model_layer. Args: name_scope: a string representing a scope name, similar to that of tf.name_scope. model_layer: a dict representing a Keras model configura...
def update_resources(self, data, type_, names=None, languages=None): """ Update or add resource data. type_ = resource type to update names = a list of resource names to update (None = all) languages = a list of resource languages to update (None = all) ...
Update or add resource data. type_ = resource type to update names = a list of resource names to update (None = all) languages = a list of resource languages to update (None = all)
Below is the the instruction that describes the task: ### Input: Update or add resource data. type_ = resource type to update names = a list of resource names to update (None = all) languages = a list of resource languages to update (None = all) ### Response: def update_resources(s...
def wait_for_model_package(self, model_package_name, poll=5): """Wait for an Amazon SageMaker endpoint deployment to complete. Args: endpoint (str): Name of the ``Endpoint`` to wait for. poll (int): Polling interval in seconds (default: 5). Returns: dict: Re...
Wait for an Amazon SageMaker endpoint deployment to complete. Args: endpoint (str): Name of the ``Endpoint`` to wait for. poll (int): Polling interval in seconds (default: 5). Returns: dict: Return value from the ``DescribeEndpoint`` API.
Below is the the instruction that describes the task: ### Input: Wait for an Amazon SageMaker endpoint deployment to complete. Args: endpoint (str): Name of the ``Endpoint`` to wait for. poll (int): Polling interval in seconds (default: 5). Returns: dict: Return...
def escape_any(value): """ Section 4.1.2 defines SPARQL shortened forms https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals Examples of literal syntax in SPARQL include: "chat" 'chat'@fr with language tag "fr" "xyz"^^<http://example.org/ns/userDatatype> ...
Section 4.1.2 defines SPARQL shortened forms https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals Examples of literal syntax in SPARQL include: "chat" 'chat'@fr with language tag "fr" "xyz"^^<http://example.org/ns/userDatatype> "abc"^^appNS:appDataType '...
Below is the the instruction that describes the task: ### Input: Section 4.1.2 defines SPARQL shortened forms https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#QSynLiterals Examples of literal syntax in SPARQL include: "chat" 'chat'@fr with language tag "fr" "xyz"^^<http://ex...
def _clean_path(path): """Create a fully fissile absolute system path with no symbolic links and environment variables""" path = path.replace('"', '') path = path.replace("'", '') # Replace ~ with /home/user path = os.path.expanduser(path) # Replace environment variables ...
Create a fully fissile absolute system path with no symbolic links and environment variables
Below is the the instruction that describes the task: ### Input: Create a fully fissile absolute system path with no symbolic links and environment variables ### Response: def _clean_path(path): """Create a fully fissile absolute system path with no symbolic links and environment variables""" path ...
def get_simbad_astrometry_info (ident, items=_simbaditems, debug=False): """Fetch astrometric information from the Simbad web service. Given the name of a source as known to the CDS Simbad service, this function looks up its positional information and returns it in a dictionary. In most cases you shoul...
Fetch astrometric information from the Simbad web service. Given the name of a source as known to the CDS Simbad service, this function looks up its positional information and returns it in a dictionary. In most cases you should use an :class:`AstrometryInfo` object and its :meth:`~AstrometryInfo.fill_...
Below is the the instruction that describes the task: ### Input: Fetch astrometric information from the Simbad web service. Given the name of a source as known to the CDS Simbad service, this function looks up its positional information and returns it in a dictionary. In most cases you should use an :c...
def consume(self, entrystream): """ Load a stream of entries into memory. Only Feature objects and sequence-region directives are loaded, all other entries are discarded. """ for entry in entrystream: if isinstance(entry, tag.directive.Directive) and \ ...
Load a stream of entries into memory. Only Feature objects and sequence-region directives are loaded, all other entries are discarded.
Below is the the instruction that describes the task: ### Input: Load a stream of entries into memory. Only Feature objects and sequence-region directives are loaded, all other entries are discarded. ### Response: def consume(self, entrystream): """ Load a stream of entries into me...
def _get_value_indices(names1, names2, lookups): """ >>> _get_value_indices(['foo', 'bar', 'baz'], ['foo', 'bar', 'baz'], ... ['bar', 'foo']) [1, 0] >>> _get_value_indices(['foo', 'bar', 'baz'], ['FOO', 'bar', 'baz'], ... ['bar', 'FOO']) [1, 0] >>> _...
>>> _get_value_indices(['foo', 'bar', 'baz'], ['foo', 'bar', 'baz'], ... ['bar', 'foo']) [1, 0] >>> _get_value_indices(['foo', 'bar', 'baz'], ['FOO', 'bar', 'baz'], ... ['bar', 'FOO']) [1, 0] >>> _get_value_indices(['foo', 'bar', 'BAZ'], ['foo', 'BAZ', 'baz'...
Below is the the instruction that describes the task: ### Input: >>> _get_value_indices(['foo', 'bar', 'baz'], ['foo', 'bar', 'baz'], ... ['bar', 'foo']) [1, 0] >>> _get_value_indices(['foo', 'bar', 'baz'], ['FOO', 'bar', 'baz'], ... ['bar', 'FOO']) [1, 0] ...
def get_queued(): """ Returns a list of emails that should be sent: - Status is queued - Has scheduled_time lower than the current time or None """ return Email.objects.filter(status=STATUS.queued) \ .select_related('template') \ .filter(Q(scheduled_time__lte=now()) | Q(schedul...
Returns a list of emails that should be sent: - Status is queued - Has scheduled_time lower than the current time or None
Below is the the instruction that describes the task: ### Input: Returns a list of emails that should be sent: - Status is queued - Has scheduled_time lower than the current time or None ### Response: def get_queued(): """ Returns a list of emails that should be sent: - Status is queued ...
def find_vasp_calculations(): """ Returns a list of all subdirectories that contain either a vasprun.xml file or a compressed vasprun.xml.gz file. Args: None Returns: (List): list of all VASP calculation subdirectories. """ dir_list = [ './' + re.sub( r'vasprun\.xml', '', p...
Returns a list of all subdirectories that contain either a vasprun.xml file or a compressed vasprun.xml.gz file. Args: None Returns: (List): list of all VASP calculation subdirectories.
Below is the the instruction that describes the task: ### Input: Returns a list of all subdirectories that contain either a vasprun.xml file or a compressed vasprun.xml.gz file. Args: None Returns: (List): list of all VASP calculation subdirectories. ### Response: def find_vasp_calcul...
def parse_record(raw_record, is_training, dtype): """Parses a record containing a training example of an image. The input record is parsed into a label and image, and the image is passed through preprocessing steps (cropping, flipping, and so on). Args: raw_record: scalar Tensor tf.string containing a ser...
Parses a record containing a training example of an image. The input record is parsed into a label and image, and the image is passed through preprocessing steps (cropping, flipping, and so on). Args: raw_record: scalar Tensor tf.string containing a serialized Example protocol buffer. is_training:...
Below is the the instruction that describes the task: ### Input: Parses a record containing a training example of an image. The input record is parsed into a label and image, and the image is passed through preprocessing steps (cropping, flipping, and so on). Args: raw_record: scalar Tensor tf.string co...
def crosstab(index, columns, values=None, rownames=None, colnames=None, aggfunc=None, margins=False, margins_name='All', dropna=True, normalize=False): """ Compute a simple cross tabulation of two (or more) factors. By default computes a frequency table of the factors unless an arr...
Compute a simple cross tabulation of two (or more) factors. By default computes a frequency table of the factors unless an array of values and an aggregation function are passed. Parameters ---------- index : array-like, Series, or list of arrays/Series Values to group by in the rows. c...
Below is the the instruction that describes the task: ### Input: Compute a simple cross tabulation of two (or more) factors. By default computes a frequency table of the factors unless an array of values and an aggregation function are passed. Parameters ---------- index : array-like, Series, o...
def alias_grade_entry(self, grade_entry_id, alias_id): """Adds an ``Id`` to a ``GradeEntry`` for the purpose of creating compatibility. The primary ``Id`` of the ``GradeEntry`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a po...
Adds an ``Id`` to a ``GradeEntry`` for the purpose of creating compatibility. The primary ``Id`` of the ``GradeEntry`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to another grade entry, it is reassigned to the give...
Below is the the instruction that describes the task: ### Input: Adds an ``Id`` to a ``GradeEntry`` for the purpose of creating compatibility. The primary ``Id`` of the ``GradeEntry`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a...
def parse_samblaster(self, f): """ Go through log file looking for samblaster output. If the Grab the name from the RG tag of the preceding bwa command """ dups_regex = "samblaster: (Removed|Marked) (\d+) of (\d+) \((\d+.\d+)%\) read ids as duplicates" input_file_regex = "samblas...
Go through log file looking for samblaster output. If the Grab the name from the RG tag of the preceding bwa command
Below is the the instruction that describes the task: ### Input: Go through log file looking for samblaster output. If the Grab the name from the RG tag of the preceding bwa command ### Response: def parse_samblaster(self, f): """ Go through log file looking for samblaster output. I...
def _prepare_resources(self, variables, overrides=None): """Create and optionally open all shared resources.""" if overrides is None: overrides = {} res_map = {} own_map = {} for decl in self.resources.values(): resource = overrides.get(decl.name) ...
Create and optionally open all shared resources.
Below is the the instruction that describes the task: ### Input: Create and optionally open all shared resources. ### Response: def _prepare_resources(self, variables, overrides=None): """Create and optionally open all shared resources.""" if overrides is None: overrides = {} ...
def render_child(self, child, view_name=None, context=None): """A shortcut to render a child block. Use this method to render your children from your own view function. If `view_name` is not provided, it will default to the view name you're being rendered with. Returns the sam...
A shortcut to render a child block. Use this method to render your children from your own view function. If `view_name` is not provided, it will default to the view name you're being rendered with. Returns the same value as :func:`render`.
Below is the the instruction that describes the task: ### Input: A shortcut to render a child block. Use this method to render your children from your own view function. If `view_name` is not provided, it will default to the view name you're being rendered with. Returns the same v...
def add_public_note(self, public_note, source=None): """Add public note. :param public_note: public note for the current article. :type public_note: string :param source: source for the given notes. :type source: string """ self._append_to('public_notes', self._...
Add public note. :param public_note: public note for the current article. :type public_note: string :param source: source for the given notes. :type source: string
Below is the the instruction that describes the task: ### Input: Add public note. :param public_note: public note for the current article. :type public_note: string :param source: source for the given notes. :type source: string ### Response: def add_public_note(self, public_note,...
def isdisjoint(self, other): """ Return ``True`` if the set has no elements in common with *other*. Sets are disjoint if and only if their intersection is the empty set. :param other: Any kind of iterable. :rtype: boolean """ def isdisjoint_trans_pure(pipe): ...
Return ``True`` if the set has no elements in common with *other*. Sets are disjoint if and only if their intersection is the empty set. :param other: Any kind of iterable. :rtype: boolean
Below is the the instruction that describes the task: ### Input: Return ``True`` if the set has no elements in common with *other*. Sets are disjoint if and only if their intersection is the empty set. :param other: Any kind of iterable. :rtype: boolean ### Response: def isdisjoint(self, o...
def bellman_ford(graph, weight, source=0): """ Single source shortest paths by Bellman-Ford :param graph: directed graph in listlist or listdict format :param weight: can be negative. in matrix format or same listdict graph :returns: distance table, precedence table, bool :explan...
Single source shortest paths by Bellman-Ford :param graph: directed graph in listlist or listdict format :param weight: can be negative. in matrix format or same listdict graph :returns: distance table, precedence table, bool :explanation: bool is True if a negative circuit is ...
Below is the the instruction that describes the task: ### Input: Single source shortest paths by Bellman-Ford :param graph: directed graph in listlist or listdict format :param weight: can be negative. in matrix format or same listdict graph :returns: distance table, precedence table...
def _construct_url(self, url, base, quote): """ Adds the orderbook to the url if base and quote are specified. """ if not base and not quote: return url else: url = url + base.lower() + quote.lower() + "/" return url
Adds the orderbook to the url if base and quote are specified.
Below is the the instruction that describes the task: ### Input: Adds the orderbook to the url if base and quote are specified. ### Response: def _construct_url(self, url, base, quote): """ Adds the orderbook to the url if base and quote are specified. """ if not base and not quote:...
async def container(self, container=None, container_type=None, params=None): """ Loads/dumps container :return: """ # Container versioning is a bit tricky, primitive type containers are not versioned. elem_type = x.container_elem_type(container_type, params) raw_c...
Loads/dumps container :return:
Below is the the instruction that describes the task: ### Input: Loads/dumps container :return: ### Response: async def container(self, container=None, container_type=None, params=None): """ Loads/dumps container :return: """ # Container versioning is a bit tricky, p...
def Load(cls, file_input, client=None): """Loads an IncrementalUploadHelper from the given file-like object. Args: file_input: a file-like object containing a serialized IncrementalUploadHelper. client: an AdWordsClient instance. If not specified, an AdWordsClient will be instantiat...
Loads an IncrementalUploadHelper from the given file-like object. Args: file_input: a file-like object containing a serialized IncrementalUploadHelper. client: an AdWordsClient instance. If not specified, an AdWordsClient will be instantiated using the default configuration file. R...
Below is the the instruction that describes the task: ### Input: Loads an IncrementalUploadHelper from the given file-like object. Args: file_input: a file-like object containing a serialized IncrementalUploadHelper. client: an AdWordsClient instance. If not specified, an AdWordsClient will...
def uninstall(self): """ Uninstalls the bundle """ with self._lock: if self._state == Bundle.ACTIVE: self.stop() # Change the bundle state self._state = Bundle.UNINSTALLED # Call the framework self.__framework....
Uninstalls the bundle
Below is the the instruction that describes the task: ### Input: Uninstalls the bundle ### Response: def uninstall(self): """ Uninstalls the bundle """ with self._lock: if self._state == Bundle.ACTIVE: self.stop() # Change the bundle state ...
def _DrawTrips(self,triplist,colpar=""): """Generates svg polylines for each transit trip. Args: # Class Trip is defined in transitfeed.py [Trip, Trip, ...] Returns: # A string containing a polyline tag for each trip ' <polyline class="T" stroke="#336633" points="433,0 ...' """...
Generates svg polylines for each transit trip. Args: # Class Trip is defined in transitfeed.py [Trip, Trip, ...] Returns: # A string containing a polyline tag for each trip ' <polyline class="T" stroke="#336633" points="433,0 ...'
Below is the the instruction that describes the task: ### Input: Generates svg polylines for each transit trip. Args: # Class Trip is defined in transitfeed.py [Trip, Trip, ...] Returns: # A string containing a polyline tag for each trip ' <polyline class="T" stroke="#336633" point...
def append(self, word, lemma=None, type=None, chunk=None, role=None, relation=None, pnp=None, anchor=None, iob=None, custom={}): """ Appends the next word to the sentence / chunk / preposition. For example: Sentence.append("clawed", "claw", "VB", "VP", role=None, relation=1) - word :...
Appends the next word to the sentence / chunk / preposition. For example: Sentence.append("clawed", "claw", "VB", "VP", role=None, relation=1) - word : the current word, - lemma : the canonical form of the word, - type : part-of-speech tag for the word (NN, JJ,...
Below is the the instruction that describes the task: ### Input: Appends the next word to the sentence / chunk / preposition. For example: Sentence.append("clawed", "claw", "VB", "VP", role=None, relation=1) - word : the current word, - lemma : the canonical form of the wo...
async def generate_wallet_key(config: Optional[str]) -> str: """ Generate wallet master key. Returned key is compatible with "RAW" key derivation method. It allows to avoid expensive key derivation for use cases when wallet keys can be stored in a secure enclave. :param config: (optional) key confi...
Generate wallet master key. Returned key is compatible with "RAW" key derivation method. It allows to avoid expensive key derivation for use cases when wallet keys can be stored in a secure enclave. :param config: (optional) key configuration json. { "seed": string, (optional) Seed that allows...
Below is the the instruction that describes the task: ### Input: Generate wallet master key. Returned key is compatible with "RAW" key derivation method. It allows to avoid expensive key derivation for use cases when wallet keys can be stored in a secure enclave. :param config: (optional) key configura...
def url(self): """The URL as a string of the resource.""" if not self._url[2].endswith('/'): self._url[2] += '/' return RestURL.url.__get__(self)
The URL as a string of the resource.
Below is the the instruction that describes the task: ### Input: The URL as a string of the resource. ### Response: def url(self): """The URL as a string of the resource.""" if not self._url[2].endswith('/'): self._url[2] += '/' return RestURL.url.__get__(self)
def maybe_cythonize_extensions(top_path, config): """Tweaks for building extensions between release and development mode.""" is_release = os.path.exists(os.path.join(top_path, 'PKG-INFO')) if is_release: build_from_c_and_cpp_files(config.ext_modules) else: message = ('Please install cyt...
Tweaks for building extensions between release and development mode.
Below is the the instruction that describes the task: ### Input: Tweaks for building extensions between release and development mode. ### Response: def maybe_cythonize_extensions(top_path, config): """Tweaks for building extensions between release and development mode.""" is_release = os.path.exists(os.pat...
def mknts(self, add_dct): """Add information from add_dct to a new copy of namedtuples stored in nts.""" nts = [] assert len(add_dct) == len(self.nts) flds = list(next(iter(self.nts))._fields) + list(next(iter(add_dct)).keys()) ntobj = cx.namedtuple("ntgoea", " ".join(flds)) ...
Add information from add_dct to a new copy of namedtuples stored in nts.
Below is the the instruction that describes the task: ### Input: Add information from add_dct to a new copy of namedtuples stored in nts. ### Response: def mknts(self, add_dct): """Add information from add_dct to a new copy of namedtuples stored in nts.""" nts = [] assert len(add_dct) == le...
def add(self, requirements, required=None): """ Add requirements to be managed :param list/Requirement requirements: List of :class:`BumpRequirement` or :class:`pkg_resources.Requirement` :param bool required: Set required flag for each requirement if provided. """ if is...
Add requirements to be managed :param list/Requirement requirements: List of :class:`BumpRequirement` or :class:`pkg_resources.Requirement` :param bool required: Set required flag for each requirement if provided.
Below is the the instruction that describes the task: ### Input: Add requirements to be managed :param list/Requirement requirements: List of :class:`BumpRequirement` or :class:`pkg_resources.Requirement` :param bool required: Set required flag for each requirement if provided. ### Response: def a...
def add_config_path(path): """Select config parser by file extension and add path into parser. """ if not os.path.isfile(path): warnings.warn("Config file does not exist: {path}".format(path=path)) return False # select parser by file extension _base, ext = os.path.splitext(path) ...
Select config parser by file extension and add path into parser.
Below is the the instruction that describes the task: ### Input: Select config parser by file extension and add path into parser. ### Response: def add_config_path(path): """Select config parser by file extension and add path into parser. """ if not os.path.isfile(path): warnings.warn("Config f...
def get_certificate(self, **kwargs): """Get the attributes of the current array certificate. :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert** :type \*\*kwargs: optional :retu...
Get the attributes of the current array certificate. :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert** :type \*\*kwargs: optional :returns: A dictionary describing the configured arra...
Below is the the instruction that describes the task: ### Input: Get the attributes of the current array certificate. :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert** :type \*\*kwargs: op...
def _extract_log_probs(num_states, dist): """Tabulate log probabilities from a batch of distributions.""" states = tf.reshape(tf.range(num_states), tf.concat([[num_states], tf.ones_like(dist.batch_shape_tensor())], axis=0)) re...
Tabulate log probabilities from a batch of distributions.
Below is the the instruction that describes the task: ### Input: Tabulate log probabilities from a batch of distributions. ### Response: def _extract_log_probs(num_states, dist): """Tabulate log probabilities from a batch of distributions.""" states = tf.reshape(tf.range(num_states), tf....
def renderModelHasComponent(self, pchRenderModelName, pchComponentName): """Returns true if the render model has a component with the specified name""" fn = self.function_table.renderModelHasComponent result = fn(pchRenderModelName, pchComponentName) return result
Returns true if the render model has a component with the specified name
Below is the the instruction that describes the task: ### Input: Returns true if the render model has a component with the specified name ### Response: def renderModelHasComponent(self, pchRenderModelName, pchComponentName): """Returns true if the render model has a component with the specified name""" ...
def lock(self): """Returns a JSON representation of the Pipfile.""" data = self.data data['_meta']['hash'] = {"sha256": self.hash} data['_meta']['pipfile-spec'] = 6 return json.dumps(data, indent=4, separators=(',', ': '))
Returns a JSON representation of the Pipfile.
Below is the the instruction that describes the task: ### Input: Returns a JSON representation of the Pipfile. ### Response: def lock(self): """Returns a JSON representation of the Pipfile.""" data = self.data data['_meta']['hash'] = {"sha256": self.hash} data['_meta']['pipfile-spec...