@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;
  }
 /**
  * Adds configured variables to the variable service.
  *
  * @param variableService service to add to
  * @param variables configured variables
  */
 protected static void initVariables(
     VariableService variableService,
     Map<String, ConfigurationVariable> variables,
     EngineImportService engineImportService) {
   for (Map.Entry<String, ConfigurationVariable> entry : variables.entrySet()) {
     try {
       Pair<String, Boolean> arrayType =
           JavaClassHelper.isGetArrayType(entry.getValue().getType());
       variableService.createNewVariable(
           null,
           entry.getKey(),
           arrayType.getFirst(),
           entry.getValue().isConstant(),
           arrayType.getSecond(),
           false,
           entry.getValue().getInitializationValue(),
           engineImportService);
       variableService.allocateVariableState(entry.getKey(), 0, null);
     } catch (VariableExistsException e) {
       throw new ConfigurationException("Error configuring variables: " + e.getMessage(), e);
     } catch (VariableTypeException e) {
       throw new ConfigurationException("Error configuring variables: " + e.getMessage(), e);
     }
   }
 }
  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;
  }
Esempio n. 4
0
 public PropertyMap deserialize(
     JsonElement json, Type typeOfT, JsonDeserializationContext context)
     throws JsonParseException {
   PropertyMap result = new PropertyMap();
   Iterator i$;
   Map.Entry<String, JsonElement> entry;
   if ((json instanceof JsonObject)) {
     JsonObject object = (JsonObject) json;
     for (i$ = object.entrySet().iterator(); i$.hasNext(); ) {
       entry = (Map.Entry) i$.next();
       if ((entry.getValue() instanceof JsonArray)) {
         for (JsonElement element : (JsonArray) entry.getValue()) {
           result.put(
               entry.getKey(), new Property((String) entry.getKey(), element.getAsString()));
         }
       }
     }
   } else if ((json instanceof JsonArray)) {
     for (JsonElement element : (JsonArray) json) {
       if ((element instanceof JsonObject)) {
         JsonObject object = (JsonObject) element;
         String name = object.getAsJsonPrimitive("name").getAsString();
         String value = object.getAsJsonPrimitive("value").getAsString();
         if (object.has("signature")) {
           result.put(
               name,
               new Property(name, value, object.getAsJsonPrimitive("signature").getAsString()));
         } else {
           result.put(name, new Property(name, value));
         }
       }
     }
   }
   return result;
 }
    public boolean equals(Object o) {
      if (!(o instanceof Map.Entry)) return false;
      Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;

      return (key == null ? e.getKey() == null : key.equals(e.getKey()))
          && (value == null ? e.getValue() == null : value.equals(e.getValue()));
    }
Esempio n. 6
0
  public List<Events> getEventsByParams() {
    ConcurrentHashMap<Integer, Events> eventBeforeSearch =
        AppStorage.INSTANCE.getEventStorageCopy();
    ConcurrentHashMap<Integer, Events> eventAfterSearch = new ConcurrentHashMap<Integer, Events>();
    if (city != null && city.length() != 0) {
      for (Map.Entry<Integer, Events> entry : eventBeforeSearch.entrySet()) {
        if (city.equalsIgnoreCase(entry.getValue().getCity()))
          eventAfterSearch.put(entry.getKey(), entry.getValue());
      }
    }
    eventBeforeSearch.clear();
    eventBeforeSearch = AppStorage.INSTANCE.getEventStorageCopy();

    if (description != null && description.length() > 0 && !description.equals("")) {
      eventAfterSearch.clear();
      for (Map.Entry<Integer, Events> entry : eventBeforeSearch.entrySet()) {
        if (entry.getValue().getDescription().contains(description))
          eventAfterSearch.put(entry.getKey(), entry.getValue());
      }
    }
    eventBeforeSearch = new ConcurrentHashMap<Integer, Events>(eventAfterSearch);

    /*   if(date != null){
            for(Map.Entry<Integer,Events> entry : eventBeforeSearch.entrySet()){
                GregorianCalendar eventDate = entry.getValue().getDate();
                GregorianCalendar before = new GregorianCalendar(eventDate.get(1),eventDate.get(2),eventDate.get(4)+1);
                GregorianCalendar after = new GregorianCalendar(eventDate.get(1),eventDate.get(2),eventDate.get(4));
                if(date.after(after) && date.before(before)) eventAfterSearch.put(entry.getKey(),entry.getValue());
            }
        }
    */ return new ArrayList<Events>(eventAfterSearch.values());
  }
  @Override
  public boolean convertRecords2Links() {
    final Map<OIdentifiable, Change> newChangedValues = new HashMap<OIdentifiable, Change>();
    for (Map.Entry<OIdentifiable, Change> entry : changes.entrySet()) {
      OIdentifiable identifiable = entry.getKey();
      if (identifiable instanceof ORecord) {
        ORID identity = identifiable.getIdentity();
        ORecord record = (ORecord) identifiable;
        identity = record.getIdentity();

        newChangedValues.put(identity, entry.getValue());
      } else newChangedValues.put(entry.getKey().getIdentity(), entry.getValue());
    }

    for (Map.Entry<OIdentifiable, Change> entry : newChangedValues.entrySet()) {
      if (entry.getKey() instanceof ORecord) {
        ORecord record = (ORecord) entry.getKey();

        newChangedValues.put(record, entry.getValue());
      } else return false;
    }

    newEntries.clear();

    changes.clear();
    changes.putAll(newChangedValues);

    return true;
  }
 @Override
 public void draw() {
   if (sliders != null) {
     MuseRenderer.drawCenteredString(
         "Tinker", (border.left() + border.right()) / 4, border.top() / 2 + 2);
     GL11.glPushMatrix();
     GL11.glScaled(SCALERATIO, SCALERATIO, SCALERATIO);
     super.draw();
     for (ClickableSlider slider : sliders) {
       slider.draw();
     }
     int nexty = (int) (sliders.size() * 24 + border.top() + 24);
     for (Map.Entry<String, Double> property : propertyStrings.entrySet()) {
       nexty += 8;
       String[] str = {
         property.getKey() + ':',
         MuseStringUtils.formatNumberFromUnits(
             property.getValue(), PowerModule.getUnit(property.getKey()))
       };
       MuseRenderer.drawStringsJustified(
           Arrays.asList(str), border.left() + 4, border.right() - 4, nexty);
     }
     GL11.glPopMatrix();
   }
 }
Esempio n. 9
0
  public static int solve() {
    Map<Integer, Integer> divisorSum = new HashMap<Integer, Integer>();
    for (int i = 1; i <= 10000; i++) {
      divisorSum.put(i, Divisors.getSumDivisors(i));
    }

    Map<Integer, Integer> amicable = new HashMap<Integer, Integer>();
    for (Map.Entry e : divisorSum.entrySet()) {
      if (divisorSum.get(e.getValue()) == null) {
        continue;
      }

      if (divisorSum.get(e.getValue()).equals(e.getKey())) {
        amicable.put((Integer) e.getValue(), (Integer) e.getKey());
      }
    }

    // System.out.println("amicable: " + amicable);

    int res = 0;
    for (Integer n : amicable.keySet()) {
      if (!n.equals(amicable.get(n))) {
        res += n;
      }
    }

    return res;
  }
Esempio n. 10
0
  public void joeFiddle() {
    EnemyHeadquartersUtilities enemyHeadquartersUtilities =
        new EnemyHeadquartersUtilities(enemyHeadquarters, game);

    Building enemyEhqNeighbor = null;
    Map<Building, WeatherStationUtilities.CardinalDirection> enemyHqNeighbor =
        enemyHeadquartersUtilities.getEnemyHeadquartersNeighbors();
    for (Map.Entry<Building, WeatherStationUtilities.CardinalDirection> enemyneighbor :
        enemyHqNeighbor.entrySet()) {
      if (enemyneighbor != null && enemyneighbor.getKey().health > 0) {
        enemyEhqNeighbor = enemyneighbor.getKey();
        break;
      }
    }
    if (enemyEhqNeighbor != null) {
      List<Warehouse> myAttackers = player.warehouses;

      while (player.bribesRemaining > 0) {
        Warehouse myAttacker =
            warehouseUtilities.getClosestWarehouse(enemyEhqNeighbor, myAttackers);
        if (myAttacker != null) {
          myAttacker.ignite(enemyEhqNeighbor);
          myAttackers.remove(myAttacker);
        }
      }
    }
  }
  private void addTagsToProperties(MethodInfo mi, JSONObject propJ) throws JSONException {
    // create description object. description tag enables the visual tools to display description of
    // keys/values
    // of a map property, items of a list, properties within a complex type.
    JSONObject descriptionObj = new JSONObject();
    if (mi.comment != null) {
      descriptionObj.put("$", mi.comment);
    }
    for (Map.Entry<String, String> descEntry : mi.descriptions.entrySet()) {
      descriptionObj.put(descEntry.getKey(), descEntry.getValue());
    }
    if (descriptionObj.length() > 0) {
      propJ.put("descriptions", descriptionObj);
    }

    // create useSchema object. useSchema tag is added to enable visual tools to be able to render a
    // text field
    // as a dropdown with choices populated from the schema attached to the port.
    JSONObject useSchemaObj = new JSONObject();
    for (Map.Entry<String, String> useSchemaEntry : mi.useSchemas.entrySet()) {
      useSchemaObj.put(useSchemaEntry.getKey(), useSchemaEntry.getValue());
    }
    if (useSchemaObj.length() > 0) {
      propJ.put("useSchema", useSchemaObj);
    }
  }
Esempio n. 12
0
 private void exportAttributes(Map<String, Object> attrMap) {
   for (Map.Entry<String, Object> e : attrMap.entrySet()) {
     if (e.getKey().equals(WikiPage.CHANGENOTE))
       exportProperty("wiki:changeNote", (String) e.getValue(), STRING);
     else exportProperty(e.getKey(), e.getValue().toString(), STRING);
   }
 }
Esempio n. 13
0
 private void buildXQueryDynamicContext(
     XQueryContext context, Object[] params, MutableDocumentSet docsToLock, boolean bindVariables)
     throws XPathException {
   context.setBackwardsCompatibility(false);
   context.setStaticallyKnownDocuments(docs);
   context.setBaseURI(baseUri == null ? new AnyURIValue("/db") : baseUri);
   if (bindVariables) {
     for (Map.Entry<QName, Object> entry : bindings.entrySet()) {
       context.declareVariable(
           new org.exist.dom.QName(
               entry.getKey().getLocalPart(),
               entry.getKey().getNamespaceURI(),
               entry.getKey().getPrefix()),
           convertValue(entry.getValue()));
     }
     if (params != null)
       for (int i = 0; i < params.length; i++) {
         Object convertedValue = convertValue(params[i]);
         if (docsToLock != null && convertedValue instanceof Sequence) {
           docsToLock.addAll(((Sequence) convertedValue).getDocumentSet());
         }
         context.declareVariable("_" + (i + 1), convertedValue);
       }
   }
 }
Esempio n. 14
0
  public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    // алфавит
    ArrayList<Character> alphabet = new ArrayList<Character>();
    for (int i = 0; i < 32; i++) {
      alphabet.add((char) ('а' + i));
    }
    alphabet.add(6, 'ё');

    // ввод строк
    ArrayList<String> list = new ArrayList<String>();
    for (int i = 0; i < 10; i++) {
      String s = reader.readLine();
      list.add(s.toLowerCase());
    }
    HashMap<Character, Integer> resultMap = Count(list, alphabet);

    for (int i = 0; i < 33; i++) {
      for (Map.Entry<Character, Integer> pair : resultMap.entrySet()) {
        if (pair.getKey() == alphabet.get(i)) {
          System.out.println(pair.getKey() + " " + pair.getValue());
        }
      }
    }
  }
Esempio n. 15
0
  @Test
  public void testAdamUpdater() {
    INDArray m, v;
    double lr = 0.01;
    int iteration = 0;
    double beta1 = 0.8;
    double beta2 = 0.888;

    NeuralNetConfiguration conf =
        new NeuralNetConfiguration.Builder()
            .learningRate(lr)
            .iterations(iteration)
            .adamMeanDecay(beta1)
            .adamVarDecay(beta2)
            .layer(
                new DenseLayer.Builder()
                    .nIn(nIn)
                    .nOut(nOut)
                    .updater(org.deeplearning4j.nn.conf.Updater.ADAM)
                    .build())
            .build();

    int numParams = LayerFactories.getFactory(conf).initializer().numParams(conf, true);
    INDArray params = Nd4j.create(1, numParams);
    Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0, params, true);
    Updater updater = UpdaterCreator.getUpdater(layer);
    int updaterStateSize = updater.stateSizeForLayer(layer);
    INDArray updaterState = Nd4j.create(1, updaterStateSize);
    updater.setStateViewArray(layer, updaterState, true);

    updater.update(layer, gradient, iteration, 1);

    double beta1t = FastMath.pow(beta1, iteration);
    double beta2t = FastMath.pow(beta2, iteration);
    double alphat = lr * FastMath.sqrt(1 - beta2t) / (1 - beta1t);
    if (Double.isNaN(alphat) || alphat == 0.0) alphat = epsilon;

    Gradient gradientDup = new DefaultGradient();
    gradientDup.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient);
    gradientDup.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient);

    for (Map.Entry<String, INDArray> entry : gradientDup.gradientForVariable().entrySet()) {
      val = entry.getValue();
      m = Nd4j.zeros(val.shape());
      v = Nd4j.zeros(val.shape());

      m.muli(beta1).addi(val.mul(1.0 - beta1));
      v.muli(beta2).addi(val.mul(val).mul(1.0 - beta2));
      gradExpected = m.mul(alphat).divi(Transforms.sqrt(v).addi(epsilon));
      if (!gradExpected.equals(gradient.getGradientFor(entry.getKey()))) {
        System.out.println(Arrays.toString(gradExpected.dup().data().asFloat()));
        System.out.println(
            Arrays.toString(gradient.getGradientFor(entry.getKey()).dup().data().asFloat()));
      }
      assertEquals(gradExpected, gradient.getGradientFor(entry.getKey()));
    }

    assertEquals(beta1, layer.conf().getLayer().getAdamMeanDecay(), 1e-4);
    assertEquals(beta2, layer.conf().getLayer().getAdamVarDecay(), 1e-4);
  }
Esempio n. 16
0
  @Test
  public void getDistinctKeysAndCounts_SortByKeyDescending() {

    Connection connection = null;
    ResultSet resultSet = null;
    try {
      ConnectionManager connectionManager = temporaryFileDatabase.getConnectionManager(true);
      initWithTestData(connectionManager);

      connection = connectionManager.getConnection(null);
      resultSet = DBQueries.getDistinctKeysAndCounts(true, NAME, connection);

      Map<String, Integer> resultSetToMap = resultSetToMap(resultSet);
      assertEquals(3, resultSetToMap.size());

      Iterator<Map.Entry<String, Integer>> entriesIterator = resultSetToMap.entrySet().iterator();

      Map.Entry entry = entriesIterator.next();
      assertEquals("gps", entry.getKey());
      assertEquals(1, entry.getValue());

      entry = entriesIterator.next();
      assertEquals("airbags", entry.getKey());
      assertEquals(1, entry.getValue());

      entry = entriesIterator.next();
      assertEquals("abs", entry.getKey());
      assertEquals(2, entry.getValue());

    } finally {
      DBUtils.closeQuietly(resultSet);
      DBUtils.closeQuietly(connection);
    }
  }
  /**
   * Filters non endpoint configuration parameters from parameter list and puts them together as
   * parameters string. According to given endpoint configuration type only non endpoint
   * configuration settings are added to parameter string.
   *
   * @param parameters
   * @param endpointConfigurationType
   * @return
   */
  protected String getParameterString(
      Map<String, String> parameters,
      Class<? extends EndpointConfiguration> endpointConfigurationType) {
    StringBuilder paramString = new StringBuilder();

    for (Map.Entry<String, String> parameterEntry : parameters.entrySet()) {
      Field field = ReflectionUtils.findField(endpointConfigurationType, parameterEntry.getKey());

      if (field == null) {
        if (paramString.length() == 0) {
          paramString
              .append("?")
              .append(parameterEntry.getKey())
              .append("=")
              .append(parameterEntry.getValue());
        } else {
          paramString
              .append("&")
              .append(parameterEntry.getKey())
              .append("=")
              .append(parameterEntry.getValue());
        }
      }
    }

    return paramString.toString();
  }
  /**
   * {@inheritDoc}
   *
   * @param ctx
   */
  @Override
  public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException {
    super.prepareMarshal(ctx);

    if (ownedVals != null) {
      ownedValKeys = ownedVals.keySet();

      ownedValVals = ownedVals.values();

      for (Map.Entry<IgniteTxKey, CacheVersionedValue> entry : ownedVals.entrySet()) {
        GridCacheContext cacheCtx = ctx.cacheContext(entry.getKey().cacheId());

        entry.getKey().prepareMarshal(cacheCtx);

        entry.getValue().prepareMarshal(cacheCtx.cacheObjectContext());
      }
    }

    if (retVal != null && retVal.cacheId() != 0) {
      GridCacheContext cctx = ctx.cacheContext(retVal.cacheId());

      assert cctx != null : retVal.cacheId();

      retVal.prepareMarshal(cctx);
    }

    if (filterFailedKeys != null) {
      for (IgniteTxKey key : filterFailedKeys) {
        GridCacheContext cctx = ctx.cacheContext(key.cacheId());

        key.prepareMarshal(cctx);
      }
    }
  }
Esempio n. 19
0
 private void buildParameters(StringBuilder buf, boolean concat, String[] parameters) {
   if (getParameters() != null && getParameters().size() > 0) {
     List<String> includes =
         (parameters == null || parameters.length == 0 ? null : Arrays.asList(parameters));
     boolean first = true;
     for (Map.Entry<String, String> entry :
         new TreeMap<String, String>(getParameters()).entrySet()) {
       if (entry.getKey() != null
           && entry.getKey().length() > 0
           && (includes == null || includes.contains(entry.getKey()))) {
         if (first) {
           if (concat) {
             buf.append("?");
           }
           first = false;
         } else {
           buf.append("&");
         }
         buf.append(entry.getKey());
         buf.append("=");
         buf.append(entry.getValue() == null ? "" : entry.getValue().trim());
       }
     }
   }
 }
 public void clopen(Object... settings) {
   config = getConfiguration();
   if (mgmt != null && mgmt.isOpen()) mgmt.rollback();
   if (null != tx && tx.isOpen()) tx.commit();
   if (settings != null && settings.length > 0) {
     Map<TestConfigOption, Object> options = validateConfigOptions(settings);
     TitanManagement gconf = null;
     ModifiableConfiguration lconf =
         new ModifiableConfiguration(
             GraphDatabaseConfiguration.ROOT_NS, config, BasicConfiguration.Restriction.LOCAL);
     for (Map.Entry<TestConfigOption, Object> option : options.entrySet()) {
       if (option.getKey().option.isLocal()) {
         lconf.set(option.getKey().option, option.getValue(), option.getKey().umbrella);
       } else {
         if (gconf == null) gconf = graph.openManagement();
         gconf.set(
             ConfigElement.getPath(option.getKey().option, option.getKey().umbrella),
             option.getValue());
       }
     }
     if (gconf != null) gconf.commit();
     lconf.close();
   }
   if (null != graph && graph.isOpen()) graph.close();
   Preconditions.checkNotNull(config);
   open(config);
 }
Esempio n. 21
0
  /**
   * Contains the logic to create URITemplate XML Element from the swagger 2.0 resource.
   *
   * @param swaggerDocObject swagger document
   * @return URITemplate element.
   */
  private static List<OMElement> createURITemplateFromSwagger2(JsonObject swaggerDocObject) {

    List<OMElement> uriTemplates = new ArrayList<>();

    JsonObject paths = swaggerDocObject.get(SwaggerConstants.PATHS).getAsJsonObject();
    Set<Map.Entry<String, JsonElement>> pathSet = paths.entrySet();

    for (Map.Entry path : pathSet) {
      JsonObject urlPattern = ((JsonElement) path.getValue()).getAsJsonObject();
      String pathText = path.getKey().toString();
      Set<Map.Entry<String, JsonElement>> operationSet = urlPattern.entrySet();

      for (Map.Entry operationEntry : operationSet) {
        OMElement uriTemplateElement = factory.createOMElement(URI_TEMPLATE, namespace);
        OMElement urlPatternElement = factory.createOMElement(URL_PATTERN, namespace);
        OMElement httpVerbElement = factory.createOMElement(HTTP_VERB, namespace);
        OMElement authTypeElement = factory.createOMElement(AUTH_TYPE, namespace);

        urlPatternElement.setText(pathText);
        httpVerbElement.setText(operationEntry.getKey().toString());

        uriTemplateElement.addChild(urlPatternElement);
        uriTemplateElement.addChild(httpVerbElement);
        uriTemplateElement.addChild(authTypeElement);
        uriTemplates.add(uriTemplateElement);
      }
    }
    return uriTemplates;
  }
Esempio n. 22
0
  private List<Expression> translate(List<Statement> list, List<RexLocalRef> rexList) {
    // First pass. Count how many times each sub-expression is used.
    this.list = null;
    for (RexNode rexExpr : rexList) {
      translate(rexExpr);
    }

    // Mark expressions as inline if they are not used more than once.
    for (Map.Entry<RexNode, Slot> entry : map.entrySet()) {
      if (entry.getValue().count < 2 || entry.getKey() instanceof RexLiteral) {
        inlineRexSet.add(entry.getKey());
      }
    }

    // Second pass. When translating each expression, if it is used more
    // than once, the first time it is encountered, add a declaration to the
    // list and set its usage count to 0.
    this.list = list;
    this.map.clear();
    List<Expression> translateds = new ArrayList<Expression>();
    for (RexNode rexExpr : rexList) {
      translateds.add(translate(rexExpr));
    }
    return translateds;
  }
Esempio n. 23
0
 /** 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);
 }
Esempio n. 24
0
  public String GetBizSign(HashMap<String, String> bizObj) throws SDKRuntimeException {
    HashMap<String, String> bizParameters = new HashMap<String, String>();

    List<Map.Entry<String, String>> infoIds =
        new ArrayList<Map.Entry<String, String>>(bizObj.entrySet());

    Collections.sort(
        infoIds,
        new Comparator<Map.Entry<String, String>>() {
          public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
            return (o1.getKey()).toString().compareTo(o2.getKey());
          }
        });

    for (int i = 0; i < infoIds.size(); i++) {
      Map.Entry<String, String> item = infoIds.get(i);
      if (item.getKey() != "") {
        bizParameters.put(item.getKey().toLowerCase(), item.getValue());
      }
    }

    if (AppKey == "") {
      throw new SDKRuntimeException("APPKEYΪ�գ�");
    }
    bizParameters.put("appkey", AppKey);
    String bizString = CommonUtil.FormatBizQueryParaMap(bizParameters, false);
    // System.out.println(bizString);

    return SHA1Util.Sha1(bizString);
  }
Esempio n. 25
0
 /**
  * Prints a usage message to the given stream.
  *
  * @param out The output stream to write to.
  */
 public void printUsage(OutputStream out) {
   Formatter formatter = new Formatter(out);
   Set<CommandLineOption> orderedOptions = new TreeSet<CommandLineOption>(new OptionComparator());
   orderedOptions.addAll(optionsByString.values());
   Map<String, String> lines = new LinkedHashMap<String, String>();
   for (CommandLineOption option : orderedOptions) {
     Set<String> orderedOptionStrings = new TreeSet<String>(new OptionStringComparator());
     orderedOptionStrings.addAll(option.getOptions());
     List<String> prefixedStrings = new ArrayList<String>();
     for (String optionString : orderedOptionStrings) {
       if (optionString.length() == 1) {
         prefixedStrings.add("-" + optionString);
       } else {
         prefixedStrings.add("--" + optionString);
       }
     }
     lines.put(GUtil.join(prefixedStrings, ", "), GUtil.elvis(option.getDescription(), ""));
   }
   int max = 0;
   for (String optionStr : lines.keySet()) {
     max = Math.max(max, optionStr.length());
   }
   for (Map.Entry<String, String> entry : lines.entrySet()) {
     if (entry.getValue().length() == 0) {
       formatter.format("%s%n", entry.getKey());
     } else {
       formatter.format("%-" + max + "s  %s%n", entry.getKey(), entry.getValue());
     }
   }
   formatter.flush();
 }
Esempio n. 26
0
    public void prepare(String query, InetAddress toExclude) throws InterruptedException {
      for (Map.Entry<Host, HostConnectionPool> entry : pools.entrySet()) {
        if (entry.getKey().getAddress().equals(toExclude)) continue;

        // Let's not wait too long if we can't get a connection. Things
        // will fix themselves once the user tries a query anyway.
        Connection c = null;
        try {
          c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS);
          c.write(new PrepareMessage(query)).get();
        } catch (ConnectionException e) {
          // Again, not being able to prepare the query right now is no big deal, so just ignore
        } catch (BusyConnectionException e) {
          // Same as above
        } catch (TimeoutException e) {
          // Same as above
        } catch (ExecutionException e) {
          // We shouldn't really get exception while preparing a
          // query, so log this (but ignore otherwise as it's not a big deal)
          logger.error(
              String.format(
                  "Unexpected error while preparing query (%s) on %s", query, entry.getKey()),
              e);
        } finally {
          if (c != null) entry.getValue().returnConnection(c);
        }
      }
    }
  @Override
  public final void runBare() throws Throwable {
    // Patch a bug with maven that does not pass properly the system property
    // with an empty value
    if ("org.hsqldb.jdbcDriver".equals(System.getProperty("gatein.test.datasource.driver"))) {
      System.setProperty("gatein.test.datasource.password", "");
    }

    //
    log.info("Running unit test:" + getName());
    for (Map.Entry<?, ?> entry : System.getProperties().entrySet()) {
      if (entry.getKey() instanceof String) {
        String key = (String) entry.getKey();
        log.debug(key + "=" + entry.getValue());
      }
    }

    //
    beforeRunBare();

    //
    try {
      super.runBare();
      log.info("Unit test " + getName() + " completed");
    } catch (Throwable throwable) {
      log.error("Unit test " + getName() + " did not complete", throwable);

      //
      throw throwable;
    } finally {
      afterRunBare();
    }
  }
Esempio n. 28
0
 public int uncommittedChanges() {
   Set<Map.Entry<String, Storeable>> indexedSet = tableIndexedData.entrySet();
   Set<Map.Entry<String, Storeable>> diskSet = tableOnDisk.entrySet();
   int count = 0;
   Iterator<Map.Entry<String, Storeable>> iter1 = indexedSet.iterator();
   Iterator<Map.Entry<String, Storeable>> iter2 = diskSet.iterator();
   while (iter1.hasNext()) {
     Map.Entry<String, Storeable> next = iter1.next();
     Storeable entryOnDisk = tableOnDisk.get(next.getKey());
     if (entryOnDisk == null) {
       // записи на диске нет, то она изменение
       ++count;
     } else if (!entryOnDisk.equals(next.getValue())) {
       // запись на диске есть, но она другая, тоже изменение
       ++count;
     }
   }
   while (iter2.hasNext()) {
     Map.Entry<String, Storeable> next = iter2.next();
     Storeable entryIndexed = tableIndexedData.get(next.getKey());
     if (entryIndexed == null) {
       // на диске есть, индексированной нет, изменение
       ++count;
     }
   }
   return count;
 }
Esempio n. 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);
  }
  private void exportParameters() {
    synchronized (exported_parameters) {
      if (!exported_parameters_dirty) {

        return;
      }

      exported_parameters_dirty = false;

      try {
        TreeMap<String, String> tm = new TreeMap<String, String>();

        Set<String> exported_keys = new HashSet<String>();

        for (String[] entry : exported_parameters.values()) {

          String key = entry[0];
          String value = entry[1];

          exported_keys.add(key);

          if (value != null) {

            tm.put(key, value);
          }
        }

        for (Map.Entry<String, String> entry : imported_parameters.entrySet()) {

          String key = entry.getKey();

          if (!exported_keys.contains(key)) {

            tm.put(key, entry.getValue());
          }
        }

        File parent_dir = new File(SystemProperties.getUserPath());

        File props = new File(parent_dir, "exported_params.properties");

        PrintWriter pw =
            new PrintWriter(new OutputStreamWriter(new FileOutputStream(props), "UTF-8"));

        try {
          for (Map.Entry<String, String> entry : tm.entrySet()) {

            pw.println(entry.getKey() + "=" + entry.getValue());
          }

        } finally {

          pw.close();
        }
      } catch (Throwable e) {

        e.printStackTrace();
      }
    }
  }