def setBody(self, body, title='', is_error=0, bogus_str_search=None): if isinstance(body, Fault): # Convert Fault object to SOAP response. body = body.AsSOAP() else: # Marshall our body as an SOAP response. Strings will be sent # strings, integers as integers, etc. We do *not* convert # everything to a string first. try: target = self._method body = premarshal(body) result = body if hasattr(result, 'typecode'): tc = result.typecode else: tc = TC.Any(aslist=1, pname=target + 'Response') result = [result] sw = SoapWriter(nsdict={}, header=True, outputclass=None, encodingStyle=None) body = str(sw.serialize(result, tc)) Node.unlink(sw.dom.node) Node.unlink(sw.body.node) del sw.dom.node del sw.body.node del sw.dom del sw.body except: self.exception() return # Set our body to the message, and fix our MIME type. self._real.setBody(body) self._setHeader() return self
def handle_tile_layer(layer: minidom.Node, builder: flatbuffers.Builder) -> int: width = int(layer.getAttribute('width')) height = int(layer.getAttribute('height')) tilewidth = float(layer.parentNode.getAttribute('tilewidth')) tileheight = float(layer.parentNode.getAttribute('tileheight')) dataNode = layer.getElementsByTagName('data')[0] if dataNode.firstChild is None: return dataString = dataNode.firstChild.nodeValue rows = dataString.splitlines() data = [] for row in rows: for tile in row.split(','): if tile == '': continue data.append(int(tile)) FlatBuffGenerated.Tilelayer.TilelayerStartTiledataVector( builder, len(data)) for tile in reversed(data): builder.PrependInt16(tile) dataOffset = builder.EndVector(len(data)) FlatBuffGenerated.Tilelayer.TilelayerStart(builder) FlatBuffGenerated.Tilelayer.TilelayerAddWidth(builder, width) FlatBuffGenerated.Tilelayer.TilelayerAddHeight(builder, height) tilesize = FlatBuffGenerated.Vec2.CreateVec2(builder, tilewidth, tileheight) FlatBuffGenerated.Tilelayer.TilelayerAddTilesize(builder, tilesize) FlatBuffGenerated.Tilelayer.TilelayerAddTiledata(builder, dataOffset) return FlatBuffGenerated.Tilelayer.TilelayerEnd(builder)
def add_class(node: minidom.Node, class_name: str): if 'class' not in node.attributes: node.attributes['class'] = class_name return node.attributes[ 'class'] = node.attributes['class'].value + f' {class_name}'
def _vtag_data(element: minidom.Node, tag: str) -> List[str]: for name in tag.split("/"): new_element = element.getElementsByTagName(name) if not new_element: return [] element = new_element[0] elements = element.getElementsByTagName("element") return [x.firstChild.data for x in elements if x.firstChild]
def handle_tileset(ts: minidom.Node, objs: GameObjects, builder: flatbuffers.Builder): firstgid = int(ts.getAttribute('firstgid')) for t in ts.getElementsByTagName('tile'): gid = int(t.getAttribute('id')) + firstgid name = os.path.basename( t.getElementsByTagName('image')[0].getAttribute('source')) fbname = builder.CreateString(name) FlatBuffGenerated.Tileinfo.TileinfoStart(builder) FlatBuffGenerated.Tileinfo.TileinfoAddName(builder, fbname) FlatBuffGenerated.Tileinfo.TileinfoAddGid(builder, gid) objs.tileinfo.append(FlatBuffGenerated.Tileinfo.TileinfoEnd(builder))
def _extract_track_data(track: Node): track_mbid = pylast._extract(track, "mbid") track_title = pylast._extract(track, "name") timestamp = dt.datetime.fromtimestamp( int(track.getElementsByTagName("date")[0].getAttribute("uts"))) artist_name = pylast._extract(track, "artist") artist_mbid = track.getElementsByTagName("artist")[0].getAttribute("mbid") album_title = pylast._extract(track, "album") album_mbid = track.getElementsByTagName("album")[0].getAttribute("mbid") # TODO: could call track/album/artist.getInfo here, and get more info? # Handle missing titles if album_title is None: album_title = "(unknown album)" # If we don't have mbids, synthesize them if not artist_mbid: artist_mbid = "md5:" + hashlib.md5( artist_name.encode("utf8")).hexdigest() if not album_mbid: h = hashlib.md5() h.update(artist_mbid.encode("utf8")) h.update(album_title.encode("utf8")) album_mbid = "md5:" + h.hexdigest() if not track_mbid: h = hashlib.md5() h.update(album_mbid.encode("utf8")) h.update(track_title.encode("utf8")) track_mbid = "md5:" + h.hexdigest() return { "artist": { "id": artist_mbid, "name": artist_name }, "album": { "id": album_mbid, "title": album_title, "artist_id": artist_mbid }, "track": { "id": track_mbid, "album_id": album_mbid, "title": track_title }, "play": { "track_id": track_mbid, "timestamp": timestamp }, }
def remove_whitespace_only_nodes(node: Node): """Removes all of the whitespace-only text descendants of a DOM node. :param node: Node to cleanup If the specified node is a whitespace-only text node then it is left unmodified. """ remove_list = [] for child in node.childNodes: # Below if returns true for TEXT_NODE which contains no characters # other than spaces and old lines if child.nodeType == Node.TEXT_NODE and not child.data.strip(): remove_list.append(child) elif child.hasChildNodes(): remove_whitespace_only_nodes(child) for node in remove_list: node.parentNode.removeChild(node) node.unlink() # Garbage collect unneeded Nodes
def handle_decoration_layer(g: minidom.Node, objs: GameObjects, builder: flatbuffers.Builder): for o in g.getElementsByTagName('object'): x, y, rot = get_pos(o) width, height = get_dim(o) gid = int(o.getAttribute('gid')) FlatBuffGenerated.Decoration.DecorationStart(builder) pos = FlatBuffGenerated.Vec2.CreateVec2(builder, x * GLOBAL_SCALE, y * GLOBAL_SCALE) FlatBuffGenerated.Decoration.DecorationAddPos(builder, pos) FlatBuffGenerated.Decoration.DecorationAddRotation(builder, rot) size = FlatBuffGenerated.Vec2.CreateVec2(builder, width, height) FlatBuffGenerated.Decoration.DecorationAddSize(builder, size) FlatBuffGenerated.Decoration.DecorationAddGid(builder, gid) objs.decoration.append( FlatBuffGenerated.Decoration.DecorationEnd(builder))
def create_text(handle: IO[bytes], text: Node, tokens: Dict[str, int], depth: int) -> bool: if text.data.strip() == "": return False if text.data[0] != "$": return create_cdata(handle, text, depth) text.data = text.data[1:] tokens[text.data] = 1 handle.write(b"\t" * depth) handle.write(b"replace( ") handle.write(text.data.encode("utf-8")) handle.write(b" )\n") return True
def handle_hidingspots_layer(g: minidom.Node, objs: GameObjects, builder: flatbuffers.Builder): for o in g.getElementsByTagName('object'): x, y, rotation = get_pos(o) poly = 0 width = 0 height = 0 isCircle = False if not o.getElementsByTagName('polygon'): width, height = get_dim(o) x += (math.cos(math.radians(rotation)) * width / 2.0 - math.sin(math.radians(rotation)) * height / 2.0) y += (math.cos(math.radians(rotation)) * height / 2.0 + math.sin(math.radians(rotation)) * width / 2.0) if o.getElementsByTagName('ellipse'): assertCircleness(o) isCircle = True else: polyverts = getPolygonVertices(o) FlatBuffGenerated.HidingSpot.HidingSpotStartPolyvertsVector( builder, len(polyverts)) for v in polyverts: vert_x, vert_y = v.split(",") vert_x_f = float(vert_x) * GLOBAL_SCALE vert_y_f = float(vert_y) * GLOBAL_SCALE FlatBuffGenerated.Vec2.CreateVec2(builder, vert_x_f, vert_y_f) poly = builder.EndVector(len(polyverts)) name = builder.CreateString(o.getAttribute('name')) FlatBuffGenerated.HidingSpot.HidingSpotStart(builder) pos = FlatBuffGenerated.Vec2.CreateVec2(builder, x * GLOBAL_SCALE, y * GLOBAL_SCALE) FlatBuffGenerated.HidingSpot.HidingSpotAddPos(builder, pos) FlatBuffGenerated.HidingSpot.HidingSpotAddRotation(builder, rotation) size = FlatBuffGenerated.Vec2.CreateVec2(builder, width * GLOBAL_SCALE, height * GLOBAL_SCALE) FlatBuffGenerated.HidingSpot.HidingSpotAddSize(builder, size) FlatBuffGenerated.HidingSpot.HidingSpotAddIsCircle(builder, isCircle) FlatBuffGenerated.HidingSpot.HidingSpotAddPolyverts(builder, poly) FlatBuffGenerated.HidingSpot.HidingSpotAddName(builder, name) objs.hidingspots.append( FlatBuffGenerated.HidingSpot.HidingSpotEnd(builder))
def cloneNode(srcNode: Node, dstDom: Document) -> Node: """ 从源node克隆一个到目标dom :param srcNode: 源node :param dstDom: 目标dom :return: 新node """ if srcNode.nodeType == Node.TEXT_NODE: return dstDom.createTextNode(srcNode.data) elif srcNode.nodeType == Node.COMMENT_NODE: return dstDom.createComment(srcNode.data) elif srcNode.nodeType == Node.ELEMENT_NODE: newNode = dstDom.createElement(srcNode.tagName) attrs = srcNode._get_attributes() for a_name in attrs.keys(): newNode.setAttribute(a_name, attrs[a_name].value) DomXmlUtil.elementAddChildNodes(srcNode.childNodes, dstDom, newNode) return newNode pass
def handle_objects_layer(g: minidom.Node, objs: GameObjects, builder: flatbuffers.Builder): for o in g.getElementsByTagName('object'): x, y, rot = get_pos(o) width, height = get_dim(o) gid = int(o.getAttribute('gid')) hspotname = "" for prop in o.getElementsByTagName("property"): if prop.getAttribute("name") == "hspotName": hspotname = prop.getAttribute("value") hspotNameFb = builder.CreateString(hspotname) FlatBuffGenerated.Object.ObjectStart(builder) pos = FlatBuffGenerated.Vec2.CreateVec2(builder, x * GLOBAL_SCALE, y * GLOBAL_SCALE) FlatBuffGenerated.Object.ObjectAddPos(builder, pos) FlatBuffGenerated.Object.ObjectAddRotation(builder, rot) FlatBuffGenerated.Object.ObjectAddGid(builder, gid) size = FlatBuffGenerated.Vec2.CreateVec2(builder, width, height) FlatBuffGenerated.Object.ObjectAddSize(builder, size) FlatBuffGenerated.Object.ObjectAddHspotname(builder, hspotNameFb) objs.objects.append(FlatBuffGenerated.Object.ObjectEnd(builder))
def get_text_from_tag_name(parent: Node, tag_name: str) -> str: return get_text(parent.getElementsByTagName(tag_name)[0].childNodes)
def create_element(handle: IO[bytes], element: Node, tokens: Dict[str, int], depth: int) -> bool: if element.tagName == "_var": return create_text(handle, element.firstChild, tokens, depth) # Open a new element() macros handle.write(b"\t" * depth) handle.write(b"element(\n") # First argument -- the tag name of the element handle.write(b"\t" * (depth + 1)) handle.write(f'"{element.tagName}",\n'.encode("utf-8")) # Second argument -- list of attributes attrs = element.attributes handle.write(b"\t" * (depth + 1)) if attrs: # Start the attrs() macro handle.write(b"attrs( ") for key in attrs.keys(): val = element.getAttribute(key) # Attribute values that start with $ are replacements # with the replacement token being the rest of the value. if val[0] == "$": tokens[val[1:]] = 1 handle.write(f'at_rep( "{key}", {val[1:]} ), '.encode("utf-8")) # Otherwise, the value is taken as a literal string else: handle.write(f'at_str( "{key}", "{val}" ), '.encode("utf-8")) # Each attribute above ends in ", ". To end the macro, we must # remove this and put the closing bracket. handle.seek(-2, SEEK_CUR) handle.write(b" ),\n") # No attributes just has this list point to NULL else: handle.write(b"NULL,\n") # Third argument: the list of child nodes handle.write(b"\t" * (depth + 1)) if element.hasChildNodes(): handle.write(b"children(\n") for child in element.childNodes: if create_node(handle, child, tokens, depth + 2): handle.seek(-1, SEEK_CUR) handle.write(b",\n") handle.seek(-2, SEEK_CUR) handle.write(b"\n") handle.write(b"\t" * (depth + 1)) handle.write(b")\n") else: handle.write(b"NULL\n") # End the element() macro handle.write(b"\t" * depth) handle.write(b")\n") # We create new code return True
def __init__(self, name: str, parent_node: dom.Node, writer): """Construct from name, parent node and writer object.""" self.writer = writer self.document = writer.document self.node = self.document.createElement(name) parent_node.appendChild(self.node)
def setAttributes(node: dom.Node, attributes: ts.Mapping[str, ts.Any]): """Set attributes of a node.""" for item in attributes.items(): node.setAttribute(*item)
def _tag_value(element: minidom.Node, tag: str) -> Optional[int]: item = element.getElementsByTagName(tag) if item: value = item[0].attributes["value"].value return int(value[0]) return None
def handle_meta_layer(g: minidom.Node, objs: GameObjects, builder: flatbuffers.Builder): for o in g.getElementsByTagName('object'): x, y, rotation = get_pos(o) width, height = get_dim(o) typ = o.getAttribute('type') if typ == 'playerwall': x += (math.cos(math.radians(rotation)) * width / 2.0 - math.sin(math.radians(rotation)) * height / 2.0) y += (math.cos(math.radians(rotation)) * height / 2.0 + math.sin(math.radians(rotation)) * width / 2.0) FlatBuffGenerated.PlayerWall.PlayerWallStart(builder) pos = FlatBuffGenerated.Vec2.CreateVec2(builder, x * GLOBAL_SCALE, y * GLOBAL_SCALE) FlatBuffGenerated.PlayerWall.PlayerWallAddPosition(builder, pos) size = FlatBuffGenerated.Vec2.CreateVec2( builder, width / 2.0 * GLOBAL_SCALE, height / 2.0 * GLOBAL_SCALE) FlatBuffGenerated.PlayerWall.PlayerWallAddSize(builder, size) FlatBuffGenerated.PlayerWall.PlayerWallAddRotation( builder, rotation) pwall = FlatBuffGenerated.PlayerWall.PlayerWallEnd(builder) objs.playerwalls.append(pwall) elif typ == 'waypoint': name = o.getAttribute('name') neighbors = [] isspawn = False isplayerspawn = False assertCircleness(o) x += (math.cos(math.radians(rotation)) * width / 2.0 - math.sin(math.radians(rotation)) * height / 2.0) y += (math.cos(math.radians(rotation)) * height / 2.0 + math.sin(math.radians(rotation)) * width / 2.0) radius = (width / 2.0) * GLOBAL_SCALE for prop in o.getElementsByTagName('property'): prop_name = prop.getAttribute('name') value = prop.getAttribute('value') if prop_name == 'wps': neighbors = value.split(',') elif prop_name == 'isspawn': isspawn = (value == 'true') elif prop_name == 'isplayerspawn': isplayerspawn = (value == 'true') else: print("WARNING: Unknown property {}".format(prop_name)) neighbors = list(filter(lambda x: x.strip() != "", neighbors)) if len(neighbors) < 2 and not isplayerspawn and not isspawn: print("WARNING: waypoint {} has < 2 neighbors".format(name)) name = builder.CreateString(name) neighOff = [builder.CreateString(x) for x in neighbors] FlatBuffGenerated.NavPoint.NavPointStartNeighborsVector( builder, len(neighOff)) for b in neighOff: builder.PrependUOffsetTRelative(b) neighs = builder.EndVector(len(neighOff)) FlatBuffGenerated.NavPoint.NavPointStart(builder) pos = FlatBuffGenerated.Vec2.CreateVec2(builder, x * GLOBAL_SCALE, y * GLOBAL_SCALE) FlatBuffGenerated.NavPoint.NavPointAddPosition(builder, pos) FlatBuffGenerated.NavPoint.NavPointAddRadius(builder, radius) FlatBuffGenerated.NavPoint.NavPointAddName(builder, name) FlatBuffGenerated.NavPoint.NavPointAddNeighbors(builder, neighs) FlatBuffGenerated.NavPoint.NavPointAddIsspawn(builder, isspawn) FlatBuffGenerated.NavPoint.NavPointAddIsplayerspawn( builder, isplayerspawn) objs.navpoints.append( FlatBuffGenerated.NavPoint.NavPointEnd(builder))
def _node_to_dict(self, node: minidom.Node) -> dict: """ <node atr1="val1" atr2="val2></node> convert to "node": { "atr1":"val1", "atr2":"val2", "atr3":"val3" } AND <node> <atr1>val1</atr1> <atr2>val1</atr2> </node> *** will be convert to "node": { "atr1":"val1", "atr2":"val2", "atr3":"val3" } ////////////////////////////////////////////////// <node> <row>element1</row> <row>element2</row> <row>element3</row> </node> *** will be convert to "node":["element1","element2", "element3"] ////////////////////////////////////////////////// <node> <subnode>subnode value</subnode> <row>element1</row> <row>element2</row> <row>element3</row> </node> *** will be convert to "node":{ "subnode": "subnode value", "row": ["element1","element2", "element3"] } """ result = {} if isinstance(node, minidom.Document): if node.hasChildNodes(): return self._node_to_dict(node.childNodes[0]) else: return XDict() if not isinstance(node, minidom.Element): return XDict() attributes = node.attributes if attributes is None: no_attributes = True else: no_attributes = False result = dict(attributes.items()) values = {} for _node in node.childNodes: if isinstance(_node, minidom.Element): name = _node.tagName text = _node.firstChild if text is not None: text = text.data.strip() if text == '': text = None if text is None: value = self._node_to_dict(_node) else: if no_attributes: result['#text'] = text continue else: value = text if name in values: values[name].append(value) else: values[name] = [value] if len(values) == 1: result = values[list(values.keys())[0]] else: for name in values: value = values[name] if len(value) == 1: value = value[0] result[name] = value #result[name] = self._node_to_dict(_node) return result
def get_pos(o: minidom.Node) -> (float, float, float): x = float(o.getAttribute('x')) y = float(o.getAttribute('y')) rotation = float(o.getAttribute('rotation') or 0) return x, y, rotation
def get_dim(o: minidom.Node) -> (float, float): w = float(o.getAttribute('width') or 0) h = float(o.getAttribute('height') or 0) return w, h