changed some filters/maps to list compr

master
idziubenko 3 years ago
parent 283b16e106
commit b315b446dc

@ -203,10 +203,11 @@ class iniParser(_error):
иначе - True
"""
if textIni.strip():
if list(filter(lambda x: x.strip(),
map(lambda x: x[0].split(";")[0],
map(lambda x: x.split("#"),
textIni.splitlines())))):
# if list(filter(lambda x: x.strip(),
# map(lambda x: x[0].split(";")[0],
# map(lambda x: x.split("#"),
# textIni.splitlines())))):
if [x for x in [y[0].split(";")[0] for y in [z.split("#") for z in textIni.splitlines()]] if x.strip()]:
return False
else:
return True

@ -171,9 +171,11 @@ class RegexpLocalization(object):
except re.error:
return None
self._catalog = list(filter(lambda x: x[0],
((create_key(k), v) for k, v in
sorted(d.items(), reverse=True) if k)))
# self._catalog = list(filter(lambda x: x[0],
# ((create_key(k), v) for k, v in
# sorted(d.items(), reverse=True) if k)))
self._catalog = [x for x in [(create_key(k), v) for k, v in
sorted(d.items(), reverse=True) if k] if x[0]]
def translate(self, s):
for k, v in self._catalog:

@ -21,7 +21,7 @@ import ldap
from .utils.common import _error
from collections import defaultdict
from ldif import LDIFParser, LDIFWriter
import cStringIO
import io
from calculate.lib.cl_lang import setLocalTranslate
from functools import reduce
@ -411,7 +411,7 @@ class LDIFAdd(LDIFParser):
def __init__(self, ldif_data, ldap_connect):
self.ldap_connect = ldap_connect
LDIFParser.__init__(self, cStringIO.StringIO(ldif_data))
LDIFParser.__init__(self, io.StringIO(ldif_data))
def handle(self, dn, entry, controls=None):
# (self, dn, entry, *args):

@ -334,9 +334,7 @@ class _shareTemplate(object):
groupName = grp.getgrgid(gid).gr_name
except Exception:
raise TemplatesError(_("Group ID %s not found") % str(gid))
groupsNames = list(map(lambda x: x.gr_name,
filter(lambda x: userName in x.gr_mem,
grp.getgrall())))
groupsNames = [x.gr_name for x in grp.getgrall() if userName in x.gr_mem]
groupsNames = [groupName] + groupsNames
return uid, gid, homeDir, groupsNames
return uid, gid, homeDir
@ -404,8 +402,7 @@ class _terms(_error, _shareTermsFunction, _shareTemplate):
# 2.3_p45 ('2.3','_','p43')
# 2.3_rc4_p45 ('2.3_rc4','_','p43')
strWorkVersion, spl, suffix = strWorkVersion.rpartition("_")
suffSplList = list(filter(lambda x: suffix.startswith(x),
self._suffixDict.keys()))
suffSplList = [x for x in self._suffixDict.keys() if suffix.startswith(x)]
if suffSplList:
suffSpl = suffSplList[0]
lenSuffSpl = len(suffSpl)
@ -496,8 +493,8 @@ class _terms(_error, _shareTermsFunction, _shareTemplate):
elemB.append(lB)
# dereferencing suffix in suffixes list
ssA = list(map(lambda x: (self._suffixDict.get(x[0], 0), x[1]), ssA))
ssB = list(map(lambda x: (self._suffixDict.get(x[0], 0), x[1]), ssB))
ssA = [(self._suffixDict.get(x[0], 0), x[1]) for x in ssA]
ssB = [(self._suffixDict.get(x[0], 0), x[1]) for x in ssB]
for suffix, sufVer in reversed(ssA):
if ssB:
sB, svB = ssB.pop()
@ -806,7 +803,7 @@ class _terms(_error, _shareTermsFunction, _shareTemplate):
mass.append(v)
v = ""
flagQ = False
elif list(filter(lambda x: x in i, listTerm)):
elif [x for x in listTerm if x in i]:
flagQ = True
v = i
else:
@ -816,8 +813,7 @@ class _terms(_error, _shareTermsFunction, _shareTemplate):
else:
mass.append(i)
foundPar = list(set(mass) - set(listPar))
return not flagQ, list(filter(lambda x: not x in foundPar,
mass)), foundPar
return not flagQ, [x for x in mass if not x in foundPar], foundPar
listPar = re.split(r"\s+", linePar)
flagFoundQ = "'" in linePar
@ -2984,7 +2980,7 @@ class templateFunction(_error, _warning, _shareTemplate, _shareTermsFunction,
if drivers == "on":
yield id
data = list(filter(None, self.objVar.Get('builder.cl_builder_image_data')))
data = [x for x in self.objVar.Get('builder.cl_builder_image_data') if x]
if funArgv == 'submenu':
res = "\n".join(generateSubmenu(data))
elif funArgv == 'xorg':
@ -3054,10 +3050,12 @@ class templateFunction(_error, _warning, _shareTemplate, _shareTermsFunction,
_("the first parameter must be the resolution"))
re_resol = re.compile(r".*?(\d+)x(\d+).*")
res = list(map(lambda x: (int(x.group(1)), int(x.group(2)), x.group()),
filter(None,
map(re_resol.search,
listDirectory(wpath)))))
# res = list(map(lambda x: (int(x.group(1)), int(x.group(2)), x.group()),
# filter(None,
# map(re_resol.search,
# listDirectory(wpath)))))
res = [(int(x.group(1)), int(x.group(2)), x.group()) for x in
[re_resol.search(z) for z in listDirectory(wpath)] if x]
width = int(resol.group(1))
height = int(resol.group(2))
gep = sqrt(height ** 2 + width ** 2)
@ -3293,7 +3291,7 @@ class templateFunction(_error, _warning, _shareTemplate, _shareTermsFunction,
vals = textLine.split(".")
if len(vals) != 2:
raise self.raiseErrTemplate()
if list(filter(lambda x: not x.strip(), vals)):
if [x for x in vals if not x.strip()]:
raise self.raiseErrTemplate()
service, option = vals
if not service or not option:
@ -3797,10 +3795,8 @@ class Template(_file, _terms, _warning, xmlShare, _shareTemplate):
protectPaths = []
allContents = {}
if "CONFIG_PROTECT" in os.environ:
protectPaths = ["/etc"] + list(filter(lambda x: x.strip(),
os.environ["CONFIG_PROTECT"].split(
" ")))
protectPaths = list(map(lambda x: os.path.normpath(x), protectPaths))
protectPaths = ["/etc"] + [x for x in os.environ["CONFIG_PROTECT"].split(" ") if x.strip()]
protectPaths = [os.path.normpath(x) for x in protectPaths]
@classmethod
def removeComment(cls, text):
@ -4315,8 +4311,7 @@ gettext -d cl_template "$*"
skipTemplates = []
debug = False
for dirsTemplate in dirsTemplates:
filesAndDirs = list(map(lambda x: os.path.join(dirsTemplate, x),
listDirectory(dirsTemplate)))
filesAndDirs = [os.path.join(dirsTemplate, x) for x in listDirectory(dirsTemplate)]
for dirFile in filesAndDirs:
if os.path.isdir(dirFile):
flagDir = True
@ -4463,8 +4458,7 @@ gettext -d cl_template "$*"
scanObj.processingFile = lambda x, y: createDictTemplates(x, y,
self.dictTemplates)
# Считаем количество шаблонов
dirsTemplatesExists = list(filter(lambda x: os.path.exists(x), dirsTemplates))
dirsTemplatesExists = [x for x in dirsTemplates if os.path.exists(x)]
if not dirsTemplatesExists and not self.cltObj:
return self.createdDirs, self.filesApply
@ -4544,10 +4538,12 @@ gettext -d cl_template "$*"
filename = PkgContents.reCfg.sub("/", filename)
if not filename in self.cltObj.filterApplyTemplates:
self.cltObj.filterApplyTemplates[filename] = []
pkgs = list(filter(
lambda x: x not in
self.cltObj.filterApplyTemplates[filename],
list(map(lambda x: x[0], pkgs))))
# pkgs = list(filter(
# lambda x: x not in
# self.cltObj.filterApplyTemplates[filename],
# list(map(lambda x: x[0], pkgs))))
pkgs = [x for x in [z[0] for z in pkgs]
if x not in self.cltObj.filterApplyTemplates[filename]]
self.cltObj.filterApplyTemplates[filename].extend(pkgs)
old_mod = self.objVar.defaultModule
try:
@ -4624,9 +4620,7 @@ gettext -d cl_template "$*"
self.updateProtectedFiles()
if self.objVar.Get('cl_verbose_set') == 'on' and \
self.filesApply:
self.verboseOutput(
list(filter(lambda x: not x.endswith('/ini.env'),
self.filesApply)))
self.verboseOutput([x for x in self.filesApply if not x.endswith('/ini.env')])
self.objVar.Set('cl_merge_pkg_pass', [], force=True)
self.objVar.Set('cl_merge_pkg_new', [], force=True)
self.objVar.Set('cl_merge_pkg', [], force=True)
@ -4736,9 +4730,8 @@ gettext -d cl_template "$*"
pkgContents.writeContents()
except IOError:
self.printWARNING(_("Failed to modify %s contents") % pkg)
self.filesApply = list(map(lambda x: autoUpdateDict.get(x, x),
self.filesApply))
if list(filter(lambda x: "._cfg" in x, self.filesApply)):
self.filesApply = [autoUpdateDict.get(x, x) for x in self.filesApply]
if [x for x in self.filesApply if "._cfg" in x]:
if self.objVar.Get('cl_ebuild_phase') != '':
self.printWARNING(_("Some config files need updating. "
"Perform run dispatch-conf."))
@ -5115,8 +5108,7 @@ gettext -d cl_template "$*"
headerLine = self.getHeaderText(textTemplate)
if headerLine:
envparam = "%s=" % HParams.Environ
moduleParam = list(filter(lambda x: x.startswith(envparam),
headerLine.split()))
moduleParam = [x for x in headerLine.split() if x.startswith(envparam)]
if moduleParam:
self.objVar.defaultModule = moduleParam[0].partition('=')[2]
try:
@ -5401,12 +5393,14 @@ gettext -d cl_template "$*"
"""
# if file in PROTECT_MASK or not in PROTECT
chrootPath = self.objVar.Get('cl_chroot_path')
if not list(filter(pathFile.startswith,
map(lambda x: pathJoin(chrootPath, x),
self.objVar.Get('cl_config_protect')))) or \
list(filter(pathFile.startswith,
map(lambda x: pathJoin(chrootPath, x),
self.objVar.Get('cl_config_protect_mask')))):
# if not list(filter(pathFile.startswith,
# map(lambda x: pathJoin(chrootPath, x),
# self.objVar.Get('cl_config_protect')))) or \
# list(filter(pathFile.startswith,
# map(lambda x: pathJoin(chrootPath, x),
# self.objVar.Get('cl_config_protect_mask')))):
if not [x for x in [pathJoin(chrootPath, y) for y in self.objVar.Get('cl_config_protect')] if pathFile.startswith(x)] or \
[x for x in [pathJoin(chrootPath, y) for y in self.objVar.Get('cl_config_protect_mask')] if pathFile.startswith(x)]:
return pathFile
# if file was already modified by templates
if pathFile in self.changedFiles.data.keys():
@ -6042,8 +6036,7 @@ gettext -d cl_template "$*"
headerLine = self.getHeaderText(self.textTemplate)
if headerLine:
envparam = "%s=" % HParams.Environ
moduleParam = list(filter(lambda x: x.startswith(envparam),
headerLine.split()))
moduleParam = [x for x in headerLine.split() if x.startswith(envparam)]
if moduleParam:
self.objVar.defaultModule = moduleParam[0].partition('=')[2]
try:

@ -716,10 +716,12 @@ class TableVariable(Variable):
self.source)):
raise VariableError(
_("Source variable %s does not contain a list") % varname)
return list(map(list,
zip_longest(
*map(lambda x: self.Get(x, humanreadable=hr),
self.source), fillvalue=''))) or [[]]
# return list(map(list,
# zip_longest(
# *map(lambda x: self.Get(x, humanreadable=hr),
# self.source), fillvalue=''))) or [[]]
return [list(x) for x in zip_longest(*[self.Get(x, humanreadable=hr)
for x in self.source], fillvalue='')] or [[]]
def getHumanReadableAuto(self):
"""

@ -278,7 +278,7 @@ class plasma(samba):
slpNamesBlock = reH.split(h)
# Отступ слева для заголовка
indentionLeft = slpNamesBlock[0]
namesBlock = list(filter(lambda x: x.strip(), slpNamesBlock))
namesBlock = [x for x in slpNamesBlock if x.strip()]
# namesBlock = map(lambda x: self.removeSymbolTerm(x), namesBlock)
findArea = findPathArea(copy.copy(namesBlock), areas)
findAreaPrev = None

@ -283,8 +283,7 @@ class xml_gconf(xml_xfce):
return s
data = self.doc.toxml().split("\n")
data = list(map(lambda x: expandStartTabs(x),
filter(lambda x: x.strip(), data)))
data = [expandStartTabs(x) for x in data if x.strip()]
dataOut = []
z = 0
lenData = len(data)

@ -158,7 +158,7 @@ class xml_xfce(TemplateFormat):
return False
if xmlOldNode.getparent():
strAttr = [attrName, attrType]
findAttr = list(filter(lambda x: x, strAttr))
findAttr = [x for x in strAttr if x]
findAttrStr = ''
if findAttr:
strAttr = u' and '.join(findAttr)

@ -326,7 +326,8 @@ class ColorTerminalOutput(SaveAttrOutput):
"""
Создать ESC строку
"""
attrs = list(map(str, ['%s[' % self.escSymb] + attrs + ['m']))
# attrs = list(map(str, ['%s[' % self.escSymb] + attrs + ['m']))
attrs = [str(x) for x in ['%s[' % self.escSymb] + attrs + ['m']]
return "%s%s%s" % (attrs[0], ";".join(attrs[1:-1]), attrs[-1])
def outputText(self, s):

@ -88,8 +88,8 @@ class _warning(object):
def genpassword(passlen=9, chars=string.ascii_letters + string.digits):
"""Return random charset specified lenght (passlen)"""
return ''.join(list(map(lambda x: choice(chars),
range(0, passlen))))
return ''.join(map(lambda x: choice(chars),
range(0, passlen)))
def getpathenv():
@ -126,10 +126,13 @@ def getTupleVersion(ver):
"rc": -1}
def toTuple(v):
return list(map(lambda x: suffix_value[x] if x in suffix_value else x,
map(lambda x: int(x) if x.isdigit() else x,
re.findall(r"r\d+$|\d+|[a-zA-Z+]+",
v.replace('-SNAPSHOT', '')))))
# return list(map(lambda x: suffix_value[x] if x in suffix_value else x,
# map(lambda x: int(x) if x.isdigit() else x,
# re.findall(r"r\d+$|\d+|[a-zA-Z+]+",
# v.replace('-SNAPSHOT', '')))))
return [suffix_value[x] if x in suffix_value else x for x
in [int(z) if z.isdigit() else z for z
in re.findall(r"r\d+$|\d+|[a-zA-Z+]+",v.replace('-SNAPSHOT', ''))]]
vers, revision = re.search(r"(^.*?)(-r\d+)?$", ver, re.S).groups()
vers = toTuple(vers)
@ -142,9 +145,7 @@ def getInstalledVideo(prefix="/"):
"""Get installed video drivers"""
usrlib = SystemPath(prefix).usrlib
x11Drivers = "%s/xorg/modules/drivers" % usrlib
return list(map(lambda x: x[:-7],
filter(lambda x: x.endswith('_drv.so'),
listDirectory(x11Drivers))))
return [x[:-7] for x in listDirectory(x11Drivers) if x.endswith('_drv.so')]
def getDistfilesVideo(prefix="/"):
@ -194,7 +195,6 @@ def getPasswdUsers(minId=1000, maxId=65000, prefix="/",
# lambda x: reNumb.match(x[2]) and minId <= int(x[2]) <= maxId,
# userData))
userData = [x for x in userData if reNumb.match(x[2]) and minId <= int(x[2]) <= maxId]
# sortUsers = list(map(lambda x: x[0], userData))
sortUsers = [x[0] for x in userData]
sortUsers.sort()
retList = ["root"] + sortUsers
@ -316,20 +316,23 @@ def getVideoFromXorgLog(prefix="/", available_drivers=()):
# Try analize Xorg.{DISPLAY}.log
display = os.environ.get('DISPLAY', ':0')
if display and available_drivers:
reDriver = re.compile('|'.join(list(map(lambda x: "%s_drv.so" % x,
available_drivers))))
reDriver = re.compile('|'.join(map(lambda x: "%s_drv.so" % x,
available_drivers)))
display_number = re.search(r':(\d+)(\..*)?', display)
reDriverName = re.compile(r'([^/]+)_drv.so')
if display_number:
xorg_log_file = path.join(prefix, 'var/log/Xorg.%s.log' %
display_number.group(1))
if path.exists(xorg_log_file):
matchStrs = list(map(
lambda x: x.group(1),
filter(lambda x: x, map(
reDriverName.search,
filter(lambda x: "drv" in x and reDriver.search(x),
readLinesFile(xorg_log_file))))))
# matchStrs = list(map(
# lambda x: x.group(1),
# filter(lambda x: x, map(
# reDriverName.search,
# filter(lambda x: "drv" in x and reDriver.search(x),
# readLinesFile(xorg_log_file))))))
matchStrs = [x.group(1) for x in [reDriverName.search(z)
for z in readLinesFile(xorg_log_file)
if "drv" in z and reDriver.search(z)] if x]
if matchStrs:
reUnload = re.compile(r'UnloadModule: "(%s)"' %r'|'.join(x
for x in matchStrs))
@ -369,10 +372,13 @@ def getVideoFromCmdLine():
def getVideoFromModules():
workedModules = list(map(lambda x: x[0],
filter(lambda x: x[1].isdigit() and int(x[1]) > 0,
map(lambda x: x.split()[:3:2],
readLinesFile('/proc/modules')))))
# workedModules = list(map(lambda x: x[0],
# filter(lambda x: x[1].isdigit() and int(x[1]) > 0,
# map(lambda x: x.split()[:3:2],
# readLinesFile('/proc/modules')))))
workedModules = [x[0] for x in [z.split()[:3:2] for z
in readLinesFile('/proc/modules')]
if x[1].isdigit() and int(x[1]) > 0]
mapModules = {'nouveau': 'nouveau',
'radeon': 'radeon',
'i915': 'intel',
@ -433,7 +439,7 @@ def getCompositeFromXorgconf(prefix="/"):
if line.startswith('Section') and '"Extensions"' in line:
flagStartExtensions = True
if lineComposite:
listOpt = list(filter(lambda x: x.strip(), lineComposite.split('"')))
listOpt = [x for x in lineComposite.split('"') if x.strip()]
if len(listOpt) == 3:
ret = listOpt[2].lower()
if ret in ("on", "true", "yes", "1"):
@ -473,10 +479,13 @@ def getUserGroups(userName, prefix="/"):
"""
Get user groups from /etc/groups
"""
return list(map(lambda x: x[0],
filter(lambda x: len(x) > 1 and userName in x[1].split(','),
map(lambda x: x.split(':')[0::3],
readLinesFile(path.join(prefix, 'etc/group'))))))
# return list(map(lambda x: x[0],
# filter(lambda x: len(x) > 1 and userName in x[1].split(','),
# map(lambda x: x.split(':')[0::3],
# readLinesFile(path.join(prefix, 'etc/group'))))))
return [x[0] for x in [z.split(':')[0::3] for z
in readLinesFile(path.join(prefix, 'etc/group'))]
if len(x) > 1 and userName in x[1].split(',')]
def getUserPrimaryGroup(userName, prefix="/"):

@ -253,8 +253,7 @@ def getCfgFiles(protected_dirs=('/etc',), prefix='/'):
Get protected cfg files
"""
reCfg = re.compile(r"/\._cfg\d{4}_", re.S)
findParams = ["find"] + list(map(lambda x: pathJoin(prefix, x),
protected_dirs)) + [
findParams = ["find"] + [pathJoin(prefix, x) for x in protected_dirs] + [
"-name", "._cfg????_*", "!", "-name", ".*~", "!", "-iname",
".*.bak", "-printf", r"%T@ %p\n"]
mapCfg = {}

@ -535,7 +535,7 @@ def humanreadableSize(size, compsize=0):
((1024 ** 3), "G", True),
((1024 ** 4), "T", True),
((1024 ** 5), "P", True))
suffix = list(filter(lambda x: abs(size-compsize) > x[0], suffix))
suffix = [x for x in suffix if abs(size-compsize) > x[0]]
if suffix:
suffix = suffix[-1]
printSize = int(size / (float(suffix[0]) / 10))

@ -86,9 +86,7 @@ from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_lib3', sys.modules[__name__])
reSearch = lambda pattern, listar: list(map(lambda x: x.groups(),
filter(None,
map(pattern.search, listar))))
reSearch = lambda pattern, listar: [x.groups() for x in map(pattern.search, listar) if x]
class FilesError(Exception):
@ -762,16 +760,12 @@ def listDirectory(directory, fullPath=False, onlyDir=False):
try:
if fullPath:
if onlyDir:
return list(filter(lambda x: path.isdir(x),
map(lambda x: path.join(directory, x),
os.listdir(directory))))
return [x for x in [path.join(directory, z) for z in os.listdir(directory)] if path.isdir(x)]
else:
return list(map(lambda x: path.join(directory, x),
os.listdir(directory)))
return [path.join(directory, x) for x in os.listdir(directory)]
else:
if onlyDir:
return list(filter(lambda x: path.isdir(path.join(directory, x)),
os.listdir(directory)))
return [x for x in os.listdir(directory) if path.isdir(path.join(directory, x))]
else:
return os.listdir(directory)
except OSError:
@ -945,9 +939,8 @@ def getCmdLineParam(paramName):
"""
cmdLine = '/proc/cmdline'
paramName = "%s=" % paramName
params = list(map(lambda x: x.partition('=')[2],
filter(lambda x: x.startswith(paramName),
readFile(cmdLine).split(' '))))
params = [x.partition('=')[2] for x
in readFile(cmdLine).split(' ') if x.startswith(paramName)]
if params:
return params[-1]
else:
@ -1121,10 +1114,8 @@ def getLoopFromPath(directory):
losetup = getProgPath('losetup')
p = process(losetup, '-a')
rePattern = re.compile(r'(^/dev/loop[^:]+)[^(]+\(([^)]+)\).*')
return list(map(lambda x: x[0],
filter(lambda x: x[1].startswith(directory),
reSearch(rePattern,
p.readlines()))))
return [x[0] for x in reSearch(rePattern, p.readlines())
if x[1].startswith(directory)]
def getMdRaidDevices():
@ -1764,15 +1755,9 @@ def getRunCommands(not_chroot=False, chroot=None, uid=None, withpid=False,
if not os.access('/proc', os.R_OK):
return []
if withpid:
return list(filter(lambda x: x[1],
map(lambda x:(x,getCmd(x)),
filter(lambda x: x.isdigit(),
listDirectory('/proc')))))
return [x for x in [(y, getCmd(y)) for y in listDirectory('/proc') if y.isdigit()] if x[1]]
else:
return list(filter(None,
map(getCmd,
filter(lambda x: x.isdigit(),
listDirectory('/proc')))))
return [x for x in [getCmd(y) for y in listDirectory('/proc') if y.isdigit()] if x]
class XAttrError(Exception):
pass

@ -103,10 +103,12 @@ class MountHelper(object):
def setlen(ar):
return ar[:6] + [""] * (6 - len(ar))
self.cache = \
list(map(lambda x: setlen(list(map(lambda y: y.strip(), x.split()))),
filter(lambda x: x.strip() and not x.lstrip().startswith("#"),
self._readdata().split('\n'))))
# self.cache = \
# list(map(lambda x: setlen(list(map(lambda y: y.strip(), x.split()))),
# filter(lambda x: x.strip() and not x.lstrip().startswith("#"),
# self._readdata().split('\n'))))
self.cache = [setlen([y.strip() for y in x.split()]) for x
in self._readdata().split('\n') if x.strip() and not x.lstrip().startswith("#")]
for data in self.cache:
convertDev = lambda x: (os.path.realpath(x)
if x.startswith('/') else x)
@ -127,7 +129,7 @@ class MountHelper(object):
filterfunc = lambda x: contains in x[where]
else:
filterfunc = lambda x: x[where] != noteq
res = list(map(lambda x: x[what], filter(filterfunc, self.cache)))
res = [x[what] for x in self.cache if filterfunc(x)]
if allentry:
return res
else:
@ -198,7 +200,7 @@ class DiskSpace(object):
data = p.read().strip()
lines = data.split('\n')
if len(lines) >= 2:
cols = list(filter(None, lines[1].split()))
cols = [x for x in lines[1].split() if x]
if len(cols) == 6:
return int(cols[3])
raise DiskSpaceError(_("Wrong df output:\n%s") % data)
@ -209,11 +211,14 @@ class DiskSpace(object):
def commonPath(*paths):
"""Return common path from list of paths"""
paths = map(lambda x: os.path.normpath(x).split('/'), paths)
res = list(map(lambda x: x[0],
filter(lambda x: filter(lambda y: x[0] == y, x[1:]), zip(*paths))))
# res = list(map(lambda x: x[0],
# filter(lambda x: filter(lambda y: x[0] == y, x[1:]), zip(*paths))))
res = [x[0] for x in zip(*paths) if [y for y in x[1:] if x[0] == y]]
return "/".join(res)
def childMounts(pathname):
"""Get all mount points which contain path"""
if pathname != "none":

@ -94,11 +94,14 @@ def getPkgUses(fullpkg, version=None, prefix="/"):
_pkgCategory = '{0}/{1}'.format(VDB_PATH, category)
pkgCategory = path.join(prefix, _pkgCategory)
if version is None:
packages = list(filter(lambda x: x['PN'] == pkg,
map(reVerSplitToPV,
filter(lambda x: x,
map(lambda x: reVerSplit.search(x),
listDirectory(pkgCategory))))))
# packages = list(filter(lambda x: x['PN'] == pkg,
# map(reVerSplitToPV,
# filter(lambda x: x,
# map(lambda x: reVerSplit.search(x),
# listDirectory(pkgCategory))))))
packages = [x for x in [reVerSplitToPV(y)
for y in [reVerSplit.search(z)
for z in listDirectory(pkgCategory)] if y] if x['PN'] == pkg]
if not packages:
return None
usePath = path.join(pkgCategory, packages[-1]['PF'], "USE")
@ -108,12 +111,14 @@ def getPkgUses(fullpkg, version=None, prefix="/"):
iusePath = path.join(pkgCategory, "%s-%s" % (pkg, version), "IUSE")
iuse = readFile(iusePath).strip().split()
use = readFile(usePath).strip().split()
return (list(map(lambda x: x[1:] if x.startswith("+") else x,
filter(lambda x: x,
use))),
list(map(lambda x: x[1:] if x.startswith("+") else x,
filter(lambda x: x,
iuse))))
# return (list(map(lambda x: x[1:] if x.startswith("+") else x,
# filter(lambda x: x,
# use))),
# list(map(lambda x: x[1:] if x.startswith("+") else x,
# filter(lambda x: x,
# iuse))))
return ([x[1:] if x.startswith("+") else x for x in use if x],
[x[1:] if x.startswith("+") else x for x in iuse if x])
def isPkgInstalled(pkg, prefix='/', sortByVersion=False):
@ -135,10 +140,8 @@ def isPkgInstalled(pkg, prefix='/', sortByVersion=False):
else:
return res
else:
return list(filter(lambda x: filter(lambda y: y['PN'] == pkg,
map(reVerSplitToPV,
listDirectory(x))),
listDirectory(pkgDir, fullPath=True)))
return [x for x in listDirectory(pkgDir, fullPath=True)
if [y for y in map(reVerSplitToPV,listDirectory(x)) if y['PN'] == pkg]]
def getPkgSlot(pkg, prefix='/'):
@ -1238,10 +1241,7 @@ class PackageList(object):
def _packages(self):
if self.result is None:
self.result = list(filter(lambda x: x['PN'],
map(lambda x: (x if isinstance(x, Mapping)
else EmergePackage(x)),
self._raw_list)))
self.result = [x for x in [(y if isinstance(y, Mapping) else EmergePackage(y)) for y in self._raw_list] if x['PN']]
return self.result
def __getitem__(self, item):
@ -1288,10 +1288,7 @@ class Manifest:
"""
Получить список файлов из Manifest
"""
return list(map(lambda x: x.group(1),
filter(None,
map(self.re_dist.search,
readLinesFile(self._manifest)))))
return [x.group(1) for x in map(self.re_dist.search, readLinesFile(self._manifest)) if x]
class Ebuild:

@ -83,9 +83,7 @@ class VariableOsX11Resolution(Variable):
sectionsScreen = filter(lambda x: "Modes" in x,
reScreenSections.findall(
readFile('/etc/X11/xorg.conf')))
modes = list(map(lambda x: x.groups()[0],
filter(lambda x: x,
map(reModes.search, sectionsScreen))))
modes = [x.groups()[0] for x in map(reModes.search, sectionsScreen) if x]
if modes:
return max(modes, key=lambda x: int(x.partition('x')[0]))

@ -111,16 +111,11 @@ class VariableClTemplateCltPath(ReadonlyVariable):
"""
chroot = self.Get('cl_chroot_path')
if "CONFIG_PROTECT" in os.environ:
protect_paths = ["/etc"] + list(filter(
lambda x: x.strip(),
os.environ["CONFIG_PROTECT"].split(" ")))
protect_paths = ["/etc"] + [x for x in os.environ["CONFIG_PROTECT"].split(" ") if x.strip()]
else:
protect_paths = ["/etc", "/usr/share/X11/xkb", "var/lib/hsqldb",
"/usr/share/config"]
return list(filter(path.exists,
map(lambda x: pathJoin(chroot, x),
protect_paths)))
return [x for x in [pathJoin(chroot, y) for y in protect_paths] if path.exists(x)]
class VariableClRootPath(Variable):
"""
@ -486,15 +481,13 @@ class VariableClFeatures(ReadonlyVariable):
def get(self):
emerge_config = self.Get('cl_emerge_config')
if emerge_config and "FEATURES" in emerge_config:
return list(filter(
# None, emerge_config['FEATURES'].encode('utf-8').split()))
None, emerge_config['FEATURES'].split()))
# return filter(None, emerge_config['FEATURES'].encode('utf-8').split())
return [x for x in emerge_config['FEATURES'].split() if x]
else:
emerge_info = self.Get('cl_emerge_info')
for line in filter(lambda x: x.startswith("FEATURES="),
emerge_info):
return list(filter(
None, line.partition("=")[2].strip('\n"\'').split()))
return [x for x in line.partition("=")[2].strip('\n"\'').split() if x]
return ""
@ -739,8 +732,7 @@ class VariableClTemplatesLocate(Variable):
return vals + ['clt']
def choice(self):
return list(map(lambda x: (x, self.descriptionMap.get(x, x)),
self.get()))
return [(x, self.descriptionMap.get(x, x)) for x in self.get()]
class VariableClTemplatePathUse(ReadonlyVariable):

@ -78,7 +78,6 @@ class VariableHrCpuNum(ReadonlyVariable):
return str(len(list(filter(lambda x: x.startswith("processor"),
readLinesFile(cpuinfo_file)))) or 1)
class VariableHrCpuName(ReadonlyVariable):
def get(self):
cpuinfo_file = "/proc/cpuinfo"

@ -493,8 +493,7 @@ class Locale(object):
return [x for x in self.langData.keys() if x not in skip]
def getLanguages(self):
return list(map(lambda x: self.langData[x]['language'],
self.langData.keys()))
return [self.langData[x]['language'] for x in self.langData.keys()]
def isLangExists(self, lang):
return lang in self.langData.keys()
@ -755,7 +754,7 @@ class VariableOsLang(ReadonlyVariable, Locale):
return self.getLangs()
def humanReadable(self):
return list(map(lambda x: self.getName(x), self.Get()))
return [self.getName(x) for x in self.Get()]
class VariableOsKeyboardLayout(ReadonlyVariable, Locale):
"""
@ -767,4 +766,4 @@ class VariableOsKeyboardLayout(ReadonlyVariable, Locale):
return self.getKeyboardLayouts()
def humanReadable(self):
return list(map(lambda x: self.getLayoutname(x), self.Get()))
return [self.getLayoutname(x) for x in self.Get()]

@ -67,11 +67,10 @@ class LdapHelper(object):
user_obj = self.getLdapUserObject()
if ldapUser and isinstance(user_obj, ldapUser):
if user_obj.connectLdap():
return list(map(lambda x: x[0][1]['uid'][0],
user_obj.ldapObj.ldapSearch(
return [ x[0][1]['uid'][0] for x in user_obj.ldapObj.ldapSearch(
user_obj.getUsersDN(),
ldap.SCOPE_ONELEVEL, '(objectClass=*)',
['uid'])))
['uid'])]
return []

Loading…
Cancel
Save