예제 #1
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());
 }
예제 #2
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) {
      }
    }
  }
예제 #3
0
파일: FolderEx.java 프로젝트: neojsy/myapp
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.folderex);

    Intent gintent = getIntent();
    getPath = gintent.getStringExtra("path");
    dbPath = gintent.getStringExtra("dbpath");

    FileList _FileList = new FileList(this);
    _FileList.setOnPathChangedListener(_OnPathChanged);
    _FileList.setOnFileSelected(_OnFileSelected);

    LinearLayout layout = (LinearLayout) findViewById(R.id.LinearLayout01);
    layout.addView(_FileList);

    Util.print("getPath = " + getPath);
    String path = " ";

    if (getPath.equals("empty")) {
      File root = Environment.getExternalStorageDirectory();
      _FileList.setPath(root.getAbsolutePath());
      path = root.getAbsolutePath();
    } else {
      _FileList.setPath(getPath);
      path = getPath;
    }

    Util.print("path = " + path);

    _FileList.setFocusable(true);
    _FileList.setFocusableInTouchMode(true);

    ((TextView) findViewById(R.id.TextView01)).setSelected(true);
  }
예제 #4
0
 public FileAccess(String domain) {
   _domain = domain;
   _isLocal = Util.isLocal();
   if (_isLocal) {
     _rootFile = Util.initLocalResource(_domain);
     return;
   }
   try {
     // _home=(IFileMgrHome)ServiceLookup.getInstance(
     //  ServiceLookup.CLIENT_CONTEXT).getHome(IFileMgrHome.class);
     // if (_home == null) {
     //  System.out.println("Lookup failure: Home should not be null.");
     //  throw new Exception();
     // }
     // _remote = _home.create();
     _remote =
         (IFileMgr)
             ServiceLocator.instance(ServiceLocator.CLIENT_CONTEXT)
                 .getObj(IFileMgrHome.class.getName(), IFileMgrHome.class, new Object[0]);
     if (_remote == null) {
       System.out.println("Lookup failure: Remote should not be null.");
       throw new Exception();
     }
   } catch (Exception ex) {
     System.out.println(" Exception in SetUp  : " + ex.getMessage());
     ex.printStackTrace();
   }
 }
예제 #5
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();
    }
  }
예제 #6
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);
        }
      }
    }
  }
예제 #7
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");
  }
예제 #8
0
 /**
  * write to an existing file in a webdav server using the current domain
  *
  * @param path The path relative to the domain for the file
  * @param buffer The contents of the file
  * @param last true if this is the last block of data
  * @return The total number of bytes stored or null if method failed
  */
 public long writeToFile(String path, byte[] buffer, boolean last) {
   long result = -1L;
   if (_tempFile == null) _tempFile = Util.createCache();
   try {
     if (buffer != null && buffer.length > 0) {
       FileOutputStream fOut = new FileOutputStream(_tempFile.getCanonicalPath(), true);
       fOut.write(buffer);
       fOut.close();
     }
     if (last) {
       if (_isLocal) {
         File tmpFile = new File(_rootFile.getCanonicalPath() + File.separatorChar + path);
         if (_tempFile.renameTo(tmpFile)) {
           _tempFile = null;
           return tmpFile.length();
         }
       } else {
         WebdavResource webdavRes = Util.initWebdavResource(_domain);
         if (webdavRes == null) {
           _tempFile.delete();
           _tempFile = null;
           return result;
         }
         result = Util.putFile(webdavRes, _domain, path, _tempFile);
       }
     } else {
       return _tempFile.length();
     }
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   return result;
 }
 /**
  * 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
 // -----------------------------------------------------------
 // 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;
 }
예제 #11
0
  static {
    String tmp;

    int max_elements = 500;
    long max_age = 5000L;

    try {
      tmp =
          Util.getProperty(new String[] {Global.UUID_CACHE_MAX_ELEMENTS}, null, null, false, "500");
      if (tmp != null) max_elements = Integer.valueOf(tmp);
    } catch (Throwable t) {
    }

    try {
      tmp = Util.getProperty(new String[] {Global.UUID_CACHE_MAX_AGE}, null, null, false, "5000");
      if (tmp != null) max_age = Long.valueOf(tmp);
    } catch (Throwable t) {
    }

    cache = new LazyRemovalCache<Address, String>(max_elements, max_age);

    /* Trying to get value of jgroups.print_uuids. PropertyPermission not granted if
     * running in an untrusted environment with JNLP */
    try {
      tmp = Util.getProperty(new String[] {Global.PRINT_UUIDS}, null, null, false, "false");
      print_uuids = Boolean.valueOf(tmp).booleanValue();
    } catch (SecurityException ex) {
    }
  }
예제 #12
0
  public int get(IBitstream _F_bs) throws IOException {
    int _F_ret = 0;
    MapResult _F_mr;
    int _F_parse = 0;
    Util.trace(_F_bs.getpos(), 0, (int) 0, "begin PATProgram");
    _F_parse = 16;
    program_number = _F_bs.getbits(_F_parse);
    Util.trace(
        _F_bs.getpos() - _F_parse,
        _F_parse,
        (int) program_number,
        "program_number" + " (" + program_number + ")");
    _F_bs.skipbits(3);
    if (program_number == 0) {
      _F_parse = 13;
      network_PID = _F_bs.getbits(_F_parse);
      Util.trace(
          _F_bs.getpos() - _F_parse,
          _F_parse,
          (int) network_PID,
          "network_PID" + " (" + network_PID + ")");
    } else {
      _F_parse = 13;
      program_map_PID = _F_bs.getbits(_F_parse);
      Util.trace(
          _F_bs.getpos() - _F_parse,
          _F_parse,
          (int) program_map_PID,
          "program_map_PID" + " (" + program_map_PID + ")");
    }

    Util.trace(_F_bs.getpos(), 0, (int) 0, "end PATProgram");
    return _F_ret;
  }
예제 #13
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.");
    }
  }
예제 #14
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);
        }
      }
    }
  }
예제 #15
0
  public void testRecursiveFileListing() throws IOException {
    String LOCAL_INPUT_FILE = "test.dat";
    String INPUT_FILE = "foo/bar/test.dat";

    PrintWriter w = new PrintWriter(new FileWriter(LOCAL_INPUT_FILE));
    w.println("1");
    w.println("2");
    w.println("3");
    w.println("5");
    w.close();

    Util.copyFromLocalToCluster(cluster, LOCAL_INPUT_FILE, INPUT_FILE);

    pigServer.registerQuery("a = load 'foo' as (nums:chararray);");
    pigServer.registerQuery("b = load 'foo' as (nums:chararray);");
    pigServer.registerQuery("d = join a by nums, b by nums USING 'skewed';");

    Iterator<Tuple> iter = pigServer.openIterator("d");
    int count = 0;
    while (iter.hasNext()) {
      iter.next();
      count++;
    }
    Assert.assertEquals(4, count);

    new File(LOCAL_INPUT_FILE).delete();
    Util.deleteFile(cluster, INPUT_FILE);
  }
예제 #16
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);
    }
  }
예제 #17
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());
 }
예제 #18
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);
        }
      }
    }
  }
예제 #19
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<>();
 }
예제 #20
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"));
 }
예제 #21
0
 /**
  * Reads parse trees either from standard input or a specified file, converting them to sentences
  * and printing those sentences on standard output.
  *
  * <pre>
  * usage: [-v|-help|-usage] [-tags] [filename]
  *         -v|-help|-usage: prints out this message
  *         -tags: indicates to spit out one S-expression per word, of the form
  *                 (word (tag))
  *         filename is the file to be processed (standard input is assumed if
  *                 this argument is "-" or is not present)
  * </pre>
  */
 public static void main(String[] args) {
   InputStream inStream = System.in;
   boolean tags = false;
   String inFile = null;
   for (int i = 0; i < args.length; i++) {
     if (args[i].equals("-help") || args[i].equals("-usage") || args[i].equals("-v")) {
       usage();
       return;
     } else if (args[i].equals("-tags")) tags = true;
     else if (!args[i].equals("-")) inFile = args[i];
   }
   if (inFile != null) {
     try {
       inStream = new FileInputStream(inFile);
     } catch (FileNotFoundException fnfe) {
       System.err.println(fnfe);
       System.exit(-1);
     }
   }
   try {
     SexpTokenizer tok = new SexpTokenizer(inStream, Language.encoding(), bufSize);
     OutputStream os = System.out;
     Writer writer = new BufferedWriter(new OutputStreamWriter(os, Language.encoding()));
     PrintWriter pw = new PrintWriter(writer);
     Sexp curr = null;
     while ((curr = Sexp.read(tok)) != null)
       pw.println(tags ? Util.collectTaggedWords(curr) : Util.collectLeaves(curr));
     pw.flush();
     pw.close();
   } catch (Exception e) {
     System.out.println(e);
   }
 }
예제 #22
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);
  }
예제 #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
  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);
    }
  }
예제 #25
0
 private static void marshalString(int size) throws Exception {
   byte[] tmp = new byte[size];
   String str = new String(tmp, 0, tmp.length);
   byte[] retval = Util.objectToByteBuffer(str);
   System.out.println("length=" + retval.length + " bytes");
   String obj = (String) Util.objectFromByteBuffer(retval);
   System.out.println("read " + obj.length() + " string");
 }
예제 #26
0
  /**
   * Retrieves the specified value. Throws an error if value cannot be read.
   *
   * @param key key
   * @param c expected type
   * @return result
   */
  private Object get(final Object[] key, final Class<?> c) {
    final Object entry = props.get(key[0].toString());
    if (entry == null) Util.notexpected("Property " + key[0] + " not defined.");

    final Class<?> cc = entry.getClass();
    if (c != cc) Util.notexpected("Property '" + key[0] + "' is a " + Util.name(cc));
    return entry;
  }
예제 #27
0
파일: GetVersion.java 프로젝트: fin-nick/fj
 private static int[] getVersionDate(String str) {
   String[] svers = Util.explode(str, '.');
   int[] ivers = new int[3];
   for (int num = 0; num < ivers.length; num++) {
     ivers[num] = Util.strToIntDef(num < svers.length ? svers[num] : "", 0);
   }
   return ivers;
 }
예제 #28
0
 /**
  * Append copies of the values from another array, from the start
  *
  * @param sa the other array
  * @param stoppingKey any equal or larger key in other array will terminate copying
  */
 protected void appendCopiesUntil(RoaringArray sa, short stoppingKey) {
   final int stopKey = Util.toIntUnsigned(stoppingKey);
   for (int i = 0; i < sa.size; ++i) {
     if (Util.toIntUnsigned(sa.array[i].key) >= stopKey) break;
     extendArray(1);
     this.array[this.size++] = new Element(sa.array[i].key, sa.array[i].value.clone());
   }
 }
예제 #29
0
 /**
  * Gets the imageicon. If the user has a predefined icon, get that, otherwise get the varian icon.
  *
  * @return the imageicon
  */
 protected ImageIcon getImageIcon() {
   ImageIcon icon = null;
   String strPath = WOperators.getDefIcon();
   if (strPath != null) {
     icon = Util.getImageIcon(strPath);
   }
   if (icon == null) icon = Util.getImageIcon(WOperators.ICON);
   return icon;
 }
예제 #30
0
파일: Util.java 프로젝트: gubo/slipwire
 public static void main(final String[] args) {
   try {
     final String encrypted = Util.encrypt("fred flintstone");
     final String decrypted = Util.decrypt(encrypted);
     DBG.m(encrypted + " / " + decrypted);
   } catch (Exception x) {
     DBG.m(x);
   }
 }