Beispiel #1
0
  /**
   * Bencodes the specified {@code HashMap}.
   *
   * @param dictionary the {@code HashMap} to bencode.
   * @return a {@code byte[]} containing the bnecoded form of the {@code HashMap}.
   * @throws BencodingException if any of the objecdts in the map is not bencodable.
   */
  private static final byte[] encodeDictionary(HashMap<ByteBuffer, Object> dictionary)
      throws BencodingException {
    TreeMap<ByteBuffer, Object> sorted_dictionary = new TreeMap<ByteBuffer, Object>();
    sorted_dictionary.putAll(dictionary);
    byte[][] dictionary_parts = new byte[sorted_dictionary.keySet().size() * 2][];
    int k = 0;
    for (Iterator<ByteBuffer> i = sorted_dictionary.keySet().iterator(); i.hasNext(); ) {
      ByteBuffer key = i.next();
      dictionary_parts[k++] = encodeString(key);
      dictionary_parts[k++] = encode(sorted_dictionary.get(key));
    }

    int total_length = 2;
    for (int i = 0; i < dictionary_parts.length; i++) {
      total_length += dictionary_parts[i].length;
    }
    byte[] bencoded_dictionary = new byte[total_length];
    bencoded_dictionary[0] = 'd';
    bencoded_dictionary[bencoded_dictionary.length - 1] = 'e';
    int offset = 1;
    for (int i = 0; i < dictionary_parts.length; i++) {
      System.arraycopy(
          dictionary_parts[i], 0, bencoded_dictionary, offset, dictionary_parts[i].length);
      offset += dictionary_parts[i].length;
    }
    return bencoded_dictionary;
  }
  private File[] sortFiles(File[] files) {

    TreeMap<String, File> dirMap =
        new TreeMap<String, File>(CaseInsensitiveComparator.sharedInstance);
    TreeMap<String, File> fileMap =
        new TreeMap<String, File>(CaseInsensitiveComparator.sharedInstance);

    for (int i = 0; i < files.length; i++) {

      if (files[i].isDirectory()) dirMap.put(files[i].getName(), files[i]);
      else fileMap.put(files[i].getName(), files[i]);
    }

    int i = 0;
    Iterator<String> dirIter = dirMap.keySet().iterator();
    while (dirIter.hasNext()) {
      files[i++] = dirMap.get(dirIter.next());
    }

    Iterator<String> fileIter = fileMap.keySet().iterator();
    while (fileIter.hasNext()) {
      files[i++] = fileMap.get(fileIter.next());
    }

    return files;
  }
Beispiel #3
0
  private ArrayList<String> searchArrayForNumbers() {
    ArrayList<String> resultsOfFind = new ArrayList<String>();

    int sizeOfArray = allWordsInFile.size();

    if (allNumbersInFile.keySet().size() > 0) {
      for (int i : allNumbersInFile.keySet()) {
        // System.out.println( i );
        if (!(i - 1 < 0) & !(i + 1 >= sizeOfArray))
          resultsOfFind.add(
              allWordsInFile.get(i - 1)
                  + " "
                  + allWordsInFile.get(i)
                  + " "
                  + allWordsInFile.get(i + 1));
        else if ((i - 1 < 0) & (i + 1 < sizeOfArray))
          resultsOfFind.add(allWordsInFile.get(i) + " " + allWordsInFile.get(i + 1));
        else if ((i - 1 > 0) & (i + 1 >= sizeOfArray))
          resultsOfFind.add(allWordsInFile.get(i - 1) + " " + allWordsInFile.get(i));
        else resultsOfFind.add(allWordsInFile.get(i));
      }

    } else {
      JOptionPane.showMessageDialog(
          null,
          "File: " + fileName + " does not contain a number",
          "Error finding number(s)!",
          JOptionPane.ERROR_MESSAGE);
      System.exit(0);
    }

    return resultsOfFind;
  }
Beispiel #4
0
  public StreamElement(TreeMap<String, Serializable> output, DataField[] fields) {
    int nbFields = output.keySet().size();
    if (output.containsKey("timed")) nbFields--;
    String fieldNames[] = new String[nbFields];
    Byte fieldTypes[] = new Byte[nbFields];
    Serializable fieldValues[] = new Serializable[nbFields];
    TreeMap<String, Integer> indexedFieldNames =
        new TreeMap<String, Integer>(new CaseInsensitiveComparator());
    int idx = 0;

    long timestamp = System.currentTimeMillis();
    for (String key : output.keySet()) {
      Serializable value = output.get(key);

      if (key.equalsIgnoreCase("timed")) timestamp = (Long) value;
      else {
        fieldNames[idx] = key;
        fieldValues[idx] = value;
        for (int i = 0; i < fields.length; i++) {
          if (fields[i].getName().equalsIgnoreCase(key))
            fieldTypes[idx] = fields[i].getDataTypeID();
        }
        indexedFieldNames.put(key, idx);
        idx++;
      }
    }
    this.fieldNames = fieldNames;
    this.fieldTypes = fieldTypes;
    this.fieldValues = fieldValues;
    this.indexedFieldNames = indexedFieldNames;
    this.timeStamp = timestamp;
  }
Beispiel #5
0
  /**
   * Returns whether a component task-thread should be closed because the containing JobInProgress
   * has completed or the task is killed by the user
   */
  public boolean shouldClose(TaskAttemptID taskid) {
    /**
     * If the task hasn't been closed yet, and it belongs to a completed TaskInProgress close it.
     *
     * <p>However, for completed map tasks we do not close the task which actually was the one
     * responsible for _completing_ the TaskInProgress.
     */
    if (tasksReportedClosed.contains(taskid)) {
      if (tasksToKill.keySet().contains(taskid)) return true;
      else return false;
    }

    boolean close = false;
    TaskStatus ts = taskStatuses.get(taskid);

    if ((ts != null)
        && ((this.failed)
            || ((job.getStatus().getRunState() != JobStatus.RUNNING
                && (job.getStatus().getRunState() != JobStatus.PREP))))) {
      tasksReportedClosed.add(taskid);
      close = true;
    } else if ((completes > 0)
        && // isComplete() is synchronized!
        !(isMapTask() && !jobSetup && !jobCleanup && isComplete(taskid))) {
      tasksReportedClosed.add(taskid);
      close = true;
    } else if (isCommitPending(taskid) && !shouldCommit(taskid)) {
      tasksReportedClosed.add(taskid);
      close = true;
    } else {
      close = tasksToKill.keySet().contains(taskid);
    }
    return close;
  }
Beispiel #6
0
  /**
   * get 部首 tree view
   *
   * @returns root tree node object
   * @throws SQLException
   */
  public DefaultMutableTreeNode getRadicalTree() throws SQLException {
    TreeMap<Integer, String> strokesAndRadicalsMap = new TreeMap<Integer, String>();
    for (int i = 0; i < RADICAL_STROKES.length; ++i) {
      String sRadical = "" + HYDC_RADICALS.charAt(i);
      if (sRadical.equals(" ")) {
        continue;
      }
      int strokes = RADICAL_STROKES[i];
      String sRadicals = strokesAndRadicalsMap.get(strokes);
      if (sRadicals == null) {
        strokesAndRadicalsMap.put(strokes, sRadicals = "");
      }
      strokesAndRadicalsMap.put(strokes, sRadicals + sRadical);
    }
    String sSql =
        "SELECT parts_strokes, unicode FROM HYDC3 "
            + "WHERE bushou = ? "
            + "ORDER BY parts_strokes, unicode";
    PreparedStatement statement = connection.prepareStatement(sSql);

    DefaultMutableTreeNode root = new DefaultMutableTreeNode("畫數 / 部首 / 畫數");
    for (Integer strokes : strokesAndRadicalsMap.keySet()) {
      String sRadicals = strokesAndRadicalsMap.get(strokes);
      DefaultMutableTreeNode strokesNode =
          new DefaultMutableTreeNode(strokes.toString() + " : " + sRadicals);
      for (int i = 0; i < sRadicals.length(); ++i) {
        String sRadical = sRadicals.substring(i, i + 1);
        DefaultMutableTreeNode radicalNode = new DefaultMutableTreeNode(sRadical);

        TreeMap<Integer, String> partsStrokesAndCharactersMap = new TreeMap<Integer, String>();
        statement.setString(1, sRadical);
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
          short partsStrokes = resultSet.getShort("parts_strokes");
          int unicode = resultSet.getInt("unicode");
          String sCharacters = partsStrokesAndCharactersMap.get((Integer) (int) partsStrokes);
          if (sCharacters == null) {
            partsStrokesAndCharactersMap.put((Integer) (int) partsStrokes, sCharacters = "");
          }
          sCharacters += new String(new int[] {unicode}, 0, 1);
          partsStrokesAndCharactersMap.put((Integer) (int) partsStrokes, sCharacters);
        }
        resultSet.close();
        strokesNode.add(radicalNode);
        for (Integer partsStrokes : partsStrokesAndCharactersMap.keySet()) {
          String sCharacters = partsStrokesAndCharactersMap.get(partsStrokes);
          DefaultMutableTreeNode partsStrokesNode =
              new DefaultMutableTreeNode(partsStrokes.toString() + " : " + sCharacters);
          radicalNode.add(partsStrokesNode);
        }
        strokesNode.add(radicalNode);
      }
      root.add(strokesNode);
    }

    statement.close();
    return root;
  }
Beispiel #7
0
  /** Construct a new stage from the information contained in the node bundle. */
  @SuppressWarnings("deprecation")
  public BundleStage(
      StageInformation stageInfo,
      UtilContext context,
      MasterMgrClient client,
      NodeMod mod,
      TreeMap<String, BaseAnnotation> annotations,
      TreeMap<String, String> toolsetRemap,
      TreeMap<String, String> selectionKeyRemap,
      TreeMap<String, String> licenseKeyRemap,
      TreeMap<String, String> hardwareKeyRemap) {
    super("Bundle", "Description...", stageInfo, context, client, mod, StageFunction.aNone);

    pOrigNodeMod = mod;

    {
      String ntset = toolsetRemap.get(mod.getToolset());
      if (ntset != null) pRemappedToolset = ntset;
      else pRemappedToolset = super.getToolset();
    }

    JobReqs jreqs = mod.getJobRequirements();
    if (jreqs != null) {
      {
        TreeSet<String> selectionKeys = new TreeSet<String>();
        for (String key : jreqs.getSelectionKeys()) {
          String nkey = selectionKeyRemap.get(key);
          if (nkey != null) selectionKeys.add(nkey);
        }
        addSelectionKeys(selectionKeys);
      }

      {
        TreeSet<String> licenseKeys = new TreeSet<String>();
        for (String key : jreqs.getLicenseKeys()) {
          String nkey = licenseKeyRemap.get(key);
          if (nkey != null) licenseKeys.add(nkey);
        }
        addLicenseKeys(licenseKeys);
      }

      {
        TreeSet<String> hardwareKeys = new TreeSet<String>();
        for (String key : jreqs.getHardwareKeys()) {
          String nkey = hardwareKeyRemap.get(key);
          if (nkey != null) hardwareKeys.add(nkey);
        }
        addHardwareKeys(hardwareKeys);
      }
    }

    for (String aname : annotations.keySet()) addAnnotation(aname, annotations.get(aname));

    {
      TreeMap<String, BaseAnnotation> annots = mod.getAnnotations();
      for (String aname : annots.keySet()) addVersionAnnotation(aname, annots.get(aname));
    }
  }
 /**
  * @param type
  * @return
  */
 private Collection<String> getCorrectList(String type) {
   if (type.equals("prop")) {
     return propsList.keySet();
   } else if (type.equals("set")) {
     return setsList.keySet();
   } else {
     return charList.keySet();
   }
 }
 public void showWordTriples() {
   wordTripleHistogram = calculateWordTriplesUI.getHistogram();
   showWordTriplesUI.createTable(wordTripleHistogram.keySet().size(), numCodes, triples, words);
   Iterator histoIterator = wordTripleHistogram.keySet().iterator();
   int rowNumber = 0;
   while (histoIterator.hasNext()) {
     Double key = (Double) histoIterator.next();
     showWordTriplesUI.addData(
         rowNumber, key.intValue(), ((Double) wordTripleHistogram.get(key)).intValue());
     rowNumber++;
   }
   showWordTriplesUI.setInfoLabelText(
       "There were " + (numCodes * numCodes * numCodes) + " possible word triples.");
 }
  // 20 LET x = 3
  public void parse(String line) {
    if (line.equalsIgnoreCase("RUN")) {
      this.run();
      return;
    }

    if (line.equalsIgnoreCase("LIST")) {
      for (int l : code.keySet()) {
        System.out.println(l + " " + code.get(l));
      }
      return;
    }

    try {
      String parts[] = line.split(" ");
      int lineNumber = Integer.parseInt(parts[0]);
      String opName = parts[1];
      Operator operator =
          OperatorFactory.createOperator(
              opName, line.substring(parts[0].length() + parts[1].length() + 2));
      code.put(lineNumber, operator);
    } catch (RuntimeException e) {
      System.err.println("Wrong operation!");
    }
  }
Beispiel #11
0
  /**
   * Return a color interpolated within the color list of this paint scale. The interpolation is a
   * linear one between the two colors in the list whose associated values frame the one given.
   */
  @Override
  public Color getPaint(double value) {
    if (colors.isEmpty()) return defaultColor;
    if (colors.size() == 1) return colors.get(colors.firstKey());

    if (value > upperBound) value = upperBound;
    if (value < lowerBound) value = lowerBound;
    Set<Double> keys = colors.keySet();
    double bottom = colors.firstKey();
    double top = colors.lastKey();
    for (double key : keys) {
      top = key;
      if (value < key) break;
      else bottom = top;
    }

    double alpha;
    if (top == bottom) alpha = 0; // we reached the end of the list
    else alpha = (value - bottom) / (top - bottom);

    Color colorBottom = colors.get(bottom);
    Color colorTop = colors.get(top);
    int red = (int) ((1 - alpha) * colorBottom.getRed() + alpha * colorTop.getRed());
    int green = (int) ((1 - alpha) * colorBottom.getGreen() + alpha * colorTop.getGreen());
    int blue = (int) ((1 - alpha) * colorBottom.getBlue() + alpha * colorTop.getBlue());
    return new Color(red, green, blue);
  }
Beispiel #12
0
 /**
  * Adds new point p with value m to this histogram.
  *
  * @param p
  * @param m
  */
 public void update(double p, long m) {
   Long mi = bin.get(p);
   if (mi != null) {
     // we found the same p so increment that counter
     bin.put(p, mi + m);
   } else {
     bin.put(p, m);
     // if bin size exceeds maximum bin size then trim down to max size
     while (bin.size() > maxBinSize) {
       // find points p1, p2 which have smallest difference
       Iterator<Double> keys = bin.keySet().iterator();
       double p1 = keys.next();
       double p2 = keys.next();
       double smallestDiff = p2 - p1;
       double q1 = p1, q2 = p2;
       while (keys.hasNext()) {
         p1 = p2;
         p2 = keys.next();
         double diff = p2 - p1;
         if (diff < smallestDiff) {
           smallestDiff = diff;
           q1 = p1;
           q2 = p2;
         }
       }
       // merge those two
       long k1 = bin.remove(q1);
       long k2 = bin.remove(q2);
       bin.put((q1 * k1 + q2 * k2) / (k1 + k2), k1 + k2);
     }
   }
 }
 private static String getNeighboursCountryString() {
   String toReturn = "";
   for (String countryKey : neighbourMap.keySet()) {
     toReturn = toReturn + "," + countryKey;
   }
   return toReturn;
 }
  /*
   *get collaboration information based on organisation - returns a collaborationList.
   */
  public HashMap<Integer, CollaborationList> getCollaborations_org(
      String id, TreeMap<Integer, Collaborator> network) {
    HashMap<Integer, CollaborationList> collaborations =
        new java.util.HashMap<Integer, CollaborationList>();

    // reset the iterator
    Set<Integer> networkKeys = network.keySet();
    Iterator<Integer> networkKeyIterator = networkKeys.iterator();
    Integer networkKey = null;

    CollaborationList collaborationList;

    // loop through the list of keys
    while (networkKeyIterator.hasNext()) {

      // get the key
      networkKey = (Integer) networkKeyIterator.next();

      // get the list of collaborations for this user
      collaborationList = getCollaborationList_org(id, networkKey.toString());

      // add the collaborationList object to the list
      collaborations.put(networkKey, collaborationList);
    }

    return collaborations;
  }
Beispiel #15
0
 @SuppressWarnings("unchecked")
 @Override
 public void show(Model model) {
   System.out.println("Voting Page");
   System.out.print("   Temas: [");
   TreeMap<String, Double> themeTransfers = (TreeMap<String, Double>) model.get("themeTransfers");
   String[] themesNames = themeTransfers.keySet().toArray(new String[0]);
   for (int i = 0; i < themesNames.length; i++) {
     if (i == 0)
       System.out.print(
           "ThemeTransfer [themeName="
               + themesNames[i]
               + ", average="
               + themeTransfers.get(themesNames[i])
               + "]");
     else
       System.out.print(
           ", ThemeTransfer [themeName="
               + themesNames[i]
               + ", average="
               + themeTransfers.get(themesNames[i])
               + "]");
   }
   System.out.println("]");
 }
  private Vector<Double> countCoOccurences(String bandName) {
    TreeMap<String, Double> countMap = new TreeMap<String, Double>();

    for (String band : bandDirectoryMapping.keySet()) countMap.put(band, new Double(0.0));
    File[] files =
        bandDirectoryMapping
            .get(bandName)
            .listFiles(
                new FileFilter() {
                  @Override
                  public boolean accept(File pathname) {
                    if (fileEnding == null) return true;
                    return pathname.getName().endsWith(fileEnding);
                  }
                });
    int filesParsed = 0;
    for (File file : files) {
      if (file.length() != 0 && filesParsed < NUMBER_OF_FILES_TO_PARSE) {
        fileIncludesBands(file, countMap);
        filesParsed++;
      }
    }

    Vector<Double> result = new Vector<Double>(countMap.values());
    System.out.println(bandName + " " + nameMapping.get(bandName).toLowerCase());
    System.out.println(result);
    return result;
  }
Beispiel #17
0
  /**
   * Creates a "status report" for this task. Includes the task ID and overall status, plus reports
   * for all the component task-threads that have ever been started.
   */
  synchronized TaskReport generateSingleReport() {
    ArrayList<String> diagnostics = new ArrayList<String>();
    for (List<String> l : taskDiagnosticData.values()) {
      diagnostics.addAll(l);
    }
    TIPStatus currentStatus = null;
    if (isRunning() && !isComplete()) {
      currentStatus = TIPStatus.RUNNING;
    } else if (isComplete()) {
      currentStatus = TIPStatus.COMPLETE;
    } else if (wasKilled()) {
      currentStatus = TIPStatus.KILLED;
    } else if (isFailed()) {
      currentStatus = TIPStatus.FAILED;
    } else if (!(isComplete() || isRunning() || wasKilled())) {
      currentStatus = TIPStatus.PENDING;
    }

    TaskReport report =
        new TaskReport(
            getTIPId(),
            (float) progress,
            state,
            diagnostics.toArray(new String[diagnostics.size()]),
            currentStatus,
            execStartTime,
            execFinishTime,
            counters);
    if (currentStatus == TIPStatus.RUNNING) {
      report.setRunningTaskAttempts(activeTasks.keySet());
    } else if (currentStatus == TIPStatus.COMPLETE) {
      report.setSuccessfulAttempt(getSuccessfulTaskid());
    }
    return report;
  }
  /** @return A Box for selecting an asset type, the old asset and its replacement asset. */
  private Box assetChoiceBox() {
    TreeSet<String> types = new TreeSet<String>();

    types.add(AssetType.CHARACTER.toString());
    types.add(AssetType.PROP.toString());
    types.add(AssetType.SET.toString());

    // JDrawer toReturn;
    Box hbox = new Box(BoxLayout.X_AXIS);
    {
      JCollectionField assetType = UIFactory.createCollectionField(types, diag, sTSize);
      assetType.setActionCommand("type");
      assetType.addActionListener(this);

      JCollectionField oldAsset = UIFactory.createCollectionField(charList.keySet(), diag, sVSize);
      JCollectionField newAsset = UIFactory.createCollectionField(charList.keySet(), diag, sVSize);
      hbox.add(assetType);
      hbox.add(Box.createHorizontalStrut(10));
      hbox.add(oldAsset);
      hbox.add(Box.createHorizontalStrut(5));
      hbox.add(newAsset);

      // pPotentials.put(oldAsset, newAsset);
    }
    list.add(Box.createVerticalStrut(5));

    return hbox; // toReturn;
  } // return assetChoiceBox
  private void setAllChartLayers() throws Exception {
    File layersDir = new File(Util.getConfig(null).getProperty(Constants.MAPCACHE_RESOURCE));
    for (File layerDir : layersDir.listFiles()) {
      // avoid files starting with dot (.)
      if (layerDir.getName().startsWith(".")) continue;
      if (layerDir.isFile()) continue;
      try {
        File layerFile = new File(layerDir, "freeboard.txt");
        if (layerFile.exists()) {
          String layer = FileUtils.readFileToString(layerFile);
          String chart = layerFile.getName();
          chart = chart.substring(0, chart.indexOf("."));
          String name = getChartName(layer, chart);
          allListMap.put(name, layer);
          if (logger.isDebugEnabled()) logger.debug("Found:" + name);
        } else {
          logger.warn(layerFile.getAbsolutePath() + " does not exist");
        }
      } catch (Exception e) {
        logger.error(e.getMessage(), e);
      }
    }

    allChartsModel = new ListModelList<String>(allListMap.keySet());
  }
  public void computeDocumentVectors(int cnt) {
    int documentCollectionSize = 0;
    double avgDocumentLen = 0;

    documentCollectionSize = documentMap.size();
    avgDocumentLen = computeAverageDocumentLength(documentCollectionSize);

    TreeMap<String, Integer> currentWordMap = queryMap.get(cnt);

    for (String term : currentWordMap.keySet()) {
      HashMap<Integer, Integer> tf = computeDocumentTF(term);
      HashMap<Integer, Integer> maxTF = computeDocumentMaxTF();
      int df = computeDocumentDF(term);
      HashMap<Integer, Double> innerDocVectorW1 = new HashMap<Integer, Double>();
      HashMap<Integer, Double> innerDocVectorW2 = new HashMap<Integer, Double>();

      for (int i = 1; i <= documentCollectionSize; i++) {
        double W1 = computeVectorByW1(tf.get(i), maxTF.get(i), df, documentCollectionSize);
        innerDocVectorW1.put(i, W1);
        double W2 =
            computeVectorByW2(
                tf.get(i),
                documentMap.get(i).documentLength,
                avgDocumentLen,
                df,
                documentCollectionSize);
        innerDocVectorW2.put(i, W2);
      }

      W1DocumentVectorMap.put(term, innerDocVectorW1);
      W2DocumentVectorMap.put(term, innerDocVectorW2);
    }
  }
    private void updateFragments(int start, int end, @NotNull String replace) {
      int docStart = psiToDocumentOffset(start);
      int docEnd = psiToDocumentOffset(end);

      TextRange startRange = findFragment(docStart);
      TextRange endRange = findFragment(docEnd);

      myPsiText = myPsiText.delete(start, end).insert(start, replace);

      TextRange newFragment =
          new TextRange(
              startRange != null ? startRange.getStartOffset() : docStart,
              endRange != null ? endRange.getEndOffset() : docEnd);
      CharSequence newReplacement =
          myPsiText.subSequence(
              documentToPsiOffset(newFragment.getStartOffset(), false),
              documentToPsiOffset(newFragment.getEndOffset(), true)
                  + replace.length()
                  - (end - start));

      for (Iterator<TextRange> iterator = myAffectedFragments.keySet().iterator();
          iterator.hasNext(); ) {
        if (iterator.next().intersects(newFragment)) {
          iterator.remove();
        }
      }
      myAffectedFragments.put(newFragment, newReplacement);
    }
 private String getMaintainers() {
   final TreeMap<String, Language> list = new TreeMap<>();
   for (final Language lang : Language.REAL_LANGUAGES) {
     if (!lang.isVariant()) {
       if (lang.getMaintainers() != null) {
         list.put(messages.getString(lang.getShortName()), lang);
       }
     }
   }
   final StringBuilder maintainersInfo = new StringBuilder();
   maintainersInfo.append("<table border=0 cellspacing=0 cellpadding=0>");
   for (String lang : list.keySet()) {
     maintainersInfo.append("<tr valign=\"top\"><td>");
     maintainersInfo.append(lang);
     maintainersInfo.append(":</td>");
     maintainersInfo.append("<td>&nbsp;</td>");
     maintainersInfo.append("<td>");
     int i = 0;
     for (Contributor contributor : list.get(lang).getMaintainers()) {
       if (i > 0) {
         maintainersInfo.append(", ");
         if (i % 3 == 0) {
           maintainersInfo.append("<br>");
         }
       }
       maintainersInfo.append(contributor.getName());
       i++;
     }
     maintainersInfo.append("</td></tr>");
   }
   maintainersInfo.append("</table>");
   return maintainersInfo.toString();
 }
Beispiel #23
0
    @Override
    public void reduce(
        Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter reporter)
        throws IOException {

      String line = "";
      String header = "";
      TreeMap<String, String> ciudades = new TreeMap<String, String>();

      // Obtenemos los datos y los metemos a un treemap para que los ordene por ciudad
      while (values.hasNext()) {
        String[] tmp = values.next().toString().split(",");
        String ciudad = tmp[0];
        String mes = tmp[1];
        String temperatura = tmp[2];
        String fecha = tmp[3];

        ciudades.put(ciudad, tmp[1] + "," + tmp[2] + "," + tmp[3]);
      }

      // Recorremos las ciudades y vamos imprimiendo
      for (String ciudad : ciudades.keySet()) {
        header += ciudad + ",,";
        String[] temporal = ciudades.get(ciudad).split(",");
        line += temporal[2] + "," + temporal[1] + ",";
      }

      if (c == 0) { // Imprimimos cabezera
        output.collect(new Text("Año,"), new Text(header));
        c++;
      }

      output.collect(new Text(key.toString() + ","), new Text(line));
    }
Beispiel #24
0
 static Set<String> listTypes(Category p_category) {
   final TreeMap<String, Type> types = typeMap.get(p_category);
   if (types != null) {
     return types.keySet();
   }
   return null;
 }
  /**
   * Tun ester2 corpus.
   *
   * @param parameter the parameter
   * @throws DiarizationException the diarization exception
   * @throws Exception the exception
   */
  public void tunEster2Corpus(Parameter parameter) throws DiarizationException, Exception {
    // Parameter parameter = getParameter(arguments);

    corpusResult = new TreeMap<String, DiarizationResultList>();
    ClusterSet fullClusterSet = initialize(parameter);
    listOfClusterSet = MainTools.splitHypotesis(fullClusterSet);

    int nbThread = parameter.getParameterDiarization().getThread();

    diarizationList = new ArrayList<Diarization>(nbThread);

    for (int i = 0; i < nbThread; i++) {
      diarizationList.add(new Diarization());
      diarizationList.get(i).start();
    }

    while (isThreadAlive() == true) {
      Thread.sleep(10000);
    }

    logger.finer("**** ALL SHOWS ***");
    for (String key : corpusResult.keySet()) {
      DiarizationResultList values = corpusResult.get(key);
      values.log(key);
    }
  }
Beispiel #26
0
 /**
  * write style attribute by TreeMap
  *
  * <pre>
  * // usage:
  * TreeMap&lt;String, String&gt; styleMap = new TreeMap&lt;String, String&gt;();
  * styleMap.put(&quot;border-color&quot;, &quot;red&quot;);
  * html.getById(Div.class, &quot;hellomsg&quot;).setStyleByTreeMap(styleMap);
  * // output:
  * // &lt;div id=&quot;hellomsg&quot; style=&quot;border-color:red;&quot;&gt;...&lt;/div&gt;
  * </pre>
  *
  * @param styleMap
  */
 public <T extends AbstractJaxb> void setStyleByTreeMap(TreeMap<String, String> styleMap) {
   String str = "";
   for (String key : styleMap.keySet()) {
     str += key + ":" + styleMap.get(key) + "; ";
   }
   this.setStyle(str);
 }
Beispiel #27
0
  public static void testCompareTo2() {
    TreeMap<Seqno, Seqno> map = new TreeMap<>(new SeqnoComparator());

    Seqno[] ranges = {
      new SeqnoRange(900, 905),
      new Seqno(550),
      new Seqno(222),
      new SeqnoRange(700, 800),
      new Seqno(650),
      new SeqnoRange(23, 200)
    };

    for (Seqno range : ranges) map.put(range, range);

    System.out.println("map = " + map.keySet());
    assert map.size() == 6;

    for (long num : new long[] {0, 1, 201, 202, 223, 1000}) {
      checkNull(map, num);
    }

    checkInRange(map, 550, 550, 550);
    checkInRange(map, 650, 650, 650);

    checkInRange(map, 23, 23, 200);
    checkInRange(map, 100, 23, 200);
    checkInRange(map, 200, 23, 200);
    checkInRange(map, 222, 222, 222);
    checkInRange(map, 750, 700, 800);
    checkInRange(map, 905, 900, 905);
  }
Beispiel #28
0
 /**
  * Prepares and returns a string ready to be signed from the params of an HTTP request
  *
  * <p>The params must be only those included in the body of the HTTP request when its content type
  * is application/x-www-urlencoded and must be urldecoded.
  *
  * @param params The params of an HTTP request.
  * @return A serialized representation of the params ready to be signed. null if there are no
  *     valid params.
  * @throws UnsupportedEncodingException If {@value CHARSET_UTF_8} charset is not supported.
  */
 private String getSerializedParams(Map<String, String> params)
     throws UnsupportedEncodingException {
   String rv = null;
   if (params != null && !params.isEmpty()) {
     TreeMap<String, String> sortedParams = new TreeMap<String, String>();
     for (String key : params.keySet()) {
       if (key != null && params.get(key) != null) {
         sortedParams.put(key, params.get(key));
       }
     }
     StringBuilder serializedParams = new StringBuilder();
     for (String key : sortedParams.keySet()) {
       serializedParams.append(URLEncoder.encode(key, CHARSET_UTF_8));
       serializedParams.append(PARAM_VALUE_SEPARATOR);
       serializedParams.append(URLEncoder.encode(sortedParams.get(key), CHARSET_UTF_8));
       if (!key.equals(sortedParams.lastKey())) {
         serializedParams.append(PARAM_SEPARATOR);
       }
     }
     if (serializedParams.length() > 0) {
       rv = serializedParams.toString();
     }
   }
   return rv;
 }
Beispiel #29
0
 /**
  * Prepares and returns a string ready to be signed from the 11-paths specific HTTP headers
  * received
  *
  * @param xHeaders a non necessarily ordered map of the HTTP headers to be ordered without
  *     duplicates.
  * @return a String with the serialized headers, an empty string if no headers are passed, or null
  *     if there's a problem such as non specific 11paths headers
  */
 private String getSerializedHeaders(Map<String, String> xHeaders) {
   if (xHeaders != null) {
     TreeMap<String, String> sortedMap = new TreeMap<String, String>();
     for (String key : xHeaders.keySet()) {
       if (!key.toLowerCase().startsWith(X_11PATHS_HEADER_PREFIX.toLowerCase())) {
         // TODO: Log this better
         System.err.println(
             "Error serializing headers. Only specific "
                 + X_11PATHS_HEADER_PREFIX
                 + " headers need to be singed");
       }
       sortedMap.put(key.toLowerCase(), xHeaders.get(key).replace("\n", " "));
     }
     StringBuilder serializedHeaders = new StringBuilder();
     for (String key : sortedMap.keySet()) {
       serializedHeaders
           .append(key)
           .append(X_11PATHS_HEADER_SEPARATOR)
           .append(sortedMap.get(key))
           .append(" ");
     }
     return serializedHeaders.toString().trim();
   } else {
     return "";
   }
 }
Beispiel #30
0
  private void logExec(String pCmdString, Map<String, String> unsortedEnv) {

    if (_log.isInfoEnabled()) {

      TreeMap<String, String> env = new TreeMap<String, String>();
      env.putAll(unsortedEnv);

      _log.info("Executing '" + pCmdString + "'");
      _log.debug("Enviroment:");
      FileWriter writer = null;
      try {
        if (_log.isDebugEnabled()) {
          File envvarFile = File.createTempFile("envvars", ".txt");
          writer = new FileWriter(envvarFile);
          _log.debug("ENVVARS will be written to " + envvarFile.getAbsolutePath());
        }
        for (String key : env.keySet()) {
          _log.debug(String.format("  %s", new Object[] {key + "=" + env.get(key)}));
          if (_log.isDebugEnabled())
            writer.write(String.format("  %s%n", new Object[] {key + "=" + env.get(key)}));
        }
        if (_log.isDebugEnabled()) writer.close();
      } catch (Exception e) {
        _log.error("Unable to log exec call: " + ExceptionUtils.getStackTrace(e));
      }
    }
  }