Ejemplo n.º 1
1
  public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    StringTokenizer st;

    t = Integer.parseInt(br.readLine());
    while (t-- > 0) {
      st = new StringTokenizer(br.readLine());
      n = Integer.parseInt(st.nextToken());
      m = Integer.parseInt(st.nextToken());
      S = Integer.parseInt(st.nextToken());
      T = Integer.parseInt(st.nextToken());

      // build graph
      AdjList = new Vector<Vector<IntegerPair>>();
      for (i = 0; i < n; i++) AdjList.add(new Vector<IntegerPair>());

      while (m-- > 0) {
        st = new StringTokenizer(br.readLine());
        a = Integer.parseInt(st.nextToken());
        b = Integer.parseInt(st.nextToken());
        w = Integer.parseInt(st.nextToken());
        AdjList.get(a).add(new IntegerPair(b, w)); // bidirectional
        AdjList.get(b).add(new IntegerPair(a, w));
      }

      // SPFA from source S
      // initially, only S has dist = 0 and in the queue
      Vector<Integer> dist = new Vector<Integer>();
      for (i = 0; i < n; i++) dist.add(INF);
      dist.set(S, 0);
      Queue<Integer> q = new LinkedList<Integer>();
      q.offer(S);
      Vector<Boolean> in_queue = new Vector<Boolean>();
      for (i = 0; i < n; i++) in_queue.add(false);
      in_queue.set(S, true);

      while (!q.isEmpty()) {
        int u = q.peek();
        q.poll();
        in_queue.set(u, false);
        for (j = 0; j < AdjList.get(u).size(); j++) { // all outgoing edges from u
          int v = AdjList.get(u).get(j).first(), weight_u_v = AdjList.get(u).get(j).second();
          if (dist.get(u) + weight_u_v < dist.get(v)) { // if can relax
            dist.set(v, dist.get(u) + weight_u_v); // relax
            if (!in_queue.get(v)) { // add to the queue only if it's not in the queue
              q.offer(v);
              in_queue.set(v, true);
            }
          }
        }
      }

      pr.printf("Case #%d: ", caseNo++);
      if (dist.get(T) != INF) pr.printf("%d\n", dist.get(T));
      else pr.printf("unreachable\n");
    }

    pr.close();
  }
Ejemplo n.º 2
0
  public static void main(String[] args) throws IOException {
    StreamsPerfTest perfTest = new StreamsPerfTest();
    PrintWriter console = new PrintWriter(System.out, true);

    print("temp file:" + TEMP_FILE_NAME);
    print("initial file contains " + FILE_CONTENT.length() + " characters");
    print("initial file contains " + FILE_CONTENT_LIST.size() + " rows");
    print("-------------------------------------------");

    String formatPattern = "%1$30s : %2$-10.4f s\n";
    print("1. test 10 attempts:");
    for (StreamTester tester : TESTERS)
      console.printf(formatPattern, tester.getName(), perfTest.test(tester, 10));
    print("-------------------------------------------");

    print("2. test 100 attempts:");
    for (StreamTester tester : TESTERS)
      console.printf(formatPattern, tester.getName(), perfTest.test(tester, 100));
    print("-------------------------------------------");

    print("3. test 200 attempts:");
    for (StreamTester tester : TESTERS)
      console.printf(formatPattern, tester.getName(), perfTest.test(tester, 200));
    print("-------------------------------------------");
  }
Ejemplo n.º 3
0
  static void dumpToFile(
      String name1,
      String name2,
      OutputStream ostream,
      Hashtable<String, PkgEntry> tbl1,
      Hashtable<String, PkgEntry> tbl2) {

    List<String> keyList = new ArrayList<String>();
    for (String x : Collections.list(tbl1.keys())) {
      keyList.add(x);
    }
    Collections.sort(keyList);
    PrintWriter pw = null;
    pw = new PrintWriter(new OutputStreamWriter(ostream));
    pw.printf("\t%s\t%s\n", name1, name2);
    long sum1 = 0L;
    long sum2 = 0L;
    for (String x : keyList) {
      pw.printf("%s\t%s\t%s\n", x, tbl1.get(x).getSize() / 1024, tbl2.get(x).getSize() / 1024);
      sum1 += tbl1.get(x).getSize();
      sum2 += tbl2.get(x).getSize();
    }
    pw.printf("Total\t%s\t%s\n", sum1 / 1024, sum2 / 1024);
    pw.flush();
  }
  @Override
  public void intercept(InterceptorStack stack, ControllerMethod method, Object instance)
      throws InterceptionException {
    try {
      stack.next(method, instance);
    } catch (Exception e) {

      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);

      Throwable cause = e.getCause();
      if (cause != null) {
        if (cause instanceof ConstraintViolationException) {
          Set<ConstraintViolation<?>> constraintViolations =
              ((ConstraintViolationException) cause).getConstraintViolations();
          pw.printf("\nConstraint Violations: \n");
          for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            pw.printf("\t" + constraintViolation.getConstraintDescriptor().getAnnotation() + "\n");
          }
          pw.printf("\n");
          log.error(sw.toString());
        }
        cause.printStackTrace(pw);
      } else {
        e.printStackTrace(pw);
      }

      pw.close();
      result.include("stacktrace", sw.toString());
      throw e;
    }
  }
 public static void printResults(WordInfo[] table, int head) {
   out.printf("\nWords        Frequency\n\n");
   while (head != -1) {
     out.printf("%-15s %2d\n", table[head].word, table[head].freq);
     head = table[head].next;
   }
 } // end printResults
Ejemplo n.º 6
0
 public void saveView(String filename) {
   BoundingSphere bs = _ipg.getBoundingSphere(true);
   Vector3 tvec = _view.getTranslate();
   try {
     FileWriter fw = new FileWriter(filename);
     PrintWriter out = new PrintWriter(fw);
     out.println(bs.getRadius());
     Point3 center = bs.getCenter();
     out.printf("%f %f %f \n", center.x, center.y, center.z);
     out.println(_view.getAzimuth());
     out.println(_view.getElevation());
     out.println(_view.getScale());
     out.printf("%f %f %f \n", tvec.x, tvec.y, tvec.z);
     Iterator<ImagePanel> itr = _ipg.getImagePanels();
     while (itr.hasNext()) {
       ImagePanel ip = itr.next();
       AxisAlignedFrame aaf = ip.getFrame();
       Point3 min = aaf.getCornerMin();
       Point3 max = aaf.getCornerMax();
       out.printf("%f %f %f %f %f %f\n", min.x, min.y, min.z, max.x, max.y, max.z);
     }
     out.println(_pmax);
     out.println(_color.getCode());
     out.close();
   } catch (Exception e) {
     System.out.println(e);
   }
 }
Ejemplo n.º 7
0
  /**
   * @param args
   * @throws IOException
   * @throws UnknownHostException
   * @throws InterruptedException
   */
  public static void main(String[] args)
      throws UnknownHostException, IOException, InterruptedException {

    System.out.printf("TcpClient SERVER_IP=%s port=%s\n", SERVER_IP, SERVER_PORT);
    Socket socket = new Socket(SERVER_IP, SERVER_PORT);

    PrintWriter printWriter = new PrintWriter(socket.getOutputStream());

    Scanner scanner = new Scanner(socket.getInputStream());

    String fileName = args[0];
    System.out.printf("TcpClient fileName=%s\n", fileName);
    List<String> lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);

    for (String line : lines) {
      System.out.printf("TcpClient Enviado='%s'\n", line);
      printWriter.printf("%s\n", line);
      printWriter.flush();
      String lineIn = scanner.nextLine();
      System.out.printf("TcpClient Recibido='%s'\n", lineIn);

      Thread.sleep(5000);
    }
    System.out.printf("TcpClient printf '.'\n");
    printWriter.printf(".\n");
    printWriter.flush();
    Thread.sleep(5000);

    System.out.printf("TcpClient end.\n");

    socket.close();
  }
Ejemplo n.º 8
0
  @Deprecated
  public static void makeCode() {
    File infile = new File("/home/hoshun/dmoz/dmoz-indexed-url");
    File outfile = new File("/home/hoshun/dmoz/generateUrlToSpecifiedCategory");
    File outformatfile = new File("/home/hoshun/dmoz/dmoz-specified-url");

    CategorizedURLs urlToCategory = new CategorizedURLs(infile, true);
    SpecifiedTopics specifiedTopics = new SpecifiedTopics();
    try {
      PrintWriter out = new PrintWriter(outfile);
      PrintWriter out2 = new PrintWriter(outformatfile);

      Map<Integer, Category> idToCategory = urlToCategory.idToCategory;
      Map<Integer, String> idToUrl = urlToCategory.idToUrl;

      for (int id : idToCategory.keySet()) {
        Category cat = idToCategory.get(id);
        if (specifiedTopics.containsCategory(cat)) {
          String url = idToUrl.get(id);

          out.printf(
              "idToCategory.put(%s,new Category(\"%s\",\"%s\"));\n", id, cat.first, cat.second);
          out.printf("idToURL.put(%s,\"%s\");\n", id, url);

          out2.printf("%s\t%s\t%s\t%s\n", id, cat.first, cat.second, url);
        }
      }

      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 9
0
  public void printReport(String outputLocation) {

    SuspectList[] suspectList = SuspectListControl.createSuspectList();

    try (PrintWriter out = new PrintWriter(outputLocation)) {

      // print title and column headings
      out.println("\n\n          CASE & SUSPECT LISTS          ");
      out.printf("%n%-15s%15s", "Cases Involved", "Suspects");
      out.printf("%n%-15s%15s", "--------------", "--------");

      for (int i = 0; i < suspectList.length; i++) {
        out.printf(
            "%n%-15s%15s", suspectList[i].getCaseInvolved(), suspectList[i].getSuspectName());

        if (suspectList[i] == suspectList[suspectList.length - 1])
          this.console.println("Report printed successfuly");
      }
    } catch (IOException ex) {
      ErrorView.display(this.getClass().getName(), "I/O Error: " + ex.getMessage());
    }

    GamePlayMenuView gamePlayMenu = new GamePlayMenuView();
    gamePlayMenu.display();
  }
Ejemplo n.º 10
0
  /**
   * Prints costs and #vehicles to the given writer
   *
   * @param out the destination writer
   * @param solution the solution to be printed
   */
  public static void print(
      PrintWriter out,
      VehicleRoutingProblem problem,
      VehicleRoutingProblemSolution solution,
      Print print) {
    String leftAlign = "| %-13s | %-8s | %n";

    out.format("+--------------------------+%n");
    out.printf("| problem                  |%n");
    out.format("+---------------+----------+%n");
    out.printf("| indicator     | value    |%n");
    out.format("+---------------+----------+%n");

    out.format(leftAlign, "noJobs", problem.getJobs().values().size());
    Jobs jobs = getNuOfJobs(problem);
    out.format(leftAlign, "noServices", jobs.nServices);
    out.format(leftAlign, "noShipments", jobs.nShipments);
    out.format(leftAlign, "fleetsize", problem.getFleetSize().toString());
    out.format("+--------------------------+%n");

    String leftAlignSolution = "| %-13s | %-40s | %n";
    out.format("+----------------------------------------------------------+%n");
    out.printf("| solution                                                 |%n");
    out.format("+---------------+------------------------------------------+%n");
    out.printf("| indicator     | value                                    |%n");
    out.format("+---------------+------------------------------------------+%n");
    out.format(leftAlignSolution, "costs", solution.getCost());
    out.format(leftAlignSolution, "noVehicles", solution.getRoutes().size());
    out.format(leftAlignSolution, "unassgndJobs", solution.getUnassignedJobs().size());
    out.format("+----------------------------------------------------------+%n");

    if (print.equals(Print.VERBOSE)) {
      printVerbose(out, problem, solution);
    }
  }
Ejemplo n.º 11
0
  private void writeStart(PrintWriter writer) {
    writer.printf("package %s;\n", getPackageName());
    writer.println("");

    // Super class. Inherit from ByteBuffer if none given.
    String superClass = getSuperClass();

    // Collect imports from generators
    for (Generator generator : generators)
      if (generator.getInclude() != null) includes.add(generator.getInclude());

    // Generate imports
    for (String include : includes) writer.printf("import %s;\n", include);

    // Import superclass
    if (superClass != null) writer.printf("import %s;\n", superClass);

    // Blank line
    if (includes.size() > 0 || superClass != null) writer.println("");

    // Class declaration
    writer.printf("public class %s", classElement.getSimpleName());

    if (superClass != null)
      writer.printf(" extends %s", superClass.substring(superClass.lastIndexOf('.') + 1));

    writer.println("");
    writer.println("{");
  }
Ejemplo n.º 12
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String appBase = ServletTestUtils.getUrlBase(req);
    String actionUrl = appBase + "/input-portal/secured/post";

    if (req.getRequestURI().endsWith("insecure")) {
      if (System.getProperty("insecure.user.principal.unsupported") == null)
        Assert.assertNotNull(req.getUserPrincipal());
      resp.setContentType("text/html");
      PrintWriter pw = resp.getWriter();
      pw.printf("<html><head><title>Input Servlet</title></head><body>%s\n", "Insecure Page");
      if (req.getUserPrincipal() != null)
        pw.printf("UserPrincipal: " + req.getUserPrincipal().getName());
      pw.print("</body></html>");
      pw.flush();
      return;
    }

    resp.setContentType("text/html");
    PrintWriter pw = resp.getWriter();
    pw.printf("<html><head><title>%s</title></head><body>", "Input Page");
    pw.printf("<form action=\"%s\" method=\"POST\">", actionUrl);
    pw.println("<input id=\"parameter\" type=\"text\" name=\"parameter\">");
    pw.println("<input name=\"submit\" type=\"submit\" value=\"Submit\"></form>");
    pw.print("</body></html>");
    pw.flush();
  }
Ejemplo n.º 13
0
  /** Force all meters in active circuit to sample. */
  @Override
  public void sampleAll() {
    Circuit ckt = DSS.activeCircuit;

    for (EnergyMeterObj meter : ckt.getEnergyMeters()) if (meter.isEnabled()) meter.takeSample();

    systemMeter.takeSample();

    if (saveDemandInterval) {
        /* Write totals demand interval file */
      PrintWriter pw = new PrintWriter(DI_Totals);

      pw.printf("%-.6g ", ckt.getSolution().getDblHour());
      for (int i = 0; i < NUM_EM_REGISTERS; i++) pw.printf(", %-.6g", DI_RegisterTotals[i]);
      pw.println();
      pw.close();

      clearDI_Totals();
      if (overloadFileIsOpen) writeOverloadReport();
      if (voltageFileIsOpen) writeVoltageReport();
    }

    // sample generator and storage objects, too
    generatorClass.sampleAll();
    DSS.storageClass.sampleAll(); // samples energymeter part of storage elements (not update)
  }
Ejemplo n.º 14
0
  /**
   * Creates an entry in the logfile with the following format:
   *
   * <pre>
   * "[dd-MM-yyyy - HH:mm:ss]\t Connecting from: %s%n", socket
   * "\t Performed Action: %s%n", performedAction
   * "\t Completed: %s%n%n", completed
   * "\t\t Path: %s\t---\tName: %s\t---\t Size: %d bytes%n", files[i].getAbsolutePath(), files[i].getName(), files[i].length()
   * "%n"
   * </pre>
   *
   * @param socket - the {@link java.net.Socket} to log
   * @param performedAction - the CRUD action performed
   * @param completed - did the {@link dk.aau.cs.giraf.savannah.server.Event} fail or succeed
   * @param files - the {@link java.io.File} objects to log
   */
  public synchronized void makeLogEntry(
      Socket socket, String performedAction, boolean completed, List<File> files) {
    FileWriter write = null;
    PrintWriter print = null;
    DateFormat dateFormat = new SimpleDateFormat("[dd-MM-yyyy - HH:mm:ss]");
    String complete = (completed == true) ? "SUCCESS" : "FAILED";

    try {
      write = new FileWriter(this.path, true);
      print = new PrintWriter(write);

      // Writing messages to the log file
      print.printf(
          dateFormat.format(Calendar.getInstance().getTime()) + "\t Connecting from: %s %n",
          socket);
      print.printf("\tPerformed Action: %s%n", performedAction);
      print.printf("\tCompleted: %s%n", complete);

      // Flushing
      print.flush();
      write.flush();

    } catch (IOException e) {
      System.err.println("Could not find file: " + this.path + " !");
    }

    for (File f : files) {
      try {
        // Writing messages to the log file
        print.printf(
            "\t\tPath: %s\t---\tName: %s\t---\tSize: %d bytes%n",
            f.getAbsolutePath(), f.getName(), f.length());

        // Flushing
        print.flush();
        write.flush();

      } catch (IOException e) {
        System.err.println("Could not find file: " + this.path + " !");
      }
    }

    try {
      print.print("%n");

      print.flush();
      write.flush();
    } catch (IOException e) {
      System.err.println("Could not find file: " + this.path + " !");
    }

    try {
      // Closing
      print.close();
      write.close();

    } catch (IOException e) {
      System.err.println("Could not find file: " + this.path + " !");
    }
  }
 public static void main(String[] args) {
   isMain = true;
   results = new double[(maxSize - minSize) + 1];
   for (int i = 0; i < results.length; i++) {
     results[i] = 0;
   }
   String paramString = "-A DmnReflexModelAgent -d ";
   for (gridSize = minSize; gridSize <= maxSize; gridSize++) {
     for (int simNum = 0; simNum < simulations; simNum++) {
       VaccumAgentDriver.main((paramString + gridSize + " " + gridSize).toString().split(" "));
     }
   }
   try {
     pw = new PrintWriter(outFileName + "X.txt");
     for (int i = 0; i < results.length; i++) {
       pw.printf("%d\n", i + minSize);
     }
     pw.close();
     pw = new PrintWriter(outFileName + "Y.txt");
     for (int i = 0; i < results.length; i++) {
       pw.printf("%.5f\n", results[i]);
     }
     pw.close();
   } catch (IOException e) {
     // System.out.println("Error initializing PrintWriter for output file " + outFileName);
   }
 }
Ejemplo n.º 16
0
  public static void main(String[] args) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter out = new PrintWriter(System.out);
    int T = parseInt(br.readLine());
    for (int t = 0; t < T; t++) {
      int N = parseInt(br.readLine());
      int[] C = new int[26];
      for (int i = 0; i < N; i++) {
        String str = br.readLine();
        int s = str.charAt(0) - 'a';
        int e = str.charAt(str.length() - 1) - 'a';
        C[s]++;
        C[e]--;
      }
      int s = 0, e = 0;
      for (int i = 0; i < 26; i++) {
        if (C[i] > 0) s += C[i];
        if (C[i] < 0) e += C[i];
      }
      boolean valid = (s == 1) && (e == -1);
      if (!valid) out.printf("The door cannot be opened.\n");
      else out.printf("Ordering is possible.\n");
    }
    out.flush();
    out.close();
    br.close();
  }
Ejemplo n.º 17
0
  public void dump(PrintWriter out) {
    FullStatFig entropyFig = new FullStatFig();
    FullStatFig numTranslationsFig = new FullStatFig();
    FullStatFig sumFig = new FullStatFig();

    for (Map.Entry<String, StringDoubleMap> e : entrySet()) {
      String s = e.getKey();
      StringDoubleMap m = e.getValue();

      FullStatFig fig = new FullStatFig(m.values());
      entropyFig.add(fig.entropy());
      numTranslationsFig.add(fig.size());
      sumFig.add(fig.total());

      out.printf(
          "%s\tentropy %s\tnTrans %d\tsum %f\n", s, Fmt.D(fig.entropy()), fig.size(), fig.total());

      ArrayList<StringDoubleMap.Entry> entries2 =
          new ArrayList<StringDoubleMap.Entry>(m.entrySet());
      Collections.sort(entries2, Collections.reverseOrder(m.entryValueComparator()));

      for (StringDoubleMap.Entry tv : entries2) {
        if (tv.getValue() < 1e-10) continue; // Skip zero entries
        String t = tv.getKey();
        out.printf("  %s: %f\n", t, tv.getValue());
      }
    }

    out.println("# entropy = " + entropyFig);
    out.println("# sum = " + sumFig);
    out.println("# numTranslations = " + numTranslationsFig);
  }
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   if (req.getParameter("setPersistBlocks") != null) {
     this.nn
         .getNamesystem()
         .setPersistBlocks(req.getParameter("setPersistBlocks").equals("ON") ? true : false);
     resp.sendRedirect("/nnconf");
     return;
   }
   if (req.getParameter("setPermissionAuditLog") != null) {
     this.nn
         .getNamesystem()
         .setPermissionAuditLog(
             req.getParameter("setPermissionAuditLog").equals("ON") ? true : false);
     resp.sendRedirect("/nnconf");
     return;
   }
   PrintWriter out = resp.getWriter();
   String hostname = this.nn.getNameNodeAddress().toString();
   out.print("<html><head>");
   out.printf("<title>%s NameNode Admininstration</title>\n", hostname);
   out.print("<link rel=\"stylesheet\" type=\"text/css\" " + "href=\"/static/hadoop.css\">\n");
   out.print("</head><body>\n");
   out.printf(
       "<h1><a href=\"/dfshealth.jsp\">%s</a> " + "NameNode Configuration Admin</h1>\n", hostname);
   showOptions(out);
   out.print("</body></html>\n");
 }
Ejemplo n.º 19
0
  private static void writeThreadInfo(PrintWriter pw, Thread thread, State state) {

    pw.printf("Main: Id %d - %s\n", thread.getId(), thread.getName());
    pw.printf("Main:Prioity: %d\n", thread.getPriority());
    pw.printf("Main:Old state:%s\n", state);
    pw.printf("Main:New state:%s\n", thread.getState());
    pw.printf("Main:***********************************\n");
  }
Ejemplo n.º 20
0
  public void getEmployeePrintWriter(
      List<PaySlipModel> emplist, String filePath, String reportType) {
    PaySlip_Earn_Deduction_Model model = new PaySlip_Earn_Deduction_Model();
    try {
      PrintWriter pw = null;
      File file = new File(filePath);
      try {
        pw = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
      } catch (IOException ex) {
        ex.printStackTrace();
      }

      PaySlipModel psm = null;
      Iterator itr = emplist.iterator();
      if ("DBF".equalsIgnoreCase(reportType)) {
        while (itr.hasNext()) {
          psm = (PaySlipModel) itr.next();
          pw.printf(
              "%-7s%-3s%-3s%-35s%-4s%-10s%-14s",
              psm.getEmpno(),
              psm.getRegion(),
              psm.getSectioncode(),
              psm.getEmployeename(),
              psm.getDesignation(),
              psm.getEpf(),
              psm.getBankaccountno());
          pw.println();
        }
      } else {
        while (itr.hasNext()) {
          psm = (PaySlipModel) itr.next();
          pw.printf(
              "%-37s",
              psm.getRegion()
                  + ","
                  + psm.getEpf()
                  + ","
                  + psm.getEmployeename()
                  + ","
                  + psm.getDesignation()
                  + ","
                  + psm.getSectionname()
                  + ","
                  + psm.getBankaccountno()
                  + ","
                  + psm.getPaymentmode()
                  + ","
                  + psm.getPayscale());
          pw.println();
        }
      }

      pw.flush();
      pw.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Ejemplo n.º 21
0
 @Override
 public void writeASCII(PrintWriter out) throws IOException {
   out.printf("nURLS: %d\n", nURLs);
   out.printf("nImages: %d %d\n", nImages, this.imageURLs.size());
   out.printf("nTweets: %d\n", nTweets);
   for (final URL url : this.imageURLs) {
     out.println(url);
   }
 }
Ejemplo n.º 22
0
 public static void main(String[] args) throws Exception {
   n = (new Scanner(new FileReader("frac1.in"))).nextInt();
   out = new PrintWriter(new BufferedWriter(new FileWriter("frac1.out")));
   out.printf("0/1\n");
   f(0, 1, 1, 1);
   out.printf("1/1\n");
   out.close();
   System.exit(0);
 }
Ejemplo n.º 23
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // 한글처리
    // request.setCharacterEncoding("euc-kr");
    response.setContentType("text/html;charset=euc-kr");

    String id = "";
    String pw = "";
    String name = "";
    String vclass = "";
    String phone1 = "";
    String phone2 = "";
    String phone3 = "";

    id = request.getParameter("id");
    pw = request.getParameter("pw");
    name = request.getParameter("name");
    // name = new String(name.getBytes("8859_1"), "euc-kr");
    name = HanConv.toKor(name);

    vclass = request.getParameter("vclass");
    // vclass = new String(vclass.getBytes("8859_1"), "euc-kr");
    vclass = HanConv.toKor(vclass);

    phone1 = request.getParameter("phone1");
    phone2 = request.getParameter("phone2");
    phone3 = request.getParameter("phone3");

    // 파일 저장 로직
    String filename = "filesaved.txt";
    //		String result;
    PrintWriter writer = null;

    try {
      String filePath = getServletContext().getRealPath("/WEB-INF/bbs/" + filename);
      writer = new PrintWriter(filePath);
      writer.printf("아이디: %s\n", id);
      writer.printf("패스워드: %s\n", pw);
      writer.printf("이름: %s\n", name);
      writer.printf("등급: %s\n", vclass);
      writer.printf("전화번호: %s-%s-%s\n", phone1, phone2, phone3);
      //			result = "SUCCESS";
    } catch (IOException ice) {
      //			result = "FAIL";
    } finally {
      try {
        writer.close();
      } catch (Exception e) {
      }
    }
    //		response.sendRedirect("jsp/Day01Practice01/QueryStringResult.jsp?RESULT="
    //				+ result);
    // 파일저장 성공유무를 JSP로 전달

  }
  private void dumpDetails(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/plain");

    PrintWriter out = resp.getWriter();

    out.printf("Method: %s%n", req.getMethod());
    out.printf("Request-URI: %s%n", req.getRequestURI());
    out.printf("Version: %s%n", req.getProtocol());
    out.printf("Request-URL: %s%n", req.getRequestURL());
  }
Ejemplo n.º 25
0
  static void mainToOutput(String[] args, PrintWriter output) throws Exception {
    if (parseArgs(args)) {
      if (!showAuc && !showConfusion && !showScores) {
        showAuc = true;
        showConfusion = true;
      }

      Auc collector = new Auc();
      LogisticModelParameters lmp = LogisticModelParameters.loadFrom(new File(modelFile));

      CsvRecordFactory csv = lmp.getCsvRecordFactory();
      OnlineLogisticRegression lr = lmp.createRegression();
      BufferedReader in = TrainLogistic.open(inputFile);
      String line = in.readLine();
      csv.firstLine(line);
      line = in.readLine();
      if (showScores) {
        output.println("\"target\",\"model-output\",\"log-likelihood\"");
      }
      while (line != null) {
        Vector v = new SequentialAccessSparseVector(lmp.getNumFeatures());
        int target = csv.processLine(line, v);

        double score = lr.classifyScalar(v);
        if (showScores) {
          output.printf(
              Locale.ENGLISH, "%d,%.3f,%.6f%n", target, score, lr.logLikelihood(target, v));
        }
        collector.add(target, score);
        line = in.readLine();
      }

      if (showAuc) {
        output.printf(Locale.ENGLISH, "AUC = %.2f%n", collector.auc());
      }
      if (showConfusion) {
        Matrix m = collector.confusion();
        output.printf(
            Locale.ENGLISH,
            "confusion: [[%.1f, %.1f], [%.1f, %.1f]]%n",
            m.get(0, 0),
            m.get(1, 0),
            m.get(0, 1),
            m.get(1, 1));
        m = collector.entropy();
        output.printf(
            Locale.ENGLISH,
            "entropy: [[%.1f, %.1f], [%.1f, %.1f]]%n",
            m.get(0, 0),
            m.get(1, 0),
            m.get(0, 1),
            m.get(1, 1));
      }
    }
  }
Ejemplo n.º 26
0
 public String toString() {
   StringWriter writer = new StringWriter();
   PrintWriter print = new PrintWriter(writer);
   print.printf("%1$20s: %2$s\n", "uuid", this.uuid);
   print.printf("%1$20s: %2$s\n", "thisHost", this.thisHost);
   print.printf("%1$20s: %2$s\n", "thisUser", this.thisUser);
   print.printf("%1$20s: %2$s\n", "lastActive", this.lastActive);
   print.printf("%1$20s: %2$s\n", "pool", this.pool);
   print.printf("%1$20s: %2$s\n", "otherConfig", this.otherConfig);
   return writer.toString();
 }
Ejemplo n.º 27
0
  private void printForm(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    PrintWriter out = response.getWriter();

    out.printf("<form method=\"get\" action=\"%s\">%n", request.getServletPath());
    out.printf("<input type=\"text\" name=\"newcrawl\" maxlength=\"200\" size=\"100\">");
    out.printf(
        "<p><input type=\"submit\" name=\"addcrawl\" value=\"add new crawl to the database\">");

    out.printf("<h2><a href='/'>Back to Search</a><h2>");
  }
Ejemplo n.º 28
0
  /** @param args */
  public static void main(String[] args) {
    Thread threads[] = new Thread[10];
    Thread.State status[] = new Thread.State[10];

    for (int i = 0; i < 10; i++) {
      threads[i] = new Thread(new Calculator(i));
      if ((i % 2 == 0)) {
        threads[i].setPriority(Thread.MAX_PRIORITY);
      } else {

        threads[i].setPriority(Thread.MIN_PRIORITY);
      }
    }
    FileWriter file = null;
    PrintWriter pw = null;
    try {
      file = new FileWriter("E:\\data\\log.txt");
      pw = new PrintWriter(file);
      for (int i = 0; i < 10; i++) {
        pw.printf("Main:Status of Thread %d : %s\n", i, threads[i].getState());
        status[i] = threads[i].getState();
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    pw.printf("***********************************************\n");

    for (int i = 0; i < 10; i++) {
      threads[i].start();
    }

    boolean finish = false;
    while (!finish) {
      for (int i = 0; i < 10; i++) {
        if (threads[i].getState() != status[i]) {
          writeThreadInfo(pw, threads[i], status[i]);
          status[i] = threads[i].getState();
        }
      }
      finish = true;
      for (int i = 0; i < 10; i++) {

        finish = finish && (threads[i].getState() == State.TERMINATED);
      }
      try {
        pw.close();
        file.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
Ejemplo n.º 29
0
 /**
  * Print the performance counters.
  *
  * @since 2.24
  */
 public void dumpPerformanceCounters(PrintWriter w) throws IOException {
   // locale fixed to English to get ',' for every 3 digits
   int l = classLoadingCount.get();
   int p = classLoadingPrefetchCacheCount.get();
   w.printf(Locale.ENGLISH, "Class loading count=%d\n", l);
   w.printf(Locale.ENGLISH, "Class loading prefetch hit=%s (%d%%)\n", p, p * 100 / l);
   w.printf(Locale.ENGLISH, "Class loading time=%,dms\n", classLoadingTime.get() / (1000 * 1000));
   w.printf(Locale.ENGLISH, "Resource loading count=%d\n", resourceLoadingCount.get());
   w.printf(
       Locale.ENGLISH, "Resource loading time=%,dms\n", resourceLoadingTime.get() / (1000 * 1000));
 }
Ejemplo n.º 30
0
  public synchronized String getSnapshot() {

    HashSet<Object> requestsKeys = new HashSet<Object>();
    HashSet<Object> servicesKeys = new HashSet<Object>();

    for (Object key : m_act_stat.keySet()) {
      if (m_act_stat.get(key).idleInfo == null) {
        requestsKeys.add(key);
      } else {
        servicesKeys.add(key);
      }
    }

    StringWriter buf = new StringWriter();
    PrintWriter printer = new PrintWriter(buf);

    printer.printf("\nREQUESTS\n");
    for (Object key : requestsKeys) {
      printer.println("=========" + key.toString());
      ActivityStatus status = m_act_stat.get(key);
      Stack<PSI> stackPSI = status.ps.getStack();
      printer.print("Stack = ");
      int i = 0;
      for (PSI psi : stackPSI) {
        if (i != 0) {
          repeat(printer, ' ', 8, false);
        }
        printer.println("" + psi.getGroup() + "." + psi.getItem() + "." + psi.getContext());
        i = i + 1;
      }
    }

    printer.printf("\nSERVICES\n");
    for (Object key : servicesKeys) {
      printer.println("=========" + key.toString());
      ActivityStatus status = m_act_stat.get(key);
      printer.println("IdleInfo = " + status.idleInfo);
      Stack<PSI> stackPSI = status.ps.getStack();
      printer.print("Stack = ");
      int i = 0;
      for (PSI psi : stackPSI) {
        if (i != 0) {
          repeat(printer, ' ', 8, false);
        }
        printer.println("" + psi.getGroup() + "." + psi.getItem() + "." + psi.getContext());
        i = i + 1;
      }
    }

    printer.close();
    buf.flush();
    return buf.toString();
  }