예제 #1
0
def Send_s6f11_Lot(_SystemByte, _CEID, _LOTID):
    clientSock = connToServer("127.0.0.1", 8099)  # 서버에 접속
    root = Element("SECS2_XML_MESSAGE")

    ## HEAD
    head = SubElement(root, "HEAD")
    SubElement(head, "SystemByte").text = str(_SystemByte)
    SubElement(head, "CMD").text = "3"
    SubElement(head, "Stream").text = "6"
    SubElement(head, "Function").text = "11"

    ## BODY
    body = SubElement(root, "BODY")
    SubElement(body, "CEID").text = str(_CEID)
    reports = SubElement(body, "REPORTS")

    ## REPORT
    report = SubElement(reports, "REPORT")
    SubElement(body, "REPORTID").text = "200"
    variables = SubElement(report, "VARIABLES")
    SubElement(variables, "LOT_ID").text = _LOTID

    indent(root)  # indent() : XML 형식으로 보기 좋게 만들어주는 함수
    dump(root)  # dump 함수는 인자로 넘어온 tag 이하를 print 해줌
    clientSock.send((root.text).encode('utf-8'))  # Server로 데이터 전송
    print(root.text)
    def generate_cfg(self):
        sumocfg = ET.Element('configuration')
        inputXML = ET.SubElement(sumocfg, 'input')
        inputXML.append(
            E('net-file', attrib={'value': self.file_name + '.net.xml'}))
        indent(sumocfg)
        if os.path.exists(
                os.path.join(self.current_path, self.file_name + '.rou.xml')):
            inputXML.append(
                E('route-files', attrib={'value':
                                         self.file_name + '.rou.xml'}))
            indent(sumocfg)

        if os.path.exists(
                os.path.join(self.current_path, self.file_name + '.add.xml')):
            inputXML.append(
                E('add-file', attrib={'value': self.file_name + '.add.xml'}))
            indent(sumocfg)

        time = ET.SubElement(sumocfg, 'time')
        time.append(E('begin', attrib={'value': str(self.sim_start)}))
        indent(sumocfg)
        time.append(E('end', attrib={'value': str(self.sim_end)}))
        indent(sumocfg)
        outputXML = ET.SubElement(sumocfg, 'output')
        # outputXML.append(
        #     E('netstate-dump', attrib={'value': self.file_name+'_dump.net.xml'}))
        indent(sumocfg)
        dump(sumocfg)
        tree = ET.ElementTree(sumocfg)
        tree.write(self.file_name + '_simulate' + '.sumocfg',
                   pretty_print=True,
                   encoding='UTF-8',
                   xml_declaration=True)
예제 #3
0
def set_base_xml(index_list, all_text_list):
    root = Element("Sheet")
    df = pd.DataFrame(all_text_list)
    SubElement(root, 'head').text = ",".join(index_list['index'])
    for i, i_name in enumerate(index_list['index']):

        #if i_name == 'B5':
        if all_text_list:
            sort_text, df = sort_in_cell(index_list['value'][i], df)
        else:
            sort_text = []
        #셀 노드 추가
        cell_element = Element("".join(map(str, i_name)))
        root.append(cell_element)
        head_list = []
        for i in range(len(sort_text)):
            head_list.append(i + 1)
        #if sort_text:
        SubElement(cell_element, 'head').text = ",".join(map(str, head_list))
        #셀노드의 텍스트 노드 추가 없으면 빈 노드가 됨.
        for i in range(len(sort_text)):
            SubElement(cell_element, str(i + 1)).text = ",".join(sort_text[i])
        #SubElement(root, "".join(map(str, i_name))).text = ",".join(sorted_text[i])

    indent(root)
    dump(root)
    return root
예제 #4
0
    def submit(self):
        self.set_time()
        print('<?xml version="1.0" ?>' + self.xml_root_node.tostring())
        response = requests.post(url,
                                 data=prefix + self.xml_root_node.tostring(),
                                 headers={'Content-Type': 'text/xml'})
        # return response.status_code, response.text

        # self.response_code = response.status_code
        self.xml_response_root = fromstring(response.text)
        path = xpath([(ns0, 'Body'), (ns1, self.__service + 'Response'),
                      (None, 'Answer')])
        answer = self.xml_response_root.findall(path)[0]
        if answer is None:
            print("Error: NoneType for ElementTree")
            return
        # print('ANSWER:')
        dump(answer)
        path = xpath([(ns_siri, 'Status')])
        status = answer.findall(path)[0]
        # print(status)
        if not status.text == 'true':
            path = xpath([(ns_siri, 'ErrorCondition'),
                          (ns_siri, 'Description')])
            description = answer.findall(path)[0]
            print("Request failed: " + description.text)
            raise SIRIFailure()

        StopMonitoringDeliveries = []

        for smd in answer.findall(xdir(ns_siri, 'StopMonitoringDelivery')):
            StopMonitoringDeliveries.append(smd)

        return StopMonitoringDeliveries
예제 #5
0
    def _generate_rou_xml(self):
        self.flows = self.specify_flow()
        self.routes = self.specify_route()
        self.vTypes = self.specify_vType()
        route_xml = ET.Element('routes')
        if len(self.vTypes) != 0:
            for _, vType_dict in enumerate(self.vTypes):
                route_xml.append(E('vType', attrib=vType_dict))
                indent(route_xml, 1)
        if len(self.routes) != 0:
            for _, route_dict in enumerate(self.routes):
                route_xml.append(E('route', attrib=route_dict))
                indent(route_xml, 1)
        if len(self.flows) != 0:
            for _, flow_dict in enumerate(self.flows):
                route_xml.append(E('flow', attrib=flow_dict))
                indent(route_xml, 1)

        dump(route_xml)
        tree = ET.ElementTree(route_xml)
        tree.write(os.path.join(self.current_Env_path,
                                self.file_name + '.rou.xml'),
                   pretty_print=True,
                   encoding='UTF-8',
                   xml_declaration=True)
def tl_logic(file_path):
    ids=str()
    # file load
    tree = parse(file_path)
    # file write setup
    tl_additional_default = ET.Element('additional')
    tl_additional = ET.Element('additional')

    # find and write
    trafficSignalList = tree.findall('trafficSignal')
    # trafficSignal내에서 찾음
    for trafficSignal in trafficSignalList:
        TODPlan = trafficSignal.findall('TODPlan')
        scheduleList = trafficSignal.findall('schedule')
        # 찾고싶은 id를 여기서 start time을 적고 넣으시오
        for plan in TODPlan[0].findall('plan'):
            if plan.attrib['startTime'] == '9000':  # 9시 25200 # 2시반? 9000
                ids = plan.attrib['schedule']

        # schedule들 내에서 찾는 과정
        for schedule in scheduleList:
            # node id 교체
            if TODPlan[0].attrib['defaultPlan'] == schedule.attrib['id']:  # default
                schedule.attrib['programID']=schedule.attrib['id']
                schedule.attrib['id'] = trafficSignal.attrib['nodeID']
                schedule.attrib['type']='static'
                tlLogic_default = ET.SubElement(
                    tl_additional_default, 'tlLogic', attrib=schedule)
                phase_set = schedule.findall('phase')
                for phase in phase_set:
                    phase_dict = dict()
                    for key in phase.keys():
                        phase_dict[key] = phase.attrib[key]
                    tlLogic_default.append(E('phase', attrib=phase_dict))

            if ids == schedule.attrib['id']:
                schedule.attrib['programID']=schedule.attrib['id']
                schedule.attrib['id'] = trafficSignal.attrib['nodeID']
                schedule.attrib['type']='static'
                tlLogic = ET.SubElement(
                    tl_additional, 'tlLogic', attrib=schedule)
                phase_set = schedule.findall('phase')
                for phase in phase_set:
                    phase_dict = dict()
                    for key in phase.keys():
                        phase_dict[key] = phase.attrib[key]
                    tlLogic.append(E('phase', attrib=phase_dict))

    print("end")

    dump(tl_additional_default)
    writetree = ET.ElementTree(tl_additional_default)
    writetree.write(os.path.join('./output_default_tl.add.xml'),
                    pretty_print=True, encoding='UTF-8', xml_declaration=True)
    writetree = ET.ElementTree(tl_additional)
    writetree.write(os.path.join('./output_tl.add.xml'),
                    pretty_print=True, encoding='UTF-8', xml_declaration=True)
    print(scheduleList)
예제 #7
0
def _log_xml(xml):
    try:
        xml.attrib
    except AttributeError:
        log.error('Did not receive an XML. Answer was: %s' % xml)
    else:
        from xml.etree.ElementTree import dump
        log.error('XML received from the PMS:')
        dump(xml)
 def recordTrainInformation(self, trainingEpochs, batchSize, minCost,
                            maxAccuracy, elapsedTime):
     note = Element("TrainingInformation")
     SubElement(note, "TrainingEpochs").text = str(trainingEpochs)
     SubElement(note, "BatchSize").text = str(batchSize)
     SubElement(note, "MinCost").text = str(minCost)
     SubElement(note, "MaxAccuracy").text = str(maxAccuracy)
     SubElement(note, "ElapsedTime").text = str(elapsedTime)
     dump(note)
     ElementTree(note).write(self.model_dir + "training_imformation.xml")
예제 #9
0
def xml_func(Input):

    now = datetime.datetime.now()
    nowdate = now.strftime('%Y-%m-%d')
    nowTime = now.strftime('%H:%M:%S')
    #root
    root = Element("Vulnerable_list ")
    root.attrib["Date"] = nowdate + " / " + nowTime
    #child
    if Input[0] is not None:
        for xx in range(0, len(Input[0][0])):

            Integrity = Element("Integrity")
            SubElement(Integrity, "I_child").text = Input[0][0][xx]
            root.append(Integrity)

    if Input[1] is not None:

        for xx1 in range(0, len(Input[1][0])):

            HardCoded = Element("HardCoded")
            SubElement(HardCoded, "H_child").text = Input[1][0][xx1]
            root.append(HardCoded)

    if Input[2] is not None:

        for xx2 in range(0, len(Input[2][0])):

            External_Library = Element("External_Library")
            SubElement(External_Library, "E_child").text = Input[2][0][xx2]
            root.append(External_Library)

    #indent method
    def indent(elem, level=0):
        i = "\n" + level * "  "
        if len(elem):
            if not elem.text or not elem.text.strip():
                elem.text = i + "  "
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
            for elem in elem:
                indent(elem, level + 1)
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
        else:
            if level and (not elem.tail or not elem.tail.strip()):
                elem.tail = i

    ElementTree(root).write('plc.xml',
                            xml_declaration=True,
                            method='xml',
                            encoding='UTF-8')

    indent(root)
    dump(root)
예제 #10
0
def build_zone_xml():
    test_string = """<source_model_zone magnitude_type="Mw">
  <zone 
  area = "5054.035" 
  name = "bad zone">
    
    <geometry 
       azimuth= "6" 
       delta_azimuth= "2" 
       dip= "15"
       delta_dip = "5"
       depth_top_seismogenic = "7"
       depth_bottom_seismogenic = "30">
      <boundary>
	  -32.4000 151.1500   
	  -32.7500 152.1700 
	  -33.4500 151.4300   
	  -32.4000 151.1500 
      </boundary>
      <excludes>
	  -32.4000 151.1500     
	  -32.7500 152.1700    
	  -33.4500 151.4300  
      </excludes>
    </geometry>
    
    <recurrence_model
      distribution = "bounded_gutenberg_richter"
      recurrence_min_mag = "3.3" 
      recurrence_max_mag = "5.4" 
      A_min= "0.568" 
      b = "1">
      <event_generation 
      generation_min_mag = "3.3"
	  number_of_mag_sample_bins = "15" 
	  number_of_events = "1000" />
    </recurrence_model>
    
    <ground_motion_models 
       fault_type = "normal" 
       ground_motion_selection = "crustal fault" />   
  </zone>
</source_model_zone>
"""

    test_string = "<source_model_zone>yeah</source_model_zone>"

    element = ET.XML("<root><child>One</child><child>Two</child></root>")
    dump(element)
    for subelement in element:
        print subelement.text

    tree = None  # ET.XML()

    return tree
예제 #11
0
def build_zone_xml():
    test_string = """<source_model_zone magnitude_type="Mw">
  <zone 
  area = "5054.035" 
  name = "bad zone">
    
    <geometry 
       azimuth= "6" 
       delta_azimuth= "2" 
       dip= "15"
       delta_dip = "5"
       depth_top_seismogenic = "7"
       depth_bottom_seismogenic = "30">
      <boundary>
	  -32.4000 151.1500   
	  -32.7500 152.1700 
	  -33.4500 151.4300   
	  -32.4000 151.1500 
      </boundary>
      <excludes>
	  -32.4000 151.1500     
	  -32.7500 152.1700    
	  -33.4500 151.4300  
      </excludes>
    </geometry>
    
    <recurrence_model
      distribution = "bounded_gutenberg_richter"
      recurrence_min_mag = "3.3" 
      recurrence_max_mag = "5.4" 
      A_min= "0.568" 
      b = "1">
      <event_generation 
      generation_min_mag = "3.3"
	  number_of_mag_sample_bins = "15" 
	  number_of_events = "1000" />
    </recurrence_model>
    
    <ground_motion_models 
       fault_type = "normal" 
       ground_motion_selection = "crustal fault" />   
  </zone>
</source_model_zone>
"""

    test_string = '<source_model_zone>yeah</source_model_zone>'

    element = ET.XML("<root><child>One</child><child>Two</child></root>")
    dump(element)
    for subelement in element:
        print subelement.text

    tree = None  #ET.XML()

    return tree
예제 #12
0
    def generate_cfg(self, route_exist, mode='simulate'):
        self._generate_nod_xml()
        self._generate_edg_xml()
        self._generate_add_xml()
        self._generate_net_xml()
        sumocfg = ET.Element('configuration')
        inputXML = ET.SubElement(sumocfg, 'input')
        inputXML.append(
            E('net-file', attrib={'value': self.file_name + '.net.xml'}))
        indent(sumocfg)
        if route_exist == True:
            self._generate_rou_xml()
            if os.path.exists(
                    os.path.join(self.current_Env_path,
                                 self.file_name + '.rou.xml')):
                inputXML.append(
                    E('route-files',
                      attrib={'value': self.file_name + '.rou.xml'}))
                indent(sumocfg)

        if os.path.exists(
                os.path.join(self.current_Env_path,
                             self.file_name + '_data.add.xml')):
            inputXML.append(
                E('additional-files',
                  attrib={'value': self.file_name + '_data.add.xml'}))
            indent(sumocfg)

        time = ET.SubElement(sumocfg, 'time')
        time.append(E('begin', attrib={'value': str(self.sim_start)}))
        indent(sumocfg)
        time.append(E('end', attrib={'value': str(self.max_steps)}))
        indent(sumocfg)
        outputXML = ET.SubElement(sumocfg, 'output')
        indent(sumocfg)
        dump(sumocfg)
        tree = ET.ElementTree(sumocfg)
        if mode == 'simulate':
            tree.write(os.path.join(self.current_Env_path,
                                    self.file_name + '_simulate.sumocfg'),
                       pretty_print=True,
                       encoding='UTF-8',
                       xml_declaration=True)
        elif mode == 'test':
            tree.write(os.path.join(self.current_Env_path,
                                    self.file_name + '_test.sumocfg'),
                       pretty_print=True,
                       encoding='UTF-8',
                       xml_declaration=True)
        elif mode == 'train' or mode == 'train_old':
            tree.write(os.path.join(self.current_Env_path,
                                    self.file_name + '_train.sumocfg'),
                       pretty_print=True,
                       encoding='UTF-8',
                       xml_declaration=True)
예제 #13
0
    def addsite(self):
        text, ok = QInputDialog.getText(self, "사이트 추가", "사이트 이름 : ")
        if ok:
            newNode = Element("site", name=text)

            self.root.append(newNode)
            dump(self.root)

            ElementTree(self.root).write("config.xml")

            self.initUI()
예제 #14
0
def print_out_paper_info(paper_info_list, out_file='book.xml'):
    ele_tree = ElementTree()
    root_paper_tree = Element('PAPERS')
    ele_tree._setroot(root_paper_tree)
    for paper_info in paper_info_list:
        temp_paper_ele = Element('PAPER')
        for key, value in paper_info.items():
            if key == 'author_list': value = '_'.join(value)
            SubElement(temp_paper_ele, key).text = value
        root_paper_tree.append(temp_paper_ele)
    dump(indent(root_paper_tree))
    ele_tree.write(out_file, "utf-8")
예제 #15
0
def to_tag(tagText, nowDate, fileName):
    fileNameTag = Element(fileName)
    fileNameTag.attrib["result"] = nowDate
    for tagNum in range(0, len(tagText), 1):
        error = Element("error")
        error.attrib["File"] = tagText[tagNum][0]
        fileNameTag.append(error)
        SubElement(error, "Location").text = "line " + tagText[tagNum][1]
        SubElement(error, "Description").text = tagText[tagNum][2]
    indent(fileNameTag)
    dump(fileNameTag)
    return fileNameTag
예제 #16
0
def to_tag(tagText, nowDate, fileName):
    fileNameTag = Element(fileName)
    fileNameTag.attrib["result"] = nowDate
    for tagNum in range(0, len(tagText), 1):
        error = Element("error")
        error.attrib["File"] = tagText[tagNum][0]
        fileNameTag.append(error)
        SubElement(error, "Location").text = "line " + tagText[tagNum][1]
        SubElement(error, "Description").text = tagText[tagNum][2]
    indent(fileNameTag)
    dump(fileNameTag)
    return fileNameTag
 def createModelInformationXML(self):
     note = Element("ModelSetting")
     to = Element("ModelName")
     to.text = self.args.load_folder_file[1]
     note.append(to)
     SubElement(note, "FeatureWidth").text = str(self.args.feature_shape[0])
     SubElement(note,
                "FeatureHeight").text = str(self.args.feature_shape[1])
     SubElement(note, "LabelSize").text = str(self.args.label_size)
     dump(note)
     ElementTree(note).write(self.model_dir +
                             self.args.load_folder_file[1] + ".xml")
예제 #18
0
def writeSelectedProject(info):
    book = ElementTree()
    parent = Element("ProjectInfo")
    book._setroot(parent)
    item = Element("project")
    parent.append(item)
    SubElement(item, "id").text = info["id"]
    SubElement(item, "name").text = info["name"]
    dump(indent(parent))
    if not os.path.exists(confPath.localXml):
        os.makedirs(confPath.localXml)
    book.write(confPath.localXml + "selectedProject.xml", "utf-8")
예제 #19
0
    def generate_cfg(self, route_exist, mode='simulate'):
        '''
        if all the generation over, inherit this function by `super`.
        '''
        sumocfg = ET.Element('configuration')
        inputXML = ET.SubElement(sumocfg, 'input')
        inputXML.append(
            E('net-file',
              attrib={
                  'value':
                  os.path.join(self.current_Env_path,
                               self.file_name + '.net.xml')
              }))
        indent(sumocfg)
        if route_exist == True:
            self._generate_rou_xml()
            if os.path.exists(
                    os.path.join(self.current_Env_path,
                                 self.file_name + '.rou.xml')):
                inputXML.append(
                    E('route-files',
                      attrib={
                          'value':
                          os.path.join(self.current_Env_path,
                                       self.file_name + '.rou.xml')
                      }))
                indent(sumocfg)

        if os.path.exists(
                os.path.join(self.current_Env_path,
                             self.file_name + '_data.add.xml')):
            inputXML.append(
                E('additional-files',
                  attrib={
                      'value':
                      os.path.join(self.current_Env_path,
                                   self.file_name + '_data.add.xml')
                  }))
            indent(sumocfg)

        time = ET.SubElement(sumocfg, 'time')
        time.append(E('begin', attrib={'value': str(self.sim_start)}))
        indent(sumocfg)
        time.append(E('end', attrib={'value': str(self.max_steps)}))
        indent(sumocfg)
        dump(sumocfg)
        tree = ET.ElementTree(sumocfg)
        tree.write(os.path.join(self.current_Env_path,
                                self.file_name + '.sumocfg'),
                   pretty_print=True,
                   encoding='UTF-8',
                   xml_declaration=True)
예제 #20
0
 def _generate_edg_xml(self):
     self.edges = self.specify_edge()
     edg_xml = ET.Element('edges')
     for _, edge_dict in enumerate(self.edges):
         edg_xml.append(E('edge', attrib=edge_dict))
         indent(edg_xml, 1)
     dump(edg_xml)
     tree = ET.ElementTree(edg_xml)
     tree.write(os.path.join(self.current_Env_path,
                             self.file_name + '.edg.xml'),
                pretty_print=True,
                encoding='UTF-8',
                xml_declaration=True)
예제 #21
0
def writeLoginInfo(info):
    book = ElementTree()
    parent = Element("LoginInfo")
    book._setroot(parent)
    item = Element("user")
    parent.append(item)
    SubElement(item, "id").text = info["userID"]
    SubElement(item, "name").text = info["userName"]
    SubElement(item, "editRole").text = info["editRole"]
    dump(indent(parent))
    if not os.path.exists(confPath.localXml):
        os.makedirs(confPath.localXml)
    book.write(confPath.localXml + "loginInfo.xml", "utf-8")
예제 #22
0
def send_s2f42(_systembyte, _hcack):
    root = Element('SECS2_XML_MESSAGE')
    head = SubElement(root, "HEAD")
    SubElement(head, "SystemByte").text = str(_systembyte)
    SubElement(head, "CMD").text = "3"
    SubElement(head, "Stream").text = "2"
    SubElement(head,"Function").text = "42"

    body = SubElement(root, "BODY")
    SubElement(body, "HCACK").text = str(_hcack)
    indent(root)    # xml 파일 보기좋게 만들기
    dump(root)      
    print(root.text)
예제 #23
0
def datatoxml(xlsdata):
	xml = ElementTree()
	Students = Element('Students')
	xml._setroot(Students)
	for i in range(0,len(xlsdata)):
		Student = Element('Student',{'Name':xlsdata[i][1]})
		Students.append(Student)
		Scores = Element('Scores')
		Student.append(Scores)
		SubElement(Scores,'math').text= xlsdata[i][2]
		SubElement(Scores,'Yuwen').text = xlsdata[i][3]
		SubElement(Scores,'English').text = xlsdata[i][4]
	dump(indent(Students))
	return xml
 def generate_edg_xml(self):
     self.specify_edge()
     self.xml_edg_pos = os.path.join(self.current_path, self.xml_edg_name)
     edg_xml = ET.Element('edges')
     for _, edge_dict in enumerate(self.edges):
         edg_xml.append(E('edge', attrib=edge_dict))
         indent(edg_xml)
     dump(edg_xml)
     tree = ET.ElementTree(edg_xml)
     # tree.write(self.xml_edg_pos+'.xml',encoding='utf-8',xml_declaration=True)
     tree.write(self.xml_edg_pos + '.xml',
                pretty_print=True,
                encoding='UTF-8',
                xml_declaration=True)
예제 #25
0
    def _generate_nod_xml(self):
        self.nodes = self.specify_node()
        nod_xml = ET.Element('nodes')

        for node_dict in self.nodes:
            nod_xml.append(E('node', attrib=node_dict))
            indent(nod_xml, 1)
        dump(nod_xml)
        tree = ET.ElementTree(nod_xml)
        tree.write(os.path.join(self.current_Env_path,
                                self.file_name + '.nod.xml'),
                   pretty_print=True,
                   encoding='UTF-8',
                   xml_declaration=True)
예제 #26
0
def read_element():
    tree = ET.parse('sample2.xml')
    root = tree.getroot()

    print('ogrigianl----')
    dump(tree)
    for rank in root.iter('rank'):
        print(rank.get('updated'))
        new_rank = int(rank.text) + 1
        rank.text = str(new_rank)
        rank.set('updated New', 'yes')

    print('after----')
    dump(tree)
예제 #27
0
def writeSelectedFile(info):
    book = ElementTree()
    parent = Element("FileInfo")
    book._setroot(parent)
    item = Element("file")
    parent.append(item)
    SubElement(item, "project_id").text = info["project_id"]
    SubElement(item, "entity_type").text = info["entity_type"]
    SubElement(item, "entity_id").text = info["entity_id"]
    SubElement(item, "task_id").text = info["task_id"]
    dump(indent(parent))
    if not os.path.exists(confPath.localXml):
        os.makedirs(confPath.localXml)
    book.write(confPath.localXml + "selectedFile.xml", "utf-8")
예제 #28
0
    def onClickAdd(self):
        text, ok = QInputDialog.getText(self, "CCTV 추가", "CCTV URI : ")
        if ok:
            node = self.tree.find('.//site[@name="' + self.names[self.idx] +
                                  '"]')
            newNode = Element("uri")
            newNode.text = text

            node.append(newNode)
            dump(self.root)

            ElementTree(self.root).write("config.xml")
            self.initXmlData()
            self.setTableData(self.idx)
예제 #29
0
def newProjectTree():
    project = Element("project")
    project.set("name", "")
    project.set("path", "")
    project.set("project_path", "")
    project.set("filename", "")
    # todo: add further attributes
    tilesets = SubElement(project, "tilesets")
    tilesets.set("path", Paths.D_TILESETS)
    maps = SubElement(project, "maps")
    maps.set("path", Paths.D_MAPS)
    # todo: add further SubElements for other game-features like sound, items and stuff.
    project_tree = ElementTree(project)
    dump(project)
    return project_tree
예제 #30
0
def writeSelectedRef(info):
    book = ElementTree()
    parent = Element("RefInfo")
    book._setroot(parent)
    item = Element("ref")
    parent.append(item)
    SubElement(item, "tab").text = info["tab"]
    SubElement(item, "parent").text = info["parent"]
    SubElement(item, "selectedNode").text = info["currentNode"]
    SubElement(item, "listIndex").text = info["listIndex"]
    SubElement(item, "inputText").text = info["text"]
    dump(indent(parent))
    if not os.path.exists(confPath.localXml):
        os.makedirs(confPath.localXml)
    book.write(confPath.localXml + "SelectedRef.xml", "utf-8")
예제 #31
0
def makeTag(tagText, nowDate):
    code_analysis = Element("code_analysis")
    code_analysis.attrib["result"] = nowDate
    for tagNum in range(0, len(tagText), 1):
        error = Element("error")
        error.attrib["File"] = tagText[tagNum][0]
        code_analysis.append(error)
        SubElement(error, "Location").text = "line " + tagText[tagNum][1]
        SubElement(error, tagText[tagNum][3]).text = tagText[tagNum][2]
        if len(tagText[tagNum]) > 4:
            for i in range(4, len(tagText[tagNum]) - 4, 1):
                SubElement(error, tagText[tagNum][3]).text = tagText[tagNum][i]
    indent(code_analysis)
    dump(code_analysis)
    return code_analysis
예제 #32
0
def makeTag(tagText, nowDate):
    code_analysis = Element("code_analysis")
    code_analysis.attrib["result"] = nowDate
    for tagNum in range(0, len(tagText), 1):
        error = Element("error")
        error.attrib["File"] = tagText[tagNum][0]
        code_analysis.append(error)
        SubElement(error, "Location").text = "line " + tagText[tagNum][1]
        SubElement(error, tagText[tagNum][3]).text = tagText[tagNum][2]
        if len(tagText[tagNum]) > 4:
            for i in range(4, len(tagText[tagNum]) - 4, 1):
                SubElement(error, tagText[tagNum][3]).text = tagText[tagNum][i]
    indent(code_analysis)
    dump(code_analysis)
    return code_analysis
예제 #33
0
    def _generate_con_xml(self):
        self.cons = self.specify_connection()
        con_xml = ET.Element('connections')
        if len(self.connections) != 0:  # empty
            for _, connection_dict in enumerate(self.connections):
                con_xml.append(E('connection', attrib=connection_dict))
                indent(con_xml, 1)

        dump(con_xml)
        tree = ET.ElementTree(con_xml)
        tree.write(os.path.join(self.current_Env_path,
                                self.file_name + '.con.xml'),
                   pretty_print=True,
                   encoding='UTF-8',
                   xml_declaration=True)
예제 #34
0
def convert_w360dp_xxxhdpi(list, resource, file_path):
    for k in list:
        parsing_type = k[0]
        parsing_name = k[1]
        parsing_value = k[2]
        dimen = SubElement(resource, parsing_type)
        dimen.attrib["name"] = parsing_name
        comment = None
        if k[0] == "px_1":
            comment = Comment(" Default screen margins, per the Android Design guidelines. ")
            resource.append(comment)
            comment = Comment(" noti ")
        elif k[0] == "noti_main_balance":
            comment = Comment(" Default screen margins, per the Android Design guidelines. ")
        elif k[0] == "noti_divider":
            comment = Comment(" START Apple Offer ")
        elif k[0] == "cpi_term_and_condition_container_height":
            comment = Comment(" END Apple Offer ")

        if comment is not None:
            resource.append(comment)

        if parsing_type == "string" or parsing_type == u'string':
            dimen.text = parsing_value
        if parsing_type == "dimen" or parsing_type == u'string':
            value = parsing_value[:-2]
            unit = parsing_value[-2:]
            if unit == "dp" or unit == u'dp':
                dp = round(float(value) * xxdhpi, 2)
                result = str(dp) + "dp"
                dimen.text = result
            elif unit == "px" or unit == u'px':
                px = round(float(value) * xxdhpi)
                result = str(px) + "px"
                dimen.text = result

    indent(resource)
    dump(resource)
    doc = ElementTree(resource)
    if not path.isdir(file_path[:file_path.find("/dimens.xml")]):
        mkdir(file_path[:file_path.find("/dimens.xml")])
    doc.write(file_path, encoding="utf-8")
    xdhpi_path = file_path[:file_path.find("/values-xxhdpi")] + "/values-xhdpi/dimens.xml"
    if not path.isdir(xdhpi_path[:file_path.find("/dimens.xml")]):
        mkdir(xdhpi_path[:file_path.find("/dimens.xml")])
    doc.write(xdhpi_path, encoding="utf-8")
 def generate_rou_xml(self):
     self.specify_flow()
     route_xml = ET.Element('routes')
     if len(self.vehicles) != 0:  # empty
         for _, vehicle_dict in enumerate(self.vehicles):
             route_xml.append(E('veh', attrib=vehicle_dict))
             indent(route_xml)
     if len(self.flows) != 0:
         for _, flow_dict in enumerate(self.flows):
             route_xml.append(E('flow', attrib=flow_dict))
             indent(route_xml)
     dump(route_xml)
     tree = ET.ElementTree(route_xml)
     tree.write(self.xml_route_pos + '.xml',
                pretty_print=True,
                encoding='UTF-8',
                xml_declaration=True)
예제 #36
0
def Save2XML(appName,cfgName):

    dic = iniCfg.GetConfig(cfgName)
    
    eTree = ElementTree()
    
    root = Element(appName)
    eTree._setroot(root)
    for subDic in dic:
        pos = subDic.find('.')
        #print "'"+skey[pos+1:]+"':{'en':"+skey[pos+1:]+"','cn':''},"
        sec =subDic[:pos]
        skey=subDic[pos+1:]
        #print 'sec:'+TransStr(sec)
        #print "____key:"+TransStr(skey)+"="+dic[subDic]
        SubElement(root,subDic,{"text":TransStr(skey),"desc":subDic,"category":TransStr(sec)}).text=dic[subDic]
    dump(indent(root))    
    eTree.write(appName+".xml","utf-8")
예제 #37
0
def print_out_xml(out_file='book.xml'):
    book = ElementTree()

    purchaseorder = Element('RECORDS')
    book._setroot(purchaseorder)

    purchaseorder2 = Element('RECORD')
    SubElement(purchaseorder2, 'id').text = 'aaaa'
    SubElement(purchaseorder2, 'article').text = 'bbbb'

    purchaseorder3 = Element('RECORD')
    SubElement(purchaseorder3, 'id').text = 'aaaa'
    SubElement(purchaseorder3, 'article').text = 'bbbb'
    purchaseorder.append(purchaseorder2)
    purchaseorder.append(purchaseorder3)

    dump(indent(purchaseorder))
    book.write(out_file, "utf-8")
예제 #38
0
def Send_s2f42(_SystemByte, _Hcack):
    clientSock = connToServer("127.0.0.1", 8099)  # 서버에 접속
    root = Element("SECS2_XML_MESSAGE")

    ## HEAD
    head = SubElement(root, "HEAD")
    SubElement(head, "SystemByte").text = str(_SystemByte)
    SubElement(head, "CMD").text = "3"
    SubElement(head, "Stream").text = "2"
    SubElement(head, "Function").text = "42"

    ## BODY
    body = SubElement(root, "BODY")
    SubElement(body, "HCACK").text = str(_Hcack)

    indent(root)  # indent() : XML 형식으로 보기 좋게 만들어주는 함수
    dump(root)  # dump 함수는 인자로 넘어온 tag 이하를 print 해줌
    clientSock.send((root.text).encode('utf-8'))  # Server로 데이터 전송
    print(root.text)
    def generate_nod_xml(self):
        self.specify_node()
        self.xml_nod_pos = os.path.join(self.current_path, self.xml_node_name)
        nod_xml = ET.Element('nodes')

        for node_dict in self.node:
            # node_dict['x']=format(node_dict['x'],'.1f')
            nod_xml.append(E('node', attrib=node_dict))
            indent(nod_xml)
        '''
        for node_attributes in nodes:
            x.append(E('node', **node_attributes))
        '''
        dump(nod_xml)
        tree = ET.ElementTree(nod_xml)
        # tree.write(self.xml_nod_pos+'.xml',encoding='utf-8',xml_declaration=True)
        tree.write(self.xml_nod_pos + '.xml',
                   pretty_print=True,
                   encoding='UTF-8',
                   xml_declaration=True)
예제 #40
0
import sys
from xml.etree.ElementTree import ElementTree, dump

tree = ElementTree()
tree.parse(sys.argv[1])

tree.find('module/param[@name="whiteList"]')[0].text = sys.argv[2]

dump(tree)
    last_day = args.grab_offset + args.grab_days
    if last_day > 6:
        last_day = 6

    threads = list()
    for d in range(args.grab_offset, last_day):
        t = threading.Thread(target=parse_day, args=(d, OBJ_XMLTV, rawclist))
        threads.append(t)
        t.start()

    [x.join() for x in threads]

    # A standard grabber should print the xmltv file to the stdout or to
    # filename if called with option --output filename
    if args.filename:
        FILE_XML = args.filename
        ElementTree(OBJ_XMLTV).write(FILE_XML, encoding="UTF-8")
    else:
        dump(ElementTree(OBJ_XMLTV))

    logger.info(
        "Grabbed "
        + str(len(OBJ_XMLTV.findall("channel")))
        + " channels and "
        + str(len(OBJ_XMLTV.findall("programme")))
        + " programmes"
    )

exit()
예제 #42
0
def VerifyServerSettings(xmlPath, studyName, clusterNum):
	errorString = ""
	passString = ""
	fullTree = ElementTree()
	fullTree.parse(xmlPath)
	serverSettingsTree = fullTree.find("serverSettings")

	"""Staging server information is stored and validated in the next set of statements"""
	stagingSettings = serverSettingsTree.find("stagingSettings")
	stagingStudyServer = stagingSettings.find("studyServer")
	if (stagingStudyServer.attrib["login"] != ("LP_" + studyName)):
		errorString += "FAIL - Staging server settings (login information) are incorrect. Please contact the PDE for this study to fix this.\n"
	if (stagingStudyServer.attrib["address"] != "stagesw.phtstudy.com:29748"):
		if (stagingStudyServer.attrib["address"] != "stagevmweb2.phtstudy.com:29748"):
			errorString += "FAIL - Staging server settings (server address) are incorrect. Please contact the PDE for this study to fix this.\n"
	if (stagingStudyServer.attrib["database"] != (studyName)):
		errorString += "FAIL - Staging server settings (database) are incorrect. Please contact the PDE for this study to fix this.\n"
	stagingLogServer = stagingSettings.find("logServer")
	if (stagingLogServer.attrib["address"] != "http://englogserver.phtstudy.com:29564/StagingLogs/servlet/LogServer"):
		errorString += "FAIL - Staging server settings (Log Server) are incorrect. Please contact the PDE for this study to fix this.\n"
	stagingProvisioningServer = stagingSettings.find("provisioningServer")
	if (stagingProvisioningServer.attrib["address"] != "https://stagepro01.phtstudy.com:443/sgserver"):
		errorString += "FAIL - Staging server settings (Provisioning Server) are incorrect. Please contact the PDE for this study to fix this.\n"
	passString += "PASS - Staging Settings are validated.\n"

	"""UST server information is stored and validated in the next set of statements"""
	USTSettings = serverSettingsTree.find("ustSettings")
	USTStudyServer = USTSettings.find("studyServer")
	if (USTStudyServer.attrib["login"] != ("LP_" + studyName + "_UST")):
	 	errorString += "FAIL - UST server settings (login information) are incorrect. Please contact the PDE for this study to fix this.\n"
	if (USTStudyServer.attrib["address"] != "myuststudysw.phtstudy.com:29748"):
		errorString += "FAIL - UST server settings (server address) are incorrect. Please contact the PDE for this study to fix this.\n"
	if (USTStudyServer.attrib["database"] != (studyName + "_UST")):
		errorString += "FAIL - UST server settings (database) are incorrect. Please contact the PDE for this study to fix this.\n"
	USTLogServer = USTSettings.find("logServer")
	if (USTLogServer.attrib["address"] != "http://naplogserv1.phtstudy.com:29564/USTLogs/servlet/LogServer"):
		errorString += "FAIL - UST server settings (Log Server) are incorrect. Please contact the PDE for this study to fix this.\n"
	USTProvisioningServer = USTSettings.find("provisioningServer")
	if (USTProvisioningServer.attrib["address"] != "https://napustpro01.phtstudy.com:443/sgserver"):
		errorString += "FAIL - UST server settings (Provisioning Server) are incorrect. Please contact the PDE for this study to fix this.\n"
	passString += "Pass - UST Settings are validated.\n"

	"""Production server information is stored and validated in the next set of statements"""
	productionSettings = serverSettingsTree.find("productionSettings")
	productionStudyServer = productionSettings.find("studyServer")
	if (productionStudyServer.attrib["login"] != ("LP_" + studyName)):
		errorString += "FAIL - Production server settings (login information) are incorrect. Please contact the PDE for this study to fix this.\n"
	if (clusterNum == "1"):
		if (productionStudyServer.attrib["address"] != "mystudysw.phtstudy.com:29748"):
			errorString += "FAIL - Production server settings (server address) are incorrect. Please verify you are using the correct cluster number, and then contact the PDE for this study to fix this.\n"
	if (clusterNum == "2"):
		if (productionStudyServer.attrib["address"] != "mystudysw2.phtstudy.com:29748"):
			errorString += "FAIL - Production server settings (server address) are incorrect. Please verify you are using the correct cluster number, and then contact the PDE for this study to fix this.\n"
	if (productionStudyServer.attrib["database"] != (studyName)):
		errorString += "FAIL - Production server settings (database) are incorrect. Please contact the PDE for this study to fix this.\n"
	productionLogServer = productionSettings.find("logServer")
	if (productionLogServer.attrib["address"] != "http://naplogserv1.phtstudy.com:29564/LogServer/servlet/LogServer"):
		errorString += "FAIL - Production server settings (Log Server) are incorrect. Please contact the PDE for this study to fix this.\n"
	productionProvisioningServer = productionSettings.find("provisioningServer")
	if (productionProvisioningServer.attrib["address"] != "https://nappro01.phtstudy.com:443/sgserver"):
		errorString += "FAIL - Production server settings (Provisioning Server) are incorrect. Please contact the PDE for this study to fix this.\n"
	passString += "Pass - Production Settings are validated"

	if (errorString != ""):
		raise RuntimeError(errorString)
	else:
		print passString
		print "Validated server settings (Objective Evidence)\n"
		dump(serverSettingsTree)
예제 #43
0
 def _dump_xml(self):
     """
     Debugging aid to dump XML so that we can see what we have.
     """
     return dump(self.custom_xml)
예제 #44
0
 def write(self,path):
     if path != None:
         dump(self.indent(self.root))
         self.tree.write(path,'utf-8')
예제 #45
0
note.append(to)
SubElement(note, "from").text = "Jani"
SubElement(note, "heading").text = "Reminder"
SubElement(note, "body").text = "Don't forget me this weekend!"


# dummy = Element("dummy")
# note.insert(1, dummy)
# note.remove(dummy)

def indent(elem, level=0):
    i = "\n" + level*"  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i

indent(note)
dump(note)
ElementTree(note).write("note.xml")
# ElementTree(note).write("note.xml")
예제 #46
0
 def out(self):
     dump(self.root)
예제 #47
0
import sys
from xml.etree.ElementTree import iterparse, dump

author = sys.argv[1]
iparse = iterparse(sys.stdin, ['start', 'end'])

for event, elem in iparse:
    if event == 'start' and elem.tag == 'log':
        logNode = elem
        break

logentries = (elem for event, elem in iparse
                   if event == 'end' and elem.tag == 'logentry')

for logentry in logentries:
    if logentry.find('author').text == author:
        dump(logentry)
    logNode.remove(logentry)

#http://stackoverflow.com/questions/4499910/how-to-display-a-specific-users-commits-in-svn-log
예제 #48
0
print(purchaseorder.find('account'))      
print(purchaseorder.find('account').get('refnum'))
print(purchaseorder.findall('account')[0].get('refnum'))
print(purchaseorder.find('item/name'))
##print(purchaseorder.find('item/name').text)
## How to use ElementTree([element,] [file])
## 1. From standard XML element, it becomes root element
##print(ElementTree(item).getroot().find('name').text)
print(ElementTree(purchaseorder).getroot().find('name').text)
## 2. From XML file
##print(ElementTree(file='book.xml').getroot().find('item/description').text)
## Create an iterator
for element in purchaseorder.getiterator():
    print(element.tag)
## Get pretty look
def indent(elem, level=0):
    i = "\n" + level*"  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        for e in elem:
            indent(e, level+1)
        if not e.tail or not e.tail.strip():
            e.tail = i
    if level and (not elem.tail or not elem.tail.strip()):
        elem.tail = i
    return elem
if __name__=="__main__":
    dump(indent(purchaseorder))
    book.write('book1.xml',"utf-8")