def write (self, etree_xml): """ Write an etree ELement or ElementTree to the output. :Parameters: etree_xml An etree ELement or ElementTree. """ # find the node at the top of the tree if (iselement (etree_xml)): assert (hasattr (etree_xml, 'tag')) root = etree_xml else: assert (hasattr (etree_xml, '_root')) root = etree_xml._root # if pretty-printing, indent a copy if (self.prettyprint): root = deepcopy (root) indent (root) # rewind and output, including header outtree = ElementTree (root) self.hndl.seek (0) self.hndl.write ("<?xml version='1.0' encoding='%s'?>\n" % self.encoding) outtree._write (self.hndl, root, self.encoding, {})
def _gen_constructor(name, name_mangled, classname, args, doc=None, cpppxd_filename=None, inst_name="self._inst"): argfill = ", ".join(['self'] + [a[0] for a in args if 2 == len(a)] + \ ["{0}={1}".format(a[0], a[2]) for a in args if 3 == len(a)]) lines = ['def {0}({1}):'.format(name_mangled, argfill)] lines += [] if doc is None else indent('\"\"\"{0}\"\"\"'.format(doc), join=False) decls = [] argbodies = [] argrtns = {} for a in args: adecl, abody, artn = cython_py2c(a[0], a[1]) if adecl is not None: decls += indent(adecl, join=False) if abody is not None: argbodies += indent(abody, join=False) argrtns[a[0]] = artn argvals = ', '.join([argrtns[a[0]] for a in args]) classname = classname if cpppxd_filename is None else \ "{0}.{1}".format(cpppxd_filename.rsplit('.', 1)[0], classname) fcall = 'self._inst = new {0}({1})'.format(classname, argvals) func_call = indent(fcall, join=False) lines += decls lines += argbodies lines += func_call lines += ['', ""] return lines
def read(self, filenames): if isinstance(filenames, basestring): self._read0(filenames) else: for file in filenames: self._read0(file) if self.etree: indent(self.etree.getroot())
def __save_xml(self): """Adds a header and indents the xml tree before saving it to disk.""" utils.debug_print("Saved download list to: %s" % self.download_file_path) file = open(self.download_file_path, "w") file.write(XML_HEADER) utils.indent(self.tree.getroot()) self.tree.write(file) file.close()
def singleNode(self, indexnumber, tagname, mediatype, itemtype): tagname = tryEncode(tagname) cleantagname = normalize_nodes(tagname) nodepath = tryDecode(xbmc.translatePath( "special://profile/library/video/")) nodeXML = "%splex_%s.xml" % (nodepath, cleantagname) path = "library://video/plex_%s.xml" % cleantagname if self.kodiversion >= 17: # Krypton windowpath = "ActivateWindow(Videos,%s,return)" % path else: windowpath = "ActivateWindow(Video,%s,return)" % path # Create the video node directory if not xbmcvfs.exists(nodepath): # We need to copy over the default items shutil.copytree( src=tryDecode(xbmc.translatePath( "special://xbmc/system/library/video")), dst=tryDecode(xbmc.translatePath( "special://profile/library/video"))) xbmcvfs.exists(path) labels = { 'Favorite movies': 30180, 'Favorite tvshows': 30181, 'channels': 30173 } label = lang(labels[tagname]) embynode = "Plex.nodes.%s" % indexnumber window('%s.title' % embynode, value=label) window('%s.path' % embynode, value=windowpath) window('%s.content' % embynode, value=path) window('%s.type' % embynode, value=itemtype) if xbmcvfs.exists(nodeXML): # Don't recreate xml if already exists return if itemtype == "channels": root = self.commonRoot(order=1, label=label, tagname=tagname, roottype=2) etree.SubElement(root, 'path').text = "plugin://plugin.video.plexkodiconnect/?id=0&mode=channels" else: root = self.commonRoot(order=1, label=label, tagname=tagname) etree.SubElement(root, 'order', {'direction': "ascending"}).text = "sorttitle" etree.SubElement(root, 'content').text = mediatype try: indent(root) except: pass etree.ElementTree(root).write(nodeXML)
def _gen_property_get(name, t, cached_names=None, inst_name="self._inst"): """This generates a Cython property getter for a variable of a given name and type.""" lines = ['def __get__(self):'] decl, body, rtn, iscached = cython_c2py(name, t, inst_name=inst_name) if decl is not None: lines += indent(decl, join=False) if body is not None: lines += indent(body, join=False) if iscached and cached_names is not None: cached_names.append(rtn) lines += indent("return {0}".format(rtn), join=False) return lines
def _gen_property_set(name, t, inst_name="self._inst", cached_name=None): """This generates a Cython property setter for a variable of a given name and type.""" lines = ['def __set__(self, value):'] decl, body, rtn = cython_py2c('value', t) if decl is not None: lines += indent(decl, join=False) if body is not None: lines += indent(body, join=False) lines += indent("{0}.{1} = {2}".format(inst_name, name, rtn), join=False) if cached_name is not None: lines += indent("{0} = None".format(cached_name), join=False) return lines
def render(self): """ Produces LaTeX code for this image. @rtype: string @return: LaTeX code for this plot """ tex = '\\addplot[point meta min={0:5f}, point meta max={1:5f}] graphics\n'.format(self.vmin, self.vmax) tex += indent('[xmin={0},xmax={1},ymin={2},ymax={3}]\n'.format(*self.limits())) tex += indent('{' + path.join(Settings.image_folder, self.filename()) + '};\n') return tex
def write(self, filename): root = ET.Element('ANNOTATION_DOCUMENT') root.set('AUTHOR', 'SPPAS by Brigitte Bigi') root.set('DATE', str(datetime.datetime.now()).replace(' ', 'T')) root.set('FORMAT', '2.7') root.set('VERSION', '2.7') root.set('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance') root.set( 'xsi:noNamespaceSchemaLocation', 'http://www.mpi.nl.tools/elan/EAFv2.7.xsd') # The Header headerRoot = ET.SubElement(root, 'HEADER') mediaFile = (self.metadata['MEDIA_FILE'] if 'MEDIA_FILE' in self.metadata else '') headerRoot.set('MEDIA_FILE', mediaFile) headerRoot.set('TIME_UNITS', 'milliseconds') # Media in Elan are sub-elements of the header self.__write_media(headerRoot) # Property if 'PROPERTY_NAME' in self.metadata.keys(): propertyRoot = ET.SubElement(headerRoot, 'PROPERTY') propertyRoot.set( 'NAME', self.metadata['PROPERTY_NAME']) propertyRoot.text = self.metadata['PROPERTY_VALUE'] # The list of Time slots self.__build_timeslots() timeOrderRoot = ET.SubElement(root, 'TIME_ORDER') self.__format_timeslots(timeOrderRoot) # Add an id in each annotation (in its metadata) self.__build_annotation_ids() # Tiers for tier in self: tierRoot = ET.SubElement(root, 'TIER') self.__format_tier(tierRoot, tier) # Ctrl Vocab and tier properties self.__write_linguistic_types(root) self.__write_constraints(root) self.__write_ctrl_vocabs(root) del self.timeSlotIds indent(root) tree = ET.ElementTree(root) tree.write(filename, encoding='utf-8', method="xml")
def getProtectedSection(self, parsed, section, ind=0): """Given a parsed python module and a section name, return a string with the protected code-section to be included in the generated module. """ outstring = utils.indent(PyParser.PROTECTED_BEGIN, ind) + u' ' + \ section + u' #fill in your manual code here\n' if parsed: sectioncode = parsed.getProtectedSection(section) if sectioncode: outstring += sectioncode + '\n' outstring += utils.indent(PyParser.PROTECTED_END, ind) + u' ' + section + u'\n' return outstring
def _gen_property(name, t, doc=None, cached_names=None, inst_name="self._inst"): """This generates a Cython property for a variable of a given name and type.""" lines = ['property {0}:'.format(name)] lines += [] if doc is None else indent('\"\"\"{0}\"\"\"'.format(doc), join=False) oldcnlen = 0 if cached_names is None else len(cached_names) lines += indent(_gen_property_get(name, t, cached_names=cached_names, inst_name=inst_name), join=False) lines += [''] newcnlen = 0 if cached_names is None else len(cached_names) cached_name = cached_names[-1] if newcnlen == 1 + oldcnlen else None lines += indent(_gen_property_set(name, t, inst_name=inst_name, cached_name=cached_name), join=False) lines += ['', ""] return lines
def write(self, filename, encoding='UTF-8'): """ Write an Antx file. :param filename: :param encoding: """ try: root = ET.Element('AnnotationSystemDataSet') root.set('xmlns', 'http://tempuri.org/AnnotationSystemDataSet.xsd') # Write layers for tier in self: Antx.__format_tier(root, tier) # Write segments for tier in self: if tier.IsPoint(): tier = point2interval(tier, ANTX_RADIUS) tier = merge_overlapping_annotations(tier) for ann in tier: self.__format_segment(root, tier, ann) # Write media if len(self.GetMedia()) > 0: for media in self.GetMedia(): if media: Antx.__format_media(root, media) # Write configurations for key, value in ELT_REQUIRED_Configuration.items(): Antx.__format_configuration(root, key, self.metadata.get(key, value)) for key, value in self.metadata.items(): if key not in ELT_REQUIRED_Configuration.keys(): Antx.__format_configuration(root, key, self.metadata.get(key, value)) indent(root) tree = ET.ElementTree(root) tree.write(filename, encoding=encoding, xml_declaration=True, method="xml") # TODO: add standalone="yes" in the declaration # (but not available with ElementTree) except Exception: # import traceback # print(traceback.format_exc()) raise
def generateMethodSecurityDeclaration(self, m): # [optilude] Added check for permission:mode - public (default), # private or protected # [jensens] You can also use the visibility value from UML # (implemented for 1.2 only!) TGV overrides UML-mode! permissionMode = m.getVisibility() or 'public' # A public method means it's part of the class' public interface, # not to be confused with the fact that Zope has a method called # declareProtected() to protect a method which is *part of the # class' public interface* with a permission. If a method is public # and has no permission set, declarePublic(). If it has a permission # declareProtected() by that permission. if permissionMode == 'public': rawPerm = m.getTaggedValue('permission',None) permission = utils.getExpression(rawPerm) if rawPerm: return utils.indent("security.declareProtected" "(%s, '%s')" % (permission, m.getName()), 1) else: return utils.indent("security.declarePublic" "('%s')" % m.getName(), 1) # A private method is always declarePrivate()'d elif permissionMode == 'private': return utils.indent("security.declarePrivate('%s')" % m.getName(), 1) # A protected method is also declarePrivate()'d. The semantic # meaning of 'protected' is that is hidden from the outside world, # but accessible to subclasses. The model may wish to be explicit # about this intention (even though python has no concept of # such protection). In this case, it's still a privately declared # method as far as TTW code is concerned. elif permissionMode == 'protected': return utils.indent("security.declarePrivate('%s')" % m.getName(), 1) # A package-level method should be without security declarartion - # it is accessible to other methods in the same module, and will # use the class/module defaults as far as TTW code is concerned. elif permissionMode == 'package': # No declaration return utils.indent("# Use class/module security " "defaults", 1) else: log.warn("Method visibility should be 'public', 'private', " "'protected' or 'package', got '%s'.", permissionMode) return ''
def to_c(self): # var_from = 0 + self.attributes["from"] from_type = self.attributes.get("from", {}).get("type", "int") from_value = self.attributes.get("from", {}).get("val", 0) # start from 0 if noting is given in to_type = self.attributes.get("to", {}).get("type", "int") to_value = self.attributes.get("to", {}).get("val", -1) # infinite loop if no "to" given in step_type = self.attributes.get("step", {}).get("type", "int") step_value = self.attributes.get("step", {}).get("val", 1) # the default is i++ c = "\n\nfor({} i={}; i<{}; i+={})".format( from_type, from_value, to_value, step_value ) + " {\n" for el in self.children: if el.tagname == "param": continue el_c = el.to_c() if el_c: c += indent(el_c, 1) c += "}\n" return c
def _handle_failure(message, exception=None): """ Call `abort` or `warn` with the given message. The value of ``env.warn_only`` determines which method is called. If ``exception`` is given, it is inspected to get a string message, which is printed alongside the user-generated ``message``. """ func = env.warn_only and warn or abort if exception is not None: # Figure out how to get a string out of the exception; EnvironmentError # subclasses, for example, "are" integers and .strerror is the string. # Others "are" strings themselves. May have to expand this further for # other error types. if hasattr(exception, 'strerror') and exception.strerror is not None: underlying_msg = exception.strerror else: underlying_msg = exception func("%s\n\nUnderlying exception message:\n%s" % ( message, indent(underlying_msg) )) else: func(message)
def start(self): """Starts the process on the MaxiNet node and returns the remote PID. Returns: True if the process started successfully, False otherwise. """ self.start_time = time.time() # start command as daemonized process logger.debug("Daemonizing \"%s\" on MaxiNet node %s" % (self._command, self._node.nn)) result = self._node.cmd( "%s %s %s" % (transport_api.TransportAPI.get_binary_path("daemonize"), configuration.get_worker_working_directory(), self._command)) pid = result.splitlines()[0] # daemonize is supposed to print ONLY the PID of the started process if not pid.isdigit(): logger.error("Failed to start process:\n{}".format( utils.indent(result, 2))) return False self.pid = int(pid) return True
def start(self): """Starts the process on the MaxiNet node and returns the remote PID. Returns: True if the process started successfully, False otherwise. """ self.start_time = time.time() # start command as daemonized process logger.debug("Daemonizing \"%s\" on MaxiNet node %s" % (self._command, self._node.nn)) result = self._node.cmd("%s %s %s" % ( transport_api.TransportAPI.get_binary_path("daemonize"), configuration.get_worker_working_directory(), self._command)) pid = result.splitlines()[0] # daemonize is supposed to print ONLY the PID of the started process if not pid.isdigit(): logger.error("Failed to start process:\n{}".format( utils.indent(result, 2))) return False self.pid = int(pid) return True
def to_c(self): return_type = self.attributes.get("returns", {}).get("val", "void") func_name = None for key in self.attributes: if key != "returns": func_name = hyphenated_to_camel_case(key) params = [] for el in self.children: if el.tagname != "param": continue param_name = el.get_name() param_type = el.get_type() params.append(param_type + " " + param_name) c = "\n\n{} {}({})".format( return_type, func_name, ", ".join(param for param in params) ) + " {\n" for el in self.children: if el.tagname == "param": continue el_c = el.to_c() if el_c: c += indent(el_c, 1) c += "}\n" return c
def ends(self, text): if self.condition is not None and self.condition: self.write_c("%s\n" % utils.indent( self.out_c.indent, "} while (%s);" % self.condition)) return 0 else: return -1
def err(self, args): print('RUNTIME ERROR') print(indent('\n'.join(map(str, args)))) print('NEAR') print(indent(bc.text(self.code[self.pc:self.pc + 5]))) print('STACK') if self.stack: print(indent('\n'.join(map(str, reversed(self.stack))))) else: print(indent('* empty *')) print('ENVIRONMENT') env = self.env.copy() if PARENT in env: env.pop(PARENT, None) env['*parent*'] = '{...}' print(indent(pformat(env)))
def generateAdapts(self, element): outfile = StringIO() adaptedClasses = element.getAdaptationParents() for adaptedClass in adaptedClasses: adaptedClassName = adaptedClass.getCleanName() print >> outfile, utils.indent('adapts(%s)' % adaptedClassName, 1) return outfile.getvalue()
def parse(self, text): char = text[0] if self.rhs is not None and self.rhs: self.write_c("%s\n" % utils.indent(self.out_c.indent, "%s = %s;" % (self.lhs, self.rhs))) self.lhs = None self.rhs = None return 0 if self.rhs is None: result = re.match(r"^\s*(<-)", text.lower()) if result: self.rhs = "" return result.end(1) if char in utils.WORD_CHARACTERS or char == " ": self.lhs += char return len(char) if char == "\n" or char == " " or char == "\t": return len(char) raise Exception("Unexpected character \"%s\" (%d) in assignment." % (char, ord(char)))
def sync_S3(): '''Download any new or modified video files from S3 for studies we can access. This only gets the video files; details are not stored in the video database.''' # Get a list of studies we have access to via Lookit API.. # TODO: allow passing a study argument to fetch videos from just one study client = experimenter.ExperimenterClient() studies = client.fetch_collection_records('studies') studyIds = [s['id'] for s in studies] # Create a list of include options to add to the aws sync call to # get only video from these studies includeStudiesCommand = sum([['--include', '*_' + ID + '_*'] for ID in studyIds], []) origVideos = paths.get_videolist() awsCommand = [ 'aws', 's3', 'sync', 's3://mitLookit', paths.VIDEO_DIR, '--only-show-errors', '--metadata-directive', 'COPY', '--exclude', '*' ] + includeStudiesCommand sp.check_call(awsCommand) allVideos = paths.get_videolist() newVideos = list(set(allVideos) - set(origVideos)) print "Downloaded {} videos:".format(len(newVideos)) print(indent(printer.pformat(newVideos), 4)) return newVideos
def generate_code_for_Bezier(degree, printer): t = symbols('t') lines = [] n_coeffs = degree + 1 syms = utils.create_coeff_symbols(n_coeffs) func = utils.bezier(degree, t, False, syms) poly, coeffs = extract_coefficients(func, t) solver_lines = utils.generate_solver_code(coeffs, poly, printer) control_variables = ", ".join( ["Scalar cx{i}, Scalar cy{i}".format(i=i) for i in range(n_coeffs)]) control_variable_arguments = ", ".join([ "ctrl_pts({i},0), ctrl_pts({i},1)".format(i=i) for i in range(n_coeffs) ]) template_function = specialization_template.format( type="Bezier", control_variables=control_variables, body="\n".join(utils.indent(solver_lines)), degree=degree) invocation = "return match_tangent_{}_degree_{}({}, tangent, t0, t1);".format( "Bezier", degree, control_variable_arguments) extern_declaration = specialization_extern_declaration_template.format( type="Bezier", degree=degree, control_variables=control_variables) extern_definition = specialization_extern_definition_template.format( type="Bezier", degree=degree, control_variables=control_variables) return template_function, invocation, extern_declaration, extern_definition
def body(self): self.add(TSimple("#deserialization")) self.add(TSimple("import json")) # message deserializers for msg in self._protocol.get_messages().as_list(): self.add(JsonMessageDeserializer(msg)) # main deserializer self.add(TSimple(StringTemplate(""" class JsonDeserializer: def __init__(self): self._deserializers = {} $deserializersInit def deserialize(self, buffer): decoded = json.loads(buffer) return self._deserialize_json(decoded) def _deserialize_json(self, decoded): MessageName = decoded.keys()[0] return self._deserializers[MessageName].deserialize(decoded[MessageName]) """).substitute({'deserializersInit' : # deserializers init "\n".join([StringTemplate( indent(2, 'self._deserializers["$messageName"] = _${messageName}Deserializer()') ).substitute({'messageName' : msg.get_name()}) for msg in self._protocol.get_messages().as_list()])}))) self.add(TSimple("jsonDeserializer = JsonDeserializer()"))
def standard_email_due_to_error(err_msg): """Return an EmailCustomContents with the given err_msg. This function allows us to perform consistent error handling when trying to call the hooks.commit-email-formatter script. It returns an EmailCustomContents where nothing is changed (and therefore the standard email gets sent) except for the addition of a warning section at the end of the email's body (just before the "Diff:" section). This warning section indicates that an error was detected, and provides information about it. PARAMETERS err_msg: A description of the error that occurred (a string). """ appendix = "WARNING:\n" \ "{err_msg}\n" \ "Falling back to default email format.\n" \ "\n" \ "$ {hook_exe} {update.ref_name}" \ " {commit.rev}\n" \ "{out}\n".format( err_msg=err_msg, hook_exe=hook_exe, update=self, commit=commit, out=out) return EmailCustomContents( appendix=indent(appendix, "| "), diff=default_diff)
def render(self): """ Produces LaTeX code for this image. @rtype: string @return: LaTeX code for this plot """ tex = '\\addplot[point meta min={0:5f}, point meta max={1:5f}] graphics\n'.format( self.vmin, self.vmax) tex += indent( '[xmin={0},xmax={1},ymin={2},ymax={3}]\n'.format(*self.limits())) tex += indent('{' + path.join(Settings.image_folder, self.filename()) + '};\n') return tex
def text(code, colored=True): nls = 1 out = '' for cmd in code: if isinstance(cmd, IN_NEWLINE) and not nls: out += '\n' nls += 1 if nls and not isinstance(cmd, NO_INDENT): out += indent('') color = COLORS[type(cmd)] if isinstance(cmd, tuple( COLORS.keys())) else None if colored and color: out += color out += str(cmd) + ' ' if colored and color: out += Style.RESET_ALL nls = 0 if isinstance(cmd, ADD_NEWLINE): out += '\n' nls += 1 return out.rstrip()
def config_attribute_filters(idp_base_dir, idphost): filter_file = idp_base_dir + '/conf/attribute-filter.xml' utils.backup_original_file(filter_file) try: # namespace for attribute filter policy. # See https://wiki.shibboleth.net/confluence/display/IDP30/AttributeFilterPolicyConfiguration ns = dict([ node for _, node in ET.iterparse(filter_file, events=['start-ns']) ]) for prefix, uri in ns.items(): ET.register_namespace(prefix, uri) parser = ET.XMLParser(target=CommentedTreeBuilder()) tree = ET.parse(filter_file, parser) root = tree.getroot() for child in root.findall( '{urn:mace:shibboleth:2.0:afp}AttributeFilterPolicy'): if child.attrib['id'] == 'config_metadata_provider': # caso já exista um AttributeFilterPolicy para o MfaProvider # (este script já foi executado, por exemplo), remove. root.remove(child) filter_policy = ET.SubElement(root, 'AttributeFilterPolicy', {'id': 'releaseToMfaProvider'}) filter_policy_sub = ET.SubElement(filter_policy, 'PolicyRequirementRule', { 'xsi:type': "Requester", "value": idphost }) # cria uma regra de liberação de atributo para cada atributo definido em # attribute_rules.txt. Cada atributo deve estar em uma linha, na forma atributo,regra: # eduPersonPrincipalName,ANY with open('attribute_rules.txt', 'r') as fa: for line in fa: attribute = line.split(',') create_elem_rule(attribute, filter_policy) utils.indent(root) tree.write(filter_file) except IOError as e: #TODO: Reverter para arquivo original print("Houve um erro ao escrever o arquivo conf/attribute-filter.xml") print("Erro: ", e) return False return True
def email_commit(self, commit): """See AbstractUpdate.email_commit.""" notes = GitNotes(commit.rev) # Get commit info for the annotated commit annotated_commit = commit_info_list("-1", notes.annotated_rev)[0] # Get a description of the annotated commit (a la "git show"), # except that we do not want the diff. # # Also, we have to handle the notes manually, as the commands # get the notes from the HEAD of the notes/commits branch, # whereas what we needs is the contents at the commit.rev. # This makes a difference when a single push updates the notes # of the same commit multiple times. annotated_rev_log = git.log(annotated_commit.rev, no_notes=True, max_count="1") notes_contents = (None if notes.contents is None else indent( notes.contents, ' ' * 4)) # Determine subject tag based on ref name: # * remove "refs/notes" prefix # * remove entire tag if remaining component is "commits" # (case of the default refs/notes/commits ref) notes_ref = self.ref_name.split('/', 2)[2] if notes_ref == "commits": subject_tag = "" else: subject_tag = "(%s)" % notes_ref subject = '[notes%s][%s] %s' % (subject_tag, self.email_info.project_name, annotated_commit.subject) body_template = (DELETED_NOTES_COMMIT_EMAIL_BODY_TEMPLATE if notes_contents is None else UPDATED_NOTES_COMMIT_EMAIL_BODY_TEMPLATE) body = body_template % { 'annotated_rev_log': annotated_rev_log, 'notes_contents': notes_contents, } # Git commands calls strip on the output, which is usually # a good thing, but not in the case of the diff output. # Prevent this from happening by putting an artificial # character at the start of the format string, and then # by stripping it from the output. diff = git.show(commit.rev, pretty="format:|", p=True)[1:] email_bcc = git_config('hooks.filer-email') email = Email(self.email_info, annotated_commit.email_to(self.ref_name), email_bcc, subject, body, commit.author, self.ref_name, commit.base_rev_for_display(), commit.rev, diff) email.enqueue()
def starts(text, parent): if re.match(r"^do\b", text.lower()): out_c = outputs.PipeOutput(parent.out_c, indent=parent.out_c.indent + 1) child = DoWhileLoopParser(out_c=out_c, out_h=parent.out_h) child.write_c("%s\n" % utils.indent(child.out_c.indent, "do {")) return 2, child else: return -1, None
async def on_guild_role_update(self, before: discord.Role, after: discord.Role): self.logger.info( color(f"role `{after.name}` edited:\n", "blue") + "Before: {}\nAfter: {}".format( indent( self.role_desc.format( **self.to_dict(before), perms=self.perms_to_str(before.permissions), ).lower(), 49, ), indent( self.role_desc.format( **self.to_dict(after), perms=self.perms_to_str(after.permissions), ).lower(), 49, ), )) log_embed = self.log_embed( "edit", description=f"**Role edited: {after.name} ({after.mention})**", footer=f"ID: {before.id}", guild=before.guild, ) log_embed.add_field( name="Before", value=self.role_desc.format( **self.to_dict(before), perms=self.perms_to_str(before.permissions), ), ) log_embed.add_field( name="After", value=self.role_desc.format( **self.to_dict(after), perms=self.perms_to_str(after.permissions), ), ) await self.log_channel.send(embed=log_embed)
def write(self, filename, encoding='UTF-8'): """ Write a XRA file. """ try: root = ET.Element('Document') root.set('Author', 'SPPAS') root.set('Date', datetime.now().strftime("%Y-%m-%d")) root.set('Format', XRA.__format) self.__tier_id_map = {} self.__tier_counter = 0 metadataRoot = ET.SubElement(root, 'Metadata') XRA.__format_metadata(metadataRoot, self) if len(metadataRoot.findall('Entry')) == 0: root.remove(metadataRoot) for tier in self: tierRoot = ET.SubElement(root, 'Tier') self.__format_tier(tierRoot, tier) for media in self.GetMedia(): if media: mediaRoot = ET.SubElement(root, 'Media') self.__format_media(mediaRoot, media) hierarchyRoot = ET.SubElement(root, 'Hierarchy') self.__format_hierarchy(hierarchyRoot, self._hierarchy) for vocabulary in self.GetCtrlVocab(): if vocabulary: vocabularyRoot = ET.SubElement(root, 'Vocabulary') self.__format_vocabulary(vocabularyRoot, vocabulary) indent(root) tree = ET.ElementTree(root) tree.write(filename, encoding=encoding, method="xml") except Exception: #import traceback #print(traceback.format_exc()) raise
def __init__(self, xml_path, input_stl_path, infos_path): self.solid = solid.Solid(input_stl_path) self.solid.display(infos_path) self.xml_root = ET.Element("model") project_name = op.splitext(op.basename(input_stl_path))[0] self.xml_root.set("id", project_name) self.xml_root.set("unit", "mm") self.xml_root.set("img", "yes") self.xml_root.set("desc", "Build a construction with rods and 3d printed corners.") self._build_corners_tree() self._build_edges_tree() tree = ET.ElementTree(self.xml_root) utils.indent(self.xml_root) tree.write(xml_path, encoding="UTF-8", xml_declaration=True)
def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', action='store', help="input HOCR html file", required=True) parser.add_argument('-o', action='store', help="output text XML file", required=True) args = parser.parse_args() hocr_file = args.i out_xml_file = args.o nlp = spacy.load("en_core_web_sm") print("loaded spacy.") tree = ET.parse(hocr_file) top = Element('pdf') for node in tree.findall('.//body/div'): handle_page(node, top_el=top, nlp=nlp) utils.indent(top) out_tree = ET.ElementTree(top) out_tree.write(out_xml_file, encoding="UTF-8") print("wrote file:", out_xml_file)
def ends(self, text): if self.condition is None: result = re.match(r"^(end\s+while)\b", text.lower()) if result: self.write_c("%s\n" % utils.indent(self.out_c.indent, "}")) return result.end(1) else: return -1 else: return -1
def to_rst(self, results): output = """**Benchmark setup** .. code-block:: python %s **Benchmark statement** .. code-block:: python %s %s """ % (indent(self.setup), indent(self.code), getTable(results['runtime'], self.name, ['name', 'repeat', 'timing', 'loops', 'units'])) return output
def make_html(file_path, content, css_path): 'Create an html file and write on it the specified content.' html = ET.Element('html') head = ET.SubElement(html, 'head') link = ET.SubElement(head, 'link') link.set('rel', 'stylesheet') link.set('href', css_path) body = ET.SubElement(html, 'body') body.set('id', os.path.splitext(os.path.basename(file_path))[0]) #body.set('onload', 'menu.getElementsById(' + element.get('id') + ') = "focus";') body.append(content) utils.indent(html) with open(file_path, 'w') as html_file: html_file.write('<!DOCTYPE html>\n') ET.ElementTree(html).write(html_file, 'utf-8')
def generateImplements(self, element, parentnames): outfile = StringIO() # Zope 2 Interfaces # "__implements__" line -> handle realization parents reparents = element.getRealizationParents() z2reparentnames = [ p.getName() for p in reparents if not p.hasStereoType('z3') ] if z2reparentnames: z2iface_implements = \ ' + '.join(["(%s,)" % i for i in z2reparentnames]) else: z2iface_implements = None if parentnames: z2parentclasses_implements = \ ' + '.join(["(getattr(%s,'__implements__',()),)" % i for i in parentnames]) else: z2parentclasses_implements = None z2implements_line = None if z2iface_implements is not None or z2parentclasses_implements is not None: z2implements_line = '__implements__ = ' if z2parentclasses_implements is not None: z2implements_line += z2parentclasses_implements if z2iface_implements and z2parentclasses_implements: z2implements_line += ' + ' if z2iface_implements is not None: z2implements_line += z2iface_implements if z2implements_line is not None: print >> outfile, utils.indent(z2implements_line, 1) # Zope 3 interfaces z3reparentnames = [ p.getName() for p in reparents if p.hasStereoType('z3') ] if z3reparentnames: print >> outfile, utils.indent('# zope3 interfaces', 1) concatstring = ', '.join(z3reparentnames) print >> outfile, utils.indent( "zope.interface.implements(%s)" % concatstring, 1) return outfile.getvalue()
def display_command(command): # Sanity check if command not in commands: abort("Command '%s' not found, exiting." % command) # Print out nicely presented docstring print("Displaying detailed information for command '%s':" % command) print('') print(indent(commands[command].__doc__, strip=True)) print('') sys.exit(0)
def classpxd(desc): """Generates a ``*pxd`` Cython header snippet for exposing a C/C++ class to other Cython wrappers based off of a dictionary description. Parameters ---------- cimport_tups : set of tuples Set of Cython cimport tuples for .pxd header file. desc : dict Class description dictonary. Returns ------- pxd : str Cython ``*.pxd`` header snippet for class. """ if 'pxd_filename' not in desc: desc['pxd_filename'] = '{0}.pxd'.format(desc['name'].lower()) pars = ', '.join([cython_cytype(p) for p in desc['parents'] or ()]) d = {'parents': pars if 0 == len(pars) else '('+pars+')'} copy_from_desc = ['name',] for key in copy_from_desc: d[key] = desc[key] cimport_tups = set() for parent in desc['parents'] or (): cython_cimport_tuples(parent, cimport_tups, set(['cy'])) from_cpppxd = desc['cpppxd_filename'].rsplit('.', 1)[0] # This is taken care of in main! #register_class(desc['name'], cython_cimport=from_cpppxd, # cython_c_type="{0}.{1}".format(from_cpppxd, desc['name']),) d['name_type'] = cython_ctype(desc['name']) cython_cimport_tuples(desc['name'], cimport_tups, set(['c'])) parentless_body = ['cdef void * _inst', 'cdef public bint _free_inst'] body = parentless_body if desc['parents'] is None else [] attritems = sorted(desc['attrs'].items()) for aname, atype in attritems: if aname.startswith('_'): continue # skip private _, _, cachename, iscached = cython_c2py(aname, atype, cache_prefix=None) if iscached: cython_cimport_tuples(atype, cimport_tups) cyt = cython_cytype(atype) decl = "cdef public {0} {1}".format(cyt, cachename) body.append(decl) d['body'] = indent(body or ['pass']) d['extra'] = desc.get('extra', {}).get('pxd', '') pxd = _pxd_class_template.format(**d) return cimport_tups, pxd
def insertTree(tree, i=0): if tree == []: return else: for node in tree: Ui.IndexMap.append(node.address) if i == 0: Ui.HierList.insert(tk.END, node.data) else: Ui.HierList.insert(tk.END, (utils.indent(i)+node.data)) if node.state == tree_node.TreeState.EXPANDED: insertTree(node.children, i+1)
def test_fn( model: torch.nn, data_loader: DataLoader, class_nums: Dict, device: torch.device): image_ids = [image_id.split('.')[1][-17:] for image_id in data_loader.dataset.image_ids] xml_root = ET.Element('predictions') model.eval() batch_size = data_loader.batch_size with torch.no_grad(): for i, (images, _) in tqdm(enumerate(data_loader)): images = list(image.to(device) for image in images) outputs = model(images) for j, output in enumerate(outputs): image_name = image_ids[i*batch_size+j] xml_image = ET.SubElement(xml_root, 'image', {'name': image_name}) masks = output['masks'].detach().cpu().numpy() labels = output['labels'].detach().cpu().numpy() scores = output['scores'].detach().cpu().numpy() for mask, label, score in zip(masks, labels, scores): mask_bin = np.where(mask[0] > 0.1, True, False) polygons = Mask(mask_bin).polygons() points = polygons.points point = ''.join([str(p[0]) + ',' + str(p[1]) +';' for p in points[0]]) attribs = { 'class_name': class_nums[label], 'score': str(float(score)), 'polygon': point, } ET.SubElement(xml_image, 'predict', attribs) indent(xml_root) tree = ET.ElementTree(xml_root) if not os.path.exists('./output/'): print('Not exists ./output/ making an weight folder...') os.mkdir('./output/') tree.write('./output/prediction.xml') print('Save predicted labels.xml...\n')
def config_tomcat(): ''' O caminho docBase está definido também no script de deploy da aplicação. ''' filename = config.get('tomcat', 'dir_tomcat_app_config') + config.get( 'mfap', 'mfapbasepath') + '.xml' try: with open(filename, 'w+') as fh: fh.write('<Context docBase="%s"\n' % config.get('tomcat', 'docBase')) fh.write('unpackWAR="true"\n') fh.write('swallowOutput="true">\n') fh.write('<Manager pathname="" />\n') fh.write('</Context>') except OSError as err: print("Erro ao escrever arquivo " + config.get('tomcat', 'docBase')) print( "verifique se a propriedade dir_tomcat_app_config no config.ini esta com o caminho correto do tomcat " ) print("IOError: ", err) return False utils.backup_original_file(config.get('tomcat', 'tomcat_server_config')) parser = ET.XMLParser(target=CommentedTreeBuilder()) tree = ET.parse(config.get('tomcat', 'tomcat_server_config'), parser) root = tree.getroot() service_catalina = root.find('Service/[@name="Catalina"]') for child in service_catalina: if child.tag == 'Connector' and 'port' in child.attrib: if child.attrib['port'] == '9443': service_catalina.remove(child) ET.SubElement(service_catalina, 'Connector', { 'port': '9443', 'address': '127.0.0.1', 'protocol': 'AJP/1.3' }) utils.indent(root) tree.write(config.get('tomcat', 'tomcat_server_config')) return True
def close(self): self.conn.close() # Write out the poicategories # WARNING: This does NOT add standalone="yes" to the xml declaration... utils.indent(self.poicategories) cElementTree.ElementTree(self.poicategories).write( os.path.join(self.dest, 'PersonalPOI', 'Package', '0', 'default', 'categories.pc'), encoding='utf-8', xml_declaration=True) # Write out the poistrings # WARNING: This does NOT add standalone="yes" to the xml declaration... utils.indent(self.poistrings) cElementTree.ElementTree(self.poistrings).write(os.path.join( self.dest, 'PersonalPOI', 'Package', '0', 'default', 'strings_de-DE.xml'), encoding='utf-8', xml_declaration=True) # Write out the poibitmaps # WARNING: This does NOT add standalone="yes" to the xml declaration... utils.indent(self.poibitmaps) self.poibitmaps.attrib['count'] = str(self.next_category) cElementTree.ElementTree(self.poibitmaps).write(os.path.join( self.dest, 'PersonalPOI', 'Package', '0', 'default', 'bitmaps.xml'), encoding='utf-8', xml_declaration=True)
def handle_read(self): read = self.recv(4096) debug_str = "" if(debug == 1 or debug == 3 or debug == 5): debug_str += term.render(' ${CYAN}Listener: %i bytes read:${NORMAL}\n') % len(read) if(debug == 3 or debug >= 5): debug_str += hexdump(read, indent=True) if debug_str: if debug >= 5: debug_str = indent(debug_str, dump_width) print(debug_str) self.from_remote_buffer += read
def build_tree(self): """build the tree.""" # we open the settings section geometry = ET.Element("geometry") # set the dimension of the problem geometry.set('dim', str(self.dim)) # dimension # Let write a description at the beginning xmldescription = self.description.replace("\n", "\n ") geometry.append(ET.Comment(text=xmldescription)) # Now we fill the information about the core core = ET.SubElement(geometry, "core") self.set_core(core) # Now we fill the information about the lattices lattices = ET.SubElement(geometry, "lattices") self.set_lattices(lattices) # Now we fill the information about the pins pins = ET.SubElement(geometry, "pins") self.set_pins(pins) # indenting the file for the pretty printing utils.indent(geometry) # we put this into the tree self.geom_xml = ET.ElementTree(geometry)
def handle_read(self): read = self.recv(4096) debug_str = "" if debug == 1 or debug == 3 or debug == 5: debug_str += term.render(" ${CYAN}Listener: %i bytes read:${NORMAL}\n") % len(read) if debug == 3 or debug >= 5: debug_str += hexdump(read, indent=True) if debug_str: if debug >= 5: debug_str = indent(debug_str, dump_width) print (debug_str) self.from_remote_buffer += read
def funccpppxd(desc, exception_type='+'): """Generates a cpp_*.pxd Cython header snippet for exposing a C/C++ function to other Cython wrappers based off of a dictionary description. Parameters ---------- desc : dict Function description dictonary. exception_type : str, optional Cython exception annotation. Set to None when exceptions should not be included. Returns ------- cimport_tups : set of tuples Set of Cython cimport tuples for cpp_*.pxd header file. cpppxd : str Cython cpp_*.pxd header file as in-memory string. """ d = {} copy_from_desc = ['name', 'namespace', 'header_filename'] for key in copy_from_desc: d[key] = desc[key] inc = set(['c']) cimport_tups = set() flines = [] estr = str() if exception_type is None else ' except {0}'.format(exception_type) funcitems = sorted(expand_default_args(desc['signatures'].items())) for fkey, frtn in funcitems: fname, fargs = fkey[0], fkey[1:] if fname.startswith('_'): continue # private argfill = ", ".join([cython_ctype(a[1]) for a in fargs]) for a in fargs: cython_cimport_tuples(a[1], cimport_tups, inc) line = "{0}({1}){2}".format(fname, argfill, estr) rtype = cython_ctype(frtn) cython_cimport_tuples(frtn, cimport_tups, inc) line = rtype + " " + line if line not in flines: flines.append(line) d['functions_block'] = indent(flines, 4) d['extra'] = desc.get('extra', {}).get('cpppxd', '') cpppxd = _cpppxd_func_template.format(**d) if 'cpppxd_filename' not in desc: desc['cpppxd_filename'] = 'cpp_{0}.pxd'.format(d['name'].lower()) return cimport_tups, cpppxd
def config_metadata_provider(idp_base_dir): metadata_file = idp_base_dir + '/conf/metadata-providers.xml' sp_file = idp_base_dir + '/metadata/mfaprovider-metadata.xml' utils.backup_original_file(metadata_file) try: # namespace for Metadata Provider. # https://wiki.shibboleth.net/confluence/display/IDP30/MetadataConfiguration ns = dict([ node for _, node in ET.iterparse(metadata_file, events=['start-ns']) ]) for prefix, uri in ns.items(): ET.register_namespace(prefix, uri) parser = ET.XMLParser(target=CommentedTreeBuilder()) tree = ET.parse(metadata_file, parser) root = tree.getroot() for child in root.findall( '{urn:mace:shibboleth:2.0:metadata}MetadataProvider'): if child.attrib['id'] == 'MfaProviderMetadata': # caso já exista um AttributeFilterPolicy para o MfaProvider # (este script já foi executado, por exemplo), remove. root.remove(child) metadata_details = { 'id': 'MfaProviderMetadata', 'xsi:type': 'FilesystemMetadataProvider', 'metadataFile': sp_file } ET.SubElement(root, 'MetadataProvider', metadata_details) utils.indent(root) tree.write(metadata_file) except IOError as e: #TODO: Reverter para arquivo original print( "Houve um erro ao escrever o arquivo conf/metadata-providers.xml") print("Erro: ", e) return False return True
def printTree(self, level): indent(level, "FUNDEF") indent(level + 1, self.id.value) indent(level + 1, "RET " + self.type.value) for arg in self.args: arg.printTree(level + 1) self.compoundInstructions.printTree(level + 1)
def display_command(command): # Sanity check if command not in commands: abort("Command '%s' not found, exiting." % command) cmd = commands[command] # Print out nicely presented docstring if found if cmd.__doc__: print("Displaying detailed information for command '%s':" % command) print('') print(indent(cmd.__doc__, strip=True)) print('') # Or print notice if not else: print("No detailed information available for command '%s':" % command) sys.exit(0)
def _dispatch(self, request): try: try: method = self.get_method(request.method) except KeyError as e: logger.error("RPC method not found: {}".format(request.method)) return request.error_respond(MethodNotFoundError(e)) # we found the method try: result = method(*request.args, **request.kwargs) except Exception as e: # an error occured within the method, return it logger.error("RPC method {} failed:\n{}".format( request.method, utils.indent(traceback.format_exc(), 2))) return request.error_respond(e) # respond with result return request.respond(result) except Exception as e: logger.error("RPC method {} failed unexpectedly:\n{}".format( request.method, utils.indent(traceback.format_exc(), 2))) # unexpected error, do not let client know what happened return request.error_respond(ServerError())
def write_page_range(out_file, pg_list, start, end): top = Element('pdf') for i in range(start, end): pg = pg_list[i] content = "" for section in pg.sections: if section.sec_type == 'bad': nl = len(section.lines) for j, line in enumerate(section.lines): if j == 0: content += '{junk}' + line + "\n" elif j == nl - 1: content += line + "{junk}\n" else: content += line + "\n" else: for line in section.lines: content += line + "\n" page_el = SubElement(top, 'page') page_el.text = content utils.indent(top) out_tree = ET.ElementTree(top) out_tree.write(out_file, encoding="UTF-8") print("wrote file:", out_file)
def test(config): result = consts.TEST_PASSED cause = None out = Cgroup.lscgroup(config, controller=[CONTROLLER, CONTROLLER], path=[PARENT_CGNAME, SIBLING_CGNAME]) if out != EXPECTED_OUT1: result = consts.TEST_FAILED cause = ( "Expected lscgroup output doesn't match received output\n" "Expected:\n{}\n" "Received:\n{}\n" "".format(utils.indent(EXPECTED_OUT1, 4), utils.indent(out, 4)) ) return result, cause ret = Cgroup.lscgroup(config, cghelp=True) if 'Usage:' not in ret: result = consts.TEST_FAILED cause = 'Failed to print help text' return result, cause return result, cause
def generateImplements(self, element, parentnames): outfile = StringIO() if element.hasStereoType('extender'): z3reparentnames = ['ISchemaExtender'] else: reparents = element.getRealizationParents() # Zope 3 interfaces z3reparentnames = [p.getName() for p in reparents if (self.getInterfaceType(p) == 'z3' or p.hasStereoType('view_class'))] if not element.isInterface() and self._isContentClass(element) and not element.hasStereoType('adapter'): z3reparentnames = ['interfaces.I'+element.getCleanName()]+z3reparentnames if z3reparentnames: concatstring = ', '.join(z3reparentnames) print >> outfile, utils.indent("implements(%s)" % concatstring, 1) return outfile.getvalue()
def parse(self, text): char = text[0] if char == "\n" or char == " " or char == "\t": return len(char) if self.condition is not None: self.write_c("%s\n" % utils.indent( self.out_c.indent, "while (%s) {" % self.condition)) self.condition = None return 0 raise Exception( "Unexpected character \"%s\" (%d) in while loop body." % (char, ord(char)))
def _gen_method(name, name_mangled, args, rtn, doc=None, inst_name="self._inst"): argfill = ", ".join(['self'] + [a[0] for a in args if 2 == len(a)] + \ ["{0}={1}".format(a[0], a[2]) for a in args if 3 == len(a)]) lines = ['def {0}({1}):'.format(name_mangled, argfill)] lines += [] if doc is None else indent('\"\"\"{0}\"\"\"'.format(doc), join=False) decls = [] argbodies = [] argrtns = {} for a in args: adecl, abody, artn = cython_py2c(a[0], a[1]) if adecl is not None: decls += indent(adecl, join=False) if abody is not None: argbodies += indent(abody, join=False) argrtns[a[0]] = artn rtype = cython_ctype(rtn) hasrtn = rtype not in set(['None', None, 'NULL', 'void']) argvals = ', '.join([argrtns[a[0]] for a in args]) fcall = '{0}.{1}({2})'.format(inst_name, name, argvals) if hasrtn: fcdecl, fcbody, fcrtn, fccached = cython_c2py('rtnval', rtn, cached=False) decls += indent("cdef {0} {1}".format(rtype, 'rtnval'), join=False) func_call = indent('rtnval = {0}'.format(fcall), join=False) if fcdecl is not None: decls += indent(fcdecl, join=False) if fcbody is not None: func_call += indent(fcbody, join=False) func_rtn = indent("return {0}".format(fcrtn), join=False) else: func_call = indent(fcall, join=False) func_rtn = [] lines += decls lines += argbodies lines += func_call lines += func_rtn lines += ['', ""] return lines