Search is not available for this dataset
text
stringlengths 75
104k
|
---|
def authenticate(username, password, service='login', encoding='utf-8',
resetcred=True):
"""Returns True if the given username and password authenticate for the
given service. Returns False otherwise.
``username``: the username to authenticate
``password``: the password in plain text
``service``: the PAM service to authenticate against.
Defaults to 'login'
The above parameters can be strings or bytes. If they are strings,
they will be encoded using the encoding given by:
``encoding``: the encoding to use for the above parameters if they
are given as strings. Defaults to 'utf-8'
``resetcred``: Use the pam_setcred() function to
reinitialize the credentials.
Defaults to 'True'.
"""
if sys.version_info >= (3,):
if isinstance(username, str):
username = username.encode(encoding)
if isinstance(password, str):
password = password.encode(encoding)
if isinstance(service, str):
service = service.encode(encoding)
@conv_func
def my_conv(n_messages, messages, p_response, app_data):
"""Simple conversation function that responds to any
prompt where the echo is off with the supplied password"""
# Create an array of n_messages response objects
addr = calloc(n_messages, sizeof(PamResponse))
p_response[0] = cast(addr, POINTER(PamResponse))
for i in range(n_messages):
if messages[i].contents.msg_style == PAM_PROMPT_ECHO_OFF:
pw_copy = strdup(password)
p_response.contents[i].resp = cast(pw_copy, c_char_p)
p_response.contents[i].resp_retcode = 0
return 0
handle = PamHandle()
conv = PamConv(my_conv, 0)
retval = pam_start(service, username, byref(conv), byref(handle))
if retval != 0:
# TODO: This is not an authentication error, something
# has gone wrong starting up PAM
return False
retval = pam_authenticate(handle, 0)
auth_success = (retval == 0)
# Re-initialize credentials (for Kerberos users, etc)
# Don't check return code of pam_setcred(), it shouldn't matter
# if this fails
if auth_success and resetcred:
retval = pam_setcred(handle, PAM_REINITIALIZE_CRED)
pam_end(handle, retval)
return auth_success |
def post(self, request):
"""
Save the provided data using the class' serializer.
Args:
request:
The request being made.
Returns:
An ``APIResponse`` instance. If the request was successful
the response will have a 200 status code and contain the
serializer's data. Otherwise a 400 status code and the
request's errors will be returned.
"""
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) |
def get_repr(self, obj, referent=None):
"""Return an HTML tree block describing the given object."""
objtype = type(obj)
typename = str(objtype.__module__) + "." + objtype.__name__
prettytype = typename.replace("__builtin__.", "")
name = getattr(obj, "__name__", "")
if name:
prettytype = "%s %r" % (prettytype, name)
key = ""
if referent:
key = self.get_refkey(obj, referent)
url = reverse('dowser_trace_object', args=(
typename,
id(obj)
))
return ('<a class="objectid" href="%s">%s</a> '
'<span class="typename">%s</span>%s<br />'
'<span class="repr">%s</span>'
% (url, id(obj), prettytype, key, get_repr(obj, 100))
) |
def get_refkey(self, obj, referent):
"""Return the dict key or attribute name of obj which refers to
referent."""
if isinstance(obj, dict):
for k, v in obj.items():
if v is referent:
return " (via its %r key)" % k
for k in dir(obj) + ['__dict__']:
if getattr(obj, k, None) is referent:
return " (via its %r attribute)" % k
return "" |
def walk(self, maxresults=100, maxdepth=None):
"""Walk the object tree, ignoring duplicates and circular refs."""
log.debug("step")
self.seen = {}
self.ignore(self, self.__dict__, self.obj, self.seen, self._ignore)
# Ignore the calling frame, its builtins, globals and locals
self.ignore_caller()
self.maxdepth = maxdepth
count = 0
log.debug("will iterate results")
for result in self._gen(self.obj):
log.debug("will yeld")
yield result
count += 1
if maxresults and count >= maxresults:
yield 0, 0, "==== Max results reached ===="
return |
def print_tree(self, maxresults=100, maxdepth=None):
"""Walk the object tree, pretty-printing each branch."""
self.ignore_caller()
for depth, refid, rep in self.walk(maxresults, maxdepth):
print(("%9d" % refid), (" " * depth * 2), rep) |
def print_tree(self, maxresults=100, maxdepth=None):
"""Walk the object tree, pretty-printing each branch."""
self.ignore_caller()
for trail in self.walk(maxresults, maxdepth):
print(trail)
if self.stops:
print("%s paths stopped because max depth reached" % self.stops) |
def get_finders():
"""
Set the media fixtures finders on settings.py.
Example:
MEDIA_FIXTURES_FILES_FINDERS = (
'django_media_fixtures.finders.FileSystemFinder',
'django_media_fixtures.finders.AppDirectoriesFinder', # default
)
"""
if hasattr(settings, 'MEDIA_FIXTURES_FILES_FINDERS'):
finders = settings.MEDIA_FIXTURES_FILES_FINDERS
else:
finders = (
'django_media_fixtures.finders.AppDirectoriesFinder',
)
for finder_path in finders:
yield get_finder(finder_path) |
def get_finder(import_path):
"""
Imports the media fixtures files finder class described by import_path, where
import_path is the full Python path to the class.
"""
Finder = import_string(import_path)
if not issubclass(Finder, BaseFinder):
raise ImproperlyConfigured('Finder "%s" is not a subclass of "%s"' %
(Finder, BaseFinder))
return Finder() |
def find(self, path, all=False):
"""
Looks for files in the extra locations
as defined in ``MEDIA_FIXTURES_FILES_DIRS``.
"""
matches = []
for prefix, root in self.locations:
if root not in searched_locations:
searched_locations.append(root)
matched_path = self.find_location(root, path, prefix)
if matched_path:
if not all:
return matched_path
matches.append(matched_path)
return matches |
def find_location(self, root, path, prefix=None):
"""
Finds a requested media file in a location, returning the found
absolute path (or ``None`` if no match).
"""
if prefix:
prefix = '%s%s' % (prefix, os.sep)
if not path.startswith(prefix):
return None
path = path[len(prefix):]
path = safe_join(root, path)
if os.path.exists(path):
return path |
def list(self, ignore_patterns):
"""
List all files in all locations.
"""
for prefix, root in self.locations:
storage = self.storages[root]
for path in utils.get_files(storage, ignore_patterns):
yield path, storage |
def list(self, ignore_patterns):
"""
List all files in all app storages.
"""
for storage in six.itervalues(self.storages):
if storage.exists(''): # check if storage location exists
for path in utils.get_files(storage, ignore_patterns):
yield path, storage |
def find(self, path, all=False):
"""
Looks for files in the app directories.
"""
matches = []
for app in self.apps:
app_location = self.storages[app].location
if app_location not in searched_locations:
searched_locations.append(app_location)
match = self.find_in_app(app, path)
if match:
if not all:
return match
matches.append(match)
return matches |
def find_in_app(self, app, path):
"""
Find a requested media file in an app's media fixtures locations.
"""
storage = self.storages.get(app, None)
if storage:
# only try to find a file if the source dir actually exists
if storage.exists(path):
matched_path = storage.path(path)
if matched_path:
return matched_path |
def set_options(self, **options):
"""
Set instance variables based on an options dict
"""
self.interactive = options['interactive']
self.verbosity = options['verbosity']
self.symlink = options['link']
self.clear = options['clear']
self.dry_run = options['dry_run']
ignore_patterns = options['ignore_patterns']
if options['use_default_ignore_patterns']:
ignore_patterns += ['CVS', '.*', '*~']
self.ignore_patterns = list(set(ignore_patterns))
self.post_process = options['post_process'] |
def collect(self):
"""
Perform the bulk of the work of collectmedia.
Split off from handle() to facilitate testing.
"""
if self.symlink and not self.local:
raise CommandError("Can't symlink to a remote destination.")
if self.clear:
self.clear_dir('')
if self.symlink:
handler = self.link_file
else:
handler = self.copy_file
found_files = OrderedDict()
for finder in get_finders():
for path, storage in finder.list(self.ignore_patterns):
# Prefix the relative path if the source storage contains it
if getattr(storage, 'prefix', None):
prefixed_path = os.path.join(storage.prefix, path)
else:
prefixed_path = path
if prefixed_path not in found_files:
found_files[prefixed_path] = (storage, path)
handler(path, prefixed_path, storage)
# Here we check if the storage backend has a post_process
# method and pass it the list of modified files.
if self.post_process and hasattr(self.storage, 'post_process'):
processor = self.storage.post_process(found_files,
dry_run=self.dry_run)
for original_path, processed_path, processed in processor:
if isinstance(processed, Exception):
self.stderr.write("Post-processing '%s' failed!" % original_path)
# Add a blank line before the traceback, otherwise it's
# too easy to miss the relevant part of the error message.
self.stderr.write("")
raise processed
if processed:
self.log("Post-processed '%s' as '%s'" %
(original_path, processed_path), level=1)
self.post_processed_files.append(original_path)
else:
self.log("Skipped post-processing '%s'" % original_path)
return {
'modified': self.copied_files + self.symlinked_files,
'unmodified': self.unmodified_files,
'post_processed': self.post_processed_files,
} |
def clear_dir(self, path):
"""
Deletes the given relative path using the destination storage backend.
"""
dirs, files = self.storage.listdir(path)
for f in files:
fpath = os.path.join(path, f)
if self.dry_run:
self.log("Pretending to delete '%s'" %
smart_text(fpath), level=1)
else:
self.log("Deleting '%s'" % smart_text(fpath), level=1)
self.storage.delete(fpath)
for d in dirs:
self.clear_dir(os.path.join(path, d)) |
def delete_file(self, path, prefixed_path, source_storage):
"""
Checks if the target file should be deleted if it already exists
"""
if self.storage.exists(prefixed_path):
try:
# When was the target file modified last time?
target_last_modified = \
self.storage.modified_time(prefixed_path)
except (OSError, NotImplementedError, AttributeError):
# The storage doesn't support ``modified_time`` or failed
pass
else:
try:
# When was the source file modified last time?
source_last_modified = source_storage.modified_time(path)
except (OSError, NotImplementedError, AttributeError):
pass
else:
# The full path of the target file
if self.local:
full_path = self.storage.path(prefixed_path)
else:
full_path = None
# Skip the file if the source file is younger
# Avoid sub-second precision (see #14665, #19540)
if (target_last_modified.replace(microsecond=0)
>= source_last_modified.replace(microsecond=0)):
if not ((self.symlink and full_path
and not os.path.islink(full_path)) or
(not self.symlink and full_path
and os.path.islink(full_path))):
if prefixed_path not in self.unmodified_files:
self.unmodified_files.append(prefixed_path)
self.log("Skipping '%s' (not modified)" % path)
return False
# Then delete the existing file if really needed
if self.dry_run:
self.log("Pretending to delete '%s'" % path)
else:
self.log("Deleting '%s'" % path)
self.storage.delete(prefixed_path)
return True |
def link_file(self, path, prefixed_path, source_storage):
"""
Attempt to link ``path``
"""
# Skip this file if it was already copied earlier
if prefixed_path in self.symlinked_files:
return self.log("Skipping '%s' (already linked earlier)" % path)
# Delete the target file if needed or break
if not self.delete_file(path, prefixed_path, source_storage):
return
# The full path of the source file
source_path = source_storage.path(path)
# Finally link the file
if self.dry_run:
self.log("Pretending to link '%s'" % source_path, level=1)
else:
self.log("Linking '%s'" % source_path, level=1)
full_path = self.storage.path(prefixed_path)
try:
os.makedirs(os.path.dirname(full_path))
except OSError:
pass
try:
if os.path.lexists(full_path):
os.unlink(full_path)
os.symlink(source_path, full_path)
except AttributeError:
import platform
raise CommandError("Symlinking is not supported by Python %s." %
platform.python_version())
except NotImplementedError:
import platform
raise CommandError("Symlinking is not supported in this "
"platform (%s)." % platform.platform())
except OSError as e:
raise CommandError(e)
if prefixed_path not in self.symlinked_files:
self.symlinked_files.append(prefixed_path) |
def copy_file(self, path, prefixed_path, source_storage):
"""
Attempt to copy ``path`` with storage
"""
# Skip this file if it was already copied earlier
if prefixed_path in self.copied_files:
return self.log("Skipping '%s' (already copied earlier)" % path)
# Delete the target file if needed or break
if not self.delete_file(path, prefixed_path, source_storage):
return
# The full path of the source file
source_path = source_storage.path(path)
# Finally start copying
if self.dry_run:
self.log("Pretending to copy '%s'" % source_path, level=1)
else:
self.log("Copying '%s'" % source_path, level=1)
with source_storage.open(path) as source_file:
self.storage.save(prefixed_path, source_file)
self.copied_files.append(prefixed_path) |
def reorderChild(self, parent, newitem):
"""Reorder a list to match target by moving a sequence at a time.
Written for QtAbstractItemModel.moveRows.
"""
source = self.getItem(parent).childItems
target = newitem.childItems
i = 0
while i < len(source):
if source[i] == target[i]:
i += 1
continue
else:
i0 = i
j0 = source.index(target[i0])
j = j0 + 1
while j < len(source):
if source[j] == target[j - j0 + i0]:
j += 1
continue
else:
break
self.moveRows(parent, i0, j0, j - j0)
i += j - j0 |
def moveRows(self, parent, index_to, index_from, length):
"""Move a sub sequence in a list
index_to must be smaller than index_from
"""
source = self.getItem(parent).childItems
self.beginMoveRows(
parent, index_from, index_from + length - 1, parent, index_to
)
sublist = [source.pop(index_from) for _ in range(length)]
for _ in range(length):
source.insert(index_to, sublist.pop())
self.endMoveRows() |
def cur_space(self, name=None):
"""Set the current space to Space ``name`` and return it.
If called without arguments, the current space is returned.
Otherwise, the current space is set to the space named ``name``
and the space is returned.
"""
if name is None:
return self._impl.model.currentspace.interface
else:
self._impl.model.currentspace = self._impl.spaces[name]
return self.cur_space() |
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = super()._baseattrs
result["spaces"] = self.spaces._baseattrs
return result |
def new_space(self, name=None, bases=None, formula=None, refs=None):
"""Create a child space.
Args:
name (str, optional): Name of the space. Defaults to ``SpaceN``,
where ``N`` is a number determined automatically.
bases (optional): A space or a sequence of spaces to be the base
space(s) of the created space.
formula (optional): Function to specify the parameters of
dynamic child spaces. The signature of this function is used
for setting parameters for dynamic child spaces.
This function should return a mapping of keyword arguments
to be passed to this method when the dynamic child spaces
are created.
Returns:
The new child space.
"""
space = self._impl.model.currentspace = self._impl.new_space(
name=name, bases=get_impls(bases), formula=formula, refs=refs
)
return space.interface |
def import_module(self, module=None, recursive=False, **params):
"""Create a child space from an module.
Args:
module: a module object or name of the module object.
recursive: Not yet implemented.
**params: arguments to pass to ``new_space``
Returns:
The new child space created from the module.
"""
if module is None:
if "module_" in params:
warnings.warn(
"Parameter 'module_' is deprecated. Use 'module' instead.")
module = params.pop("module_")
else:
raise ValueError("no module specified")
if "bases" in params:
params["bases"] = get_impls(params["bases"])
space = (
self._impl.model.currentspace
) = self._impl.new_space_from_module(
module, recursive=recursive, **params
)
return get_interfaces(space) |
def new_space_from_module(self, module, recursive=False, **params):
"""Create a child space from an module.
Alias to :py:meth:`import_module`.
Args:
module: a module object or name of the module object.
recursive: Not yet implemented.
**params: arguments to pass to ``new_space``
Returns:
The new child space created from the module.
"""
if "bases" in params:
params["bases"] = get_impls(params["bases"])
space = (
self._impl.model.currentspace
) = self._impl.new_space_from_module(
module, recursive=recursive, **params
)
return get_interfaces(space) |
def new_space_from_excel(
self,
book,
range_,
sheet=None,
name=None,
names_row=None,
param_cols=None,
space_param_order=None,
cells_param_order=None,
transpose=False,
names_col=None,
param_rows=None,
):
"""Create a child space from an Excel range.
To use this method, ``openpyxl`` package must be installed.
Args:
book (str): Path to an Excel file.
range_ (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1".
sheet (str): Sheet name (case ignored).
name (str, optional): Name of the space. Defaults to ``SpaceN``,
where ``N`` is a number determined automatically.
names_row (optional): an index number indicating
what row contains the names of cells and parameters.
Defaults to the top row (0).
param_cols (optional): a sequence of index numbers
indicating parameter columns.
Defaults to only the leftmost column ([0]).
names_col (optional): an index number, starting from 0,
indicating what column contains additional parameters.
param_rows (optional): a sequence of index numbers, starting from
0, indicating rows of additional parameters, in case cells are
defined in two dimensions.
transpose (optional): Defaults to ``False``.
If set to ``True``, "row(s)" and "col(s)" in the parameter
names are interpreted inversely, i.e.
all indexes passed to "row(s)" parameters are interpreted
as column indexes,
and all indexes passed to "col(s)" parameters as row indexes.
space_param_order: a sequence to specify space parameters and
their orders. The elements of the sequence denote the indexes
of ``param_cols`` elements, and optionally the index of
``param_rows`` elements shifted by the length of
``param_cols``. The elements of this parameter and
``cell_param_order`` must not overlap.
cell_param_order (optional): a sequence to reorder the parameters.
The elements of the sequence denote the indexes of
``param_cols`` elements, and optionally the index of
``param_rows`` elements shifted by the length of
``param_cols``. The elements of this parameter and
``cell_space_order`` must not overlap.
Returns:
The new child space created from the Excel range.
"""
space = self._impl.new_space_from_excel(
book,
range_,
sheet,
name,
names_row,
param_cols,
space_param_order,
cells_param_order,
transpose,
names_col,
param_rows,
)
return get_interfaces(space) |
def restore_state(self, system):
"""Called after unpickling to restore some attributes manually."""
for space in self._spaces.values():
space.restore_state(system) |
def new_space(
self,
name=None,
bases=None,
formula=None,
*,
refs=None,
source=None,
is_derived=False,
prefix=""
):
"""Create a new child space.
Args:
name (str): Name of the space. If omitted, the space is
created automatically.
bases: If specified, the new space becomes a derived space of
the `base` space.
formula: Function whose parameters used to set space parameters.
refs: a mapping of refs to be added.
arguments: ordered dict of space parameter names to their values.
source: A source module from which cell definitions are read.
prefix: Prefix to the autogenerated name when name is None.
"""
from modelx.core.space import StaticSpaceImpl
if name is None:
name = self.spacenamer.get_next(self.namespace, prefix)
if name in self.namespace:
raise ValueError("Name '%s' already exists." % name)
if not prefix and not is_valid_name(name):
raise ValueError("Invalid name '%s'." % name)
space = self._new_space(
name=name,
formula=formula,
refs=refs,
source=source,
is_derived=is_derived,
)
self._set_space(space)
self.model.spacegraph.add_space(space)
# Set up direct base spaces and mro
if bases is not None:
if isinstance(bases, StaticSpaceImpl):
bases = [bases]
space.add_bases(bases)
return space |
def get_node(obj, args, kwargs):
"""Create a node from arguments and return it"""
if args is None and kwargs is None:
return (obj,)
if kwargs is None:
kwargs = {}
return obj, _bind_args(obj, args, kwargs) |
def node_get_args(node):
"""Return an ordered mapping from params to args"""
obj = node[OBJ]
key = node[KEY]
boundargs = obj.formula.signature.bind(*key)
boundargs.apply_defaults()
return boundargs.arguments |
def tuplize_key(obj, key, remove_extra=False):
"""Args"""
paramlen = len(obj.formula.parameters)
if isinstance(key, str):
key = (key,)
elif not isinstance(key, Sequence):
key = (key,)
if not remove_extra:
return key
else:
arglen = len(key)
if arglen:
return key[: min(arglen, paramlen)]
else:
return key |
def defcells(space=None, name=None, *funcs):
"""Decorator/function to create cells from Python functions.
Convenience decorator/function to create new cells directly from function
definitions or function objects substituting for calling
:py:meth:`new_cells <modelx.core.space.StaticSpace.new_cells>`
method of the parent space.
There are 3 ways to use ``defcells`` to define cells from functions.
**1. As a decorator without arguments**
To create a cells from a function definition in the current space of the
current model with the same name as the function's::
@defcells
def foo(x):
return x
**2. As a decorator with arguments**
To create a cells from a function definition in a given space and/or with
a given name::
@defcells(space=space, name=name)
def foo(x):
return x
**3. As a function**
To create a multiple cells from a multiple function definitions::
def foo(x):
return x
def bar(y):
return foo(y)
foo, bar = defcells(foo, bar)
Args:
space(optional): For the 2nd usage, a space to create the cells in.
Defaults to the current space of the current model.
name(optional): For the 2nd usage, a name of the created cells.
Defaults to the function name.
*funcs: For the 3rd usage, function objects. (``space`` and ``name``
also take function objects for the 3rd usage.)
Returns:
For the 1st and 2nd usage, the newly created single cells is returned.
For the 3rd usage, a list of newly created cells are returned.
"""
if isinstance(space, _FunctionType) and name is None:
# called as a function decorator
func = space
return _system.currentspace.new_cells(formula=func).interface
elif (isinstance(space, _Space) or space is None) and (
isinstance(name, str) or name is None
):
# return decorator itself
if space is None:
space = _system.currentspace.interface
return _CellsMaker(space=space._impl, name=name)
elif all(
isinstance(func, _FunctionType) for func in (space, name) + funcs
):
return [defcells(func) for func in (space, name) + funcs]
else:
raise TypeError("invalid defcells arguments") |
def get_object(name: str):
"""Get a modelx object from its full name."""
# TODO: Duplicate of system.get_object
elms = name.split(".")
parent = get_models()[elms.pop(0)]
while len(elms) > 0:
obj = elms.pop(0)
parent = getattr(parent, obj)
return parent |
def _get_node(name: str, args: str):
"""Get node from object name and arg string
Not Used. Left for future reference purpose.
"""
obj = get_object(name)
args = ast.literal_eval(args)
if not isinstance(args, tuple):
args = (args,)
return obj.node(*args) |
def cur_model(model=None):
"""Get and/or set the current model.
If ``model`` is given, set the current model to ``model`` and return it.
``model`` can be the name of a model object, or a model object itself.
If ``model`` is not given, the current model is returned.
"""
if model is None:
if _system.currentmodel is not None:
return _system.currentmodel.interface
else:
return None
else:
if isinstance(model, _Model):
_system.currentmodel = model._impl
else:
_system.currentmodel = _system.models[model]
return _system.currentmodel.interface |
def cur_space(space=None):
"""Get and/or set the current space of the current model.
If ``name`` is given, the current space of the current model is
set to ``name`` and return it.
If ``name`` is not given, the current space of the current model
is returned.
"""
if space is None:
if _system.currentmodel is not None:
if _system.currentmodel.currentspace is not None:
return _system.currentmodel.currentspace.interface
else:
return None
else:
return None
else:
if isinstance(space, _Space):
cur_model(space.model)
_system.currentmodel.currentspace = space._impl
else:
_system.currentmodel.currentspace = _system.currentmodel.spaces[
space
]
return cur_space() |
def custom_showwarning(
message, category, filename="", lineno=-1, file=None, line=None
):
"""Hook to override default showwarning.
https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings
"""
if file is None:
file = sys.stderr
if file is None:
# sys.stderr is None when run with pythonw.exe:
# warnings get lost
return
text = "%s: %s\n" % (category.__name__, message)
try:
file.write(text)
except OSError:
# the file (probably stderr) is invalid - this warning gets lost.
pass |
def custom_showtraceback(
self,
exc_tuple=None,
filename=None,
tb_offset=None,
exception_only=False,
running_compiled_code=False,
):
"""Custom showtraceback for monkey-patching IPython's InteractiveShell
https://stackoverflow.com/questions/1261668/cannot-override-sys-excepthook
"""
self.default_showtraceback(
exc_tuple,
filename,
tb_offset,
exception_only=True,
running_compiled_code=running_compiled_code,
) |
def excepthook(self, except_type, exception, traceback):
"""Not Used: Custom exception hook to replace sys.excepthook
This is for CPython's default shell. IPython does not use sys.exepthook.
https://stackoverflow.com/questions/27674602/hide-traceback-unless-a-debug-flag-is-set
"""
if except_type is DeepReferenceError:
print(exception.msg)
else:
self.default_excepthook(except_type, exception, traceback) |
def tracemessage(self, maxlen=6):
"""
if maxlen > 0, the message is shortened to maxlen traces.
"""
result = ""
for i, value in enumerate(self):
result += "{0}: {1}\n".format(i, get_node_repr(value))
result = result.strip("\n")
lines = result.split("\n")
if maxlen and len(lines) > maxlen:
i = int(maxlen / 2)
lines = lines[:i] + ["..."] + lines[-(maxlen - i) :]
result = "\n".join(lines)
return result |
def setup_ipython(self):
"""Monkey patch shell's error handler.
This method is to monkey-patch the showtraceback method of
IPython's InteractiveShell to
__IPYTHON__ is not detected when starting an IPython kernel,
so this method is called from start_kernel in spyder-modelx.
"""
if self.is_ipysetup:
return
from ipykernel.kernelapp import IPKernelApp
self.shell = IPKernelApp.instance().shell # None in PyCharm console
if not self.shell and is_ipython():
self.shell = get_ipython()
if self.shell:
shell_class = type(self.shell)
shell_class.default_showtraceback = shell_class.showtraceback
shell_class.showtraceback = custom_showtraceback
self.is_ipysetup = True
else:
raise RuntimeError("IPython shell not found.") |
def restore_ipython(self):
"""Restore default IPython showtraceback"""
if not self.is_ipysetup:
return
shell_class = type(self.shell)
shell_class.showtraceback = shell_class.default_showtraceback
del shell_class.default_showtraceback
self.is_ipysetup = False |
def restore_python(self):
"""Restore Python settings to the original states"""
orig = self.orig_settings
sys.setrecursionlimit(orig["sys.recursionlimit"])
if "sys.tracebacklimit" in orig:
sys.tracebacklimit = orig["sys.tracebacklimit"]
else:
if hasattr(sys, "tracebacklimit"):
del sys.tracebacklimit
if "showwarning" in orig:
warnings.showwarning = orig["showwarning"]
orig.clear()
threading.stack_size() |
def get_object(self, name):
"""Retrieve an object by its absolute name."""
parts = name.split(".")
model_name = parts.pop(0)
return self.models[model_name].get_object(".".join(parts)) |
def get_modeltree(model=None):
"""Alias to :func:`get_tree`."""
if model is None:
model = mx.cur_model()
treemodel = ModelTreeModel(model._baseattrs)
view = QTreeView()
view.setModel(treemodel)
view.setWindowTitle("Model %s" % model.name)
view.setAlternatingRowColors(True)
return view |
def show_tree(model=None):
"""Display the model tree window.
Args:
model: :class:`Model <modelx.core.model.Model>` object.
Defaults to the current model.
Warnings:
For this function to work with Spyder, *Graphics backend* option
of Spyder must be set to *inline*.
"""
if model is None:
model = mx.cur_model()
view = get_modeltree(model)
app = QApplication.instance()
if not app:
raise RuntimeError("QApplication does not exist.")
view.show()
app.exec_() |
def get_interfaces(impls):
"""Get interfaces from their implementations."""
if impls is None:
return None
elif isinstance(impls, OrderMixin):
result = OrderedDict()
for name in impls.order:
result[name] = impls[name].interface
return result
elif isinstance(impls, Mapping):
return {name: impls[name].interface for name in impls}
elif isinstance(impls, Sequence):
return [impl.interface for impl in impls]
else:
return impls.interface |
def get_impls(interfaces):
"""Get impls from their interfaces."""
if interfaces is None:
return None
elif isinstance(interfaces, Mapping):
return {name: interfaces[name]._impl for name in interfaces}
elif isinstance(interfaces, Sequence):
return [interfaces._impl for interfaces in interfaces]
else:
return interfaces._impl |
def update_lazyevals(self):
"""Update all LazyEvals in self
self.lzy_evals must be set to LazyEval object(s) enough to
update all owned LazyEval objects.
"""
if self.lazy_evals is None:
return
elif isinstance(self.lazy_evals, LazyEval):
self.lazy_evals.get_updated()
else:
for lz in self.lazy_evals:
lz.get_updated() |
def evalrepr(self):
"""Evaluable repr"""
if self.is_model():
return self.get_fullname()
else:
return self.parent.evalrepr + "." + self.name |
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = {
"type": type(self).__name__,
"id": id(self),
"name": self.name,
"fullname": self.fullname,
"repr": self._get_repr(),
}
return result |
def _to_attrdict(self, attrs=None):
"""Get extra attributes"""
result = self._baseattrs
for attr in attrs:
if hasattr(self, attr):
result[attr] = getattr(self, attr)._to_attrdict(attrs)
return result |
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = {"type": type(self).__name__}
try:
result["items"] = {
name: item._baseattrs
for name, item in self.items()
if name[0] != "_"
}
except:
raise RuntimeError("%s literadict raised an error" % self)
return result |
def _update_data(self):
"""Update altfunc"""
func = self.owner.formula.func
codeobj = func.__code__
name = func.__name__ # self.cells.name # func.__name__
namespace_impl = self.owner._namespace_impl.get_updated()
namespace = namespace_impl.interfaces
selfnode = get_node(self.owner, None, None)
for name in self.owner.formula.srcnames:
if name in namespace_impl and isinstance(
namespace_impl[name], ReferenceImpl
):
refnode = get_node(namespace_impl[name], None, None)
self.owner.model.lexdep.add_path([selfnode, refnode])
closure = func.__closure__ # None normally.
if closure is not None: # pytest fails without this.
closure = create_closure(self.owner.interface)
self.altfunc = FunctionType(
codeobj, namespace, name=name, closure=closure
) |
def convert_args(args, kwargs):
"""If args and kwargs contains Cells, Convert them to their values."""
found = False
for arg in args:
if isinstance(arg, Cells):
found = True
break
if found:
args = tuple(
arg.value if isinstance(arg, Cells) else arg for arg in args
)
if kwargs is not None:
for key, arg in kwargs.items():
if isinstance(arg, Cells):
kwargs[key] = arg.value
return args, kwargs |
def shareable_parameters(cells):
"""Return parameter names if the parameters are shareable among cells.
Parameters are shareable among multiple cells when all the cells
have the parameters in the same order if they ever have any.
For example, if cells are foo(), bar(x), baz(x, y), then
('x', 'y') are shareable parameters amounts them, as 'x' and 'y'
appear in the same order in the parameter list if they ever appear.
Args:
cells: An iterator yielding cells.
Returns:
None if parameters are not share,
tuple of shareable parameter names,
() if cells are all scalars.
"""
result = []
for c in cells.values():
params = c.formula.parameters
for i in range(min(len(result), len(params))):
if params[i] != result[i]:
return None
for i in range(len(result), len(params)):
result.append(params[i])
return result |
def copy(self, space=None, name=None):
"""Make a copy of itself and return it."""
return Cells(space=space, name=name, formula=self.formula) |
def node(self, *args, **kwargs):
"""Return a :class:`CellNode` object for the given arguments."""
return CellNode(get_node(self._impl, *convert_args(args, kwargs))) |
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = super()._baseattrs
result["params"] = ", ".join(self.parameters)
return result |
def value(self):
"""Return the value of the cells."""
if self.has_value:
return self._impl[OBJ].get_value(self._impl[KEY])
else:
raise ValueError("Value not found") |
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = {
"type": type(self).__name__,
"obj": self.cells._baseattrs,
"args": self.args,
"value": self.value if self.has_value else None,
"predslen": len(self.preds),
"succslen": len(self.succs),
"repr_parent": self.cells._impl.repr_parent(),
"repr": self.cells._get_repr(),
}
return result |
def reorder_list(source, targetorder):
"""Reorder a list to match target by moving a sequence at a time.
Written for QtAbstractItemModel.moveRows.
"""
i = 0
while i < len(source):
if source[i] == targetorder[i]:
i += 1
continue
else:
i0 = i
j0 = source.index(targetorder[i0])
j = j0 + 1
while j < len(source):
if source[j] == targetorder[j - j0 + i0]:
j += 1
continue
else:
break
move_elements(source, i0, j0, j - j0)
i += j - j0 |
def move_elements(source, index_to, index_from, length):
"""Move a sub sequence in a list"""
sublist = [source.pop(index_from) for _ in range(length)]
for _ in range(length):
source.insert(index_to, sublist.pop()) |
def _get_col_index(name):
"""Convert column name to index."""
index = string.ascii_uppercase.index
col = 0
for c in name.upper():
col = col * 26 + index(c) + 1
return col |
def _get_range(book, range_, sheet):
"""Return a range as nested dict of openpyxl cells."""
filename = None
if isinstance(book, str):
filename = book
book = opxl.load_workbook(book, data_only=True)
elif isinstance(book, opxl.Workbook):
pass
else:
raise TypeError
if _is_range_address(range_):
sheet_names = [name.upper() for name in book.sheetnames]
index = sheet_names.index(sheet.upper())
data = book.worksheets[index][range_]
else:
data = _get_namedrange(book, range_, sheet)
if data is None:
raise ValueError(
"Named range '%s' not found in %s" % (range_, filename or book)
)
return data |
def read_range(filepath, range_expr, sheet=None, dict_generator=None):
"""Read values from an Excel range into a dictionary.
`range_expr` ie either a range address string, such as "A1", "$C$3:$E$5",
or a defined name string for a range, such as "NamedRange1".
If a range address is provided, `sheet` argument must also be provided.
If a named range is provided and `sheet` is not, book level defined name
is searched. If `sheet` is also provided, sheet level defined name for the
specified `sheet` is searched.
If range_expr points to a single cell, its value is returned.
`dictgenerator` is a generator function that yields keys and values of
the returned dictionary. the excel range, as a nested tuple of openpyxl's
Cell objects, is passed to the generator function as its single argument.
If not specified, default generator is used, which maps tuples of row and
column indexes, both starting with 0, to their values.
Args:
filepath (str): Path to an Excel file.
range_epxr (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1"
sheet (str): Sheet name (case ignored).
None if book level defined range name is passed as `range_epxr`.
dict_generator: A generator function taking a nested tuple of cells
as a single parameter.
Returns:
Nested list containing range values.
"""
def default_generator(cells):
for row_ind, row in enumerate(cells):
for col_ind, cell in enumerate(row):
yield (row_ind, col_ind), cell.value
book = opxl.load_workbook(filepath, data_only=True)
if _is_range_address(range_expr):
sheet_names = [name.upper() for name in book.sheetnames]
index = sheet_names.index(sheet.upper())
cells = book.worksheets[index][range_expr]
else:
cells = _get_namedrange(book, range_expr, sheet)
# In case of a single cell, return its value.
if isinstance(cells, opxl.cell.Cell):
return cells.value
if dict_generator is None:
dict_generator = default_generator
gen = dict_generator(cells)
return {keyval[0]: keyval[1] for keyval in gen} |
def _get_namedrange(book, rangename, sheetname=None):
"""Get range from a workbook.
A workbook can contain multiple definitions for a single name,
as a name can be defined for the entire book or for
a particular sheet.
If sheet is None, the book-wide def is searched,
otherwise sheet-local def is looked up.
Args:
book: An openpyxl workbook object.
rangename (str): Range expression, such as "A1", "$G4:$K10",
named range "NamedRange1".
sheetname (str, optional): None for book-wide name def,
sheet name for sheet-local named range.
Returns:
Range object specified by the name.
"""
def cond(namedef):
if namedef.type.upper() == "RANGE":
if namedef.name.upper() == rangename.upper():
if sheetname is None:
if not namedef.localSheetId:
return True
else: # sheet local name
sheet_id = [sht.upper() for sht in book.sheetnames].index(
sheetname.upper()
)
if namedef.localSheetId == sheet_id:
return True
return False
def get_destinations(name_def):
"""Workaround for the bug in DefinedName.destinations"""
from openpyxl.formula import Tokenizer
from openpyxl.utils.cell import SHEETRANGE_RE
if name_def.type == "RANGE":
tok = Tokenizer("=" + name_def.value)
for part in tok.items:
if part.subtype == "RANGE":
m = SHEETRANGE_RE.match(part.value)
if m.group("quoted"):
sheet_name = m.group("quoted")
else:
sheet_name = m.group("notquoted")
yield sheet_name, m.group("cells")
namedef = next(
(item for item in book.defined_names.definedName if cond(item)), None
)
if namedef is None:
return None
dests = get_destinations(namedef)
xlranges = []
sheetnames_upper = [name.upper() for name in book.sheetnames]
for sht, addr in dests:
if sheetname:
sht = sheetname
index = sheetnames_upper.index(sht.upper())
xlranges.append(book.worksheets[index][addr])
if len(xlranges) == 1:
return xlranges[0]
else:
return xlranges |
def get_mro(self, space):
"""Calculate the Method Resolution Order of bases using the C3 algorithm.
Code modified from
http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/
Args:
bases: sequence of direct base spaces.
Returns:
mro as a list of bases including node itself
"""
seqs = [self.get_mro(base) for base
in self.get_bases(space)] + [list(self.get_bases(space))]
res = []
while True:
non_empty = list(filter(None, seqs))
if not non_empty:
# Nothing left to process, we're done.
res.insert(0, space)
return res
for seq in non_empty: # Find merge candidates among seq heads.
candidate = seq[0]
not_head = [s for s in non_empty if candidate in s[1:]]
if not_head:
# Reject the candidate.
candidate = None
else:
break
if not candidate:
raise TypeError(
"inconsistent hierarchy, no C3 MRO is possible")
res.append(candidate)
for seq in non_empty:
# Remove candidate.
if seq[0] == candidate:
del seq[0] |
def _alter_code(code, **attrs):
"""Create a new code object by altering some of ``code`` attributes
Args:
code: code objcect
attrs: a mapping of names of code object attrs to their values
"""
PyCode_New = ctypes.pythonapi.PyCode_New
PyCode_New.argtypes = (
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.py_object,
ctypes.c_int,
ctypes.py_object)
PyCode_New.restype = ctypes.py_object
args = [
[code.co_argcount, 'co_argcount'],
[code.co_kwonlyargcount, 'co_kwonlyargcount'],
[code.co_nlocals, 'co_nlocals'],
[code.co_stacksize, 'co_stacksize'],
[code.co_flags, 'co_flags'],
[code.co_code, 'co_code'],
[code.co_consts, 'co_consts'],
[code.co_names, 'co_names'],
[code.co_varnames, 'co_varnames'],
[code.co_freevars, 'co_freevars'],
[code.co_cellvars, 'co_cellvars'],
[code.co_filename, 'co_filename'],
[code.co_name, 'co_name'],
[code.co_firstlineno, 'co_firstlineno'],
[code.co_lnotab, 'co_lnotab']]
for arg in args:
if arg[1] in attrs:
arg[0] = attrs[arg[1]]
return PyCode_New(
args[0][0], # code.co_argcount,
args[1][0], # code.co_kwonlyargcount,
args[2][0], # code.co_nlocals,
args[3][0], # code.co_stacksize,
args[4][0], # code.co_flags,
args[5][0], # code.co_code,
args[6][0], # code.co_consts,
args[7][0], # code.co_names,
args[8][0], # code.co_varnames,
args[9][0], # code.co_freevars,
args[10][0], # code.co_cellvars,
args[11][0], # code.co_filename,
args[12][0], # code.co_name,
args[13][0], # code.co_firstlineno,
args[14][0]) |
def alter_freevars(func, globals_=None, **vars):
"""Replace local variables with free variables
Warnings:
This function does not work.
"""
if globals_ is None:
globals_ = func.__globals__
frees = tuple(vars.keys())
oldlocs = func.__code__.co_names
newlocs = tuple(name for name in oldlocs if name not in frees)
code = _alter_code(func.__code__,
co_freevars=frees,
co_names=newlocs,
co_flags=func.__code__.co_flags | inspect.CO_NESTED)
closure = _create_closure(*vars.values())
return FunctionType(code, globals_, closure=closure) |
def fix_lamdaline(source):
"""Remove the last redundant token from lambda expression
lambda x: return x)
^
Return string without irrelevant tokens
returned from inspect.getsource on lamda expr returns
"""
# Using undocumented generate_tokens due to a tokenize.tokenize bug
# See https://bugs.python.org/issue23297
strio = io.StringIO(source)
gen = tokenize.generate_tokens(strio.readline)
tkns = []
try:
for t in gen:
tkns.append(t)
except tokenize.TokenError:
pass
# Find the position of 'lambda'
lambda_pos = [(t.type, t.string) for t in tkns].index(
(tokenize.NAME, "lambda")
)
# Ignore tokes before 'lambda'
tkns = tkns[lambda_pos:]
# Find the position of th las OP
lastop_pos = (
len(tkns) - 1 - [t.type for t in tkns[::-1]].index(tokenize.OP)
)
lastop = tkns[lastop_pos]
# Remove OP from the line
fiedlineno = lastop.start[0]
fixedline = lastop.line[: lastop.start[1]] + lastop.line[lastop.end[1] :]
tkns = tkns[:lastop_pos]
fixedlines = ""
last_lineno = 0
for t in tkns:
if last_lineno == t.start[0]:
continue
elif t.start[0] == fiedlineno:
fixedlines += fixedline
last_lineno = t.start[0]
else:
fixedlines += t.line
last_lineno = t.start[0]
return fixedlines |
def find_funcdef(source):
"""Find the first FuncDef ast object in source"""
try:
module_node = compile(
source, "<string>", mode="exec", flags=ast.PyCF_ONLY_AST
)
except SyntaxError:
return find_funcdef(fix_lamdaline(source))
for node in ast.walk(module_node):
if isinstance(node, ast.FunctionDef) or isinstance(node, ast.Lambda):
return node
raise ValueError("function definition not found") |
def extract_params(source):
"""Extract parameters from a function definition"""
funcdef = find_funcdef(source)
params = []
for node in ast.walk(funcdef.args):
if isinstance(node, ast.arg):
if node.arg not in params:
params.append(node.arg)
return params |
def extract_names(source):
"""Extract names from a function definition
Looks for a function definition in the source.
Only the first function definition is examined.
Returns:
a list names(identifiers) used in the body of the function
excluding function parameters.
"""
if source is None:
return None
source = dedent(source)
funcdef = find_funcdef(source)
params = extract_params(source)
names = []
if isinstance(funcdef, ast.FunctionDef):
stmts = funcdef.body
elif isinstance(funcdef, ast.Lambda):
stmts = [funcdef.body]
else:
raise ValueError("must not happen")
for stmt in stmts:
for node in ast.walk(stmt):
if isinstance(node, ast.Name):
if node.id not in names and node.id not in params:
names.append(node.id)
return names |
def is_funcdef(src):
"""True if src is a function definition"""
module_node = ast.parse(dedent(src))
if len(module_node.body) == 1 and isinstance(
module_node.body[0], ast.FunctionDef
):
return True
else:
return False |
def remove_decorator(source: str):
"""Remove decorators from function definition"""
lines = source.splitlines()
atok = asttokens.ASTTokens(source, parse=True)
for node in ast.walk(atok.tree):
if isinstance(node, ast.FunctionDef):
break
if node.decorator_list:
deco_first = node.decorator_list[0]
deco_last = node.decorator_list[-1]
line_first = atok.tokens[deco_first.first_token.index - 1].start[0]
line_last = atok.tokens[deco_last.last_token.index + 1].start[0]
lines = lines[:line_first - 1] + lines[line_last:]
return "\n".join(lines) + "\n" |
def replace_funcname(source: str, name: str):
"""Replace function name"""
lines = source.splitlines()
atok = asttokens.ASTTokens(source, parse=True)
for node in ast.walk(atok.tree):
if isinstance(node, ast.FunctionDef):
break
i = node.first_token.index
for i in range(node.first_token.index, node.last_token.index):
if (atok.tokens[i].type == token.NAME
and atok.tokens[i].string == "def"):
break
lineno, col_begin = atok.tokens[i + 1].start
lineno_end, col_end = atok.tokens[i + 1].end
assert lineno == lineno_end
lines[lineno-1] = (
lines[lineno-1][:col_begin] + name + lines[lineno-1][col_end:]
)
return "\n".join(lines) + "\n" |
def has_lambda(src):
"""True if only one lambda expression is included"""
module_node = ast.parse(dedent(src))
lambdaexp = [node for node in ast.walk(module_node)
if isinstance(node, ast.Lambda)]
return bool(lambdaexp) |
def _reload(self, module=None):
"""Reload the source function from the source module.
**Internal use only**
Update the source function of the formula.
This method is used to updated the underlying formula
when the source code of the module in which the source function
is read from is modified.
If the formula was not created from a module, an error is raised.
If ``module_`` is not given, the source module of the formula is
reloaded. If ``module_`` is given and matches the source module,
then the module_ is used without being reloaded.
If ``module_`` is given and does not match the source module of
the formula, an error is raised.
Args:
module_: A ``ModuleSource`` object
Returns:
self
"""
if self.module is None:
raise RuntimeError
elif module is None:
import importlib
module = ModuleSource(importlib.reload(module))
elif module.name != self.module:
raise RuntimeError
if self.name in module.funcs:
func = module.funcs[self.name]
self.__init__(func=func)
else:
self.__init__(func=NULL_FORMULA)
return self |
def get_description():
"""Get long description from README."""
with open(path.join(here, 'README.rst'), 'r') as f:
data = f.read()
return data |
def to_frame(self, *args):
"""Convert the cells in the view into a DataFrame object.
If ``args`` is not given, this method returns a DataFrame that
has an Index or a MultiIndex depending of the number of
cells parameters and columns each of which corresponds to each
cells included in the view.
``args`` can be given to calculate cells values and limit the
DataFrame indexes to the given arguments.
The cells in this view may have different number of parameters,
but parameters shared among multiple cells
must appear in the same position in all the parameter lists.
For example,
Having ``foo()``, ``bar(x)`` and ``baz(x, y=1)`` is okay
because the shared parameter ``x`` is always the first parameter,
but this method does not work if the view has ``quz(x, z=2, y=1)``
cells in addition to the first three cells, because ``y`` appears
in different positions.
Args:
args(optional): multiple arguments,
or an iterator of arguments to the cells.
"""
if sys.version_info < (3, 6, 0):
from collections import OrderedDict
impls = OrderedDict()
for name, obj in self.items():
impls[name] = obj._impl
else:
impls = get_impls(self)
return _to_frame_inner(impls, args) |
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = super()._baseattrs
result["static_spaces"] = self.static_spaces._baseattrs
result["dynamic_spaces"] = self.dynamic_spaces._baseattrs
result["cells"] = self.cells._baseattrs
result["refs"] = self.refs._baseattrs
if self.has_params():
result["params"] = ", ".join(self.parameters)
else:
result["params"] = ""
return result |
def new_cells(self, name=None, formula=None):
"""Create a cells in the space.
Args:
name: If omitted, the model is named automatically ``CellsN``,
where ``N`` is an available number.
func: The function to define the formula of the cells.
Returns:
The new cells.
"""
# Outside formulas only
return self._impl.new_cells(name, formula).interface |
def import_funcs(self, module):
"""Create a cells from a module."""
# Outside formulas only
newcells = self._impl.new_cells_from_module(module)
return get_interfaces(newcells) |
def new_cells_from_excel(
self,
book,
range_,
sheet=None,
names_row=None,
param_cols=None,
param_order=None,
transpose=False,
names_col=None,
param_rows=None,
):
"""Create multiple cells from an Excel range.
This method reads values from a range in an Excel file,
create cells and populate them with the values in the range.
To use this method, ``openpyxl`` package must be installed.
The Excel file to read data from is specified by ``book``
parameters. The ``range_`` can be a range address, such as "$G4:$K10",
or a named range. In case a range address is given,
``sheet`` must also be given.
By default, cells data are interpreted as being laid out side-by-side.
``names_row`` is a row index (starting from 0) to specify the
row that contains the names of cells and parameters.
Cells and parameter names must be contained in a single row.
``param_cols`` accepts a sequence (such as list or tuple) of
column indexes (starting from 0) that indicate columns that
contain cells arguments.
**2-dimensional cells definitions**
The optional ``names_col`` and ``param_rows`` parameters are used,
when data for one cells spans more than one column.
In such cases, the cells data is 2-dimensional, and
there must be parameter row(s) across the columns
that contain arguments of the parameters.
A sequence of row indexes that indicate parameter rows
is passed to ``param_rows``.
The names of those parameters must be contained in the
same rows as parameter values (arguments), and
``names_col`` is to indicate the column position at which
the parameter names are defined.
**Horizontal arrangement**
By default, cells data are interpreted as being placed
side-by-side, regardless of whether one cells corresponds
to a single column or multiple columns.
``transpose`` parameter is used to alter this orientation,
and if it is set to ``True``, cells values are
interpreted as being placed one above the other.
"row(s)" and "col(s)" in the parameter
names are interpreted inversely, i.e.
all indexes passed to "row(s)" parameters are interpreted
as column indexes,
and all indexes passed to "col(s)" parameters as row indexes.
Args:
book (str): Path to an Excel file.
range_ (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1".
sheet (str): Sheet name (case ignored).
names_row (optional): an index number indicating
what row contains the names of cells and parameters.
Defaults to the top row (0).
param_cols (optional): a sequence of index numbers
indicating parameter columns.
Defaults to only the leftmost column ([0]).
names_col (optional): an index number, starting from 0,
indicating what column contains additional parameters.
param_rows (optional): a sequence of index numbers, starting from
0, indicating rows of additional parameters, in case cells are
defined in two dimensions.
transpose (optional): Defaults to ``False``.
If set to ``True``, "row(s)" and "col(s)" in the parameter
names are interpreted inversely, i.e.
all indexes passed to "row(s)" parameters are interpreted
as column indexes,
and all indexes passed to "col(s)" parameters as row indexes.
param_order (optional): a sequence to reorder the parameters.
The elements of the sequence are the indexes of ``param_cols``
elements, and optionally the index of ``param_rows`` elements
shifted by the length of ``param_cols``.
"""
return self._impl.new_cells_from_excel(
book,
range_,
sheet,
names_row,
param_cols,
param_order,
transpose,
names_col,
param_rows,
) |
def get_object(self, name):
"""Retrieve an object by a dotted name relative to the space."""
parts = name.split(".")
child = parts.pop(0)
if parts:
return self.spaces[child].get_object(".".join(parts))
else:
return self._namespace_impl[child] |
def _get_dynamic_base(self, bases_):
"""Create or get the base space from a list of spaces
if a direct base space in `bases` is dynamic, replace it with
its base.
"""
bases = tuple(
base.bases[0] if base.is_dynamic() else base for base in bases_
)
if len(bases) == 1:
return bases[0]
elif len(bases) > 1:
return self.model.get_dynamic_base(bases)
else:
RuntimeError("must not happen") |
def _new_dynspace(
self,
name=None,
bases=None,
formula=None,
refs=None,
arguments=None,
source=None,
):
"""Create a new dynamic root space."""
if name is None:
name = self.spacenamer.get_next(self.namespace)
if name in self.namespace:
raise ValueError("Name '%s' already exists." % name)
if not is_valid_name(name):
raise ValueError("Invalid name '%s'." % name)
space = RootDynamicSpaceImpl(
parent=self,
name=name,
formula=formula,
refs=refs,
source=source,
arguments=arguments,
)
space.is_derived = False
self._set_space(space)
if bases: # i.e. not []
dynbase = self._get_dynamic_base(bases)
space._dynbase = dynbase
dynbase._dynamic_subs.append(space)
return space |
def get_dynspace(self, args, kwargs=None):
"""Create a dynamic root space
Called from interface methods
"""
node = get_node(self, *convert_args(args, kwargs))
key = node[KEY]
if key in self.param_spaces:
return self.param_spaces[key]
else:
last_self = self.system.self
self.system.self = self
try:
space_args = self.eval_formula(node)
finally:
self.system.self = last_self
if space_args is None:
space_args = {"bases": [self]} # Default
else:
if "bases" in space_args:
bases = get_impls(space_args["bases"])
if isinstance(bases, StaticSpaceImpl):
space_args["bases"] = [bases]
elif bases is None:
space_args["bases"] = [self] # Default
else:
space_args["bases"] = bases
else:
space_args["bases"] = [self]
space_args["arguments"] = node_get_args(node)
space = self._new_dynspace(**space_args)
self.param_spaces[key] = space
space.inherit(clear_value=False)
return space |
def restore_state(self, system):
"""Called after unpickling to restore some attributes manually."""
super().restore_state(system)
BaseSpaceContainerImpl.restore_state(self, system)
for cells in self._cells.values():
cells.restore_state(system) |
def new_cells_from_excel(
self,
book,
range_,
sheet=None,
names_row=None,
param_cols=None,
param_order=None,
transpose=False,
names_col=None,
param_rows=None,
):
"""Create multiple cells from an Excel range.
Args:
book (str): Path to an Excel file.
range_ (str): Range expression, such as "A1", "$G4:$K10",
or named range "NamedRange1".
sheet (str): Sheet name (case ignored).
names_row: Cells names in a sequence, or an integer number, or
a string expression indicating row (or column depending on
```orientation```) to read cells names from.
param_cols: a sequence of them
indicating parameter columns (or rows depending on ```
orientation```)
param_order: a sequence of integers representing
the order of params and extra_params.
transpose: in which direction 'vertical' or 'horizontal'
names_col: a string or a list of names of the extra params.
param_rows: integer or string expression, or a sequence of them
indicating row (or column) to be interpreted as parameters.
"""
import modelx.io.excel as xl
cellstable = xl.CellsTable(
book,
range_,
sheet,
names_row,
param_cols,
param_order,
transpose,
names_col,
param_rows,
)
if cellstable.param_names:
sig = "=None, ".join(cellstable.param_names) + "=None"
else:
sig = ""
blank_func = "def _blank_func(" + sig + "): pass"
for cellsdata in cellstable.items():
cells = self.new_cells(name=cellsdata.name, formula=blank_func)
for args, value in cellsdata.items():
cells.set_value(args, value) |
def set_attr(self, name, value):
"""Implementation of attribute setting
``space.name = value`` by user script
Called from ``Space.__setattr__``
"""
if not is_valid_name(name):
raise ValueError("Invalid name '%s'" % name)
if name in self.namespace:
if name in self.refs:
if name in self.self_refs:
self.new_ref(name, value)
else:
raise KeyError("Ref '%s' cannot be changed" % name)
elif name in self.cells:
if self.cells[name].is_scalar():
self.cells[name].set_value((), value)
else:
raise AttributeError("Cells '%s' is not a scalar." % name)
else:
raise ValueError
else:
self.new_ref(name, value) |
def del_attr(self, name):
"""Implementation of attribute deletion
``del space.name`` by user script
Called from ``StaticSpace.__delattr__``
"""
if name in self.namespace:
if name in self.cells:
self.del_cells(name)
elif name in self.spaces:
self.del_space(name)
elif name in self.refs:
self.del_ref(name)
else:
raise RuntimeError("Must not happen")
else:
raise KeyError("'%s' not found in Space '%s'" % (name, self.name)) |
def del_space(self, name):
"""Delete a space."""
if name not in self.spaces:
raise ValueError("Space '%s' does not exist" % name)
if name in self.static_spaces:
space = self.static_spaces[name]
if space.is_derived:
raise ValueError(
"%s has derived spaces" % repr(space.interface)
)
else:
self.static_spaces.del_item(name)
self.model.spacegraph.remove_node(space)
self.inherit()
self.model.spacegraph.update_subspaces(self)
# TODO: Destroy space
elif name in self.dynamic_spaces:
# TODO: Destroy space
self.dynamic_spaces.del_item(name)
else:
raise ValueError("Derived cells cannot be deleted") |
def del_cells(self, name):
"""Implementation of cells deletion
``del space.name`` where name is a cells, or
``del space.cells['name']``
"""
if name in self.cells:
cells = self.cells[name]
self.cells.del_item(name)
self.inherit()
self.model.spacegraph.update_subspaces(self)
elif name in self.dynamic_spaces:
cells = self.dynamic_spaces.pop(name)
self.dynamic_spaces.set_update()
else:
raise KeyError("Cells '%s' does not exist" % name)
NullImpl(cells) |
def evalrepr(self):
"""Evaluable repr"""
args = [repr(arg) for arg in get_interfaces(self.argvalues)]
param = ", ".join(args)
return "%s(%s)" % (self.parent.evalrepr, param) |
def cellsiter_to_dataframe(cellsiter, args, drop_allna=True):
"""Convert multiple cells to a frame.
If args is an empty sequence, all values are included.
If args is specified, cellsiter must have shareable parameters.
Args:
cellsiter: A mapping from cells names to CellsImpl objects.
args: A sequence of arguments
"""
from modelx.core.cells import shareable_parameters
if len(args):
indexes = shareable_parameters(cellsiter)
else:
indexes = get_all_params(cellsiter.values())
result = None
for cells in cellsiter.values():
df = cells_to_dataframe(cells, args)
if drop_allna and df.isnull().all().all():
continue # Ignore all NA or empty
if df.index.names != [None]:
if isinstance(df.index, pd.MultiIndex):
if _pd_ver < (0, 20):
df = _reset_naindex(df)
df = df.reset_index()
missing_params = set(indexes) - set(df)
for params in missing_params:
df[params] = np.nan
if result is None:
result = df
else:
try:
result = pd.merge(result, df, how="outer")
except MergeError:
# When no common column exists, i.e. all cells are scalars.
result = pd.concat([result, df], axis=1)
except ValueError:
# When common columns are not coercible (numeric vs object),
# Make the numeric column object type
cols = set(result.columns) & set(df.columns)
for col in cols:
# When only either of them has object dtype
if (
len(
[
str(frame[col].dtype)
for frame in (result, df)
if str(frame[col].dtype) == "object"
]
)
== 1
):
if str(result[col].dtype) == "object":
frame = df
else:
frame = result
frame[[col]] = frame[col].astype("object")
# Try again
result = pd.merge(result, df, how="outer")
if result is None:
return pd.DataFrame()
else:
return result.set_index(indexes) if indexes else result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.