code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def lock(self, connection, session): """Explicitly lock the specified connection :type connection: psycopg2.extensions.connection :param connection: The connection to lock :param queries.Session session: The session to hold the lock """ cid = id(connection) try:...
Explicitly lock the specified connection :type connection: psycopg2.extensions.connection :param connection: The connection to lock :param queries.Session session: The session to hold the lock
Below is the the instruction that describes the task: ### Input: Explicitly lock the specified connection :type connection: psycopg2.extensions.connection :param connection: The connection to lock :param queries.Session session: The session to hold the lock ### Response: def lock(self, con...
def get_setter(cls, prop_name, # @NoSelf user_setter=None, setter_takes_name=False, user_getter=None, getter_takes_name=False): """Similar to get_getter, but for setting property values. If user_getter is specified, that it may be used to get the old value...
Similar to get_getter, but for setting property values. If user_getter is specified, that it may be used to get the old value of the property before setting it (this is the case in some derived classes' implementation). if getter_takes_name is True and user_getter is not None, than ...
Below is the the instruction that describes the task: ### Input: Similar to get_getter, but for setting property values. If user_getter is specified, that it may be used to get the old value of the property before setting it (this is the case in some derived classes' implementation). if ...
def setup_and_run_bwakit(job, uuid, url, rg_line, config, paired_url=None): """ Downloads and runs bwakit for BAM or FASTQ files :param JobFunctionWrappingJob job: passed automatically by Toil :param str uuid: Unique sample identifier :param str url: FASTQ or BAM file URL. BAM alignment URL must ha...
Downloads and runs bwakit for BAM or FASTQ files :param JobFunctionWrappingJob job: passed automatically by Toil :param str uuid: Unique sample identifier :param str url: FASTQ or BAM file URL. BAM alignment URL must have .bam extension. :param Namespace config: Input parameters and shared FileStoreIDs...
Below is the the instruction that describes the task: ### Input: Downloads and runs bwakit for BAM or FASTQ files :param JobFunctionWrappingJob job: passed automatically by Toil :param str uuid: Unique sample identifier :param str url: FASTQ or BAM file URL. BAM alignment URL must have .bam extension. ...
def _list_existing(filesystem, glob, paths): """ Get all the paths that do in fact exist. Returns a set of all existing paths. Takes a luigi.target.FileSystem object, a str which represents a glob and a list of strings representing paths. """ globs = _constrain_glob(glob, paths) time_start ...
Get all the paths that do in fact exist. Returns a set of all existing paths. Takes a luigi.target.FileSystem object, a str which represents a glob and a list of strings representing paths.
Below is the the instruction that describes the task: ### Input: Get all the paths that do in fact exist. Returns a set of all existing paths. Takes a luigi.target.FileSystem object, a str which represents a glob and a list of strings representing paths. ### Response: def _list_existing(filesystem, glob, ...
def get_as_list(self, tag_name): """ Return the value of a tag, making sure that it's a list. Absent tags are returned as an empty-list; single tags are returned as a one-element list. The returned list is a copy, and modifications do not affect the original object. ...
Return the value of a tag, making sure that it's a list. Absent tags are returned as an empty-list; single tags are returned as a one-element list. The returned list is a copy, and modifications do not affect the original object.
Below is the the instruction that describes the task: ### Input: Return the value of a tag, making sure that it's a list. Absent tags are returned as an empty-list; single tags are returned as a one-element list. The returned list is a copy, and modifications do not affect the orig...
def circle(self, x, y, radius): """draw circle""" self._add_instruction("arc", x, y, radius, 0, math.pi * 2)
draw circle
Below is the the instruction that describes the task: ### Input: draw circle ### Response: def circle(self, x, y, radius): """draw circle""" self._add_instruction("arc", x, y, radius, 0, math.pi * 2)
def persist(self): """Trigger saving the current sensorgraph to persistent storage.""" self.persisted_nodes = self.graph.dump_nodes() self.persisted_streamers = self.graph.dump_streamers() self.persisted_exists = True self.persisted_constants = self._sensor_log.dump_constants()
Trigger saving the current sensorgraph to persistent storage.
Below is the the instruction that describes the task: ### Input: Trigger saving the current sensorgraph to persistent storage. ### Response: def persist(self): """Trigger saving the current sensorgraph to persistent storage.""" self.persisted_nodes = self.graph.dump_nodes() self.persisted_...
def monitor_counters(mc, output, counters, detailed, f): """Monitor the counters on a specified machine, taking a snap-shot every time the generator 'f' yields.""" # Print CSV header output.write("time,{}{}\n".format("x,y," if detailed else "", ",".join(counters))) ...
Monitor the counters on a specified machine, taking a snap-shot every time the generator 'f' yields.
Below is the the instruction that describes the task: ### Input: Monitor the counters on a specified machine, taking a snap-shot every time the generator 'f' yields. ### Response: def monitor_counters(mc, output, counters, detailed, f): """Monitor the counters on a specified machine, taking a snap-shot eve...
def recount_view(request): """ Recount number_of_messages for all threads and number_of_responses for all requests. Also set the change_date for every thread to the post_date of the latest message associated with that thread. """ requests_changed = 0 for req in Request.objects.all(): ...
Recount number_of_messages for all threads and number_of_responses for all requests. Also set the change_date for every thread to the post_date of the latest message associated with that thread.
Below is the the instruction that describes the task: ### Input: Recount number_of_messages for all threads and number_of_responses for all requests. Also set the change_date for every thread to the post_date of the latest message associated with that thread. ### Response: def recount_view(request): ""...
def angle(self, value): """gets/sets the angle""" if self._angle != value and \ isinstance(value, (int, float, long)): self._angle = value
gets/sets the angle
Below is the the instruction that describes the task: ### Input: gets/sets the angle ### Response: def angle(self, value): """gets/sets the angle""" if self._angle != value and \ isinstance(value, (int, float, long)): self._angle = value
def is_func_decorator(node: astroid.node_classes.NodeNG) -> bool: """return true if the name is used in function decorator""" parent = node.parent while parent is not None: if isinstance(parent, astroid.Decorators): return True if parent.is_statement or isinstance( pa...
return true if the name is used in function decorator
Below is the the instruction that describes the task: ### Input: return true if the name is used in function decorator ### Response: def is_func_decorator(node: astroid.node_classes.NodeNG) -> bool: """return true if the name is used in function decorator""" parent = node.parent while parent is not Non...
def _zeros(ftype, *dims): """Return a new farray filled with zeros.""" shape = _dims2shape(*dims) objs = [ftype.box(0) for _ in range(_volume(shape))] return farray(objs, shape, ftype)
Return a new farray filled with zeros.
Below is the the instruction that describes the task: ### Input: Return a new farray filled with zeros. ### Response: def _zeros(ftype, *dims): """Return a new farray filled with zeros.""" shape = _dims2shape(*dims) objs = [ftype.box(0) for _ in range(_volume(shape))] return farray(objs, shape, fty...
def argparse(argv, parser, arguments): """ A command line argument parser. Parses arguments coming from the argv Observable and outputs them as Argument items in the output observable. Parameters ----------- argv : Observable An Observable of strings. parser : Observable An ...
A command line argument parser. Parses arguments coming from the argv Observable and outputs them as Argument items in the output observable. Parameters ----------- argv : Observable An Observable of strings. parser : Observable An Observable containing one Parser item. argu...
Below is the the instruction that describes the task: ### Input: A command line argument parser. Parses arguments coming from the argv Observable and outputs them as Argument items in the output observable. Parameters ----------- argv : Observable An Observable of strings. parser : ...
def keep_only_positive_boxes(boxes): """ Given a set of BoxList containing the `labels` field, return a set of BoxList for which `labels > 0`. Arguments: boxes (list of BoxList) """ assert isinstance(boxes, (list, tuple)) assert isinstance(boxes[0], BoxList) assert boxes[0].has_...
Given a set of BoxList containing the `labels` field, return a set of BoxList for which `labels > 0`. Arguments: boxes (list of BoxList)
Below is the the instruction that describes the task: ### Input: Given a set of BoxList containing the `labels` field, return a set of BoxList for which `labels > 0`. Arguments: boxes (list of BoxList) ### Response: def keep_only_positive_boxes(boxes): """ Given a set of BoxList containing...
def __Delete(self, path, request, headers): """Azure Cosmos 'DELETE' http request. :params str url: :params str path: :params dict headers: :return: Tuple of (result, headers). :rtype: tuple of (dict, dict) """ return synchronize...
Azure Cosmos 'DELETE' http request. :params str url: :params str path: :params dict headers: :return: Tuple of (result, headers). :rtype: tuple of (dict, dict)
Below is the the instruction that describes the task: ### Input: Azure Cosmos 'DELETE' http request. :params str url: :params str path: :params dict headers: :return: Tuple of (result, headers). :rtype: tuple of (dict, dict) ### Response: def __Dele...
def _set_table(self, schema, **kwargs): """ http://sqlite.org/lang_createtable.html """ query_str = [] query_str.append("CREATE TABLE {} (".format(self._normalize_table_name(schema))) query_fields = [] for field_name, field in schema.fields.items(): q...
http://sqlite.org/lang_createtable.html
Below is the the instruction that describes the task: ### Input: http://sqlite.org/lang_createtable.html ### Response: def _set_table(self, schema, **kwargs): """ http://sqlite.org/lang_createtable.html """ query_str = [] query_str.append("CREATE TABLE {} (".format(self._nor...
def squareAspect(rect): """ Crops either the width or height, as necessary, to make a rectangle into a square. The input rectangle and return value are both a tuple of (x,y,w,h). """ # Determine which dimension needs to be cropped x,y,w,h = rect if w > h: cropX = (w - h) // 2 return cropRect(rect, 0, 0, ...
Crops either the width or height, as necessary, to make a rectangle into a square. The input rectangle and return value are both a tuple of (x,y,w,h).
Below is the the instruction that describes the task: ### Input: Crops either the width or height, as necessary, to make a rectangle into a square. The input rectangle and return value are both a tuple of (x,y,w,h). ### Response: def squareAspect(rect): """ Crops either the width or height, as necessary, to m...
def delete_datapoint(self, datapoint): """Delete the provided datapoint from this stream :raises devicecloud.DeviceCloudHttpException: in the case of an unexpected http error """ datapoint = validate_type(datapoint, DataPoint) self._conn.delete("/ws/DataPoint/{stream_id}/{datap...
Delete the provided datapoint from this stream :raises devicecloud.DeviceCloudHttpException: in the case of an unexpected http error
Below is the the instruction that describes the task: ### Input: Delete the provided datapoint from this stream :raises devicecloud.DeviceCloudHttpException: in the case of an unexpected http error ### Response: def delete_datapoint(self, datapoint): """Delete the provided datapoint from this stre...
def setLog(self, fileName, writeName=False): """ Opens a log file with name fileName. """ self.log = 1 self.logFile = fileName self._logPtr = open(fileName, "w") if writeName: self._namePtr = open(fileName + ".name", "w")
Opens a log file with name fileName.
Below is the the instruction that describes the task: ### Input: Opens a log file with name fileName. ### Response: def setLog(self, fileName, writeName=False): """ Opens a log file with name fileName. """ self.log = 1 self.logFile = fileName self._logPtr = open(file...
def chunk(seq: ActualIterable[T]) -> ActualIterable[ActualIterable[T]]: """ >>> from Redy.Collections import Traversal, Flow >>> x = [1, 1, 2] >>> assert Flow(x)[Traversal.chunk][list].unbox == [[1, 1], [2]] >>> assert Flow([])[Traversal.chunk][list].unbox == [] """ seq = iter(seq) try: ...
>>> from Redy.Collections import Traversal, Flow >>> x = [1, 1, 2] >>> assert Flow(x)[Traversal.chunk][list].unbox == [[1, 1], [2]] >>> assert Flow([])[Traversal.chunk][list].unbox == []
Below is the the instruction that describes the task: ### Input: >>> from Redy.Collections import Traversal, Flow >>> x = [1, 1, 2] >>> assert Flow(x)[Traversal.chunk][list].unbox == [[1, 1], [2]] >>> assert Flow([])[Traversal.chunk][list].unbox == [] ### Response: def chunk(seq: ActualIterable[T]) -> ...
def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.string_types): raise KeyError('The key must be a string.') if '.' not in key: raise Key...
Load a single item if you have it
Below is the the instruction that describes the task: ### Input: Load a single item if you have it ### Response: def _load(self, key): ''' Load a single item if you have it ''' # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, six.s...
def main(): """ NAME sundec.py DESCRIPTION calculates calculates declination from sun compass measurements INPUT FORMAT GMT_offset, lat,long,year,month,day,hours,minutes,shadow_angle where GMT_offset is the hours to subtract from local time for GMT. SYNTAX sun...
NAME sundec.py DESCRIPTION calculates calculates declination from sun compass measurements INPUT FORMAT GMT_offset, lat,long,year,month,day,hours,minutes,shadow_angle where GMT_offset is the hours to subtract from local time for GMT. SYNTAX sundec.py [-i][-f FILE] [< ...
Below is the the instruction that describes the task: ### Input: NAME sundec.py DESCRIPTION calculates calculates declination from sun compass measurements INPUT FORMAT GMT_offset, lat,long,year,month,day,hours,minutes,shadow_angle where GMT_offset is the hours to subtract fr...
def byte_list_to_u16le_list(byteData): """! @brief Convert a byte array into a halfword array""" data = [] for i in range(0, len(byteData), 2): data.append(byteData[i] | (byteData[i + 1] << 8)) return data
! @brief Convert a byte array into a halfword array
Below is the the instruction that describes the task: ### Input: ! @brief Convert a byte array into a halfword array ### Response: def byte_list_to_u16le_list(byteData): """! @brief Convert a byte array into a halfword array""" data = [] for i in range(0, len(byteData), 2): data.append(byteData...
def add_model(self, model): """ Add a model to the document """ if model.identity not in self._models.keys(): self._models[model.identity] = model else: raise ValueError("{} has already been defined".format(model.identity))
Add a model to the document
Below is the the instruction that describes the task: ### Input: Add a model to the document ### Response: def add_model(self, model): """ Add a model to the document """ if model.identity not in self._models.keys(): self._models[model.identity] = model else: ...
def _do_history(self, cmd, args): """\ Display history. history Display history. history clear Clear history. history clearall Clear history for all shells. """ if args and args[0] == 'clear': readline.clear_history() ...
\ Display history. history Display history. history clear Clear history. history clearall Clear history for all shells.
Below is the the instruction that describes the task: ### Input: \ Display history. history Display history. history clear Clear history. history clearall Clear history for all shells. ### Response: def _do_history(self, cmd, args): """\ ...
def export_to_json( table, filename_or_fobj=None, encoding="utf-8", indent=None, *args, **kwargs ): """Export a `rows.Table` to a JSON file or file-like object. If a file-like object is provided it MUST be open in binary mode (like in `open('myfile.json', mode='wb')`). """ # TODO: will work onl...
Export a `rows.Table` to a JSON file or file-like object. If a file-like object is provided it MUST be open in binary mode (like in `open('myfile.json', mode='wb')`).
Below is the the instruction that describes the task: ### Input: Export a `rows.Table` to a JSON file or file-like object. If a file-like object is provided it MUST be open in binary mode (like in `open('myfile.json', mode='wb')`). ### Response: def export_to_json( table, filename_or_fobj=None, encodi...
def delete(self): """ Easy delete for db models """ try: if self.exists() is False: return None self.db.session.delete(self) self.db.session.commit() except (Exception, BaseException) as error: # fail silently r...
Easy delete for db models
Below is the the instruction that describes the task: ### Input: Easy delete for db models ### Response: def delete(self): """ Easy delete for db models """ try: if self.exists() is False: return None self.db.session.delete(self) self.db.ses...
def _view_changed(self, event=None): """Linked view transform has changed; update ticks. """ tr = self.node_transform(self._linked_view.scene) p1, p2 = tr.map(self._axis_ends()) if self.orientation in ('left', 'right'): self.axis.domain = (p1[1], p2[1]) else: ...
Linked view transform has changed; update ticks.
Below is the the instruction that describes the task: ### Input: Linked view transform has changed; update ticks. ### Response: def _view_changed(self, event=None): """Linked view transform has changed; update ticks. """ tr = self.node_transform(self._linked_view.scene) p1, p2 = tr....
def get_default_config(self): """ Return the default config for the handler """ config = super(GraphiteHandler, self).get_default_config() config.update({ 'host': 'localhost', 'port': 2003, 'proto': 'tcp', 'timeout': 15, ...
Return the default config for the handler
Below is the the instruction that describes the task: ### Input: Return the default config for the handler ### Response: def get_default_config(self): """ Return the default config for the handler """ config = super(GraphiteHandler, self).get_default_config() config.update(...
def reset_all(self): """Reset status for all servers in the list""" self._LOG.debug("Marking all CMs as Good.") for key in self.list: self.mark_good(key)
Reset status for all servers in the list
Below is the the instruction that describes the task: ### Input: Reset status for all servers in the list ### Response: def reset_all(self): """Reset status for all servers in the list""" self._LOG.debug("Marking all CMs as Good.") for key in self.list: self.mark_good(key)
def imag(self, newimag): """Setter for the imaginary part. This method is invoked by ``x.imag = other``. Parameters ---------- newimag : array-like or scalar Values to be assigned to the imaginary part of this element. """ try: iter(newim...
Setter for the imaginary part. This method is invoked by ``x.imag = other``. Parameters ---------- newimag : array-like or scalar Values to be assigned to the imaginary part of this element.
Below is the the instruction that describes the task: ### Input: Setter for the imaginary part. This method is invoked by ``x.imag = other``. Parameters ---------- newimag : array-like or scalar Values to be assigned to the imaginary part of this element. ### Response: ...
def write_molpro(basis): '''Converts a basis set to Molpro format ''' # Uncontract all, and make as generally-contracted as possible basis = manip.uncontract_spdf(basis, 0, True) basis = manip.make_general(basis, False) basis = sort.sort_basis(basis, True) s = '' # Elements for which ...
Converts a basis set to Molpro format
Below is the the instruction that describes the task: ### Input: Converts a basis set to Molpro format ### Response: def write_molpro(basis): '''Converts a basis set to Molpro format ''' # Uncontract all, and make as generally-contracted as possible basis = manip.uncontract_spdf(basis, 0, True) ...
def offer_simple(pool, answer, rationale, student_id, options): """ The simple selection algorithm. This algorithm randomly select an answer from the pool to discard and add the new one when the pool reaches the limit """ existing = pool.setdefault(answer, {}) if len(existing) >= get_max_si...
The simple selection algorithm. This algorithm randomly select an answer from the pool to discard and add the new one when the pool reaches the limit
Below is the the instruction that describes the task: ### Input: The simple selection algorithm. This algorithm randomly select an answer from the pool to discard and add the new one when the pool reaches the limit ### Response: def offer_simple(pool, answer, rationale, student_id, options): """ T...
def list_solvers(args=None): """Entry point for listing available solvers.""" parser = argparse.ArgumentParser( description='''List LP solver available in PSAMM. This will produce a list of all of the available LP solvers in prioritized order. Addtional requ...
Entry point for listing available solvers.
Below is the the instruction that describes the task: ### Input: Entry point for listing available solvers. ### Response: def list_solvers(args=None): """Entry point for listing available solvers.""" parser = argparse.ArgumentParser( description='''List LP solver available in PSAMM. This will produ...
def tag_timexes(self): """Create ``timexes`` layer. Depends on morphological analysis data in ``words`` layer and tags it automatically, if it is not present.""" if not self.is_tagged(ANALYSIS): self.tag_analysis() if not self.is_tagged(TIMEXES): if self._...
Create ``timexes`` layer. Depends on morphological analysis data in ``words`` layer and tags it automatically, if it is not present.
Below is the the instruction that describes the task: ### Input: Create ``timexes`` layer. Depends on morphological analysis data in ``words`` layer and tags it automatically, if it is not present. ### Response: def tag_timexes(self): """Create ``timexes`` layer. Depends on morpholo...
def make_chunk_for(output_dir=LOCAL_DIR, local_dir=LOCAL_DIR, game_dir=None, model_num=1, positions=EXAMPLES_PER_GENERATION, threads=8, sampling_frac=0.02): """ Explicitly make a golden chunk for a ...
Explicitly make a golden chunk for a given model `model_num` (not necessarily the most recent one). While we haven't yet got enough samples (EXAMPLES_PER_GENERATION) Add samples from the games of previous model.
Below is the the instruction that describes the task: ### Input: Explicitly make a golden chunk for a given model `model_num` (not necessarily the most recent one). While we haven't yet got enough samples (EXAMPLES_PER_GENERATION) Add samples from the games of previous model. ### Response: def mak...
def check_has_path(self, api): '''An API class must have a `path` attribute.''' if not hasattr(api, 'path'): msg = 'The Api class "{}" lacks a `path` attribute.' return [msg.format(api.__name__)]
An API class must have a `path` attribute.
Below is the the instruction that describes the task: ### Input: An API class must have a `path` attribute. ### Response: def check_has_path(self, api): '''An API class must have a `path` attribute.''' if not hasattr(api, 'path'): msg = 'The Api class "{}" lacks a `path` attribute.' ...
def remove_from_gallery(self): """Remove this image from the gallery.""" url = self._imgur._base_url + "/3/gallery/{0}".format(self.id) self._imgur._send_request(url, needs_auth=True, method='DELETE') if isinstance(self, Image): item = self._imgur.get_image(self.id) e...
Remove this image from the gallery.
Below is the the instruction that describes the task: ### Input: Remove this image from the gallery. ### Response: def remove_from_gallery(self): """Remove this image from the gallery.""" url = self._imgur._base_url + "/3/gallery/{0}".format(self.id) self._imgur._send_request(url, needs_aut...
def get_api_docs(routes): """ Generates GitHub Markdown formatted API documentation using provided schemas in RequestHandler methods and their docstrings. :type routes: [(url, RequestHandler), ...] :param routes: List of routes (this is ideally all possible routes of the app) :rtype: s...
Generates GitHub Markdown formatted API documentation using provided schemas in RequestHandler methods and their docstrings. :type routes: [(url, RequestHandler), ...] :param routes: List of routes (this is ideally all possible routes of the app) :rtype: str :returns: generated GFM-formatt...
Below is the the instruction that describes the task: ### Input: Generates GitHub Markdown formatted API documentation using provided schemas in RequestHandler methods and their docstrings. :type routes: [(url, RequestHandler), ...] :param routes: List of routes (this is ideally all possible routes of...
def transform(self, X): """Imputes all missing values in X. Note that this is stochastic, and that if random_state is not fixed, repeated calls, or permuted input, will yield different results. Parameters ---------- X : array-like, shape = [n_samples, n_features] ...
Imputes all missing values in X. Note that this is stochastic, and that if random_state is not fixed, repeated calls, or permuted input, will yield different results. Parameters ---------- X : array-like, shape = [n_samples, n_features] The input data to complete. ...
Below is the the instruction that describes the task: ### Input: Imputes all missing values in X. Note that this is stochastic, and that if random_state is not fixed, repeated calls, or permuted input, will yield different results. Parameters ---------- X : array-like, shap...
def repl_member_add(self, params): """create new mongod instances and add it to the replica set. Args: params - mongod params return True if operation success otherwise False """ repl_config = self.config member_id = max([member['_id'] for member in repl_confi...
create new mongod instances and add it to the replica set. Args: params - mongod params return True if operation success otherwise False
Below is the the instruction that describes the task: ### Input: create new mongod instances and add it to the replica set. Args: params - mongod params return True if operation success otherwise False ### Response: def repl_member_add(self, params): """create new mongod instanc...
def _get_oxm_field_int(self): """Return a valid integer value for oxm_field. Used while packing. Returns: int: valid oxm_field value. Raises: ValueError: If :attribute:`oxm_field` is bigger than 7 bits or should be :class:`OxmOfbMatchField` and ...
Return a valid integer value for oxm_field. Used while packing. Returns: int: valid oxm_field value. Raises: ValueError: If :attribute:`oxm_field` is bigger than 7 bits or should be :class:`OxmOfbMatchField` and the enum has no such valu...
Below is the the instruction that describes the task: ### Input: Return a valid integer value for oxm_field. Used while packing. Returns: int: valid oxm_field value. Raises: ValueError: If :attribute:`oxm_field` is bigger than 7 bits or should be :c...
def get_inputs_outputs(namespace, method, snapshot_id): """Get a description of the inputs and outputs for a method. The method should exist in the methods repository. Args: namespace (str): Methods namespace method (str): method name snapshot_id (int): snapshot_id of the method ...
Get a description of the inputs and outputs for a method. The method should exist in the methods repository. Args: namespace (str): Methods namespace method (str): method name snapshot_id (int): snapshot_id of the method Swagger: https://api.firecloud.org/#!/Method_Reposit...
Below is the the instruction that describes the task: ### Input: Get a description of the inputs and outputs for a method. The method should exist in the methods repository. Args: namespace (str): Methods namespace method (str): method name snapshot_id (int): snapshot_id of the met...
def compare(node1, node2): """Compares two Werkzeug hg versions.""" if not os.path.isdir("a"): print("error: comparison feature not initialized", file=sys.stderr) sys.exit(4) print("=" * 80) print("WERKZEUG INTERNAL BENCHMARK -- COMPARE MODE".center(80)) print("-" * 80) def _hg...
Compares two Werkzeug hg versions.
Below is the the instruction that describes the task: ### Input: Compares two Werkzeug hg versions. ### Response: def compare(node1, node2): """Compares two Werkzeug hg versions.""" if not os.path.isdir("a"): print("error: comparison feature not initialized", file=sys.stderr) sys.exit(4) ...
def load_stock_quantity(self): """ Loads quantities for all stocks """ info = StocksInfo(self.config) for stock in self.model.stocks: stock.quantity = info.load_stock_quantity(stock.symbol) info.gc_book.close()
Loads quantities for all stocks
Below is the the instruction that describes the task: ### Input: Loads quantities for all stocks ### Response: def load_stock_quantity(self): """ Loads quantities for all stocks """ info = StocksInfo(self.config) for stock in self.model.stocks: stock.quantity = info.load_stock_q...
def ncdegree(polynomial): """Returns the degree of a noncommutative polynomial. :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: int -- the degree of the polynomial. """ degree = 0 if is_number_type(polynomial): ret...
Returns the degree of a noncommutative polynomial. :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: int -- the degree of the polynomial.
Below is the the instruction that describes the task: ### Input: Returns the degree of a noncommutative polynomial. :param polynomial: Polynomial of noncommutive variables. :type polynomial: :class:`sympy.core.expr.Expr`. :returns: int -- the degree of the polynomial. ### Response: def ncdegree(polyn...
def main(device_type): """Parse command-line arguments.""" epilog = ('See https://github.com/romanz/trezor-agent/blob/master/' 'doc/README-GPG.md for usage examples.') parser = argparse.ArgumentParser(epilog=epilog) agent_package = device_type.package_name() resources_map = {r.key: r ...
Parse command-line arguments.
Below is the the instruction that describes the task: ### Input: Parse command-line arguments. ### Response: def main(device_type): """Parse command-line arguments.""" epilog = ('See https://github.com/romanz/trezor-agent/blob/master/' 'doc/README-GPG.md for usage examples.') parser = arg...
def export_image(input, output, timeout=20, palette='white', resolution=150, layers=None, command=None, mirror=False, showgui=False): ''' Exporting eagle .sch or .brd file into image file. GUI is not displayed if ``pyvirtualdisplay`` is installed. If export is blocked somehow (e.g. popup window is displ...
Exporting eagle .sch or .brd file into image file. GUI is not displayed if ``pyvirtualdisplay`` is installed. If export is blocked somehow (e.g. popup window is displayed) then after timeout operation is canceled with exception. Problem can be investigated by setting 'showgui' flag. Exporting generates...
Below is the the instruction that describes the task: ### Input: Exporting eagle .sch or .brd file into image file. GUI is not displayed if ``pyvirtualdisplay`` is installed. If export is blocked somehow (e.g. popup window is displayed) then after timeout operation is canceled with exception. Problem ca...
def call_orig(self, *args, **kwargs): ''' Calls the original function. ''' return self._orig(self._obj, *args, **kwargs)
Calls the original function.
Below is the the instruction that describes the task: ### Input: Calls the original function. ### Response: def call_orig(self, *args, **kwargs): ''' Calls the original function. ''' return self._orig(self._obj, *args, **kwargs)
def QA_indicator_RSI(DataFrame, N1=12, N2=26, N3=9): '相对强弱指标RSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100;' CLOSE = DataFrame['close'] LC = REF(CLOSE, 1) RSI1 = SMA(MAX(CLOSE - LC, 0), N1) / SMA(ABS(CLOSE - LC), N1) * 100 RSI2 = SMA(MAX(CLOSE - LC, 0), N2) / SMA(ABS(CLOSE - LC), N2) * 1...
相对强弱指标RSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100;
Below is the the instruction that describes the task: ### Input: 相对强弱指标RSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100; ### Response: def QA_indicator_RSI(DataFrame, N1=12, N2=26, N3=9): '相对强弱指标RSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100;' CLOSE = DataFrame['close'] LC = REF(C...
def whichEncoding(self): """How should I be encoded? @returns: one of ENCODE_URL, ENCODE_HTML_FORM, or ENCODE_KVFORM. @change: 2.1.0 added the ENCODE_HTML_FORM response. """ if self.request.mode in BROWSER_REQUEST_MODES: if self.fields.getOpenIDNamespace() == OPENID...
How should I be encoded? @returns: one of ENCODE_URL, ENCODE_HTML_FORM, or ENCODE_KVFORM. @change: 2.1.0 added the ENCODE_HTML_FORM response.
Below is the the instruction that describes the task: ### Input: How should I be encoded? @returns: one of ENCODE_URL, ENCODE_HTML_FORM, or ENCODE_KVFORM. @change: 2.1.0 added the ENCODE_HTML_FORM response. ### Response: def whichEncoding(self): """How should I be encoded? @retur...
def interpolate_nans_1d(x, y, kind='linear'): """Interpolate NaN values in y. Interpolate NaN values in the y dimension. Works with unsorted x values. Parameters ---------- x : array-like 1-dimensional array of numeric x-values y : array-like 1-dimensional array of numeric y-va...
Interpolate NaN values in y. Interpolate NaN values in the y dimension. Works with unsorted x values. Parameters ---------- x : array-like 1-dimensional array of numeric x-values y : array-like 1-dimensional array of numeric y-values kind : string specifies the kind of ...
Below is the the instruction that describes the task: ### Input: Interpolate NaN values in y. Interpolate NaN values in the y dimension. Works with unsorted x values. Parameters ---------- x : array-like 1-dimensional array of numeric x-values y : array-like 1-dimensional array...
def setMinimumPixmapSize(self, size): """ Sets the minimum pixmap size that will be displayed to the user for the dock widget. :param size | <int> """ self._minimumPixmapSize = size position = self.position() self._position = None ...
Sets the minimum pixmap size that will be displayed to the user for the dock widget. :param size | <int>
Below is the the instruction that describes the task: ### Input: Sets the minimum pixmap size that will be displayed to the user for the dock widget. :param size | <int> ### Response: def setMinimumPixmapSize(self, size): """ Sets the minimum pixmap size that will ...
def plugins_context(classes, category=None): """ context manager to load plugin class(es) then unload on exit Parameters ---------- classes: list list of classes category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import ppr...
context manager to load plugin class(es) then unload on exit Parameters ---------- classes: list list of classes category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> class DecoderPlugin(object): ... ...
Below is the the instruction that describes the task: ### Input: context manager to load plugin class(es) then unload on exit Parameters ---------- classes: list list of classes category : None or str if str, apply for single plugin category Examples -------- >>> from p...
def reload_napps(self, napps=None): """Reload a specific NApp or all Napps. Args: napp (list): NApp list to be reload. Raises: requests.HTTPError: When there's a server error. """ if napps is None: napps = [] api = self._config.ge...
Reload a specific NApp or all Napps. Args: napp (list): NApp list to be reload. Raises: requests.HTTPError: When there's a server error.
Below is the the instruction that describes the task: ### Input: Reload a specific NApp or all Napps. Args: napp (list): NApp list to be reload. Raises: requests.HTTPError: When there's a server error. ### Response: def reload_napps(self, napps=None): """Reload a sp...
def top_corner_label(self, label, position=None, rotation=0, offset=0.2, **kwargs): """ Sets the label on the bottom axis. Parameters ---------- label: String The axis label position: 3-Tuple of floats, None The position o...
Sets the label on the bottom axis. Parameters ---------- label: String The axis label position: 3-Tuple of floats, None The position of the text label rotation: float, 0 The angle of rotation of the label offset: float, Use...
Below is the the instruction that describes the task: ### Input: Sets the label on the bottom axis. Parameters ---------- label: String The axis label position: 3-Tuple of floats, None The position of the text label rotation: float, 0 The ...
def record_set_absent(name, zone_name, resource_group, connection_auth=None): ''' .. versionadded:: Fluorine Ensure a record set does not exist in the DNS zone. :param name: Name of the record set. :param zone_name: Name of the DNS zone. :param resource_group: The res...
.. versionadded:: Fluorine Ensure a record set does not exist in the DNS zone. :param name: Name of the record set. :param zone_name: Name of the DNS zone. :param resource_group: The resource group assigned to the DNS zone. :param connection_auth: A dict with sub...
Below is the the instruction that describes the task: ### Input: .. versionadded:: Fluorine Ensure a record set does not exist in the DNS zone. :param name: Name of the record set. :param zone_name: Name of the DNS zone. :param resource_group: The resource group assigned ...
def format(self, record): """Print out any 'extra' data provided in logs.""" if hasattr(record, 'data'): return "%s. DEBUG DATA=%s" % ( logging.Formatter.format(self, record), record.__dict__['data']) return logging.Formatter.format(self, record)
Print out any 'extra' data provided in logs.
Below is the the instruction that describes the task: ### Input: Print out any 'extra' data provided in logs. ### Response: def format(self, record): """Print out any 'extra' data provided in logs.""" if hasattr(record, 'data'): return "%s. DEBUG DATA=%s" % ( logging.For...
def set_col_min_width(self, x: int, min_width: int): """Sets a minimum width for blocks in the column with coordinate x.""" if x < 0: raise IndexError('x < 0') self._min_widths[x] = min_width
Sets a minimum width for blocks in the column with coordinate x.
Below is the the instruction that describes the task: ### Input: Sets a minimum width for blocks in the column with coordinate x. ### Response: def set_col_min_width(self, x: int, min_width: int): """Sets a minimum width for blocks in the column with coordinate x.""" if x < 0: raise Ind...
def init_cli(self, app): """ Initialize the Flask CLI support in case it was enabled for the app. Works with both Flask>=1.0's CLI support as well as the backport in the Flask-CLI package for Flask<1.0. """ # in case click isn't installed after all if cli...
Initialize the Flask CLI support in case it was enabled for the app. Works with both Flask>=1.0's CLI support as well as the backport in the Flask-CLI package for Flask<1.0.
Below is the the instruction that describes the task: ### Input: Initialize the Flask CLI support in case it was enabled for the app. Works with both Flask>=1.0's CLI support as well as the backport in the Flask-CLI package for Flask<1.0. ### Response: def init_cli(self, app): """ ...
def commandline_to_list(self, cmdline_str, trigger_string): ''' cmdline_str is the string of the command line trigger_string is the trigger string, to be removed ''' cmdline = salt.utils.args.shlex_split(cmdline_str[len(trigger_string):]) # Remove slack url parsing ...
cmdline_str is the string of the command line trigger_string is the trigger string, to be removed
Below is the the instruction that describes the task: ### Input: cmdline_str is the string of the command line trigger_string is the trigger string, to be removed ### Response: def commandline_to_list(self, cmdline_str, trigger_string): ''' cmdline_str is the string of the command line ...
def loadStructuredPoints(filename): """Load a ``vtkStructuredPoints`` object from file and return an ``Actor(vtkActor)`` object. .. hint:: |readStructuredPoints| |readStructuredPoints.py|_ """ reader = vtk.vtkStructuredPointsReader() reader.SetFileName(filename) reader.Update() gf = vtk.vtk...
Load a ``vtkStructuredPoints`` object from file and return an ``Actor(vtkActor)`` object. .. hint:: |readStructuredPoints| |readStructuredPoints.py|_
Below is the the instruction that describes the task: ### Input: Load a ``vtkStructuredPoints`` object from file and return an ``Actor(vtkActor)`` object. .. hint:: |readStructuredPoints| |readStructuredPoints.py|_ ### Response: def loadStructuredPoints(filename): """Load a ``vtkStructuredPoints`` object ...
def write(self, buf): ''' Write buffer data into logger/stdout ''' for line in buf.rstrip().splitlines(): self.orig_stdout.write(line.rstrip() + '\n') self.orig_stdout.flush() try: self.logger.log(self.log_level, line.rstrip()) ...
Write buffer data into logger/stdout
Below is the the instruction that describes the task: ### Input: Write buffer data into logger/stdout ### Response: def write(self, buf): ''' Write buffer data into logger/stdout ''' for line in buf.rstrip().splitlines(): self.orig_stdout.write(line.rstrip() + '\n') ...
def dumps_etree(pid, record, **kwargs): """Dump MARC21 compatible record. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` instance. :param record: The :class:`invenio_records.api.Record` instance. :returns: A LXML Element instance. """ from dojson.contrib.to_marc21...
Dump MARC21 compatible record. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` instance. :param record: The :class:`invenio_records.api.Record` instance. :returns: A LXML Element instance.
Below is the the instruction that describes the task: ### Input: Dump MARC21 compatible record. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` instance. :param record: The :class:`invenio_records.api.Record` instance. :returns: A LXML Element instance. ### Response: def ...
def iter_parsed_values(self, field: Field) -> Iterable[Tuple[str, Any]]: """ Walk the dictionary of parsers and emit all non-null values. """ for key, func in self.parsers.items(): value = func(field) if not value: continue yield key, ...
Walk the dictionary of parsers and emit all non-null values.
Below is the the instruction that describes the task: ### Input: Walk the dictionary of parsers and emit all non-null values. ### Response: def iter_parsed_values(self, field: Field) -> Iterable[Tuple[str, Any]]: """ Walk the dictionary of parsers and emit all non-null values. """ ...
def _convert_json_response_to_entities(response, property_resolver, require_encryption, key_encryption_key, key_resolver): ''' Converts the response to tables class. ''' if response is None or response.body is None: return None entities = _list() enti...
Converts the response to tables class.
Below is the the instruction that describes the task: ### Input: Converts the response to tables class. ### Response: def _convert_json_response_to_entities(response, property_resolver, require_encryption, key_encryption_key, key_resolver): ''' Converts the response to ta...
def _add_child(self, collection, set, child): """Adds 'child' to 'collection', first checking 'set' to see if it's already present.""" added = None for c in child: if c not in set: set.add(c) collection.append(c) added = 1 ...
Adds 'child' to 'collection', first checking 'set' to see if it's already present.
Below is the the instruction that describes the task: ### Input: Adds 'child' to 'collection', first checking 'set' to see if it's already present. ### Response: def _add_child(self, collection, set, child): """Adds 'child' to 'collection', first checking 'set' to see if it's already presen...
def from_string(cls, serialized): """Deprecated. Use :meth:`locator.CourseLocator.from_string`.""" warnings.warn( "SlashSeparatedCourseKey is deprecated! Please use locator.CourseLocator", DeprecationWarning, stacklevel=2 ) return CourseLocator.from_st...
Deprecated. Use :meth:`locator.CourseLocator.from_string`.
Below is the the instruction that describes the task: ### Input: Deprecated. Use :meth:`locator.CourseLocator.from_string`. ### Response: def from_string(cls, serialized): """Deprecated. Use :meth:`locator.CourseLocator.from_string`.""" warnings.warn( "SlashSeparatedCourseKey is depreca...
def get_reference_section_beginning(fulltext): """Get start of reference section.""" sect_start = { 'start_line': None, 'end_line': None, 'title_string': None, 'marker_pattern': None, 'marker': None, 'how_found_start': None, } # Find start of refs section...
Get start of reference section.
Below is the the instruction that describes the task: ### Input: Get start of reference section. ### Response: def get_reference_section_beginning(fulltext): """Get start of reference section.""" sect_start = { 'start_line': None, 'end_line': None, 'title_string': None, 'mar...
def show_time_as_short_string(self, seconds): """ converts seconds to a string in terms of seconds -> years to show complexity of algorithm """ if seconds < 60: return str(seconds) + ' seconds' elif seconds < 3600: return str(round(seconds/60, 1)...
converts seconds to a string in terms of seconds -> years to show complexity of algorithm
Below is the the instruction that describes the task: ### Input: converts seconds to a string in terms of seconds -> years to show complexity of algorithm ### Response: def show_time_as_short_string(self, seconds): """ converts seconds to a string in terms of seconds -> years to ...
def get_max_seq_len(self) -> Optional[int]: """ :return: The maximum length supported by the encoder if such a restriction exists. """ max_seq_len = min((encoder.get_max_seq_len() for encoder in self.encoders if encoder.get_max_seq_len() is not None), default=N...
:return: The maximum length supported by the encoder if such a restriction exists.
Below is the the instruction that describes the task: ### Input: :return: The maximum length supported by the encoder if such a restriction exists. ### Response: def get_max_seq_len(self) -> Optional[int]: """ :return: The maximum length supported by the encoder if such a restriction exists. ...
def _css_select(soup, css_selector): """ Returns the content of the element pointed by the CSS selector, or an empty string if not found """ selection = soup.select(css_selector) if len(selection) > 0: if hasattr(selection[0], 'text'): retour = selection[0].te...
Returns the content of the element pointed by the CSS selector, or an empty string if not found
Below is the the instruction that describes the task: ### Input: Returns the content of the element pointed by the CSS selector, or an empty string if not found ### Response: def _css_select(soup, css_selector): """ Returns the content of the element pointed by the CSS selector, or an empty...
def from_polar(r, theta, phi): """Convert ``(r, theta, phi)`` to Cartesian coordinates ``[x y z]``. ``r`` - vector length ``theta`` - angle above (+) or below (-) the xy-plane ``phi`` - angle around the z-axis The meaning and order of the three polar parameters is designed to match both ISO 31...
Convert ``(r, theta, phi)`` to Cartesian coordinates ``[x y z]``. ``r`` - vector length ``theta`` - angle above (+) or below (-) the xy-plane ``phi`` - angle around the z-axis The meaning and order of the three polar parameters is designed to match both ISO 31-11 and the traditional order used by ...
Below is the the instruction that describes the task: ### Input: Convert ``(r, theta, phi)`` to Cartesian coordinates ``[x y z]``. ``r`` - vector length ``theta`` - angle above (+) or below (-) the xy-plane ``phi`` - angle around the z-axis The meaning and order of the three polar parameters is de...
def register_gym_env(class_entry_point, version="v0", kwargs=None): """Registers the class in Gym and returns the registered name and the env.""" split_on_colon = class_entry_point.split(":") assert len(split_on_colon) == 2 class_name = split_on_colon[1] # We have to add the version to conform to gym's API....
Registers the class in Gym and returns the registered name and the env.
Below is the the instruction that describes the task: ### Input: Registers the class in Gym and returns the registered name and the env. ### Response: def register_gym_env(class_entry_point, version="v0", kwargs=None): """Registers the class in Gym and returns the registered name and the env.""" split_on_colo...
def to_frame(self): """Convert the object to its frame format.""" self.sanitize() res = [] res.append((1 << 7) + (1 << 4) + (self.repeat << 5) + (self.priority << 2)) res.append(self.src_addr >> 8) res.append(self.src_addr % 0x100) res.append(se...
Convert the object to its frame format.
Below is the the instruction that describes the task: ### Input: Convert the object to its frame format. ### Response: def to_frame(self): """Convert the object to its frame format.""" self.sanitize() res = [] res.append((1 << 7) + (1 << 4) + (self.repeat << 5) + ...
def get_output(self, assets_by_taxo, haz, rlzi=None): """ :param assets_by_taxo: a dictionary taxonomy index -> assets on a site :param haz: an array or a dictionary of hazard on that site :param rlzi: if given, a realization index """ if isinstance(haz, numpy.ndarray): ...
:param assets_by_taxo: a dictionary taxonomy index -> assets on a site :param haz: an array or a dictionary of hazard on that site :param rlzi: if given, a realization index
Below is the the instruction that describes the task: ### Input: :param assets_by_taxo: a dictionary taxonomy index -> assets on a site :param haz: an array or a dictionary of hazard on that site :param rlzi: if given, a realization index ### Response: def get_output(self, assets_by_taxo, haz, rlzi...
def bind(self, instance, auto=False): """ Bind deps to instance :param instance: :param auto: follow update of DI and refresh binds once we will get something new :return: """ methods = [ (m, cls.__dict__[m]) for cls in inspect.getmro(type...
Bind deps to instance :param instance: :param auto: follow update of DI and refresh binds once we will get something new :return:
Below is the the instruction that describes the task: ### Input: Bind deps to instance :param instance: :param auto: follow update of DI and refresh binds once we will get something new :return: ### Response: def bind(self, instance, auto=False): """ Bind deps to instance ...
def _compile(self, **kwargs): '''Compile the Theano functions for evaluating and updating our model. ''' util.log('compiling evaluation function') self.f_eval = theano.function(self._inputs, self._monitor_exprs, ...
Compile the Theano functions for evaluating and updating our model.
Below is the the instruction that describes the task: ### Input: Compile the Theano functions for evaluating and updating our model. ### Response: def _compile(self, **kwargs): '''Compile the Theano functions for evaluating and updating our model. ''' util.log('compiling evaluation function...
def add_atype(self, ): """Add a atype and store it in the self.atypes :returns: None :rtype: None :raises: None """ i = self.atype_tablev.currentIndex() item = i.internalPointer() if item: atype = item.internal_data() atype.project...
Add a atype and store it in the self.atypes :returns: None :rtype: None :raises: None
Below is the the instruction that describes the task: ### Input: Add a atype and store it in the self.atypes :returns: None :rtype: None :raises: None ### Response: def add_atype(self, ): """Add a atype and store it in the self.atypes :returns: None :rtype: None ...
def delete_managed_disk(call=None, kwargs=None): # pylint: disable=unused-argument ''' Delete a managed disk from a resource group. ''' compconn = get_conn(client_type='compute') try: compconn.disks.delete(kwargs['resource_group'], kwargs['blob']) except Exception as exc: log....
Delete a managed disk from a resource group.
Below is the the instruction that describes the task: ### Input: Delete a managed disk from a resource group. ### Response: def delete_managed_disk(call=None, kwargs=None): # pylint: disable=unused-argument ''' Delete a managed disk from a resource group. ''' compconn = get_conn(client_type='comp...
def runctx(self, cmd, globals, locals): """Similar to profile.Profile.runctx .""" with self(): exec(cmd, globals, locals) return self
Similar to profile.Profile.runctx .
Below is the the instruction that describes the task: ### Input: Similar to profile.Profile.runctx . ### Response: def runctx(self, cmd, globals, locals): """Similar to profile.Profile.runctx .""" with self(): exec(cmd, globals, locals) return self
def ovsdb_server_method(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ovsdb_server = ET.SubElement(config, "ovsdb-server", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(ovsdb_server, "name") name_key.text = kwargs.pop('...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def ovsdb_server_method(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ovsdb_server = ET.SubElement(config, "ovsdb-server", xmlns="urn:brocade.com:mgmt:broca...
def forward_tcp(self, host, port): """Open a connection to host:port via an ssh tunnel. Args: host (str): The host to connect to. port (int): The port to connect to. Returns: A socket-like object that is connected to the provided host:port. """ ...
Open a connection to host:port via an ssh tunnel. Args: host (str): The host to connect to. port (int): The port to connect to. Returns: A socket-like object that is connected to the provided host:port.
Below is the the instruction that describes the task: ### Input: Open a connection to host:port via an ssh tunnel. Args: host (str): The host to connect to. port (int): The port to connect to. Returns: A socket-like object that is connected to the provided host:...
def mutate(self, info_in): """Replicate an info + mutation. To mutate an info, that info must have a method called ``_mutated_contents``. """ # check self is not failed if self.failed: raise ValueError("{} cannot mutate as it has failed.".format(self)) ...
Replicate an info + mutation. To mutate an info, that info must have a method called ``_mutated_contents``.
Below is the the instruction that describes the task: ### Input: Replicate an info + mutation. To mutate an info, that info must have a method called ``_mutated_contents``. ### Response: def mutate(self, info_in): """Replicate an info + mutation. To mutate an info, that info must ...
def get_proxy_for_requests(self, url): """ Get proxy configuration for a given URL, in a form ready to use with the Requests library. :param str url: The URL for which to obtain proxy configuration. :returns: Proxy configuration in a form recognized by Requests, for use with the ``proxi...
Get proxy configuration for a given URL, in a form ready to use with the Requests library. :param str url: The URL for which to obtain proxy configuration. :returns: Proxy configuration in a form recognized by Requests, for use with the ``proxies`` parameter. :rtype: dict :raises ProxyC...
Below is the the instruction that describes the task: ### Input: Get proxy configuration for a given URL, in a form ready to use with the Requests library. :param str url: The URL for which to obtain proxy configuration. :returns: Proxy configuration in a form recognized by Requests, for use with t...
def _read_varint(self): """Read exactly a varint out of the underlying file.""" buf = self._read(8) (n, l) = _DecodeVarint(buf, 0) self._unread(buf[l:]) return n
Read exactly a varint out of the underlying file.
Below is the the instruction that describes the task: ### Input: Read exactly a varint out of the underlying file. ### Response: def _read_varint(self): """Read exactly a varint out of the underlying file.""" buf = self._read(8) (n, l) = _DecodeVarint(buf, 0) self._unread(buf[l:]) ...
def eeg_add_channel(raw, channel, sync_index_eeg=0, sync_index_channel=0, channel_type=None, channel_name=None): """ Add a channel to a mne's Raw m/eeg file. It will basically synchronize the channel to the eeg data following a particular index and add it. Parameters ---------- raw : mne.io.Raw ...
Add a channel to a mne's Raw m/eeg file. It will basically synchronize the channel to the eeg data following a particular index and add it. Parameters ---------- raw : mne.io.Raw Raw EEG data. channel : list or numpy.array The channel to be added. sync_index_eeg : int or list ...
Below is the the instruction that describes the task: ### Input: Add a channel to a mne's Raw m/eeg file. It will basically synchronize the channel to the eeg data following a particular index and add it. Parameters ---------- raw : mne.io.Raw Raw EEG data. channel : list or numpy.array ...
def sparseHealpixFiles(title, infiles, field='MAGLIM',**kwargs): """ Inputs: field """ #map = ugali.utils.skymap.readSparseHealpixMaps(infiles,field) map = ugali.utils.skymap.read_partial_map(infiles,field) ax = hp.mollview(map=map, title=title, **kwargs) return ax, m...
Inputs: field
Below is the the instruction that describes the task: ### Input: Inputs: field ### Response: def sparseHealpixFiles(title, infiles, field='MAGLIM',**kwargs): """ Inputs: field """ #map = ugali.utils.skymap.readSparseHealpixMaps(infiles,field) map = ugali.utils.skymap.rea...
def edit(self, **kwargs): """ Change this Job's name. This will affect the historical data available for this Job, e.g. past run logs will no longer be accessible. """ logger.debug('Job {0} changing name to {1}'.format(self.name, kwargs.get('name'))) if not self.state.a...
Change this Job's name. This will affect the historical data available for this Job, e.g. past run logs will no longer be accessible.
Below is the the instruction that describes the task: ### Input: Change this Job's name. This will affect the historical data available for this Job, e.g. past run logs will no longer be accessible. ### Response: def edit(self, **kwargs): """ Change this Job's name. This will affe...
def expected_number_of_transactions_in_first_n_periods(self, n): r""" Return expected number of transactions in first n n_periods. Expected number of transactions occurring across first n transaction opportunities. Used by Fader and Hardie to assess in-sample fit. .. ma...
r""" Return expected number of transactions in first n n_periods. Expected number of transactions occurring across first n transaction opportunities. Used by Fader and Hardie to assess in-sample fit. .. math:: Pr(X(n) = x| \alpha, \beta, \gamma, \delta) See (7) in Fade...
Below is the the instruction that describes the task: ### Input: r""" Return expected number of transactions in first n n_periods. Expected number of transactions occurring across first n transaction opportunities. Used by Fader and Hardie to assess in-sample fit. .. math::...
def iter(self, offs): ''' Iterate over items in a sequence from a given offset. Args: offs (int): The offset to begin iterating from. Yields: (indx, valu): The index and valu of the item. ''' startkey = s_common.int64en(offs) for lkey, l...
Iterate over items in a sequence from a given offset. Args: offs (int): The offset to begin iterating from. Yields: (indx, valu): The index and valu of the item.
Below is the the instruction that describes the task: ### Input: Iterate over items in a sequence from a given offset. Args: offs (int): The offset to begin iterating from. Yields: (indx, valu): The index and valu of the item. ### Response: def iter(self, offs): ''...
def ctcp_reply(self, target, ctcp_verb, argument=None): """Send a CTCP reply to the given target.""" # we don't support complex ctcp encapsulation because we're somewhat sane atoms = [ctcp_verb] if argument is not None: atoms.append(argument) X_DELIM = '\x01' ...
Send a CTCP reply to the given target.
Below is the the instruction that describes the task: ### Input: Send a CTCP reply to the given target. ### Response: def ctcp_reply(self, target, ctcp_verb, argument=None): """Send a CTCP reply to the given target.""" # we don't support complex ctcp encapsulation because we're somewhat sane ...
def save(self, filehandle, destination=None, metadata=None, validate=True, catch_all_errors=False, *args, **kwargs): """Saves the filehandle to the provided destination or the attached default destination. Allows passing arbitrary positional and keyword arguments to the saving mecha...
Saves the filehandle to the provided destination or the attached default destination. Allows passing arbitrary positional and keyword arguments to the saving mechanism :param filehandle: werkzeug.FileStorage instance :param dest: String path, callable or writable destination to pass the...
Below is the the instruction that describes the task: ### Input: Saves the filehandle to the provided destination or the attached default destination. Allows passing arbitrary positional and keyword arguments to the saving mechanism :param filehandle: werkzeug.FileStorage instance :...
def remove_contributor(self, project_id, email, language): """ Removes a contributor """ self._run( url_path="contributors/remove", id=project_id, email=email, language=language ) return True
Removes a contributor
Below is the the instruction that describes the task: ### Input: Removes a contributor ### Response: def remove_contributor(self, project_id, email, language): """ Removes a contributor """ self._run( url_path="contributors/remove", id=project_id, ...
def build_dir(): ''' Build the directory used for templates. ''' tag_arr = ['add', 'edit', 'view', 'list', 'infolist'] path_arr = [os.path.join(CRUD_PATH, x) for x in tag_arr] for wpath in path_arr: if os.path.exists(wpath): continue os.makedirs(wpath)
Build the directory used for templates.
Below is the the instruction that describes the task: ### Input: Build the directory used for templates. ### Response: def build_dir(): ''' Build the directory used for templates. ''' tag_arr = ['add', 'edit', 'view', 'list', 'infolist'] path_arr = [os.path.join(CRUD_PATH, x) for x in tag_arr] ...
def canClose(self): """ Checks to see if the view widget can close by checking all of its \ sub-views to make sure they're ok to close. :return <bool> """ for view in self.findChildren(XView): if not view.canClose(): return False ...
Checks to see if the view widget can close by checking all of its \ sub-views to make sure they're ok to close. :return <bool>
Below is the the instruction that describes the task: ### Input: Checks to see if the view widget can close by checking all of its \ sub-views to make sure they're ok to close. :return <bool> ### Response: def canClose(self): """ Checks to see if the view widget can clo...
def put_keys(self, press_keys=None, hold_keys=None, press_delay=50): """Put scancodes that represent keys defined in the sequences provided. Arguments: press_keys: Press a sequence of keys hold_keys: While pressing the sequence of keys, hold down the keys de...
Put scancodes that represent keys defined in the sequences provided. Arguments: press_keys: Press a sequence of keys hold_keys: While pressing the sequence of keys, hold down the keys defined in hold_keys. press_delay: Number of milliseconds to delay bet...
Below is the the instruction that describes the task: ### Input: Put scancodes that represent keys defined in the sequences provided. Arguments: press_keys: Press a sequence of keys hold_keys: While pressing the sequence of keys, hold down the keys defined in ho...
def dfs_tree(graph, start=0): """DFS, build DFS tree in unweighted graph :param graph: directed graph in listlist or listdict format :param int start: source vertex :returns: precedence table :complexity: `O(|V|+|E|)` """ to_visit = [start] prec = [None] * len(graph) ...
DFS, build DFS tree in unweighted graph :param graph: directed graph in listlist or listdict format :param int start: source vertex :returns: precedence table :complexity: `O(|V|+|E|)`
Below is the the instruction that describes the task: ### Input: DFS, build DFS tree in unweighted graph :param graph: directed graph in listlist or listdict format :param int start: source vertex :returns: precedence table :complexity: `O(|V|+|E|)` ### Response: def dfs_tree(graph, st...
def handle_api_exceptions(self, method, *url_parts, **kwargs): """Call REST API and handle exceptions Params: method: 'HEAD', 'GET', 'POST', 'PATCH' or 'DELETE' url_parts: like in rest_api_url() method api_ver: like in rest_api_url() method kwargs: othe...
Call REST API and handle exceptions Params: method: 'HEAD', 'GET', 'POST', 'PATCH' or 'DELETE' url_parts: like in rest_api_url() method api_ver: like in rest_api_url() method kwargs: other parameters passed to requests.request, but the only nota...
Below is the the instruction that describes the task: ### Input: Call REST API and handle exceptions Params: method: 'HEAD', 'GET', 'POST', 'PATCH' or 'DELETE' url_parts: like in rest_api_url() method api_ver: like in rest_api_url() method kwargs: other par...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'message_type') and self.message_type is not None: _dict['message_type'] = self.message_type if hasattr(self, 'text') and self.text is not None: _dict['text'] =...
Return a json dictionary representing this model.
Below is the the instruction that describes the task: ### Input: Return a json dictionary representing this model. ### Response: def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'message_type') and self.message_type is not None: ...