Beispiel #1
0
 public TestFile writelns(Iterable<String> lines) {
   Formatter formatter = new Formatter();
   for (String line : lines) {
     formatter.format("%s%n", line);
   }
   return write(formatter);
 }
  private boolean filterTinv(
      Grib2Record gr, FeatureCollectionConfig.GribIntvFilter intvFilter, Formatter f) {
    int[] intv = tables.getForecastTimeIntervalOffset(gr);
    if (intv == null) return false;
    int haveLength = intv[1] - intv[0];

    // HACK
    if (haveLength == 0 && intvFilter.isZeroExcluded()) { // discard 0,0
      if ((intv[0] == 0) && (intv[1] == 0)) {
        f.format(" FILTER INTV [0, 0] %s%n", gr);
        return true;
      }
      return false;

    } else if (intvFilter.hasMap()) {
      int discipline = gr.getIs().getDiscipline();
      int category = gr.getPDS().getParameterCategory();
      int number = gr.getPDS().getParameterNumber();
      int id = (discipline << 16) + (category << 8) + number;
      Integer needLength = intvFilter.getLengthById(id);

      if (needLength != null && needLength != haveLength) {
        f.format(" FILTER INTV [%d != %d] %s%n", haveLength, needLength, gr);
        return true;
      }
    }
    return false;
  }
Beispiel #3
0
  private void showDeclaration(BeanTableSorted from, boolean isNcml) {
    Variable v = getCurrentVariable(from);
    if (v == null) return;
    infoTA.clear();
    if (isNcml) {
      Formatter out = new Formatter();
      try {
        NCdumpW.writeNcMLVariable(v, out);
      } catch (IOException e) {
        e.printStackTrace();
      }
      infoTA.appendLine(out.toString());

    } else {
      infoTA.appendLine(v.toString());
    }

    if (Debug.isSet("Xdeveloper")) {
      infoTA.appendLine("\n");
      infoTA.appendLine("FULL NAME = " + v.getFullName());
      infoTA.appendLine("\n");
      infoTA.appendLine(v.toStringDebug());
    }
    infoTA.gotoTop();
    infoWindow.setTitle("Variable Info");
    infoWindow.show();
  }
Beispiel #4
0
 private void setExecutablePermissions(File gradleHome) {
   if (isWindows()) {
     return;
   }
   File gradleCommand = new File(gradleHome, "bin/gradle");
   String errorMessage = null;
   try {
     ProcessBuilder pb = new ProcessBuilder("chmod", "755", gradleCommand.getCanonicalPath());
     Process p = pb.start();
     if (p.waitFor() == 0) {
       System.out.println("Set executable permissions for: " + gradleCommand.getAbsolutePath());
     } else {
       BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
       Formatter stdout = new Formatter();
       String line;
       while ((line = is.readLine()) != null) {
         stdout.format("%s%n", line);
       }
       errorMessage = stdout.toString();
     }
   } catch (IOException e) {
     errorMessage = e.getMessage();
   } catch (InterruptedException e) {
     errorMessage = e.getMessage();
   }
   if (errorMessage != null) {
     System.out.println(
         "Could not set executable permissions for: " + gradleCommand.getAbsolutePath());
     System.out.println("Please do this manually if you want to use the Gradle UI.");
   }
 }
 @Override
 protected void printDocumentResults(Results results) {
   printSeparator();
   Formatter formatter = new Formatter(System.out, Locale.US);
   formatter.format(" |   Total: |");
   results.printResults(formatter);
 }
  /**
   * Returns a string describing a method declaration. It contains the access flags (public,
   * private, static, etc), the return type, the method name, and the types of each of its
   * arguments.
   */
  public static String get_method_declaration(Method m) {

    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);

    f.format("%s %s %s (", get_access_flags(m), m.getReturnType(), m.getName());
    for (Type at : m.getArgumentTypes()) {
      f.format("%s, ", at);
    }
    f.format(")");
    return (sb.toString().replace(", )", ")"));
  }
  @Override
  public void getDetailInfo(Formatter f) {
    super.getDetailInfo(f);

    if (runMatcher != null) f.format("  runMatcher=%s%n", runMatcher);
    /*  if (forecastMatcher != null)
      f.format("  forecastMatcher=%s%n", forecastMatcher);
    if (offsetMatcher != null)
      f.format("  offsetMatcher=%s%n", offsetMatcher); */
  }
  private String listFiles(final File cache, List<File> toDelete) throws Exception {
    boolean stopServices = false;
    if (toDelete == null) {
      toDelete = new ArrayList<File>();
    } else {
      stopServices = true;
    }
    int count = 0;
    Formatter f = new Formatter();

    f.format(" - Cache:%n    * %s%n", cache.getCanonicalPath());
    f.format(" - Commands:%n");
    for (CommandData cdata : getCommands(new File(cache, COMMANDS))) {
      f.format("    * %s \t0 handle for \"%s\"%n", cdata.bin, cdata.name);
      toDelete.add(new File(cdata.bin));
      count++;
    }
    f.format(" - Services:%n");
    for (ServiceData sdata : getServices(new File(cache, SERVICE))) {
      if (sdata != null) {
        f.format("    * %s \t0 service directory for \"%s\"%n", sdata.sdir, sdata.name);
        toDelete.add(new File(sdata.sdir));
        File initd = platform.getInitd(sdata);
        if (initd != null && initd.exists()) {
          f.format("    * %s \t0 init.d file for \"%s\"%n", initd.getCanonicalPath(), sdata.name);
          toDelete.add(initd);
        }
        if (stopServices) {
          Service s = getService(sdata);
          try {
            s.stop();
          } catch (Exception e) {
          }
        }
        count++;
      }
    }
    f.format("%n");

    String result = (count > 0) ? f.toString() : null;
    f.close();
    return result;
  }
  private String listSupportFiles(List<File> toDelete) throws Exception {
    Formatter f = new Formatter();
    try {
      if (toDelete == null) {
        toDelete = new ArrayList<File>();
      }
      int precount = toDelete.size();
      File confFile = IO.getFile(platform.getConfigFile()).getCanonicalFile();
      if (confFile.exists()) {
        f.format("    * %s \t0 Config file%n", confFile);
        toDelete.add(confFile);
      }

      String result = (toDelete.size() > precount) ? f.toString() : null;
      return result;
    } finally {
      f.close();
    }
  }
Beispiel #10
0
  public SummaryTab(VMPanel vmPanel) {
    super(vmPanel, getTabName());

    setLayout(new BorderLayout());

    info = new HTMLPane();
    setAccessibleName(info, getTabName());
    add(new JScrollPane(info));

    headerDateTimeFormat =
        Formatter.getDateTimeFormat(Messages.SUMMARY_TAB_HEADER_DATE_TIME_FORMAT);
  }
  private boolean createIndex(File indexFile, CollectionManager.Force ff, Formatter f)
      throws IOException {
    long start = System.currentTimeMillis();

    ArrayList<String> filenames = new ArrayList<String>();
    List<Group> groups = makeAggregatedGroups(filenames, ff, f);
    createIndex(indexFile, groups, filenames, f);

    long took = System.currentTimeMillis() - start;
    f.format("That took %d msecs%n", took);
    return true;
  }
  public String toString() {

    StringBuilder out = new StringBuilder();
    Formatter formatter = new Formatter(out, Locale.US);

    for (int topic = 0; topic < numTopics; topic++) {

      formatter.format("Topic %d", topic);

      for (TopicScores scores : diagnostics) {
        formatter.format("\t%s=%.4f", scores.name, scores.scores[topic]);
      }
      formatter.format("\n");

      for (int position = 0; position < topicTopWords[topic].length; position++) {
        if (topicTopWords[topic][position] == null) {
          break;
        }

        formatter.format("  %s", topicTopWords[topic][position]);
        for (TopicScores scores : diagnostics) {
          if (scores.wordScoresDefined) {
            formatter.format("\t%s=%.4f", scores.name, scores.topicWordScores[topic][position]);
          }
        }
        out.append("\n");
      }
    }

    return out.toString();
  }
  /**
   * Constructor.
   *
   * @param ncfile the netccdf file
   * @param typedDataVariables list of data variables; all record variables will be added to this
   *     list, except . You can remove extra
   * @param obsTimeVName observation time variable name (required)
   * @param nomTimeVName nominal time variable name (may be null)
   * @throws IllegalArgumentException if ncfile has no unlimited dimension and recDimName is null.
   */
  public RecordDatasetHelper(
      NetcdfDataset ncfile,
      String obsTimeVName,
      String nomTimeVName,
      List<VariableSimpleIF> typedDataVariables,
      String recDimName,
      Formatter errBuffer) {
    this.ncfile = ncfile;
    this.obsTimeVName = obsTimeVName;
    this.nomTimeVName = nomTimeVName;
    this.errs = errBuffer;

    // check if we already have a structure vs if we have to add it.

    if (this.ncfile.hasUnlimitedDimension()) {
      this.ncfile.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE);
      this.recordVar = (StructureDS) this.ncfile.getRootGroup().findVariable("record");
      this.obsDim = ncfile.getUnlimitedDimension();

    } else {
      if (recDimName == null)
        throw new IllegalArgumentException(
            "File <"
                + this.ncfile.getLocation()
                + "> has no unlimited dimension, specify psuedo record dimension with observationDimension global attribute.");
      this.obsDim = this.ncfile.getRootGroup().findDimension(recDimName);
      this.recordVar = new StructurePseudoDS(this.ncfile, null, "record", null, obsDim);
    }

    // create member variables
    List<Variable> recordMembers = ncfile.getVariables();
    for (Variable v : recordMembers) {
      if (v == recordVar) continue;
      if (v.isScalar()) continue;
      if (v.getDimension(0) == this.obsDim) typedDataVariables.add(v);
    }

    // need the time units
    Variable timeVar = ncfile.findVariable(obsTimeVName);
    String timeUnitString =
        ncfile.findAttValueIgnoreCase(timeVar, CDM.UNITS, "seconds since 1970-01-01");
    try {
      timeUnit = new DateUnit(timeUnitString);
    } catch (Exception e) {
      if (null != errs) errs.format("Error on string = %s == %s%n", timeUnitString, e.getMessage());
      try {
        timeUnit = new DateUnit("seconds since 1970-01-01");
      } catch (Exception e1) {
        // cant happen
      }
    }
  }
  /**
   * Prints a usage message to the given stream.
   *
   * @param out The output stream to write to.
   */
  public void printUsage(Appendable out) {
    Formatter formatter = new Formatter(out);
    Set<CommandLineOption> orderedOptions = new TreeSet<CommandLineOption>(new OptionComparator());
    orderedOptions.addAll(optionsByString.values());
    Map<String, String> lines = new LinkedHashMap<String, String>();
    for (CommandLineOption option : orderedOptions) {
      Set<String> orderedOptionStrings = new TreeSet<String>(new OptionStringComparator());
      orderedOptionStrings.addAll(option.getOptions());
      List<String> prefixedStrings = new ArrayList<String>();
      for (String optionString : orderedOptionStrings) {
        if (optionString.length() == 1) {
          prefixedStrings.add("-" + optionString);
        } else {
          prefixedStrings.add("--" + optionString);
        }
      }

      String key = join(prefixedStrings, ", ");
      String value = option.getDescription();
      if (value == null || value.length() == 0) {
        value = "";
      }

      lines.put(key, value);
    }
    int max = 0;
    for (String optionStr : lines.keySet()) {
      max = Math.max(max, optionStr.length());
    }
    for (Map.Entry<String, String> entry : lines.entrySet()) {
      if (entry.getValue().length() == 0) {
        formatter.format("%s%n", entry.getKey());
      } else {
        formatter.format("%-" + max + "s  %s%n", entry.getKey(), entry.getValue());
      }
    }
    formatter.flush();
  }
Beispiel #15
0
  private void compareDataset(CompareDialog.Data data) {
    if (data.name == null) return;

    NetcdfFile compareFile = null;
    try {
      compareFile = NetcdfDataset.openFile(data.name, null);

      Formatter f = new Formatter();
      CompareNetcdf2 cn = new CompareNetcdf2(f, data.showCompare, data.showDetails, data.readData);
      if (data.howMuch == CompareDialog.HowMuch.All) cn.compare(ds, compareFile);
      else {
        NestedTable nested = nestedTableList.get(0);
        Variable org = getCurrentVariable(nested.table);
        if (org == null) return;
        Variable ov = compareFile.findVariable(org.getFullNameEscaped());
        if (ov != null) cn.compareVariable(org, ov);
      }

      infoTA.setText(f.toString());
      infoTA.gotoTop();
      infoWindow.setTitle("Compare");
      infoWindow.show();

    } catch (Throwable ioe) {
      ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
      ioe.printStackTrace(new PrintStream(bos));
      infoTA.setText(bos.toString());
      infoTA.gotoTop();
      infoWindow.show();

    } finally {
      if (compareFile != null)
        try {
          compareFile.close();
        } catch (Exception eek) {
        }
    }
  }
  // single file
  private Grib2CollectionBuilder(File file, Formatter f) throws IOException {
    try {
      // String spec = StringUtil2.substitute(file.getPath(), "\\", "/");
      CollectionManager dcm = new DatasetCollectionSingleFile(file);
      this.collections.add(dcm);
      this.gc = new Grib2Collection(file.getName(), new File(dcm.getRoot()));

    } catch (Exception e) {
      ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
      e.printStackTrace(new PrintStream(bos));
      f.format("%s", bos.toString());
      throw new IOException(e);
    }
  }
  private void dumpDDS() {
    List<MessageBean> beans = messageTable.getBeans();
    HashMap<Integer, Message> map = new HashMap<Integer, Message>(2 * beans.size());

    for (MessageBean mb : beans) {
      map.put(mb.m.hashCode(), mb.m);
    }

    if (fileChooser == null)
      fileChooser = new FileManager(null, null, null, (PreferencesExt) prefs.node("FileManager"));

    String defloc = (raf.getLocation() == null) ? "." : raf.getLocation();
    int pos = defloc.lastIndexOf(".");
    if (pos > 0) defloc = defloc.substring(0, pos);
    String filename = fileChooser.chooseFilenameToSave(defloc + ".txt");
    if (filename == null) return;

    try {
      File file = new File(filename);
      FileOutputStream fos = new FileOutputStream(file);

      int count = 0;
      for (Message m : map.values()) {
        Formatter f = new Formatter(fos);
        m.dump(f);
        f.flush();
        count++;
      }
      fos.close();
      JOptionPane.showMessageDialog(
          BufrMessageViewer.this, count + " successfully written to " + filename);

    } catch (IOException e1) {
      JOptionPane.showMessageDialog(BufrMessageViewer.this, e1.getMessage());
      e1.printStackTrace();
    }
  }
Beispiel #18
0
  public void saveFile() {
    try {
      cardFormatter = new Formatter(currentFile);
    } catch (Exception e) {
      System.out.print("That File doesn't exist");
    }
    cardFormatter.format("%s%n", currentPlayer.getName());
    cardFormatter.format("%d%n", currentPlayer.getTotalCardsOwned());
    cardFormatter.format("%d%n", currentPlayer.getNumberOfCardsInDeck());
    cardFormatter.format("%d%n", currentPlayer.getWins());
    cardFormatter.format("%d%n", currentPlayer.getLosses());
    cardFormatter.format("%d%n", currentPlayer.getMoney());

    Card[] deck = currentPlayer.getDeck();

    for (int count = 0; count < deck.length; count++) {
      cardFormatter.format("%d%n", deck[count].getCardIndex());
      cardFormatter.format("%b%n", deck[count].getInDeck());
    }
    cardFormatter.close();
  }
  public void setLocationInfo(String latVName, String lonVName, String zcoordVName) {
    this.latVName = latVName;
    this.lonVName = lonVName;
    this.zcoordVName = zcoordVName;

    // check for meter conversion
    if (zcoordVName != null) {
      Variable v = ncfile.findVariable(zcoordVName);
      zcoordUnits = ncfile.findAttValueIgnoreCase(v, CDM.UNITS, null);
      if (zcoordUnits != null)
        try {
          altScaleFactor = getMetersConversionFactor(zcoordUnits);
        } catch (Exception e) {
          if (errs != null) errs.format("%s", e.getMessage());
        }
    }
  }
  // single file
  private Grib2CollectionBuilder(MFile file, FeatureCollectionConfig.GribConfig config, Formatter f)
      throws IOException {
    this.isSingleFile = true;
    try {
      // String spec = StringUtil2.substitute(file.getPath(), "\\", "/");
      CollectionManager dcm = new CollectionManagerSingleFile(file);
      if (config != null) dcm.putAuxInfo(FeatureCollectionConfig.AUX_GRIB_CONFIG, config);
      this.collections.add(dcm);
      this.gc = new Grib2Collection(file.getName(), new File(dcm.getRoot()), config);

    } catch (Exception e) {
      ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
      e.printStackTrace(new PrintStream(bos));
      f.format("%s", bos.toString());
      throw new IOException(e);
    }
  }
 public void closeFile() {
   System.out.println("Closing file ... ");
   f.close();
 }
 private static void test(String fs) {
   Formatter f = new Formatter(new StringBuilder(), Locale.US);
   f.format(fs, "fail");
   ck(fs, "fail", f.toString());
 }
 public void addRecord() {
   System.out.println("Adding record ... ");
   f.format("%s%s%s%s", "Author: ", "Melvin ", "Kong ", "Cabatuan");
 }
  private void run(String[] argv) throws IOException {
    int i, index;
    BufferedReader fp = null, fp_restore = null;
    String save_filename = null;
    String restore_filename = null;
    String data_filename = null;

    for (i = 0; i < argv.length; i++) {
      if (argv[i].charAt(0) != '-') break;
      ++i;
      switch (argv[i - 1].charAt(1)) {
        case 'l':
          lower = Double.parseDouble(argv[i]);
          break;
        case 'u':
          upper = Double.parseDouble(argv[i]);
          break;
        case 'y':
          y_lower = Double.parseDouble(argv[i]);
          ++i;
          y_upper = Double.parseDouble(argv[i]);
          y_scaling = true;
          break;
        case 's':
          save_filename = argv[i];
          break;
        case 'r':
          restore_filename = argv[i];
          break;
        default:
          System.err.println("unknown option");
          exit_with_help();
      }
    }

    if (!(upper > lower) || (y_scaling && !(y_upper > y_lower))) {
      System.err.println("inconsistent lower/upper specification");
      System.exit(1);
    }
    if (restore_filename != null && save_filename != null) {
      System.err.println("cannot use -r and -s simultaneously");
      System.exit(1);
    }

    if (argv.length != i + 1) exit_with_help();

    data_filename = argv[i];
    try {
      fp = new BufferedReader(new FileReader(data_filename));
    } catch (Exception e) {
      System.err.println("can't open file " + data_filename);
      System.exit(1);
    }

    /* assumption: min index of attributes is 1 */
    /* pass 1: find out max index of attributes */
    max_index = 0;

    if (restore_filename != null) {
      int idx, c;

      try {
        fp_restore = new BufferedReader(new FileReader(restore_filename));
      } catch (Exception e) {
        System.err.println("can't open file " + restore_filename);
        System.exit(1);
      }
      if ((c = fp_restore.read()) == 'y') {
        fp_restore.readLine();
        fp_restore.readLine();
        fp_restore.readLine();
      }
      fp_restore.readLine();
      fp_restore.readLine();

      String restore_line = null;
      while ((restore_line = fp_restore.readLine()) != null) {
        StringTokenizer st2 = new StringTokenizer(restore_line);
        idx = Integer.parseInt(st2.nextToken());
        max_index = Math.max(max_index, idx);
      }
      fp_restore = rewind(fp_restore, restore_filename);
    }

    while (readline(fp) != null) {
      StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
      System.out.println(line);
      st.nextToken();
      while (st.hasMoreTokens()) {
        index = Integer.parseInt(st.nextToken());
        max_index = Math.max(max_index, index);
        st.nextToken();
        num_nonzeros++;
      }
    }

    try {
      feature_max = new double[(max_index + 1)];
      feature_min = new double[(max_index + 1)];
    } catch (OutOfMemoryError e) {
      System.err.println("can't allocate enough memory");
      System.exit(1);
    }

    for (i = 0; i <= max_index; i++) {
      feature_max[i] = -Double.MAX_VALUE;
      feature_min[i] = Double.MAX_VALUE;
    }

    fp = rewind(fp, data_filename);

    /* pass 2: find out min/max value */
    while (readline(fp) != null) {
      int next_index = 1;
      double target;
      double value;

      StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
      target = Double.parseDouble(st.nextToken());
      y_max = Math.max(y_max, target);
      y_min = Math.min(y_min, target);

      while (st.hasMoreTokens()) {
        index = Integer.parseInt(st.nextToken());
        value = Double.parseDouble(st.nextToken());

        for (i = next_index; i < index; i++) {
          feature_max[i] = Math.max(feature_max[i], 0);
          feature_min[i] = Math.min(feature_min[i], 0);
        }

        feature_max[index] = Math.max(feature_max[index], value);
        feature_min[index] = Math.min(feature_min[index], value);
        next_index = index + 1;
      }

      for (i = next_index; i <= max_index; i++) {
        feature_max[i] = Math.max(feature_max[i], 0);
        feature_min[i] = Math.min(feature_min[i], 0);
      }
    }

    fp = rewind(fp, data_filename);

    /* pass 2.5: save/restore feature_min/feature_max */
    if (restore_filename != null) {
      // fp_restore rewinded in finding max_index
      int idx, c;
      double fmin, fmax;

      fp_restore.mark(2); // for reset
      if ((c = fp_restore.read()) == 'y') {
        fp_restore.readLine(); // pass the '\n' after 'y'
        StringTokenizer st = new StringTokenizer(fp_restore.readLine());
        y_lower = Double.parseDouble(st.nextToken());
        y_upper = Double.parseDouble(st.nextToken());
        st = new StringTokenizer(fp_restore.readLine());
        y_min = Double.parseDouble(st.nextToken());
        y_max = Double.parseDouble(st.nextToken());
        y_scaling = true;
      } else fp_restore.reset();

      if (fp_restore.read() == 'x') {
        fp_restore.readLine(); // pass the '\n' after 'x'
        StringTokenizer st = new StringTokenizer(fp_restore.readLine());
        lower = Double.parseDouble(st.nextToken());
        upper = Double.parseDouble(st.nextToken());
        String restore_line = null;
        while ((restore_line = fp_restore.readLine()) != null) {
          StringTokenizer st2 = new StringTokenizer(restore_line);
          idx = Integer.parseInt(st2.nextToken());
          fmin = Double.parseDouble(st2.nextToken());
          fmax = Double.parseDouble(st2.nextToken());
          if (idx <= max_index) {
            feature_min[idx] = fmin;
            feature_max[idx] = fmax;
          }
        }
      }
      fp_restore.close();
    }

    if (save_filename != null) {
      Formatter formatter = new Formatter(new StringBuilder());
      BufferedWriter fp_save = null;

      try {
        fp_save = new BufferedWriter(new FileWriter(save_filename));
      } catch (IOException e) {
        System.err.println("can't open file " + save_filename);
        System.exit(1);
      }

      if (y_scaling) {
        formatter.format("y\n");
        formatter.format("%.16g %.16g\n", y_lower, y_upper);
        formatter.format("%.16g %.16g\n", y_min, y_max);
      }
      formatter.format("x\n");
      formatter.format("%.16g %.16g\n", lower, upper);
      for (i = 1; i <= max_index; i++) {
        if (feature_min[i] != feature_max[i])
          formatter.format("%d %.16g %.16g\n", i, feature_min[i], feature_max[i]);
      }
      fp_save.write(formatter.toString());
      fp_save.close();
    }

    /* pass 3: scale */
    while (readline(fp) != null) {
      int next_index = 1;
      double target;
      double value;

      StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
      target = Double.parseDouble(st.nextToken());
      output_target(target);
      while (st.hasMoreElements()) {
        index = Integer.parseInt(st.nextToken());
        value = Double.parseDouble(st.nextToken());
        for (i = next_index; i < index; i++) output(i, 0);
        output(index, value);
        next_index = index + 1;
      }

      for (i = next_index; i <= max_index; i++) output(i, 0);
      System.out.print("\n");
    }
    if (new_num_nonzeros > num_nonzeros)
      System.err.print(
          "WARNING: original #nonzeros "
              + num_nonzeros
              + "\n"
              + "         new      #nonzeros "
              + new_num_nonzeros
              + "\n"
              + "Use -l 0 if many original feature values are zeros\n");

    fp.close();
  }
 private static void test(Locale l, String fs, String exp, Object... args) {
   Formatter f = new Formatter(new StringBuilder(), l);
   f.format(fs, args);
   ck(fs, exp, f.toString());
 }
  public void deinit(Appendable out, boolean force) throws Exception {
    Settings settings = new Settings(platform.getConfigFile());

    if (!force) {
      Justif justify = new Justif(80, 40);
      StringBuilder sb = new StringBuilder();
      Formatter f = new Formatter(sb);

      try {
        String list = listFiles(platform.getGlobal());
        if (list != null) {
          f.format("In global default environment:%n");
          f.format(list);
        }

        list = listFiles(platform.getLocal());
        if (list != null) {
          f.format("In local default environment:%n");
          f.format(list);
        }

        if (settings.containsKey(JPM_CACHE_GLOBAL)) {
          list = listFiles(IO.getFile(settings.get(JPM_CACHE_GLOBAL)));
          if (list != null) {
            f.format("In global configured environment:%n");
            f.format(list);
          }
        }

        if (settings.containsKey(JPM_CACHE_LOCAL)) {
          list = listFiles(IO.getFile(settings.get(JPM_CACHE_LOCAL)));
          if (list != null) {
            f.format("In local configured environment:%n");
            f.format(list);
          }
        }

        list = listSupportFiles();
        if (list != null) {
          f.format("jpm support files:%n");
          f.format(list);
        }

        f.format("%n%n");

        f.format(
            "All files listed above will be deleted if deinit is run with the force flag set"
                + " (\"jpm deinit -f\" or \"jpm deinit --force\"%n%n");
        f.flush();

        justify.wrap(sb);
        out.append(sb.toString());
      } finally {
        f.close();
      }
    } else { // i.e. if(force)
      int count = 0;
      File[] caches = {platform.getGlobal(), platform.getLocal(), null, null};
      if (settings.containsKey(JPM_CACHE_LOCAL)) {
        caches[2] = IO.getFile(settings.get(JPM_CACHE_LOCAL));
      }
      if (settings.containsKey(JPM_CACHE_GLOBAL)) {
        caches[3] = IO.getFile(settings.get(JPM_CACHE_GLOBAL));
      }
      ArrayList<File> toDelete = new ArrayList<File>();

      for (File cache : caches) {
        if (cache == null || !cache.exists()) {
          continue;
        }
        listFiles(cache, toDelete);
        if (toDelete.size() > count) {
          count = toDelete.size();
          if (!cache.canWrite()) {
            reporter.error(PERMISSION_ERROR + " (" + cache + ")");
            return;
          }
          toDelete.add(cache);
        }
      }
      listSupportFiles(toDelete);

      for (File f : toDelete) {
        if (f.exists() && !f.canWrite()) {
          reporter.error(PERMISSION_ERROR + " (" + f + ")");
        }
      }
      if (reporter.getErrors().size() > 0) {
        return;
      }

      for (File f : toDelete) {
        if (f.exists()) {
          IO.deleteWithException(f);
        }
      }
    }
  }
Beispiel #27
0
 private void printHelp() throws Exception {
   Formatter f = new Formatter();
   opts._command().help(f, this);
   bnd.out.println(f);
   f.close();
 }
  public String toXML() {

    int[] tokensPerTopic = model.tokensPerTopic;

    StringBuilder out = new StringBuilder();
    Formatter formatter = new Formatter(out, Locale.US);

    out.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    out.append("<model>\n");

    for (int topic = 0; topic < numTopics; topic++) {

      int[][] matrix = topicCodocumentMatrices[topic];

      formatter.format("<topic id='%d'", topic);

      for (TopicScores scores : diagnostics) {
        formatter.format(" %s='%.4f'", scores.name, scores.scores[topic]);
      }
      out.append(">\n");

      TreeSet<IDSorter> sortedWords = topicSortedWords.get(topic);

      // How many words should we report? Some topics may have fewer than
      //  the default number of words with non-zero weight.
      int limit = numTopWords;
      if (sortedWords.size() < numTopWords) {
        limit = sortedWords.size();
      }

      double cumulativeProbability = 0.0;

      Iterator<IDSorter> iterator = sortedWords.iterator();
      for (int position = 0; position < limit; position++) {
        IDSorter info = iterator.next();
        double probability = info.getWeight() / tokensPerTopic[topic];
        cumulativeProbability += probability;

        formatter.format(
            "<word rank='%d' count='%.0f' prob='%.5f' cumulative='%.5f' docs='%d'",
            position + 1,
            info.getWeight(),
            probability,
            cumulativeProbability,
            matrix[position][position]);

        for (TopicScores scores : diagnostics) {
          if (scores.wordScoresDefined) {
            formatter.format(" %s='%.4f'", scores.name, scores.topicWordScores[topic][position]);
          }
        }
        formatter.format(
            ">%s</word>\n",
            topicTopWords[topic][position].replaceAll("&", "&amp;").replaceAll("<", "&gt;"));
      }

      out.append("</topic>\n");
    }
    out.append("</model>\n");

    return out.toString();
  }
  public String what(String key, boolean oneliner) throws Exception {
    byte[] sha;

    Matcher m = SHA_P.matcher(key);
    if (m.matches()) {
      sha = Hex.toByteArray(key);
    } else {
      m = URL_P.matcher(key);
      if (m.matches()) {
        URL url = new URL(key);
        sha = SHA1.digest(url.openStream()).digest();
      } else {
        File jarfile = new File(key);
        if (!jarfile.exists()) {
          reporter.error("File does not exist: %s", jarfile.getCanonicalPath());
        }
        sha = SHA1.digest(jarfile).digest();
      }
    }
    reporter.trace("sha %s", Hex.toHexString(sha));
    Revision revision = library.getRevision(sha);
    if (revision == null) {
      return null;
    }

    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    Justif justif = new Justif(120, 20, 70, 20, 75);
    DateFormat dateFormat = DateFormat.getDateInstance();

    try {
      if (oneliner) {
        f.format("%20s %s%n", Hex.toHexString(revision._id), createCoord(revision));
      } else {
        f.format("Artifact: %s%n", revision.artifactId);
        if (revision.organization != null && revision.organization.name != null) {
          f.format(" (%s)", revision.organization.name);
        }
        f.format("%n");
        f.format("Coordinates\t0: %s%n", createCoord(revision));
        f.format("Created\t0: %s%n", dateFormat.format(new Date(revision.created)));
        f.format("Size\t0: %d%n", revision.size);
        f.format("Sha\t0: %s%n", Hex.toHexString(revision._id));
        f.format("URL\t0: %s%n", createJpmLink(revision));
        f.format("%n");
        f.format("%s%n", revision.description);
        f.format("%n");
        f.format("Dependencies\t0:%n");
        boolean flag = false;
        Iterable<RevisionRef> closure = library.getClosure(revision._id, true);
        for (RevisionRef dep : closure) {
          f.format(
              " - %s \t2- %s \t3- %s%n",
              dep.name, createCoord(dep), dateFormat.format(new Date(dep.created)));
          flag = true;
        }
        if (!flag) {
          f.format("     None%n");
        }
        f.format("%n");
      }
      f.flush();
      justif.wrap(sb);
      return sb.toString();
    } finally {
      f.close();
    }
  }
Beispiel #30
0
 @Override
 public String augmentSetup(String setup, String alias, Map<String, String> parameters)
     throws Exception {
   Formatter f = new Formatter();
   f.format("%s", setup);
   try {
     f.format("\n#\n# Change disk layout to fit maven\n#\n\n");
     f.format("-outputmask = ${@bsn}-${version;===S;${@version}}.jar\n");
     f.format("src=src/main/java\n");
     f.format("bin=target/classes\n");
     f.format("testsrc=src/test/java\n");
     f.format("testbin=target/test-classes\n");
     f.format("target-dir=target\n");
     return f.toString();
   } finally {
     f.close();
   }
 }