code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
device = '0.0.%s' % fcp
port_add = "echo '%s' > " % target_wwpn
port_add += "/sys/bus/ccw/drivers/zfcp/%s/port_add" % device
unit_add = "echo '%s' > " % target_lun
unit_add += "/sys/bus/ccw/drivers/zfcp/%(device)s/%(wwpn)s/unit_add\n"\
% {'device': de... | def _set_sysfs(self, fcp, target_wwpn, target_lun) | rhel6 set WWPN and LUN in sysfs | 3.565821 | 3.529099 | 1.010406 |
device = '0.0.%s' % fcp
set_zfcp_conf = 'echo "%(device)s %(wwpn)s %(lun)s" >> /etc/zfcp.conf'\
% {'device': device, 'wwpn': target_wwpn,
'lun': target_lun}
trigger_uevent = 'echo "add" >> /sys/bus/ccw/devices/%s/uevent\n'\
... | def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun) | rhel6 set WWPN and LUN in configuration files | 3.855309 | 3.890312 | 0.991003 |
device = '0.0.%s' % fcp
unit_add = "echo '%s' > " % target_lun
unit_add += "/sys/bus/ccw/drivers/zfcp/%(device)s/%(wwpn)s/unit_add\n"\
% {'device': device, 'wwpn': target_wwpn}
return unit_add | def _set_sysfs(self, fcp, target_wwpn, target_lun) | rhel7 set WWPN and LUN in sysfs | 5.811399 | 5.826233 | 0.997454 |
sub_str = '%(read)s %%k %(read)s %(write)s %(data)s qeth' % {
'read': channel_read,
'read': channel_read,
'write': channel_write,
'data': channel_da... | def _get_udev_rules(self, channel_read, channel_write, channel_data) | construct udev rules info. | 2.157583 | 2.149867 | 1.003589 |
vdev = vdev.lower()
rules_file_name = '/etc/udev/rules.d/51-qeth-0.0.%s.rules' % vdev
cmd = 'rm -f %s\n' % rules_file_name
address = '0.0.%s' % str(vdev).zfill(4)
udev_file_name = '/etc/udev/rules.d/70-persistent-net.rules'
cmd += "sed -i '/%s/d' %s\n" % (addres... | def _delete_vdev_info(self, vdev) | handle udev rules file. | 3.645405 | 3.245625 | 1.123175 |
device = '0.0.%s' % fcp
# host config
host_config = '/sbin/zfcp_host_configure %s 1' % device
# disk config
disk_config = '/sbin/zfcp_disk_configure ' +\
'%(device)s %(wwpn)s %(lun)s 1' %\
{'device': device, 'wwpn': target_wwpn... | def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun) | sles set WWPN and LUN in configuration files | 2.83908 | 2.844357 | 0.998145 |
# modprobe DM multipath kernel module
modprobe = 'modprobe dm_multipath'
conf_file = '#blacklist {\n'
conf_file += '#\tdevnode \\"*\\"\n'
conf_file += '#}\n'
conf_cmd = 'echo -e "%s" > /etc/multipath.conf' % conf_file
restart = self._restart_multipath()
... | def _set_zfcp_multipath(self) | sles | 6.775049 | 6.720705 | 1.008086 |
device = '0.0.%s' % fcp
# disk config
disk_config = '/sbin/zfcp_disk_configure ' +\
'%(device)s %(wwpn)s %(lun)s 0' %\
{'device': device, 'wwpn': target_wwpn,
'lun': target_lun}
# host config
host_config ... | def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath) | sles offline zfcp. sampe to all rhel distro. | 3.684314 | 3.58884 | 1.026603 |
cfg_files = []
cmd_strings = ''
network_config_file_name = self._get_network_file()
network_cfg_str = 'auto lo\n'
network_cfg_str += 'iface lo inet loopback\n'
net_enable_cmd = ''
if first:
clean_cmd = self._get_clean_command()
else:
... | def create_network_configuration_files(self, file_path, guest_networks,
first, active=False) | Generate network configuration files for guest vm
:param list guest_networks: a list of network info for the guest.
It has one dictionary that contain some of the below keys for
each network, the format is:
{'ip_addr': (str) IP address,
'dns_addr': (l... | 2.939048 | 2.85149 | 1.030706 |
vdev = vdev.lower()
network_config_file_name = self._get_network_file()
device = self._get_device_name(vdev)
cmd = '\n'.join(("num=$(sed -n '/auto %s/=' %s)" % (device,
network_config_file_name),
"dns=$(... | def _delete_vdev_info(self, vdev) | handle vdev related info. | 4.769705 | 4.65657 | 1.024296 |
host_config = '/sbin/chzdev zfcp-host %s -e' % fcp
device = '0.0.%s' % fcp
target = '%s:%s:%s' % (device, target_wwpn, target_lun)
disk_config = '/sbin/chzdev zfcp-lun %s -e\n' % target
return '\n'.join((host_config,
disk_config)) | def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun) | ubuntu zfcp configuration | 5.41331 | 5.326031 | 1.016387 |
device = '0.0.%s' % fcp
target = '%s:%s:%s' % (device, target_wwpn, target_lun)
disk_offline = '/sbin/chzdev zfcp-lun %s -d' % target
host_offline = '/sbin/chzdev zfcp-host %s -d' % fcp
offline_dev = 'chccwdev -d %s' % fcp
return '\n'.join((disk_offline,
... | def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath) | ubuntu offline zfcp. | 5.425825 | 5.126595 | 1.058368 |
supported = {'rhel': ['rhel', 'redhat', 'red hat'],
'sles': ['suse', 'sles'],
'ubuntu': ['ubuntu']}
os_version = os_version.lower()
for distro, patterns in supported.items():
for i in patterns:
if os_version.startswith(... | def parse_dist(self, os_version) | Separate os and version from os_version.
Possible return value are only:
('rhel', x.y) and ('sles', x.y) where x.y may not be digits | 4.661537 | 4.855239 | 0.960104 |
rh.printSysLog("Enter migrateVM.getStatus")
parms = ["-T", rh.userid]
if 'all' in rh.parms:
parms.extend(["-k", "status_target=ALL"])
elif 'incoming' in rh.parms:
parms.extend(["-k", "status_target=INCOMING"])
elif 'outgoing' in rh.parms:
parms.extend(["-k", "status_t... | def getStatus(rh) | Get status of a VMRelocate request.
Input:
Request Handle with the following properties:
function - 'MIGRATEVM'
subfunction - 'STATUS'
userid - userid of the virtual machine
parms['all'] - If present, set status_target to ALL.
parms['incoming']... | 4.197295 | 3.380974 | 1.241445 |
if self.function == 'HELP':
# General help for all functions.
self.printLn("N", "")
self.printLn("N", "Usage:")
self.printLn("N", " python " + self.cmdName + " --help")
for key in sorted(ReqHandle.funcHandler):
ReqHandle.func... | def driveFunction(self) | Drive the function/subfunction call.
Input:
Self with request filled in.
Output:
Request Handle updated with the results.
Overall return code - 0: successful, non-zero: error | 4.539351 | 4.197865 | 1.081348 |
self.printSysLog("Enter ReqHandle.parseCmdline")
# Save the request data based on the type of operand.
if isinstance(requestData, list):
self.requestString = ' '.join(requestData) # Request as a string
self.request = requestData # Request as a... | def parseCmdline(self, requestData) | Parse the request command string.
Input:
Self with request filled in.
Output:
Request Handle updated with the parsed information so that
it is accessible via key/value pairs for later processing.
Return code - 0: successful, non-zero: error | 2.805399 | 2.76773 | 1.01361 |
if 'E' in respType:
respString = '(Error) ' + respString
if 'W' in respType:
respString = '(Warning) ' + respString
if 'S' in respType:
self.printSysLog(respString)
self.results['response'] = (self.results['response'] +
... | def printLn(self, respType, respString) | Add one or lines of output to the response list.
Input:
Response type: One or more characters indicate type of response.
E - Error message
N - Normal message
S - Output should be logged
W - Warning message | 3.962635 | 3.696654 | 1.071952 |
if zvmsdklog.LOGGER.getloglevel() <= logging.DEBUG:
# print log only when debug is enabled
if self.daemon == '':
self.logger.debug(self.requestId + ": " + logString)
else:
self.daemon.logger.debug(self.requestId + ": " + logString)
... | def printSysLog(self, logString) | Log one or more lines. Optionally, add them to logEntries list.
Input:
Strings to be logged. | 5.625998 | 6.365277 | 0.883858 |
if 'reset' in kwArgs.keys():
reset = kwArgs['reset']
else:
reset = 0
if reset == 0:
# Not a reset. Set the keys from the provided dictionary.
for key in newResults.keys():
if key == 'response' or key == 'logEntries':
... | def updateResults(self, newResults, **kwArgs) | Update the results related to this request excluding the 'response'
and 'logEntries' values.
We specifically update (if present):
overallRC, rc, rs, errno.
Input:
Dictionary containing the results to be updated or an empty
dictionary the reset keyword was spe... | 2.808829 | 1.829165 | 1.53558 |
instance = copy(self)
i = len(instance._filters)
instance._filters.append({
'filter[field][%d]' % i: str(field),
'filter[operator][%d]' % i: str(operator),
'filter[value][%d]' % i: str(value),
})
return instance | def filter(self, field, operator, value) | Add a query filter to be applied to the next API list call for this resource.
:param field: Field name to filter by
:type field: str
:param operator: Operator value
:type operator: str
:param value: Value of filter
:type value: str
:par... | 3.098863 | 3.710754 | 0.835103 |
instance = copy(self)
instance._filters.append({
'resultsperpage': value
})
return instance | def resultsperpage(self, value) | Set the number of results that will be retrieved by the request.
:param value: 'resultsperpage' parameter value for the rest api call
:type value: str
Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object | 11.070643 | 14.061425 | 0.787306 |
instance = copy(self)
instance._filters.append({
'page': value
})
return instance | def page(self, value) | Set the page which will be returned.
:param value: 'page' parameter value for the rest api call
:type value: str
Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object | 12.498531 | 14.302301 | 0.873883 |
params = {}
for _filter in self._filters:
params.update(_filter)
return params | def filters(self) | Returns a merged dictionary of filters. | 7.442926 | 4.958097 | 1.501166 |
body = webob.exc.strip_tags(body)
status_code = int(status.split(None, 1)[0])
error_dict = {
'status': status_code,
'title': title,
'detail': body
}
return {'errors': [error_dict]} | def json_error_formatter(body, status, title, environ) | A json_formatter for webob exceptions. | 2.825673 | 2.683879 | 1.052832 |
try:
return super(SdkWsgify, self).call_func(req, *args, **kwargs)
except webob.exc.HTTPException as exc:
msg = ('encounter %(error)s error') % {'error': exc}
LOG.debug(msg)
exc.json_formatter = json_error_formatter
code = exc.status_i... | def call_func(self, req, *args, **kwargs) | Add json_error_formatter to any webob HTTPExceptions. | 4.819426 | 4.322768 | 1.114893 |
def load_lon():
return arange(ds.RasterXSize)*b[1]+b[0]
def load_lat():
return arange(ds.RasterYSize)*b[5]+b[3]
ds = self.ds
b = self.ds.GetGeoTransform() # bbox, interval
if with_dask:
lat = Array(
{('lat', 0): (load... | def _load_GeoTransform(self) | Calculate latitude and longitude variable calculated from the
gdal.Open.GetGeoTransform method | 3.316992 | 3.210173 | 1.033275 |
cwd = getcwd()
full_fname = os.path.join(cwd, fname)
if os.path.exists(full_fname):
return full_fname
if env_key in os.environ:
path = os.environ[env_key]
if os.path.exists(path):
if os.path.isdir(path):
full_fname = os.path.join(path, fname)
... | def psyplot_fname(env_key='PSYPLOTRC', fname='psyplotrc.yml',
if_exists=True) | Get the location of the config file.
The file location is determined in the following order
- `$PWD/psyplotrc.yml`
- environment variable `PSYPLOTRC` (pointing to the file location or a
directory containing the file `psyplotrc.yml`)
- `$PSYPLOTCONFIGDIR/psyplot`
- On Linux and osx,
... | 1.734066 | 1.774621 | 0.977147 |
if s is None:
return None
if os.path.exists(s):
return s
else:
raise ValueError('"%s" should be a path but it does not exist' % s) | def validate_path_exists(s) | If s is a path, return s, else False | 3.408563 | 3.168593 | 1.075734 |
try:
return dict(d)
except TypeError:
d = validate_path_exists(d)
try:
with open(d) as f:
return dict(yaml.load(f))
except Exception:
raise ValueError("Could not convert {} to dictionary!".format(d)) | def validate_dict(d) | Validate a dictionary
Parameters
----------
d: dict or str
If str, it must be a path to a yaml file
Returns
-------
dict
Raises
------
ValueError | 3.970888 | 4.04383 | 0.981962 |
'Convert b to a boolean or raise'
if isinstance(b, six.string_types):
b = b.lower()
if b is None or b == 'none':
return None
return validate_bool(b) | def validate_bool_maybe_none(b) | Convert b to a boolean or raise | 4.514147 | 3.368993 | 1.33991 |
if isinstance(b, six.string_types):
b = b.lower()
if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True):
return True
elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False):
return False
else:
raise ValueError('Could not convert "%s" to boolean' % b) | def validate_bool(b) | Convert b to a boolean or raise | 1.831145 | 1.832885 | 0.999051 |
if not isinstance(s, six.string_types):
raise ValueError("Did not found string!")
return six.text_type(s) | def validate_str(s) | Validate a string
Parameters
----------
s: str
Returns
-------
str
Raises
------
ValueError | 5.671498 | 9.621156 | 0.589482 |
if isinstance(s, six.string_types):
return [six.text_type(v.strip()) for v in s.split(',') if v.strip()]
else:
try:
return list(map(validate_str, s))
except TypeError as e:
raise ValueError(e.message) | def validate_stringlist(s) | Validate a list of strings
Parameters
----------
val: iterable of strings
Returns
-------
list
list of str
Raises
------
ValueError | 2.844733 | 3.662308 | 0.77676 |
base_str = safe_list(base_str)
pattern_base = safe_list(pattern_base or [])
for i, s in enumerate(base_str):
if '%(key)s' not in s:
base_str[i] += '%(key)s'
if pattern_base:
for i, s in enumerate(pattern_base):
if '%(key)s'... | def add_base_str(self, base_str, pattern='.+', pattern_base=None,
append=True) | Add further base string to this instance
Parameters
----------
base_str: str or list of str
Strings that are used as to look for keys to get and set keys in
the :attr:`base` dictionary. If a string does not contain
``'%(key)s'``, it will be appended at the en... | 2.322852 | 2.327854 | 0.997851 |
patterns = self.patterns
replace = self.replace
seen = set()
for key in six.iterkeys(self.base):
for pattern in patterns:
m = pattern.match(key)
if m:
ret = m.group('key') if replace else m.group()
... | def iterkeys(self) | Unsorted iterator over keys | 3.380252 | 3.526641 | 0.95849 |
depr = self._all_deprecated
return dict((key, val[1]) for key, val in
six.iteritems(self.defaultParams)
if key not in depr) | def validate(self) | Dictionary with validation methods as values | 10.310802 | 8.985151 | 1.147538 |
return {key: val[2] for key, val in six.iteritems(self.defaultParams)
if len(val) >= 3} | def descriptions(self) | The description of each keyword in the rcParams dictionary | 7.764838 | 5.477551 | 1.417575 |
key = self._get_depreceated(key)[0]
if key is not None:
self._connections[key].append(func) | def connect(self, key, func) | Connect a function to the given formatoption
Parameters
----------
key: str
The rcParams key
func: function
The function that shall be called when the rcParams key changes.
It must accept a single value that is the new value of the
key. | 8.303781 | 9.122028 | 0.9103 |
if key is None:
for key, connections in self._connections.items():
for conn in connections[:]:
if func is None or conn is func:
connections.remove(conn)
else:
connections = self._connections[key]
for... | def disconnect(self, key=None, func=None) | Disconnect the connections to the an rcParams key
Parameters
----------
key: str
The rcParams key. If None, all keys are used
func: function
The function that is connected. If None, all functions are
connected | 2.133966 | 2.385633 | 0.894507 |
if defaultParams is None:
defaultParams = self.defaultParams
self.update({key: val[0] for key, val in defaultParams.items()
if plotters or key != 'project.plotters'}) | def update_from_defaultParams(self, defaultParams=None,
plotters=True) | Update from the a dictionary like the :attr:`defaultParams`
Parameters
----------
defaultParams: dict
The :attr:`defaultParams` like dictionary. If None, the
:attr:`defaultParams` attribute will be updated
plotters: bool
If True, ``'project.plotters'`... | 4.389862 | 3.696357 | 1.187619 |
k = list(dict.keys(self))
k.sort()
return k | def keys(self) | Return sorted list of keys. | 5.816538 | 4.472183 | 1.300604 |
pattern_re = re.compile(pattern)
ret = RcParams()
ret.defaultParams = self.defaultParams
ret.update((key, value) for key, value in self.items()
if pattern_re.search(key))
return ret | def find_all(self, pattern) | Return the subset of this RcParams dictionary whose keys match,
using :func:`re.search`, the given ``pattern``.
Parameters
----------
pattern: str
pattern as suitable for re.compile
Returns
-------
RcParams
RcParams instance with entries ... | 5.275342 | 4.300161 | 1.226778 |
fname = fname or psyplot_fname()
if fname and os.path.exists(fname):
with open(fname) as f:
d = yaml.load(f)
self.update(d)
if (d.get('project.plotters.user') and
'project.plotters' in self):
... | def load_from_file(self, fname=None) | Update rcParams from user-defined settings
This function updates the instance with what is found in `fname`
Parameters
----------
fname: str
Path to the yaml configuration file. Possible keys of the
dictionary are defined by :data:`config.rcsetup.defaultParams`.... | 4.750636 | 4.300872 | 1.104575 |
if fname is not None and not overwrite and os.path.exists(fname):
raise IOError(
'%s already exists! Set overwrite=True to overwrite it!' % (
fname))
if six.PY2:
kwargs.setdefault('encoding', 'utf-8')
d = {key: val for key, val... | def dump(self, fname=None, overwrite=True, include_keys=None,
exclude_keys=['project.plotters'], include_descriptions=True,
**kwargs) | Dump this instance to a yaml file
Parameters
----------
fname: str or None
file name to write to. If None, the string that would be written
to a file is returned
overwrite: bool
If True and `fname` already exists, it will be overwritten
includ... | 2.460671 | 2.626714 | 0.936787 |
from pkg_resources import iter_entry_points
def load_plugin(ep):
if plugins_env == ['no']:
return False
elif ep.module_name in exclude_plugins:
return False
elif include_plugins and ep.module_name not in include_plugins:
... | def _load_plugin_entrypoints(self) | Load the modules for the psyplot plugins
Yields
------
pkg_resources.EntryPoint
The entry point for the psyplot plugin module | 3.032659 | 2.834213 | 1.070018 |
pm_env = os.getenv('PSYPLOT_PLOTMETHODS', '').split('::')
include_pms = [s[4:] for s in pm_env if s.startswith('yes:')]
exclude_pms = [s[3:] for s in pm_env if s.startswith('no:')]
logger = logging.getLogger(__name__)
plotters = self['project.plotters']
def_pl... | def load_plugins(self, raise_error=False) | Load the plotters and defaultParams from the plugins
This method loads the `plotters` attribute and `defaultParams`
attribute from the plugins that use the entry point specified by
`group`. Entry points must be objects (or modules) that have a
`defaultParams` and a `plotters` attribute.... | 3.190477 | 2.975058 | 1.072408 |
request_log = requestlog.RequestLog
header_addon = HeaderControl
fault_wrapper = FaultWrapper
application = handler.SdkHandler()
# currently we have 3 middleware
for middleware in (header_addon,
fault_wrapper,
request_log,
... | def deploy(project_name) | Assemble the middleware pipeline | 14.297334 | 12.013427 | 1.190113 |
LOG.info("Begin to power on vm %s", userid)
self._smtclient.guest_start(userid)
LOG.info("Complete power on vm %s", userid) | def guest_start(self, userid) | Power on z/VM instance. | 5.045881 | 4.125769 | 1.223016 |
LOG.info("Begin to reboot vm %s", userid)
self._smtclient.guest_reboot(userid)
LOG.info("Complete reboot vm %s", userid) | def guest_reboot(self, userid) | Reboot a guest vm. | 4.775968 | 4.639758 | 1.029357 |
LOG.info("Begin to reset vm %s", userid)
self._smtclient.guest_reset(userid)
LOG.info("Complete reset vm %s", userid) | def guest_reset(self, userid) | Reset z/VM instance. | 5.293084 | 4.706963 | 1.124522 |
# Check guest state is 'on'
state = self.get_power_state(userid)
if state != 'on':
LOG.error("Failed to live migrate guest %s, error: "
"guest is inactive, cann't perform live migrate." %
userid)
raise exception.SDKConflict... | def live_migrate_vm(self, userid, destination, parms, action) | Move an eligible, running z/VM(R) virtual machine transparently
from one z/VM system to another within an SSI cluster. | 5.381765 | 5.578352 | 0.964759 |
LOG.info("Creating the user directory for vm %s", userid)
info = self._smtclient.create_vm(userid, cpu, memory,
disk_list, user_profile,
max_cpu, max_mem, ipl_from,
ipl_param, ipl_loadparam... | def create_vm(self, userid, cpu, memory, disk_list,
user_profile, max_cpu, max_mem, ipl_from,
ipl_param, ipl_loadparam) | Create z/VM userid into user directory for a z/VM instance. | 4.2813 | 4.028599 | 1.062727 |
LOG.info("Begin to delete vm %s", userid)
self._smtclient.delete_vm(userid)
# remove userid from smapi namelist
self._smtclient.namelist_remove(self._namelist, userid)
LOG.info("Complete delete vm %s", userid) | def delete_vm(self, userid) | Delete z/VM userid for the instance. | 5.563234 | 5.501336 | 1.011251 |
LOG.debug("executing cmd: %s", cmdStr)
return self._smtclient.execute_cmd(userid, cmdStr) | def execute_cmd(self, userid, cmdStr) | Execute commands on the guest vm. | 4.786159 | 4.538716 | 1.054518 |
tmp_path = self._pathutils.get_guest_temp_path(userid)
if not os.path.exists(tmp_path):
os.makedirs(tmp_path)
tmp_file = tmp_path + '/hostname.sh'
lnxdist = self._dist_manager.get_linux_dist(os_version)()
lines = lnxdist.generate_set_hostname_script(hostname... | def set_hostname(self, userid, hostname, os_version) | Punch a script that used to set the hostname of the guest.
:param str guest: the user id of the guest
:param str hostname: the hostname of the guest
:param str os_version: version of guest operation system | 4.182808 | 4.009554 | 1.04321 |
rh.printSysLog("Enter generalUtils.cvtToBlocks")
blocks = 0
results = {'overallRC': 0, 'rc': 0, 'rs': 0, 'errno': 0}
blocks = diskSize.strip().upper()
lastChar = blocks[-1]
if lastChar == 'G' or lastChar == 'M':
# Convert the bytes to blocks
byteSize = blocks[:-1]
... | def cvtToBlocks(rh, diskSize) | Convert a disk storage value to a number of blocks.
Input:
Request Handle
Size of disk in bytes
Output:
Results structure:
overallRC - Overall return code for the function:
0 - Everything went ok
4 - Input validation error
... | 2.868963 | 2.602287 | 1.102477 |
rh.printSysLog("Enter generalUtils.cvtToMag")
mSize = ''
size = size / (1024 * 1024)
if size > (1024 * 5):
# Size is greater than 5G. Using "G" magnitude.
size = size / 1024
mSize = "%.1fG" % size
else:
# Size is less than or equal 5G. Using "M" magnitude.
... | def cvtToMag(rh, size) | Convert a size value to a number with a magnitude appended.
Input:
Request Handle
Size bytes
Output:
Converted value with a magnitude | 4.129141 | 3.750134 | 1.101065 |
rh.printSysLog("Enter generalUtils.getSizeFromPage")
bSize = float(page) * 4096
mSize = cvtToMag(rh, bSize)
rh.printSysLog("Exit generalUtils.getSizeFromPage, magSize: " + mSize)
return mSize | def getSizeFromPage(rh, page) | Convert a size value from page to a number with a magnitude appended.
Input:
Request Handle
Size in page
Output:
Converted value with a magnitude | 7.285954 | 7.914329 | 0.920603 |
time.sleep(1)
return resource.execute(url, params) | def default_52xhandler(response, resource, url, params) | Default 52x handler that loops every second until a non 52x response is received.
:param response: The response of the last executed api request.
:param resource: The resource of the last executed api request.
:param url: The url of the last executed api request sans encoded query parameters.
:param par... | 9.948505 | 10.30086 | 0.965794 |
if not self.api_token or not self.api_token_secret:
raise ImproperlyConfigured("'api_token' and 'api_token_secret' are required for authentication.")
if self.response_type not in ["json", "pson", "xml", "debug", None]:
raise ImproperlyConfigured("'%s' is an invalid resp... | def validate(self) | Perform validation check on properties. | 4.038989 | 3.846563 | 1.050025 |
response = requests.get(url, params=params, **self.config.requests_kwargs)
if 520 <= response.status_code < 530:
if self.config.handler52x:
return self.config.handler52x(response, self, url, params)
response.raise_for_status()
if not self.config.re... | def execute(self, url, params) | Executes a call to the API.
:param url: The full url for the api call.
:param params: Query parameters encoded in the request. | 3.159707 | 3.412476 | 0.925928 |
LOG.debug('Creating invokeScript shell in the folder %s'
% network_file_path)
invokeScript = "invokeScript.sh"
conf = "#!/bin/bash \n"
command = commands
for file in files_map:
target_path = file['target_path']
source_file = fil... | def _create_invokeScript(self, network_file_path, commands,
files_map) | invokeScript: Configure zLinux os network
invokeScript is included in the network.doscript, it is used to put
the network configuration file to the directory where it belongs and
call znetconfig to configure the network | 3.910533 | 3.493397 | 1.119407 |
# Generate the tar package for punch
LOG.debug('Creating network doscript in the folder %s'
% network_file_path)
network_doscript = os.path.join(network_file_path, 'network.doscript')
tar = tarfile.open(network_doscript, "w")
for file in os.listdir(netw... | def _create_network_doscript(self, network_file_path) | doscript: contains a invokeScript.sh which will do the special work
The network.doscript contains network configuration files and it will
be used by zvmguestconfigure to configure zLinux os network when it
starts up | 2.804409 | 2.795682 | 1.003122 |
a = (X[a1] + X[a2]) & 0xffffffff
X[destination] ^= ((a << b) | (a >> (32 - b))) | def R(X, destination, a1, a2, b) | A single Salsa20 row operation | 3.522991 | 3.139888 | 1.122012 |
# Merged blockxor for speed
for i in xrange(16):
x[i] = B[i] = B[i] ^ src[s_start + i]
# This is the actual Salsa 20/8: four identical double rounds
for i in xrange(4):
R(x, 4, 0,12, 7);R(x, 8, 4, 0, 9);R(x,12, 8, 4,13);R(x, 0,12, 8,18)
R(x, 9, 5, 1, 7);R(x,13, 9, 5, 9);R(... | def salsa20_8(B, x, src, s_start, dest, d_start) | Salsa20/8 http://en.wikipedia.org/wiki/Salsa20 | 1.899747 | 1.898803 | 1.000497 |
while True:
chunk = file_object.read(file_chunk_size)
if chunk:
yield chunk
else:
break | def fileChunkIter(file_object, file_chunk_size=65536) | Return an iterator to a file-like object that yields fixed size chunks
:param file_object: a file-like object
:param file_chunk_size: maximum size of chunk | 1.843777 | 2.543786 | 0.724816 |
check_args(password, salt, N, r, p, olen)
out = ctypes.create_string_buffer(olen)
ret = _libscrypt_scrypt(password, len(password), salt, len(salt),
N, r, p, out, len(out))
if ret:
raise ValueError
return out.raw | 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.... | 2.733487 | 3.31783 | 0.823878 |
if (prefix != SCRYPT_MCF_PREFIX_s1 and prefix != SCRYPT_MCF_PREFIX_ANY):
return mcf_mod.scrypt_mcf(scrypt, password, salt, N, r, p, prefix)
if isinstance(password, unicode):
password = password.encode('utf8')
elif not isinstance(password, bytes):
raise TypeError('password must b... | 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.978256 | 3.007589 | 0.990247 |
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')
if len(mcf) != 124 or b'\0' in ... | def scrypt_mcf_check(mcf, password) | Returns True if the password matches the given MCF hash | 2.653066 | 2.657126 | 0.998472 |
arrs = [[], [], []]
for group in line.split(' '):
for col, coord in enumerate(group.split('/')):
if coord:
arrs[col].append(int(coord))
return [tuple(arr) for arr in arrs] | def parse_mixed_delim_str(line) | Turns .obj face index string line into [verts, texcoords, normals] numeric tuples. | 3.922589 | 3.384922 | 1.158842 |
verts = defaultdict(list)
obj_props = []
with open(fname) as f:
lines = f.read().splitlines()
for line in lines:
if line:
split_line = line.strip().split(' ', 1)
if len(split_line) < 2:
continue
prefix, value = split_line[0], spl... | def read_objfile(fname) | Takes .obj filename and returns dict of object properties for each object in file. | 3.409614 | 3.361212 | 1.0144 |
fname_mtl = ''
geoms = read_objfile(fname_obj)
for line in open(fname_obj):
if line:
split_line = line.strip().split(' ', 1)
if len(split_line) < 2:
continue
prefix, data = split_line[0], split_line[1]
if 'mtllib' in prefix:
... | def read_wavefront(fname_obj) | Returns mesh dictionary along with their material dictionary from a wavefront (.obj and/or .mtl) file. | 3.028165 | 2.66646 | 1.13565 |
rh.printSysLog("Enter vmUtils.disableEnableDisk, userid: " + userid +
" addr: " + vaddr + " option: " + option)
results = {
'overallRC': 0,
'rc': 0,
'rs': 0,
'response': ''
}
for secs in [0.1, 0.4, 1, 1.5, 3, 7, 15, 32... | def disableEnableDisk(rh, userid, vaddr, option) | Disable or enable a disk.
Input:
Request Handle:
owning userid
virtual address
option ('-e': enable, '-d': disable)
Output:
Dictionary containing the following:
overallRC - overall return code, 0: success, non-zero: failure
rc - rc from th... | 3.828325 | 3.174911 | 1.205805 |
rh.printSysLog("Enter vmUtils.getPerfInfo, userid: " + useridlist)
parms = ["-T", rh.userid,
"-c", "1"]
results = invokeSMCLI(rh, "Image_Performance_Query", parms)
if results['overallRC'] != 0:
# SMCLI failed.
rh.printLn("ES", results['response'])
rh.printSysLog... | def getPerfInfo(rh, useridlist) | Get the performance information for a userid
Input:
Request Handle
Userid to query <- may change this to a list later.
Output:
Dictionary containing the following:
overallRC - overall return code, 0: success, non-zero: failure
rc - RC returned from SMCLI if over... | 2.998827 | 2.893277 | 1.036481 |
rh.printSysLog("Enter vmUtils.isLoggedOn, userid: " + userid)
results = {
'overallRC': 0,
'rc': 0,
'rs': 0,
}
cmd = ["sudo", "/sbin/vmcp", "query", "user", userid]
strCmd = ' '.join(cmd)
rh.printSysLog("Invoking: " + strCmd)
try:
... | def isLoggedOn(rh, userid) | Determine whether a virtual machine is logged on.
Input:
Request Handle:
userid being queried
Output:
Dictionary containing the following:
overallRC - overall return code, 0: success, non-zero: failure
rc - 0: if we got status. Otherwise, it is the
... | 3.682722 | 3.482841 | 1.05739 |
rh.printSysLog("Enter vmUtils.waitForOSState, userid: " + userid +
" state: " + desiredState +
" maxWait: " + str(maxQueries) +
" sleepSecs: " + str(sleepSecs))
results = {}
strCmd = "echo 'ping'"
stateFnd = False
... | def waitForOSState(rh, userid, desiredState, maxQueries=90, sleepSecs=5) | Wait for the virtual OS to go into the indicated state.
Input:
Request Handle
userid whose state is to be monitored
Desired state, 'up' or 'down', case sensitive
Maximum attempts to wait for desired state before giving up
Sleep duration between waits
Output:
Dictionar... | 3.964766 | 3.428546 | 1.156398 |
rh.printSysLog("Enter vmUtils.waitForVMState, userid: " + userid +
" state: " + desiredState +
" maxWait: " + str(maxQueries) +
" sleepSecs: " + str(sleepSecs))
results = {}
cmd = ["sudo", "/sbin/vmcp", "query", "user",... | def waitForVMState(rh, userid, desiredState, maxQueries=90, sleepSecs=5) | Wait for the virtual machine to go into the indicated state.
Input:
Request Handle
userid whose state is to be monitored
Desired state, 'on' or 'off', case sensitive
Maximum attempts to wait for desired state before giving up
Sleep duration between waits
Output:
Dicti... | 3.277894 | 3.18805 | 1.028182 |
stripped = line.stripped
return stripped.startswith('#') and not stripped.startswith('#{') | def match(self, context, line) | Match lines prefixed with a hash ("#") mark that don't look like text. | 9.279368 | 6.91865 | 1.341211 |
input = (i for i in input if i) # Omits `None` (empty wrappers) and empty chunks.
if encoding: # Automatically, and iteratively, encode the text if requested.
input = iterencode(input, encoding, errors=errors)
return input | def stream(input, encoding=None, errors='strict') | Safely iterate a template generator, ignoring ``None`` values and optionally stream encoding.
Used internally by ``cinje.flatten``, this allows for easy use of a template generator as a WSGI body. | 11.068237 | 10.465121 | 1.057631 |
input = stream(input, encoding, errors)
if file is None: # Exit early if we're not writing to a file.
return b''.join(input) if encoding else ''.join(input)
counter = 0
for chunk in input:
file.write(chunk)
counter += len(chunk)
return counter | def flatten(input, file=None, encoding=None, errors='strict') | Return a flattened representation of a cinje chunk stream.
This has several modes of operation. If no `file` argument is given, output will be returned as a string.
The type of string will be determined by the presence of an `encoding`; if one is given the returned value is a
binary string, otherwise the native u... | 3.586645 | 4.038981 | 0.888007 |
if isinstance(string, bytes):
string = string.decode('utf-8')
if ": def" in string or ":def" in string:
code = string.encode('utf8').decode('cinje')
name = None
else:
code = ": def {name}\n\n{string}".format(
name = name,
string = string,
).encode('utf8').decode('cinje')
environ = dict(co... | def fragment(string, name="anonymous", **context) | Translate a template fragment into a callable function.
**Note:** Use of this function is discouraged everywhere except tests, as no caching is implemented at this time.
Only one function may be declared, either manually, or automatically. If automatic defintition is chosen the
resulting function takes no argume... | 5.330512 | 5.028615 | 1.060036 |
global next, Iteration
next = next
Iteration = Iteration
total = len(obj) if isinstance(obj, Sized) else None
iterator = iter(obj)
first = True
last = False
i = 0
try:
value = next(iterator)
except StopIteration:
return
while True:
try:
next_value = next(iterator)
except StopIteration:
... | def iterate(obj) | Loop over an iterable and track progress, including first and last state.
On each iteration yield an Iteration named tuple with the first and last flags, current element index, total
iterable length (if possible to acquire), and value, in that order.
for iteration in iterate(something):
iteration.value # Do... | 3.063129 | 2.486461 | 1.231923 |
skipping = 0 # How many closing parenthesis will we need to skip?
start = None # Starting position of current match.
last = 0
i = 0
text = line.line
while i < len(text):
if start is not None:
if text[i] == '{':
skipping += 1
elif text[i] == '}':
if skipping:
skipping -= 1
... | def chunk(line, mapping={None: 'text', '${': 'escape', '#{': 'bless', '&{': 'args', '%{': 'format', '@{': 'json'}) | Chunkify and "tag" a block of text into plain text and code sections.
The first delimeter is blank to represent text sections, and keep the indexes aligned with the tags.
Values are yielded in the form (tag, text). | 2.757664 | 2.832311 | 0.973645 |
self.scope = 0
self.mapping = deque([0])
self._handler = [i() for i in sorted(self.handlers, key=lambda handler: handler.priority)] | def prepare(self) | Prepare the ordered list of transformers and reset context state to initial. | 9.157333 | 7.925405 | 1.15544 |
if 'init' not in self.flag:
root = True
self.prepare()
else:
root = False
# Track which lines were generated in response to which lines of source code.
# The end result is that there is one entry here for every line emitted, each integer representing the source
# line number that triggered i... | def stream(self) | The workhorse of cinje: transform input lines and emit output lines.
After constructing an instance with a set of input lines iterate this property to generate the template. | 10.411384 | 9.94258 | 1.047151 |
for handler in self._handler:
if handler.match(self, line):
return handler | def classify(self, line) | Identify the correct handler for a given line of input. | 5.885137 | 4.070869 | 1.445671 |
line = 0
deltas = []
for value in numbers:
deltas.append(value - line)
line = value
return b64encode(compress(b''.join(chr(i).encode('latin1') for i in deltas))).decode('latin1') | def red(numbers) | Encode the deltas to reduce entropy. | 4.456256 | 3.533185 | 1.261258 |
return line.kind == 'code' and line.partitioned[0] in self._both | def match(self, context, line) | Match code lines prefixed with a variety of keywords. | 26.420429 | 19.729652 | 1.339123 |
field = model_class._meta.get_field(field_name)
return (
field, # field
field.model, # model
not field.auto_created or field.concrete, # direct
field.many_to_many # m2m
) | def _get_field_by_name(model_class, field_name) | Compatible with old API of model_class._meta.get_field_by_name(field_name) | 4.16403 | 3.749869 | 1.110447 |
if hasattr(field, 'remote_field'):
return field.remote_field
elif hasattr(field, 'related'):
return field.related
else:
return None | def _get_remote_field(field) | Compatible with Django 1.8~1.10 ('related' was renamed to 'remote_field') | 2.422736 | 1.875849 | 1.291541 |
return list(set(chain.from_iterable(
(field.name, field.attname) if hasattr(field, 'attname') else (field.name,)
for field in model._meta.get_fields()
# For complete backwards compatibility, you may want to exclude
# GenericForeignKey from the results.
if not (field.many... | def _get_all_field_names(model) | 100% compatible version of the old API of model._meta.get_all_field_names()
From: https://docs.djangoproject.com/en/1.9/ref/models/meta/#migrating-from-the-old-api | 2.512236 | 2.296908 | 1.093747 |
relation_fields = []
all_fields_names = _get_all_field_names(model_class)
for field_name in all_fields_names:
field, model, direct, m2m = _get_field_by_name(model_class, field_name)
# get_all_field_names will return the same field
# both with and without _id. Ignore the duplicat... | def get_relation_fields_from_model(model_class) | Get related fields (m2m, FK, and reverse FK) | 3.501951 | 3.386127 | 1.034205 |
direct_fields = []
all_fields_names = _get_all_field_names(model_class)
for field_name in all_fields_names:
field, model, direct, m2m = _get_field_by_name(model_class, field_name)
if direct and not m2m and not _get_remote_field(field):
direct_fields += [field]
return dir... | def get_direct_fields_from_model(model_class) | Direct, not m2m, not FK | 2.755322 | 2.527605 | 1.090092 |
for path_section in path.split('__'):
if path_section:
try:
field, model, direct, m2m = _get_field_by_name(root_model, path_section)
except FieldDoesNotExist:
return root_model
if direct:
if _get_remote_field(field):
... | def get_model_from_path_string(root_model, path) | Return a model class for a related model
root_model is the class of the initial model
path is like foo__bar where bar is related to foo | 2.745099 | 2.66076 | 1.031697 |
fields = get_direct_fields_from_model(model_class)
app_label = model_class._meta.app_label
if field_name != '':
field, model, direct, m2m = _get_field_by_name(model_class, field_name)
path += field_name
path += '__'
if direct: # Direct field
try:
... | def get_fields(model_class, field_name='', path='') | Get fields and meta data from a model
:param model_class: A django model class
:param field_name: The field name to get sub fields from
:param path: path of our field in format
field_name__second_field_name__ect__
:returns: Returns fields and meta data about such fields
fields: Django m... | 2.819192 | 3.18236 | 0.885881 |
if field_name:
field, model, direct, m2m = _get_field_by_name(model_class, field_name)
if direct:
# Direct field
try:
new_model = _get_remote_field(field).parent_model()
except AttributeError:
new_model = _get_remote_field(fiel... | def get_related_fields(model_class, field_name, path="") | Get fields for a given model | 3.129896 | 3.105484 | 1.007861 |
if declaration is None:
declaration = Line(0, '')
if {'text', 'dirty'}.issubset(context.flag):
yield declaration.clone(line='yield "".join(_buffer)')
context.flag.remove('text') # This will force a new buffer to be constructed.
context.flag.remove('dirty')
if reconstruct:
for i in ensure_buf... | def flush_template(context, declaration=None, reconstruct=True) | Emit the code needed to flush the buffer.
Will only emit the yield and clear if the buffer is known to be dirty. | 7.564104 | 6.264402 | 1.207474 |
argspec = argspec.strip()
optimization = ", ".join(i + "=" + i for i in self.OPTIMIZE)
split = None
prefix = ''
suffix = ''
if argspec:
matches = list(self.STARARGS.finditer(argspec))
if matches:
split = matches[-1].span()[1] # Inject after, a la "*args>_<", as we're positional-only ... | def _optimize(self, context, argspec) | Inject speedup shortcut bindings into the argument specification for a function.
This assigns these labels to the local scope, avoiding a cascade through to globals(), saving time.
This also has some unfortunate side-effects for using these sentinels in argument default values! | 4.122964 | 3.927719 | 1.04971 |
model_name = model._meta.model_name
app_label = model._meta.app_label
can_change = user.has_perm(app_label + '.change_' + model_name)
can_view = user.has_perm(app_label + '.view_' + model_name)
return can_change or can_view | def _can_change_or_view(model, user) | Return True iff `user` has either change or view permission
for `model`. | 1.82404 | 1.871314 | 0.974738 |
model_class = queryset.model
objects = queryset
message = ""
if not _can_change_or_view(model_class, user):
return [], 'Permission Denied'
# Convert list of strings to DisplayField objects.
new_display_fields = []
for display_field in display_fields:
field_list = disp... | def report_to_list(queryset, display_fields, user) | Create list from a report with all data filtering.
queryset: initial queryset to generate results
display_fields: list of field references or DisplayField models
user: requesting user
Returns list, message in case of issues. | 3.429153 | 3.496035 | 0.980869 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.