Exemple #1
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);
       }
   }
 }
Exemple #2
0
 private void buildXQueryStaticContext(XQueryContext context, boolean importModules)
     throws XPathException {
   context.declareNamespaces(namespaceBindings.getCombinedMap());
   for (Map.Entry<String, Document> entry : moduleMap.entrySet()) {
     context.importModule(entry.getKey(), null, "xmldb:exist:///db" + entry.getValue().path());
   }
 }
Exemple #3
0
  // Build the MDP and value function, as well as the Q-functions for
  // executing the greedy policy.
  public MDPSim(String prob_file, String vfun_file) {
    _mdp = new MDP(prob_file, DD.TYPE_ADD);
    _bUseBasis = vfun_file.equalsIgnoreCase("basis");
    if (_bUseBasis) {
      _mdp._valueDD = null;
    } else {
      _mdp._valueDD =
          _mdp._context.buildDDFromUnorderedTree(
              MDPConverter.ADDFileToTree(vfun_file), _mdp._tmVar2ID);

      _qfuns = new HashMap();
      Iterator i = _mdp._hmName2Action.entrySet().iterator();
      while (i.hasNext()) {

        Map.Entry me = (Map.Entry) i.next();
        Action a = (Action) me.getValue();

        //////////////////////////////////////////////////////////////
        // Regress the current value function through each action
        //////////////////////////////////////////////////////////////
        Object qfun =
            _mdp.regress(_mdp._context.remapGIDsInt(_mdp._valueDD, _mdp._hmPrimeRemap), a);
        System.out.println("Calculating Q-function for action: " + a._sName);
        // System.out.println(_mdp._context.printNode(qfun) + "\n");

        _qfuns.put(a._sName, qfun);
      }
    }
    System.out.println(_mdp);
  }
  /**
   * Prints the given map with nice line breaks.
   *
   * @param out the stream to print to
   * @param key the key that maps to the map in some other map
   * @param map the map to print
   */
  public static synchronized void debugPrint(PrintStream out, Object key, Map map) {
    debugPrintIndent(out);
    out.println(key + " = ");

    debugPrintIndent(out);
    out.println("{");
    ++debugIndent;

    for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iter.next();
      String childKey = (String) entry.getKey();
      Object childValue = entry.getValue();
      if (childValue instanceof Map) {
        verbosePrint(out, childKey, (Map) childValue);
      } else {
        debugPrintIndent(out);

        String typeName = (childValue != null) ? childValue.getClass().getName() : null;

        out.println(childKey + " = " + childValue + " class: " + typeName);
      }
    }
    --debugIndent;
    debugPrintIndent(out);
    out.println("}");
  }
Exemple #5
0
 private static String getConfigString(Configuration config) {
   String output = "";
   Iterator<Map.Entry<String, String>> iterConfig = config.iterator();
   while (iterConfig.hasNext()) {
     Map.Entry<String, String> curEntry = iterConfig.next();
     output = output + "Key: \t" + curEntry.getKey() + "\nValue: \t" + curEntry.getValue() + "\n";
   }
   return output;
 }
 public void putAll(Map m) {
   Iterator iter = m.entrySet().iterator();
   while (iter.hasNext()) {
     Map.Entry entry = (Map.Entry) iter.next();
     Object key = entry.getKey();
     Object value = entry.getValue();
     validate(key, value);
   }
   map.putAll(m);
 }
  /**
   * Adds the channel-bundles of this <tt>Conference</tt> as
   * <tt>ColibriConferenceIQ.ChannelBundle</tt> instances in <tt>iq</tt>.
   *
   * @param iq the <tt>ColibriConferenceIQ</tt> in which to describe.
   */
  void describeChannelBundles(ColibriConferenceIQ iq) {
    synchronized (transportManagers) {
      for (Map.Entry<String, IceUdpTransportManager> entry : transportManagers.entrySet()) {
        ColibriConferenceIQ.ChannelBundle responseBundleIQ =
            new ColibriConferenceIQ.ChannelBundle(entry.getKey());

        entry.getValue().describe(responseBundleIQ);
        iq.addChannelBundle(responseBundleIQ);
      }
    }
  }
 /**
  * Gets a new Properties object initialised with the values from a Map. A null input will return
  * an empty properties object.
  *
  * @param map the map to convert to a Properties object
  * @return the properties object
  */
 public static Properties toProperties(Map map) {
   Properties answer = new Properties();
   if (map != null) {
     for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
       Map.Entry entry = (Map.Entry) iter.next();
       Object key = entry.getKey();
       Object value = entry.getValue();
       answer.put(key, value);
     }
   }
   return answer;
 }
Exemple #9
0
 /**
  * Return the value associated with the first pattern that the string matches, or the specified
  * default value if none, considering only patterns whose associated value is less than or equal
  * to maxPri.
  */
 public int getMatch(String str, int dfault, int maxPri) {
   Perl5Matcher matcher = RegexpUtil.getMatcher();
   for (Map.Entry<Pattern, Integer> ent : patternMap.entrySet()) {
     if (ent.getValue() <= maxPri) {
       Pattern pat = ent.getKey();
       if (matcher.contains(str, pat)) {
         log.debug2("getMatch(" + str + "): " + ent.getValue());
         return ent.getValue();
       }
     }
   }
   log.debug2("getMatch(" + str + "): default: " + dfault);
   return dfault;
 }
Exemple #10
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);
 }
Exemple #11
0
 /**
  * Clone this query service, optionally overriding the clone's namespace and variable bindings. If
  * the namespace bindings override or variable bindings override is specified, then that object is
  * cloned and used for its respective purpose. If an override is not specified, the bindings are
  * cloned from the original query service.
  *
  * @param nsBindingsOverride the namespace bindings to clone, or <code>null</code> to clone from
  *     the original
  * @param varBindingsOverride the variable bindings to clone, or <code>null</code> to clone from
  *     the original
  * @return a clone of this query service with bindings optionally overridden
  */
 public QueryService clone(NamespaceMap nsBindingsOverride, Map<QName, ?> varBindingsOverride) {
   try {
     QueryService that = (QueryService) super.clone();
     that.namespaceBindings =
         nsBindingsOverride != null ? nsBindingsOverride.clone() : that.namespaceBindings.clone();
     if (varBindingsOverride == null) {
       that.bindings = new HashMap<QName, Object>(that.bindings);
     } else {
       that.bindings = new HashMap<QName, Object>();
       for (Map.Entry<QName, ?> entry : varBindingsOverride.entrySet()) {
         that.let(entry.getKey(), entry.getValue());
       }
     }
     that.moduleMap = new TreeMap<String, Document>(moduleMap);
     return that;
   } catch (CloneNotSupportedException e) {
     throw new RuntimeException("unexpected exception", e);
   }
 }
 public PredicatedMap(Map map, Predicate keyPred, Predicate valuePred) {
   super(map);
   if (map == null) {
     throw new IllegalArgumentException("Map must not be null");
   }
   if (keyPred == null) {
     throw new IllegalArgumentException("Key Predicate must not be null");
   }
   if (valuePred == null) {
     throw new IllegalArgumentException("Value Predicate must not be null");
   }
   this.keyPredicate = keyPred;
   this.valuePredicate = valuePred;
   Iterator iter = map.entrySet().iterator();
   while (iter.hasNext()) {
     Map.Entry entry = (Map.Entry) iter.next();
     Object key = entry.getKey();
     Object value = entry.getValue();
     validate(key, value);
   }
 }
  public int numberOfSubsets(int goodValue, int[] d) {
    HashMap<Integer, Integer> map = new HashMap<>(); // prod, sets
    for (int i = 0; i < d.length; i++) {
      HashMap<Integer, Integer> nmap = new HashMap<>();
      nmap.put(d[i], 1);
      for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
        // not use
        Integer setcount = nmap.get(entry.getKey());
        if (setcount == null) setcount = 0;
        setcount = (entry.getValue() + setcount) % MOD;

        nmap.put(entry.getKey(), setcount);

        // use
        int nprod = entry.getKey();
        if (nprod > goodValue / d[i]) continue;
        nprod *= d[i];
        if (goodValue % nprod != 0) continue;

        setcount = nmap.get(nprod);
        if (setcount == null) setcount = 0;
        setcount = (entry.getValue() + setcount) % MOD;
        nmap.put(nprod, setcount);
      }
      map = nmap;
    }
    return map.get(goodValue) == null ? 0 : map.get(goodValue);
  }
Exemple #14
0
 public String toString() {
   StringBuilder sb = new StringBuilder();
   sb.append("[pm: ");
   if (patternMap.isEmpty()) {
     sb.append("EMPTY");
   } else {
     for (Iterator<Map.Entry<Pattern, Integer>> iter = patternMap.entrySet().iterator();
         iter.hasNext(); ) {
       Map.Entry<Pattern, Integer> ent = iter.next();
       sb.append("[");
       sb.append(ent.getKey().getPattern());
       sb.append(": ");
       sb.append(ent.getValue());
       sb.append("]");
       if (iter.hasNext()) {
         sb.append(", ");
       }
     }
   }
   sb.append("]");
   return sb.toString();
 }
  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    Scanner input = new Scanner(System.in);
    int numberOfTestCases = input.nextInt();
    ArrayList<Integer> order = new ArrayList<Integer>(numberOfTestCases);
    int previousKey = -1;
    int previousValue = 0;
    int cycleNumber = 0;

    Map<Integer, Integer> testCases = new TreeMap<Integer, Integer>();

    for (int i = 0; i < numberOfTestCases; i++) {
      int numberOfCycles = input.nextInt();
      testCases.put(numberOfCycles, 1);
      order.add(numberOfCycles);
    }

    for (Map.Entry<Integer, Integer> entry : testCases.entrySet()) {
      int numberOfCycles;
      int initialHeight;

      if (previousKey == -1) {
        numberOfCycles = entry.getKey();
        initialHeight = entry.getValue();
      } else {
        numberOfCycles = entry.getKey() - previousKey;
        initialHeight = previousValue;
      }

      for (int i = 0; i < numberOfCycles; i++) {
        if (cycleNumber % 2 == 0) {
          initialHeight *= 2;
        } else {
          initialHeight += 1;
        }
        cycleNumber++;
      }

      entry.setValue(initialHeight);
      previousKey = entry.getKey();
      previousValue = initialHeight;
    }

    for (Integer element : order) {
      System.out.println(testCases.get(element));
    }

    long elapsed = System.currentTimeMillis() - start;
    System.out.println("time: " + elapsed);
  }
  @Override
  public void handle(
      String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    if (!path.equals(request.getRequestURI())) {
      return;
    }

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("text/plain");

    PrintWriter out = null;
    try {
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");

      out = response.getWriter();

      Map<String, Endpoint> endpointMap = tracker.getEndpointMap();
      Map<String, Long> expirationMap = tracker.getExpirationMap();

      out.println("Active sessions:");
      out.println();

      for (Map.Entry<String, Endpoint> ep : endpointMap.entrySet()) {
        String key = ep.getKey();
        out.print(ep.getKey());
        out.print(" => ");
        out.print(ep.getValue());

        Long expiration = expirationMap.get(key);
        if (expiration == null) {
          out.println(" (expiration unknown)");
        } else {
          out.print(" (expires ");
          out.print(df.format(new Date(expiration)));
          out.println(")");
        }
      }

      out.println();
      out.println("Events:");
      out.println();

      for (EndpointEvent event : tracker.getEvents()) {
        out.print(df.format(new Date(event.getTimestamp())));
        out.print(" ");
        out.print(event.getStatus().name());
        out.print(" ");
        out.print(event.getConnectionId());
        out.print(" ");
        out.print(event.getDetails());
        out.println();
      }
    } finally {
      try {
        if (out != null) {
          out.close();
        }
      } catch (Throwable ignored) {
      }
    }
    baseRequest.setHandled(true);
  }
 public Object getValue() {
   return entry.getValue();
 }
 public Object setValue(Object o) {
   if (!predicate.evaluate(o)) {
     throw new IllegalArgumentException("Cannot set value - Predicate rejected it");
   }
   return entry.setValue(o);
 }
 public Object getKey() {
   return entry.getKey();
 }
 public String toString() {
   return entry.toString();
 }
 public int hashCode() {
   return entry.hashCode();
 }
 public boolean equals(Object o) {
   return entry.equals(o);
 }
  public CommandData parseCommandData(ArtifactData artifact) throws Exception {
    File source = new File(artifact.file);
    if (!source.isFile()) throw new FileNotFoundException();

    CommandData data = new CommandData();
    data.sha = artifact.sha;
    data.jpmRepoDir = repoDir.getCanonicalPath();
    JarFile jar = new JarFile(source);
    try {
      reporter.trace("Parsing %s", source);
      Manifest m = jar.getManifest();
      Attributes main = m.getMainAttributes();
      data.name = data.bsn = main.getValue("Bundle-SymbolicName");
      String version = main.getValue("Bundle-Version");
      if (version == null) data.version = Version.LOWEST;
      else data.version = new Version(version);

      data.main = main.getValue("Main-Class");
      data.description = main.getValue("Bundle-Description");
      data.title = main.getValue("JPM-Name");

      reporter.trace("name " + data.name + " " + data.main + " " + data.title);
      DependencyCollector path = new DependencyCollector(this);
      path.add(artifact);
      DependencyCollector bundles = new DependencyCollector(this);
      if (main.getValue("JPM-Classpath") != null) {
        Parameters requires = OSGiHeader.parseHeader(main.getValue("JPM-Classpath"));

        for (Map.Entry<String, Attrs> e : requires.entrySet()) {
          path.add(e.getKey(), e.getValue().get("name")); // coordinate
        }
      } else if (!artifact.local) { // No JPM-Classpath, falling back to
        // server's revision
        // Iterable<RevisionRef> closure =
        // library.getClosure(artifact.sha,
        // false);
        // System.out.println("getting closure " + artifact.url + " " +
        // Strings.join("\n",closure));

        // if (closure != null) {
        // for (RevisionRef ref : closure) {
        // path.add(Hex.toHexString(ref.revision));
        // }
        // }
      }

      if (main.getValue("JPM-Runbundles") != null) {
        Parameters jpmrunbundles = OSGiHeader.parseHeader(main.getValue("JPM-Runbundles"));

        for (Map.Entry<String, Attrs> e : jpmrunbundles.entrySet()) {
          bundles.add(e.getKey(), e.getValue().get("name"));
        }
      }

      reporter.trace("collect digests runpath");
      data.dependencies.addAll(path.getDigests());
      reporter.trace("collect digests bundles");
      data.runbundles.addAll(bundles.getDigests());

      Parameters command = OSGiHeader.parseHeader(main.getValue("JPM-Command"));
      if (command.size() > 1) reporter.error("Only one command can be specified");

      for (Map.Entry<String, Attrs> e : command.entrySet()) {
        data.name = e.getKey();

        Attrs attrs = e.getValue();

        if (attrs.containsKey("jvmargs")) data.jvmArgs = attrs.get("jvmargs");

        if (attrs.containsKey("title")) data.title = attrs.get("title");

        if (data.title != null) data.title = data.name;
      }
      return data;
    } finally {
      jar.close();
    }
  }