convert the Schema to XHTML with the given output filename or with the given extension.
190850
def xhtml(self, outfn=None, ext='.xhtml', css=None, **params):
        """"""
        from markdown import markdown
        from copy import deepcopy
        from bl.file import File
        from .xslt import XSLT
        from .rng import RNG
        from . import XML, PATH, etree
        rncfn = os.path.splitext(self.fn)[0] + '.rnc'
        rngfn = os.path.splitext(self.fn)[0] + '.rng'
        htmlfn = os.path.splitext(self.fn)[0] + '.html'
        if self.fn==rncfn or os.path.exists(rncfn):
            rngfn = Schema(rncfn).trang(ext='.rng')
        assert os.path.exists(rngfn)

        # convert all <r:define> elements into a <a:definition> blocks containing a compact syntax alternative
        rng = RNG(fn=rngfn)
        for define in rng.xpath(rng.root, "//r:define"):
            log.debug("%s %r" % (rng.tag_name(define), define.attrib))
            tempdefine = deepcopy(define)
            tempgrammar = deepcopy(rng.root); tempgrammar.text = '\n'
            for ch in tempgrammar.getchildren(): rng.remove(ch)
            tempgrammar.insert(0, tempdefine)
            for adoc in rng.xpath(tempdefine, ".//a:documentation | .//a:definition"):
                rng.remove(adoc)
            with tempfile.TemporaryDirectory() as tempdir:
                x = XML(fn=os.path.join(tempdir, 'define.rng'), root=tempgrammar)
                x.write()
                newfn = Schema(x.fn).trang(ext='.rnc')
                txt = open(newfn, 'rb').read().decode('utf-8')
                if '\n\n' in txt:
                    txt = txt[txt.index('\n\n')+1:].strip()
            adef = etree.Element("{%(a)s}definition" % RNG.NS)
            adef.text = txt
            adef.tail = '\n\t\t'
            log.debug(adef.text)
            annotations = rng.xpath(define, "a:*")
            if len(annotations) > 0:
                index = define.index(annotations[-1])+1
            else:
                index = 0
            define.insert(index, adef)
        rng.write()

        xslt = XSLT(fn=os.path.join(PATH, 'xslts', 'rng2md.xslt'))
        md = xslt.saxon9(rng.root, **params).strip()
        html_body = markdown(md, 
            output_format="xhtml5", 
            extensions=[                            # see https://python-markdown.github.io/extensions/
                'markdown.extensions.extra',    
                'markdown.extensions.admonition', 
                'markdown.extensions.headerid', 
                'markdown.extensions.sane_lists', 
                'markdown.extensions.toc']).strip()
        html_text = """<html><head><meta charset="UTF-8"/><style type="text/css">
            body {font-family:sans-serif;line-height:1.3}
            h1,h2,h3 {margin:1em 0 .25em 0}
            h1 {font-size:2rem;font-weight:normal;}
            h2 {font-size:1.2rem;font-weight:bold;}
            h3 {font-size:1.15rem;font-weight:normal;font-style:italic;}
            p {margin:0 0 .5rem 0;}
            p.subtitle {font-size:1.2rem;font-family:sans-serif;margin-bottom:1em}
            p.code {font-family:monospace;font-size:.6rem;color:#666;line-height:1.1}
            pre {font-family:monospace;font-size:.6rem;color:#666;line-height:1.1;margin-left:1.5rem;}
            hr {border:0;border-top:1px solid #999;margin:1rem 0;}
            </style></head><body>\n""" + html_body + """\n</body></html>"""
        html = XML(fn=htmlfn, root=html_text)
        return html
158396
private Document toXML(Collection<ArchiveEntry> files) throws Exception
    {
        Document doc = new DOMDocument();

        Element packageElement = new DOMElement("package");
        doc.setRootElement(packageElement);

        Element infoElement = new DOMElement("infos");
        packageElement.add(infoElement);
        addInfoElements(infoElement);

        Element filesElement = new DOMElement(FILES_TAG);
        packageElement.add(filesElement);
        addFileElements(files, filesElement);

        return doc;
    }
283074
def _get_schema_file(extension, path):
        
        for file in os.listdir(path):
            if file.endswith(extension):
                return os.path.join(path, file)
954917
public void doSchema(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        setHeaders(rsp);
        rsp.setContentType("application/xml");
        StreamResult r = new StreamResult(rsp.getOutputStream());
        new SchemaGenerator(new ModelBuilder().get(bean.getClass())).generateSchema(r);
        r.getOutputStream().close();
    }
1127692
private static void alterHtmlDocs(Options opt, String outputFolder, String packageName, String className,
	    String htmlFileName, Pattern insertPointPattern, RootDoc root) throws IOException {
	// setup files
	File output = new File(outputFolder, packageName.replace(".", "/"));
	File htmlFile = new File(output, htmlFileName);
	File alteredFile = new File(htmlFile.getAbsolutePath() + ".uml");
	if (!htmlFile.exists()) {
	    System.err.println("Expected file not found: " + htmlFile.getAbsolutePath());
	    return;
	}

	// parse & rewrite
	BufferedWriter writer = null;
	BufferedReader reader = null;
	boolean matched = false;
	try {
	    writer = new BufferedWriter(new OutputStreamWriter(new
		    FileOutputStream(alteredFile), opt.outputEncoding));
	    reader = new BufferedReader(new InputStreamReader(new
		    FileInputStream(htmlFile), opt.outputEncoding));

	    String line;
	    while ((line = reader.readLine()) != null) {
		writer.write(line);
		writer.newLine();
		if (!matched && insertPointPattern.matcher(line).matches()) {
		    matched = true;
			
		    String tag;
		    if (opt.autoSize)
		        tag = String.format(UML_AUTO_SIZED_DIV_TAG, className);
		    else
                tag = String.format(UML_DIV_TAG, className);
		    if (opt.collapsibleDiagrams)
		    	tag = String.format(EXPANDABLE_UML, tag, "Show UML class diagram", "Hide UML class diagram");
		    writer.write("<!-- UML diagram added by UMLGraph version " +
		    		Version.VERSION + 
				" (http://www.spinellis.gr/umlgraph/) -->");
		    writer.newLine();
		    writer.write(tag);
		    writer.newLine();
		}
	    }
	} finally {
	    if (writer != null)
		writer.close();
	    if (reader != null)
		reader.close();
	}

	// if altered, delete old file and rename new one to the old file name
	if (matched) {
	    htmlFile.delete();
	    alteredFile.renameTo(htmlFile);
	} else {
	    root.printNotice("Warning, could not find a line that matches the pattern '" + insertPointPattern.pattern() 
		    + "'.\n Class diagram reference not inserted");
	    alteredFile.delete();
	}
    }
1181727
function generateModel(path, modelName, modelFields, generateMethod, ts, cb) {
    var fields = formatTools.getFieldsForModelTemplate(modelFields);
    var schemaName = modelName + 'Schema';

    var extension = (ts) ? 'ts' : 'js';
    var model = ft.loadTemplateSync('model.' + extension);
    model = model.replace(/{modelName}/, modelName);
    model = model.replace(/{schemaName}/g, schemaName);
    model = model.replace(/{fields}/, fields);

    if (generateMethod === 't') {
        ft.createDirIfIsNotDefined(path, 'models', function () {
            ft.writeFile(path + '/models/' + modelName + 'Model.' + extension, model, null, cb);
        });
    } else {
        ft.createDirIfIsNotDefined(path, modelName, function () {
            ft.writeFile(path + '/' + modelName + '/' + modelName + 'Model.' + extension, model, null, cb);
        });
    }
}
795913
public void toFileWithoutExtension(Path outputFile) {
        Validate.notNull(outputFile, "outputFile must not be null");

        applyOverviewDocument().writeToFileWithoutExtension(outputFile, StandardCharsets.UTF_8);
        applyPathsDocument().writeToFileWithoutExtension(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
        applyDefinitionsDocument().writeToFileWithoutExtension(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
        applySecurityDocument().writeToFileWithoutExtension(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
    }
1319682
def to_html
      output_options = Nokogiri::XML::Node::SaveOptions::DEFAULT_XHTML ^
        Nokogiri::XML::Node::SaveOptions::FORMAT
      @fragment.children.inject("") do |out, child|
        out << child.serialize(:save_with => output_options, :encoding => 'UTF-8')
      end
    end
1072227
void generateAntIvyXml(Definition def, String outputDir)
   {
      try
      {
         FileWriter antfw = Utils.createFile("build.xml", outputDir);
         BuildIvyXmlGen bxGen = new BuildIvyXmlGen();
         bxGen.generate(def, antfw);
         antfw.close();

         FileWriter ivyfw = Utils.createFile("ivy.xml", outputDir);
         IvyXmlGen ixGen = new IvyXmlGen();
         ixGen.generate(def, ivyfw);
         ivyfw.close();

         FileWriter ivySettingsfw = Utils.createFile("ivy.settings.xml", outputDir);
         IvySettingsXmlGen isxGen = new IvySettingsXmlGen();
         isxGen.generate(def, ivySettingsfw);
         ivySettingsfw.close();
      }
      catch (IOException ioe)
      {
         ioe.printStackTrace();
      }
   }
1068637
def display_results_html
		  output ="<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title></title></head><body>"
		  output.concat("<table><thead><tr><td>FileName</td></tr><tr><td>#{@folder1}</td></tr><tr><td>#{@folder2}</td></tr><tr><td>Equal</td></tr></thead>")
      @filehash.each{ |key, value| output.concat("<tbody><tr><td>#{value.file_name}</td></tr><tr><td>#{value.file_hash1}</td></tr><tr><td>#{value.file_hash2}</td></tr><tr><td>#{value.file_hash1==value.file_hash2}</td></tr>")}
      output.concat("</tbody></table></body></html>")
      puts output
    end
718374
def DefaultExtension(schema_obj, form_obj, schemata=None):
    """"""

    if schemata is None:
        schemata = ['systemconfig', 'profile', 'client']

    DefaultExtends = {
        'schema': {
            "properties/modules": [
                schema_obj
            ]
        },
        'form': {
            'modules': {
                'items/': form_obj
            }
        }
    }

    output = {}

    for schema in schemata:
        output[schema] = DefaultExtends

    return output
194428
public static void createHtmlSequencePlotFile(String title, Schema schema, List<List<Writable>> sequence,
                    File output) throws Exception {
        String s = createHtmlSequencePlots(title, schema, sequence);
        FileUtils.writeStringToFile(output, s, StandardCharsets.UTF_8);
    }
1203174
private String getHtmlForPDFConversion() throws IOException {
        StringBuilder oldContent = new StringBuilder();

        FileReader fr = new FileReader(file);
        try (BufferedReader reader = new BufferedReader(fr)) {
            String line;
            while ((line = reader.readLine()) != null) {
                oldContent.append(line);
                oldContent.append("\r\n");
            }
        }

        // replace all non convertible elements with empty text or modify for conversion
        String str = oldContent.toString()
                .replaceAll("<script type='text/javascript'>(?s).*</script>", "")
                .replaceAll("<tr>\\s*<th>View Results</th>(?s).*?</tr>", "")
                .replaceAll("&nbsp;", " ");

        String imagePattern = "(<img(?s).*? src='(.*?)'(?s).*?)</img>";
        Pattern r = Pattern.compile(imagePattern);
        Matcher m = r.matcher(str);
        int imageCount = 0;
        while (m.find()) {
            str = str.replaceFirst("<a href='javascript:void\\(0\\)'(?s).*?(<img(?s).*? src='(.*?)'(?s).*?)" +
                            " style(?s).*?</img>",
                    "<a href=\"#image-" + imageCount + "\">View Screenshot</a>");
            str = str.replaceFirst("</body>", "<p style='page-break-before: always' id='image-" + imageCount++ + "'></p" +
                    ">" +
                    m.group().replaceAll("width='300px' style(?s).*?'>", "height='600px' width='1000px'>") + "</body>");
        }
        return str;
    }
956349
def convertforoutput(self,outputfile):
        """"""
        super(CharEncodingConverter,self).convertforoutput(outputfile)

        return withheaders( flask.make_response( ( line.encode(self.charset) for line in outputfile ) ) , 'text/plain; charset=' + self.charset)
1162842
def fill_schema_from_xsd_file(filename, schema):
    
    ifmap_statements = _parse_xsd_file(filename)
    properties_all = []

    for v in ifmap_statements.values():
        if (isinstance(v[0], IDLParser.Link)):
            src_name = v[1]
            target_name = v[2]
            src = schema._get_or_add_resource(src_name)
            target = schema._get_or_add_resource(target_name)
            if "has" in v[3]:
                src.children.append(target_name)
                target.parent = src_name
            if "ref" in v[3]:
                src.refs.append(target_name)
                target.back_refs.append(src_name)
        elif isinstance(v[0], IDLParser.Property):
            target_name = v[1][0]
            prop = ResourceProperty(v[0].name, is_list=v[0].is_list, is_map=v[0].is_map)
            if target_name != 'all':
                target = schema._get_or_add_resource(target_name)
                target.properties.append(prop)
            else:
                properties_all.append(prop)

    for r in schema.all_resources():
        schema.resource(r).properties += properties_all
1298432
def generate_schema(table, export_fields, output_format, output_fobj):
    

    if output_format in ("csv", "txt"):
        from rows import plugins

        data = [
            {
                "field_name": fieldname,
                "field_type": fieldtype.__name__.replace("Field", "").lower(),
            }
            for fieldname, fieldtype in table.fields.items()
            if fieldname in export_fields
        ]
        table = plugins.dicts.import_from_dicts(
            data, import_fields=["field_name", "field_type"]
        )
        if output_format == "txt":
            plugins.txt.export_to_txt(table, output_fobj)
        elif output_format == "csv":
            plugins.csv.export_to_csv(table, output_fobj)

    elif output_format == "sql":
        # TODO: may use dict from rows.plugins.sqlite or postgresql
        sql_fields = {
            rows.fields.BinaryField: "BLOB",
            rows.fields.BoolField: "BOOL",
            rows.fields.IntegerField: "INT",
            rows.fields.FloatField: "FLOAT",
            rows.fields.PercentField: "FLOAT",
            rows.fields.DateField: "DATE",
            rows.fields.DatetimeField: "DATETIME",
            rows.fields.TextField: "TEXT",
            rows.fields.DecimalField: "FLOAT",
            rows.fields.EmailField: "TEXT",
            rows.fields.JSONField: "TEXT",
        }
        fields = [
            "    {} {}".format(field_name, sql_fields[field_type])
            for field_name, field_type in table.fields.items()
            if field_name in export_fields
        ]
        sql = (
            dedent(
                """
                CREATE TABLE IF NOT EXISTS {name} (
                {fields}
                );
                """
            )
            .strip()
            .format(name=table.name, fields=",\n".join(fields))
            + "\n"
        )
        output_fobj.write(sql)

    elif output_format == "django":
        django_fields = {
            rows.fields.BinaryField: "BinaryField",
            rows.fields.BoolField: "BooleanField",
            rows.fields.IntegerField: "IntegerField",
            rows.fields.FloatField: "FloatField",
            rows.fields.PercentField: "DecimalField",
            rows.fields.DateField: "DateField",
            rows.fields.DatetimeField: "DateTimeField",
            rows.fields.TextField: "TextField",
            rows.fields.DecimalField: "DecimalField",
            rows.fields.EmailField: "EmailField",
            rows.fields.JSONField: "JSONField",
        }
        table_name = "".join(word.capitalize() for word in table.name.split("_"))

        lines = ["from django.db import models"]
        if rows.fields.JSONField in [
            table.fields[field_name] for field_name in export_fields
        ]:
            lines.append("from django.contrib.postgres.fields import JSONField")
        lines.append("")

        lines.append("class {}(models.Model):".format(table_name))
        for field_name, field_type in table.fields.items():
            if field_name not in export_fields:
                continue

            if field_type is not rows.fields.JSONField:
                django_type = "models.{}()".format(django_fields[field_type])
            else:
                django_type = "JSONField()"
            lines.append("    {} = {}".format(field_name, django_type))

        result = "\n".join(lines) + "\n"
        output_fobj.write(result)
601126
def render_file(self, filename):
        
        dirname, basename = split(filename)
        with changedir(dirname):
            infile = abspath(basename)
            outfile = abspath('.%s.html' % basename)
            self.docutils.publish_file(infile, outfile, self.styles)
            return outfile