Esempio n. 1
0
    def fix_linking_packages(self, package, dry=False):
        project = self.api.project
        file_list = self.api.get_filelist_for_package(package, project)
        # ignore linked packages
        if '_link' in file_list:
            return
        needed_links = set()
        # if there's a multibuild we assume all flavors are built
        # using multibuild. So any potential previous links have to
        # be removed ie set of needed_links left empty.
        if '_multibuild' not in file_list:
            for file in file_list:
                if file.endswith('.spec') and file != f'{package}.spec':
                    needed_links.add(file[:-5])
        local_links = set()
        for link in self.api.linked_packages(package):
            if link['project'] == project:
                local_links.add(link['package'])

        # Deleting all the packages that no longer have a .spec file
        for link in local_links - needed_links:
            print(f"Deleting package {project}/{link}")
            if dry:
                continue
            try:
                delete_package(self.api.apiurl,
                               project,
                               link,
                               msg=f"No longer linking to {package}")
            except HTTPError as err:
                if err.code == 404:
                    # the package link was not yet created, which was likely a mistake from earlier
                    pass
                else:
                    # If the package was there bug could not be delete, raise the error
                    raise

            # Remove package from Rings in case 2nd specfile was removed
            if self.api.ring_packages.get(link):
                delete_package(self.api.apiurl,
                               self.api.ring_packages.get(link),
                               link,
                               force=True,
                               msg="Cleanup package in Rings")

        for link in needed_links - local_links:
            # There is more than one .spec file in the package; link package containers as needed
            meta = ET.fromstring(
                source_file_load(self.api.apiurl, project, package, '_meta'))
            print(f"Creating new link {link}->{package}")
            if dry:
                continue

            meta.attrib['name'] = link
            bcnt = meta.find('bcntsynctag')
            if bcnt is None:
                bcnt = ET.SubElement(meta, 'bcntsynctag')
            bcnt.text = package
            devel = meta.find('devel')
            if devel is None:
                devel = ET.SubElement(meta, 'devel')
            devel.attrib['project'] = project
            devel.attrib['package'] = package

            source_file_save(self.api.apiurl, project, link, '_meta',
                             ET.tostring(meta))
            xml = f"<link package='{package}' cicount='copy' />"
            source_file_save(self.api.apiurl, project, link, '_link', xml)
Esempio n. 2
0
    def outputMeshVTU(cls):
        #from blenderScripts.Continuity.continuityShellAccess import getContVF
        #contVF = getContVF()

        # determine if elements are 2D
        elements2D = False
        try:
            cls.__elements[0][7]
        except IndexError as e:
            elements2D = True

        # top level header
        vtkFile = XML.Element("VTKFile",
                              type="UnstructuredGrid",
                              version="0.1",
                              byte_order="LittleEndian")
        # UnstructuredGrid top level
        unstructuredGrid = XML.SubElement(vtkFile, "UnstructuredGrid")

        # made of multiple independent pieces, this is the base geometry
        pieceBase = XML.SubElement(unstructuredGrid,
                                   "Piece",
                                   NumberOfPoints=str(len(cls.__vertices)),
                                   NumberOfCells=str(len(cls.__elements)))

        # contains points, cells, pointData(optional), cellData(optional)

        # points level, NumberOfComponents = length of a vertex definition
        points = XML.SubElement(pieceBase, "Points")
        pointString = []
        # all rows, columns 0, 1, 2
        for x, y, z in cls.__vertices[:, list(range(3))]:
            pointString.append("" + str(x) + " " + str(y) + " " + str(z) +
                               "\n")
        pointString = ''.join(pointString)
        dataArrayPoints = XML.SubElement(points,
                                         "DataArray",
                                         type="Float32",
                                         NumberOfComponents="3",
                                         format="ascii").text = pointString

        # cells level
        cells = XML.SubElement(pieceBase, "Cells")

        # connectivity of points to make the cells, all appended
        connectivityString = []
        for element in cls.__elements:
            cellString = None
            if (not elements2D):
                cellString = str(element[0]) + " " + str(
                    element[2]) + " " + str(element[3]) + " " + str(
                        element[1]) + " " + str(element[4]) + " " + str(
                            element[6]) + " " + str(element[7]) + " " + str(
                                element[5]) + "\n"
            else:
                cellString = str(element[0]) + " " + str(element[2]) + \
                    " " + str(element[3]) + " " + str(element[1]) + "\n"
            connectivityString.append(cellString)
        connectivityString = ''.join(connectivityString)
        dataArrayCellsConnectivity = XML.SubElement(
            cells,
            "DataArray",
            type="Int32",
            Name="connectivity",
            format="ascii").text = connectivityString

        # delimiters of where each cell definition ends, ex for a cell def of 4
        # points the first offset would be 4, then 8, then 12 and so on.
        offsetsString = []
        # 4 for quad, 8 for hexahedron
        elementOffsetIncrement = 4 if elements2D else 8
        elementOffsetNumber = elementOffsetIncrement
        while (elementOffsetNumber <=
               elementOffsetIncrement * len(cls.__elements)):
            offsetsString.append(str(elementOffsetNumber) + "\n")
            elementOffsetNumber += elementOffsetIncrement
        offsetsString = ''.join(offsetsString)
        dataArrayCellsOffsets = XML.SubElement(
            cells, "DataArray", type="Int32", Name="offsets",
            format="ascii").text = offsetsString

        # cell type of each cell in order 9 for quad, 12 for hexahedron
        cellType = "9\n" if elements2D else "12\n"
        cellTypesString = [cellType] * len(cls.__elements)
        cellTypesString = ''.join(cellTypesString)
        dataArrayCellsOffsets = XML.SubElement(
            cells, "DataArray", type="UInt8", Name="types",
            format="ascii").text = cellTypesString

        # pointData level, skip if no data fields
        if (len(cls.__vertices[0]) > 3):
            pointData = XML.SubElement(pieceBase, "PointData")
            for fieldVar in range(
                    3, len(cls.__vertices[0])
            ):  # these are the field variables that are not coordinates
                fieldString = []
                for i in range(len(cls.__vertices)):
                    fieldString.append(str(cls.__vertices[i, fieldVar]) + "\n")
                fieldString = ''.join(fieldString)
                field = XML.SubElement(
                    pointData,
                    "DataArray",
                    type="Float32",
                    Name="FieldVariable " + str(fieldVar - 2),
                    format="ascii"
                ).text = fieldString  # -2 in order to start numbering at 1 (for variable index 3)

        # get the tree starting at the root of the vtkFile level, then write to
        # file
        vtuFile = XML.ElementTree(vtkFile)
        vtuFile.write(cls.filename + ".vtu", xml_declaration=True)
Esempio n. 3
0
 def set_stem_dir(self, dir):
     stem_dir = etree.SubElement(self.current_note, "stem")
     stem_dir.text = dir
Esempio n. 4
0
    
    *tags* if specified is either a single allowable tag name or sequence of allowable alternatives

    *attrs* if specified is a sequence of required attributes, each of which may be a sequence of several allowable alternatives

    Raises :exc:`XMLError` if the requirements are not met.
    """
    ele = to_ele(x)
    if tags:
        if isinstance(tags, basestring):
            tags = [tags]
        if ele.tag not in tags:
            raise XMLError("Element [%s] does not meet requirement" % ele.tag)
    if attrs:
        for req in attrs:
            if isinstance(req, basestring): req = [req]
            for alt in req:
                if alt in ele.attrib:
                    break
            else:
                raise XMLError(
                    "Element [%s] does not have required attributes" % ele.tag)
    return ele


new_ele = lambda tag, attrs={}, **extra: ET.Element(qualify(tag), attrs, **
                                                    extra)

sub_ele = lambda parent, tag, attrs={}, **extra: ET.SubElement(
    parent, qualify(tag), attrs, **extra)
Esempio n. 5
0
    def any(self):

        match_1_element = xml.SubElement(self.match_element, "any")

        return self.root
Esempio n. 6
0
import json as j
with open("test.json") as json_format_file:
    d = j.load(json_format_file)
import xml.etree.cElementTree as e
r = e.Element("Employee")
e.SubElement(r, "Name").text = d["Name"]
e.SubElement(r, "Designation").text = d["Designation"]
e.SubElement(r, "Salary").text = str(d["Salary"])
e.SubElement(r, "Age").text = str(d["Age"])
project = e.SubElement(r, "Projects")
for z in d["Projects"]:
    e.SubElement(project, "Topic").text = z["Topic"]
    e.SubElement(project, "Category").text = z["Category"]
    e.SubElement(project, "Months").text = str(z["Months"])
a = e.ElementTree(r)
a.write("json_to_xml.xml")
Esempio n. 7
0
 def addSubElement(self, parentElem, name, value=None):
     childElem = ET.SubElement(parentElem, name)
     if value is not None:
         childElem.text = str(value)
     return childElem
Esempio n. 8
0
def math_and_row():
    math = eTree.Element('math')
    row = eTree.SubElement(math, 'mrow')
    yield math, row
Esempio n. 9
0
def test_matrix(math_and_row):
    math, row = math_and_row
    table = eTree.SubElement(row, 'mtable')

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'a'
    td = eTree.SubElement(tr, 'mtd')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'b'

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'c'
    td = eTree.SubElement(tr, 'mtd')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'd'

    assert _convert(math) == convert(r'\begin{matrix}a & b \\ c & d \end{matrix}')
Esempio n. 10
0
def bl_to_xml(region, xml_path, eval_type="baselines"):
    if "baselines" not in region:
        raise Exception("This takes in only a single region for now")

    baselines = region['baselines']
    textlines = region['textlines']

    if not os.path.exists(os.path.dirname(xml_path)) and len(os.path.dirname(xml_path)) > 0:
        os.makedirs(os.path.dirname(xml_path))

    root = ET.Element("PcGts")
    tree = ET.ElementTree(element=root)

    metadata = ET.SubElement(root, "Metadata")
    ET.SubElement(metadata, "Creator").text = "Fotini Simistira"
    ET.SubElement(metadata, "Created").text = "2016-06-17T08:11:03.128Z"
    ET.SubElement(metadata, "LastChange").text = "2017-02-14T13:47:41.020Z"

    page = ET.SubElement(root, "Page")
    page.attrib["imageWidth"] = "0"
    page.attrib['imageHeight'] = "0"
    page.attrib['imageFilename'] = ""

    text_region = ET.SubElement(page, "TextRegion")
    text_region.attrib['id'] = "region_textline"

    region_coords = ET.SubElement(text_region, "Coords")
    region_coords.attrib['points'] = pts_to_xml_str(region.get("bounding_poly", []))

    if eval_type == "baselines":
        for i, baseline in enumerate(region['baselines']):
            text_line = ET.SubElement(text_region, "TextLine")
            text_line.attrib['id'] = "textline_"+str(i)

            text_coords = ET.SubElement(text_line, "Coords")
            text_coords.attrib['points'] = pts_to_xml_str([[0,0],[0,0]])

            el_baseline = ET.SubElement(text_line, "Baseline")
            el_baseline.attrib['points'] = pts_to_xml_str(baseline)

    elif eval_type == "textlines":
        for i, textline in enumerate(region['textlines']):
            text_line = ET.SubElement(text_region, "TextLine")
            text_line.attrib['id'] = "textline_"+str(i)

            text_coords = ET.SubElement(text_line, "Coords")
            text_coords.attrib['points'] = pts_to_xml_str(textline)

            el_baseline = ET.SubElement(text_line, "Baseline")
            el_baseline.attrib['points'] = pts_to_xml_str([[0,0],[0,0]])


    xml_str = ET.tostring(root)
    #Hack for namespacing issue
    xml_str = xml_str.replace("<PcGts>", '<PcGts xmlns="http://schema.primaresearch.org/PAGE/gts/pagecontent/2013-07-15" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schema.primaresearch.org/PAGE/gts/pagecontent/2013-07-15 http://schema.primaresearch.org/PAGE/gts/pagecontent/2013-07-15/pagecontent.xsd">')

    with open(xml_path, 'w') as f:
        f.write(xml_str)
Esempio n. 11
0
def test_space(math_and_row):
    math, row = math_and_row
    eTree.SubElement(row, 'mspace', width='0.167em')
    assert _convert(math) == convert('\,')
Esempio n. 12
0
def wrap_boolean_tag(value: bool, master_wrapper):
    tag_in_value = 'true' if value else 'false'
    boolean_tag = ET.SubElement(master_wrapper, tag_in_value)
Esempio n. 13
0
def wrap_string_tag(text: str, master_wrapper):
    string_tag = ET.SubElement(master_wrapper, InfoPropertyListTags.STRING)
    string_tag.text = text
Esempio n. 14
0
def wrap_key_tag(text: str, master_wrapper):
    key_tag = ET.SubElement(master_wrapper, InfoPropertyListTags.KEY)
    key_tag.text = text
Esempio n. 15
0
 def process_root_element(self, root):
     ET.SubElement(root, "someextraelement")
     return root
Esempio n. 16
0
def test_matrix_without_begin_and_end(math_and_row):  # taken from MathJax
    math, row = math_and_row
    table = eTree.SubElement(row, 'mtable')

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'a'
    td = eTree.SubElement(tr, 'mtd')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'b'

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'c'
    td = eTree.SubElement(tr, 'mtd')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'd'

    assert _convert(math) == convert(r'\matrix{a & b \\ c & d}')
Esempio n. 17
0
def to_XML(parameter_obj, path_obj):

    root = ET.Element("root")
    par = ET.SubElement(root, "parametri")
    ET.SubElement(par, "p1", name="minLateralSeparation").text = str(
        parameter_obj.minLateralSeparation)
    ET.SubElement(par, "p2",
                  name="cv2thresh").text = str(parameter_obj.cv2thresh)
    ET.SubElement(par, "p3", name="minVal").text = str(parameter_obj.minVal)
    ET.SubElement(par, "p4", name="maxVal").text = str(parameter_obj.maxVal)
    ET.SubElement(par, "p5", name="theta").text = str(parameter_obj.theta)
    ET.SubElement(par, "p6", name="thresholdHough").text = str(
        parameter_obj.thresholdHough)
    ET.SubElement(par, "p7",
                  name="maxLineGap").text = str(parameter_obj.maxLineGap)
    ET.SubElement(par, "p8", name="minPts").text = str(parameter_obj.minPts)
    ET.SubElement(par, "p9", name="h").text = str(parameter_obj.h)
    ET.SubElement(par, "p10",
                  name="minOffset").text = str(parameter_obj.minOffset)
    ET.SubElement(par, "p11",
                  name="diagonali").text = str(parameter_obj.diagonali)
    ET.SubElement(par, "p12", name="m").text = str(parameter_obj.m)
    ET.SubElement(par, "p13",
                  name="flip_dataset").text = str(parameter_obj.flip_dataset)

    par2 = ET.SubElement(root, "path")
    ET.SubElement(par2, "p1", name="INFOLDERS").text = str(path_obj.INFOLDERS)
    ET.SubElement(par2, "p2",
                  name="OUTFOLDERS").text = str(path_obj.OUTFOLDERS)
    ET.SubElement(par2, "p3", name="DATASETs").text = str(path_obj.DATASETs)
    ET.SubElement(par2, "p4",
                  name="data_out_path").text = str(path_obj.data_out_path)
    ET.SubElement(par2, "p5", name="metricMap").text = str(path_obj.metricMap)
    ET.SubElement(par2, "p6", name="nome_gt").text = str(path_obj.nome_gt)
    ET.SubElement(par2, "p7", name="filepath").text = str(path_obj.filepath)
    ET.SubElement(par2, "p8", name="filepath_pickle_layout").text = str(
        path_obj.filepath_pickle_layout)
    ET.SubElement(par2, "p9",
                  name="filepath_pickle_grafoTopologico").text = str(
                      path_obj.filepath_pickle_grafoTopologico)

    tree = ET.ElementTree(root)
    tree.write(path_obj.filepath + "parametri.xml")
Esempio n. 18
0
def test_matrix_with_alignment(math_and_row):
    math, row = math_and_row
    table = eTree.SubElement(row, 'mtable')

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd', columnalign='right')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'a'
    td = eTree.SubElement(tr, 'mtd', columnalign='right')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'b'

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd', columnalign='right')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'c'
    td = eTree.SubElement(tr, 'mtd', columnalign='right')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'd'

    assert _convert(math) == convert(r'\begin{matrix*}[r]a & b \\ c & d \end{matrix*}')
Esempio n. 19
0
def create_object_xml(filename, num_objects, object_mass, friction_params, object_meshes,
                      finger_sensors, maxlen, minlen, load_dict_list, obj_classname = None,
                      block_height = 0.03, block_width = 0.03, cylinder_radius = 0.04):
    """
    :param hyperparams:
    :param load_dict_list: if not none load configuration, instead of sampling
    :return: if not loading, save dictionary with static object properties
    """
    xmldir = '/'.join(str.split(filename, '/')[:-1])
    root = ET.Element("top")

    save_dict_list = []

    if finger_sensors:
        sensor_frame = ET.SubElement(root, "sensor")
        ET.SubElement(sensor_frame, "touch", name = "finger1_sensor", site = "finger1_surf")
        ET.SubElement(sensor_frame, "touch", name = "finger2_sensor", site = "finger2_surf")
    else:
        sensor_frame = None
    f_sliding, f_torsion, f_rolling = friction_params
    world_body = ET.SubElement(root, "worldbody")

    loaded_meshes = {}

    for i in range(num_objects):
        if load_dict_list == None:
            dict = {}

            color1 = dict['color1'] = np.random.uniform(0.3, 1., 3)
            color2 = dict['color2'] = np.random.uniform(0.3, 1., 3)


            l1 = dict['l1'] =np.random.uniform(minlen, maxlen)
            l2 = dict['l2'] =np.random.uniform(minlen, maxlen)

            pos2 = dict['pos2']= np.random.uniform(0.01, l1)
        else:
            dict = load_dict_list[i]
            color1 = dict.get('color1', (1, 0, 0))
            color2 = dict.get('color2', (0, 1, 0))
            l1 = dict.get('l1', 0)
            l2 = dict.get('l2', 0)
            pos2 = dict.get('pos2', (0, 0, 0))


        save_dict_list.append(dict)

        obj_string = "object{}".format(i)
        print('using friction=({}, {}, {}), object mass{}'.format(f_sliding, f_torsion, f_rolling, object_mass))


        if object_meshes is not None:
            assets = ET.SubElement(root, "asset")

            chosen_mesh = random.choice(object_meshes)
            if chosen_mesh not in loaded_meshes:
                o_mesh = ASSET_BASE_DIR + '{}/'.format(chosen_mesh)
                print('import mesh dir', o_mesh)
                stl_files = glob.glob(o_mesh + '*.stl')
                convex_hull_files = [x for x in stl_files if 'Shape_IndexedFaceSet' in x]
                object_file = [x for x in stl_files
                               if x not in convex_hull_files and 'Lamp' not in x and 'Camera' not in x and 'GM' not in x][0]



                mesh_object = mesh.Mesh.from_file(object_file)
                minx, maxx, miny, maxy, minz, maxz = find_mins_maxs(mesh_object)
                min_length = min((maxx - minx), (maxy - miny))
                scale = [0.12 / min_length for _ in range(3)]

                if chosen_mesh in ['Knife', 'Fork', 'Spoon']:      #should add a more extensible way to handle different rescale rules
                    max_length = max((maxx - minx), (maxy - miny))
                    scale = [0.24 / max_length for _ in range(3)]

                    if chosen_mesh == 'Knife':
                        scale[2] *= 10

                object_pos = [0., 0., 0.]
                object_pos[0] -= scale[0] * (minx + maxx) / 2.0
                object_pos[1] -= scale[1] * (miny + maxy) / 2.0
                object_pos[2] -= 0.08 + scale[2] * (minz + maxz) / 2.0

                mass_per_elem, n_cvx_files = object_mass / (1 + len(convex_hull_files)), len(convex_hull_files)
                loaded_meshes[chosen_mesh] = (object_pos, mass_per_elem, n_cvx_files)

                ET.SubElement(assets, "mesh", name=chosen_mesh + "_mesh", file=object_file,
                              scale="{} {} {}".format(scale[0], scale[1], scale[2]))
                for n, c_file in enumerate(convex_hull_files):
                    ET.SubElement(assets, "mesh", name=chosen_mesh + "_convex_mesh{}".format(n), file=c_file,
                                  scale="{} {} {}".format(scale[0], scale[1], scale[2]))

            else: object_pos, mass_per_elem, n_cvx_files = loaded_meshes[chosen_mesh]

            pos_str = "{} {} {}".format(object_pos[0], object_pos[1], object_pos[2])

            if obj_classname is not None:
                obj = ET.SubElement(world_body, "body",name=obj_string, pos=pos_str,
                                    childclass=obj_classname)
            else: obj = ET.SubElement(world_body, "body",name=obj_string, pos=pos_str)

            ET.SubElement(obj, "joint", type="free")

            #visual mesh
            ET.SubElement(obj, "geom", type="mesh", mesh = chosen_mesh + "_mesh",
                          rgba="{} {} {} 1".format(color1[0], color1[1], color1[2]), mass="{}".format(mass_per_elem),
                          contype="0", conaffinity="0")
            #contact meshes
            for n in range(n_cvx_files):
                ET.SubElement(obj, "geom", type="mesh", mesh=chosen_mesh + "_convex_mesh{}".format(n),
                              rgba="0 1 0 0", mass="{}".format(mass_per_elem),
                              contype="7", conaffinity="7", friction="{} {} {}".format(f_sliding, f_torsion, f_rolling)
                              )



        else:
            obj = None
            if obj_classname is not None:
                obj = ET.SubElement(world_body, "body", name=obj_string, pos="0 0 0",
                                    childclass=obj_classname)
            else: obj = ET.SubElement(world_body, "body", name=obj_string, pos="0 0 0")


            ET.SubElement(obj, "joint", type="free", limited='false', damping="0", armature="0")

            # ET.SubElement(obj, "geom", type="box", size="{} {} {}".format(block_width, l1, block_height),
            #                rgba="{} {} {} 1".format(color1[0], color1[1], color1[2]), mass="{}".format(object_mass),
            #                contype="7", conaffinity="7", friction="{} {} {}".format(f_sliding, f_torsion, f_rolling)
            #                )
            # ET.SubElement(obj, "geom", pos="{} {} 0.0".format(l2, pos2),
            #                type="box", size="{} {} {}".format(l2, block_width, block_height),
            #                rgba="{} {} {} 1".format(color2[0], color2[1], color2[2]), mass="{}".format(object_mass),
            #                contype="7", conaffinity="7", friction="{} {} {}".format(f_sliding, f_torsion, f_rolling)
            #                )
            ET.SubElement(obj, "inertial", mass="0.1", pos="0 0 0", diaginertia="100000 100000 100000")

            # ET.SubElement(obj, "geom", pos="{} {} 0.0".format(l2, pos2), type="cylinder", size=str(cylinder_radius) + " 0.02",
            #                             rgba="{} {} {} 1".format(color2[0], color2[1], color2[2]), mass="{}".format(object_mass),
            #                             contype="7", conaffinity="7", friction="{} {} {}".format(f_sliding, f_torsion, f_rolling))
            ET.SubElement(obj, "geom", pos="0 0 0", type="cylinder", size=str(cylinder_radius) + " 0.015",
                                        rgba="{} {} {} 1".format(color2[0], color2[1], color2[2]),
                                        contype="18", conaffinity="20")

            # ET.SubElement(obj, "site", name=obj_string, pos="{} {} 0.0".format(l2, pos2), size="0.01")

        if sensor_frame is None:
            sensor_frame = ET.SubElement(root, "sensor")
        ET.SubElement(sensor_frame, "framepos", name=obj_string + '_sensor', objtype="body", objname=obj_string)

    tree = ET.ElementTree(root)

    xml_str = minidom.parseString(ET.tostring(
        tree.getroot(),
        'utf-8')).toprettyxml(indent="    ")

    xml_str = xml_str.splitlines()[1:]
    xml_str = "\n".join(xml_str)
    with open(xmldir + "/auto_gen_objects{}.xml".format(os.getpid()), "w") as f:
        f.write(xml_str)

    return save_dict_list
Esempio n. 20
0
def test_matrix_with_negative_sign(math_and_row):
    math, row = math_and_row
    table = eTree.SubElement(row, 'mtable')

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd')
    mo = eTree.SubElement(td, 'mo')
    mo.text = '&#x02212;'
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'a'
    td = eTree.SubElement(tr, 'mtd')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'b'

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'c'
    td = eTree.SubElement(tr, 'mtd')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'd'

    assert _convert(math) == convert(r'\begin{matrix}-a & b \\ c & d \end{matrix}')
Esempio n. 21
0
def to_XML(parameter_obj, path_obj):

    root = ET.Element("root")
    par = ET.SubElement(root, "parametri")
    ET.SubElement(par, "p1", name="minLateralSeparation").text = str(
        parameter_obj.minLateralSeparation)
    ET.SubElement(par, "p2",
                  name="cv2thresh").text = str(parameter_obj.cv2thresh)
    ET.SubElement(par, "p3", name="minVal").text = str(parameter_obj.minVal)
    ET.SubElement(par, "p4", name="maxVal").text = str(parameter_obj.maxVal)
    ET.SubElement(par, "p5", name="rho").text = str(parameter_obj.rho)
    ET.SubElement(par, "p6", name="theta").text = str(parameter_obj.theta)
    ET.SubElement(par, "p7", name="thresholdHough").text = str(
        parameter_obj.thresholdHough)
    ET.SubElement(par, "p8",
                  name="minLineLength").text = str(parameter_obj.minLineLength)
    ET.SubElement(par, "p9",
                  name="maxLineGap").text = str(parameter_obj.maxLineGap)
    ET.SubElement(par, "p10", name="eps").text = str(parameter_obj.eps)
    ET.SubElement(par, "p11", name="minPts").text = str(parameter_obj.minPts)
    ET.SubElement(par, "p12", name="h").text = str(parameter_obj.h)
    ET.SubElement(par, "p13",
                  name="minOffset").text = str(parameter_obj.minOffset)
    ET.SubElement(par, "p14",
                  name="diagonali").text = str(parameter_obj.diagonali)
    ET.SubElement(par, "p15", name="m").text = str(parameter_obj.m)
    ET.SubElement(par, "p16",
                  name="flip_dataset").text = str(parameter_obj.flip_dataset)
    ET.SubElement(par, "p17",
                  name="apertureSize").text = str(parameter_obj.apertureSize)
    ET.SubElement(par, "p18", name="t").text = str(parameter_obj.t)
    ET.SubElement(par, "p19", name="sogliaLateraleClusterMura").text = str(
        parameter_obj.sogliaLateraleClusterMura)
    ET.SubElement(par, "p20", name="soglia_q_split").text = str(
        parameter_obj.soglia_q_split)

    par2 = ET.SubElement(root, "path")
    ET.SubElement(par2, "p1", name="INFOLDERS").text = str(path_obj.INFOLDERS)
    ET.SubElement(par2, "p2",
                  name="OUTFOLDERS").text = str(path_obj.OUTFOLDERS)
    #ET.SubElement(par2, "p3", name="DATASETs").text = path_obj.DATASETs
    ET.SubElement(par2, "p4",
                  name="data_out_path").text = str(path_obj.data_out_path)
    ET.SubElement(par2, "p5", name="metricMap").text = str(path_obj.metricMap)
    ET.SubElement(par2, "p6", name="nome_gt").text = str(path_obj.nome_gt)
    ET.SubElement(par2, "p7", name="filepath").text = str(path_obj.filepath)
    ET.SubElement(par2, "p8", name="filepath_pickle_layout").text = str(
        path_obj.filepath_pickle_layout)
    ET.SubElement(par2, "p9",
                  name="filepath_pickle_grafoTopologico").text = str(
                      path_obj.filepath_pickle_grafoTopologico)

    tree = ET.ElementTree(root)
    indent(root)
    tree.write(path_obj.filepath + "parametri.xml")
Esempio n. 22
0
def test_pmatrix(math_and_row):
    math, row = math_and_row
    mo = eTree.SubElement(row, 'mo')
    mo.text = '&#x00028;'
    table = eTree.SubElement(row, 'mtable')

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'a'
    td = eTree.SubElement(tr, 'mtd')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'b'

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'c'
    td = eTree.SubElement(tr, 'mtd')
    mi = eTree.SubElement(td, 'mi')
    mi.text = 'd'

    mo = eTree.SubElement(row, 'mo')
    mo.text = '&#x00029;'

    assert _convert(math) == convert(r'\begin{pmatrix}a & b \\ c & d \end{pmatrix}')
Esempio n. 23
0
    def protocol(self):
        """Protocols XML Configuration"""

        protocols = ('application-group',
                     'arp'
                         , 'attribute'
                         , 'bgp'
                         , 'bittorrent'
                         , 'bridge'
                         , 'cdp'
                         , 'cifs'
                         , 'citrix'
                         , 'clns'
                         , 'clns_es'
                         , 'clns_is'
                         , 'cmns'
                         , 'compressedtcp'
                         , 'cuseeme'
                         , 'dhcp'
                         , 'dht'
                         , 'directconnect'
                         , 'dns'
                         , 'edonkey'
                         , 'egp'
                         , 'eigrp'
                         , 'exchange'
                         , 'fasttrack'
                         , 'finger'
                         , 'ftp'
                         , 'gnutella'
                         , 'gopher'
                         , 'gre'
                         , 'http'
                         , 'http-local-net'
                         , 'https'
                         , 'icmp'
                         , 'imap'
                         , 'ip'
                         , 'ipinip'
                         , 'ipsec'
                         , 'ipv6'
                         , 'ipv6-icmp'
                         , 'irc'
                         , 'kazaa2'
                         , 'kerberos'
                         , 'l2tp'
                         , 'ldap'
                         , 'llc2'
                         , 'mgcp'
                         , 'ms-rpc'
                         , 'netbios'
                         , 'netshow'
                         , 'nfs'
                         , 'nntp'
                         , 'notes'
                         , 'novadigm'
                         , 'ntp'
                         , 'ospf'
                         , 'pad'
                         , 'pop3'
                         , 'pppoe'
                         , 'pppoe-discovery'
                         , 'pptp'
                         , 'printer'
                         , 'rip'
                         , 'rsrb'
                         , 'rsvp'
                         , 'rtcp'
                         , 'rtp'
                         , 'rtsp'
                         , 'secure-ftp'
                         , 'secure-http'
                         , 'secure-imap'
                         , 'secure-irc'
                         , 'secure-ldap'
                         , 'secure-nntp'
                         , 'secure-pop3'
                         , 'secure-telnet'
                         , 'sip'
                         , 'skinny'
                         , 'skype'
                         , 'smtp'
                         , 'snapshot'
                         , 'snmp'
                         , 'socks'
                         , 'sqlnet'
                         , 'sqlserver'
                         , 'ssh'
                         , 'ssl'
                         , 'stun-nat'
                         , 'sunrpc'
                         , 'syslog'
                         , 'telepresence-control'
                         , 'telnet'
                         , 'teredo-ipv6-tunneled'
                         , 'tftp'
                         , 'vdolive'
                         , 'winmx'
                         , 'xmpp-client'
                         , 'xwindows'
                         , " "
                         , " "
                         , " ")

        [print(' | '.join(protocols[i * 10:(i + 1) * 10])) for i in range(10)]
        print("\n")
        while True:
            try:
                protocol = input("Protocol:  ")
                if protocol in protocols:
                    match_1_element = xml.SubElement(self.match_element, "protocol")
                    match_2_element = xml.SubElement(match_1_element, "protocols-list")
                    match_3_element = xml.SubElement(match_2_element, "protocols")
                    match_3_element.text = protocol
                else:
                    print("Invalid protocol")
            except KeyboardInterrupt:
                break

        return self.root
Esempio n. 24
0
def test_simple_array(math_and_row):
    math, row = math_and_row
    table = eTree.SubElement(row, 'mtable')

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd', columnalign='center')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '1'
    td = eTree.SubElement(tr, 'mtd', columnalign='right')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '2'

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd', columnalign='center')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '3'
    td = eTree.SubElement(tr, 'mtd', columnalign='right')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '4'
    assert _convert(math) == convert(r'\begin{array}{cr} 1 & 2 \\ 3 & 4 \end{array}')
Esempio n. 25
0
    def finish(self):
        extents = self._adjust_coordinates()
        w = extents.width * self.scale
        h = extents.height * self.scale


        nsmap = {
                "dc": "http://purl.org/dc/elements/1.1/",
                "cc": "http://creativecommons.org/ns#",
                "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
                "svg": "http://www.w3.org/2000/svg",
                "xlink": "http://www.w3.org/1999/xlink",
                "inkscape": "http://www.inkscape.org/namespaces/inkscape",
            }
        ET.register_namespace("", "http://www.w3.org/2000/svg")
        ET.register_namespace("xlink", "http://www.w3.org/1999/xlink")
        svg = ET.Element('svg', width=f"{w:.2f}mm", height=f"{h:.2f}mm",
                         viewBox=f"0.0 0.0 {w:.2f} {h:.2f}",
                         xmlns="http://www.w3.org/2000/svg")
        for name, value in nsmap.items():
            svg.set(f"xmlns:{name}", value)
        svg.text = "\n"
        tree = ET.ElementTree(svg)

        self._add_metadata(svg)
        
        for i, part in enumerate(self.parts):
            if not part.pathes:
                continue
            g = ET.SubElement(svg, "g", id=f"p-{i}",
                              style="fill:none;stroke-linecap:round;stroke-linejoin:round;")
            g.text = "\n  "
            g.tail = "\n"
            for j, path in enumerate(part.pathes):
                p = []
                x, y = 0, 0
                start = None
                last = None
                path.faster_edges()
                for c in path.path:
                    x0, y0 = x, y
                    C, x, y = c[0:3]
                    if C == "M":
                        if start and points_equal(start[1], start[2],
                                                  last[1], last[2]):
                            p.append("Z")
                        start = c
                        p.append(f"M {x:.3f} {y:.3f}")
                    elif C == "L":
                        if abs(x - x0) < EPS:
                            p.append(f"V {y:.3f}")
                        elif abs(y - y0) < EPS:
                            p.append(f"H {x:.3f}")
                        else:
                            p.append(f"L {x:.3f} {y:.3f}")
                    elif C == "C":
                        x1, y1, x2, y2 = c[3:]
                        p.append(
                            f"C {x1:.3f} {y1:.3f} {x2:.3f} {y2:.3f} {x:.3f} {y:.3f}"
                        )
                    elif C == "T":
                        m, text, params = c[3:]
                        m = m * Affine.translation(0, -params['fs'])
                        tm = " ".join((f"{m[i]:.3f}" for i in (0, 3, 1, 4, 2, 5)))
                        font, bold, italic = params['ff']
                        fontweight = ("normal", "bold")[bool(bold)]
                        fontstyle = ("normal", "italic")[bool(italic)]

                        style = f"font-family: {font} ; font-weight: {fontweight}; font-style: {fontstyle}; fill: {rgb_to_svg_color(*params['rgb'])}"
                        t = ET.SubElement(g, "text",
                                          #x=f"{x:.3f}", y=f"{y:.3f}",
                                          transform=f"matrix( {tm} )",
                                          style=style)
                        t.text = text
                        t.set("font-size", f"{params['fs']}px")
                        t.set("text-anchor", params.get('align', 'left'))
                        t.set("alignment-baseline", 'hanging')
                    else:
                        print("Unknown", c)

                    last = c

                if start and start is not last and \
                   points_equal(start[1], start[2], last[1], last[2]):
                    p.append("Z")
                color = (
                    random_svg_color()
                    if RANDOMIZE_COLORS
                    else rgb_to_svg_color(*path.params["rgb"])
                )
                if p and p[-1][0] == "M":
                    p.pop()
                if p:  # might be empty if only contains text
                    t = ET.SubElement(g, "path", d=" ".join(p), stroke=color)
                    t.set("stroke-width", f'{path.params["lw"]*self.scale:.2f}')
                    t.tail = "\n  "
            t.tail = "\n"
        tree.write(open(self._fname, "wb"), xml_declaration=True, method="xml")
Esempio n. 26
0
def test_array_with_vertical_bars(math_and_row):
    math, row = math_and_row
    table = eTree.SubElement(row, 'mtable', columnlines='solid none')
    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd', columnalign='center')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '1'
    td = eTree.SubElement(tr, 'mtd', columnalign='right')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '2'
    td = eTree.SubElement(tr, 'mtd', columnalign='left')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '3'

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd', columnalign='center')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '4'
    td = eTree.SubElement(tr, 'mtd', columnalign='right')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '5'
    td = eTree.SubElement(tr, 'mtd', columnalign='left')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '6'

    assert _convert(math) == convert(r'\begin{array}{c|rl} 1 & 2 & 3 \\ 4 & 5 & 6 \end{array}')
Esempio n. 27
0
    def outputFiberVTU(cls):
        # top level header
        vtkFile = XML.Element("VTKFile",
                              type="UnstructuredGrid",
                              version="0.1",
                              byte_order="LittleEndian")
        # UnstructuredGrid top level
        unstructuredGrid = XML.SubElement(vtkFile, "UnstructuredGrid")

        # made of multiple independent pieces, this is the fibers section
        pieceFibers = XML.SubElement(
            unstructuredGrid,
            "Piece",
            NumberOfPoints=str(len(cls.fibers['coordinates'])),
            NumberOfCells=str(len(cls.fibers['coordinates'])))

        # contains points, cells, pointData(optional), cellData(optional)

        # points level, NumberOfComponents = length of a vertex definition
        points = XML.SubElement(pieceFibers, "Points")
        pointString = []
        for vertex in cls.fibers['coordinates']:
            pointString.append("" + str(vertex[0]) + " " + str(vertex[1]) +
                               " " + str(vertex[2]) + "\n")
        pointString = ''.join(pointString)
        dataArrayPoints = XML.SubElement(points,
                                         "DataArray",
                                         type="Float32",
                                         NumberOfComponents="3",
                                         format="ascii").text = pointString

        # cells level
        cells = XML.SubElement(pieceFibers, "Cells")

        # connectivity of points to make the cells, all appended
        connectivityString = []
        for i in range(len(cls.fibers['coordinates'])):
            connectivityString.append(str(i) + "\n")
        connectivityString = ''.join(connectivityString)
        dataArrayCellsConnectivity = XML.SubElement(
            cells,
            "DataArray",
            type="Int32",
            Name="connectivity",
            format="ascii").text = connectivityString

        # delimiters of where each cell definition ends, ex for a cell def of 4
        # points the first offset would be 4, then 8, then 12 and so on.
        offsetsString = []
        for i in range(1, len(cls.fibers['coordinates']) + 1):
            offsetsString.append(str(i) + "\n")
        offsetsString = ''.join(offsetsString)
        dataArrayCellsOffsets = XML.SubElement(
            cells, "DataArray", type="Int32", Name="offsets",
            format="ascii").text = offsetsString

        # cell type of each cell in order 1 vertex
        cellTypesString = ["1\n"] * len(cls.fibers['coordinates'])
        cellTypesString = ''.join(cellTypesString)
        dataArrayCellsOffsets = XML.SubElement(
            cells, "DataArray", type="UInt8", Name="types",
            format="ascii").text = cellTypesString

        # pointData level
        pointData = XML.SubElement(pieceFibers, "PointData", Vectors="Vector")

        tensorData = ([], [], [])
        tensorName = ("FibersX", "FibersY", "FibersZ")
        for tensor in cls.fibers['tensors']:
            for i in range(3):
                tensorLine = ""
                for j in range(3):
                    value = str(tensor[i][j])
                    if value == "nan":
                        value = "0"
                    tensorLine = tensorLine + value + " "
                tensorLine += "\n"
                tensorData[i].append(tensorLine)

        for i in range(3):
            XML.SubElement(pointData,
                           "DataArray",
                           type="Float32",
                           Name=tensorName[i],
                           format="ascii",
                           NumberOfComponents="3").text = ''.join(
                               tensorData[i])

        # get the tree starting at the root of the vtkFile level, then write to
        # file
        vtuFile = XML.ElementTree(vtkFile)
        vtuFile.write(cls.filename + "Fiber.vtu", xml_declaration=True)
Esempio n. 28
0
def test_array_with_horizontal_lines(math_and_row):
    math, row = math_and_row
    table = eTree.SubElement(row, 'mtable', rowlines='none solid')

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd', columnalign='center')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '1'

    td = eTree.SubElement(tr, 'mtd', columnalign='right')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '2'

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd', columnalign='center')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '3'

    td = eTree.SubElement(tr, 'mtd', columnalign='right')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '4'

    tr = eTree.SubElement(table, 'mtr')
    td = eTree.SubElement(tr, 'mtd', columnalign='center')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '5'

    td = eTree.SubElement(tr, 'mtd', columnalign='right')
    mn = eTree.SubElement(td, 'mn')
    mn.text = '6'

    s = r'\begin{array}{cr} 1 & 2 \\ 3 & 4 \\ \hline 5 & 6 \end{array}'

    assert _convert(math) == convert(s)
Esempio n. 29
0
 def add_rest(self):
     """Create rest."""
     etree.SubElement(self.current_note, "rest")
Esempio n. 30
0
        xml_place = m.group(1).lstrip().rstrip()

    print(
        "---------------------------------------- Article ----------------------------------------"
    )
    print("Headline =", xml_headline)
    print("Description =", xml_description)
    print("Author =", xml_author)
    print("Content =", xml_content)
    print("Date Published =", xml_date)
    print("Place =", xml_place)
    print(
        "-----------------------------------------------------------------------------------------"
    )

    tag_article = et.SubElement(tag_news, "article")

    tag_headline = et.SubElement(tag_article, "headline")
    tag_headline.text = xml_headline

    tag_description = et.SubElement(tag_article, "description")
    tag_description.text = xml_description

    tag_author = et.SubElement(tag_article, "author")
    tag_author.text = xml_author

    tag_content = et.SubElement(tag_article, "content")
    tag_content.text = xml_content

    tag_date = et.SubElement(tag_article, "date")
    tag_date.text = xml_date