예제 #1
0
  public static void main(String[] args) throws Exception {
    int size = Util.getPropertyInt("size", 100);
    double min = Util.getPropertyDouble("min", 0.01);
    double max = Util.getPropertyDouble("max", 0.9);
    Font font = new Font("serif", Font.PLAIN, size);
    String fpath = Util.getProperty("font", null);
    if (fpath != null) {
      font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(fpath));
    }

    for (char c = Character.MIN_VALUE + 1; c < Character.MAX_VALUE; ++c) {
      int type = Character.getType(c);
      if (type != Character.CONTROL
          && type != Character.FORMAT
          && type != Character.PRIVATE_USE
          && type != Character.SURROGATE
          && type != Character.UNASSIGNED
          && !Character.isMirrored(c)
          && !Character.isSpaceChar(c)) {
        String s = "" + c;
        if (Normalizer.normalize(s, NFKC).contains("\u0308")) continue; // TODO: adhoc
        UnigramMetrics m = new UnigramMetrics(s, size, false, true, font);
        if (min < m.getBlackness() && m.getBlackness() < max) {
          System.out.println("" + c + " " + (int) c);
        }
      }
    }
  }
예제 #2
0
  /**
   * Adds the string representation of an object:
   *
   * <ul>
   *   <li>objects of type {@link Throwable} are converted to a string representation via {@link
   *       Util#message}.
   *   <li>objects of type {@link Class} are converted via {@link Util#className(Class)}.
   *   <li>{@code null} references are replaced by the string {@code "null"}.
   *   <li>byte arrays are directly inserted as tokens.
   *   <li>for all other typed, {@link Object#toString} is called.
   * </ul>
   *
   * The specified string may contain {@code "%"} characters as place holders. All place holders
   * will be replaced by the specified extensions. If a digit is specified after the place holder
   * character, it will be interpreted as insertion position.
   *
   * @param object string to be extended
   * @param ext optional extensions
   * @return self reference
   */
  public TokenBuilder addExt(final Object object, final Object... ext) {
    final byte[] t;
    if (object instanceof byte[]) {
      t = (byte[]) object;
    } else {
      final String s;
      if (object == null) {
        s = "null";
      } else if (object instanceof Throwable) {
        s = Util.message((Throwable) object);
      } else if (object instanceof Class<?>) {
        s = Util.className((Class<?>) object);
      } else {
        s = object.toString();
      }
      t = token(s);
    }

    for (int i = 0, e = 0; i < t.length; ++i) {
      if (t[i] != '%' || e == ext.length) {
        addByte(t[i]);
      } else {
        final byte c = i + 1 < t.length ? t[i + 1] : 0;
        final boolean d = c >= '1' && c <= '9';
        if (d) ++i;
        final int n = d ? c - '1' : e++;
        final Object o = n < ext.length ? ext[n] : null;
        addExt(o);
      }
    }
    return this;
  }
예제 #3
0
 // -----------------------------------------------------------
 // for "SrvRqst"
 // find the matched URLs with (type, scope, predicate, ltag)
 // return: error code (short)
 //         number of matched URLs (short)
 //         URL blocks (decided bt previous #URL)
 // -----------------------------------------------------------
 public synchronized byte[] getMatchedURL(String type, String scope, String pred, String ltag) {
   byte[] buf = null;
   int ecode = Const.OK;
   if (!Util.shareString(daf.getScope(), scope, ",")) {
     ecode = Const.SCOPE_NOT_SUPPORTED;
   }
   b.reset();
   try {
     int count = 0;
     d.writeShort(ecode); // error code
     d.writeShort(count); // URL count, place holder
     if (ecode == Const.OK) { // no error, find matched URLs
       Iterator values = table.values().iterator();
       while (values.hasNext()) {
         Entry e = (Entry) values.next();
         if (e.match(type, scope, pred, ltag)) {
           count++;
           d.writeByte(0);
           d.writeShort(e.getLifetime());
           d.writeShort(e.getURL().length());
           d.writeBytes(e.getURL());
           d.writeByte(0);
         }
       }
     }
     buf = b.toByteArray();
     if (count > 0) Util.writeInt(buf, 2, count, 2); // update count
   } catch (Exception e) {
     if (ServiceLocationManager.displayMSLPTrace) e.printStackTrace();
   }
   return buf;
 }
예제 #4
0
  static void marshal(Object obj) throws Exception {
    byte[] buf = Util.objectToByteBuffer(obj);
    assert buf != null;
    assert buf.length > 0;
    Object obj2 = Util.objectFromByteBuffer(buf);
    System.out.println(
        "obj="
            + obj
            + ", obj2="
            + obj2
            + " (type="
            + obj.getClass().getName()
            + ", length="
            + buf.length
            + " bytes)");
    Assert.assertEquals(obj, obj2);

    if (obj instanceof Integer) { // test compressed ints and longs
      buf = new byte[10];
      Bits.writeIntCompressed((int) obj, buf, 0);
      obj2 = Bits.readIntCompressed(buf, 0);
      assert obj.equals(obj2);
    }
    if (obj instanceof Long) { // test compressed ints and longs
      buf = new byte[10];
      Bits.writeLongCompressed((long) obj, buf, 0);
      obj2 = Bits.readLongCompressed(buf, 0);
      assert obj.equals(obj2);
    }
  }
예제 #5
0
  public static void testDetermineMergeParticipantsAndMergeCoords() {
    Address a = Util.createRandomAddress(),
        b = Util.createRandomAddress(),
        c = Util.createRandomAddress();
    org.jgroups.util.UUID.add(a, "A");
    org.jgroups.util.UUID.add(b, "B");
    org.jgroups.util.UUID.add(c, "C");

    View v1 = View.create(b, 1, b, a, c);
    View v2 = View.create(b, 2, b, c);
    View v3 = View.create(b, 2, b, c);

    Map<Address, View> map = new HashMap<>();
    map.put(a, v1);
    map.put(b, v2);
    map.put(c, v3);
    StringBuilder sb = new StringBuilder("map:\n");
    for (Map.Entry<Address, View> entry : map.entrySet())
      sb.append(entry.getKey() + ": " + entry.getValue() + "\n");
    System.out.println(sb);

    Collection<Address> merge_participants = Util.determineMergeParticipants(map);
    System.out.println("merge_participants = " + merge_participants);
    assert merge_participants.size() == 2;
    assert merge_participants.contains(a) && merge_participants.contains(b);

    Collection<Address> merge_coords = Util.determineMergeCoords(map);
    System.out.println("merge_coords = " + merge_coords);
    assert merge_coords.size() == 1;
    assert merge_coords.contains(b);
  }
예제 #6
0
    /**
     * @param views Guaranteed to be non-null and to have >= 2 members, or else this thread would
     *     not be started
     */
    public synchronized void start(Map<Address, View> views) {
      if (thread == null || thread.isAlive()) {
        this.coords.clear();

        // now remove all members which don't have us in their view, so RPCs won't block (e.g.
        // FLUSH)
        // https://jira.jboss.org/browse/JGRP-1061
        sanitizeViews(views);

        // Add all different coordinators of the views into the hashmap and sets their members:
        Collection<Address> coordinators = Util.determineMergeCoords(views);
        for (Address coord : coordinators) {
          View view = views.get(coord);
          if (view != null) this.coords.put(coord, new ArrayList<Address>(view.getMembers()));
        }

        // For the merge participants which are not coordinator, we simply add them, and the
        // associated
        // membership list consists only of themselves
        Collection<Address> merge_participants = Util.determineMergeParticipants(views);
        merge_participants.removeAll(coordinators);
        for (Address merge_participant : merge_participants) {
          Collection<Address> tmp = new ArrayList<Address>();
          tmp.add(merge_participant);
          coords.putIfAbsent(merge_participant, tmp);
        }

        thread = gms.getThreadFactory().newThread(this, "MergeTask");
        thread.setDaemon(true);
        thread.start();
      }
    }
예제 #7
0
 public static void testMessageToByteBuffer() throws Exception {
   _testMessage(new Message());
   _testMessage(new Message(null, null, "hello world"));
   _testMessage(new Message(null, Util.createRandomAddress(), null));
   _testMessage(new Message(null, Util.createRandomAddress(), null));
   _testMessage(new Message(null, Util.createRandomAddress(), "bela"));
 }
  private int send(FileDescriptor fd, ByteBuffer src, SocketAddress target) throws IOException {
    if (src instanceof DirectBuffer) return sendFromNativeBuffer(fd, src, target);

    // Substitute a native buffer
    int pos = src.position();
    int lim = src.limit();
    assert (pos <= lim);
    int rem = (pos <= lim ? lim - pos : 0);

    ByteBuffer bb = Util.getTemporaryDirectBuffer(rem);
    try {
      bb.put(src);
      bb.flip();
      // Do not update src until we see how many bytes were written
      src.position(pos);

      int n = sendFromNativeBuffer(fd, bb, target);
      if (n > 0) {
        // now update src
        src.position(pos + n);
      }
      return n;
    } finally {
      Util.releaseTemporaryDirectBuffer(bb);
    }
  }
 /**
  * Create a searcher manually, suppling a dependency tree, an optional classifier for when to
  * split clauses, and a featurizer for that classifier. You almost certainly want to use {@link
  * ClauseSplitter#load(String)} instead of this constructor.
  *
  * @param tree The dependency tree to search over.
  * @param assumedTruth The assumed truth of the tree (relevant for natural logic inference). If in
  *     doubt, pass in true.
  * @param isClauseClassifier The classifier for whether a given dependency arc should be a new
  *     clause. If this is not given, all arcs are treated as clause separators.
  * @param featurizer The featurizer for the classifier. If no featurizer is given, one should be
  *     given in {@link ClauseSplitterSearchProblem#search(java.util.function.Predicate,
  *     Classifier, Map, java.util.function.Function, int)}, or else the classifier will be
  *     useless.
  * @see ClauseSplitter#load(String)
  */
 protected ClauseSplitterSearchProblem(
     SemanticGraph tree,
     boolean assumedTruth,
     Optional<Classifier<ClauseSplitter.ClauseClassifierLabel, String>> isClauseClassifier,
     Optional<
             Function<
                 Triple<
                     ClauseSplitterSearchProblem.State,
                     ClauseSplitterSearchProblem.Action,
                     ClauseSplitterSearchProblem.State>,
                 Counter<String>>>
         featurizer) {
   this.tree = new SemanticGraph(tree);
   this.assumedTruth = assumedTruth;
   this.isClauseClassifier = isClauseClassifier;
   this.featurizer = featurizer;
   // Index edges
   this.tree.edgeIterable().forEach(edgeToIndex::addToIndex);
   // Get length
   List<IndexedWord> sortedVertices = tree.vertexListSorted();
   sentenceLength = sortedVertices.get(sortedVertices.size() - 1).index();
   // Register extra edges
   for (IndexedWord vertex : sortedVertices) {
     extraEdgesByGovernor.put(vertex, new ArrayList<>());
     extraEdgesByDependent.put(vertex, new ArrayList<>());
   }
   List<SemanticGraphEdge> extraEdges = Util.cleanTree(this.tree);
   assert Util.isTree(this.tree);
   for (SemanticGraphEdge edge : extraEdges) {
     extraEdgesByGovernor.get(edge.getGovernor()).add(edge);
     extraEdgesByDependent.get(edge.getDependent()).add(edge);
   }
 }
예제 #10
0
 /**
  * Creates a JavaRelImplementor
  *
  * @param rexBuilder Builder for {@link RexNode}s
  * @param implementorTable Table of implementations of operators. Must not be null
  */
 public JavaRelImplementor(RexBuilder rexBuilder, OJRexImplementorTable implementorTable) {
   super(rexBuilder);
   Util.pre(rexBuilder != null, "rexBuilder != null");
   Util.pre(implementorTable != null, "implementorTable != null");
   this.implementorTable = implementorTable;
   nextVariableId = 0;
 }
예제 #11
0
  /**
   * Message contains MethodCall. Execute it against *this* object and return result. Use
   * MethodCall.invoke() to do this. Return result.
   */
  public Object handle(Message req) throws Exception {
    if (server_obj == null) {
      log.error(Util.getMessage("NoMethodHandlerIsRegisteredDiscardingRequest"));
      return null;
    }

    if (req == null || req.getLength() == 0) {
      log.error(Util.getMessage("MessageOrMessageBufferIsNull"));
      return null;
    }

    Object body =
        req_marshaller != null
            ? req_marshaller.objectFromBuffer(req.getRawBuffer(), req.getOffset(), req.getLength())
            : req.getObject();

    if (!(body instanceof MethodCall))
      throw new IllegalArgumentException("message does not contain a MethodCall object");

    MethodCall method_call = (MethodCall) body;

    if (log.isTraceEnabled()) log.trace("[sender=%s], method_call: %s", req.getSrc(), method_call);

    if (method_call.getMode() == MethodCall.ID) {
      if (method_lookup == null)
        throw new Exception(
            String.format(
                "MethodCall uses ID=%d, but method_lookup has not been set", method_call.getId()));
      Method m = method_lookup.findMethod(method_call.getId());
      if (m == null) throw new Exception("no method found for " + method_call.getId());
      method_call.setMethod(m);
    }

    return method_call.invoke(server_obj);
  }
예제 #12
0
 @Override
 public ParseTree visitChildInternal(RelNode child, int ordinal) {
   final Convention convention = child.getConvention();
   if (!(child instanceof JavaRel)) {
     throw Util.newInternal(
         "Relational expression '"
             + child
             + "' has '"
             + convention
             + "' calling convention, so must implement interface "
             + JavaRel.class);
   }
   JavaRel javaRel = (JavaRel) child;
   final ParseTree p = javaRel.implement(this);
   if ((convention == CallingConvention.JAVA) && (p != null)) {
     throw Util.newInternal(
         "Relational expression '"
             + child
             + "' returned '"
             + p
             + " on implement, but should have "
             + "returned null, because it has JAVA calling-convention. "
             + "(Note that similar calling-conventions, such as "
             + "Iterator, must return a value.)");
   }
   return p;
 }
예제 #13
0
  @Override
  public final void service(final HttpServletRequest req, final HttpServletResponse res)
      throws IOException {

    final HTTPContext http = new HTTPContext(req, res, this);
    final boolean restxq = this instanceof RestXqServlet;
    try {
      run(http);
      http.log("", SC_OK);
    } catch (final HTTPException ex) {
      http.status(ex.getStatus(), Util.message(ex), restxq);
    } catch (final LoginException ex) {
      http.status(SC_UNAUTHORIZED, Util.message(ex), restxq);
    } catch (final IOException ex) {
      http.status(SC_BAD_REQUEST, Util.message(ex), restxq);
    } catch (final QueryException ex) {
      http.status(SC_BAD_REQUEST, Util.message(ex), restxq);
    } catch (final Exception ex) {
      final String msg = Util.bug(ex);
      Util.errln(msg);
      http.status(SC_INTERNAL_SERVER_ERROR, Util.info(UNEXPECTED, msg), restxq);
    } finally {
      if (Prop.debug) {
        Util.outln("_ REQUEST _________________________________" + Prop.NL + req);
        final Enumeration<String> en = req.getHeaderNames();
        while (en.hasMoreElements()) {
          final String key = en.nextElement();
          Util.outln(Text.LI + key + Text.COLS + req.getHeader(key));
        }
        Util.out("_ RESPONSE ________________________________" + Prop.NL + res);
      }
      http.close();
    }
  }
예제 #14
0
파일: BaseX.java 프로젝트: james-jw/basex
  /** Launches the console mode, which reads and executes user input. */
  private void console() {
    Util.outln(header() + NL + TRY_MORE_X);
    verbose = true;

    // create console reader
    try (final ConsoleReader cr = ConsoleReader.get()) {
      // loop until console is set to false (may happen in server mode)
      while (console) {
        // get next line
        final String in = cr.readLine(PROMPT);
        // end of input: break loop
        if (in == null) break;
        // skip empty lines
        if (in.isEmpty()) continue;

        try {
          if (!execute(new CommandParser(in, context).pwReader(cr.pwReader()))) {
            // show goodbye message if method returns false
            Util.outln(BYE[new Random().nextInt(4)]);
            break;
          }
        } catch (final IOException ex) {
          // output error messages
          Util.errln(ex);
        }
      }
    }
  }
예제 #15
0
 @Override
 public String det() {
   final String path = input.io().path();
   return path.isEmpty()
       ? Util.info(LINE_X, input.line())
       : Util.info(SCANPOS_X_X, input.io().path(), input.line());
 }
예제 #16
0
  /** Variant of {@link #trimFields(RelNode, BitSet, Set)} for {@link TableModificationRel}. */
  public TrimResult trimFields(
      TableModificationRel modifier, BitSet fieldsUsed, Set<RelDataTypeField> extraFields) {
    // Ignore what consumer wants. We always project all columns.
    Util.discard(fieldsUsed);

    final RelDataType rowType = modifier.getRowType();
    final int fieldCount = rowType.getFieldCount();
    RelNode input = modifier.getChild();

    // We want all fields from the child.
    final int inputFieldCount = input.getRowType().getFieldCount();
    BitSet inputFieldsUsed = Util.bitSetBetween(0, inputFieldCount);

    // Create input with trimmed columns.
    final Set<RelDataTypeField> inputExtraFields = Collections.emptySet();
    TrimResult trimResult = trimChild(modifier, input, inputFieldsUsed, inputExtraFields);
    RelNode newInput = trimResult.left;
    final Mapping inputMapping = trimResult.right;
    if (!inputMapping.isIdentity()) {
      // We asked for all fields. Can't believe that the child decided
      // to permute them!
      throw Util.newInternal("Expected identity mapping, got " + inputMapping);
    }

    TableModificationRel newModifier = modifier;
    if (newInput != input) {
      newModifier = modifier.copy(modifier.getTraitSet(), Collections.singletonList(newInput));
    }
    assert newModifier.getClass() == modifier.getClass();

    // Always project all fields.
    Mapping mapping = Mappings.createIdentity(fieldCount);
    return new TrimResult(newModifier, mapping);
  }
예제 #17
0
  void getBaseCompilerFlags_common(Vector defines, Vector includes, String outDir, Vector rv) {

    // advanced M$ IDE (2003) can only recognize name if it's first or
    // second attribute in the tag - go guess
    addAttr(rv, "Name", "VCCLCompilerTool");
    addAttr(rv, "AdditionalIncludeDirectories", Util.join(",", includes));
    addAttr(rv, "PreprocessorDefinitions", Util.join(";", defines).replace("\"", "&quot;"));
    addAttr(rv, "PrecompiledHeaderThrough", "incls" + Util.sep + "_precompiled.incl");
    addAttr(rv, "PrecompiledHeaderFile", outDir + Util.sep + "vm.pch");
    addAttr(rv, "AssemblerListingLocation", outDir);
    addAttr(rv, "ObjectFile", outDir + Util.sep);
    addAttr(rv, "ProgramDataBaseFileName", outDir + Util.sep + "vm.pdb");
    // Set /nologo optin
    addAttr(rv, "SuppressStartupBanner", "TRUE");
    // Surpass the default /Tc or /Tp. 0 is compileAsDefault
    addAttr(rv, "CompileAs", "0");
    // Set /W3 option. 3 is warningLevel_3
    addAttr(rv, "WarningLevel", "3");
    // Set /WX option,
    addAttr(rv, "WarnAsError", "TRUE");
    // Set /GS option
    addAttr(rv, "BufferSecurityCheck", "FALSE");
    // Set /Zi option. 3 is debugEnabled
    addAttr(rv, "DebugInformationFormat", "3");
  }
예제 #18
0
  /**
   * Given a filename, parses the seeds of the various independent streams from the file. An example
   * seedfile looks like:
   *
   * <p>
   *
   * <pre>
   * PLACES 6167 34322 540141     #to place nodes on the plane
   * CONNECT 4149 3274 811023     #to connect nodes
   * EDGE_CONN 4321 6394 564736   #used in the edge connection method in TopDownHier model
   * GROUPING 39856 9062 30034    #used when grouping routers into an AS, in BottomUpHier model
   * ASSIGNMENT 2603 24124 6350  #used in BottomUpHierModel to decide how many routers each AS gets.
   * BANDWIDTH 1073 33601 47040  #used to specify bandwidth to edges in a topology
   * </pre>
   *
   * <p>The divisions of three are to maintain compatability with the C++ version's erand48() call.
   */
  public void parse(String filename) {
    BufferedReader br = null;
    try {
      br = new BufferedReader(new FileReader(new File(filename)));
    } catch (IOException e) {
      Util.ERR("Error reading seedfile. " + e);
    }

    String line = "";
    try {
      while ((line = br.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(line);
        String seedName = st.nextToken();
        String first = st.nextToken();
        String second = st.nextToken();
        String third = st.nextToken();
        String seedString = first.trim() + second.trim() + third.trim();
        long seedValue = Long.parseLong(seedString);
        if (seedName.equals("PLACES")) setPlaceNodesSeed(seedValue);
        else if (seedName.equals("CONNECT")) setConnectNodesSeed(seedValue);
        else if (seedName.equals("BANDWIDTH")) setBWSeed(seedValue);
        else if (seedName.equals("EDGE_CONN")) setEdgeConnSeed(seedValue);
        else if (seedName.equals("GROUPING")) setGroupingSeed(seedValue);
        else if (seedName.equals("ASSIGNMENT")) setAssignSeed(seedValue);
      }
    } catch (Exception e2) {
      Util.ERR("Error reading seedfile. " + e2);
    }
  }
예제 #19
0
  /**
   * Invoked upon receiving a MERGE event from the MERGE layer. Starts the merge protocol. See
   * description of protocol in DESIGN.
   *
   * @param views A List of <em>different</em> views detected by the merge protocol
   */
  public void merge(Map<Address, View> views) {
    if (isMergeInProgress()) {
      if (log.isTraceEnabled())
        log.trace(gms.local_addr + ": merge is already running (merge_id=" + merge_id + ")");
      return;
    }

    // we need the merge *coordinators* not merge participants because not everyone can lead a merge
    // !
    Collection<Address> coords = Util.determineMergeCoords(views);
    Collection<Address> merge_participants = Util.determineMergeParticipants(views);
    Membership tmp =
        new Membership(coords); // establish a deterministic order, so that coords can elect leader
    tmp.sort();
    Address merge_leader = tmp.elementAt(0);
    if (log.isDebugEnabled()) log.debug("determining merge leader from " + merge_participants);
    if (merge_leader.equals(gms.local_addr)) {
      if (log.isDebugEnabled())
        log.debug(
            "I ("
                + gms.local_addr
                + ") will be the leader. Starting the merge task for "
                + merge_participants);
      merge_task.start(views);
    } else {
      if (log.isDebugEnabled())
        log.debug(
            "I ("
                + gms.local_addr
                + ") am not the merge leader, "
                + "waiting for merge leader ("
                + merge_leader
                + ") to initiate merge");
    }
  }
예제 #20
0
  protected void setBgColor(Color bgColor) {
    setBackgroundColor(bgColor);

    panelForBtns.setBackground(Util.getBgColor());
    addButton.setBackground(Util.getBgColor());
    removeButton.setBackground(Util.getBgColor());
  }
예제 #21
0
 private static void _testMessage(Message msg) throws Exception {
   Buffer buf = Util.messageToByteBuffer(msg);
   Message msg2 = Util.byteBufferToMessage(buf.getBuf(), buf.getOffset(), buf.getLength());
   Assert.assertEquals(msg.getSrc(), msg2.getSrc());
   Assert.assertEquals(msg.getDest(), msg2.getDest());
   Assert.assertEquals(msg.getLength(), msg2.getLength());
 }
예제 #22
0
  /** Callback invoked by the protocol stack to deliver a message batch */
  public void up(MessageBatch batch) {
    if (stats) {
      received_msgs += batch.size();
      received_bytes += batch.length();
    }

    // discard local messages (sent by myself to me)
    if (discard_own_messages
        && local_addr != null
        && batch.sender() != null
        && local_addr.equals(batch.sender())) return;

    for (Message msg : batch) {
      if (up_handler != null) {
        try {
          up_handler.up(new Event(Event.MSG, msg));
        } catch (Throwable t) {
          log.error(Util.getMessage("UpHandlerFailure"), t);
        }
      } else if (receiver != null) {
        try {
          receiver.receive(msg);
        } catch (Throwable t) {
          log.error(Util.getMessage("ReceiverFailure"), t);
        }
      }
    }
  }
예제 #23
0
  public static void testAllEqual() {
    Address[] mbrs = Util.createRandomAddresses(5);
    View[] views = {
      View.create(mbrs[0], 1, mbrs), View.create(mbrs[0], 1, mbrs), View.create(mbrs[0], 1, mbrs)
    };

    boolean same = Util.allEqual(Arrays.asList(views));
    System.out.println("views=" + Arrays.toString(views) + ", same = " + same);
    assert same;

    views =
        new View[] {
          View.create(mbrs[0], 1, mbrs),
          View.create(mbrs[0], 2, mbrs),
          View.create(mbrs[0], 1, mbrs)
        };
    same = Util.allEqual(Arrays.asList(views));
    System.out.println("views=" + Arrays.toString(views) + ", same = " + same);
    assert !same;

    views =
        new View[] {
          View.create(mbrs[1], 1, mbrs),
          View.create(mbrs[0], 1, mbrs),
          View.create(mbrs[0], 1, mbrs)
        };
    same = Util.allEqual(Arrays.asList(views));
    System.out.println("views=" + Arrays.toString(views) + ", same = " + same);
    assert !same;
  }
예제 #24
0
  public Exp validate(Exp exp, boolean scalar) {
    Exp resolved;
    try {
      resolved = (Exp) resolvedNodes.get(exp);
    } catch (ClassCastException e) {
      // A classcast exception will occur if there is a String
      // placeholder in the map. This is an internal error -- should
      // not occur for any query, valid or invalid.
      throw Util.newInternal(
          e, "Infinite recursion encountered while validating '" + Util.unparse(exp) + "'");
    }
    if (resolved == null) {
      try {
        stack.push((QueryPart) exp);
        // To prevent recursion, put in a placeholder while we're
        // resolving.
        resolvedNodes.put((QueryPart) exp, placeHolder);
        resolved = exp.accept(this);
        Util.assertTrue(resolved != null);
        resolvedNodes.put((QueryPart) exp, (QueryPart) resolved);
      } finally {
        stack.pop();
      }
    }

    if (scalar) {
      final Type type = resolved.getType();
      if (!TypeUtil.canEvaluate(type)) {
        String exprString = Util.unparse(resolved);
        throw MondrianResource.instance().MdxMemberExpIsSet.ex(exprString);
      }
    }

    return resolved;
  }
예제 #25
0
 JavacState(Options op, boolean removeJavacState, PrintStream o, PrintStream e) {
   options = op;
   out = o;
   err = e;
   numCores = options.getNumCores();
   theArgs = options.getStateArgsString();
   binDir = Util.pathToFile(options.getDestDir());
   gensrcDir = Util.pathToFile(options.getGenSrcDir());
   headerDir = Util.pathToFile(options.getHeaderDir());
   stateDir = Util.pathToFile(options.getStateDir());
   javacState = new File(stateDir, "javac_state");
   if (removeJavacState && javacState.exists()) {
     javacState.delete();
   }
   newJavacState = false;
   if (!javacState.exists()) {
     newJavacState = true;
     // If there is no javac_state then delete the contents of all the artifact dirs!
     // We do not want to risk building a broken incremental build.
     // BUT since the makefiles still copy things straight into the bin_dir et al,
     // we avoid deleting files here, if the option --permit-unidentified-classes was supplied.
     if (!options.areUnidentifiedArtifactsPermitted()) {
       deleteContents(binDir);
       deleteContents(gensrcDir);
       deleteContents(headerDir);
     }
     needsSaving = true;
   }
   prev = new BuildState();
   now = new BuildState();
   taintedPackages = new HashSet<>();
   recompiledPackages = new HashSet<>();
   packagesWithChangedPublicApis = new HashSet<>();
 }
예제 #26
0
 /** diagnostic trace of static tables. */
 public static void trace_static() {
   int i, j;
   System.out.print("AES Static Tablesn");
   System.out.print("S[] = n");
   for (i = 0; i < 16; i++) {
     for (j = 0; j < 16; j++) System.out.print(Util.toHEX1(S[i * 16 + j]) + ", ");
     System.out.println();
   }
   System.out.print("Si[] = n");
   for (i = 0; i < 16; i++) {
     for (j = 0; j < 16; j++) System.out.print(Util.toHEX1(Si[i * 16 + j]) + ", ");
     System.out.println();
   }
   System.out.print("rcon[] = n");
   for (i = 0; i < 5; i++) {
     for (j = 0; j < 6; j++) System.out.print(Util.toHEX1(rcon[i * 6 + j]) + ", ");
     System.out.println();
   }
   System.out.print("log[] = n");
   for (i = 0; i < 32; i++) {
     for (j = 0; j < 8; j++) System.out.print(Util.toHEX1(log[i * 8 + j]) + ", ");
     System.out.println();
   }
   System.out.print("alog[] = n");
   for (i = 0; i < 32; i++) {
     for (j = 0; j < 8; j++) System.out.print(Util.toHEX1(alog[i * 8 + j]) + ", ");
     System.out.println();
   }
 }
예제 #27
0
  public void init() {
    String host = util.getHost();
    String bindAddr = util.getBindAddress();
    int port = util.getPort(ListeningContextFace.DEFAULT_TRAP_PORT);
    String socketType = util.getSocketType();
    // String oid = util.getOid();
    String community = util.getCommunity();

    try {
      context = new SnmpContextv2c(host, port, bindAddr, socketType);
      context.setCommunity(community);

      pdu = new TrapPduv2(context);
      pdu.addOid(sysUpTime, new AsnUnsInteger(5));
      pdu.addOid(snmpTrapOID, new AsnObjectId(warmStart));

      System.out.println(pdu.toString());
      pdu.send();

      // when calling destroy, the pdu might not be sent
      // context.destroy();
    } catch (java.io.IOException exc) {
      System.out.println("IOException " + exc.getMessage());
    } catch (uk.co.westhawk.snmp.stack.PduException exc) {
      System.out.println("PduException " + exc.getMessage());
    }
    // System.exit(0);
  }
예제 #28
0
  // Sets a configuration value for this plugin.
  @Override
  public void setConfigValue(String setting, String value) {
    Log.getInstance()
        .write(
            Log.LOGLEVEL_ALL,
            "PlugIn: setConfigValue received from Plugin Manager. Setting = "
                + setting
                + ":"
                + value);

    if (setting.startsWith(SETTING_LOGLEVEL)) {
      if (value.startsWith("None")) Log.getInstance().SetLogLevel(Log.LOGLEVEL_NONE);
      else if (value.startsWith("Error")) Log.getInstance().SetLogLevel(Log.LOGLEVEL_ERROR);
      else if (value.startsWith("Warn")) Log.getInstance().SetLogLevel(Log.LOGLEVEL_WARN);
      else if (value.startsWith("Trace")) Log.getInstance().SetLogLevel(Log.LOGLEVEL_TRACE);
      else if (value.startsWith("Verbose")) Log.getInstance().SetLogLevel(Log.LOGLEVEL_VERBOSE);
      else if (value.startsWith("Maximum")) Log.getInstance().SetLogLevel(Log.LOGLEVEL_ALL);
      else Log.getInstance().SetLogLevel(Log.LOGLEVEL_ERROR);
    } else if (setting.startsWith(SETTING_DEFAULT_MAX)) {
      if (value.equalsIgnoreCase("5309")) {
        System.out.println("LIR:: Deleting all user records.");
        UserRecordAPI.DeleteAllUserRecords(DataStore.STORE);
        showInFocus = null;
      } else Configuration.SetServerProperty(PROPERTY_DEFAULT_MAX, verifyMax(value));
    } else if (setting.startsWith(SETTING_REDUCE_TO_MAX)) {
      Configuration.SetServerProperty(PROPERTY_REDUCE_TO_MAX, value);
    } else if (setting.startsWith(SETTING_KEEP_OLDEST)) {
      Configuration.SetServerProperty(PROPERTY_KEEP_OLDEST, value);
    } else if (setting.startsWith(SETTING_PICK_SHOW)) {

      // The user just selected a show.  Put it in focus.
      showInFocus = Util.removeNumberMax(value);

    } else if (setting.startsWith(SETTING_HAVE_SHOW)) {

      // The user just selected a different show.  Put it in focus.
      showInFocus = Util.removeNumberMax(value);

    } else if (setting.startsWith(SETTING_SHOW_MAX)) {

      // The user just entered a new max for this show. If it's non null add it.
      if (value == null || value.trim().length() == 0) return;

      try {
        Integer.parseInt(value);
      } catch (NumberFormatException e) {
        return;
      }

      DataStore store = new DataStore(showInFocus);
      store.addRecord(showInFocus);
      store.setMax(verifyMax(value));
    } else if (setting.startsWith(SETTING_RESET_SHOW)) {

      // The user wants to reset this show so just delete the User Record.
      DataStore store = new DataStore(showInFocus);
      if (store.deleteRecord()) showInFocus = null;
      else Log.getInstance().write(Log.LOGLEVEL_WARN, "Plugin: Could not delete the User Record.");
    }
  }
예제 #29
0
  public void switchLayout(int newId, boolean bLayout) {

    if (layoutId == newId) return;
    if (newId >= nviews) updateVpInfo(newId + 1);

    if (bSwitching) {
      return;
    }

    bSwitching = true;
    int oldId = layoutId;
    vpId = newId;
    layoutId = newId;

    recordCurrentLayout();
    VpLayoutInfo vInfo = Util.getViewArea().getLayoutInfo(oldId);
    if (vInfo != null) { // save current layout info
      vInfo.tp_selectedTab = tp_selectedTab;
      vInfo.setVerticalTabName(selectedTabName);
      // copyCurrentLayout(vInfo);
    }

    vInfo = Util.getViewArea().getLayoutInfo(newId);

    putHsLayout(oldId);
    if (bLayout) getHsLayout(vpId);

    for (int i = 0; i < toolList.size(); i++)
      ((VToolPanel) toolList.get(i)).switchLayout(newId, bLayout);

    if (bLayout) setCurrentLayout();
    /*
    if(comparePanelLayout(oldId, newId)) {
    setCurrentLayout();
           }
           if ((vInfo != null) && vInfo.bAvailable &&
    compareCurrentLayout(vInfo)) {
                  setCurrentLayout(vInfo);
           }

    for(int i=0; i< toolList.size(); i++)
        ((VToolPanel) toolList.get(i)).switchLayout(newId);
           */

    // setViewPort(newId);

    if (bLayout) setCurrentLayout(vInfo);

    updateValue();

    if (bLayout) {
      if (pinPanel.isOpen()) {
        if (!pinPanel.isVisible()) pinPanel.setVisible(true);
      } else pinPanel.setVisible(false);
    }
    validate();
    repaint();

    bSwitching = false;
  }
예제 #30
0
파일: Command.java 프로젝트: plutext/basex
  /**
   * Runs the command without permission, data and concurrency checks.
   *
   * @param ctx database context
   * @param os output stream
   * @return result of check
   */
  public boolean run(final Context ctx, final OutputStream os) {
    perf = new Performance();
    context = ctx;
    prop = ctx.prop;
    mprop = ctx.mprop;
    out = PrintOutput.get(os);

    try {
      return run();
    } catch (final ProgressException ex) {
      // process was interrupted by the user or server
      abort();
      return error(INTERRUPTED);
    } catch (final Throwable ex) {
      // unexpected error
      Performance.gc(2);
      abort();
      if (ex instanceof OutOfMemoryError) {
        Util.debug(ex);
        return error(OUT_OF_MEM + (createWrite() ? H_OUT_OF_MEM : ""));
      }
      return error(Util.bug(ex) + NL + info.toString());
    } finally {
      // flushes the output
      try {
        if (out != null) out.flush();
      } catch (final IOException ignored) {
      }
    }
  }