text
stringlengths
18
773k
def export(self, output, tight=False, concat=True, close_pdf=None, use_time=False, **kwargs): """Exports the figures of the project to one or more image files Parameters ---------- output: str, iterable or matplotlib.backends.backend_pdf.PdfPages if string or ...
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, xar...
def save_project(self, fname=None, pwd=None, pack=False, **kwargs): """ Save this project to a file Parameters ---------- fname: str or None If None, the dictionary will be returned. Otherwise the necessary information to load this project via the :meth:`...
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 ------- ...
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 Return...
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 ...
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 ----...
def load_project(cls, fname, auto_update=None, make_plot=True, draw=False, alternative_axes=None, main=False, encoding=None, enable_post=False, new_fig=True, clear=None, **kwargs): """ Load a project from a file or dict This classme...
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 subpr...
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...
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""" return fig.number, { 'num':...
def load_figure(d, new_fig=True): """Create a figure from what is returned by :meth:`inspect_figure`""" import matplotlib.pyplot as plt subplotpars = d.pop('subplotpars', None) if subplotpars is not None: subplotpars.pop('validate', None) subplotpars = mfig.Subplo...
def inspect_axes(ax): """Inspect an axes or subplot to get the initialization parameters""" 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()...
def load_axes(d): """Create an axes or subplot from what is returned by :meth:`inspect_axes`""" 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_inverte...
def _plot_methods(self): """A dictionary with mappings from plot method to their summary""" ret = {} for attr in filter(lambda s: not s.startswith("_"), dir(self)): obj = getattr(self, attr) if isinstance(obj, PlotterInterface): ret[attr] = obj._summary ...
def show_plot_methods(self): """Print the plotmethods of this instance""" 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...
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'], ......
def _gen_doc(cls, summary, full_name, identifier, example_call, doc_str, show_examples): """Generate the documentation docstring for a PlotMethod""" ret = docstrings.dedents(""" %s This plotting method adds data arrays and plots them via :class:`%s` ...
def plotter_cls(self): """The plotter class""" 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 I...
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` att...
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 ...
def _gen_doc(cls, summary, full_name, identifier, example_call, doc_str, show_examples): """Generate the documentation docstring for a PlotMethod""" # leave out the first argument example_call = ', '.join(map(str.strip, example_call.split(',')[1:])) ret = docstrings.dede...
def check_data(self, *args, **kwargs): """Check whether the plotter of this plot method can visualize the data """ 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.al...
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 """ # this meth...
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. """ lookup = self._load_param_file(fpath) if not lookup: return content = "\n".join...
def get_libsodium(): '''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 c...
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....
def make_plot(fnames=[], name=[], dims=None, plot_method=None, output=None, project=None, engine=None, formatoptions=None, tight=False, rc_file=None, encoding=None, enable_post=False, seaborn_style=None, output_project=None, concat_dim=get_default_value(xr.open_mf...
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""" #: The parse that is used to parse arguments from the command line ...
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...
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 m...
def scrypt_mcf_check(mcf, password): """Returns True if the password matches the given MCF hash""" 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...
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 d...
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 chec...
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 dict...
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""" if val...
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 attribu...
def check_guest_exist(check_index=0): """Check guest exist in database. :param check_index: The parameter index of userid(s), default as 0 """ def outer(f): @six.wraps(f) def inner(self, *args, **kw): userids = args[check_index] if isinstance(userids, list): ...
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 """ action = "start guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_start...
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 i...
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>: ...
def guest_reboot(self, userid): """Reboot a virtual machine :param str userid: the id of the virtual machine to be reboot :returns: None """ action = "reboot guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_reboot(use...
def guest_reset(self, userid): """reset a virtual machine :param str userid: the id of the virtual machine to be reset :returns: None """ action = "reset guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_reset(userid)
def guest_pause(self, userid): """Pause a virtual machine. :param str userid: the id of the virtual machine to be paused :returns: None """ action = "pause guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_pause(useri...
def guest_unpause(self, userid): """Unpause a virtual machine. :param str userid: the id of the virtual machine to be unpaused :returns: None """ action = "unpause guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_unp...
def guest_get_power_state(self, userid): """Returns power state.""" 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_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 all...
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 """ ...
def image_delete(self, image_name): """Delete image from image repository :param image_name: the name of the image to be deleted """ try: self._imageops.image_delete(image_name) except exception.SDKBaseException: LOG.error("Failed to delete image '%s'" % ...
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 """ try: return self._imageops.image_get_root_disk_size(image_name) except...
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...
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 """ ...
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 t...
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 transportf...
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 ...
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 ...
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 """ self._networ...
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 ...
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 ...
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 o...
def guest_create(self, userid, vcpus, memory, disk_list=None, user_profile=CONF.zvm.user_profile, max_cpu=CONF.zvm.user_default_max_cpu, max_mem=CONF.zvm.user_default_max_memory, ipl_from='', ipl_param='', ipl_loadparam=''): """...
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 shoul...
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 ...
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 ...
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...
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 ...
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'] """ action = "de...
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 :p...
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 a...
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): """ C...
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 """ action = "get the console output of guest '%s'" % userid with zvmutils.log_an...
def guest_delete(self, userid): """Delete guest. :param userid: the user id of the vm """ # 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(user...
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': { ...
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': ...
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 """ self._networkops.se...
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 dis...
def vswitch_set(self, vswitch_name, **kwargs): """Change the configuration of an existing virtual switch :param str vswitch_name: the name of the virtual switch :param dict kwargs: - grant_userid=<value>: A userid to be added to the access list - user_vla...
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 """ self._networkops.delete_vswitch(vswitch_name, persist)
def guest_create_network_interface(self, userid, os_version, guest_networks, active=False): """ Create network interface(s) for the guest inux system. It will create the nic for the guest, add NICDEF record into the user direct. It will also constru...
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 identifi...
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 """ action = "get virtual switch information" with zvmutils.log_and_...
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 :para...
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 :typ...
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 fo...
def _fixpath(self, p): """Apply tilde expansion and absolutization to a path.""" return os.path.abspath(os.path.expanduser(p))
def _get_config_dirs(self): """Return a list of directories where config files may be located. following directories are returned:: ./ ../etc ~/ /etc/zvmsdk/ """ _cwd = os.path.split(os.path.abspath(__file__))[0] _pdir = os.pat...
def _search_dirs(self, dirs, basename, extension=""): """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 :...
def find_config_file(self, project=None, extension='.conf'): """Return the config file. :param project: "zvmsdk" :param extension: the type of the config file """ cfg_dirs = self._get_config_dirs() config_files = self._search_dirs(cfg_dirs, project, extension) ...
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 g...
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. """ if not isinstance(mcf, bytes): raise TypeError('MCF must be a byte string') if isinstance(password, unicode): passw...
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 th...
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 whethe...
def switch_delete_record_for_userid(self, userid): """Remove userid switch record from switch table.""" with get_network_conn() as conn: conn.execute("DELETE FROM switch WHERE userid=?", (userid,)) LOG.debug("Switch record for user %s is removed from " ...
def switch_delete_record_for_nic(self, userid, interface): """Remove userid switch record from switch table.""" with get_network_conn() as conn: conn.execute("DELETE FROM switch WHERE userid=? and interface=?", (userid, interface)) LOG.debug("Switch recor...
def switch_add_record(self, userid, interface, port=None, switch=None, comments=None): """Add userid and nic name address into switch table.""" with get_network_conn() as conn: conn.execute("INSERT INTO switch VALUES (?, ?, ?, ?, ?)", (useri...
def switch_update_record_with_switch(self, userid, interface, switch=None): """Update information in switch table.""" if not self._get_switch_by_user_interface(userid, interface): msg = "User %s with nic %s does not exist in DB" % (userid, ...
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.""" if imagename: with get_image_conn() as conn: ...
def get_comments_by_userid(self, userid): """ Get comments record. output should be like: {'k1': 'v1', 'k2': 'v2'}' """ userid = userid with get_guest_conn() as conn: res = conn.execute("SELECT comments FROM guests " "WHERE userid=?", (u...
def get_metadata_by_userid(self, userid): """get metadata record. output should be like: "a=1,b=2,c=3" """ userid = userid with get_guest_conn() as conn: res = conn.execute("SELECT * FROM guests " "WHERE userid=?", (userid,)) ...
def transfer_metadata_to_dict(self, meta): """transfer str to dict. output should be like: {'a':1, 'b':2, 'c':3} """ dic = {} arr = meta.strip(' ,').split(',') for i in arr: temp = i.split('=') key = temp[0].strip() value = temp[1].stri...