Example usage for java.util ListIterator next

List of usage examples for java.util ListIterator next

Introduction

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

Prototype

E next();

Source Link

Document

Returns the next element in the list and advances the cursor position.

Usage

From source file:com.xmobileapp.rockplayer.LastFmEventImporter.java

/*********************************
 * //from w  ww.jav a 2  s  . c  o  m
 * Get Artist Events
 * @throws SAXException 
 * @throws ParserConfigurationException 
 *
 *********************************/
public void getArtistEvents() throws SAXException, ParserConfigurationException {
    /*
     * Initialize Artist Cursor
     */
    artistCursor = ((RockPlayer) context).contentResolver.query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
            ((RockPlayer) context).ARTIST_COLS, // we should minimize the number of columns
            null, // all albums 
            null, // parameters to the previous parameter - which is null also 
            null // sort order, SQLite-like
    );

    /*
     * Declare & Initialize some vars
     */
    String artistName = null;
    String artistNameFiltered = null;
    String artistConcertFileName = null;
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    XMLArtistEventHandler xmlHandler = new XMLArtistEventHandler();
    xmlHandler.myLocation = this.myLocation;
    xmlReader.setContentHandler(xmlHandler);

    /*
     * Set Distance Limit
     */
    xmlHandler.MAX_DISTANCE = this.concertRadius;

    /*
     * Loop through the artists
     */
    artistCursor.moveToFirst();
    for (int i = 0; i < artistCursor.getCount(); i++) {
        /*
         * Get artist name
         */
        artistName = artistCursor.getString(artistCursor.getColumnIndex(MediaStore.Audio.Artists.ARTIST));
        if (artistName.equals("<unknown>")) {
            artistCursor.moveToNext();
            continue;
        }
        artistNameFiltered = filterString(artistName);
        artistConcertFileName = ((RockPlayer) context).FILEX_CONCERT_PATH + validateFileName(artistName);

        /*
         * UI feedback
         */
        Bundle data = new Bundle();
        data.putString("info", artistName);
        Message msg = new Message();
        msg.setData(data);
        ((RockPlayer) context).analyseConcertInfoHandler.sendMessage(msg);

        /*
         * If we dont have yet or info is too old, update the concert info of this artist
         */
        if (hasConcertInfo(artistName) == false || concertInfoNeedsUpdate(artistName) == true) {
            Log.i("INET", "Getting concert info from LastFM");
            if (hasConcertInfo(artistName) == false)
                Log.i("INET", "Because there is no concert info yet");
            if (concertInfoNeedsUpdate(artistName) == true)
                Log.i("INET", "Because Info is too old");

            File artistConcertFile = new File(artistConcertFileName);
            if (!artistConcertFile.exists()) {
                try {
                    artistConcertFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            URL lastFmApiRequest;
            try {
                lastFmApiRequest = new URL(
                        this.LAST_FM_API_URL + "&artist=" + URLEncoder.encode(artistNameFiltered));
                BufferedInputStream bufferedURLStream = new BufferedInputStream(lastFmApiRequest.openStream());
                BufferedOutputStream bufferedFileWriter = new BufferedOutputStream(
                        new FileOutputStream(artistConcertFile));

                byte[] buf = new byte[1024];
                int len;
                while ((len = bufferedURLStream.read(buf)) >= 0)
                    bufferedFileWriter.write(buf, 0, len);
                bufferedURLStream.close();
                bufferedFileWriter.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        /*
         * get event list from cached XML files
         */
        File artistConcertFile = new File(artistConcertFileName);
        if (artistConcertFile.exists() && artistConcertFile.length() > 0) {
            try {
                BufferedReader xmlFileReader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(artistConcertFile)));
                xmlHandler.resetList();
                xmlHandler.artist = artistName;
                xmlReader.parse(new InputSource(xmlFileReader));
                insertListInListByDate(xmlHandler.artistEventList);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        artistCursor.moveToNext();
    }

    /*
     * Debug
     */
    ArtistEvent artistEventDebug = null;
    if (!artistEventList.isEmpty()) {
        artistEventList.getFirst();
        ListIterator<ArtistEvent> listIterator = artistEventList.listIterator(0);
        for (artistEventDebug = listIterator.next(); listIterator
                .hasNext() == true; artistEventDebug = listIterator.next()) {
            if (artistEventDebug != null)
                Log.i("DBG", artistEventDebug.date + " " + artistEventDebug.city);
            //   Log.i("DBG", artistEventDebug.date+" "+artistEventDebug.city+" "+artistEventDebug.artist);
            else
                Log.i("DBG", "NULL");
        }
    }
    /*
     * Update Adapter
     */
    eventLinkedListAdapter = new EventLinkedListAdapter(context, R.layout.eventlist_item, artistEventList);
    if (eventLinkedListAdapter == null)
        Log.i("NULL", "NULL");
    ((RockPlayer) context).updateEventListHandler.sendEmptyMessage(0);

    /*
     * Give feedback to the user
     */
    Bundle data = new Bundle();
    Message msg = new Message();
    data.putString("info", "Done!");
    msg.setData(data);
    ((RockPlayer) context).analyseConcertInfoHandler.sendMessage(msg);
}

From source file:de.unisb.cs.st.javaslicer.tracer.instrumentation.PauseTracingInstrumenter.java

@SuppressWarnings("unchecked")
public void transformMethod(final MethodNode method, final ListIterator<MethodNode> methodIt,
        final String className) {
    if ((method.access & ACC_ABSTRACT) != 0 || (method.access & ACC_NATIVE) != 0)
        return;//  w  ww .  ja v a 2 s  . c  o  m

    int tracerLocalVarIndex = (method.access & Opcodes.ACC_STATIC) == 0 ? 1 : 0;
    for (final Type t : Type.getArgumentTypes(method.desc))
        tracerLocalVarIndex += t.getSize();

    // increment number of local variables by one (for the threadtracer)
    ++method.maxLocals;

    // and increment all local variable indexes after the new one by one
    for (final Object o : method.localVariables) {
        final LocalVariableNode localVar = (LocalVariableNode) o;
        if (localVar.index >= tracerLocalVarIndex)
            ++localVar.index;
    }
    final LabelNode l0 = new LabelNode();
    final LabelNode l1 = new LabelNode();

    final ListIterator<AbstractInsnNode> insnIt = method.instructions.iterator();

    insnIt.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(Tracer.class), "getInstance",
            "()L" + Type.getInternalName(Tracer.class) + ";"));
    insnIt.add(new MethodInsnNode(INVOKEVIRTUAL, Type.getInternalName(Tracer.class), "getThreadTracer",
            "()L" + Type.getInternalName(ThreadTracer.class) + ";"));
    insnIt.add(new InsnNode(DUP));
    insnIt.add(new VarInsnNode(ASTORE, tracerLocalVarIndex));
    insnIt.add(new MethodInsnNode(INVOKEINTERFACE, Type.getInternalName(ThreadTracer.class), "pauseTracing",
            "()V"));
    insnIt.add(l0);

    while (insnIt.hasNext()) {
        final AbstractInsnNode insn = insnIt.next();
        switch (insn.getType()) {
        case AbstractInsnNode.INSN:
            switch (insn.getOpcode()) {
            case IRETURN:
            case LRETURN:
            case FRETURN:
            case DRETURN:
            case ARETURN:
            case RETURN:
                insnIt.previous();
                insnIt.add(new VarInsnNode(ALOAD, tracerLocalVarIndex));
                insnIt.add(new MethodInsnNode(INVOKEINTERFACE, Type.getInternalName(ThreadTracer.class),
                        "resumeTracing", "()V"));
                insnIt.next();
            }
            break;
        case AbstractInsnNode.IINC_INSN:
            if (((IincInsnNode) insn).var >= tracerLocalVarIndex)
                ++((IincInsnNode) insn).var;
            break;
        case AbstractInsnNode.VAR_INSN:
            if (((VarInsnNode) insn).var >= tracerLocalVarIndex)
                ++((VarInsnNode) insn).var;
            break;
        default:
            break;
        }
    }

    method.instructions.add(l1);

    method.instructions.add(new VarInsnNode(ALOAD, tracerLocalVarIndex));
    method.instructions.add(new MethodInsnNode(INVOKEINTERFACE, Type.getInternalName(ThreadTracer.class),
            "resumeTracing", "()V"));
    method.instructions.add(new InsnNode(ATHROW));

    method.tryCatchBlocks.add(new TryCatchBlockNode(l0, l1, l1, null));

    // finally: create a copy of the method that gets the ThreadTracer as argument
    if (!"<clinit>".equals(method.name) && this.tracer.wasRedefined(className)) {
        final Type[] oldMethodArguments = Type.getArgumentTypes(method.desc);
        final Type[] newMethodArguments = Arrays.copyOf(oldMethodArguments, oldMethodArguments.length + 1);
        newMethodArguments[oldMethodArguments.length] = Type.getType(ThreadTracer.class);
        final String newMethodDesc = Type.getMethodDescriptor(Type.getReturnType(method.desc),
                newMethodArguments);
        final MethodNode newMethod = new MethodNode(method.access, method.name, newMethodDesc, method.signature,
                (String[]) method.exceptions.toArray(new String[method.exceptions.size()]));
        methodIt.add(newMethod);

        final Map<LabelNode, LabelNode> newMethodLabels = LazyMap.decorate(new HashMap<LabelNode, LabelNode>(),
                new Factory() {
                    @Override
                    public Object create() {
                        return new LabelNode();
                    }
                });

        // copy the local variables information to the new method
        for (final Object o : method.localVariables) {
            final LocalVariableNode lv = (LocalVariableNode) o;
            newMethod.localVariables.add(new LocalVariableNode(lv.name, lv.desc, lv.signature,
                    newMethodLabels.get(lv.start), newMethodLabels.get(lv.end), lv.index));
        }

        newMethod.maxLocals = method.maxLocals;
        newMethod.maxStack = method.maxStack;

        // copy the try-catch-blocks
        for (final Object o : method.tryCatchBlocks) {
            final TryCatchBlockNode tcb = (TryCatchBlockNode) o;
            newMethod.tryCatchBlocks.add(new TryCatchBlockNode(newMethodLabels.get(tcb.start),
                    newMethodLabels.get(tcb.end), newMethodLabels.get(tcb.handler), tcb.type));
        }

        // skip the first 4 instructions, replace them with this:
        newMethod.instructions.add(new VarInsnNode(ALOAD, tracerLocalVarIndex));
        final Iterator<AbstractInsnNode> oldInsnIt = method.instructions.iterator(4);
        // and add all the other instructions
        while (oldInsnIt.hasNext()) {
            final AbstractInsnNode insn = oldInsnIt.next();
            newMethod.instructions.add(insn.clone(newMethodLabels));
        }
    }
}

From source file:oscar.form.study.hsfo2.pageUtil.ManageHSFOAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    logger.info("ContextPath: " + request.getContextPath());
    logger.info("pathInfo: " + request.getPathInfo());
    Map<String, String[]> params = request.getParameterMap();

    Hsfo2Visit latestHsfo2Visit = new Hsfo2Visit();
    PatientList historyList = new PatientList();
    // RecordList record = new RecordList();
    List recordList = new LinkedList();

    String patientId = (String) request.getAttribute("demographic_no");
    if (patientId == null) {
        patientId = request.getParameter("demographic_no");
    }//  w w w. j a  v a2 s  .  c om
    String isfirstrecord = "";
    boolean isFirstRecord = false;
    String user = (String) request.getSession().getAttribute("user");

    HSFODAO hsfoDAO = new HSFODAO();
    isFirstRecord = hsfoDAO.isFirstRecord(patientId);

    DemographicData demoData = new DemographicData();
    //DemographicData.Demographic de = demoData.getDemographic( patientId );
    Demographic de = demoData.getDemographic(patientId);

    boolean isDisplayGraphs = "displayGraphs".equalsIgnoreCase(request.getParameter("operation"));

    boolean isFromRegistrationForm = false;
    if ("true".equalsIgnoreCase(request.getParameter("isFromRegistrationForm"))) {
        //true means the request is from registration form, should goto followup form
        isFromRegistrationForm = true;
    }

    FORM forwardToForm = null;
    int patientHistorySize = 0;
    boolean isFirstVisitRecordForThePatient = false;
    //    boolean isFromRegistrationForm = false;  

    Integer formId = getFormIdFromRequest(request);
    Hsfo2Visit formHsfo2Visit = null;
    if (formId != null)
        formHsfo2Visit = hsfoDAO.retrieveSelectedRecord(formId);
    boolean isHistoryForm = !isFromRegistrationForm && (formId != null && formHsfo2Visit != null);

    if (formId != null)
        isFirstVisitRecordForThePatient = hsfoDAO.isFirstVisitRecordForThePatient(patientId, formId);
    boolean isRegistForm = !isDisplayGraphs && !isFromRegistrationForm
            && (isFirstRecord || isFirstVisitRecordForThePatient);

    //prepare data
    Hsfo2Patient hsfo2Patient = hsfoDAO.retrievePatientRecord(patientId);
    if (hsfo2Patient == null)
        hsfo2Patient = new Hsfo2Patient();
    List patientHistory = hsfoDAO.retrieveVisitRecord(patientId);

    //save only or submit, it's for registration form and stay in that form
    boolean isSaveOnly = "Save".equalsIgnoreCase(request.getParameter("Save"));
    if (!isSaveOnly && !isFirstRecord) {
        isSaveOnly = !hsfo2Patient.isSubmitted();
    }

    if (isSaveOnly) {
        //stay in regist form and treat as history
        isRegistForm = true;
        isHistoryForm = true;
        if (patientHistory.size() > 0)
            formHsfo2Visit = (Hsfo2Visit) patientHistory.get(patientHistory.size() - 1);
    }

    if (isHistoryForm) {
        latestHsfo2Visit = formHsfo2Visit;
    } else // create new form
    {
        patientHistorySize = patientHistory.size();

        if (patientHistorySize >= 1) {
            latestHsfo2Visit = (Hsfo2Visit) patientHistory.get(patientHistorySize - 1);
            latestHsfo2Visit.setVisitDateIdToday();
            latestHsfo2Visit.setId(hsfoDAO.getMaxVisitId() + 1);
            cleanNonePrefilledData(latestHsfo2Visit);
            getLabWork(latestHsfo2Visit, hsfo2Patient, ConvertUtil.toInt(patientId));

            //If it's followup form, BP should not be prepopulated. Clean again.
            latestHsfo2Visit.setSBP(0);
            latestHsfo2Visit.setDBP(0);
        } else {
            latestHsfo2Visit = new Hsfo2Visit();
            latestHsfo2Visit.setVisitDateIdToday();
            getLabWork(latestHsfo2Visit, hsfo2Patient, ConvertUtil.toInt(patientId));
        }

    }

    if (isRegistForm) {
        // registration, get data from DemographicData;
        isfirstrecord = "true";

        hsfo2Patient.setPatient_Id(patientId);

        if (!isHistoryForm) {
            hsfo2Patient.setFName(de.getFirstName());
            hsfo2Patient.setLName(de.getLastName());
            hsfo2Patient.setBirthDate(oscar.util.DateUtils.toDate(de.getFormattedDob()));
            hsfo2Patient.setSex(de.getSex());
            hsfo2Patient.setPostalCode(de.getPostal());

            hsfo2Patient.setRegistrationId(HsfoUtil.getRegistrationId());
            latestHsfo2Visit.setVisitDateIdToday();
        }

        request.setAttribute("EmrHCPId1", user);
        request.setAttribute("EmrHCPId2", de.getProviderNo()); // TODO: may need to convert to provider name

        forwardToForm = FORM.registration;
    } else {
        //populate graphy data for followup form. the latestHsfo2Visit already keep the information of last visit.
        isfirstrecord = "false";

        if (!isDisplayGraphs)
            forwardToForm = FORM.flowsheet;
        else {
            // If patientHistory is greater than 1 than fill the graphing arrays
            TimeSeries sbpSeries = new TimeSeries("Systolic Blood Pressure", Day.class);
            TimeSeries dbpSeries = new TimeSeries("Diastolic Blood Pressure", Day.class);
            TimeSeries bmiSeries = new TimeSeries("BMI", Day.class);
            TimeSeries waistSeries = new TimeSeries("Waist", Day.class);
            TimeSeries ldlSeries = new TimeSeries("LDL", Day.class);
            TimeSeries tcHdlSeries = new TimeSeries("TC/HDL", Day.class);
            TimeSeries importanceSeries = new TimeSeries("Importance", Day.class);
            TimeSeries confidenceSeries = new TimeSeries("Confidence", Day.class);

            Map<GraphDesc, TimeSeries> graphDescSeriesMap = new HashMap<GraphDesc, TimeSeries>();
            graphDescSeriesMap.put(new GraphDesc("Systolic Blood Pressure", "Dates", "SBP(mmHg)"), sbpSeries);
            graphDescSeriesMap.put(new GraphDesc("Diastolic Blood Pressure", "Dates", "DBP(mmHg)"), dbpSeries);
            graphDescSeriesMap.put(new GraphDesc("BMI", "Dates", "BMI(kg/m2)"), bmiSeries);
            graphDescSeriesMap.put(new GraphDesc("Waist", "Dates", "Waist(cm)"), waistSeries);
            graphDescSeriesMap.put(new GraphDesc("LDL", "Dates", "LDL(mmol/L)"), ldlSeries);
            {
                GraphDesc tcHdlDesc = new GraphDesc("TC/HDL", "Dates", "TC/HDL(ratio)");
                tcHdlDesc.setFileName("TC_HDL");
                graphDescSeriesMap.put(tcHdlDesc, tcHdlSeries);
            }
            graphDescSeriesMap.put(new GraphDesc("Importance", "Dates", "Importance(1-10)"), importanceSeries);
            graphDescSeriesMap.put(new GraphDesc("Confidence", "Dates", "Confidence(1-10)"), confidenceSeries);

            if (patientHistorySize >= 1) {

                ListIterator patientHistoryIt = patientHistory.listIterator();
                //        int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0;
                while (patientHistoryIt.hasNext()) {
                    Hsfo2Visit Hsfo2Visit = (Hsfo2Visit) patientHistoryIt.next();
                    //          visitDateArray.add( setDateFull( Hsfo2Visit.getVisitDate_Id() ) );
                    //          visitIdArray.add( "" + Hsfo2Visit.getID() );

                    // ////////
                    final Date visitDate = Hsfo2Visit.getVisitDate_Id();
                    if (visitDate != null) {
                        final Day visitDay = new Day(visitDate);
                        if (Hsfo2Visit.getSBP() != 0) {
                            sbpSeries.addOrUpdate(visitDay, Hsfo2Visit.getSBP());
                        }

                        if (Hsfo2Visit.getDBP() != 0) {
                            dbpSeries.addOrUpdate(visitDay, Hsfo2Visit.getDBP());
                        }

                        if (Hsfo2Visit.getWeight() != 0) {
                            Double bmi = getBmi(Hsfo2Visit, hsfo2Patient);
                            if (bmi > 0)
                                bmiSeries.addOrUpdate(visitDay, bmi);
                        }
                        // modified by victor for waist_unit null bug,2007
                        // if (Hsfo2Visit.getWaist() != 0{
                        if (Hsfo2Visit.getWaist() != 0 && Hsfo2Visit.getWaist_unit() != null) {
                            double waistv = Hsfo2Visit.getWaist();
                            String waistunit = Hsfo2Visit.getWaist_unit();
                            double waist = 0.0;
                            if (waistunit.equals("cm")) {
                                waist = waistv;
                            } else {
                                // 1 inch = 2.54 cm
                                waist = waistv * 2.54;
                            }
                            waistSeries.addOrUpdate(visitDay, waist);
                        }

                        if (Hsfo2Visit.getChange_importance() != 0) {
                            importanceSeries.addOrUpdate(visitDay, Hsfo2Visit.getChange_importance());
                        }

                        if (Hsfo2Visit.getChange_confidence() != 0) {
                            confidenceSeries.addOrUpdate(visitDay, Hsfo2Visit.getChange_confidence());
                        }
                    }

                    final Date labResultDate = Hsfo2Visit.getTC_HDL_LabresultsDate();
                    if (labResultDate != null) {
                        final Day labResultDay = new Day(labResultDate);
                        if (Hsfo2Visit.getTC_HDL() != 0) {
                            tcHdlSeries.addOrUpdate(labResultDay, Hsfo2Visit.getTC_HDL());
                        }

                        if (Hsfo2Visit.getLDL() != 0) {
                            ldlSeries.addOrUpdate(labResultDay, Hsfo2Visit.getLDL());
                        }
                    }

                }

            }

            //generate the graph and export as picture.
            generateGraphs(request, response, graphDescSeriesMap);
            forwardToForm = FORM.graphs;
            ;
        }

    }

    historyList.setPatientHistory(patientHistory);

    // set request attributes to forward to jsp
    request.setAttribute("siteId", OscarProperties.getInstance().getProperty("hsfo2.loginSiteCode", "xxx"));

    request.setAttribute("Hsfo2Patient", hsfo2Patient);
    request.setAttribute("historyList", historyList);
    request.setAttribute("Hsfo2Visit", latestHsfo2Visit); //getDay() is date of week
    request.setAttribute("isFirstRecord", isfirstrecord);

    return mapping.findForward(forwardToForm.name());
}

From source file:com.projity.pm.criticalpath.CriticalPath.java

private void doPass(Task startTask, TaskSchedule.CalculationContext context) {
    if (startTask != null) {
        startTask.getSchedule(context.scheduleType).invalidate();
        startTask.setCalculationStateCount(getCalculationStateCount());
    }// w w w.j a  va  2  s.  c om

    PredecessorTaskList.TaskReference taskReference;
    boolean forward = context.forward;
    ListIterator i = forward ? predecessorTaskList.listIterator() : predecessorTaskList.reverseIterator();
    Task task;
    TaskSchedule schedule;

    //      int count = 0;
    //      long z = System.currentTimeMillis();
    boolean projectForward = project.isForward();
    while (forward ? i.hasNext() : i.hasPrevious()) {
        taskReference = (PredecessorTaskList.TaskReference) (forward ? i.next() : i.previous());
        traceTask = task = taskReference.getTask();
        context.taskReferenceType = taskReference.getType();
        schedule = task.getSchedule(context.scheduleType);
        if (!forward)
            context.taskReferenceType = -taskReference.getType();

        if (task.isReverseScheduled()) {//  reverse scheduled must always be calculated
            schedule.invalidate();
            task.setCalculationStateCount(context.stateCount);
        }
        if (task.getCalculationStateCount() >= context.stateCount) {
            schedule.calcDates(context);
            if (context.assign && (projectForward || !task.isWbsParent())) { // in reverse scheduling, I see some parents have 0 or 1 as their dates. This is a workaround.
                if (schedule.getBegin() != 0L && !isSentinel(task))
                    earliestStart = Math.min(earliestStart, schedule.getStart());
                if (schedule.getEnd() != 0 && !isSentinel(task))
                    latestFinish = Math.max(latestFinish, schedule.getFinish());
            }

            //            schedule.dump();
        }
    }
    //      System.out.println("pass forward=" + forward + " tasks:" + count + " time " + (System.currentTimeMillis() -z) + " ms");
}

From source file:playground.christoph.evacuation.analysis.EvacuationTimePictureWriter.java

public FolderType getLinkFolder(String transportMode, Map<Id, BasicLocation> locations,
        Map<Id, Double> evacuationTimes) throws IOException {

    calcMaxEvacuationTime(evacuationTimes);

    /*// w w w . ja  v  a  2 s  .  c o m
     * create Folders and connect them
     */
    FolderType mainFolder = this.kmlObjectFactory.createFolderType();
    FolderType linkFolder = this.kmlObjectFactory.createFolderType();
    FolderType facilityFolder = this.kmlObjectFactory.createFolderType();
    FolderType linkFolderA = this.kmlObjectFactory.createFolderType(); // 0 .. 10 valid Trips
    FolderType linkFolderB = this.kmlObjectFactory.createFolderType(); // 10 .. 100 valid Trips
    FolderType linkFolderC = this.kmlObjectFactory.createFolderType(); // 100 .. 1000 valid Trips
    FolderType linkFolderD = this.kmlObjectFactory.createFolderType(); // 1000 and more valid Trips
    FolderType facilityFolderA = this.kmlObjectFactory.createFolderType(); // 0 .. 10 valid Trips
    FolderType facilityFolderB = this.kmlObjectFactory.createFolderType(); // 10 .. 100 valid Trips
    FolderType facilityFolderC = this.kmlObjectFactory.createFolderType(); // 100 .. 1000 valid Trips
    FolderType facilityFolderD = this.kmlObjectFactory.createFolderType(); // 1000 and more valid Trips

    mainFolder.setName("Evacuation Times " + transportMode);
    linkFolder.setName("Links");
    facilityFolder.setName("Facilities");
    linkFolderA.setName("Links with 0..9 valid Trips");
    linkFolderB.setName("Links with 10..99 valid Trips");
    linkFolderC.setName("Links with 100..9 valid Trips");
    linkFolderD.setName("Links with 1000 and more valid Trips");
    facilityFolderA.setName("Facilities with 0..9 valid Trips");
    facilityFolderB.setName("Facilities with 10..99 valid Trips");
    facilityFolderC.setName("Facilities with 100..9 valid Trips");
    facilityFolderD.setName("Facilities with 1000 and more valid Trips");

    mainFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(linkFolder));
    mainFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(facilityFolder));
    linkFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(linkFolderA));
    linkFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(linkFolderB));
    linkFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(linkFolderC));
    linkFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(linkFolderD));
    facilityFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(facilityFolderA));
    facilityFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(facilityFolderB));
    facilityFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(facilityFolderC));
    facilityFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(facilityFolderD));

    /*
     * create overall histogram and add it to the kmz file
     */
    ScreenOverlayType histogram = createHistogram(transportMode, evacuationTimes);
    mainFolder.getAbstractFeatureGroup().add(kmlObjectFactory.createScreenOverlay(histogram));

    /*
     * create legend and add it to the kmz file
     */
    ScreenOverlayType legend = createLegend(transportMode);
    mainFolder.getAbstractFeatureGroup().add(kmlObjectFactory.createScreenOverlay(legend));

    Map<BasicLocation, List<Double>> locationMap = new HashMap<BasicLocation, List<Double>>();

    for (Entry<Id, BasicLocation> entry : locations.entrySet()) {
        Id id = entry.getKey();
        BasicLocation location = entry.getValue();

        List<Double> list = locationMap.get(location);
        if (list == null) {
            list = new ArrayList<Double>();
            locationMap.put(location, list);
        }

        Double value = evacuationTimes.get(id);
        if (value == null)
            value = Double.NaN;
        list.add(value);
    }

    log.info("Number of different start locations found: " + locationMap.size());

    if (doClustering) {
        EvacuationTimeClusterer clusterer = new EvacuationTimeClusterer(scenario.getNetwork(), locationMap,
                scenario.getConfig().global().getNumberOfThreads());
        int numClusters = (int) Math.ceil(locationMap.size() / clusterFactor);
        locationMap = clusterer.buildCluster(numClusters, clusterIterations);
    }

    for (Entry<BasicLocation, List<Double>> entry : locationMap.entrySet()) {
        BasicLocation location = entry.getKey();
        List<Double> list = entry.getValue();

        int valid = 0;
        int invalid = 0;

        /*
         * Remove NaN entries from the List
         */
        List<Double> listWithoutNaN = new ArrayList<Double>();
        for (Double d : list) {
            if (d.isNaN()) {
                invalid++;
            } else
                listWithoutNaN.add(d);
        }

        /*
         * If trip with significant to high evacuation times should be cut off
         */
        if (limitMaxEvacuationTime) {
            double cutOffValue = meanEvacuationTime + standardDeviation * evacuationTimeCutOffFactor;
            ListIterator<Double> iter = listWithoutNaN.listIterator();
            while (iter.hasNext()) {
                double value = iter.next();
                if (value > cutOffValue) {
                    iter.remove();
                    invalid++;
                }
            }
        }
        valid = list.size() - invalid;

        double mean = 0.0;
        for (Double d : list) {
            mean = mean + d;
        }
        mean = mean / list.size();

        // if at least one valid entry found - otherwise it would result in a divide by zero error
        if (listWithoutNaN.size() == 0)
            continue;
        //         if (invalid < list.size()) mean = mean / (list.size() - invalid);
        //         else continue;

        int index = getColorIndex(mean);

        StyleType styleType = colorBarStyles[index];

        PlacemarkType placemark = createPlacemark(transportMode, location, mean, valid, invalid);
        placemark.setStyleUrl(styleType.getId());
        if (location instanceof Facility) {
            if (valid < 10)
                facilityFolderA.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
            else if (valid < 100)
                facilityFolderB.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
            else if (valid < 1000)
                facilityFolderC.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
            else
                facilityFolderD.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));

        } else if (location instanceof Link) {
            if (valid < 10)
                linkFolderA.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
            else if (valid < 100)
                linkFolderB.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
            else if (valid < 1000)
                linkFolderC.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
            else
                linkFolderD.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
        } else {
            mainFolder.getAbstractFeatureGroup().add(this.kmlObjectFactory.createPlacemark(placemark));
        }

        histogramToKMZ(transportMode, location, listWithoutNaN);
        boxplotToKMZ(transportMode, location, listWithoutNaN);
    }

    return mainFolder;
}

From source file:marytts.modules.phonemiser.AllophoneSet.java

/**
 * Syllabify a string of allophones. If stress markers are provided, they are preserved; otherwise, primary stress will be
 * assigned to the initial syllable.//from w  w w. j  av a2  s . c  o m
 * <p>
 * The syllabification algorithm itself follows the <i>Core Syllabification Principle (CSP)</i> from <blockquote>G.N. Clements
 * (1990) "The role of the sonority cycle in core syllabification." In: J. Kingston &amp; M.E. Beckman (Eds.),
 * <em>Papers in Laboratory Phonology I: Between the Grammar and Physics of Speech</em>, Ch. 17, pp. 283-333, Cambridge
 * University Press.</blockquote>
 *
 * @param phoneString
 *            phoneString
 * @return a syllabified string; individual allophones are separated by spaces, and syllables, by dashes.
 * @throws IllegalArgumentException
 *             if the <b>phoneString</b> is empty or contains a symbol that satisfies none of the following conditions:
 *             <ol>
 *             <li>the symbol corresponds to an Allophone, or</li> <li>the symbol is a stress symbol (cf. {@link Stress}), or
 *             </li> <li>the symbol is a syllable boundary (<code>-</code>)</li>
 *             </ol>
 * 
 */
public String syllabify(String phoneString) throws IllegalArgumentException {
    // Before we process, a sanity check:
    if (phoneString.trim().isEmpty()) {
        throw new IllegalArgumentException("Cannot syllabify empty phone string");
    }

    // First, split phoneString into a List of allophone Strings...
    List<String> allophoneStrings = splitIntoAllophoneList(phoneString, true);
    // ...and create from it a List of generic Objects
    List<Object> phonesAndSyllables = new ArrayList<Object>(allophoneStrings);

    // Create an iterator
    ListIterator<Object> iterator = phonesAndSyllables.listIterator();

    // First iteration (left-to-right):
    // CSP (a): Associate each [+syllabic] segment to a syllable node.
    Syllable currentSyllable = null;
    while (iterator.hasNext()) {
        String phone = (String) iterator.next();
        try {
            // either it's an Allophone
            Allophone allophone = getAllophone(phone);
            if (allophone.isSyllabic()) {
                // if /6/ immediately follows a non-diphthong vowel, it should be appended instead of forming its own syllable
                boolean appendR = false;
                if (allophone.getFeature("ctype").equals("r")) {
                    // it's an /6/
                    if (iterator.previousIndex() > 1) {
                        Object previousPhoneOrSyllable = phonesAndSyllables.get(iterator.previousIndex() - 1);
                        if (previousPhoneOrSyllable == currentSyllable) {
                            // the /6/ immediately follows the current syllable
                            if (!currentSyllable.getLastAllophone().isDiphthong()) {
                                // the vowel immediately preceding the /6/ is not a diphthong
                                appendR = true;
                            }
                        }
                    }
                }
                if (appendR) {
                    iterator.remove();
                    currentSyllable.appendAllophone(allophone);
                } else {
                    currentSyllable = new Syllable(allophone);
                    iterator.set(currentSyllable);
                }
            }
        } catch (IllegalArgumentException e) {
            // or a stress or boundary marker
            if (!getIgnoreChars().contains(phone)) {
                throw e;
            }
        }
    }

    // Second iteration (right-to-left):
    // CSP (b): Given P (an unsyllabified segment) preceding Q (a syllabified segment), adjoin P to the syllable containing Q
    // iff P has lower sonority rank than Q (iterative).
    currentSyllable = null;
    boolean foundPrimaryStress = false;
    iterator = phonesAndSyllables.listIterator(phonesAndSyllables.size());
    while (iterator.hasPrevious()) {
        Object phoneOrSyllable = iterator.previous();
        if (phoneOrSyllable instanceof Syllable) {
            currentSyllable = (Syllable) phoneOrSyllable;
        } else if (currentSyllable == null) {
            // haven't seen a Syllable yet in this iteration
            continue;
        } else {
            String phone = (String) phoneOrSyllable;
            try {
                // it's an Allophone -- prepend to the Syllable
                Allophone allophone = getAllophone(phone);
                if (allophone.sonority() < currentSyllable.getFirstAllophone().sonority()) {
                    iterator.remove();
                    currentSyllable.prependAllophone(allophone);
                }
            } catch (IllegalArgumentException e) {
                // it's a provided stress marker -- assign it to the Syllable
                switch (phone) {
                case Stress.PRIMARY:
                    iterator.remove();
                    currentSyllable.setStress(Stress.PRIMARY);
                    foundPrimaryStress = true;
                    break;
                case Stress.SECONDARY:
                    iterator.remove();
                    currentSyllable.setStress(Stress.SECONDARY);
                    break;
                case "-":
                    iterator.remove();
                    // TODO handle syllable boundaries
                    break;
                default:
                    throw e;
                }
            }
        }
    }

    // Third iteration (left-to-right):
    // CSP (c): Given Q (a syllabified segment) followed by R (an unsyllabified segment), adjoin R to the syllable containing
    // Q iff has a lower sonority rank than Q (iterative).
    Syllable initialSyllable = currentSyllable;
    currentSyllable = null;
    iterator = phonesAndSyllables.listIterator();
    while (iterator.hasNext()) {
        Object phoneOrSyllable = iterator.next();
        if (phoneOrSyllable instanceof Syllable) {
            currentSyllable = (Syllable) phoneOrSyllable;
        } else {
            String phone = (String) phoneOrSyllable;
            try {
                // it's an Allophone -- append to the Syllable
                Allophone allophone;
                try {
                    allophone = getAllophone(phone);
                } catch (IllegalArgumentException e) {
                    // or a stress or boundary marker -- remove
                    if (getIgnoreChars().contains(phone)) {
                        iterator.remove();
                        continue;
                    } else {
                        throw e;
                    }
                }
                if (currentSyllable == null) {
                    // haven't seen a Syllable yet in this iteration
                    iterator.remove();
                    if (initialSyllable == null) {
                        // haven't seen any syllable at all
                        initialSyllable = new Syllable(allophone);
                        iterator.add(initialSyllable);
                    } else {
                        initialSyllable.prependAllophone(allophone);
                    }
                } else {
                    // append it to the last seen Syllable
                    iterator.remove();
                    currentSyllable.appendAllophone(allophone);
                }
            } catch (IllegalArgumentException e) {
                throw e;
            }
        }
    }

    // if primary stress was not provided, assign it to initial syllable
    if (!foundPrimaryStress) {
        initialSyllable.setStress(Stress.PRIMARY);
    }

    // join Syllables with dashes and return the String
    return StringUtils.join(phonesAndSyllables, " - ");
}

From source file:com.edgenius.wiki.render.macro.ProgressMacro.java

protected void replaceHTML(HTMLNode node, ListIterator<HTMLNode> iter, RenderContext context) {
    if (node.getPair() == null) {
        log.warn("Unexpect case: No close tag for " + this.getClass().getName());
        return;/*w ww. j  av  a  2 s.c  o m*/
    }
    node.getPair().reset("", true);

    String value = null, height = null, width = null, text = "";

    if (node.getStyle() != null) {
        height = node.getStyle().get("height");
        width = node.getStyle().get("width");
    }
    if (DEFAULT_HEIGHT.equalsIgnoreCase(height)) {
        height = null;
    }
    if (DEFAULT_WIDTH.equalsIgnoreCase(width)) {
        width = null;
    }

    //reset all inside node to blank
    //!!! Here changes ListIterator cursor position!!!
    HTMLNode reqireText = null;
    HTMLNode subnode;
    for (; iter.hasNext();) {
        subnode = iter.next();
        if (subnode == node.getPair())
            break;

        if (!subnode.isTextNode()) {
            if (subnode.getAttributes() != null) {
                if (subnode.getAttributes().get("class").equalsIgnoreCase("value")
                        && subnode.getStyle() != null) {
                    value = subnode.getStyle().get("width");
                } else if (subnode.getAttributes().get("class").equalsIgnoreCase("text")) {
                    reqireText = subnode.getPair();
                }
            }
            if (reqireText != null && reqireText == subnode) {
                reqireText = null;
            }
            subnode.reset("", true);
            if (subnode.getPair() != null)
                subnode.getPair().reset("", true);
        } else {
            if (reqireText != null) {
                text += subnode.getText();
            }
            subnode.reset("", true);
        }
    }

    if (DEFAULT_VALUE.equalsIgnoreCase(value)) {
        value = null;
    }

    StringBuffer sb = new StringBuffer("{progress");
    boolean dirty = false;
    if (value != null) {
        dirty = true;
        sb.append(":complete=").append(value);
    }
    if (width != null) {
        sb.append(dirty ? "|" : ":").append("width=").append(GwtUtils.removeUnit(width));
        dirty = true;
    }
    if (height != null) {
        sb.append(dirty ? "|" : ":").append("height=").append(GwtUtils.removeUnit(height));
        dirty = true;
    }
    if (!StringUtils.isBlank(text)) {
        sb.append(dirty ? "|" : ":").append("text=").append(text.trim());
        dirty = true;
    }
    sb.append("}");

    node.reset(sb.toString(), true);
}

From source file:ipnat.skel.Strahler.java

/**
 * This method is called when the plugin is loaded.
 *
 * @param arg//w ww.  j av a 2 s  . co  m
 *            the arguments as specified in {@code plugins.config}
 *
 */
@Override
public void run(final String arg) {

    // Retrieve analysis image and its ROI
    srcImp = WindowManager.getCurrentImage();
    if (!validRequirements(srcImp))
        return;

    title = srcImp.getTitle();
    rootRoi = srcImp.getRoi();
    validRootRoi = (rootRoi != null && rootRoi.getType() == Roi.RECTANGLE);

    // TODO: 3D Roots are special. We need to:
    // 1) Check if ROI is associated with all slices or just one
    // 2) Ignore counts above/below the ROI, as needed
    // 3) Extend ip operations to stack
    if (srcImp.getNSlices() > 1) {
        final String warning = "3D images are currently supported with the following limitations:\n"
                + "    - 'Root-protecting' ROIs are not yet supported\n"
                + "    - Lengths are estimated from Z-projections\n \n"
                + "These issues will be addressed in future releases.";
        if (IJ.macroRunning())
            IJ.log(warning);
        else
            IJ.showMessage("Warning", warning);
        validRootRoi = false;
    }

    // Retrieve grayscale image for intensity-based pruning of skel. loops
    if (!getSettings())
        return;

    // Work on a skeletonized copy since we'll be modifing the image
    if (rootRoi != null)
        srcImp.killRoi();
    final ImagePlus imp = srcImp.duplicate();
    if (rootRoi != null)
        srcImp.setRoi(rootRoi);
    ip = imp.getProcessor();
    skeletonizeWithoutHermits(imp);

    // Initialize ResultsTable: main and detailed info
    final ResultsTable rt = Utils.getTable(STRAHLER_TABLE);
    final ResultsTable logrt = Utils.getTable(VERBOSE_TABLE);

    // Analyze root
    ImagePlus rootImp;
    ImageProcessor rootIp = null;
    SkeletonResult rootResult = null;
    ArrayList<Point> rootEndpointsList = null;
    int nRootEndpoints = 0, nRootJunctions = 0;

    if (validRootRoi && verbose) {

        // Duplicate entire canvas. Ignore tree(s) outside ROI
        rootImp = imp.duplicate();
        rootIp = rootImp.getProcessor();
        rootIp.setValue(0.0);
        rootIp.fillOutside(rootRoi);

        // Get root properties
        final AnalyzeSkeleton_ root = new AnalyzeSkeleton_();
        root.setup("", rootImp);
        rootResult = root.run(pruneChoice, false, false, grayscaleImp, true, false);
        rootImp.flush();

        // We assume ROI contains only end-point branches, slab voxels and
        // no junction points. We'll thus remove end-points at ROI
        // boundaries
        nRootJunctions = sum(rootResult.getJunctions());
        rootEndpointsList = rootResult.getListOfEndPoints();
        final ListIterator<Point> it = rootEndpointsList.listIterator();
        final Rectangle r = rootRoi.getBounds();
        while (it.hasNext()) {
            final Point p = it.next();
            if (p.x == r.x || p.y == r.y || p.x == (int) (r.x + r.getWidth() - 1)
                    || p.y == (int) (r.y + r.getHeight() - 1))
                it.remove();
        }
        rootResult.setListOfEndPoints(rootEndpointsList);
        nRootEndpoints = rootEndpointsList.size();

    }

    // Initialize display images. Use Z-projections to populate
    // iteration stack when dealing with 3D skeletons
    final int nSlices = imp.getNSlices();
    ZProjector zp = null;

    final ImageStack iterationStack = new ImageStack(imp.getWidth(), imp.getHeight());
    if (nSlices > 1) {
        zp = new ZProjector(imp);
        zp.setMethod(ZProjector.MAX_METHOD);
        zp.setStartSlice(1);
        zp.setStopSlice(nSlices);
    }

    // Initialize AnalyzeSkeleton_
    final AnalyzeSkeleton_ as = new AnalyzeSkeleton_();
    as.setup("", imp);

    // Perform the iterative pruning
    int order = 1, nEndpoints = 0, nJunctions = 0, nJunctions2 = 0;
    ArrayList<Point> endpointsList = null, junctionsList = null;
    String errorMsg = "";

    do {

        IJ.showStatus("Retrieving measurements for order " + order + "...");
        IJ.showProgress(order, getMaxOrder());

        // (Re)skeletonize image
        if (order > 1)
            skeletonizeWithoutHermits(imp);

        // Get properties of loop-resolved tree(s)
        final SkeletonResult sr = as.run(pruneChoice, false, false, grayscaleImp, true, false);
        nEndpoints = sum(sr.getEndPoints());
        nJunctions = sum(sr.getJunctions());

        if (order == 1) {
            // Remember initial properties
            endpointsList = sr.getListOfEndPoints();
            junctionsList = sr.getListOfJunctionVoxels();

            // Do not include root in 1st order calculations
            nEndpoints -= nRootEndpoints;
            nJunctions -= nRootJunctions;
        }

        // Is it worth proceeding?
        if (nEndpoints == 0 || nJunctions2 == nJunctions) {
            errorMsg = "Error! Iteration " + order + " aborted: ";
            errorMsg += (nEndpoints == 0) ? "No end-poins found" : "Unsolved loop(s) detected";
            break;
        }

        // Add current tree(s) to debug animation
        ImageProcessor ipd;
        if (nSlices > 1) {
            zp.doProjection();
            ipd = zp.getProjection().getProcessor();
        } else {
            ipd = ip.duplicate();
        }
        iterationStack.addSlice("Order " + IJ.pad(order, 2), ipd);

        // Report properties of pruned structures
        if (verbose) {
            logrt.incrementCounter();
            logrt.addValue("Image", title);
            logrt.addValue("Structure", "Skel. at iteration " + Integer.toString(order));
            logrt.addValue("Notes", errorMsg);
            logrt.addValue("# Trees", sr.getNumOfTrees());
            logrt.addValue("# Branches", sum(sr.getBranches()));
            logrt.addValue("# End-points", nEndpoints);
            logrt.addValue("# Junctions", nJunctions);
            logrt.addValue("# Triple points", sum(sr.getTriples()));
            logrt.addValue("# Quadruple points", sum(sr.getQuadruples()));
            logrt.addValue("Average branch length", average(sr.getAverageBranchLength()));
        }

        // Remember main results
        nJunctions2 = nJunctions;

        // Eliminate end-points
        as.run(pruneChoice, true, false, grayscaleImp, true, false, rootRoi);

    } while (order++ <= getMaxOrder() && nJunctions > 0);

    // Set counter to the de facto order
    order -= 1;

    // Append root properties to log table
    if (validRootRoi && verbose) {

        // Check if ROI contains unexpected structures
        final String msg = (nRootJunctions > 0) ? "Warning: ROI contains ramified root(s)"
                : "Root-branches inferred from ROI";
        logrt.incrementCounter();
        logrt.addValue("Image", title);
        logrt.addValue("Structure", "Root");
        logrt.addValue("Notes", msg);
        logrt.addValue("# Trees", rootResult.getNumOfTrees());
        logrt.addValue("# Branches", sum(rootResult.getBranches()));
        logrt.addValue("# End-points", nRootEndpoints);
        logrt.addValue("# Junctions", nRootJunctions);
        logrt.addValue("# Triple points", sum(rootResult.getTriples()));
        logrt.addValue("# Quadruple points", sum(rootResult.getQuadruples()));
        logrt.addValue("Average branch length", average(rootResult.getAverageBranchLength()));

    }

    // Safety check
    if (iterationStack == null || iterationStack.getSize() < 1) {
        error("Enable \"detailed\" mode and check " + VERBOSE_TABLE + " for details.");
        return;
    }

    // Create iteration stack
    final Calibration cal = srcImp.getCalibration();
    final ImagePlus imp2 = new ImagePlus("StrahlerIteration_" + title, iterationStack);
    imp2.setCalibration(cal);
    if (outIS) {
        if (validRootRoi) {
            iterationStack.addSlice("Root", rootIp);
            paintPoints(iterationStack, rootEndpointsList, 255, "Root end-points");
            imp2.setRoi(rootRoi);
        }
        paintPoints(iterationStack, endpointsList, 255, "End-points");
        paintPoints(iterationStack, junctionsList, 255, "Junction-points");
    }

    // Generate Strahler mask
    zp = new ZProjector(imp2);
    zp.setMethod(ZProjector.SUM_METHOD);
    zp.setStartSlice(1);
    zp.setStopSlice(order);
    zp.doProjection();
    final ImageProcessor ip3 = zp.getProjection().getProcessor().convertToShortProcessor(false);
    clearPoints(ip3, junctionsList); // disconnect branches
    ip3.multiply(1 / 255.0); // map intensities to Strahler orders
    final ImagePlus imp3 = new ImagePlus("StrahlerMask_" + title, ip3);
    imp3.setCalibration(cal);

    // Measure segmented orders
    double prevNbranches = Double.NaN;
    for (int i = 1; i <= order; i++) {

        // Segment branches by order
        final ImagePlus maskImp = imp3.duplicate(); // Calibration is
        // retained
        IJ.setThreshold(maskImp, i, i);
        IJ.run(maskImp, "Convert to Mask", "");

        // Analyze segmented order
        final AnalyzeSkeleton_ maskAs = new AnalyzeSkeleton_();
        maskAs.setup("", maskImp);
        final SkeletonResult maskSr = maskAs.run(pruneChoice, false, false, grayscaleImp, true, false);
        maskImp.flush();

        // Since all branches are disconnected at this stage, the n. of
        // branches is
        // the same as the # the trees unless zero-branches trees exist,
        // i.e., trees
        // with no slab voxels (defined by just an end-point). We will
        // ignore those
        // trees if the user requested it
        final int nBranches = (erodeIsolatedPixels) ? sum(maskSr.getBranches()) : maskSr.getNumOfTrees();

        // Log measurements
        rt.incrementCounter();
        rt.addValue("Image", title);
        rt.addValue("Strahler Order", i);
        rt.addValue("# Branches", nBranches);
        rt.addValue("Ramification ratios", prevNbranches / nBranches);
        rt.addValue("Average branch length", average(maskSr.getAverageBranchLength()));
        rt.addValue("Unit", cal.getUnit());
        String noteMsg = "";
        if (i == 1) {
            noteMsg = (erodeIsolatedPixels) ? "Ignoring" : "Including";
            noteMsg += " single-point arbors...";
        }
        rt.addValue("Notes", noteMsg);

        // Remember results for previous order
        prevNbranches = nBranches;

    }

    // Append any errors to last row
    rt.addValue("Notes", errorMsg);

    // Display outputs
    if (!tabular) {
        if (outIS)
            imp2.show();
        ip3.setMinAndMax(0, order);
        ColorMaps.applyMagmaColorMap(imp3, 200, false);
        if (validRootRoi)
            imp3.setRoi(rootRoi);
        imp3.show();
        addCalibrationBar(imp3, Math.min(order, 5), "Black");
    }
    if (verbose)
        logrt.show(VERBOSE_TABLE);
    rt.show(STRAHLER_TABLE);

    IJ.showProgress(0, 0);
    IJ.showTime(imp, imp.getStartTime(), "Strahler Analysis concluded... ");
    imp.flush();

}

From source file:com.ibm.asset.trails.action.ShowConfirmation.java

@UserRole(userRole = UserRoleType.READER)
public String deleteSelectedLicenses() {
    List<License> llLicense = getRecon().getLicenseList();
    ListIterator<License> lliLicense = null;
    License llTemp;/*w w w. j a v a  2 s  . c o  m*/

    List<Report> lReport = new ArrayList<Report>();
    lReport.add(new Report("License baseline", "licenseBaseline"));
    setReportList(lReport);

    if (llLicense == null) {
        llLicense = new ArrayList<License>();
    }

    for (String lsLicenseId : selectedLicenseId) {
        lliLicense = llLicense.listIterator();

        while (lliLicense.hasNext()) {
            llTemp = lliLicense.next();

            if (llTemp.getId().compareTo(Long.valueOf(lsLicenseId)) == 0) {
                lliLicense.remove();
                break;
            }
        }
    }

    getRecon().setLicenseList(llLicense);
    recon.setAutomated(automated);
    recon.setManual(manual);
    recon.setRunon(runon);
    if (getMaxLicenses() != null && getMaxLicenses().trim().length() > 0) {
        recon.setMaxLicenses(new Integer(maxLicenses));
    }
    recon.setPer(per);

    return "license";
}

From source file:com.impetus.kundera.query.KunderaQueryParser.java

private void buildFrom() {
    ListIterator<Expression> fromIter = null;
    if (query.isSelectStatement() && query.getSelectStatement().hasFromClause()) {
        FromClause fromClause = (FromClause) query.getSelectStatement().getFromClause();
        fromIter = fromClause.children().iterator();

    } else if (query.isUpdateStatement()) {
        fromIter = query.getUpdateStatement().getUpdateClause().children().iterator();

    }//from w w w  .  j  a v  a  2 s.  co m
    if (query.isDeleteStatement()) {
        fromIter = query.getDeleteStatement().getDeleteClause().children().iterator();

    }

    if (fromIter != null) {
        while (fromIter.hasNext()) {
            String textObj = fromIter.next().toActualText().trim();

            if (!StringUtils.isEmpty(textObj)) {
                query.setFrom(textObj);
                break;
            }

        }
    }
}