code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
rh.printSysLog("Enter makeVM.createVM") dirLines = [] dirLines.append("USER " + rh.userid + " " + rh.parms['pw'] + " " + rh.parms['priMemSize'] + " " + rh.parms['maxMemSize'] + " " + rh.parms['privClasses']) if 'profName' in rh.parms: dirLines.append("INCLUDE " + rh.parm...
def createVM(rh)
Create a virtual machine in z/VM. Input: Request Handle with the following properties: function - 'CMDVM' subfunction - 'CMD' userid - userid of the virtual machine Output: Request Handle updated with the results. Return code - 0: ok, non-zero: error
3.624791
3.613472
1.003133
if rh.function == 'HELP': rh.printLn("N", " For the MakeVM function:") else: rh.printLn("N", "Sub-Functions(s):") rh.printLn("N", " directory - " + "Create a virtual machine in the z/VM user directory.") rh.printLn("N", " help - Displays this help in...
def showOperandLines(rh)
Produce help output related to operands. Input: Request Handle
3.300582
3.311352
0.996747
# check power state, if down, start it ret = sdk_client.send_request('guest_get_power_state', userid) power_status = ret['output'] if power_status == 'off': sdk_client.send_request('guest_start', userid) # TODO: how much time? time.sleep(1) # do capture image_name =...
def capture_guest(userid)
Caputre a virtual machine image. Input parameters: :userid: USERID of the guest, last 8 if length > 8 Output parameters: :image_name: Image name that captured
4.501034
4.730998
0.951392
image_name = os.path.basename(image_path) print("Checking if image %s exists or not, import it if not exists" % image_name) image_info = sdk_client.send_request('image_query', imagename=image_name) if 'overallRC' in image_info and image_info['overallRC']: print("Importing image %s...
def import_image(image_path, os_version)
Import image. Input parameters: :image_path: Image file path :os_version: Operating system version. e.g. rhel7.2
3.537889
3.987827
0.887172
# Import image if not exists import_image(image_path, os_version) # Start time spawn_start = time.time() # Create userid print("Creating userid %s ..." % userid) ret = sdk_client.send_request('guest_create', userid, cpu, memory, disk_list=disks_list, ...
def _run_guest(userid, image_path, os_version, profile, cpu, memory, network_info, disks_list)
Deploy and provision a virtual machine. Input parameters: :userid: USERID of the guest, no more than 8. :image_name: path of the image file :os_version: os version of the image file :profile: profile of the userid :cpu: the number of vcpus :m...
2.616813
2.599621
1.006613
global GUEST_USERID global GUEST_PROFILE global GUEST_VCPUS global GUEST_MEMORY global GUEST_ROOT_DISK_SIZE global DISK_POOL global IMAGE_PATH global IMAGE_OS_VERSION global GUEST_IP_ADDR global GATEWAY global CIDR global VSWITCH_NAME network_info = {'ip_addr': ...
def run_guest()
A sample for quick deploy and start a virtual guest.
3.294076
3.173675
1.037938
additional_properties = schema.get('addtionalProperties', True) if additional_properties: pattern_regexes = [] patterns = schema.get('patternProperties', None) if patterns: for regex in patterns: pattern_regexes.append(re.compile(regex)) for pa...
def _remove_unexpected_query_parameters(schema, req)
Remove unexpected properties from the req.GET.
3.293918
3.066684
1.074098
def add_validator(func): @functools.wraps(func) def wrapper(*args, **kwargs): if 'req' in kwargs: req = kwargs['req'] else: req = args[1] if req.environ['wsgiorg.routing_args'][1]: if _schema_validation_helper...
def query_schema(query_params_schema, min_version=None, max_version=None)
Register a schema to validate request query parameters.
2.658463
2.592717
1.025358
# Yield each chunk in the response body for chunk in response.iter_content(chunk_size=chunk_size): yield chunk # Once we're done streaming the body, ensure everything is closed. response.close()
def _close_after_stream(self, response, chunk_size)
Iterate over the content and ensure the response is closed after.
4.549363
3.648253
1.246998
with open(path, 'wb') as tfile: for chunk in data: tfile.write(chunk)
def _save_file(self, data, path)
Save an file to the specified path. :param data: binary data of the file :param path: path to save the file to
3.61045
4.049284
0.891627
result_lines = lines if app.config.napoleon_numpy_docstring: docstring = ExtendedNumpyDocstring( result_lines, app.config, app, what, name, obj, options) result_lines = docstring.lines() if app.config.napoleon_google_docstring: docstring = ExtendedGoogleDocstring( ...
def process_docstring(app, what, name, obj, options, lines)
Process the docstring for a given python object. Called when autodoc has read and processed a docstring. `lines` is a list of docstring lines that `_process_docstring` modifies in place to change what Sphinx outputs. The following settings in conf.py control what styles of docstrings will be parse...
2.396677
2.736004
0.875977
from sphinx.application import Sphinx if not isinstance(app, Sphinx): return # probably called by tests app.connect('autodoc-process-docstring', process_docstring) return napoleon_setup(app)
def setup(app)
Sphinx extension setup function When the extension is loaded, Sphinx imports this module and executes the ``setup()`` function, which in turn notifies Sphinx of everything the extension offers. Parameters ---------- app : sphinx.application.Sphinx Application object representing the Sp...
5.170999
6.214478
0.832089
if isinstance(x, (datetime64, datetime)): return format_timestamp(x) elif isinstance(x, (timedelta64, timedelta)): return format_timedelta(x) elif isinstance(x, ndarray): return list(x) if x.ndim else x[()] return x
def format_time(x)
Formats date values This function formats :class:`datetime.datetime` and :class:`datetime.timedelta` objects (and the corresponding numpy objects) using the :func:`xarray.core.formatting.format_timestamp` and the :func:`xarray.core.formatting.format_timedelta` functions. Parameters ---------- ...
3.23308
3.420929
0.945088
if callable(fmto.data_dependent): return fmto.data_dependent(data) return fmto.data_dependent
def is_data_dependent(fmto, data)
Check whether a formatoption is data dependent Parameters ---------- fmto: Formatoption The :class:`Formatoption` instance to check data: xarray.DataArray The data array to use if the :attr:`~Formatoption.data_dependent` attribute is a callable Returns ------- bool ...
3.213867
3.523053
0.912239
value = value if not validate else self.validate(value) # if the key in the plotter is not already set (i.e. it is initialized # with None, we set it) if self.plotter[self.key] is None: with self.plotter.no_validation: self.plotter[self.key] = value.c...
def set_value(self, value, validate=True, todefault=False)
Set (and validate) the value in the plotter Parameters ---------- %(Formatoption.set_value.parameters)s Notes ----- - If the current value in the plotter is None, then it will be set with the given `value`, otherwise the current value in the plotter is ...
3.97498
3.842441
1.034494
if self._ax is None: import matplotlib.pyplot as plt plt.figure() self._ax = plt.axes(projection=self._get_sample_projection()) return self._ax
def ax(self)
Axes instance of the plot
3.938134
3.737267
1.053747
if isinstance(self.data, InteractiveList): return dict(chain(*map( lambda arr: six.iteritems(arr.psy.base_variables), self.data))) else: return self.data.psy.base_variables
def base_variables(self)
A mapping from the base_variable names to the variables
8.698361
8.068622
1.078048
if isinstance(self.data, InteractiveList): return chain(*(arr.psy.iter_base_variables for arr in self.data)) else: return self.data.psy.iter_base_variables
def iter_base_variables(self)
A mapping from the base_variable names to the variables
7.732368
7.803952
0.990827
return {key: value for key, value in six.iteritems(self) if getattr(self, key).changed}
def changed(self)
:class:`dict` containing the key value pairs that are not the default
5.879532
6.188302
0.950104
ret = defaultdict(set) for key in self: ret[getattr(self, key).group].add(getattr(self, key)) return dict(ret)
def _fmto_groups(self)
Mapping from group to a set of formatoptions
4.460927
3.158848
1.412201
try: return self.data.psy.logger.getChild(self.__class__.__name__) except AttributeError: name = '%s.%s' % (self.__module__, self.__class__.__name__) return logging.getLogger(name)
def logger(self)
:class:`logging.Logger` of this plotter
4.382864
4.164914
1.05233
try: fmto.set_value(*args, **kwargs) except Exception as e: critical("Error while setting %s!" % fmto.key, logger=getattr(self, 'logger', None)) raise e
def _try2set(self, fmto, *args, **kwargs)
Sets the value in `fmto` and gives additional informations when fail Parameters ---------- fmto: Formatoption ``*args`` and ``**kwargs`` Anything that is passed to `fmto`s :meth:`~Formatoption.set_value` method
5.241565
5.146095
1.018552
return check_key( key, possible_keys=list(self), raise_error=raise_error, name='formatoption keyword', *args, **kwargs)
def check_key(self, key, raise_error=True, *args, **kwargs)
Checks whether the key is a valid formatoption Parameters ---------- %(check_key.parameters.no_possible_keys|name)s Returns ------- %(check_key.returns)s Raises ------ %(check_key.raises)s
10.60985
10.022836
1.058568
if isinstance(name, six.string_types): name = [name] dims = [dims] is_unstructured = [is_unstructured] N = len(name) if len(dims) != N or len(is_unstructured) != N: return [False] * N, [ 'Number of provided names (%i) and d...
def check_data(cls, name, dims, is_unstructured)
A validation method for the data shape The default method does nothing and should be subclassed to validate the results. If the plotter accepts a :class:`InteractiveList`, it should accept a list for name and dims Parameters ---------- name: str or list of str ...
2.631168
2.387964
1.101846
if data is None and self.data is not None: data = self.data else: self.data = data self.ax = ax if data is None: # nothing to do if no data is given return self.no_auto_update = not ( not self.no_auto_update or not data.ps...
def initialize_plot(self, data=None, ax=None, make_plot=True, clear=False, draw=False, remove=False, priority=None)
Initialize the plot for a data array Parameters ---------- data: InteractiveArray or ArrayList, optional Data object that shall be visualized. - If not None and `plot` is True, the given data is visualized. - If None and the :attr:`data` attribute is not Non...
4.253977
3.988559
1.066545
if self.disabled: return self.replot = self.replot or replot self._todefault = self._todefault or todefault if force is True: force = list(fmt) self._force.update( [ret[0] for ret in map(self.check_key, force or [])]) # check t...
def _register_update(self, fmt={}, replot=False, force=False, todefault=False)
Register formatoptions for the update Parameters ---------- fmt: dict Keys can be any valid formatoptions with the corresponding values (see the :attr:`formatoptions` attribute) replot: bool Boolean that determines whether the data specific formatopti...
5.219178
5.201404
1.003417
def update_the_others(): for fmto in fmtos: for other_fmto in fmto.shared: if not other_fmto.plotter._updating: other_fmto.plotter._register_update( force=[other_fmto.key]) for fmto in fmtos:...
def start_update(self, draw=None, queues=None, update_shared=True)
Conduct the registered plot updates This method starts the updates from what has been registered by the :meth:`update` method. You can call this method if you did not set the `auto_update` parameter to True when calling the :meth:`update` method and when the :attr:`no_auto_update` attri...
4.590915
4.765551
0.963354
# call the initialize_plot method. Note that clear can be set to # False if any fmto has requires_clearing attribute set to True, # because this then has been cleared before self.initialize_plot( self.data, self._ax, draw=draw, clear=clear or any( fmt...
def reinit(self, draw=None, clear=False)
Reinitializes the plot with the same data and on the same axes. Parameters ---------- %(InteractiveBase.start_update.parameters.draw)s clear: bool Whether to clear the axes or not Warnings -------- The axes may be cleared when calling this method (ev...
11.529953
11.531388
0.999876
for fig in self.figs2draw: fig.canvas.draw() self._figs2draw.clear()
def draw(self)
Draw the figures and those that are shared and have been changed
7.155304
5.045074
1.418275
fmtos = [] seen = set() for key in self._force: self._registered_updates.setdefault(key, getattr(self, key).value) for key, value in chain( six.iteritems(self._registered_updates), six.iteritems( {key: getattr(self,...
def _set_and_filter(self)
Filters the registered updates and sort out what is not needed This method filters out the formatoptions that have not changed, sets the new value and returns an iterable that is sorted by the priority (highest priority comes first) and dependencies Returns ------- list...
5.342847
4.86555
1.098097
def get_dependencies(fmto): if fmto is None: return [] return fmto.dependencies + list(chain(*map( lambda key: get_dependencies(getattr(self, key, None)), fmto.dependencies))) seen = seen or {fmto.key for fmto in fmtos} ...
def _insert_additionals(self, fmtos, seen=None)
Insert additional formatoptions into `fmtos`. This method inserts those formatoptions into `fmtos` that are required because one of the following criteria is fullfilled: 1. The :attr:`replot` attribute is True 2. Any formatoption with START priority is in `fmtos` 3. A dependenc...
3.441524
2.943642
1.169138
def pop_fmto(key): idx = fmtos_keys.index(key) del fmtos_keys[idx] return fmtos.pop(idx) def get_children(fmto, parents_keys): all_fmtos = fmtos_keys + parents_keys for key in fmto.children + fmto.dependencies: if key ...
def _sorted_by_priority(self, fmtos, changed=None)
Sort the formatoption objects by their priority and dependency Parameters ---------- fmtos: list list of :class:`Formatoption` instances changed: list the list of formatoption keys that have changed Yields ------ Formatoption ...
3.002838
2.780873
1.079818
def base_fmtos(base): return filter( lambda key: isinstance(getattr(cls, key), Formatoption), getattr(base, '_get_formatoptions', empty)(False)) def empty(*args, **kwargs): return list() fmtos = (attr for attr, obj in six.iteritem...
def _get_formatoptions(cls, include_bases=True)
Iterator over formatoptions This class method returns an iterator that contains all the formatoptions descriptors that are in this class and that are defined in the base classes Notes ----- There is absolutely no need to call this method besides the plotter init...
5.165813
5.781164
0.893559
all_keys = list(cls._get_formatoptions()) if isinstance(keys, six.string_types): keys = [keys] else: keys = list(keys or sorted(all_keys)) fmto_groups = defaultdict(list) for key in all_keys: fmto_groups[getattr(cls, key).group].append...
def _enhance_keys(cls, keys=None, *args, **kwargs)
Enhance the given keys by groups Parameters ---------- keys: list of str or None If None, the all formatoptions of the given class are used. Group names from the :attr:`psyplot.plotter.groups` mapping are replaced by the formatoptions Other Parameter...
3.747762
3.597045
1.0419
def titled_group(groupname): bars = str_indent + '*' * len(groupname) + '\n' return bars + str_indent + groupname + '\n' + bars keys = cls._enhance_keys(keys, *args, **kwargs) str_indent = " " * indent func = func or default_print_func # call thi...
def show_keys(cls, keys=None, indent=0, grouped=False, func=None, include_links=False, *args, **kwargs)
Classmethod to return a nice looking table with the given formatoptions Parameters ---------- %(Plotter._enhance_keys.parameters)s indent: int The indentation of the table grouped: bool, optional If True, the formatoptions are grouped corresponding to the...
3.802217
3.704078
1.026495
def titled_group(groupname): bars = str_indent + '*' * len(groupname) + '\n' return bars + str_indent + groupname + '\n' + bars func = func or default_print_func keys = cls._enhance_keys(keys, *args, **kwargs) str_indent = " " * indent if groupe...
def _show_doc(cls, fmt_func, keys=None, indent=0, grouped=False, func=None, include_links=False, *args, **kwargs)
Classmethod to print the formatoptions and their documentation This function is the basis for the :meth:`show_summaries` and :meth:`show_docs` methods Parameters ---------- fmt_func: function A function that takes the key, the key as it is printed, and the ...
3.551634
3.599557
0.986687
def find_summary(key, key_txt, doc): return '\n'.join(wrapper.wrap(doc[:doc.find('\n\n')])) str_indent = " " * indent wrapper = TextWrapper(width=80, initial_indent=str_indent + ' ' * 4, subsequent_indent=str_indent + ' ' * 4) return cls...
def show_summaries(cls, keys=None, indent=0, *args, **kwargs)
Classmethod to print the summaries of the formatoptions Parameters ---------- %(Plotter.show_keys.parameters)s Other Parameters ---------------- %(Plotter.show_keys.other_parameters)s Returns ------- %(Plotter.show_keys.returns)s See Al...
3.994404
4.4931
0.889009
def full_doc(key, key_txt, doc): return ('=' * len(key_txt)) + '\n' + doc + '\n' return cls._show_doc(full_doc, keys=keys, indent=indent, *args, **kwargs)
def show_docs(cls, keys=None, indent=0, *args, **kwargs)
Classmethod to print the full documentations of the formatoptions Parameters ---------- %(Plotter.show_keys.parameters)s Other Parameters ---------------- %(Plotter.show_keys.other_parameters)s Returns ------- %(Plotter.show_keys.returns)s ...
5.427734
6.117347
0.887269
return list(unique_everseen(chain( *map(lambda base: getattr(base, '_rcparams_string', []), cls.__mro__))))
def _get_rc_strings(cls)
Recursive method to get the base strings in the rcParams dictionary. This method takes the :attr:`_rcparams_string` attribute from the given `class` and combines it with the :attr:`_rcparams_string` attributes from the base classes. The returned frozenset can be used as base strings for...
10.144757
7.237605
1.401673
base_str = self._get_rc_strings() # to make sure that the '.' is not interpreted as a regex pattern, # we specify the pattern_base by ourselves pattern_base = map(lambda s: s.replace('.', '\.'), base_str) # pattern for valid keys being all formatoptions in this plotter ...
def _set_rc(self)
Method to set the rcparams and defaultParams for this plotter
6.769574
5.94255
1.13917
if self.disabled: return fmt = dict(fmt) if kwargs: fmt.update(kwargs) # if the data is None, update like a usual dictionary (but with # validation) if not self._initialized: for key, val in six.iteritems(fmt): ...
def update(self, fmt={}, replot=False, auto_update=False, draw=None, force=False, todefault=False, **kwargs)
Update the formatoptions and the plot If the :attr:`data` attribute of this plotter is None, the plotter is updated like a usual dictionary (see :meth:`dict.update`). Otherwise the update is registered and the plot is updated if `auto_update` is True or if the :meth:`start_update` metho...
4.933574
3.802649
1.297405
if isinstance(keys, str): keys = {keys} keys = set(self) if keys is None else set(keys) fmto_groups = self._fmto_groups keys.update(chain(*(map(lambda fmto: fmto.key, fmto_groups[key]) for key in keys.intersection(fmto_groups)))) k...
def _set_sharing_keys(self, keys)
Set the keys to share or unshare Parameters ---------- keys: string or iterable of strings The iterable may contain formatoptions that shall be shared (or unshared), or group names of formatoptions to share all formatoptions of that group (see the :attr:`fmt_...
4.686209
4.471654
1.047981
auto_update = auto_update or not self.no_auto_update if isinstance(plotters, Plotter): plotters = [plotters] keys = self._set_sharing_keys(keys) for plotter in plotters: for key in keys: fmto = self._shared.get(key, getattr(self, key)) ...
def share(self, plotters, keys=None, draw=None, auto_update=False)
Share the formatoptions of this plotter with others This method shares the formatoptions of this :class:`Plotter` instance with others to make sure that, if the formatoption of this changes, those of the others change as well Parameters ---------- plotters: list of :cla...
3.055125
3.259889
0.937187
auto_update = auto_update or not self.no_auto_update if isinstance(plotters, Plotter): plotters = [plotters] keys = self._set_sharing_keys(keys) for plotter in plotters: plotter.unshare_me(keys, auto_update=auto_update, draw=draw, ...
def unshare(self, plotters, keys=None, auto_update=False, draw=None)
Close the sharing connection of this plotter with others This method undoes the sharing connections made by the :meth:`share` method and releases the given `plotters` again, such that the formatoptions in this plotter may be updated again to values different from this one. Para...
3.277505
3.691408
0.887874
auto_update = auto_update or not self.no_auto_update keys = self._set_sharing_keys(keys) to_update = [] for key in keys: fmto = getattr(self, key) try: other_fmto = self._shared.pop(key) except KeyError: pass ...
def unshare_me(self, keys=None, auto_update=False, draw=None, update_other=True)
Close the sharing connection of this plotter with others This method undoes the sharing connections made by the :meth:`share` method and release this plotter again. Parameters ---------- keys: string or iterable of strings The formatoptions to unshare, or group name...
3.568762
3.693626
0.966195
if self._initializing or key not in self: return fmto = getattr(self, key) if self._old_fmt and key in self._old_fmt[-1]: old_val = self._old_fmt[-1][key] else: old_val = fmto.default if (fmto.diff(old_val) or (include_last and ...
def has_changed(self, key, include_last=True)
Determine whether a formatoption changed in the last update Parameters ---------- key: str A formatoption key contained in this plotter include_last: bool if True and the formatoption has been included in the last update, the return value will not be ...
4.862454
4.244027
1.145717
# Parse cmd string to a list if not isinstance(cmd, list): cmd = shlex.split(cmd) # Execute command rc = 0 output = "" try: output = subprocess.check_output(cmd, close_fds=True, stderr=subprocess.STDOUT) except subprocess.CalledP...
def execute(cmd)
execute command, return rc and output string. The cmd argument can be a string or a list composed of the command name and each of its argument. eg, ['/usr/bin/cp', '-r', 'src', 'dst']
2.758319
2.53158
1.089564
time_start = time.time() expiration = time_start + timeout retry = True while retry: expired = timeout and (time.time() > expiration) LOG.debug( "timeout is %(timeout)s, expiration is %(expiration)s, \ time_start is %(time_start)s" % ...
def looping_call(f, sleep=5, inc_sleep=0, max_sleep=60, timeout=600, exceptions=(), *args, **kwargs)
Helper function that to run looping call with fixed/dynamical interval. :param f: the looping call function or method. :param sleep: initial interval of the looping calls. :param inc_sleep: sleep time increment, default as 0. :param max_sleep: max sleep time. :param timeout: loop...
3.116707
3.102337
1.004632
s = s.upper() try: if s.endswith('G'): return float(s[:-1].strip()) * 1024 elif s.endswith('T'): return float(s[:-1].strip()) * 1024 * 1024 else: return float(s[:-1].strip()) except (IndexError, ValueError, KeyError, TypeError): errmsg...
def convert_to_mb(s)
Convert memory size from GB to MB.
2.671104
2.434044
1.097393
''' Validates a mac address''' if not isinstance(addr, six.string_types): return False valid = re.compile(r''' (^([0-9A-F]{2}[:]){5}([0-9A-F]{2})$) ''', re.VERBOSE | re.IGNORECASE) return valid.match(addr) is not None
def valid_mac_addr(addr)
Validates a mac address
2.775561
2.992491
0.927509
def decorator(function): @functools.wraps(function) def wrap_func(*args, **kwargs): if args[0]._skip_input_check: # skip input check return function(*args, **kwargs) # drop class object self inputs = args[1:] if (le...
def check_input_types(*types, **validkeys)
This is a function decorator to check all input parameters given to decorated function are in expected types. The checks can be skipped by specify skip_input_checks=True in decorated function. :param tuple types: expected types of input parameters to the decorated function ...
2.766794
2.778898
0.995644
try: yield except (ValueError, TypeError, IndexError, AttributeError, KeyError) as err: msg = ('Invalid smt response data: %s. Error: %s' % (data, six.text_type(err))) LOG.error(msg) raise exception.SDKInternalError(msg=msg)
def expect_invalid_resp_data(data='')
Catch exceptions when using zvm client response data.
4.930391
4.215283
1.169646
@functools.wraps(function) def decorated_function(*arg, **kwargs): try: return function(*arg, **kwargs) except (ValueError, TypeError, IndexError, AttributeError, KeyError) as err: msg = ('Invalid smt response data. Error: %s' % si...
def wrap_invalid_resp_data_error(function)
Catch exceptions when using zvm client response data.
3.071465
2.747905
1.117748
try: yield except exception.SDKInternalError as err: msg = err.format_message() raise exception.SDKInternalError(msg, modID=modID)
def expect_and_reraise_internal_error(modID='SDK')
Catch all kinds of zvm client request failure and reraise. modID: the moduleID that the internal error happens in.
3.64115
3.96375
0.918612
try: yield except exception.SDKSMTRequestFailed as err: msg = '' if action is not None: msg = "Failed to %s. " % action msg += "SMT error: %s" % err.format_message() LOG.error(msg) raise exception.SDKSMTRequestFailed(err.results, msg)
def log_and_reraise_smt_request_failed(action=None)
Catch SDK base exception and print error log before reraise exception. msg: the error message to be logged.
3.688506
3.785929
0.974267
cmd = ["sudo", "/sbin/vmcp", "query userid"] try: userid = subprocess.check_output(cmd, close_fds=True, stderr=subprocess.STDOUT) userid = bytes.decode(userid) userid = userid.split()[0] return...
def get_smt_userid()
Get the userid of smt server
4.207939
3.912145
1.075609
if CONF.zvm.namelist is not None: # namelist length limit should be 64, but there's bug limit to 8 # will change the limit to 8 once the bug fixed if len(CONF.zvm.namelist) <= 8: return CONF.zvm.namelist # return ''.join(('NL', get_smt_userid().rjust(6, '0')[-6:])) ...
def get_namelist()
Generate namelist. Either through set CONF.zvm.namelist, or by generate based on smt userid.
7.66925
5.693815
1.346944
lines = ['#!/bin/bash\n', 'echo -n %s > /etc/iucv_authorized_userid\n' % client] with open(fn, 'w') as f: f.writelines(lines)
def generate_iucv_authfile(fn, client)
Generate the iucv_authorized_userid file
3.740894
2.658799
1.406986
data_list = rawdata.split("\n") data = {} for ls in data_list: for k in list(dirt.keys()): if ls.__contains__(dirt[k]): data[k] = ls[(ls.find(dirt[k]) + len(dirt[k])):].strip() break if data == {}: msg = ("Invalid smt response data. Erro...
def translate_response_to_dict(rawdata, dirt)
Translate SMT response to a python dictionary. SMT response example: keyword1: value1\n keyword2: value2\n ... keywordn: valuen\n Will return a python dictionary: {keyword1: value1, keyword2: value2, ... keywordn: valuen,}
3.952973
4.018928
0.983589
# Check if the guest exists. guest_list_info = client.send_request('guest_list') # the string 'userid' need to be coded as 'u'userid' in case of py2 interpreter. userid_1 = (unicode(userid, "utf-8") if sys.version[0] == '2' else userid) if userid_1 not in guest_list_info['output']: Run...
def delete_guest(userid)
Destroy a virtual machine. Input parameters: :userid: USERID of the guest, last 8 if length > 8
5.320416
5.18984
1.02516
# Check if the guest exists. guest_list_info = client.send_request('guest_list') userid_1 = (unicode(userid, "utf-8") if sys.version[0] == '2' else userid) if userid_1 not in guest_list_info['output']: raise RuntimeError("Guest %s does not exist!" % userid) guest_describe_info = clie...
def describe_guest(userid)
Get the basic information of virtual machine. Input parameters: :userid: USERID of the guest, last 8 if length > 8
5.236436
5.454451
0.96003
image_name = os.path.basename(image_path) print("\nChecking if image %s exists ..." % image_name) image_query_info = client.send_request('image_query', imagename = image_name) if image_query_info['overallRC']: print("Importing image %s ..." % image_name) url = "file://" + image_pat...
def import_image(image_path, os_version)
Import the specific image. Input parameters: :image_path: Image file name :os_version: Operation System version. e.g. rhel7.4
2.737501
3.036622
0.901496
# Check if the userid already exists. guest_list_info = client.send_request('guest_list') userid_1 = (unicode(userid, "utf-8") if sys.version[0] == '2' else userid) if userid_1 in guest_list_info['output']: raise RuntimeError("Guest %s already exists!" % userid) # Create the guest. ...
def create_guest(userid, cpu, memory, disks_list, profile)
Create the userid. Input parameters: :userid: USERID of the guest, last 8 if length > 8 :cpu: the number of vcpus :memory: memory :disks_list: list of disks to add :profile: profile of the userid
3.199174
3.316457
0.964636
print("\nDeploying %s to %s ..." % (image_name, userid)) guest_deploy_info = client.send_request('guest_deploy', userid, image_name) # if failed to deploy, then delete the guest. if guest_deploy_info['overallRC']: print("\nFailed to deploy guest %s!\n%s" % (userid, guest_deploy_info)) ...
def deploy_guest(userid, image_name)
Deploy image to root disk. Input parameters: :userid: USERID of the guest, last 8 if length > 8 :image_path: Image file name
3.96862
4.272702
0.928831
print("\nConfiguring network interface for %s ..." % userid) network_create_info = client.send_request('guest_create_network_interface', userid, os_version, network_info) if network_create_info['overallRC']: raise RuntimeError("Failed to create ne...
def create_network(userid, os_version, network_info)
Create network device and configure network interface. Input parameters: :userid: USERID of the guest, last 8 if length > 8 :os_version: os version of the image file :network_info: dict of network info
3.97918
4.098343
0.970924
print("\nCoupleing to vswitch for %s ..." % userid) vswitch_info = client.send_request('guest_nic_couple_to_vswitch', userid, '1000', vswitch_name) if vswitch_info['overallRC']: raise RuntimeError("Failed to couple to vswitch for guest %s!\n%s" % ...
def coupleTo_vswitch(userid, vswitch_name)
Couple to vswitch. Input parameters: :userid: USERID of the guest, last 8 if length > 8 :network_info: dict of network info
4.296857
4.286424
1.002434
print("\nGranting user %s ..." % userid) user_grant_info = client.send_request('vswitch_grant_user', vswitch_name, userid) if user_grant_info['overallRC']: raise RuntimeError("Failed to grant user %s!" %userid) else: print("Succeeded to grant user %s!" % userid)
def grant_user(userid, vswitch_name)
Grant user. Input parameters: :userid: USERID of the guest, last 8 if length > 8 :network_info: dict of network info
4.722243
5.311415
0.889074
# Check the power state before starting guest. power_state_info = client.send_request('guest_get_power_state', userid) print("\nPower state is: %s." % power_state_info['output']) # start guest. guest_start_info = client.send_request('guest_start', userid) if guest_start_info['overallRC']:...
def start_guest(userid)
Power on the vm. Input parameters: :userid: USERID of the guest, last 8 if length > 8
2.645907
2.735666
0.967189
print("Start deploying a virtual machine:") # Import image if not exists. import_image(image_path, os_version) # Start time. spawn_start = time.time() # Create guest. create_guest(userid, cpu, memory, disks_list, profile) # Deploy image to root disk. image_na...
def _run_guest(userid, image_path, os_version, profile, cpu, memory, network_info, vswitch_name, disks_list)
Deploy and provide a virtual machine. Input parameters: :userid: USERID of the guest, no more than 8 :image_path: image file path :os_version: os version of the image file :profile: profile of the userid :cpu: the number of vc...
3.9104
3.956916
0.988244
global GUEST_USERID global GUEST_PROFILE global GUEST_VCPUS global GUEST_MEMORY global GUEST_ROOT_DISK_SIZE global DISK_POOL global IMAGE_PATH global IMAGE_OS_VERSION global GUEST_IP_ADDR global GATEWAY global CIDR global VSWITCH_NAME global NETWORK_INFO glob...
def _user_input_properties()
User input the properties of guest, image, and network.
2.759329
2.599663
1.061418
# user input the properties of guest, image and network. _user_input_properties() # run a guest. _run_guest(GUEST_USERID, IMAGE_PATH, IMAGE_OS_VERSION, GUEST_PROFILE, GUEST_VCPUS, GUEST_MEMORY, NETWORK_INFO, VSWITCH_NAME, DISKS_LIST)
def run_guest()
A sample for quickly deploy and start a virtual guest.
10.01779
9.600622
1.043452
_locals = {} with open(filename) as fp: exec(fp.read(), None, _locals) return _locals[varname]
def package_version(filename, varname)
Return package version string by reading `filename` and retrieving its module-global variable `varnam`.
3.03634
3.013479
1.007586
self.reqCnt = self.reqCnt + 1 # Determine whether the request will be capturing logs if 'captureLogs' in kwArgs.keys(): logFlag = kwArgs['captureLogs'] else: logFlag = self.captureLogs # Pass along or generate a request Id if 'requestId...
def request(self, requestData, **kwArgs)
Process a request. Input: Request as either a string or a list. captureLogs=<True|False> Enables or disables log capture per request. This overrides the value from SMT. requestId=<id> to pass a value for the request Id instead of using ...
5.232686
3.977131
1.315694
rh.printSysLog("Enter smapi.invokeSmapiApi") if rh.userid != 'HYPERVISOR': userid = rh.userid else: userid = 'dummy' parms = ["-T", userid] if 'operands' in rh.parms: parms.extend(rh.parms['operands']) results = invokeSMCLI(rh, rh.parms['apiName'], parms) if r...
def invokeSmapiApi(rh)
Invoke a SMAPI API. Input: Request Handle with the following properties: function - 'SMAPI' subfunction - 'API' userid - 'HYPERVISOR' parms['apiName'] - Name of API as defined by SMCLI parms['operands'] - List (array) of operands to send or ...
4.533221
3.552444
1.276085
if isinstance(init_info, list) and (len(init_info) == 5): self._dev_no = self._get_dev_number_from_line(init_info[0]) self._npiv_port = self._get_wwpn_from_line(init_info[2]) self._chpid = self._get_chpid_from_line(init_info[3]) self._physical_port = self...
def _parse(self, init_info)
Initialize a FCP device object from several lines of string describing properties of the FCP device. Here is a sample: opnstk1: FCP device number: B83D opnstk1: Status: Free opnstk1: NPIV world wide port number: NONE opnstk1: Channe...
3.280735
2.392212
1.371423
# TODO master_fcp_list (zvm_zhcp_fcp_list) really need? fcp_list = CONF.volume.fcp_list if fcp_list == '': errmsg = ("because CONF.volume.fcp_list is empty, " "no volume functions available") LOG.info(errmsg) return self...
def init_fcp(self, assigner_id)
init_fcp to init the FCP managed by this host
6.558826
6.146289
1.06712
complete_fcp_set = self._expand_fcp_list(fcp_list) fcp_info = self._get_all_fcp_info(assigner_id) lines_per_item = 5 num_fcps = len(fcp_info) // lines_per_item for n in range(0, num_fcps): fcp_init_info = fcp_info[(5 * n):(5 * (n + 1))] fcp = FCP...
def _init_fcp_pool(self, fcp_list, assigner_id)
The FCP infomation got from smt(zthin) looks like : host: FCP device number: xxxx host: Status: Active host: NPIV world wide port number: xxxxxxxx host: Channel path ID: xx host: Physical world wide port number: xxxxxxxx ...... host: F...
3.049882
2.916084
1.045883
LOG.debug("Expand FCP list %s" % fcp_list) if not fcp_list: return set() range_pattern = '[0-9a-fA-F]{1,4}(-[0-9a-fA-F]{1,4})?' match_pattern = "^(%(range)s)(;%(range)s)*$" % {'range': range_pattern} if not re.match(match_pattern, fcp_list): er...
def _expand_fcp_list(fcp_list)
Expand fcp list string into a python list object which contains each fcp devices in the list string. A fcp list is composed of fcp device addresses, range indicator '-', and split indicator ';'. For example, if fcp_list is "0011-0013;0015;0017-0018", expand_fcp_list(fcp_list) will retur...
2.369353
2.308061
1.026556
try: LOG.info("fcp %s found in CONF.volume.fcp_list, add it to db" % fcp) self.db.new(fcp) except Exception: LOG.info("failed to add fcp %s into db", fcp)
def _add_fcp(self, fcp)
add fcp to db if it's not in db but in fcp list and init it
5.306765
4.374906
1.213001
fcp_db_list = self.db.get_all() for fcp_rec in fcp_db_list: if not fcp_rec[0].lower() in self._fcp_pool: self._report_orphan_fcp(fcp_rec[0]) for fcp_conf_rec, v in self._fcp_pool.items(): res = self.db.get_from_fcp(fcp_conf_rec) # i...
def _sync_db_fcp_list(self)
sync db records from given fcp list, for example, you need warn if some FCP already removed while it's still in use, or info about the new FCP added
4.007758
3.784544
1.05898
fcp_list = self.db.get_from_assigner(assigner_id) if not fcp_list: new_fcp = self.db.find_and_reserve() if new_fcp is None: LOG.info("no more fcp to be allocated") return None LOG.debug("allocated %s fcp for %s assigner" % ...
def find_and_reserve_fcp(self, assigner_id)
reserve the fcp to assigner_id The function to reserve a fcp for user 1. Check whether assigner_id has a fcp already if yes, make the reserve of that record to 1 2. No fcp, then find a fcp and reserve it fcp will be returned, or None indicate no fcp
2.955166
3.03793
0.972756
# TODO: check assigner_id to make sure on the correct fcp record connections = self.db.get_connections_from_assigner(assigner_id) new = False if connections == 0: self.db.assign(fcp, assigner_id) new = True else: self.db.increase_usag...
def increase_fcp_usage(self, fcp, assigner_id=None)
Incrase fcp usage of given fcp Returns True if it's a new fcp, otherwise return False
4.574353
4.40181
1.039198
# get the unreserved FCP devices belongs to assigner_id available_list = [] free_unreserved = self.db.get_all_free_unreserved() for item in free_unreserved: available_list.append(item[0]) return available_list
def get_available_fcp(self)
get all the fcps not reserved
6.547527
5.414587
1.209239
LOG.info('Start to attach device to %s' % assigner_id) self.fcp_mgr.init_fcp(assigner_id) new = self.fcp_mgr.increase_fcp_usage(fcp, assigner_id) try: if new: self._dedicate_fcp(fcp, assigner_id) self._add_disk(fcp, assigner_id, target_ww...
def _attach(self, fcp, assigner_id, target_wwpn, target_lun, multipath, os_version, mount_point)
Attach a volume First, we need translate fcp into local wwpn, then dedicate fcp to the user if it's needed, after that call smt layer to call linux command
3.511293
3.476611
1.009976
LOG.info('Start to detach device from %s' % assigner_id) connections = self.fcp_mgr.decrease_fcp_usage(fcp, assigner_id) try: self._remove_disk(fcp, assigner_id, target_wwpn, target_lun, multipath, os_version, mount_point) if not co...
def _detach(self, fcp, assigner_id, target_wwpn, target_lun, multipath, os_version, mount_point)
Detach a volume from a guest
3.09055
3.095212
0.998494
fcp = connection_info['zvm_fcp'] fcp = fcp.lower() target_wwpn = connection_info['target_wwpn'] target_lun = connection_info['target_lun'] assigner_id = connection_info['assigner_id'] assigner_id = assigner_id.upper() multipath = connection_info['multipat...
def detach(self, connection_info)
Detach a volume from a guest
2.786974
2.660346
1.047598
empty_connector = {'zvm_fcp': [], 'wwpns': [], 'host': ''} # init fcp pool self.fcp_mgr.init_fcp(assigner_id) fcp_list = self.fcp_mgr.get_available_fcp() if not fcp_list: errmsg = "No available FCP device found." LOG.warning(errmsg) ...
def get_volume_connector(self, assigner_id)
Get connector information of the instance for attaching to volumes. Connector information is a dictionary representing the ip of the machine that will be making the connection, the name of the iscsi initiator and the hostname of the machine as follows:: { 'zvm_fcp':...
2.310158
2.177253
1.061043
start = (2 * r - 1) * 16 X = BY[start:start+16] # BlockMix - 1 tmp = [0]*16 for i in xrange(2 * r): # BlockMix - 2 #blockxor(BY, i * 16, X, 0, 16) # BlockMix - 3(inner) salsa20_8(X, tmp, BY, i * 16, BY, Yi + i*1...
def blockmix_salsa8(BY, Yi, r)
Blockmix; Used by SMix
2.992759
3.024627
0.989464
X[0:(0)+(32 * r)] = B[Bi:(Bi)+(32 * r)] for i in xrange(N): # ROMix - 2 V[i * (32 * r):(i * (32 * r))+(32 * r)] = X[0:(0)+(32 * r)] blockmix_salsa8(X, 32 * r, r) # ROMix - 4 for i in xrange(N): # ROMix - 6...
def smix(B, Bi, r, N, V, X)
SMix; a specific case of ROMix based on Salsa20/8
3.31247
3.092124
1.07126
check_args(password, salt, N, r, p, olen) # Everything is lists of 32-bit uints for all but pbkdf2 try: B = _pbkdf2('sha256', password, salt, 1, p * 128 * r) B = list(struct.unpack('<%dI' % (len(B) // 4), B)) XY = [0] * (64 * r) V = [0] * (32 * r * N) except (Me...
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.935367
4.146987
0.94897
return mcf_mod.scrypt_mcf(scrypt, password, salt, N, r, p, prefix)
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...
4.30875
8.012963
0.537722
for pm_name in plot._plot_methods: pm = getattr(plot, pm_name) plugin = pm._plugin if (plugin is not None and plugin not in _versions and pm.module in sys.modules): _versions.update(get_versions(key=lambda s: s == plugin))
def _update_versions()
Update :attr:`_versions` with the registered plotter methods
7.627968
6.549733
1.164623
import matplotlib.pyplot as plt axes = np.array([]) maxplots = maxplots or rows * cols kwargs.setdefault('figsize', [ min(8.*cols, 16), min(6.5*rows, 12)]) if for_maps: import cartopy.crs as ccrs subplot_kw = kwargs.setdefault('subplot_kw', {}) subplot_kw['projec...
def multiple_subplots(rows=1, cols=1, maxplots=None, n=1, delete=True, for_maps=False, *args, **kwargs)
Function to create subplots. This function creates so many subplots on so many figures until the specified number `n` is reached. Parameters ---------- rows: int The number of subplots per rows cols: int The number of subplots per column maxplots: int The number of ...
2.856023
3.050601
0.936217
@wraps(func) def wrapper(self, *args, **kwargs): if not self.is_main: return getattr(self.main, func.__name__)(*args, **kwargs) return func(self, *args, **kwargs) return wrapper
def _only_main(func)
Call the given `func` only from the main project
1.875908
1.972429
0.951065
if main: return project() if _current_project is None else _current_project else: return gcp(True) if _current_subproject is None else \ _current_subproject
def gcp(main=False)
Get the current project Parameters ---------- main: bool If True, the current main project is returned, otherwise the current subproject is returned. See Also -------- scp: Sets the current project project: Creates a new project
5.087996
4.05575
1.254514
global _current_subproject global _current_project if p is None: mp = project() if main or _current_project is None else \ _current_project _current_subproject = Project(main=mp) elif not main: _current_subproject = p else: _current_project = p
def _scp(p, main=False)
scp version that allows a bit more control over whether the project is a main project or not
4.823476
4.530292
1.064716
numbers = [project.num for project in _open_projects] if num in numbers: return _open_projects[numbers.index(num)] if num is None: num = max(numbers) + 1 if numbers else 1 project = PROJECT_CLS.new(num, *args, **kwargs) _open_projects.append(project) return project
def project(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 -------- scp: Sets the current project g...
3.078092
3.526723
0.872791
kws = dict(figs=figs, data=data, ds=ds, remove_only=remove_only) cp_num = gcp(True).num got_cp = False if num is None: project = gcp() scp(None) project.close(**kws) elif num == 'all': for project in _open_projects[:]: project.close(**kws) ...
def close(num=None, figs=True, data=True, ds=True, remove_only=False)
Close the project This method closes the current project (figures, data and datasets) or the project specified by `num` Parameters ---------- num: int, None or 'all' if :class:`int`, it specifies the number of the project, if None, the current subproject is closed, if ``'all'``, al...
3.395027
3.429412
0.989974
if plotter_cls is None: if ((import_plotter is None and rcParams['project.auto_import']) or import_plotter): try: plotter_cls = getattr(import_module(module), plotter_name) except Exception as e: critical(("Could not import %s!\n" ...
def register_plotter(identifier, module, plotter_name, plotter_cls=None, sorter=True, plot_func=True, import_plotter=None, **kwargs)
Register a :class:`psyplot.plotter.Plotter` for the projects This function registers plotters for the :class:`Project` class to allow a dynamical handling of different plotter classes. Parameters ---------- %(Project._register_plotter.parameters.no_plotter_cls)s sorter: bool, optional ...
2.3788
2.180067
1.091159
d = registered_plotters.get(identifier, {}) if sorter and hasattr(Project, identifier): delattr(Project, identifier) d['sorter'] = False if plot_func and hasattr(ProjectPlotter, identifier): for cls in [ProjectPlotter, DatasetPlotter, DataArrayPlotter]: delattr(cls, ...
def unregister_plotter(identifier, sorter=True, plot_func=True)
Unregister a :class:`psyplot.plotter.Plotter` for the projects Parameters ---------- identifier: str Name of the attribute that is used to filter for the instances belonging to this plotter or to create plots with this plotter sorter: bool If True, the identifier will be unregis...
3.269123
3.138694
1.041555