_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q255300 | _f_gene | validation | def _f_gene(sid, prefix="G_"):
"""Clips gene prefix | python | {
"resource": ""
} |
q255301 | read_sbml_model | validation | def read_sbml_model(filename, number=float, f_replace=F_REPLACE,
set_missing_bounds=False, **kwargs):
"""Reads SBML model from given filename.
If the given filename ends with the suffix ''.gz'' (for example,
''myfile.xml.gz'),' the file is assumed to be compressed in gzip
format and will be automatically decompressed upon reading. Similarly,
if the given filename ends with ''.zip'' or ''.bz2',' the file is
assumed to be compressed in zip or bzip2 format (respectively). Files
whose names lack these suffixes will be read uncompressed. Note that
if the file is in zip format but the archive contains more than one
file, only the first file in the archive will be read and the rest
ignored.
To read a gzip/zip file, libSBML needs to be configured and linked
with the zlib library at compile time. It also needs to be linked
with the bzip2 library to read files in bzip2 format. (Both of these
are the default configurations for libSBML.)
This function supports SBML with FBC-v1 and FBC-v2. FBC-v1 models
are converted to FBC-v2 models before reading.
The parser tries to fall back to information in notes dictionaries
if information is not available in the FBC packages, e.g.,
CHARGE, FORMULA on species, or GENE_ASSOCIATION, SUBSYSTEM on reactions.
Parameters
----------
| python | {
"resource": ""
} |
q255302 | _get_doc_from_filename | validation | def _get_doc_from_filename(filename):
"""Get SBMLDocument from given filename.
Parameters
----------
filename : path to SBML, or SBML string, or filehandle
Returns
-------
libsbml.SBMLDocument
"""
if isinstance(filename, string_types):
if ("win" in platform) and (len(filename) < 260) \
and os.path.exists(filename):
# path (win)
doc = libsbml.readSBMLFromFile(filename) # noqa: E501 type: libsbml.SBMLDocument
elif ("win" not in platform) and os.path.exists(filename):
# path other
doc = libsbml.readSBMLFromFile(filename) # noqa: E501 type: libsbml.SBMLDocument
else:
# string representation
if "<sbml" not in filename:
raise IOError("The file with 'filename' does not exist, "
"or is not an SBML string. Provide the path to "
"an existing SBML | python | {
"resource": ""
} |
q255303 | write_sbml_model | validation | def write_sbml_model(cobra_model, filename, f_replace=F_REPLACE, **kwargs):
"""Writes cobra model to filename.
The created model is SBML level 3 version 1 (L1V3) with
fbc package v2 (fbc-v2).
If the given filename ends with the suffix ".gz" (for example,
"myfile.xml.gz"), libSBML assumes the caller wants the file to be
written compressed in gzip format. Similarly, if the given filename
ends with ".zip" or ".bz2", libSBML assumes the caller wants the
file to be compressed in zip or bzip2 format (respectively). Files
whose names lack these suffixes will be written uncompressed. Special
considerations for the zip format: If the given filename ends with
".zip", the file placed in the zip archive will have the suffix
".xml" or ".sbml". For example, the file in the zip archive will
be named "test.xml" if the given filename is "test.xml.zip" or
"test.zip". Similarly, the filename in the archive will be
"test.sbml" if the given filename is | python | {
"resource": ""
} |
q255304 | _create_bound | validation | def _create_bound(model, reaction, bound_type, f_replace, units=None,
flux_udef=None):
"""Creates bound in model for given reaction.
Adds the parameters for the bounds to the SBML model.
Parameters
----------
model : libsbml.Model
SBML model instance
reaction : cobra.core.Reaction
Cobra reaction instance from which the bounds are read.
bound_type : {LOWER_BOUND, UPPER_BOUND}
Type of bound
f_replace : dict of id replacement functions
units : flux units
Returns
-------
Id of bound parameter.
"""
value = getattr(reaction, bound_type)
if value == config.lower_bound:
return LOWER_BOUND_ID
elif value == 0:
return ZERO_BOUND_ID
| python | {
"resource": ""
} |
q255305 | _create_parameter | validation | def _create_parameter(model, pid, value, sbo=None, constant=True, units=None,
flux_udef=None):
"""Create parameter in SBML model."""
parameter = model.createParameter() # type: libsbml.Parameter
parameter.setId(pid)
parameter.setValue(value)
| python | {
"resource": ""
} |
q255306 | _check_required | validation | def _check_required(sbase, value, attribute):
"""Get required attribute from SBase.
Parameters
----------
sbase : libsbml.SBase
value : existing value
attribute: name of attribute
Returns
-------
attribute value (or value if already set)
"""
if (value is None) or (value == ""):
msg = "Required attribute '%s' cannot be found or parsed in '%s'" % \
(attribute, sbase)
if hasattr(sbase, "getId") and sbase.getId():
msg += " with id '%s'" % sbase.getId()
| python | {
"resource": ""
} |
q255307 | _check | validation | def _check(value, message):
"""
Checks the libsbml return value and logs error messages.
If 'value' is None, logs an error message constructed using
'message' and then exits with status code 1. If 'value' is an integer,
it assumes it is a libSBML return status code. If the code value is
LIBSBML_OPERATION_SUCCESS, returns without further action; if it is not,
prints an error message constructed using 'message' along with text from
libSBML explaining the meaning of the code, and exits with status code 1.
"""
if value is None:
LOGGER.error('Error: LibSBML returned a null value trying '
| python | {
"resource": ""
} |
q255308 | _parse_notes_dict | validation | def _parse_notes_dict(sbase):
""" Creates dictionary of COBRA notes.
Parameters
----------
sbase : libsbml.SBase
Returns
-------
dict of notes
"""
notes = sbase.getNotesString()
| python | {
"resource": ""
} |
q255309 | _sbase_notes_dict | validation | def _sbase_notes_dict(sbase, notes):
"""Set SBase notes based on dictionary.
Parameters
----------
sbase : libsbml.SBase
SBML object to set notes on
notes : notes object
notes information from cobra object
"""
if notes and len(notes) > 0:
tokens = ['<html xmlns = "http://www.w3.org/1999/xhtml" >'] + \
| python | {
"resource": ""
} |
q255310 | _parse_annotations | validation | def _parse_annotations(sbase):
"""Parses cobra annotations from a given SBase object.
Annotations are dictionaries with the providers as keys.
Parameters
----------
sbase : libsbml.SBase
SBase from which the SBML annotations are read
Returns
-------
dict (annotation dictionary)
FIXME: annotation format must be updated (this is a big collection of
fixes) - see: https://github.com/opencobra/cobrapy/issues/684)
"""
annotation = {}
# SBO term
if sbase.isSetSBOTerm():
# FIXME: correct handling of annotations
annotation["sbo"] = sbase.getSBOTermID()
# RDF annotation
cvterms = sbase.getCVTerms()
if cvterms is None:
return annotation
for cvterm in cvterms: # type: libsbml.CVTerm
for k in range(cvterm.getNumResources()):
# FIXME: read and store the qualifier
uri = cvterm.getResourceURI(k)
match = URL_IDENTIFIERS_PATTERN.match(uri)
if not match:
LOGGER.warning("%s does not conform to "
| python | {
"resource": ""
} |
q255311 | _sbase_annotations | validation | def _sbase_annotations(sbase, annotation):
"""Set SBase annotations based on cobra annotations.
Parameters
----------
sbase : libsbml.SBase
SBML object to annotate
annotation : cobra annotation structure
cobra object with annotation information
FIXME: annotation format must be updated
(https://github.com/opencobra/cobrapy/issues/684)
"""
if not annotation or len(annotation) == 0:
return
# standardize annotations
annotation_data = deepcopy(annotation)
for key, value in annotation_data.items():
# handling of non-string annotations (e.g. integers)
if isinstance(value, (float, int)):
value = str(value)
if isinstance(value, string_types):
annotation_data[key] = [("is", value)]
for key, value in annotation_data.items():
for idx, item in enumerate(value):
if isinstance(item, string_types):
value[idx] = ("is", item)
# set metaId
meta_id = "meta_{}".format(sbase.getId())
sbase.setMetaId(meta_id)
# rdf_items = []
for provider, data in iteritems(annotation_data):
# set SBOTerm
if provider in ["SBO", "sbo"]:
if provider == "SBO":
LOGGER.warning("'SBO' provider is deprecated, "
"use 'sbo' provider instead")
sbo_term = data[0][1]
_check(sbase.setSBOTerm(sbo_term),
"Setting SBOTerm: {}".format(sbo_term))
# FIXME: sbo should also be written as CVTerm
continue
for item in data:
qualifier_str, entity = item[0], item[1]
qualifier = QUALIFIER_TYPES.get(qualifier_str, None)
if qualifier is None:
qualifier = libsbml.BQB_IS
LOGGER.error("Qualifier type is not supported on "
| python | {
"resource": ""
} |
q255312 | _error_string | validation | def _error_string(error, k=None):
"""String representation of SBMLError.
Parameters
----------
error : libsbml.SBMLError
k : index of error
Returns
-------
string representation of error
"""
package = error.getPackage()
| python | {
"resource": ""
} |
q255313 | production_envelope | validation | def production_envelope(model, reactions, objective=None, carbon_sources=None,
points=20, threshold=None):
"""Calculate the objective value conditioned on all combinations of
fluxes for a set of chosen reactions
The production envelope can be used to analyze a model's ability to
produce a given compound conditional on the fluxes for another set of
reactions, such as the uptake rates. The model is alternately optimized
with respect to minimizing and maximizing the objective and the
obtained fluxes are recorded. Ranges to compute production is set to the
effective
bounds, i.e., the minimum / maximum fluxes that can be obtained given
current reaction bounds.
Parameters
----------
model : cobra.Model
The model to compute the production envelope for.
reactions : list or string
A list of reactions, reaction identifiers or a single reaction.
objective : string, dict, model.solver.interface.Objective, optional
The objective (reaction) to use for the production envelope. Use the
model's current objective if left missing.
carbon_sources : list or string, optional
One or more reactions or reaction identifiers that are the source of
carbon for computing carbon (mol carbon in output over mol carbon in
input) and mass yield (gram product over gram output). Only objectives
with a carbon containing input and output metabolite is supported.
Will identify active carbon sources in the medium if none are specified.
points : int, optional
The number of points to calculate production for.
threshold : float, optional
A cut-off under which flux values will be considered to be zero
(default model.tolerance).
Returns
-------
pandas.DataFrame
A data frame with one row per evaluated point and
- reaction id : one column per input reaction indicating the flux at
each given point,
- carbon_source: identifiers of carbon exchange reactions
A column for the maximum and minimum each for the following types:
- flux: the objective flux
- carbon_yield: if carbon source is defined and the product is a
single metabolite (mol carbon product per mol carbon feeding source)
- mass_yield: if carbon source is defined and the product is a
single metabolite (gram product per 1 g of feeding source)
Examples
--------
>>> import cobra.test
>>> from cobra.flux_analysis import production_envelope
>>> model = cobra.test.create_test_model("textbook")
>>> production_envelope(model, ["EX_glc__D_e", "EX_o2_e"])
"""
reactions = model.reactions.get_by_any(reactions)
objective = model.solver.objective if objective is None else objective
data = dict()
if carbon_sources is None:
c_input = find_carbon_sources(model)
else:
| python | {
"resource": ""
} |
q255314 | total_yield | validation | def total_yield(input_fluxes, input_elements, output_flux, output_elements):
"""
Compute total output per input unit.
Units are typically mol carbon atoms or gram of source and product.
Parameters
----------
input_fluxes : list
A list of input reaction fluxes in the same order as the
``input_components``.
input_elements : list
A list of reaction components which are in turn list of numbers.
output_flux : float
The output flux value.
output_elements : list
A list of stoichiometrically weighted output reaction components.
Returns
-------
float
The ratio between output (mol carbon atoms or grams of product) and
| python | {
"resource": ""
} |
q255315 | reaction_elements | validation | def reaction_elements(reaction):
"""
Split metabolites into the atoms times their stoichiometric coefficients.
Parameters
----------
reaction : Reaction
The metabolic reaction whose components are desired.
Returns
-------
list
Each of the reaction's metabolites' desired carbon elements (if any)
| python | {
"resource": ""
} |
q255316 | reaction_weight | validation | def reaction_weight(reaction):
"""Return the metabolite weight times its stoichiometric coefficient."""
if len(reaction.metabolites) != 1:
raise ValueError('Reaction weight is only defined for single '
| python | {
"resource": ""
} |
q255317 | total_components_flux | validation | def total_components_flux(flux, components, consumption=True):
"""
Compute the total components consumption or production flux.
Parameters
----------
flux : float
The reaction flux for the components.
components : list
List of stoichiometrically weighted components.
consumption : bool, optional
| python | {
"resource": ""
} |
q255318 | find_carbon_sources | validation | def find_carbon_sources(model):
"""
Find all active carbon source reactions.
Parameters
----------
model : Model
A genome-scale metabolic model.
Returns
-------
list
The medium reactions with carbon input flux.
"""
try:
model.slim_optimize(error_value=None)
except OptimizationError:
return []
reactions = | python | {
"resource": ""
} |
q255319 | assess | validation | def assess(model, reaction, flux_coefficient_cutoff=0.001, solver=None):
"""Assesses production capacity.
Assesses the capacity of the model to produce the precursors for the
reaction and absorb the production of the reaction while the reaction is
operating at, or above, the specified cutoff.
Parameters
----------
model : cobra.Model
The cobra model to assess production capacity for
reaction : reaction identifier or cobra.Reaction
The reaction to assess
flux_coefficient_cutoff : float
The minimum flux that reaction must carry to be considered active.
solver : basestring
Solver name. If None, the default solver will be used.
Returns
-------
bool or dict
True if the model can produce the precursors and absorb the products
for the reaction operating at, or above, flux_coefficient_cutoff.
| python | {
"resource": ""
} |
q255320 | assess_component | validation | def assess_component(model, reaction, side, flux_coefficient_cutoff=0.001,
solver=None):
"""Assesses the ability of the model to provide sufficient precursors,
or absorb products, for a reaction operating at, or beyond,
the specified cutoff.
Parameters
----------
model : cobra.Model
The cobra model to assess production capacity for
reaction : reaction identifier or cobra.Reaction
The reaction to assess
side : basestring
Side of the reaction, 'products' or 'reactants'
flux_coefficient_cutoff : float
The minimum flux that reaction must carry to be considered active.
solver : basestring
Solver name. If None, the default solver will be used.
Returns
-------
bool or dict
True if the precursors can be simultaneously produced at the
specified cutoff. False, if the model has the capacity to produce
each individual precursor at the specified threshold but not all
precursors at the required level simultaneously. Otherwise a
dictionary of the required and the produced fluxes for each reactant
that is not produced in sufficient quantities.
"""
reaction = model.reactions.get_by_any(reaction)[0]
result_key = dict(reactants='produced', products='capacity')[side]
get_components = attrgetter(side)
with model as m: | python | {
"resource": ""
} |
q255321 | assess_precursors | validation | def assess_precursors(model, reaction, flux_coefficient_cutoff=0.001,
solver=None):
"""Assesses the ability of the model to provide sufficient precursors for
a reaction operating at, or beyond, the specified cutoff.
Deprecated: use assess_component instead
Parameters
----------
model : cobra.Model
The cobra model to assess production capacity for
reaction : reaction identifier or cobra.Reaction
The reaction to assess
flux_coefficient_cutoff : float
The minimum flux that reaction must carry to be considered active.
solver : basestring
Solver name. If None, the default solver will be used.
Returns
-------
bool or dict
True if the precursors can be simultaneously produced at the | python | {
"resource": ""
} |
q255322 | assess_products | validation | def assess_products(model, reaction, flux_coefficient_cutoff=0.001,
solver=None):
"""Assesses whether the model has the capacity to absorb the products of
a reaction at a given flux rate.
Useful for identifying which components might be blocking a reaction
from achieving a specific flux rate.
Deprecated: use assess_component instead
Parameters
----------
model : cobra.Model
The cobra model to assess production capacity for
reaction : reaction identifier or cobra.Reaction
The reaction to assess
flux_coefficient_cutoff : float
The minimum flux that reaction must carry to be considered active.
solver : basestring
Solver name. If None, the default solver will be used.
Returns
-------
bool or dict
| python | {
"resource": ""
} |
q255323 | add_loopless | validation | def add_loopless(model, zero_cutoff=None):
"""Modify a model so all feasible flux distributions are loopless.
In most cases you probably want to use the much faster `loopless_solution`.
May be used in cases where you want to add complex constraints and
objecives (for instance quadratic objectives) to the model afterwards
or use an approximation of Gibbs free energy directions in you model.
Adds variables and constraints to a model which will disallow flux
distributions with loops. The used formulation is described in [1]_.
This function *will* modify your model.
Parameters
----------
model : cobra.Model
The model to which to add the constraints.
zero_cutoff : positive float, optional
Cutoff used for null space. Coefficients with an absolute value smaller
than `zero_cutoff` are considered to be zero (default model.tolerance).
Returns
-------
Nothing
References
----------
.. [1] Elimination of thermodynamically infeasible loops in steady-state
metabolic models. Schellenberger J, Lewis NE, Palsson BO. Biophys J.
2011 Feb 2;100(3):544-53. doi: 10.1016/j.bpj.2010.12.3707. Erratum
in: Biophys J. 2011 Mar 2;100(5):1381.
"""
zero_cutoff = normalize_cutoff(model, zero_cutoff)
internal = [i for i, r in enumerate(model.reactions) if not r.boundary]
s_int = create_stoichiometric_matrix(model)[:, numpy.array(internal)]
n_int = nullspace(s_int).T
max_bound = max(max(abs(b) for b in r.bounds) for r in model.reactions)
prob = model.problem
# Add indicator variables and new constraints
to_add = []
for i in internal:
rxn = model.reactions[i]
# indicator variable a_i
indicator = prob.Variable("indicator_" + rxn.id, type="binary")
| python | {
"resource": ""
} |
q255324 | _add_cycle_free | validation | def _add_cycle_free(model, fluxes):
"""Add constraints for CycleFreeFlux."""
model.objective = model.solver.interface.Objective(
Zero, direction="min", sloppy=True)
objective_vars = []
for rxn in model.reactions:
flux = fluxes[rxn.id]
if rxn.boundary:
rxn.bounds = (flux, flux)
continue
if flux >= 0:
rxn.bounds = max(0, rxn.lower_bound), max(flux, rxn.upper_bound)
objective_vars.append(rxn.forward_variable)
| python | {
"resource": ""
} |
q255325 | loopless_solution | validation | def loopless_solution(model, fluxes=None):
"""Convert an existing solution to a loopless one.
Removes as many loops as possible (see Notes).
Uses the method from CycleFreeFlux [1]_ and is much faster than
`add_loopless` and should therefore be the preferred option to get loopless
flux distributions.
Parameters
----------
model : cobra.Model
The model to which to add the constraints.
fluxes : dict
A dictionary {rxn_id: flux} that assigns a flux to each reaction. If
not None will use the provided flux values to obtain a close loopless
solution.
Returns
-------
cobra.Solution
A solution object containing the fluxes with the least amount of
loops possible or None if the optimization failed (usually happening
if the flux distribution in `fluxes` is infeasible).
Notes
-----
The returned flux solution has the following properties:
- it contains the minimal number of loops possible and no loops at all if
all flux bounds include zero
- it has an objective value close to the original one and the same
objective value id the objective expression can not form a cycle
(which is usually true since it consumes metabolites)
- it has the same exact exchange fluxes as the previous solution
- all fluxes have the same sign (flow in the same direction) as the
previous solution
References
----------
.. [1] CycleFreeFlux: efficient removal of thermodynamically infeasible
loops from flux | python | {
"resource": ""
} |
q255326 | loopless_fva_iter | validation | def loopless_fva_iter(model, reaction, solution=False, zero_cutoff=None):
"""Plugin to get a loopless FVA solution from single FVA iteration.
Assumes the following about `model` and `reaction`:
1. the model objective is set to be `reaction`
2. the model has been optimized and contains the minimum/maximum flux for
`reaction`
3. the model contains an auxiliary variable called "fva_old_objective"
denoting the previous objective
Parameters
----------
model : cobra.Model
The model to be used.
reaction : cobra.Reaction
The reaction currently minimized/maximized.
solution : boolean, optional
Whether to return the entire solution or only the minimum/maximum for
`reaction`.
zero_cutoff : positive float, optional
Cutoff used for loop removal. Fluxes with an absolute value smaller
than `zero_cutoff` are considered to be zero (default model.tolerance).
Returns
-------
single float or dict
Returns the minimized/maximized flux through `reaction` if
all_fluxes == False (default). Otherwise returns a loopless flux
solution containing the minimum/maximum flux for `reaction`. | python | {
"resource": ""
} |
q255327 | create_stoichiometric_matrix | validation | def create_stoichiometric_matrix(model, array_type='dense', dtype=None):
"""Return a stoichiometric array representation of the given model.
The the columns represent the reactions and rows represent
metabolites. S[i,j] therefore contains the quantity of metabolite `i`
produced (negative for consumed) by reaction `j`.
Parameters
----------
model : cobra.Model
The cobra model to construct the matrix for.
array_type : string
The type of array to construct. if 'dense', return a standard
numpy.array, 'dok', or 'lil' will construct a sparse array using
scipy of the corresponding type and 'DataFrame' will give a
pandas `DataFrame` with metabolite indices and reaction columns
dtype : data-type
The desired data-type for the array. If not given, defaults to float.
Returns
-------
matrix of class `dtype`
The stoichiometric matrix for the given model.
"""
if array_type not in ('DataFrame', 'dense') and not dok_matrix:
raise ValueError('Sparse matrices require scipy')
if dtype is None:
dtype = np.float64
array_constructor = {
'dense': np.zeros, 'dok': dok_matrix, 'lil': lil_matrix,
'DataFrame': np.zeros,
}
n_metabolites = len(model.metabolites)
n_reactions = len(model.reactions) | python | {
"resource": ""
} |
q255328 | nullspace | validation | def nullspace(A, atol=1e-13, rtol=0):
"""Compute an approximate basis for the nullspace of A.
The algorithm used by this function is based on the singular value
decomposition of `A`.
Parameters
----------
A : numpy.ndarray
A should be at most 2-D. A 1-D array with length k will be treated
as a 2-D with shape (1, k)
atol : float
The absolute tolerance for a zero singular value. Singular values
smaller than `atol` are considered to be zero.
rtol : float
The relative tolerance. Singular values less than rtol*smax are
considered to be zero, where smax is the largest singular value.
If both `atol` and `rtol` are positive, the combined tolerance is the
maximum of the two; that is::
tol = max(atol, rtol * smax)
Singular values smaller than `tol` are considered to be zero. | python | {
"resource": ""
} |
q255329 | constraint_matrices | validation | def constraint_matrices(model, array_type='dense', include_vars=False,
zero_tol=1e-6):
"""Create a matrix representation of the problem.
This is used for alternative solution approaches that do not use optlang.
The function will construct the equality matrix, inequality matrix and
bounds for the complete problem.
Notes
-----
To accomodate non-zero equalities the problem will add the variable
"const_one" which is a variable that equals one.
Arguments
---------
model : cobra.Model
The model from which to obtain the LP problem.
array_type : string
The type of array to construct. if 'dense', return a standard
numpy.array, 'dok', or 'lil' will construct a sparse array using
scipy of the corresponding type and 'DataFrame' will give a
pandas `DataFrame` with metabolite indices and reaction columns.
zero_tol : float
The zero tolerance used to judge whether two bounds are the same.
Returns
-------
collections.namedtuple
A named tuple consisting of 6 matrices and 2 vectors:
- "equalities" is a matrix S such that S*vars = b. It includes a row
for each constraint and one column for each variable.
- "b" the right side of the equality equation such that S*vars = b.
- "inequalities" is a matrix M such that lb <= M*vars <= ub.
It contains a row for each inequality and as many columns as
variables.
- "bounds" is a compound matrix [lb ub] containing the lower and
upper bounds for the inequality constraints in M.
- "variable_fixed" is a boolean vector indicating whether the variable
at that index is fixed (lower bound == upper_bound) and
is thus bounded by an equality constraint.
- "variable_bounds" is a compound matrix [lb ub] containing the
lower and upper bounds for all variables.
"""
if array_type not in ('DataFrame', 'dense') and not dok_matrix:
raise ValueError('Sparse matrices require scipy')
array_builder = {
'dense': np.array, 'dok': dok_matrix, 'lil': lil_matrix,
'DataFrame': pd.DataFrame,
}[array_type]
Problem = namedtuple("Problem",
["equalities", "b", "inequalities", "bounds",
| python | {
"resource": ""
} |
q255330 | add_room | validation | def add_room(model, solution=None, linear=False, delta=0.03, epsilon=1E-03):
r"""
Add constraints and objective for ROOM.
This function adds variables and constraints for applying regulatory
on/off minimization (ROOM) to the model.
Parameters
----------
model : cobra.Model
The model to add ROOM constraints and objective to.
solution : cobra.Solution, optional
A previous solution to use as a reference. If no solution is given,
one will be computed using pFBA.
linear : bool, optional
Whether to use the linear ROOM formulation or not (default False).
delta: float, optional
The relative tolerance range which is additive in nature
(default 0.03).
epsilon: float, optional
The absolute range of tolerance which is multiplicative
(default 0.001).
Notes
-----
The formulation used here is the same as stated in the original paper [1]_.
The mathematical expression is given below:
minimize \sum_{i=1}^m y^i
s.t. Sv = 0
v_min <= v <= v_max
v_j = 0
j ∈ A
for 1 <= i <= m
v_i - y_i(v_{max,i} - w_i^u) <= w_i^u (1)
v_i - y_i(v_{min,i} - w_i^l) <= w_i^l (2)
y_i ∈ {0,1} (3)
w_i^u = w_i + \delta|w_i| + \epsilon
w_i^l = w_i - \delta|w_i| - \epsilon
So, for the linear version of the ROOM , constraint (3) is relaxed to
0 <= y_i <= 1.
See Also
--------
pfba : parsimonious FBA
References
----------
.. [1] Tomer Shlomi, Omer Berkman and Eytan Ruppin, "Regulatory on/off
minimization of metabolic flux changes after genetic perturbations",
PNAS 2005 102 (21) 7695-7700; doi:10.1073/pnas.0406346102
"""
if 'room_old_objective' in model.solver.variables:
raise ValueError('model is already adjusted for ROOM')
| python | {
"resource": ""
} |
q255331 | sample | validation | def sample(model, n, method="optgp", thinning=100, processes=1, seed=None):
"""Sample valid flux distributions from a cobra model.
The function samples valid flux distributions from a cobra model.
Currently we support two methods:
1. 'optgp' (default) which uses the OptGPSampler that supports parallel
sampling [1]_. Requires large numbers of samples to be performant
(n < 1000). For smaller samples 'achr' might be better suited.
or
2. 'achr' which uses artificial centering hit-and-run. This is a single
process method with good convergence [2]_.
Parameters
----------
model : cobra.Model
The model from which to sample flux distributions.
n : int
The number of samples to obtain. When using 'optgp' this must be a
multiple of `processes`, otherwise a larger number of samples will be
returned.
method : str, optional
The sampling algorithm to use.
thinning : int, optional
The thinning factor of the generated sampling chain. A thinning of 10
means samples are returned every 10 steps. Defaults to 100 which in
benchmarks gives approximately uncorrelated samples. If set to one
will return all iterates.
processes : int, optional
Only used for 'optgp'. The number of processes used to generate
samples.
seed : int > 0, optional
The random number seed to be used. Initialized to current time stamp
if None.
Returns
-------
pandas.DataFrame
The generated flux samples. Each row corresponds to a sample | python | {
"resource": ""
} |
q255332 | optimizely | validation | def optimizely(parser, token):
"""
Optimizely template tag.
Renders Javascript code to set-up A/B testing. You must supply
your Optimizely account number in the ``OPTIMIZELY_ACCOUNT_NUMBER``
setting.
"""
| python | {
"resource": ""
} |
q255333 | clicky | validation | def clicky(parser, token):
"""
Clicky tracking template tag.
Renders Javascript code to track page visits. You must supply
your Clicky Site ID (as a string) in the ``CLICKY_SITE_ID``
setting.
""" | python | {
"resource": ""
} |
q255334 | chartbeat_top | validation | def chartbeat_top(parser, token):
"""
Top Chartbeat template tag.
Render the top Javascript code for Chartbeat.
"""
bits = token.split_contents()
if len(bits) | python | {
"resource": ""
} |
q255335 | chartbeat_bottom | validation | def chartbeat_bottom(parser, token):
"""
Bottom Chartbeat template tag.
Render the bottom Javascript code for Chartbeat. You must supply
your Chartbeat User ID (as a string) in the ``CHARTBEAT_USER_ID``
setting.
""" | python | {
"resource": ""
} |
q255336 | woopra | validation | def woopra(parser, token):
"""
Woopra tracking template tag.
Renders Javascript code to track page visits. You must supply
your Woopra domain in the ``WOOPRA_DOMAIN`` setting.
"""
bits = | python | {
"resource": ""
} |
q255337 | spring_metrics | validation | def spring_metrics(parser, token):
"""
Spring Metrics tracking template tag.
Renders Javascript code to track page visits. You must supply
your Spring Metrics Tracking ID in the
``SPRING_METRICS_TRACKING_ID`` setting.
"""
| python | {
"resource": ""
} |
q255338 | kiss_insights | validation | def kiss_insights(parser, token):
"""
KISSinsights set-up template tag.
Renders Javascript code to set-up surveys. You must supply
your account number and site code in the
``KISS_INSIGHTS_ACCOUNT_NUMBER`` and ``KISS_INSIGHTS_SITE_CODE``
settings.
| python | {
"resource": ""
} |
q255339 | matomo | validation | def matomo(parser, token):
"""
Matomo tracking template tag.
Renders Javascript code to track page visits. You must supply
your Matomo domain (plus optional URI path), and tracked site ID
in the ``MATOMO_DOMAIN_PATH`` and the ``MATOMO_SITE_ID`` setting.
Custom variables can be passed in the ``matomo_vars`` context
variable. It is an iterable of custom variables as tuples like:
``(index, name, value[, scope])`` where scope may be ``'page'`` | python | {
"resource": ""
} |
q255340 | snapengage | validation | def snapengage(parser, token):
"""
SnapEngage set-up template tag.
Renders Javascript code to set-up SnapEngage chat. You must supply
your widget ID in the ``SNAPENGAGE_WIDGET_ID`` setting.
"""
| python | {
"resource": ""
} |
q255341 | performable | validation | def performable(parser, token):
"""
Performable template tag.
Renders Javascript code to set-up Performable tracking. You must
supply your Performable API key in the ``PERFORMABLE_API_KEY``
setting.
"""
| python | {
"resource": ""
} |
q255342 | _hashable_bytes | validation | def _hashable_bytes(data):
"""
Coerce strings to hashable bytes.
"""
if isinstance(data, bytes):
return data
elif isinstance(data, str):
| python | {
"resource": ""
} |
q255343 | intercom_user_hash | validation | def intercom_user_hash(data):
"""
Return a SHA-256 HMAC `user_hash` as expected by Intercom, if configured.
Return None if the `INTERCOM_HMAC_SECRET_KEY` setting is not configured.
| python | {
"resource": ""
} |
q255344 | intercom | validation | def intercom(parser, token):
"""
Intercom.io template tag.
Renders Javascript code to intercom.io testing. You must supply
your APP ID account number in the ``INTERCOM_APP_ID``
setting.
"""
| python | {
"resource": ""
} |
q255345 | uservoice | validation | def uservoice(parser, token):
"""
UserVoice tracking template tag.
Renders Javascript code to track page visits. You must supply
your UserVoice Widget Key in the ``USERVOICE_WIDGET_KEY``
setting or the ``uservoice_widget_key`` template context variable.
""" | python | {
"resource": ""
} |
q255346 | kiss_metrics | validation | def kiss_metrics(parser, token):
"""
KISSinsights tracking template tag.
Renders Javascript code to track page visits. You must supply
your KISSmetrics API key in the ``KISS_METRICS_API_KEY``
setting.
"""
| python | {
"resource": ""
} |
q255347 | piwik | validation | def piwik(parser, token):
"""
Piwik tracking template tag.
Renders Javascript code to track page visits. You must supply
your Piwik domain (plus optional URI path), and tracked site ID
in the ``PIWIK_DOMAIN_PATH`` and the ``PIWIK_SITE_ID`` setting.
Custom variables can be passed in the ``piwik_vars`` context
variable. It is an iterable of custom variables as tuples like:
``(index, name, value[, scope])`` where scope may be ``'page'``
| python | {
"resource": ""
} |
q255348 | get_required_setting | validation | def get_required_setting(setting, value_re, invalid_msg):
"""
Return a constant from ``django.conf.settings``. The `setting`
argument is the constant name, the `value_re` argument is a regular
expression used to validate the setting value and the `invalid_msg`
argument is used as exception message if the value is | python | {
"resource": ""
} |
q255349 | get_user_from_context | validation | def get_user_from_context(context):
"""
Get the user instance from the template context, if possible.
If the context does not contain a `request` or `user` attribute,
`None` is returned.
"""
try:
return context['user']
except KeyError:
| python | {
"resource": ""
} |
q255350 | get_identity | validation | def get_identity(context, prefix=None, identity_func=None, user=None):
"""
Get the identity of a logged in user from a template context.
The `prefix` argument is used to provide different identities to
different analytics services. The `identity_func` argument is a
function that returns the identity of the user; by default the
identity is the username.
"""
if prefix is not None:
try:
return context['%s_identity' % prefix]
except KeyError:
pass
try:
return context['analytical_identity']
except KeyError:
pass | python | {
"resource": ""
} |
q255351 | is_internal_ip | validation | def is_internal_ip(context, prefix=None):
"""
Return whether the visitor is coming from an internal IP address,
based on information from the template context.
The prefix is used to allow different analytics services to have
different notions of internal addresses.
"""
try:
request = context['request']
remote_ip = request.META.get('HTTP_X_FORWARDED_FOR', '')
if not remote_ip:
remote_ip = request.META.get('REMOTE_ADDR', '')
if not remote_ip:
return False
internal_ips = None
| python | {
"resource": ""
} |
q255352 | mixpanel | validation | def mixpanel(parser, token):
"""
Mixpanel tracking template tag.
Renders Javascript code to track page visits. You must supply
your Mixpanel token in the ``MIXPANEL_API_TOKEN`` setting.
"""
bits = token.split_contents() | python | {
"resource": ""
} |
q255353 | gosquared | validation | def gosquared(parser, token):
"""
GoSquared tracking template tag.
Renders Javascript code to track page visits. You must supply
your GoSquared site token in the ``GOSQUARED_SITE_TOKEN`` setting.
"""
bits = | python | {
"resource": ""
} |
q255354 | olark | validation | def olark(parser, token):
"""
Olark set-up template tag.
Renders Javascript code to set-up Olark chat. You must supply
your site ID in the ``OLARK_SITE_ID`` setting.
"""
bits = | python | {
"resource": ""
} |
q255355 | clickmap | validation | def clickmap(parser, token):
"""
Clickmap tracker template tag.
Renders Javascript code to track page visits. You must supply
your clickmap tracker ID (as a string) in the ``CLICKMAP_TRACKER_ID``
setting.
""" | python | {
"resource": ""
} |
q255356 | gauges | validation | def gauges(parser, token):
"""
Gaug.es template tag.
Renders Javascript code to gaug.es testing. You must supply
your Site ID account number in the ``GAUGES_SITE_ID``
setting.
"""
| python | {
"resource": ""
} |
q255357 | crazy_egg | validation | def crazy_egg(parser, token):
"""
Crazy Egg tracking template tag.
Renders Javascript code to track page clicks. You must supply
your Crazy Egg account number (as a string) in the
``CRAZY_EGG_ACCOUNT_NUMBER`` setting.
""" | python | {
"resource": ""
} |
q255358 | yandex_metrica | validation | def yandex_metrica(parser, token):
"""
Yandex.Metrica counter template tag.
Renders Javascript code to track page visits. You must supply
your website counter ID (as a string) in the
``YANDEX_METRICA_COUNTER_ID`` setting.
""" | python | {
"resource": ""
} |
q255359 | hubspot | validation | def hubspot(parser, token):
"""
HubSpot tracking template tag.
Renders Javascript code to track page visits. You must supply
your portal ID (as a string) in the ``HUBSPOT_PORTAL_ID`` setting.
"""
| python | {
"resource": ""
} |
q255360 | status_printer | validation | def status_printer():
"""Manage the printing and in-place updating of a line of characters
.. note::
If the string is longer than a line, then in-place updating may not
work (it will print a new line at each refresh).
"""
last_len = [0]
def p(s):
s = | python | {
"resource": ""
} |
q255361 | do_apply | validation | def do_apply(mutation_pk, dict_synonyms, backup):
"""Apply a specified mutant to the source code
:param mutation_pk: mutmut cache primary key of the mutant to apply
:type mutation_pk: str
:param dict_synonyms: list of synonym keywords for a python dictionary
:type dict_synonyms: list[str]
:param backup: if :obj:`True` create a backup of the source file
before applying the mutation
:type backup: bool
"""
filename, | python | {
"resource": ""
} |
q255362 | popen_streaming_output | validation | def popen_streaming_output(cmd, callback, timeout=None):
"""Open a subprocess and stream its output without hard-blocking.
:param cmd: the command to execute within the subprocess
:type cmd: str
:param callback: function that intakes the subprocess' stdout line by line.
It is called for each line received from the subprocess' stdout stream.
:type callback: Callable[[Context], bool]
:param timeout: the timeout time of the subprocess
:type timeout: float
:raises TimeoutError: if the subprocess' execution time exceeds
the timeout time
:return: the return code of the executed subprocess
:rtype: int
"""
if os.name == 'nt': # pragma: no cover
process = subprocess.Popen(
shlex.split(cmd),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout = process.stdout
else:
master, slave = os.openpty()
process = subprocess.Popen(
shlex.split(cmd, posix=True),
stdout=slave,
stderr=slave
)
stdout = os.fdopen(master)
os.close(slave)
def kill(process_):
"""Kill the specified process on Timer completion"""
try:
process_.kill()
except OSError:
pass
# python 2-3 agnostic process timer
timer = Timer(timeout, kill, [process])
timer.setDaemon(True)
timer.start()
while process.returncode is None:
try:
if os.name == 'nt': # pragma: no cover
line = stdout.readline()
# windows gives readline() raw stdout as a b''
# need to decode it
line = line.decode("utf-8")
if line: # ignore empty strings | python | {
"resource": ""
} |
q255363 | python_source_files | validation | def python_source_files(path, tests_dirs):
"""Attempt to guess where the python source files to mutate are and yield
their paths
:param path: path to a python source file or package directory
:type path: str
:param tests_dirs: list of directory paths containing test files
(we do not want to mutate these!)
:type tests_dirs: list[str]
:return: generator listing the paths to the python source files to mutate
:rtype: Generator[str, None, None]
| python | {
"resource": ""
} |
q255364 | compute_exit_code | validation | def compute_exit_code(config, exception=None):
"""Compute an exit code for mutmut mutation testing
The following exit codes are available for mutmut:
* 0 if all mutants were killed (OK_KILLED)
* 1 if a fatal error occurred
* 2 if one or more mutants survived (BAD_SURVIVED)
* 4 if one or more mutants timed out (BAD_TIMEOUT)
* 8 if one or more mutants caused tests to take twice as long (OK_SUSPICIOUS)
Exit codes 1 to 8 will be bit-ORed so that it is possible to know what
different mutant statuses occurred during mutation testing.
:param exception:
:type exception: Exception
:param config:
:type config: Config
:return: integer noting the exit code | python | {
"resource": ""
} |
q255365 | CoreBluetoothDevice._update_advertised | validation | def _update_advertised(self, advertised):
"""Called when advertisement data is received."""
# Advertisement data was received, pull out advertised service UUIDs and
# name from advertisement data.
| python | {
"resource": ""
} |
q255366 | CoreBluetoothDevice._characteristics_discovered | validation | def _characteristics_discovered(self, service):
"""Called when GATT characteristics have been discovered."""
# Characteristics for the specified service were discovered. Update
# set of discovered services and signal when all have been discovered.
self._discovered_services.add(service)
| python | {
"resource": ""
} |
q255367 | CoreBluetoothDevice._characteristic_changed | validation | def _characteristic_changed(self, characteristic):
"""Called when the specified characteristic has changed its value."""
# Called when a characteristic is changed. Get the on_changed handler
# for this characteristic (if it exists) and call it.
on_changed = self._char_on_changed.get(characteristic, None)
if on_changed is not None:
on_changed(characteristic.value().bytes().tobytes())
| python | {
"resource": ""
} |
q255368 | CoreBluetoothDevice._descriptor_changed | validation | def _descriptor_changed(self, descriptor):
"""Called when the specified descriptor has changed its value."""
# Tell the descriptor it has a new value to | python | {
"resource": ""
} |
q255369 | CoreBluetoothDevice.rssi | validation | def rssi(self, timeout_sec=TIMEOUT_SEC):
"""Return the RSSI signal strength in decibels."""
# Kick off query to get RSSI, then wait for it to return asyncronously
# when the _rssi_changed() function is called.
self._rssi_read.clear()
self._peripheral.readRSSI()
| python | {
"resource": ""
} |
q255370 | BluezGattService.list_characteristics | validation | def list_characteristics(self):
"""Return list of GATT characteristics that have been discovered for this
service.
"""
paths | python | {
"resource": ""
} |
q255371 | BluezGattCharacteristic.list_descriptors | validation | def list_descriptors(self):
"""Return list of GATT descriptors that have been discovered for this
characteristic.
"""
paths | python | {
"resource": ""
} |
q255372 | CoreBluetoothAdapter._state_changed | validation | def _state_changed(self, state):
"""Called when the power state changes."""
logger.debug('Adapter state change: {0}'.format(state))
# Handle when powered on.
if state == 5:
self._powered_off.clear()
| python | {
"resource": ""
} |
q255373 | CoreBluetoothAdapter.start_scan | validation | def start_scan(self, timeout_sec=TIMEOUT_SEC):
"""Start scanning for BLE devices.""" | python | {
"resource": ""
} |
q255374 | CoreBluetoothAdapter.stop_scan | validation | def stop_scan(self, timeout_sec=TIMEOUT_SEC):
"""Stop scanning for BLE devices."""
| python | {
"resource": ""
} |
q255375 | CoreBluetoothAdapter.power_on | validation | def power_on(self, timeout_sec=TIMEOUT_SEC):
"""Power on Bluetooth."""
# Turn on bluetooth and wait for powered on event to be set.
self._powered_on.clear()
IOBluetoothPreferenceSetControllerPowerState(1)
| python | {
"resource": ""
} |
q255376 | CoreBluetoothAdapter.power_off | validation | def power_off(self, timeout_sec=TIMEOUT_SEC):
"""Power off Bluetooth."""
# Turn off bluetooth.
self._powered_off.clear()
IOBluetoothPreferenceSetControllerPowerState(0)
if | python | {
"resource": ""
} |
q255377 | ServiceBase.find_device | validation | def find_device(cls, timeout_sec=TIMEOUT_SEC):
"""Find the first available device that supports this service and return
it, or None | python | {
"resource": ""
} |
q255378 | ServiceBase.discover | validation | def discover(cls, device, timeout_sec=TIMEOUT_SEC):
"""Wait until the specified device has discovered the expected services
and characteristics for this service. Should be called once before other
calls are made on the service. Returns true if the service has been
| python | {
"resource": ""
} |
q255379 | Device.find_service | validation | def find_service(self, uuid):
"""Return the first child service found that has the specified
UUID. Will return None if no service that matches is found.
"""
| python | {
"resource": ""
} |
q255380 | BluezDevice.list_services | validation | def list_services(self):
"""Return a list of GattService objects that have been discovered for
this device.
"""
return map(BluezGattService,
| python | {
"resource": ""
} |
q255381 | BluezDevice.advertised | validation | def advertised(self):
"""Return a list of UUIDs for services that are advertised by this
device.
"""
uuids = []
# Get UUIDs property but wrap it in a try/except to catch if the property
# doesn't exist as it is optional.
try:
uuids = self._props.Get(_INTERFACE, 'UUIDs')
except dbus.exceptions.DBusException as | python | {
"resource": ""
} |
q255382 | GattService.find_characteristic | validation | def find_characteristic(self, uuid):
"""Return the first child characteristic found that has the specified
UUID. Will return None if no characteristic that matches is found.
""" | python | {
"resource": ""
} |
q255383 | GattCharacteristic.find_descriptor | validation | def find_descriptor(self, uuid):
"""Return the first child descriptor found that has the specified
UUID. Will return None if no descriptor that matches is found.
""" | python | {
"resource": ""
} |
q255384 | CoreBluetoothGattCharacteristic.read_value | validation | def read_value(self, timeout_sec=TIMEOUT_SEC):
"""Read the value of this characteristic."""
# Kick off a query to read the value of the characteristic, then wait
# for the result to return asyncronously.
self._value_read.clear()
| python | {
"resource": ""
} |
q255385 | CoreBluetoothGattCharacteristic.write_value | validation | def write_value(self, value, write_type=0):
"""Write the specified value to this characteristic."""
data = NSData.dataWithBytes_length_(value, len(value))
| python | {
"resource": ""
} |
q255386 | CoreBluetoothGattDescriptor.read_value | validation | def read_value(self):
"""Read the value of this descriptor."""
pass
# Kick off a query to read the value of the descriptor, then wait
# for the result to return asyncronously.
self._value_read.clear()
| python | {
"resource": ""
} |
q255387 | BluezAdapter.start_scan | validation | def start_scan(self, timeout_sec=TIMEOUT_SEC):
"""Start scanning for BLE devices with this adapter."""
self._scan_started.clear()
self._adapter.StartDiscovery()
if | python | {
"resource": ""
} |
q255388 | BluezAdapter.stop_scan | validation | def stop_scan(self, timeout_sec=TIMEOUT_SEC):
"""Stop scanning for BLE devices with this adapter."""
self._scan_stopped.clear()
self._adapter.StopDiscovery()
if | python | {
"resource": ""
} |
q255389 | CentralDelegate.centralManager_didDiscoverPeripheral_advertisementData_RSSI_ | validation | def centralManager_didDiscoverPeripheral_advertisementData_RSSI_(self, manager, peripheral, data, rssi):
"""Called when the BLE adapter found a device while scanning, or has
new advertisement data for a device.
"""
logger.debug('centralManager_didDiscoverPeripheral_advertisementData_RSSI called')
# Log name of device found while scanning.
#logger.debug('Saw device advertised with name: {0}'.format(peripheral.name()))
| python | {
"resource": ""
} |
q255390 | CentralDelegate.centralManager_didConnectPeripheral_ | validation | def centralManager_didConnectPeripheral_(self, manager, peripheral):
"""Called when a device is connected."""
logger.debug('centralManager_didConnectPeripheral called')
# Setup peripheral delegate and kick off service discovery. For now just
# assume all services need to be discovered.
peripheral.setDelegate_(self)
| python | {
"resource": ""
} |
q255391 | CentralDelegate.centralManager_didDisconnectPeripheral_error_ | validation | def centralManager_didDisconnectPeripheral_error_(self, manager, peripheral, error):
"""Called when a device is disconnected."""
logger.debug('centralManager_didDisconnectPeripheral called')
# Get the device and remove it from the device list, then fire its
# disconnected event.
device = device_list().get(peripheral)
| python | {
"resource": ""
} |
q255392 | CentralDelegate.peripheral_didDiscoverServices_ | validation | def peripheral_didDiscoverServices_(self, peripheral, services):
"""Called when services are discovered for a device."""
logger.debug('peripheral_didDiscoverServices called')
# Make sure the discovered services are added to the list of known
# services, and kick off characteristic discovery for each one.
# NOTE: For some reason the services parameter is never set to a good
# value, instead you must query peripheral.services() to enumerate the
# discovered services.
for service in peripheral.services():
if service_list().get(service) is None:
| python | {
"resource": ""
} |
q255393 | CentralDelegate.peripheral_didUpdateValueForCharacteristic_error_ | validation | def peripheral_didUpdateValueForCharacteristic_error_(self, peripheral, characteristic, error):
"""Called when characteristic value was read or updated."""
logger.debug('peripheral_didUpdateValueForCharacteristic_error called')
# Stop if there was some kind of error.
if error is not None:
| python | {
"resource": ""
} |
q255394 | CentralDelegate.peripheral_didUpdateValueForDescriptor_error_ | validation | def peripheral_didUpdateValueForDescriptor_error_(self, peripheral, descriptor, error):
"""Called when descriptor value was read or updated."""
logger.debug('peripheral_didUpdateValueForDescriptor_error called')
# Stop if there was some kind of error.
if error is not None:
| python | {
"resource": ""
} |
q255395 | CentralDelegate.peripheral_didReadRSSI_error_ | validation | def peripheral_didReadRSSI_error_(self, peripheral, rssi, error):
"""Called when a new RSSI value for the peripheral is available."""
logger.debug('peripheral_didReadRSSI_error called')
# Note this appears to be completely undocumented at the time of this
# writing. Can see more details at:
# http://stackoverflow.com/questions/25952218/ios-8-corebluetooth-deprecated-rssi-methods
# | python | {
"resource": ""
} |
q255396 | CoreBluetoothProvider.initialize | validation | def initialize(self):
"""Initialize the BLE provider. Must be called once before any other
calls are made to the provider.
"""
# Setup the central manager and its delegate.
self._central_manager = CBCentralManager.alloc()
| python | {
"resource": ""
} |
q255397 | CoreBluetoothProvider.disconnect_devices | validation | def disconnect_devices(self, service_uuids):
"""Disconnect any connected devices that have any of the specified
service UUIDs.
"""
# Get list of connected devices with specified services.
cbuuids = map(uuid_to_cbuuid, service_uuids)
| python | {
"resource": ""
} |
q255398 | BluezProvider.initialize | validation | def initialize(self):
"""Initialize bluez DBus communication. Must be called before any other
calls are made!
"""
# Ensure GLib's threading is initialized to support python threads, and
# make a default mainloop that all DBus objects will inherit. These
# commands MUST execute before any other DBus commands!
GObject.threads_init()
dbus.mainloop.glib.threads_init()
# Set the default main loop, this | python | {
"resource": ""
} |
q255399 | BluezProvider.clear_cached_data | validation | def clear_cached_data(self):
"""Clear any internally cached BLE device data. Necessary in some cases
to prevent issues with stale device data getting cached by the OS.
"""
# Go through and remove any device that isn't currently connected.
for device in self.list_devices():
# Skip any connected device.
if device.is_connected:
continue
# Remove this device. First get the adapter associated with the device.
adapter = | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.