code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
plotters = self.plotters
if len(plotters) == 0:
return {}
p0 = plotters[0]
if len(plotters) == 1:
return p0._fmtos
return (getattr(p0, key) for key in set(p0).intersection(
*map(set, plotters[1:]))) | def _fmtos(self) | An iterator over formatoption objects
Contains only the formatoption whose keys are in all plotters in this
list | 4.352815 | 3.600284 | 1.20902 |
ret = utils.DefaultOrderedDict(lambda: self[1:0])
for arr in self:
if arr.psy.plotter is not None:
ret[arr.psy.plotter.ax.get_figure()].append(arr)
return OrderedDict(ret) | def figs(self) | A mapping from figures to data objects with the plotter in this
figure | 8.121238 | 7.119695 | 1.140672 |
ret = utils.DefaultOrderedDict(lambda: self[1:0])
for arr in self:
if arr.psy.plotter is not None:
ret[arr.psy.plotter.ax].append(arr)
return OrderedDict(ret) | def axes(self) | A mapping from axes to data objects with the plotter in this axes | 8.790481 | 7.291116 | 1.205643 |
if not self.is_main:
return self.main.logger
try:
return self._logger
except AttributeError:
name = '%s.%s.%s' % (self.__module__, self.__class__.__name__,
self.num)
self._logger = logging.getLogger(name)
... | def logger(self) | :class:`logging.Logger` of this instance | 3.578938 | 3.397047 | 1.053544 |
return {key: val['ds'] for key, val in six.iteritems(
self._get_ds_descriptions(self.array_info(ds_description=['ds'])))} | def datasets(self) | A mapping from dataset numbers to datasets in this list | 15.56643 | 14.762096 | 1.054486 |
if plotter_cls is not None: # plotter has already been imported
def get_x(self):
return self(plotter_cls)
else:
def get_x(self):
return self(getattr(import_module(module), plotter_name))
setattr(cls, identifier, property(get_x, do... | def _register_plotter(cls, identifier, module, plotter_name,
plotter_cls=None) | Register a plotter in the :class:`Project` class to easy access it
Parameters
----------
identifier: str
Name of the attribute that is used to filter for the instances
belonging to this plotter
module: str
The module from where to import the `plotter_... | 4.126655 | 4.558956 | 0.905175 |
for arr in self:
if arr.psy.plotter:
arr.psy.plotter.disabled = True | def disable(self) | Disables the plotters in this list | 15.578444 | 9.935454 | 1.567965 |
import matplotlib.pyplot as plt
close_ds = ds
for arr in self[:]:
if figs and arr.psy.plotter is not None:
if remove_only:
for fmto in arr.psy.plotter._fmtos:
try:
fmto.remove()
... | def close(self, figs=True, data=False, ds=False, remove_only=False) | Close this project instance
Parameters
----------
figs: bool
Close the figures
data: bool
delete the arrays from the (main) project
ds: bool
If True, close the dataset as well
remove_only: bool
If True and `figs` is True, t... | 5.595933 | 5.639352 | 0.992301 |
if enhanced:
all_attrs = [
plotter.get_enhanced_attrs(
getattr(plotter, 'plot_data' if plot_data else 'data'))
for plotter in self.plotters]
else:
if plot_data:
all_attrs = [plotter.plot_data.attrs
... | def joined_attrs(self, delimiter=', ', enhanced=True, plot_data=False,
keep_all=True) | Join the attributes of the arrays in this project
Parameters
----------
%(join_dicts.parameters.delimiter)s
enhanced: bool
If True, the :meth:`psyplot.plotter.Plotter.get_enhanced_attrs`
method is used, otherwise the :attr:`xarray.DataArray.attrs`
att... | 2.838182 | 2.624175 | 1.081552 |
if by is not None:
if base is not None:
if hasattr(base, 'psy') or isinstance(base, Plotter):
base = [base]
if by.lower() in ['ax', 'axes']:
bases = {ax: p[0] for ax, p in six.iteritems(
Project(... | def share(self, base=None, keys=None, by=None, **kwargs) | Share the formatoptions of one plotter with all the others
This method shares specified formatoptions from `base` with all the
plotters in this instance.
Parameters
----------
base: None, Plotter, xarray.DataArray, InteractiveList, or list of them
The source of the ... | 3.184718 | 2.712069 | 1.174276 |
class TmpClass(Plotter):
pass
for fmto in self._fmtos:
setattr(TmpClass, fmto.key, type(fmto)(fmto.key))
return TmpClass.show_keys(*args, **kwargs) | def keys(self, *args, **kwargs) | Show the available formatoptions in this project
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s | 9.949017 | 7.150269 | 1.391419 |
class TmpClass(Plotter):
pass
for fmto in self._fmtos:
setattr(TmpClass, fmto.key, type(fmto)(fmto.key))
return TmpClass.show_summaries(*args, **kwargs) | def summaries(self, *args, **kwargs) | Show the available formatoptions and their summaries in this project
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s | 8.829254 | 7.346865 | 1.201772 |
class TmpClass(Plotter):
pass
for fmto in self._fmtos:
setattr(TmpClass, fmto.key, type(fmto)(fmto.key))
return TmpClass.show_docs(*args, **kwargs) | def docs(self, *args, **kwargs) | Show the available formatoptions in this project and their full docu
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s | 9.1794 | 7.168346 | 1.280547 |
main = kwargs.pop('main', None)
ret = super(Project, cls).from_dataset(*args, **kwargs)
if main is not None:
ret.main = main
main.extend(ret, new_name=False)
return ret | def from_dataset(cls, *args, **kwargs) | Construct an ArrayList instance from an existing base dataset
Parameters
----------
%(ArrayList.from_dataset.parameters)s
main: Project
The main project that this project corresponds to
Other Parameters
----------------
%(ArrayList.from_dataset.other... | 4.341903 | 4.423532 | 0.981546 |
if project is None:
_scp(None)
cls.oncpchange.emit(gcp())
elif not project.is_main:
if project.main is not _current_project:
_scp(project.main, True)
cls.oncpchange.emit(project.main)
_scp(project)
cls.o... | def scp(cls, project) | Set the current project
Parameters
----------
project: Project or None
The project to set. If it is None, the current subproject is set
to empty. If it is a sub project (see:attr:`Project.is_main`),
the current subproject is set to this project. Otherwise it
... | 4.136594 | 3.572231 | 1.157986 |
project = cls(*args, num=num, **kwargs)
scp(project)
return project | def new(cls, num=None, *args, **kwargs) | Create a new main project
Parameters
----------
num: int
The number of the project
%(Project.parameters.no_num)s
Returns
-------
Project
The with the given `num` (if it does not already exist, it is
created)
See Also
... | 10.230425 | 11.612426 | 0.880989 |
return fig.number, {
'num': fig.number,
'figsize': (fig.get_figwidth(), fig.get_figheight()),
'dpi': fig.get_dpi() / getattr(fig.canvas, '_dpi_ratio', 1),
'facecolor': fig.get_facecolor(),
'edgecolor': fig.get_edgecolor(),
'frameon... | def inspect_figure(fig) | Get the parameters (heigth, width, etc.) to create a figure
This method returns the number of the figure and a dictionary
containing the necessary information for the
:func:`matplotlib.pyplot.figure` function | 2.511638 | 2.352572 | 1.067614 |
import matplotlib.pyplot as plt
subplotpars = d.pop('subplotpars', None)
if subplotpars is not None:
subplotpars.pop('validate', None)
subplotpars = mfig.SubplotParams(**subplotpars)
if new_fig:
nums = plt.get_fignums()
if d.get('n... | def load_figure(d, new_fig=True) | Create a figure from what is returned by :meth:`inspect_figure` | 2.943754 | 2.790504 | 1.054919 |
ret = {'fig': ax.get_figure().number}
if mpl.__version__ < '2.0':
ret['axisbg'] = ax.get_axis_bgcolor()
else: # axisbg is depreceated
ret['facecolor'] = ax.get_facecolor()
proj = getattr(ax, 'projection', None)
if proj is not None and not isinsta... | def inspect_axes(ax) | Inspect an axes or subplot to get the initialization parameters | 2.937917 | 2.897868 | 1.01382 |
import matplotlib.pyplot as plt
fig = plt.figure(d.pop('fig', None))
proj = d.pop('projection', None)
spines = d.pop('spines', None)
invert_yaxis = d.pop('yaxis_inverted', None)
invert_xaxis = d.pop('xaxis_inverted', None)
if mpl.__version__ >= '2.0' and ... | def load_axes(d) | Create an axes or subplot from what is returned by
:meth:`inspect_axes` | 2.235463 | 2.173244 | 1.02863 |
ret = {}
for attr in filter(lambda s: not s.startswith("_"), dir(self)):
obj = getattr(self, attr)
if isinstance(obj, PlotterInterface):
ret[attr] = obj._summary
return ret | def _plot_methods(self) | A dictionary with mappings from plot method to their summary | 4.199617 | 3.092365 | 1.35806 |
print_func = PlotterInterface._print_func
if print_func is None:
print_func = six.print_
s = "\n".join(
"%s\n %s" % t for t in six.iteritems(self._plot_methods))
return print_func(s) | def show_plot_methods(self) | Print the plotmethods of this instance | 5.137844 | 4.644112 | 1.106314 |
full_name = '%s.%s' % (module, plotter_name)
if plotter_cls is not None: # plotter has already been imported
docstrings.params['%s.formatoptions' % (full_name)] = \
plotter_cls.show_keys(
indent=4, func=str,
# include links in... | def _register_plotter(cls, identifier, module, plotter_name,
plotter_cls=None, summary='', prefer_list=False,
default_slice=None, default_dims={},
show_examples=True,
example_call="filename, name=['my_variable'], ...... | Register a plotter for making plots
This class method registeres a plot function for the :class:`Project`
class under the name of the given `identifier`
Parameters
----------
%(Project._register_plotter.parameters)s
Other Parameters
----------------
pre... | 5.308284 | 5.493142 | 0.966348 |
ret = docstrings.dedents( % (summary, full_name, identifier, example_call, doc_str))
if show_examples:
ret += '\n\n' + cls._gen_examples(identifier)
return ret | def _gen_doc(cls, summary, full_name, identifier, example_call, doc_str,
show_examples) | Generate the documentation docstring for a PlotMethod | 5.690151 | 6.115232 | 0.930488 |
ret = self._plotter_cls
if ret is None:
self._logger.debug('importing %s', self.module)
mod = import_module(self.module)
plotter = self.plotter_name
if plotter not in vars(mod):
raise ImportError("Module %r does not have a %r plott... | def plotter_cls(self) | The plotter class | 4.768838 | 4.667237 | 1.021769 |
if isinstance(name, six.string_types):
name = [name]
dims = [dims]
else:
dims = list(dims)
variables = [ds[safe_list(n)[0]] for n in name]
decoders = [CFDecoder.get_decoder(ds, var) for var in variables]
default_slice = slice(None) if ... | def check_data(self, ds, name, dims) | A validation method for the data shape
Parameters
----------
name: list of lists of strings
The variable names (see the
:meth:`~psyplot.plotter.Plotter.check_data` method of the
:attr:`plotter_cls` attribute for details)
dims: list of dictionaries
... | 4.697573 | 4.504964 | 1.042755 |
# this method is just a shortcut to the :meth:`Project._add_data`
# method but is reimplemented by subclasses as the
# :class:`DatasetPlotter` or the :class:`DataArrayPlotter`
return super(DatasetPlotter, self)._add_data(plotter_cls, self._ds,
... | def _add_data(self, plotter_cls, *args, **kwargs) | Add new plots to the project
Parameters
----------
%(ProjectPlotter._add_data.parameters.no_filename_or_obj)s
Other Parameters
----------------
%(ProjectPlotter._add_data.other_parameters)s
Returns
-------
%(ProjectPlotter._add_data.returns)s | 6.719588 | 6.693215 | 1.00394 |
# leave out the first argument
example_call = ', '.join(map(str.strip, example_call.split(',')[1:]))
ret = docstrings.dedents( % (summary, full_name, identifier, example_call, doc_str))
if show_examples:
ret += '\n\n' + cls._gen_examples(identifier)
return r... | def _gen_doc(cls, summary, full_name, identifier, example_call, doc_str,
show_examples) | Generate the documentation docstring for a PlotMethod | 4.980978 | 5.076754 | 0.981134 |
plotter_cls = self.plotter_cls
da_list = self._project_plotter._da.psy.to_interactive_list()
return plotter_cls.check_data(
da_list.all_names, da_list.all_dims, da_list.is_unstructured) | def check_data(self, *args, **kwargs) | Check whether the plotter of this plot method can visualize the data | 12.185539 | 10.836717 | 1.124468 |
# this method is just a shortcut to the :meth:`Project._add_data`
# method but is reimplemented by subclasses as the
# :class:`DatasetPlotter` or the :class:`DataArrayPlotter`
return plotter_cls(self._da, *args, **kwargs) | def _add_data(self, plotter_cls, *args, **kwargs) | Visualize this data array
Parameters
----------
%(Plotter.parameters.no_data)s
Returns
-------
psyplot.plotter.Plotter
The plotter that visualizes the data | 9.00087 | 10.160418 | 0.885876 |
lookup = self._load_param_file(fpath)
if not lookup:
return
content = "\n".join(self.content)
parsed = yaml.safe_load(content)
# self.app.info("Params loaded is %s" % parsed)
# self.app.info("Lookup table looks like %s" % lookup)
new_content... | def yaml_from_file(self, fpath) | Collect Parameter stanzas from inline + file.
This allows use to reference an external file for the actual
parameter definitions. | 3.617681 | 3.488208 | 1.037117 |
'''Locate the libsodium C library'''
__SONAMES = (13, 10, 5, 4)
# Import libsodium from system
sys_sodium = ctypes.util.find_library('sodium')
if sys_sodium is None:
sys_sodium = ctypes.util.find_library('libsodium')
if sys_sodium:
try:
return ctypes.CDLL(sys_sodium... | def get_libsodium() | Locate the libsodium C library | 2.346193 | 2.301632 | 1.01936 |
try:
from psyplot_gui import get_parser as _get_parser
except ImportError:
logger.debug('Failed to import gui', exc_info=True)
parser = get_parser(create=False)
parser.update_arg('output', required=True)
parser.create_arguments()
parser.parse2func(args)
e... | def main(args=None) | Main function for usage of psyplot from the command line
This function creates a parser that parses command lines to the
:func:`make_plot` functions or (if the ``psyplot_gui`` module is
present, to the :func:`psyplot_gui.start_app` function)
Returns
-------
psyplot.parser.FuncArgParser
... | 6.166615 | 4.822707 | 1.278663 |
#: The parse that is used to parse arguments from the command line
epilog = docstrings.get_sections(docstrings.dedents(), 'parser', ['Examples'])
if _on_rtd: # make a rubric examples section
epilog = '.. rubric:: Examples\n' + '\n'.join(epilog.splitlines()[2:])
parser = FuncArgParser(
... | def get_parser(create=True) | Return a parser to make that can be used to make plots or open files
from the command line
Returns
-------
psyplot.parser.FuncArgParser
The :class:`argparse.ArgumentParser` instance | 4.328369 | 4.235448 | 1.021939 |
check_args(password, salt, N, r, p, olen)
if _scrypt_ll:
out = ctypes.create_string_buffer(olen)
if _scrypt_ll(password, len(password), salt, len(salt),
N, r, p, out, olen):
raise ValueError
return out.raw
if len(salt) != _scrypt_salt or r != ... | def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64) | Returns a key derived using the scrypt key-derivarion function
N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)
r and p must be positive numbers such that r * p < 2 ** 30
The default values are:
N -- 2**14 (~16k)
r -- 8
p -- 1
Memory usage is proportional to N*r.... | 3.382481 | 3.529498 | 0.958346 |
if isinstance(password, unicode):
password = password.encode('utf8')
elif not isinstance(password, bytes):
raise TypeError('password must be a unicode or byte string')
if N < 2 or (N & (N - 1)):
raise ValueError('scrypt N must be a power of 2 greater than 1')
if p > 255 or p... | def scrypt_mcf(password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p,
prefix=SCRYPT_MCF_PREFIX_DEFAULT) | Derives a Modular Crypt Format hash using the scrypt KDF
Parameter space is smaller than for scrypt():
N must be a power of two larger than 1 but no larger than 2 ** 31
r and p must be positive numbers between 1 and 255
Salt must be a byte string 1-16 bytes long.
If no salt is given, a random salt... | 2.993749 | 3.035356 | 0.986293 |
if isinstance(password, unicode):
password = password.encode('utf8')
elif not isinstance(password, bytes):
raise TypeError('password must be a unicode or byte string')
if not isinstance(mcf, bytes):
raise TypeError('MCF must be a byte string')
if mcf_mod._scrypt_mcf_7_is_sta... | def scrypt_mcf_check(mcf, password) | Returns True if the password matches the given MCF hash | 3.645195 | 3.554526 | 1.025508 |
def getx(self):
if getattr(self, '_' + propname, None) is not None:
return getattr(self, '_' + propname)
else:
setattr(self, '_' + propname, _TempBool(default))
return getattr(self, '_' + propname)
def setx(self, value):
getattr(self, propname).value... | def _temp_bool_prop(propname, doc="", default=False) | Creates a property that uses the :class:`_TempBool` class
Parameters
----------
propname: str
The attribute name to use. The _TempBool instance will be stored in the
``'_' + propname`` attribute of the corresponding instance
doc: str
The documentation of the property
default... | 2.336543 | 2.108397 | 1.108209 |
if key not in possible_keys:
similarkeys = get_close_matches(key, possible_keys, *args, **kwargs)
if similarkeys:
msg = ('Unknown %s %s! Possible similiar '
'frasings are %s.') % (name, key, ', '.join(similarkeys))
else:
msg = ("Unknown %s %s! ... | def check_key(key, possible_keys, raise_error=True,
name='formatoption keyword',
msg=("See show_fmtkeys function for possible formatopion "
"keywords"),
*args, **kwargs) | Checks whether the key is in a list of possible keys
This function checks whether the given `key` is in `possible_keys` and if
not looks for similar sounding keys
Parameters
----------
key: str
Key to check
possible_keys: list of strings
a list of possible keys to use
raise... | 3.75944 | 3.574572 | 1.051717 |
return chain(
({key: kwargs.pop(key) for key in params.intersection(kwargs)}
for params in map(set, param_lists)), [kwargs]) | def sort_kwargs(kwargs, *param_lists) | Function to sort keyword arguments and sort them into dictionaries
This function returns dictionaries that contain the keyword arguments
from `kwargs` corresponding given iterables in ``*params``
Parameters
----------
kwargs: dict
Original dictionary
``*param_lists``
iterables ... | 6.887794 | 9.544033 | 0.721686 |
if val is None:
return val
try:
hash(val)
except TypeError:
return repr(val)
else:
return val | def hashable(val) | Test if `val` is hashable and if not, get it's string representation
Parameters
----------
val: object
Any (possibly not hashable) python object
Returns
-------
val or string
The given `val` if it is hashable or it's string representation | 2.666546 | 4.012952 | 0.664485 |
if not dicts:
return {}
if keep_all:
all_keys = set(chain(*(d.keys() for d in dicts)))
else:
all_keys = set(dicts[0])
for d in dicts[1:]:
all_keys.intersection_update(d)
ret = {}
for key in all_keys:
vals = {hashable(d.get(key, None)) for d in... | def join_dicts(dicts, delimiter=None, keep_all=False) | Join multiple dictionaries into one
Parameters
----------
dicts: list of dict
A list of dictionaries
delimiter: str
The string that shall be used as the delimiter in case that there
are multiple values for one attribute in the arrays. If None, they
will be returned as se... | 2.042312 | 2.201749 | 0.927586 |
def outer(f):
@six.wraps(f)
def inner(self, *args, **kw):
userids = args[check_index]
if isinstance(userids, list):
# convert all userids to upper case
userids = [uid.upper() for uid in userids]
new_args = (args[:check_in... | def check_guest_exist(check_index=0) | Check guest exist in database.
:param check_index: The parameter index of userid(s), default as 0 | 2.48427 | 2.384719 | 1.041745 |
action = "start guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_start(userid) | def guest_start(self, userid) | Power on a virtual machine.
:param str userid: the id of the virtual machine to be power on
:returns: None | 4.987435 | 7.18685 | 0.693967 |
action = "stop guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_stop(userid, **kwargs) | def guest_stop(self, userid, **kwargs) | Power off a virtual machine.
:param str userid: the id of the virtual machine to be power off
:param dict kwargs:
- timeout=<value>:
Integer, time to wait for vm to be deactivate, the
recommended value is 300
- poll_interval=<value>
... | 4.580479 | 7.362001 | 0.622178 |
action = "soft stop guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_softstop(userid, **kwargs) | def guest_softstop(self, userid, **kwargs) | Issue a shutdown command to shutdown the OS in a virtual
machine and then log the virtual machine off z/VM..
:param str userid: the id of the virtual machine to be power off
:param dict kwargs:
- timeout=<value>:
Integer, time to wait for vm to be deactivate, the... | 4.481779 | 6.894486 | 0.650053 |
action = "reboot guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_reboot(userid) | def guest_reboot(self, userid) | Reboot a virtual machine
:param str userid: the id of the virtual machine to be reboot
:returns: None | 4.586191 | 6.506291 | 0.704886 |
action = "reset guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_reset(userid) | def guest_reset(self, userid) | reset a virtual machine
:param str userid: the id of the virtual machine to be reset
:returns: None | 4.961147 | 6.455796 | 0.76848 |
action = "pause guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_pause(userid) | def guest_pause(self, userid) | Pause a virtual machine.
:param str userid: the id of the virtual machine to be paused
:returns: None | 4.66379 | 6.693287 | 0.696786 |
action = "unpause guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_unpause(userid) | def guest_unpause(self, userid) | Unpause a virtual machine.
:param str userid: the id of the virtual machine to be unpaused
:returns: None | 4.331001 | 6.257287 | 0.692153 |
action = "get power state of guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._vmops.get_power_state(userid) | def guest_get_power_state(self, userid) | Returns power state. | 4.092619 | 4.117096 | 0.994055 |
action = "get info of guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._vmops.get_info(userid) | def guest_get_info(self, userid) | Get the status of a virtual machine.
:param str userid: the id of the virtual machine
:returns: Dictionary contains:
power_state: (str) the running state, one of on | off
max_mem_kb: (int) the maximum memory in KBytes allowed
mem_kb: (int) the memo... | 5.2334 | 7.091073 | 0.738027 |
# disk_pool must be assigned. disk_pool default to None because
# it is more convenient for users to just type function name when
# they want to get the disk pool info of CONF.zvm.disk_pool
if disk_pool is None:
disk_pool = CONF.zvm.disk_pool
if ':' not in d... | def host_diskpool_get_info(self, disk_pool=None) | Retrieve diskpool information.
:param str disk_pool: the disk pool info. It use ':' to separate
disk pool type and pool name, eg "ECKD:eckdpool" or "FBA:fbapool"
:returns: Dictionary describing disk pool usage info | 3.556806 | 3.180638 | 1.118268 |
try:
self._imageops.image_delete(image_name)
except exception.SDKBaseException:
LOG.error("Failed to delete image '%s'" % image_name)
raise | def image_delete(self, image_name) | Delete image from image repository
:param image_name: the name of the image to be deleted | 3.856106 | 4.493852 | 0.858085 |
try:
return self._imageops.image_get_root_disk_size(image_name)
except exception.SDKBaseException:
LOG.error("Failed to get root disk size units of image '%s'" %
image_name)
raise | def image_get_root_disk_size(self, image_name) | Get the root disk size of the image
:param image_name: the image name in image Repository
:returns: the disk size in units CYL or BLK | 3.858237 | 4.233318 | 0.911398 |
try:
self._imageops.image_import(image_name, url, image_meta,
remote_host=remote_host)
except exception.SDKBaseException:
LOG.error("Failed to import image '%s'" % image_name)
raise | def image_import(self, image_name, url, image_meta, remote_host=None) | Import image to zvmsdk image repository
:param image_name: image name that can be uniquely identify an image
:param str url: image url to specify the location of image such as
http://netloc/path/to/file.tar.gz.0
https://netloc/path/to/file.tar.gz.0
file:///p... | 3.024974 | 2.986408 | 1.012914 |
try:
return self._imageops.image_query(imagename)
except exception.SDKBaseException:
LOG.error("Failed to query image")
raise | def image_query(self, imagename=None) | Get the list of image info in image repository
:param imagename: Used to retrieve the specified image info,
if not specified, all images info will be returned
:returns: A list that contains the specified or all images info | 5.601776 | 6.710632 | 0.834761 |
try:
return self._imageops.image_export(image_name, dest_url,
remote_host)
except exception.SDKBaseException:
LOG.error("Failed to export image '%s'" % image_name)
raise | def image_export(self, image_name, dest_url, remote_host=None) | Export the image to the specified location
:param image_name: image name that can be uniquely identify an image
:param dest_url: the location of exported image, eg.
file:///opt/images/export.img, now only support export to remote server
or local server's file system
:param remote... | 3.602495 | 3.256266 | 1.106327 |
action = ("deploy image '%(img)s' to guest '%(vm)s'" %
{'img': image_name, 'vm': userid})
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_deploy(userid, image_name, transportfiles,
remotehost, vdev, hostna... | def guest_deploy(self, userid, image_name, transportfiles=None,
remotehost=None, vdev=None, hostname=None) | Deploy the image to vm.
:param userid: (str) the user id of the vm
:param image_name: (str) the name of image that used to deploy the vm
:param transportfiles: (str) the files that used to customize the vm
:param remotehost: the server where the transportfiles located, the
... | 2.84759 | 3.638817 | 0.782559 |
action = ("capture guest '%(vm)s' to generate image '%(img)s'" %
{'vm': userid, 'img': image_name})
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_capture(userid, image_name,
capture_type=capture_type,
... | def guest_capture(self, userid, image_name, capture_type='rootonly',
compress_level=6) | Capture the guest to generate a image
:param userid: (str) the user id of the vm
:param image_name: (str) the unique image name after capture
:param capture_type: (str) the type of capture, the value can be:
rootonly: indicate just root device will be captured
alld... | 2.953722 | 3.182279 | 0.928178 |
if mac_addr is not None:
if not zvmutils.valid_mac_addr(mac_addr):
raise exception.SDKInvalidInputFormat(
msg=("Invalid mac address, format should be "
"xx:xx:xx:xx:xx:xx, and x is a hexadecimal digit"))
return self._netwo... | def guest_create_nic(self, userid, vdev=None, nic_id=None,
mac_addr=None, active=False) | Create the nic for the vm, add NICDEF record into the user direct.
:param str userid: the user id of the vm
:param str vdev: nic device number, 1- to 4- hexadecimal digits
:param str nic_id: nic identifier
:param str mac_addr: mac address, it is only be used when changing
... | 2.768335 | 2.565675 | 1.078989 |
self._networkops.delete_nic(userid, vdev, active=active) | def guest_delete_nic(self, userid, vdev, active=False) | delete the nic for the vm
:param str userid: the user id of the vm
:param str vdev: nic device number, 1- to 4- hexadecimal digits
:param bool active: whether delete a nic on active guest system | 5.611352 | 8.137688 | 0.689551 |
action = "get the definition info of guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._vmops.get_definition_info(userid, **kwargs) | def guest_get_definition_info(self, userid, **kwargs) | Get definition info for the specified guest vm, also could be used
to check specific info.
:param str userid: the user id of the guest vm
:param dict kwargs: Dictionary used to check specific info in user
direct. Valid keywords for kwargs:
... | 4.580823 | 5.78237 | 0.792205 |
userid = userid.upper()
if not zvmutils.check_userid_exist(userid):
LOG.error("User directory '%s' does not exist." % userid)
raise exception.SDKObjectNotExistError(
obj_desc=("Guest '%s'" % userid), modID='guest')
else:
action = "... | def guest_register(self, userid, meta, net_set) | DB operation for migrate vm from another z/VM host in same SSI
:param userid: (str) the userid of the vm to be relocated or tested
:param meta: (str) the metadata of the vm to be relocated or tested
:param net_set: (str) the net_set of the vm, default is 1. | 3.367446 | 3.39778 | 0.991072 |
if lgr_action.lower() == 'move':
if dest_zcc_userid == '':
errmsg = ("'dest_zcc_userid' is required if the value of "
"'lgr_action' equals 'move'.")
LOG.error(errmsg)
raise exception.SDKMissingRequiredInput(msg=errmsg... | def guest_live_migrate(self, userid, dest_zcc_userid, destination,
parms, lgr_action) | Move an eligible, running z/VM(R) virtual machine transparently
from one z/VM system to another within an SSI cluster.
:param userid: (str) the userid of the vm to be relocated or tested
:param dest_zcc_userid: (str) the userid of zcc on destination
:param destination: (str) the system ... | 3.340772 | 3.244677 | 1.029616 |
action = "live resize guest '%s' to have '%i' virtual cpus" % (userid,
cpu_cnt)
LOG.info("Begin to %s" % action)
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.live_resize_cpus(userid, c... | def guest_live_resize_cpus(self, userid, cpu_cnt) | Live resize virtual cpus of guests.
:param userid: (str) the userid of the guest to be live resized
:param cpu_cnt: (int) The number of virtual cpus that the guest should
have in active state after live resize. The value should be an
integer between 1 and 64. | 3.819344 | 3.933707 | 0.970928 |
action = "resize guest '%s' to have '%i' virtual cpus" % (userid,
cpu_cnt)
LOG.info("Begin to %s" % action)
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.resize_cpus(userid, cpu_cnt)
... | def guest_resize_cpus(self, userid, cpu_cnt) | Resize virtual cpus of guests.
:param userid: (str) the userid of the guest to be resized
:param cpu_cnt: (int) The number of virtual cpus that the guest should
have defined in user directory after resize. The value should
be an integer between 1 and 64. | 4.035025 | 4.353764 | 0.92679 |
action = "live resize guest '%s' to have '%s' memory" % (userid,
size)
LOG.info("Begin to %s" % action)
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.live_resize_memory(userid, size)
... | def guest_live_resize_mem(self, userid, size) | Live resize memory of guests.
:param userid: (str) the userid of the guest to be live resized
:param size: (str) The memory size that the guest should have
in available status after live resize.
The value should be specified by 1-4 bits of number suffixed by
... | 4.243093 | 4.406436 | 0.962931 |
action = "resize guest '%s' to have '%s' memory" % (userid, size)
LOG.info("Begin to %s" % action)
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.resize_memory(userid, size)
LOG.info("%s successfully." % action) | def guest_resize_mem(self, userid, size) | Resize memory of guests.
:param userid: (str) the userid of the guest to be resized
:param size: (str) The memory size that the guest should have
defined in user directory after resize.
The value should be specified by 1-4 bits of number suffixed by
either M... | 4.186203 | 4.700563 | 0.890575 |
if disk_list == [] or disk_list is None:
# nothing to do
LOG.debug("No disk specified when calling guest_create_disks, "
"nothing happened")
return
action = "create disks '%s' for guest '%s'" % (str(disk_list), userid)
with zvmu... | def guest_create_disks(self, userid, disk_list) | Add disks to an existing guest vm.
:param userid: (str) the userid of the vm to be created
:param disk_list: (list) a list of disks info for the guest.
It has one dictionary that contain some of the below keys for
each disk, the root disk should be the first element in the... | 4.050801 | 4.260104 | 0.950869 |
action = "delete disks '%s' from guest '%s'" % (str(disk_vdev_list),
userid)
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.delete_disks(userid, disk_vdev_list) | def guest_delete_disks(self, userid, disk_vdev_list) | Delete disks from an existing guest vm.
:param userid: (str) the userid of the vm to be deleted
:param disk_vdev_list: (list) the vdev list of disks to be deleted,
for example: ['0101', '0102'] | 3.21856 | 3.848423 | 0.836332 |
self._networkops.couple_nic_to_vswitch(userid, nic_vdev,
vswitch_name, active=active) | def guest_nic_couple_to_vswitch(self, userid, nic_vdev,
vswitch_name, active=False) | Couple nic device to specified vswitch.
:param str userid: the user's name who owns the nic
:param str nic_vdev: nic device number, 1- to 4- hexadecimal digits
:param str vswitch_name: the name of the vswitch
:param bool active: whether make the change on active guest system | 3.157903 | 4.159799 | 0.759148 |
self._networkops.uncouple_nic_from_vswitch(userid, nic_vdev,
active=active) | def guest_nic_uncouple_from_vswitch(self, userid, nic_vdev,
active=False) | Disonnect nic device with network.
:param str userid: the user's name who owns the nic
:param str nic_vdev: nic device number, 1- to 4- hexadecimal digits
:param bool active: whether make the change on active guest system | 3.385103 | 4.475739 | 0.756323 |
if ((queue_mem < 1) or (queue_mem > 8)):
errmsg = ('API vswitch_create: Invalid "queue_mem" input, '
'it should be 1-8')
raise exception.SDKInvalidInputFormat(msg=errmsg)
if isinstance(vid, int) or vid.upper() != 'UNAWARE':
if ((native_... | def vswitch_create(self, name, rdev=None, controller='*',
connection='CONNECT', network_type='ETHERNET',
router="NONROUTER", vid='UNAWARE', port_type='ACCESS',
gvrp='GVRP', queue_mem=8, native_vid=1,
persist=True) | Create vswitch.
:param str name: the vswitch name
:param str rdev: the real device number, a maximum of three devices,
all 1-4 characters in length, delimited by blanks. 'NONE'
may also be specified
:param str controller: the vswitch's controller, it could be the u... | 2.142712 | 2.172342 | 0.98636 |
action = "get the console output of guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
output = self._vmops.get_console_output(userid)
return output | def guest_get_console_output(self, userid) | Get the console output of the guest virtual machine.
:param str userid: the user id of the vm
:returns: console log string
:rtype: str | 4.484808 | 5.48504 | 0.817644 |
# check guest exist in database or not
userid = userid.upper()
if not self._vmops.check_guests_exist_in_db(userid, raise_exc=False):
if zvmutils.check_userid_exist(userid):
LOG.error("Guest '%s' does not exist in guests database" %
... | def guest_delete(self, userid) | Delete guest.
:param userid: the user id of the vm | 3.915765 | 3.884758 | 1.007982 |
if not isinstance(userid_list, list):
userid_list = [userid_list]
action = "get the statistics of guest '%s'" % str(userid_list)
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._monitor.inspect_stats(userid_list) | def guest_inspect_stats(self, userid_list) | Get the statistics including cpu and mem of the guests
:param userid_list: a single userid string or a list of guest userids
:returns: dictionary describing the cpu statistics of the vm
in the form {'UID1':
{
'guest_cpus': xx,
'use... | 3.830384 | 4.254716 | 0.900268 |
if not isinstance(userid_list, list):
userid_list = [userid_list]
action = "get the vnics statistics of guest '%s'" % str(userid_list)
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._monitor.inspect_vnics(userid_list) | def guest_inspect_vnics(self, userid_list) | Get the vnics statistics of the guest virtual machines
:param userid_list: a single userid string or a list of guest userids
:returns: dictionary describing the vnics statistics of the vm
in the form
{'UID1':
[{
'vswitch_name': xx,... | 3.851243 | 3.903436 | 0.986629 |
self._networkops.set_vswitch_port_vlan_id(vswitch_name,
userid, vlan_id) | def vswitch_set_vlan_id_for_user(self, vswitch_name, userid, vlan_id) | Set vlan id for user when connecting to the vswitch
:param str vswitch_name: the name of the vswitch
:param str userid: the user id of the vm
:param int vlan_id: the VLAN id | 5.030593 | 6.815244 | 0.738138 |
action = "config disks for userid '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_config_minidisks(userid, disk_info) | def guest_config_minidisks(self, userid, disk_info) | Punch the script that used to process additional disks to vm
:param str userid: the user id of the vm
:param disk_info: a list contains disks info for the guest. It
contains dictionaries that describes disk info for each disk.
Each dictionary has 3 keys, format is require... | 4.376216 | 4.792213 | 0.913193 |
self._networkops.delete_vswitch(vswitch_name, persist) | def vswitch_delete(self, vswitch_name, persist=True) | Delete vswitch.
:param str name: the vswitch name
:param bool persist: whether delete the vswitch from the permanent
configuration for the system | 5.626595 | 9.486341 | 0.593126 |
action = "get nic information"
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._networkops.get_nic_info(userid=userid, nic_id=nic_id,
vswitch=vswitch) | def guests_get_nic_info(self, userid=None, nic_id=None, vswitch=None) | Retrieve nic information in the network database according to
the requirements, the nic information will include the guest
name, nic device number, vswitch name that the nic is coupled
to, nic identifier and the comments.
:param str userid: the user id of the vm
:par... | 3.879404 | 5.066989 | 0.765623 |
action = "get virtual switch information"
with zvmutils.log_and_reraise_sdkbase_error(action):
return self._networkops.vswitch_query(vswitch_name) | def vswitch_query(self, vswitch_name) | Check the virtual switch status
:param str vswitch_name: the name of the virtual switch
:returns: Dictionary describing virtual switch info
:rtype: dict | 6.169946 | 8.184975 | 0.753814 |
self._networkops.delete_nic(userid, vdev, active=active)
self._networkops.delete_network_configuration(userid, os_version,
vdev, active=active) | def guest_delete_network_interface(self, userid, os_version,
vdev, active=False) | delete the nic and network configuration for the vm
:param str userid: the user id of the guest
:param str os_version: operating system version of the guest
:param str vdev: nic device number, 1- to 4- hexadecimal digits
:param bool active: whether delete a nic on active guest system | 3.514424 | 3.480505 | 1.009746 |
_orig_adapters = session.adapters
mock_adapter = adapter.Adapter()
session.adapters = OrderedDict()
if isinstance(url, (list, tuple)):
for u in url:
session.mount(u, mock_adapter)
else:
session.mount(url, mock_adapter)
mock_adapter.register_path(path)
yield
... | def mock_session_with_fixtures(session, path, url) | Context Manager
Mock the responses with a particular session
to any files found within a static path
:param session: The requests session object
:type session: :class:`requests.Session`
:param path: The path to the fixtures
:type path: ``str``
:param url: The base URL to mock, e.g. htt... | 3.21974 | 3.81613 | 0.843719 |
_orig_adapters = session.adapters
mock_adapter = adapter.ClassAdapter(cls)
session.adapters = OrderedDict()
if isinstance(url, (list, tuple)):
for u in url:
session.mount(u, mock_adapter)
else:
session.mount(url, mock_adapter)
yield
session.adapters = _orig_a... | def mock_session_with_class(session, cls, url) | Context Manager
Mock the responses with a particular session
to any private methods for the URLs
:param session: The requests session object
:type session: :class:`requests.Session`
:param cls: The class instance with private methods for URLs
:type cls: ``object``
:param url: The base ... | 2.945801 | 3.831625 | 0.768812 |
def _fixpath(self, p):
return os.path.abspath(os.path.expanduser(p)) | Apply tilde expansion and absolutization to a path. | null | null | null | |
def _get_config_dirs(self):
_cwd = os.path.split(os.path.abspath(__file__))[0]
_pdir = os.path.split(_cwd)[0]
_etcdir = ''.join((_pdir, '/', 'etc/'))
cfg_dirs = [
self._fixpath(_cwd),
self._fixpath('/etc/zvmsdk/'),
self._fixpath('/etc/... | Return a list of directories where config files may be located.
following directories are returned::
./
../etc
~/
/etc/zvmsdk/ | null | null | null | |
def _search_dirs(self, dirs, basename, extension=""):
for d in dirs:
path = os.path.join(d, '%s%s' % (basename, extension))
if os.path.exists(path):
return path
return None | Search a list of directories for a given filename or directory name.
Iterator over the supplied directories, returning the first file
found with the supplied name and extension.
:param dirs: a list of directories
:param basename: the filename
:param extension: the file e... | null | null | null | |
def find_config_file(self, project=None, extension='.conf'):
cfg_dirs = self._get_config_dirs()
config_files = self._search_dirs(cfg_dirs, project, extension)
return config_files | Return the config file.
:param project: "zvmsdk"
:param extension: the type of the config file | null | null | null | |
if isinstance(password, unicode):
password = password.encode('utf8')
elif not isinstance(password, bytes):
raise TypeError('password must be a unicode or byte string')
if salt is not None and not isinstance(salt, bytes):
raise TypeError('salt must be a byte string')
if salt ... | def scrypt_mcf(scrypt, password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p,
prefix=SCRYPT_MCF_PREFIX_DEFAULT) | Derives a Modular Crypt Format hash using the scrypt KDF given
Expects the signature:
scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64)
If no salt is given, a random salt of 128+ bits is used. (Recommended.) | 2.091773 | 2.136221 | 0.979193 |
if not isinstance(mcf, bytes):
raise TypeError('MCF must be a byte string')
if isinstance(password, unicode):
password = password.encode('utf8')
elif not isinstance(password, bytes):
raise TypeError('password must be a unicode or byte string')
N, r, p, salt, hash, hlen = _s... | def scrypt_mcf_check(scrypt, mcf, password) | Returns True if the password matches the given MCF hash
Supports both the libscrypt $s1$ format and the $7$ format. | 2.62317 | 2.674792 | 0.9807 |
name = osp.basename(odir)
if py_name is None:
py_name = name.replace('-', '_')
src = osp.join(osp.dirname(__file__), 'plugin-template-files')
# copy the source files
shutil.copytree(src, odir)
os.rename(osp.join(odir, 'plugin_template'), osp.join(odir, py_name))
replacements =... | def new_plugin(odir, py_name=None, version='0.0.1.dev0',
description='New plugin') | Create a new plugin for the psyplot package
Parameters
----------
odir: str
The name of the directory where the data will be copied to. The
directory must not exist! The name of the directory also defines the
name of the package.
py_name: str
The name of the python packa... | 2.065291 | 2.109408 | 0.979086 |
from pkg_resources import iter_entry_points
ret = {'psyplot': _get_versions(requirements)}
for ep in iter_entry_points(group='psyplot', name='plugin'):
if str(ep) in rcParams._plugins:
logger.debug('Loading entrypoint %s', ep)
if key is not None and not key(ep.module_nam... | def get_versions(requirements=True, key=None) | Get the version information for psyplot, the plugins and its requirements
Parameters
----------
requirements: bool
If True, the requirements of the plugins and psyplot are investigated
key: func
A function that determines whether a plugin shall be considererd or
not. The functio... | 3.212465 | 3.085536 | 1.041137 |
with get_network_conn() as conn:
conn.execute("DELETE FROM switch WHERE userid=?",
(userid,))
LOG.debug("Switch record for user %s is removed from "
"switch table" % userid) | def switch_delete_record_for_userid(self, userid) | Remove userid switch record from switch table. | 6.035991 | 5.16576 | 1.168461 |
with get_network_conn() as conn:
conn.execute("DELETE FROM switch WHERE userid=? and interface=?",
(userid, interface))
LOG.debug("Switch record for user %s with nic %s is removed from "
"switch table" % (userid, interface)) | def switch_delete_record_for_nic(self, userid, interface) | Remove userid switch record from switch table. | 4.698369 | 4.147593 | 1.132794 |
with get_network_conn() as conn:
conn.execute("INSERT INTO switch VALUES (?, ?, ?, ?, ?)",
(userid, interface, switch, port, comments))
LOG.debug("New record in the switch table: user %s, "
"nic %s, port %s" %
... | def switch_add_record(self, userid, interface, port=None,
switch=None, comments=None) | Add userid and nic name address into switch table. | 4.343831 | 3.969133 | 1.094403 |
if not self._get_switch_by_user_interface(userid, interface):
msg = "User %s with nic %s does not exist in DB" % (userid,
interface)
LOG.error(msg)
obj_desc = ('User %s with nic %s' % (userid, interface)... | def switch_update_record_with_switch(self, userid, interface,
switch=None) | Update information in switch table. | 2.605001 | 2.538581 | 1.026164 |
if imagename:
with get_image_conn() as conn:
result = conn.execute("SELECT * FROM image WHERE "
"imagename=?", (imagename,))
image_list = result.fetchall()
if not image_list:
obj_desc = "Image... | def image_query_record(self, imagename=None) | Query the image record from database, if imagename is None, all
of the image records will be returned, otherwise only the specified
image record will be returned. | 3.705121 | 3.605789 | 1.027548 |
userid = userid
with get_guest_conn() as conn:
res = conn.execute("SELECT comments FROM guests "
"WHERE userid=?", (userid,))
result = res.fetchall()
comments = {}
if result[0][0]:
comments = json.loads(result[0][0]... | def get_comments_by_userid(self, userid) | Get comments record.
output should be like: {'k1': 'v1', 'k2': 'v2'}' | 4.402214 | 3.826893 | 1.150336 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.