Example #1
0
    def _get_lines(self, cr, uid, ids, decl_datas, company, dispatchmode=False,
                   extendedmode=False, context=None):
        intrastatcode_mod = self.pool['report.intrastat.code']
        invoiceline_mod = self.pool['account.invoice.line']
        product_mod = self.pool['product.product']
        region_mod = self.pool['l10n_be_intrastat.region']
        warehouse_mod = self.pool['stock.warehouse']

        if dispatchmode:
            mode1 = 'out_invoice'
            mode2 = 'in_refund'
            declcode = "29"
        else:
            mode1 = 'in_invoice'
            mode2 = 'out_refund'
            declcode = "19"

        decl = ET.Element('Report')
        if not extendedmode:
            decl.set('code', 'EX%sS' % declcode)
        else:
            decl.set('code', 'EX%sE' % declcode)
        decl.set('date', '%s-%s' % (decl_datas.year, decl_datas.month))
        datas = ET.SubElement(decl, 'Data')
        if not extendedmode:
            datas.set('form', 'EXF%sS' % declcode)
        else:
            datas.set('form', 'EXF%sE' % declcode)
        datas.set('close', 'true')
        intrastatkey = namedtuple("intrastatkey",
                                  ['EXTRF', 'EXCNT', 'EXTTA', 'EXREG',
                                   'EXGO', 'EXTPC', 'EXDELTRM'])
        entries = {}

        sqlreq = """
            select
                inv_line.id
            from
                account_invoice_line inv_line
                join account_invoice inv on inv_line.invoice_id=inv.id
                left join res_country on res_country.id = inv.intrastat_country_id
                left join res_partner on res_partner.id = inv.partner_id
                left join res_country countrypartner on countrypartner.id = res_partner.country_id
                join product_product on inv_line.product_id=product_product.id
                join product_template on product_product.product_tmpl_id=product_template.id
            where
                inv.state in ('open','paid')
                and inv.company_id=%s
                and not product_template.type='service'
                and (res_country.intrastat=true or (inv.intrastat_country_id is null
                                                    and countrypartner.intrastat=true))
                and ((res_country.code is not null and not res_country.code=%s)
                     or (res_country.code is null and countrypartner.code is not null
                     and not countrypartner.code=%s))
                and inv.type in (%s, %s)
                and to_char(inv.date_invoice, 'YYYY')=%s
                and to_char(inv.date_invoice, 'MM')=%s
            """

        cr.execute(sqlreq, (company.id, company.partner_id.country_id.code,
                            company.partner_id.country_id.code, mode1, mode2,
                            decl_datas.year, decl_datas.month))
        lines = cr.fetchall()
        invoicelines_ids = [rec[0] for rec in lines]
        invoicelines = invoiceline_mod.browse(cr, uid, invoicelines_ids, context=context)
        for inv_line in invoicelines:

            #Check type of transaction
            if inv_line.invoice_id.intrastat_transaction_id:
                extta = inv_line.invoice_id.intrastat_transaction_id.code
            else:
                extta = "1"
            #Check country
            if inv_line.invoice_id.intrastat_country_id:
                excnt = inv_line.invoice_id.intrastat_country_id.code
            else:
                excnt = inv_line.invoice_id.partner_id.country_id.code

            #Check region
            #If purchase, comes from purchase order, linked to a location,
            #which is linked to the warehouse
            #if sales, the sale order is linked to the warehouse
            #if sales, from a delivery order, linked to a location,
            #which is linked to the warehouse
            #If none found, get the company one.
            exreg = None
            if inv_line.invoice_id.type in ('in_invoice', 'in_refund'):
                #comes from purchase
                POL = self.pool['purchase.order.line']
                poline_ids = POL.search(
                    cr, uid, [('invoice_lines', 'in', inv_line.id)], context=context)
                if poline_ids:
                    purchaseorder = POL.browse(cr, uid, poline_ids[0], context=context).order_id
                    region_id = warehouse_mod.get_regionid_from_locationid(
                        cr, uid, purchaseorder.location_id.id, context=context)
                    if region_id:
                        exreg = region_mod.browse(cr, uid, region_id).code
            elif inv_line.invoice_id.type in ('out_invoice', 'out_refund'):
                #comes from sales
                soline_ids = self.pool['sale.order.line'].search(
                    cr, uid, [('invoice_lines', 'in', inv_line.id)], context=context)
                if soline_ids:
                    saleorder = self.pool['sale.order.line'].browse(
                        cr, uid, soline_ids[0], context=context).order_id
                    if saleorder and saleorder.warehouse_id and saleorder.warehouse_id.region_id:
                        exreg = region_mod.browse(
                            cr, uid, saleorder.warehouse_id.region_id.id, context=context).code

            if not exreg:
                if company.region_id:
                    exreg = company.region_id.code
                else:
                    self._company_warning(
                        cr, uid,
                        _('The Intrastat Region of the selected company is not set, '
                          'please make sure to configure it first.'),
                        context=context)

            #Check commodity codes
            intrastat_id = product_mod.get_intrastat_recursively(
                cr, uid, inv_line.product_id.id, context=context)
            if intrastat_id:
                exgo = intrastatcode_mod.browse(cr, uid, intrastat_id, context=context).name
            else:
                raise exceptions.Warning(
                    _('Product "%s" has no intrastat code, please configure it') %
                        inv_line.product_id.display_name)

            #In extended mode, 2 more fields required
            if extendedmode:
                #Check means of transport
                if inv_line.invoice_id.transport_mode_id:
                    extpc = inv_line.invoice_id.transport_mode_id.code
                elif company.transport_mode_id:
                    extpc = company.transport_mode_id.code
                else:
                    self._company_warning(
                        cr, uid,
                        _('The default Intrastat transport mode of your company '
                          'is not set, please make sure to configure it first.'),
                        context=context)

                #Check incoterm
                if inv_line.invoice_id.incoterm_id:
                    exdeltrm = inv_line.invoice_id.incoterm_id.code
                elif company.incoterm_id:
                    exdeltrm = company.incoterm_id.code
                else:
                    self._company_warning(
                        cr, uid,
                        _('The default Incoterm of your company is not set, '
                          'please make sure to configure it first.'),
                        context=context)
            else:
                extpc = ""
                exdeltrm = ""
            linekey = intrastatkey(EXTRF=declcode, EXCNT=excnt,
                                   EXTTA=extta, EXREG=exreg, EXGO=exgo,
                                   EXTPC=extpc, EXDELTRM=exdeltrm)
            #We have the key
            #calculate amounts
            if inv_line.price_unit and inv_line.quantity:
                amount = inv_line.price_unit * inv_line.quantity
            else:
                amount = 0
            if (not inv_line.uos_id.category_id
                    or not inv_line.product_id.uom_id.category_id
                    or inv_line.uos_id.category_id.id != inv_line.product_id.uom_id.category_id.id):
                weight = inv_line.product_id.weight_net * inv_line.quantity
            else:
                weight = (inv_line.product_id.weight_net *
                          inv_line.quantity * inv_line.uos_id.factor)
            if (not inv_line.uos_id.category_id or not inv_line.product_id.uom_id.category_id
                    or inv_line.uos_id.category_id.id != inv_line.product_id.uom_id.category_id.id):
                supply_units = inv_line.quantity
            else:
                supply_units = inv_line.quantity * inv_line.uos_id.factor
            amounts = entries.setdefault(linekey, (0, 0, 0))
            amounts = (amounts[0] + amount, amounts[1] + weight, amounts[2] + supply_units)
            entries[linekey] = amounts

        numlgn = 0
        for linekey in entries:
            numlgn += 1
            amounts = entries[linekey]
            item = ET.SubElement(datas, 'Item')
            self._set_Dim(item, 'EXSEQCODE', unicode(numlgn))
            self._set_Dim(item, 'EXTRF', unicode(linekey.EXTRF))
            self._set_Dim(item, 'EXCNT', unicode(linekey.EXCNT))
            self._set_Dim(item, 'EXTTA', unicode(linekey.EXTTA))
            self._set_Dim(item, 'EXREG', unicode(linekey.EXREG))
            self._set_Dim(item, 'EXTGO', unicode(linekey.EXGO))
            if extendedmode:
                self._set_Dim(item, 'EXTPC', unicode(linekey.EXTPC))
                self._set_Dim(item, 'EXDELTRM', unicode(linekey.EXDELTRM))
            self._set_Dim(item, 'EXTXVAL', unicode(round(amounts[0], 0)).replace(".", ","))
            self._set_Dim(item, 'EXWEIGHT', unicode(round(amounts[1], 0)).replace(".", ","))
            self._set_Dim(item, 'EXUNITS', unicode(round(amounts[2], 0)).replace(".", ","))

        if numlgn == 0:
            #no datas
            datas.set('action', 'nihil')
        return decl
Example #2
0
    def cells(
        self,
        cells: dict[str, ArrayLike] | list[tuple[str, ArrayLike] | CellBlock],
        grid: ET.Element,
    ) -> None:
        if isinstance(cells, dict):
            # convert dict to list of tuples
            cells = list(cells.items())

        # conver to cell_blocks
        cell_blocks = []
        for cell_block in cells:
            if isinstance(cell_block, tuple):
                cell_type, data = cell_block
                cell_block = CellBlock(cell_type, np.asarray(data))
            cell_blocks.append(cell_block)

        if len(cell_blocks) == 1:
            meshio_type = cell_blocks[0].type
            num_cells = len(cell_blocks[0].data)
            xdmf_type = meshio_to_xdmf_type[meshio_type][0]
            topo = ET.SubElement(
                grid,
                "Topology",
                TopologyType=xdmf_type,
                NumberOfElements=str(num_cells),
            )
            dt, prec = numpy_to_xdmf_dtype[cell_blocks[0].data.dtype.name]
            data_item = ET.SubElement(
                topo,
                "DataItem",
                DataType=dt,
                Dimensions="{} {}".format(*cell_blocks[0].data.shape),
                Format=self.data_format,
                Precision=prec,
            )
            data_item.text = self.numpy_to_xml_string(cell_blocks[0].data)
        elif len(cell_blocks) > 1:
            total_num_cells = sum(len(c.data) for c in cell_blocks)
            topo = ET.SubElement(
                grid,
                "Topology",
                TopologyType="Mixed",
                NumberOfElements=str(total_num_cells),
            )
            total_num_cell_items = sum(
                np.prod(c.data.shape) for c in cell_blocks)
            dim = total_num_cell_items + total_num_cells
            # Lines translate to Polylines, and one needs to specify the exact
            # number of nodes. Hence, prepend 2.
            for c in cell_blocks:
                if c.type == "line":
                    c.data[:] = np.insert(c.data, 0, 2, axis=1)
                    dim += len(c.data)
            dim = str(dim)
            cd = np.concatenate([
                # prepend column with xdmf type index
                np.insert(c.data, 0, meshio_type_to_xdmf_index[c.type],
                          axis=1).flatten() for c in cell_blocks
            ])
            dt, prec = numpy_to_xdmf_dtype[cd.dtype.name]
            data_item = ET.SubElement(
                topo,
                "DataItem",
                DataType=dt,
                Dimensions=dim,
                Format=self.data_format,
                Precision=prec,
            )
            data_item.text = self.numpy_to_xml_string(cd)
Example #3
0
def pose2origin(node, pose):
  xyz, rpy = homogeneous2translation_rpy(pose)
  ET.SubElement(node, 'origin', {'xyz': array2string(rounded(xyz)), 'rpy': array2string(rounded(rpy))})
Example #4
0
	def add_map_def(self,map_name):
		self.MAP_DEF=ET.SubElement(ROOT,'map-def')
		self.MAP_DEF.attrib['macro'] = 'DFHMDI'
		MAP_DEF.attrib['map-name'] = map_name
        # Start the frames per second throughput estimator
        fps = FPS().start()

        for img_path, img_name in zip(image_paths, image_names):
            frame = cv2.imread(img_path)

            # If skip frames passed, run detector
            if total_frames % config.SKIP == 0:
                # detections should be a list/array of shape (num_faces, 4)
                detections = config.DETECTOR.detect(frame)
                if config.SKIP != 1:
                    config.TRACKER.create_trackers(detections, frame)
            else:
                detections = config.TRACKER.update_trackers(frame)

            frame_info = ET.SubElement(root, "frame", name="{}".format(img_name))
            for detection in detections:
                ET.SubElement(frame_info, "bbox", x_left="{}".format(detection[0]), y_top="{}".format(detection[1]),
                              x_right="{}".format(detection[2]), y_bottom="{}".format(detection[3]))
            # Update counters
            fps.update()
            total_frames += 1

            # If we want to see things happening, render video. This should be off during
            # actual benchmark
            if config.SHOW:
                cv2.imshow(video_sequence_name, draw_boxes_on_image(frame, detections))
                _ = cv2.waitKey(1) & 0xFF

        # Before closing the output file write FPS info
        fps.stop()
Example #6
0
def project_reserve_xml(publication):
    project_body = publication['project']
    proj = project_body['value']
    xml_obj = _project_required_xml(publication)
    now = dateutil.parser.parse(publication['created'])
    if not project_body.get('doi', ''):
        reserve_resp = _reserve_doi(xml_obj, TARGET_BASE.format(project_id=proj['projectId']))
        doi, ark = reserve_resp.split('|')
    else:
        doi = project_body.get('doi')
        ark = project_body.get('doi')
    doi = doi.strip()
    ark = ark.strip()
    logger.debug('doi: %s', doi)
    identifier = xml_obj.find('identifier')
    identifier.text = doi

    #Optional stuff
    resource = xml_obj
    subjects = ET.SubElement(resource, 'subjects')
    for keyword in proj['keywords'].split(','):
        subject = ET.SubElement(subjects, 'subject')
        subject.text = keyword.strip().title()

    institutions = publication['institutions']
    contributors = ET.SubElement(resource, 'contributors')
    for institution in institutions:
        if institution.get('label', None) is None:
            continue

        contrib = ET.SubElement(contributors, 'contributor')
        name = ET.SubElement(contrib, 'contributorName')
        name.text = institution['label']
        contrib.attrib['contributorType'] = 'HostingInstitution'

    dates = ET.SubElement(resource, 'dates')
    date_publication = ET.SubElement(dates, 'date')
    date_publication.attrib['dateType'] = 'Accepted'
    date_publication.text = '{}-{}-{}'.format(now.year, now.month, now.day)

    language = ET.SubElement(resource, 'language')
    language.text = 'English'

    alternate_ids = ET.SubElement(resource, 'alternateIdentifiers')
    if proj['awardNumber']:
        award_number = ET.SubElement(alternate_ids, 'alternateIdentifier')
        award_number.attrib['alternateIdentifierType'] = 'NSF Award Number'
        award_number.text = proj['awardNumber']

    project_id = ET.SubElement(alternate_ids, 'alternateIdentifier')
    project_id.attrib['alternateIdentifierType'] = 'Project ID'
    project_id.text = proj['projectId']

    rights_list = ET.SubElement(resource, 'rightsList')
    rights = ET.SubElement(rights_list, 'rights')
    rights.attrib['rightsURI'] = 'http://opendatacommons.org/licenses/by/1-0/'
    rights.text = 'ODC-BY 1.0'
    logger.debug(pretty_print(xml_obj))
    _update_doi(doi, xml_obj)
    return (doi, ark, xml_obj)
Example #7
0
def rbridge_id_vrf_address_family_ipv6_unicast_ipv6_route_static_route_nh_route_attributes_metric(
        **kwargs):
    """Auto Generated Code
    """
    config = ET.Element("config")
    rbridge_id = ET.SubElement(config,
                               "rbridge-id",
                               xmlns="urn:brocade.com:mgmt:brocade-rbridge")
    if kwargs.pop('delete_rbridge_id', False) is True:
        delete_rbridge_id = config.find('.//*rbridge-id')
        delete_rbridge_id.set('operation', 'delete')

    rbridge_id_key = ET.SubElement(rbridge_id, "rbridge-id")
    rbridge_id_key.text = kwargs.pop('rbridge_id')
    if kwargs.pop('delete_rbridge_id', False) is True:
        delete_rbridge_id = config.find('.//*rbridge-id')
        delete_rbridge_id.set('operation', 'delete')

    vrf = ET.SubElement(rbridge_id,
                        "vrf",
                        xmlns="urn:brocade.com:mgmt:brocade-vrf")
    if kwargs.pop('delete_vrf', False) is True:
        delete_vrf = config.find('.//*vrf')
        delete_vrf.set('operation', 'delete')

    vrf_name_key = ET.SubElement(vrf, "vrf-name")
    vrf_name_key.text = kwargs.pop('vrf_name')
    if kwargs.pop('delete_vrf_name', False) is True:
        delete_vrf_name = config.find('.//*vrf-name')
        delete_vrf_name.set('operation', 'delete')

    address_family = ET.SubElement(vrf, "address-family")
    if kwargs.pop('delete_address_family', False) is True:
        delete_address_family = config.find('.//*address-family')
        delete_address_family.set('operation', 'delete')

    ipv6 = ET.SubElement(address_family, "ipv6")
    if kwargs.pop('delete_ipv6', False) is True:
        delete_ipv6 = config.find('.//*ipv6')
        delete_ipv6.set('operation', 'delete')

    unicast = ET.SubElement(ipv6, "unicast")
    if kwargs.pop('delete_unicast', False) is True:
        delete_unicast = config.find('.//*unicast')
        delete_unicast.set('operation', 'delete')

    ipv6 = ET.SubElement(unicast,
                         "ipv6",
                         xmlns="urn:brocade.com:mgmt:brocade-ipv6-rtm")
    if kwargs.pop('delete_ipv6', False) is True:
        delete_ipv6 = config.find('.//*ipv6')
        delete_ipv6.set('operation', 'delete')

    route = ET.SubElement(ipv6, "route")
    if kwargs.pop('delete_route', False) is True:
        delete_route = config.find('.//*route')
        delete_route.set('operation', 'delete')

    static_route_nh = ET.SubElement(route, "static-route-nh")
    if kwargs.pop('delete_static_route_nh', False) is True:
        delete_static_route_nh = config.find('.//*static-route-nh')
        delete_static_route_nh.set('operation', 'delete')

    static_route_dest_key = ET.SubElement(static_route_nh, "static-route-dest")
    static_route_dest_key.text = kwargs.pop('static_route_dest')
    if kwargs.pop('delete_static_route_dest', False) is True:
        delete_static_route_dest = config.find('.//*static-route-dest')
        delete_static_route_dest.set('operation', 'delete')

    static_route_next_hop_key = ET.SubElement(static_route_nh,
                                              "static-route-next-hop")
    static_route_next_hop_key.text = kwargs.pop('static_route_next_hop')
    if kwargs.pop('delete_static_route_next_hop', False) is True:
        delete_static_route_next_hop = config.find('.//*static-route-next-hop')
        delete_static_route_next_hop.set('operation', 'delete')

    route_attributes = ET.SubElement(static_route_nh, "route-attributes")
    if kwargs.pop('delete_route_attributes', False) is True:
        delete_route_attributes = config.find('.//*route-attributes')
        delete_route_attributes.set('operation', 'delete')

    metric = ET.SubElement(route_attributes, "metric")
    if kwargs.pop('delete_metric', False) is True:
        delete_metric = config.find('.//*metric')
        delete_metric.set('operation', 'delete')

    metric.text = kwargs.pop('metric')

    callback = kwargs.pop('callback', _callback)
    return callback(config, mgr=kwargs.pop('mgr'))
def interface_port_channel_switchport_trunk_private_vlan_classification_private_vlan_trunk_allowed_vlan_add_trunk_vlan_id(**kwargs):
    """Auto Generated Code
    """
    config = ET.Element("config")
    interface = ET.SubElement(config, "interface", xmlns="urn:brocade.com:mgmt:brocade-interface")
    if kwargs.pop('delete_interface', False) is True:
        delete_interface = config.find('.//*interface')
        delete_interface.set('operation', 'delete')
        
    port_channel = ET.SubElement(interface, "port-channel")
    if kwargs.pop('delete_port_channel', False) is True:
        delete_port_channel = config.find('.//*port-channel')
        delete_port_channel.set('operation', 'delete')
        
    name_key = ET.SubElement(port_channel, "name")
    name_key.text = kwargs.pop('name')
    if kwargs.pop('delete_name', False) is True:
        delete_name = config.find('.//*name')
        delete_name.set('operation', 'delete')
            
    switchport = ET.SubElement(port_channel, "switchport")
    if kwargs.pop('delete_switchport', False) is True:
        delete_switchport = config.find('.//*switchport')
        delete_switchport.set('operation', 'delete')
        
    trunk_private_vlan_classification = ET.SubElement(switchport, "trunk-private-vlan-classification")
    if kwargs.pop('delete_trunk_private_vlan_classification', False) is True:
        delete_trunk_private_vlan_classification = config.find('.//*trunk-private-vlan-classification')
        delete_trunk_private_vlan_classification.set('operation', 'delete')
        
    private_vlan = ET.SubElement(trunk_private_vlan_classification, "private-vlan")
    if kwargs.pop('delete_private_vlan', False) is True:
        delete_private_vlan = config.find('.//*private-vlan')
        delete_private_vlan.set('operation', 'delete')
        
    trunk = ET.SubElement(private_vlan, "trunk")
    if kwargs.pop('delete_trunk', False) is True:
        delete_trunk = config.find('.//*trunk')
        delete_trunk.set('operation', 'delete')
        
    allowed = ET.SubElement(trunk, "allowed")
    if kwargs.pop('delete_allowed', False) is True:
        delete_allowed = config.find('.//*allowed')
        delete_allowed.set('operation', 'delete')
        
    vlan = ET.SubElement(allowed, "vlan")
    if kwargs.pop('delete_vlan', False) is True:
        delete_vlan = config.find('.//*vlan')
        delete_vlan.set('operation', 'delete')
        
    add = ET.SubElement(vlan, "add")
    if kwargs.pop('delete_add', False) is True:
        delete_add = config.find('.//*add')
        delete_add.set('operation', 'delete')
        
    trunk_ctag_id_key = ET.SubElement(add, "trunk-ctag-id")
    trunk_ctag_id_key.text = kwargs.pop('trunk_ctag_id')
    if kwargs.pop('delete_trunk_ctag_id', False) is True:
        delete_trunk_ctag_id = config.find('.//*trunk-ctag-id')
        delete_trunk_ctag_id.set('operation', 'delete')
            
    trunk_vlan_id = ET.SubElement(add, "trunk-vlan-id")
    if kwargs.pop('delete_trunk_vlan_id', False) is True:
        delete_trunk_vlan_id = config.find('.//*trunk-vlan-id')
        delete_trunk_vlan_id.set('operation', 'delete')
        
    trunk_vlan_id.text = kwargs.pop('trunk_vlan_id')

    callback = kwargs.pop('callback', _callback)
    return callback(config, mgr=kwargs.pop('mgr'))
def rbridge_id_router_router_bgp_router_bgp_attributes_neighbor_peer_grps_neighbor_peer_grp_af_neighbor_capability_as4_neighbor_as4_disable(**kwargs):
    """Auto Generated Code
    """
    config = ET.Element("config")
    rbridge_id = ET.SubElement(config, "rbridge-id", xmlns="urn:brocade.com:mgmt:brocade-rbridge")
    if kwargs.pop('delete_rbridge_id', False) is True:
        delete_rbridge_id = config.find('.//*rbridge-id')
        delete_rbridge_id.set('operation', 'delete')
        
    rbridge_id_key = ET.SubElement(rbridge_id, "rbridge-id")
    rbridge_id_key.text = kwargs.pop('rbridge_id')
    if kwargs.pop('delete_rbridge_id', False) is True:
        delete_rbridge_id = config.find('.//*rbridge-id')
        delete_rbridge_id.set('operation', 'delete')
            
    router = ET.SubElement(rbridge_id, "router")
    if kwargs.pop('delete_router', False) is True:
        delete_router = config.find('.//*router')
        delete_router.set('operation', 'delete')
        
    router_bgp = ET.SubElement(router, "router-bgp", xmlns="urn:brocade.com:mgmt:brocade-bgp")
    if kwargs.pop('delete_router_bgp', False) is True:
        delete_router_bgp = config.find('.//*router-bgp')
        delete_router_bgp.set('operation', 'delete')
        
    router_bgp_attributes = ET.SubElement(router_bgp, "router-bgp-attributes")
    if kwargs.pop('delete_router_bgp_attributes', False) is True:
        delete_router_bgp_attributes = config.find('.//*router-bgp-attributes')
        delete_router_bgp_attributes.set('operation', 'delete')
        
    neighbor = ET.SubElement(router_bgp_attributes, "neighbor")
    if kwargs.pop('delete_neighbor', False) is True:
        delete_neighbor = config.find('.//*neighbor')
        delete_neighbor.set('operation', 'delete')
        
    peer_grps = ET.SubElement(neighbor, "peer-grps")
    if kwargs.pop('delete_peer_grps', False) is True:
        delete_peer_grps = config.find('.//*peer-grps')
        delete_peer_grps.set('operation', 'delete')
        
    neighbor_peer_grp = ET.SubElement(peer_grps, "neighbor-peer-grp")
    if kwargs.pop('delete_neighbor_peer_grp', False) is True:
        delete_neighbor_peer_grp = config.find('.//*neighbor-peer-grp')
        delete_neighbor_peer_grp.set('operation', 'delete')
        
    router_bgp_neighbor_peer_grp_key = ET.SubElement(neighbor_peer_grp, "router-bgp-neighbor-peer-grp")
    router_bgp_neighbor_peer_grp_key.text = kwargs.pop('router_bgp_neighbor_peer_grp')
    if kwargs.pop('delete_router_bgp_neighbor_peer_grp', False) is True:
        delete_router_bgp_neighbor_peer_grp = config.find('.//*router-bgp-neighbor-peer-grp')
        delete_router_bgp_neighbor_peer_grp.set('operation', 'delete')
            
    af_neighbor_capability = ET.SubElement(neighbor_peer_grp, "af-neighbor-capability")
    if kwargs.pop('delete_af_neighbor_capability', False) is True:
        delete_af_neighbor_capability = config.find('.//*af-neighbor-capability')
        delete_af_neighbor_capability.set('operation', 'delete')
        
    as4 = ET.SubElement(af_neighbor_capability, "as4")
    if kwargs.pop('delete_as4', False) is True:
        delete_as4 = config.find('.//*as4')
        delete_as4.set('operation', 'delete')
        
    neighbor_as4_disable = ET.SubElement(as4, "neighbor-as4-disable")
    if kwargs.pop('delete_neighbor_as4_disable', False) is True:
        delete_neighbor_as4_disable = config.find('.//*neighbor-as4-disable')
        delete_neighbor_as4_disable.set('operation', 'delete')
        

    callback = kwargs.pop('callback', _callback)
    return callback(config, mgr=kwargs.pop('mgr'))
def rbridge_id_router_router_bgp_address_family_ipv4_ipv4_unicast_default_vrf_af_common_cmds_holder_dampening_ch_dampening_source_ca_dampening_specify_values_values_reuse_value(**kwargs):
    """Auto Generated Code
    """
    config = ET.Element("config")
    rbridge_id = ET.SubElement(config, "rbridge-id", xmlns="urn:brocade.com:mgmt:brocade-rbridge")
    if kwargs.pop('delete_rbridge_id', False) is True:
        delete_rbridge_id = config.find('.//*rbridge-id')
        delete_rbridge_id.set('operation', 'delete')
        
    rbridge_id_key = ET.SubElement(rbridge_id, "rbridge-id")
    rbridge_id_key.text = kwargs.pop('rbridge_id')
    if kwargs.pop('delete_rbridge_id', False) is True:
        delete_rbridge_id = config.find('.//*rbridge-id')
        delete_rbridge_id.set('operation', 'delete')
            
    router = ET.SubElement(rbridge_id, "router")
    if kwargs.pop('delete_router', False) is True:
        delete_router = config.find('.//*router')
        delete_router.set('operation', 'delete')
        
    router_bgp = ET.SubElement(router, "router-bgp", xmlns="urn:brocade.com:mgmt:brocade-bgp")
    if kwargs.pop('delete_router_bgp', False) is True:
        delete_router_bgp = config.find('.//*router-bgp')
        delete_router_bgp.set('operation', 'delete')
        
    address_family = ET.SubElement(router_bgp, "address-family")
    if kwargs.pop('delete_address_family', False) is True:
        delete_address_family = config.find('.//*address-family')
        delete_address_family.set('operation', 'delete')
        
    ipv4 = ET.SubElement(address_family, "ipv4")
    if kwargs.pop('delete_ipv4', False) is True:
        delete_ipv4 = config.find('.//*ipv4')
        delete_ipv4.set('operation', 'delete')
        
    ipv4_unicast = ET.SubElement(ipv4, "ipv4-unicast")
    if kwargs.pop('delete_ipv4_unicast', False) is True:
        delete_ipv4_unicast = config.find('.//*ipv4-unicast')
        delete_ipv4_unicast.set('operation', 'delete')
        
    default_vrf = ET.SubElement(ipv4_unicast, "default-vrf")
    if kwargs.pop('delete_default_vrf', False) is True:
        delete_default_vrf = config.find('.//*default-vrf')
        delete_default_vrf.set('operation', 'delete')
        
    af_common_cmds_holder = ET.SubElement(default_vrf, "af-common-cmds-holder")
    if kwargs.pop('delete_af_common_cmds_holder', False) is True:
        delete_af_common_cmds_holder = config.find('.//*af-common-cmds-holder')
        delete_af_common_cmds_holder.set('operation', 'delete')
        
    dampening = ET.SubElement(af_common_cmds_holder, "dampening")
    if kwargs.pop('delete_dampening', False) is True:
        delete_dampening = config.find('.//*dampening')
        delete_dampening.set('operation', 'delete')
        
    ch_dampening_source = ET.SubElement(dampening, "ch-dampening-source")
    if kwargs.pop('delete_ch_dampening_source', False) is True:
        delete_ch_dampening_source = config.find('.//*ch-dampening-source')
        delete_ch_dampening_source.set('operation', 'delete')
        
    ca_dampening_specify_values = ET.SubElement(ch_dampening_source, "ca-dampening-specify-values")
    if kwargs.pop('delete_ca_dampening_specify_values', False) is True:
        delete_ca_dampening_specify_values = config.find('.//*ca-dampening-specify-values')
        delete_ca_dampening_specify_values.set('operation', 'delete')
        
    values = ET.SubElement(ca_dampening_specify_values, "values")
    if kwargs.pop('delete_values', False) is True:
        delete_values = config.find('.//*values')
        delete_values.set('operation', 'delete')
        
    reuse_value = ET.SubElement(values, "reuse-value")
    if kwargs.pop('delete_reuse_value', False) is True:
        delete_reuse_value = config.find('.//*reuse-value')
        delete_reuse_value.set('operation', 'delete')
        
    reuse_value.text = kwargs.pop('reuse_value')

    callback = kwargs.pop('callback', _callback)
    return callback(config, mgr=kwargs.pop('mgr'))
    root = tree.getroot()

    network_section = root.find("{http://schemas.dmtf.org/ovf/envelope/1}NetworkSection")

    nat_found = False
    hostonly_found = False

    for node in network_section.findall("{http://schemas.dmtf.org/ovf/envelope/1}Network"):
        network_name = node.get("{http://schemas.dmtf.org/ovf/envelope/1}name").lower()
        if network_name == "nat":
            nat_found = True
        elif network_name == "hostonly":
            hostonly_found = True

    if hostonly_found is False:
        network = ET.SubElement(network_section, '{http://schemas.dmtf.org/ovf/envelope/1}Network')
        network.set("{http://schemas.dmtf.org/ovf/envelope/1}name", "hostonly")
        description = ET.SubElement(network, "{http://schemas.dmtf.org/ovf/envelope/1}Description")
        description.text = "The hostonly network"
        print("Fix missing hostonly")

    if nat_found is False:
        network = ET.SubElement(network_section, '{http://schemas.dmtf.org/ovf/envelope/1}Network')
        network.set("{http://schemas.dmtf.org/ovf/envelope/1}name", "nat")
        description = ET.SubElement(network, "{http://schemas.dmtf.org/ovf/envelope/1}Description")
        description.text = "The nat network"
        print("Fix missing nat")

    connection_id = 0
    for item in root.iter('{http://schemas.dmtf.org/ovf/envelope/1}Item'):
        connection = item.find('{http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData}Connection')
Example #12
0
 def export_to_xml(self, parent):
     elem = ET.SubElement(parent, xmlio.get_tag_from_class(type(self)))
     elem.set('finish_thickness', str(self.finish_thickness))
     return elem
Example #13
0
    def create_xml(self, cr, uid, ids, context=None):
        """Creates xml that is to be exported and sent to estate for partner vat intra.
        :return: Value for next action.
        :rtype: dict
        """
        decl_datas = self.browse(cr, uid, ids[0])
        company = decl_datas.tax_code_id.company_id
        if not (company.partner_id and company.partner_id.country_id and
                company.partner_id.country_id.id):
            self._company_warning(
                cr, uid,
                _('The country of your company is not set, '
                  'please make sure to configure it first.'),
                context=context)
        kbo = company.company_registry
        if not kbo:
            self._company_warning(
                cr, uid,
                _('The registry number of your company is not set, '
                  'please make sure to configure it first.'),
                context=context)
        if len(decl_datas.year) != 4:
            raise exceptions.Warning(_('Year must be 4 digits number (YYYY)'))

        #Create root declaration
        decl = ET.Element('DeclarationReport')
        decl.set('xmlns', INTRASTAT_XMLNS)

        #Add Administration elements
        admin = ET.SubElement(decl, 'Administration')
        fromtag = ET.SubElement(admin, 'From')
        fromtag.text = kbo
        fromtag.set('declarerType', 'KBO')
        ET.SubElement(admin, 'To').text = "NBB"
        ET.SubElement(admin, 'Domain').text = "SXX"
        if decl_datas.arrivals == 'be-standard':
            decl.append(self._get_lines(cr, SUPERUSER_ID, ids, decl_datas, company,
                                        dispatchmode=False, extendedmode=False, context=context))
        elif decl_datas.arrivals == 'be-extended':
            decl.append(self._get_lines(cr, SUPERUSER_ID, ids, decl_datas, company,
                                        dispatchmode=False, extendedmode=True, context=context))
        if decl_datas.dispatches == 'be-standard':
            decl.append(self._get_lines(cr, SUPERUSER_ID, ids, decl_datas, company,
                                        dispatchmode=True, extendedmode=False, context=context))
        elif decl_datas.dispatches == 'be-extended':
            decl.append(self._get_lines(cr, SUPERUSER_ID, ids, decl_datas, company,
                                        dispatchmode=True, extendedmode=True, context=context))

        #Get xml string with declaration
        data_file = ET.tostring(decl, encoding='UTF-8', method='xml')

        #change state of the wizard
        self.write(cr, uid, ids,
                   {'name': 'intrastat_%s%s.xml' % (decl_datas.year, decl_datas.month),
                    'file_save': base64.encodestring(data_file),
                    'state': 'download'},
                   context=context)
        return {
            'name': _('Save'),
            'context': context,
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'l10n_be_intrastat_xml.xml_decl',
            'type': 'ir.actions.act_window',
            'target': 'new',
            'res_id': ids[0],
        }
Example #14
0
 def _set_Dim(self, item, prop, value):
     dim = ET.SubElement(item, 'Dim')
     dim.set('prop', prop)
     dim.text = value
Example #15
0
def _analysis_required_xml(users, analysis, created):
    anl = analysis['value']
    xml_obj = _project_header()

    resource = xml_obj
    identifier = ET.SubElement(resource, 'identifier')
    identifier.attrib['identifierType'] = 'DOI'
    identifier.text = SHOULDER.replace('doi:', '')
    creators = ET.SubElement(resource, 'creators')
    #um = get_user_model()
    users = sorted(users, key=lambda x: x['_ui']['order'])
    authors = anl.get('authors', users)
    for author in authors:
        _userf = filter(lambda x: x['username'] == author, users)
        if not len(_userf):
            continue

        _user = _userf[0]
        creator = ET.SubElement(creators, 'creator')
        creator_name = ET.SubElement(creator, 'creatorName')
        creator_name.text = '{}, {}'.format(_user['last_name'], _user['first_name'])

    titles = ET.SubElement(resource, 'titles')
    title = ET.SubElement(titles, 'title')
    title.text = anl['title']
    publisher = ET.SubElement(resource, 'publisher')
    publisher.text = 'Designsafe-CI'

    now = dateutil.parser.parse(created)
    publication_year = ET.SubElement(resource, 'publicationYear')
    publication_year.text = str(now.year)

    resource_type = ET.SubElement(resource, 'resourceType')
    resource_type.text = 'Analysis'
    resource_type.attrib['resourceTypeGeneral'] = 'Other'
    descriptions = ET.SubElement(resource, 'descriptions')
    desc = ET.SubElement(descriptions, 'description')
    desc.attrib['descriptionType'] = 'Abstract'
    desc.text = anl['description']
    return xml_obj
Example #16
0
def fileinfo_xml(flavour, non_init_patch_ids, force_preset):
    """Build FileInformation.xml metadata file.

    Args:
        flavour: "xd", "og", "prologue", "monologue", "kk"
        non_init_patch_ids (list of ints): 0-based list of non-Init-Program patches
        force_preset: preset file output

    Returns:
        str: formatted xml

    """
    assert flavour in valid_flavours

    # create the file structure
    root = ET.Element("KorgMSLibrarian_Data")
    product = ET.SubElement(root, "Product")
    product.text = {
        "monologue": "monologue",
        "xd": "minilogue xd",
        "og": "minilogue",
        "prologue": "prologue",
        "monologue": "monologue",
        "kk": "KingKORG",
    }[flavour]
    contents = ET.SubElement(root, "Contents")

    contents.set("NumProgramData", str(len(non_init_patch_ids)))
    if force_preset:
        contents.set("NumPresetInformation", "1")
        ET.SubElement(ET.SubElement(contents, "PresetInformation"),
                      "File").text = "PresetInformation.xml"
    else:
        contents.set("NumPresetInformation", "0")
    contents.set("NumTuneScaleData", "0")
    contents.set("NumTuneOctData", "0")

    if len(non_init_patch_ids) <= 1 or force_preset:
        if flavour == "prologue":
            contents.set("NumLivesetData", "0")
        elif flavour != "monologue":
            contents.set("NumFavoriteData", "0")
    else:
        if flavour == "prologue":
            contents.set("NumLivesetData", "1")
            fave = ET.SubElement(contents, "LivesetData")
            fave_info = ET.SubElement(fave, "File")
            fave_info.text = "LivesetData.lvs_data"
        elif flavour != "monologue":
            contents.set("NumFavoriteData", "1")
            fave = ET.SubElement(contents, "FavoriteData")
            fave_info = ET.SubElement(fave, "File")
            fave_info.text = "FavoriteData.fav_data"

    for i in non_init_patch_ids:
        prog = ET.SubElement(contents, "ProgramData")
        prog_info = ET.SubElement(prog, "Information")
        prog_info.text = f"Prog_{i:03d}.prog_info"
        prog_bin = ET.SubElement(prog, "ProgramBinary")
        prog_bin.text = f"Prog_{i:03d}.prog_bin"

    # https://stackoverflow.com/a/3095723
    formatted_xml = minidom.parseString(
        ET.tostring(root, encoding="utf-8",
                    method="xml")).toprettyxml(indent="  ")

    return formatted_xml
Example #17
0
def _simulation_required_xml(users, simulation, created):
    sim = simulation['value']
    xml_obj = _project_header()

    resource = xml_obj
    identifier = ET.SubElement(resource, 'identifier')
    identifier.attrib['identifierType'] = 'DOI'
    if sim.get('doi', ''):
        identifier.text = sim.get('doi')
    else:
        identifier.text = SHOULDER.replace('doi:', '')
    creators = ET.SubElement(resource, 'creators')
    #um = get_user_model()
    authors = sim.get('authors')
    #authors = authors or users
    for author in authors:
        _userf = filter(lambda x: x['username'] == author, users)
        if not len(_userf):
            continue

        _user = _userf[0]
        creator = ET.SubElement(creators, 'creator')
        creator_name = ET.SubElement(creator, 'creatorName')
        creator_name.text = '{}, {}'.format(_user['last_name'], _user['first_name'])

    titles = ET.SubElement(resource, 'titles')
    title = ET.SubElement(titles, 'title')
    title.text = sim['title']
    publisher = ET.SubElement(resource, 'publisher')
    publisher.text = 'Designsafe-CI'

    now = dateutil.parser.parse(created)
    publication_year = ET.SubElement(resource, 'publicationYear')
    publication_year.text = str(now.year)

    resource_type = ET.SubElement(resource, 'resourceType')
    resource_type.text = "Simulation/{}".format(
            sim['simulationType'].title())
    resource_type.attrib['resourceTypeGeneral'] = 'Dataset'
    descriptions = ET.SubElement(resource, 'descriptions')
    desc = ET.SubElement(descriptions, 'description')
    desc.attrib['descriptionType'] = 'Abstract'
    desc.text = sim['description']
    return xml_obj
Example #18
0
 def add(self, name):
     if not name in self.value:
         self.value.add(name)
         ElementTree.SubElement(self.root, 'reagent-label', {'name': name})
Example #19
0
    def to_xml_element(self, cross_sections=None):
        """Return XML representation of the material

        Parameters
        ----------
        cross_sections : str
            Path to an XML cross sections listing file

        Returns
        -------
        element : xml.etree.ElementTree.Element
            XML element containing material data

        """

        # Create Material XML element
        element = ET.Element("material")
        element.set("id", str(self._id))

        if len(self._name) > 0:
            element.set("name", str(self._name))

        if self._depletable:
            element.set("depletable", "true")

        if self._volume:
            element.set("volume", str(self._volume))

        # Create temperature XML subelement
        if self.temperature is not None:
            element.set("temperature", str(self.temperature))

        # Create density XML subelement
        if self._density is not None or self._density_units == 'sum':
            subelement = ET.SubElement(element, "density")
            if self._density_units != 'sum':
                subelement.set("value", str(self._density))
            subelement.set("units", self._density_units)
        else:
            raise ValueError('Density has not been set for material {}!'
                             .format(self.id))

        if self._macroscopic is None:
            # Create nuclide XML subelements
            subelements = self._get_nuclides_xml(self._nuclides)
            for subelement in subelements:
                element.append(subelement)
        else:
            # Create macroscopic XML subelements
            subelement = self._get_macroscopic_xml(self._macroscopic)
            element.append(subelement)

        if self._sab:
            for sab in self._sab:
                subelement = ET.SubElement(element, "sab")
                subelement.set("name", sab[0])
                if sab[1] != 1.0:
                    subelement.set("fraction", str(sab[1]))

        if self._isotropic:
            subelement = ET.SubElement(element, "isotropic")
            subelement.text = ' '.join(self._isotropic)

        return element
    def __init__(self, stream, config):
        super().__init__(stream, config)

        # -- XXX-JE-PREPARED-BUT-DISABLED:
        # XXX Seldom changed value.
        # XXX Should only be in configuration-file in own section
        #     "behave.formatter.html" ?!?
        # XXX Config support must be provided.
        # XXX REASON: Don't clutter behave config-space w/ formatter/plugin
        #     related config data.
        # self.css = self.default_css
        # if config.css is not None:
        #    self.css = config.css
        self.html = ET.Element("html")
        head = ET.SubElement(self.html, "head")
        ET.SubElement(head, "title").text = self.title
        ET.SubElement(
            head,
            "meta",
            {
                "content": "text/html;charset=utf-8",
                "http-equiv": "content-type",
            },
        )
        style = ET.SubElement(head, "style", type=u"text/css")
        style.append(ET.Comment(Page.theme.stylesheet_text))
        script = ET.SubElement(head, "script", type=u"text/javascript")
        script_text = ET.Comment(JavascriptLibrary.collapsible)
        script.append(script_text)

        self.stream = self.open()
        body = ET.SubElement(self.html, "body")
        self.suite = ET.SubElement(body, "div", {"class": "behave"})

        # Summary
        self.header = ET.SubElement(self.suite, "div", id="behave-header")
        label = ET.SubElement(self.header, "div", id="label")
        self.title_el = ET.SubElement(label, "h1")
        self.title_el.text = self.title

        summary = ET.SubElement(self.header, "div", id="summary")

        totals = ET.SubElement(summary, "p", id="totals")

        self.current_feature_totals = ET.SubElement(totals, "p", id="feature_totals")
        self.scenario_totals = ET.SubElement(totals, "p", id="scenario_totals")
        self.step_totals = ET.SubElement(totals, "p", id="step_totals")
        self.duration = ET.SubElement(summary, "p", id="duration")

        # -- PART: Expand/Collapse All
        expand_collapse = ET.SubElement(summary, "div", id="expand-collapse")
        expander = ET.SubElement(expand_collapse, "a", id="expander", href="#")
        expander.set("onclick", "Collapsible_expandAll('scenario_steps')")
        expander.text = u"Expand All"
        cea_spacer = ET.SubElement(expand_collapse, "span")
        cea_spacer.text = u" | "
        collapser = ET.SubElement(expand_collapse, "a", id="collapser", href="#")
        collapser.set("onclick", "Collapsible_collapseAll('scenario_steps')")
        collapser.text = u"Collapse All"
        cea_spacer = ET.SubElement(expand_collapse, "span")
        cea_spacer.text = u" | "
        expander = ET.SubElement(expand_collapse, "a", id="failed_expander", href="#")
        expander.set("onclick", "Collapsible_expandAllFailed()")
        expander.text = u"Expand All Failed"

        self.embed_id = 0
        self.embed_in_this_step = None
        self.embed_data = None
        self.embed_mime_type = None
        self.last_scenario = None
        self.scenario_id = 0
Example #21
0
    def __setitem__(self, key, value):
        self._lookup[key] = value
        for node in self._elems:
            if node.attrib['name'] != key: continue
            type = node.attrib['type'].lower()

            if value is None:
                pass
            elif type == 'string':
                if not isinstance(value, basestring):
                    raise TypeError('String UDF requires str or unicode value')
            elif type == 'str':
                if not isinstance(value, basestring):
                    raise TypeError('String UDF requires str or unicode value')
            elif type == 'text':
                if not isinstance(value, basestring):
                    raise TypeError('Text UDF requires str or unicode value')
            elif type == 'numeric':
                if not isinstance(value, (int, float)):
                    raise TypeError('Numeric UDF requires int or float value')
                value = str(value)
            elif type == 'boolean':
                if not isinstance(value, bool):
                    raise TypeError('Boolean UDF requires bool value')
                value = value and 'True' or 'False'
            elif type == 'date':
                if not isinstance(value, datetime.date): # Too restrictive?
                    raise TypeError('Date UDF requires datetime.date value')
                value = str(value)
            elif type == 'uri':
                if not isinstance(value, basestring):
                    raise TypeError('URI UDF requires str or punycode (unicode) value')
                value = str(value)
            else:
                raise NotImplemented("UDF type '%s'" % type)
            if not isinstance(value, unicode):
                value = unicode(value, 'UTF-8')
            node.text = value
            break
        else:                           # Create new entry; heuristics for type
            if isinstance(value, basestring):
                type = '\n' in value and 'Text' or 'String'
            elif isinstance(value, (int, float)):
                type = 'Numeric'
            elif isinstance(value, bool):
                type = 'Boolean'
                value = value and 'True' or 'False'
            elif isinstance(value, datetime.date):
                type = 'Date'
                value = str(value)
            else:
                raise NotImplementedError("Cannot handle value of type '%s'"
                                          " for UDF" % type(value))
            if self._udt:
                root = self.instance.root.find(nsmap('udf:type'))
            else:
                root = self.instance.root
            elem = ElementTree.SubElement(root,
                                          nsmap('udf:field'),
                                          type=type,
                                          name=key)
            if not isinstance(value, unicode):
                value = unicode(str(value), 'UTF-8')
            elem.text = value
    def match(self, match):
        if self.actual is None or self.actual.get("next_step", None) is None:
            self.actual = self.first_step
        else:
            self.actual = self.actual["next_step"]

        step_el = ET.SubElement(self.steps, "li")
        step_name = ET.SubElement(step_el, "div", {"class": "step_name"})

        keyword = ET.SubElement(step_name, "span", {"class": "keyword"})
        keyword.text = self.actual["keyword"] + u" "

        step_text = ET.SubElement(step_name, "span", {"class": "step val"})

        step_duration = ET.SubElement(step_name, "small", {"class": "step_duration"})

        step_file = ET.SubElement(step_el, "div", {"class": "step_file"})

        self.actual["act_step_embed_span"] = ET.SubElement(step_el, "span")
        self.actual["act_step_embed_span"].set("class", "embed")

        self.actual["step_el"] = step_el

        self.actual["step_duration_el"] = step_duration

        if match.arguments:
            text_start = 0
            for argument in match.arguments:
                step_part = ET.SubElement(step_text, "span")
                step_part.text = self.actual["name"][text_start : argument.start]
                ET.SubElement(step_text, "b").text = str(argument.value)
                text_start = argument.end
            step_part = ET.SubElement(step_text, "span")
            step_part.text = self.actual["name"][match.arguments[-1].end :]
        else:
            step_text.text = self.actual["name"]

        if match.location:
            if match.location.filename.startswith("../"):
                fname = abspath(match.location.filename)
            else:
                fname = match.location.filename
            location = "%s:%s" % (fname, match.location.line)
        else:
            location = "<unknown>"
        ET.SubElement(step_file, "span").text = location
Example #23
0
	def add_map_size(self,map,map_size):
		self.MAP_SIZE = ET.SubElement(MAP_DEF,'map-size')
    def _doEmbed(self, span, mime_type, data, caption):
        self.embed_id += 1

        link = ET.SubElement(span, "a")
        link.set("onclick", "Collapsible_toggle('embed_%s')" % self.embed_id)

        if "video/" in mime_type:
            if not caption:
                caption = u"Video"
            link.text = six.u(caption)

            embed = ET.SubElement(
                span,
                "video",
                {
                    "id": "embed_%s" % self.embed_id,
                    "style": "display: none",
                    "width": "1024",
                    "controls": "",
                },
            )
            embed.tail = u"    "
            ET.SubElement(
                embed,
                "source",
                {"src": u"data:%s;base64,%s" % (mime_type, data), "type": mime_type},
            )

        if "image/" in mime_type:
            if not caption:
                caption = u"Screenshot"
            link.text = six.u(caption)

            embed = ET.SubElement(
                span,
                "img",
                {
                    "id": "embed_%s" % self.embed_id,
                    "style": "display: none",
                    "src": u"data:%s;base64,%s" % (mime_type, data),
                },
            )
            embed.tail = u"    "

        if "text/" in mime_type:
            if not caption:
                caption = u"Data"
            link.text = six.u(caption)

            cleaned_data = "".join(c for c in data if _valid_XML_char_ordinal(ord(c)))

            embed = ET.SubElement(
                span,
                "pre",
                {
                    "id": "embed_%s" % self.embed_id,
                    "style": "display: none",
                },
            )
            embed.text = six.u(cleaned_data)
            embed.tail = u"    "

        if mime_type == "link":
            if not caption:
                caption = u"Link"
            link.text = six.u(caption)

            embed_div = ET.SubElement(
                span,
                "div",
                {
                    "id": "embed_%s" % self.embed_id,
                    "style": "display: none",
                },
            )
            for single_link in data:
                breakline = ET.SubElement(embed_div, "br")
                embed_string = ET.SubElement(embed_div, "a")
                embed_string.set("href", single_link[0])
                embed_string.text = single_link[1]
            breakline = ET.SubElement(embed_div, "br")
            breakline = ET.SubElement(embed_div, "br")
Example #25
0
def rbridge_id_vrf_address_family_ipv6_unicast_ipv6_route_link_local_static_route_nh_link_local_static_route_dest(
        **kwargs):
    """Auto Generated Code
    """
    config = ET.Element("config")
    rbridge_id = ET.SubElement(config,
                               "rbridge-id",
                               xmlns="urn:brocade.com:mgmt:brocade-rbridge")
    if kwargs.pop('delete_rbridge_id', False) is True:
        delete_rbridge_id = config.find('.//*rbridge-id')
        delete_rbridge_id.set('operation', 'delete')

    rbridge_id_key = ET.SubElement(rbridge_id, "rbridge-id")
    rbridge_id_key.text = kwargs.pop('rbridge_id')
    if kwargs.pop('delete_rbridge_id', False) is True:
        delete_rbridge_id = config.find('.//*rbridge-id')
        delete_rbridge_id.set('operation', 'delete')

    vrf = ET.SubElement(rbridge_id,
                        "vrf",
                        xmlns="urn:brocade.com:mgmt:brocade-vrf")
    if kwargs.pop('delete_vrf', False) is True:
        delete_vrf = config.find('.//*vrf')
        delete_vrf.set('operation', 'delete')

    vrf_name_key = ET.SubElement(vrf, "vrf-name")
    vrf_name_key.text = kwargs.pop('vrf_name')
    if kwargs.pop('delete_vrf_name', False) is True:
        delete_vrf_name = config.find('.//*vrf-name')
        delete_vrf_name.set('operation', 'delete')

    address_family = ET.SubElement(vrf, "address-family")
    if kwargs.pop('delete_address_family', False) is True:
        delete_address_family = config.find('.//*address-family')
        delete_address_family.set('operation', 'delete')

    ipv6 = ET.SubElement(address_family, "ipv6")
    if kwargs.pop('delete_ipv6', False) is True:
        delete_ipv6 = config.find('.//*ipv6')
        delete_ipv6.set('operation', 'delete')

    unicast = ET.SubElement(ipv6, "unicast")
    if kwargs.pop('delete_unicast', False) is True:
        delete_unicast = config.find('.//*unicast')
        delete_unicast.set('operation', 'delete')

    ipv6 = ET.SubElement(unicast,
                         "ipv6",
                         xmlns="urn:brocade.com:mgmt:brocade-ipv6-rtm")
    if kwargs.pop('delete_ipv6', False) is True:
        delete_ipv6 = config.find('.//*ipv6')
        delete_ipv6.set('operation', 'delete')

    route = ET.SubElement(ipv6, "route")
    if kwargs.pop('delete_route', False) is True:
        delete_route = config.find('.//*route')
        delete_route.set('operation', 'delete')

    link_local_static_route_nh = ET.SubElement(route,
                                               "link-local-static-route-nh")
    if kwargs.pop('delete_link_local_static_route_nh', False) is True:
        delete_link_local_static_route_nh = config.find(
            './/*link-local-static-route-nh')
        delete_link_local_static_route_nh.set('operation', 'delete')

    link_local_nexthop_key = ET.SubElement(link_local_static_route_nh,
                                           "link-local-nexthop")
    link_local_nexthop_key.text = kwargs.pop('link_local_nexthop')
    if kwargs.pop('delete_link_local_nexthop', False) is True:
        delete_link_local_nexthop = config.find('.//*link-local-nexthop')
        delete_link_local_nexthop.set('operation', 'delete')

    link_local_route_oif_type_key = ET.SubElement(link_local_static_route_nh,
                                                  "link-local-route-oif-type")
    link_local_route_oif_type_key.text = kwargs.pop(
        'link_local_route_oif_type')
    if kwargs.pop('delete_link_local_route_oif_type', False) is True:
        delete_link_local_route_oif_type = config.find(
            './/*link-local-route-oif-type')
        delete_link_local_route_oif_type.set('operation', 'delete')

    link_local_route_oif_name_key = ET.SubElement(link_local_static_route_nh,
                                                  "link-local-route-oif-name")
    link_local_route_oif_name_key.text = kwargs.pop(
        'link_local_route_oif_name')
    if kwargs.pop('delete_link_local_route_oif_name', False) is True:
        delete_link_local_route_oif_name = config.find(
            './/*link-local-route-oif-name')
        delete_link_local_route_oif_name.set('operation', 'delete')

    link_local_static_route_dest = ET.SubElement(
        link_local_static_route_nh, "link-local-static-route-dest")
    if kwargs.pop('delete_link_local_static_route_dest', False) is True:
        delete_link_local_static_route_dest = config.find(
            './/*link-local-static-route-dest')
        delete_link_local_static_route_dest.set('operation', 'delete')

    link_local_static_route_dest.text = kwargs.pop(
        'link_local_static_route_dest')

    callback = kwargs.pop('callback', _callback)
    return callback(config, mgr=kwargs.pop('mgr'))
 def set_title(self, title, append=False, tag="span", **kwargs):
     if not append:
         self.title_el.clear()
     ET.SubElement(self.title_el, tag, kwargs).text = title
Example #27
0
def construct_xml_document(pascal_coordinates: List[int], class_name: str,
                           class_id: int, output_file_path: str, height: int,
                           width: int) -> ET.ElementTree:
    """
    Creates a new XML annotation file for a particular frame, and adds one bounding box

    Args:
        pascal_coordinates: The Pascal-VOC bounding box
            coordinates (x-top left, y-top left, x-bottom right, y-bottom right)
        class_name: The class name of the annotated object
        class_id: The class ID of the annotated object
        output_file_path: The path + filename of the XML file to be created (the frame number is embedded within the
            output filename)
        height: The height in pixels of each input frame
        width: The width in pixels of each input frame

    Returns:
        xml_tree: The tree representing the XML annotation file
    """
    # Create root element as <annotation>...</annotation>
    root = ET.Element("annotation")

    # Create folder element as <folder>...</folder>
    folder_element = ET.Element("folder")
    folder_element.text = get_folder_or_file_name(FLAGS.output_folder)
    root.append(folder_element)

    # Create filename element as <filename>...</filename>
    filename_element = ET.Element("filename")
    filename_element.text = get_folder_or_file_name(output_file_path)
    root.append(filename_element)

    # Create source element as <source>...</source>
    source_element = ET.Element("source")
    root.append(source_element)
    # Add subelements to <source> element
    database_element = ET.SubElement(source_element, "database")
    database_element.text = "PEViD-UHD"
    annotation_element = ET.SubElement(source_element, "annotation")
    annotation_element.text = "PEViD-UHD"
    image_element = ET.SubElement(source_element, "image")
    image_element.text = "EPFL"
    url_element = ET.SubElement(source_element, "url")
    url_element.text = "https://alabama.app.box.com/folder/124516925859"

    # Create size element as <size>...</size>
    size_element = ET.Element("size")
    root.append(size_element)
    # Add subelemnts to <size> element
    width_element = ET.SubElement(size_element, "width")
    width_element.text = str(width)
    height_element = ET.SubElement(size_element, "height")
    height_element.text = str(height)
    depth_element = ET.SubElement(size_element, "depth")
    depth_element.text = str(3)

    # Create segmented element as <segmented>...</segmented>
    segmented_element = ET.Element("segmented")
    segmented_element.text = str(0)
    root.append(segmented_element)

    # Create object element as <object>...</object>
    object_element = ET.Element("object")
    root.append(object_element)
    # Create name subelement
    name_element = ET.SubElement(object_element, "name")
    name_element.text = class_name
    # Create bounding box subelement and add coordinates
    bndbox_element = ET.SubElement(object_element, "bndbox")
    xmin_element = ET.SubElement(bndbox_element, "xmin")
    xmin_element.text = str(pascal_coordinates[0])
    ymin_element = ET.SubElement(bndbox_element, "ymin")
    ymin_element.text = str(pascal_coordinates[3])
    xmax_element = ET.SubElement(bndbox_element, "xmax")
    xmax_element.text = str(pascal_coordinates[2])
    ymax_element = ET.SubElement(bndbox_element, "ymax")
    ymax_element.text = str(pascal_coordinates[1])

    xml_tree = ET.ElementTree(root)
    return xml_tree
Example #28
0
def _project_required_xml(publication):
    project_body = publication['project']
    proj = project_body['value']
    xml_obj = _project_header()

    resource = xml_obj
    identifier = ET.SubElement(resource, 'identifier')
    identifier.attrib['identifierType'] = 'DOI'
    if project_body.get('doi', ''):
        identifier.text = project_body.get('doi')
    else:
        identifier.text = SHOULDER.replace('doi:', '')
    creators = ET.SubElement(resource, 'creators')
    #um = get_user_model()
    users = sorted(publication['users'], key=lambda x: x['_ui']['order'])
    for author in users:
        creator = ET.SubElement(creators, 'creator')
        creator_name = ET.SubElement(creator, 'creatorName')
        creator_name.text = '{}, {}'.format(author['last_name'], author['first_name'])

    titles = ET.SubElement(resource, 'titles')
    title = ET.SubElement(titles, 'title')
    title.text = proj['title']
    publisher = ET.SubElement(resource, 'publisher')
    publisher.text = 'Designsafe-CI'

    now = dateutil.parser.parse(publication['created'])
    publication_year = ET.SubElement(resource, 'publicationYear')
    publication_year.text = str(now.year)

    resource_type = ET.SubElement(resource, 'resourceType')
    resource_type.text = "Project/{}".format(proj['projectType'].title())
    resource_type.attrib['resourceTypeGeneral'] = 'Dataset'
    descriptions = ET.SubElement(resource, 'descriptions')
    desc = ET.SubElement(descriptions, 'description')
    desc.attrib['descriptionType'] = 'Abstract'
    desc.text = proj['description']
    return xml_obj
Example #29
0
 def add_urdf_elements(self, node, link_pose):
   inertialnode = ET.SubElement(node, 'inertial')
   massnode = ET.SubElement(inertialnode, 'mass', {'value': str(self.mass)})
   pose2origin(inertialnode, self.pose)  # inertial reference frame is relative to the link reference frame in URDF and SDF
   self.inertia.add_urdf_elements(inertialnode)
    def write_to_dir(self, path):
        SpriteSheet = ET.Element("SpriteSheet", {
            "a": str(self.max_components),
            "b": str(self.num_variations),
        })

        PaletteList = ET.SubElement(SpriteSheet, "PaletteList")
        RasterList = ET.SubElement(SpriteSheet, "RasterList")
        AnimationList = ET.SubElement(SpriteSheet, "AnimationList")

        palette_to_raster = {}

        for i, image in enumerate(self.images):
            name = self.image_names[i] if self.image_names else f"Raster_{i:02X}"
            image.write(path / (name + ".png"), self.palettes[image.palette_index])

            if image.palette_index not in palette_to_raster:
                palette_to_raster[image.palette_index] = []
            palette_to_raster[image.palette_index].append(image)

            ET.SubElement(RasterList, "Raster", {
                "id": f"{i:X}",
                "palette": f"{image.palette_index:X}",
                "src": name + ".png",
            })

        for i, palette in enumerate(self.palettes):
            name = self.palette_names[i] if self.palette_names else f"Palette_{i:02X}"

            if i in palette_to_raster:
                img = palette_to_raster[i][0]
            else:
                img = self.images[0]

            img.write(path / (name + ".png"), palette)

            ET.SubElement(PaletteList, "Palette", {
                "id": f"{i:X}",
                "src": name + ".png",
            })

        for i, components in enumerate(self.animations):
            Animation = ET.SubElement(AnimationList, "Animation", {
                "name": self.animation_names[i] if self.animation_names else f"Anim_{i:X}",
            })

            for j, comp in enumerate(components):
                Component = ET.SubElement(Animation, "Component", {
                    "name": f"Comp_{j:X}",
                    "xyz": ",".join(map(str, [comp.x, comp.y, comp.z])),
                })

                for cmd in comp.commands:
                    ET.SubElement(Component, "Command", {"val": f"{cmd:X}"})

        xml = ET.ElementTree(SpriteSheet)

        # pretty print (Python 3.9+)
        if hasattr(ET, "indent"):
            ET.indent(xml, "    ")

        xml.write(str(path / "SpriteSheet.xml"), encoding="unicode")