Example usage for java.util Formatter Formatter

List of usage examples for java.util Formatter Formatter

Introduction

In this page you can find the example usage for java.util Formatter Formatter.

Prototype

public Formatter(OutputStream os) 

Source Link

Document

Constructs a new formatter with the specified output stream.

Usage

From source file:marytts.tools.analysis.CopySynthesis.java

/**
 * @param args// ww  w. j  a va2s .c om
 */
public static void main(String[] args) throws Exception {
    String wavFilename = null;
    String labFilename = null;
    String pitchFilename = null;
    String textFilename = null;

    String locale = System.getProperty("locale");
    if (locale == null) {
        throw new IllegalArgumentException("No locale given (-Dlocale=...)");
    }

    for (String arg : args) {
        if (arg.endsWith(".txt"))
            textFilename = arg;
        else if (arg.endsWith(".wav"))
            wavFilename = arg;
        else if (arg.endsWith(".ptc"))
            pitchFilename = arg;
        else if (arg.endsWith(".lab"))
            labFilename = arg;
        else
            throw new IllegalArgumentException("Don't know how to treat argument: " + arg);
    }

    // The intonation contour
    double[] contour = null;
    double frameShiftTime = -1;
    if (pitchFilename == null) { // need to create pitch contour from wav file 
        if (wavFilename == null) {
            throw new IllegalArgumentException("Need either a pitch file or a wav file");
        }
        AudioInputStream ais = AudioSystem.getAudioInputStream(new File(wavFilename));
        AudioDoubleDataSource audio = new AudioDoubleDataSource(ais);
        PitchFileHeader params = new PitchFileHeader();
        params.fs = (int) ais.getFormat().getSampleRate();
        F0TrackerAutocorrelationHeuristic tracker = new F0TrackerAutocorrelationHeuristic(params);
        tracker.pitchAnalyze(audio);
        frameShiftTime = tracker.getSkipSizeInSeconds();
        contour = tracker.getF0Contour();
    } else { // have a pitch file -- ignore any wav file
        PitchReaderWriter f0rw = new PitchReaderWriter(pitchFilename);
        if (f0rw.contour == null) {
            throw new NullPointerException("Cannot read f0 contour from " + pitchFilename);
        }
        contour = f0rw.contour;
        frameShiftTime = f0rw.header.skipSizeInSeconds;
    }
    assert contour != null;
    assert frameShiftTime > 0;

    // The ALLOPHONES data and labels
    if (labFilename == null) {
        throw new IllegalArgumentException("No label file given");
    }
    if (textFilename == null) {
        throw new IllegalArgumentException("No text file given");
    }
    MaryTranscriptionAligner aligner = new MaryTranscriptionAligner();
    aligner.SetEnsureInitialBoundary(false);
    String labels = MaryTranscriptionAligner.readLabelFile(aligner.getEntrySeparator(),
            aligner.getEnsureInitialBoundary(), labFilename);
    MaryHttpClient mary = new MaryHttpClient();
    String text = FileUtils.readFileToString(new File(textFilename), "ASCII");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mary.process(text, "TEXT", "ALLOPHONES", locale, null, null, baos);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(true);
    DocumentBuilder builder = docFactory.newDocumentBuilder();
    Document doc = builder.parse(bais);
    aligner.alignXmlTranscriptions(doc, labels);
    assert doc != null;

    // durations
    double[] endTimes = new LabelfileDoubleDataSource(new File(labFilename)).getAllData();
    assert endTimes.length == labels.split(Pattern.quote(aligner.getEntrySeparator())).length;

    // Now add durations and f0 targets to document
    double prevEnd = 0;
    NodeIterator ni = MaryDomUtils.createNodeIterator(doc, MaryXML.PHONE, MaryXML.BOUNDARY);
    for (int i = 0; i < endTimes.length; i++) {
        Element e = (Element) ni.nextNode();
        if (e == null)
            throw new IllegalStateException("More durations than elements -- this should not happen!");
        double durInSeconds = endTimes[i] - prevEnd;
        int durInMillis = (int) (1000 * durInSeconds);
        if (e.getTagName().equals(MaryXML.PHONE)) {
            e.setAttribute("d", String.valueOf(durInMillis));
            e.setAttribute("end", new Formatter(Locale.US).format("%.3f", endTimes[i]).toString());
            // f0 targets at beginning, mid, and end of phone
            StringBuilder f0String = new StringBuilder();
            double startF0 = getF0(contour, frameShiftTime, prevEnd);
            if (startF0 != 0 && !Double.isNaN(startF0)) {
                f0String.append("(0,").append((int) startF0).append(")");
            }
            double midF0 = getF0(contour, frameShiftTime, prevEnd + 0.5 * durInSeconds);
            if (midF0 != 0 && !Double.isNaN(midF0)) {
                f0String.append("(50,").append((int) midF0).append(")");
            }
            double endF0 = getF0(contour, frameShiftTime, endTimes[i]);
            if (endF0 != 0 && !Double.isNaN(endF0)) {
                f0String.append("(100,").append((int) endF0).append(")");
            }
            if (f0String.length() > 0) {
                e.setAttribute("f0", f0String.toString());
            }
        } else { // boundary
            e.setAttribute("duration", String.valueOf(durInMillis));
        }
        prevEnd = endTimes[i];
    }
    if (ni.nextNode() != null) {
        throw new IllegalStateException("More elements than durations -- this should not happen!");
    }

    // TODO: add pitch values

    String acoustparams = DomUtils.document2String(doc);
    System.out.println("ACOUSTPARAMS:");
    System.out.println(acoustparams);
}

From source file:com.globalsight.ling.tm3.tools.ShowTmCommand.java

@Override
protected void handle(CommandLine command) throws Exception {
    Formatter f = new Formatter(System.out);

    List<String> args = command.getArgList();
    if (args.size() == 0) {
        TM3DataFactory factory = getDataFactory();
        showAll(getManager().getAllTms(factory), f);
    } else {//from   www  .j  a va  2 s  . c o m
        for (String a : args) {
            TM3Tm tm = getTm(a);
            if (tm == null) {
                System.err.println("Skipping '" + a + "' - not a valid id");
                continue;
            }
            showOne(tm, f);
            System.out.println("");
        }
    }
    f.flush();
}

From source file:com.itemanalysis.psychometrics.factoranalysis.RotationResults.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);

    int nrow = L.getRowDimension();
    int ncol = L.getColumnDimension();
    f.format("%-40s", "Factor Loadings: " + rotationMethod.toString());
    f.format("%n");
    f.format("%40s", "========================================");
    f.format("%n");
    for (int i = 0; i < nrow; i++) {
        for (int j = 0; j < ncol; j++) {
            f.format("% 6.4f", L.getEntry(i, j));
            f.format("%4s", "");
        }//from  w w  w. jav  a 2s. co m
        f.format("%n");
    }
    f.format("%n");
    f.format("%n");

    f.format("%-30s", "Factor Correlations");
    f.format("%n");
    f.format("%30s", "==============================");
    f.format("%n");
    for (int i = 0; i < Phi.getRowDimension(); i++) {
        for (int j = 0; j < Phi.getColumnDimension(); j++) {
            f.format("% 6.4f", Phi.getEntry(i, j));
            f.format("%4s", "");
        }
        f.format("%n");
    }
    f.format("%n");

    return f.toString();
}

From source file:ca.nines.ise.cmd.Abbrs.java

/**
 * {@inheritDoc}/*from w w w  . j a  va  2s  . c  o m*/
 */
@Override
public void execute(CommandLine cmd) throws Exception {
    File[] files;

    Locale.setDefault(Locale.ENGLISH);
    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    if (cmd.hasOption("l")) {
        out = new PrintStream(new FileOutputStream(cmd.getOptionValue("l")), true, "UTF-8");
    }

    files = getFilePaths(cmd);
    Formatter formatter = new Formatter(out);

    if (files != null) {
        out.println("Found " + files.length + " files to check.");
        for (File in : files) {
            DOM dom = new DOMBuilder(in).build();
            for (Node n : dom) {
                if (n.type() == NodeType.ABBR) {
                    formatter.format("%s:%d:%d%n", n.getSource(), n.getLine(), n.getColumn());
                    formatter.format("  near TLN %s%n", n.getTLN());
                    formatter.format("  %s%n", n.getText().substring(0, Math.min(64, n.getText().length())));
                    formatter.format("  %s%n", dom.getLine(n.getLine() - 1));
                    formatter.format("%n");
                }
            }
        }
    }
}

From source file:com.itemanalysis.psychometrics.reliability.KR21.java

@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    Formatter f = new Formatter(builder);
    String f2 = "%.4f";
    f.format("%7s", "KR-21: ");
    f.format(f2, this.value());
    return f.toString();
}

From source file:com.itemanalysis.psychometrics.cfa.CfaSummary.java

public String multipleCfa(int estimationMethod, int optimizationMethod) {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);

    ConfirmatoryFactorAnalysis congeneric = new ConfirmatoryFactorAnalysis(cfaMatrix, numberOfExaminees,
            ConfirmatoryFactorAnalysisModel.CONGENERIC, estimationMethod);
    congeneric.optimize(optimizationMethod);
    logger.info("Congeneric Model CFA completed\n" + congeneric.printOptimizationSummary());

    ConfirmatoryFactorAnalysis tauEquivalent = new ConfirmatoryFactorAnalysis(cfaMatrix, numberOfExaminees,
            ConfirmatoryFactorAnalysisModel.TAU_EQUIVALENT, estimationMethod);
    tauEquivalent.optimize(optimizationMethod);
    logger.info("Tau-equivalent Model CFA completed\n" + tauEquivalent.printOptimizationSummary());

    ConfirmatoryFactorAnalysis parallel = new ConfirmatoryFactorAnalysis(cfaMatrix, numberOfExaminees,
            ConfirmatoryFactorAnalysisModel.PARALLEL, estimationMethod);
    parallel.optimize(optimizationMethod);
    logger.info("Parallel Model CFA completed\n" + parallel.printOptimizationSummary());

    f.format("%-60s", "            CONGENERIC, TAU-EQUIVALENT, AND PARALLEL");
    f.format("%n");
    f.format("%-60s", "                  CONFIRMATORY FACTOR ANLAYSIS");
    f.format("%n");
    f.format("%n");
    f.format("%n");
    f.format("%-60s", "   ****CAUTION CONFIRMATORY FACTOR ANALYSIS IS STILL IN DEVELOPMENT****");
    f.format("%n");
    f.format("%-60s", "            ****IT HAS NOT BEEN THOROUGHLY TESTED****");
    f.format("%n");
    f.format("%n");
    f.format("%-25s", "                         MODEL SUMMARY");
    f.format("%n");
    f.format("%-60s", "=================================================================");
    f.format("%n");
    f.format("%11s", "Statistic");
    f.format("%5s", "");
    f.format("%10s", "Congeneric");
    f.format("%5s", "");
    f.format("%14s", "Tau-Equivalent");
    f.format("%5s", "");
    f.format("%10s", "Parallel");
    f.format("%n");
    f.format("%-60s", "-----------------------------------------------------------------");
    f.format("%n");
    f.format("%11s", "Fmin");
    f.format("%5s", "");
    f.format("% 10.4f", congeneric.getEstimator().fMin());
    f.format("%5s", "");
    f.format("% 10.4f", tauEquivalent.getEstimator().fMin());
    f.format("%9s", "");
    f.format("% 10.4f", parallel.getEstimator().fMin());
    f.format("%n");
    f.format("%11s", "Chi^2");
    f.format("%5s", "");
    f.format("% 10.4f", congeneric.getEstimator().chisquare());
    f.format("%5s", "");
    f.format("% 10.4f", tauEquivalent.getEstimator().chisquare());
    f.format("%9s", "");
    f.format("% 10.4f", parallel.getEstimator().chisquare());
    f.format("%n");
    f.format("%11s", "df");
    f.format("%5s", "");
    f.format("% 10.4f", congeneric.getEstimator().degreesOfFreedom());
    f.format("%5s", "");
    f.format("% 10.4f", tauEquivalent.getEstimator().degreesOfFreedom());
    f.format("%9s", "");
    f.format("% 10.4f", parallel.getEstimator().degreesOfFreedom());
    f.format("%n");
    f.format("%11s", "p-rho");
    f.format("%5s", "");
    f.format("% 10.4f", congeneric.getEstimator().pvalue());
    f.format("%5s", "");
    f.format("% 10.4f", tauEquivalent.getEstimator().pvalue());
    f.format("%9s", "");
    f.format("% 10.4f", parallel.getEstimator().pvalue());
    f.format("%n");
    f.format("%11s", "GFI");
    f.format("%5s", "");
    f.format("% 10.4f", congeneric.getEstimator().gfi());
    f.format("%5s", "");
    f.format("% 10.4f", tauEquivalent.getEstimator().gfi());
    f.format("%9s", "");
    f.format("% 10.4f", parallel.getEstimator().gfi());
    f.format("%n");
    f.format("%11s", "AGFI");
    f.format("%5s", "");
    f.format("% 10.4f", congeneric.getEstimator().agfi());
    f.format("%5s", "");
    f.format("% 10.4f", tauEquivalent.getEstimator().agfi());
    f.format("%9s", "");
    f.format("% 10.4f", parallel.getEstimator().agfi());
    f.format("%n");
    f.format("%11s", "RMR");
    f.format("%5s", "");
    f.format("% 10.4f", Math.sqrt(congeneric.getEstimator().meanSquaredResidual()));
    f.format("%5s", "");
    f.format("% 10.4f", Math.sqrt(tauEquivalent.getEstimator().meanSquaredResidual()));
    f.format("%9s", "");
    f.format("% 10.4f", Math.sqrt(parallel.getEstimator().meanSquaredResidual()));
    f.format("%n");
    f.format("%11s", "RMSEA");
    f.format("%5s", "");
    f.format("% 10.4f", congeneric.getEstimator().rmsea());
    f.format("%5s", "");
    f.format("% 10.4f", tauEquivalent.getEstimator().rmsea());
    f.format("%9s", "");
    f.format("% 10.4f", parallel.getEstimator().rmsea());
    f.format("%n");
    f.format("%11s", "Reliability");
    f.format("%5s", "");
    f.format("% 10.4f", congeneric.getEstimator().mcdonaldOmega());
    f.format("%5s", "");
    f.format("% 10.4f", tauEquivalent.getEstimator().mcdonaldOmega());
    f.format("%9s", "");
    f.format("% 10.4f", parallel.getEstimator().mcdonaldOmega());
    f.format("%n");
    f.format("%-60s", "-----------------------------------------------------------------");
    f.format("%n");
    f.format("%n");
    f.format("%n");
    f.format("%n");
    sb.append(congeneric.getEstimator().printEstimates(items));
    f.format("%n");
    f.format("%n");
    f.format("%n");
    sb.append(tauEquivalent.getEstimator().printEstimates(items));
    f.format("%n");
    f.format("%n");
    f.format("%n");
    sb.append(parallel.getEstimator().printEstimates(items));
    f.format("%n");
    f.format("%n");

    return f.toString();
}

From source file:com.cognifide.slice.cq.taglib.FormatTag.java

/** {@inheritDoc} */
@Override// ww w. ja  v  a 2 s  .  c o m
public int doStartTag() throws JspException {
    if (StringUtils.isNotBlank(format)) {
        Writer out = getJspWriter();

        Formatter formatter;
        if (locale == null) {
            formatter = new Formatter(out);
        } else {
            formatter = new Formatter(out, locale);
        }

        formatter.format(format, value);
        formatter.flush();
        formatter.close();
    }
    return SKIP_BODY;
}

From source file:com.dgsd.android.ShiftTracker.Adapter.WeekPagerAdapter.java

public WeekPagerAdapter(Context context, FragmentManager fm, int weekContainingJulianDay) {
    super(fm);/*from  w  w w  .  ja  v a2  s  .co  m*/
    mContext = context;
    mTime = new Time();
    mStringBuilder = new StringBuilder();
    mFormatter = new Formatter(mStringBuilder);

    SharedPreferences p = context.getSharedPreferences(Const.SHARED_PREFS_NAME, Context.MODE_PRIVATE);
    String startDayAsStr = p.getString(context.getString(R.string.settings_key_start_day), "1");
    mWeekStartDay = Integer.valueOf(startDayAsStr);

    mCenterJulianDay = adjustJulianDay(mWeekStartDay, weekContainingJulianDay);
}

From source file:ar.com.zauber.labs.kraken.providers.wikipedia.apps.administrative.ArgentinaWikiSecondLevel.java

/** @see Object#toString() */
@Override//from w ww.  j av  a  2 s. co  m
public final String toString() {
    final StringBuilder sb = new StringBuilder();
    new Formatter(sb).format("{province: %s, department: %s, capital: %s}", province, department, capitalCity);
    return sb.toString();
}

From source file:com.globalsight.ling.tm3.tools.HistoryCommand.java

@SuppressWarnings("unchecked")
@Override//from   w ww  .  j av  a  2s .  c o  m
protected void handle(CommandLine command) throws Exception {
    TM3Tm tm = getTm(command.getOptionValue(TM));
    if (tm == null) {
        die("Not a valid TM id: '" + command.getOptionValue(TM) + "'");
    }

    Formatter f = new Formatter(System.out);

    // If there are no segments listed, just show segment history.
    if (command.getArgs().length == 0) {
        printEvents(tm.getEventLog(), "TM " + tm.getId(), f);
    }
}