Example usage for java.util TreeMap pollFirstEntry

List of usage examples for java.util TreeMap pollFirstEntry

Introduction

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

Prototype

public Map.Entry<K, V> pollFirstEntry() 

Source Link

Usage

From source file:beproject.MainGUI.java

void createTagCloud() throws SQLException {
    TreeMap tmp = getFrequentWords();
    Cloud cld = new Cloud();
    JPanel tmpPanel = new JPanel();
    FlowLayout t1 = new FlowLayout();
    tmpPanel.setPreferredSize(new Dimension(512, 512));
    tmpPanel.setLayout(t1);//  w  w  w .  j  a  va  2 s .  c o  m
    tmpPanel.setBounds(0, 0, 512, 512);
    //FlowLayout lm=(FlowLayout) tmpPanel.getLayout();
    for (int i = 0; i < 40 && !tmp.isEmpty(); i++) {
        Map.Entry mp = tmp.pollFirstEntry();
        Tag t = new Tag((String) mp.getKey(), (int) (mp.getValue()));
        cld.addTag(t);
    }
    Random rand = new Random();
    for (Tag tag : cld.tags()) {
        final JLabel label = new JLabel(tag.getName());
        label.setOpaque(false);
        label.setFont(label.getFont().deriveFont(rand.nextFloat() * 39));
        label.setForeground(new Color(rand.nextInt()));
        tmpPanel.add(label);
    }
    if (tagCloudPanel == null) {
        tagCloudPanel = new JScrollPane(tmpPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    } else {
        jPanel3.remove(tagCloudPanel);
        jPanel3.validate();
        tagCloudPanel = new JScrollPane(tmpPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    }
    //tagCloudPanel.setLayout(new ScrollPaneLayout());
    //tagCloudPanel.setAutoscrolls(true);
    tmpPanel.validate();
    tagCloudPanel.validate();
    jPanel3.add(tagCloudPanel, BorderLayout.CENTER);
    jPanel3.validate();

}

From source file:com.joliciel.talismane.parser.TransitionBasedGlobalLearningParser.java

public List<ParseConfiguration> parseSentence(List<PosTagSequence> posTagSequences,
        FeatureWeightVector weightVector, RankingSolution correctSolution) {
    MONITOR.startTask("parseSentence");
    try {/*w w w  .  ja  v a 2 s  .c o  m*/
        long startTime = (new Date()).getTime();
        int maxAnalysisTimeMilliseconds = maxAnalysisTimePerSentence * 1000;
        int minFreeMemoryBytes = minFreeMemory * KILOBYTE;

        TokenSequence tokenSequence = posTagSequences.get(0).getTokenSequence();

        TreeMap<Integer, TreeSet<ParseConfiguration>> heaps = new TreeMap<Integer, TreeSet<ParseConfiguration>>();

        TreeSet<ParseConfiguration> heap0 = new TreeSet<ParseConfiguration>();
        for (PosTagSequence posTagSequence : posTagSequences) {
            // add an initial ParseConfiguration for each postag sequence
            ParseConfiguration initialConfiguration = this.getParserServiceInternal()
                    .getInitialConfiguration(posTagSequence);
            initialConfiguration.setScoringStrategy(new SimpleRankingScoringStrategy());
            initialConfiguration.setRankingScore(0.0);
            heap0.add(initialConfiguration);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Adding initial posTagSequence: " + posTagSequence);
            }
        }
        heaps.put(0, heap0);
        TreeSet<ParseConfiguration> backupHeap = null;

        TreeSet<ParseConfiguration> finalHeap = null;
        while (heaps.size() > 0) {
            Entry<Integer, TreeSet<ParseConfiguration>> heapEntry = heaps.firstEntry();
            TreeSet<ParseConfiguration> currentHeap = heapEntry.getValue();
            int currentHeapIndex = heapEntry.getKey();
            if (LOG.isTraceEnabled()) {
                LOG.trace("##### Polling next heap: " + heapEntry.getKey() + ", size: "
                        + heapEntry.getValue().size());
            }

            boolean finished = false;
            // systematically set the final heap here, just in case we exit "naturally" with no more heaps
            finalHeap = heapEntry.getValue();
            backupHeap = new TreeSet<ParseConfiguration>();

            // we jump out when either (a) all tokens have been attached or (b) we go over the max alloted time
            ParseConfiguration topConf = currentHeap.first();
            if (topConf.isTerminal()) {
                LOG.trace("Exiting with terminal heap: " + heapEntry.getKey() + ", size: "
                        + heapEntry.getValue().size());
                finished = true;
            }

            // check if we've gone over alloted time for this sentence
            long analysisTime = (new Date()).getTime() - startTime;
            if (maxAnalysisTimePerSentence > 0 && analysisTime > maxAnalysisTimeMilliseconds) {
                LOG.info("Parse tree analysis took too long for sentence: " + tokenSequence.getText());
                LOG.info("Breaking out after " + maxAnalysisTimePerSentence + " seconds.");
                finished = true;
            }

            // check if we've enough memory to process this sentence
            if (minFreeMemory > 0) {
                long freeMemory = Runtime.getRuntime().freeMemory();
                if (freeMemory < minFreeMemoryBytes) {
                    LOG.info("Not enough memory left to parse sentence: " + tokenSequence.getText());
                    LOG.info("Min free memory (bytes):" + minFreeMemoryBytes);
                    LOG.info("Current free memory (bytes): " + freeMemory);
                    finished = true;
                }
            }

            // check if any of the remaining top-N solutions on any heap can lead to the correct solution
            if (correctSolution != null) {
                boolean canReachCorrectSolution = false;
                for (TreeSet<ParseConfiguration> heap : heaps.values()) {
                    int j = 1;
                    for (ParseConfiguration solution : heap) {
                        if (j > beamWidth)
                            break;
                        if (solution.canReach(correctSolution)) {
                            canReachCorrectSolution = true;
                            break;
                        }
                        j++;
                    }
                    if (canReachCorrectSolution)
                        break;
                }
                if (!canReachCorrectSolution) {
                    LOG.debug("None of the solutions on the heap can reach the gold solution. Exiting.");
                    finished = true;
                }
            }

            if (finished) {
                // combine any remaining heaps
                for (TreeSet<ParseConfiguration> heap : heaps.values()) {
                    if (finalHeap != heap) {
                        finalHeap.addAll(heap);
                    }
                }
                break;
            }

            // remove heap from set of heaps
            heapEntry = heaps.pollFirstEntry();

            // limit the breadth to K
            int maxSolutions = currentHeap.size() > this.beamWidth ? this.beamWidth : currentHeap.size();

            int j = 0;
            while (currentHeap.size() > 0) {
                ParseConfiguration history = currentHeap.pollFirst();
                backupHeap.add(history);
                if (LOG.isTraceEnabled()) {
                    LOG.trace("### Next configuration on heap " + heapEntry.getKey() + ":");
                    LOG.trace(history.toString());
                    LOG.trace("Score: " + df.format(history.getScore()));
                    LOG.trace(history.getPosTagSequence());
                }

                Set<Transition> transitions = new HashSet<Transition>();

                // test the positive rules on the current configuration
                boolean ruleApplied = false;
                if (parserPositiveRules != null) {
                    MONITOR.startTask("check rules");
                    try {
                        for (ParserRule rule : parserPositiveRules) {
                            if (LOG.isTraceEnabled()) {
                                LOG.trace("Checking rule: " + rule.getCondition().getName());
                            }
                            RuntimeEnvironment env = this.featureService.getRuntimeEnvironment();
                            FeatureResult<Boolean> ruleResult = rule.getCondition().check(history, env);
                            if (ruleResult != null && ruleResult.getOutcome()) {
                                transitions.add(rule.getTransition());
                                ruleApplied = true;
                                if (LOG.isTraceEnabled()) {
                                    LOG.trace("Rule applies. Setting transition to: "
                                            + rule.getTransition().getCode());
                                }

                                if (!rule.getTransition().checkPreconditions(history)) {
                                    LOG.error("Cannot apply rule, preconditions not met.");
                                    ruleApplied = false;
                                }
                                break;
                            }
                        }
                    } finally {
                        MONITOR.endTask("check rules");
                    }
                }

                if (!ruleApplied) {
                    transitions = parsingConstrainer.getPossibleTransitions(history);

                    Set<Transition> eliminatedTransitions = new HashSet<Transition>();
                    for (Transition transition : transitions) {
                        if (!transition.checkPreconditions(history)) {
                            eliminatedTransitions.add(transition);
                        }
                    }
                    transitions.removeAll(eliminatedTransitions);

                    // apply the negative rules
                    eliminatedTransitions = new HashSet<Transition>();
                    if (parserNegativeRules != null) {
                        MONITOR.startTask("check negative rules");
                        try {
                            for (ParserRule rule : parserNegativeRules) {
                                if (LOG.isTraceEnabled()) {
                                    LOG.trace("Checking negative rule: " + rule.getCondition().getName());
                                }
                                RuntimeEnvironment env = this.featureService.getRuntimeEnvironment();
                                FeatureResult<Boolean> ruleResult = rule.getCondition().check(history, env);
                                if (ruleResult != null && ruleResult.getOutcome()) {
                                    eliminatedTransitions.add(rule.getTransition());
                                    if (LOG.isTraceEnabled()) {
                                        LOG.debug("Rule applies. Eliminating transition: "
                                                + rule.getTransition().getCode());
                                    }
                                }
                            }

                            if (eliminatedTransitions.size() == transitions.size()) {
                                LOG.debug("All transitions eliminated! Restoring original transitions.");
                            } else {
                                transitions.removeAll(eliminatedTransitions);
                            }
                        } finally {
                            MONITOR.endTask("check negative rules");
                        }
                    }
                } // has a positive rule been applied?

                if (transitions.size() == 0) {
                    // just in case the we run out of both heaps and analyses, we build this backup heap
                    backupHeap.add(history);
                    if (LOG.isTraceEnabled())
                        LOG.trace(
                                "No transitions could be applied: not counting this solution as part of the beam");
                } else {
                    // up the counter, since we will count this solution towards the heap
                    j++;
                    // add solutions to the heap, one per valid transition
                    MONITOR.startTask("heap sort");
                    try {
                        Map<Transition, Double> deltaScorePerTransition = new HashMap<Transition, Double>();
                        double absoluteMax = 1;

                        for (Transition transition : transitions) {
                            if (LOG.isTraceEnabled()) {
                                LOG.trace("Applying transition: " + transition.getCode());
                            }
                            ParseConfiguration configuration = this.parserServiceInternal
                                    .getConfiguration(history);
                            transition.apply(configuration);
                            configuration.setRankingScore(history.getRankingScore());
                            configuration.getIncrementalFeatureResults()
                                    .addAll(history.getIncrementalFeatureResults());

                            // test the features on the new configuration
                            double scoreDelta = 0.0;
                            MONITOR.startTask("feature analyse");
                            List<FeatureResult<?>> featureResults = new ArrayList<FeatureResult<?>>();
                            try {
                                for (ParseConfigurationFeature<?> feature : this.parseFeatures) {
                                    MONITOR.startTask(feature.getName());
                                    try {
                                        RuntimeEnvironment env = this.featureService.getRuntimeEnvironment();
                                        FeatureResult<?> featureResult = feature.check(configuration, env);
                                        if (featureResult != null) {
                                            featureResults.add(featureResult);
                                            double weight = weightVector.getWeight(featureResult);
                                            scoreDelta += weight;
                                            if (LOG.isTraceEnabled()) {
                                                LOG.trace(featureResult.toString() + " = " + weight);
                                            }
                                        }
                                    } finally {
                                        MONITOR.endTask(feature.getName());
                                    }
                                }
                                configuration.getIncrementalFeatureResults().add(featureResults);
                                if (LOG.isTraceEnabled()) {
                                    LOG.trace("Score = " + configuration.getRankingScore() + " + " + scoreDelta
                                            + " = " + (configuration.getRankingScore() + scoreDelta));
                                }
                                configuration.setRankingScore(configuration.getRankingScore() + scoreDelta);
                                deltaScorePerTransition.put(transition, scoreDelta);
                                if (Math.abs(scoreDelta) > absoluteMax)
                                    absoluteMax = Math.abs(scoreDelta);

                            } finally {
                                MONITOR.endTask("feature analyse");
                            }

                            int nextHeapIndex = parseComparisonStrategy.getComparisonIndex(configuration)
                                    * 1000;
                            while (nextHeapIndex <= currentHeapIndex)
                                nextHeapIndex++;

                            TreeSet<ParseConfiguration> nextHeap = heaps.get(nextHeapIndex);
                            if (nextHeap == null) {
                                nextHeap = new TreeSet<ParseConfiguration>();
                                heaps.put(nextHeapIndex, nextHeap);
                                if (LOG.isTraceEnabled())
                                    LOG.trace("Created heap with index: " + nextHeapIndex);
                            }
                            nextHeap.add(configuration);
                            if (LOG.isTraceEnabled()) {
                                LOG.trace("Added configuration with score " + configuration.getScore()
                                        + " to heap: " + nextHeapIndex + ", total size: " + nextHeap.size());
                            }

                            configuration.clearMemory();
                        } // next transition

                        // Create a probability distribution of transitions
                        // normalise probabilities for each transition via normalised exponential
                        // e^(x/absmax)/sum(e^(x/absmax))
                        // where x/absmax is in [-1,1]
                        // e^(x/absmax) is in [1/e,e]

                        double total = 0.0;
                        for (Transition transition : deltaScorePerTransition.keySet()) {
                            double deltaScore = deltaScorePerTransition.get(transition);
                            deltaScore = Math.exp(deltaScore / absoluteMax);
                            deltaScorePerTransition.put(transition, deltaScore);
                            total += deltaScore;
                        }

                        for (Transition transition : deltaScorePerTransition.keySet()) {
                            double probability = deltaScorePerTransition.get(transition);
                            probability /= total;
                            Decision<Transition> decision = machineLearningService.createDecision(transition,
                                    probability);
                            transition.setDecision(decision);
                            if (LOG.isTraceEnabled()) {
                                LOG.trace("Transition: " + transition.getCode() + ", Prob: " + probability);
                            }
                        }

                    } finally {
                        MONITOR.endTask("heap sort");
                    }
                } // have we any transitions?

                // beam width test
                if (j == maxSolutions)
                    break;
            } // next history   
        } // next atomic index

        // return the best sequences on the heap
        List<ParseConfiguration> bestConfigurations = new ArrayList<ParseConfiguration>();
        int i = 0;

        if (finalHeap.isEmpty())
            finalHeap = backupHeap;

        while (!finalHeap.isEmpty()) {
            bestConfigurations.add(finalHeap.pollFirst());
            i++;
            if (i >= this.getBeamWidth())
                break;
        }
        if (LOG.isDebugEnabled()) {
            if (correctSolution != null) {
                LOG.debug("Gold transitions: " + correctSolution.getIncrementalOutcomes());
            }
            for (ParseConfiguration finalConfiguration : bestConfigurations) {
                LOG.debug(df.format(finalConfiguration.getScore()) + ": " + finalConfiguration.toString());
                LOG.debug("Pos tag sequence: " + finalConfiguration.getPosTagSequence());
                LOG.debug("Transitions: " + finalConfiguration.getTransitions());
                if (LOG.isTraceEnabled()) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(" * PosTag sequence score ");
                    sb.append(df.format(finalConfiguration.getPosTagSequence().getScore()));
                    sb.append(" = ");
                    for (PosTaggedToken posTaggedToken : finalConfiguration.getPosTagSequence()) {
                        sb.append(" * ");
                        sb.append(df.format(posTaggedToken.getDecision().getProbability()));
                    }
                    sb.append(" root ");
                    sb.append(finalConfiguration.getPosTagSequence().size());
                    LOG.trace(sb.toString());

                    sb = new StringBuilder();
                    sb.append(" * Token sequence score = ");
                    sb.append(df.format(finalConfiguration.getPosTagSequence().getTokenSequence().getScore()));
                    LOG.trace(sb.toString());

                }
            }
        }
        return bestConfigurations;
    } finally {
        MONITOR.endTask("parseSentence");
    }
}

From source file:net.spfbl.http.ServerHTTP.java

private static String getControlPanel(Locale locale, User user, Long begin, String filter) {
    StringBuilder builder = new StringBuilder();
    if (begin == null && filter == null) {
        //            builder.append("<!DOCTYPE html>\n");
        builder.append("<html lang=\"");
        builder.append(locale.getLanguage());
        builder.append("\">\n");
        builder.append("  <head>\n");
        builder.append("    <meta charset=\"UTF-8\">\n");
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("    <title>Painel de controle do SPFBL</title>\n");
        } else {//w ww  .ja  v  a 2s .  c o m
            builder.append("    <title>SPFBL control panel</title>\n");
        }
        // Styled page.
        builder.append("    <style type=\"text/css\">\n");
        builder.append("      body {\n");
        builder.append("        margin:180px 0px 30px 0px;\n");
        builder.append("        background:lightgray;\n");
        builder.append("      }\n");
        builder.append("      iframe {\n");
        builder.append("        border-width: 0px 0px 0px 0px;\n");
        builder.append("        width:100%;\n");
        builder.append("        height:150px;\n");
        builder.append("      }\n");
        builder.append("      .header {\n");
        builder.append("        background-color:lightgray;\n");
        builder.append("        border-width: 0px 0px 0px 0px;\n");
        builder.append("        position:fixed;\n");
        builder.append("        top:0px;\n");
        builder.append("        margin:auto;\n");
        builder.append("        z-index:1;\n");
        builder.append("        width:100%;\n");
        builder.append("        height:180px;\n");
        builder.append("      }\n");
        builder.append("      .bottom {\n");
        builder.append("        background-color:lightgray;\n");
        builder.append("        border-width: 0px 0px 0px 0px;\n");
        builder.append("        position:fixed;\n");
        builder.append("        bottom:0px;\n");
        builder.append("        margin:auto;\n");
        builder.append("        z-index:1;\n");
        builder.append("        width:100%;\n");
        builder.append("        height:30px;\n");
        builder.append("      }\n");
        builder.append("      .button {\n");
        builder.append("          background-color: #4CAF50;\n");
        builder.append("          border: none;\n");
        builder.append("          color: white;\n");
        builder.append("          padding: 16px 32px;\n");
        builder.append("          text-align: center;\n");
        builder.append("          text-decoration: none;\n");
        builder.append("          display: inline-block;\n");
        builder.append("          font-size: 16px;\n");
        builder.append("          margin: 4px 2px;\n");
        builder.append("          -webkit-transition-duration: 0.4s;\n");
        builder.append("          transition-duration: 0.4s;\n");
        builder.append("          cursor: pointer;\n");
        builder.append("      }\n");
        builder.append("      .sender {\n");
        builder.append("          background-color: white; \n");
        builder.append("          color: black; \n");
        builder.append("          border: 2px solid #008CBA;\n");
        builder.append("          width: 100%;\n");
        builder.append("          word-wrap: break-word;\n");
        builder.append("      }\n");
        builder.append("      .sender:hover {\n");
        builder.append("          background-color: #008CBA;\n");
        builder.append("          color: white;\n");
        builder.append("      }\n");
        builder.append("      .highlight {\n");
        builder.append("        background: #b4b9d2;\n");
        builder.append("        color:black;\n");
        builder.append("        border-top: 1px solid #22262e;\n");
        builder.append("        border-bottom: 1px solid #22262e;\n");
        builder.append("      }\n");
        builder.append("      .highlight:nth-child(odd) td {\n");
        builder.append("        background: #b4b9d2;\n");
        builder.append("      }\n");
        builder.append("      .click {\n");
        builder.append("        cursor:pointer;\n");
        builder.append("        cursor:hand;\n");
        builder.append("      }\n");
        builder.append("      table {\n");
        builder.append("        background: white;\n");
        builder.append("        table-layout:fixed;\n");
        builder.append("        border-collapse: collapse;\n");
        builder.append("        word-wrap:break-word;\n");
        builder.append("        border-radius:3px;\n");
        builder.append("        border-collapse: collapse;\n");
        builder.append("        margin: auto;\n");
        builder.append("        padding:2px;\n");
        builder.append("        width: 100%;\n");
        builder.append("        box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);\n");
        builder.append("        animation: float 5s infinite;\n");
        builder.append("      }\n");
        builder.append("      th {\n");
        builder.append("        color:#FFFFFF;;\n");
        builder.append("        background:#1b1e24;\n");
        builder.append("        border-bottom:4px solid #9ea7af;\n");
        builder.append("        border-right: 0px;\n");
        builder.append("        font-size:16px;\n");
        builder.append("        font-weight: bold;\n");
        builder.append("        padding:4px;\n");
        builder.append("        text-align:left;\n");
        builder.append("        text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);\n");
        builder.append("        vertical-align:middle;\n");
        builder.append("        height:30px;\n");
        builder.append("      }\n");
        builder.append("      tr {\n");
        builder.append("        border-top: 1px solid #C1C3D1;\n");
        builder.append("        border-bottom-: 1px solid #C1C3D1;\n");
        builder.append("        font-size:16px;\n");
        builder.append("        font-weight:normal;\n");
        builder.append("        text-shadow: 0 1px 1px rgba(256, 256, 256, 0.1);\n");
        builder.append("      }\n");
        builder.append("      tr:nth-child(odd) td {\n");
        builder.append("        background:#EBEBEB;\n");
        builder.append("      }\n");
        builder.append("      td {\n");
        builder.append("        padding:2px;\n");
        builder.append("        vertical-align:middle;\n");
        builder.append("        font-size:16px;\n");
        builder.append("        text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.1);\n");
        builder.append("        border-right: 1px solid #C1C3D1;\n");
        builder.append("      }\n");
        builder.append("      input[type=text], select {\n");
        builder.append("        width: 400px;\n");
        builder.append("        padding: 0px 4px;\n");
        builder.append("        margin: 1px 0;\n");
        builder.append("        display: inline-block;\n");
        builder.append("        background: #b4b9d2;\n");
        builder.append("        border: 1px solid #ccc;\n");
        builder.append("        border-radius: 4px;\n");
        builder.append("        box-sizing: border-box;\n");
        builder.append("      }\n");
        builder.append("    </style>\n");
        // JavaScript functions.
        TreeMap<Long, Query> queryMap = user.getQueryMap(null, null);
        builder.append(
                "    <script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n");
        builder.append("    <script type=\"text/javascript\">\n");
        builder.append("      window.onbeforeunload = function () {\n");
        builder.append("        document.getElementById('filterField').value = '';\n");
        builder.append("        window.scrollTo(0, 0);\n");
        builder.append("      }\n");
        builder.append("      var last = ");
        if (queryMap.isEmpty()) {
            builder.append(0);
        } else {
            builder.append(queryMap.lastKey());
        }
        builder.append(";\n");
        builder.append("      var filterText = '';\n");
        builder.append("      function view(query) {\n");
        builder.append("        if (query == undefined || query == 0) {\n");
        builder.append("          var viewer = document.getElementById('viewer');\n");
        builder.append("          viewer.src = 'about:blank';\n");
        builder.append("          last = 0;\n");
        builder.append("        } else if (last != query) {\n");
        builder.append("          var viewer = document.getElementById('viewer');\n");
        builder.append("          viewer.addEventListener('load', function() {\n");
        builder.append("            if (document.getElementById(last)) {\n");
        builder.append("              document.getElementById(last).className = 'tr';\n");
        builder.append("              document.getElementById(last).className = 'click';\n");
        builder.append("            }\n");
        builder.append("            document.getElementById(query).className = 'highlight';\n");
        builder.append("            last = query;\n");
        builder.append("          });\n");
        builder.append("          viewer.src = '");
        builder.append(Core.getURL());
        builder.append("' + query;\n");
        builder.append("        }\n");
        builder.append("      }\n");
        builder.append("      function more(query) {\n");
        builder.append("        var rowMore = document.getElementById('rowMore');\n");
        builder.append("        rowMore.onclick = '';\n");
        builder.append("        rowMore.className = 'tr';\n");
        builder.append("        var columnMore = document.getElementById('columnMore');\n");
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("        columnMore.innerHTML = 'carregando mais registros';\n");
        } else {
            builder.append("        columnMore.innerHTML = 'loading more records';\n");
        }
        builder.append("        $.post(\n");
        builder.append("          '");
        builder.append(Core.getURL());
        builder.append(user.getEmail());
        builder.append("',\n");
        builder.append("          {filter:filterText,begin:query},\n");
        builder.append("          function(data, status) {\n");
        builder.append("            if (status == 'success') {\n");
        builder.append("              rowMore.parentNode.removeChild(rowMore);\n");
        builder.append("              $('#tableBody').append(data);\n");
        builder.append("            } else {\n");
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append(
                    "              alert('Houve uma falha de sistema ao tentar realizar esta operao.');\n");
        } else {
            builder.append(
                    "              alert('There was a system crash while trying to perform this operation.');\n");
        }
        builder.append("            }\n");
        builder.append("          }\n");
        builder.append("        );\n");
        builder.append("      }\n");
        builder.append("      function refresh() {\n");
        builder.append("        filterText = document.getElementById('filterField').value;\n");
        builder.append("        $.post(\n");
        builder.append("          '");
        builder.append(Core.getURL());
        builder.append(user.getEmail());
        builder.append("',\n");
        builder.append("          {filter:filterText},\n");
        builder.append("          function(data, status) {\n");
        builder.append("            if (status == 'success') {\n");
        builder.append("              $('#tableBody').html(data);\n");
        builder.append("              view($('#tableBody tr').attr('id'));\n");
        builder.append("            } else {\n");
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append(
                    "              alert('Houve uma falha de sistema ao tentar realizar esta operao.');\n");
        } else {
            builder.append(
                    "              alert('There was a system crash while trying to perform this operation.');\n");
        }
        builder.append("            }\n");
        builder.append("          }\n");
        builder.append("        );\n");
        builder.append("      }\n");
        builder.append("    </script>\n");
        builder.append("  </head>\n");
        // Body.
        builder.append("  <body>\n");
        builder.append("    <div class=\"header\">\n");
        if (queryMap.isEmpty()) {
            builder.append("      <iframe id=\"viewer\" src=\"about:blank\"></iframe>\n");
        } else {
            builder.append("      <iframe id=\"viewer\" src=\"");
            builder.append(Core.getURL());
            builder.append(queryMap.lastKey());
            builder.append("\"></iframe>\n");
        }
        // Construo da tabela de consultas.
        builder.append("      <table>\n");
        builder.append("        <thead>\n");
        builder.append("          <tr>\n");
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append("            <th style=\"width:120px;\">Recepo</th>\n");
            builder.append("            <th>Origem</th>\n");
            builder.append("            <th>Remetente</th>\n");
            builder.append("            <th>Contedo</th>\n");
            builder.append("            <th>Entrega</th>\n");
        } else {
            builder.append("            <th style=\"width:160px;\">Reception</th>\n");
            builder.append("            <th style=\"width:auto;\">Source</th>\n");
            builder.append("            <th style=\"width:auto;\">Sender</th>\n");
            builder.append("            <th style=\"width:auto;\">Content</th>\n");
            builder.append("            <th style=\"width:auto;\">Delivery</th>\n");
        }
        builder.append("          </tr>\n");
        builder.append("        </thead>\n");
        builder.append("      </table>\n");
        builder.append("    </div>\n");
        if (queryMap.isEmpty()) {
            builder.append("    <table>\n");
            builder.append("      <tbody>\n");
            builder.append("        <tr>\n");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append(
                        "          <td colspan=\"5\" align=\"center\">nenhum registro encontrado</td>\n");
            } else {
                builder.append("          <td colspan=\"5\" align=\"center\">no records found</td>\n");
            }
            builder.append("        </tr>\n");
            builder.append("      </tbody>\n");
            builder.append("    </table>\n");
        } else {
            DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale);
            GregorianCalendar calendar = new GregorianCalendar();
            Long nextQuery = null;
            while (queryMap.size() > User.QUERY_MAX_ROWS) {
                nextQuery = queryMap.pollFirstEntry().getKey();
            }
            builder.append("    <table>\n");
            builder.append("      <tbody id=\"tableBody\">\n");
            for (Long time : queryMap.descendingKeySet()) {
                User.Query query = queryMap.get(time);
                boolean highlight = time.equals(queryMap.lastKey());
                buildQueryRow(locale, builder, dateFormat, calendar, time, query, highlight);
            }
            if (nextQuery == null) {
                builder.append("      <tr>\n");
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append(
                            "        <td colspan=\"5\" align=\"center\">no foram encontrados outros registros</td>\n");
                } else {
                    builder.append("        <td colspan=\"5\" align=\"center\">no more records found</td>\n");
                }
                builder.append("      </tr>\n");
            } else {
                builder.append("        <tr id=\"rowMore\" class=\"click\" onclick=\"more('");
                builder.append(nextQuery);
                builder.append("')\">\n");
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append(
                            "          <td id=\"columnMore\" colspan=\"5\" align=\"center\">clique para ver mais registros</td>\n");
                } else {
                    builder.append(
                            "          <td id=\"columnMore\" colspan=\"5\" align=\"center\">click to see more records</td>\n");
                }
                builder.append("        </tr>\n");
            }
            builder.append("      </tbody>\n");
            builder.append("    </table>\n");
        }
        builder.append("    <div class=\"bottom\">\n");
        builder.append("      <table>\n");
        builder.append("        <tr>\n");
        if (locale.getLanguage().toLowerCase().equals("pt")) {
            builder.append(
                    "          <th>Pesquisar <input type=\"text\" id=\"filterField\" name=\"filterField\" onkeydown=\"if (event.keyCode == 13) refresh();\" autofocus></th>\n");
        } else {
            builder.append(
                    "          <th>Search <input type=\"text\" id=\"filterField\" name=\"filterField\" onkeydown=\"if (event.keyCode == 13) refresh();\" autofocus></th>\n");
        }
        builder.append("          <th style=\"text-align:right;\"><small>");
        builder.append(
                "Powered by <a target=\"_blank\" href=\"http://spfbl.net/\" style=\"color: #b4b9d2;\">SPFBL.net</a></small>");
        builder.append("</th>\n");
        builder.append("        </tr>\n");
        builder.append("      <table>\n");
        builder.append("    </div>\n");
        builder.append("  </body>\n");
        builder.append("</html>\n");
    } else {
        TreeMap<Long, Query> queryMap = user.getQueryMap(begin, filter);
        if (queryMap.isEmpty()) {
            builder.append("        <tr>\n");
            if (locale.getLanguage().toLowerCase().equals("pt")) {
                builder.append(
                        "          <td colspan=\"5\" align=\"center\">nenhum registro encontrado</td>\n");
            } else {
                builder.append("          <td colspan=\"5\" align=\"center\">no records found</td>\n");
            }
            builder.append("        </tr>\n");
        } else {
            DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale);
            GregorianCalendar calendar = new GregorianCalendar();
            Long nextQuery = null;
            while (queryMap.size() > User.QUERY_MAX_ROWS) {
                nextQuery = queryMap.pollFirstEntry().getKey();
            }
            for (Long time : queryMap.descendingKeySet()) {
                User.Query query = queryMap.get(time);
                buildQueryRow(locale, builder, dateFormat, calendar, time, query, false);
            }
            if (nextQuery == null) {
                builder.append("        <tr>\n");
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append(
                            "          <td colspan=\"5\" align=\"center\">no foram encontrados outros registros</td>\n");
                } else {
                    builder.append("          <td colspan=\"5\" align=\"center\">no more records found</td>\n");
                }
                builder.append("        </tr>\n");
            } else {
                builder.append("        <tr id=\"rowMore\" class=\"click\" onclick=\"more('");
                builder.append(nextQuery);
                builder.append("')\">\n");
                if (locale.getLanguage().toLowerCase().equals("pt")) {
                    builder.append(
                            "          <td id=\"columnMore\" colspan=\"5\" align=\"center\">clique para ver mais registros</td>\n");
                } else {
                    builder.append(
                            "          <td id=\"columnMore\" colspan=\"5\" align=\"center\">click to see more records</td>\n");
                }
                builder.append("        </tr>\n");
            }
        }
    }
    return builder.toString();
}