コード例 #1
0
 public void testAsList() {
   ImmutableMultiset<String> multiset = ImmutableMultiset.of("a", "a", "b", "b", "b");
   ImmutableList<String> list = multiset.asList();
   assertEquals(ImmutableList.of("a", "a", "b", "b", "b"), list);
   assertEquals(2, list.indexOf("b"));
   assertEquals(4, list.lastIndexOf("b"));
 }
コード例 #2
0
ファイル: ImportOp.java プロジェクト: scooterw/GeoGit
 /**
  * Translates a feature pointed by a node from its original feature type to a given one, using
  * values from those attributes that exist in both original and destination feature type. New
  * attributes are populated with null values
  *
  * @param node The node that points to the feature. No checking is performed to ensure the node
  *     points to a feature instead of other type
  * @param featureType the destination feature type
  * @return a feature with the passed feature type and data taken from the input feature
  */
 private Feature alter(NodeRef node, RevFeatureType featureType) {
   RevFeature oldFeature =
       command(RevObjectParse.class).setObjectId(node.objectId()).call(RevFeature.class).get();
   RevFeatureType oldFeatureType;
   oldFeatureType =
       command(RevObjectParse.class)
           .setObjectId(node.getMetadataId())
           .call(RevFeatureType.class)
           .get();
   ImmutableList<PropertyDescriptor> oldAttributes = oldFeatureType.sortedDescriptors();
   ImmutableList<PropertyDescriptor> newAttributes = featureType.sortedDescriptors();
   ImmutableList<Optional<Object>> oldValues = oldFeature.getValues();
   List<Optional<Object>> newValues = Lists.newArrayList();
   for (int i = 0; i < newAttributes.size(); i++) {
     int idx = oldAttributes.indexOf(newAttributes.get(i));
     if (idx != -1) {
       Optional<Object> oldValue = oldValues.get(idx);
       newValues.add(oldValue);
     } else {
       newValues.add(Optional.absent());
     }
   }
   RevFeature newFeature = RevFeature.build(ImmutableList.copyOf(newValues));
   FeatureBuilder featureBuilder = new FeatureBuilder(featureType);
   Feature feature = featureBuilder.build(node.name(), newFeature);
   return feature;
 }
コード例 #3
0
  /**
   * Get similarity of X submission to Y submission.
   *
   * @param xSubmission Submission to get similarities for
   * @param ySubmission Submission to get similarities relative to
   * @return Similarities of xSubmission to ySubmission
   * @throws NoSuchSubmissionException Thrown if either xSubmission or ySubmission are not present
   *     in the matrix
   */
  public AlgorithmResults getEntryFor(Submission xSubmission, Submission ySubmission)
      throws NoSuchSubmissionException {
    checkNotNull(xSubmission);
    checkNotNull(ySubmission);

    if (!xSubmissions.contains(xSubmission)) {
      throw new NoSuchSubmissionException(
          "X Submission with name " + xSubmission.getName() + " not found in similarity matrix!");
    } else if (!ySubmissions.contains(ySubmission)) {
      throw new NoSuchSubmissionException(
          "Y Submission with name " + ySubmission.getName() + " not found in similarity matrix!");
    }

    int xIndex = xSubmissions.indexOf(xSubmission);
    int yIndex = ySubmissions.indexOf(ySubmission);

    return entries[xIndex][yIndex];
  }
コード例 #4
0
 public void testAsList() {
   ImmutableSortedMultiset<String> multiset = ImmutableSortedMultiset.of("a", "a", "b", "b", "b");
   ImmutableList<String> list = multiset.asList();
   assertEquals(ImmutableList.of("a", "a", "b", "b", "b"), list);
   assertTrue(list instanceof ImmutableAsList);
   ImmutableList<String> copy = SerializableTester.reserializeAndAssert(list);
   assertTrue(copy instanceof ImmutableAsList);
   assertEquals(2, list.indexOf("b"));
   assertEquals(4, list.lastIndexOf("b"));
 }
コード例 #5
0
  /**
   * Gets the context of this event within a stream
   *
   * @return the context in struct form
   */
  public StructDefinition getContext() {

    /* Most common case so far */
    if (fStreamContext == null) {
      return fEventContext;
    }

    /* streamContext is not null, but the context of the event is null */
    if (fEventContext == null) {
      return fStreamContext;
    }

    // TODO: cache if this is a performance issue

    /* The stream context and event context are assigned. */
    StructDeclaration mergedDeclaration = new StructDeclaration(1);

    Builder<String> builder = ImmutableList.<String>builder();
    List<Definition> fieldValues = new ArrayList<>();

    /* Add fields from the stream */
    for (String fieldName : fStreamContext.getFieldNames()) {
      Definition definition = fStreamContext.getDefinition(fieldName);
      mergedDeclaration.addField(fieldName, definition.getDeclaration());
      builder.add(fieldName);
      fieldValues.add(definition);
    }

    ImmutableList<String> fieldNames = builder.build();
    /*
     * Add fields from the event context, overwrite the stream ones if
     * needed.
     */
    for (String fieldName : fEventContext.getFieldNames()) {
      Definition definition = fEventContext.getDefinition(fieldName);
      mergedDeclaration.addField(fieldName, definition.getDeclaration());
      if (fieldNames.contains(fieldName)) {
        fieldValues.set((fieldNames.indexOf(fieldName)), definition);
      } else {
        builder.add(fieldName);
        fieldValues.add(definition);
      }
    }
    fieldNames = builder.build();
    StructDefinition mergedContext =
        new StructDefinition(
            mergedDeclaration,
            this,
            "context", //$NON-NLS-1$
            fieldNames,
            fieldValues.toArray(new Definition[fieldValues.size()]));
    return mergedContext;
  }
コード例 #6
0
ファイル: ImmutableList.java プロジェクト: kongtaotao/gitTest
 @Override
 public int lastIndexOf(@Nullable Object object) {
   int index = forwardList.indexOf(object);
   return (index >= 0) ? reverseIndex(index) : -1;
 }
コード例 #7
0
ファイル: FMLModContainer.java プロジェクト: recon88/FML
  @Subscribe
  public void constructMod(FMLConstructionEvent event) {
    try {
      ModClassLoader modClassLoader = event.getModClassLoader();
      modClassLoader.addFile(source);
      modClassLoader.clearNegativeCacheFor(candidate.getClassList());
      Class<?> clazz = Class.forName(className, true, modClassLoader);

      Certificate[] certificates = clazz.getProtectionDomain().getCodeSource().getCertificates();
      int len = 0;
      if (certificates != null) {
        len = certificates.length;
      }
      Builder<String> certBuilder = ImmutableList.<String>builder();
      for (int i = 0; i < len; i++) {
        certBuilder.add(CertificateHelper.getFingerprint(certificates[i]));
      }

      ImmutableList<String> certList = certBuilder.build();
      sourceFingerprints = ImmutableSet.copyOf(certList);

      String expectedFingerprint = (String) descriptor.get("certificateFingerprint");

      fingerprintNotPresent = true;

      if (expectedFingerprint != null && !expectedFingerprint.isEmpty()) {
        if (!sourceFingerprints.contains(expectedFingerprint)) {
          Level warnLevel = Level.SEVERE;
          if (source.isDirectory()) {
            warnLevel = Level.FINER;
          }
          FMLLog.log(
              getModId(),
              warnLevel,
              "The mod %s is expecting signature %s for source %s, however there is no signature matching that description",
              getModId(),
              expectedFingerprint,
              source.getName());
        } else {
          certificate = certificates[certList.indexOf(expectedFingerprint)];
          fingerprintNotPresent = false;
        }
      }

      CustomProperty[] props = (CustomProperty[]) descriptor.get("customProperties");
      if (props != null && props.length > 0) {
        com.google.common.collect.ImmutableMap.Builder<String, String> builder =
            ImmutableMap.<String, String>builder();
        for (CustomProperty p : props) {
          builder.put(p.k(), p.v());
        }
        customModProperties = builder.build();
      } else {
        customModProperties = EMPTY_PROPERTIES;
      }

      Method factoryMethod = gatherAnnotations(clazz);
      modInstance = getLanguageAdapter().getNewInstance(this, clazz, modClassLoader, factoryMethod);
      isNetworkMod =
          FMLNetworkHandler.instance().registerNetworkMod(this, clazz, event.getASMHarvestedData());
      if (fingerprintNotPresent) {
        eventBus.post(
            new FMLFingerprintViolationEvent(
                source.isDirectory(),
                source,
                ImmutableSet.copyOf(this.sourceFingerprints),
                expectedFingerprint));
      }
      ProxyInjector.inject(
          this,
          event.getASMHarvestedData(),
          FMLCommonHandler.instance().getSide(),
          getLanguageAdapter());
      processFieldAnnotations(event.getASMHarvestedData());
    } catch (Throwable e) {
      controller.errorOccurred(this, e);
      Throwables.propagateIfPossible(e);
    }
  }
コード例 #8
0
ファイル: BaseFunction.java プロジェクト: vanwaals/bazel
  /**
   * Process the caller-provided arguments into an array suitable for the callee (this function).
   */
  public Object[] processArguments(
      List<Object> args, @Nullable Map<String, Object> kwargs, @Nullable Location loc)
      throws EvalException {

    Object[] arguments = new Object[getArgArraySize()];

    // extract function signature
    FunctionSignature sig = signature.getSignature();
    FunctionSignature.Shape shape = sig.getShape();
    ImmutableList<String> names = sig.getNames();
    List<Object> defaultValues = signature.getDefaultValues();

    // Note that this variable will be adjusted down if there are extra positionals,
    // after these extra positionals are dumped into starParam.
    int numPositionalArgs = args.size();

    int numMandatoryPositionalParams = shape.getMandatoryPositionals();
    int numOptionalPositionalParams = shape.getOptionalPositionals();
    int numMandatoryNamedOnlyParams = shape.getMandatoryNamedOnly();
    int numOptionalNamedOnlyParams = shape.getOptionalNamedOnly();
    boolean hasStarParam = shape.hasStarArg();
    boolean hasKwParam = shape.hasKwArg();
    int numPositionalParams = numMandatoryPositionalParams + numOptionalPositionalParams;
    int numNamedOnlyParams = numMandatoryNamedOnlyParams + numOptionalNamedOnlyParams;
    int numNamedParams = numPositionalParams + numNamedOnlyParams;
    int kwParamIndex = names.size() - 1; // only valid if hasKwParam

    // (1) handle positional arguments
    if (hasStarParam) {
      // Nota Bene: we collect extra positional arguments in a (tuple,) rather than a [list],
      // and this is actually the same as in Python.
      int starParamIndex = numNamedParams;
      if (numPositionalArgs > numPositionalParams) {
        arguments[starParamIndex] =
            Tuple.copyOf(args.subList(numPositionalParams, numPositionalArgs));
        numPositionalArgs = numPositionalParams; // clip numPositionalArgs
      } else {
        arguments[starParamIndex] = Tuple.EMPTY;
      }
    } else if (numPositionalArgs > numPositionalParams) {
      throw new EvalException(
          loc,
          numPositionalParams > 0
              ? "too many (" + numPositionalArgs + ") positional arguments in call to " + this
              : this + " does not accept positional arguments, but got " + numPositionalArgs);
    }

    for (int i = 0; i < numPositionalArgs; i++) {
      arguments[i] = args.get(i);
    }

    // (2) handle keyword arguments
    if (kwargs == null || kwargs.isEmpty()) {
      // Easy case (2a): there are no keyword arguments.
      // All arguments were positional, so check we had enough to fill all mandatory positionals.
      if (numPositionalArgs < numMandatoryPositionalParams) {
        throw new EvalException(
            loc,
            String.format(
                "insufficient arguments received by %s (got %s, expected at least %s)",
                this, numPositionalArgs, numMandatoryPositionalParams));
      }
      // We had no named argument, so fail if there were mandatory named-only parameters
      if (numMandatoryNamedOnlyParams > 0) {
        throw new EvalException(
            loc, String.format("missing mandatory keyword arguments in call to %s", this));
      }
      // Fill in defaults for missing optional parameters, that were conveniently grouped together,
      // thanks to the absence of mandatory named-only parameters as checked above.
      if (defaultValues != null) {
        int j = numPositionalArgs - numMandatoryPositionalParams;
        int endOptionalParams = numPositionalParams + numOptionalNamedOnlyParams;
        for (int i = numPositionalArgs; i < endOptionalParams; i++) {
          arguments[i] = defaultValues.get(j++);
        }
      }
      // If there's a kwParam, it's empty.
      if (hasKwParam) {
        // TODO(bazel-team): create a fresh mutable dict, like Python does
        arguments[kwParamIndex] = ImmutableMap.<String, Object>of();
      }
    } else if (hasKwParam && numNamedParams == 0) {
      // Easy case (2b): there are no named parameters, but there is a **kwParam.
      // Therefore all keyword arguments go directly to the kwParam.
      // Note that *starParam and **kwParam themselves don't count as named.
      // Also note that no named parameters means no mandatory parameters that weren't passed,
      // and no missing optional parameters for which to use a default. Thus, no loops.
      // TODO(bazel-team): create a fresh mutable dict, like Python does
      arguments[kwParamIndex] = kwargs; // NB: not 2a means kwarg isn't null
    } else {
      // Hard general case (2c): some keyword arguments may correspond to named parameters
      HashMap<String, Object> kwArg = hasKwParam ? new HashMap<String, Object>() : null;

      // For nicer stabler error messages, start by checking against
      // an argument being provided both as positional argument and as keyword argument.
      ArrayList<String> bothPosKey = new ArrayList<>();
      for (int i = 0; i < numPositionalArgs; i++) {
        String name = names.get(i);
        if (kwargs.containsKey(name)) {
          bothPosKey.add(name);
        }
      }
      if (!bothPosKey.isEmpty()) {
        throw new EvalException(
            loc,
            String.format(
                "argument%s '%s' passed both by position and by name in call to %s",
                (bothPosKey.size() > 1 ? "s" : ""), Joiner.on("', '").join(bothPosKey), this));
      }

      // Accept the arguments that were passed.
      for (Map.Entry<String, Object> entry : kwargs.entrySet()) {
        String keyword = entry.getKey();
        Object value = entry.getValue();
        int pos = names.indexOf(keyword); // the list should be short, so linear scan is OK.
        if (0 <= pos && pos < numNamedParams) {
          arguments[pos] = value;
        } else {
          if (!hasKwParam) {
            List<String> unexpected =
                Ordering.natural()
                    .sortedCopy(
                        Sets.difference(
                            kwargs.keySet(),
                            ImmutableSet.copyOf(names.subList(0, numNamedParams))));
            throw new EvalException(
                loc,
                String.format(
                    "unexpected keyword%s '%s' in call to %s",
                    unexpected.size() > 1 ? "s" : "", Joiner.on("', '").join(unexpected), this));
          }
          if (kwArg.containsKey(keyword)) {
            throw new EvalException(
                loc,
                String.format("%s got multiple values for keyword argument '%s'", this, keyword));
          }
          kwArg.put(keyword, value);
        }
      }
      if (hasKwParam) {
        // TODO(bazel-team): create a fresh mutable dict, like Python does
        arguments[kwParamIndex] = ImmutableMap.copyOf(kwArg);
      }

      // Check that all mandatory parameters were filled in general case 2c.
      // Note: it's possible that numPositionalArgs > numMandatoryPositionalParams but that's OK.
      for (int i = numPositionalArgs; i < numMandatoryPositionalParams; i++) {
        if (arguments[i] == null) {
          throw new EvalException(
              loc,
              String.format(
                  "missing mandatory positional argument '%s' while calling %s",
                  names.get(i), this));
        }
      }

      int endMandatoryNamedOnlyParams = numPositionalParams + numMandatoryNamedOnlyParams;
      for (int i = numPositionalParams; i < endMandatoryNamedOnlyParams; i++) {
        if (arguments[i] == null) {
          throw new EvalException(
              loc,
              String.format(
                  "missing mandatory named-only argument '%s' while calling %s",
                  names.get(i), this));
        }
      }

      // Get defaults for those parameters that weren't passed.
      if (defaultValues != null) {
        for (int i = Math.max(numPositionalArgs, numMandatoryPositionalParams);
            i < numPositionalParams;
            i++) {
          if (arguments[i] == null) {
            arguments[i] = defaultValues.get(i - numMandatoryPositionalParams);
          }
        }
        int numMandatoryParams = numMandatoryPositionalParams + numMandatoryNamedOnlyParams;
        for (int i = numMandatoryParams + numOptionalPositionalParams; i < numNamedParams; i++) {
          if (arguments[i] == null) {
            arguments[i] = defaultValues.get(i - numMandatoryParams);
          }
        }
      }
    } // End of general case 2c for argument passing.

    return arguments;
  }