repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
mfcloud/python-zvm-sdk | smtLayer/changeVM.py | dedicate | def dedicate(rh):
"""
Dedicate device.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'DEDICATEDM'
userid - userid of the virtual machine
parms['vaddr'] - Virtual address
parms['raddr'] - Real address
parms['mode'] - Read only mode or not.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.dedicate")
parms = [
"-T", rh.userid,
"-v", rh.parms['vaddr'],
"-r", rh.parms['raddr'],
"-R", rh.parms['mode']]
hideList = []
results = invokeSMCLI(rh,
"Image_Device_Dedicate_DM",
parms,
hideInLog=hideList)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
if results['overallRC'] == 0:
results = isLoggedOn(rh, rh.userid)
if (results['overallRC'] == 0 and results['rs'] == 0):
# Dedicate device to active configuration.
parms = [
"-T", rh.userid,
"-v", rh.parms['vaddr'],
"-r", rh.parms['raddr'],
"-R", rh.parms['mode']]
results = invokeSMCLI(rh, "Image_Device_Dedicate", parms)
if results['overallRC'] == 0:
rh.printLn("N", "Dedicated device " + rh.parms['vaddr'] +
" to the active configuration.")
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit changeVM.dedicate, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def dedicate(rh):
"""
Dedicate device.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'DEDICATEDM'
userid - userid of the virtual machine
parms['vaddr'] - Virtual address
parms['raddr'] - Real address
parms['mode'] - Read only mode or not.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.dedicate")
parms = [
"-T", rh.userid,
"-v", rh.parms['vaddr'],
"-r", rh.parms['raddr'],
"-R", rh.parms['mode']]
hideList = []
results = invokeSMCLI(rh,
"Image_Device_Dedicate_DM",
parms,
hideInLog=hideList)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
if results['overallRC'] == 0:
results = isLoggedOn(rh, rh.userid)
if (results['overallRC'] == 0 and results['rs'] == 0):
# Dedicate device to active configuration.
parms = [
"-T", rh.userid,
"-v", rh.parms['vaddr'],
"-r", rh.parms['raddr'],
"-R", rh.parms['mode']]
results = invokeSMCLI(rh, "Image_Device_Dedicate", parms)
if results['overallRC'] == 0:
rh.printLn("N", "Dedicated device " + rh.parms['vaddr'] +
" to the active configuration.")
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit changeVM.dedicate, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"dedicate",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter changeVM.dedicate\"",
")",
"parms",
"=",
"[",
"\"-T\"",
",",
"rh",
".",
"userid",
",",
"\"-v\"",
",",
"rh",
".",
"parms",
"[",
"'vaddr'",
"]",
",",
"\"-r\"",
",",
"rh",
"... | Dedicate device.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'DEDICATEDM'
userid - userid of the virtual machine
parms['vaddr'] - Virtual address
parms['raddr'] - Real address
parms['mode'] - Read only mode or not.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Dedicate",
"device",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/changeVM.py#L338-L395 | train | 43,600 |
mfcloud/python-zvm-sdk | smtLayer/changeVM.py | addAEMOD | def addAEMOD(rh):
"""
Send an Activation Modification Script to the virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'AEMOD'
userid - userid of the virtual machine
parms['aeScript'] - File specification of the AE script
parms['invparms'] - invparms operand
Output:
Request Handle updated with the results.
Return code - 0: ok
Return code - 4: input error, rs - 11 AE script not found
"""
rh.printSysLog("Enter changeVM.addAEMOD")
invokeScript = "invokeScript.sh"
trunkFile = "aemod.doscript"
fileClass = "X"
tempDir = tempfile.mkdtemp()
if os.path.isfile(rh.parms['aeScript']):
# Get the short name of our activation engine modifier script
if rh.parms['aeScript'].startswith("/"):
s = rh.parms['aeScript']
tmpAEScript = s[s.rindex("/") + 1:]
else:
tmpAEScript = rh.parms['aeScript']
# Copy the mod script to our temp directory
shutil.copyfile(rh.parms['aeScript'], tempDir + "/" + tmpAEScript)
# Create the invocation script.
conf = "#!/bin/bash \n"
baseName = os.path.basename(rh.parms['aeScript'])
parm = "/bin/bash %s %s \n" % (baseName, rh.parms['invParms'])
fh = open(tempDir + "/" + invokeScript, "w")
fh.write(conf)
fh.write(parm)
fh.close()
# Generate the tar package for punch
tar = tarfile.open(tempDir + "/" + trunkFile, "w")
for file in os.listdir(tempDir):
tar.add(tempDir + "/" + file, arcname=file)
tar.close()
# Punch file to reader
punch2reader(rh, rh.userid, tempDir + "/" + trunkFile, fileClass)
shutil.rmtree(tempDir)
else:
# Worker script does not exist.
shutil.rmtree(tempDir)
msg = msgs.msg['0400'][1] % (modId, rh.parms['aeScript'])
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0400'][0])
rh.printSysLog("Exit changeVM.addAEMOD, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def addAEMOD(rh):
"""
Send an Activation Modification Script to the virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'AEMOD'
userid - userid of the virtual machine
parms['aeScript'] - File specification of the AE script
parms['invparms'] - invparms operand
Output:
Request Handle updated with the results.
Return code - 0: ok
Return code - 4: input error, rs - 11 AE script not found
"""
rh.printSysLog("Enter changeVM.addAEMOD")
invokeScript = "invokeScript.sh"
trunkFile = "aemod.doscript"
fileClass = "X"
tempDir = tempfile.mkdtemp()
if os.path.isfile(rh.parms['aeScript']):
# Get the short name of our activation engine modifier script
if rh.parms['aeScript'].startswith("/"):
s = rh.parms['aeScript']
tmpAEScript = s[s.rindex("/") + 1:]
else:
tmpAEScript = rh.parms['aeScript']
# Copy the mod script to our temp directory
shutil.copyfile(rh.parms['aeScript'], tempDir + "/" + tmpAEScript)
# Create the invocation script.
conf = "#!/bin/bash \n"
baseName = os.path.basename(rh.parms['aeScript'])
parm = "/bin/bash %s %s \n" % (baseName, rh.parms['invParms'])
fh = open(tempDir + "/" + invokeScript, "w")
fh.write(conf)
fh.write(parm)
fh.close()
# Generate the tar package for punch
tar = tarfile.open(tempDir + "/" + trunkFile, "w")
for file in os.listdir(tempDir):
tar.add(tempDir + "/" + file, arcname=file)
tar.close()
# Punch file to reader
punch2reader(rh, rh.userid, tempDir + "/" + trunkFile, fileClass)
shutil.rmtree(tempDir)
else:
# Worker script does not exist.
shutil.rmtree(tempDir)
msg = msgs.msg['0400'][1] % (modId, rh.parms['aeScript'])
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0400'][0])
rh.printSysLog("Exit changeVM.addAEMOD, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"addAEMOD",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter changeVM.addAEMOD\"",
")",
"invokeScript",
"=",
"\"invokeScript.sh\"",
"trunkFile",
"=",
"\"aemod.doscript\"",
"fileClass",
"=",
"\"X\"",
"tempDir",
"=",
"tempfile",
".",
"mkdtemp",
"(... | Send an Activation Modification Script to the virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'AEMOD'
userid - userid of the virtual machine
parms['aeScript'] - File specification of the AE script
parms['invparms'] - invparms operand
Output:
Request Handle updated with the results.
Return code - 0: ok
Return code - 4: input error, rs - 11 AE script not found | [
"Send",
"an",
"Activation",
"Modification",
"Script",
"to",
"the",
"virtual",
"machine",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/changeVM.py#L453-L516 | train | 43,601 |
mfcloud/python-zvm-sdk | smtLayer/changeVM.py | addLOADDEV | def addLOADDEV(rh):
"""
Sets the LOADDEV statement in the virtual machine's directory entry.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'ADDLOADDEV'
userid - userid of the virtual machine
parms['boot'] - Boot program number
parms['addr'] - Logical block address of the boot record
parms['lun'] - One to eight-byte logical unit number
of the FCP-I/O device.
parms['wwpn'] - World-Wide Port Number
parms['scpDataType'] - SCP data type
parms['scpData'] - Designates information to be passed to the
program is loaded during guest IPL.
Note that any of the parms may be left blank, in which case
we will not update them.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.addLOADDEV")
# scpDataType and scpData must appear or disappear concurrently
if ('scpData' in rh.parms and 'scpDataType' not in rh.parms):
msg = msgs.msg['0014'][1] % (modId, "scpData", "scpDataType")
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0014'][0])
return
if ('scpDataType' in rh.parms and 'scpData' not in rh.parms):
if rh.parms['scpDataType'].lower() == "delete":
scpDataType = 1
else:
# scpDataType and scpData must appear or disappear
# concurrently unless we're deleting data
msg = msgs.msg['0014'][1] % (modId, "scpDataType", "scpData")
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0014'][0])
return
scpData = ""
if 'scpDataType' in rh.parms:
if rh.parms['scpDataType'].lower() == "hex":
scpData = rh.parms['scpData']
scpDataType = 3
elif rh.parms['scpDataType'].lower() == "ebcdic":
scpData = rh.parms['scpData']
scpDataType = 2
# scpDataType not hex, ebcdic or delete
elif rh.parms['scpDataType'].lower() != "delete":
msg = msgs.msg['0016'][1] % (modId, rh.parms['scpDataType'])
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0016'][0])
return
else:
# Not specified, 0 for do nothing
scpDataType = 0
scpData = ""
if 'boot' not in rh.parms:
boot = ""
else:
boot = rh.parms['boot']
if 'addr' not in rh.parms:
block = ""
else:
block = rh.parms['addr']
if 'lun' not in rh.parms:
lun = ""
else:
lun = rh.parms['lun']
# Make sure it doesn't have the 0x prefix
lun.replace("0x", "")
if 'wwpn' not in rh.parms:
wwpn = ""
else:
wwpn = rh.parms['wwpn']
# Make sure it doesn't have the 0x prefix
wwpn.replace("0x", "")
parms = [
"-T", rh.userid,
"-b", boot,
"-k", block,
"-l", lun,
"-p", wwpn,
"-s", str(scpDataType)]
if scpData != "":
parms.extend(["-d", scpData])
results = invokeSMCLI(rh, "Image_SCSI_Characteristics_Define_DM", parms)
# SMAPI API failed.
if results['overallRC'] != 0:
rh.printLn("ES", results['response'])
rh.updateResults(results)
rh.printSysLog("Exit changeVM.addLOADDEV, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def addLOADDEV(rh):
"""
Sets the LOADDEV statement in the virtual machine's directory entry.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'ADDLOADDEV'
userid - userid of the virtual machine
parms['boot'] - Boot program number
parms['addr'] - Logical block address of the boot record
parms['lun'] - One to eight-byte logical unit number
of the FCP-I/O device.
parms['wwpn'] - World-Wide Port Number
parms['scpDataType'] - SCP data type
parms['scpData'] - Designates information to be passed to the
program is loaded during guest IPL.
Note that any of the parms may be left blank, in which case
we will not update them.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.addLOADDEV")
# scpDataType and scpData must appear or disappear concurrently
if ('scpData' in rh.parms and 'scpDataType' not in rh.parms):
msg = msgs.msg['0014'][1] % (modId, "scpData", "scpDataType")
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0014'][0])
return
if ('scpDataType' in rh.parms and 'scpData' not in rh.parms):
if rh.parms['scpDataType'].lower() == "delete":
scpDataType = 1
else:
# scpDataType and scpData must appear or disappear
# concurrently unless we're deleting data
msg = msgs.msg['0014'][1] % (modId, "scpDataType", "scpData")
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0014'][0])
return
scpData = ""
if 'scpDataType' in rh.parms:
if rh.parms['scpDataType'].lower() == "hex":
scpData = rh.parms['scpData']
scpDataType = 3
elif rh.parms['scpDataType'].lower() == "ebcdic":
scpData = rh.parms['scpData']
scpDataType = 2
# scpDataType not hex, ebcdic or delete
elif rh.parms['scpDataType'].lower() != "delete":
msg = msgs.msg['0016'][1] % (modId, rh.parms['scpDataType'])
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0016'][0])
return
else:
# Not specified, 0 for do nothing
scpDataType = 0
scpData = ""
if 'boot' not in rh.parms:
boot = ""
else:
boot = rh.parms['boot']
if 'addr' not in rh.parms:
block = ""
else:
block = rh.parms['addr']
if 'lun' not in rh.parms:
lun = ""
else:
lun = rh.parms['lun']
# Make sure it doesn't have the 0x prefix
lun.replace("0x", "")
if 'wwpn' not in rh.parms:
wwpn = ""
else:
wwpn = rh.parms['wwpn']
# Make sure it doesn't have the 0x prefix
wwpn.replace("0x", "")
parms = [
"-T", rh.userid,
"-b", boot,
"-k", block,
"-l", lun,
"-p", wwpn,
"-s", str(scpDataType)]
if scpData != "":
parms.extend(["-d", scpData])
results = invokeSMCLI(rh, "Image_SCSI_Characteristics_Define_DM", parms)
# SMAPI API failed.
if results['overallRC'] != 0:
rh.printLn("ES", results['response'])
rh.updateResults(results)
rh.printSysLog("Exit changeVM.addLOADDEV, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"addLOADDEV",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter changeVM.addLOADDEV\"",
")",
"# scpDataType and scpData must appear or disappear concurrently",
"if",
"(",
"'scpData'",
"in",
"rh",
".",
"parms",
"and",
"'scpDataType'",
"not",
"in",
"rh... | Sets the LOADDEV statement in the virtual machine's directory entry.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'ADDLOADDEV'
userid - userid of the virtual machine
parms['boot'] - Boot program number
parms['addr'] - Logical block address of the boot record
parms['lun'] - One to eight-byte logical unit number
of the FCP-I/O device.
parms['wwpn'] - World-Wide Port Number
parms['scpDataType'] - SCP data type
parms['scpData'] - Designates information to be passed to the
program is loaded during guest IPL.
Note that any of the parms may be left blank, in which case
we will not update them.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Sets",
"the",
"LOADDEV",
"statement",
"in",
"the",
"virtual",
"machine",
"s",
"directory",
"entry",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/changeVM.py#L558-L663 | train | 43,602 |
mfcloud/python-zvm-sdk | smtLayer/changeVM.py | purgeRDR | def purgeRDR(rh):
"""
Purge the reader belonging to the virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'PURGERDR'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.purgeRDR")
results = purgeReader(rh)
rh.updateResults(results)
rh.printSysLog("Exit changeVM.purgeRDR, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def purgeRDR(rh):
"""
Purge the reader belonging to the virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'PURGERDR'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.purgeRDR")
results = purgeReader(rh)
rh.updateResults(results)
rh.printSysLog("Exit changeVM.purgeRDR, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"purgeRDR",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter changeVM.purgeRDR\"",
")",
"results",
"=",
"purgeReader",
"(",
"rh",
")",
"rh",
".",
"updateResults",
"(",
"results",
")",
"rh",
".",
"printSysLog",
"(",
"\"Exit changeVM.purgeRDR,... | Purge the reader belonging to the virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'PURGERDR'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Purge",
"the",
"reader",
"belonging",
"to",
"the",
"virtual",
"machine",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/changeVM.py#L826-L846 | train | 43,603 |
mfcloud/python-zvm-sdk | smtLayer/changeVM.py | removeDisk | def removeDisk(rh):
"""
Remove a disk from a virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'REMOVEDISK'
userid - userid of the virtual machine
parms['vaddr'] - Virtual address
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.removeDisk")
results = {'overallRC': 0, 'rc': 0, 'rs': 0}
# Is image logged on
loggedOn = False
results = isLoggedOn(rh, rh.userid)
if results['overallRC'] == 0:
if results['rs'] == 0:
loggedOn = True
results = disableEnableDisk(
rh,
rh.userid,
rh.parms['vaddr'],
'-d')
if results['overallRC'] != 0:
rh.printLn("ES", results['response'])
rh.updateResults(results)
if results['overallRC'] == 0 and loggedOn:
strCmd = "/sbin/vmcp detach " + rh.parms['vaddr']
results = execCmdThruIUCV(rh, rh.userid, strCmd)
if results['overallRC'] != 0:
if re.search('(^HCP\w\w\w040E)', results['response']):
# Device does not exist, ignore the error
results = {'overallRC': 0, 'rc': 0, 'rs': 0, 'response': ''}
else:
rh.printLn("ES", results['response'])
rh.updateResults(results)
if results['overallRC'] == 0:
# Remove the disk from the user entry.
parms = [
"-T", rh.userid,
"-v", rh.parms['vaddr'],
"-e", "0"]
results = invokeSMCLI(rh, "Image_Disk_Delete_DM", parms)
if results['overallRC'] != 0:
if (results['overallRC'] == 8 and results['rc'] == 208 and
results['rs'] == 36):
# Disk does not exist, ignore the error
results = {'overallRC': 0, 'rc': 0, 'rs': 0, 'response': ''}
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
else:
# Unexpected error. Message already sent.
rh.updateResults(results)
rh.printSysLog("Exit changeVM.removeDisk, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def removeDisk(rh):
"""
Remove a disk from a virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'REMOVEDISK'
userid - userid of the virtual machine
parms['vaddr'] - Virtual address
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter changeVM.removeDisk")
results = {'overallRC': 0, 'rc': 0, 'rs': 0}
# Is image logged on
loggedOn = False
results = isLoggedOn(rh, rh.userid)
if results['overallRC'] == 0:
if results['rs'] == 0:
loggedOn = True
results = disableEnableDisk(
rh,
rh.userid,
rh.parms['vaddr'],
'-d')
if results['overallRC'] != 0:
rh.printLn("ES", results['response'])
rh.updateResults(results)
if results['overallRC'] == 0 and loggedOn:
strCmd = "/sbin/vmcp detach " + rh.parms['vaddr']
results = execCmdThruIUCV(rh, rh.userid, strCmd)
if results['overallRC'] != 0:
if re.search('(^HCP\w\w\w040E)', results['response']):
# Device does not exist, ignore the error
results = {'overallRC': 0, 'rc': 0, 'rs': 0, 'response': ''}
else:
rh.printLn("ES", results['response'])
rh.updateResults(results)
if results['overallRC'] == 0:
# Remove the disk from the user entry.
parms = [
"-T", rh.userid,
"-v", rh.parms['vaddr'],
"-e", "0"]
results = invokeSMCLI(rh, "Image_Disk_Delete_DM", parms)
if results['overallRC'] != 0:
if (results['overallRC'] == 8 and results['rc'] == 208 and
results['rs'] == 36):
# Disk does not exist, ignore the error
results = {'overallRC': 0, 'rc': 0, 'rs': 0, 'response': ''}
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
else:
# Unexpected error. Message already sent.
rh.updateResults(results)
rh.printSysLog("Exit changeVM.removeDisk, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"removeDisk",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter changeVM.removeDisk\"",
")",
"results",
"=",
"{",
"'overallRC'",
":",
"0",
",",
"'rc'",
":",
"0",
",",
"'rs'",
":",
"0",
"}",
"# Is image logged on",
"loggedOn",
"=",
"False"... | Remove a disk from a virtual machine.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'REMOVEDISK'
userid - userid of the virtual machine
parms['vaddr'] - Virtual address
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Remove",
"a",
"disk",
"from",
"a",
"virtual",
"machine",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/changeVM.py#L849-L920 | train | 43,604 |
mfcloud/python-zvm-sdk | zvmconnector/connector.py | ZVMConnector.send_request | def send_request(self, api_name, *api_args, **api_kwargs):
"""Refer to SDK API documentation.
:param api_name: SDK API name
:param *api_args: SDK API sequence parameters
:param **api_kwargs: SDK API keyword parameters
"""
return self.conn.request(api_name, *api_args, **api_kwargs) | python | def send_request(self, api_name, *api_args, **api_kwargs):
"""Refer to SDK API documentation.
:param api_name: SDK API name
:param *api_args: SDK API sequence parameters
:param **api_kwargs: SDK API keyword parameters
"""
return self.conn.request(api_name, *api_args, **api_kwargs) | [
"def",
"send_request",
"(",
"self",
",",
"api_name",
",",
"*",
"api_args",
",",
"*",
"*",
"api_kwargs",
")",
":",
"return",
"self",
".",
"conn",
".",
"request",
"(",
"api_name",
",",
"*",
"api_args",
",",
"*",
"*",
"api_kwargs",
")"
] | Refer to SDK API documentation.
:param api_name: SDK API name
:param *api_args: SDK API sequence parameters
:param **api_kwargs: SDK API keyword parameters | [
"Refer",
"to",
"SDK",
"API",
"documentation",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmconnector/connector.py#L89-L96 | train | 43,605 |
mfcloud/python-zvm-sdk | smtLayer/getHost.py | getDiskPoolNames | def getDiskPoolNames(rh):
"""
Obtain the list of disk pools known to the directory manager.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'DISKPOOLNAMES'
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter getHost.getDiskPoolNames")
parms = ["-q", "1", "-e", "3", "-T", "dummy"]
results = invokeSMCLI(rh, "Image_Volume_Space_Query_DM", parms)
if results['overallRC'] == 0:
for line in results['response'].splitlines():
poolName = line.partition(' ')[0]
rh.printLn("N", poolName)
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit getHost.getDiskPoolNames, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def getDiskPoolNames(rh):
"""
Obtain the list of disk pools known to the directory manager.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'DISKPOOLNAMES'
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter getHost.getDiskPoolNames")
parms = ["-q", "1", "-e", "3", "-T", "dummy"]
results = invokeSMCLI(rh, "Image_Volume_Space_Query_DM", parms)
if results['overallRC'] == 0:
for line in results['response'].splitlines():
poolName = line.partition(' ')[0]
rh.printLn("N", poolName)
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit getHost.getDiskPoolNames, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"getDiskPoolNames",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter getHost.getDiskPoolNames\"",
")",
"parms",
"=",
"[",
"\"-q\"",
",",
"\"1\"",
",",
"\"-e\"",
",",
"\"3\"",
",",
"\"-T\"",
",",
"\"dummy\"",
"]",
"results",
"=",
"invokeSMC... | Obtain the list of disk pools known to the directory manager.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'DISKPOOLNAMES'
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Obtain",
"the",
"list",
"of",
"disk",
"pools",
"known",
"to",
"the",
"directory",
"manager",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/getHost.py#L110-L139 | train | 43,606 |
mfcloud/python-zvm-sdk | smtLayer/getHost.py | getDiskPoolSpace | def getDiskPoolSpace(rh):
"""
Obtain disk pool space information for all or a specific disk pool.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'DISKPOOLSPACE'
parms['poolName'] - Name of the disk pool. Optional,
if not present then information for all
disk pools is obtained.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter getHost.getDiskPoolSpace")
results = {'overallRC': 0}
if 'poolName' not in rh.parms:
poolNames = ["*"]
else:
if isinstance(rh.parms['poolName'], list):
poolNames = rh.parms['poolName']
else:
poolNames = [rh.parms['poolName']]
if results['overallRC'] == 0:
# Loop thru each pool getting total. Do it for query 2 & 3
totals = {}
for qType in ["2", "3"]:
parms = [
"-q", qType,
"-e", "3",
"-T", "DUMMY",
"-n", " ".join(poolNames)]
results = invokeSMCLI(rh, "Image_Volume_Space_Query_DM", parms)
if results['overallRC'] == 0:
for line in results['response'].splitlines():
parts = line.split()
if len(parts) == 9:
poolName = parts[7]
else:
poolName = parts[4]
if poolName not in totals:
totals[poolName] = {"2": 0., "3": 0.}
if parts[1][:4] == "3390":
totals[poolName][qType] += int(parts[3]) * 737280
elif parts[1][:4] == "9336":
totals[poolName][qType] += int(parts[3]) * 512
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
break
if results['overallRC'] == 0:
if len(totals) == 0:
# No pool information found.
msg = msgs.msg['0402'][1] % (modId, " ".join(poolNames))
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0402'][0])
else:
# Produce a summary for each pool
for poolName in sorted(totals):
total = totals[poolName]["2"] + totals[poolName]["3"]
rh.printLn("N", poolName + " Total: " +
generalUtils.cvtToMag(rh, total))
rh.printLn("N", poolName + " Used: " +
generalUtils.cvtToMag(rh, totals[poolName]["3"]))
rh.printLn("N", poolName + " Free: " +
generalUtils.cvtToMag(rh, totals[poolName]["2"]))
rh.printSysLog("Exit getHost.getDiskPoolSpace, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def getDiskPoolSpace(rh):
"""
Obtain disk pool space information for all or a specific disk pool.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'DISKPOOLSPACE'
parms['poolName'] - Name of the disk pool. Optional,
if not present then information for all
disk pools is obtained.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter getHost.getDiskPoolSpace")
results = {'overallRC': 0}
if 'poolName' not in rh.parms:
poolNames = ["*"]
else:
if isinstance(rh.parms['poolName'], list):
poolNames = rh.parms['poolName']
else:
poolNames = [rh.parms['poolName']]
if results['overallRC'] == 0:
# Loop thru each pool getting total. Do it for query 2 & 3
totals = {}
for qType in ["2", "3"]:
parms = [
"-q", qType,
"-e", "3",
"-T", "DUMMY",
"-n", " ".join(poolNames)]
results = invokeSMCLI(rh, "Image_Volume_Space_Query_DM", parms)
if results['overallRC'] == 0:
for line in results['response'].splitlines():
parts = line.split()
if len(parts) == 9:
poolName = parts[7]
else:
poolName = parts[4]
if poolName not in totals:
totals[poolName] = {"2": 0., "3": 0.}
if parts[1][:4] == "3390":
totals[poolName][qType] += int(parts[3]) * 737280
elif parts[1][:4] == "9336":
totals[poolName][qType] += int(parts[3]) * 512
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
break
if results['overallRC'] == 0:
if len(totals) == 0:
# No pool information found.
msg = msgs.msg['0402'][1] % (modId, " ".join(poolNames))
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0402'][0])
else:
# Produce a summary for each pool
for poolName in sorted(totals):
total = totals[poolName]["2"] + totals[poolName]["3"]
rh.printLn("N", poolName + " Total: " +
generalUtils.cvtToMag(rh, total))
rh.printLn("N", poolName + " Used: " +
generalUtils.cvtToMag(rh, totals[poolName]["3"]))
rh.printLn("N", poolName + " Free: " +
generalUtils.cvtToMag(rh, totals[poolName]["2"]))
rh.printSysLog("Exit getHost.getDiskPoolSpace, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"getDiskPoolSpace",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter getHost.getDiskPoolSpace\"",
")",
"results",
"=",
"{",
"'overallRC'",
":",
"0",
"}",
"if",
"'poolName'",
"not",
"in",
"rh",
".",
"parms",
":",
"poolNames",
"=",
"[",
"\... | Obtain disk pool space information for all or a specific disk pool.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'DISKPOOLSPACE'
parms['poolName'] - Name of the disk pool. Optional,
if not present then information for all
disk pools is obtained.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Obtain",
"disk",
"pool",
"space",
"information",
"for",
"all",
"or",
"a",
"specific",
"disk",
"pool",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/getHost.py#L142-L221 | train | 43,607 |
mfcloud/python-zvm-sdk | smtLayer/getHost.py | getFcpDevices | def getFcpDevices(rh):
"""
Lists the FCP device channels that are active, free, or offline.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'FCPDEVICES'
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter getHost.getFcpDevices")
parms = ["-T", "dummy"]
results = invokeSMCLI(rh, "System_WWPN_Query", parms)
if results['overallRC'] == 0:
rh.printLn("N", results['response'])
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit getHost.getFcpDevices, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def getFcpDevices(rh):
"""
Lists the FCP device channels that are active, free, or offline.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'FCPDEVICES'
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter getHost.getFcpDevices")
parms = ["-T", "dummy"]
results = invokeSMCLI(rh, "System_WWPN_Query", parms)
if results['overallRC'] == 0:
rh.printLn("N", results['response'])
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
rh.printSysLog("Exit getHost.getFcpDevices, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"getFcpDevices",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter getHost.getFcpDevices\"",
")",
"parms",
"=",
"[",
"\"-T\"",
",",
"\"dummy\"",
"]",
"results",
"=",
"invokeSMCLI",
"(",
"rh",
",",
"\"System_WWPN_Query\"",
",",
"parms",
")",
... | Lists the FCP device channels that are active, free, or offline.
Input:
Request Handle with the following properties:
function - 'GETHOST'
subfunction - 'FCPDEVICES'
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Lists",
"the",
"FCP",
"device",
"channels",
"that",
"are",
"active",
"free",
"or",
"offline",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/getHost.py#L224-L251 | train | 43,608 |
mfcloud/python-zvm-sdk | smtLayer/deleteVM.py | deleteMachine | def deleteMachine(rh):
"""
Delete a virtual machine from the user directory.
Input:
Request Handle with the following properties:
function - 'DELETEVM'
subfunction - 'DIRECTORY'
userid - userid of the virtual machine to be deleted.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter deleteVM.deleteMachine")
results = {'overallRC': 0, 'rc': 0, 'rs': 0}
# Is image logged on ?
state = 'on' # Assume 'on'.
results = isLoggedOn(rh, rh.userid)
if results['overallRC'] != 0:
# Cannot determine the log on/off state.
# Message already included. Act as if it is 'on'.
pass
elif results['rs'] == 0:
# State is powered on.
pass
else:
state = 'off'
# Reset values for rest of subfunction
results['overallRC'] = 0
results['rc'] = 0
results['rs'] = 0
if state == 'on':
parms = ["-T", rh.userid, "-f IMMED"]
results = invokeSMCLI(rh, "Image_Deactivate", parms)
if results['overallRC'] == 0:
pass
elif (results['overallRC'] == 8 and results['rc'] == 200 and
(results['rs'] == 12 or results['rs'] == 16)):
# Tolerable error. Machine is already in or going into the state
# that we want it to enter.
rh.updateResults({}, reset=1)
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results returned by invokeSMCLI
# Clean up the reader before delete
if results['overallRC'] == 0:
result = purgeReader(rh)
if result['overallRC'] != 0:
# Tolerable the purge failure error
rh.updateResults({}, reset=1)
if results['overallRC'] == 0:
parms = ["-T", rh.userid, "-e", "0"]
results = invokeSMCLI(rh, "Image_Delete_DM", parms)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results returned by invokeSMCLI
rh.printSysLog("Exit deleteVM.deleteMachine, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def deleteMachine(rh):
"""
Delete a virtual machine from the user directory.
Input:
Request Handle with the following properties:
function - 'DELETEVM'
subfunction - 'DIRECTORY'
userid - userid of the virtual machine to be deleted.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter deleteVM.deleteMachine")
results = {'overallRC': 0, 'rc': 0, 'rs': 0}
# Is image logged on ?
state = 'on' # Assume 'on'.
results = isLoggedOn(rh, rh.userid)
if results['overallRC'] != 0:
# Cannot determine the log on/off state.
# Message already included. Act as if it is 'on'.
pass
elif results['rs'] == 0:
# State is powered on.
pass
else:
state = 'off'
# Reset values for rest of subfunction
results['overallRC'] = 0
results['rc'] = 0
results['rs'] = 0
if state == 'on':
parms = ["-T", rh.userid, "-f IMMED"]
results = invokeSMCLI(rh, "Image_Deactivate", parms)
if results['overallRC'] == 0:
pass
elif (results['overallRC'] == 8 and results['rc'] == 200 and
(results['rs'] == 12 or results['rs'] == 16)):
# Tolerable error. Machine is already in or going into the state
# that we want it to enter.
rh.updateResults({}, reset=1)
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results returned by invokeSMCLI
# Clean up the reader before delete
if results['overallRC'] == 0:
result = purgeReader(rh)
if result['overallRC'] != 0:
# Tolerable the purge failure error
rh.updateResults({}, reset=1)
if results['overallRC'] == 0:
parms = ["-T", rh.userid, "-e", "0"]
results = invokeSMCLI(rh, "Image_Delete_DM", parms)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results returned by invokeSMCLI
rh.printSysLog("Exit deleteVM.deleteMachine, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"deleteMachine",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter deleteVM.deleteMachine\"",
")",
"results",
"=",
"{",
"'overallRC'",
":",
"0",
",",
"'rc'",
":",
"0",
",",
"'rs'",
":",
"0",
"}",
"# Is image logged on ?",
"state",
"=",
"'... | Delete a virtual machine from the user directory.
Input:
Request Handle with the following properties:
function - 'DELETEVM'
subfunction - 'DIRECTORY'
userid - userid of the virtual machine to be deleted.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Delete",
"a",
"virtual",
"machine",
"from",
"the",
"user",
"directory",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/deleteVM.py#L60-L128 | train | 43,609 |
mfcloud/python-zvm-sdk | smtLayer/powerVM.py | activate | def activate(rh):
"""
Activate a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'ON'
userid - userid of the virtual machine
parms['desiredState'] - Desired state. Optional,
unless 'maxQueries' is specified.
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.activate, userid: " + rh.userid)
parms = ["-T", rh.userid]
smcliResults = invokeSMCLI(rh, "Image_Activate", parms)
if smcliResults['overallRC'] == 0:
pass
elif (smcliResults['overallRC'] == 8 and
smcliResults['rc'] == 200 and smcliResults['rs'] == 8):
pass # All good. No need to change the ReqHandle results.
else:
# SMAPI API failed.
rh.printLn("ES", smcliResults['response'])
rh.updateResults(smcliResults) # Use results from invokeSMCLI
if rh.results['overallRC'] == 0 and 'maxQueries' in rh.parms:
# Wait for the system to be in the desired state of:
# OS is 'up' and reachable or VM is 'on'.
if rh.parms['desiredState'] == 'up':
results = waitForOSState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
else:
results = waitForVMState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if results['overallRC'] == 0:
rh.printLn("N", "%s: %s" %
(rh.userid, rh.parms['desiredState']))
else:
rh.updateResults(results)
rh.printSysLog("Exit powerVM.activate, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def activate(rh):
"""
Activate a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'ON'
userid - userid of the virtual machine
parms['desiredState'] - Desired state. Optional,
unless 'maxQueries' is specified.
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.activate, userid: " + rh.userid)
parms = ["-T", rh.userid]
smcliResults = invokeSMCLI(rh, "Image_Activate", parms)
if smcliResults['overallRC'] == 0:
pass
elif (smcliResults['overallRC'] == 8 and
smcliResults['rc'] == 200 and smcliResults['rs'] == 8):
pass # All good. No need to change the ReqHandle results.
else:
# SMAPI API failed.
rh.printLn("ES", smcliResults['response'])
rh.updateResults(smcliResults) # Use results from invokeSMCLI
if rh.results['overallRC'] == 0 and 'maxQueries' in rh.parms:
# Wait for the system to be in the desired state of:
# OS is 'up' and reachable or VM is 'on'.
if rh.parms['desiredState'] == 'up':
results = waitForOSState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
else:
results = waitForVMState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if results['overallRC'] == 0:
rh.printLn("N", "%s: %s" %
(rh.userid, rh.parms['desiredState']))
else:
rh.updateResults(results)
rh.printSysLog("Exit powerVM.activate, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"activate",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter powerVM.activate, userid: \"",
"+",
"rh",
".",
"userid",
")",
"parms",
"=",
"[",
"\"-T\"",
",",
"rh",
".",
"userid",
"]",
"smcliResults",
"=",
"invokeSMCLI",
"(",
"rh",
",",
... | Activate a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'ON'
userid - userid of the virtual machine
parms['desiredState'] - Desired state. Optional,
unless 'maxQueries' is specified.
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Activate",
"a",
"virtual",
"machine",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/powerVM.py#L121-L183 | train | 43,610 |
mfcloud/python-zvm-sdk | smtLayer/powerVM.py | checkIsReachable | def checkIsReachable(rh):
"""
Check if a virtual machine is reachable.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'ISREACHABLE'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
overallRC - 0: determined the status, non-zero: some weird failure
while trying to execute a command
on the guest via IUCV
rc - RC returned from execCmdThruIUCV
rs - 0: not reachable, 1: reachable
"""
rh.printSysLog("Enter powerVM.checkIsReachable, userid: " +
rh.userid)
strCmd = "echo 'ping'"
results = execCmdThruIUCV(rh, rh.userid, strCmd)
if results['overallRC'] == 0:
rh.printLn("N", rh.userid + ": reachable")
reachable = 1
else:
# A failure from execCmdThruIUCV is acceptable way of determining
# that the system is unreachable. We won't pass along the
# error message.
rh.printLn("N", rh.userid + ": unreachable")
reachable = 0
rh.updateResults({"rs": reachable})
rh.printSysLog("Exit powerVM.checkIsReachable, rc: 0")
return 0 | python | def checkIsReachable(rh):
"""
Check if a virtual machine is reachable.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'ISREACHABLE'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
overallRC - 0: determined the status, non-zero: some weird failure
while trying to execute a command
on the guest via IUCV
rc - RC returned from execCmdThruIUCV
rs - 0: not reachable, 1: reachable
"""
rh.printSysLog("Enter powerVM.checkIsReachable, userid: " +
rh.userid)
strCmd = "echo 'ping'"
results = execCmdThruIUCV(rh, rh.userid, strCmd)
if results['overallRC'] == 0:
rh.printLn("N", rh.userid + ": reachable")
reachable = 1
else:
# A failure from execCmdThruIUCV is acceptable way of determining
# that the system is unreachable. We won't pass along the
# error message.
rh.printLn("N", rh.userid + ": unreachable")
reachable = 0
rh.updateResults({"rs": reachable})
rh.printSysLog("Exit powerVM.checkIsReachable, rc: 0")
return 0 | [
"def",
"checkIsReachable",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter powerVM.checkIsReachable, userid: \"",
"+",
"rh",
".",
"userid",
")",
"strCmd",
"=",
"\"echo 'ping'\"",
"results",
"=",
"execCmdThruIUCV",
"(",
"rh",
",",
"rh",
".",
"userid"... | Check if a virtual machine is reachable.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'ISREACHABLE'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
overallRC - 0: determined the status, non-zero: some weird failure
while trying to execute a command
on the guest via IUCV
rc - RC returned from execCmdThruIUCV
rs - 0: not reachable, 1: reachable | [
"Check",
"if",
"a",
"virtual",
"machine",
"is",
"reachable",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/powerVM.py#L186-L223 | train | 43,611 |
mfcloud/python-zvm-sdk | smtLayer/powerVM.py | deactivate | def deactivate(rh):
"""
Deactivate a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'OFF'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.deactivate, userid: " +
rh.userid)
parms = ["-T", rh.userid, "-f", "IMMED"]
results = invokeSMCLI(rh, "Image_Deactivate", parms)
if results['overallRC'] == 0:
pass
elif (results['overallRC'] == 8 and results['rc'] == 200 and
(results['rs'] == 12 or results['rs'] == 16)):
# Tolerable error. Machine is already in or going into the state
# we want it to enter.
rh.printLn("N", rh.userid + ": off")
rh.updateResults({}, reset=1)
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
if results['overallRC'] == 0 and 'maxQueries' in rh.parms:
results = waitForVMState(
rh,
rh.userid,
'off',
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if results['overallRC'] == 0:
rh.printLn("N", rh.userid + ": off")
else:
rh.updateResults(results)
rh.printSysLog("Exit powerVM.deactivate, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def deactivate(rh):
"""
Deactivate a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'OFF'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.deactivate, userid: " +
rh.userid)
parms = ["-T", rh.userid, "-f", "IMMED"]
results = invokeSMCLI(rh, "Image_Deactivate", parms)
if results['overallRC'] == 0:
pass
elif (results['overallRC'] == 8 and results['rc'] == 200 and
(results['rs'] == 12 or results['rs'] == 16)):
# Tolerable error. Machine is already in or going into the state
# we want it to enter.
rh.printLn("N", rh.userid + ": off")
rh.updateResults({}, reset=1)
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
if results['overallRC'] == 0 and 'maxQueries' in rh.parms:
results = waitForVMState(
rh,
rh.userid,
'off',
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if results['overallRC'] == 0:
rh.printLn("N", rh.userid + ": off")
else:
rh.updateResults(results)
rh.printSysLog("Exit powerVM.deactivate, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"deactivate",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter powerVM.deactivate, userid: \"",
"+",
"rh",
".",
"userid",
")",
"parms",
"=",
"[",
"\"-T\"",
",",
"rh",
".",
"userid",
",",
"\"-f\"",
",",
"\"IMMED\"",
"]",
"results",
"=",
... | Deactivate a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'OFF'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Deactivate",
"a",
"virtual",
"machine",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/powerVM.py#L226-L279 | train | 43,612 |
mfcloud/python-zvm-sdk | smtLayer/powerVM.py | reset | def reset(rh):
"""
Reset a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'RESET'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.reset, userid: " + rh.userid)
# Log off the user
parms = ["-T", rh.userid]
results = invokeSMCLI(rh, "Image_Deactivate", parms)
if results['overallRC'] != 0:
if results['rc'] == 200 and results['rs'] == 12:
# Tolerated error. Machine is already in the desired state.
results['overallRC'] = 0
results['rc'] = 0
results['rs'] = 0
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
# Wait for the logoff to complete
if results['overallRC'] == 0:
results = waitForVMState(rh, rh.userid, "off",
maxQueries=30, sleepSecs=10)
# Log the user back on
if results['overallRC'] == 0:
parms = ["-T", rh.userid]
results = invokeSMCLI(rh, "Image_Activate", parms)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
if results['overallRC'] == 0 and 'maxQueries' in rh.parms:
if rh.parms['desiredState'] == 'up':
results = waitForOSState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
else:
results = waitForVMState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if results['overallRC'] == 0:
rh.printLn("N", rh.userid + ": " +
rh.parms['desiredState'])
else:
rh.updateResults(results)
rh.printSysLog("Exit powerVM.reset, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def reset(rh):
"""
Reset a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'RESET'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.reset, userid: " + rh.userid)
# Log off the user
parms = ["-T", rh.userid]
results = invokeSMCLI(rh, "Image_Deactivate", parms)
if results['overallRC'] != 0:
if results['rc'] == 200 and results['rs'] == 12:
# Tolerated error. Machine is already in the desired state.
results['overallRC'] = 0
results['rc'] = 0
results['rs'] = 0
else:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
# Wait for the logoff to complete
if results['overallRC'] == 0:
results = waitForVMState(rh, rh.userid, "off",
maxQueries=30, sleepSecs=10)
# Log the user back on
if results['overallRC'] == 0:
parms = ["-T", rh.userid]
results = invokeSMCLI(rh, "Image_Activate", parms)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
if results['overallRC'] == 0 and 'maxQueries' in rh.parms:
if rh.parms['desiredState'] == 'up':
results = waitForOSState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
else:
results = waitForVMState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if results['overallRC'] == 0:
rh.printLn("N", rh.userid + ": " +
rh.parms['desiredState'])
else:
rh.updateResults(results)
rh.printSysLog("Exit powerVM.reset, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"reset",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter powerVM.reset, userid: \"",
"+",
"rh",
".",
"userid",
")",
"# Log off the user",
"parms",
"=",
"[",
"\"-T\"",
",",
"rh",
".",
"userid",
"]",
"results",
"=",
"invokeSMCLI",
"(",
"r... | Reset a virtual machine.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'RESET'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds. Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Reset",
"a",
"virtual",
"machine",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/powerVM.py#L570-L644 | train | 43,613 |
mfcloud/python-zvm-sdk | smtLayer/powerVM.py | softDeactivate | def softDeactivate(rh):
"""
Deactivate a virtual machine by first shutting down Linux and
then log it off.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'SOFTOFF'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds.
Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.softDeactivate, userid: " +
rh.userid)
strCmd = "echo 'ping'"
iucvResults = execCmdThruIUCV(rh, rh.userid, strCmd)
if iucvResults['overallRC'] == 0:
# We could talk to the machine, tell it to shutdown nicely.
strCmd = "shutdown -h now"
iucvResults = execCmdThruIUCV(rh, rh.userid, strCmd)
if iucvResults['overallRC'] == 0:
time.sleep(15)
else:
# Shutdown failed. Let CP take down the system
# after we log the results.
rh.printSysLog("powerVM.softDeactivate " + rh.userid +
" is unreachable. Treating it as already shutdown.")
else:
# Could not ping the machine. Treat it as a success
# after we log the results.
rh.printSysLog("powerVM.softDeactivate " + rh.userid +
" is unreachable. Treating it as already shutdown.")
# Tell z/VM to log off the system.
parms = ["-T", rh.userid]
smcliResults = invokeSMCLI(rh, "Image_Deactivate", parms)
if smcliResults['overallRC'] == 0:
pass
elif (smcliResults['overallRC'] == 8 and smcliResults['rc'] == 200 and
(smcliResults['rs'] == 12 or + smcliResults['rs'] == 16)):
# Tolerable error.
# Machine is already logged off or is logging off.
rh.printLn("N", rh.userid + " is already logged off.")
else:
# SMAPI API failed.
rh.printLn("ES", smcliResults['response'])
rh.updateResults(smcliResults) # Use results from invokeSMCLI
if rh.results['overallRC'] == 0 and 'maxQueries' in rh.parms:
# Wait for the system to log off.
waitResults = waitForVMState(
rh,
rh.userid,
'off',
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if waitResults['overallRC'] == 0:
rh.printLn("N", "Userid '" + rh.userid +
" is in the desired state: off")
else:
rh.updateResults(waitResults)
rh.printSysLog("Exit powerVM.softDeactivate, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def softDeactivate(rh):
"""
Deactivate a virtual machine by first shutting down Linux and
then log it off.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'SOFTOFF'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds.
Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.softDeactivate, userid: " +
rh.userid)
strCmd = "echo 'ping'"
iucvResults = execCmdThruIUCV(rh, rh.userid, strCmd)
if iucvResults['overallRC'] == 0:
# We could talk to the machine, tell it to shutdown nicely.
strCmd = "shutdown -h now"
iucvResults = execCmdThruIUCV(rh, rh.userid, strCmd)
if iucvResults['overallRC'] == 0:
time.sleep(15)
else:
# Shutdown failed. Let CP take down the system
# after we log the results.
rh.printSysLog("powerVM.softDeactivate " + rh.userid +
" is unreachable. Treating it as already shutdown.")
else:
# Could not ping the machine. Treat it as a success
# after we log the results.
rh.printSysLog("powerVM.softDeactivate " + rh.userid +
" is unreachable. Treating it as already shutdown.")
# Tell z/VM to log off the system.
parms = ["-T", rh.userid]
smcliResults = invokeSMCLI(rh, "Image_Deactivate", parms)
if smcliResults['overallRC'] == 0:
pass
elif (smcliResults['overallRC'] == 8 and smcliResults['rc'] == 200 and
(smcliResults['rs'] == 12 or + smcliResults['rs'] == 16)):
# Tolerable error.
# Machine is already logged off or is logging off.
rh.printLn("N", rh.userid + " is already logged off.")
else:
# SMAPI API failed.
rh.printLn("ES", smcliResults['response'])
rh.updateResults(smcliResults) # Use results from invokeSMCLI
if rh.results['overallRC'] == 0 and 'maxQueries' in rh.parms:
# Wait for the system to log off.
waitResults = waitForVMState(
rh,
rh.userid,
'off',
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if waitResults['overallRC'] == 0:
rh.printLn("N", "Userid '" + rh.userid +
" is in the desired state: off")
else:
rh.updateResults(waitResults)
rh.printSysLog("Exit powerVM.softDeactivate, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"softDeactivate",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter powerVM.softDeactivate, userid: \"",
"+",
"rh",
".",
"userid",
")",
"strCmd",
"=",
"\"echo 'ping'\"",
"iucvResults",
"=",
"execCmdThruIUCV",
"(",
"rh",
",",
"rh",
".",
"userid"... | Deactivate a virtual machine by first shutting down Linux and
then log it off.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'SOFTOFF'
userid - userid of the virtual machine
parms['maxQueries'] - Maximum number of queries to issue.
Optional.
parms['maxWait'] - Maximum time to wait in seconds.
Optional,
unless 'maxQueries' is specified.
parms['poll'] - Polling interval in seconds. Optional,
unless 'maxQueries' is specified.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Deactivate",
"a",
"virtual",
"machine",
"by",
"first",
"shutting",
"down",
"Linux",
"and",
"then",
"log",
"it",
"off",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/powerVM.py#L743-L820 | train | 43,614 |
mfcloud/python-zvm-sdk | smtLayer/powerVM.py | wait | def wait(rh):
"""
Wait for the virtual machine to go into the specified state.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'WAIT'
userid - userid of the virtual machine
parms['desiredState'] - Desired state
parms['maxQueries'] - Maximum number of queries to issue
parms['maxWait'] - Maximum time to wait in seconds
parms['poll'] - Polling interval in seconds
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.wait, userid: " + rh.userid)
if (rh.parms['desiredState'] == 'off' or
rh.parms['desiredState'] == 'on'):
results = waitForVMState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
else:
results = waitForOSState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if results['overallRC'] == 0:
rh.printLn("N", rh.userid + ": " + rh.parms['desiredState'])
else:
rh.updateResults(results)
rh.printSysLog("Exit powerVM.wait, rc: " + str(rh.results['overallRC']))
return rh.results['overallRC'] | python | def wait(rh):
"""
Wait for the virtual machine to go into the specified state.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'WAIT'
userid - userid of the virtual machine
parms['desiredState'] - Desired state
parms['maxQueries'] - Maximum number of queries to issue
parms['maxWait'] - Maximum time to wait in seconds
parms['poll'] - Polling interval in seconds
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter powerVM.wait, userid: " + rh.userid)
if (rh.parms['desiredState'] == 'off' or
rh.parms['desiredState'] == 'on'):
results = waitForVMState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
else:
results = waitForOSState(
rh,
rh.userid,
rh.parms['desiredState'],
maxQueries=rh.parms['maxQueries'],
sleepSecs=rh.parms['poll'])
if results['overallRC'] == 0:
rh.printLn("N", rh.userid + ": " + rh.parms['desiredState'])
else:
rh.updateResults(results)
rh.printSysLog("Exit powerVM.wait, rc: " + str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"wait",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter powerVM.wait, userid: \"",
"+",
"rh",
".",
"userid",
")",
"if",
"(",
"rh",
".",
"parms",
"[",
"'desiredState'",
"]",
"==",
"'off'",
"or",
"rh",
".",
"parms",
"[",
"'desiredState'... | Wait for the virtual machine to go into the specified state.
Input:
Request Handle with the following properties:
function - 'POWERVM'
subfunction - 'WAIT'
userid - userid of the virtual machine
parms['desiredState'] - Desired state
parms['maxQueries'] - Maximum number of queries to issue
parms['maxWait'] - Maximum time to wait in seconds
parms['poll'] - Polling interval in seconds
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Wait",
"for",
"the",
"virtual",
"machine",
"to",
"go",
"into",
"the",
"specified",
"state",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/powerVM.py#L853-L896 | train | 43,615 |
mfcloud/python-zvm-sdk | zvmconnector/socketclient.py | SDKSocketClient.call | def call(self, func, *api_args, **api_kwargs):
"""Send API call to SDK server and return results"""
if not isinstance(func, str) or (func == ''):
msg = ('Invalid input for API name, should be a'
'string, type: %s specified.') % type(func)
return self._construct_api_name_error(msg)
# Create client socket
try:
cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
return self._construct_socket_error(1, error=six.text_type(err))
try:
# Set socket timeout
cs.settimeout(self.timeout)
# Connect SDK server
try:
cs.connect((self.addr, self.port))
except socket.error as err:
return self._construct_socket_error(2, addr=self.addr,
port=self.port,
error=six.text_type(err))
# Prepare the data to be sent and switch to bytes if needed
api_data = json.dumps((func, api_args, api_kwargs))
api_data = api_data.encode()
# Send the API call data to SDK server
sent = 0
total_len = len(api_data)
got_error = False
try:
while (sent < total_len):
this_sent = cs.send(api_data[sent:])
if this_sent == 0:
got_error = True
break
sent += this_sent
except socket.error as err:
return self._construct_socket_error(5,
error=six.text_type(err))
if got_error or sent != total_len:
return self._construct_socket_error(3, sent=sent,
api=api_data)
# Receive data from server
return_blocks = []
try:
while True:
block = cs.recv(4096)
if not block:
break
block = bytes.decode(block)
return_blocks.append(block)
except socket.error as err:
# When the sdkserver cann't handle all the client request,
# some client request would be rejected.
# Under this case, the client socket can successfully
# connect/send, but would get exception in recv with error:
# "error: [Errno 104] Connection reset by peer"
return self._construct_socket_error(6,
error=six.text_type(err))
finally:
# Always close the client socket to avoid too many hanging
# socket left.
cs.close()
# Transform the received stream to standard result form
# This client assumes that the server would return result in
# the standard result form, so client just return the received
# data
if return_blocks:
results = json.loads(''.join(return_blocks))
else:
results = self._construct_socket_error(4)
return results | python | def call(self, func, *api_args, **api_kwargs):
"""Send API call to SDK server and return results"""
if not isinstance(func, str) or (func == ''):
msg = ('Invalid input for API name, should be a'
'string, type: %s specified.') % type(func)
return self._construct_api_name_error(msg)
# Create client socket
try:
cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
return self._construct_socket_error(1, error=six.text_type(err))
try:
# Set socket timeout
cs.settimeout(self.timeout)
# Connect SDK server
try:
cs.connect((self.addr, self.port))
except socket.error as err:
return self._construct_socket_error(2, addr=self.addr,
port=self.port,
error=six.text_type(err))
# Prepare the data to be sent and switch to bytes if needed
api_data = json.dumps((func, api_args, api_kwargs))
api_data = api_data.encode()
# Send the API call data to SDK server
sent = 0
total_len = len(api_data)
got_error = False
try:
while (sent < total_len):
this_sent = cs.send(api_data[sent:])
if this_sent == 0:
got_error = True
break
sent += this_sent
except socket.error as err:
return self._construct_socket_error(5,
error=six.text_type(err))
if got_error or sent != total_len:
return self._construct_socket_error(3, sent=sent,
api=api_data)
# Receive data from server
return_blocks = []
try:
while True:
block = cs.recv(4096)
if not block:
break
block = bytes.decode(block)
return_blocks.append(block)
except socket.error as err:
# When the sdkserver cann't handle all the client request,
# some client request would be rejected.
# Under this case, the client socket can successfully
# connect/send, but would get exception in recv with error:
# "error: [Errno 104] Connection reset by peer"
return self._construct_socket_error(6,
error=six.text_type(err))
finally:
# Always close the client socket to avoid too many hanging
# socket left.
cs.close()
# Transform the received stream to standard result form
# This client assumes that the server would return result in
# the standard result form, so client just return the received
# data
if return_blocks:
results = json.loads(''.join(return_blocks))
else:
results = self._construct_socket_error(4)
return results | [
"def",
"call",
"(",
"self",
",",
"func",
",",
"*",
"api_args",
",",
"*",
"*",
"api_kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"func",
",",
"str",
")",
"or",
"(",
"func",
"==",
"''",
")",
":",
"msg",
"=",
"(",
"'Invalid input for API name, sho... | Send API call to SDK server and return results | [
"Send",
"API",
"call",
"to",
"SDK",
"server",
"and",
"return",
"results"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmconnector/socketclient.py#L64-L141 | train | 43,616 |
mfcloud/python-zvm-sdk | zvmsdk/sdkwsgi/handler.py | dispatch | def dispatch(environ, start_response, mapper):
"""Find a matching route for the current request.
:raises: 404(not found) if no match request
405(method not allowed) if route exist but
method not provided.
"""
result = mapper.match(environ=environ)
if result is None:
info = environ.get('PATH_INFO', '')
LOG.debug('The route for %s can not be found', info)
raise webob.exc.HTTPNotFound(
json_formatter=util.json_error_formatter)
handler = result.pop('action')
environ['wsgiorg.routing_args'] = ((), result)
return handler(environ, start_response) | python | def dispatch(environ, start_response, mapper):
"""Find a matching route for the current request.
:raises: 404(not found) if no match request
405(method not allowed) if route exist but
method not provided.
"""
result = mapper.match(environ=environ)
if result is None:
info = environ.get('PATH_INFO', '')
LOG.debug('The route for %s can not be found', info)
raise webob.exc.HTTPNotFound(
json_formatter=util.json_error_formatter)
handler = result.pop('action')
environ['wsgiorg.routing_args'] = ((), result)
return handler(environ, start_response) | [
"def",
"dispatch",
"(",
"environ",
",",
"start_response",
",",
"mapper",
")",
":",
"result",
"=",
"mapper",
".",
"match",
"(",
"environ",
"=",
"environ",
")",
"if",
"result",
"is",
"None",
":",
"info",
"=",
"environ",
".",
"get",
"(",
"'PATH_INFO'",
",... | Find a matching route for the current request.
:raises: 404(not found) if no match request
405(method not allowed) if route exist but
method not provided. | [
"Find",
"a",
"matching",
"route",
"for",
"the",
"current",
"request",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/sdkwsgi/handler.py#L125-L142 | train | 43,617 |
mfcloud/python-zvm-sdk | zvmsdk/sdkwsgi/handler.py | handle_not_allowed | def handle_not_allowed(environ, start_response):
"""Return a 405 response when method is not allowed.
If _methods are in routing_args, send an allow header listing
the methods that are possible on the provided URL.
"""
_methods = util.wsgi_path_item(environ, '_methods')
headers = {}
if _methods:
headers['allow'] = str(_methods)
raise webob.exc.HTTPMethodNotAllowed(
('The method specified is not allowed for this resource.'),
headers=headers, json_formatter=util.json_error_formatter) | python | def handle_not_allowed(environ, start_response):
"""Return a 405 response when method is not allowed.
If _methods are in routing_args, send an allow header listing
the methods that are possible on the provided URL.
"""
_methods = util.wsgi_path_item(environ, '_methods')
headers = {}
if _methods:
headers['allow'] = str(_methods)
raise webob.exc.HTTPMethodNotAllowed(
('The method specified is not allowed for this resource.'),
headers=headers, json_formatter=util.json_error_formatter) | [
"def",
"handle_not_allowed",
"(",
"environ",
",",
"start_response",
")",
":",
"_methods",
"=",
"util",
".",
"wsgi_path_item",
"(",
"environ",
",",
"'_methods'",
")",
"headers",
"=",
"{",
"}",
"if",
"_methods",
":",
"headers",
"[",
"'allow'",
"]",
"=",
"str... | Return a 405 response when method is not allowed.
If _methods are in routing_args, send an allow header listing
the methods that are possible on the provided URL. | [
"Return",
"a",
"405",
"response",
"when",
"method",
"is",
"not",
"allowed",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/sdkwsgi/handler.py#L145-L157 | train | 43,618 |
mfcloud/python-zvm-sdk | zvmsdk/sdkwsgi/handler.py | make_map | def make_map(declarations):
"""Process route declarations to create a Route Mapper."""
mapper = routes.Mapper()
for route, methods in ROUTE_LIST:
allowed_methods = []
for method, func in methods.items():
mapper.connect(route, action=func,
conditions=dict(method=[method]))
allowed_methods.append(method)
allowed_methods = ', '.join(allowed_methods)
mapper.connect(route, action=handle_not_allowed,
_methods=allowed_methods)
return mapper | python | def make_map(declarations):
"""Process route declarations to create a Route Mapper."""
mapper = routes.Mapper()
for route, methods in ROUTE_LIST:
allowed_methods = []
for method, func in methods.items():
mapper.connect(route, action=func,
conditions=dict(method=[method]))
allowed_methods.append(method)
allowed_methods = ', '.join(allowed_methods)
mapper.connect(route, action=handle_not_allowed,
_methods=allowed_methods)
return mapper | [
"def",
"make_map",
"(",
"declarations",
")",
":",
"mapper",
"=",
"routes",
".",
"Mapper",
"(",
")",
"for",
"route",
",",
"methods",
"in",
"ROUTE_LIST",
":",
"allowed_methods",
"=",
"[",
"]",
"for",
"method",
",",
"func",
"in",
"methods",
".",
"items",
... | Process route declarations to create a Route Mapper. | [
"Process",
"route",
"declarations",
"to",
"create",
"a",
"Route",
"Mapper",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/sdkwsgi/handler.py#L160-L172 | train | 43,619 |
mfcloud/python-zvm-sdk | zvmsdk/dist.py | rhel._offline_fcp_device | def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath):
"""rhel offline zfcp. sampe to all rhel distro."""
offline_dev = 'chccwdev -d %s' % fcp
delete_records = self._delete_zfcp_config_records(fcp,
target_wwpn,
target_lun)
return '\n'.join((offline_dev,
delete_records)) | python | def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath):
"""rhel offline zfcp. sampe to all rhel distro."""
offline_dev = 'chccwdev -d %s' % fcp
delete_records = self._delete_zfcp_config_records(fcp,
target_wwpn,
target_lun)
return '\n'.join((offline_dev,
delete_records)) | [
"def",
"_offline_fcp_device",
"(",
"self",
",",
"fcp",
",",
"target_wwpn",
",",
"target_lun",
",",
"multipath",
")",
":",
"offline_dev",
"=",
"'chccwdev -d %s'",
"%",
"fcp",
"delete_records",
"=",
"self",
".",
"_delete_zfcp_config_records",
"(",
"fcp",
",",
"tar... | rhel offline zfcp. sampe to all rhel distro. | [
"rhel",
"offline",
"zfcp",
".",
"sampe",
"to",
"all",
"rhel",
"distro",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/dist.py#L576-L583 | train | 43,620 |
mfcloud/python-zvm-sdk | zvmsdk/dist.py | rhel6._set_sysfs | def _set_sysfs(self, fcp, target_wwpn, target_lun):
"""rhel6 set WWPN and LUN in sysfs"""
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': device, 'wwpn': target_wwpn}
return '\n'.join((port_add,
unit_add)) | python | def _set_sysfs(self, fcp, target_wwpn, target_lun):
"""rhel6 set WWPN and LUN in sysfs"""
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': device, 'wwpn': target_wwpn}
return '\n'.join((port_add,
unit_add)) | [
"def",
"_set_sysfs",
"(",
"self",
",",
"fcp",
",",
"target_wwpn",
",",
"target_lun",
")",
":",
"device",
"=",
"'0.0.%s'",
"%",
"fcp",
"port_add",
"=",
"\"echo '%s' > \"",
"%",
"target_wwpn",
"port_add",
"+=",
"\"/sys/bus/ccw/drivers/zfcp/%s/port_add\"",
"%",
"devi... | rhel6 set WWPN and LUN in sysfs | [
"rhel6",
"set",
"WWPN",
"and",
"LUN",
"in",
"sysfs"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/dist.py#L679-L688 | train | 43,621 |
mfcloud/python-zvm-sdk | zvmsdk/dist.py | rhel6._set_zfcp_config_files | def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun):
"""rhel6 set WWPN and LUN in configuration files"""
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'\
% device
return '\n'.join((set_zfcp_conf,
trigger_uevent)) | python | def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun):
"""rhel6 set WWPN and LUN in configuration files"""
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'\
% device
return '\n'.join((set_zfcp_conf,
trigger_uevent)) | [
"def",
"_set_zfcp_config_files",
"(",
"self",
",",
"fcp",
",",
"target_wwpn",
",",
"target_lun",
")",
":",
"device",
"=",
"'0.0.%s'",
"%",
"fcp",
"set_zfcp_conf",
"=",
"'echo \"%(device)s %(wwpn)s %(lun)s\" >> /etc/zfcp.conf'",
"%",
"{",
"'device'",
":",
"device",
"... | rhel6 set WWPN and LUN in configuration files | [
"rhel6",
"set",
"WWPN",
"and",
"LUN",
"in",
"configuration",
"files"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/dist.py#L690-L699 | train | 43,622 |
mfcloud/python-zvm-sdk | zvmsdk/dist.py | rhel7._set_sysfs | def _set_sysfs(self, fcp, target_wwpn, target_lun):
"""rhel7 set WWPN and LUN in sysfs"""
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 | python | def _set_sysfs(self, fcp, target_wwpn, target_lun):
"""rhel7 set WWPN and LUN in sysfs"""
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",
")",
":",
"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... | rhel7 set WWPN and LUN in sysfs | [
"rhel7",
"set",
"WWPN",
"and",
"LUN",
"in",
"sysfs"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/dist.py#L769-L775 | train | 43,623 |
mfcloud/python-zvm-sdk | zvmsdk/dist.py | sles._get_udev_rules | def _get_udev_rules(self, channel_read, channel_write, channel_data):
"""construct udev rules info."""
sub_str = '%(read)s %%k %(read)s %(write)s %(data)s qeth' % {
'read': channel_read,
'read': channel_read,
'write': channel_write,
'data': channel_data}
rules_str = '# Configure qeth device at'
rules_str += ' %(read)s/%(write)s/%(data)s\n' % {
'read': channel_read,
'write': channel_write,
'data': channel_data}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"drivers\", KERNEL=='
'\"qeth\", IMPORT{program}=\"collect %s\"\n') % sub_str
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(read)s\", IMPORT{program}="collect %(channel)s\"\n') % {
'read': channel_read, 'channel': sub_str}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(write)s\", IMPORT{program}=\"collect %(channel)s\"\n') % {
'write': channel_write, 'channel': sub_str}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(data)s\", IMPORT{program}=\"collect %(channel)s\"\n') % {
'data': channel_data, 'channel': sub_str}
rules_str += ('ACTION==\"remove\", SUBSYSTEM==\"drivers\", KERNEL==\"'
'qeth\", IMPORT{program}=\"collect --remove %s\"\n') % sub_str
rules_str += ('ACTION==\"remove\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(read)s\", IMPORT{program}=\"collect --remove %(channel)s\"\n'
) % {'read': channel_read, 'channel': sub_str}
rules_str += ('ACTION==\"remove\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(write)s\", IMPORT{program}=\"collect --remove %(channel)s\"\n'
) % {'write': channel_write, 'channel': sub_str}
rules_str += ('ACTION==\"remove\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(data)s\", IMPORT{program}=\"collect --remove %(channel)s\"\n'
) % {'data': channel_data, 'channel': sub_str}
rules_str += ('TEST==\"[ccwgroup/%(read)s]\", GOTO=\"qeth-%(read)s'
'-end\"\n') % {'read': channel_read, 'read': channel_read}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccw\", ENV{COLLECT_'
'%(read)s}==\"0\", ATTR{[drivers/ccwgroup:qeth]group}=\"'
'%(read)s,%(write)s,%(data)s\"\n') % {
'read': channel_read, 'read': channel_read,
'write': channel_write, 'data': channel_data}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"drivers\", KERNEL==\"qeth'
'\", ENV{COLLECT_%(read)s}==\"0\", ATTR{[drivers/'
'ccwgroup:qeth]group}=\"%(read)s,%(write)s,%(data)s\"\n'
'LABEL=\"qeth-%(read)s-end\"\n') % {
'read': channel_read, 'read': channel_read, 'write': channel_write,
'data': channel_data, 'read': channel_read}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccwgroup\", KERNEL=='
'\"%s\", ATTR{layer2}=\"1\"\n') % channel_read
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccwgroup\", KERNEL=='
'\"%s\", ATTR{online}=\"1\"\n') % channel_read
return rules_str | python | def _get_udev_rules(self, channel_read, channel_write, channel_data):
"""construct udev rules info."""
sub_str = '%(read)s %%k %(read)s %(write)s %(data)s qeth' % {
'read': channel_read,
'read': channel_read,
'write': channel_write,
'data': channel_data}
rules_str = '# Configure qeth device at'
rules_str += ' %(read)s/%(write)s/%(data)s\n' % {
'read': channel_read,
'write': channel_write,
'data': channel_data}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"drivers\", KERNEL=='
'\"qeth\", IMPORT{program}=\"collect %s\"\n') % sub_str
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(read)s\", IMPORT{program}="collect %(channel)s\"\n') % {
'read': channel_read, 'channel': sub_str}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(write)s\", IMPORT{program}=\"collect %(channel)s\"\n') % {
'write': channel_write, 'channel': sub_str}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(data)s\", IMPORT{program}=\"collect %(channel)s\"\n') % {
'data': channel_data, 'channel': sub_str}
rules_str += ('ACTION==\"remove\", SUBSYSTEM==\"drivers\", KERNEL==\"'
'qeth\", IMPORT{program}=\"collect --remove %s\"\n') % sub_str
rules_str += ('ACTION==\"remove\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(read)s\", IMPORT{program}=\"collect --remove %(channel)s\"\n'
) % {'read': channel_read, 'channel': sub_str}
rules_str += ('ACTION==\"remove\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(write)s\", IMPORT{program}=\"collect --remove %(channel)s\"\n'
) % {'write': channel_write, 'channel': sub_str}
rules_str += ('ACTION==\"remove\", SUBSYSTEM==\"ccw\", KERNEL==\"'
'%(data)s\", IMPORT{program}=\"collect --remove %(channel)s\"\n'
) % {'data': channel_data, 'channel': sub_str}
rules_str += ('TEST==\"[ccwgroup/%(read)s]\", GOTO=\"qeth-%(read)s'
'-end\"\n') % {'read': channel_read, 'read': channel_read}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccw\", ENV{COLLECT_'
'%(read)s}==\"0\", ATTR{[drivers/ccwgroup:qeth]group}=\"'
'%(read)s,%(write)s,%(data)s\"\n') % {
'read': channel_read, 'read': channel_read,
'write': channel_write, 'data': channel_data}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"drivers\", KERNEL==\"qeth'
'\", ENV{COLLECT_%(read)s}==\"0\", ATTR{[drivers/'
'ccwgroup:qeth]group}=\"%(read)s,%(write)s,%(data)s\"\n'
'LABEL=\"qeth-%(read)s-end\"\n') % {
'read': channel_read, 'read': channel_read, 'write': channel_write,
'data': channel_data, 'read': channel_read}
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccwgroup\", KERNEL=='
'\"%s\", ATTR{layer2}=\"1\"\n') % channel_read
rules_str += ('ACTION==\"add\", SUBSYSTEM==\"ccwgroup\", KERNEL=='
'\"%s\", ATTR{online}=\"1\"\n') % channel_read
return rules_str | [
"def",
"_get_udev_rules",
"(",
"self",
",",
"channel_read",
",",
"channel_write",
",",
"channel_data",
")",
":",
"sub_str",
"=",
"'%(read)s %%k %(read)s %(write)s %(data)s qeth'",
"%",
"{",
"'read'",
":",
"channel_read",
",",
"'read'",
":",
"channel_read",
",",
"'wr... | construct udev rules info. | [
"construct",
"udev",
"rules",
"info",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/dist.py#L865-L916 | train | 43,624 |
mfcloud/python-zvm-sdk | zvmsdk/dist.py | sles._delete_vdev_info | def _delete_vdev_info(self, vdev):
"""handle udev rules file."""
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" % (address, udev_file_name)
cmd += "sed -i '/%s/d' %s\n" % (address,
'/boot/zipl/active_devices.txt')
return cmd | python | def _delete_vdev_info(self, vdev):
"""handle udev rules file."""
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" % (address, udev_file_name)
cmd += "sed -i '/%s/d' %s\n" % (address,
'/boot/zipl/active_devices.txt')
return cmd | [
"def",
"_delete_vdev_info",
"(",
"self",
",",
"vdev",
")",
":",
"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... | handle udev rules file. | [
"handle",
"udev",
"rules",
"file",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/dist.py#L956-L967 | train | 43,625 |
mfcloud/python-zvm-sdk | zvmsdk/dist.py | sles._set_zfcp_config_files | def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun):
"""sles set WWPN and LUN in configuration files"""
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,
'lun': target_lun}
create_config = 'touch /etc/udev/rules.d/51-zfcp-%s.rules' % device
# check if the file already contains the zFCP channel
check_channel = ('out=`cat "/etc/udev/rules.d/51-zfcp-%s.rules" '
'| egrep -i "ccw/%s]online"`\n' % (device, device))
check_channel += 'if [[ ! $out ]]; then\n'
check_channel += (' echo "ACTION==\\"add\\", SUBSYSTEM==\\"ccw\\", '
'KERNEL==\\"%(device)s\\", IMPORT{program}=\\"'
'collect %(device)s %%k %(device)s zfcp\\""'
'| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules'
'\n' % {'device': device})
check_channel += (' echo "ACTION==\\"add\\", SUBSYSTEM==\\"drivers\\"'
', KERNEL==\\"zfcp\\", IMPORT{program}=\\"'
'collect %(device)s %%k %(device)s zfcp\\""'
'| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules'
'\n' % {'device': device})
check_channel += (' echo "ACTION==\\"add\\", '
'ENV{COLLECT_%(device)s}==\\"0\\", '
'ATTR{[ccw/%(device)s]online}=\\"1\\""'
'| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules'
'\n' % {'device': device})
check_channel += 'fi\n'
check_channel += ('echo "ACTION==\\"add\\", KERNEL==\\"rport-*\\", '
'ATTR{port_name}==\\"%(wwpn)s\\", '
'SUBSYSTEMS==\\"ccw\\", KERNELS==\\"%(device)s\\",'
'ATTR{[ccw/%(device)s]%(wwpn)s/unit_add}='
'\\"%(lun)s\\""'
'| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules'
'\n' % {'device': device, 'wwpn': target_wwpn,
'lun': target_lun})
return '\n'.join((host_config,
'sleep 2',
disk_config,
'sleep 2',
create_config,
check_channel)) | python | def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun):
"""sles set WWPN and LUN in configuration files"""
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,
'lun': target_lun}
create_config = 'touch /etc/udev/rules.d/51-zfcp-%s.rules' % device
# check if the file already contains the zFCP channel
check_channel = ('out=`cat "/etc/udev/rules.d/51-zfcp-%s.rules" '
'| egrep -i "ccw/%s]online"`\n' % (device, device))
check_channel += 'if [[ ! $out ]]; then\n'
check_channel += (' echo "ACTION==\\"add\\", SUBSYSTEM==\\"ccw\\", '
'KERNEL==\\"%(device)s\\", IMPORT{program}=\\"'
'collect %(device)s %%k %(device)s zfcp\\""'
'| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules'
'\n' % {'device': device})
check_channel += (' echo "ACTION==\\"add\\", SUBSYSTEM==\\"drivers\\"'
', KERNEL==\\"zfcp\\", IMPORT{program}=\\"'
'collect %(device)s %%k %(device)s zfcp\\""'
'| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules'
'\n' % {'device': device})
check_channel += (' echo "ACTION==\\"add\\", '
'ENV{COLLECT_%(device)s}==\\"0\\", '
'ATTR{[ccw/%(device)s]online}=\\"1\\""'
'| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules'
'\n' % {'device': device})
check_channel += 'fi\n'
check_channel += ('echo "ACTION==\\"add\\", KERNEL==\\"rport-*\\", '
'ATTR{port_name}==\\"%(wwpn)s\\", '
'SUBSYSTEMS==\\"ccw\\", KERNELS==\\"%(device)s\\",'
'ATTR{[ccw/%(device)s]%(wwpn)s/unit_add}='
'\\"%(lun)s\\""'
'| tee -a /etc/udev/rules.d/51-zfcp-%(device)s.rules'
'\n' % {'device': device, 'wwpn': target_wwpn,
'lun': target_lun})
return '\n'.join((host_config,
'sleep 2',
disk_config,
'sleep 2',
create_config,
check_channel)) | [
"def",
"_set_zfcp_config_files",
"(",
"self",
",",
"fcp",
",",
"target_wwpn",
",",
"target_lun",
")",
":",
"device",
"=",
"'0.0.%s'",
"%",
"fcp",
"# host config",
"host_config",
"=",
"'/sbin/zfcp_host_configure %s 1'",
"%",
"device",
"# disk config",
"disk_config",
... | sles set WWPN and LUN in configuration files | [
"sles",
"set",
"WWPN",
"and",
"LUN",
"in",
"configuration",
"files"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/dist.py#L985-L1029 | train | 43,626 |
mfcloud/python-zvm-sdk | zvmsdk/dist.py | sles._offline_fcp_device | def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath):
"""sles offline zfcp. sampe to all rhel distro."""
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 = '/sbin/zfcp_host_configure %s 0' % device
return '\n'.join((disk_config,
host_config)) | python | def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath):
"""sles offline zfcp. sampe to all rhel distro."""
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 = '/sbin/zfcp_host_configure %s 0' % device
return '\n'.join((disk_config,
host_config)) | [
"def",
"_offline_fcp_device",
"(",
"self",
",",
"fcp",
",",
"target_wwpn",
",",
"target_lun",
",",
"multipath",
")",
":",
"device",
"=",
"'0.0.%s'",
"%",
"fcp",
"# disk config",
"disk_config",
"=",
"'/sbin/zfcp_disk_configure '",
"+",
"'%(device)s %(wwpn)s %(lun)s 0'"... | sles offline zfcp. sampe to all rhel distro. | [
"sles",
"offline",
"zfcp",
".",
"sampe",
"to",
"all",
"rhel",
"distro",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/dist.py#L1050-L1061 | train | 43,627 |
mfcloud/python-zvm-sdk | zvmsdk/dist.py | ubuntu._delete_vdev_info | def _delete_vdev_info(self, vdev):
"""handle vdev related info."""
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=$(awk 'NR==(\"\'$num\'\"+6)&&"
"/dns-nameservers/' %s)" %
network_config_file_name,
"if [[ -n $dns ]]; then",
" sed -i '/auto %s/,+6d' %s" % (device,
network_config_file_name),
"else",
" sed -i '/auto %s/,+5d' %s" % (device,
network_config_file_name),
"fi"))
return cmd | python | def _delete_vdev_info(self, vdev):
"""handle vdev related info."""
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=$(awk 'NR==(\"\'$num\'\"+6)&&"
"/dns-nameservers/' %s)" %
network_config_file_name,
"if [[ -n $dns ]]; then",
" sed -i '/auto %s/,+6d' %s" % (device,
network_config_file_name),
"else",
" sed -i '/auto %s/,+5d' %s" % (device,
network_config_file_name),
"fi"))
return cmd | [
"def",
"_delete_vdev_info",
"(",
"self",
",",
"vdev",
")",
":",
"vdev",
"=",
"vdev",
".",
"lower",
"(",
")",
"network_config_file_name",
"=",
"self",
".",
"_get_network_file",
"(",
")",
"device",
"=",
"self",
".",
"_get_device_name",
"(",
"vdev",
")",
"cmd... | handle vdev related info. | [
"handle",
"vdev",
"related",
"info",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/dist.py#L1205-L1222 | train | 43,628 |
mfcloud/python-zvm-sdk | zvmsdk/dist.py | ubuntu._set_zfcp_config_files | def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun):
"""ubuntu zfcp configuration """
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)) | python | def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun):
"""ubuntu zfcp configuration """
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",
")",
":",
"host_config",
"=",
"'/sbin/chzdev zfcp-host %s -e'",
"%",
"fcp",
"device",
"=",
"'0.0.%s'",
"%",
"fcp",
"target",
"=",
"'%s:%s:%s'",
"%",
"(",
"device",
... | ubuntu zfcp configuration | [
"ubuntu",
"zfcp",
"configuration"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/dist.py#L1344-L1352 | train | 43,629 |
mfcloud/python-zvm-sdk | zvmsdk/dist.py | ubuntu._offline_fcp_device | def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath):
"""ubuntu offline zfcp."""
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,
host_offline,
offline_dev)) | python | def _offline_fcp_device(self, fcp, target_wwpn, target_lun, multipath):
"""ubuntu offline zfcp."""
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,
host_offline,
offline_dev)) | [
"def",
"_offline_fcp_device",
"(",
"self",
",",
"fcp",
",",
"target_wwpn",
",",
"target_lun",
",",
"multipath",
")",
":",
"device",
"=",
"'0.0.%s'",
"%",
"fcp",
"target",
"=",
"'%s:%s:%s'",
"%",
"(",
"device",
",",
"target_wwpn",
",",
"target_lun",
")",
"d... | ubuntu offline zfcp. | [
"ubuntu",
"offline",
"zfcp",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/dist.py#L1383-L1392 | train | 43,630 |
mfcloud/python-zvm-sdk | zvmsdk/dist.py | LinuxDistManager.parse_dist | 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
"""
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(i):
# Not guarrentee the version is digital
remain = os_version.split(i, 2)[1]
release = self._parse_release(os_version, distro, remain)
return distro, release
msg = 'Can not handle os: %s' % os_version
raise exception.ZVMException(msg=msg) | python | 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
"""
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(i):
# Not guarrentee the version is digital
remain = os_version.split(i, 2)[1]
release = self._parse_release(os_version, distro, remain)
return distro, release
msg = 'Can not handle os: %s' % os_version
raise exception.ZVMException(msg=msg) | [
"def",
"parse_dist",
"(",
"self",
",",
"os_version",
")",
":",
"supported",
"=",
"{",
"'rhel'",
":",
"[",
"'rhel'",
",",
"'redhat'",
",",
"'red hat'",
"]",
",",
"'sles'",
":",
"[",
"'suse'",
",",
"'sles'",
"]",
",",
"'ubuntu'",
":",
"[",
"'ubuntu'",
... | 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 | [
"Separate",
"os",
"and",
"version",
"from",
"os_version",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/dist.py#L1435-L1454 | train | 43,631 |
mfcloud/python-zvm-sdk | smtLayer/migrateVM.py | getStatus | 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'] - If present, set status_target to INCOMING.
parms['outgoing'] - If present, set status_target to OUTGOING.
if parms does not contain 'all', 'incoming' or 'outgoing', the
status_target is set to 'USER <userid>'.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
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_target=OUTGOING"])
else:
parms.extend(["-k", "status_target=USER " + rh.userid + ""])
results = invokeSMCLI(rh, "VMRELOCATE_Status", parms)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
if results['rc'] == 4 and results['rs'] == 3001:
# No relocation in progress
msg = msgs.msg['0419'][1] % (modId, rh.userid)
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0419'][0])
else:
rh.printLn("N", results['response'])
rh.printSysLog("Exit migrateVM.getStatus, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | python | 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'] - If present, set status_target to INCOMING.
parms['outgoing'] - If present, set status_target to OUTGOING.
if parms does not contain 'all', 'incoming' or 'outgoing', the
status_target is set to 'USER <userid>'.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
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_target=OUTGOING"])
else:
parms.extend(["-k", "status_target=USER " + rh.userid + ""])
results = invokeSMCLI(rh, "VMRELOCATE_Status", parms)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
if results['rc'] == 4 and results['rs'] == 3001:
# No relocation in progress
msg = msgs.msg['0419'][1] % (modId, rh.userid)
rh.printLn("ES", msg)
rh.updateResults(msgs.msg['0419'][0])
else:
rh.printLn("N", results['response'])
rh.printSysLog("Exit migrateVM.getStatus, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | [
"def",
"getStatus",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter migrateVM.getStatus\"",
")",
"parms",
"=",
"[",
"\"-T\"",
",",
"rh",
".",
"userid",
"]",
"if",
"'all'",
"in",
"rh",
".",
"parms",
":",
"parms",
".",
"extend",
"(",
"[",
... | 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'] - If present, set status_target to INCOMING.
parms['outgoing'] - If present, set status_target to OUTGOING.
if parms does not contain 'all', 'incoming' or 'outgoing', the
status_target is set to 'USER <userid>'.
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | [
"Get",
"status",
"of",
"a",
"VMRelocate",
"request",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/migrateVM.py#L169-L217 | train | 43,632 |
mfcloud/python-zvm-sdk | smtLayer/ReqHandle.py | ReqHandle.parseCmdline | 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
"""
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 list
elif isinstance(requestData, string_types):
self.requestString = requestData # Request as a string
self.request = shlex.split(requestData) # Request as a list
else:
# Request data type is not supported.
msg = msgs.msg['0012'][1] % (modId, type(requestData))
self.printLn("ES", msg)
self.updateResults(msgs.msg['0012'][0])
return self.results
self.totalParms = len(self.request) # Number of parms in the cmd
# Handle the request, parse it or return an error.
if self.totalParms == 0:
# Too few arguments.
msg = msgs.msg['0009'][1] % modId
self.printLn("ES", msg)
self.updateResults(msgs.msg['0009'][0])
elif self.totalParms == 1:
self.function = self.request[0].upper()
if self.function == 'HELP' or self.function == 'VERSION':
pass
else:
# Function is not HELP or VERSION.
msg = msgs.msg['0008'][1] % (modId, self.function)
self.printLn("ES", msg)
self.updateResults(msgs.msg['0008'][0])
else:
# Process based on the function operand.
self.function = self.request[0].upper()
if self.request[0] == 'HELP' or self.request[0] == 'VERSION':
pass
else:
# Handle the function related parms by calling the function
# parser.
if self.function in ReqHandle.funcHandler:
self.funcHandler[self.function][2](self)
else:
# Unrecognized function
msg = msgs.msg['0007'][1] % (modId, self.function)
self.printLn("ES", msg)
self.updateResults(msgs.msg['0007'][0])
self.printSysLog("Exit ReqHandle.parseCmdline, rc: " +
str(self.results['overallRC']))
return self.results | python | 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
"""
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 list
elif isinstance(requestData, string_types):
self.requestString = requestData # Request as a string
self.request = shlex.split(requestData) # Request as a list
else:
# Request data type is not supported.
msg = msgs.msg['0012'][1] % (modId, type(requestData))
self.printLn("ES", msg)
self.updateResults(msgs.msg['0012'][0])
return self.results
self.totalParms = len(self.request) # Number of parms in the cmd
# Handle the request, parse it or return an error.
if self.totalParms == 0:
# Too few arguments.
msg = msgs.msg['0009'][1] % modId
self.printLn("ES", msg)
self.updateResults(msgs.msg['0009'][0])
elif self.totalParms == 1:
self.function = self.request[0].upper()
if self.function == 'HELP' or self.function == 'VERSION':
pass
else:
# Function is not HELP or VERSION.
msg = msgs.msg['0008'][1] % (modId, self.function)
self.printLn("ES", msg)
self.updateResults(msgs.msg['0008'][0])
else:
# Process based on the function operand.
self.function = self.request[0].upper()
if self.request[0] == 'HELP' or self.request[0] == 'VERSION':
pass
else:
# Handle the function related parms by calling the function
# parser.
if self.function in ReqHandle.funcHandler:
self.funcHandler[self.function][2](self)
else:
# Unrecognized function
msg = msgs.msg['0007'][1] % (modId, self.function)
self.printLn("ES", msg)
self.updateResults(msgs.msg['0007'][0])
self.printSysLog("Exit ReqHandle.parseCmdline, rc: " +
str(self.results['overallRC']))
return self.results | [
"def",
"parseCmdline",
"(",
"self",
",",
"requestData",
")",
":",
"self",
".",
"printSysLog",
"(",
"\"Enter ReqHandle.parseCmdline\"",
")",
"# Save the request data based on the type of operand.",
"if",
"isinstance",
"(",
"requestData",
",",
"list",
")",
":",
"self",
... | 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 | [
"Parse",
"the",
"request",
"command",
"string",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/ReqHandle.py#L212-L275 | train | 43,633 |
mfcloud/python-zvm-sdk | smtLayer/ReqHandle.py | ReqHandle.printLn | 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
"""
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'] +
respString.splitlines())
return | python | 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
"""
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'] +
respString.splitlines())
return | [
"def",
"printLn",
"(",
"self",
",",
"respType",
",",
"respString",
")",
":",
"if",
"'E'",
"in",
"respType",
":",
"respString",
"=",
"'(Error) '",
"+",
"respString",
"if",
"'W'",
"in",
"respType",
":",
"respString",
"=",
"'(Warning) '",
"+",
"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 | [
"Add",
"one",
"or",
"lines",
"of",
"output",
"to",
"the",
"response",
"list",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/ReqHandle.py#L277-L297 | train | 43,634 |
mfcloud/python-zvm-sdk | smtLayer/ReqHandle.py | ReqHandle.printSysLog | def printSysLog(self, logString):
"""
Log one or more lines. Optionally, add them to logEntries list.
Input:
Strings to be logged.
"""
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)
if self.captureLogs is True:
self.results['logEntries'].append(self.requestId + ": " +
logString)
return | python | def printSysLog(self, logString):
"""
Log one or more lines. Optionally, add them to logEntries list.
Input:
Strings to be logged.
"""
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)
if self.captureLogs is True:
self.results['logEntries'].append(self.requestId + ": " +
logString)
return | [
"def",
"printSysLog",
"(",
"self",
",",
"logString",
")",
":",
"if",
"zvmsdklog",
".",
"LOGGER",
".",
"getloglevel",
"(",
")",
"<=",
"logging",
".",
"DEBUG",
":",
"# print log only when debug is enabled",
"if",
"self",
".",
"daemon",
"==",
"''",
":",
"self",... | Log one or more lines. Optionally, add them to logEntries list.
Input:
Strings to be logged. | [
"Log",
"one",
"or",
"more",
"lines",
".",
"Optionally",
"add",
"them",
"to",
"logEntries",
"list",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/ReqHandle.py#L299-L317 | train | 43,635 |
rpkilby/SurveyGizmo | surveygizmo/api/base.py | Resource.filters | def filters(self):
"""
Returns a merged dictionary of filters.
"""
params = {}
for _filter in self._filters:
params.update(_filter)
return params | python | def filters(self):
"""
Returns a merged dictionary of filters.
"""
params = {}
for _filter in self._filters:
params.update(_filter)
return params | [
"def",
"filters",
"(",
"self",
")",
":",
"params",
"=",
"{",
"}",
"for",
"_filter",
"in",
"self",
".",
"_filters",
":",
"params",
".",
"update",
"(",
"_filter",
")",
"return",
"params"
] | Returns a merged dictionary of filters. | [
"Returns",
"a",
"merged",
"dictionary",
"of",
"filters",
"."
] | a097091dc7dcfb58f70242fb1becabc98df049a5 | https://github.com/rpkilby/SurveyGizmo/blob/a097091dc7dcfb58f70242fb1becabc98df049a5/surveygizmo/api/base.py#L109-L117 | train | 43,636 |
mfcloud/python-zvm-sdk | zvmsdk/sdkwsgi/util.py | json_error_formatter | def json_error_formatter(body, status, title, environ):
"""A json_formatter for webob exceptions."""
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]} | python | def json_error_formatter(body, status, title, environ):
"""A json_formatter for webob exceptions."""
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",
")",
":",
"body",
"=",
"webob",
".",
"exc",
".",
"strip_tags",
"(",
"body",
")",
"status_code",
"=",
"int",
"(",
"status",
".",
"split",
"(",
"None",
",",
"1",
"... | A json_formatter for webob exceptions. | [
"A",
"json_formatter",
"for",
"webob",
"exceptions",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/sdkwsgi/util.py#L45-L54 | train | 43,637 |
mfcloud/python-zvm-sdk | zvmsdk/sdkwsgi/util.py | SdkWsgify.call_func | def call_func(self, req, *args, **kwargs):
"""Add json_error_formatter to any webob HTTPExceptions."""
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_int
explanation = six.text_type(exc)
fault_data = {
'overallRC': 400,
'rc': 400,
'rs': code,
'modID': SDKWSGI_MODID,
'output': '',
'errmsg': explanation}
exc.text = six.text_type(json.dumps(fault_data))
raise exc | python | def call_func(self, req, *args, **kwargs):
"""Add json_error_formatter to any webob HTTPExceptions."""
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_int
explanation = six.text_type(exc)
fault_data = {
'overallRC': 400,
'rc': 400,
'rs': code,
'modID': SDKWSGI_MODID,
'output': '',
'errmsg': explanation}
exc.text = six.text_type(json.dumps(fault_data))
raise exc | [
"def",
"call_func",
"(",
"self",
",",
"req",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"super",
"(",
"SdkWsgify",
",",
"self",
")",
".",
"call_func",
"(",
"req",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"... | Add json_error_formatter to any webob HTTPExceptions. | [
"Add",
"json_error_formatter",
"to",
"any",
"webob",
"HTTPExceptions",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/sdkwsgi/util.py#L224-L243 | train | 43,638 |
Chilipp/psyplot | psyplot/gdal_store.py | GdalStore._load_GeoTransform | def _load_GeoTransform(self):
"""Calculate latitude and longitude variable calculated from the
gdal.Open.GetGeoTransform method"""
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_lat,)}, 'lat', (self.ds.RasterYSize,),
shape=(self.ds.RasterYSize,), dtype=float)
lon = Array(
{('lon', 0): (load_lon,)}, 'lon', (self.ds.RasterXSize,),
shape=(self.ds.RasterXSize,), dtype=float)
else:
lat = load_lat()
lon = load_lon()
return Variable(('lat',), lat), Variable(('lon',), lon) | python | def _load_GeoTransform(self):
"""Calculate latitude and longitude variable calculated from the
gdal.Open.GetGeoTransform method"""
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_lat,)}, 'lat', (self.ds.RasterYSize,),
shape=(self.ds.RasterYSize,), dtype=float)
lon = Array(
{('lon', 0): (load_lon,)}, 'lon', (self.ds.RasterXSize,),
shape=(self.ds.RasterXSize,), dtype=float)
else:
lat = load_lat()
lon = load_lon()
return Variable(('lat',), lat), Variable(('lon',), lon) | [
"def",
"_load_GeoTransform",
"(",
"self",
")",
":",
"def",
"load_lon",
"(",
")",
":",
"return",
"arange",
"(",
"ds",
".",
"RasterXSize",
")",
"*",
"b",
"[",
"1",
"]",
"+",
"b",
"[",
"0",
"]",
"def",
"load_lat",
"(",
")",
":",
"return",
"arange",
... | Calculate latitude and longitude variable calculated from the
gdal.Open.GetGeoTransform method | [
"Calculate",
"latitude",
"and",
"longitude",
"variable",
"calculated",
"from",
"the",
"gdal",
".",
"Open",
".",
"GetGeoTransform",
"method"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/gdal_store.py#L109-L129 | train | 43,639 |
Chilipp/psyplot | psyplot/config/rcsetup.py | psyplot_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,
- `$HOME/.config/psyplot/psyplotrc.yml`
- On other platforms,
- `$HOME/.psyplot/psyplotrc.yml` if `$HOME` is defined.
- Lastly, it looks in `$PSYPLOTDATA/psyplotrc.yml` for a
system-defined copy.
Parameters
----------
env_key: str
The environment variable that can be used for the configuration
directory
fname: str
The name of the configuration file
if_exists: bool
If True, the path is only returned if the file exists
Returns
-------
None or str
None, if no file could be found and `if_exists` is True, else the path
to the psyplot configuration file
Notes
-----
This function is motivated by the :func:`matplotlib.matplotlib_fname`
function"""
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)
if os.path.exists(full_fname):
return full_fname
else:
return path
configdir = get_configdir()
if configdir is not None:
full_fname = os.path.join(configdir, fname)
if os.path.exists(full_fname) or not if_exists:
return full_fname
return None | python | 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,
- `$HOME/.config/psyplot/psyplotrc.yml`
- On other platforms,
- `$HOME/.psyplot/psyplotrc.yml` if `$HOME` is defined.
- Lastly, it looks in `$PSYPLOTDATA/psyplotrc.yml` for a
system-defined copy.
Parameters
----------
env_key: str
The environment variable that can be used for the configuration
directory
fname: str
The name of the configuration file
if_exists: bool
If True, the path is only returned if the file exists
Returns
-------
None or str
None, if no file could be found and `if_exists` is True, else the path
to the psyplot configuration file
Notes
-----
This function is motivated by the :func:`matplotlib.matplotlib_fname`
function"""
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)
if os.path.exists(full_fname):
return full_fname
else:
return path
configdir = get_configdir()
if configdir is not None:
full_fname = os.path.join(configdir, fname)
if os.path.exists(full_fname) or not if_exists:
return full_fname
return None | [
"def",
"psyplot_fname",
"(",
"env_key",
"=",
"'PSYPLOTRC'",
",",
"fname",
"=",
"'psyplotrc.yml'",
",",
"if_exists",
"=",
"True",
")",
":",
"cwd",
"=",
"getcwd",
"(",
")",
"full_fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"fname",
")",... | 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,
- `$HOME/.config/psyplot/psyplotrc.yml`
- On other platforms,
- `$HOME/.psyplot/psyplotrc.yml` if `$HOME` is defined.
- Lastly, it looks in `$PSYPLOTDATA/psyplotrc.yml` for a
system-defined copy.
Parameters
----------
env_key: str
The environment variable that can be used for the configuration
directory
fname: str
The name of the configuration file
if_exists: bool
If True, the path is only returned if the file exists
Returns
-------
None or str
None, if no file could be found and `if_exists` is True, else the path
to the psyplot configuration file
Notes
-----
This function is motivated by the :func:`matplotlib.matplotlib_fname`
function | [
"Get",
"the",
"location",
"of",
"the",
"config",
"file",
"."
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/rcsetup.py#L861-L927 | train | 43,640 |
Chilipp/psyplot | psyplot/config/rcsetup.py | validate_path_exists | def validate_path_exists(s):
"""If s is a path, return s, else False"""
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) | python | def validate_path_exists(s):
"""If s is a path, return s, else False"""
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",
"None",
":",
"return",
"None",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"s",
")",
":",
"return",
"s",
"else",
":",
"raise",
"ValueError",
"(",
"'\"%s\" should be a path but it does not... | If s is a path, return s, else False | [
"If",
"s",
"is",
"a",
"path",
"return",
"s",
"else",
"False"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/rcsetup.py#L975-L982 | train | 43,641 |
Chilipp/psyplot | psyplot/config/rcsetup.py | validate_dict | 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"""
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)) | python | 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"""
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",
")",
":",
"try",
":",
"return",
"dict",
"(",
"d",
")",
"except",
"TypeError",
":",
"d",
"=",
"validate_path_exists",
"(",
"d",
")",
"try",
":",
"with",
"open",
"(",
"d",
")",
"as",
"f",
":",
"return",
"dict",
"(",
... | Validate a dictionary
Parameters
----------
d: dict or str
If str, it must be a path to a yaml file
Returns
-------
dict
Raises
------
ValueError | [
"Validate",
"a",
"dictionary"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/rcsetup.py#L985-L1008 | train | 43,642 |
Chilipp/psyplot | psyplot/config/rcsetup.py | validate_str | def validate_str(s):
"""Validate a string
Parameters
----------
s: str
Returns
-------
str
Raises
------
ValueError"""
if not isinstance(s, six.string_types):
raise ValueError("Did not found string!")
return six.text_type(s) | python | def validate_str(s):
"""Validate a string
Parameters
----------
s: str
Returns
-------
str
Raises
------
ValueError"""
if not isinstance(s, six.string_types):
raise ValueError("Did not found string!")
return six.text_type(s) | [
"def",
"validate_str",
"(",
"s",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"\"Did not found string!\"",
")",
"return",
"six",
".",
"text_type",
"(",
"s",
")"
] | Validate a string
Parameters
----------
s: str
Returns
-------
str
Raises
------
ValueError | [
"Validate",
"a",
"string"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/rcsetup.py#L1032-L1048 | train | 43,643 |
Chilipp/psyplot | psyplot/config/rcsetup.py | validate_stringlist | def validate_stringlist(s):
"""Validate a list of strings
Parameters
----------
val: iterable of strings
Returns
-------
list
list of str
Raises
------
ValueError"""
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) | python | def validate_stringlist(s):
"""Validate a list of strings
Parameters
----------
val: iterable of strings
Returns
-------
list
list of str
Raises
------
ValueError"""
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",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"string_types",
")",
":",
"return",
"[",
"six",
".",
"text_type",
"(",
"v",
".",
"strip",
"(",
")",
")",
"for",
"v",
"in",
"s",
".",
"split",
"(",
"'... | Validate a list of strings
Parameters
----------
val: iterable of strings
Returns
-------
list
list of str
Raises
------
ValueError | [
"Validate",
"a",
"list",
"of",
"strings"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/rcsetup.py#L1051-L1072 | train | 43,644 |
Chilipp/psyplot | psyplot/config/rcsetup.py | SubDict.add_base_str | 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 end. ``'%(key)s'`` will
be replaced by the specific key for getting and setting an item.
pattern: str
Default: ``'.+'``. This is the pattern that is inserted for
``%(key)s`` in a base string to look for matches (using the
:mod:`re` module) in the `base` dictionary. The default `pattern`
matches everything without white spaces.
pattern_base: str or list or str
If None, the whatever is given in the `base_str` is used.
Those strings will be used for generating the final search
patterns. You can specify this parameter by yourself to avoid the
misinterpretation of patterns. For example for a `base_str` like
``'my.str'`` it is recommended to additionally provide the
`pattern_base` keyword with ``'my\.str'``.
Like for `base_str`, the ``%(key)s`` is appended if not already in
the string.
append: bool
If True, the given `base_str` are appended (i.e. it is first
looked for them in the :attr:`base` dictionary), otherwise they are
put at the beginning"""
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' not in s:
pattern_base[i] += '%(key)s'
else:
pattern_base = base_str
self.base_str = base_str + self.base_str
self.patterns = list(map(lambda s: re.compile(s.replace(
'%(key)s', '(?P<key>%s)' % pattern)), pattern_base)) + \
self.patterns | python | 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 end. ``'%(key)s'`` will
be replaced by the specific key for getting and setting an item.
pattern: str
Default: ``'.+'``. This is the pattern that is inserted for
``%(key)s`` in a base string to look for matches (using the
:mod:`re` module) in the `base` dictionary. The default `pattern`
matches everything without white spaces.
pattern_base: str or list or str
If None, the whatever is given in the `base_str` is used.
Those strings will be used for generating the final search
patterns. You can specify this parameter by yourself to avoid the
misinterpretation of patterns. For example for a `base_str` like
``'my.str'`` it is recommended to additionally provide the
`pattern_base` keyword with ``'my\.str'``.
Like for `base_str`, the ``%(key)s`` is appended if not already in
the string.
append: bool
If True, the given `base_str` are appended (i.e. it is first
looked for them in the :attr:`base` dictionary), otherwise they are
put at the beginning"""
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' not in s:
pattern_base[i] += '%(key)s'
else:
pattern_base = base_str
self.base_str = base_str + self.base_str
self.patterns = list(map(lambda s: re.compile(s.replace(
'%(key)s', '(?P<key>%s)' % pattern)), pattern_base)) + \
self.patterns | [
"def",
"add_base_str",
"(",
"self",
",",
"base_str",
",",
"pattern",
"=",
"'.+'",
",",
"pattern_base",
"=",
"None",
",",
"append",
"=",
"True",
")",
":",
"base_str",
"=",
"safe_list",
"(",
"base_str",
")",
"pattern_base",
"=",
"safe_list",
"(",
"pattern_ba... | 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 end. ``'%(key)s'`` will
be replaced by the specific key for getting and setting an item.
pattern: str
Default: ``'.+'``. This is the pattern that is inserted for
``%(key)s`` in a base string to look for matches (using the
:mod:`re` module) in the `base` dictionary. The default `pattern`
matches everything without white spaces.
pattern_base: str or list or str
If None, the whatever is given in the `base_str` is used.
Those strings will be used for generating the final search
patterns. You can specify this parameter by yourself to avoid the
misinterpretation of patterns. For example for a `base_str` like
``'my.str'`` it is recommended to additionally provide the
`pattern_base` keyword with ``'my\.str'``.
Like for `base_str`, the ``%(key)s`` is appended if not already in
the string.
append: bool
If True, the given `base_str` are appended (i.e. it is first
looked for them in the :attr:`base` dictionary), otherwise they are
put at the beginning | [
"Add",
"further",
"base",
"string",
"to",
"this",
"instance"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/rcsetup.py#L120-L164 | train | 43,645 |
Chilipp/psyplot | psyplot/config/rcsetup.py | SubDict.iterkeys | def iterkeys(self):
"""Unsorted iterator over keys"""
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()
if ret not in seen:
seen.add(ret)
yield ret
break
for key in DictMethods.iterkeys(self):
if key not in seen:
yield key | python | def iterkeys(self):
"""Unsorted iterator over keys"""
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()
if ret not in seen:
seen.add(ret)
yield ret
break
for key in DictMethods.iterkeys(self):
if key not in seen:
yield key | [
"def",
"iterkeys",
"(",
"self",
")",
":",
"patterns",
"=",
"self",
".",
"patterns",
"replace",
"=",
"self",
".",
"replace",
"seen",
"=",
"set",
"(",
")",
"for",
"key",
"in",
"six",
".",
"iterkeys",
"(",
"self",
".",
"base",
")",
":",
"for",
"patter... | Unsorted iterator over keys | [
"Unsorted",
"iterator",
"over",
"keys"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/rcsetup.py#L304-L320 | train | 43,646 |
Chilipp/psyplot | psyplot/config/rcsetup.py | RcParams.validate | def validate(self):
"""Dictionary with validation methods as values"""
depr = self._all_deprecated
return dict((key, val[1]) for key, val in
six.iteritems(self.defaultParams)
if key not in depr) | python | def validate(self):
"""Dictionary with validation methods as values"""
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",
")",
":",
"depr",
"=",
"self",
".",
"_all_deprecated",
"return",
"dict",
"(",
"(",
"key",
",",
"val",
"[",
"1",
"]",
")",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"defaultParams",
")... | Dictionary with validation methods as values | [
"Dictionary",
"with",
"validation",
"methods",
"as",
"values"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/rcsetup.py#L350-L355 | train | 43,647 |
Chilipp/psyplot | psyplot/config/rcsetup.py | RcParams.descriptions | def descriptions(self):
"""The description of each keyword in the rcParams dictionary"""
return {key: val[2] for key, val in six.iteritems(self.defaultParams)
if len(val) >= 3} | python | def descriptions(self):
"""The description of each keyword in the rcParams dictionary"""
return {key: val[2] for key, val in six.iteritems(self.defaultParams)
if len(val) >= 3} | [
"def",
"descriptions",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"val",
"[",
"2",
"]",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"defaultParams",
")",
"if",
"len",
"(",
"val",
")",
">=",
"3",
"}"
] | The description of each keyword in the rcParams dictionary | [
"The",
"description",
"of",
"each",
"keyword",
"in",
"the",
"rcParams",
"dictionary"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/rcsetup.py#L358-L361 | train | 43,648 |
Chilipp/psyplot | psyplot/config/rcsetup.py | RcParams.connect | 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."""
key = self._get_depreceated(key)[0]
if key is not None:
self._connections[key].append(func) | python | 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."""
key = self._get_depreceated(key)[0]
if key is not None:
self._connections[key].append(func) | [
"def",
"connect",
"(",
"self",
",",
"key",
",",
"func",
")",
":",
"key",
"=",
"self",
".",
"_get_depreceated",
"(",
"key",
")",
"[",
"0",
"]",
"if",
"key",
"is",
"not",
"None",
":",
"self",
".",
"_connections",
"[",
"key",
"]",
".",
"append",
"("... | 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. | [
"Connect",
"a",
"function",
"to",
"the",
"given",
"formatoption"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/rcsetup.py#L457-L470 | train | 43,649 |
Chilipp/psyplot | psyplot/config/rcsetup.py | RcParams.disconnect | 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
"""
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 conn in connections[:]:
if func is None or conn is func:
connections.remove(conn) | python | 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
"""
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 conn in connections[:]:
if func is None or conn is func:
connections.remove(conn) | [
"def",
"disconnect",
"(",
"self",
",",
"key",
"=",
"None",
",",
"func",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"for",
"key",
",",
"connections",
"in",
"self",
".",
"_connections",
".",
"items",
"(",
")",
":",
"for",
"conn",
"in",
... | 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 | [
"Disconnect",
"the",
"connections",
"to",
"the",
"an",
"rcParams",
"key"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/rcsetup.py#L472-L492 | train | 43,650 |
Chilipp/psyplot | psyplot/config/rcsetup.py | RcParams.keys | def keys(self):
"""
Return sorted list of keys.
"""
k = list(dict.keys(self))
k.sort()
return k | python | def keys(self):
"""
Return sorted list of keys.
"""
k = list(dict.keys(self))
k.sort()
return k | [
"def",
"keys",
"(",
"self",
")",
":",
"k",
"=",
"list",
"(",
"dict",
".",
"keys",
"(",
"self",
")",
")",
"k",
".",
"sort",
"(",
")",
"return",
"k"
] | Return sorted list of keys. | [
"Return",
"sorted",
"list",
"of",
"keys",
"."
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/rcsetup.py#L542-L548 | train | 43,651 |
Chilipp/psyplot | psyplot/config/rcsetup.py | RcParams.load_from_file | 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`.
If None, the :func:`config.rcsetup.psyplot_fname` function is used.
See Also
--------
dump_to_file, psyplot_fname"""
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):
self['project.plotters'].update(d['project.plotters.user']) | python | 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`.
If None, the :func:`config.rcsetup.psyplot_fname` function is used.
See Also
--------
dump_to_file, psyplot_fname"""
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):
self['project.plotters'].update(d['project.plotters.user']) | [
"def",
"load_from_file",
"(",
"self",
",",
"fname",
"=",
"None",
")",
":",
"fname",
"=",
"fname",
"or",
"psyplot_fname",
"(",
")",
"if",
"fname",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
")",
"a... | 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`.
If None, the :func:`config.rcsetup.psyplot_fname` function is used.
See Also
--------
dump_to_file, psyplot_fname | [
"Update",
"rcParams",
"from",
"user",
"-",
"defined",
"settings"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/rcsetup.py#L629-L651 | train | 43,652 |
Chilipp/psyplot | psyplot/config/rcsetup.py | RcParams.dump | 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
include_keys: None or list of str
Keys in the dictionary to be included. If None, all keys are
included
exclude_keys: list of str
Keys from the :class:`RcParams` instance to be excluded
Other Parameters
----------------
``**kwargs``
Any other parameter for the :func:`yaml.dump` function
Returns
-------
str or None
if fname is ``None``, the string is returned. Otherwise, ``None``
is returned
Raises
------
IOError
If `fname` already exists and `overwrite` is False
See Also
--------
load_from_file"""
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 in six.iteritems(self) if (
include_keys is None or key in include_keys) and
key not in exclude_keys}
kwargs['default_flow_style'] = False
if include_descriptions:
s = yaml.dump(d, **kwargs)
desc = self.descriptions
i = 2
header = self.HEADER.splitlines() + [
'', 'Created with python', ''] + sys.version.splitlines() + [
'', '']
lines = ['# ' + l for l in header] + s.splitlines()
for l in lines[2:]:
key = l.split(':')[0]
if key in desc:
lines.insert(i, '# ' + '\n# '.join(desc[key].splitlines()))
i += 1
i += 1
s = '\n'.join(lines)
if fname is None:
return s
else:
with open(fname, 'w') as f:
f.write(s)
else:
if fname is None:
return yaml.dump(d, **kwargs)
with open(fname, 'w') as f:
yaml.dump(d, f, **kwargs)
return None | python | 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
include_keys: None or list of str
Keys in the dictionary to be included. If None, all keys are
included
exclude_keys: list of str
Keys from the :class:`RcParams` instance to be excluded
Other Parameters
----------------
``**kwargs``
Any other parameter for the :func:`yaml.dump` function
Returns
-------
str or None
if fname is ``None``, the string is returned. Otherwise, ``None``
is returned
Raises
------
IOError
If `fname` already exists and `overwrite` is False
See Also
--------
load_from_file"""
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 in six.iteritems(self) if (
include_keys is None or key in include_keys) and
key not in exclude_keys}
kwargs['default_flow_style'] = False
if include_descriptions:
s = yaml.dump(d, **kwargs)
desc = self.descriptions
i = 2
header = self.HEADER.splitlines() + [
'', 'Created with python', ''] + sys.version.splitlines() + [
'', '']
lines = ['# ' + l for l in header] + s.splitlines()
for l in lines[2:]:
key = l.split(':')[0]
if key in desc:
lines.insert(i, '# ' + '\n# '.join(desc[key].splitlines()))
i += 1
i += 1
s = '\n'.join(lines)
if fname is None:
return s
else:
with open(fname, 'w') as f:
f.write(s)
else:
if fname is None:
return yaml.dump(d, **kwargs)
with open(fname, 'w') as f:
yaml.dump(d, f, **kwargs)
return None | [
"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
include_keys: None or list of str
Keys in the dictionary to be included. If None, all keys are
included
exclude_keys: list of str
Keys from the :class:`RcParams` instance to be excluded
Other Parameters
----------------
``**kwargs``
Any other parameter for the :func:`yaml.dump` function
Returns
-------
str or None
if fname is ``None``, the string is returned. Otherwise, ``None``
is returned
Raises
------
IOError
If `fname` already exists and `overwrite` is False
See Also
--------
load_from_file | [
"Dump",
"this",
"instance",
"to",
"a",
"yaml",
"file"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/rcsetup.py#L653-L725 | train | 43,653 |
Chilipp/psyplot | psyplot/config/rcsetup.py | RcParams._load_plugin_entrypoints | def _load_plugin_entrypoints(self):
"""Load the modules for the psyplot plugins
Yields
------
pkg_resources.EntryPoint
The entry point for the psyplot plugin module"""
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:
return False
return True
self._plugins = self._plugins or []
plugins_env = os.getenv('PSYPLOT_PLUGINS', '').split('::')
include_plugins = [s[4:] for s in plugins_env if s.startswith('yes:')]
exclude_plugins = [s[3:] for s in plugins_env if s.startswith('no:')]
logger = logging.getLogger(__name__)
for ep in iter_entry_points(group='psyplot', name='plugin'):
if not load_plugin(ep):
logger.debug('Skipping entrypoint %s', ep)
continue
self._plugins.append(str(ep))
logger.debug('Loading entrypoint %s', ep)
yield ep | python | def _load_plugin_entrypoints(self):
"""Load the modules for the psyplot plugins
Yields
------
pkg_resources.EntryPoint
The entry point for the psyplot plugin module"""
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:
return False
return True
self._plugins = self._plugins or []
plugins_env = os.getenv('PSYPLOT_PLUGINS', '').split('::')
include_plugins = [s[4:] for s in plugins_env if s.startswith('yes:')]
exclude_plugins = [s[3:] for s in plugins_env if s.startswith('no:')]
logger = logging.getLogger(__name__)
for ep in iter_entry_points(group='psyplot', name='plugin'):
if not load_plugin(ep):
logger.debug('Skipping entrypoint %s', ep)
continue
self._plugins.append(str(ep))
logger.debug('Loading entrypoint %s', ep)
yield ep | [
"def",
"_load_plugin_entrypoints",
"(",
"self",
")",
":",
"from",
"pkg_resources",
"import",
"iter_entry_points",
"def",
"load_plugin",
"(",
"ep",
")",
":",
"if",
"plugins_env",
"==",
"[",
"'no'",
"]",
":",
"return",
"False",
"elif",
"ep",
".",
"module_name",
... | Load the modules for the psyplot plugins
Yields
------
pkg_resources.EntryPoint
The entry point for the psyplot plugin module | [
"Load",
"the",
"modules",
"for",
"the",
"psyplot",
"plugins"
] | 75a0a15a9a1dd018e79d2df270d56c4bf5f311d5 | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/config/rcsetup.py#L727-L759 | train | 43,654 |
mfcloud/python-zvm-sdk | zvmsdk/sdkwsgi/deploy.py | deploy | def deploy(project_name):
"""Assemble the middleware pipeline"""
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,
):
if middleware:
application = middleware(application)
return application | python | def deploy(project_name):
"""Assemble the middleware pipeline"""
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,
):
if middleware:
application = middleware(application)
return application | [
"def",
"deploy",
"(",
"project_name",
")",
":",
"request_log",
"=",
"requestlog",
".",
"RequestLog",
"header_addon",
"=",
"HeaderControl",
"fault_wrapper",
"=",
"FaultWrapper",
"application",
"=",
"handler",
".",
"SdkHandler",
"(",
")",
"# currently we have 3 middlewa... | Assemble the middleware pipeline | [
"Assemble",
"the",
"middleware",
"pipeline"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/sdkwsgi/deploy.py#L139-L154 | train | 43,655 |
mfcloud/python-zvm-sdk | zvmsdk/vmops.py | VMOps.guest_reboot | def guest_reboot(self, userid):
"""Reboot a guest vm."""
LOG.info("Begin to reboot vm %s", userid)
self._smtclient.guest_reboot(userid)
LOG.info("Complete reboot vm %s", userid) | python | def guest_reboot(self, userid):
"""Reboot a guest vm."""
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",
")",
":",
"LOG",
".",
"info",
"(",
"\"Begin to reboot vm %s\"",
",",
"userid",
")",
"self",
".",
"_smtclient",
".",
"guest_reboot",
"(",
"userid",
")",
"LOG",
".",
"info",
"(",
"\"Complete reboot vm %s\"",
"... | Reboot a guest vm. | [
"Reboot",
"a",
"guest",
"vm",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/vmops.py#L134-L138 | train | 43,656 |
mfcloud/python-zvm-sdk | zvmsdk/vmops.py | VMOps.execute_cmd | def execute_cmd(self, userid, cmdStr):
"""Execute commands on the guest vm."""
LOG.debug("executing cmd: %s", cmdStr)
return self._smtclient.execute_cmd(userid, cmdStr) | python | def execute_cmd(self, userid, cmdStr):
"""Execute commands on the guest vm."""
LOG.debug("executing cmd: %s", cmdStr)
return self._smtclient.execute_cmd(userid, cmdStr) | [
"def",
"execute_cmd",
"(",
"self",
",",
"userid",
",",
"cmdStr",
")",
":",
"LOG",
".",
"debug",
"(",
"\"executing cmd: %s\"",
",",
"cmdStr",
")",
"return",
"self",
".",
"_smtclient",
".",
"execute_cmd",
"(",
"userid",
",",
"cmdStr",
")"
] | Execute commands on the guest vm. | [
"Execute",
"commands",
"on",
"the",
"guest",
"vm",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/vmops.py#L236-L239 | train | 43,657 |
mfcloud/python-zvm-sdk | zvmsdk/vmops.py | VMOps.set_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
"""
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)
with open(tmp_file, 'w') as f:
f.writelines(lines)
requestData = "ChangeVM " + userid + " punchfile " + \
tmp_file + " --class x"
LOG.debug("Punch script to guest %s to set hostname" % userid)
try:
self._smtclient._request(requestData)
except exception.SDKSMTRequestFailed as err:
msg = ("Failed to punch set_hostname script to userid '%s'. SMT "
"error: %s" % (userid, err.format_message()))
LOG.error(msg)
raise exception.SDKSMTRequestFailed(err.results, msg)
finally:
self._pathutils.clean_temp_folder(tmp_path) | python | 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
"""
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)
with open(tmp_file, 'w') as f:
f.writelines(lines)
requestData = "ChangeVM " + userid + " punchfile " + \
tmp_file + " --class x"
LOG.debug("Punch script to guest %s to set hostname" % userid)
try:
self._smtclient._request(requestData)
except exception.SDKSMTRequestFailed as err:
msg = ("Failed to punch set_hostname script to userid '%s'. SMT "
"error: %s" % (userid, err.format_message()))
LOG.error(msg)
raise exception.SDKSMTRequestFailed(err.results, msg)
finally:
self._pathutils.clean_temp_folder(tmp_path) | [
"def",
"set_hostname",
"(",
"self",
",",
"userid",
",",
"hostname",
",",
"os_version",
")",
":",
"tmp_path",
"=",
"self",
".",
"_pathutils",
".",
"get_guest_temp_path",
"(",
"userid",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"tmp_path",
"... | 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 | [
"Punch",
"a",
"script",
"that",
"used",
"to",
"set",
"the",
"hostname",
"of",
"the",
"guest",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/vmops.py#L241-L270 | train | 43,658 |
mfcloud/python-zvm-sdk | smtLayer/generalUtils.py | cvtToBlocks | 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
rc - Return code causing the return. Same as overallRC.
rs - Reason code causing the return.
errno - Errno value causing the return. Always zero.
Converted value in blocks
"""
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]
if byteSize == '':
# The size of the disk is not valid.
msg = msgs.msg['0200'][1] % (modId, blocks)
rh.printLn("ES", msg)
results = msgs.msg['0200'][0]
else:
try:
if lastChar == 'M':
blocks = (float(byteSize) * 1024 * 1024) / 512
elif lastChar == 'G':
blocks = (float(byteSize) * 1024 * 1024 * 1024) / 512
blocks = str(int(math.ceil(blocks)))
except Exception:
# Failed to convert to a number of blocks.
msg = msgs.msg['0201'][1] % (modId, byteSize)
rh.printLn("ES", msg)
results = msgs.msg['0201'][0]
elif blocks.strip('1234567890'):
# Size is not an integer size of blocks.
msg = msgs.msg['0202'][1] % (modId, blocks)
rh.printLn("ES", msg)
results = msgs.msg['0202'][0]
rh.printSysLog("Exit generalUtils.cvtToBlocks, rc: " +
str(results['overallRC']))
return results, blocks | python | 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
rc - Return code causing the return. Same as overallRC.
rs - Reason code causing the return.
errno - Errno value causing the return. Always zero.
Converted value in blocks
"""
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]
if byteSize == '':
# The size of the disk is not valid.
msg = msgs.msg['0200'][1] % (modId, blocks)
rh.printLn("ES", msg)
results = msgs.msg['0200'][0]
else:
try:
if lastChar == 'M':
blocks = (float(byteSize) * 1024 * 1024) / 512
elif lastChar == 'G':
blocks = (float(byteSize) * 1024 * 1024 * 1024) / 512
blocks = str(int(math.ceil(blocks)))
except Exception:
# Failed to convert to a number of blocks.
msg = msgs.msg['0201'][1] % (modId, byteSize)
rh.printLn("ES", msg)
results = msgs.msg['0201'][0]
elif blocks.strip('1234567890'):
# Size is not an integer size of blocks.
msg = msgs.msg['0202'][1] % (modId, blocks)
rh.printLn("ES", msg)
results = msgs.msg['0202'][0]
rh.printSysLog("Exit generalUtils.cvtToBlocks, rc: " +
str(results['overallRC']))
return results, blocks | [
"def",
"cvtToBlocks",
"(",
"rh",
",",
"diskSize",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter generalUtils.cvtToBlocks\"",
")",
"blocks",
"=",
"0",
"results",
"=",
"{",
"'overallRC'",
":",
"0",
",",
"'rc'",
":",
"0",
",",
"'rs'",
":",
"0",
",",
"... | 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
rc - Return code causing the return. Same as overallRC.
rs - Reason code causing the return.
errno - Errno value causing the return. Always zero.
Converted value in blocks | [
"Convert",
"a",
"disk",
"storage",
"value",
"to",
"a",
"number",
"of",
"blocks",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/generalUtils.py#L25-L78 | train | 43,659 |
mfcloud/python-zvm-sdk | smtLayer/generalUtils.py | cvtToMag | 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
"""
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.
mSize = "%.1fM" % size
rh.printSysLog("Exit generalUtils.cvtToMag, magSize: " + mSize)
return mSize | python | 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
"""
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.
mSize = "%.1fM" % size
rh.printSysLog("Exit generalUtils.cvtToMag, magSize: " + mSize)
return mSize | [
"def",
"cvtToMag",
"(",
"rh",
",",
"size",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter generalUtils.cvtToMag\"",
")",
"mSize",
"=",
"''",
"size",
"=",
"size",
"/",
"(",
"1024",
"*",
"1024",
")",
"if",
"size",
">",
"(",
"1024",
"*",
"5",
")",
... | Convert a size value to a number with a magnitude appended.
Input:
Request Handle
Size bytes
Output:
Converted value with a magnitude | [
"Convert",
"a",
"size",
"value",
"to",
"a",
"number",
"with",
"a",
"magnitude",
"appended",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/generalUtils.py#L137-L163 | train | 43,660 |
mfcloud/python-zvm-sdk | smtLayer/generalUtils.py | getSizeFromPage | 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
"""
rh.printSysLog("Enter generalUtils.getSizeFromPage")
bSize = float(page) * 4096
mSize = cvtToMag(rh, bSize)
rh.printSysLog("Exit generalUtils.getSizeFromPage, magSize: " + mSize)
return mSize | python | 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
"""
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",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter generalUtils.getSizeFromPage\"",
")",
"bSize",
"=",
"float",
"(",
"page",
")",
"*",
"4096",
"mSize",
"=",
"cvtToMag",
"(",
"rh",
",",
"bSize",
")",
"rh",
... | 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 | [
"Convert",
"a",
"size",
"value",
"from",
"page",
"to",
"a",
"number",
"with",
"a",
"magnitude",
"appended",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/generalUtils.py#L166-L183 | train | 43,661 |
rpkilby/SurveyGizmo | surveygizmo/surveygizmo.py | Config.validate | def validate(self):
"""
Perform validation check on properties.
"""
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 response_type" % self.response_type) | python | def validate(self):
"""
Perform validation check on properties.
"""
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 response_type" % self.response_type) | [
"def",
"validate",
"(",
"self",
")",
":",
"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",
".",... | Perform validation check on properties. | [
"Perform",
"validation",
"check",
"on",
"properties",
"."
] | a097091dc7dcfb58f70242fb1becabc98df049a5 | https://github.com/rpkilby/SurveyGizmo/blob/a097091dc7dcfb58f70242fb1becabc98df049a5/surveygizmo/surveygizmo.py#L41-L49 | train | 43,662 |
jvarho/pylibscrypt | pylibscrypt/pypyscrypt.py | R | def R(X, destination, a1, a2, b):
"""A single Salsa20 row operation"""
a = (X[a1] + X[a2]) & 0xffffffff
X[destination] ^= ((a << b) | (a >> (32 - b))) | python | def R(X, destination, a1, a2, b):
"""A single Salsa20 row operation"""
a = (X[a1] + X[a2]) & 0xffffffff
X[destination] ^= ((a << b) | (a >> (32 - b))) | [
"def",
"R",
"(",
"X",
",",
"destination",
",",
"a1",
",",
"a2",
",",
"b",
")",
":",
"a",
"=",
"(",
"X",
"[",
"a1",
"]",
"+",
"X",
"[",
"a2",
"]",
")",
"&",
"0xffffffff",
"X",
"[",
"destination",
"]",
"^=",
"(",
"(",
"a",
"<<",
"b",
")",
... | A single Salsa20 row operation | [
"A",
"single",
"Salsa20",
"row",
"operation"
] | f2ff02e49f44aa620e308a4a64dd8376b9510f99 | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pypyscrypt.py#L60-L64 | train | 43,663 |
mfcloud/python-zvm-sdk | zvmsdk/sdkwsgi/handlers/file.py | fileChunkIter | 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
"""
while True:
chunk = file_object.read(file_chunk_size)
if chunk:
yield chunk
else:
break | python | 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
"""
while True:
chunk = file_object.read(file_chunk_size)
if chunk:
yield chunk
else:
break | [
"def",
"fileChunkIter",
"(",
"file_object",
",",
"file_chunk_size",
"=",
"65536",
")",
":",
"while",
"True",
":",
"chunk",
"=",
"file_object",
".",
"read",
"(",
"file_chunk_size",
")",
"if",
"chunk",
":",
"yield",
"chunk",
"else",
":",
"break"
] | 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 | [
"Return",
"an",
"iterator",
"to",
"a",
"file",
"-",
"like",
"object",
"that",
"yields",
"fixed",
"size",
"chunks"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/sdkwsgi/handlers/file.py#L223-L235 | train | 43,664 |
ratcave/wavefront_reader | wavefront_reader/reading.py | read_objfile | def read_objfile(fname):
"""Takes .obj filename and returns dict of object properties for each object in file."""
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], split_line[1]
if prefix == 'o':
obj_props.append({})
obj = obj_props[-1]
obj['f'] = []
obj[prefix] = value
# For files without an 'o' statement
elif prefix == 'v' and len(obj_props) < 1:
obj_props.append({})
obj = obj_props[-1]
obj['f'] = []
obj['o'] = fname
if obj_props:
if prefix[0] == 'v':
verts[prefix].append([float(val) for val in value.split(' ')])
elif prefix == 'f':
obj[prefix].append(parse_mixed_delim_str(value))
else:
obj[prefix] = value
# Reindex vertices to be in face index order, then remove face indices.
verts = {key: np.array(value) for key, value in iteritems(verts)}
for obj in obj_props:
obj['f'] = tuple(np.array(verts) if verts[0] else tuple() for verts in zip(*obj['f']))
for idx, vertname in enumerate(['v' ,'vt', 'vn']):
if vertname in verts:
obj[vertname] = verts[vertname][obj['f'][idx].flatten() - 1, :]
else:
obj[vertname] = tuple()
del obj['f']
geoms = {obj['o']:obj for obj in obj_props}
return geoms | python | def read_objfile(fname):
"""Takes .obj filename and returns dict of object properties for each object in file."""
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], split_line[1]
if prefix == 'o':
obj_props.append({})
obj = obj_props[-1]
obj['f'] = []
obj[prefix] = value
# For files without an 'o' statement
elif prefix == 'v' and len(obj_props) < 1:
obj_props.append({})
obj = obj_props[-1]
obj['f'] = []
obj['o'] = fname
if obj_props:
if prefix[0] == 'v':
verts[prefix].append([float(val) for val in value.split(' ')])
elif prefix == 'f':
obj[prefix].append(parse_mixed_delim_str(value))
else:
obj[prefix] = value
# Reindex vertices to be in face index order, then remove face indices.
verts = {key: np.array(value) for key, value in iteritems(verts)}
for obj in obj_props:
obj['f'] = tuple(np.array(verts) if verts[0] else tuple() for verts in zip(*obj['f']))
for idx, vertname in enumerate(['v' ,'vt', 'vn']):
if vertname in verts:
obj[vertname] = verts[vertname][obj['f'][idx].flatten() - 1, :]
else:
obj[vertname] = tuple()
del obj['f']
geoms = {obj['o']:obj for obj in obj_props}
return geoms | [
"def",
"read_objfile",
"(",
"fname",
")",
":",
"verts",
"=",
"defaultdict",
"(",
"list",
")",
"obj_props",
"=",
"[",
"]",
"with",
"open",
"(",
"fname",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"read",
"(",
")",
".",
"splitlines",
"(",
")",
"f... | Takes .obj filename and returns dict of object properties for each object in file. | [
"Takes",
".",
"obj",
"filename",
"and",
"returns",
"dict",
"of",
"object",
"properties",
"for",
"each",
"object",
"in",
"file",
"."
] | c515164a3952d6b85f8044f429406fddd862bfd0 | https://github.com/ratcave/wavefront_reader/blob/c515164a3952d6b85f8044f429406fddd862bfd0/wavefront_reader/reading.py#L18-L65 | train | 43,665 |
mfcloud/python-zvm-sdk | smtLayer/vmUtils.py | disableEnableDisk | 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 the chccwdev command or IUCV transmission.
rs - rs from the chccwdev command or IUCV transmission.
results - possible error message from the IUCV transmission.
"""
rh.printSysLog("Enter vmUtils.disableEnableDisk, userid: " + userid +
" addr: " + vaddr + " option: " + option)
results = {
'overallRC': 0,
'rc': 0,
'rs': 0,
'response': ''
}
"""
Can't guarantee the success of online/offline disk, need to wait
Until it's done because we may detach the disk after -d option
or use the disk after the -e option
"""
for secs in [0.1, 0.4, 1, 1.5, 3, 7, 15, 32, 30, 30,
60, 60, 60, 60, 60]:
strCmd = "sudo /sbin/chccwdev " + option + " " + vaddr + " 2>&1"
results = execCmdThruIUCV(rh, userid, strCmd)
if results['overallRC'] == 0:
break
elif (results['overallRC'] == 2 and results['rc'] == 8 and
results['rs'] == 1 and option == '-d'):
# Linux does not know about the disk being disabled.
# Ok, nothing to do. Treat this as a success.
results = {'overallRC': 0, 'rc': 0, 'rs': 0, 'response': ''}
break
time.sleep(secs)
rh.printSysLog("Exit vmUtils.disableEnableDisk, rc: " +
str(results['overallRC']))
return results | python | 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 the chccwdev command or IUCV transmission.
rs - rs from the chccwdev command or IUCV transmission.
results - possible error message from the IUCV transmission.
"""
rh.printSysLog("Enter vmUtils.disableEnableDisk, userid: " + userid +
" addr: " + vaddr + " option: " + option)
results = {
'overallRC': 0,
'rc': 0,
'rs': 0,
'response': ''
}
"""
Can't guarantee the success of online/offline disk, need to wait
Until it's done because we may detach the disk after -d option
or use the disk after the -e option
"""
for secs in [0.1, 0.4, 1, 1.5, 3, 7, 15, 32, 30, 30,
60, 60, 60, 60, 60]:
strCmd = "sudo /sbin/chccwdev " + option + " " + vaddr + " 2>&1"
results = execCmdThruIUCV(rh, userid, strCmd)
if results['overallRC'] == 0:
break
elif (results['overallRC'] == 2 and results['rc'] == 8 and
results['rs'] == 1 and option == '-d'):
# Linux does not know about the disk being disabled.
# Ok, nothing to do. Treat this as a success.
results = {'overallRC': 0, 'rc': 0, 'rs': 0, 'response': ''}
break
time.sleep(secs)
rh.printSysLog("Exit vmUtils.disableEnableDisk, rc: " +
str(results['overallRC']))
return results | [
"def",
"disableEnableDisk",
"(",
"rh",
",",
"userid",
",",
"vaddr",
",",
"option",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter vmUtils.disableEnableDisk, userid: \"",
"+",
"userid",
"+",
"\" addr: \"",
"+",
"vaddr",
"+",
"\" option: \"",
"+",
"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 the chccwdev command or IUCV transmission.
rs - rs from the chccwdev command or IUCV transmission.
results - possible error message from the IUCV transmission. | [
"Disable",
"or",
"enable",
"a",
"disk",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/vmUtils.py#L28-L77 | train | 43,666 |
mfcloud/python-zvm-sdk | smtLayer/vmUtils.py | getPerfInfo | 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 overallRC = 0.
rs - RS returned from SMCLI if overallRC = 0.
errno - Errno returned from SMCLI if overallRC = 0.
response - Stripped and reformatted output of the SMCLI command.
"""
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("Exit vmUtils.getPerfInfo, rc: " +
str(results['overallRC']))
return results
lines = results['response'].split("\n")
usedTime = 0
totalCpu = 0
totalMem = 0
usedMem = 0
try:
for line in lines:
if "Used CPU time:" in line:
usedTime = line.split()[3].strip('"')
# Value is in us, need make it seconds
usedTime = int(usedTime) / 1000000
if "Guest CPUs:" in line:
totalCpu = line.split()[2].strip('"')
if "Max memory:" in line:
totalMem = line.split()[2].strip('"')
# Value is in Kb, need to make it Mb
totalMem = int(totalMem) / 1024
if "Used memory:" in line:
usedMem = line.split()[2].strip('"')
usedMem = int(usedMem) / 1024
except Exception as e:
msg = msgs.msg['0412'][1] % (modId, type(e).__name__,
str(e), results['response'])
rh.printLn("ES", msg)
results['overallRC'] = 4
results['rc'] = 4
results['rs'] = 412
if results['overallRC'] == 0:
memstr = "Total Memory: %iM\n" % totalMem
usedmemstr = "Used Memory: %iM\n" % usedMem
procstr = "Processors: %s\n" % totalCpu
timestr = "CPU Used Time: %i sec\n" % usedTime
results['response'] = memstr + usedmemstr + procstr + timestr
rh.printSysLog("Exit vmUtils.getPerfInfo, rc: " +
str(results['rc']))
return results | python | 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 overallRC = 0.
rs - RS returned from SMCLI if overallRC = 0.
errno - Errno returned from SMCLI if overallRC = 0.
response - Stripped and reformatted output of the SMCLI command.
"""
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("Exit vmUtils.getPerfInfo, rc: " +
str(results['overallRC']))
return results
lines = results['response'].split("\n")
usedTime = 0
totalCpu = 0
totalMem = 0
usedMem = 0
try:
for line in lines:
if "Used CPU time:" in line:
usedTime = line.split()[3].strip('"')
# Value is in us, need make it seconds
usedTime = int(usedTime) / 1000000
if "Guest CPUs:" in line:
totalCpu = line.split()[2].strip('"')
if "Max memory:" in line:
totalMem = line.split()[2].strip('"')
# Value is in Kb, need to make it Mb
totalMem = int(totalMem) / 1024
if "Used memory:" in line:
usedMem = line.split()[2].strip('"')
usedMem = int(usedMem) / 1024
except Exception as e:
msg = msgs.msg['0412'][1] % (modId, type(e).__name__,
str(e), results['response'])
rh.printLn("ES", msg)
results['overallRC'] = 4
results['rc'] = 4
results['rs'] = 412
if results['overallRC'] == 0:
memstr = "Total Memory: %iM\n" % totalMem
usedmemstr = "Used Memory: %iM\n" % usedMem
procstr = "Processors: %s\n" % totalCpu
timestr = "CPU Used Time: %i sec\n" % usedTime
results['response'] = memstr + usedmemstr + procstr + timestr
rh.printSysLog("Exit vmUtils.getPerfInfo, rc: " +
str(results['rc']))
return results | [
"def",
"getPerfInfo",
"(",
"rh",
",",
"useridlist",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter vmUtils.getPerfInfo, userid: \"",
"+",
"useridlist",
")",
"parms",
"=",
"[",
"\"-T\"",
",",
"rh",
".",
"userid",
",",
"\"-c\"",
",",
"\"1\"",
"]",
"results"... | 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 overallRC = 0.
rs - RS returned from SMCLI if overallRC = 0.
errno - Errno returned from SMCLI if overallRC = 0.
response - Stripped and reformatted output of the SMCLI command. | [
"Get",
"the",
"performance",
"information",
"for",
"a",
"userid"
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/vmUtils.py#L206-L269 | train | 43,667 |
mfcloud/python-zvm-sdk | smtLayer/vmUtils.py | isLoggedOn | 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
error return code from the commands issued.
rs - Based on rc value. For rc==0, rs is:
0: if we determined it is logged on.
1: if we determined it is logged off.
"""
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:
subprocess.check_output(
cmd,
close_fds=True,
stderr=subprocess.STDOUT)
except CalledProcessError as e:
search_pattern = '(^HCP\w\w\w045E|^HCP\w\w\w361E)'.encode()
match = re.search(search_pattern, e.output)
if match:
# Not logged on
results['rs'] = 1
else:
# Abnormal failure
rh.printLn("ES", msgs.msg['0415'][1] % (modId, strCmd,
e.returncode, e.output))
results = msgs.msg['0415'][0]
results['rs'] = e.returncode
except Exception as e:
# All other exceptions.
results = msgs.msg['0421'][0]
rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
type(e).__name__, str(e)))
rh.printSysLog("Exit vmUtils.isLoggedOn, overallRC: " +
str(results['overallRC']) + " rc: " + str(results['rc']) +
" rs: " + str(results['rs']))
return results | python | 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
error return code from the commands issued.
rs - Based on rc value. For rc==0, rs is:
0: if we determined it is logged on.
1: if we determined it is logged off.
"""
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:
subprocess.check_output(
cmd,
close_fds=True,
stderr=subprocess.STDOUT)
except CalledProcessError as e:
search_pattern = '(^HCP\w\w\w045E|^HCP\w\w\w361E)'.encode()
match = re.search(search_pattern, e.output)
if match:
# Not logged on
results['rs'] = 1
else:
# Abnormal failure
rh.printLn("ES", msgs.msg['0415'][1] % (modId, strCmd,
e.returncode, e.output))
results = msgs.msg['0415'][0]
results['rs'] = e.returncode
except Exception as e:
# All other exceptions.
results = msgs.msg['0421'][0]
rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
type(e).__name__, str(e)))
rh.printSysLog("Exit vmUtils.isLoggedOn, overallRC: " +
str(results['overallRC']) + " rc: " + str(results['rc']) +
" rs: " + str(results['rs']))
return results | [
"def",
"isLoggedOn",
"(",
"rh",
",",
"userid",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter vmUtils.isLoggedOn, userid: \"",
"+",
"userid",
")",
"results",
"=",
"{",
"'overallRC'",
":",
"0",
",",
"'rc'",
":",
"0",
",",
"'rs'",
":",
"0",
",",
"}",
... | 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
error return code from the commands issued.
rs - Based on rc value. For rc==0, rs is:
0: if we determined it is logged on.
1: if we determined it is logged off. | [
"Determine",
"whether",
"a",
"virtual",
"machine",
"is",
"logged",
"on",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/vmUtils.py#L724-L779 | train | 43,668 |
mfcloud/python-zvm-sdk | smtLayer/vmUtils.py | waitForOSState | 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:
Dictionary containing the following:
overallRC - overall return code, 0: success, non-zero: failure
rc - RC returned from execCmdThruIUCV if overallRC = 0.
rs - RS returned from execCmdThruIUCV if overallRC = 0.
errno - Errno returned from execCmdThruIUCV if overallRC = 0.
response - Updated with an error message if wait times out.
Note:
"""
rh.printSysLog("Enter vmUtils.waitForOSState, userid: " + userid +
" state: " + desiredState +
" maxWait: " + str(maxQueries) +
" sleepSecs: " + str(sleepSecs))
results = {}
strCmd = "echo 'ping'"
stateFnd = False
for i in range(1, maxQueries + 1):
results = execCmdThruIUCV(rh, rh.userid, strCmd)
if results['overallRC'] == 0:
if desiredState == 'up':
stateFnd = True
break
else:
if desiredState == 'down':
stateFnd = True
break
if i < maxQueries:
time.sleep(sleepSecs)
if stateFnd is True:
results = {
'overallRC': 0,
'rc': 0,
'rs': 0,
}
else:
maxWait = maxQueries * sleepSecs
rh.printLn("ES", msgs.msg['0413'][1] % (modId, userid,
desiredState, maxWait))
results = msgs.msg['0413'][0]
rh.printSysLog("Exit vmUtils.waitForOSState, rc: " +
str(results['overallRC']))
return results | python | 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:
Dictionary containing the following:
overallRC - overall return code, 0: success, non-zero: failure
rc - RC returned from execCmdThruIUCV if overallRC = 0.
rs - RS returned from execCmdThruIUCV if overallRC = 0.
errno - Errno returned from execCmdThruIUCV if overallRC = 0.
response - Updated with an error message if wait times out.
Note:
"""
rh.printSysLog("Enter vmUtils.waitForOSState, userid: " + userid +
" state: " + desiredState +
" maxWait: " + str(maxQueries) +
" sleepSecs: " + str(sleepSecs))
results = {}
strCmd = "echo 'ping'"
stateFnd = False
for i in range(1, maxQueries + 1):
results = execCmdThruIUCV(rh, rh.userid, strCmd)
if results['overallRC'] == 0:
if desiredState == 'up':
stateFnd = True
break
else:
if desiredState == 'down':
stateFnd = True
break
if i < maxQueries:
time.sleep(sleepSecs)
if stateFnd is True:
results = {
'overallRC': 0,
'rc': 0,
'rs': 0,
}
else:
maxWait = maxQueries * sleepSecs
rh.printLn("ES", msgs.msg['0413'][1] % (modId, userid,
desiredState, maxWait))
results = msgs.msg['0413'][0]
rh.printSysLog("Exit vmUtils.waitForOSState, rc: " +
str(results['overallRC']))
return results | [
"def",
"waitForOSState",
"(",
"rh",
",",
"userid",
",",
"desiredState",
",",
"maxQueries",
"=",
"90",
",",
"sleepSecs",
"=",
"5",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter vmUtils.waitForOSState, userid: \"",
"+",
"userid",
"+",
"\" state: \"",
"+",
"d... | 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:
Dictionary containing the following:
overallRC - overall return code, 0: success, non-zero: failure
rc - RC returned from execCmdThruIUCV if overallRC = 0.
rs - RS returned from execCmdThruIUCV if overallRC = 0.
errno - Errno returned from execCmdThruIUCV if overallRC = 0.
response - Updated with an error message if wait times out.
Note: | [
"Wait",
"for",
"the",
"virtual",
"OS",
"to",
"go",
"into",
"the",
"indicated",
"state",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/vmUtils.py#L955-L1016 | train | 43,669 |
mfcloud/python-zvm-sdk | smtLayer/vmUtils.py | waitForVMState | 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:
Dictionary containing the following:
overallRC - overall return code, 0: success, non-zero: failure
rc - RC returned from SMCLI if overallRC = 0.
rs - RS returned from SMCLI if overallRC = 0.
Note:
"""
rh.printSysLog("Enter vmUtils.waitForVMState, userid: " + userid +
" state: " + desiredState +
" maxWait: " + str(maxQueries) +
" sleepSecs: " + str(sleepSecs))
results = {}
cmd = ["sudo", "/sbin/vmcp", "query", "user", userid]
strCmd = " ".join(cmd)
stateFnd = False
for i in range(1, maxQueries + 1):
rh.printSysLog("Invoking: " + strCmd)
try:
out = subprocess.check_output(
cmd,
close_fds=True,
stderr=subprocess.STDOUT)
if isinstance(out, bytes):
out = bytes.decode(out)
if desiredState == 'on':
stateFnd = True
break
except CalledProcessError as e:
match = re.search('(^HCP\w\w\w045E|^HCP\w\w\w361E)', e.output)
if match:
# Logged off
if desiredState == 'off':
stateFnd = True
break
else:
# Abnormal failure
out = e.output
rh.printLn("ES", msgs.msg['0415'][1] % (modId, strCmd,
e.returncode, out))
results = msgs.msg['0415'][0]
results['rs'] = e.returncode
break
except Exception as e:
# All other exceptions.
rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
type(e).__name__, str(e)))
results = msgs.msg['0421'][0]
if i < maxQueries:
# Sleep a bit before looping.
time.sleep(sleepSecs)
if stateFnd is True:
results = {
'overallRC': 0,
'rc': 0,
'rs': 0,
}
else:
maxWait = maxQueries * sleepSecs
rh.printLn("ES", msgs.msg['0414'][1] % (modId, userid,
desiredState, maxWait))
results = msgs.msg['0414'][0]
rh.printSysLog("Exit vmUtils.waitForVMState, rc: " +
str(results['overallRC']))
return results | python | 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:
Dictionary containing the following:
overallRC - overall return code, 0: success, non-zero: failure
rc - RC returned from SMCLI if overallRC = 0.
rs - RS returned from SMCLI if overallRC = 0.
Note:
"""
rh.printSysLog("Enter vmUtils.waitForVMState, userid: " + userid +
" state: " + desiredState +
" maxWait: " + str(maxQueries) +
" sleepSecs: " + str(sleepSecs))
results = {}
cmd = ["sudo", "/sbin/vmcp", "query", "user", userid]
strCmd = " ".join(cmd)
stateFnd = False
for i in range(1, maxQueries + 1):
rh.printSysLog("Invoking: " + strCmd)
try:
out = subprocess.check_output(
cmd,
close_fds=True,
stderr=subprocess.STDOUT)
if isinstance(out, bytes):
out = bytes.decode(out)
if desiredState == 'on':
stateFnd = True
break
except CalledProcessError as e:
match = re.search('(^HCP\w\w\w045E|^HCP\w\w\w361E)', e.output)
if match:
# Logged off
if desiredState == 'off':
stateFnd = True
break
else:
# Abnormal failure
out = e.output
rh.printLn("ES", msgs.msg['0415'][1] % (modId, strCmd,
e.returncode, out))
results = msgs.msg['0415'][0]
results['rs'] = e.returncode
break
except Exception as e:
# All other exceptions.
rh.printLn("ES", msgs.msg['0421'][1] % (modId, strCmd,
type(e).__name__, str(e)))
results = msgs.msg['0421'][0]
if i < maxQueries:
# Sleep a bit before looping.
time.sleep(sleepSecs)
if stateFnd is True:
results = {
'overallRC': 0,
'rc': 0,
'rs': 0,
}
else:
maxWait = maxQueries * sleepSecs
rh.printLn("ES", msgs.msg['0414'][1] % (modId, userid,
desiredState, maxWait))
results = msgs.msg['0414'][0]
rh.printSysLog("Exit vmUtils.waitForVMState, rc: " +
str(results['overallRC']))
return results | [
"def",
"waitForVMState",
"(",
"rh",
",",
"userid",
",",
"desiredState",
",",
"maxQueries",
"=",
"90",
",",
"sleepSecs",
"=",
"5",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter vmUtils.waitForVMState, userid: \"",
"+",
"userid",
"+",
"\" state: \"",
"+",
"d... | 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:
Dictionary containing the following:
overallRC - overall return code, 0: success, non-zero: failure
rc - RC returned from SMCLI if overallRC = 0.
rs - RS returned from SMCLI if overallRC = 0.
Note: | [
"Wait",
"for",
"the",
"virtual",
"machine",
"to",
"go",
"into",
"the",
"indicated",
"state",
"."
] | de9994ceca764f5460ce51bd74237986341d8e3c | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/vmUtils.py#L1019-L1102 | train | 43,670 |
marrow/cinje | cinje/util.py | stream | 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.
"""
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 | python | 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.
"""
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'",
")",
":",
"input",
"=",
"(",
"i",
"for",
"i",
"in",
"input",
"if",
"i",
")",
"# Omits `None` (empty wrappers) and empty chunks.",
"if",
"encoding",
":",
"# Automatic... | 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. | [
"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",
"a... | 413bdac7242020ce8379d272720c649a9196daa2 | https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/util.py#L71-L82 | train | 43,671 |
marrow/cinje | cinje/util.py | Context.prepare | def prepare(self):
"""Prepare the ordered list of transformers and reset context state to initial."""
self.scope = 0
self.mapping = deque([0])
self._handler = [i() for i in sorted(self.handlers, key=lambda handler: handler.priority)] | python | def prepare(self):
"""Prepare the ordered list of transformers and reset context state to initial."""
self.scope = 0
self.mapping = deque([0])
self._handler = [i() for i in sorted(self.handlers, key=lambda handler: handler.priority)] | [
"def",
"prepare",
"(",
"self",
")",
":",
"self",
".",
"scope",
"=",
"0",
"self",
".",
"mapping",
"=",
"deque",
"(",
"[",
"0",
"]",
")",
"self",
".",
"_handler",
"=",
"[",
"i",
"(",
")",
"for",
"i",
"in",
"sorted",
"(",
"self",
".",
"handlers",
... | Prepare the ordered list of transformers and reset context state to initial. | [
"Prepare",
"the",
"ordered",
"list",
"of",
"transformers",
"and",
"reset",
"context",
"state",
"to",
"initial",
"."
] | 413bdac7242020ce8379d272720c649a9196daa2 | https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/util.py#L468-L472 | train | 43,672 |
marrow/cinje | cinje/util.py | Context.classify | def classify(self, line):
"""Identify the correct handler for a given line of input."""
for handler in self._handler:
if handler.match(self, line):
return handler | python | def classify(self, line):
"""Identify the correct handler for a given line of input."""
for handler in self._handler:
if handler.match(self, line):
return handler | [
"def",
"classify",
"(",
"self",
",",
"line",
")",
":",
"for",
"handler",
"in",
"self",
".",
"_handler",
":",
"if",
"handler",
".",
"match",
"(",
"self",
",",
"line",
")",
":",
"return",
"handler"
] | Identify the correct handler for a given line of input. | [
"Identify",
"the",
"correct",
"handler",
"for",
"a",
"given",
"line",
"of",
"input",
"."
] | 413bdac7242020ce8379d272720c649a9196daa2 | https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/util.py#L513-L518 | train | 43,673 |
marrow/cinje | cinje/block/module.py | red | def red(numbers):
"""Encode the deltas to reduce entropy."""
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') | python | def red(numbers):
"""Encode the deltas to reduce entropy."""
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",
")",
":",
"line",
"=",
"0",
"deltas",
"=",
"[",
"]",
"for",
"value",
"in",
"numbers",
":",
"deltas",
".",
"append",
"(",
"value",
"-",
"line",
")",
"line",
"=",
"value",
"return",
"b64encode",
"(",
"compress",
"(",
"b'... | Encode the deltas to reduce entropy. | [
"Encode",
"the",
"deltas",
"to",
"reduce",
"entropy",
"."
] | 413bdac7242020ce8379d272720c649a9196daa2 | https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/block/module.py#L12-L22 | train | 43,674 |
marrow/cinje | cinje/block/generic.py | Generic.match | def match(self, context, line):
"""Match code lines prefixed with a variety of keywords."""
return line.kind == 'code' and line.partitioned[0] in self._both | python | def match(self, context, line):
"""Match code lines prefixed with a variety of keywords."""
return line.kind == 'code' and line.partitioned[0] in self._both | [
"def",
"match",
"(",
"self",
",",
"context",
",",
"line",
")",
":",
"return",
"line",
".",
"kind",
"==",
"'code'",
"and",
"line",
".",
"partitioned",
"[",
"0",
"]",
"in",
"self",
".",
"_both"
] | Match code lines prefixed with a variety of keywords. | [
"Match",
"code",
"lines",
"prefixed",
"with",
"a",
"variety",
"of",
"keywords",
"."
] | 413bdac7242020ce8379d272720c649a9196daa2 | https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/block/generic.py#L56-L59 | train | 43,675 |
fgmacedo/django-export-action | export_action/introspection.py | get_direct_fields_from_model | def get_direct_fields_from_model(model_class):
""" Direct, not m2m, not FK """
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 direct_fields | python | def get_direct_fields_from_model(model_class):
""" Direct, not m2m, not FK """
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 direct_fields | [
"def",
"get_direct_fields_from_model",
"(",
"model_class",
")",
":",
"direct_fields",
"=",
"[",
"]",
"all_fields_names",
"=",
"_get_all_field_names",
"(",
"model_class",
")",
"for",
"field_name",
"in",
"all_fields_names",
":",
"field",
",",
"model",
",",
"direct",
... | Direct, not m2m, not FK | [
"Direct",
"not",
"m2m",
"not",
"FK"
] | 215fecb9044d22e3ae19d86c3b220041a11fad07 | https://github.com/fgmacedo/django-export-action/blob/215fecb9044d22e3ae19d86c3b220041a11fad07/export_action/introspection.py#L66-L74 | train | 43,676 |
fgmacedo/django-export-action | export_action/introspection.py | get_fields | 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 model fields
properties: Any properties the model has
path: Our new path
:rtype: dict
"""
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:
new_model = _get_remote_field(field).parent_model
except AttributeError:
new_model = _get_remote_field(field).model
else: # Indirect related field
new_model = field.related_model
fields = get_direct_fields_from_model(new_model)
app_label = new_model._meta.app_label
return {
'fields': fields,
'path': path,
'app_label': app_label,
} | python | 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 model fields
properties: Any properties the model has
path: Our new path
:rtype: dict
"""
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:
new_model = _get_remote_field(field).parent_model
except AttributeError:
new_model = _get_remote_field(field).model
else: # Indirect related field
new_model = field.related_model
fields = get_direct_fields_from_model(new_model)
app_label = new_model._meta.app_label
return {
'fields': fields,
'path': path,
'app_label': app_label,
} | [
"def",
"get_fields",
"(",
"model_class",
",",
"field_name",
"=",
"''",
",",
"path",
"=",
"''",
")",
":",
"fields",
"=",
"get_direct_fields_from_model",
"(",
"model_class",
")",
"app_label",
"=",
"model_class",
".",
"_meta",
".",
"app_label",
"if",
"field_name"... | 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 model fields
properties: Any properties the model has
path: Our new path
:rtype: dict | [
"Get",
"fields",
"and",
"meta",
"data",
"from",
"a",
"model"
] | 215fecb9044d22e3ae19d86c3b220041a11fad07 | https://github.com/fgmacedo/django-export-action/blob/215fecb9044d22e3ae19d86c3b220041a11fad07/export_action/introspection.py#L102-L139 | train | 43,677 |
fgmacedo/django-export-action | export_action/introspection.py | get_related_fields | def get_related_fields(model_class, field_name, path=""):
""" Get fields for a given model """
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(field).model
else:
# Indirect related field
if hasattr(field, 'related_model'): # Django>=1.8
new_model = field.related_model
else:
new_model = field.model()
path += field_name
path += '__'
else:
new_model = model_class
new_fields = get_relation_fields_from_model(new_model)
model_ct = ContentType.objects.get_for_model(new_model)
return (new_fields, model_ct, path) | python | def get_related_fields(model_class, field_name, path=""):
""" Get fields for a given model """
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(field).model
else:
# Indirect related field
if hasattr(field, 'related_model'): # Django>=1.8
new_model = field.related_model
else:
new_model = field.model()
path += field_name
path += '__'
else:
new_model = model_class
new_fields = get_relation_fields_from_model(new_model)
model_ct = ContentType.objects.get_for_model(new_model)
return (new_fields, model_ct, path) | [
"def",
"get_related_fields",
"(",
"model_class",
",",
"field_name",
",",
"path",
"=",
"\"\"",
")",
":",
"if",
"field_name",
":",
"field",
",",
"model",
",",
"direct",
",",
"m2m",
"=",
"_get_field_by_name",
"(",
"model_class",
",",
"field_name",
")",
"if",
... | Get fields for a given model | [
"Get",
"fields",
"for",
"a",
"given",
"model"
] | 215fecb9044d22e3ae19d86c3b220041a11fad07 | https://github.com/fgmacedo/django-export-action/blob/215fecb9044d22e3ae19d86c3b220041a11fad07/export_action/introspection.py#L142-L167 | train | 43,678 |
marrow/cinje | cinje/inline/flush.py | flush_template | 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.
"""
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_buffer(context):
yield i
if declaration.stripped == 'yield':
yield declaration | python | 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.
"""
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_buffer(context):
yield i
if declaration.stripped == 'yield':
yield declaration | [
"def",
"flush_template",
"(",
"context",
",",
"declaration",
"=",
"None",
",",
"reconstruct",
"=",
"True",
")",
":",
"if",
"declaration",
"is",
"None",
":",
"declaration",
"=",
"Line",
"(",
"0",
",",
"''",
")",
"if",
"{",
"'text'",
",",
"'dirty'",
"}",... | Emit the code needed to flush the buffer.
Will only emit the yield and clear if the buffer is known to be dirty. | [
"Emit",
"the",
"code",
"needed",
"to",
"flush",
"the",
"buffer",
".",
"Will",
"only",
"emit",
"the",
"yield",
"and",
"clear",
"if",
"the",
"buffer",
"is",
"known",
"to",
"be",
"dirty",
"."
] | 413bdac7242020ce8379d272720c649a9196daa2 | https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/inline/flush.py#L6-L26 | train | 43,679 |
fgmacedo/django-export-action | export_action/report.py | _can_change_or_view | def _can_change_or_view(model, user):
""" Return True iff `user` has either change or view permission
for `model`.
"""
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 | python | def _can_change_or_view(model, user):
""" Return True iff `user` has either change or view permission
for `model`.
"""
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",
")",
":",
"model_name",
"=",
"model",
".",
"_meta",
".",
"model_name",
"app_label",
"=",
"model",
".",
"_meta",
".",
"app_label",
"can_change",
"=",
"user",
".",
"has_perm",
"(",
"app_label",
"+",
"'... | Return True iff `user` has either change or view permission
for `model`. | [
"Return",
"True",
"iff",
"user",
"has",
"either",
"change",
"or",
"view",
"permission",
"for",
"model",
"."
] | 215fecb9044d22e3ae19d86c3b220041a11fad07 | https://github.com/fgmacedo/django-export-action/blob/215fecb9044d22e3ae19d86c3b220041a11fad07/export_action/report.py#L37-L46 | train | 43,680 |
fgmacedo/django-export-action | export_action/report.py | report_to_list | 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.
"""
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 = display_field.split('__')
field = field_list[-1]
path = '__'.join(field_list[:-1])
if path:
path += '__' # Legacy format to append a __ here.
df = DisplayField(path, field)
new_display_fields.append(df)
display_fields = new_display_fields
# Display Values
display_field_paths = []
for i, display_field in enumerate(display_fields):
model = get_model_from_path_string(model_class, display_field.path)
if not model or _can_change_or_view(model, user):
display_field_key = display_field.path + display_field.field
display_field_paths.append(display_field_key)
else:
message += 'Error: Permission denied on access to {0}.'.format(
display_field.name
)
values_list = objects.values_list(*display_field_paths)
values_and_properties_list = [list(row) for row in values_list]
return values_and_properties_list, message | python | 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.
"""
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 = display_field.split('__')
field = field_list[-1]
path = '__'.join(field_list[:-1])
if path:
path += '__' # Legacy format to append a __ here.
df = DisplayField(path, field)
new_display_fields.append(df)
display_fields = new_display_fields
# Display Values
display_field_paths = []
for i, display_field in enumerate(display_fields):
model = get_model_from_path_string(model_class, display_field.path)
if not model or _can_change_or_view(model, user):
display_field_key = display_field.path + display_field.field
display_field_paths.append(display_field_key)
else:
message += 'Error: Permission denied on access to {0}.'.format(
display_field.name
)
values_list = objects.values_list(*display_field_paths)
values_and_properties_list = [list(row) for row in values_list]
return values_and_properties_list, message | [
"def",
"report_to_list",
"(",
"queryset",
",",
"display_fields",
",",
"user",
")",
":",
"model_class",
"=",
"queryset",
".",
"model",
"objects",
"=",
"queryset",
"message",
"=",
"\"\"",
"if",
"not",
"_can_change_or_view",
"(",
"model_class",
",",
"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. | [
"Create",
"list",
"from",
"a",
"report",
"with",
"all",
"data",
"filtering",
"."
] | 215fecb9044d22e3ae19d86c3b220041a11fad07 | https://github.com/fgmacedo/django-export-action/blob/215fecb9044d22e3ae19d86c3b220041a11fad07/export_action/report.py#L49-L100 | train | 43,681 |
fgmacedo/django-export-action | export_action/report.py | list_to_workbook | def list_to_workbook(data, title='report', header=None, widths=None):
""" Create just a openpxl workbook from a list of data """
wb = Workbook()
title = re.sub(r'\W+', '', title)[:30]
if isinstance(data, dict):
i = 0
for sheet_name, sheet_data in data.items():
if i > 0:
wb.create_sheet()
ws = wb.worksheets[i]
build_sheet(
sheet_data, ws, sheet_name=sheet_name, header=header)
i += 1
else:
ws = wb.worksheets[0]
build_sheet(data, ws, header=header, widths=widths)
return wb | python | def list_to_workbook(data, title='report', header=None, widths=None):
""" Create just a openpxl workbook from a list of data """
wb = Workbook()
title = re.sub(r'\W+', '', title)[:30]
if isinstance(data, dict):
i = 0
for sheet_name, sheet_data in data.items():
if i > 0:
wb.create_sheet()
ws = wb.worksheets[i]
build_sheet(
sheet_data, ws, sheet_name=sheet_name, header=header)
i += 1
else:
ws = wb.worksheets[0]
build_sheet(data, ws, header=header, widths=widths)
return wb | [
"def",
"list_to_workbook",
"(",
"data",
",",
"title",
"=",
"'report'",
",",
"header",
"=",
"None",
",",
"widths",
"=",
"None",
")",
":",
"wb",
"=",
"Workbook",
"(",
")",
"title",
"=",
"re",
".",
"sub",
"(",
"r'\\W+'",
",",
"''",
",",
"title",
")",
... | Create just a openpxl workbook from a list of data | [
"Create",
"just",
"a",
"openpxl",
"workbook",
"from",
"a",
"list",
"of",
"data"
] | 215fecb9044d22e3ae19d86c3b220041a11fad07 | https://github.com/fgmacedo/django-export-action/blob/215fecb9044d22e3ae19d86c3b220041a11fad07/export_action/report.py#L136-L153 | train | 43,682 |
fgmacedo/django-export-action | export_action/report.py | build_xlsx_response | def build_xlsx_response(wb, title="report"):
""" Take a workbook and return a xlsx file response """
title = generate_filename(title, '.xlsx')
myfile = BytesIO()
myfile.write(save_virtual_workbook(wb))
response = HttpResponse(
myfile.getvalue(),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % title
response['Content-Length'] = myfile.tell()
return response | python | def build_xlsx_response(wb, title="report"):
""" Take a workbook and return a xlsx file response """
title = generate_filename(title, '.xlsx')
myfile = BytesIO()
myfile.write(save_virtual_workbook(wb))
response = HttpResponse(
myfile.getvalue(),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % title
response['Content-Length'] = myfile.tell()
return response | [
"def",
"build_xlsx_response",
"(",
"wb",
",",
"title",
"=",
"\"report\"",
")",
":",
"title",
"=",
"generate_filename",
"(",
"title",
",",
"'.xlsx'",
")",
"myfile",
"=",
"BytesIO",
"(",
")",
"myfile",
".",
"write",
"(",
"save_virtual_workbook",
"(",
"wb",
"... | Take a workbook and return a xlsx file response | [
"Take",
"a",
"workbook",
"and",
"return",
"a",
"xlsx",
"file",
"response"
] | 215fecb9044d22e3ae19d86c3b220041a11fad07 | https://github.com/fgmacedo/django-export-action/blob/215fecb9044d22e3ae19d86c3b220041a11fad07/export_action/report.py#L156-L166 | train | 43,683 |
fgmacedo/django-export-action | export_action/report.py | list_to_csv_response | def list_to_csv_response(data, title='report', header=None, widths=None):
""" Make 2D list into a csv response for download data.
"""
response = HttpResponse(content_type="text/csv; charset=UTF-8")
cw = csv.writer(response)
for row in chain([header] if header else [], data):
cw.writerow([force_text(s).encode(response.charset) for s in row])
return response | python | def list_to_csv_response(data, title='report', header=None, widths=None):
""" Make 2D list into a csv response for download data.
"""
response = HttpResponse(content_type="text/csv; charset=UTF-8")
cw = csv.writer(response)
for row in chain([header] if header else [], data):
cw.writerow([force_text(s).encode(response.charset) for s in row])
return response | [
"def",
"list_to_csv_response",
"(",
"data",
",",
"title",
"=",
"'report'",
",",
"header",
"=",
"None",
",",
"widths",
"=",
"None",
")",
":",
"response",
"=",
"HttpResponse",
"(",
"content_type",
"=",
"\"text/csv; charset=UTF-8\"",
")",
"cw",
"=",
"csv",
".",... | Make 2D list into a csv response for download data. | [
"Make",
"2D",
"list",
"into",
"a",
"csv",
"response",
"for",
"download",
"data",
"."
] | 215fecb9044d22e3ae19d86c3b220041a11fad07 | https://github.com/fgmacedo/django-export-action/blob/215fecb9044d22e3ae19d86c3b220041a11fad07/export_action/report.py#L179-L186 | train | 43,684 |
marrow/cinje | cinje/inline/text.py | Text.gather | def gather(input):
"""Collect contiguous lines of text, preserving line numbers."""
try:
line = input.next()
except StopIteration:
return
lead = True
buffer = []
# Gather contiguous (uninterrupted) lines of template text.
while line.kind == 'text':
value = line.line.rstrip().rstrip('\\') + ('' if line.continued else '\n')
if lead and line.stripped:
yield Line(line.number, value)
lead = False
elif not lead:
if line.stripped:
for buf in buffer:
yield buf
buffer = []
yield Line(line.number, value)
else:
buffer.append(Line(line.number, value))
try:
line = input.next()
except StopIteration:
line = None
break
if line:
input.push(line) | python | def gather(input):
"""Collect contiguous lines of text, preserving line numbers."""
try:
line = input.next()
except StopIteration:
return
lead = True
buffer = []
# Gather contiguous (uninterrupted) lines of template text.
while line.kind == 'text':
value = line.line.rstrip().rstrip('\\') + ('' if line.continued else '\n')
if lead and line.stripped:
yield Line(line.number, value)
lead = False
elif not lead:
if line.stripped:
for buf in buffer:
yield buf
buffer = []
yield Line(line.number, value)
else:
buffer.append(Line(line.number, value))
try:
line = input.next()
except StopIteration:
line = None
break
if line:
input.push(line) | [
"def",
"gather",
"(",
"input",
")",
":",
"try",
":",
"line",
"=",
"input",
".",
"next",
"(",
")",
"except",
"StopIteration",
":",
"return",
"lead",
"=",
"True",
"buffer",
"=",
"[",
"]",
"# Gather contiguous (uninterrupted) lines of template text.",
"while",
"l... | Collect contiguous lines of text, preserving line numbers. | [
"Collect",
"contiguous",
"lines",
"of",
"text",
"preserving",
"line",
"numbers",
"."
] | 413bdac7242020ce8379d272720c649a9196daa2 | https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/inline/text.py#L73-L110 | train | 43,685 |
marrow/cinje | cinje/inline/text.py | Text.process | def process(self, context, lines):
"""Chop up individual lines into static and dynamic parts.
Applies light optimizations, such as empty chunk removal, and calls out to other methods to process different
chunk types.
The processor protocol here requires the method to accept values by yielding resulting lines while accepting
sent chunks. Deferral of multiple chunks is possible by yielding None. The processor will be sent None to
be given a chance to yield a final line and perform any clean-up.
"""
handler = None
for line in lines:
for chunk in chunk_(line):
if 'strip' in context.flag:
chunk.line = chunk.stripped
if not chunk.line: continue # Eliminate empty chunks, i.e. trailing text segments, ${}, etc.
if not handler or handler[0] != chunk.kind:
if handler:
try:
result = next(handler[1])
except StopIteration:
result = None
if result: yield result
handler = getattr(self, 'process_' + chunk.kind, self.process_generic)(chunk.kind, context)
handler = (chunk.kind, handler)
try:
next(handler[1]) # We fast-forward to the first yield.
except StopIteration:
return
result = handler[1].send(chunk) # Send the handler the next contiguous chunk.
if result: yield result
if __debug__: # In development mode we skip the contiguous chunk compaction optimization.
handler = (None, handler[1])
# Clean up the final iteration.
if handler:
try:
result = next(handler[1])
except StopIteration:
return
if result: yield result | python | def process(self, context, lines):
"""Chop up individual lines into static and dynamic parts.
Applies light optimizations, such as empty chunk removal, and calls out to other methods to process different
chunk types.
The processor protocol here requires the method to accept values by yielding resulting lines while accepting
sent chunks. Deferral of multiple chunks is possible by yielding None. The processor will be sent None to
be given a chance to yield a final line and perform any clean-up.
"""
handler = None
for line in lines:
for chunk in chunk_(line):
if 'strip' in context.flag:
chunk.line = chunk.stripped
if not chunk.line: continue # Eliminate empty chunks, i.e. trailing text segments, ${}, etc.
if not handler or handler[0] != chunk.kind:
if handler:
try:
result = next(handler[1])
except StopIteration:
result = None
if result: yield result
handler = getattr(self, 'process_' + chunk.kind, self.process_generic)(chunk.kind, context)
handler = (chunk.kind, handler)
try:
next(handler[1]) # We fast-forward to the first yield.
except StopIteration:
return
result = handler[1].send(chunk) # Send the handler the next contiguous chunk.
if result: yield result
if __debug__: # In development mode we skip the contiguous chunk compaction optimization.
handler = (None, handler[1])
# Clean up the final iteration.
if handler:
try:
result = next(handler[1])
except StopIteration:
return
if result: yield result | [
"def",
"process",
"(",
"self",
",",
"context",
",",
"lines",
")",
":",
"handler",
"=",
"None",
"for",
"line",
"in",
"lines",
":",
"for",
"chunk",
"in",
"chunk_",
"(",
"line",
")",
":",
"if",
"'strip'",
"in",
"context",
".",
"flag",
":",
"chunk",
".... | Chop up individual lines into static and dynamic parts.
Applies light optimizations, such as empty chunk removal, and calls out to other methods to process different
chunk types.
The processor protocol here requires the method to accept values by yielding resulting lines while accepting
sent chunks. Deferral of multiple chunks is possible by yielding None. The processor will be sent None to
be given a chance to yield a final line and perform any clean-up. | [
"Chop",
"up",
"individual",
"lines",
"into",
"static",
"and",
"dynamic",
"parts",
".",
"Applies",
"light",
"optimizations",
"such",
"as",
"empty",
"chunk",
"removal",
"and",
"calls",
"out",
"to",
"other",
"methods",
"to",
"process",
"different",
"chunk",
"type... | 413bdac7242020ce8379d272720c649a9196daa2 | https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/inline/text.py#L112-L162 | train | 43,686 |
marrow/cinje | cinje/inline/text.py | Text.process_text | def process_text(self, kind, context):
"""Combine multiple lines of bare text and emit as a Python string literal."""
result = None
while True:
chunk = yield None
if chunk is None:
if result:
yield result.clone(line=repr(result.line))
return
if not result:
result = chunk
continue
result.line += chunk.line | python | def process_text(self, kind, context):
"""Combine multiple lines of bare text and emit as a Python string literal."""
result = None
while True:
chunk = yield None
if chunk is None:
if result:
yield result.clone(line=repr(result.line))
return
if not result:
result = chunk
continue
result.line += chunk.line | [
"def",
"process_text",
"(",
"self",
",",
"kind",
",",
"context",
")",
":",
"result",
"=",
"None",
"while",
"True",
":",
"chunk",
"=",
"yield",
"None",
"if",
"chunk",
"is",
"None",
":",
"if",
"result",
":",
"yield",
"result",
".",
"clone",
"(",
"line"... | Combine multiple lines of bare text and emit as a Python string literal. | [
"Combine",
"multiple",
"lines",
"of",
"bare",
"text",
"and",
"emit",
"as",
"a",
"Python",
"string",
"literal",
"."
] | 413bdac7242020ce8379d272720c649a9196daa2 | https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/inline/text.py#L164-L182 | train | 43,687 |
marrow/cinje | cinje/inline/text.py | Text.process_generic | def process_generic(self, kind, context):
"""Transform otherwise unhandled kinds of chunks by calling an underscore prefixed function by that name."""
result = None
while True:
chunk = yield result
if chunk is None:
return
result = chunk.clone(line='_' + kind + '(' + chunk.line + ')') | python | def process_generic(self, kind, context):
"""Transform otherwise unhandled kinds of chunks by calling an underscore prefixed function by that name."""
result = None
while True:
chunk = yield result
if chunk is None:
return
result = chunk.clone(line='_' + kind + '(' + chunk.line + ')') | [
"def",
"process_generic",
"(",
"self",
",",
"kind",
",",
"context",
")",
":",
"result",
"=",
"None",
"while",
"True",
":",
"chunk",
"=",
"yield",
"result",
"if",
"chunk",
"is",
"None",
":",
"return",
"result",
"=",
"chunk",
".",
"clone",
"(",
"line",
... | Transform otherwise unhandled kinds of chunks by calling an underscore prefixed function by that name. | [
"Transform",
"otherwise",
"unhandled",
"kinds",
"of",
"chunks",
"by",
"calling",
"an",
"underscore",
"prefixed",
"function",
"by",
"that",
"name",
"."
] | 413bdac7242020ce8379d272720c649a9196daa2 | https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/inline/text.py#L185-L196 | train | 43,688 |
marrow/cinje | cinje/inline/text.py | Text.process_format | def process_format(self, kind, context):
"""Handle transforming format string + arguments into Python code."""
result = None
while True:
chunk = yield result
if chunk is None:
return
# We need to split the expression defining the format string from the values to pass when formatting.
# We want to allow any Python expression, so we'll need to piggyback on Python's own parser in order
# to exploit the currently available syntax. Apologies, this is probably the scariest thing in here.
split = -1
line = chunk.line
try:
ast.parse(line)
except SyntaxError as e: # We expect this, and catch it. It'll have exploded after the first expr.
split = line.rfind(' ', 0, e.offset)
result = chunk.clone(line='_bless(' + line[:split].rstrip() + ').format(' + line[split:].lstrip() + ')') | python | def process_format(self, kind, context):
"""Handle transforming format string + arguments into Python code."""
result = None
while True:
chunk = yield result
if chunk is None:
return
# We need to split the expression defining the format string from the values to pass when formatting.
# We want to allow any Python expression, so we'll need to piggyback on Python's own parser in order
# to exploit the currently available syntax. Apologies, this is probably the scariest thing in here.
split = -1
line = chunk.line
try:
ast.parse(line)
except SyntaxError as e: # We expect this, and catch it. It'll have exploded after the first expr.
split = line.rfind(' ', 0, e.offset)
result = chunk.clone(line='_bless(' + line[:split].rstrip() + ').format(' + line[split:].lstrip() + ')') | [
"def",
"process_format",
"(",
"self",
",",
"kind",
",",
"context",
")",
":",
"result",
"=",
"None",
"while",
"True",
":",
"chunk",
"=",
"yield",
"result",
"if",
"chunk",
"is",
"None",
":",
"return",
"# We need to split the expression defining the format string fro... | Handle transforming format string + arguments into Python code. | [
"Handle",
"transforming",
"format",
"string",
"+",
"arguments",
"into",
"Python",
"code",
"."
] | 413bdac7242020ce8379d272720c649a9196daa2 | https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/inline/text.py#L198-L220 | train | 43,689 |
morpframework/morpfw | morpfw/app.py | Request.copy | def copy(self, *args, **kwargs):
"""
Copy the request and environment object.
This only does a shallow copy, except of wsgi.input
"""
self.make_body_seekable()
env = self.environ.copy()
new_req = self.__class__(env, *args, **kwargs)
new_req.copy_body()
new_req.identity = self.identity
return new_req | python | def copy(self, *args, **kwargs):
"""
Copy the request and environment object.
This only does a shallow copy, except of wsgi.input
"""
self.make_body_seekable()
env = self.environ.copy()
new_req = self.__class__(env, *args, **kwargs)
new_req.copy_body()
new_req.identity = self.identity
return new_req | [
"def",
"copy",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"make_body_seekable",
"(",
")",
"env",
"=",
"self",
".",
"environ",
".",
"copy",
"(",
")",
"new_req",
"=",
"self",
".",
"__class__",
"(",
"env",
",",
"*... | Copy the request and environment object.
This only does a shallow copy, except of wsgi.input | [
"Copy",
"the",
"request",
"and",
"environment",
"object",
"."
] | 803fbf29714e6f29456482f1cfbdbd4922b020b0 | https://github.com/morpframework/morpfw/blob/803fbf29714e6f29456482f1cfbdbd4922b020b0/morpfw/app.py#L48-L59 | train | 43,690 |
azavea/python-omgeo | omgeo/geocoder.py | Geocoder.add_source | def add_source(self, source):
"""
Add a geocoding service to this instance.
"""
geocode_service = self._get_service_by_name(source[0])
self._sources.append(geocode_service(**source[1])) | python | def add_source(self, source):
"""
Add a geocoding service to this instance.
"""
geocode_service = self._get_service_by_name(source[0])
self._sources.append(geocode_service(**source[1])) | [
"def",
"add_source",
"(",
"self",
",",
"source",
")",
":",
"geocode_service",
"=",
"self",
".",
"_get_service_by_name",
"(",
"source",
"[",
"0",
"]",
")",
"self",
".",
"_sources",
".",
"append",
"(",
"geocode_service",
"(",
"*",
"*",
"source",
"[",
"1",
... | Add a geocoding service to this instance. | [
"Add",
"a",
"geocoding",
"service",
"to",
"this",
"instance",
"."
] | 40f4e006f087dbc795a5d954ffa2c0eab433f8c9 | https://github.com/azavea/python-omgeo/blob/40f4e006f087dbc795a5d954ffa2c0eab433f8c9/omgeo/geocoder.py#L37-L42 | train | 43,691 |
azavea/python-omgeo | omgeo/geocoder.py | Geocoder.remove_source | def remove_source(self, source):
"""
Remove a geocoding service from this instance.
"""
geocode_service = self._get_service_by_name(source[0])
self._sources.remove(geocode_service(**source[1])) | python | def remove_source(self, source):
"""
Remove a geocoding service from this instance.
"""
geocode_service = self._get_service_by_name(source[0])
self._sources.remove(geocode_service(**source[1])) | [
"def",
"remove_source",
"(",
"self",
",",
"source",
")",
":",
"geocode_service",
"=",
"self",
".",
"_get_service_by_name",
"(",
"source",
"[",
"0",
"]",
")",
"self",
".",
"_sources",
".",
"remove",
"(",
"geocode_service",
"(",
"*",
"*",
"source",
"[",
"1... | Remove a geocoding service from this instance. | [
"Remove",
"a",
"geocoding",
"service",
"from",
"this",
"instance",
"."
] | 40f4e006f087dbc795a5d954ffa2c0eab433f8c9 | https://github.com/azavea/python-omgeo/blob/40f4e006f087dbc795a5d954ffa2c0eab433f8c9/omgeo/geocoder.py#L44-L49 | train | 43,692 |
azavea/python-omgeo | omgeo/geocoder.py | Geocoder.set_sources | def set_sources(self, sources):
"""
Creates GeocodeServiceConfigs from each str source
"""
if len(sources) == 0:
raise Exception('Must declare at least one source for a geocoder')
self._sources = []
for source in sources: # iterate through a list of sources
self.add_source(source) | python | def set_sources(self, sources):
"""
Creates GeocodeServiceConfigs from each str source
"""
if len(sources) == 0:
raise Exception('Must declare at least one source for a geocoder')
self._sources = []
for source in sources: # iterate through a list of sources
self.add_source(source) | [
"def",
"set_sources",
"(",
"self",
",",
"sources",
")",
":",
"if",
"len",
"(",
"sources",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
"'Must declare at least one source for a geocoder'",
")",
"self",
".",
"_sources",
"=",
"[",
"]",
"for",
"source",
"in",... | Creates GeocodeServiceConfigs from each str source | [
"Creates",
"GeocodeServiceConfigs",
"from",
"each",
"str",
"source"
] | 40f4e006f087dbc795a5d954ffa2c0eab433f8c9 | https://github.com/azavea/python-omgeo/blob/40f4e006f087dbc795a5d954ffa2c0eab433f8c9/omgeo/geocoder.py#L51-L59 | train | 43,693 |
venmo/btnamespace | btnamespace/patch.py | PatchedMethod._apply_param_actions | def _apply_param_actions(self, params, schema_params):
"""Traverse a schema and perform the updates it describes to params."""
for key, val in schema_params.items():
if key not in params:
continue
if isinstance(val, dict):
self._apply_param_actions(params[key], schema_params[key])
elif isinstance(val, ResourceId):
resource_id = val
# Callers can provide ints as ids.
# We normalize them to strings so that actions don't get confused.
params[key] = str(params[key])
resource_id.action(params, schema_params, key,
resource_id, self.state, self.options)
else:
logger.error("Invalid value in schema params: %r. schema_params: %r and params: %r",
val, schema_params, params) | python | def _apply_param_actions(self, params, schema_params):
"""Traverse a schema and perform the updates it describes to params."""
for key, val in schema_params.items():
if key not in params:
continue
if isinstance(val, dict):
self._apply_param_actions(params[key], schema_params[key])
elif isinstance(val, ResourceId):
resource_id = val
# Callers can provide ints as ids.
# We normalize them to strings so that actions don't get confused.
params[key] = str(params[key])
resource_id.action(params, schema_params, key,
resource_id, self.state, self.options)
else:
logger.error("Invalid value in schema params: %r. schema_params: %r and params: %r",
val, schema_params, params) | [
"def",
"_apply_param_actions",
"(",
"self",
",",
"params",
",",
"schema_params",
")",
":",
"for",
"key",
",",
"val",
"in",
"schema_params",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"params",
":",
"continue",
"if",
"isinstance",
"(",
"val",
... | Traverse a schema and perform the updates it describes to params. | [
"Traverse",
"a",
"schema",
"and",
"perform",
"the",
"updates",
"it",
"describes",
"to",
"params",
"."
] | 55a42959bbfbb2409e8b5cb6bfc4cb75f37cbcde | https://github.com/venmo/btnamespace/blob/55a42959bbfbb2409e8b5cb6bfc4cb75f37cbcde/btnamespace/patch.py#L52-L72 | train | 43,694 |
raonyguimaraes/pynnotator | pynnotator/annotator.py | Annotator.snpeff | def snpeff(self):
"""
Annotation with snpEff
"""
# calculate time thread took to finish
# logging.info('Starting snpEff')
tstart = datetime.now()
se = snpeff.Snpeff(self.vcf_file)
std = se.run()
tend = datetime.now()
execution_time = tend - tstart | python | def snpeff(self):
"""
Annotation with snpEff
"""
# calculate time thread took to finish
# logging.info('Starting snpEff')
tstart = datetime.now()
se = snpeff.Snpeff(self.vcf_file)
std = se.run()
tend = datetime.now()
execution_time = tend - tstart | [
"def",
"snpeff",
"(",
"self",
")",
":",
"# calculate time thread took to finish",
"# logging.info('Starting snpEff')",
"tstart",
"=",
"datetime",
".",
"now",
"(",
")",
"se",
"=",
"snpeff",
".",
"Snpeff",
"(",
"self",
".",
"vcf_file",
")",
"std",
"=",
"se",
"."... | Annotation with snpEff | [
"Annotation",
"with",
"snpEff"
] | 84ba8c3cdefde4c1894b853ba8370d3b4ff1d62a | https://github.com/raonyguimaraes/pynnotator/blob/84ba8c3cdefde4c1894b853ba8370d3b4ff1d62a/pynnotator/annotator.py#L207-L219 | train | 43,695 |
morpframework/morpfw | morpfw/cli.py | cli | def cli(ctx, settings, app):
"""Manage Morp application services"""
if app is None and settings is None:
print('Either --app or --settings must be supplied')
ctx.ensure_object(dict)
ctx.obj['app'] = app
ctx.obj['settings'] = settings | python | def cli(ctx, settings, app):
"""Manage Morp application services"""
if app is None and settings is None:
print('Either --app or --settings must be supplied')
ctx.ensure_object(dict)
ctx.obj['app'] = app
ctx.obj['settings'] = settings | [
"def",
"cli",
"(",
"ctx",
",",
"settings",
",",
"app",
")",
":",
"if",
"app",
"is",
"None",
"and",
"settings",
"is",
"None",
":",
"print",
"(",
"'Either --app or --settings must be supplied'",
")",
"ctx",
".",
"ensure_object",
"(",
"dict",
")",
"ctx",
".",... | Manage Morp application services | [
"Manage",
"Morp",
"application",
"services"
] | 803fbf29714e6f29456482f1cfbdbd4922b020b0 | https://github.com/morpframework/morpfw/blob/803fbf29714e6f29456482f1cfbdbd4922b020b0/morpfw/cli.py#L71-L77 | train | 43,696 |
azavea/python-omgeo | omgeo/services/base.py | GeocodeService._settings_checker | def _settings_checker(self, required_settings=None, accept_none=True):
"""
Take a list of required _settings dictionary keys
and make sure they are set. This can be added to a custom
constructor in a subclass and tested to see if it returns ``True``.
:arg list required_settings: A list of required keys to look for.
:arg bool accept_none: Boolean set to True if None is an acceptable
setting. Set to False if None is not an
acceptable setting.
:returns: * bool ``True`` if all required settings exist, OR
* str <key name> for the first key missing from _settings.
"""
if required_settings is not None:
for keyname in required_settings:
if keyname not in self._settings:
return keyname
if accept_none is False and self._settings[keyname] is None:
return keyname
return True | python | def _settings_checker(self, required_settings=None, accept_none=True):
"""
Take a list of required _settings dictionary keys
and make sure they are set. This can be added to a custom
constructor in a subclass and tested to see if it returns ``True``.
:arg list required_settings: A list of required keys to look for.
:arg bool accept_none: Boolean set to True if None is an acceptable
setting. Set to False if None is not an
acceptable setting.
:returns: * bool ``True`` if all required settings exist, OR
* str <key name> for the first key missing from _settings.
"""
if required_settings is not None:
for keyname in required_settings:
if keyname not in self._settings:
return keyname
if accept_none is False and self._settings[keyname] is None:
return keyname
return True | [
"def",
"_settings_checker",
"(",
"self",
",",
"required_settings",
"=",
"None",
",",
"accept_none",
"=",
"True",
")",
":",
"if",
"required_settings",
"is",
"not",
"None",
":",
"for",
"keyname",
"in",
"required_settings",
":",
"if",
"keyname",
"not",
"in",
"s... | Take a list of required _settings dictionary keys
and make sure they are set. This can be added to a custom
constructor in a subclass and tested to see if it returns ``True``.
:arg list required_settings: A list of required keys to look for.
:arg bool accept_none: Boolean set to True if None is an acceptable
setting. Set to False if None is not an
acceptable setting.
:returns: * bool ``True`` if all required settings exist, OR
* str <key name> for the first key missing from _settings. | [
"Take",
"a",
"list",
"of",
"required",
"_settings",
"dictionary",
"keys",
"and",
"make",
"sure",
"they",
"are",
"set",
".",
"This",
"can",
"be",
"added",
"to",
"a",
"custom",
"constructor",
"in",
"a",
"subclass",
"and",
"tested",
"to",
"see",
"if",
"it",... | 40f4e006f087dbc795a5d954ffa2c0eab433f8c9 | https://github.com/azavea/python-omgeo/blob/40f4e006f087dbc795a5d954ffa2c0eab433f8c9/omgeo/services/base.py#L109-L129 | train | 43,697 |
azavea/python-omgeo | omgeo/services/base.py | GeocodeService._get_response | def _get_response(self, endpoint, query, is_post=False):
"""Returns response or False in event of failure"""
timeout_secs = self._settings.get('timeout', 10)
headers = self._settings.get('request_headers', {})
try:
if is_post:
response = requests.post(
endpoint, data=query, headers=headers, timeout=timeout_secs)
else:
response = requests.get(
endpoint, params=query, headers=headers, timeout=timeout_secs)
except requests.exceptions.Timeout as e:
raise Exception(
'API request timed out after %s seconds.' % timeout_secs)
except Exception as e:
raise e
if response.status_code != 200:
raise Exception('Received status code %s from %s. Content is:\n%s'
% (response.status_code,
self.get_service_name(),
response.text))
return response | python | def _get_response(self, endpoint, query, is_post=False):
"""Returns response or False in event of failure"""
timeout_secs = self._settings.get('timeout', 10)
headers = self._settings.get('request_headers', {})
try:
if is_post:
response = requests.post(
endpoint, data=query, headers=headers, timeout=timeout_secs)
else:
response = requests.get(
endpoint, params=query, headers=headers, timeout=timeout_secs)
except requests.exceptions.Timeout as e:
raise Exception(
'API request timed out after %s seconds.' % timeout_secs)
except Exception as e:
raise e
if response.status_code != 200:
raise Exception('Received status code %s from %s. Content is:\n%s'
% (response.status_code,
self.get_service_name(),
response.text))
return response | [
"def",
"_get_response",
"(",
"self",
",",
"endpoint",
",",
"query",
",",
"is_post",
"=",
"False",
")",
":",
"timeout_secs",
"=",
"self",
".",
"_settings",
".",
"get",
"(",
"'timeout'",
",",
"10",
")",
"headers",
"=",
"self",
".",
"_settings",
".",
"get... | Returns response or False in event of failure | [
"Returns",
"response",
"or",
"False",
"in",
"event",
"of",
"failure"
] | 40f4e006f087dbc795a5d954ffa2c0eab433f8c9 | https://github.com/azavea/python-omgeo/blob/40f4e006f087dbc795a5d954ffa2c0eab433f8c9/omgeo/services/base.py#L131-L153 | train | 43,698 |
azavea/python-omgeo | omgeo/services/base.py | GeocodeService._get_json_obj | def _get_json_obj(self, endpoint, query, is_post=False):
"""
Return False if connection could not be made.
Otherwise, return a response object from JSON.
"""
response = self._get_response(endpoint, query, is_post=is_post)
content = response.text
try:
return loads(content)
except ValueError:
raise Exception('Could not decode content to JSON:\n%s'
% self.__class__.__name__, content) | python | def _get_json_obj(self, endpoint, query, is_post=False):
"""
Return False if connection could not be made.
Otherwise, return a response object from JSON.
"""
response = self._get_response(endpoint, query, is_post=is_post)
content = response.text
try:
return loads(content)
except ValueError:
raise Exception('Could not decode content to JSON:\n%s'
% self.__class__.__name__, content) | [
"def",
"_get_json_obj",
"(",
"self",
",",
"endpoint",
",",
"query",
",",
"is_post",
"=",
"False",
")",
":",
"response",
"=",
"self",
".",
"_get_response",
"(",
"endpoint",
",",
"query",
",",
"is_post",
"=",
"is_post",
")",
"content",
"=",
"response",
"."... | Return False if connection could not be made.
Otherwise, return a response object from JSON. | [
"Return",
"False",
"if",
"connection",
"could",
"not",
"be",
"made",
".",
"Otherwise",
"return",
"a",
"response",
"object",
"from",
"JSON",
"."
] | 40f4e006f087dbc795a5d954ffa2c0eab433f8c9 | https://github.com/azavea/python-omgeo/blob/40f4e006f087dbc795a5d954ffa2c0eab433f8c9/omgeo/services/base.py#L155-L166 | train | 43,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.