/** {@inheritDoc} */
 public void putAll(Map<? extends Integer, ? extends Integer> map) {
   ensureCapacity(map.size());
   // could optimize this for cases when map instanceof THashMap
   for (Map.Entry<? extends Integer, ? extends Integer> entry : map.entrySet()) {
     this.put(entry.getKey().intValue(), entry.getValue().intValue());
   }
 }
  /**
   * Sample demonstrating the calculation of the bond's full EOD measures from price, TSY spread, or
   * yield
   *
   * <p>USE WITH CARE: This sample ignores errors and does not handle exceptions.
   */
  public static final void BondEODSample() {
    JulianDate dtEOD = JulianDate.CreateFromYMD(2012, 1, 13);

    String strISIN = "US78490FUS63"; // Short dated floater 9/15/2012
    // String strISIN = "US78442GGV23"; // Long dated floater
    // String strISIN = "US44180Y2046"; // Plain old fixed coupon

    Map<String, Double> mapPriceMeasures = FI.BondEODMeasuresFromPrice(strISIN, dtEOD, 1.);

    System.out.println("\n--------------\nPrice Measures\n--------------");

    for (Map.Entry<String, Double> me : mapPriceMeasures.entrySet())
      System.out.println(me.getKey() + "=" + me.getValue());

    Map<String, Double> mapTSYSpreadMeasures =
        FI.BondEODMeasuresFromTSYSpread(strISIN, dtEOD, 0.0486);

    System.out.println("\n---------------\nSpread Measures\n---------------");

    for (Map.Entry<String, Double> me : mapTSYSpreadMeasures.entrySet())
      System.out.println(me.getKey() + "=" + me.getValue());

    Map<String, Double> mapYieldMeasures = FI.BondEODMeasuresFromYield(strISIN, dtEOD, 0.0749);

    System.out.println("\n--------------\nYield Measures\n--------------");

    for (Map.Entry<String, Double> me : mapYieldMeasures.entrySet())
      System.out.println(me.getKey() + "=" + me.getValue());
  }
  @NotNull
  public List<FileNameMatcher> getAssociations(@NotNull T type) {
    List<FileNameMatcher> result = new ArrayList<FileNameMatcher>();
    for (Pair<FileNameMatcher, T> mapping : myMatchingMappings) {
      if (mapping.getSecond() == type) {
        result.add(mapping.getFirst());
      }
    }

    for (Map.Entry<CharSequence, T> entries : myExactFileNameMappings.entrySet()) {
      if (entries.getValue() == type) {
        result.add(new ExactFileNameMatcher(entries.getKey().toString()));
      }
    }

    for (Map.Entry<CharSequence, T> entries : myExactFileNameAnyCaseMappings.entrySet()) {
      if (entries.getValue() == type) {
        result.add(new ExactFileNameMatcher(entries.getKey().toString(), true));
      }
    }

    for (Map.Entry<CharSequence, T> entries : myExtensionMappings.entrySet()) {
      if (entries.getValue() == type) {
        result.add(new ExtensionFileNameMatcher(entries.getKey().toString()));
      }
    }

    return result;
  }
Beispiel #4
1
  private Individual[] buildChilds(
      Map<Integer, Integer> mapPath1, Map<Integer, Integer> mapPath2, int[] path1, int[] path2) {
    // TODO Auto-generated method stub

    int[] childPath1 = new int[path1.length];
    int[] childPath2 = new int[path1.length];

    Iterator<Entry<Integer, Integer>> t = mapPath1.entrySet().iterator();
    while (t.hasNext()) {
      Entry<Integer, Integer> entry = t.next();
      int index = entry.getKey();
      int cycle = entry.getValue();
      if (cycle % 2 != 0) {
        childPath1[index] = path1[index];
      } else {
        childPath2[index] = path1[index];
      }
    }
    Iterator<Entry<Integer, Integer>> i = mapPath2.entrySet().iterator();
    while (i.hasNext()) {
      Entry<Integer, Integer> entry2 = i.next();
      int index2 = entry2.getKey();
      int cycle2 = entry2.getValue();
      if (cycle2 % 2 != 0) {
        childPath2[index2] = path2[index2];
      } else {
        childPath1[index2] = path2[index2];
      }
    }
    Individual child1 = new RoverCircuit(data, crossoverType, mutationType, childPath1);
    Individual child2 = new RoverCircuit(data, crossoverType, mutationType, childPath2);
    Individual[] children = {child1, child2};

    return children;
  }
Beispiel #5
1
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    long n = scanner.nextLong();
    long m = scanner.nextLong();
    Map<Integer, Integer> nmap = primeDivisorAndCounts(n);
    Map<Integer, Integer> mmap = primeDivisorAndCounts(m);

    int sameCount = 1;

    for (Map.Entry<Integer, Integer> entry : nmap.entrySet()) {
      int divisor = entry.getKey();
      int counts = 0;
      if (mmap.containsKey(divisor)) {
        int nc = entry.getValue();
        int mc = mmap.get(divisor);
        counts = nc < mc ? nc : mc;
      }
      sameCount *= counts + 1;
    }

    int nDiviorsCount = 1;
    for (Map.Entry<Integer, Integer> entry : nmap.entrySet()) {
      nDiviorsCount *= entry.getValue() + 1;
    }
    int mDiviorsCount = 1;
    for (Map.Entry<Integer, Integer> entry : mmap.entrySet()) {
      mDiviorsCount *= entry.getValue() + 1;
    }

    int maxCount = nDiviorsCount * mDiviorsCount;

    int maxDivisor = gcd(maxCount, sameCount);

    System.out.println(maxCount / maxDivisor + " " + sameCount / maxDivisor);
  }
  /** Create the generated part of the NOTICE file based on the summary of resolved licenses */
  protected String generateLicenseSummaryLines(Map<String, String> resolvedLicenses) {
    final StringBuilder builder = new StringBuilder();

    Map<String, Integer> licenseSummary =
        new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);

    for (final Map.Entry<String, String> resolvedEntry : resolvedLicenses.entrySet()) {
      Integer licenseCount = licenseSummary.get(resolvedEntry.getValue());
      if (licenseCount == null) {
        licenseCount = 0;
      }
      licenseCount++;
      licenseSummary.put(resolvedEntry.getValue(), licenseCount);
    }

    final MessageFormat licenseSummaryMessageFormat = getLicenseSummaryMessageFormat();

    int index = 1;
    for (final Map.Entry<String, Integer> licenseSummaryEntry : licenseSummary.entrySet()) {
      final String line =
          parsedLicenseSummaryMessage.format(
              new Object[] {index, licenseSummaryEntry.getKey(), licenseSummaryEntry.getValue()});
      index++;
      builder.append(line).append(IOUtils.LINE_SEPARATOR);
    }

    return builder.toString();
  }
  public MemtableUnfilteredPartitionIterator makePartitionIterator(
      final ColumnFilter columnFilter, final DataRange dataRange, final boolean isForThrift) {
    AbstractBounds<PartitionPosition> keyRange = dataRange.keyRange();

    boolean startIsMin = keyRange.left.isMinimum();
    boolean stopIsMin = keyRange.right.isMinimum();

    boolean isBound = keyRange instanceof Bounds;
    boolean includeStart = isBound || keyRange instanceof IncludingExcludingBounds;
    boolean includeStop = isBound || keyRange instanceof Range;
    Map<PartitionPosition, AtomicBTreePartition> subMap;
    if (startIsMin)
      subMap = stopIsMin ? partitions : partitions.headMap(keyRange.right, includeStop);
    else
      subMap =
          stopIsMin
              ? partitions.tailMap(keyRange.left, includeStart)
              : partitions.subMap(keyRange.left, includeStart, keyRange.right, includeStop);

    int minLocalDeletionTime = Integer.MAX_VALUE;

    // avoid iterating over the memtable if we purge all tombstones
    if (cfs.getCompactionStrategyManager().onlyPurgeRepairedTombstones())
      minLocalDeletionTime = findMinLocalDeletionTime(subMap.entrySet().iterator());

    final Iterator<Map.Entry<PartitionPosition, AtomicBTreePartition>> iter =
        subMap.entrySet().iterator();

    return new MemtableUnfilteredPartitionIterator(
        cfs, iter, isForThrift, minLocalDeletionTime, columnFilter, dataRange);
  }
Beispiel #8
0
  private void computeOriginWeight() {

    int totalFileCount = fileCount.get();
    if (debug) {
      logger.info("总文件数: {}", totalFileCount);
    }

    posMap = new ConcurrentHashMap<>();
    // 记录默认词序
    int i = 0;
    for (Entry<String, AtomicInteger> wordsCount : wordCountPerUnit.entrySet()) {
      String word = wordsCount.getKey();
      posMap.put(word, i);
      i++;
    }
    // 计算idf = filecount/file count with this word
    for (Entry<String, Integer> entry : posMap.entrySet()) {
      String word = entry.getKey();
      double idf = 0d;
      int unitCount = wordCountPerUnit.get(word).get();
      double iidf = (double) totalFileCount / (unitCount + 0);
      idf = Math.log(iidf);
      if (debug) {
        logger.info(
            "词: {}, 包含该词的文件数:{}, 未log前的idf值:{}, idf:{}",
            new String[] {word, unitCount + "", iidf + "", idf + ""});
      }
      weightMap.put(word, idf);
    }
    logger.info(
        "voc words count is {} (after filter the low and high frequency words)",
        (weightMap.size()));
    logger.info("word weight compute over");
  }
  Entry encode(final T o, final String parentDN) throws LDAPPersistException {
    // Get the attributes that should be included in the entry.
    final LinkedHashMap<String, Attribute> attrMap = new LinkedHashMap<String, Attribute>();
    attrMap.put("objectClass", objectClassAttribute);

    for (final Map.Entry<String, FieldInfo> e : fieldMap.entrySet()) {
      final FieldInfo i = e.getValue();
      if (!i.includeInAdd()) {
        continue;
      }

      final Attribute a = i.encode(o, false);
      if (a != null) {
        attrMap.put(e.getKey(), a);
      }
    }

    for (final Map.Entry<String, GetterInfo> e : getterMap.entrySet()) {
      final GetterInfo i = e.getValue();
      if (!i.includeInAdd()) {
        continue;
      }

      final Attribute a = i.encode(o);
      if (a != null) {
        attrMap.put(e.getKey(), a);
      }
    }

    final String dn = constructDN(o, parentDN, attrMap);
    final Entry entry = new Entry(dn, attrMap.values());

    if (postEncodeMethod != null) {
      try {
        postEncodeMethod.invoke(o, entry);
      } catch (Throwable t) {
        debugException(t);

        if (t instanceof InvocationTargetException) {
          t = ((InvocationTargetException) t).getTargetException();
        }

        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_ERROR_INVOKING_POST_ENCODE_METHOD.get(
                postEncodeMethod.getName(), type.getName(), getExceptionMessage(t)),
            t);
      }
    }

    setDNAndEntryFields(o, entry);

    if (superclassHandler != null) {
      final Entry e = superclassHandler.encode(o, parentDN);
      for (final Attribute a : e.getAttributes()) {
        entry.addAttribute(a);
      }
    }

    return entry;
  }
Beispiel #10
0
  public static void main(String[] args) {
    Map<String, String> a = new HashMap<String, String>();
    a.put("cat", "猫");
    a.put("desk", "桌子");
    a.put("table", "桌子");
    a.put("table", "表格");

    System.out.println(a.get("table"));

    // 遍历表格
    Set<String> key = a.keySet();
    Iterator<String> it = key.iterator();
    while (it.hasNext()) {
      String s = it.next();
      System.out.println(s + "---->" + a.get(s));
    }

    Set<Map.Entry<String, String>> et = a.entrySet();
    Iterator<Map.Entry<String, String>> it2 = et.iterator();
    while (it2.hasNext()) {
      Map.Entry en = it2.next();
    }

    Set st = a.entrySet();
    Iterator it3 = st.iterator();
    while (it3.hasNext()) {
      Map.Entry en = (Map.Entry) it3.next();
      System.out.println(en.getKey() + "+++" + en.getValue());
    }
  }
 private AnalyticsEvent(
     final String eventId,
     final String eventType,
     final Map<String, String> attributes,
     final Map<String, Double> metrics,
     final SDKInfo sdkInfo,
     String sessionId,
     long sessionStart,
     Long sessionEnd,
     Long sessionDuration,
     long timestamp,
     String uniqueId,
     AndroidAppDetails appDetails,
     AndroidDeviceDetails deviceDetails) {
   this.eventId = eventId;
   this.sdkName = sdkInfo.getName();
   this.sdkVersion = sdkInfo.getVersion();
   this.session = new PinpointSession(sessionId, sessionStart, sessionEnd, sessionDuration);
   this.timestamp = timestamp;
   this.uniqueId = uniqueId;
   this.eventType = eventType;
   this.appDetails = appDetails;
   this.deviceDetails = deviceDetails;
   if (null != attributes) {
     for (Entry<String, String> kvp : attributes.entrySet()) {
       this.addAttribute(kvp.getKey(), kvp.getValue());
     }
   }
   if (null != metrics) {
     for (Entry<String, Double> kvp : metrics.entrySet()) {
       this.addMetric(kvp.getKey(), kvp.getValue());
     }
   }
 }
Beispiel #12
0
  /**
   * Process all found properties for the component.
   *
   * @param globalProperties Global properties are set on all components.
   * @param iLog The issue log.
   * @throws SCRDescriptorException
   */
  public void processProperties(final Map<String, String> globalProperties, final IssueLog iLog)
      throws SCRDescriptorException {
    final Iterator<Map.Entry<String, PropertyDescription>> propIter =
        properties.entrySet().iterator();
    while (propIter.hasNext()) {
      final Map.Entry<String, PropertyDescription> entry = propIter.next();
      final String propName = entry.getKey();
      final PropertyDescription desc = entry.getValue();
      this.processProperty(desc.propertyTag, propName, desc.field, iLog);
    }
    // apply pre configured global properties
    if (globalProperties != null) {
      final Iterator<Map.Entry<String, String>> globalPropIter =
          globalProperties.entrySet().iterator();
      while (globalPropIter.hasNext()) {
        final Map.Entry<String, String> entry = globalPropIter.next();
        final String name = entry.getKey();

        // check if the service already provides this property
        if (!properties.containsKey(name) && entry.getValue() != null) {
          final String value = entry.getValue();

          final Property p = new Property();
          p.setName(name);
          p.setValue(value);
          p.setType("String");
          p.setPrivate(true);
          component.addProperty(p);
        }
      }
    }
  }
 /** histograms are sampled, but we just update points */
 public void mergeHistograms(
     MetricInfo metricInfo,
     String meta,
     Map<Integer, MetricSnapshot> data,
     Map<String, Integer> metaCounters,
     Map<String, Map<Integer, Histogram>> histograms) {
   Map<Integer, MetricSnapshot> existing = metricInfo.get_metrics().get(meta);
   if (existing == null) {
     metricInfo.put_to_metrics(meta, data);
     Map<Integer, Histogram> histogramMap = new HashMap<>();
     for (Map.Entry<Integer, MetricSnapshot> dataEntry : data.entrySet()) {
       Histogram histogram = MetricUtils.metricSnapshot2Histogram(dataEntry.getValue());
       histogramMap.put(dataEntry.getKey(), histogram);
     }
     histograms.put(meta, histogramMap);
   } else {
     for (Map.Entry<Integer, MetricSnapshot> dataEntry : data.entrySet()) {
       Integer win = dataEntry.getKey();
       MetricSnapshot snapshot = dataEntry.getValue();
       MetricSnapshot old = existing.get(win);
       if (old == null) {
         existing.put(win, snapshot);
         histograms.get(meta).put(win, MetricUtils.metricSnapshot2Histogram(snapshot));
       } else {
         if (snapshot.get_ts() >= old.get_ts()) {
           old.set_ts(snapshot.get_ts());
           // update points
           MetricUtils.updateHistogramPoints(histograms.get(meta).get(win), snapshot.get_points());
         }
       }
     }
   }
   updateMetricCounters(meta, metaCounters);
 }
Beispiel #14
0
  @UiHandler("btnOk")
  void saveChanges(ClickEvent e) {
    if (separator.isVisible()) {
      editMode(false);
    }

    if (removedRecs.size() > 0) {

      final InputItem rec = removedRecs.entrySet().iterator().next().getValue();

      MethodCallback<Void> cb =
          new MethodCallback<Void>() {
            @Override
            public void onFailure(Method method, Throwable exception) {
              askRetry(rec, "Error removing record " + rec.getName() + ". Retry ?");
            }

            @Override
            public void onSuccess(Method method, Void response) {
              removedRecs.remove(rec.getId());
              saveChanges(null);
            }
          };

      md.info(MDS, "Removing record " + rec.getName());
      clientApi.iitemsApi().delete(rec.getId(), cb);

    } else if (changedRecs.size() > 0) {

      final InputItem rec = changedRecs.entrySet().iterator().next().getValue();

      MethodCallback<Void> cb =
          new MethodCallback<Void>() {
            @Override
            public void onFailure(Method method, Throwable exception) {
              askRetry(rec, "Error updating user " + rec.getName() + ". Retry ?");
            }

            @Override
            public void onSuccess(Method method, Void response) {
              changedRecs.remove(rec.getId());
              saveChanges(null);
            }
          };

      if (rec.getId() == 0) {
        md.info(MDS, "Creating user " + rec);
        clientApi.iitemsApi().create(rec, cb);
      } else {
        md.info(MDS, "Updating user " + rec);
        clientApi.iitemsApi().update(rec.getId(), rec, cb);
      }

    } else {
      refreshRecords(e);
      md.clear(MDS);
    }
  }
 protected static void purgeOutdatedBotherTimeouts(Map<BotherTimeout, Date> botherTimeouts) {
   Date now = Calendar.getInstance().getTime();
   List<Entry<BotherTimeout, Date>> entriesToDelete = new ArrayList<Entry<BotherTimeout, Date>>();
   for (Entry<BotherTimeout, Date> entry : botherTimeouts.entrySet()) {
     if (entry.getValue().before(now)) {
       entriesToDelete.add(entry);
     }
   }
   botherTimeouts.entrySet().removeAll(entriesToDelete);
 }
Beispiel #16
0
  protected void revert(
      Map<Link, Long> oldTraffic, Map<Switch, Switch.FeasibleState> oldSwitchStates) {
    for (Map.Entry<Link, Long> linkUsedCapacity : oldTraffic.entrySet()) {
      linkUsedCapacity.getKey().setUsedCapacity(linkUsedCapacity.getValue());
    }

    for (Map.Entry<Switch, Switch.FeasibleState> entry : oldSwitchStates.entrySet()) {
      entry.getKey().setState(entry.getValue());
    }
  }
  public void process(@NotNull BodiesResolveContext bodiesResolveContext) {
    for (JetFile file : bodiesResolveContext.getFiles()) {
      checkModifiersAndAnnotationsInPackageDirective(file);
      AnnotationTargetChecker.INSTANCE$.check(file, trace);
    }

    Map<JetClassOrObject, ClassDescriptorWithResolutionScopes> classes =
        bodiesResolveContext.getDeclaredClasses();
    for (Map.Entry<JetClassOrObject, ClassDescriptorWithResolutionScopes> entry :
        classes.entrySet()) {
      JetClassOrObject classOrObject = entry.getKey();
      ClassDescriptorWithResolutionScopes classDescriptor = entry.getValue();

      checkSupertypesForConsistency(classDescriptor);
      checkTypesInClassHeader(classOrObject);

      if (classOrObject instanceof JetClass) {
        JetClass jetClass = (JetClass) classOrObject;
        checkClass(bodiesResolveContext, jetClass, classDescriptor);
        descriptorResolver.checkNamesInConstraints(
            jetClass, classDescriptor, classDescriptor.getScopeForClassHeaderResolution(), trace);
      } else if (classOrObject instanceof JetObjectDeclaration) {
        checkObject((JetObjectDeclaration) classOrObject, classDescriptor);
      }

      checkPrimaryConstructor(classOrObject, classDescriptor);

      modifiersChecker.checkModifiersForDeclaration(classOrObject, classDescriptor);
    }

    Map<JetNamedFunction, SimpleFunctionDescriptor> functions = bodiesResolveContext.getFunctions();
    for (Map.Entry<JetNamedFunction, SimpleFunctionDescriptor> entry : functions.entrySet()) {
      JetNamedFunction function = entry.getKey();
      SimpleFunctionDescriptor functionDescriptor = entry.getValue();

      checkFunction(function, functionDescriptor);
      modifiersChecker.checkModifiersForDeclaration(function, functionDescriptor);
    }

    Map<JetProperty, PropertyDescriptor> properties = bodiesResolveContext.getProperties();
    for (Map.Entry<JetProperty, PropertyDescriptor> entry : properties.entrySet()) {
      JetProperty property = entry.getKey();
      PropertyDescriptor propertyDescriptor = entry.getValue();

      checkProperty(property, propertyDescriptor);
      modifiersChecker.checkModifiersForDeclaration(property, propertyDescriptor);
    }

    for (Map.Entry<JetSecondaryConstructor, ConstructorDescriptor> entry :
        bodiesResolveContext.getSecondaryConstructors().entrySet()) {
      ConstructorDescriptor constructorDescriptor = entry.getValue();
      JetSecondaryConstructor declaration = entry.getKey();
      checkConstructorDeclaration(constructorDescriptor, declaration);
    }
  }
  /** @throws Exception If failed. */
  public void testAffinityPut() throws Exception {
    Thread.sleep(2 * TOP_REFRESH_FREQ);

    assertEquals(NODES_CNT, client.compute().refreshTopology(false, false).size());

    Map<UUID, Grid> gridsByLocNode = new HashMap<>(NODES_CNT);

    GridClientData partitioned = client.data(PARTITIONED_CACHE_NAME);

    GridClientCompute compute = client.compute();

    for (int i = 0; i < NODES_CNT; i++) gridsByLocNode.put(grid(i).localNode().id(), grid(i));

    for (int i = 0; i < 100; i++) {
      String key = "key" + i;

      UUID primaryNodeId = grid(0).mapKeyToNode(PARTITIONED_CACHE_NAME, key).id();

      assertEquals("Affinity mismatch for key: " + key, primaryNodeId, partitioned.affinity(key));

      assertEquals(primaryNodeId, partitioned.affinity(key));

      // Must go to primary node only. Since backup count is 0, value must present on
      // primary node only.
      partitioned.put(key, "val" + key);

      for (Map.Entry<UUID, Grid> entry : gridsByLocNode.entrySet()) {
        Object val = entry.getValue().cache(PARTITIONED_CACHE_NAME).peek(key);

        if (primaryNodeId.equals(entry.getKey())) assertEquals("val" + key, val);
        else assertNull(val);
      }
    }

    // Now check that we will see value in near cache in pinned mode.
    for (int i = 100; i < 200; i++) {
      String pinnedKey = "key" + i;

      UUID primaryNodeId = grid(0).mapKeyToNode(PARTITIONED_CACHE_NAME, pinnedKey).id();

      UUID pinnedNodeId = F.first(F.view(gridsByLocNode.keySet(), F.notEqualTo(primaryNodeId)));

      GridClientNode node = compute.node(pinnedNodeId);

      partitioned.pinNodes(node).put(pinnedKey, "val" + pinnedKey);

      for (Map.Entry<UUID, Grid> entry : gridsByLocNode.entrySet()) {
        Object val = entry.getValue().cache(PARTITIONED_CACHE_NAME).peek(pinnedKey);

        if (primaryNodeId.equals(entry.getKey()) || pinnedNodeId.equals(entry.getKey()))
          assertEquals("val" + pinnedKey, val);
        else assertNull(val);
      }
    }
  }
Beispiel #19
0
  private void update() {
    if (party.memb != om) {
      Collection<Member> old = new HashSet<Member>(avs.keySet());
      for (final Member m : (om = party.memb).values()) {
        if (m.gobid == ign) continue;
        Avaview w = avs.get(m);
        if (w == null) {
          w =
              new Avaview(Coord.z, this, m.gobid, new Coord(27, 27)) {
                private Tex tooltip = null;

                public Object tooltip(Coord c, boolean again) {
                  Gob gob = m.getgob();
                  if (gob == null) return (tooltip);
                  KinInfo ki = gob.getattr(KinInfo.class);
                  if (ki == null) return (null);
                  return (tooltip = ki.rendered());
                }
              };
          avs.put(m, w);
        } else {
          old.remove(m);
        }
      }
      for (Member m : old) {
        ui.destroy(avs.get(m));
        avs.remove(m);
      }
      List<Map.Entry<Member, Avaview>> wl =
          new ArrayList<Map.Entry<Member, Avaview>>(avs.entrySet());
      Collections.sort(
          wl,
          new Comparator<Map.Entry<Member, Avaview>>() {
            public int compare(Entry<Member, Avaview> a, Entry<Member, Avaview> b) {
              return (a.getKey().gobid - b.getKey().gobid);
            }
          });
      int i = 0;
      for (Map.Entry<Member, Avaview> e : wl) {
        e.getValue().c = new Coord((i % 2) * 43, (i / 2) * 43 + 24);
        i++;
      }
    }
    for (Map.Entry<Member, Avaview> e : avs.entrySet()) {
      e.getValue().color = e.getKey().col;
    }
    if ((avs.size() > 0) && (leave == null)) {
      leave = new Button(Coord.z, 84, this, "Leave party");
    }
    if ((avs.size() == 0) && (leave != null)) {
      ui.destroy(leave);
      leave = null;
    }
    sz.y = MainFrame.getScreenSize().y - c.y;
  }
  // @include
  public static List<String> searchFrequentTtems(List<String> in, int k) {
    // Finds the candidates which may occur > n / k times.
    String buf = "";
    Map<String, Integer> hash = new HashMap<>();
    int n = 0; // Counts the number of strings.

    Iterator<String> sin = in.iterator();
    while (sin.hasNext()) {
      buf = sin.next();
      hash.put(buf, hash.containsKey(buf) ? hash.get(buf) + 1 : 1);
      ++n;
      // Detecting k items in hash, at least one of them must have exactly one
      // in it. We will discard those k items by one for each.
      if (hash.size() == k) {
        List<String> delKeys = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : hash.entrySet()) {
          if (entry.getValue() - 1 == 0) {
            delKeys.add(entry.getKey());
          }
        }
        for (String s : delKeys) {
          hash.remove(s);
        }

        for (Map.Entry<String, Integer> e : hash.entrySet()) {
          hash.put(e.getKey(), e.getValue() - 1);
        }
      }
    }

    // Resets hash for the following counting.
    for (String it : hash.keySet()) {
      hash.put(it, 0);
    }

    // Counts the occurrence of each candidate word.
    sin = in.iterator();
    while (sin.hasNext()) {
      buf = sin.next();
      Integer it = hash.get(buf);
      if (it != null) {
        hash.put(buf, it + 1);
      }
    }

    // Selects the word which occurs > n / k times.
    List<String> ret = new ArrayList<>();
    for (Map.Entry<String, Integer> it : hash.entrySet()) {
      if (n * 1.0 / k < (double) it.getValue()) {
        ret.add(it.getKey());
      }
    }

    return ret;
  }
Beispiel #21
0
 public static void main(String args[]) {
   Map<String, String> in = new HashMap<>();
   in.put("val1", "10.0");
   in.put("val2", "60.0");
   Map<String, Float> mOriginal = filterLoadedValues(in);
   Map<String, Float> mLambda = filterLoadedValuesLambda(in);
   System.out.println("\nOriginal Entries\n--");
   mOriginal.entrySet().stream().forEach(TransformMap::printEntry);
   System.out.println("\nLambda Entries\n--");
   mLambda.entrySet().stream().forEach(TransformMap::printEntry);
 }
  /** {@inheritDoc} */
  @SuppressWarnings("BusyWait")
  @Override
  public Boolean reduce(List<GridComputeJobResult> results) throws GridException {
    assert taskSes != null;
    assert results != null;
    assert params != null;
    assert !params.isEmpty();
    assert results.size() == params.size();

    Map<String, Integer> receivedParams = new HashMap<>();

    boolean allAttrReceived = false;

    int cnt = 0;

    while (!allAttrReceived && cnt++ < 3) {
      allAttrReceived = true;

      for (Map.Entry<String, Integer> entry : params.entrySet()) {
        assert taskSes.getAttribute(entry.getKey()) != null;

        Integer newVal = (Integer) taskSes.getAttribute(entry.getKey());

        assert newVal != null;

        receivedParams.put(entry.getKey(), newVal);

        if (newVal != entry.getValue() + 1) allAttrReceived = false;
      }

      if (!allAttrReceived) {
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
          throw new GridException("Thread interrupted.", e);
        }
      }
    }

    if (log.isDebugEnabled()) {
      for (Map.Entry<String, Integer> entry : receivedParams.entrySet()) {
        log.debug(
            "Received session attr value [name="
                + entry.getKey()
                + ", val="
                + entry.getValue()
                + ", expected="
                + (params.get(entry.getKey()) + 1)
                + ']');
      }
    }

    return allAttrReceived;
  }
Beispiel #23
0
  public Map<String, Object> getOptions() {
    Map<String, Object> options = new LinkedHashMap<String, Object>();
    for (Map.Entry<String, SpecifiedOption> entry : declaredOptions.entrySet()) {
      options.put(entry.getKey(), entry.getValue());
    }
    for (Map.Entry<String, Object> entry : undeclaredOptions.entrySet()) {
      options.put(entry.getKey(), entry.getValue());
    }

    return options;
  }
Beispiel #24
0
  /**
   * 把词按照频率排序返回,用于查看高频词或低频词 便于加入停词中
   *
   * @return
   */
  public List<Entry<String, Integer>> showFrequencyWords(boolean flag) {
    Map<String, Integer> tMap = new HashMap<>();
    for (Entry<String, AtomicInteger> entry : wordCountPerUnit.entrySet()) {
      String key = entry.getKey();
      int i = entry.getValue().get();
      tMap.put(key, i);
    }

    ArrayList<Entry<String, Integer>> countList = new ArrayList<>(tMap.entrySet());
    Utils.sortMapStringAndInteger(countList, flag);
    return countList;
  }
  /*
  var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
  _.result(object, 'cheese');
  => "crumpets"
  _.result(object, 'stuff');
  => "nonsense"
  */
  @Test
  public void result() {
    Map<String, Object> object =
        new LinkedHashMap<String, Object>() {
          {
            put("cheese", "crumpets");
            put(
                "stuff",
                new Function<String>() {
                  public String apply() {
                    return "nonsense";
                  }
                });
          }
        };

    assertEquals(
        "crumpets",
        $.result(
            object.entrySet(),
            new Predicate<Map.Entry<String, Object>>() {
              public Boolean apply(Map.Entry<String, Object> item) {
                return item.getKey().equals("cheese");
              }
            }));
    assertEquals(
        "nonsense",
        $.result(
            object.entrySet(),
            new Predicate<Map.Entry<String, Object>>() {
              public Boolean apply(Map.Entry<String, Object> item) {
                return item.getKey().equals("stuff");
              }
            }));
    assertEquals(
        "result1",
        $.result(
            asList("result1", "result2"),
            new Predicate<String>() {
              public Boolean apply(String item) {
                return item.equals("result1");
              }
            }));
    assertEquals(
        null,
        $.result(
            asList("result1", "result2"),
            new Predicate<String>() {
              public Boolean apply(String item) {
                return item.equals("result3");
              }
            }));
  }
Beispiel #26
0
  /**
   * {@link IntlAbstractOperations#oldStyleLanguageTags}
   *
   * @param cldrMainDir the CLDR main directory
   * @throws IOException if an I/O error occurs
   */
  static void oldStyleLanguageTags(Path cldrMainDir) throws IOException {
    try (DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(cldrMainDir)) {
      Map<String, String> names = new LinkedHashMap<>();
      Map<String, String> aliased = new LinkedHashMap<>();
      for (Path path : newDirectoryStream) {
        try (Reader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
          Document xml = xml(reader);
          Element identity = getElementByTagName(xml.getDocumentElement(), "identity");
          assert identity != null;
          Element language = getElementByTagName(xml.getDocumentElement(), "language");
          Element script = getElementByTagName(xml.getDocumentElement(), "script");
          Element territory = getElementByTagName(xml.getDocumentElement(), "territory");

          String tag = language.getAttribute("type");
          if (script != null) {
            tag += "-" + script.getAttribute("type");
          }
          if (territory != null) {
            tag += "-" + territory.getAttribute("type");
          }

          String filename = Objects.requireNonNull(path.getFileName()).toString();
          filename = filename.substring(0, filename.lastIndexOf('.'));
          names.put(filename, tag);

          Element alias = getElementByTagName(xml.getDocumentElement(), "alias");
          if (alias != null && script == null && territory != null) {
            aliased.put(tag, alias.getAttribute("source"));
          }
        }
      }
      Map<String, String> result = new LinkedHashMap<>();
      for (Map.Entry<String, String> entry : aliased.entrySet()) {
        String from = entry.getKey();
        String to = names.get(entry.getValue());

        String value = result.get(to);
        if (value == null) {
          value = "";
        } else {
          value += ", ";
        }
        value += "\"" + from + "\"";
        result.put(to, value);
      }

      for (Map.Entry<String, String> entry : result.entrySet()) {
        System.out.printf("map.put(\"%s\", new String[]{%s});%n", entry.getKey(), entry.getValue());
      }
    }
  }
 public Integer extractSectionIndex(JsonNode sections, String seasonNumber) throws ParseException {
   Map<String, Integer> sectionsList = extractSectionsList(sections);
   for (Map.Entry<String, Integer> section : sectionsList.entrySet()) {
     if (matchNumberedSection(section.getKey(), seasonNumber)) {
       return section.getValue();
     }
   }
   for (Map.Entry<String, Integer> section : sectionsList.entrySet()) {
     if (section.getKey().matches(EPISODES)) {
       return section.getValue();
     }
   }
   throw new ParseException("Section not found.", 0);
 }
Beispiel #28
0
 private org.exist.source.Source buildQuerySource(String query, Object[] params, String cookie) {
   Map<String, String> combinedMap = namespaceBindings.getCombinedMap();
   for (Map.Entry<String, Document> entry : moduleMap.entrySet()) {
     combinedMap.put("<module> " + entry.getKey(), entry.getValue().path());
   }
   for (Map.Entry<QName, Object> entry : bindings.entrySet()) {
     combinedMap.put(
         "<var> " + entry.getKey(),
         null); // don't care about values, as long as the same vars are bound
   }
   combinedMap.put("<posvars> " + params.length, null);
   combinedMap.put("<cookie>", cookie);
   // TODO: should include statically known documents and baseURI too?
   return new StringSourceWithMapKey(query, combinedMap);
 }
Beispiel #29
0
  static void itTest4(Map s, int size, int pos) {
    IdentityHashMap seen = new IdentityHashMap(size);
    reallyAssert(s.size() == size);
    int sum = 0;
    timer.start("Iter XEntry            ", size);
    Iterator it = s.entrySet().iterator();
    Object k = null;
    Object v = null;
    for (int i = 0; i < size - pos; ++i) {
      Map.Entry x = (Map.Entry) (it.next());
      k = x.getKey();
      v = x.getValue();
      seen.put(k, k);
      if (x != MISSING) ++sum;
    }
    reallyAssert(s.containsKey(k));
    it.remove();
    reallyAssert(!s.containsKey(k));
    while (it.hasNext()) {
      Map.Entry x = (Map.Entry) (it.next());
      Object k2 = x.getKey();
      seen.put(k2, k2);
      if (x != MISSING) ++sum;
    }

    reallyAssert(s.size() == size - 1);
    s.put(k, v);
    reallyAssert(seen.size() == size);
    timer.finish();
    reallyAssert(sum == size);
    reallyAssert(s.size() == size);
  }
Beispiel #30
0
  private static Map<String, Double> sortByComparator(
      Map<String, Double> map, final boolean order) {
    List<Entry<String, Double>> list = new LinkedList<Entry<String, Double>>(map.entrySet());

    // Sorting the list based on values
    Collections.sort(
        list,
        new Comparator<Entry<String, Double>>() {
          public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
            if (order) {
              return o1.getValue().compareTo(o2.getValue());
            } else {
              return o2.getValue().compareTo(o1.getValue());
            }
          }
        });

    // Maintaining insertion order with the help of LinkedList
    Map<String, Double> sortedMap = new LinkedHashMap<String, Double>();
    for (Entry<String, Double> entry : list) {
      sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
  }