/**
   * Returns submap of x and y values according to the given start and end
   *
   * @param start start x value
   * @param stop stop x value
   * @return a submap of x and y values
   */
  public synchronized SortedMap<Double, Double> getRange(
      double start, double stop, int beforeAfterPoints) {
    // we need to add one point before the start and one point after the end (if
    // there are any)
    // to ensure that line doesn't end before the end of the screen

    // this would be simply: start = mXY.lowerKey(start) but NavigableMap is
    // available since API 9
    SortedMap<Double, Double> headMap = mXY.headMap(start);
    if (!headMap.isEmpty()) {
      start = headMap.lastKey();
    }

    // this would be simply: end = mXY.higherKey(end) but NavigableMap is
    // available since API 9
    // so we have to do this hack in order to support older versions
    SortedMap<Double, Double> tailMap = mXY.tailMap(stop);
    if (!tailMap.isEmpty()) {
      Iterator<Double> tailIterator = tailMap.keySet().iterator();
      Double next = tailIterator.next();
      if (tailIterator.hasNext()) {
        stop = tailIterator.next();
      } else {
        stop += next;
      }
    }
    return new TreeMap<Double, Double>(mXY.subMap(start, stop));
  }
 public void testDescendingSubMapContents2() {
   ConcurrentNavigableMap map = dmap5();
   SortedMap sm = map.subMap(m2, m3);
   assertEquals(1, sm.size());
   assertEquals(m2, sm.firstKey());
   assertEquals(m2, sm.lastKey());
   assertFalse(sm.containsKey(m1));
   assertTrue(sm.containsKey(m2));
   assertFalse(sm.containsKey(m3));
   assertFalse(sm.containsKey(m4));
   assertFalse(sm.containsKey(m5));
   Iterator i = sm.keySet().iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(m2, k);
   assertFalse(i.hasNext());
   Iterator j = sm.keySet().iterator();
   j.next();
   j.remove();
   assertFalse(map.containsKey(m2));
   assertEquals(4, map.size());
   assertEquals(0, sm.size());
   assertTrue(sm.isEmpty());
   assertSame(sm.remove(m3), null);
   assertEquals(4, map.size());
 }
 public void testSubMapContents2() {
   ConcurrentNavigableMap map = map5();
   SortedMap sm = map.subMap(two, three);
   assertEquals(1, sm.size());
   assertEquals(two, sm.firstKey());
   assertEquals(two, sm.lastKey());
   assertFalse(sm.containsKey(one));
   assertTrue(sm.containsKey(two));
   assertFalse(sm.containsKey(three));
   assertFalse(sm.containsKey(four));
   assertFalse(sm.containsKey(five));
   Iterator i = sm.keySet().iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(two, k);
   assertFalse(i.hasNext());
   Iterator j = sm.keySet().iterator();
   j.next();
   j.remove();
   assertFalse(map.containsKey(two));
   assertEquals(4, map.size());
   assertEquals(0, sm.size());
   assertTrue(sm.isEmpty());
   assertSame(sm.remove(three), null);
   assertEquals(4, map.size());
 }
 /**
  * Returns the number of option values amongst all internal option containers.
  *
  * @return the number of option values amongst all internal option containers
  */
 public int getNumberOfOptionValues() {
   SortedSet<Option> union = new TreeSet<Option>(savedOptionMap.keySet());
   union.addAll(dependenciesResolvedOptionMap.keySet());
   union.addAll(commandLineOptionMap.keySet());
   union.addAll(optionFileOptionMap.keySet());
   return union.size();
 }
 /* (non-Javadoc)
  * @see java.lang.Object#toString()
  */
 public String toString() {
   final StringBuilder sb = new StringBuilder();
   SortedSet<Option> union = new TreeSet<Option>(savedOptionMap.keySet());
   union.addAll(dependenciesResolvedOptionMap.keySet());
   union.addAll(commandLineOptionMap.keySet());
   union.addAll(optionFileOptionMap.keySet());
   for (Option option : union) {
     Object value = null;
     for (int i = OptionContainer.SAVEDOPTION; i <= OptionContainer.OPTIONFILE; i++) {
       if (i == OptionContainer.SAVEDOPTION) {
         value = savedOptionMap.get(option);
       } else if (i == OptionContainer.DEPENDENCIES_RESOLVED) {
         value = dependenciesResolvedOptionMap.get(option);
       } else if (i == OptionContainer.COMMANDLINE) {
         value = commandLineOptionMap.get(option);
       } else if (i == OptionContainer.OPTIONFILE) {
         value = optionFileOptionMap.get(option);
       }
       if (value != null) {
         break;
       }
     }
     sb.append(option.getGroup().getName() + "\t" + option.getName() + "\t" + value + "\n");
   }
   return sb.toString();
 }
Ejemplo n.º 6
0
  public void noMoreInstances() throws MaltChainedException {
    //		if (getGuide().getGuideMode() == Guide.GuideMode.CLASSIFY) {
    //			throw new GuideException("Can only finish all data during learning. ");
    //		}

    if (divideModels != null) {
      divideFeature.updateCardinality();
      for (Integer index : divideModels.keySet()) {
        divideModels.get(index).noMoreInstances();
      }
      final TreeSet<Integer> removeSet = new TreeSet<Integer>();
      for (Integer index : divideModels.keySet()) {
        if (divideModels.get(index).getFrequency() <= divideThreshold) {
          divideModels
              .get(index)
              .moveAllInstances(masterModel, divideFeature, divideFeatureIndexVector);
          removeSet.add(index);
        }
      }
      for (Integer index : removeSet) {
        divideModels.remove(index);
      }
      masterModel.noMoreInstances();

    } else {
      throw new GuideException("The feature divide models cannot be found. ");
    }
  }
  private void algorithm(
      int initialSl,
      SortedMap bslToList,
      BundleInfo configuratorBInfo,
      List setToInitialConfig,
      List setToSimpleConfig,
      LocationInfo info) {
    int configuratorSL = configuratorBInfo.getStartLevel();

    Integer sL0 = (Integer) bslToList.keySet().iterator().next(); // StartLevel == 0;
    List list0 = (List) bslToList.get(sL0);
    if (sL0.intValue() == 0)
      for (Iterator ite2 = list0.iterator(); ite2.hasNext(); ) {
        BundleInfo bInfo = (BundleInfo) ite2.next();
        if (isSystemBundle(bInfo.getLocation(), info)) {
          setToSimpleConfig.add(bInfo);
          break;
        }
      }

    for (Iterator ite = bslToList.keySet().iterator(); ite.hasNext(); ) {
      Integer sL = (Integer) ite.next();
      List list = (List) bslToList.get(sL);

      if (sL.intValue() < configuratorSL) {
        for (Iterator ite2 = list.iterator(); ite2.hasNext(); ) {
          BundleInfo bInfo = (BundleInfo) ite2.next();
          if (!isSystemBundle(bInfo.getLocation(), info)) setToInitialConfig.add(bInfo);
        }
      } else if (sL.intValue() > configuratorSL) {
        for (Iterator ite2 = list.iterator(); ite2.hasNext(); ) {
          BundleInfo bInfo = (BundleInfo) ite2.next();
          if (isPrerequisiteBundles(bInfo.getLocation(), info)
              || isSystemFragmentBundle(bInfo.getLocation(), info))
            if (!isSystemBundle(bInfo.getLocation(), info)) setToInitialConfig.add(bInfo);
          setToSimpleConfig.add(bInfo);
        }
      } else {
        boolean found = false;
        for (Iterator ite2 = list.iterator(); ite2.hasNext(); ) {
          BundleInfo bInfo = (BundleInfo) ite2.next();
          if (found) {
            if (!isSystemBundle(bInfo.getLocation(), info))
              if (isPrerequisiteBundles(bInfo.getLocation(), info)
                  || isSystemFragmentBundle(bInfo.getLocation(), info))
                setToInitialConfig.add(bInfo);
            setToSimpleConfig.add(bInfo);
            continue;
          }
          if (isTargetConfiguratorBundle(bInfo.getLocation())) found = true;
          else if (!isSystemBundle(bInfo.getLocation(), info)) setToInitialConfig.add(bInfo);
          setToSimpleConfig.add(bInfo);
        }
      }
    }

    setToInitialConfig.add(configuratorBInfo);
  }
Ejemplo n.º 8
0
  private boolean logPropertyDifferences(
      String message, SortedMap<String, Class> prevMap, SortedMap<String, Class> newMap) {
    boolean foundDifference = false;
    for (String prevKey : prevMap.keySet()) {

      if (nonVersionSpecificAttributes.contains(prevKey)) continue;

      Class prevClass = prevMap.get(prevKey);
      Class newClass = newMap.get(prevKey);

      if (prevClass != null && prevClass != newClass) {
        if (newClass == null) {
          if (!foundDifference) {
            log.info(message);
            foundDifference = true;
          }
          log.info(
              "\tnew event missing field in prev event: %s = %s",
              prevKey, prevClass.getSimpleName());
        } else {
          if (!foundDifference) {
            log.info(message);
            foundDifference = true;
          }
          // should fail in subsequent esper update anyway
          log.warn(
              "\tnew event has new type for %s, prev: %s, new: %s",
              prevKey, prevClass.getSimpleName(), newClass.getSimpleName());
        }
      }
    }

    for (String newKey : newMap.keySet()) {

      if (nonVersionSpecificAttributes.contains(newKey)) continue;

      Class newClass = newMap.get(newKey);
      Class prevClass = prevMap.get(newKey);

      if (newClass != null && prevClass != newClass) {
        if (prevClass == null) {
          if (!foundDifference) {
            log.info(message);
            foundDifference = true;
          }
          log.info("\tnew event has new field: %s = %s", newKey, newClass.getSimpleName());
        }
      }
    }

    return foundDifference;
  }
  /** writes activity type to typical activity duration to file. */
  private void writeTypicalAndMinimumActivityDurations(final String configFile) {

    Config config = new Config();
    config.addCoreModules();
    ConfigReader reader = new ConfigReader(config);
    reader.readFile(configFile);

    SortedMap<String, Double> act2TypDur = new TreeMap<>();
    SortedMap<String, Double> act2MinDur = new TreeMap<>();

    for (String actTyp : config.planCalcScore().getActivityTypes()) {
      act2TypDur.put(actTyp, config.planCalcScore().getActivityParams(actTyp).getTypicalDuration());
      act2MinDur.put(actTyp, config.planCalcScore().getActivityParams(actTyp).getMinimalDuration());
    }

    String fileName = outputDir + "/analysis/actTyp2TypicalAndMinimumActDurations.txt";
    BufferedWriter writer = IOUtils.getBufferedWriter(fileName);
    try {
      writer.write("actType \t typicalActDuration \t minimumActDuration \n");
      for (String actTyp : act2MinDur.keySet()) {
        writer.write(actTyp + "\t" + act2TypDur.get(actTyp) + "\t" + act2MinDur.get(actTyp) + "\n");
      }
      writer.close();
    } catch (Exception e) {
      throw new RuntimeException("Data is not written. Reason - " + e);
    }
    ActivityType2DurationHandler.LOG.info("Data is written to file " + fileName);
  }
Ejemplo n.º 10
0
  private String createParameterString() {

    // put required parameters
    for (OauthConstants constant : OauthConstants.values()) {
      String key = OAuth.percentEncode(constant.name());
      String value = OAuth.percentEncode(properties.getProperty(constant.name()));
      if (constant.equals(OauthConstants.oauth_nonce)) {
        value = OAuth.percentEncode(nonce);
      }
      if (constant.equals(OauthConstants.oauth_timestamp)) {
        value = OAuth.percentEncode(String.valueOf(timestamp));
      }
      parameterMap.put(key, value);
    }

    // put optional parameters
    for (Object key_ : optionalParameters.keySet()) {
      String keyStr = (String) key_;
      String key = OAuth.percentEncode(keyStr);
      String value = OAuth.percentEncode(optionalParameters.get(keyStr).toString());
      parameterMap.put(key, value);
    }

    StringBuilder builder = new StringBuilder();

    for (String s : parameterMap.keySet()) {
      builder.append(s).append('=').append(parameterMap.get(s)).append("&");
    }
    builder.setLength(builder.lastIndexOf("&"));
    return builder.toString();
  }
Ejemplo n.º 11
0
 private Integer getBin(SortedMap<Integer, Integer[]> distribution, Double distance) {
   Integer bin = distribution.firstKey();
   for (Integer nextBin : distribution.keySet())
     if (distance < nextBin) return bin;
     else bin = nextBin;
   return bin;
 }
Ejemplo n.º 12
0
 /**
  * Pushes a new Construct onto the end of the array. If the index is specified, this works like a
  * "insert" operation, in that all values are shifted to the right, starting with the value at
  * that index. If the array is associative though, you MUST send null, otherwise an {@link
  * IllegalArgumentException} is thrown. Ideally, you should use {@link #set} anyways for an
  * associative array.
  *
  * @param c The Construct to add to the array
  * @throws IllegalArgumentException If index is not null, and this is an associative array.
  * @throws IndexOutOfBoundsException If the index is not null, and the index specified is out of
  *     range.
  */
 public void push(Construct c, Integer index, Target t)
     throws IllegalArgumentException, IndexOutOfBoundsException {
   if (!associative_mode) {
     if (index != null) {
       array.add(index, c);
     } else {
       array.add(c);
     }
     next_index++;
   } else {
     if (index != null) {
       throw new IllegalArgumentException("Cannot insert into an associative array");
     }
     int max = 0;
     for (String key : associative_array.keySet()) {
       try {
         int i = Integer.parseInt(key);
         max = java.lang.Math.max(max, i);
       } catch (NumberFormatException e) {
       }
     }
     if (c instanceof CEntry) {
       associative_array.put(Integer.toString(max + 1), ((CEntry) c).construct());
     } else {
       associative_array.put(Integer.toString(max + 1), c);
     }
   }
   if (c instanceof CArray) {
     ((CArray) c).parent = this;
   }
   regenValue(new HashSet<CArray>());
 }
Ejemplo n.º 13
0
 public CArray(Target t, int initialCapacity, Construct... items) {
   super("{}", ConstructType.ARRAY, t);
   if (initialCapacity == -1) {
     associative_mode = true;
   } else if (items != null) {
     for (Construct item : items) {
       if (item instanceof CEntry) {
         // it's an associative array
         associative_mode = true;
         break;
       }
     }
   }
   associative_array = new TreeMap<>(comparator);
   array =
       associative_mode
           ? new ArrayList<Construct>()
           : initialCapacity > 0
               ? new ArrayList<Construct>(initialCapacity)
               : items != null
                   ? new ArrayList<Construct>(items.length)
                   : new ArrayList<Construct>();
   if (associative_mode) {
     if (items != null) {
       for (Construct item : items) {
         if (item instanceof CEntry) {
           associative_array.put(
               normalizeConstruct(((CEntry) item).ckey), ((CEntry) item).construct);
         } else {
           int max = Integer.MIN_VALUE;
           for (String key : associative_array.keySet()) {
             try {
               int i = Integer.parseInt(key);
               max = java.lang.Math.max(max, i);
             } catch (NumberFormatException e) {
             }
           }
           if (max == Integer.MIN_VALUE) {
             max = -1; // Special case, there are no integer indexes in here yet.
           }
           associative_array.put(Integer.toString(max + 1), item);
           if (item instanceof CArray) {
             ((CArray) item).parent = this;
           }
         }
       }
     }
   } else {
     if (items != null) {
       for (Construct item : items) {
         array.add(item);
         if (item instanceof CArray) {
           ((CArray) item).parent = this;
         }
       }
     }
     this.next_index = array.size();
   }
   regenValue(new HashSet<CArray>());
 }
Ejemplo n.º 14
0
 public static Combo createEncodingCombo(Composite parent, String curCharset) {
   if (curCharset == null) {
     curCharset = GeneralUtils.getDefaultFileEncoding();
   }
   Combo encodingCombo = new Combo(parent, SWT.DROP_DOWN);
   encodingCombo.setVisibleItemCount(30);
   SortedMap<String, Charset> charsetMap = Charset.availableCharsets();
   int index = 0;
   int defIndex = -1;
   for (String csName : charsetMap.keySet()) {
     Charset charset = charsetMap.get(csName);
     encodingCombo.add(charset.displayName());
     if (charset.displayName().equalsIgnoreCase(curCharset)) {
       defIndex = index;
     }
     if (defIndex < 0) {
       for (String alias : charset.aliases()) {
         if (alias.equalsIgnoreCase(curCharset)) {
           defIndex = index;
         }
       }
     }
     index++;
   }
   if (defIndex >= 0) {
     encodingCombo.select(defIndex);
   } else {
     log.warn("Charset '" + curCharset + "' is not recognized"); // $NON-NLS-1$ //$NON-NLS-2$
   }
   return encodingCombo;
 }
Ejemplo n.º 15
0
  private void resolveFields() {
    for (Method method : objectType.getMethods()) {
      if ((method.getModifiers() & Modifier.STATIC) != 0) {
        continue;
      }

      String fieldName = null;
      if (method.getName().startsWith("get")) {
        if (method.getName().equals("getId") || method.getName().length() <= 3) {
          continue;
        }
        // Found a field!
        fieldName = getFieldName(method.getName());
      } else if (method.getName().startsWith("is")) {
        if (method.getName().length() <= 2) {
          continue;
        }
        // Found a field!
        fieldName = getFieldName(method.getName());
      }

      if (fieldName != null) {
        fieldTypeMap.put(fieldName, method.getReturnType());
      }
    }

    int index = 0;
    for (String fieldName : fieldTypeMap.keySet()) {
      fieldIndexMap.put(fieldName, index++);
    }
  }
Ejemplo n.º 16
0
  /** Map from char */
  public char map(char src) {
    // find first segment with endcode > src
    for (Iterator i = segments.keySet().iterator(); i.hasNext(); ) {
      Segment s = (Segment) i.next();

      if (s.endCode >= src) {
        // are we within range?
        if (s.startCode <= src) {
          if (s.hasMap) {
            // return the index of this character in
            // the segment's map
            char[] map = (char[]) segments.get(s);
            return map[src - s.startCode];
          } else {
            // return the character code + idDelta
            Integer idDelta = (Integer) segments.get(s);
            return (char) (src + idDelta.intValue());
          }
        } else {
          // undefined character
          return (char) 0;
        }
      }
    }

    // shouldn't get here!
    return (char) 0;
  }
Ejemplo n.º 17
0
  /** Get the src code which maps to the given glyphID */
  public char reverseMap(short glyphID) {
    // look at each segment
    for (Iterator i = segments.keySet().iterator(); i.hasNext(); ) {
      Segment s = (Segment) i.next();

      // see if we have a map or a delta
      if (s.hasMap) {
        char[] map = (char[]) segments.get(s);

        // if we have a map, we have to iterate through it
        for (int c = 0; c < map.length; c++) {
          if (map[c] == glyphID) {
            return (char) (s.startCode + c);
          }
        }
      } else {
        Integer idDelta = (Integer) segments.get(s);

        // we can do the math to see if we're in range
        int start = s.startCode + idDelta.intValue();
        int end = s.endCode + idDelta.intValue();

        if (glyphID >= start && glyphID <= end) {
          // we're in the range
          return (char) (glyphID - idDelta.intValue());
        }
      }
    }

    // not found!
    return (char) 0;
  }
Ejemplo n.º 18
0
 public String[] getStocksInPortfolio() {
   Set<String> ids = stockmap.keySet();
   String[] result = new String[ids.size()];
   int i = 0;
   for (String s : ids) result[i++] = s;
   return result;
 }
Ejemplo n.º 19
0
  public static PackageInfo[] chooseModulePackages() {
    ClassInfo[] classes = Converter.rootClasses();
    SortedMap<String, PackageInfo> sorted = new TreeMap<String, PackageInfo>();
    for (ClassInfo cl : classes) {
      if (!cl.isModule()) {
        continue;
      }

      PackageInfo pkg = cl.containingPackage();
      String name;
      if (pkg == null) {
        name = "";
      } else {
        name = pkg.name();
      }
      sorted.put(name, pkg);
    }

    ArrayList<PackageInfo> result = new ArrayList<PackageInfo>();

    for (String s : sorted.keySet()) {
      PackageInfo pkg = sorted.get(s);

      result.add(pkg);
    }

    return result.toArray(new PackageInfo[result.size()]);
  }
Ejemplo n.º 20
0
 public boolean next(SubRequest request) {
   MOScope scope = request.getQuery().getScope();
   SortedMap<OID, Variable> tail = vbs.tailMap(scope.getLowerBound());
   OID first = tail.firstKey();
   if (scope.getLowerBound().equals(first) && (!scope.isLowerIncluded())) {
     if (tail.size() > 1) {
       Iterator<OID> it = tail.keySet().iterator();
       it.next();
       first = it.next();
     } else {
       return false;
     }
   }
   if (first != null) {
     Variable vb = vbs.get(first);
     if (vb == null) {
       request.getVariableBinding().setVariable(Null.noSuchInstance);
     }
     request.getVariableBinding().setOid(first);
     request.getVariableBinding().setVariable(vb);
     request.completed();
     return true;
   }
   return false;
 }
Ejemplo n.º 21
0
    /**
     * Construct a Strategy that parses a TimeZone
     *
     * @param locale The Locale
     */
    TimeZoneStrategy(final Locale locale) {
      final String[][] zones = DateFormatSymbols.getInstance(locale).getZoneStrings();
      for (String[] zone : zones) {
        if (zone[ID].startsWith("GMT")) {
          continue;
        }
        final TimeZone tz = TimeZone.getTimeZone(zone[ID]);
        if (!tzNames.containsKey(zone[LONG_STD])) {
          tzNames.put(zone[LONG_STD], tz);
        }
        if (!tzNames.containsKey(zone[SHORT_STD])) {
          tzNames.put(zone[SHORT_STD], tz);
        }
        if (tz.useDaylightTime()) {
          if (!tzNames.containsKey(zone[LONG_DST])) {
            tzNames.put(zone[LONG_DST], tz);
          }
          if (!tzNames.containsKey(zone[SHORT_DST])) {
            tzNames.put(zone[SHORT_DST], tz);
          }
        }
      }

      final StringBuilder sb = new StringBuilder();
      sb.append("(GMT[+\\-]\\d{0,1}\\d{2}|[+\\-]\\d{2}:?\\d{2}|");
      for (final String id : tzNames.keySet()) {
        escapeRegex(sb, id, false).append('|');
      }
      sb.setCharAt(sb.length() - 1, ')');
      validTimeZoneChars = sb.toString();
    }
Ejemplo n.º 22
0
  public void dumpHeader(TabbedPrintWriter writer) throws java.io.IOException {
    writer.println("/* " + className + " - Decompiled by JODE");
    writer.println(" * Visit " + GlobalOptions.URL);
    writer.println(" */");
    if (pkg.length() != 0) writer.println("package " + pkg + ";");

    cleanUpImports();
    Iterator iter = imports.keySet().iterator();
    String lastFirstPart = null;
    while (iter.hasNext()) {
      String pkgName = (String) iter.next();
      if (!pkgName.equals("java.lang.*")) {
        int firstDot = pkgName.indexOf('.');
        if (firstDot != -1) {
          String firstPart = pkgName.substring(0, firstDot);
          if (lastFirstPart != null && !lastFirstPart.equals(firstPart)) {
            writer.println("");
          }
          lastFirstPart = firstPart;
        }
        writer.println("import " + pkgName + ";");
      }
    }
    writer.println("");
  }
  /**
   * Method that combines the fingerprint evidence across all the read groups for the same sample
   * and then produces a matrix of LOD scores for comparing every sample with every other sample.
   */
  private void crossCheckSamples(final List<Fingerprint> fingerprints, final PrintStream out) {
    final SortedMap<String, Fingerprint> sampleFps =
        FingerprintChecker.mergeFingerprintsBySample(fingerprints);
    final SortedSet<String> samples = (SortedSet<String>) sampleFps.keySet();

    // Print header row
    out.print("\t");
    for (final String sample : samples) {
      out.print(sample);
      out.print("\t");
    }
    out.println();

    // Print results rows
    for (final String sample : samples) {
      out.print(sample);
      final Fingerprint fp = sampleFps.get(sample);

      for (final String otherSample : samples) {
        final MatchResults results =
            FingerprintChecker.calculateMatchResults(
                fp, sampleFps.get(otherSample), GENOTYPING_ERROR_RATE, LOSS_OF_HET_RATE);
        out.print("\t");
        out.print(formatUtil.format(results.getLOD()));
      }

      out.println();
    }
  }
Ejemplo n.º 24
0
  @Test
  public void testOrderBy() {
    final JPAEnvironment env = getEnvironment();
    final EntityManager em = env.getEntityManager();
    final SortedMap<String, Employee> attendeeMap = new TreeMap<String, Employee>();
    try {
      env.beginTransaction(em);
      final Course course = createAndPersistCourse(em);
      final Long courseId = Long.valueOf(course.getCourseId());
      final Employee employee1 = em.find(Employee.class, EMP_ID_DORIS);
      attendeeMap.put(employee1.getLastName(), employee1);
      final Employee employee2 = em.find(Employee.class, EMP_ID_SABINE);
      attendeeMap.put(employee2.getLastName(), employee2);
      env.commitTransactionAndClear(em);

      env.beginTransaction(em);
      final Course storedCourse = em.find(Course.class, courseId);
      verify(storedCourse != null, "didnt find course again");
      final List<Employee> attendees = storedCourse.getAttendees();
      verify(attendees != null, "course lost attendees");
      final Iterator<Employee> orderedEmployees = attendees.iterator();
      for (final String lastName : attendeeMap.keySet()) {
        Employee nextEmployee = orderedEmployees.next();
        verify(
            nextEmployee.getLastName().equals(lastName),
            "wrong order of employees, expected name: "
                + lastName
                + ", but got name: "
                + nextEmployee.getLastName());
      }
      env.commitTransactionAndClear(em);
    } finally {
      closeEntityManager(em);
    }
  }
Ejemplo n.º 25
0
  /** Get a pretty string */
  @Override
  public String toString() {
    StringBuffer buf = new StringBuffer();
    String indent = "        ";

    buf.append(super.toString());
    buf.append(indent + "SegmentCount : " + getSegmentCount() + "\n");
    buf.append(indent + "SearchRange  : " + getSearchRange() + "\n");
    buf.append(indent + "EntrySelector: " + getEntrySelector() + "\n");
    buf.append(indent + "RangeShift   : " + getRangeShift() + "\n");

    for (Iterator i = segments.keySet().iterator(); i.hasNext(); ) {
      Segment s = (Segment) i.next();

      buf.append(indent);
      buf.append("Segment: " + Integer.toHexString(s.startCode));
      buf.append("-" + Integer.toHexString(s.endCode) + " ");
      buf.append("hasMap: " + s.hasMap + " ");

      if (!s.hasMap) {
        buf.append("delta: " + segments.get(s));
      }

      buf.append("\n");
    }

    return buf.toString();
  }
  /*
   * values[]: the alphabet (provided as Integers) bitLengths[]: the number of
   * bits of symbil's huffman code
   */
  public CanonicalHuffmanIntegerCodec(int[] values, int[] bitLengths) {
    super();

    // 1. Sort by (a) bit length and (b) by symbol value -----------
    SortedMap codebook = new TreeMap<Integer, SortedSet<Integer>>();
    for (int i = 0; i < values.length; i++) {
      if (codebook.containsKey(bitLengths[i]))
        ((TreeSet) codebook.get(bitLengths[i])).add(values[i]);
      else {
        TreeSet<Integer> entry = new TreeSet<Integer>();
        entry.add(values[i]);
        codebook.put(bitLengths[i], entry);
      }
    }
    codeLentghSorted = new Integer[codebook.size()];
    int keys = 0;

    // 2. Calculate and Assign Canonical Huffman Codes -------------
    int codeLength = 0, codeValue = -1; // first Canonical is always 0
    codes = new TreeMap<Integer, HuffmanBitCode>();
    Set keySet = codebook.keySet();
    for (Object key : keySet) { // Iterate over code lengths
      int iKey = Integer.parseInt(key.toString());
      codeLentghSorted[keys++] = iKey;

      TreeSet<Integer> get = (TreeSet<Integer>) codebook.get(key);
      for (Integer entry : get) { // Iterate over symbols
        HuffmanBitCode code = new HuffmanBitCode();
        code.bitLentgh = iKey; // given: bit length
        code.value = entry; // given: symbol

        codeValue++; // increment bit value by 1
        int delta = iKey - codeLength; // new length?
        codeValue = codeValue << delta; // pad with 0's
        code.bitCode = codeValue; // calculated: huffman code
        codeLength += delta; // adjust current code len

        if (NumberOfSetBits(codeValue) > iKey)
          throw new IllegalArgumentException("Symbol out of range");

        codes.put(entry, code); // Store HuffmanBitCode

        Map<Long, Integer> codeMap = codeCache.get(code.bitLentgh);
        if (codeMap == null) {
          codeMap = new HashMap<Long, Integer>();
          codeCache.put(code.bitLentgh, codeMap);
        }
        codeMap.put(new Long(code.bitCode), code.value);
      }
    }

    // 3. Done. Just have to populate codeMaps ---------------------
    if (codeLentghSorted.length > 0)
      codeMaps = new Map[codeLentghSorted[codeLentghSorted.length - 1] + 1];
    else codeMaps = new Map[1];
    for (int len : codeLentghSorted) { // Iterate over code lengths
      codeMaps[len] = codeCache.get(len);
    }
  }
Ejemplo n.º 27
0
  @Test
  public void testAssignMigrations() {
    servers.clear();
    servers.put(
        new TServerInstance(HostAndPort.fromParts("127.0.0.1", 1234), "a"), new FakeTServer());
    servers.put(
        new TServerInstance(HostAndPort.fromParts("127.0.0.1", 1235), "b"), new FakeTServer());
    servers.put(
        new TServerInstance(HostAndPort.fromParts("127.0.0.1", 1236), "c"), new FakeTServer());
    List<KeyExtent> metadataTable = new ArrayList<KeyExtent>();
    String table = "t1";
    metadataTable.add(makeExtent(table, null, null));
    table = "t2";
    metadataTable.add(makeExtent(table, "a", null));
    metadataTable.add(makeExtent(table, null, "a"));
    table = "t3";
    metadataTable.add(makeExtent(table, "a", null));
    metadataTable.add(makeExtent(table, "b", "a"));
    metadataTable.add(makeExtent(table, "c", "b"));
    metadataTable.add(makeExtent(table, "d", "c"));
    metadataTable.add(makeExtent(table, "e", "d"));
    metadataTable.add(makeExtent(table, null, "e"));
    Collections.sort(metadataTable);

    TestDefaultLoadBalancer balancer = new TestDefaultLoadBalancer();

    SortedMap<TServerInstance, TabletServerStatus> current =
        new TreeMap<TServerInstance, TabletServerStatus>();
    for (Entry<TServerInstance, FakeTServer> entry : servers.entrySet()) {
      current.put(entry.getKey(), entry.getValue().getStatus(entry.getKey()));
    }
    assignTablets(metadataTable, servers, current, balancer);

    // Verify that the counts on the tables are correct
    Map<String, Integer> expectedCounts = new HashMap<String, Integer>();
    expectedCounts.put("t1", 1);
    expectedCounts.put("t2", 1);
    expectedCounts.put("t3", 2);
    checkBalance(metadataTable, servers, expectedCounts);

    // Rebalance once
    for (Entry<TServerInstance, FakeTServer> entry : servers.entrySet()) {
      current.put(entry.getKey(), entry.getValue().getStatus(entry.getKey()));
    }

    // Nothing should happen, we are balanced
    ArrayList<TabletMigration> out = new ArrayList<TabletMigration>();
    balancer.getMigrations(current, out);
    assertEquals(out.size(), 0);

    // Take down a tabletServer
    TServerInstance first = current.keySet().iterator().next();
    current.remove(first);
    FakeTServer remove = servers.remove(first);

    // reassign offline extents
    assignTablets(remove.extents, servers, current, balancer);
    checkBalance(metadataTable, servers, null);
  }
Ejemplo n.º 28
0
  // TODO obj
  private SortedMap<Date, Double> sCalcOutput(SortedMap<Date, double[]> calcOutput) {

    SortedMap<Date, Double> sCalcOutput = new TreeMap<Date, Double>();
    for (Date date : calcOutput.keySet()) {
      sCalcOutput.put(date, calcOutput.get(date)[0]);
    }
    return sCalcOutput;
  }
Ejemplo n.º 29
0
 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   Log.i(
       AbstractCollectionProvider.cTag,
       "Upgrading database from version " + oldVersion + " to " + newVersion);
   SortedMap<Integer, Migration> migrations = ALL_MIGRATIONS.subMap(oldVersion, newVersion);
   executeMigrations(db, migrations.keySet());
 }
Ejemplo n.º 30
0
  private void cleanUpImports() {
    Integer dummyVote = new Integer(Integer.MAX_VALUE);
    SortedMap newImports = new TreeMap(comparator);
    List classImports = new LinkedList();
    Iterator iter = imports.keySet().iterator();
    while (iter.hasNext()) {
      String importName = (String) iter.next();
      Integer vote = (Integer) imports.get(importName);
      if (!importName.endsWith(".*")) {
        if (vote.intValue() < importClassLimit) continue;
        int delim = importName.lastIndexOf(".");

        if (delim != -1) {
          /*
           * Since the imports are sorted, newImports already contains
           * the package if it should be imported.
           */
          if (newImports.containsKey(importName.substring(0, delim) + ".*")) continue;

          /*
           * This is a single Class import, that is not superseeded by
           * a package import. Mark it for importation, but don't put
           * it in newImports, yet.
           */
          classImports.add(importName);
        } else if (pkg.length() != 0) {
          /*
           * This is a Class import from the unnamed package. It must
           * always be imported.
           */
          newImports.put(importName, dummyVote);
        }
      } else {
        if (vote.intValue() < importPackageLimit) continue;
        newImports.put(importName, dummyVote);
      }
    }

    imports = newImports;
    cachedClassNames = new Hashtable();
    /*
     * Now check if the class import conflict with any of the package
     * imports.
     */
    iter = classImports.iterator();
    while (iter.hasNext()) {
      /*
       * If there are more than one single class imports with the same
       * name, exactly the first (in sorted order) will be imported.
       */
      String classFQName = (String) iter.next();
      if (!conflictsImport(classFQName)) {
        imports.put(classFQName, dummyVote);
        String name = classFQName.substring(classFQName.lastIndexOf('.') + 1);
        cachedClassNames.put(classFQName, name);
      }
    }
  }