예제 #1
0
    def __init__(self, filename, places):

        root = FromXmlFile(filename)

        walker = root.createTreeWalker(root.documentElement,
                                      NodeFilter.SHOW_ELEMENT, None, 0)

        while 1:
            nodeName = walker.currentNode.nodeName
            attribs = walker.currentNode.attributes

            if nodeName == 'game':
                self.startingPlace = attribs['startingPlace'].value
                self.serverHost = attribs['serverHost'].value
                self.serverPort = attribs['serverPort'].value
                
            elif nodeName == 'place':
                placeName = attribs['name'].value
                desc = attribs['description'].value
                currentPlace = Place(placeName, desc)
                places[placeName] = currentPlace

            elif nodeName == 'object':
                currentPlace.addObject(attribs['name'].value)

            elif nodeName == 'connection':
                currentPlace.addConnection(attribs['place'].value)

            next = walker.nextNode()
            
            if next is None: break
예제 #2
0
    def __init__(self, filename, places):

        root = FromXmlFile(filename)

        walker = root.createTreeWalker(root.documentElement,
                                       NodeFilter.SHOW_ELEMENT, None, 0)

        while 1:
            nodeName = walker.currentNode.nodeName
            attribs = walker.currentNode.attributes

            if nodeName == 'game':
                self.startingPlace = attribs['startingPlace'].value

            elif nodeName == 'place':
                placeName = attribs['name'].value
                desc = attribs['description'].value
                currentPlace = Place(placeName, desc)
                places[placeName] = currentPlace

            elif nodeName == 'object':
                currentPlace.addObject(attribs['name'].value)

            elif nodeName == 'connection':
                currentPlace.addConnection(attribs['place'].value)

            next = walker.nextNode()

            if next is None: break
예제 #3
0
    def createDOMs(self, fileName):
	doc=FromXmlFile(fileName)
	dom=doc.getElementsByTagName("template").item(0)
	className=doc.getElementsByTagName("template").item(0).getAttribute("class")
	#print "className is '"+className+"' added to classesDOMs={}"
	if className != "":
	    self.classesDOMs[className]=dom
예제 #4
0
    def include(self):

	# Записать эти файлы в storyall.xml
	try:
	    doc = FromXmlFile("storyall.xml")
	    #Print (doc)
	    dom = doc.documentElement

	    inc = doc.createElement("include")
	    inc.setAttribute("url", self.toFile)
	    isIncAlready=False
	    incs = dom.getElementsByTagName("include")
	    for i in incs:
		if i.getAttribute("url")==inc.getAttribute("url"):
		    isIncAlready=True
		    break
	    if not isIncAlready:
		dom.appendChild(inc)
		dom.appendChild(doc.createTextNode("\n"))


	    f=open("storyall.xml", 'w')
	    Print(doc, f, "utf-8")

	except Exception, msg:
	    print "Strelka-Canceler::include(): EXCEPTION (while writing to 'storyall.xml'):", msg
예제 #5
0
    def appendStoryallXml(self, xmlFile, templates_path,result_path):
	os.system("cp "+xmlFile+" "+xmlFile+".old")
        doc=FromXmlFile(xmlFile)
	dom=doc.getElementsByTagName("root").item(0)
	for file in os.listdir(templates_path):
	    if re.search("\.template\.xml",file) and not re.search("impulses\.", file):
	        try:
	            ff = open(result_path+"/"+file.replace(".template",""),'r')
	            ff.close()
	            include = doc.createElement("include")
	            include.setAttribute("url",file.replace(".template",""))
	            includes = dom.getElementsByTagName("include")
	            isAppend = True
	            for inc in includes:
	                if inc.getAttribute("url") == file.replace(".template",""):
	                    isAppend = False
	            if isAppend:
	                dom.appendChild(include)
	                newStr=doc.createTextNode("\n")
		        dom.appendChild(newStr)
		        print "В storyall.xml добавлена нода "+str(include)
		    else:
		        print "В storyall.xml уже имеется нода <include url='"+file.replace(".template","")+"' />"
		except:
		    continue
																																												
	file=open(xmlFile,'w')
	Print(doc,file,"utf-8")
	print "Записан файл ", str(xmlFile)
예제 #6
0
    def appendTsXml(self, tsXmlFile):
	os.system("cp "+tsXmlFile+" "+tsXmlFile+".old")
	doc=FromXmlFile(tsXmlFile)
	dom=doc.getElementsByTagName("g").item(0)
	for file in os.listdir(tsXmlFile.replace("/ts.xml","")):
    	    if re.search("impulses\.",file) and re.search("\.xml", file) and not re.search("\.old", file):
		include = doc.createElement("include")
		include.setAttribute("url",file)
	    
		includes = dom.getElementsByTagName("include")
		isAppend = True
		for inc in includes:
		    if inc.getAttribute("url") == file:
			isAppend = False
	    
		if isAppend:
		    dom.appendChild(include)
		    newStr=doc.createTextNode("\n")
		    dom.appendChild(newStr)
		    #Obj.sig(self.out,_("В ts.xml добавлена нода "+str(include)))
		    print _("В ts.xml добавлена нода "+str(include))
		else:
		    #Obj.sig(self.out,_("В ts.xml уже имеется нода <include url='"+file+"' />"))
		    print _("В ts.xml уже имеется нода <include url='"+file+"' />")
	file=open(tsXmlFile,'w')
	Print(doc,file,"utf-8")
	#Obj.sig(self.out,_("Записан файл "+str(tsXmlFile)))
	print "Записан файл ", str(tsXmlFile)
예제 #7
0
def load(filename):
    log = logging.getLogger("input.planitLoader.load")

    doc = FromXmlFile(filename)

    rootEL = doc.getElementsByTagName("project")[0]

    return loadProject(rootEL)
예제 #8
0
def load( filename ):
	log = logging.getLogger( "input.planitLoader.load" )

	doc = FromXmlFile( filename )

	rootEL = doc.getElementsByTagName( "project" )[0]

	return loadProject( rootEL )
예제 #9
0
    def setStationName(self, name, file):
	doc=FromXmlFile(file)
	title = doc.getElementsByTagName("widget").item(0).getAttribute("title")
	#if title == "" or title != "":
	doc.documentElement.setAttribute("title", name)
	f = open (file, 'w')
	Print (doc,f,"utf-8")
	f.close()
	#Obj.sig(self.out,_("Установлено новое имя станции"))
	print _("Установлено новое имя станции")
예제 #10
0
def setSize(where, height, width):
    print "Установка значений высоты ("+str(height)+") и ширины ("+str(width)+")"
    for file in filesToChange:

	try:
	
	    doc=FromXmlFile(where+"/"+file)
	    doc.getElementsByTagName("svg").item(0).setAttribute("height", str(height))
	    doc.getElementsByTagName("svg").item(0).setAttribute("width", str(width))
	    file1 = open(where+"/"+file,'w')
    	    Print(doc,file1,"utf-8")
	    print "Записан файл "+file
	
	except:
	    donothing=0
	    
	try:
	#if True:
	    doc=FromXmlFile(where+"/"+file)
	    widgets = doc.getElementsByTagName("widget")
	    for widget in widgets:
		if widget.getAttribute("url")=="svg/ladst.svg":
		    widget.setAttribute("height", str(height))
		    widget.setAttribute("width", str(width))
	    	    file1 = open(where+"/"+file,'w')
    		    Print(doc,file1,"utf-8")
		    print "Записан файл "+file
	except:
	    donothing=0
예제 #11
0
    def LoadFromXML(self, filename):
        self.settings = {}
        self.filename = filename
        if USE_MINIDOM:
            doc = minidom.parse(open(filename))
        else:
            doc = FromXmlFile(filename)

        settings = doc.getElementsByTagName("Setting")
        for item in settings:
            if item.attributes:
                myname = ""
                myvalue = ""
                for i in range(0, len(item.attributes)):
                    attr = item.attributes.item(i)
                    if attr.name == "name":
                        myname = attr.value
                    elif attr.name == "value":
                        myvalue = attr.value
                self.settings[myname] = myvalue
예제 #12
0
    def setSize(self):
	print "Установка значений высоты (",str(self.height),") и ширины (",str(self.width),")"
        for file in self.filesToChange:

	    doc=FromXmlFile(self.where+"/"+file)

	    try:
	
		doc.getElementsByTagName("svg").item(0).setAttribute("height", str(self.height))
		doc.getElementsByTagName("svg").item(0).setAttribute("width", str(self.width))
	        file1 = open(self.where+"/"+file,'w')
    		Print(doc,file1,"utf-8")
	
	    except Exception, msg:
		print "SvgSetter::setSize() error: ", msg
	    	    
	    try:
		widgets = doc.getElementsByTagName("widget")
		for widget in widgets:
		    if widget.getAttribute("url")=="svg/ladst.svg":
			widget.setAttribute("height", str(self.height))
			widget.setAttribute("width", str(self.width))
	    		file1 = open(self.where+"/"+file,'w')
    			Print(doc,file1,"utf-8")
	    except Exception, msg:
		print "SvgSetter::setSize() error 2: ", msg
예제 #13
0
    def __init__(self, file=None):
        if type(file) == StringType:
            self._dom = FromXmlFile(file)
        elif type(file) == FileType:
            self._dom = FromXmlStream(file)
        else:
            raise ValueError, \
                  "XML_Objectify must be initialized with filename or file handle"

        self._processing_instruction = {}

        for child in self._dom.childNodes:
            if child.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
                self._processing_instruction[child.nodeName] = child.nodeValue
            elif child.nodeType == Node.ELEMENT_NODE:
                self._root = child.nodeName
        self._PyObject = pyobj_from_dom(self._dom)
예제 #14
0
class XML_Generator(object):
    _logger = logging.getLogger('XML_Generator')

    def __init__(self, template, nsmap=None):
        self.root = etree.fromstring(template)
        self.nsmap = nsmap

    # end def __init__

    def generate(self, **scope_dict):
        if self.nsmap:
            root = etree.Element(self.root.tag,
                                 self.root.attrib,
                                 nsmap=self.nsmap)
        else:
            root = etree.Element(self.root.tag, self.root.attrib)
        self.out = etree.ElementTree(root)
        self._iterate(self.root, root, scope_dict)
        return self.out

    # end def generate

    def write(self, xml_file, pretty=True):
        from xml.dom.ext import PrettyPrint
        from xml.dom.ext.reader.Sax import FromXmlFile

        try:
            f = open(xml_file, "w")
            try:
                self.out.write(f)
            finally:
                f.close()
        except (SystemExit, KeyboardInterrupt), exc:
            raise

        if pretty:
            doc = FromXmlFile(xml_file)
            try:
                f = open(xml_file, "w")
                try:
                    PrettyPrint(doc, f)
                finally:
                    f.close()
            except (SystemExit, KeyboardInterrupt), exc:
                raise
예제 #15
0
    def __init__(self, fileName):
	self.fileName = fileName
	print "++++ Начало создания файла '"+fileName+"'"
	try:
	    f = open(fileName,'r')
	    oldContent = f.read()
	    f.close()
	    
	    f1 = open(fileName+".old",'w')
	    f1.write(oldContent)
	    f1.close()
	except:
	    donothing=0

	file = open(fileName,'w')
	file.write("<?xml version='1.0' encoding='utf-8'?>\n<root>\n</root>")
	file.close()
	self.root=FromXmlFile(fileName)
예제 #16
0
from xml.dom.ext.reader.Sax import FromXmlFile
from xml.dom.NodeFilter import NodeFilter

root = FromXmlFile('problem1.xml')

walker = root.createTreeWalker(root.documentElement,
                              NodeFilter.SHOW_ELEMENT, None, 0)

while 1:
    nodeName = walker.currentNode.nodeName

    if nodeName == 'game':
        print("Hey, I found the game tag!")
        
    next = walker.nextNode()
    
    if next is None: break
예제 #17
0
class CreatorTU:

    fileName=""
    root=None


    def __init__(self, fileName):
	self.fileName = fileName
	print "++++ Начало создания файла '"+fileName+"'"
	try:
	    f = open(fileName,'r')
	    oldContent = f.read()
	    f.close()
	    
	    f1 = open(fileName+".old",'w')
	    f1.write(oldContent)
	    f1.close()
	except:
	    donothing=0

	file = open(fileName,'w')
	file.write("<?xml version='1.0' encoding='utf-8'?>\n<root>\n</root>")
	file.close()
	self.root=FromXmlFile(fileName)
	

    #добавить новый документ для обработки
    def add(self, doc):
	#print "$$$$$$$$$$$$$ called add()"
	objs = doc.getElementsByTagName("obj")
	for obj in objs:
	    tu = self.root.createElement("tu")
	    
	    klass = obj.getAttribute("class")
	    name = obj.getAttribute("name")
	    
	    sets = obj.getElementsByTagName("sets")
	    for set in sets:
		tuCommandName = set.getAttribute("attr")
		if set.firstChild.TEXT_NODE:
		    #print "$$$$$$ ok"
		    tuCommand = set.firstChild.data
		    tuCommand = tuCommand.replace("\"","")
		    tuCommand = tuCommand.replace("'","")
		    tuCommand = tuCommand.replace("(","")
		    tuCommand = tuCommand.replace(")","")
		
		    tu.setAttribute("class",klass)
		    tu.setAttribute("who",name)
		    tu.setAttribute("prop",tuCommandName)
		    tu.setAttribute("value",tuCommand)
		
		    newStr = self.root.createTextNode("\n")
		    
		    dom = self.root.getElementsByTagName("root").item(0)
		    
		    dom.appendChild(tu)
		    dom.appendChild(newStr)
		else:
		    print "ОШИБКА в файле "+str(self.fileName)+" (пропущено) "
	
	
    #деструктор (сохраняет полученный файл)
    def __del__(self):
	try:
	    f=open(self.fileName,'w')
	    Print(self.root,f,"utf-8")
	    f.close()
	    print "Сохранен файл '"+self.fileName+"'"
	except:
	    print "Невозможно сохранить файл '"+self.fileName+"'"
예제 #18
0
    def LoadFromXML(self, filename):
        self.filename = filename
        self.directory = os.path.split(filename)[0]
        if os.path.exists(os.path.join(self.directory, "settings.xml")):
            self.settings.LoadFromXML(os.path.join(self.directory, "settings.xml"))
        self.content = ContentList()
        self.updatedids = {}
        self.nodes = []
        try: 
            myfile = utils.openFile(filename)
            data = myfile.read()
            myfile.close()
            
            if data.find("\x92") != -1 or data.find("\x93") != -1 or data.find("\x94") != -1:
                data = data.replace("encoding=\"iso8859-1\"", "encoding=\"cp1252\"")
                myfile = utils.openFile(filename, "w")
                myfile.write(data)
                myfile.close()
                print "Ugh, smart quotes..."
                
            if USE_MINIDOM:
                doc = minidom.parse(utils.openFile(filename))
            else:
                doc = FromXmlFile(filename)
        except:
            return "The EClass project file cannot be loaded. The error message is: " + `sys.exc_value.args`

        manifest = doc.getElementsByTagName("manifest")[0]
        if manifest.attributes:
            for i in range(0, len(manifest.attributes)):
                attr = manifest.attributes.item(i)
                if attr.name == "identifier" and string.find(attr.value, self.namespace) != -1:
                    self.id = string.replace(attr.value, self.namespace, "")
                    self.id = string.replace(self.id, "-", "")

            if self.id == "":
                self.id = utils.getUUID()
                    
        metadata = doc.getElementsByTagName("metadata")[0]
        if metadata.childNodes:
            if metadata.getElementsByTagName("PublicationID"):
                if metadata.getElementsByTagName("PublicationID")[0].childNodes:
                    self.pubid = metadata.getElementsByTagName("PublicationID")[0].childNodes[0].nodeValue
                    #print self.pubid
            else:
                self.pubid = ""
            imsmetadata = doc.getElementsByTagName("imsmd:General")
            self._GetMetadata(metadata)
        resources = doc.getElementsByTagName("resource")
        self._GetResources(resources)
        toc = doc.getElementsByTagName("tableofcontents")
        if not toc:
            toc = doc.getElementsByTagName("organization")
            if toc:
                toc = toc[0]
        else:
            toc = toc[0]
        if toc.attributes:
            for i in range(0, len(toc.attributes)):
                attr = toc.attributes.item(i)
                if attr.name == "identifier" and string.find(attr.value, self.namespace) != -1:
                    self.orgid = string.replace(attr.value, self.namespace, "")
                    self.orgid = string.replace(self.orgid, "-", "")

            if self.orgid == "":
                self.orgid = utils.getUUID()
        items = doc.getElementsByTagName("item")[0]
        self._GetNodes(items, None)
        self.CurrentNode = self.nodes[0]
        return ""
예제 #19
0
    def __init__(self,resultFileName, path, _isEmptyGroupsRemove=True):
	print "Начало создания таблицы ТС"	
    
	self.resultFileName = resultFileName
	self.path = path
	
	

	# сохранить имеющийся файл resultFileName с расширением old
        try:
            f = open(resultFileName,'r')
            oldContent = f.read()
            f.close()

            f1 = open(resultFileName+".old",'w')
            f1.write(oldContent)
            f1.close()
        except:
            donothing=0


        
	
	#просмотреть данную директорию на наличие файлов impulses.<....>.xml
	try:
	    os.listdir(self.path)
	except:
	    print "\nОШИБКА! Не могу прочитать каталог ", self.path, ". Остановлено\n"
	    return 
	for file in os.listdir(self.path):
	    isRequired=True
	    
	    for nu in self.notUsed:
		if re.search(nu, file):
		    isRequired=False
		    break
	    #if re.search("impulses.",file) and re.search(".xml", file):
	    if isRequired and re.search("^impulses.",file) and re.search(".xml$", file) and not re.search(".old$",file) and not re.search(".back$",file) :
		print "Найден файл "+str(file)
		
		try:
		#if True:
		    impDoc = FromXmlFile(self.path+"/"+file)
		    root = impDoc.getElementsByTagName("root").item(0)
		    objs = root.getElementsByTagName("obj")
		    for obj in objs:
			# имя рассматриваемого объекта
			objName = obj.getAttribute("name")
			RusName = obj.getAttribute("title")
			sets = obj.getElementsByTagName("sets")
			for set in sets:
		    	    if set.firstChild.TEXT_NODE and set.getAttribute("attr")=="address":
		    		ts = set.firstChild.data
				ts = ts.replace("\"","")
				ts = ts.replace("'","")
				ts = re.sub("\s$","", ts,1)
				ts = re.sub("^\s","", ts,1)
			
				#try:
				if True: # '9	 0'
				    tsList = re.split("\s", ts)
				    #получить номера канала, группы и импульса

				    #print objName, " - ", tsList
				    tsList2=[]
				    
				    # удалить пустые члены
				    for tss in tsList:
					if tss!="":
					    tsList2.append(tss)
				    
				    if len(tsList2)!=4:
					print "Объект", objName, "имеет неверный формат ТС"
					sys.exit(0)
				    
				    channel = string.atoi(tsList2[1])
				    group = string.atoi(tsList2[2])
				    imp = string.atoi(tsList2[3])
				    # отправить на обработку объекту класса matrix.Matrix
				    #if(channel==_channel):
				    #    self.matr.append(group,imp, objName)
				    if not (imp==0 or group==0):
					self.channels.append(channel)
					self.groups.append(group)
					self.impulses.append(imp)
					self.names.append(objName)
					if RusName!="":
					    self.RusNames.append(str(RusName.encode("utf-8")))
					else:
					    self.RusNames.append(str(objName))
				#except:
				#    donothing=0
				
		except:
		    print "Не получилось обработать файл "+str(self.path)+"/"+str(file)+" (пропущено)"
		    continue
		    
		    
	channelsReal = []
	#создать копию массива channels
	for i in self.channels:
	    channelsReal.append(i)    
			    
	    
	channelsReal.sort()
	
	self.ch = []
	for i in range(0, len(channelsReal)):
	    if i!=0:
		if channelsReal[i]!=channelsReal[i-1]:
		    self.ch.append(channelsReal[i])
	    else:
		self.ch.append(channelsReal[0])
	
	
	    
	for i in self.ch:
	
	    print "++++++ Канал = "+str(i)
	    
	    matr = matrix.Matrix()
	    
	    for j in range(0, len(self.groups)):
		if self.channels[j]==i:
		    #print str(len(self.names))+" - "+str(len(self.RusNames))
	    	    matr.append(self.groups[j], self.impulses[j], self.names[j], self.RusNames[j])
	    
	    self.matrixes.append( matr.getMatrix(_isEmptyGroupsRemove) )
	    self.XminLines.append( matr.getYmin() )
	    self.YminLines.append( matr.getXmin() )
	    self.Xs.append(matr.getXs())
	    matr = None
예제 #20
0
    def __init__(self, templatePath, resultsPath, ini):

	self.tsSeller=seller.TSandTUseller(8, ".last.diag.ts", "1:0")
	self.tsSeller.station=3

	self.templatePath=templatePath
	self.resultsPath=resultsPath
	self.ini = ini
	
	print "Diag::_init__(): Template path=", self.templatePath
	print "Diag::_init__(): Results path=", self.resultsPath
	print "Diag::_init__(): ini =", self.ini

	iniDoc=FromXmlFile(self.ini)
	iniDom=iniDoc.documentElement
    
	self.fullDoc=FromXmlFile(self.templatePath+"/full-template.svg")
	fullDom=iniDoc.documentElement
    
	umvs=iniDom.getElementsByTagName("umv")
	udos=iniDom.getElementsByTagName("udo")
	rios=iniDom.getElementsByTagName("rio")
    
	f1=open(self.templatePath+"/impulses.diag.template.xml")
	self.impTemplate=f1.read()
	f1.close()

	f2=open(self.templatePath+"/diag.template.xml")
	self.diagTemplate=f2.read()
	f2.close()


	f22=open(self.templatePath+"/rio-cps.template.xml")
	self.rioTemplate=f22.read()
	f22.close()


	f3=open(self.templatePath+"/impulses.umv-tests.template.xml")
	self.umvTestsImpTemplate=f3.read()
	f3.close()

	f4=open(self.templatePath+"/umv-tests.template.xml")
	self.umvTestsTemplate=f4.read()
	f4.close()

	self.diagCont+="<?xml version=\"1.0\" encoding='utf-8'?>\n<root>\n"

	self.impCont+="<?xml version=\"1.0\" encoding='utf-8'?>\n<root>\n"

	self.umvTestsCont+="<?xml version=\"1.0\" encoding='utf-8'?>\n<root>\n"
	self.umvTestsImpCont+="<?xml version=\"1.0\" encoding='utf-8'?>\n<root>\n"

	coords = self.makeShelfs(umvs, self.umv, self.umvWidth, self.umvHeight, True, False)

	self.Y += (coords["y"] + 1) * self.umvHeight
	self.X += (coords["x"] + 1) * self.umvWidth

	coords = self.makeShelfs(udos, self.udo, self.udoWidth, self.udoHeight, False, False)

	self.Y += (coords["y"]+1) * self.udoHeight
	if coords["x"]>self.X:
	    self.X += (coords["x"]+1) * self.udoWidth

	coords = self.makeShelfs(rios, self.rio, self.rioWidth, self.rioHeight, False, True)

	self.Y += (coords["y"] + 1) * self.rioHeight
	if coords["x"]>self.X:
	    self.X += (coords["x"] + 1) * self.rioWidth

	self.diagCont+="\n</root>"
	
	self.impCont+="""
<obj class="signalImp" name="test1_button" />
<obj class="signalImp" name="test2_button" />
<obj class="signalImp" name="test3_button" />
<obj class="signalImp" name="test4_button" />
<obj class="signalImp" name="test5_button" />
<obj class="signalImp" name="test6_button" />
<obj class="signalImp" name="test7_button" />
<obj class="signalImp" name="test8_button" />
</root>	"""


	self.umvTestsCont+="\n</root>"
	self.umvTestsImpCont+="\n</root>"
예제 #21
0
    def saveAll(self):

	open(self.resultsPath+"/impulses.diag.xml", 'w').write(self.impCont)
	
	open(self.resultsPath+"/diag.xml", 'w').write(self.diagCont)

	diagButtons=open(self.templatePath+"/diag.buttons.xml", 'r').read()
	open(self.resultsPath+"/diag.buttons.xml", 'w').write(diagButtons)

	open(self.resultsPath+"/diag-tests.xml", 'w').write(self.umvTestsCont)

	open(self.resultsPath+"/impulses.diag-tests.xml", 'w').write(self.umvTestsImpCont)
	
	self.background()	
	
	file=open("../svg/diag/"+self.resultsPath+"/full.svg", 'w')
	Print(self.fullDoc, file, "utf-8")
	file.close()
	    
	


	# Записать эти файлы в storyall.xml
	try:
	    doc = FromXmlFile(self.resultsPath+"/storyall.xml")
	    Print (doc)
	    dom = doc.documentElement
	    
	    inc = doc.createElement("include")
	    inc.setAttribute("url", "diag-tests.xml")
	    isIncAlready=False
	    incs = dom.getElementsByTagName("include")
	    for i in incs:
		if i.getAttribute("url")==inc.getAttribute("url"):
		    isIncAlready=True
		    break
	    if not isIncAlready:
		dom.appendChild(inc)	
		dom.appendChild(doc.createTextNode("\n"))
	
	    inc = doc.createElement("include")
	    inc.setAttribute("url", "diag.xml")
	    isIncAlready=False
	    incs = dom.getElementsByTagName("include")
	    for i in incs:
		if i.getAttribute("url")==inc.getAttribute("url"):
		    isIncAlready=True
		    break
	    if not isIncAlready:
		dom.appendChild(inc)	
		dom.appendChild(doc.createTextNode("\n"))
	    	
	    inc = doc.createElement("include")
	    inc.setAttribute("url", "diag.buttons.xml")
	    isIncAlready=False
	    incs = dom.getElementsByTagName("include")
	    for i in incs:
		if i.getAttribute("url")==inc.getAttribute("url"):
		    isIncAlready=True
		    break
	    if not isIncAlready:
		dom.appendChild(inc)	
		dom.appendChild(doc.createTextNode("\n"))
	
	    f=open(self.resultsPath+"/storyall.xml", 'w')
	    Print(doc, f, "utf-8")
	
	except Exception, msg:
	    print "Diag::saveAll(): EXCEPTION (while writing to 'storyall.xml'):", msg
예제 #22
0
class Diag:

    umvWidth=115
    umvHeight=177
    udoWidth=77
    udoHeight=98

    leftField=3
    rightField=3
    topField=3
    bottomField=3
    
    rioWidth=77
    rioHeight=98

    fullDoc=None

    impTemplate=""
    diagTemplate=""

    rioTemplate=""

    umvTestsTemplate=""
    umvTestsImpTemplate=""
    
    tsSeller=None

    diagCont=""
    impCont=""
    umvTestsCont=""
    umvTestsImpCont=""

    
    resultsPath=""
    iniPath=""
        
    iniStr=""
    
    Y=0 # текущие координаты
    X=0

    includes=[] #список нод <include ...> - вставляться будут свгешки УДО, УМВ, РИО, расставленные в соответствии с конфигом
	


    def __init__(self, templatePath, resultsPath, ini):

	self.tsSeller=seller.TSandTUseller(8, ".last.diag.ts", "1:0")
	self.tsSeller.station=3

	self.templatePath=templatePath
	self.resultsPath=resultsPath
	self.ini = ini
	
	print "Diag::_init__(): Template path=", self.templatePath
	print "Diag::_init__(): Results path=", self.resultsPath
	print "Diag::_init__(): ini =", self.ini

	iniDoc=FromXmlFile(self.ini)
	iniDom=iniDoc.documentElement
    
	self.fullDoc=FromXmlFile(self.templatePath+"/full-template.svg")
	fullDom=iniDoc.documentElement
    
	umvs=iniDom.getElementsByTagName("umv")
	udos=iniDom.getElementsByTagName("udo")
	rios=iniDom.getElementsByTagName("rio")
    
	f1=open(self.templatePath+"/impulses.diag.template.xml")
	self.impTemplate=f1.read()
	f1.close()

	f2=open(self.templatePath+"/diag.template.xml")
	self.diagTemplate=f2.read()
	f2.close()


	f22=open(self.templatePath+"/rio-cps.template.xml")
	self.rioTemplate=f22.read()
	f22.close()


	f3=open(self.templatePath+"/impulses.umv-tests.template.xml")
	self.umvTestsImpTemplate=f3.read()
	f3.close()

	f4=open(self.templatePath+"/umv-tests.template.xml")
	self.umvTestsTemplate=f4.read()
	f4.close()

	self.diagCont+="<?xml version=\"1.0\" encoding='utf-8'?>\n<root>\n"

	self.impCont+="<?xml version=\"1.0\" encoding='utf-8'?>\n<root>\n"

	self.umvTestsCont+="<?xml version=\"1.0\" encoding='utf-8'?>\n<root>\n"
	self.umvTestsImpCont+="<?xml version=\"1.0\" encoding='utf-8'?>\n<root>\n"

	coords = self.makeShelfs(umvs, self.umv, self.umvWidth, self.umvHeight, True, False)

	self.Y += (coords["y"] + 1) * self.umvHeight
	self.X += (coords["x"] + 1) * self.umvWidth

	coords = self.makeShelfs(udos, self.udo, self.udoWidth, self.udoHeight, False, False)

	self.Y += (coords["y"]+1) * self.udoHeight
	if coords["x"]>self.X:
	    self.X += (coords["x"]+1) * self.udoWidth

	coords = self.makeShelfs(rios, self.rio, self.rioWidth, self.rioHeight, False, True)

	self.Y += (coords["y"] + 1) * self.rioHeight
	if coords["x"]>self.X:
	    self.X += (coords["x"] + 1) * self.rioWidth

	self.diagCont+="\n</root>"
	
	self.impCont+="""
<obj class="signalImp" name="test1_button" />
<obj class="signalImp" name="test2_button" />
<obj class="signalImp" name="test3_button" />
<obj class="signalImp" name="test4_button" />
<obj class="signalImp" name="test5_button" />
<obj class="signalImp" name="test6_button" />
<obj class="signalImp" name="test7_button" />
<obj class="signalImp" name="test8_button" />
</root>	"""


	self.umvTestsCont+="\n</root>"
	self.umvTestsImpCont+="\n</root>"








    def getIni(self):
	self.tsSeller.endIni()
	return self.tsSeller.getIni()




    # "сделать полки" shelfArr=список нод, описывающих ту или иную плату  
    # isUMV - это УМВ? Если да - делать тестовые входы
    # shelfWidth, shelfHeight - ширина и высота платы
    def makeShelfs(self, shelfArr, function, shelfWidth, shelfHeight, isUMV=False, isRIO=False ):

	mainX=0
	mainY=0
		
        #создание полок с платами
        for shelf in shelfArr:
	    include=self.fullDoc.createElement("include")
	    
	    xStr=shelf.getAttribute("x")
	    x=string.atoi(xStr)
	    
	    yStr=shelf.getAttribute("y")
	    y=string.atoi(yStr)

	    name=shelf.getAttribute("name")
	    title=shelf.getAttribute("title")
		    	    
	    include.setAttribute("url", "svg/diag/"+name+".svg")
	    include.setAttribute("x", str(self.leftField + x*shelfWidth))
	    include.setAttribute("y", str(self.Y + self.topField + y*shelfHeight))

	    if x > mainX: mainX=x
	    if y > mainY: mainY=y	    
	    
	    self.includes.append(include)
	    function(name,title)
	    
	    tmp = ""
	    
	    if not isRIO:
		tmp=re.sub("@NAME@", str(name), self.diagTemplate, 100)
		tmp=re.sub("@TITLE@", str(title.encode("utf-8")), tmp, 100)	    
	    else:
		tmp=re.sub("@NAME@", str(name), self.rioTemplate, 100)
		tmp=re.sub("@TITLE@", str(title.encode("utf-8")), tmp, 100)	    

	    
	    
	    self.diagCont+=tmp

	    tmp=re.sub("@NAME@", str(name), self.impTemplate, 100)
	    tmp=re.sub("@TITLE@", str(title.encode("utf-8")), tmp, 100)	    
	    
	    i=0
	    while True:
		if re.search("@TS@", tmp) != None:
		    tmp = re.sub("@TS@", self.tsSeller.buy(self.tsSeller.getFullTitle(i,tmp)), tmp, 1 )
		    i+=1
		else:
		    break
											    
	    self.impCont+=tmp
	    

	    tmp=re.sub("@NAME@", str(name)+"@NAME@", self.umvTestsTemplate, 100)
	    tmp=re.sub("@TITLE_R@", str(title.encode("utf-8")+"р")+"@TITLE@", tmp, 100)

	    tmpImp=re.sub("@NAME@", str(name)+"@NAME@", self.umvTestsImpTemplate, 100)
	    tmpImp=re.sub("@TITLE_R@", str(title.encode("utf-8")+"р")+"@TITLE@", tmpImp, 100)

	    tmp=re.sub("@TITLE_O@", str(title.encode("utf-8")+"о")+"@TITLE@", tmp, 100)
	    tmpImp=re.sub("@TITLE_O@", str(title.encode("utf-8")+"о")+"@TITLE@", tmpImp, 100)

	    
	    if isUMV:
    	        for i in range(1,9):
		    
	    	    tmp1=re.sub("@NAME@", "w"+str(i), tmp, 100)
		    tmp1=re.sub("@TITLE@", ".Тест. вх. "+str(i)+"", tmp1, 100)
		    self.umvTestsCont+=tmp1
		    tmp2=re.sub("@NAME@", "w"+str(i), tmpImp, 100)
		    tmp2=re.sub("@TITLE@", ". Тест. вх. "+str(i)+"", tmp2, 100)
		    i=0
		    while True:
	    	        if re.search("@TS@", tmp2) != None:
		    	    tmp2 = re.sub("@TS@", self.tsSeller.buy(self.tsSeller.getFullTitle(i,tmp2)), tmp2, 1 )
			    i+=1
		        else:
			    break
		    self.umvTestsImpCont+=tmp2






	coords={}
	coords["x"]=mainX
	coords["y"]=mainY
	
	#print "makeShelfs: returned mainX="+str(mainX)+", mainY="+str(mainY)
	return coords


	

	







    def saveAll(self):

	open(self.resultsPath+"/impulses.diag.xml", 'w').write(self.impCont)
	
	open(self.resultsPath+"/diag.xml", 'w').write(self.diagCont)

	diagButtons=open(self.templatePath+"/diag.buttons.xml", 'r').read()
	open(self.resultsPath+"/diag.buttons.xml", 'w').write(diagButtons)

	open(self.resultsPath+"/diag-tests.xml", 'w').write(self.umvTestsCont)

	open(self.resultsPath+"/impulses.diag-tests.xml", 'w').write(self.umvTestsImpCont)
	
	self.background()	
	
	file=open("../svg/diag/"+self.resultsPath+"/full.svg", 'w')
	Print(self.fullDoc, file, "utf-8")
	file.close()
	    
	


	# Записать эти файлы в storyall.xml
	try:
	    doc = FromXmlFile(self.resultsPath+"/storyall.xml")
	    Print (doc)
	    dom = doc.documentElement
	    
	    inc = doc.createElement("include")
	    inc.setAttribute("url", "diag-tests.xml")
	    isIncAlready=False
	    incs = dom.getElementsByTagName("include")
	    for i in incs:
		if i.getAttribute("url")==inc.getAttribute("url"):
		    isIncAlready=True
		    break
	    if not isIncAlready:
		dom.appendChild(inc)	
		dom.appendChild(doc.createTextNode("\n"))
	
	    inc = doc.createElement("include")
	    inc.setAttribute("url", "diag.xml")
	    isIncAlready=False
	    incs = dom.getElementsByTagName("include")
	    for i in incs:
		if i.getAttribute("url")==inc.getAttribute("url"):
		    isIncAlready=True
		    break
	    if not isIncAlready:
		dom.appendChild(inc)	
		dom.appendChild(doc.createTextNode("\n"))
	    	
	    inc = doc.createElement("include")
	    inc.setAttribute("url", "diag.buttons.xml")
	    isIncAlready=False
	    incs = dom.getElementsByTagName("include")
	    for i in incs:
		if i.getAttribute("url")==inc.getAttribute("url"):
		    isIncAlready=True
		    break
	    if not isIncAlready:
		dom.appendChild(inc)	
		dom.appendChild(doc.createTextNode("\n"))
	
	    f=open(self.resultsPath+"/storyall.xml", 'w')
	    Print(doc, f, "utf-8")
	
	except Exception, msg:
	    print "Diag::saveAll(): EXCEPTION (while writing to 'storyall.xml'):", msg





	# Записать эти файлы в ts.xml
	try:
	    doc = FromXmlFile(self.resultsPath+"/ts.xml")
	    Print (doc)
	    dom = doc.documentElement
	    
	    inc = doc.createElement("include")
	    inc.setAttribute("url", "impulses.diag-tests.xml")
	    isIncAlready=False
	    incs = dom.getElementsByTagName("include")
	    for i in incs:
		if i.getAttribute("url")==inc.getAttribute("url"):
		    isIncAlready=True
		    break
	    if not isIncAlready:
		dom.appendChild(inc)	
		dom.appendChild(doc.createTextNode("\n"))
	
	    inc = doc.createElement("include")
	    inc.setAttribute("url", "impulses.diag.xml")
	    isIncAlready=False
	    incs = dom.getElementsByTagName("include")
	    for i in incs:
		if i.getAttribute("url")==inc.getAttribute("url"):
		    isIncAlready=True
		    break
	    if not isIncAlready:
		dom.appendChild(inc)	
		dom.appendChild(doc.createTextNode("\n"))
	    	
		
	    f=open(self.resultsPath+"/ts.xml", 'w')
	    Print(doc, f, "utf-8")
	
	except Exception, msg:
	    print "Diag::saveAll(): EXCEPTION (while writing to 'ts.xml'):", msg
	print "И путь до АРМа в качестве второго параметра"
	print "И слово True в качестве третьего параметра, если хотите, чтобы произошла сортировка стрелок по горловинам"
	sys.exit()	


    print "Выбраны параметры:"
    print "Путь до СВГ-файла: ", svgFile
    print "Путь до папки с АРМом: ", commPath
    if isTwoTabs:
	print "Разделяем стрелки по горловинам"
    else:
	print "НЕ Разделяем стрелки по горловинам"
    print "Обождите..."

    
    SVGDocument=FromXmlFile(sys.argv[1])
    SVGDom = SVGDocument.documentElement


    objs=SVGDom.getElementsByTagName("include")
    
    for obj in objs:
    
        temp=string.split(obj.getAttribute("url"), "/")
        inc_file=temp[len(temp)-1]
	
        temp1=string.split(svgFile, "/")
	
        real_path=""
        for i in range (0, len(temp1)-1):
            real_path+="/"+temp1[i]
예제 #24
0
		dom.appendChild(doc.createTextNode("\n"))
	

	    f=open("storyall.xml", 'w')
	    Print(doc, f, "utf-8")

	except Exception, msg:
	    print "Maket::include(): EXCEPTION (while writing to 'storyall.xml'):", msg





	# Записать эти файлы в ts.xml
	try:
	    doc = FromXmlFile("ts.xml")
	    Print (doc)
	    dom = doc.documentElement

	    inc = doc.createElement("include")
	    inc.setAttribute("url", "impulses.maket.xml")
	    isIncAlready=False
	    incs = dom.getElementsByTagName("include")
	    for i in incs:
		if i.getAttribute("url")==inc.getAttribute("url"):
		    isIncAlready=True
		    break
	    if not isIncAlready:
		dom.appendChild(inc)
		dom.appendChild(doc.createTextNode("\n"))