private RetSortedSet getAllEqualsIndices(IndexType indexType) {
    boolean ungleiche = false;
    // ----------------------------------------------------------------
    // Alle gleichen ermitteln und ob es ungleiche gibt.
    // ----------------------------------------------------------------

    SortedSet<String> sortedSet = new TreeSet<String>();

    // jetzt den Rest durchhuehnern
    boolean erstesBild = true;
    List<PM_Picture> pictures = index.controller.getPictureListDisplayed();
    for (PM_Picture picture : pictures) {
      if (erstesBild) {
        erstesBild = false;
        sortedSet = getSortedSetIndex(indexType, picture);
        continue; // der erste darstellbare wurde erzeugt
      }
      int anz = sortedSet.size();
      SortedSet<String> sortedSetMeta = getSortedSetIndex(indexType, picture);
      sortedSet.retainAll(sortedSetMeta); // der Durchschnitt
      // (Intersektion) bleibt
      // erhalten
      if (sortedSetMeta.size() != sortedSet.size() || anz != sortedSetMeta.size()) ungleiche = true;
    }

    return new RetSortedSet(sortedSet, ungleiche);
  }
Esempio n. 2
0
 /** @tests java.util.TreeSet#addAll(java.util.Collection) */
 public void test_addAllLjava_util_Collection() {
   // Test for method boolean
   // java.util.TreeSet.addAll(java.util.Collection)
   SortedSet s = db.createTreeSet("test");
   s.addAll(ts);
   assertTrue("Incorrect size after add", s.size() == ts.size());
   Iterator i = ts.iterator();
   while (i.hasNext()) assertTrue("Returned incorrect set", s.contains(i.next()));
 }
Esempio n. 3
0
 /**
  * Loads tune responses
  *
  * @param tuneSet is a Map from questions to responses
  */
 public void setTune(Map<TypeQ, TypeR> tuneSet) {
   log.debug("Setting tune set...");
   if (!(categToInt != null)) log.error("Result Vector not computed.");
   assert categToInt != null : "Result Vector not computed.";
   DoubleMatrix indicator = DoubleMatrix.zeros(sortedQuestions.size());
   DoubleMatrix tuneVec = DoubleMatrix.zeros(sortedQuestions.size());
   int idx = 0;
   for (TypeQ iter : sortedQuestions) {
     if (tuneSet.containsKey(iter)) {
       indicator.put(idx, 1.0d);
       tuneVec.put(idx, categToInt.get(tuneSet.get(iter)));
     }
     idx++;
   }
   tuneVector = new Pair<DoubleMatrix, DoubleMatrix>(tuneVec, indicator);
 }
  /**
   * O(N) Determine if this set is equal to other. Two sets are equal if they have exactly the same
   * elements. The order of the elements does not matter. <br>
   * pre: none
   *
   * @param other the object to compare to this set
   * @return true if other is a Set and has the same elements as this set
   */
  public boolean equals(Object other) {
    // Calling object cannot be null so if other is null then the two objects
    // cannot be equal
    if (other == null) return false;
    if (!(other instanceof ISet<?>)) return false;
    // At this point we KNOW that other is a non-null ISet object
    ISet<?> otherSet = (ISet<?>) other;

    // we know E is a Comparable, but we don't know if
    // otherSet is a SortedSet.

    // local var of correct type so we only have to cast once
    SortedSet<?> otherSortedSet;

    // do we need to create a new SortedSet based on otherSet or is otherSet
    // really a SortedSet?
    if (!(otherSet instanceof SortedSet<?>)) return super.equals(otherSet);
    else otherSortedSet = (SortedSet<?>) otherSet;

    if (otherSortedSet.size() != this.size()) return false;
    else {
      for (int x = 0; x < this.size(); x++) {
        if (!(this.myCon.get(x).equals(otherSortedSet.myCon.get(x)))) return false;
      }
      return true;
    }
  }
  /** Set the contents of the field selector list. */
  private void setupFieldSelector() {
    fieldListModel.clear();
    SortedSet<String> contents = new TreeSet<String>();
    for (String s : metaData) {
      if (s.startsWith(Globals.SELECTOR_META_PREFIX)) {
        contents.add(s.substring(Globals.SELECTOR_META_PREFIX.length()));
      }
    }
    if (contents.size() == 0) {
      // if nothing was added, put the default fields (as described in the help)
      fieldListModel.addElement("author");
      fieldListModel.addElement("journal");
      fieldListModel.addElement("keywords");
      fieldListModel.addElement("publisher");
    } else {
      for (String s : contents) {
        fieldListModel.addElement(s);
      }
    }

    if (currentField == null) {
      // if dialog is created for the whole database,
      // select the first field to avoid confusions in GUI usage
      fieldList.setSelectedIndex(0);
    } else {
      // a specific field has been chosen at the constructur
      // select this field
      int i = fieldListModel.indexOf(currentField);
      if (i != -1) {
        // field has been found in list, select it
        fieldList.setSelectedIndex(i);
      }
    }
  }
  /**
   * Read from line to line
   *
   * @param from
   * @param to
   * @return
   * @throws IOException
   */
  public SortedMap<Integer, String> readLines(int from, int to) throws IOException {
    assertIsOpen();
    if (from < 1) {
      throw new IllegalArgumentException("'from' must be greater than or equal to 1");
    }
    if (to < from) {
      throw new IllegalArgumentException("'to' must be greater than or equal to 'from'");
    }
    if (from > index.size()) {
      throw new IllegalArgumentException("'from' must be less than the file's number of lines");
    }

    SortedMap<Integer, String> lines = new TreeMap<>();
    List<Long> positions = new ArrayList<>(index);

    try {
      lock.lock();

      raf.seek(positions.get(from - 1));
      for (int i = from; i <= to; i++) {
        String line = raf.getNextLine(charset);
        if (line != null) {
          lines.put(i, line);
        } else {
          break;
        }
      }

      return lines;
    } finally {
      lock.unlock();
    }
  }
Esempio n. 7
0
 /**
  * Loads ground truth responses
  *
  * @param groundTruth is a Map from questions to responses
  */
 public void setGroundTruth(Map<TypeQ, TypeR> groundTruth) {
   log.debug("Setting ground truth...");
   if (!(categToInt != null)) log.error("Result Vector not computed.");
   assert categToInt != null : "Result Vector not computed.";
   DoubleMatrix indicator = DoubleMatrix.zeros(sortedQuestions.size());
   DoubleMatrix gtVec = DoubleMatrix.zeros(sortedQuestions.size());
   int idx = 0;
   for (TypeQ iter : sortedQuestions) {
     if (groundTruth.containsKey(iter)) {
       indicator.put(idx, 1.0d);
       gtVec.put(idx, categToInt.get(groundTruth.get(iter)));
     }
     idx++;
   }
   groundTruthVector = new Pair<DoubleMatrix, DoubleMatrix>(gtVec, indicator);
 }
Esempio n. 8
0
 /** @tests java.util.TreeSet#add(java.lang.Object) */
 public void test_addLjava_lang_Object() {
   // Test for method boolean java.util.TreeSet.add(java.lang.Object)
   ts.add(new Integer(-8));
   assertTrue("Failed to add Object", ts.contains(new Integer(-8)));
   ts.add(objArray[0]);
   assertTrue("Added existing element", ts.size() == objArray.length + 1);
 }
 public List<File> getAffectedPaths() {
   final SortedSet<FilePath> set = myIdx.getAffectedPaths();
   final List<File> result = new ArrayList<File>(set.size());
   for (FilePath path : set) {
     result.add(path.getIOFile());
   }
   return result;
 }
Esempio n. 10
0
 public ParseStoredExpr(Map<String, Map<String, Double>> stored) {
   storedExpr = stored;
   SortedSet<String> exptNameSet = new TreeSet<String>(storedExpr.keySet());
   SortedSet<String> orfNameSet = new TreeSet<String>();
   exptNames = new String[exptNameSet.size()];
   int i = 0;
   for (String exptName : exptNameSet) {
     exptNames[i++] = exptName;
     System.out.println(i + ": " + exptNames[i - 1] + " (" + exptName + ")");
     orfNameSet.addAll(storedExpr.get(exptName).keySet());
   }
   orfs = new String[orfNameSet.size()];
   i = 0;
   for (String orfName : orfNameSet) {
     orfs[i++] = orfName;
   }
 }
 @Override
 protected Integer detectCurrentVersionNumber() throws IOException {
   SortedSet<CueballFilePath> localBases = Cueball.getBases(localPartitionRoot);
   if (localBases.size() > 0) {
     return localBases.last().getVersion();
   } else {
     return null;
   }
 }
Esempio n. 12
0
 /**
  * The earliest start date of this research staff.
  *
  * @return the active date
  */
 @Transient
 public Date getActiveDate() {
   SortedSet<Date> dates = new TreeSet<Date>();
   for (SiteResearchStaff srs : this.getSiteResearchStaffs()) {
     Date activeDate = srs.getActiveDate();
     if (activeDate != null) dates.add(activeDate);
   }
   if (dates.size() > 0) return dates.first();
   else return null;
 }
  /**
   * Read last n line from file
   *
   * @param n
   * @return
   * @throws IOException
   */
  public SortedMap<Integer, String> tail(int n) throws IOException {
    assertIsOpen();
    if (n < 1) {
      throw new IllegalArgumentException("'n' must be greater than or equal to 1");
    }

    int from = index.size() - n;
    int to = from + n;
    return readLines(from, to);
  }
  /** Scratch method for Lane to work on Fast Intersection */
  public static void fastIntersection() {

    SortedSet<Integer> setA = new TreeSet<Integer>();
    SortedSet<Integer> setB = new TreeSet<Integer>();

    Random rand = new Random();

    for (int i = 0; i < 100000; i++) {
      setA.add(rand.nextInt());
    }

    List<Integer> dataSet = new ArrayList<Integer>(setA);

    for (int i = 0; i < 50; i++) {
      setB.add(rand.nextInt());
      setB.add(dataSet.get(rand.nextInt(setA.size())));
    }

    List<Integer> querySet = new ArrayList<Integer>(setB);

    // for (int i=0, n=dataSet.size(); i < n; i++, n++) dataSet.get(i);

    // Calculate intersection

    // List<Integer> intersection = new ArrayList<Integer>();
    /*
    for (int query : querySet) {
    	//System.out.println("Querying for " + query);
    	if (Collections.binarySearch(dataSet, query) >= 0) {
    		intersection.add(query);
    	}
    }
    */

    SortedSet<Integer> intersection = new TreeSet<Integer>();

    fastIntersect(dataSet, querySet, intersection);

    System.out.println(intersection.size());
    // int medianQuery = querySet.get(querySet.size()/2);
  }
Esempio n. 15
0
  /**
   * Returns all supported sample rates.
   *
   * @return an array of sample rates, in Hertz, never <code>null</code>.
   */
  public Integer[] getSampleRates() {
    final String rawValue = this.properties.get(DEVICE_SAMPLERATES);
    final String[] values = rawValue.split(",\\s*");
    final SortedSet<Integer> result =
        new TreeSet<Integer>(
            NumberUtils.<Integer>createNumberComparator(false /* aSortAscending */));
    for (String value : values) {
      result.add(Integer.valueOf(value.trim()));
    }

    return result.toArray(new Integer[result.size()]);
  }
Esempio n. 16
0
  private void storeGraph(Graph graph) {
    if (numPatternsToStore < 1) return;

    if (topGraphs.isEmpty() || score > topGraphs.first().getScore()) {
      Graph graphCopy = new EdgeListGraphSingleConnections(graph);

      topGraphs.add(new ScoredGraph(graphCopy, score));

      if (topGraphs.size() > getNumPatternsToStore()) {
        topGraphs.remove(topGraphs.first());
      }
    }
  }
  public RecalibrationReport(final File recalFile, final SortedSet<String> allReadGroups) {
    final GATKReport report = new GATKReport(recalFile);

    argumentTable = report.getTable(RecalUtils.ARGUMENT_REPORT_TABLE_TITLE);
    RAC = initializeArgumentCollectionTable(argumentTable);

    GATKReportTable quantizedTable = report.getTable(RecalUtils.QUANTIZED_REPORT_TABLE_TITLE);
    quantizationInfo = initializeQuantizationTable(quantizedTable);

    Pair<ArrayList<Covariate>, ArrayList<Covariate>> covariates =
        RecalUtils.initializeCovariates(RAC); // initialize the required and optional covariates
    ArrayList<Covariate> requiredCovariates = covariates.getFirst();
    ArrayList<Covariate> optionalCovariates = covariates.getSecond();
    requestedCovariates = new Covariate[requiredCovariates.size() + optionalCovariates.size()];
    optionalCovariateIndexes = new HashMap<String, Integer>(optionalCovariates.size());
    int covariateIndex = 0;
    for (final Covariate covariate : requiredCovariates)
      requestedCovariates[covariateIndex++] = covariate;
    for (final Covariate covariate : optionalCovariates) {
      requestedCovariates[covariateIndex] = covariate;
      final String covariateName =
          covariate
              .getClass()
              .getSimpleName()
              .split("Covariate")[
              0]; // get the name of the covariate (without the "covariate" part of it) so we can
                  // match with the GATKReport
      optionalCovariateIndexes.put(covariateName, covariateIndex - 2);
      covariateIndex++;
    }

    for (Covariate cov : requestedCovariates)
      cov.initialize(
          RAC); // initialize any covariate member variables using the shared argument collection

    recalibrationTables = new RecalibrationTables(requestedCovariates, allReadGroups.size());

    initializeReadGroupCovariates(allReadGroups);

    parseReadGroupTable(
        report.getTable(RecalUtils.READGROUP_REPORT_TABLE_TITLE),
        recalibrationTables.getReadGroupTable());

    parseQualityScoreTable(
        report.getTable(RecalUtils.QUALITY_SCORE_REPORT_TABLE_TITLE),
        recalibrationTables.getQualityScoreTable());

    parseAllCovariatesTable(
        report.getTable(RecalUtils.ALL_COVARIATES_REPORT_TABLE_TITLE), recalibrationTables);
  }
Esempio n. 18
0
  /**
   * Prints one Unicode property value per line, along with its aliases, if any, for the given
   * unicodeVersion.
   *
   * @param unicodeVersion The Unicode version to print property values and aliases for
   * @throws UnicodeProperties.UnsupportedUnicodeVersionException if unicodeVersion is not supported
   */
  private static void printUnicodePropertyValuesAndAliases(String unicodeVersion)
      throws UnicodeProperties.UnsupportedUnicodeVersionException {
    Pattern versionPattern = Pattern.compile("(\\d+)(?:\\.(\\d+))?(?:\\.\\d+)?");
    Matcher matcher = versionPattern.matcher(unicodeVersion);
    if (!matcher.matches()) {
      throw new UnicodeProperties.UnsupportedUnicodeVersionException();
    }
    String underscoreVersion =
        matcher.group(1) + (null == matcher.group(2) ? "_0" : "_" + matcher.group(2));

    String[] propertyValues;
    String[] propertyValueAliases;
    try {
      Class<?> clazz = Class.forName("jflex.unicode.data.Unicode_" + underscoreVersion);
      Field field = clazz.getField("propertyValues");
      propertyValues = (String[]) field.get(null);
      field = clazz.getField("propertyValueAliases");
      propertyValueAliases = (String[]) field.get(null);
    } catch (Exception e) {
      throw new UnicodeProperties.UnsupportedUnicodeVersionException();
    }
    SortedMap<String, SortedSet<String>> propertyValuesToAliases =
        new TreeMap<String, SortedSet<String>>();
    for (String value : propertyValues) {
      propertyValuesToAliases.put(value, new TreeSet<String>());
    }
    for (int i = 0; i < propertyValueAliases.length; i += 2) {
      String alias = propertyValueAliases[i];
      String value = propertyValueAliases[i + 1];
      SortedSet<String> aliases = propertyValuesToAliases.get(value);
      if (null == aliases) {
        aliases = new TreeSet<String>();
        propertyValuesToAliases.put(value, aliases);
      }
      aliases.add(alias);
    }
    for (Map.Entry<String, SortedSet<String>> entry : propertyValuesToAliases.entrySet()) {
      String value = entry.getKey();
      SortedSet<String> aliases = entry.getValue();
      Out.print(value);
      if (aliases.size() > 0) {
        for (String alias : aliases) {
          Out.print(", " + alias);
        }
      }
      Out.println("");
    }
  }
Esempio n. 19
0
  @Test
  public void canGetAllKeysAsSortedSet() {
    Map<String, String> map = new HashMap<>();

    map.put("key2", "value2");
    map.put("key1", "value1");
    map.put("key3", "value3");

    SortedSet<String> keys = new TreeSet<String>(map.keySet());

    String[] keysa = new String[keys.size()];
    keys.toArray(keysa);

    assertEquals("key1", keysa[0]);
    assertEquals("key2", keysa[1]);
    assertEquals("key3", keysa[2]);
  }
Esempio n. 20
0
 /**
  * Tests if a specific relation type is defined.
  *
  * <p>Note that this routine returns false both when a snumber/dnumber are swapped, and when a
  * typecombo does not exist - it is not possible to derive whether one or the other has occurred.
  *
  * <p>
  *
  * @param n1 The source type number.
  * @param n2 The destination type number.
  * @param r The relation definition (role) number, or -1 if the role does not matter r can only be
  *     -1 if virtual is <code>true</code>
  * @param restriction if {@link #STRICT}, contains only returns true if the typerel occurs as-is
  *     in the database. if {@link #INCLUDE_DESCENDANTS}, contains returns true if the typerel
  *     occurs as a virtual (derived) node, where source or destination may also be descendants of
  *     the specified type. if {@link #INCLUDE_PARENTS}, contains returns true if the typerel
  *     occurs as a virtual (derived) node, where source or destination may also be parents of the
  *     specified type. if {@link #INCLUDE_PARENTS_AND_DESCENDANTS}, contains returns true if the
  *     typerel occurs as a virtual (derived) node, where source or destination may also be
  *     descendants or parents of the specified type.
  * @return <code>true</code> when the relation exists, false otherwise.
  * @since MMBase-1.6.2
  */
 public boolean contains(int n1, int n2, int r, int restriction) {
   switch (restriction) {
     case INCLUDE_DESCENDANTS:
       return typeRelNodes.contains(new VirtualTypeRelNode(n1, n2, r));
     case INCLUDE_PARENTS:
       return parentTypeRelNodes.contains(new VirtualTypeRelNode(n1, n2, r));
     case INCLUDE_PARENTS_AND_DESCENDANTS:
       return typeRelNodes.contains(new VirtualTypeRelNode(n1, n2, r))
           || parentTypeRelNodes.contains(new VirtualTypeRelNode(n1, n2, r));
     case STRICT:
       SortedSet<MMObjectNode> existingNodes = typeRelNodes.getBySourceDestinationRole(n1, n2, r);
       return (existingNodes.size() > 0 && !existingNodes.first().isVirtual());
     default:
       log.error("Unknown restriction " + restriction);
       return false;
   }
 }
Esempio n. 21
0
 /** @tests java.util.TreeSet#TreeSet(java.util.SortedSet) */
 public void test_ConstructorLjava_util_SortedSet() {
   // Test for method java.util.TreeSet(java.util.SortedSet)
   ReversedIntegerComparator comp = new ReversedIntegerComparator();
   SortedSet myTreeSet = db.createTreeSet("test", comp, null);
   for (int i = 0; i < objArray.length; i++) myTreeSet.add(objArray[i]);
   SortedSet anotherTreeSet = db.getTreeSet("test");
   anotherTreeSet.addAll(myTreeSet);
   assertTrue("TreeSet is not correct size", anotherTreeSet.size() == objArray.length);
   for (int counter = 0; counter < objArray.length; counter++)
     assertTrue(
         "TreeSet does not contain correct elements", anotherTreeSet.contains(objArray[counter]));
   assertEquals(
       "TreeSet does not answer correct comparator",
       anotherTreeSet.comparator().getClass(),
       comp.getClass());
   assertEquals(
       "TreeSet does not use comparator", anotherTreeSet.first(), objArray[objArray.length - 1]);
 }
Esempio n. 22
0
 /**
  * Does this match?
  *
  * @param token The current token
  * @param no The token number
  * @param stack The fork stack... may be used if there are partial matches
  * @param lookBackStack The reverse stack (ignored)
  */
 public TypeExpr matches(Token token, int no, Stack<MatchFork> stack, List<Token> lookBackStack) {
   if (matches == null) {
     if (set) {
       matches = new TreeSet<WordListEntry>();
       WordListSet wls = WordListSet.getWordListSetByName(wordListName);
       if (wls == null) {
         throw new IllegalArgumentException("Cannot find word list set %" + wordListName);
       }
       for (Map.Entry<String, WordList> entry : wls.getWordListSets()) {
         matches.addAll(WordListSet.getMatchSet(entry.getKey(), token.termText().toLowerCase()));
       }
       // currentMatch = wls.getEntry(token.termText().toLowerCase());
       currentMatch = new WordListEntry(new LinkedList<String>());
       currentMatch.addWord(token.term().toLowerCase());
     } else {
       matches =
           new TreeSet<WordListEntry>(
               WordListSet.getMatchSet(wordListName, token.termText().toLowerCase()));
       // currentMatch =
       // WordListSet.getWordListSetByList(wordListName).getEntry(token.termText().toLowerCase());
       currentMatch = new WordListEntry(new LinkedList<String>());
       currentMatch.addWord(token.term().toLowerCase());
     }
   } else {
     currentMatch.addWord(token.termText().toLowerCase());
   }
   MatchFork mf = MatchFork.find(stack, no, this);
   if (mf != null && (mf.used == true || stack.peek() == mf)) {
     stack.peek().split(no, this);
     return this;
   }
   Iterator<WordListEntry> wleIter = matches.iterator();
   while (wleIter.hasNext()) {
     WordListEntry wle = wleIter.next();
     if (wle.equals(currentMatch)) {
       if (matches.size() > 1 && (stack.empty() || stack.peek().tokenNo < no))
         stack.push(new MatchFork(no, this));
       return next;
     }
     if (!wle.matchable(currentMatch)) wleIter.remove();
   }
   if (matches.isEmpty()) return null;
   else return this;
 }
Esempio n. 23
0
  public static String getNext(SortedSet<String> slines, String num) {
    String nxt = "";
    SortedSet<String> candidates = new TreeSet<String>();
    for (String s : slines) {
      if (s.contains(num) && s.indexOf(num) < s.length() - 1) {
        candidates.add(s.split("")[s.indexOf(num) + 1]);
      }
    }
    // System.out.println(candidates);
    if (candidates.size() == 0) return null;
    nxt = candidates.first();
    for (String s : slines) {
      for (String c : candidates) {
        if (s.contains(c) && s.contains(nxt) && s.indexOf(c) < s.indexOf(nxt)) nxt = c;
      }
    }

    return nxt;
  }
 /**
  * 遍历时间触发器,如果已经达到执行时间,那么就执行任务回调
  *
  * @param now
  * @return
  */
 public List<TaskTrigger> acquireNextTriggers(long now) {
   List<TaskTrigger> taskTriggerList = null;
   try {
     if (timeTriggers.size() > 0) {
       // 获取离当前时间最近要执行的
       Long time = timeTriggers.first();
       if (time != null) {
         // 与当前时间比对,如果到达执行时间点
         if (time <= now) {
           timeTriggers.remove(time);
           taskTriggerList = triggerMap.get(time);
           triggerMap.remove(time);
         }
       }
     }
   } catch (Exception e) {
     logger.error("acquireNextTriggers error", e);
   }
   return taskTriggerList;
 }
Esempio n. 25
0
  /** @tests java.util.TreeSet#subSet(java.lang.Object, java.lang.Object) */
  public void test_subSetLjava_lang_ObjectLjava_lang_Object() {
    // Test for method java.util.SortedSet
    // java.util.TreeSet.subSet(java.lang.Object, java.lang.Object)
    final int startPos = objArray.length / 4;
    final int endPos = 3 * objArray.length / 4;
    SortedSet aSubSet = ts.subSet(objArray[startPos], objArray[endPos]);
    assertTrue("Subset has wrong number of elements", aSubSet.size() == (endPos - startPos));
    for (int counter = startPos; counter < endPos; counter++)
      assertTrue(
          "Subset does not contain all the elements it should",
          aSubSet.contains(objArray[counter]));

    int result;
    try {
      ts.subSet(objArray[3], objArray[0]);
      result = 0;
    } catch (IllegalArgumentException e) {
      result = 1;
    }
    assertEquals("end less than start should throw", 1, result);
  }
Esempio n. 26
0
  /** Create a new set of shared job state counters for all jobs in the given group. */
  public void initCounters(TaskTimer timer, QueueJobGroup group) {
    long groupID = group.getGroupID();

    if (LogMgr.getInstance().isLoggable(LogMgr.Kind.Ops, LogMgr.Level.Finest))
      LogMgr.getInstance()
          .log(LogMgr.Kind.Ops, LogMgr.Level.Finest, "Init Job Counts for Group (" + groupID + ")");

    SortedSet<Long> jobIDs = group.getJobIDs();
    Counters counters = new Counters(jobIDs.size());

    timer.acquire();
    synchronized (pCountersByGroup) {
      timer.resume();

      if (pCountersByGroup.put(groupID, counters) != null)
        LogMgr.getInstance()
            .logAndFlush(
                LogMgr.Kind.Ops,
                LogMgr.Level.Warning,
                "Somehow the job group ("
                    + groupID
                    + ") was already in the state "
                    + "counts table!");
    }

    timer.acquire();
    synchronized (pCountersByJob) {
      timer.resume();

      for (Long jobID : jobIDs) {
        if (pCountersByJob.put(jobID, counters) != null)
          LogMgr.getInstance()
              .logAndFlush(
                  LogMgr.Kind.Ops,
                  LogMgr.Level.Warning,
                  "Somehow the job (" + jobID + ") was already in the state counts table!");
      }
    }
  }
Esempio n. 27
0
 /** Computes results as a vector of type DoubleMatrix */
 public void computeComparableResultVector() {
   log.info("Computing comparable result vector...");
   if (!(sortedRePrPairs != null))
     log.error("Attempted to compute results vector before results.");
   assert sortedRePrPairs != null : "Attempted to compute results vector before results.";
   categToInt = new HashMap<TypeR, Integer>();
   resultVector = DoubleMatrix.zeros(sortedQuestions.size());
   categoriesMat = DoubleMatrix.zeros(responseCategories.size());
   int temp = 1;
   for (TypeR iter : responseCategories) {
     categToInt.put(iter, temp);
     categoriesMat.put(temp - 1, temp);
     temp++;
   }
   if (log.isDebugEnabled()) log.debug("Computed map from categories to integers:\n" + categToInt);
   temp = 0;
   for (Pair<TypeR, Double> iter : sortedRePrPairs) {
     resultVector.put(temp, categToInt.get(iter.getFirst()));
     temp++;
   }
   if (log.isDebugEnabled()) log.debug("Computed results vector:\n" + resultVector);
   log.info("Computed result vector.");
 }
  private void buildToJsonForOption(
      PropertyWrapper pWrap, OJAnnotatedClass annotatedClass, OJBlock block) {

    SortedSet<Classifier> concreteImplementations =
        new TreeSet<Classifier>(
            new Comparator<Classifier>() {
              @Override
              public int compare(Classifier o1, Classifier o2) {
                return o1.getName().compareTo(o2.getName());
              }
            });

    // For derived unions only show tabs for each property that makes up the union.
    if (pWrap.isDerivedUnion()) {
      List<Property> subsettingProperties =
          ModelLoader.INSTANCE.findSubsettingProperties(pWrap.getProperty());
      for (Property subsettingProperty : subsettingProperties) {
        concreteImplementations.addAll(
            UmlgClassOperations.getConcreteImplementations(
                (Classifier) subsettingProperty.getType()));
      }
    } else {
      // For non derived union show all concrete implementations
      concreteImplementations =
          UmlgClassOperations.getConcreteImplementations((Classifier) pWrap.getType());
    }

    Set<Classifier> concreteImplementationsFrom =
        UmlgClassOperations.getConcreteImplementations((Classifier) pWrap.getOwningType());
    if (!concreteImplementationsFrom.isEmpty()) {
      annotatedClass.addToImports(UmlgGenerationUtil.ToJsonUtil);
      // blok get reassigned for the meta data if statement
      OJBlock returnBlock = block;
      block.addToStatements("StringBuilder json = new StringBuilder()");
      block.addToStatements("json.append(\"[\")");

      int count = 1;
      // For meta data, put where one is navigating to first, then where on is
      // navigating from
      // This is consistent with navigating to a entity with a vertex where
      // there is no navigating from.
      // i.e. the first meta data in the array is the entity navigating to.
      for (Classifier concreteClassifierTo : concreteImplementations) {
        annotatedClass.addToImports(UmlgClassOperations.getPathName(concreteClassifierTo));

        for (Classifier concreteClassifierFrom : concreteImplementationsFrom) {

          block.addToStatements("json.append(\"{\")");

          block.addToStatements("json.append(\" \\\"meta\\\" : {\")");
          block.addToStatements(
              "json.append(\"\\\"qualifiedName\\\": \\\"" + pWrap.getQualifiedName() + "\\\"\")");

          // The execute ocl query resource is only required if the below
          // visitor is available
          if (RestletVisitors.containsVisitorForClass(QueryExecuteResourceBuilder.class)
              && (pWrap
                      .getType()
                      .getQualifiedName()
                      .equals(UmlgRestletGenerationUtil.instanceQueryQualifiedName)
                  || pWrap
                      .getType()
                      .getQualifiedName()
                      .equals(UmlgRestletGenerationUtil.classQueryQualifiedName))) {
            block.addToStatements(
                "json.append(\", \\\"oclExecuteUri\\\": \\\"/"
                    + pWrap.getModel().getName()
                    + "/{contextId}/oclExecuteQuery\\\"\")");
          }
          block.addToStatements("json.append(\", \\\"to\\\": \")");
          OJBlock conditionBlockFrom = new OJBlock();
          annotatedClass.addToImports(UmlgClassOperations.getPathName(concreteClassifierFrom));

          conditionBlockFrom.addToStatements(
              "json.append("
                  + UmlgClassOperations.propertyEnumName(concreteClassifierTo)
                  + ".asJson())");
          conditionBlockFrom.addToStatements("json.append(\", \\\"from\\\": \")");
          conditionBlockFrom.addToStatements(
              "json.append("
                  + UmlgClassOperations.propertyEnumName(concreteClassifierFrom)
                  + ".asJson())");
          annotatedClass.addToImports(
              UmlgClassOperations.getPathName(concreteClassifierFrom)
                  .append(UmlgClassOperations.propertyEnumName(concreteClassifierFrom)));

          block.addToStatements(conditionBlockFrom);

          annotatedClass.addToImports(
              UmlgClassOperations.getPathName(pWrap.getOwningType())
                  .append(UmlgClassOperations.propertyEnumName(pWrap.getOwningType())));
          annotatedClass.addToImports(
              UmlgClassOperations.getPathName(concreteClassifierTo)
                  .append(UmlgClassOperations.propertyEnumName(concreteClassifierTo)));

          if (count++ < (concreteImplementations.size() * concreteImplementationsFrom.size())) {
            block.addToStatements("json.append(\"}},\")");
          } else {
            block.addToStatements("json.append(\"}}\")");
          }
        }
        block = returnBlock;
      }
      returnBlock.addToStatements("json.append(\"]\")");
      returnBlock.addToStatements(
          "return new "
              + UmlgRestletGenerationUtil.JsonRepresentation.getLast()
              + "(json.toString())");
    } else {
      // TODO not thought through
      block.addToStatements("return null");
    }
  }
  private void buildToJson(PropertyWrapper pWrap, OJAnnotatedClass annotatedClass, OJBlock block) {

    // This is very important to be a sorted set. The get and options method need to return the meta
    // data in the same order.
    // This allows the client to merge them easily

    SortedSet<Classifier> sortedConcreteImplementations =
        new TreeSet<Classifier>(
            new Comparator<Classifier>() {
              @Override
              public int compare(Classifier o1, Classifier o2) {
                return o1.getName().compareTo(o2.getName());
              }
            });

    // For derived unions only show tabs for each property that makes up the union.
    if (pWrap.isDerivedUnion()) {
      List<Property> subsettingProperties =
          ModelLoader.INSTANCE.findSubsettingProperties(pWrap.getProperty());
      for (Property subsettingProperty : subsettingProperties) {
        sortedConcreteImplementations.addAll(
            UmlgClassOperations.getConcreteImplementations(
                (Classifier) subsettingProperty.getType()));
      }
    } else {
      // For non derived union show all concrete implementations
      sortedConcreteImplementations =
          UmlgClassOperations.getConcreteImplementations((Classifier) pWrap.getType());
    }

    Set<Classifier> concreteImplementationsFrom =
        UmlgClassOperations.getConcreteImplementations((Classifier) pWrap.getOwningType());
    if (!concreteImplementationsFrom.isEmpty()) {
      annotatedClass.addToImports(UmlgGenerationUtil.ToJsonUtil);
      // block get reassigned for the meta data if statement
      OJBlock returnBlock = block;
      block.addToStatements("StringBuilder json = new StringBuilder()");
      block.addToStatements("json.append(\"[\")");

      int count = 1;
      // For meta data, put where one is navigating to first, then where on is
      // navigating from
      // This is consistent with navigating to a entity with a vertex where
      // there is no navigating from.
      // i.e. the first meta data in the array is the entity navigating to.
      for (Classifier concreteClassifierTo : sortedConcreteImplementations) {
        annotatedClass.addToImports(UmlgClassOperations.getPathName(concreteClassifierTo));
        if (pWrap.isOne()) {
          block.addToStatements("json.append(\"{\\\"data\\\": \")");
        } else {
          block.addToStatements("json.append(\"{\\\"data\\\": [\")");
        }
        if (pWrap.isOne()) {
          OJIfStatement ifOneInstanceOf =
              new OJIfStatement(
                  "parentResource."
                      + pWrap.getter()
                      + "() != null && parentResource."
                      + pWrap.getter()
                      + "().getClass() == "
                      + UmlgClassOperations.getPathName(concreteClassifierTo).getLast()
                      + ".class");
          ifOneInstanceOf.addToThenPart(
              "json.append("
                  + UmlgGenerationUtil.ToJsonUtil.getLast()
                  + ".toJsonWithoutCompositeParent(parentResource."
                  + pWrap.getter()
                  + "()))");
          ifOneInstanceOf.addToElsePart("json.append(\"null\")");
          block.addToStatements(ifOneInstanceOf);
        } else {
          block.addToStatements(
              "json.append("
                  + UmlgGenerationUtil.ToJsonUtil.getLast()
                  + ".toJsonWithoutCompositeParent(parentResource."
                  + pWrap.getter()
                  + "().select(new "
                  + UmlgGenerationUtil.BooleanExpressionEvaluator.getCopy()
                      .addToGenerics(UmlgClassOperations.getPathName(pWrap.getType()))
                      .getLast()
                  + "() {\n			@Override\n			public Boolean evaluate("
                  + UmlgClassOperations.getPathName(pWrap.getType()).getLast()
                  + " e) {\n				return e.getClass() == "
                  + UmlgClassOperations.getPathName(concreteClassifierTo).getLast()
                  + ".class;\n			}\n		})))");
          annotatedClass.addToImports(UmlgGenerationUtil.BooleanExpressionEvaluator);
        }
        annotatedClass.addToImports(UmlgClassOperations.getPathName(pWrap.getType()));
        if (pWrap.isOne()) {
          block.addToStatements("json.append(\",\")");
        } else {
          block.addToStatements("json.append(\"],\")");
        }

        block.addToStatements("json.append(\" \\\"meta\\\" : {\")");
        block.addToStatements(
            "json.append(\"\\\"qualifiedName\\\": \\\"" + pWrap.getQualifiedName() + "\\\"\")");

        block.addToStatements(
            "json.append(\",\\\"qualifiedNameFrom\\\": \\\"\" + parentResource.getQualifiedName() + \"\\\"\")");
        block.addToStatements(
            "json.append(\",\\\"qualifiedNameTo\\\": \\\""
                + concreteClassifierTo.getQualifiedName()
                + "\\\"\")");

        block.addToStatements("json.append(\"}\")");
        if (sortedConcreteImplementations.size() != 1
            && count != sortedConcreteImplementations.size()) {
          block.addToStatements("json.append(\"}, \")");
        }
        block = returnBlock;
        count++;
      }
      returnBlock.addToStatements("json.append(\"}]\")");
      returnBlock.addToStatements(
          "return new "
              + UmlgRestletGenerationUtil.JsonRepresentation.getLast()
              + "(json.toString())");
    } else {
      // TODO not thought through
      block.addToStatements("return null");
    }
  }
 int getActiveThreadCount() {
   return active_threads.size();
 }