code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def minmax(self, minimum=None, maximum=None): """Min/Max Sets or gets the minimum and/or maximum values for the Node. For getting, returns {"minimum":mixed,"maximum":mixed} Arguments: minimum {mixed} -- The minimum value maximum {mixed} -- The maximum value Raises: TypeError, ValueError Returns...
Min/Max Sets or gets the minimum and/or maximum values for the Node. For getting, returns {"minimum":mixed,"maximum":mixed} Arguments: minimum {mixed} -- The minimum value maximum {mixed} -- The maximum value Raises: TypeError, ValueError Returns: None | dict
Below is the the instruction that describes the task: ### Input: Min/Max Sets or gets the minimum and/or maximum values for the Node. For getting, returns {"minimum":mixed,"maximum":mixed} Arguments: minimum {mixed} -- The minimum value maximum {mixed} -- The maximum value Raises: TypeError, Val...
def set_properties(self, properties, recursive=True): """ Adds new or modifies existing properties listed in properties properties - is a dict which contains the property names and values to set. Property values can be a list or tuple to set multiple values ...
Adds new or modifies existing properties listed in properties properties - is a dict which contains the property names and values to set. Property values can be a list or tuple to set multiple values for a key. recursive - on folders property attachment is rec...
Below is the the instruction that describes the task: ### Input: Adds new or modifies existing properties listed in properties properties - is a dict which contains the property names and values to set. Property values can be a list or tuple to set multiple values ...
def remove(self, element): """ Return a new PSet with element removed. Raises KeyError if element is not present. >>> s1 = s(1, 2) >>> s1.remove(2) pset([1]) """ if element in self._map: return self.evolver().remove(element).persistent() rais...
Return a new PSet with element removed. Raises KeyError if element is not present. >>> s1 = s(1, 2) >>> s1.remove(2) pset([1])
Below is the the instruction that describes the task: ### Input: Return a new PSet with element removed. Raises KeyError if element is not present. >>> s1 = s(1, 2) >>> s1.remove(2) pset([1]) ### Response: def remove(self, element): """ Return a new PSet with element remove...
def expected_counts_stationary(T, n, mu=None): r"""Expected transition counts for Markov chain in equilibrium. Since mu is stationary for T we have .. math:: E(C^{(n)})=n diag(mu)*T. Parameters ---------- T : (M, M) sparse matrix Transition matrix. n : int Number ...
r"""Expected transition counts for Markov chain in equilibrium. Since mu is stationary for T we have .. math:: E(C^{(n)})=n diag(mu)*T. Parameters ---------- T : (M, M) sparse matrix Transition matrix. n : int Number of steps for chain. mu : (M,) ndarray (optional...
Below is the the instruction that describes the task: ### Input: r"""Expected transition counts for Markov chain in equilibrium. Since mu is stationary for T we have .. math:: E(C^{(n)})=n diag(mu)*T. Parameters ---------- T : (M, M) sparse matrix Transition matrix. n : i...
def arcs_missing(self): """Returns a sorted list of the arcs in the code not executed.""" possible = self.arc_possibilities() executed = self.arcs_executed() missing = [ p for p in possible if p not in executed and p[0] not in self.no_branc...
Returns a sorted list of the arcs in the code not executed.
Below is the the instruction that describes the task: ### Input: Returns a sorted list of the arcs in the code not executed. ### Response: def arcs_missing(self): """Returns a sorted list of the arcs in the code not executed.""" possible = self.arc_possibilities() executed = self.arcs_execu...
def make_perfect_cd(wcs): """ Create a perfect (square, orthogonal, undistorted) CD matrix from the input WCS. """ def_scale = (wcs.pscale) / 3600. def_orientat = np.deg2rad(wcs.orientat) perfect_cd = def_scale * np.array( [[-np.cos(def_orientat),np.sin(def_orientat)], [np.s...
Create a perfect (square, orthogonal, undistorted) CD matrix from the input WCS.
Below is the the instruction that describes the task: ### Input: Create a perfect (square, orthogonal, undistorted) CD matrix from the input WCS. ### Response: def make_perfect_cd(wcs): """ Create a perfect (square, orthogonal, undistorted) CD matrix from the input WCS. """ def_scale = ...
def load(path=None, **kwargs): ''' Loads the configuration from the file provided onto the device. path (required) Path where the configuration/template file is present. If the file has a ``.conf`` extension, the content is treated as text format. If the file has a ``.xml`` extensio...
Loads the configuration from the file provided onto the device. path (required) Path where the configuration/template file is present. If the file has a ``.conf`` extension, the content is treated as text format. If the file has a ``.xml`` extension, the content is treated as XML format. If...
Below is the the instruction that describes the task: ### Input: Loads the configuration from the file provided onto the device. path (required) Path where the configuration/template file is present. If the file has a ``.conf`` extension, the content is treated as text format. If the fi...
def graph_structure(self, x, standalone=True): """ Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0. Args: x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation of 5 tensors of [3, 3, 3, 2, 1] channels. standalone: If True, this mod...
Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0. Args: x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation of 5 tensors of [3, 3, 3, 2, 1] channels. standalone: If True, this model is used to predict flow from two inputs. If Fals...
Below is the the instruction that describes the task: ### Input: Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0. Args: x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation of 5 tensors of [3, 3, 3, 2, 1] channels. standalone: If True, this m...
def handle_request(self): """Handles an HTTP request.The actual HTTP request is handled using a different thread. """ timeout = self.socket.gettimeout() if timeout is None: timeout = self.timeout elif self.timeout is not None: timeout = min(time...
Handles an HTTP request.The actual HTTP request is handled using a different thread.
Below is the the instruction that describes the task: ### Input: Handles an HTTP request.The actual HTTP request is handled using a different thread. ### Response: def handle_request(self): """Handles an HTTP request.The actual HTTP request is handled using a different thread. ...
def paragraphs(self): """ Immutable sequence of |_Paragraph| instances corresponding to the paragraphs in this text frame. A text frame always contains at least one paragraph. """ return tuple([_Paragraph(p, self) for p in self._txBody.p_lst])
Immutable sequence of |_Paragraph| instances corresponding to the paragraphs in this text frame. A text frame always contains at least one paragraph.
Below is the the instruction that describes the task: ### Input: Immutable sequence of |_Paragraph| instances corresponding to the paragraphs in this text frame. A text frame always contains at least one paragraph. ### Response: def paragraphs(self): """ Immutable sequence of |_Para...
def addDraftThingType(self, thingTypeId, name = None, description = None, schemaId = None, metadata = None): """ Creates a thing type. It accepts thingTypeId (string), name (string), description (string), schemaId(string) and metadata(dict) as parameter In case of failure it throws APIEx...
Creates a thing type. It accepts thingTypeId (string), name (string), description (string), schemaId(string) and metadata(dict) as parameter In case of failure it throws APIException
Below is the the instruction that describes the task: ### Input: Creates a thing type. It accepts thingTypeId (string), name (string), description (string), schemaId(string) and metadata(dict) as parameter In case of failure it throws APIException ### Response: def addDraftThingType(self, thingType...
def _parse_ldap(ldap_filter): # type: (str) -> Optional[LDAPFilter] """ Parses the given LDAP filter string :param ldap_filter: An LDAP filter string :return: An LDAPFilter object, None if the filter was empty :raise ValueError: The LDAP filter string is invalid """ if ldap_filter is No...
Parses the given LDAP filter string :param ldap_filter: An LDAP filter string :return: An LDAPFilter object, None if the filter was empty :raise ValueError: The LDAP filter string is invalid
Below is the the instruction that describes the task: ### Input: Parses the given LDAP filter string :param ldap_filter: An LDAP filter string :return: An LDAPFilter object, None if the filter was empty :raise ValueError: The LDAP filter string is invalid ### Response: def _parse_ldap(ldap_filter): ...
def list_firewall_rules(self, server_name): ''' Retrieves the set of firewall rules for an Azure SQL Database Server. server_name: Name of the server. ''' _validate_not_none('server_name', server_name) response = self._perform_get(self._get_firewall_rules_pat...
Retrieves the set of firewall rules for an Azure SQL Database Server. server_name: Name of the server.
Below is the the instruction that describes the task: ### Input: Retrieves the set of firewall rules for an Azure SQL Database Server. server_name: Name of the server. ### Response: def list_firewall_rules(self, server_name): ''' Retrieves the set of firewall rules for an Azure...
def orient_import2(self, event): """ initialize window to import an AzDip format file into the working directory """ pmag_menu_dialogs.ImportAzDipFile(self.parent, self.parent.WD)
initialize window to import an AzDip format file into the working directory
Below is the the instruction that describes the task: ### Input: initialize window to import an AzDip format file into the working directory ### Response: def orient_import2(self, event): """ initialize window to import an AzDip format file into the working directory """ pmag_menu_d...
def parse_case_snake_to_camel(snake, upper_first=True): """ Convert a string from snake_case to CamelCase. :param str snake: The snake_case string to convert. :param bool upper_first: Whether or not to capitalize the first character of the string. :return: The CamelCase version of string. :rtype: str """ sna...
Convert a string from snake_case to CamelCase. :param str snake: The snake_case string to convert. :param bool upper_first: Whether or not to capitalize the first character of the string. :return: The CamelCase version of string. :rtype: str
Below is the the instruction that describes the task: ### Input: Convert a string from snake_case to CamelCase. :param str snake: The snake_case string to convert. :param bool upper_first: Whether or not to capitalize the first character of the string. :return: The CamelCase version of string. :rtype: str ##...
def solve_minimize( self, func, weights, constraints, lower_bound=0.0, upper_bound=1.0, func_deriv=False ): """ Returns the solution to a minimization problem. """ bounds = ((lower_bound, upper_bound), ) * len(self.SUPPORTED_CO...
Returns the solution to a minimization problem.
Below is the the instruction that describes the task: ### Input: Returns the solution to a minimization problem. ### Response: def solve_minimize( self, func, weights, constraints, lower_bound=0.0, upper_bound=1.0, func_deriv=False ): """ ...
def create(self, input=None, live_stream=False, outputs=None, options=None): """ Creates a transcoding job. Here are some examples:: job.create('s3://zencodertesting/test.mov') job.create(live_stream=True) job.create(input='http://example.com/input.mov', ...
Creates a transcoding job. Here are some examples:: job.create('s3://zencodertesting/test.mov') job.create(live_stream=True) job.create(input='http://example.com/input.mov', outputs=({'label': 'test output'},)) https://app.zencoder.com/docs/api/jobs/c...
Below is the the instruction that describes the task: ### Input: Creates a transcoding job. Here are some examples:: job.create('s3://zencodertesting/test.mov') job.create(live_stream=True) job.create(input='http://example.com/input.mov', outputs=({'label'...
def rdkitmol_Hs(self): r'''RDKit object of the chemical, with hydrogen. If RDKit is not available, holds None. For examples of what can be done with RDKit, see `their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_. ''' if self.__rdkitmol_Hs: ...
r'''RDKit object of the chemical, with hydrogen. If RDKit is not available, holds None. For examples of what can be done with RDKit, see `their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_.
Below is the the instruction that describes the task: ### Input: r'''RDKit object of the chemical, with hydrogen. If RDKit is not available, holds None. For examples of what can be done with RDKit, see `their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_. ### Response: ...
def makeObjectFeed( paginator, objectToXMLFunction, feedId, title, webRoot, idAttr="id", nameAttr="name", dateAttr=None, request=None, page=1, count=20, author=APP_AUTHOR): """ Take a list of some kind of object, a conversion function, an id and a title Return XML representing an ATO...
Take a list of some kind of object, a conversion function, an id and a title Return XML representing an ATOM feed
Below is the the instruction that describes the task: ### Input: Take a list of some kind of object, a conversion function, an id and a title Return XML representing an ATOM feed ### Response: def makeObjectFeed( paginator, objectToXMLFunction, feedId, title, webRoot, idAttr="id", nameAttr="nam...
def canonical_order(self): """The vertices in a canonical or normalized order. This routine will return a list of vertices in an order that does not depend on the initial order, but only depends on the connectivity and the return values of the function self.get_vertex_string. ...
The vertices in a canonical or normalized order. This routine will return a list of vertices in an order that does not depend on the initial order, but only depends on the connectivity and the return values of the function self.get_vertex_string. Only the vertices that are ...
Below is the the instruction that describes the task: ### Input: The vertices in a canonical or normalized order. This routine will return a list of vertices in an order that does not depend on the initial order, but only depends on the connectivity and the return values of the fun...
def _get_upper_bound(self): r"""Return an upper bound on the eigenvalues of the Laplacian.""" if self.lap_type == 'normalized': return 2 # Equal iff the graph is bipartite. elif self.lap_type == 'combinatorial': bounds = [] # Equal for full graphs. ...
r"""Return an upper bound on the eigenvalues of the Laplacian.
Below is the the instruction that describes the task: ### Input: r"""Return an upper bound on the eigenvalues of the Laplacian. ### Response: def _get_upper_bound(self): r"""Return an upper bound on the eigenvalues of the Laplacian.""" if self.lap_type == 'normalized': return 2 # Equa...
def connect(self, f, mode=None): """ Connect an object `f` to the signal. The type the object needs to have depends on `mode`, but usually it needs to be a callable. :meth:`connect` returns an opaque token which can be used with :meth:`disconnect` to disconnect the object from t...
Connect an object `f` to the signal. The type the object needs to have depends on `mode`, but usually it needs to be a callable. :meth:`connect` returns an opaque token which can be used with :meth:`disconnect` to disconnect the object from the signal. The default value for `mode` is :...
Below is the the instruction that describes the task: ### Input: Connect an object `f` to the signal. The type the object needs to have depends on `mode`, but usually it needs to be a callable. :meth:`connect` returns an opaque token which can be used with :meth:`disconnect` to disconnect t...
def accountSummary(self, account: str = '') -> List[AccountValue]: """ List of account values for the given account, or of all accounts if account is left blank. This method is blocking on first run, non-blocking after that. Args: account: If specified, filter for t...
List of account values for the given account, or of all accounts if account is left blank. This method is blocking on first run, non-blocking after that. Args: account: If specified, filter for this account name.
Below is the the instruction that describes the task: ### Input: List of account values for the given account, or of all accounts if account is left blank. This method is blocking on first run, non-blocking after that. Args: account: If specified, filter for this account name. ...
def lpush(self, key, *values): """ Insert all the specified values at the head of the list stored at key. :param key: The list's key :type key: :class:`str`, :class:`bytes` :param values: One or more positional arguments to insert at the beginning of the list. Each ...
Insert all the specified values at the head of the list stored at key. :param key: The list's key :type key: :class:`str`, :class:`bytes` :param values: One or more positional arguments to insert at the beginning of the list. Each value is inserted at the beginning of t...
Below is the the instruction that describes the task: ### Input: Insert all the specified values at the head of the list stored at key. :param key: The list's key :type key: :class:`str`, :class:`bytes` :param values: One or more positional arguments to insert at the beginning o...
def verify(path): """Verify that `path` has the qpimage series file format""" valid = False try: h5 = h5py.File(path, mode="r") qpi0 = h5["qpi_0"] except (OSError, KeyError): pass else: if ("qpimage version" in qpi0.attrs and ...
Verify that `path` has the qpimage series file format
Below is the the instruction that describes the task: ### Input: Verify that `path` has the qpimage series file format ### Response: def verify(path): """Verify that `path` has the qpimage series file format""" valid = False try: h5 = h5py.File(path, mode="r") qpi0 =...
def _pfp__build(self, stream=None, save_offset=False): """Build the field and write the result into the stream :stream: An IO stream that can be written to :returns: None """ if stream is not None and save_offset: self._pfp__offset = stream.tell() if self.b...
Build the field and write the result into the stream :stream: An IO stream that can be written to :returns: None
Below is the the instruction that describes the task: ### Input: Build the field and write the result into the stream :stream: An IO stream that can be written to :returns: None ### Response: def _pfp__build(self, stream=None, save_offset=False): """Build the field and write the result int...
def clear_nonexistent_import_errors(self, session): """ Clears import errors for files that no longer exist. :param session: session for ORM operations :type session: sqlalchemy.orm.session.Session """ query = session.query(errors.ImportError) if self._file_paths...
Clears import errors for files that no longer exist. :param session: session for ORM operations :type session: sqlalchemy.orm.session.Session
Below is the the instruction that describes the task: ### Input: Clears import errors for files that no longer exist. :param session: session for ORM operations :type session: sqlalchemy.orm.session.Session ### Response: def clear_nonexistent_import_errors(self, session): """ Clear...
def regex_in(pl,regex): ''' regex = re.compile("^[a-z]+$") pl = ['b1c3d','xab15cxx','1x','y2'] regex_in(pl,regex) regex = re.compile("^[0-9a-z]+$") pl = ['b1c3d','xab15cxx','1x','y2'] regex_in(pl,regex) ''' def cond_func(ele,regex): m...
regex = re.compile("^[a-z]+$") pl = ['b1c3d','xab15cxx','1x','y2'] regex_in(pl,regex) regex = re.compile("^[0-9a-z]+$") pl = ['b1c3d','xab15cxx','1x','y2'] regex_in(pl,regex)
Below is the the instruction that describes the task: ### Input: regex = re.compile("^[a-z]+$") pl = ['b1c3d','xab15cxx','1x','y2'] regex_in(pl,regex) regex = re.compile("^[0-9a-z]+$") pl = ['b1c3d','xab15cxx','1x','y2'] regex_in(pl,regex) ### Response: def regex_in...
def get_dashboard_info(adapter, institute_id=None, slice_query=None): """Returns cases with phenotype If phenotypes are provided search for only those Args: adapter(adapter.MongoAdapter) institute_id(str): an institute _id slice_query(str): query to filter cases to obtain stat...
Returns cases with phenotype If phenotypes are provided search for only those Args: adapter(adapter.MongoAdapter) institute_id(str): an institute _id slice_query(str): query to filter cases to obtain statistics for. Returns: data(dict): Dictionary with relevant inform...
Below is the the instruction that describes the task: ### Input: Returns cases with phenotype If phenotypes are provided search for only those Args: adapter(adapter.MongoAdapter) institute_id(str): an institute _id slice_query(str): query to filter cases to obtain statistics f...
def fdf(self, x): """Calculate the value of the functional for the specified arguments, and the derivatives with respect to the parameters (taking any specified mask into account). :param x: the value(s) to evaluate at """ x = self._flatten(x) n = 1 if has...
Calculate the value of the functional for the specified arguments, and the derivatives with respect to the parameters (taking any specified mask into account). :param x: the value(s) to evaluate at
Below is the the instruction that describes the task: ### Input: Calculate the value of the functional for the specified arguments, and the derivatives with respect to the parameters (taking any specified mask into account). :param x: the value(s) to evaluate at ### Response: def fdf(self,...
def darken(self, amount): ''' Darken (reduce the luminance) of this color. Args: amount (float) : Amount to reduce the luminance by (clamped above zero) Returns: Color ''' hsl = self.to_hsl() hsl.l = self.clamp(hsl.l - amount) ...
Darken (reduce the luminance) of this color. Args: amount (float) : Amount to reduce the luminance by (clamped above zero) Returns: Color
Below is the the instruction that describes the task: ### Input: Darken (reduce the luminance) of this color. Args: amount (float) : Amount to reduce the luminance by (clamped above zero) Returns: Color ### Response: def darken(self, amount): ''' Da...
def copy_to(source, dest, engine_or_conn, **flags): """Export a query or select to a file. For flags, see the PostgreSQL documentation at http://www.postgresql.org/docs/9.5/static/sql-copy.html. Examples: :: select = MyTable.select() with open('/path/to/file.tsv', 'w') as fp: co...
Export a query or select to a file. For flags, see the PostgreSQL documentation at http://www.postgresql.org/docs/9.5/static/sql-copy.html. Examples: :: select = MyTable.select() with open('/path/to/file.tsv', 'w') as fp: copy_to(select, fp, conn) query = session.query(MyMo...
Below is the the instruction that describes the task: ### Input: Export a query or select to a file. For flags, see the PostgreSQL documentation at http://www.postgresql.org/docs/9.5/static/sql-copy.html. Examples: :: select = MyTable.select() with open('/path/to/file.tsv', 'w') as fp: ...
def hasattrs(object, *names): """ Takes in an object and a variable length amount of named attributes, and checks to see if the object has each property. If any of the attributes are missing, this returns false. :param object: an object that may or may not contain the listed attributes :param n...
Takes in an object and a variable length amount of named attributes, and checks to see if the object has each property. If any of the attributes are missing, this returns false. :param object: an object that may or may not contain the listed attributes :param names: a variable amount of attribute names...
Below is the the instruction that describes the task: ### Input: Takes in an object and a variable length amount of named attributes, and checks to see if the object has each property. If any of the attributes are missing, this returns false. :param object: an object that may or may not contain the lis...
def get_core(self): """ Get an unsatisfiable core if the formula was previously unsatisfied. """ if self.maplesat and self.status == False: return pysolvers.maplesat_core(self.maplesat)
Get an unsatisfiable core if the formula was previously unsatisfied.
Below is the the instruction that describes the task: ### Input: Get an unsatisfiable core if the formula was previously unsatisfied. ### Response: def get_core(self): """ Get an unsatisfiable core if the formula was previously unsatisfied. """ if self.m...
def insert(cls, cur, table: str, values: dict): """ Creates an insert statement with only chosen fields Args: table: a string indicating the name of the table values: a dict of fields and values to be inserted Returns: A 'Record' object with table co...
Creates an insert statement with only chosen fields Args: table: a string indicating the name of the table values: a dict of fields and values to be inserted Returns: A 'Record' object with table columns as properties
Below is the the instruction that describes the task: ### Input: Creates an insert statement with only chosen fields Args: table: a string indicating the name of the table values: a dict of fields and values to be inserted Returns: A 'Record' object with table c...
def constraint_matches(self, c, m): """ Return dict noting the substitution values (or False for no match) """ if isinstance(m, tuple): d = {} if isinstance(c, Operator) and c._op_name == m[0]: for c1, m1 in zip(c._args, m[1:]): ...
Return dict noting the substitution values (or False for no match)
Below is the the instruction that describes the task: ### Input: Return dict noting the substitution values (or False for no match) ### Response: def constraint_matches(self, c, m): """ Return dict noting the substitution values (or False for no match) """ if isinstance(m, tuple): ...
def paginate_sources(owner=None, page=1, page_size=DEFAULT_PAGE_SIZE): '''Paginate harvest sources''' sources = _sources_queryset(owner=owner) page = max(page or 1, 1) return sources.paginate(page, page_size)
Paginate harvest sources
Below is the the instruction that describes the task: ### Input: Paginate harvest sources ### Response: def paginate_sources(owner=None, page=1, page_size=DEFAULT_PAGE_SIZE): '''Paginate harvest sources''' sources = _sources_queryset(owner=owner) page = max(page or 1, 1) return sources.paginate(pag...
def sort_sam(sam, sort): """ sort sam file """ tempdir = '%s/' % (os.path.abspath(sam).rsplit('/', 1)[0]) if sort is True: mapping = '%s.sorted.sam' % (sam.rsplit('.', 1)[0]) if sam != '-': if os.path.exists(mapping) is False: os.system("\ ...
sort sam file
Below is the the instruction that describes the task: ### Input: sort sam file ### Response: def sort_sam(sam, sort): """ sort sam file """ tempdir = '%s/' % (os.path.abspath(sam).rsplit('/', 1)[0]) if sort is True: mapping = '%s.sorted.sam' % (sam.rsplit('.', 1)[0]) if sam != '...
def get_gateway_info(self): """ Return the gateway info. Returns a Command. """ def process_result(result): return GatewayInfo(result) return Command('get', [ROOT_GATEWAY, ATTR_GATEWAY_INFO], process_result=proce...
Return the gateway info. Returns a Command.
Below is the the instruction that describes the task: ### Input: Return the gateway info. Returns a Command. ### Response: def get_gateway_info(self): """ Return the gateway info. Returns a Command. """ def process_result(result): return GatewayInfo(res...
def _locateConvergencePoint(stats, minOverlap, maxOverlap): """ Walk backwards through stats until you locate the first point that diverges from target overlap values. We need this to handle cases where it might get to target values, diverge, and then get back again. We want the last convergence p...
Walk backwards through stats until you locate the first point that diverges from target overlap values. We need this to handle cases where it might get to target values, diverge, and then get back again. We want the last convergence point.
Below is the the instruction that describes the task: ### Input: Walk backwards through stats until you locate the first point that diverges from target overlap values. We need this to handle cases where it might get to target values, diverge, and then get back again. We want the last convergence poin...
def getall(self, table): """ Get all rows values for a table """ try: self._check_db() except Exception as e: self.err(e, "Can not connect to database") return if table not in self.db.tables: self.warning("The table " + tabl...
Get all rows values for a table
Below is the the instruction that describes the task: ### Input: Get all rows values for a table ### Response: def getall(self, table): """ Get all rows values for a table """ try: self._check_db() except Exception as e: self.err(e, "Can not connect t...
def _key_values(self, sn: "SequenceNode") -> Union[EntryKeys, EntryValue]: """Parse leaf-list value or list keys.""" try: keys = self.up_to("/") except EndOfInput: keys = self.remaining() if not keys: raise UnexpectedInput(self, "entry value or keys") ...
Parse leaf-list value or list keys.
Below is the the instruction that describes the task: ### Input: Parse leaf-list value or list keys. ### Response: def _key_values(self, sn: "SequenceNode") -> Union[EntryKeys, EntryValue]: """Parse leaf-list value or list keys.""" try: keys = self.up_to("/") except EndOfInput: ...
def set_sig_figs(n=4): """Set the number of significant figures used to print Pint, Pandas, and NumPy quantities. Args: n (int): Number of significant figures to display. """ u.default_format = '.' + str(n) + 'g' pd.options.display.float_format = ('{:,.' + str(n) + '}').format
Set the number of significant figures used to print Pint, Pandas, and NumPy quantities. Args: n (int): Number of significant figures to display.
Below is the the instruction that describes the task: ### Input: Set the number of significant figures used to print Pint, Pandas, and NumPy quantities. Args: n (int): Number of significant figures to display. ### Response: def set_sig_figs(n=4): """Set the number of significant figures used t...
def vectorize(density_matrix, method='col'): """Flatten an operator to a vector in a specified basis. Args: density_matrix (ndarray): a density matrix. method (str): the method of vectorization. Allowed values are - 'col' (default) flattens to column-major vector. - 'row...
Flatten an operator to a vector in a specified basis. Args: density_matrix (ndarray): a density matrix. method (str): the method of vectorization. Allowed values are - 'col' (default) flattens to column-major vector. - 'row' flattens to row-major vector. - 'pauli...
Below is the the instruction that describes the task: ### Input: Flatten an operator to a vector in a specified basis. Args: density_matrix (ndarray): a density matrix. method (str): the method of vectorization. Allowed values are - 'col' (default) flattens to column-major vector. ...
def add(self, years=0, months=0, weeks=0, days=0): """ Add duration to the instance. :param years: The number of years :type years: int :param months: The number of months :type months: int :param weeks: The number of weeks :type weeks: int :pa...
Add duration to the instance. :param years: The number of years :type years: int :param months: The number of months :type months: int :param weeks: The number of weeks :type weeks: int :param days: The number of days :type days: int :rtype: D...
Below is the the instruction that describes the task: ### Input: Add duration to the instance. :param years: The number of years :type years: int :param months: The number of months :type months: int :param weeks: The number of weeks :type weeks: int :para...
def MultiDelete(self, urns, token=None): """Drop all the information about given objects. DANGEROUS! This recursively deletes all objects contained within the specified URN. Args: urns: Urns of objects to remove. token: The Security Token to use for opening this item. Raises: Va...
Drop all the information about given objects. DANGEROUS! This recursively deletes all objects contained within the specified URN. Args: urns: Urns of objects to remove. token: The Security Token to use for opening this item. Raises: ValueError: If one of the urns is too short. This ...
Below is the the instruction that describes the task: ### Input: Drop all the information about given objects. DANGEROUS! This recursively deletes all objects contained within the specified URN. Args: urns: Urns of objects to remove. token: The Security Token to use for opening this item. ...
def fetch_fieldnames(self, sql: str, *args) -> List[str]: """Executes SQL; returns just the output fieldnames.""" self.ensure_db_open() cursor = self.db.cursor() self.db_exec_with_cursor(cursor, sql, *args) try: return [i[0] for i in cursor.description] except...
Executes SQL; returns just the output fieldnames.
Below is the the instruction that describes the task: ### Input: Executes SQL; returns just the output fieldnames. ### Response: def fetch_fieldnames(self, sql: str, *args) -> List[str]: """Executes SQL; returns just the output fieldnames.""" self.ensure_db_open() cursor = self.db.cursor() ...
def header(self, array): """Specify the header of the table """ self._check_row_size(array) self._header = list(map(obj2unicode, array)) return self
Specify the header of the table
Below is the the instruction that describes the task: ### Input: Specify the header of the table ### Response: def header(self, array): """Specify the header of the table """ self._check_row_size(array) self._header = list(map(obj2unicode, array)) return self
def rst_to_notebook(infile, outfile): """Convert an rst file to a notebook file.""" # Read infile into a string with open(infile, 'r') as fin: rststr = fin.read() # Convert string from rst to markdown mdfmt = 'markdown_github+tex_math_dollars+fenced_code_attributes' mdstr = pypandoc.con...
Convert an rst file to a notebook file.
Below is the the instruction that describes the task: ### Input: Convert an rst file to a notebook file. ### Response: def rst_to_notebook(infile, outfile): """Convert an rst file to a notebook file.""" # Read infile into a string with open(infile, 'r') as fin: rststr = fin.read() # Conver...
def status(self): """ Status of this SMS. Can be ENROUTE, DELIVERED or FAILED The actual status report object may be accessed via the 'report' attribute if status is 'DELIVERED' or 'FAILED' """ if self.report == None: return SentSms.ENROUTE else: ...
Status of this SMS. Can be ENROUTE, DELIVERED or FAILED The actual status report object may be accessed via the 'report' attribute if status is 'DELIVERED' or 'FAILED'
Below is the the instruction that describes the task: ### Input: Status of this SMS. Can be ENROUTE, DELIVERED or FAILED The actual status report object may be accessed via the 'report' attribute if status is 'DELIVERED' or 'FAILED' ### Response: def status(self): """ Status of thi...
def configuration(self, plugin): """ Get plugin configuration. Return a tuple of (on|off|default, args) """ conf = self.config.get(plugin, "default;").split(';') if len(conf) == 1: conf.append('') return tuple(conf)
Get plugin configuration. Return a tuple of (on|off|default, args)
Below is the the instruction that describes the task: ### Input: Get plugin configuration. Return a tuple of (on|off|default, args) ### Response: def configuration(self, plugin): """ Get plugin configuration. Return a tuple of (on|off|default, args) """ conf = self...
def _to_pandas(ob): """Convert an array-like to a pandas object. Parameters ---------- ob : array-like The object to convert. Returns ------- pandas_structure : pd.Series or pd.DataFrame The correct structure based on the dimensionality of the data. """ if isinstanc...
Convert an array-like to a pandas object. Parameters ---------- ob : array-like The object to convert. Returns ------- pandas_structure : pd.Series or pd.DataFrame The correct structure based on the dimensionality of the data.
Below is the the instruction that describes the task: ### Input: Convert an array-like to a pandas object. Parameters ---------- ob : array-like The object to convert. Returns ------- pandas_structure : pd.Series or pd.DataFrame The correct structure based on the dimensiona...
def get_rate_limits(response): """Returns a list of rate limit information from a given response's headers.""" periods = response.headers['X-RateLimit-Period'] if not periods: return [] rate_limits = [] periods = periods.split(',') limits = response.headers['X-RateLimit-Limit'].split('...
Returns a list of rate limit information from a given response's headers.
Below is the the instruction that describes the task: ### Input: Returns a list of rate limit information from a given response's headers. ### Response: def get_rate_limits(response): """Returns a list of rate limit information from a given response's headers.""" periods = response.headers['X-RateLimit-Per...
def get_all_not_wh_regions(db_connection): """ Gets a list of all regions that are not WH regions. :return: A list of all regions not including wormhole regions. Results have regionID and regionName. :rtype: list """ if not hasattr(get_all_not_wh_regions, '_results'): sql = 'CALL get_all_n...
Gets a list of all regions that are not WH regions. :return: A list of all regions not including wormhole regions. Results have regionID and regionName. :rtype: list
Below is the the instruction that describes the task: ### Input: Gets a list of all regions that are not WH regions. :return: A list of all regions not including wormhole regions. Results have regionID and regionName. :rtype: list ### Response: def get_all_not_wh_regions(db_connection): """ Gets a lis...
def rescan_images(registry): '''Update the kernel image metadata from all configured docker registries.''' with Session() as session: try: result = session.Image.rescanImages(registry) except Exception as e: print_error(e) sys.exit(1) if result['ok']: ...
Update the kernel image metadata from all configured docker registries.
Below is the the instruction that describes the task: ### Input: Update the kernel image metadata from all configured docker registries. ### Response: def rescan_images(registry): '''Update the kernel image metadata from all configured docker registries.''' with Session() as session: try: ...
def convert_to_file(file, ndarr): """ Writes the contents of the numpy.ndarray ndarr to file in IDX format. file is a file-like object (with write() method) or a file name. """ if isinstance(file, six_string_types): with open(file, 'wb') as fp: _internal_write(fp, ndarr) else...
Writes the contents of the numpy.ndarray ndarr to file in IDX format. file is a file-like object (with write() method) or a file name.
Below is the the instruction that describes the task: ### Input: Writes the contents of the numpy.ndarray ndarr to file in IDX format. file is a file-like object (with write() method) or a file name. ### Response: def convert_to_file(file, ndarr): """ Writes the contents of the numpy.ndarray ndarr to f...
def conference_undeaf(self, call_params): """REST Conference Undeaf helper """ path = '/' + self.api_version + '/ConferenceUndeaf/' method = 'POST' return self.request(path, method, call_params)
REST Conference Undeaf helper
Below is the the instruction that describes the task: ### Input: REST Conference Undeaf helper ### Response: def conference_undeaf(self, call_params): """REST Conference Undeaf helper """ path = '/' + self.api_version + '/ConferenceUndeaf/' method = 'POST' return self.reques...
def requestPdpContextActivation(AccessPointName_presence=0): """REQUEST PDP CONTEXT ACTIVATION Section 9.5.4""" a = TpPd(pd=0x8) b = MessageType(mesType=0x44) # 01000100 c = PacketDataProtocolAddress() packet = a / b / c if AccessPointName_presence is 1: d = AccessPointName(ieiAPN=0x28)...
REQUEST PDP CONTEXT ACTIVATION Section 9.5.4
Below is the the instruction that describes the task: ### Input: REQUEST PDP CONTEXT ACTIVATION Section 9.5.4 ### Response: def requestPdpContextActivation(AccessPointName_presence=0): """REQUEST PDP CONTEXT ACTIVATION Section 9.5.4""" a = TpPd(pd=0x8) b = MessageType(mesType=0x44) # 01000100 c = ...
def smart_account(app): """尝试使用内置方式构建账户""" if os.environ['FANTASY_ACTIVE_ACCOUNT'] == 'no': return from flask_security import SQLAlchemyUserDatastore, Security account_module_name, account_class_name = os.environ[ 'FANTASY_ACCOUNT_MODEL'].rsplit('.', 1) account_module = importlib....
尝试使用内置方式构建账户
Below is the the instruction that describes the task: ### Input: 尝试使用内置方式构建账户 ### Response: def smart_account(app): """尝试使用内置方式构建账户""" if os.environ['FANTASY_ACTIVE_ACCOUNT'] == 'no': return from flask_security import SQLAlchemyUserDatastore, Security account_module_name, account_class_na...
def log_url (self, url_data): """Write url checking info.""" self.writeln() if self.has_part('url'): self.write_url(url_data) if url_data.name and self.has_part('name'): self.write_name(url_data) if url_data.parent_url and self.has_part('parenturl'): ...
Write url checking info.
Below is the the instruction that describes the task: ### Input: Write url checking info. ### Response: def log_url (self, url_data): """Write url checking info.""" self.writeln() if self.has_part('url'): self.write_url(url_data) if url_data.name and self.has_part('name'...
def create(callback=None, path=None, method=Method.POST, resource=None, tags=None, summary="Create a new resource", middleware=None): # type: (Callable, Path, Methods, Resource, Tags, str, List[Any]) -> Operation """ Decorator to configure an operation that creates a resource. """ def inn...
Decorator to configure an operation that creates a resource.
Below is the the instruction that describes the task: ### Input: Decorator to configure an operation that creates a resource. ### Response: def create(callback=None, path=None, method=Method.POST, resource=None, tags=None, summary="Create a new resource", middleware=None): # type: (Callable, Path, M...
def _create_affine_multiframe(multiframe_dicom): """ Function to create the affine matrix for a siemens mosaic dataset This will work for siemens dti and 4D if in mosaic format """ first_frame = multiframe_dicom[Tag(0x5200, 0x9230)][0] last_frame = multiframe_dicom[Tag(0x5200, 0x9230)][-1] #...
Function to create the affine matrix for a siemens mosaic dataset This will work for siemens dti and 4D if in mosaic format
Below is the the instruction that describes the task: ### Input: Function to create the affine matrix for a siemens mosaic dataset This will work for siemens dti and 4D if in mosaic format ### Response: def _create_affine_multiframe(multiframe_dicom): """ Function to create the affine matrix for a siem...
def spectra(i, **kwargs): """ Define colours by number. Can be plotted either in order of gray scale or in the 'best' order for having a strong gray contrast for only three or four lines :param i: the index to access a colour """ ordered = kwargs.get('ordered', False) options = kwargs.ge...
Define colours by number. Can be plotted either in order of gray scale or in the 'best' order for having a strong gray contrast for only three or four lines :param i: the index to access a colour
Below is the the instruction that describes the task: ### Input: Define colours by number. Can be plotted either in order of gray scale or in the 'best' order for having a strong gray contrast for only three or four lines :param i: the index to access a colour ### Response: def spectra(i, **kwargs): ...
def clear(self, *args, **kwargs): """Clear only drafts. Status required: ``'draft'``. Meta information inside `_deposit` are preserved. """ super(Deposit, self).clear(*args, **kwargs)
Clear only drafts. Status required: ``'draft'``. Meta information inside `_deposit` are preserved.
Below is the the instruction that describes the task: ### Input: Clear only drafts. Status required: ``'draft'``. Meta information inside `_deposit` are preserved. ### Response: def clear(self, *args, **kwargs): """Clear only drafts. Status required: ``'draft'``. Meta in...
def str_to_num(i, exact_match=True): """ Attempts to convert a str to either an int or float """ # TODO: Cleanup -- this is really ugly if not isinstance(i, str): return i try: if not exact_match: return int(i) elif str(int(i)) == i: return int(i) ...
Attempts to convert a str to either an int or float
Below is the the instruction that describes the task: ### Input: Attempts to convert a str to either an int or float ### Response: def str_to_num(i, exact_match=True): """ Attempts to convert a str to either an int or float """ # TODO: Cleanup -- this is really ugly if not isinstance(i, str): ...
def _customized_loader(container, loader=Loader, mapping_tag=_MAPPING_TAG): """ Create or update loader with making given callble 'container' to make mapping objects such as dict and OrderedDict, used to construct python object from yaml mapping node internally. :param container: Set container used...
Create or update loader with making given callble 'container' to make mapping objects such as dict and OrderedDict, used to construct python object from yaml mapping node internally. :param container: Set container used internally
Below is the the instruction that describes the task: ### Input: Create or update loader with making given callble 'container' to make mapping objects such as dict and OrderedDict, used to construct python object from yaml mapping node internally. :param container: Set container used internally ### Res...
def create_widget(self): """ Create the underlying widget. A dialog is not a subclass of view, hence we don't set name as widget or children will try to use it as their parent. """ d = self.declaration self.dialog = BottomSheetDialog(self.get_context(), d.style)
Create the underlying widget. A dialog is not a subclass of view, hence we don't set name as widget or children will try to use it as their parent.
Below is the the instruction that describes the task: ### Input: Create the underlying widget. A dialog is not a subclass of view, hence we don't set name as widget or children will try to use it as their parent. ### Response: def create_widget(self): """ Create the underlying widget. ...
def euler_trans_matrix(etheta, elongan, eincl): """ Get the transformation matrix R to translate/rotate a mesh according to euler angles. The matrix is R(long,incl,theta) = Rz(pi).Rz(long).Rx(incl).Rz(theta) Rz(long).Rx(-incl).Rz(theta).Rz(pi) where Rx(u) = 1, 0, ...
Get the transformation matrix R to translate/rotate a mesh according to euler angles. The matrix is R(long,incl,theta) = Rz(pi).Rz(long).Rx(incl).Rz(theta) Rz(long).Rx(-incl).Rz(theta).Rz(pi) where Rx(u) = 1, 0, 0 0, cos(u), -sin(u) 0, ...
Below is the the instruction that describes the task: ### Input: Get the transformation matrix R to translate/rotate a mesh according to euler angles. The matrix is R(long,incl,theta) = Rz(pi).Rz(long).Rx(incl).Rz(theta) Rz(long).Rx(-incl).Rz(theta).Rz(pi) where Rx(u) = 1...
def user_twitter_list_bag_of_words(twitter_list_corpus, sent_tokenize, _treebank_word_tokenize, tagger, lemmatizer, lemmatize, stopset, first_cap_re, all_cap_re, digits_punctuation_whitespace_re, ...
Extract a bag-of-words for a corpus of Twitter lists pertaining to a Twitter user. Inputs: - twitter_list_corpus: A python list of Twitter lists in json format. - lemmatizing: A string containing one of the following: "porter", "snowball" or "wordnet". Output: - bag_of_words: A bag-of-words in pyt...
Below is the the instruction that describes the task: ### Input: Extract a bag-of-words for a corpus of Twitter lists pertaining to a Twitter user. Inputs: - twitter_list_corpus: A python list of Twitter lists in json format. - lemmatizing: A string containing one of the following: "porter", "snowb...
def _populate_inputs(self, total): """Request the names for all active, configured inputs on the device. Once we learn how many inputs are configured, this function is called which will ask for the name of each active input. """ total = total + 1 for input_number in rang...
Request the names for all active, configured inputs on the device. Once we learn how many inputs are configured, this function is called which will ask for the name of each active input.
Below is the the instruction that describes the task: ### Input: Request the names for all active, configured inputs on the device. Once we learn how many inputs are configured, this function is called which will ask for the name of each active input. ### Response: def _populate_inputs(self, total...
def service_create(auth=None, **kwargs): ''' Create a service CLI Example: .. code-block:: bash salt '*' keystoneng.service_create name=glance type=image salt '*' keystoneng.service_create name=glance type=image description="Image" ''' cloud = get_operator_cloud(auth) kwar...
Create a service CLI Example: .. code-block:: bash salt '*' keystoneng.service_create name=glance type=image salt '*' keystoneng.service_create name=glance type=image description="Image"
Below is the the instruction that describes the task: ### Input: Create a service CLI Example: .. code-block:: bash salt '*' keystoneng.service_create name=glance type=image salt '*' keystoneng.service_create name=glance type=image description="Image" ### Response: def service_create(aut...
def path_locations(home_dir): """Return the path locations for the environment (where libraries are, where scripts go, etc)""" # XXX: We'd use distutils.sysconfig.get_python_inc/lib but its # prefix arg is broken: http://bugs.python.org/issue3386 if sys.platform == 'win32': # Windows has lot...
Return the path locations for the environment (where libraries are, where scripts go, etc)
Below is the the instruction that describes the task: ### Input: Return the path locations for the environment (where libraries are, where scripts go, etc) ### Response: def path_locations(home_dir): """Return the path locations for the environment (where libraries are, where scripts go, etc)""" # ...
def extend_expiration_date(self, days=KEY_EXPIRATION_DELTA): """ Extend expiration date a number of given years """ delta = timedelta_days(days) self.expiration_date = self.expiration_date + delta self.save()
Extend expiration date a number of given years
Below is the the instruction that describes the task: ### Input: Extend expiration date a number of given years ### Response: def extend_expiration_date(self, days=KEY_EXPIRATION_DELTA): """ Extend expiration date a number of given years """ delta = timedelta_days(days) self...
def from_dict(data, ctx): """ Instantiate a new AccountChangesState from a dict (generally from loading a JSON response). The data used to instantiate the AccountChangesState is a shallow copy of the dict passed in, with any complex child types instantiated appropriately. ...
Instantiate a new AccountChangesState from a dict (generally from loading a JSON response). The data used to instantiate the AccountChangesState is a shallow copy of the dict passed in, with any complex child types instantiated appropriately.
Below is the the instruction that describes the task: ### Input: Instantiate a new AccountChangesState from a dict (generally from loading a JSON response). The data used to instantiate the AccountChangesState is a shallow copy of the dict passed in, with any complex child types instantiated...
def _run_web_container(self, port, command, address, log_syslog=False, datapusher=True, interactive=False): """ Start web container on port with command """ if is_boot2docker(): ro = {} volumes_from = self._get_container_name('venv') ...
Start web container on port with command
Below is the the instruction that describes the task: ### Input: Start web container on port with command ### Response: def _run_web_container(self, port, command, address, log_syslog=False, datapusher=True, interactive=False): """ Start web container on port with command...
def ensure_dir(self, *path_parts): """Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory. """ path = self.getpath(*path_parts) ensure_directory(path) ...
Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory.
Below is the the instruction that describes the task: ### Input: Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory. ### Response: def ensure_dir(self, *path_parts): """Ensu...
def position_target_global_int_encode(self, time_boot_ms, coordinate_frame, type_mask, lat_int, lon_int, alt, vx, vy, vz, afx, afy, afz, yaw, yaw_rate): ''' Reports the current commanded vehicle position, velocity, and acceleration as specified by the autopilot. This ...
Reports the current commanded vehicle position, velocity, and acceleration as specified by the autopilot. This should match the commands sent in SET_POSITION_TARGET_GLOBAL_INT if the vehicle is being controlled this way. time_boot_ms ...
Below is the the instruction that describes the task: ### Input: Reports the current commanded vehicle position, velocity, and acceleration as specified by the autopilot. This should match the commands sent in SET_POSITION_TARGET_GLOBAL_INT if the vehicle is being ...
def inception_v3(pretrained=False, **kwargs): r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_. .. note:: **Important**: In contrast to the other models the inception_v3 expects tensors with a size of N...
r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_. .. note:: **Important**: In contrast to the other models the inception_v3 expects tensors with a size of N x 3 x 299 x 299, so ensure your images are sized ...
Below is the the instruction that describes the task: ### Input: r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_. .. note:: **Important**: In contrast to the other models the inception_v3 expects tensors with ...
def get_load_balancer(self, id): """ Returns a Load Balancer object by its ID. Args: id (str): Load Balancer ID """ return LoadBalancer.get_object(api_token=self.token, id=id)
Returns a Load Balancer object by its ID. Args: id (str): Load Balancer ID
Below is the the instruction that describes the task: ### Input: Returns a Load Balancer object by its ID. Args: id (str): Load Balancer ID ### Response: def get_load_balancer(self, id): """ Returns a Load Balancer object by its ID. Args: ...
def enable_audit_device(self, device_type, description=None, options=None, path=None): """Enable a new audit device at the supplied path. The path can be a single word name or a more complex, nested path. Supported methods: PUT: /sys/audit/{path}. Produces: 204 (empty body) ...
Enable a new audit device at the supplied path. The path can be a single word name or a more complex, nested path. Supported methods: PUT: /sys/audit/{path}. Produces: 204 (empty body) :param device_type: Specifies the type of the audit device. :type device_type: str | uni...
Below is the the instruction that describes the task: ### Input: Enable a new audit device at the supplied path. The path can be a single word name or a more complex, nested path. Supported methods: PUT: /sys/audit/{path}. Produces: 204 (empty body) :param device_type: Specifi...
def sort_ranges(inranges): """from an array of ranges, make a sorted array of ranges :param inranges: List of GenomicRange data :type inranges: GenomicRange[] :returns: a new sorted GenomicRange list :rtype: GenomicRange[] """ return sorted(inranges,key=lambda x: (x.chr,x.start,x.end,x.direction))
from an array of ranges, make a sorted array of ranges :param inranges: List of GenomicRange data :type inranges: GenomicRange[] :returns: a new sorted GenomicRange list :rtype: GenomicRange[]
Below is the the instruction that describes the task: ### Input: from an array of ranges, make a sorted array of ranges :param inranges: List of GenomicRange data :type inranges: GenomicRange[] :returns: a new sorted GenomicRange list :rtype: GenomicRange[] ### Response: def sort_ranges(inranges): """fr...
def main(cls): """Main entry point of Laniakea. """ args = cls.parse_args() if args.focus: Focus.init() else: Focus.disable() logging.basicConfig(format='[Laniakea] %(asctime)s %(levelname)s: %(message)s', level=args.v...
Main entry point of Laniakea.
Below is the the instruction that describes the task: ### Input: Main entry point of Laniakea. ### Response: def main(cls): """Main entry point of Laniakea. """ args = cls.parse_args() if args.focus: Focus.init() else: Focus.disable() loggin...
def process(self, context, internal_response): """ Manage consent and attribute filtering :type context: satosa.context.Context :type internal_response: satosa.internal.InternalData :rtype: satosa.response.Response :param context: response context :param interna...
Manage consent and attribute filtering :type context: satosa.context.Context :type internal_response: satosa.internal.InternalData :rtype: satosa.response.Response :param context: response context :param internal_response: the response :return: response
Below is the the instruction that describes the task: ### Input: Manage consent and attribute filtering :type context: satosa.context.Context :type internal_response: satosa.internal.InternalData :rtype: satosa.response.Response :param context: response context :param inter...
def gtr(self, value): """ Set a new GTR object Parameters ----------- value : GTR the new GTR object """ if not (isinstance(value, GTR) or isinstance(value, GTR_site_specific)): raise TypeError(" GTR instance expected") self._gtr...
Set a new GTR object Parameters ----------- value : GTR the new GTR object
Below is the the instruction that describes the task: ### Input: Set a new GTR object Parameters ----------- value : GTR the new GTR object ### Response: def gtr(self, value): """ Set a new GTR object Parameters ----------- value : G...
def send_eth_to(self, private_key: str, to: str, gas_price: int, value: int, gas: int=22000, retry: bool = False, block_identifier=None, max_eth_to_send: int = 0) -> bytes: """ Send ether using configured account :param to: to :param gas_price: gas_price :para...
Send ether using configured account :param to: to :param gas_price: gas_price :param value: value(wei) :param gas: gas, defaults to 22000 :param retry: Retry if a problem is found :param block_identifier: None default, 'pending' not confirmed txs :return: tx_hash
Below is the the instruction that describes the task: ### Input: Send ether using configured account :param to: to :param gas_price: gas_price :param value: value(wei) :param gas: gas, defaults to 22000 :param retry: Retry if a problem is found :param block_identifier...
def in_unit_of(self, unit, as_quantity=False): """ Return the current value transformed to the new units :param unit: either an astropy.Unit instance, or a string which can be converted to an astropy.Unit instance, like "1 / (erg cm**2 s)" :param as_quantity: if True, the me...
Return the current value transformed to the new units :param unit: either an astropy.Unit instance, or a string which can be converted to an astropy.Unit instance, like "1 / (erg cm**2 s)" :param as_quantity: if True, the method return an astropy.Quantity, if False just a floating point num...
Below is the the instruction that describes the task: ### Input: Return the current value transformed to the new units :param unit: either an astropy.Unit instance, or a string which can be converted to an astropy.Unit instance, like "1 / (erg cm**2 s)" :param as_quantity: if True, the ...
def serializeTransform(transformObj): """ Reserializes the transform data with some cleanups. """ return ' '.join([command + '(' + ' '.join([scourUnitlessLength(number) for number in numbers]) + ')' for command, numbers in transformObj])
Reserializes the transform data with some cleanups.
Below is the the instruction that describes the task: ### Input: Reserializes the transform data with some cleanups. ### Response: def serializeTransform(transformObj): """ Reserializes the transform data with some cleanups. """ return ' '.join([command + '(' + ' '.join([scourUnitlessLength(numb...
def department_update(self, department_id, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/departments#update-department-by-id" api_path = "/api/v2/departments/{department_id}" api_path = api_path.format(department_id=department_id) return self.call(api_path, method="P...
https://developer.zendesk.com/rest_api/docs/chat/departments#update-department-by-id
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/chat/departments#update-department-by-id ### Response: def department_update(self, department_id, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/departments#update-department-by-...
def _mine_flush(self, load, skip_verify=False): ''' Allow the minion to delete all of its own mine contents ''' if not skip_verify and 'id' not in load: return False if self.opts.get('minion_data_cache', False) or self.opts.get('enforce_mine_cache', False): ...
Allow the minion to delete all of its own mine contents
Below is the the instruction that describes the task: ### Input: Allow the minion to delete all of its own mine contents ### Response: def _mine_flush(self, load, skip_verify=False): ''' Allow the minion to delete all of its own mine contents ''' if not skip_verify and 'id' not in l...
def validate(self, dct): """ Choose a schema for client request operation and validate the operation field. If the schema is not found skips validation. :param dct: an operation field from client request :return: raises exception if invalid request """ if not isin...
Choose a schema for client request operation and validate the operation field. If the schema is not found skips validation. :param dct: an operation field from client request :return: raises exception if invalid request
Below is the the instruction that describes the task: ### Input: Choose a schema for client request operation and validate the operation field. If the schema is not found skips validation. :param dct: an operation field from client request :return: raises exception if invalid request ### Res...
def outLineReceived(self, line): """ Handle data via stdout linewise. This is useful if you turned off buffering. In your subclass, override this if you want to handle the line as a protocol line in addition to logging it. (You may upcall this function safely.) "...
Handle data via stdout linewise. This is useful if you turned off buffering. In your subclass, override this if you want to handle the line as a protocol line in addition to logging it. (You may upcall this function safely.)
Below is the the instruction that describes the task: ### Input: Handle data via stdout linewise. This is useful if you turned off buffering. In your subclass, override this if you want to handle the line as a protocol line in addition to logging it. (You may upcall this function sa...
def validate_authentication(self, username, password, handler): """authenticate user with password """ user = authenticate( **{self.username_field: username, 'password': password} ) account = self.get_account(username) if not (user and account): ra...
authenticate user with password
Below is the the instruction that describes the task: ### Input: authenticate user with password ### Response: def validate_authentication(self, username, password, handler): """authenticate user with password """ user = authenticate( **{self.username_field: username, 'password'...
def get_patient_expression(job, patient_dict): """ Convenience function to get the expression from the patient dict :param dict patient_dict: dict of patient info :return: The gene and isoform expression :rtype: toil.fileStore.FileID """ expression_archive = job.fileStore.readGlobalFile(pat...
Convenience function to get the expression from the patient dict :param dict patient_dict: dict of patient info :return: The gene and isoform expression :rtype: toil.fileStore.FileID
Below is the the instruction that describes the task: ### Input: Convenience function to get the expression from the patient dict :param dict patient_dict: dict of patient info :return: The gene and isoform expression :rtype: toil.fileStore.FileID ### Response: def get_patient_expression(job, patient_...
def run(self, cmd, timeout=None, key=None): """ Run a command on the phablet device using ssh :param cmd: a list of strings to execute as a command :param timeout: a timeout (in seconds) for device discovery :param key: a path to a public ssh ...
Run a command on the phablet device using ssh :param cmd: a list of strings to execute as a command :param timeout: a timeout (in seconds) for device discovery :param key: a path to a public ssh key to use for connection :returns: the exit...
Below is the the instruction that describes the task: ### Input: Run a command on the phablet device using ssh :param cmd: a list of strings to execute as a command :param timeout: a timeout (in seconds) for device discovery :param key: a path to a public...
def result(self, psd_state): """Return freqs and averaged PSD for given center frequency""" freq_array = numpy.fft.fftshift(psd_state['freq_array']) pwr_array = numpy.fft.fftshift(psd_state['pwr_array']) if self._crop_factor: crop_bins_half = round((self._crop_factor * self....
Return freqs and averaged PSD for given center frequency
Below is the the instruction that describes the task: ### Input: Return freqs and averaged PSD for given center frequency ### Response: def result(self, psd_state): """Return freqs and averaged PSD for given center frequency""" freq_array = numpy.fft.fftshift(psd_state['freq_array']) pwr_ar...
def validate(self): """ method starts validation of the tree. @see TreeNode.validate """ for timeperiod, child in self.root.children.items(): child.validate() self.validation_timestamp = datetime.utcnow()
method starts validation of the tree. @see TreeNode.validate
Below is the the instruction that describes the task: ### Input: method starts validation of the tree. @see TreeNode.validate ### Response: def validate(self): """ method starts validation of the tree. @see TreeNode.validate """ for timeperiod, child in self.root.children.it...
def mismatches(s1, s2, context=0, eq=operator.eq): '''extract mismatched segments from aligned strings >>> list(mismatches(*align('pharmacy', 'farmácia'), context=1)) [('pha', ' fa'), ('mac', 'mác'), ('c y', 'cia')] >>> list(mismatches(*align('constitution', 'constituição'), context=1)) [('ution',...
extract mismatched segments from aligned strings >>> list(mismatches(*align('pharmacy', 'farmácia'), context=1)) [('pha', ' fa'), ('mac', 'mác'), ('c y', 'cia')] >>> list(mismatches(*align('constitution', 'constituição'), context=1)) [('ution', 'uição')] >>> list(mismatches(*align('idea', 'ideia'...
Below is the the instruction that describes the task: ### Input: extract mismatched segments from aligned strings >>> list(mismatches(*align('pharmacy', 'farmácia'), context=1)) [('pha', ' fa'), ('mac', 'mác'), ('c y', 'cia')] >>> list(mismatches(*align('constitution', 'constituição'), context=1)) ...
def inferMainPropertyType(uriref): """ Attempt to reduce the property types to 4 main types (without the OWL ontology - which would be the propert way) In [3]: for x in g.all_properties: ...: print x.rdftype ...: http://www.w3.org/2002/07/owl#FunctionalProperty http://www.w3.org/...
Attempt to reduce the property types to 4 main types (without the OWL ontology - which would be the propert way) In [3]: for x in g.all_properties: ...: print x.rdftype ...: http://www.w3.org/2002/07/owl#FunctionalProperty http://www.w3.org/2002/07/owl#FunctionalProperty http://www.w...
Below is the the instruction that describes the task: ### Input: Attempt to reduce the property types to 4 main types (without the OWL ontology - which would be the propert way) In [3]: for x in g.all_properties: ...: print x.rdftype ...: http://www.w3.org/2002/07/owl#FunctionalProperty ...
def expose(dists): """Exposes vendored code in isolated chroots. Any vendored distributions listed in ``dists`` will be unpacked to individual chroots for addition to the ``sys.path``; ie: ``expose(['setuptools', 'wheel'])`` will unpack these vendored distributions and yield the two chroot paths they were unpa...
Exposes vendored code in isolated chroots. Any vendored distributions listed in ``dists`` will be unpacked to individual chroots for addition to the ``sys.path``; ie: ``expose(['setuptools', 'wheel'])`` will unpack these vendored distributions and yield the two chroot paths they were unpacked to. :param dists...
Below is the the instruction that describes the task: ### Input: Exposes vendored code in isolated chroots. Any vendored distributions listed in ``dists`` will be unpacked to individual chroots for addition to the ``sys.path``; ie: ``expose(['setuptools', 'wheel'])`` will unpack these vendored distributions ...
def _should_fetch_reason_with_robots(self, request: Request) -> Tuple[bool, str]: '''Return info whether the URL should be fetched including checking robots.txt. Coroutine. ''' result = yield from \ self._fetch_rule.check_initial_web_request(self._item_session, reque...
Return info whether the URL should be fetched including checking robots.txt. Coroutine.
Below is the the instruction that describes the task: ### Input: Return info whether the URL should be fetched including checking robots.txt. Coroutine. ### Response: def _should_fetch_reason_with_robots(self, request: Request) -> Tuple[bool, str]: '''Return info whether the URL should be ...