コード例 #1
0
ファイル: ConsoleClient.java プロジェクト: Solgrid/armitage
  public void _sendString(String text) {
    if (writeCommand == null) return;

    /* intercept sessions -i and deliver it to a listener within armitage */
    if (sessionListener != null) {
      Matcher m = interact.matcher(text);
      if (m.matches()) {
        sessionListener.actionPerformed(new ActionEvent(this, 0, m.group(1)));
        return;
      }
    }

    Map read = null;

    try {
      synchronized (this) {
        if (window != null && echo) {
          window.append(window.getPromptText() + text);
        }
      }

      if ("armitage.push".equals(writeCommand)) {
        read = (Map) connection.execute(writeCommand, new Object[] {session, text});
      } else {
        connection.execute(writeCommand, new Object[] {session, text});
        read = readResponse();
      }
      processRead(read);

      fireSessionWroteEvent(text);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
コード例 #2
0
ファイル: DocumentEditGUI.java プロジェクト: elmerlu/FileEdit
 public void save(int i) {
   BufferedWriter brw = null;
   TextDocument ta = (TextDocument) td.getComponentAt(i);
   try {
     File file = null;
     if (ta.file == null) { // 判斷是否為新黨案,是的話使用預設路徑儲存
       file = new File(default_auto_save_path + "\\" + ta.fileName);
     } else {
       file = ta.file; // 儲存於原檔案
     }
     brw = new BufferedWriter(new FileWriter(file));
     ta.write(brw);
     ta.save = true;
     td.setTitleAt(i, ta.fileName); // 更新標題名稱
   } catch (FileNotFoundException ffe) { // 若預設路徑不存在,則跳出警告
     JOptionPane.showMessageDialog(
         null,
         ta.fileName + "儲存失敗!\n請檢查Default AutoSave-Path是否存在,或是權限不足.",
         "Save error",
         JOptionPane.ERROR_MESSAGE);
   } catch (Exception exc) {
     exc.printStackTrace();
   } finally {
     try {
       brw.close();
     } catch (Exception exc) {
     }
   }
 }
コード例 #3
0
ファイル: Test.java プロジェクト: bokix/bokix-private-project
  public static void main(String[] args) throws Exception {

    Context jndiContext = null;
    try {
      Hashtable env = new Hashtable();
      env.put(Context.INITIAL_CONTEXT_FACTORY, providerContextFactory);
      env.put(Context.PROVIDER_URL, "tibjmsnaming://localhost:7222");
      //			env.put(Context.SECURITY_PRINCIPAL, "admin");
      //			env.put(Context.SECURITY_CREDENTIALS, "");
      jndiContext = new InitialContext(env);
    } catch (Exception e) {
      System.out.println("Failed to create InitialContext");
      e.printStackTrace();
    }
    System.out.println("contex is " + jndiContext.getEnvironment().toString());
    //		ConnectionFactory factory = (javax.jms.ConnectionFactory)
    // jndiContext.lookup("ConnectionFactory");
    //		System.out.println(jndiContext.lookup("topic.sample"));
    //		jndiContext.bind("jbofy","Jbofy Yang");
    //		TopicConnectionFactory topicFactory = (javax.jms.TopicConnectionFactory) jndiContext
    //				.lookup("jms");
    //
    QueueConnectionFactory queueFactory =
        (javax.jms.QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory");
    System.out.println(queueFactory);

    Topic topic = (javax.jms.Topic) jndiContext.lookup("topic/subscribe");
    Queue queue = (javax.jms.Queue) jndiContext.lookup("queue/request");

    System.out.println(topic);
    System.out.println(queue);
  }
コード例 #4
0
  protected String getRallyAPIError(String responseXML) {
    String errorMsg = "";

    try {

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Errors");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Element item = (Element) iter.next();
        errorMsg = item.getChildText("OperationResultError");
      }

    } catch (Exception e) {
      errorMsg = e.toString();
    }

    return errorMsg;
  }
コード例 #5
0
ファイル: DocumentEditGUI.java プロジェクト: elmerlu/FileEdit
 @Override
 public void actionPerformed(ActionEvent e) {
   if (td.getTabCount() > 0) {
     JFileChooser f = new JFileChooser();
     f.setFileFilter(new MyFileFilter());
     int choose = f.showSaveDialog(getContentPane());
     if (choose == JFileChooser.APPROVE_OPTION) {
       BufferedWriter brw = null;
       try {
         File file = f.getSelectedFile();
         brw = new BufferedWriter(new FileWriter(file));
         int i = td.getSelectedIndex();
         TextDocument ta = (TextDocument) td.getComponentAt(i);
         ta.write(brw);
         ta.fileName = file.getName(); // 將檔案名稱更新為存檔的名稱
         td.setTitleAt(td.getSelectedIndex(), ta.fileName);
         ta.file = file;
         ta.save = true; // 設定已儲存
         System.out.println("Save as pass!");
         td.setTitleAt(i, ta.fileName); // 更新標題名稱
       } catch (Exception exc) {
         exc.printStackTrace();
       } finally {
         try {
           brw.close();
         } catch (Exception ecx) {
           ecx.printStackTrace();
         }
       }
     }
   } else {
     JOptionPane.showMessageDialog(null, "沒有檔案可以儲存!");
   }
 }
コード例 #6
0
 private static void printHelp(OptionParser parser) {
   try {
     parser.printHelpOn(System.out);
   } catch (Exception exception) {
     exception.printStackTrace();
   }
 }
コード例 #7
0
ファイル: Test.java プロジェクト: bokix/bokix-private-project
  public static void destroySubscribe(HttpServletRequest req, HttpServletResponse res) {

    try {
      AsyncMessage message = new AsyncMessage();
      message.setMessageType("test_subscribe");

      SubscriberController controller =
          (SubscriberController) BeanFactory.getBean("publish_subscribe_controller");
      controller.unregist(message);
      //			String mseq = req.getParameter("mseq");
      HttpSession session = req.getSession(false);
      //			SSysOperatorsList list =
      // (SSysOperatorsList)req.getSession(false).getAttribute(mseq);
      //			int size = list.size();
      res.getWriter().println("<a href=\"./index.html\">返回首页</a><br>");
      res.getWriter().println("<pre>");
      res.getWriter().println("<a href=\"./index.html\">返回首页</a><br>");
    } catch (Exception e) {
      try {
        res.getWriter().println("<pre>");
        e.printStackTrace(res.getWriter());
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
コード例 #8
0
ファイル: Test.java プロジェクト: bokix/bokix-private-project
 /**
  * 发起同步请求,获取后台信息,直接显示在页面上
  *
  * @param req
  * @param res
  */
 public static void sync(HttpServletRequest req, HttpServletResponse res) {
   System.setProperty("0", "aaaaaaaa");
   //		h.put(i+"","aaaaaaaaaaaaaaaaaaaaaaaa");
   //		i++;
   //		System.out.println("*************************system prop is " +
   // System.getProperties());
   IAsyncMgntInt iAsyncMgntInt = new IAsyncMgntInt();
   SSysOperatorsListHolder holder = new SSysOperatorsListHolder();
   CBSErrorMsg errMsg = new CBSErrorMsg();
   try {
     res.getWriter().println("<a href=\"./index.html\">返回首页</a></script>");
     int result = iAsyncMgntInt.select_sysOperators(holder, errMsg);
     System.out.println("*****result is " + result);
     if (result != 0) {
       res.getWriter().println(errMsg.get_errorMsg() + ":" + errMsg.get_errorCode());
     }
     SSysOperatorsList list = holder.value;
     int size = list.size();
     res.getWriter().println("<pre>");
     for (int i = 0; i < size; i++) {
       SSysOperators opers = (SSysOperators) list.get(i);
       res.getWriter().println(i + ":" + opers.get_loginName());
     }
     res.getWriter().println("<a href=\"./index.html\">返回首页</a></script>");
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #9
0
ファイル: Test.java プロジェクト: bokix/bokix-private-project
  /**
   * 超时测试
   *
   * @param req
   * @param res
   */
  public static void asyncTimeout(HttpServletRequest req, HttpServletResponse res) {
    IAsyncMgntInt iAsyncMgntInt = new IAsyncMgntInt();
    iAsyncMgntInt.setAsyncCall(true); // 标志异步调用
    iAsyncMgntInt.setTimeout(10000);
    SSysOperatorsListHolder holder = new SSysOperatorsListHolder();
    CBSErrorMsg errMsg = new CBSErrorMsg();
    try {

      int result = iAsyncMgntInt.select_sysOperators_timeout(holder, errMsg); // 获取响应结果

      SSysOperatorsList list = holder.value;
      int size = list.size();
      res.getWriter().println("<a href=\"./index.html\">返回首页</a><br>");
      res.getWriter().println("<pre>");
      for (int i = 0; i < size; i++) {
        SSysOperators opers = (SSysOperators) list.get(i);
        res.getWriter().println(i + ":" + opers.get_loginName());
      }
      res.getWriter().println("<a href=\"./index.html\">返回首页</a><br>");
    } catch (Exception e) {
      try {
        res.getWriter().println("<pre>");
        e.printStackTrace(res.getWriter());
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
コード例 #10
0
    // Creates a new thread, runs the program in that thread, and reports any errors as needed.
    private void run(String clazz) {
      try {
        // Makes sure the JVM resets if it's already running.
        if (JVMrunning) kill();

        // Some String constants for java path and OS-specific separators.
        String separator = System.getProperty("file.separator");
        String path = System.getProperty("java.home") + separator + "bin" + separator + "java";

        // Tries to run compiled code.
        ProcessBuilder builder = new ProcessBuilder(path, clazz);

        // Should be good now! Everything past this is on you. Don't mess it up.
        println(
            "Build succeeded on " + java.util.Calendar.getInstance().getTime().toString(), progErr);
        println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", progErr);

        JVM = builder.start();

        // Note that as of right now, there is no support for input. Only output.
        Reader errorReader = new InputStreamReader(JVM.getErrorStream());
        Reader outReader = new InputStreamReader(JVM.getInputStream());
        // Writer inReader = new OutputStreamWriter(JVM.getOutputStream());

        redirectErr = redirectIOStream(errorReader, err);
        redirectOut = redirectIOStream(outReader, out);
        // redirectIn = redirectIOStream(null, inReader);
      } catch (Exception e) {
        // This catches any other errors we might get.
        println("Some error thrown", progErr);
        logError(e.toString());
        displayLog();
        return;
      }
    }
コード例 #11
0
ファイル: Macro.java プロジェクト: bramk/bnd
 private String doCommand(Object target, String method, String[] args) {
   if (target == null) ; // System.err.println("Huh? Target should never be null " +
   // domain);
   else {
     String cname = "_" + method.replaceAll("-", "_");
     try {
       Method m = target.getClass().getMethod(cname, new Class[] {String[].class});
       return (String) m.invoke(target, new Object[] {args});
     } catch (NoSuchMethodException e) {
       // Ignore
     } catch (InvocationTargetException e) {
       if (e.getCause() instanceof IllegalArgumentException) {
         domain.error(
             "%s, for cmd: %s, arguments; %s",
             e.getCause().getMessage(), method, Arrays.toString(args));
       } else {
         domain.warning("Exception in replace: %s", e.getCause());
         e.getCause().printStackTrace();
       }
     } catch (Exception e) {
       domain.warning("Exception in replace: " + e + " method=" + method);
       e.printStackTrace();
     }
   }
   return null;
 }
コード例 #12
0
  // test
  public static void main(String[] args) {
    String vers = "3.0";
    String wnhome = "C:/Program Files/WordNet/" + vers + "/dict";
    String icfile =
        "C:/Program Files/WordNet/" + vers + "/WordNet-InfoContent-" + vers + "/ic-semcor.dat";
    URL url = null;
    try {
      url = new URL("file", null, wnhome);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
    if (url == null) {
      return;
    }
    IDictionary dict = new Dictionary(url);
    try {
      dict.open();
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    ICFinder icfinder = new ICFinder(icfile);
    DepthFinder depthfinder = new DepthFinder(dict, icfile);
    double depth1 = depthfinder.getSynsetDepth("opposition", 2, "n");
    System.out.println(depth1);
  }
コード例 #13
0
  public static void main(String[] args) {
    String inputStr = null;
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    try {
      while ((inputStr = reader.readLine()) != null) {
        inputStr = inputStr.trim();

        if (DEST_MATCHER.reset(inputStr).matches()) {
          System.out.println("Destination field!\n");
        } else if (SOURCE_MATCHER.reset(inputStr).matches()) {
          System.out.println("Source field!\n");
        } else if (STRING_MATCHER.reset(inputStr).matches()) {
          System.out.println("String literal!\n");
        } else if (VAR_MATCHER.reset(inputStr).matches()) {
          System.out.println("Variable!\n");
        } else if (NUM_MATCHER.reset(inputStr).matches()) {
          System.out.println("Number!\n");
        } else {
          System.out.println("Huh???\n");
        }
      }
    } catch (Exception ioe) {
      System.out.println("Exception: " + ioe.toString());
      ioe.printStackTrace();
    }
  }
コード例 #14
0
ファイル: Test.java プロジェクト: bokix/bokix-private-project
  /**
   * 获取异步请求结果
   *
   * @param req
   * @param res
   */
  public static void asyncResult(HttpServletRequest req, HttpServletResponse res) {
    IAsyncMgntInt iAsyncMgntInt = new IAsyncMgntInt();
    SSysOperatorsListHolder holder = new SSysOperatorsListHolder();
    CBSErrorMsg errMsg = new CBSErrorMsg();
    iAsyncMgntInt.setAsyncCall(true);

    try {
      String mseq = req.getParameter("mseq");

      MessageSequence ms = new MessageSequence(mseq);

      iAsyncMgntInt.setMseq(ms);
      int result = iAsyncMgntInt.select_sysOperators_response(holder, errMsg);
      res.getWriter().println("<a href=\"./index.html\">返回首页</a></script>");
      SSysOperatorsList list = holder.value;
      int size = list.size();
      res.getWriter().println("<pre>");
      for (int i = 0; i < size; i++) {
        SSysOperators opers = (SSysOperators) list.get(i);
        res.getWriter().println(i + ":" + opers.get_loginName());
      }
      res.getWriter().println("<a href=\"./index.html\">返回首页</a></script>");
    } catch (Exception e) {
      // TODO Auto-generated catch block
      try {
        e.printStackTrace(res.getWriter());
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
コード例 #15
0
ファイル: DocumentEditGUI.java プロジェクト: elmerlu/FileEdit
 @Override
 public void actionPerformed(ActionEvent e) {
   JFileChooser f = new JFileChooser();
   f.setFileFilter(new MyFileFilter()); // 設定檔案選擇器
   int choose = f.showOpenDialog(getContentPane()); // 顯示檔案選取
   if (choose == JFileChooser.OPEN_DIALOG) { // 有開啟檔案的話,開始讀檔
     BufferedReader br = null;
     try {
       File file = f.getSelectedFile();
       br = new BufferedReader(new FileReader(file));
       TextDocument ta = new TextDocument(file.getName(), file);
       ta.addKeyListener(new SystemTrackSave());
       ta.read(br, null);
       td.add(ta);
       td.setTitleAt(docCount++, file.getName());
     } catch (Exception exc) {
       exc.printStackTrace();
     } finally {
       try {
         br.close();
       } catch (Exception ecx) {
         ecx.printStackTrace();
       }
     }
   }
 }
コード例 #16
0
ファイル: FNPat.java プロジェクト: sandeepyohans/basex
  /**
   * Evaluates the replace function.
   *
   * @param val input value
   * @param ctx query context
   * @return function result
   * @throws QueryException query exception
   */
  private Item replace(final byte[] val, final QueryContext ctx) throws QueryException {
    final byte[] rep = checkStr(expr[2], ctx);
    for (int i = 0; i < rep.length; ++i) {
      if (rep[i] == '\\') {
        if (i + 1 == rep.length || rep[i + 1] != '\\' && rep[i + 1] != '$') FUNREPBS.thrw(info);
        ++i;
      }
      if (rep[i] == '$'
          && (i == 0 || rep[i - 1] != '\\')
          && (i + 1 == rep.length || !digit(rep[i + 1]))) FUNREPDOL.thrw(info);
    }

    final Pattern p = pattern(expr[1], expr.length == 4 ? expr[3] : null, ctx);
    if (p.pattern().isEmpty()) REGROUP.thrw(info);

    String r = string(rep);
    if ((p.flags() & Pattern.LITERAL) != 0) {
      r = SLASH.matcher(BSLASH.matcher(r).replaceAll("\\\\\\\\")).replaceAll("\\\\\\$");
    }

    try {
      return Str.get(p.matcher(string(val)).replaceAll(r));
    } catch (final Exception ex) {
      if (ex.getMessage().contains("No group")) REGROUP.thrw(info);
      throw REGPAT.thrw(info, ex);
    }
  }
コード例 #17
0
  @Override
  public synchronized void run() {
    try {
      for (int i = 0; i < NUM_PIPES; i++) {
        while (Thread.currentThread() == reader[i]) {
          try {
            this.wait(100);
          } catch (InterruptedException ie) {
          }
          if (pin[i].available() != 0) {
            String input = this.readLine(pin[i]);
            appendMsg(htmlize(input));
            if (textArea.getDocument().getLength() > 0) {
              textArea.setCaretPosition(textArea.getDocument().getLength() - 1);
            }
          }
          if (quit) {
            return;
          }
        }
      }

    } catch (Exception e) {
      Debug.error(me + "Console reports an internal error:\n%s", e.getMessage());
    }
  }
コード例 #18
0
 public static void main(final String[] args) {
   MyServerServlets server = new MyServerServlets();
   try {
     server.run(args);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #19
0
ファイル: Macro.java プロジェクト: bramk/bnd
 public String _long2date(String args[]) {
   try {
     return new Date(Long.parseLong(args[1])).toString();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return "not a valid long";
 }
コード例 #20
0
 /**
  * closes all files
  *
  * @author [email protected]
  * @date Thu Dec 1 22:00:05 2011
  */
 void closeFiles() {
   try {
     m_wrMkdirs.close();
     m_wrChmods.close();
   } catch (Exception e) {
     System.err.println("ERROR: failed to close files: " + e.toString());
   }
 }
コード例 #21
0
 private void appendMsg(String msg) {
   HTMLDocument doc = (HTMLDocument) textArea.getDocument();
   HTMLEditorKit kit = (HTMLEditorKit) textArea.getEditorKit();
   try {
     kit.insertHTML(doc, doc.getLength(), msg, 0, 0, null);
   } catch (Exception e) {
     Debug.error(me + "Problem appending text to message area!\n%s", e.getMessage());
   }
 }
コード例 #22
0
ファイル: WordCountJ.java プロジェクト: flockom/cs553-prog2
  public static void main(String[] args) {
    Date start = new Date();
    if (args.length < 3) {
      System.out.println("Wrong number of arguments:\n" + USAGE);
      return;
    }

    // get # threads
    int tc = Integer.parseInt(args[0]);
    String outfile = args[1];

    // make a threadsafe queue of all files to process
    ConcurrentLinkedQueue<String> files = new ConcurrentLinkedQueue<String>();
    for (int i = 2; i < args.length; i++) {
      files.add(args[i]);
    }

    // hastable for results
    Hashtable<String, Integer> results = new Hashtable<String, Integer>(HASH_SIZE, LF);

    // spin up the threads
    Thread[] workers = new Thread[tc];
    for (int i = 0; i < tc; i++) {
      workers[i] = new Worker(files, results);
      workers[i].start();
    }

    // wait for them to finish
    try {
      for (int i = 0; i < tc; i++) {
        workers[i].join();
      }
    } catch (Exception e) {
      System.out.println("Caught Exception: " + e.getMessage());
    }

    // terminal output
    Date end = new Date();
    System.out.println(end.getTime() - start.getTime() + " total milliseconds");
    System.out.println(results.size() + " unique words");

    // sort results for easy comparison/verification
    List<Map.Entry<String, Integer>> sorted_results =
        new ArrayList<Map.Entry<String, Integer>>(results.entrySet());
    Collections.sort(sorted_results, new KeyComp());
    // file output
    try {
      PrintStream out = new PrintStream(outfile);
      for (int i = 0; i < sorted_results.size(); i++) {
        out.println(sorted_results.get(i).getKey() + "\t" + sorted_results.get(i).getValue());
      }
    } catch (Exception e) {
      System.out.println("Caught Exception: " + e.getMessage());
    }
  }
コード例 #23
0
ファイル: ProfileChooser.java プロジェクト: zhbaics/UWS-MTPP
 public ProfileChooser(
     SanBootView view, Backupable bakable, String title, boolean modal, int mode, int type) {
   super((Dialog) bakable, title, modal);
   try {
     jbInit();
     myInit(view, bakable, mode, type);
     pack();
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
コード例 #24
0
ファイル: AccessLevel.java プロジェクト: raulastu/TCProject
 // BEGIN CUT HERE
 public static void main(String[] args) {
   try {
     eq(0, (new AccessLevel()).canAccess(new int[] {0, 1, 2, 3, 4, 5}, 2), "DDAAAA");
     eq(1, (new AccessLevel()).canAccess(new int[] {5, 3, 2, 10, 0}, 20), "DDDDD");
     eq(2, (new AccessLevel()).canAccess(new int[] {}, 20), "");
     eq(3, (new AccessLevel()).canAccess(new int[] {34, 78, 9, 52, 11, 1}, 49), "DADADD");
   } catch (Exception exx) {
     System.err.println(exx);
     exx.printStackTrace(System.err);
   }
 }
コード例 #25
0
ファイル: JCanvas.java プロジェクト: xaleth09/Connect4-AI
 /** print the canvas scaled with factor <code>scale</code> */
 public void print(double scale) {
   printScale = scale;
   PrinterJob printJob = PrinterJob.getPrinterJob();
   printJob.setPrintable(this);
   if (printJob.printDialog()) {
     try {
       printJob.print();
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
 }
コード例 #26
0
 // BEGIN CUT HERE
 public static void main(String[] args) {
   try {
     eq(0, (new KnockoutTourney()).meetRival(16, 1, 2), 1);
     eq(1, (new KnockoutTourney()).meetRival(16, 8, 9), 4);
     eq(2, (new KnockoutTourney()).meetRival(1000, 20, 31), 4);
     eq(3, (new KnockoutTourney()).meetRival(65536, 1000, 35000), 16);
     eq(4, (new KnockoutTourney()).meetRival(60000, 101, 891), 10);
   } catch (Exception exx) {
     System.err.println(exx);
     exx.printStackTrace(System.err);
   }
 }
コード例 #27
0
 public static void main(String[] args) {
   try {
     eq(
         0,
         (new BallsSeparating_2())
             .minOperations(new int[] {1, 1, 1}, new int[] {1, 1, 1}, new int[] {1, 1, 1}),
         6);
     eq(
         1,
         (new BallsSeparating_2()).minOperations(new int[] {5}, new int[] {6}, new int[] {8}),
         -1);
     eq(
         2,
         (new BallsSeparating_2())
             .minOperations(
                 new int[] {4, 6, 5, 7}, new int[] {7, 4, 6, 3}, new int[] {6, 5, 3, 8}),
         37);
     eq(
         3,
         (new BallsSeparating_2())
             .minOperations(
                 new int[] {7, 12, 9, 9, 7},
                 new int[] {7, 10, 8, 8, 9},
                 new int[] {8, 9, 5, 6, 13}),
         77);
     eq(
         4,
         (new BallsSeparating_2())
             .minOperations(
                 new int[] {
                   842398, 491273, 958925, 849859, 771363, 67803, 184892, 391907, 256150, 75799
                 },
                 new int[] {
                   268944, 342402, 894352, 228640, 903885, 908656, 414271, 292588, 852057, 889141
                 },
                 new int[] {
                   662939, 340220, 600081, 390298, 376707, 372199, 435097, 40266, 145590, 505103
                 }),
         7230607);
     int[] a = new int[50];
     int[] b = new int[50];
     int[] c = new int[50];
     fill(a, 1);
     fill(b, 1);
     fill(c, 1);
     eq(5, (new BallsSeparating_2()).minOperations(a, b, c), 7230607);
   } catch (Exception exx) {
     System.err.println(exx);
     exx.printStackTrace(System.err);
   }
 }
コード例 #28
0
ファイル: ConsoleClient.java プロジェクト: Solgrid/armitage
  public void run() {
    Map read;
    boolean shouldRead = go_read;
    String command = null;
    long last = 0;

    try {
      /* swallow the banner if requested to do so */
      if (swallow) {
        readResponse();
      }

      while (shouldRead) {
        synchronized (listeners) {
          if (commands.size() > 0) {
            command = (String) commands.removeFirst();
          }
        }

        if (command != null) {
          _sendString(command);
          command = null;
          lastRead = System.currentTimeMillis();
        }

        long now = System.currentTimeMillis();
        if (this.window != null && !this.window.isShowing() && (now - last) < 1500) {
          /* check if our window is not showing... if not, then we're going to switch to a very reduced
          read schedule. */
        } else {
          read = readResponse();
          if (read == null || "failure".equals(read.get("result") + "")) {
            break;
          }

          processRead(read);
          last = System.currentTimeMillis();
        }

        Thread.sleep(100);

        synchronized (listeners) {
          shouldRead = go_read;
        }
      }
    } catch (Exception javaSucksBecauseItMakesMeCatchEverythingFuckingThing) {
      javaSucksBecauseItMakesMeCatchEverythingFuckingThing.printStackTrace();
    }
  }
コード例 #29
0
ファイル: WordCountJ.java プロジェクト: flockom/cs553-prog2
  public void run() {
    // each file is processed into a local hash table and then merged with the global results
    // this will cause much less contention on the global table, but still avoids a sequential
    // update
    Hashtable<String, Integer> local_results =
        new Hashtable<String, Integer>(WordCountJ.HASH_SIZE, WordCountJ.LF);
    // grab a file to work on
    String cf;
    while ((cf = files.poll()) != null) {
      try {
        BufferedReader input = new BufferedReader(new FileReader(cf));
        String text;
        // well go line-by-line... maybe this is not the fastest
        while ((text = input.readLine()) != null) {
          // parse words
          Matcher matcher = pattern.matcher(text);
          while (matcher.find()) {
            String word = matcher.group(1);
            if (local_results.containsKey(word)) {
              local_results.put(word, 1 + local_results.get(word));
            } else {
              local_results.put(word, 1);
            }
          }
        }
        input.close();
      } catch (Exception e) {
        System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
        return;
      }
      // merge local hashmap with shared one,could have a
      // seperate thread do this but that might be cheating

      Iterator<Map.Entry<String, Integer>> updates = local_results.entrySet().iterator();
      while (updates.hasNext()) {
        Map.Entry<String, Integer> kv = updates.next();
        String k = kv.getKey();
        Integer v = kv.getValue();
        synchronized (results) {
          if (results.containsKey(k)) {
            results.put(k, v + results.get(k));
          } else {
            results.put(k, v);
          }
        }
      }
      local_results.clear();
    }
  }
コード例 #30
0
  // BEGIN CUT HERE
  public static void main(String[] args) {
    try {
      eq(0, (new ImprovingStatistics_NOTSOLVED()).howManyGames(10, 8), 1);
      eq(1, (new ImprovingStatistics_NOTSOLVED()).howManyGames(100, 80), 6);
      eq(2, (new ImprovingStatistics_NOTSOLVED()).howManyGames(47, 47), -1);
      eq(3, (new ImprovingStatistics_NOTSOLVED()).howManyGames(99000, 0), 1000);
      eq(4, (new ImprovingStatistics_NOTSOLVED()).howManyGames(1000000000, 470000000), 19230770);
      eq(4, (new ImprovingStatistics_NOTSOLVED()).howManyGames(1750, 1015), 43);
      eq(4, (new ImprovingStatistics_NOTSOLVED()).howManyGames(32532, 3342), 266);

    } catch (Exception exx) {
      System.err.println(exx);
      exx.printStackTrace(System.err);
    }
  }