Пример #1
1
 /**
  * This is for debug only: print out training matrices in a CSV type format so that the matrices
  * can be examined in a spreadsheet program for debugging purposes.
  */
 private void WriteCSVfile(
     List<String> rowNames, List<String> colNames, float[][] buf, String fileName) {
   p("tagList.size()=" + tagList.size());
   try {
     FileWriter fw = new FileWriter(fileName + ".txt");
     PrintWriter bw = new PrintWriter(new BufferedWriter(fw));
     // write the first title row:
     StringBuffer sb = new StringBuffer(500);
     for (int i = 0, size = colNames.size(); i < size; i++) {
       sb.append("," + colNames.get(i));
     }
     bw.println(sb.toString());
     // loop on remaining rows:
     for (int i = 0, size = buf.length; i < size; i++) {
       sb.delete(0, sb.length());
       sb.append(rowNames.get(i));
       for (int j = 0, size2 = buf[i].length; j < size2; j++) {
         sb.append("," + buf[i][j]);
       }
       bw.println(sb.toString());
     }
     bw.close();
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
 }
Пример #2
0
  /**
   * Writes the XML Declaration and the opening RDF tag to the print Writer. Encoding attribute is
   * specified as the encoding argument.
   *
   * @param out PrintWriter
   * @throws IOException
   */
  protected void writeHeader(OutputStreamWriter out) throws IOException {

    // validate
    if (out != null) {

      // wrapper for output stream writer (enable autoflushing)
      PrintWriter writer = new PrintWriter(out, true);

      // get encoding from the Encoding map
      String encoding = EncodingMap.getJava2IANAMapping(out.getEncoding());

      // only insert encoding if there is a value
      if (encoding != null) {

        // print opening tags <?xml version="1.0" encoding=*encoding*?>
        writer.println("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>");
      } else {

        // print opening tags <?xml version="1.0"?>
        writer.println("<?xml version=\"1.0\"?>");
      }

      // print the Entities
      this.writeXMLEntities(writer);

      // print the opening RDF tag (including namespaces)
      this.writeRDFHeader(writer);
    } else {

      throw new IllegalArgumentException("Cannot write to null Writer.");
    }
  }
Пример #3
0
  // ---------------------------------------------------------------------------
  private void printDependencies(String target, PrintWriter pw, int spacing)
      throws TablesawException {
    Rule tr = findTargetRule(target);
    String[] pre;

    for (int I = 0; I < spacing; I++) pw.print("\t");

    List<String> targetList = new ArrayList<String>();
    if (tr != null) {
      for (String name : tr.getDependNames()) {
        targetList.add(name);
      }

      for (Rule r : tr.getDependRules()) {
        if ((r.getName() != null) && (!r.getName().startsWith(NAMED_RULE_PREFIX))) {
          targetList.add(r.getName());
        } else {
          for (String t : r.getTargets()) {
            targetList.add(t);
          }
        }
      }
    }

    if (!m_printedDependencies.add(target) && (targetList.size() != 0)) {
      pw.println(target + "*");
      return;
    }

    pw.println(target);

    for (String t : targetList) printDependencies(t, pw, spacing + 1);
  }
Пример #4
0
 /**
  * Recursive function to sort array of integers using the Quick Sort Algorithm.
  *
  * @param array Array of integers to sort.
  * @param begin The starting index in <code>array</code> of the range to be sorted.
  * @param end The ending index in <code>array</code> of the range to be sorted.
  */
 void sort(int[] array, int begin, int end) {
   int[] arraycpy = new int[array.length];
   for (int i = 0; i < array.length; i++) arraycpy[i] = array[i];
   if (begin < end) {
     // fibQuestion q = new fibQuestion(out, (new Integer(qIndex)).toString());
     // Remember that Animal wants quotes around the question text
     // q.setQuestionText("\"Which number in the array will be chosen as pivot index?\"");
     // questions.addQuestion(q);
     // out.println("{");
     // questions.animalInsertQuestion(qIndex);
     // out.println("}");
     int pivIndex = partition(array, begin, end);
     // After calling on partition, pivIndex is used to set the answer
     // for the question
     // And, remember that Animal wants quotes around the question answer
     // q.setAnswer("\"" + arraycpy[pivIndex] + "\"");
     // qIndex++;
     sort(array, begin, pivIndex - 1);
     sort(array, pivIndex + 1, end);
   } else {
     out.println("{");
     out.println("highlightArrayCell on \"qarray\" position " + begin);
     out.println("}");
   }
 }
Пример #5
0
  public static void main(String args[]) {

    wmatrix wmatrix = new wmatrix();
    wmatrix.start();
    try {
      PrintWriter profilefout =
          new PrintWriter(
              new BufferedWriter(
                  new FileWriter(
                      "profile_"
                          + Data.kinease
                          + "_"
                          + Data.code
                          + "_"
                          + Data.windows_size
                          + ".csv")));

      profilefout.print("Position=");
      for (int j = 0; j < Data.windows_size; j++) {
        profilefout.print("," + (j - Data.windows_size / 2));
      }
      profilefout.println();

      for (int i = 0; i < 20; i++) {
        for (int j = 0; j < Data.windows_size; j++) {
          profilefout.print("," + wm[i][j]);
        }
        profilefout.println();
      }
      profilefout.close();

    } catch (IOException ex) {

    }
  }
 public void process() {
   for (TypeDeclaration typeDecl : env.getSpecifiedTypeDeclarations()) {
     ExtractInterface annot = typeDecl.getAnnotation(ExtractInterface.class);
     if (annot == null) break;
     for (MethodDeclaration m : typeDecl.getMethods())
       if (m.getModifiers().contains(Modifier.PUBLIC)
           && !(m.getModifiers().contains(Modifier.STATIC))) interfaceMethods.add(m);
     if (interfaceMethods.size() > 0) {
       try {
         PrintWriter writer = env.getFiler().createSourceFile(annot.value());
         writer.println("package " + typeDecl.getPackage().getQualifiedName() + ";");
         writer.println("public interface " + annot.value() + " {");
         for (MethodDeclaration m : interfaceMethods) {
           writer.print("  public ");
           writer.print(m.getReturnType() + " ");
           writer.print(m.getSimpleName() + " (");
           int i = 0;
           for (ParameterDeclaration parm : m.getParameters()) {
             writer.print(parm.getType() + " " + parm.getSimpleName());
             if (++i < m.getParameters().size()) writer.print(", ");
           }
           writer.println(");");
         }
         writer.println("}");
         writer.close();
       } catch (IOException ioe) {
         throw new RuntimeException(ioe);
       }
     }
   }
 }
  public static void reconstructHeaders(Iterable<NativeLibrary> libraries, PrintWriter out) {
    List<MemberRef> orphanMembers = new ArrayList<MemberRef>();
    Map<TypeRef, List<MemberRef>> membersByClass = new HashMap<TypeRef, List<MemberRef>>();
    for (NativeLibrary library : libraries) {
      for (Symbol symbol : library.getSymbols()) {
        MemberRef mr = symbol.getParsedRef();
        if (mr == null) continue;

        TypeRef et = mr.getEnclosingType();
        if (et == null) orphanMembers.add(mr);
        else {
          List<MemberRef> mrs = membersByClass.get(et);
          if (mrs == null) membersByClass.put(et, mrs = new ArrayList<MemberRef>());
          mrs.add(mr);
        }
      }
    }
    for (TypeRef tr : membersByClass.keySet()) out.println("class " + tr + ";");

    for (MemberRef mr : orphanMembers) out.println(mr + ";");

    for (Map.Entry<TypeRef, List<MemberRef>> e : membersByClass.entrySet()) {
      TypeRef tr = e.getKey();
      List<MemberRef> mrs = e.getValue();
      out.println("class " + tr + " \n{");
      for (MemberRef mr : mrs) {
        out.println("\t" + mr + ";");
      }
      out.println("}");
    }
  }
Пример #8
0
  /**
   * Gera uma partícula aleatória de dimensões fixas.
   *
   * <p>Define os valores para size, maxValue, dimensions, lBest e inertia.
   *
   * @param pagesArray array com as páginas do banco de dados
   * @param size quantidade de dimensões da partícula
   */
  public Particle(int[] pagesArray, int size, int inertia, Random r) throws IOException {

    maxValue = pagesArray.length;
    dimensions = new int[size];
    velocity = new int[size];
    lBest = new int[size];
    this.inertia = inertia;
    this.rnd = r;

    for (int i = 0; i < size; i++) {

      dimensions[i] = (int) (rnd.nextFloat() * pagesArray.length);
      lBest[i] = (int) (rnd.nextFloat() * pagesArray.length);
      // System.out.println("dimensions["+i+"] : "+dimensions[i]);
    }

    File f = new File("dimensions");

    FileWriter fw = new FileWriter(f, true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter pw = new PrintWriter(bw);

    pw.println("pagesArray.length " + pagesArray.length);
    for (int i = 0; i < dimensions.length; i++) {
      pw.print(dimensions[i] + " ");
    }
    pw.println();

    pw.close();
    bw.close();
    fw.close();
  }
Пример #9
0
 void run() throws IOException {
   BufferedReader f = new BufferedReader(new FileReader("ttwo.in"));
   PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("ttwo.out")));
   StringTokenizer st;
   int min = 0;
   for (int i = 0; i < 10; i++) {
     st = new StringTokenizer(f.readLine());
     String s = st.nextToken();
     for (int j = 0; j < 10; j++) {
       if (s.charAt(j) == '*') {
         sq[i][j] = 1;
       } else if (s.charAt(j) == '.') {
         sq[i][j] = 0;
       } else if (s.charAt(j) == 'F') {
         fLoc = 10 * i + j;
         sq[i][j] = 0;
       } else {
         cLoc = 10 * i + j;
         sq[i][j] = 0;
       }
     }
   }
   while (fLoc != cLoc) {
     move();
     min++;
     if (min == 160000) {
       out.println(0);
       out.close();
       System.exit(0);
     }
   }
   out.println(min);
   out.close();
   System.exit(0);
 }
Пример #10
0
 public void save(File target) {
   try {
     target.createNewFile(); // Creates a new file, if one doesn't exist already
     PrintWriter writer = new PrintWriter(target);
     // Prints some game info
     writer.println(sideLength_);
     writer.println(currentPlayer_);
     // Printing the state of the board
     for (int y = 0; y < sideLength_; y++) {
       for (int x = 0; x < sideLength_; x++) {
         writer.print(board_[x][y]);
         if (x != sideLength_ - 1) {
           writer.print(valueSeparator_);
         }
       }
       if (y != sideLength_ - 1) // Not yet the last line
       {
         writer.println();
       }
     }
     writer.close();
   } catch (Exception e) {
     System.out.println(e);
   }
 }
Пример #11
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Session Tracking Example";
    HttpSession session = request.getSession(true);
    String heading;

    Integer accessCount = (Integer) session.getAttribute("accessCount");

    if (accessCount == null) {
      accessCount = new Integer(0);
      heading = "Welcome, Newcomer";
    } else {
      heading = "Welcome Back";
      accessCount = new Integer(accessCount.intValue() + 1);
    }

    session.setAttribute("accessCount", accessCount);
    out.println(
        "<BODY BGCOLOR=\"#FDF5E6\">\n"
            + "<H1 ALIGN=\"CENTER\">"
            + heading
            + "</H1>\n"
            + "<H2>Information on Your Session:</H2>\n"
            + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n"
            + "<TR BGCOLOR=\"#FFAD00\">\n"
            + "  <TH>Info Type<TH>Value\n"
            + "<TR>\n"
            + "  <TD>ID\n"
            + "  <TD>"
            + session.getId()
            + "\n"
            + "<TR>\n"
            + "  <TD>Creation Time\n"
            + "  <TD>"
            + new Date(session.getCreationTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Time of Last Access\n"
            + "  <TD>"
            + new Date(session.getLastAccessedTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Number of Previous Accesses\n"
            + "  <TD>"
            + accessCount
            + "\n"
            + "</TR>"
            + "</TABLE>\n");

    // the following two statements show how to retrieve parameters in
    // the request.  The URL format is something like:
    // http://localhost:8080/project2/servlet/ShowSession?myname=Chen%20Li
    String myname = request.getParameter("myname");
    if (myname != null) out.println("Hey " + myname + "<br><br>");

    out.println("</BODY></HTML>");
  }
Пример #12
0
  public void exportMainlineDataToText() throws IOException {

    for (int key : detectors.keySet()) {

      Double[] flow =
          MyUtilities.scaleVector(
              detectors.get(key).getFlowDataArray(),
              (double) detectors.get(key).getNumberOfLanes());
      Double[] speed = detectors.get(key).getSpeedDataArray();
      Double[] density =
          MyUtilities.scaleVector(
              detectors.get(key).getDensityDataArray(),
              (double) detectors.get(key).getNumberOfLanes());

      PrintWriter outFlow = new PrintWriter(new FileWriter(key + "_flw.txt"));
      PrintWriter outSpeed = new PrintWriter(new FileWriter(key + "_spd.txt"));
      PrintWriter outDensity = new PrintWriter(new FileWriter(key + "_dty.txt"));

      for (int i = 0; i < flow.length; i++) {

        outFlow.println(flow[i]);
        outSpeed.println(speed[i]);
        outDensity.println(density[i]);
      }

      outFlow.close();
      outSpeed.close();
      outDensity.close();
    }
  }
Пример #13
0
 public static void main(String[] args) throws IOException {
   Scanner scan = new Scanner(/*System.in*/ new File("ariprog.in"));
   PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("ariprog.out")));
   int length = scan.nextInt();
   int max = scan.nextInt();
   int[] squares = new int[(max) * max * 2 + 1];
   // ArrayList<Integer> squares = new ArrayList<Integer>();
   for (int i = 0; i <= max; i++) {
     for (int j = i; j <= max; j++) {
       squares[i * i + j * j] = 1;
     }
   }
   ArrayList<Integer> starts = new ArrayList<Integer>();
   ArrayList<Integer> diffs = new ArrayList<Integer>();
   boolean has = false;
   for (int diff = 1; diff <= ((max * max * 2 / (length - 1))); diff++) {
     for (int start = 0; start < squares.length - length; start++) {
       if (squares[start] == 1) {
         if (check(diff, start, squares, length)) {
           starts.add(start);
           diffs.add(diff);
           // out.println(squares[start] + " " + diff);
           has = true;
         }
       }
     }
   }
   remove(starts, diffs);
   for (int i = 0; i < starts.size(); i++) {
     /*System.*/ out.println(starts.get(i) + " " + diffs.get(i));
   }
   if (!has) /*System.*/ out.println("NONE");
   out.close();
   System.exit(0);
 }
Пример #14
0
  /**
   * Used to write Resources for a Subject. Literals will by-pass this method and use "Literal"
   * method.
   *
   * @param predicate PredicateNode
   * @param object ObjectNode
   * @param writer PrintWriter
   * @throws GraphException
   */
  protected void writeStatement(
      Graph graph,
      SubjectNode subject,
      PredicateNode predicate,
      ObjectNode object,
      PrintWriter writer)
      throws GraphException {

    // Literals are written differently
    if (object instanceof Literal) {

      this.writeStatement(graph, subject, predicate, (Literal) object, writer);
    } else if (object instanceof BlankNode) {

      // write as:  <predicateURI> *blank node as subject* </predicateURI>
      writer.println("    <" + this.getURI(predicate) + ">");

      // write blank node as a "subject"
      this.writeSubject(graph, (BlankNode) object, writer);

      writer.println("    </" + this.getURI(predicate) + ">");
    } else if (subject instanceof BlankNode) {

      // predicatNode representing RDF Type
      PredicateNode rdfTypeNode = null;

      try {

        rdfTypeNode = graph.getElementFactory().createResource(RDF.TYPE);
      } catch (GraphElementFactoryException factoryException) {

        throw new GraphException("Could not create RDF Type node.", factoryException);
      }

      // do not write the RDF Type element
      if (!rdfTypeNode.equals(predicate)) {

        // write as:  <predicateURI rdf:resource="resourceURI"/>
        writer.println(
            "    <"
                + this.getURI(predicate)
                + " "
                + RDF_PREFIX
                + ":resource=\""
                + this.getNodeString(object)
                + "\"/>");
      }
    } else {

      // write as:  <predicateURI rdf:resource="resourceURI"/>
      writer.println(
          "    <"
              + this.getURI(predicate)
              + " "
              + RDF_PREFIX
              + ":resource=\""
              + this.getNodeString(object)
              + "\"/>");
    }
  }
Пример #15
0
  // Write <Cluster>.ini file
  // Given Hashtable mapping cluster name to Vector of plugin names
  // <Cluster>.ini File format:
  // [ Cluster ]
  // uic = <Agentname>
  // cloned = false
  // [ Plugins ]
  // plugin = <pluginname>
  // ...
  //
  private void dumpClusterInfo(Hashtable all_clusters, String path) throws IOException {
    // Dump hashtable of clusters
    for (Enumeration e = all_clusters.keys(); e.hasMoreElements(); ) {
      String cluster_name = (String) e.nextElement();
      PrintWriter cluster_file;

      try {
        if (path != null) {
          cluster_file = createPrintWriter(path + File.separator + cluster_name + ".ini");
        } else {
          cluster_file = createPrintWriter(cluster_name + ".ini");
        }

        cluster_file.println("[ Cluster ]");
        cluster_file.println("uic = " + cluster_name);
        cluster_file.println("cloned = false\n");
        cluster_file.println("[ Plugins ]");
        Vector plugins = (Vector) (all_clusters.get(cluster_name));
        for (Enumeration p = plugins.elements(); p.hasMoreElements(); ) {
          String plugin = (String) (p.nextElement());
          cluster_file.println("plugin = " + plugin);
        }
        cluster_file.close();
      } catch (IOException exc) {
        System.out.println("IOException:  " + exc);
        System.exit(-1);
      }
    }
  }
Пример #16
0
  private boolean handleMsg(String str) {
    if (userId <= 0 || !KotoServer.loggedin.containsKey(userId)) {
      out.println("ERROR:NotLoggedIn");
      return false;
    }
    String[] data = str.split(":", 2);
    if (!(data[0].length() > 0)) {
      out.println("ERROR:BadUser");
      System.out.println("Unable to send message, target user does not exist");
      return true;
    }
    int targetId;
    try {
      targetId = Integer.parseInt(data[0]);
    } catch (NumberFormatException e) {
      out.println("ERROR:BadUser");
      System.out.println("Unable to send message, target user does not exist");
      return true;
    }

    if (KotoServer.loggedin.containsKey(targetId)) {
      KotoServer.sendMsg(targetId, "MSG:" + userId + ":" + data[1]);
      System.out.println("sent message from user " + userId + " to " + targetId);
    } else if (KotoServer.users.containsKey(targetId)) {
      KotoServer.users.get(targetId).addMessage(str);
      System.out.println(
          "saved message from user" + userId + " to " + targetId + " for further deliver");
    } else {
      out.println("ERROR:BadUser");
      System.out.println("Unable to send message, target user does not exist");
    }
    return true;
  }
Пример #17
0
 /**
  * Prints an entire subpopulation in a form readable by humans but also parseable by the computer
  * using readSubpopulation(EvolutionState, LineNumberReader).
  */
 public void printSubpopulation(final EvolutionState state, final PrintWriter writer) {
   writer.println(NUM_INDIVIDUALS_PREAMBLE + Code.encode(individuals.length));
   for (int i = 0; i < individuals.length; i++) {
     writer.println(INDIVIDUAL_INDEX_PREAMBLE + Code.encode(i));
     individuals[i].printIndividual(state, writer);
   }
 }
Пример #18
0
 //
 // f0 -> "switch"
 // f1 -> "("
 // f2 -> Expression()
 // f3 -> ")"
 // f4 -> "{"
 // f5 -> ( SwitchLabel() ( BlockStatement() )* )*
 // f6 -> "}"
 //
 public void visit(SwitchStatement n) {
   out.print(n.f0 + " " + n.f1);
   n.f2.accept(this);
   out.println(n.f3);
   out.println(spc.spc + n.f4);
   spc.updateSpc(+1);
   for (Enumeration e = n.f5.elements(); e.hasMoreElements(); ) {
     NodeSequence seq = (NodeSequence) e.nextElement();
     out.print(spc.spc);
     seq.elementAt(0).accept(this);
     spc.updateSpc(+1);
     if (((NodeListOptional) seq.elementAt(1)).present()) {
       if (((NodeListOptional) seq.elementAt(1)).size() == 1) out.print(" ");
       else {
         out.println();
         out.print(spc.spc);
       }
       visit((NodeListOptional) seq.elementAt(1), "\n" + spc.spc);
     }
     out.println();
     spc.updateSpc(-1);
   }
   spc.updateSpc(-1);
   out.println(spc.spc + n.f6);
 }
Пример #19
0
 public void totalExport() {
   File expf = new File("export");
   if (expf.exists()) rmrf(expf);
   expf.mkdirs();
   for (int sto = 0; sto < storeLocs.size(); sto++) {
     try {
       String sl =
           storeLocs.get(sto).getAbsolutePath().replaceAll("/", "-").replaceAll("\\\\", "-");
       File estore = new File(expf, sl);
       estore.mkdir();
       File log = new File(estore, LIBRARY_NAME);
       PrintWriter pw = new PrintWriter(log);
       for (int i = 0; i < store.getRowCount(); i++)
         if (store.curStore(i) == sto) {
           File enc = store.locate(i);
           File dec = sec.prepareMainFile(enc, estore, false);
           pw.println(dec.getName());
           pw.println(store.getValueAt(i, Storage.COL_DATE));
           pw.println(store.getValueAt(i, Storage.COL_TAGS));
           synchronized (jobs) {
             jobs.addLast(expJob(enc, dec));
           }
         }
       pw.close();
     } catch (IOException exc) {
       exc.printStackTrace();
       JOptionPane.showMessageDialog(frm, "Exporting Failed");
       return;
     }
   }
   JOptionPane.showMessageDialog(frm, "Exporting to:\n   " + expf.getAbsolutePath());
 }
Пример #20
0
  //
  // f0 -> "try"
  // f1 -> Block()
  // f2 -> ( "catch" "(" FormalParameter() ")" Block() )*
  // f3 -> [ "finally" Block() ]
  //
  public void visit(TryStatement n) {
    out.println(n.f0);
    out.print(spc.spc);
    n.f1.accept(this);
    for (Enumeration e = n.f2.elements(); e.hasMoreElements(); ) {
      NodeSequence seq = (NodeSequence) e.nextElement();
      out.println();
      out.print(spc.spc);
      seq.elementAt(0).accept(this);
      out.print(" ");
      seq.elementAt(1).accept(this);
      seq.elementAt(2).accept(this);
      seq.elementAt(3).accept(this);
      out.println();
      out.print(spc.spc);
      seq.elementAt(4).accept(this);
    }

    if (n.f3.present()) {
      NodeSequence seq = (NodeSequence) n.f3.node;
      out.println();
      seq.elementAt(0).accept(this);
      out.println();
      out.print(spc.spc);
      seq.elementAt(1).accept(this);
    }
  }
  private void validateDTD() throws InvalidWorkflowDescriptorException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);

    StringWriter sw = new StringWriter();
    PrintWriter writer = new PrintWriter(sw);
    writer.println(XML_HEADER);
    writer.println(DOCTYPE_DECL);
    writeXML(writer, 0);

    WorkflowLoader.AllExceptionsErrorHandler errorHandler =
        new WorkflowLoader.AllExceptionsErrorHandler();

    try {
      DocumentBuilder db = dbf.newDocumentBuilder();
      db.setEntityResolver(new DTDEntityResolver());

      db.setErrorHandler(errorHandler);
      db.parse(new InputSource(new StringReader(sw.toString())));

      if (errorHandler.getExceptions().size() > 0) {
        throw new InvalidWorkflowDescriptorException(errorHandler.getExceptions().toString());
      }
    } catch (InvalidWorkflowDescriptorException e) {
      throw e;
    } catch (Exception e) {
      throw new InvalidWorkflowDescriptorException(e.toString());
    }
  }
  /**
   * GML (Graph Modeling Language) is a text file format supporting network data with a very easy
   * syntax. It is used by Graphlet, Pajek, yEd, LEDA and NetworkX.
   */
  public void exportAsGML(File gmlFile, List<SemanticPath> paths) {
    gmlFile.getParentFile().mkdirs();

    try (PrintWriter writer = new PrintWriter(Files.newWriter(gmlFile, Charsets.UTF_8)); ) {

      writer.println("graph\n[");
      // write vertex
      for (SemanticPath path : paths) {
        for (int i = 0; i < path.length(); i++) {
          writer.println("\tnode\n\t[");
          writer.println("\t\tid " + path.id(i));
          writer.println("\t\tlabel \"" + path.name(i) + "\"");
          writer.println("\t]");
        }
      }

      // write edge
      for (SemanticPath path : paths) {
        for (int i = 0; i < path.length() - 1; i++) {
          writer.println("\tedge\n\t[");
          writer.println("\t\tsource " + path.id(i + 1));
          writer.println("\t\ttarget " + path.id(i));
          writer.println("\t]");
        }
      }
      writer.println(']');
      writer.flush();
    } catch (IOException e) {
      LOG.error("Export to GML file error!", e);
    }
  }
Пример #23
0
 public static void addToPlaylist(File[] filesnames) throws Exception {
   if (logger.isDebugEnabled()) logger.debug("Add to playlist (with parameters - filenames[]).");
   File f = new File(Lecteur.CURRENTPLAYLIST.NAME);
   File Fe =
       new File(
           Lecteur.CURRENTPLAYLIST.NAME.substring(0, Lecteur.CURRENTPLAYLIST.NAME.length() - 19)
               + "wssederdferdtdfdgetrdfdte.pl");
   PrintWriter br = new PrintWriter(new BufferedWriter(new FileWriter(Fe)));
   BufferedReader br1 = new BufferedReader(new FileReader(f));
   String st = null;
   while ((st = br1.readLine()) != null) {
     br.println(st);
   }
   for (int i = 0; i < filesnames.length - 1; i++) {
     br.println(filesnames[i].toString());
   }
   br.print(filesnames[filesnames.length - 1].toString());
   br.close();
   br1.close();
   new File(Lecteur.CURRENTPLAYLIST.NAME).delete();
   (new File(
           Lecteur.CURRENTPLAYLIST.NAME.substring(0, Lecteur.CURRENTPLAYLIST.NAME.length() - 19)
               + "wssederdferdtdfdgetrdfdte.pl"))
       .renameTo(new File(Lecteur.CURRENTPLAYLIST.NAME));
 }
Пример #24
0
 public static void main(String... orange) throws IOException {
   Scanner scan = new Scanner(new File("barn1.in"));
   PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("barn1.out")));
   int bars = scan.nextInt();
   int total = scan.nextInt();
   int have = scan.nextInt();
   ArrayList<Integer> values = new ArrayList<Integer>();
   ArrayList<Integer> locations = new ArrayList<Integer>();
   for (int i = 0; i < have; i++) {
     values.add(scan.nextInt());
   }
   Collections.sort(values);
   int first = values.get(0);
   for (int i = 1; i < have; i++) {
     int current = values.get(i);
     locations.add(current - first);
     first = current;
   }
   if (bars >= have) {
     out.println(have);
   } else {
     for (int i = 0; i < bars - 1; i++) {
       locations.remove(Collections.max(locations));
     }
     int sum = 0;
     for (int i = 0; i < locations.size(); i++) sum += locations.get(i);
     sum += bars;
     out.println(sum);
   }
   out.close();
   System.exit(0);
 }
Пример #25
0
  public static void main(String args[]) throws Exception {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */

    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    SuperStack stack = new SuperStack();
    PrintWriter out = new PrintWriter(System.out, true);
    for (int i = 0; i < n; i++) {
      String s = in.next();
      if (s.equals("push")) {
        int value = in.nextInt();
        out.println(stack.push(value));
      } else if (s.equals("pop")) {
        int res = stack.pop();
        if (stack.size == 0) {
          out.println("EMPTY");
        } else {
          out.println(res);
        }
      } else if (s.equals("inc")) {
        int x = in.nextInt();
        int d = in.nextInt();
        out.println(stack.inc(x, d));
      }
    }
    out.close();
  }
Пример #26
0
  private void writeLogEntry(PrintWriter out, LogEntry logEntry) {
    if (logEntry.getEntriesCount() == 0) {
      return;
    }

    String message = logEntry.getMessage().replace(QUOTE_CHARACTER, QUOTE_SPECIAL_CHARACTER);
    message =
        message.replace(ANGLE_OPENING_BRACKET_CHARACTER, ANGLE_OPENING_BRACKET_SPECIAL_CHARACTER);
    message =
        message.replace(ANGLE_CLOSING_BRACKET_CHARACTER, ANGLE_CLOSING_BRACKET_SPECIAL_CHARACTER);

    out.println(
        MessageFormat.format(
            LOGENTRY_START_NODE,
            new String[] {message, Integer.toString(logEntry.getRevision()), logEntry.getDate()}));

    List<PathEntry> pathEntries = logEntry.getPathEntries();
    for (PathEntry pathEntry : pathEntries) {
      out.println(
          MessageFormat.format(
              PATH_NODE, new String[] {pathEntry.getAction(), pathEntry.getPath()}));
    }

    out.println(LOGENTRY_END_NODE);
  }
Пример #27
0
  // Saves the user info to a file
  public void saveUserInfo(String path) throws IOException {
    // Declare and initialize file object
    File file = new File(path + "\\Personal.txt");

    // Test if the file exists
    if (file.exists()) {
    } else file.createNewFile();

    // Declare and initialize a writer object
    PrintWriter write = new PrintWriter(new FileWriter(file, false));

    // Write information to file
    write.println(first);
    write.println(last);
    write.println(gender);
    write.println(birthDate);
    write.println(address);
    write.println(phoneNumber);
    write.println(province);
    write.println(city);
    write.println(postal);
    write.println(sin);

    write.close();
  } // End of saveUserInfo method
Пример #28
0
  // Generate files for given node
  // Given Hashtable mapping node_name to Vector of cluster names
  // <Node>.ini File format:
  // [ Clusters ]
  // cluster = <clustername>
  // ...
  private void dumpNodeInfo(Hashtable all_nodes, String path) throws IOException {
    PrintWriter node_file;
    // Iterate over hashtable of nodes and write <Node>.ini file for each
    for (Enumeration e = all_nodes.keys(); e.hasMoreElements(); ) {
      String node_name = (String) (e.nextElement());

      try {
        if (path != null) {
          node_file = createPrintWriter(path + File.separator + node_name + ".ini");
        } else {
          node_file = createPrintWriter(node_name + ".ini");
        }
        node_file.println("[ Clusters ]");
        Vector clusters = (Vector) all_nodes.get(node_name);
        for (Enumeration c = clusters.elements(); c.hasMoreElements(); ) {
          String cluster_name = (String) (c.nextElement());
          node_file.println("cluster = " + cluster_name);
        }
        node_file.close();
      } catch (IOException exc) {
        System.out.println("IOException:  " + exc);
        System.exit(-1);
      }
    }
  }
Пример #29
0
  /**
   * This is for book production only: print out training matrices in a Latex type format so that
   * the matrices can be inserted into my manuscript:
   *
   * <p>\begin{table}[htdp] \caption{Runtimes by Method} \centering
   *
   * <p>\begin{tabular}{|l|l|l|} \hline \textbf{Class.method name}&\textbf{Percent of total
   * runtime}&\textbf{Percent in this method}\\ \hline Chess.main&97.7&0.0\\
   * GameSearch.playGame&96.5&0.0\\
   *
   * <p>Chess.calcPieceMoves&1.7&0.8\\ \hline \end{tabular}
   *
   * <p>\label{tab:runtimes_by_method} \end{table}
   */
  private void WriteLatexFile(
      List<String> rowNames, List<String> colNames, float[][] buf, String fileName) {
    p("tagList.size()=" + tagList.size());
    int SKIP = 6;
    try {
      FileWriter fw = new FileWriter(fileName + ".latex");
      PrintWriter bw = new PrintWriter(new BufferedWriter(fw));
      int size = colNames.size() - SKIP;
      bw.print("\\begin{table*}[htdp]\n\\caption{ADD CAPTION}\\centering\\begin{tabular}{|");
      for (int i = 0; i < size + 1; i++) bw.print("l|");
      bw.println("}\n\\hline");
      bw.print(" &");
      for (int i = 0; i < size; i++) {
        bw.print("\\emph{" + colNames.get(i) + "}");
        if (i < (size - 1)) bw.print("&");
      }
      bw.println("\\\\\n\\hline");

      // bw.printf(format, args)
      // loop on remaining rows:
      for (int i = 0, size3 = buf.length - SKIP; i < size3; i++) {
        bw.print(rowNames.get(i) + "&");
        for (int j = 0, size2 = buf[i].length - SKIP; j < size2; j++) {
          bw.printf("%.2f", buf[i][j]);
          if (j < (size2 - 1)) bw.print("&");
        }
        bw.println("\\\\");
      }
      bw.println("\\hline\n\\end{tabular}\n\\label{tab:CHANGE_THIS_LABEL}\n\\end{table*}");
      bw.close();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
Пример #30
0
 public void print(PrintWriter out) {
   int x, y, z;
   for (z = size - 1; z >= 0; z--) {
     // print borders
     for (y = size - 1; y >= 0; y--) {
       out.print("    +");
       for (x = 0; x < size; x++) {
         out.print("---+");
       }
       out.println();
       // numbers
       out.format("%2d: |", y);
       // x's and o's
       for (x = 0; x < size; x++) {
         out.format(" %s |", isEmpty(x, y, z) ? " " : grid[x][y][z]);
       }
       out.println();
     }
     // bottom border
     out.print("    +");
     for (x = 0; x < size; x++) {
       out.print("---+");
     }
     out.println();
     // numbers on bottom
     out.print("     ");
     for (x = 0; x < size; x++) {
       out.format("%2d  ", x);
     }
     out.println();
   }
 }