_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q255100 | WsgiDAVApp.resolve_provider | validation | def resolve_provider(self, path):
"""Get the registered DAVProvider for a given path.
Returns:
tuple: (share, provider)
"""
# Find DAV provider that matches the share
share = None
lower_path = path.lower()
for r in self.sorted_share_list:
... | python | {
"resource": ""
} |
q255101 | HTTPAuthenticator.compute_digest_response | validation | def compute_digest_response(
self, realm, user_name, method, uri, nonce, cnonce, qop, nc, environ
):
"""Computes digest hash.
Calculation of the A1 (HA1) part is delegated to the dc interface method
`digest_auth_user()`.
Args:
realm (str):
user_name ... | python | {
"resource": ""
} |
q255102 | FileLikeQueue.read | validation | def read(self, size=0):
"""Read a chunk of bytes from queue.
size = 0: Read next chunk (arbitrary length)
> 0: Read one chunk of `size` bytes (or less if stream was closed)
< 0: Read all bytes as single chunk (i.e. blocks until stream is closed)
This method blocks unt... | python | {
"resource": ""
} |
q255103 | StreamingFile.read | validation | def read(self, size=None):
"""Read bytes from an iterator."""
while size is None or len(self.buffer) < size:
try:
self.buffer += next(self.data_stream)
except StopIteration:
break
sized_chunk = self.buffer[:size]
if size is None:
... | python | {
"resource": ""
} |
q255104 | ExtServer.handle_error | validation | def handle_error(self, request, client_address):
"""Handle an error gracefully. May be overridden.
The default is to _logger.info a traceback and continue.
"""
ei = sys.exc_info()
e = ei[1]
# Suppress stack trace when client aborts connection disgracefully:
# 1... | python | {
"resource": ""
} |
q255105 | HgResource.end_write | validation | def end_write(self, with_errors):
"""Called when PUT has finished writing.
See DAVResource.end_write()
"""
if not with_errors:
commands.add(self.provider.ui, self.provider.repo, self.localHgPath) | python | {
"resource": ""
} |
q255106 | HgResource.handle_copy | validation | def handle_copy(self, dest_path, depth_infinity):
"""Handle a COPY request natively.
"""
destType, destHgPath = util.pop_path(dest_path)
destHgPath = destHgPath.strip("/")
ui = self.provider.ui
repo = self.provider.repo
_logger.info("handle_copy %s -> %s" % (self... | python | {
"resource": ""
} |
q255107 | HgResourceProvider._get_log | validation | def _get_log(self, limit=None):
"""Read log entries into a list of dictionaries."""
self.ui.pushbuffer()
commands.log(self.ui, self.repo, limit=limit, date=None, rev=None, user=None)
res = self.ui.popbuffer().strip()
logList = []
for logentry in res.split("\n\n"):
... | python | {
"resource": ""
} |
q255108 | HgResourceProvider._get_repo_info | validation | def _get_repo_info(self, environ, rev, reload=False):
"""Return a dictionary containing all files under source control.
dirinfos:
Dictionary containing direct members for every collection.
{folderpath: (collectionlist, filelist), ...}
files:
Sorted list of al... | python | {
"resource": ""
} |
q255109 | HgResourceProvider.get_resource_inst | validation | def get_resource_inst(self, path, environ):
"""Return HgResource object for path.
See DAVProvider.get_resource_inst()
"""
self._count_get_resource_inst += 1
# HG expects the resource paths without leading '/'
localHgPath = path.strip("/")
rev = None
cmd,... | python | {
"resource": ""
} |
q255110 | _DAVResource.get_preferred_path | validation | def get_preferred_path(self):
"""Return preferred mapping for a resource mapping.
Different URLs may map to the same resource, e.g.:
'/a/b' == '/A/b' == '/a/b/'
get_preferred_path() returns the same value for all these variants, e.g.:
'/a/b/' (assuming resource names c... | python | {
"resource": ""
} |
q255111 | _DAVResource.get_href | validation | def get_href(self):
"""Convert path to a URL that can be passed to XML responses.
Byte string, UTF-8 encoded, quoted.
See http://www.webdav.org/specs/rfc4918.html#rfc.section.8.3
We are using the path-absolute option. i.e. starting with '/'.
URI ; See section 3.2.1 of [RFC2068]... | python | {
"resource": ""
} |
q255112 | _DAVResource.set_property_value | validation | def set_property_value(self, name, value, dry_run=False):
"""Set a property value or remove a property.
value == None means 'remove property'.
Raise HTTP_FORBIDDEN if property is read-only, or not supported.
When dry_run is True, this function should raise errors, as in a real
... | python | {
"resource": ""
} |
q255113 | _DAVResource.remove_all_properties | validation | def remove_all_properties(self, recursive):
"""Remove all associated dead properties."""
if self.provider.prop_manager:
self.provider.prop_manager.remove_properties(
self.get_ref_url(), self.environ
) | python | {
"resource": ""
} |
q255114 | _DAVResource.is_locked | validation | def is_locked(self):
"""Return True, if URI is locked."""
if self.provider.lock_manager is None:
return False
return self.provider.lock_manager.is_url_locked(self.get_ref_url()) | python | {
"resource": ""
} |
q255115 | DAVProvider.set_share_path | validation | def set_share_path(self, share_path):
"""Set application location for this resource provider.
@param share_path: a UTF-8 encoded, unquoted byte string.
"""
# if isinstance(share_path, unicode):
# share_path = share_path.encode("utf8")
assert share_path == "" or share... | python | {
"resource": ""
} |
q255116 | DAVProvider.ref_url_to_path | validation | def ref_url_to_path(self, ref_url):
"""Convert a refUrl to a path, by stripping the share prefix.
Used to calculate the <path> from a storage key by inverting get_ref_url().
"""
return "/" + compat.unquote(util.lstripstr(ref_url, self.share_path)).lstrip(
"/"
) | python | {
"resource": ""
} |
q255117 | DAVProvider.is_collection | validation | def is_collection(self, path, environ):
"""Return True, if path maps to an existing collection resource.
This method should only be used, if no other information is queried
for <path>. Otherwise a _DAVResource should be created first.
"""
res = self.get_resource_inst(path, envir... | python | {
"resource": ""
} |
q255118 | string_to_xml | validation | def string_to_xml(text):
"""Convert XML string into etree.Element."""
try:
return etree.XML(text)
except Exception:
# TODO:
# ExpatError: reference to invalid character number: line 1, column 62
# litmus fails, when xml is used instead of lxml
# 18. propget.............. | python | {
"resource": ""
} |
q255119 | xml_to_bytes | validation | def xml_to_bytes(element, pretty_print=False):
"""Wrapper for etree.tostring, that takes care of unsupported pretty_print
option and prepends an encoding header."""
if use_lxml:
xml = etree.tostring(
element, encoding="UTF-8", xml_declaration=True, pretty_print=pretty_print
)
... | python | {
"resource": ""
} |
q255120 | make_sub_element | validation | def make_sub_element(parent, tag, nsmap=None):
"""Wrapper for etree.SubElement, that takes care of unsupported nsmap option."""
if use_lxml:
return etree.SubElement(parent, tag, nsmap=nsmap)
return etree.SubElement(parent, tag) | python | {
"resource": ""
} |
q255121 | element_content_as_string | validation | def element_content_as_string(element):
"""Serialize etree.Element.
Note: element may contain more than one child or only text (i.e. no child
at all). Therefore the resulting string may raise an exception, when
passed back to etree.XML().
"""
if len(element) == 0:
return ele... | python | {
"resource": ""
} |
q255122 | _get_checked_path | validation | def _get_checked_path(path, config, must_exist=True, allow_none=True):
"""Convert path to absolute if not None."""
if path in (None, ""):
if allow_none:
return None
raise ValueError("Invalid path {!r}".format(path))
# Evaluate path relative to the folder of the config file (if an... | python | {
"resource": ""
} |
q255123 | _read_config_file | validation | def _read_config_file(config_file, verbose):
"""Read configuration file options into a dictionary."""
config_file = os.path.abspath(config_file)
if not os.path.exists(config_file):
raise RuntimeError("Couldn't open configuration file '{}'.".format(config_file))
if config_file.endswith(".json"... | python | {
"resource": ""
} |
q255124 | _run_paste | validation | def _run_paste(app, config, mode):
"""Run WsgiDAV using paste.httpserver, if Paste is installed.
See http://pythonpaste.org/modules/httpserver.html for more options
"""
from paste import httpserver
version = "WsgiDAV/{} {} Python {}".format(
__version__, httpserver.WSGIHandler.server_versi... | python | {
"resource": ""
} |
q255125 | _run_gevent | validation | def _run_gevent(app, config, mode):
"""Run WsgiDAV using gevent if gevent is installed.
See
https://github.com/gevent/gevent/blob/master/src/gevent/pywsgi.py#L1356
https://github.com/gevent/gevent/blob/master/src/gevent/server.py#L38
for more options
"""
import gevent
import gevent... | python | {
"resource": ""
} |
q255126 | _run__cherrypy | validation | def _run__cherrypy(app, config, mode):
"""Run WsgiDAV using cherrypy.wsgiserver if CherryPy is installed."""
assert mode == "cherrypy-wsgiserver"
try:
from cherrypy import wsgiserver
from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter
_logger.warning("WARNING: cherrypy.ws... | python | {
"resource": ""
} |
q255127 | _run_cheroot | validation | def _run_cheroot(app, config, mode):
"""Run WsgiDAV using cheroot.server if Cheroot is installed."""
assert mode == "cheroot"
try:
from cheroot import server, wsgi
# from cheroot.ssl.builtin import BuiltinSSLAdapter
# import cheroot.ssl.pyopenssl
except ImportError:
... | python | {
"resource": ""
} |
q255128 | _run_flup | validation | def _run_flup(app, config, mode):
"""Run WsgiDAV using flup.server.fcgi if Flup is installed."""
# http://trac.saddi.com/flup/wiki/FlupServers
if mode == "flup-fcgi":
from flup.server.fcgi import WSGIServer, __version__ as flupver
elif mode == "flup-fcgi-fork":
from flup.server.fcgi_fork... | python | {
"resource": ""
} |
q255129 | _run_wsgiref | validation | def _run_wsgiref(app, config, mode):
"""Run WsgiDAV using wsgiref.simple_server, on Python 2.5+."""
# http://www.python.org/doc/2.5.2/lib/module-wsgiref.html
from wsgiref.simple_server import make_server, software_version
version = "WsgiDAV/{} {}".format(__version__, software_version)
_logger.info(... | python | {
"resource": ""
} |
q255130 | _run_ext_wsgiutils | validation | def _run_ext_wsgiutils(app, config, mode):
"""Run WsgiDAV using ext_wsgiutils_server from the wsgidav package."""
from wsgidav.server import ext_wsgiutils_server
_logger.info(
"Running WsgiDAV {} on wsgidav.ext_wsgiutils_server...".format(__version__)
)
_logger.warning(
"WARNING: Th... | python | {
"resource": ""
} |
q255131 | RequestServer.do_PROPPATCH | validation | def do_PROPPATCH(self, environ, start_response):
"""Handle PROPPATCH request to set or remove a property.
@see http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH
"""
path = environ["PATH_INFO"]
res = self._davProvider.get_resource_inst(path, environ)
# Only accep... | python | {
"resource": ""
} |
q255132 | RequestServer.do_MKCOL | validation | def do_MKCOL(self, environ, start_response):
"""Handle MKCOL request to create a new collection.
@see http://www.webdav.org/specs/rfc4918.html#METHOD_MKCOL
"""
path = environ["PATH_INFO"]
provider = self._davProvider
# res = provider.get_resource_inst(path, enviro... | python | {
"resource": ""
} |
q255133 | RequestServer._stream_data_chunked | validation | def _stream_data_chunked(self, environ, block_size):
"""Get the data from a chunked transfer."""
# Chunked Transfer Coding
# http://www.servlets.com/rfcs/rfc2616-sec3.html#sec3.6.1
if "Darwin" in environ.get("HTTP_USER_AGENT", "") and environ.get(
"HTTP_X_EXPECTED_ENTITY_LEN... | python | {
"resource": ""
} |
q255134 | RequestServer._stream_data | validation | def _stream_data(self, environ, content_length, block_size):
"""Get the data from a non-chunked transfer."""
if content_length == 0:
# TODO: review this
# XP and Vista MiniRedir submit PUT with Content-Length 0,
# before LOCK and the real PUT. So we have to accept thi... | python | {
"resource": ""
} |
q255135 | CouchPropertyManager._find | validation | def _find(self, url):
"""Return properties document for path."""
# Query the permanent view to find a url
vr = self.db.view("properties/by_url", key=url, include_docs=True)
_logger.debug("find(%r) returned %s" % (url, len(vr)))
assert len(vr) <= 1, "Found multiple matches for %r"... | python | {
"resource": ""
} |
q255136 | SimpleDomainController.get_domain_realm | validation | def get_domain_realm(self, path_info, environ):
"""Resolve a relative url to the appropriate realm name."""
realm = self._calc_realm_from_path_provider(path_info, environ)
return realm | python | {
"resource": ""
} |
q255137 | SimpleDomainController.digest_auth_user | validation | def digest_auth_user(self, realm, user_name, environ):
"""Computes digest hash A1 part."""
user = self._get_realm_entry(realm, user_name)
if user is None:
return False
password = user.get("password")
environ["wsgidav.auth.roles"] = user.get("roles", [])
return... | python | {
"resource": ""
} |
q255138 | LockStorageDict.get | validation | def get(self, token):
"""Return a lock dictionary for a token.
If the lock does not exist or is expired, None is returned.
token:
lock token
Returns:
Lock dictionary or <None>
Side effect: if lock is expired, it will be purged and None is returned.
... | python | {
"resource": ""
} |
q255139 | LockStorageDict.create | validation | def create(self, path, lock):
"""Create a direct lock for a resource path.
path:
Normalized path (utf8 encoded string, no trailing '/')
lock:
lock dictionary, without a token entry
Returns:
New unique lock token.: <lock
**Note:** the lock dic... | python | {
"resource": ""
} |
q255140 | LockStorageDict.refresh | validation | def refresh(self, token, timeout):
"""Modify an existing lock's timeout.
token:
Valid lock token.
timeout:
Suggested lifetime in seconds (-1 for infinite).
The real expiration time may be shorter than requested!
Returns:
Lock dictionary.
... | python | {
"resource": ""
} |
q255141 | LockStorageDict.delete | validation | def delete(self, token):
"""Delete lock.
Returns True on success. False, if token does not exist, or is expired.
"""
self._lock.acquire_write()
try:
lock = self._dict.get(token)
_logger.debug("delete {}".format(lock_string(lock)))
if lock is N... | python | {
"resource": ""
} |
q255142 | LockStorageShelve.clear | validation | def clear(self):
"""Delete all entries."""
self._lock.acquire_write() # TODO: read access is enough?
try:
was_closed = self._dict is None
if was_closed:
self.open()
if len(self._dict):
self._dict.clear()
self._d... | python | {
"resource": ""
} |
q255143 | FileResource.set_last_modified | validation | def set_last_modified(self, dest_path, time_stamp, dry_run):
"""Set last modified time for destPath to timeStamp on epoch-format"""
# Translate time from RFC 1123 to seconds since epoch format
secs = util.parse_time_string(time_stamp)
if not dry_run:
os.utime(self._file_path,... | python | {
"resource": ""
} |
q255144 | lock_string | validation | def lock_string(lock_dict):
"""Return readable rep."""
if not lock_dict:
return "Lock: None"
if lock_dict["expire"] < 0:
expire = "Infinite ({})".format(lock_dict["expire"])
else:
expire = "{} (in {} seconds)".format(
util.get_log_time(lock_dict["expire"]), lock_dict... | python | {
"resource": ""
} |
q255145 | LockManager._generate_lock | validation | def _generate_lock(
self, principal, lock_type, lock_scope, lock_depth, lock_owner, path, timeout
):
"""Acquire lock and return lock_dict.
principal
Name of the principal.
lock_type
Must be 'write'.
lock_scope
Must be 'shared' or 'exclusiv... | python | {
"resource": ""
} |
q255146 | LockManager.acquire | validation | def acquire(
self,
url,
lock_type,
lock_scope,
lock_depth,
lock_owner,
timeout,
principal,
token_list,
):
"""Check for permissions and acquire a lock.
On success return new lock dictionary.
On error raise a DAVError wit... | python | {
"resource": ""
} |
q255147 | LockManager.refresh | validation | def refresh(self, token, timeout=None):
"""Set new timeout for lock, if existing and valid."""
if timeout is None:
timeout = LockManager.LOCK_TIME_OUT_DEFAULT
return self.storage.refresh(token, timeout) | python | {
"resource": ""
} |
q255148 | LockManager.get_lock | validation | def get_lock(self, token, key=None):
"""Return lock_dict, or None, if not found or invalid.
Side effect: if lock is expired, it will be purged and None is returned.
key:
name of lock attribute that will be returned instead of a dictionary.
"""
assert key in (
... | python | {
"resource": ""
} |
q255149 | ReadWriteLock.acquire_read | validation | def acquire_read(self, timeout=None):
"""Acquire a read lock for the current thread, waiting at most
timeout seconds or doing a non-blocking check in case timeout is <= 0.
In case timeout is None, the call to acquire_read blocks until the
lock request can be serviced.
In case t... | python | {
"resource": ""
} |
q255150 | ReadWriteLock.acquire_write | validation | def acquire_write(self, timeout=None):
"""Acquire a write lock for the current thread, waiting at most
timeout seconds or doing a non-blocking check in case timeout is <= 0.
In case the write lock cannot be serviced due to the deadlock
condition mentioned above, a ValueError is raised.
... | python | {
"resource": ""
} |
q255151 | ReadWriteLock.release | validation | def release(self):
"""Release the currently held lock.
In case the current thread holds no lock, a ValueError is thrown."""
me = currentThread()
self.__condition.acquire()
try:
if self.__writer is me:
# We are the writer, take one nesting depth away.... | python | {
"resource": ""
} |
q255152 | init_logging | validation | def init_logging(config):
"""Initialize base logger named 'wsgidav'.
The base logger is filtered by the `verbose` configuration option.
Log entries will have a time stamp and thread id.
:Parameters:
verbose : int
Verbosity configuration (0..5)
enable_loggers : string list
... | python | {
"resource": ""
} |
q255153 | dynamic_instantiate_middleware | validation | def dynamic_instantiate_middleware(name, args, expand=None):
"""Import a class and instantiate with custom args.
Example:
name = "my.module.Foo"
args_dict = {
"bar": 42,
"baz": "qux"
}
=>
from my.module import Foo
return Foo(bar=42, ba... | python | {
"resource": ""
} |
q255154 | string_repr | validation | def string_repr(s):
"""Return a string as hex dump."""
if compat.is_bytes(s):
res = "{!r}: ".format(s)
for b in s:
if type(b) is str: # Py2
b = ord(b)
res += "%02x " % b
return res
return "{}".format(s) | python | {
"resource": ""
} |
q255155 | byte_number_string | validation | def byte_number_string(
number, thousandsSep=True, partition=False, base1024=True, appendBytes=True
):
"""Convert bytes into human-readable representation."""
magsuffix = ""
bytesuffix = ""
if partition:
magnitude = 0
if base1024:
while number >= 1024:
ma... | python | {
"resource": ""
} |
q255156 | read_and_discard_input | validation | def read_and_discard_input(environ):
"""Read 1 byte from wsgi.input, if this has not been done yet.
Returning a response without reading from a request body might confuse the
WebDAV client.
This may happen, if an exception like '401 Not authorized', or
'500 Internal error' was raised BEFORE anythin... | python | {
"resource": ""
} |
q255157 | join_uri | validation | def join_uri(uri, *segments):
"""Append segments to URI.
Example: join_uri("/a/b", "c", "d")
"""
sub = "/".join(segments)
if not sub:
return uri
return uri.rstrip("/") + "/" + sub | python | {
"resource": ""
} |
q255158 | is_child_uri | validation | def is_child_uri(parentUri, childUri):
"""Return True, if childUri is a child of parentUri.
This function accounts for the fact that '/a/b/c' and 'a/b/c/' are
children of '/a/b' (and also of '/a/b/').
Note that '/a/b/cd' is NOT a child of 'a/b/c'.
"""
return (
parentUri
and chil... | python | {
"resource": ""
} |
q255159 | is_equal_or_child_uri | validation | def is_equal_or_child_uri(parentUri, childUri):
"""Return True, if childUri is a child of parentUri or maps to the same resource.
Similar to <util.is_child_uri>_ , but this method also returns True, if parent
equals child. ('/a/b' is considered identical with '/a/b/').
"""
return (
parentU... | python | {
"resource": ""
} |
q255160 | make_complete_url | validation | def make_complete_url(environ, localUri=None):
"""URL reconstruction according to PEP 333.
@see https://www.python.org/dev/peps/pep-3333/#url-reconstruction
"""
url = environ["wsgi.url_scheme"] + "://"
if environ.get("HTTP_HOST"):
url += environ["HTTP_HOST"]
else:
url += environ... | python | {
"resource": ""
} |
q255161 | parse_xml_body | validation | def parse_xml_body(environ, allow_empty=False):
"""Read request body XML into an etree.Element.
Return None, if no request body was sent.
Raise HTTP_BAD_REQUEST, if something else went wrong.
TODO: this is a very relaxed interpretation: should we raise HTTP_BAD_REQUEST
instead, if CONTENT_LENGTH i... | python | {
"resource": ""
} |
q255162 | send_status_response | validation | def send_status_response(environ, start_response, e, add_headers=None, is_head=False):
"""Start a WSGI response for a DAVError or status code."""
status = get_http_status_string(e)
headers = []
if add_headers:
headers.extend(add_headers)
# if 'keep-alive' in environ.get('HTTP_CONNECTION',... | python | {
"resource": ""
} |
q255163 | calc_base64 | validation | def calc_base64(s):
"""Return base64 encoded binarystring."""
s = compat.to_bytes(s)
s = compat.base64_encodebytes(s).strip() # return bytestring
return compat.to_native(s) | python | {
"resource": ""
} |
q255164 | read_timeout_value_header | validation | def read_timeout_value_header(timeoutvalue):
"""Return -1 if infinite, else return numofsecs."""
timeoutsecs = 0
timeoutvaluelist = timeoutvalue.split(",")
for timeoutspec in timeoutvaluelist:
timeoutspec = timeoutspec.strip()
if timeoutspec.lower() == "infinite":
return -1
... | python | {
"resource": ""
} |
q255165 | parse_if_header_dict | validation | def parse_if_header_dict(environ):
"""Parse HTTP_IF header into a dictionary and lists, and cache the result.
@see http://www.webdav.org/specs/rfc4918.html#HEADER_If
"""
if "wsgidav.conditions.if" in environ:
return
if "HTTP_IF" not in environ:
environ["wsgidav.conditions.if"] = No... | python | {
"resource": ""
} |
q255166 | guess_mime_type | validation | def guess_mime_type(url):
"""Use the mimetypes module to lookup the type for an extension.
This function also adds some extensions required for HTML5
"""
(mimetype, _mimeencoding) = mimetypes.guess_type(url)
if not mimetype:
ext = os.path.splitext(url)[1]
mimetype = _MIME_TYPES.get(... | python | {
"resource": ""
} |
q255167 | Group.add_members | validation | def add_members(self, new_members):
"""
Add objects to the group.
Parameters
----------
new_members : list
A list of cobrapy objects to add to the group.
"""
if isinstance(new_members, string_types) or \
hasattr(new_members, "id"):
... | python | {
"resource": ""
} |
q255168 | Group.remove_members | validation | def remove_members(self, to_remove):
"""
Remove objects from the group.
Parameters
----------
to_remove : list
A list of cobra objects to remove from the group
"""
if isinstance(to_remove, string_types) or \
hasattr(to_remove, "id"):
... | python | {
"resource": ""
} |
q255169 | geometric_fba | validation | def geometric_fba(model, epsilon=1E-06, max_tries=200, processes=None):
"""
Perform geometric FBA to obtain a unique, centered flux distribution.
Geometric FBA [1]_ formulates the problem as a polyhedron and
then solves it by bounding the convex hull of the polyhedron.
The bounding forms a box arou... | python | {
"resource": ""
} |
q255170 | DictList._generate_index | validation | def _generate_index(self):
"""rebuild the _dict index"""
self._dict = {v.id: k for k, v in enumerate(self)} | python | {
"resource": ""
} |
q255171 | DictList.get_by_any | validation | def get_by_any(self, iterable):
"""
Get a list of members using several different ways of indexing
Parameters
----------
iterable : list (if not, turned into single element list)
list where each element is either int (referring to an index in
in this Dict... | python | {
"resource": ""
} |
q255172 | DictList.query | validation | def query(self, search_function, attribute=None):
"""Query the list
Parameters
----------
search_function : a string, regular expression or function
Used to find the matching elements in the list.
- a regular expression (possibly compiled), in which case the
... | python | {
"resource": ""
} |
q255173 | DictList._replace_on_id | validation | def _replace_on_id(self, new_object):
"""Replace an object by another with the same id."""
the_id = new_object.id
the_index = self._dict[the_id]
list.__setitem__(self, the_index, new_object) | python | {
"resource": ""
} |
q255174 | DictList.append | validation | def append(self, object):
"""append object to end"""
the_id = object.id
self._check(the_id)
self._dict[the_id] = len(self)
list.append(self, object) | python | {
"resource": ""
} |
q255175 | DictList.union | validation | def union(self, iterable):
"""adds elements with id's not already in the model"""
_dict = self._dict
append = self.append
for i in iterable:
if i.id not in _dict:
append(i) | python | {
"resource": ""
} |
q255176 | DictList.extend | validation | def extend(self, iterable):
"""extend list by appending elements from the iterable"""
# Sometimes during initialization from an older pickle, _dict
# will not have initialized yet, because the initialization class was
# left unspecified. This is an issue because unpickling calls
... | python | {
"resource": ""
} |
q255177 | DictList._extend_nocheck | validation | def _extend_nocheck(self, iterable):
"""extends without checking for uniqueness
This function should only be used internally by DictList when it
can guarantee elements are already unique (as in when coming from
self or other DictList). It will be faster because it skips these
ch... | python | {
"resource": ""
} |
q255178 | DictList.index | validation | def index(self, id, *args):
"""Determine the position in the list
id: A string or a :class:`~cobra.core.Object.Object`
"""
# because values are unique, start and stop are not relevant
if isinstance(id, string_types):
try:
return self._dict[id]
... | python | {
"resource": ""
} |
q255179 | DictList.insert | validation | def insert(self, index, object):
"""insert object before index"""
self._check(object.id)
list.insert(self, index, object)
# all subsequent entries now have been shifted up by 1
_dict = self._dict
for i, j in iteritems(_dict):
if j >= index:
_di... | python | {
"resource": ""
} |
q255180 | Metabolite.elements | validation | def elements(self):
""" Dictionary of elements as keys and their count in the metabolite
as integer. When set, the `formula` property is update accordingly """
tmp_formula = self.formula
if tmp_formula is None:
return {}
# necessary for some old pickles which use the ... | python | {
"resource": ""
} |
q255181 | Metabolite.shadow_price | validation | def shadow_price(self):
"""
The shadow price in the most recent solution.
Shadow price is the dual value of the corresponding constraint in the
model.
Warnings
--------
* Accessing shadow prices through a `Solution` object is the safer,
preferred, and ... | python | {
"resource": ""
} |
q255182 | to_yaml | validation | def to_yaml(model, sort=False, **kwargs):
"""
Return the model as a YAML document.
``kwargs`` are passed on to ``yaml.dump``.
Parameters
----------
model : cobra.Model
The cobra model to represent.
sort : bool, optional
Whether to sort the metabolites, reactions, and genes ... | python | {
"resource": ""
} |
q255183 | save_yaml_model | validation | def save_yaml_model(model, filename, sort=False, **kwargs):
"""
Write the cobra model to a file in YAML format.
``kwargs`` are passed on to ``yaml.dump``.
Parameters
----------
model : cobra.Model
The cobra model to represent.
filename : str or file-like
File path or descri... | python | {
"resource": ""
} |
q255184 | load_yaml_model | validation | def load_yaml_model(filename):
"""
Load a cobra model from a file in YAML format.
Parameters
----------
filename : str or file-like
File path or descriptor that contains the YAML document describing the
cobra model.
Returns
-------
cobra.Model
The cobra model as... | python | {
"resource": ""
} |
q255185 | add_pfba | validation | def add_pfba(model, objective=None, fraction_of_optimum=1.0):
"""Add pFBA objective
Add objective to minimize the summed flux of all reactions to the
current objective.
See Also
-------
pfba
Parameters
----------
model : cobra.Model
The model to add the objective to
ob... | python | {
"resource": ""
} |
q255186 | _process_flux_dataframe | validation | def _process_flux_dataframe(flux_dataframe, fva, threshold, floatfmt):
"""Some common methods for processing a database of flux information into
print-ready formats. Used in both model_summary and metabolite_summary. """
abs_flux = flux_dataframe['flux'].abs()
flux_threshold = threshold * abs_flux.max(... | python | {
"resource": ""
} |
q255187 | linear_reaction_coefficients | validation | def linear_reaction_coefficients(model, reactions=None):
"""Coefficient for the reactions in a linear objective.
Parameters
----------
model : cobra model
the model object that defined the objective
reactions : list
an optional list for the reactions to get the coefficients for. All... | python | {
"resource": ""
} |
q255188 | _valid_atoms | validation | def _valid_atoms(model, expression):
"""Check whether a sympy expression references the correct variables.
Parameters
----------
model : cobra.Model
The model in which to check for variables.
expression : sympy.Basic
A sympy expression.
Returns
-------
boolean
T... | python | {
"resource": ""
} |
q255189 | set_objective | validation | def set_objective(model, value, additive=False):
"""Set the model objective.
Parameters
----------
model : cobra model
The model to set the objective for
value : model.problem.Objective,
e.g. optlang.glpk_interface.Objective, sympy.Basic or dict
If the model objective is... | python | {
"resource": ""
} |
q255190 | interface_to_str | validation | def interface_to_str(interface):
"""Give a string representation for an optlang interface.
Parameters
----------
interface : string, ModuleType
Full name of the interface in optlang or cobra representation.
For instance 'optlang.glpk_interface' or 'optlang-glpk'.
Returns
------... | python | {
"resource": ""
} |
q255191 | get_solver_name | validation | def get_solver_name(mip=False, qp=False):
"""Select a solver for a given optimization problem.
Parameters
----------
mip : bool
Does the solver require mixed integer linear programming capabilities?
qp : bool
Does the solver require quadratic programming capabilities?
Returns
... | python | {
"resource": ""
} |
q255192 | choose_solver | validation | def choose_solver(model, solver=None, qp=False):
"""Choose a solver given a solver name and model.
This will choose a solver compatible with the model and required
capabilities. Also respects model.solver where it can.
Parameters
----------
model : a cobra model
The model for which to ... | python | {
"resource": ""
} |
q255193 | add_cons_vars_to_problem | validation | def add_cons_vars_to_problem(model, what, **kwargs):
"""Add variables and constraints to a Model's solver object.
Useful for variables and constraints that can not be expressed with
reactions and lower/upper bounds. Will integrate with the Model's context
manager in order to revert changes upon leaving... | python | {
"resource": ""
} |
q255194 | remove_cons_vars_from_problem | validation | def remove_cons_vars_from_problem(model, what):
"""Remove variables and constraints from a Model's solver object.
Useful to temporarily remove variables and constraints from a Models's
solver object.
Parameters
----------
model : a cobra model
The model from which to remove the variable... | python | {
"resource": ""
} |
q255195 | add_absolute_expression | validation | def add_absolute_expression(model, expression, name="abs_var", ub=None,
difference=0, add=True):
"""Add the absolute value of an expression to the model.
Also defines a variable for the absolute value that can be used in other
objectives or constraints.
Parameters
-----... | python | {
"resource": ""
} |
q255196 | fix_objective_as_constraint | validation | def fix_objective_as_constraint(model, fraction=1, bound=None,
name='fixed_objective_{}'):
"""Fix current objective as an additional constraint.
When adding constraints to a model, such as done in pFBA which
minimizes total flux, these constraints can become too powerful,
... | python | {
"resource": ""
} |
q255197 | check_solver_status | validation | def check_solver_status(status, raise_error=False):
"""Perform standard checks on a solver's status."""
if status == OPTIMAL:
return
elif (status in has_primals) and not raise_error:
warn("solver status is '{}'".format(status), UserWarning)
elif status is None:
raise Optimization... | python | {
"resource": ""
} |
q255198 | assert_optimal | validation | def assert_optimal(model, message='optimization failed'):
"""Assert model solver status is optimal.
Do nothing if model solver status is optimal, otherwise throw
appropriate exception depending on the status.
Parameters
----------
model : cobra.Model
The model to check the solver statu... | python | {
"resource": ""
} |
q255199 | add_lp_feasibility | validation | def add_lp_feasibility(model):
"""
Add a new objective and variables to ensure a feasible solution.
The optimized objective will be zero for a feasible solution and otherwise
represent the distance from feasibility (please see [1]_ for more
information).
Parameters
----------
model : c... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.