Example usage for java.util TreeSet TreeSet

List of usage examples for java.util TreeSet TreeSet

Introduction

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

Prototype

public TreeSet() 

Source Link

Document

Constructs a new, empty tree set, sorted according to the natural ordering of its elements.

Usage

From source file:fr.cs.examples.attitude.EarthObservation_day_night_switch_with_spinned_transitions.java

/** Program entry point.
 * @param args program arguments (unused here)
 *///w  w  w . j  ava2 s.  c o  m
public static void main(String[] args) {
    try {

        // configure Orekit
        Autoconfiguration.configureOrekit();
        final SortedSet<String> output = new TreeSet<String>();

        //----------------------------------------
        //  Initial state definition : date, orbit
        //----------------------------------------
        final AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 02, 00, 00, 00.000,
                TimeScalesFactory.getUTC());
        final Vector3D position = new Vector3D(-6142438.668, 3492467.560, -25767.25680);
        final Vector3D velocity = new Vector3D(505.8479685, 942.7809215, 7435.922231);
        final Orbit initialOrbit = new KeplerianOrbit(new PVCoordinates(position, velocity),
                FramesFactory.getEME2000(), initialDate, Constants.EIGEN5C_EARTH_MU);

        //------------------------------
        // Attitudes sequence definition
        //------------------------------
        final AttitudesSequence attitudesSequence = new AttitudesSequence();

        // Attitude laws definition
        final double settingRate = FastMath.toRadians(1.0);
        final AttitudeProvider dayObservationLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(40), 0);
        final AttitudeProvider nightRestingLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH);
        final AttitudeProvider transitionLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), 0, 0);
        final AttitudeProvider rollSetUpLaw = new SpinStabilized(nightRestingLaw, AbsoluteDate.J2000_EPOCH,
                Vector3D.PLUS_I, settingRate);
        final AttitudeProvider pitchSetUpLaw = new SpinStabilized(transitionLaw, AbsoluteDate.J2000_EPOCH,
                Vector3D.PLUS_J, settingRate);
        final AttitudeProvider pitchTearDownLaw = new SpinStabilized(dayObservationLaw,
                AbsoluteDate.J2000_EPOCH, Vector3D.PLUS_J, -settingRate);
        final AttitudeProvider rollTearDownLaw = new SpinStabilized(transitionLaw, AbsoluteDate.J2000_EPOCH,
                Vector3D.PLUS_I, -settingRate);

        // Event detectors definition
        //---------------------------
        final PVCoordinatesProvider sun = CelestialBodyFactory.getSun();
        final PVCoordinatesProvider earth = CelestialBodyFactory.getEarth();

        // Detectors : end day-night rdv 2
        final DateDetector endDayNightRdV2Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to night law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-day-night-2 night-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endDayNightRdV2Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to night law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-day-night-2 night-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detectors : end day-night rdv 1
        final DateDetector endDayNightRdV1Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to day-night rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-day-night-1 day-night-rdv2-mode");
                            endDayNightRdV2Event_increase.addEventDate(s.getDate().shiftedBy(20));
                            endDayNightRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(20));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endDayNightRdV1Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to day-night rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-day-night-1 day-night-rdv2-mode");
                            endDayNightRdV2Event_increase.addEventDate(s.getDate().shiftedBy(20));
                            endDayNightRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(20));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detector : eclipse entry
        final EventDetector dayNightEvent = new EclipseDetector(sun, 696000000., earth,
                Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new EventHandler<EclipseDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final EclipseDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to day-night rdv 1 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " eclipse-entry day-night-rdv1-mode");
                            endDayNightRdV1Event_increase.addEventDate(s.getDate().shiftedBy(40));
                            endDayNightRdV1Event_decrease.addEventDate(s.getDate().shiftedBy(40));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(EclipseDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detectors : end night-day rdv 2
        final DateDetector endNightDayRdV2Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to day law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-night-day-2 day-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endNightDayRdV2Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to day law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-night-day-2 day-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detectors : end night-day rdv 1
        final DateDetector endNightDayRdV1Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to night-day rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-night-day-1 night-day-rdv2-mode");
                            endNightDayRdV2Event_increase.addEventDate(s.getDate().shiftedBy(40));
                            endNightDayRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(40));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endNightDayRdV1Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to night-day rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-night-day-1 night-day-rdv2-mode");
                            endNightDayRdV2Event_increase.addEventDate(s.getDate().shiftedBy(40));
                            endNightDayRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(40));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detector : eclipse exit
        final EventDetector nightDayEvent = new EclipseDetector(sun, 696000000., earth,
                Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new EventHandler<EclipseDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final EclipseDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to night-day rdv 1 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " eclipse-exit night-day-rdv1-mode");
                            endNightDayRdV1Event_increase.addEventDate(s.getDate().shiftedBy(20));
                            endNightDayRdV1Event_decrease.addEventDate(s.getDate().shiftedBy(20));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(EclipseDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Attitude sequences definition
        //------------------------------
        attitudesSequence.addSwitchingCondition(dayObservationLaw, dayNightEvent, false, true,
                pitchTearDownLaw);
        attitudesSequence.addSwitchingCondition(pitchTearDownLaw, endDayNightRdV1Event_increase, true, false,
                rollTearDownLaw);
        attitudesSequence.addSwitchingCondition(pitchTearDownLaw, endDayNightRdV1Event_decrease, false, true,
                rollTearDownLaw);
        attitudesSequence.addSwitchingCondition(rollTearDownLaw, endDayNightRdV2Event_increase, true, false,
                nightRestingLaw);
        attitudesSequence.addSwitchingCondition(rollTearDownLaw, endDayNightRdV2Event_decrease, false, true,
                nightRestingLaw);
        attitudesSequence.addSwitchingCondition(nightRestingLaw, nightDayEvent, true, false, rollSetUpLaw);
        attitudesSequence.addSwitchingCondition(rollSetUpLaw, endNightDayRdV1Event_increase, true, false,
                pitchSetUpLaw);
        attitudesSequence.addSwitchingCondition(rollSetUpLaw, endNightDayRdV1Event_decrease, false, true,
                pitchSetUpLaw);
        attitudesSequence.addSwitchingCondition(pitchSetUpLaw, endNightDayRdV2Event_increase, true, false,
                dayObservationLaw);
        attitudesSequence.addSwitchingCondition(pitchSetUpLaw, endNightDayRdV2Event_decrease, false, true,
                dayObservationLaw);

        // Initialisation
        //---------------
        if (dayNightEvent.g(new SpacecraftState(initialOrbit)) >= 0) {
            // initial position is in daytime
            attitudesSequence.resetActiveProvider(dayObservationLaw);
            System.out
                    .println("# " + (initialDate.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY)
                            + " begin with day law");
        } else {
            // initial position is in nighttime
            attitudesSequence.resetActiveProvider(nightRestingLaw);
            System.out
                    .println("# " + (initialDate.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY)
                            + " begin with night law");
        }

        //----------------------
        // Propagator definition
        //----------------------

        // Propagator : consider the analytical Eckstein-Hechler model
        final Propagator propagator = new EcksteinHechlerPropagator(initialOrbit, attitudesSequence,
                Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS, Constants.EIGEN5C_EARTH_MU,
                Constants.EIGEN5C_EARTH_C20, Constants.EIGEN5C_EARTH_C30, Constants.EIGEN5C_EARTH_C40,
                Constants.EIGEN5C_EARTH_C50, Constants.EIGEN5C_EARTH_C60);
        // Register the switching events to the propagator
        attitudesSequence.registerSwitchEvents(propagator);

        propagator.setMasterMode(10.0, new OrekitFixedStepHandler() {
            private DecimalFormat f1 = new DecimalFormat("0.0000000000000000E00",
                    new DecimalFormatSymbols(Locale.US));
            private Vector3DFormat f2 = new Vector3DFormat(" ", " ", " ", f1);
            private PVCoordinatesProvider sun = CelestialBodyFactory.getSun();
            private PVCoordinatesProvider moon = CelestialBodyFactory.getMoon();
            private Frame eme2000 = FramesFactory.getEME2000();
            private Frame itrf2005 = FramesFactory.getITRF(IERSConventions.IERS_2010, true);

            private String printVector3D(final String name, final Vector3D v) {
                return name + " " + f2.format(v);
            }

            private String printRotation(final String name, final Rotation r) {
                return name + " " + f1.format(r.getQ1()) + " " + f1.format(r.getQ2()) + " "
                        + f1.format(r.getQ3()) + " " + f1.format(r.getQ0());
            }

            private String printRotation2(final String name, final Rotation r) {
                return name + " " + f1.format(-r.getQ1()) + " " + f1.format(-r.getQ2()) + " "
                        + f1.format(-r.getQ3()) + " " + f1.format(-r.getQ0());
            }

            public void init(final SpacecraftState s0, final AbsoluteDate t) {
            }

            public void handleStep(SpacecraftState currentState, boolean isLast) throws PropagationException {
                try {
                    // the Earth position in spacecraft should be along spacecraft Z axis
                    // during nigthtime and away from it during daytime due to roll and pitch offsets
                    final Vector3D earth = currentState.toTransform().transformPosition(Vector3D.ZERO);
                    final double pointingOffset = Vector3D.angle(earth, Vector3D.PLUS_K);

                    // the g function is the eclipse indicator, its an angle between Sun and Earth limb,
                    // positive when Sun is outside of Earth limb, negative when Sun is hidden by Earth limb
                    final double eclipseAngle = dayNightEvent.g(currentState);

                    final double endNightDayTimer1 = endNightDayRdV1Event_decrease.g(currentState);
                    final double endNightDayTimer2 = endNightDayRdV2Event_decrease.g(currentState);
                    final double endDayNightTimer1 = endDayNightRdV1Event_decrease.g(currentState);
                    final double endDayNightTimer2 = endDayNightRdV2Event_decrease.g(currentState);

                    output.add(currentState.getDate() + " " + FastMath.toDegrees(eclipseAngle) + " "
                            + endNightDayTimer1 + " " + endNightDayTimer2 + " " + endDayNightTimer1 + " "
                            + endDayNightTimer2 + " " + FastMath.toDegrees(pointingOffset));
                    final AbsoluteDate date = currentState.getDate();
                    final PVCoordinates pv = currentState.getPVCoordinates(eme2000);
                    final Rotation lvlhRot = new Rotation(pv.getPosition(), pv.getMomentum(), Vector3D.MINUS_K,
                            Vector3D.MINUS_J);
                    final Rotation earthRot = eme2000.getTransformTo(itrf2005, date).getRotation();
                    System.out.println("Scenario::setVectorMap 0x960b7e0 "
                            + (date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " "
                            + printVector3D("sun", sun.getPVCoordinates(date, eme2000).getPosition()) + " "
                            + printVector3D("moon", moon.getPVCoordinates(date, eme2000).getPosition()) + " "
                            + printVector3D("satPos", pv.getPosition()) + " "
                            + printVector3D("satVel", pv.getVelocity()) + " "
                            + printVector3D("orbMom", pv.getMomentum()));
                    System.out.println("Scenario::setQuatMap 0x960b7e0 "
                            + (date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " "
                            + printRotation("earthFrame", earthRot) + " "
                            + printRotation("LVLHFrame", lvlhRot));
                    System.out.println("Scenario::computeStep 0x960b7e0 "
                            + (date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY));
                    System.out.println("  -> " + printRotation2("", currentState.getAttitude().getRotation())
                            + " " + printVector3D("", currentState.getAttitude().getSpin()));
                } catch (OrekitException oe) {
                    throw new PropagationException(oe);
                }
            }
        });

        //----------
        // Propagate
        //----------

        // Propagate from the initial date for the fixed duration
        propagator.propagate(initialDate.shiftedBy(1.75 * 3600.));

        //--------------
        // Print results
        //--------------

        // we print the lines according to lexicographic order, which is chronological order here
        // to make sure out of orders calls between step handler and event handlers don't mess things up
        for (final String line : output) {
            System.out.println(line);
        }

    } catch (OrekitException oe) {
        System.err.println(oe.getMessage());
    }
}

From source file:br.com.thiagomoreira.bancodobrasil.Main.java

/**
 * @param args//from   w w w.  j  av  a2s.  com
 */
public static void main(String[] args) throws Exception {
    if (args != null) {
        NumberFormat formatter = NumberFormat.getNumberInstance(new Locale("pt", "BR"));

        formatter.setMaximumFractionDigits(2);
        formatter.setMinimumFractionDigits(2);

        double total = 0;

        for (String arg : args) {
            File input = new File(arg);
            if (input.exists()) {
                List<String> lines = IOUtils.readLines(new FileInputStream(input), "ISO-8859-1");

                Parser parser = new DefaultParser();

                List<Transaction> transactions = parser.parse(lines);

                TransactionList transactionList = new TransactionList();
                transactionList.setStart(parser.getStartDate());
                transactionList.setEnd(parser.getEndDate());
                transactionList.setTransactions(transactions);

                CreditCardAccountDetails creditCardAccountDetails = new CreditCardAccountDetails();
                creditCardAccountDetails.setAccountNumber("7616-3");
                creditCardAccountDetails.setAccountKey(parser.getAccountKey());

                CreditCardStatementResponse creditCardStatementResponse = new CreditCardStatementResponse();
                creditCardStatementResponse.setAccount(creditCardAccountDetails);
                creditCardStatementResponse.setCurrencyCode("BRL");
                creditCardStatementResponse.setTransactionList(transactionList);

                Status status = new Status();
                status.setCode(Status.KnownCode.SUCCESS);
                status.setSeverity(Status.Severity.INFO);

                CreditCardStatementResponseTransaction statementResponse = new CreditCardStatementResponseTransaction();
                statementResponse.setClientCookie(UUID.randomUUID().toString());
                statementResponse.setStatus(status);
                statementResponse.setUID(UUID.randomUUID().toString());
                statementResponse.setMessage(creditCardStatementResponse);

                CreditCardResponseMessageSet creditCardResponseMessageSet = new CreditCardResponseMessageSet();
                creditCardResponseMessageSet.setStatementResponse(statementResponse);

                SortedSet<ResponseMessageSet> messageSets = new TreeSet<ResponseMessageSet>();
                messageSets.add(creditCardResponseMessageSet);

                ResponseEnvelope envelope = new ResponseEnvelope();
                envelope.setUID(UUID.randomUUID().toString());
                envelope.setSecurity(ApplicationSecurity.NONE);
                envelope.setMessageSets(messageSets);

                double brazilianRealsamount = parser.getBrazilianRealsAmount();
                double dolarsAmount = parser.getDolarsAmount();
                double cardTotal = dolarsAmount * parser.getExchangeRate() + brazilianRealsamount;
                total += cardTotal;

                System.out.println(creditCardAccountDetails.getAccountKey());
                System.out.println("TOTAL EM RS " + formatter.format(brazilianRealsamount));
                System.out.println("TOTAL EM US " + formatter.format(dolarsAmount));
                System.out.println("TOTAL FATURA EM RS " + formatter.format(cardTotal));
                System.out.println();

                if (!transactions.isEmpty()) {
                    String parent = System.getProperty("user.home") + "/Downloads";
                    String fileName = arg.replace(".txt", ".ofx");
                    File output = new File(parent, fileName);
                    FileOutputStream fos = new FileOutputStream(output);

                    OFXV1Writer writer = new OFXV1Writer(fos);
                    writer.setWriteAttributesOnNewLine(true);

                    AggregateMarshaller marshaller = new AggregateMarshaller();
                    marshaller.setConversion(new MyFinanceStringConversion());
                    marshaller.marshal(envelope, writer);

                    writer.flush();
                    writer.close();
                }
            }
        }
        System.out.println("TOTAL FATURAS EM RS " + formatter.format(total));
    }

}

From source file:cc.twittertools.search.api.RunQueriesBaselineThrift.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("string").hasArg().withDescription("host").create(HOST_OPTION));
    options.addOption(OptionBuilder.withArgName("port").hasArg().withDescription("port").create(PORT_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("file containing topics in TREC format").create(QUERIES_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));
    options.addOption(/*from   w  w  w  .jav  a2s  .  c  om*/
            OptionBuilder.withArgName("string").hasArg().withDescription("group id").create(GROUP_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("access token").create(TOKEN_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION));
    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(HOST_OPTION) || !cmdline.hasOption(PORT_OPTION)
            || !cmdline.hasOption(QUERIES_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(RunQueriesThrift.class.getName(), options);
        System.exit(-1);
    }

    String queryFile = cmdline.getOptionValue(QUERIES_OPTION);
    if (!new File(queryFile).exists()) {
        System.err.println("Error: " + queryFile + " doesn't exist!");
        System.exit(-1);
    }

    String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG;

    TrecTopicSet topicsFile = TrecTopicSet.fromFile(new File(queryFile));

    int numResults = 1000;
    try {
        if (cmdline.hasOption(NUM_RESULTS_OPTION)) {
            numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION));
        }
    } catch (NumberFormatException e) {
        System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION));
        System.exit(-1);
    }

    String group = cmdline.hasOption(GROUP_OPTION) ? cmdline.getOptionValue(GROUP_OPTION) : null;
    String token = cmdline.hasOption(TOKEN_OPTION) ? cmdline.getOptionValue(TOKEN_OPTION) : null;

    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);

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

    TrecSearchThriftClient client = new TrecSearchThriftClient(cmdline.getOptionValue(HOST_OPTION),
            Integer.parseInt(cmdline.getOptionValue(PORT_OPTION)), group, token);

    for (cc.twittertools.search.TrecTopic query : topicsFile) {
        List<TResult> results = client.search(query.getQuery(), query.getQueryTweetTime(), numResults);

        SortedSet<TResultComparable> sortedResults = new TreeSet<TResultComparable>();
        for (TResult result : results) {
            // Throw away retweets.
            if (result.getRetweeted_status_id() == 0) {
                sortedResults.add(new TResultComparable(result));
            }
        }

        int i = 1;
        int dupliCount = 0;
        double rsvPrev = 0;
        for (TResultComparable sortedResult : sortedResults) {
            TResult result = sortedResult.getTResult();
            double rsvCurr = result.rsv;
            if (Math.abs(rsvCurr - rsvPrev) > 0.0000001) {
                dupliCount = 0;
            } else {
                dupliCount++;
                rsvCurr = rsvCurr - 0.000001 / numResults * dupliCount;
            }
            out.println(String.format("%s Q0 %d %d %." + (int) (6 + Math.ceil(Math.log10(numResults))) + "f %s",
                    query.getId(), result.id, i, rsvCurr, runtag));
            if (verbose) {
                out.println("# " + result.toString().replaceAll("[\\n\\r]+", " "));
            }
            i++;
            rsvPrev = result.rsv;
        }

    }
    out.close();
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step7CollectMTurkResults.java

public static void main(String[] args) throws Exception {
    // input dir - list of xml query containers
    // /home/user-ukp/research/data/dip/wp1-documents/step4-boiler-plate/
    File inputDir = new File(args[0] + "/");

    // MTurk result file

    // output dir
    File outputDir = new File(args[2]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();//from   www. ja v a  2 s  .  co m

    }

    // Folder with success files
    File mturkSuccessDir = new File(args[1]);

    Collection<File> files = FileUtils.listFiles(mturkSuccessDir, new String[] { "result" }, false);
    if (files.isEmpty()) {
        throw new IllegalArgumentException("Input folder is empty. " + mturkSuccessDir);
    }

    HashMap<String, List<MTurkAnnotation>> mturkAnnotations = new HashMap<>();

    // parsing all CSV files
    for (File mturkCSVResultFile : files) {
        System.out.println("Parsing " + mturkCSVResultFile.getName());

        MTurkOutputReader outputReader = new MTurkOutputReader(
                new HashSet<>(Arrays.asList("annotation", "workerid")), mturkCSVResultFile);

        // for fixing broken data input: for each hit, collect all sentence IDs
        Map<String, SortedSet<String>> hitSentences = new HashMap<>();

        // first iteration: collect the sentences
        for (Map<String, String> record : outputReader) {
            String hitID = record.get("hitid");
            if (!hitSentences.containsKey(hitID)) {
                hitSentences.put(hitID, new TreeSet<>());
            }

            String relevantSentences = record.get("Answer.relevant_sentences");
            String irrelevantSentences = record.get("Answer.irrelevant_sentences");

            if (relevantSentences != null) {
                hitSentences.get(hitID).addAll(Arrays.asList(relevantSentences.split(",")));
            }

            if (irrelevantSentences != null) {
                hitSentences.get(hitID).addAll(Arrays.asList(irrelevantSentences.split(",")));
            }
        }

        // and now second iteration
        for (Map<String, String> record : outputReader) {
            String hitID = record.get("hitid");
            String annotatorID = record.get("workerid");
            String acceptTime = record.get("assignmentaccepttime");
            String submitTime = record.get("assignmentsubmittime");
            String relevantSentences = record.get("Answer.relevant_sentences");
            String irrelevantSentences = record.get("Answer.irrelevant_sentences");
            String reject = record.get("reject");
            String filename[];
            String comment;
            String clueWeb;
            String[] relevant = {};
            String[] irrelevant = {};

            filename = record.get("annotation").split("_");
            String fileXml = filename[0];
            clueWeb = filename[1].trim();
            comment = record.get("Answer.comment");

            if (relevantSentences != null) {
                relevant = relevantSentences.split(",");
            }

            if (irrelevantSentences != null) {
                irrelevant = irrelevantSentences.split(",");
            }

            // sanitizing data: if both relevant and irrelevant are empty, that's a bug
            // we're gonna look up all sentences from this HIT and treat this assignment
            // as if there were only irrelevant ones
            if (relevant.length == 0 && irrelevant.length == 0) {
                SortedSet<String> strings = hitSentences.get(hitID);
                irrelevant = new String[strings.size()];
                strings.toArray(irrelevant);
            }

            if (reject != null) {
                System.out.println(" HIT " + hitID + " annotated by " + annotatorID + " was rejected ");
            } else {
                /*
                // relevant sentences is a comma-delimited string,
                // this regular expression is rather strange
                // it must contain digits, it might be that there is only one space or a comma or some other char
                // digits are the sentence ids. if relevant sentences do not contain digits then it is wrong
                if (relevantSentences.matches("^\\D*$") &&
                    irrelevantSentences.matches("^\\D*$")) {
                try {
                    throw new IllegalStateException(
                            "No annotations found for HIT " + hitID + " in " +
                                    fileXml + " for document " + clueWeb);
                }
                catch (IllegalStateException ex) {
                    ex.printStackTrace();
                }
                        
                }
                */
                MTurkAnnotation mturkAnnotation;
                try {
                    mturkAnnotation = new MTurkAnnotation(hitID, annotatorID, acceptTime, submitTime, comment,
                            clueWeb, relevant, irrelevant);
                } catch (IllegalArgumentException ex) {
                    throw new IllegalArgumentException("Record: " + record, ex);
                }

                List<MTurkAnnotation> listOfAnnotations = mturkAnnotations.get(fileXml);

                if (listOfAnnotations == null) {
                    listOfAnnotations = new ArrayList<>();
                }
                listOfAnnotations.add(mturkAnnotation);
                mturkAnnotations.put(fileXml, listOfAnnotations);
            }

        }
        //            parser.close();
    }

    // Debugging: output number of HITs of a query
    System.out.println("Accepted HITs for a query:");
    for (Map.Entry e : mturkAnnotations.entrySet()) {
        ArrayList<MTurkAnnotation> a = (ArrayList<MTurkAnnotation>) e.getValue();
        System.out.println(e.getKey() + " " + a.size());
    }

    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));
        String fileName = f.getName();
        List<MTurkAnnotation> listOfAnnotations = mturkAnnotations.get(fileName);

        if (listOfAnnotations == null || listOfAnnotations.isEmpty()) {
            throw new IllegalStateException("No annotations for " + f.getName());
        }

        for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
            for (MTurkAnnotation mtAnnotation : listOfAnnotations) {
                String clueWeb = mtAnnotation.clueWeb;
                if (rankedResults.clueWebID.equals(clueWeb)) {
                    List<QueryResultContainer.MTurkRelevanceVote> mTurkRelevanceVotes = rankedResults.mTurkRelevanceVotes;
                    QueryResultContainer.MTurkRelevanceVote relevanceVote = new QueryResultContainer.MTurkRelevanceVote();
                    String annotatorID = mtAnnotation.annotatorID;
                    String hitID = mtAnnotation.hitID;
                    String acceptTime = mtAnnotation.acceptTime;
                    String submitTime = mtAnnotation.submitTime;
                    String comment = mtAnnotation.comment;
                    String[] relevant = mtAnnotation.relevant;
                    String[] irrelevant = mtAnnotation.irrelevant;
                    relevanceVote.turkID = annotatorID.trim();
                    relevanceVote.hitID = hitID.trim();
                    relevanceVote.acceptTime = acceptTime.trim();
                    relevanceVote.submitTime = submitTime.trim();
                    relevanceVote.comment = comment != null ? comment.trim() : null;
                    if (relevant.length == 0 && irrelevant.length == 0) {
                        try {
                            throw new IllegalStateException("the length of the annotations is 0"
                                    + rankedResults.clueWebID + " for HIT " + relevanceVote.hitID);
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        }
                    }
                    for (String r : relevant) {
                        String sentenceId = r.trim();
                        if (!sentenceId.isEmpty() && sentenceId.matches("\\d+")) {
                            QueryResultContainer.SingleSentenceRelevanceVote singleSentenceVote = new QueryResultContainer.SingleSentenceRelevanceVote();
                            singleSentenceVote.sentenceID = sentenceId;
                            singleSentenceVote.relevant = "true";
                            relevanceVote.singleSentenceRelevanceVotes.add(singleSentenceVote);
                        }
                    }
                    for (String r : irrelevant) {
                        String sentenceId = r.trim();
                        if (!sentenceId.isEmpty() && sentenceId.matches("\\d+")) {
                            QueryResultContainer.SingleSentenceRelevanceVote singleSentenceVote = new QueryResultContainer.SingleSentenceRelevanceVote();
                            singleSentenceVote.sentenceID = sentenceId;
                            singleSentenceVote.relevant = "false";
                            relevanceVote.singleSentenceRelevanceVotes.add(singleSentenceVote);
                        }
                    }
                    mTurkRelevanceVotes.add(relevanceVote);
                }
            }

        }
        File outputFile = new File(outputDir, f.getName());
        FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8");
        System.out.println("Finished " + outputFile);
    }

}

From source file:com.act.biointerpretation.ProductExtractor.java

public static void main(String[] args) throws Exception {
    CLIUtil cliUtil = new CLIUtil(ProductExtractor.class, HELP_MESSAGE, OPTION_BUILDERS);
    CommandLine cl = cliUtil.parseCommandLine(args);

    String orgPrefix = cl.getOptionValue(OPTION_ORGANISM_PREFIX);
    LOGGER.info("Using organism prefix %s", orgPrefix);

    MongoDB db = new MongoDB(DEFAULT_DB_HOST, DEFAULT_DB_PORT, cl.getOptionValue(OPTION_DB_NAME));

    Map<Long, String> validOrganisms = new TreeMap<>();
    DBIterator orgIter = db.getDbIteratorOverOrgs();
    Organism o = null;// ww  w. j  ava2s .c  om
    while ((o = db.getNextOrganism(orgIter)) != null) {
        if (!o.getName().isEmpty() && o.getName().startsWith(orgPrefix)) {
            validOrganisms.put(o.getUUID(), o.getName());
        }
    }

    LOGGER.info("Found %d valid organisms", validOrganisms.size());

    Set<Long> productIds = new TreeSet<>(); // Use something with implicit ordering we can traverse in order.
    DBIterator reactionIterator = db.getIteratorOverReactions();
    Reaction r;
    while ((r = db.getNextReaction(reactionIterator)) != null) {
        Set<JSONObject> proteins = r.getProteinData();
        boolean valid = false;
        for (JSONObject j : proteins) {
            if (j.has("organism") && validOrganisms.containsKey(j.getLong("organism"))) {
                valid = true;
                break;
            } else if (j.has("organisms")) {
                JSONArray organisms = j.getJSONArray("organisms");
                for (int i = 0; i < organisms.length(); i++) {
                    if (validOrganisms.containsKey(organisms.getLong(i))) {
                        valid = true;
                        break;
                    }
                }
            }
        }

        if (valid) {
            for (Long id : r.getProducts()) {
                productIds.add(id);
            }
            for (Long id : r.getProductCofactors()) {
                productIds.add(id);
            }
        }
    }

    LOGGER.info("Found %d valid product ids for '%s'", productIds.size(), orgPrefix);
    PrintWriter writer = cl.hasOption(OPTION_OUTPUT_FILE)
            ? new PrintWriter(new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE)))
            : new PrintWriter(System.out);

    for (Long id : productIds) {
        Chemical c = db.getChemicalFromChemicalUUID(id);
        String inchi = c.getInChI();
        if (inchi.startsWith("InChI=") && !inchi.startsWith("InChI=/FAKE")) {
            writer.println(inchi);
        }
    }

    if (cl.hasOption(OPTION_OUTPUT_FILE)) {
        writer.close();
    }
    LOGGER.info("Done.");
}

From source file:com.github.fritaly.svngraph.SvnGraph.java

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.out.println(String.format("%s <input-file> <output-file>", SvnGraph.class.getSimpleName()));
        System.exit(1);/*from w ww .  j  ava  2s.c  om*/
    }

    final File input = new File(args[0]);

    if (!input.exists()) {
        throw new IllegalArgumentException(
                String.format("The given file '%s' doesn't exist", input.getAbsolutePath()));
    }

    final File output = new File(args[1]);

    final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);

    final History history = new History(document);

    final Set<String> rootPaths = history.getRootPaths();

    System.out.println(rootPaths);

    for (String path : rootPaths) {
        System.out.println(path);
        System.out.println(history.getHistory(path).getRevisions());
        System.out.println();
    }

    int count = 0;

    FileWriter fileWriter = null;
    GraphMLWriter graphWriter = null;

    try {
        fileWriter = new FileWriter(output);

        graphWriter = new GraphMLWriter(fileWriter);

        final NodeStyle tagStyle = graphWriter.getNodeStyle();
        tagStyle.setFillColor(Color.WHITE);

        graphWriter.graph();

        // map associating node labels to their corresponding node id in the graph
        final Map<String, String> nodeIdsPerLabel = new TreeMap<>();

        // the node style associated to each branch
        final Map<String, NodeStyle> nodeStyles = new TreeMap<>();

        for (Revision revision : history.getSignificantRevisions()) {
            System.out.println(revision.getNumber() + " - " + revision.getMessage());

            // TODO Render also the deletion of branches
            // there should be only 1 significant update per revision (the one with action ADD)
            for (Update update : revision.getSignificantUpdates()) {
                if (update.isCopy()) {
                    // a merge is also considered a copy
                    final RevisionPath source = update.getCopySource();

                    System.out.println(String.format("  > %s %s from %s@%d", update.getAction(),
                            update.getPath(), source.getPath(), source.getRevision()));

                    final String sourceRoot = Utils.getRootName(source.getPath());

                    if (sourceRoot == null) {
                        // skip the revisions whose associated root is
                        // null (happens whether a branch was created
                        // outside the 'branches' directory for
                        // instance)
                        System.err.println(String.format("Skipped revision %d because of a null root",
                                source.getRevision()));
                        continue;
                    }

                    final String sourceLabel = computeNodeLabel(sourceRoot, source.getRevision());

                    // create a node for the source (path, revision)
                    final String sourceId;

                    if (nodeIdsPerLabel.containsKey(sourceLabel)) {
                        // retrieve the id of the existing node
                        sourceId = nodeIdsPerLabel.get(sourceLabel);
                    } else {
                        // create the new node
                        if (Utils.isTagPath(source.getPath())) {
                            graphWriter.setNodeStyle(tagStyle);
                        } else {
                            if (!nodeStyles.containsKey(sourceRoot)) {
                                final NodeStyle style = new NodeStyle();
                                style.setFillColor(randomColor());

                                nodeStyles.put(sourceRoot, style);
                            }

                            graphWriter.setNodeStyle(nodeStyles.get(sourceRoot));
                        }

                        sourceId = graphWriter.node(sourceLabel);

                        nodeIdsPerLabel.put(sourceLabel, sourceId);
                    }

                    // and another for the newly created directory
                    final String targetRoot = Utils.getRootName(update.getPath());

                    if (targetRoot == null) {
                        System.err.println(String.format("Skipped revision %d because of a null root",
                                revision.getNumber()));
                        continue;
                    }

                    final String targetLabel = computeNodeLabel(targetRoot, revision.getNumber());

                    if (Utils.isTagPath(update.getPath())) {
                        graphWriter.setNodeStyle(tagStyle);
                    } else {
                        if (!nodeStyles.containsKey(targetRoot)) {
                            final NodeStyle style = new NodeStyle();
                            style.setFillColor(randomColor());

                            nodeStyles.put(targetRoot, style);
                        }

                        graphWriter.setNodeStyle(nodeStyles.get(targetRoot));
                    }

                    final String targetId;

                    if (nodeIdsPerLabel.containsKey(targetLabel)) {
                        // retrieve the id of the existing node
                        targetId = nodeIdsPerLabel.get(targetLabel);
                    } else {
                        // create the new node
                        if (Utils.isTagPath(update.getPath())) {
                            graphWriter.setNodeStyle(tagStyle);
                        } else {
                            if (!nodeStyles.containsKey(targetRoot)) {
                                final NodeStyle style = new NodeStyle();
                                style.setFillColor(randomColor());

                                nodeStyles.put(targetRoot, style);
                            }

                            graphWriter.setNodeStyle(nodeStyles.get(targetRoot));
                        }

                        targetId = graphWriter.node(targetLabel);

                        nodeIdsPerLabel.put(targetLabel, targetId);
                    }

                    // create an edge between the 2 nodes
                    graphWriter.edge(sourceId, targetId);
                } else {
                    System.out.println(String.format("  > %s %s", update.getAction(), update.getPath()));
                }
            }

            System.out.println();

            count++;
        }

        // Dispatch the revisions per corresponding branch
        final Map<String, Set<Long>> revisionsPerBranch = new TreeMap<>();

        for (String nodeLabel : nodeIdsPerLabel.keySet()) {
            if (nodeLabel.contains("@")) {
                final String branchName = StringUtils.substringBefore(nodeLabel, "@");
                final long revision = Long.parseLong(StringUtils.substringAfter(nodeLabel, "@"));

                if (!revisionsPerBranch.containsKey(branchName)) {
                    revisionsPerBranch.put(branchName, new TreeSet<Long>());
                }

                revisionsPerBranch.get(branchName).add(revision);
            } else {
                throw new IllegalStateException(nodeLabel);
            }
        }

        // Recreate the missing edges between revisions from a same branch
        for (String branchName : revisionsPerBranch.keySet()) {
            final List<Long> branchRevisions = new ArrayList<>(revisionsPerBranch.get(branchName));

            for (int i = 0; i < branchRevisions.size() - 1; i++) {
                final String nodeLabel1 = String.format("%s@%d", branchName, branchRevisions.get(i));
                final String nodeLabel2 = String.format("%s@%d", branchName, branchRevisions.get(i + 1));

                graphWriter.edge(nodeIdsPerLabel.get(nodeLabel1), nodeIdsPerLabel.get(nodeLabel2));
            }
        }

        graphWriter.closeGraph();

        System.out.println(String.format("Found %d significant revisions", count));
    } finally {
        if (graphWriter != null) {
            graphWriter.close();
        }
        if (fileWriter != null) {
            fileWriter.close();
        }
    }

    System.out.println("Done");
}

From source file:Main.java

public static final <E> SortedSet<E> newTreeSet() {
    return new TreeSet<E>();
}

From source file:Main.java

@SafeVarargs
public static <E> Set<E> $s(E... ee) {
    Set<E> set = new TreeSet<>();
    for (E e : ee) {
        set.add(e);//from   ww w  .  ja v a  2 s.  c o  m
    }
    return set;
}

From source file:Main.java

public static TreeSet copySet(List ls) {
    TreeSet s = new TreeSet();
    s.addAll(ls);
    return s;
}

From source file:Main.java

@Deprecated
// use com.google.common.collect.Sets.newTreeSet
public static <T> TreeSet<T> newTreeSet() {
    return new TreeSet<T>();
}