public void writeFooter() { output.append( " private Matcher<? extends List> withLabel(String label) {\n" + " return WidgetMatcherFactory.withLabel(label, finder);\n" + " }\n\n"); output.append('}').append(newLine); }
public static Map<Lang, Result> convertFromFiles( ClassLoader loader, List<Lang> lang, String file, String fqn, String method) throws Exception { DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); StandardJavaFileManager manager = javac.getStandardFileManager(diagnostics, locale, charset); Iterable<? extends JavaFileObject> fileObjects = manager.getJavaFileObjects(file); StringWriter out = new StringWriter(); JavaCompiler.CompilationTask task = javac.getTask( out, manager, diagnostics, Collections.<String>emptyList(), Collections.<String>emptyList(), fileObjects); task.setLocale(locale); ConvertingProcessor processor = new ConvertingProcessor(lang, fqn, method); task.setProcessors(Collections.<Processor>singletonList(processor)); if (task.call()) { return processor.getResults(); } else { StringWriter message = new StringWriter(); PrintWriter writer = new PrintWriter(message); writer.append("Compilation of ").append(file).println(" failed:"); for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { writer.append(diagnostic.getMessage(locale)); } writer.println("console:"); writer.append(out.getBuffer()); throw new Exception(message.toString()); } }
@Override public Void visitar(NoRetorne no) throws ExcecaoVisitaASA { NoExpressao expressao = no.getExpressao(); if (expressao != null) { saida.append("return "); if (no.temPai()) { if (no.getPai() instanceof NoDeclaracaoFuncao) { TipoDado tipoRetornoFuncao = ((NoDeclaracaoFuncao) no.getPai()).getTipoDado(); if (expressao.getTipoResultante() == TipoDado.REAL && tipoRetornoFuncao == TipoDado.INTEIRO) { saida.append("(int)"); } } } else { throw new IllegalStateException("retorne não tem pai!"); } expressao.aceitar(this); } else { saida.append("return"); } return null; }
private VisitorGeracaoCodigo geraInicializacaoVariaveisGlobais() throws ExcecaoVisitaASA { boolean excluiConstantes = true; List<NoDeclaracaoInicializavel> variaveisGlobais = getVariaveisGlobaisDeclaradas(asa, excluiConstantes); if (variaveisGlobais .isEmpty()) // não sobrescreve o método de inicialização se não houverem variáveis globais // que não são constantes { return this; } saida.append(Utils.geraIdentacao(nivelEscopo)).append("@Override").println(); saida.append(Utils.geraIdentacao(nivelEscopo)); saida .format("protected void inicializar() throws ErroExecucao, InterruptedException {") .println(); inicializaVariaveisGlobaisNaoPassadasPorReferencia(variaveisGlobais); inicializaVariaveisGlobaisQueSaoPassadasPorReferencia(); saida.append(Utils.geraIdentacao(nivelEscopo)); saida.append("}").println(); return this; }
@Override public Void visitar(NoFacaEnquanto no) throws ExcecaoVisitaASA { String identacao = Utils.geraIdentacao(nivelEscopo); saida.append("do").println(); saida.append(identacao).append("{").println(); geraVerificacaoThreadInterrompida(); List<NoBloco> blocos = no.getBlocos(); if (blocos != null) { visitarBlocos(blocos); saida.println(); } saida.append(identacao).append("}").println(); saida.append(identacao).append("while("); no.getCondicao().aceitar(this); saida.append(");").println(); return null; }
public static void makeAdjacencyMatrixDirected(int n) { Random randy = new Random(); double[][] edges = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { edges[i][j] = randy.nextInt(n); } } try (PrintWriter print = new PrintWriter(new File(n + "diradj.csv"))) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { print.append(edges[i][j] + ","); /*if (j == n-1){ print.append("\"" + edges[i][j] + "\""); } else { print.append("\"" + edges[i][j] + "\","); }*/ } print.append("\n"); } print.close(); } catch (FileNotFoundException e) { } }
// Append new table row + text input private void addRowWithInput(PrintWriter w, String name, String value) throws IOException { if (value == null) value = ""; w.append("<tr><td>"); w.append(name + "</td><td>"); addInput(w, name, value); w.append("</td></tr>"); }
private static void assertSameChecks( Map<String, Throwable> singlePassChecks, Map<String, Throwable> multiPassChecks) { if (!singlePassChecks.keySet().equals(multiPassChecks.keySet())) { Map<String, Throwable> missing = new HashMap<>(singlePassChecks); Map<String, Throwable> extras = new HashMap<>(multiPassChecks); missing.keySet().removeAll(multiPassChecks.keySet()); extras.keySet().removeAll(singlePassChecks.keySet()); StringBuilder headers = new StringBuilder("\n"); StringWriter diff = new StringWriter(); PrintWriter writer = new PrintWriter(diff); if (!missing.isEmpty()) { writer.append("These expected checks were missing:\n"); for (Map.Entry<String, Throwable> check : missing.entrySet()) { writer.append(" "); headers.append("Missing: ").append(check.getKey()).append("\n"); check.getValue().printStackTrace(writer); } } if (!extras.isEmpty()) { writer.append("These extra checks were not expected:\n"); for (Map.Entry<String, Throwable> check : extras.entrySet()) { writer.append(" "); headers.append("Unexpected: ").append(check.getKey()).append("\n"); check.getValue().printStackTrace(writer); } } fail(headers.toString() + diff.toString()); } }
@Override public void transcode(BasicStroke stroke, PrintWriter output) { if (stroke.getDashArray() == null) { output.append( "new BasicStroke(" + FloatTranscoder.INSTANCE.transcode(stroke.getLineWidth()) + ", " + stroke.getEndCap() + ", " + stroke.getLineJoin() + ", " + FloatTranscoder.INSTANCE.transcode(stroke.getMiterLimit()) + ")"); } else { output.append( "new BasicStroke(" + FloatTranscoder.INSTANCE.transcode(stroke.getLineWidth()) + ", " + stroke.getEndCap() + ", " + stroke.getLineJoin() + ", " + FloatTranscoder.INSTANCE.transcode(stroke.getMiterLimit()) + ", " + FloatArrayTranscoder.INSTANCE.transcode(stroke.getDashArray()) + ", " + FloatTranscoder.INSTANCE.transcode(stroke.getDashPhase()) + ")"); } }
@Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { synchronized (mLock) { String prefix = (args.length > 0) ? args[0] : ""; String tab = " "; pw.append(prefix).append("print jobs:").println(); final int printJobCount = mPrintJobs.size(); for (int i = 0; i < printJobCount; i++) { PrintJobInfo printJob = mPrintJobs.get(i); pw.append(prefix).append(tab).append(printJob.toString()); pw.println(); } pw.append(prefix).append("print job files:").println(); File[] files = getFilesDir().listFiles(); if (files != null) { final int fileCount = files.length; for (int i = 0; i < fileCount; i++) { File file = files[i]; if (file.isFile() && file.getName().startsWith(PRINT_JOB_FILE_PREFIX)) { pw.append(prefix).append(tab).append(file.getName()).println(); } } } } }
@Override public void getInfo(PrintWriter pw) { pw.append(" CellDomainName = ").println(getCellDomainName()); pw.format( " I/O rcv=%d;asw=%d;frw=%d;rpy=%d;exc=%d\n", _packetsReceived, _packetsAnswered, _packetsForwarded, _packetsReplied, _exceptionCounter); long fm = _runtime.freeMemory(); long tm = _runtime.totalMemory(); pw.format(" Memory : tot=%d;free=%d;used=%d\n", tm, fm, tm - fm); pw.println(" Cells (Threads)"); for (String name : _nucleus.getCellNames()) { pw.append(" ").append(name).append("("); Thread[] threads = _nucleus.getThreads(name); if (threads != null) { boolean first = true; for (Thread thread : threads) { pw.print(thread.getName()); if (first) { first = false; } else { pw.print(","); } } } pw.println(")"); } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uri = req.getRequestURI(); if (uri.endsWith("/display")) { printInfo(resp.getWriter()); } else if (uri.endsWith("/redirect")) { resp.sendRedirect("servlet/display"); // do a redirect, the cid is not propagated; } else if (uri.endsWith("/begin")) { conversation.begin(); printInfo(resp.getWriter()); } else if (uri.endsWith("/end")) { conversation.end(); printInfo(resp.getWriter()); } else if (uri.endsWith("/set")) { setMessage(req); printInfo(resp.getWriter()); } else if (uri.endsWith("/invalidateSession")) { observer.reset(); req.getSession().invalidate(); printInfo(resp.getWriter()); } else if (uri.endsWith("/listConversationsDestroyedWhileBeingAssociated")) { PrintWriter writer = resp.getWriter(); writer.append("ConversationsDestroyedWhileBeingAssociated: "); printSessionIds(writer, observer.getAssociatedConversationIds()); } else if (uri.endsWith("/listConversationsDestroyedWhileBeingDisassociated")) { PrintWriter writer = resp.getWriter(); writer.append("ConversationsDestroyedWhileBeingDisassociated: "); printSessionIds(writer, observer.getDisassociatedConversationIds()); } else { resp.setStatus(404); } resp.setContentType("text/plain"); }
public void writeHeader(Set<String> imports) { output.append("// Generated source.").append(newLine); // $NON-NLS-1$ output.append("package ").append(packageName).append(';').append(newLine); // $NON-NLS-1$ output.append(newLine); output.append(newLine); writeImports(imports); }
/** * Write HTML header information. * * @param writer */ private void appendHeader(PrintWriter writer) { writer.append("<html>\n"); writer.append("<head>\n"); writer.append("<title>Monthly Event Schedule</title>\n"); writer.append("</head>\n"); writer.append("<body>\n"); writer.append("<h1>Monthly Event Schedule</h1>\n"); }
/** * Adds a form field to the request * * @param name field name * @param value field value */ public void addFormField(String name, String value) { writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED); writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED); writer.append(LINE_FEED); writer.append(value).append(LINE_FEED); writer.flush(); }
@Override public void printSetup(PrintWriter pw) { pw.append("rh set timeout ").println(TimeUnit.MILLISECONDS.toSeconds(stageTimeout)); pw.append("st set timeout ").println(TimeUnit.MILLISECONDS.toSeconds(flushTimeout)); pw.append("rm set timeout ").println(TimeUnit.MILLISECONDS.toSeconds(removeTimeout)); synchronized (suppressedStoreErrors) { suppressedStoreErrors.forEach(rc -> pw.append("st suppress rc ").println(rc)); } }
@Override public void execute() throws MojoExecutionException, MojoFailureException { File basedir = new File(prefix); TemplateLoader loader = new FileTemplateLoader(basedir, suffix); Handlebars handlebars = new Handlebars(loader); File output = new File(this.output); PrintWriter writer = null; boolean error = true; InputStream runtimeIS = getClass().getResourceAsStream("/handlebars.runtime.js"); try { writer = new PrintWriter(output); if (includeRuntime) { IOUtil.copy(runtimeIS, writer); } List<File> files = FileUtils.getFiles(basedir, "/**/*" + suffix, null); getLog().info("Compiling templates..."); getLog().debug("Options:"); getLog().debug(" output: " + output); getLog().debug(" prefix: " + prefix); getLog().debug(" suffix: " + suffix); getLog().debug(" minimize: " + minimize); getLog().debug(" includeRuntime: " + includeRuntime); Context nullContext = Context.newContext(null); for (File file : files) { String templateName = file.getPath().replace(prefix, "").replace(suffix, ""); if (templateName.startsWith("/")) { templateName = templateName.substring(1); } getLog().debug("compiling: " + templateName); Template template = handlebars.compileInline("{{precompile \"" + templateName + "\"}}"); Options opts = new Options.Builder(handlebars, TagType.VAR, nullContext, template).build(); writer.append("// Source: ").append(file.getPath()).append("\n"); writer.append(PrecompileHelper.INSTANCE.apply(templateName, opts)).append("\n\n"); } writer.flush(); IOUtil.close(writer); if (minimize) { minimize(output); } if (files.size() > 0) { getLog().info(" templates were saved in: " + output); error = false; } else { getLog().warn(" no templates were found"); } } catch (IOException ex) { throw new MojoFailureException("Can't scan directory " + basedir, ex); } finally { IOUtil.close(runtimeIS); IOUtil.close(writer); if (error) { output.delete(); } } }
public static void main(String[] args) throws Exception { OptionsParser parser = OptionsParser.newOptionsParser(RemoteOptions.class, RemoteWorkerOptions.class); parser.parseAndExitUponError(args); RemoteOptions remoteOptions = parser.getOptions(RemoteOptions.class); RemoteWorkerOptions remoteWorkerOptions = parser.getOptions(RemoteWorkerOptions.class); if (remoteWorkerOptions.workPath == null) { printUsage(parser); return; } System.out.println("*** Starting Hazelcast server."); ConcurrentMap<String, byte[]> cache = new HazelcastCacheFactory().create(remoteOptions); System.out.println( "*** Starting grpc server on all locally bound IPs on port " + remoteWorkerOptions.listenPort + "."); Path workPath = getFileSystem().getPath(remoteWorkerOptions.workPath); FileSystemUtils.createDirectoryAndParents(workPath); RemoteWorker worker = new RemoteWorker(workPath, remoteOptions, remoteWorkerOptions, cache); final Server server = ServerBuilder.forPort(remoteWorkerOptions.listenPort).addService(worker).build(); server.start(); final Path pidFile; if (remoteWorkerOptions.pidFile != null) { pidFile = getFileSystem().getPath(remoteWorkerOptions.pidFile); PrintWriter writer = new PrintWriter(pidFile.getOutputStream()); writer.append(Integer.toString(ProcessUtils.getpid())); writer.append("\n"); writer.close(); } else { pidFile = null; } Runtime.getRuntime() .addShutdownHook( new Thread() { @Override public void run() { System.err.println("*** Shutting down grpc server."); server.shutdown(); if (pidFile != null) { try { pidFile.delete(); } catch (IOException e) { System.err.println("Cannot remove pid file: " + pidFile.toString()); } } System.err.println("*** Server shut down."); } }); server.awaitTermination(); }
public void printMatrixIntoCSV(PrintWriter wr, Matrix matrix) { for (int i = 0; i < matrix.getRow(); i++) { for (int j = 0; j < matrix.getColumn(); j++) { String valueStr = matrix.getValuePos(i, j).toString(); valueStr = valueStr.replace(".", ","); wr.append(valueStr + ";"); // Siguiente celda } wr.append("\n"); // Salto de fila en excel } }
@Override public Void visitar(NoPare noPare) throws ExcecaoVisitaASA { if (simularBreakCaso) { saida.append(GeradorSwitchCase.NOME_VARIAVEL_BREAK).append(" = true"); } else { saida.append("break"); } return null; }
@Override public Void visitar(NoReferenciaVetor no) throws ExcecaoVisitaASA { saida.append(no.getNome()); saida.append("["); no.getIndice().aceitar(this); saida.append("]"); return null; }
// Escribe en el fichero los dos vectores introducidos por parámetrosb public void writeInputsOutputs( ArrayList<BigDecimal[]> inputs, ArrayList<BigDecimal[]> desiredOutput) { for (int i = 0; i < inputs.size(); i++) { wr.append("Patrón: " + i + "\n"); for (int j = 0; j < inputs.get(i).length; j++) { wr.append("Rm: " + inputs.get(i)[j] + " Ri: " + desiredOutput.get(i)[j] + "\n"); } wr.append("\n"); } }
private void renderErrors(PrintWriter writer, Collection<CompilationError> errors) throws IOException { sendJuzuCSS(writer); // writer.append("<div class=\"juzu\">"); for (CompilationError error : errors) { writer.append("<div class=\"juzu-box\">"); writer.append("<div class=\"juzu-message\">").append(error.getMessage()).append("</div>"); // Display the source code File source = error.getSourceFile(); if (source != null) { int line = error.getLocation().getLine(); int from = line - 2; int to = line + 3; BufferedReader reader = new BufferedReader(new FileReader(source)); int count = 1; writer.append("<pre><ol start=\"").append(String.valueOf(from)).append("\">"); for (String s = reader.readLine(); s != null; s = reader.readLine()) { if (count >= from && count < to) { if (count == line) { writer.append("<li><span class=\"error\">").append(s).append("</span></li>"); } else { writer.append("<li><span>").append(s).append("</span></li>"); } } count++; } writer.append("</ol></pre>"); } writer.append("</div>"); } writer.append("</div>"); }
public void batchPredict() { // load all test set String modelFile = "data\\AcquireValueShopper\\decisionTable_bayes_trees.model".replace("\\", File.separator); String pathTest = "data/AcquireValueShopper/test_new.csv"; String pathPredict = "data/AcquireValueShopper/submission.csv"; Scanner scanner; String line = ""; String[] partsOfLine = null; String id = ""; PrintWriter output; Map<String, String> testSet = new HashMap<String, String>(); try { scanner = new Scanner(new File(pathTest)); while (scanner.hasNext()) { line = scanner.nextLine().trim(); partsOfLine = line.split(","); id = partsOfLine[0]; testSet.put(id, line); } scanner.close(); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } double[] returnProb; double prob = 0.0; // predict try { // load model Classifier classifier = (Classifier) SerializationHelper.read(modelFile); output = new PrintWriter(pathPredict); output.append("id,repeatProbability" + "\n"); Iterator<String> idIterator = testSet.keySet().iterator(); while (idIterator.hasNext()) { id = idIterator.next(); line = testSet.get(id); Instances instances = buildInstance(line); Instance instance = instances.instance(0); returnProb = classifier.distributionForInstance(instance); prob = returnProb[1]; // prob = classifier.classifyInstance(instance); output.append(id + "," + prob + "\n"); } output.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * @param request * @param response * @param doc * @throws IOException */ private void send( SlingHttpServletRequest request, SlingHttpServletResponse response, ServletDocumentation doc) throws IOException { PrintWriter writer = response.getWriter(); writer.append(DocumentationConstants.HTML_HEADER); writer.append("<h1>Service: "); writer.append(doc.getName()); writer.append("</h1>"); doc.send(request, response); writer.append(DocumentationConstants.HTML_FOOTER); }
public void writeOuDesiredOuObtained( ArrayList<BigDecimal[]> outputs, ArrayList<BigDecimal[]> desiredOutput) { for (int i = 0; i < outputs.size(); i++) { wr.append("Patrón: " + i + "\n"); for (int j = 0; j < outputs.get(i).length; j++) { wr.append( "Obtenida: " + outputs.get(i)[j] + " Deseada " + desiredOutput.get(i)[j] + "\n"); } wr.append("\n"); } }
/** * Writes the configuration to the given stream, flushing it at the end * * @param out Output destination * @param comments Comments which are added to the beginning of the stream. One comment is written * on each line, and they are all prefixed with the comment character */ public void outputConfiguration(OutputStream out, String... comments) throws IOException { PrintWriter w = new PrintWriter(out); if (comments.length > 0) { for (String comment : comments) w.append("% " + comment + "\n"); w.append("\n"); } outputConfiguration(w, ""); w.flush(); }
public void printMatrixIntoFile(Matrix matrix) { for (int i = 0; i < matrix.getRow(); i++) { for (int j = 0; j < matrix.getColumn(); j++) { BigDecimal b = matrix.getValuePos(i, j); wr.append(b + ";"); // String valueStr = matrix.getValuePos(i, j).toString(); // valueStr = valueStr.replace(".", ","); // wr.append(valueStr+ ";"); //Siguiente celda } wr.append("\n"); // Salto de fila en excel } }
public void writeMatriz(Matrix W) { wr.append("Matrix W:\n"); for (int i = 0; i < W.getRow(); i++) { for (int j = 0; j < W.getColumn(); j++) { String valueStr = W.getValuePos(i, j).toString(); valueStr = valueStr.replace(".", ","); wr.append(valueStr + ";"); // Siguiente celda } wr.append("\n"); // Salto de fila en excel } }
private void writeItemsFile() { try { File items = new File("plugins" + File.separator + "MinecartMania" + File.separator + "items.txt"); PrintWriter pw = new PrintWriter(items); pw.append( "This file is a list of all the data values, and matching item names for Minecart Mania. \nThis list is never used, and changes made to this file will be ignored"); pw.append("\n"); pw.append("\n"); pw.append("Items:"); pw.append("\n"); for (Item item : Item.values()) { String name = "Item Name: " + item.toString(); pw.append(name); String id = ""; for (int i = name.length() - 1; i < 40; i++) { id += " "; } pw.append(id); id = "Item Id: " + String.valueOf(item.getId()); pw.append(id); String data = ""; for (int i = id.length() - 1; i < 15; i++) { data += " "; } data += "Item Data: " + String.valueOf(item.getData()); pw.append(data); pw.append("\n"); } pw.close(); } catch (Exception e) { } }