// Task: create collection to translate Polish-English words in two ways
  public static void main(String[] args) {
    ENGLISH_WORD[] englishWords = ENGLISH_WORD.values();
    String[] russianWords = {"jeden", "dwa", "trzy", "kula", "snieg"};

    // Create Multiset
    BiMap<ENGLISH_WORD, String> biMap = EnumHashBiMap.create(ENGLISH_WORD.class);
    // Create English-Polish dictionary
    int i = 0;
    for (ENGLISH_WORD englishWord : englishWords) {
      biMap.put(englishWord, russianWords[i]);
      i++;
    }

    // Print count words
    System.out.println(biMap); // print {ONE=jeden, TWO=dwa, THREE=trzy, BALL=kula, SNOW=snieg}
    // Print all unique words
    System.out.println(biMap.keySet()); // print [ONE, TWO, THREE, BALL, SNOW]
    System.out.println(biMap.values()); // print [jeden, dwa, trzy, kula, snieg]

    // Print translate by words
    System.out.println("one = " + biMap.get(ENGLISH_WORD.ONE)); // print one = jeden
    System.out.println("two = " + biMap.get(ENGLISH_WORD.TWO)); // print two = dwa
    System.out.println("kula = " + biMap.inverse().get("kula")); // print kula = BALL
    System.out.println("snieg = " + biMap.inverse().get("snieg")); // print snieg = SNOW
    System.out.println("empty = " + biMap.get("empty")); // print empty = null

    // Print count word's pair
    System.out.println(biMap.size()); // print 5
  }
 public IdEObject getByOid(long oid) {
   IdEObject result = objectsToCommitFirst.inverse().get(oid);
   if (result == null) {
     return objectsToCommitSecond.inverse().get(oid);
   }
   return result;
 }
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    String request = packet.content().toString(CharsetUtil.UTF_8);
    if (logger.isDebugEnabled())
      logger.debug("Sender " + packet.sender() + " sent request:" + request);

    if (!sessionList.inverse().containsKey(packet.sender())) {
      String session = UUID.randomUUID().toString();
      String localAddress = ctx.channel().localAddress().toString();
      String remoteAddress = ctx.channel().remoteAddress().toString();
      SubscriptionManagerFactory.getInstance()
          .add(session, session, outputType, localAddress, remoteAddress);
      sessionList.put(session, packet.sender());
      if (logger.isDebugEnabled())
        logger.debug("Added Sender " + packet.sender() + ", session:" + session);
      ctx.channel()
          .writeAndFlush(
              new DatagramPacket(
                  Unpooled.copiedBuffer(
                      Util.getWelcomeMsg().toString() + "\r\n", CharsetUtil.UTF_8),
                  packet.sender()));
    }

    Map<String, Object> headers = getHeaders(sessionList.inverse().get(packet.sender()));
    producer.sendBodyAndHeaders(request, headers);
  }
  @SuppressWarnings("unchecked")
  public ByteBuffer serialize() {
    if (serialized != null) {
      return serialized.duplicate();
    }

    ByteBufferOutputStream out = new ByteBufferOutputStream();

    int i = 0;
    for (Component c : components) {
      Serializer<?> s = serializerForPosition(i);
      ByteBuffer cb = c.getBytes(s);
      if (cb == null) {
        cb = ByteBuffer.allocate(0);
      }

      if (dynamic) {
        String comparator = comparatorForPosition(i);
        if (comparator == null) {
          comparator = c.getComparator();
        }
        if (comparator == null) {
          comparator = BYTESTYPE.getTypeName();
        }
        int p = comparator.indexOf("(reversed=true)");
        boolean desc = false;
        if (p >= 0) {
          comparator = comparator.substring(0, p);
          desc = true;
        }
        if (aliasToComparatorMapping.inverse().containsKey(comparator)) {
          byte a = aliasToComparatorMapping.inverse().get(comparator);
          if (desc) {
            a = (byte) Character.toUpperCase((char) a);
          }
          out.writeShort((short) (0x8000 | a));
        } else {
          out.writeShort((short) comparator.length());
          out.write(comparator.getBytes(Charsets.UTF_8));
        }
        // if (comparator.equals(BYTESTYPE.getTypeName()) && (cb.remaining() ==
        // 0)) {
        // log.warn("Writing zero-length BytesType, probably an error");
        // }
      }
      out.writeShort((short) cb.remaining());
      out.write(cb.slice());
      if ((i == (components.size() - 1)) && (equality != ComponentEquality.EQUAL)) {
        out.write(equality.toByte());
      } else {
        out.write(c.getEquality().toByte());
      }
      i++;
    }

    serialized = out.getByteBuffer();
    return serialized.duplicate();
  }
  /** Adds an expression and returns a reference name. */
  public String addExpr(Expr expr) throws PlanningException {
    if (idToExprBiMap.inverse().containsKey(expr)) {
      int refId = idToExprBiMap.inverse().get(expr);
      return idToNamesMap.get(refId).get(0);
    }

    String generatedName = plan.generateUniqueColumnName(expr);
    return addExpr(expr, generatedName);
  }
  public void removeEndpoint(InetAddress endpoint) {
    assert endpoint != null;

    lock.writeLock().lock();
    try {
      bootstrapTokens.inverse().remove(endpoint);
      tokenToEndPointMap.inverse().remove(endpoint);
      leavingEndPoints.remove(endpoint);
      sortedTokens = sortTokens();
    } finally {
      lock.writeLock().unlock();
    }
  }
  public void updateNormalToken(Token token, InetAddress endpoint) {
    assert token != null;
    assert endpoint != null;

    lock.writeLock().lock();
    try {
      bootstrapTokens.inverse().remove(endpoint);
      tokenToEndPointMap.inverse().remove(endpoint);
      if (!endpoint.equals(tokenToEndPointMap.put(token, endpoint))) {
        sortedTokens = sortTokens();
      }
      leavingEndPoints.remove(endpoint);
    } finally {
      lock.writeLock().unlock();
    }
  }
  private int regionToDot(Region r, StringBuilder str, Map<Region, Integer> cache) {
    if (cache.containsKey(r)) { // use same region again
      return cache.get(r);

    } else {
      Triple<Region, Region, Region> triple = delegate.getIfThenElse(r);

      // create node with label
      String predName = regionMap.inverse().get(triple.getFirst());
      nodeCounter += 1; // one more node is created
      int predNum = nodeCounter;
      str.append(predNum).append(" [label=\"").append(predName).append("\"];\n");

      // create arrow for true branch
      Region trueBranch = triple.getSecond();
      int trueTarget = regionToDot(trueBranch, str, cache);
      str.append(predNum).append(" -> ").append(trueTarget).append(" [style=filled];\n");

      // create arrow for false branch
      Region falseBranch = triple.getThird();
      int falseTarget = regionToDot(falseBranch, str, cache);
      str.append(predNum).append(" -> ").append(falseTarget).append(" [style=dotted];\n");

      cache.put(r, predNum);
      return predNum;
    }
  }
  public void addBootstrapToken(Token token, InetAddress endpoint) {
    assert token != null;
    assert endpoint != null;

    lock.writeLock().lock();
    try {
      InetAddress oldEndPoint = null;

      oldEndPoint = bootstrapTokens.get(token);
      if (oldEndPoint != null && !oldEndPoint.equals(endpoint))
        throw new RuntimeException(
            "Bootstrap Token collision between "
                + oldEndPoint
                + " and "
                + endpoint
                + " (token "
                + token);

      oldEndPoint = tokenToEndPointMap.get(token);
      if (oldEndPoint != null && !oldEndPoint.equals(endpoint))
        throw new RuntimeException(
            "Bootstrap Token collision between "
                + oldEndPoint
                + " and "
                + endpoint
                + " (token "
                + token);

      bootstrapTokens.inverse().remove(endpoint);
      bootstrapTokens.put(token, endpoint);
    } finally {
      lock.writeLock().unlock();
    }
  }
Exemple #10
0
  public static void main(String[] args) {

    // 注意BiMap的key和value都不能重复,否则inverse之后就不能保证键值一一对应了
    BiMap<String, Integer> users = HashBiMap.create();

    users.put("bandery", 10);
    users.put("ryan", 11);
    users.put("liuyan", 12);

    // 反转,key变成value,value变成key
    System.out.println(users.inverse().get(10));

    // 会有异常,key和value都不能重复
    // System.out.println(users.inverse().get(11));
    // 异常,"bandery"已经存在
    // users.put("bandery", 1);

    // 如果想插入的话,可以用forcePut强制插入,但在这之前会将相同的K或者V对应
    // 的键值对删除

    // 这样会把之前的bandery-10删除
    users.forcePut("bandery", 13);

    // 这样会把之前的ryan-11和liuyan-12都删除
    users.forcePut("ryan", 12);

    // 当然还有putAll方法
    Map<String, Integer> toadd = HashBiMap.create();
    toadd.put("aaa", 111111);
    toadd.put("bbb", 22222);
    users.putAll(toadd);
  }
  /**
   * Store an end-point to host ID mapping. Each ID must be unique, and cannot be changed after the
   * fact.
   *
   * @param hostId
   * @param endpoint
   */
  public void updateHostId(UUID hostId, InetAddress endpoint) {
    assert hostId != null;
    assert endpoint != null;

    lock.writeLock().lock();
    try {
      InetAddress storedEp = endpointToHostIdMap.inverse().get(hostId);
      if (storedEp != null) {
        if (!storedEp.equals(endpoint) && (FailureDetector.instance.isAlive(storedEp))) {
          throw new RuntimeException(
              String.format(
                  "Host ID collision between active endpoint %s and %s (id=%s)",
                  storedEp, endpoint, hostId));
        }
      }

      UUID storedId = endpointToHostIdMap.get(endpoint);
      if ((storedId != null) && (!storedId.equals(hostId)))
        logger.warn("Changing {}'s host ID from {} to {}", endpoint, storedId, hostId);

      endpointToHostIdMap.forcePut(endpoint, hostId);
    } finally {
      lock.writeLock().unlock();
    }
  }
  @EventHandler(priority = EventPriority.MONITOR)
  public void onPlayerMove(PlayerMoveEvent event) {

    // BAD BAD BAD test code
    //	hwh.randomlyRegisterWorld(event.getPlayer().getWorld());

    Location to = event.getTo();
    int newY = to.getBlockY();
    if (newY < HigherWorldsHack.SHARE_HEIGHT) {
      Player p = event.getPlayer();
      World w = worldStack.get(event.getTo().getWorld());
      if (w == null) return;
      Location toTeleportTo =
          new Location(w, to.getX(), HigherWorldsHack.transformPosUp(newY), to.getZ());
      HigherWorldsHack.HWH_LOGGER.log(
          Level.WARNING, "Player moved from " + to + " to " + toTeleportTo);
      p.teleport(toTeleportTo);
    } else if (newY > HigherWorldsHack.WORLD_HEIGHT - HigherWorldsHack.SHARE_HEIGHT) {
      Player p = event.getPlayer();
      World w = worldStack.inverse().get(event.getTo().getWorld());
      if (w == null) return;
      Location toTeleportTo =
          new Location(w, to.getX(), HigherWorldsHack.transformPosDown(newY), to.getZ());
      HigherWorldsHack.HWH_LOGGER.log(
          Level.WARNING, "Player moved from " + to + " to " + toTeleportTo);
      p.teleport(toTeleportTo);
    }
  }
 @SuppressWarnings({
   "rawtypes",
   "unchecked"
 }) // I can't parameterize this either; it scares the compiler
 private static <T extends VariantData<U, T, ?>, U extends CatalogType> T getItemData(
     ItemStack item, Class<T> type, BiMap<U, Integer> map) {
   int damage = item.getDurability();
   if (!map.containsValue(damage)) {
     throw new UnsupportedOperationException();
   }
   // no idea why a typecast is necessary here but excluding it makes javac angry
   @SuppressWarnings("RedundantCast")
   T data =
       (T)
           Pore.getGame()
               .getRegistry()
               .createItemBuilder()
               .itemType(MaterialConverter.asItem(item.getType()))
               .quantity(1)
               .build()
               .getOrCreate(type)
               .get();
   data.type().set(map.inverse().get(damage));
   return data;
 }
 /** Return the end-point for a unique host ID */
 public InetAddress getEndpointForHostId(UUID hostId) {
   lock.readLock().lock();
   try {
     return endpointToHostIdMap.inverse().get(hostId);
   } finally {
     lock.readLock().unlock();
   }
 }
  public String toString() {
    StringBuilder sb = new StringBuilder();
    lock.readLock().lock();
    try {
      Set<InetAddress> eps = tokenToEndPointMap.inverse().keySet();

      if (!eps.isEmpty()) {
        sb.append("Normal Tokens:");
        sb.append(System.getProperty("line.separator"));
        for (InetAddress ep : eps) {
          sb.append(ep);
          sb.append(":");
          sb.append(tokenToEndPointMap.inverse().get(ep));
          sb.append(System.getProperty("line.separator"));
        }
      }

      if (!bootstrapTokens.isEmpty()) {
        sb.append("Bootstrapping Tokens:");
        sb.append(System.getProperty("line.separator"));
        for (Map.Entry<Token, InetAddress> entry : bootstrapTokens.entrySet()) {
          sb.append(entry.getValue() + ":" + entry.getKey());
          sb.append(System.getProperty("line.separator"));
        }
      }

      if (!leavingEndPoints.isEmpty()) {
        sb.append("Leaving EndPoints:");
        sb.append(System.getProperty("line.separator"));
        for (InetAddress ep : leavingEndPoints) {
          sb.append(ep);
          sb.append(System.getProperty("line.separator"));
        }
      }

      if (!pendingRanges.isEmpty()) {
        sb.append("Pending Ranges:");
        sb.append(System.getProperty("line.separator"));
        sb.append(printPendingRanges());
      }
    } finally {
      lock.readLock().unlock();
    }

    return sb.toString();
  }
  @Test
  public void whenCreateBiMap_thenCreated() {
    final BiMap<String, Integer> words = HashBiMap.create();
    words.put("First", 1);
    words.put("Second", 2);
    words.put("Third", 3);

    assertEquals(2, words.get("Second").intValue());
    assertEquals("Third", words.inverse().get(3));
  }
  public boolean isMember(InetAddress endpoint) {
    assert endpoint != null;

    lock.readLock().lock();
    try {
      return tokenToEndPointMap.inverse().containsKey(endpoint);
    } finally {
      lock.readLock().unlock();
    }
  }
  public Token getToken(InetAddress endpoint) {
    assert endpoint != null;
    assert isMember(endpoint); // don't want to return nulls

    lock.readLock().lock();
    try {
      return tokenToEndPointMap.inverse().get(endpoint);
    } finally {
      lock.readLock().unlock();
    }
  }
Exemple #19
0
  public static void main(String[] args) {
    BiMap<Integer, String> bm = HashBiMap.create();
    bm.put(1, "s1");
    bm.put(2, "s2");

    System.out.println(bm.get(1));
    System.out.println(bm.inverse().get("s1"));
    System.out.println(bm.getOrDefault(77, "s0"));

    // this throws and exception
    // bm.put(3, "s2");
    // this forces the new mapping
    System.out.println(bm.get(2));
    bm.forcePut(3, "s2");
    System.out.println(bm.get(2));
    System.out.println(bm.get(3));
    System.out.println(bm.inverse().get("s2"));
    // after this key 2 is gone
    bm.forcePut(1, "s2");
    System.out.println(bm);
  }
  public String unmap(String typeName) {
    if (classNameBiMap == null || classNameBiMap.isEmpty()) {
      return typeName;
    }

    if (classNameBiMap.containsValue(typeName)) {
      return classNameBiMap.inverse().get(typeName);
    }
    int dollarIdx = typeName.indexOf('$');
    String realType = dollarIdx > -1 ? typeName.substring(0, dollarIdx) : typeName;
    String subType = dollarIdx > -1 ? typeName.substring(dollarIdx + 1) : "";

    String result =
        classNameBiMap.containsValue(realType)
            ? classNameBiMap.inverse().get(realType)
            : mcpNameBiMap.containsValue(realType)
                ? mcpNameBiMap.inverse().get(realType)
                : realType;
    result = dollarIdx > -1 ? result + "$" + subType : result;
    return result;
  }
  /**
   * Renders the page-to-page navigation graph into the file {@code navgraph.gv} in the {@code
   * .errai} cache directory.
   */
  private void renderNavigationToDotFile(BiMap<String, MetaClass> pages) {
    final File dotFile = new File(RebindUtils.getErraiCacheDir().getAbsolutePath(), "navgraph.gv");
    PrintWriter out = null;
    try {
      out = new PrintWriter(dotFile);
      out.println("digraph Navigation {");
      final MetaClass transitionToType = MetaClassFactory.get(TransitionTo.class);
      final MetaClass transitionAnchorType = MetaClassFactory.get(TransitionAnchor.class);
      final MetaClass transitionAnchorFactoryType =
          MetaClassFactory.get(TransitionAnchorFactory.class);
      for (Map.Entry<String, MetaClass> entry : pages.entrySet()) {
        String pageName = entry.getKey();
        MetaClass pageClass = entry.getValue();

        // entry for the node itself
        out.print("\"" + pageName + "\"");

        Page pageAnnotation = pageClass.getAnnotation(Page.class);
        List<Class<? extends PageRole>> roles = Arrays.asList(pageAnnotation.role());
        if (roles.contains(DefaultPage.class)) {
          out.print(" [penwidth=3]");
        }
        out.println();

        for (MetaField field : getAllFields(pageClass)) {
          if (field.getType().getErased().equals(transitionToType)
              || field.getType().getErased().equals(transitionAnchorType)
              || field.getType().getErased().equals(transitionAnchorFactoryType)) {
            MetaType targetPageType = field.getType().getParameterizedType().getTypeParameters()[0];
            String targetPageName = pages.inverse().get(targetPageType);

            // entry for the link between nodes
            out.println(
                "\""
                    + pageName
                    + "\" -> \""
                    + targetPageName
                    + "\" [label=\""
                    + field.getName()
                    + "\"]");
          }
        }
      }
      out.println("}");
    } catch (FileNotFoundException e) {
      throw new RuntimeException(e);
    } finally {
      if (out != null) {
        out.close();
      }
    }
  }
 public String toFieldName(String cls, String attributeName) {
   if (referenceFields.get(cls) == null) {
     BiMap<String, String> bimap = HashBiMap.create();
     referenceFields.put(cls, bimap);
   }
   BiMap<String, String> map = referenceFields.get(cls);
   String key = getKey(cls, attributeName);
   if (map.get(key) != null) return map.get(key);
   else {
     String optimalFieldName = Util.lowerFirst(Util.toJavaIdentifier(attributeName));
     String fieldName = optimalFieldName;
     if (map.inverse().get(fieldName) != null) {
       int i = 1;
       while (map.inverse().get(fieldName + i) != null) {
         i++;
       }
       fieldName = fieldName + i;
     }
     map.put(key, fieldName);
     return fieldName;
   }
 }
 public String toTableName(String schema, String className) {
   if (referencedTables.get(schema) == null) {
     BiMap<String, String> bimap = HashBiMap.create();
     referencedTables.put(schema, bimap);
   }
   BiMap<String, String> map = referencedTables.get(schema);
   String key = getKey(schema, className);
   if (map.get(key) != null) return map.get(key);
   else {
     String optimalName = Util.lowerFirst(Util.toColumnName(className));
     String name = optimalName;
     if (map.inverse().get(name) != null || isReservedWord(name)) {
       int i = 1;
       while (map.inverse().get(name + "_" + i) != null) {
         i++;
       }
       name = name + "_" + i;
     }
     map.put(key, name);
     return name;
   }
 }
 public String toColumnName(String cls, String attributeName) {
   if (referencedColumns.get(cls) == null) {
     BiMap<String, String> bimap = HashBiMap.create();
     referencedColumns.put(cls, bimap);
   }
   BiMap<String, String> map = referencedColumns.get(cls);
   String key = getKey(cls, attributeName);
   if (map.get(key) != null) return map.get(key);
   else {
     String optimalColumnName = Util.lowerFirst(Util.toColumnName(attributeName));
     String columnName = optimalColumnName;
     if (map.inverse().get(columnName) != null || isReservedWord(columnName)) {
       int i = 1;
       while (map.inverse().get(columnName + "_" + i) != null) {
         i++;
       }
       columnName = columnName + "_" + i;
     }
     map.put(key, columnName);
     return columnName;
   }
 }
  private void dumpRegion(Region r, Appendable out) throws IOException {
    if (regionMap.containsValue(r)) {
      out.append(regionMap.inverse().get(r));

    } else if (r.isFalse()) {
      out.append("FALSE");

    } else if (r.isTrue()) {
      out.append("TRUE");

    } else {
      Triple<Region, Region, Region> triple = delegate.getIfThenElse(r);
      String predName = regionMap.inverse().get(triple.getFirst());

      Region trueBranch = triple.getSecond();
      Region falseBranch = triple.getThird();

      if (trueBranch.isFalse()) {
        assert !falseBranch.isFalse();
        // only falseBranch is present
        out.append("!").append(predName).append(" & ");
        dumpRegion(falseBranch, out);

      } else if (falseBranch.isFalse()) {
        // only trueBranch is present
        out.append(predName).append(" & ");
        dumpRegion(trueBranch, out);

      } else {
        // both branches present
        out.append("((").append(predName).append(" & ");
        dumpRegion(trueBranch, out);
        out.append(") | (").append("!").append(predName).append(" & ");
        dumpRegion(falseBranch, out);
        out.append("))");
      }
    }
  }
Exemple #26
0
 public String getAntlrRuleName(AbstractRule rule, int paramConfig) {
   String result = antlrNameToRule.inverse().get(rule);
   int idx;
   if (result.startsWith("super")) {
     idx = 5;
   } else if (result.startsWith("rule")) {
     idx = 4;
   } else {
     throw new IllegalArgumentException(result);
   }
   if (paramConfig != 0) {
     result = (idx == 4 ? "norm" : "normSuper") + paramConfig + "_" + result.substring(idx);
   }
   return result;
 }
  @Test
  public void testBiMap() {
    BiMap<String, String> dataMap = HashBiMap.create();
    dataMap.put("number", "dea123");
    dataMap.put("dataEntered", "10/10/2012");
    dataMap.put("keyCode", "code00001");
    dataMap.put("isActive", "true");
    // key and value are both unique.
    dataMap.forcePut("isMember", "true");

    Assert.assertEquals("dea123", dataMap.get("number"));
    BiMap<String, String> inverseMap = dataMap.inverse();
    Assert.assertEquals("keyCode", inverseMap.get("code00001"));
    Assert.assertEquals("isMember", inverseMap.get("true"));
  }
  /**
   * Adds an expression with an alias name and returns a reference name. It specifies the alias as
   * an reference name.
   */
  public String addExpr(Expr expr, String alias) throws PlanningException {

    // if this name already exists, just returns the name.
    if (nameToIdMap.containsKey(alias)) {
      return alias;
    }

    // if the name is first
    int refId;
    if (idToExprBiMap.inverse().containsKey(expr)) {
      refId = idToExprBiMap.inverse().get(expr);
    } else {
      refId = getNextId();
      idToExprBiMap.put(refId, expr);
    }

    nameToIdMap.put(alias, refId);
    evaluationStateMap.put(refId, false);

    // add the entry to idToNames map
    TUtil.putToNestedList(idToNamesMap, refId, alias);

    return alias;
  }
 public String getName(final UUID uuid) {
   if (uuid == null) {
     return null;
   }
   // check online
   final PlotPlayer player = getPlayer(uuid);
   if (player != null) {
     return player.getName();
   }
   // check cache
   final StringWrapper name = uuidMap.inverse().get(uuid);
   if (name != null) {
     return name.value;
   }
   return null;
 }
 public String toFieldName(String cls, String viewedClass, BigInteger rNum) {
   if (referenceFields.get(cls) == null) {
     BiMap<String, String> bimap = HashBiMap.create();
     referenceFields.put(cls, bimap);
   }
   BiMap<String, String> map = referenceFields.get(cls);
   String key = getKey(viewedClass, rNum);
   if (map.get(key) != null) return map.get(key);
   else {
     String optimalFieldName = Util.lowerFirst(Util.toJavaIdentifier(viewedClass)) + "_R" + rNum;
     String currentKey = map.inverse().get(optimalFieldName);
     String fieldName;
     if (currentKey == null) fieldName = optimalFieldName;
     else fieldName = optimalFieldName + "_R" + rNum;
     map.put(key, fieldName);
     return fieldName;
   }
 }