示例#1
0
文件: ZCM.java 项目: ZeroCM/zcm
  /**
   * Remove this particular regex/subscriber pair (UNTESTED AND API MAY CHANGE). If regex is null,
   * all subscriptions for 'sub' are cancelled. If subscriber is null, any previous subscriptions
   * matching the regular expression will be cancelled. If both 'sub' and 'regex' are null, all
   * subscriptions will be cancelled.
   */
  public void unsubscribe(String regex, ZCMSubscriber sub) {
    if (this.closed) throw new IllegalStateException();

    synchronized (this) {
      for (Provider p : providers) p.unsubscribe(regex);
    }

    // TODO: providers don't seem to use anything beyond first channel

    synchronized (subscriptions) {

      // Find and remove subscriber from list
      for (Iterator<SubscriptionRecord> it = subscriptions.iterator(); it.hasNext(); ) {
        SubscriptionRecord sr = it.next();

        if ((sub == null || sr.lcsub == sub) && (regex == null || sr.regex.equals(regex))) {
          it.remove();
        }
      }

      // Find and remove subscriber from map
      for (String channel : subscriptionsMap.keySet()) {
        for (Iterator<SubscriptionRecord> it = subscriptionsMap.get(channel).iterator();
            it.hasNext(); ) {
          SubscriptionRecord sr = it.next();

          if ((sub == null || sr.lcsub == sub) && (regex == null || sr.regex.equals(regex))) {
            it.remove();
          }
        }
      }
    }
  }
 private int[] getHashes(LireFeature feature) {
   // result = new int[maximumHits];
   hashingResultScoreDocs.clear();
   maxDistance = 0f;
   tmpScore = 0f;
   int rep = 0;
   LireFeature tmpFeature;
   for (Iterator<LireFeature> iterator = representatives.iterator(); iterator.hasNext(); ) {
     tmpFeature = iterator.next();
     tmpScore = tmpFeature.getDistance(feature);
     if (hashingResultScoreDocs.size() < maximumHits) {
       hashingResultScoreDocs.add(new SimpleResult(tmpScore, null, rep));
       maxDistance = Math.max(maxDistance, tmpScore);
     } else if (tmpScore < maxDistance) {
       hashingResultScoreDocs.add(new SimpleResult(tmpScore, null, rep));
     }
     while (hashingResultScoreDocs.size() > maximumHits) {
       hashingResultScoreDocs.remove(hashingResultScoreDocs.last());
       maxDistance = hashingResultScoreDocs.last().getDistance();
     }
     rep++;
   }
   rep = 0;
   for (Iterator<SimpleResult> iterator = hashingResultScoreDocs.iterator();
       iterator.hasNext(); ) {
     SimpleResult next = iterator.next();
     result[rep] = next.getIndexNumber();
     rep++;
   }
   return result;
 }
示例#3
0
  public static void main(String[] args) throws FileNotFoundException {
    String s;

    ArrayList<String> AL = new ArrayList<String>();
    AL.add("one");
    AL.add("two");
    AL.add("three");
    AL.add("four");
    AL.add("five");
    AL.add("six");
    System.out.println("ArrayList (iterator) " + AL);
    Iterator<String> it = AL.iterator();
    while (it.hasNext()) {
      s = it.next();
      System.out.println("AL: " + s);
    }
    System.out.println();

    myList ml = new myList();
    ml.add(20);
    ml.add(50);
    ml.add(12);
    ml.add(13);
    ml.add(53);
    ml.add(33);
    ml.add(23);

    System.out.println(ml);
    Iterator<Integer> mlit = ml.iterator();
    while (mlit.hasNext()) {
      System.out.println(mlit.next());
    }
  }
  private void func_22181_a(
      File file, ArrayList arraylist, int i, int j, IProgressUpdate iprogressupdate) {
    Collections.sort(arraylist);
    byte abyte0[] = new byte[4096];
    int i1;
    for (Iterator iterator = arraylist.iterator();
        iterator.hasNext();
        iprogressupdate.setLoadingProgress(i1)) {
      ChunkFile chunkfile = (ChunkFile) iterator.next();
      int k = chunkfile.func_22323_b();
      int l = chunkfile.func_22321_c();
      RegionFile regionfile = RegionFileCache.func_22193_a(file, k, l);
      if (!regionfile.func_22202_c(k & 0x1f, l & 0x1f)) {
        try {
          DataInputStream datainputstream =
              new DataInputStream(
                  new GZIPInputStream(new FileInputStream(chunkfile.func_22324_a())));
          DataOutputStream dataoutputstream =
              regionfile.getChunkDataOutputStream(k & 0x1f, l & 0x1f);
          for (int j1 = 0; (j1 = datainputstream.read(abyte0)) != -1; ) {
            dataoutputstream.write(abyte0, 0, j1);
          }

          dataoutputstream.close();
          datainputstream.close();
        } catch (IOException ioexception) {
          ioexception.printStackTrace();
        }
      }
      i++;
      i1 = (int) Math.round((100D * (double) i) / (double) j);
    }

    RegionFileCache.func_22192_a();
  }
  /**
   * Submit a request to the server which expects a list of execution items in the response, and
   * return a single QueuedItemResult parsed from the response.
   *
   * @param tempxml xml temp file (or null)
   * @param otherparams parameters for the request
   * @param requestPath
   * @return a single QueuedItemResult
   * @throws com.dtolabs.rundeck.core.dispatcher.CentralDispatcherException if an error occurs
   */
  private QueuedItemResult submitExecutionRequest(
      final File tempxml, final HashMap<String, String> otherparams, final String requestPath)
      throws CentralDispatcherException {

    final HashMap<String, String> params = new HashMap<String, String>();
    if (null != otherparams) {
      params.putAll(otherparams);
    }

    final WebserviceResponse response;
    try {
      response = serverService.makeRundeckRequest(requestPath, params, tempxml, null);
    } catch (MalformedURLException e) {
      throw new CentralDispatcherServerRequestException("Failed to make request", e);
    }
    validateResponse(response);

    final ArrayList<QueuedItem> list = parseExecutionListResult(response);
    if (null == list || list.size() < 1) {

      return QueuedItemResultImpl.failed("Server response contained no success information.");
    } else {

      final QueuedItem next = list.iterator().next();
      return QueuedItemResultImpl.successful(
          "Succeeded queueing " + next.getName(), next.getId(), next.getUrl(), next.getName());
    }
  }
  public Iterator handlePixels(Image img, Rectangle rect) {
    int x = rect.x;
    int y = rect.y;
    int w = rect.width;
    int h = rect.height;

    int[] pixels = new int[w * h];
    PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);
    try {
      pg.grabPixels();
    } catch (InterruptedException e) {
      System.err.println("interrupted waiting for pixels!");
      return null;
    }
    if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
      System.err.println("image fetch aborted or errored");
      return null;
    }
    ArrayList tmpList = new ArrayList();
    for (int j = 0; j < h; j++) {
      for (int i = 0; i < w; i++) {
        tmpList.add(handleSinglePixel(x + i, y + j, pixels[j * w + i]));
      }
    }
    return tmpList.iterator();
  }
示例#7
0
  public static void main(String args[]) {
    int N;
    Scanner in = new Scanner(System.in);
    N = in.nextInt();
    int arr[] = new int[N];
    ArrayList even = new ArrayList();
    ArrayList odd = new ArrayList();
    ArrayList list = new ArrayList();

    for (int i = 0; i < N; i++) {
      arr[i] = in.nextInt();
    }
    int evenSum = 0;
    int oddSum = 0;
    for (int i = 0; i < N; i++) {
      if (arr[i] % 2 == 0) {
        even.add(arr[i]);
        evenSum = evenSum + arr[i];
      } else {
        odd.add(arr[i]);
        oddSum = oddSum + arr[i];
      }
    }
    even.add(evenSum);
    odd.add(oddSum);
    Collections.sort(even);
    Collections.sort(odd);
    list.addAll(even);
    list.addAll(odd);
    Iterator itr = list.iterator();
    while (itr.hasNext()) {
      System.out.println(itr.next());
    }
  }
示例#8
0
  public void updateConnectionStatus(boolean connected) {
    if (connected == true) {
      headerPanel.setLogoutText();
      loginMenuItem.setText("Logout");
    } else {
      headerPanel.setLoginText();
      loginMenuItem.setText("Login...");
    }
    mainCommandPanel.updateConnectionStatus(connected);
    propertiePanel.updateConnectionStatus(connected);
    cmdConsole.updateConnectionStatus(connected);
    Iterator iterator = plugins.iterator();
    PluginPanel updatePluginPanel = null;
    while (iterator.hasNext()) {
      updatePluginPanel = (PluginPanel) iterator.next();
      updatePluginPanel.updateConnectionStatus(connected);
    }

    if (connected == true) {
      int selected = tabbedPane.getSelectedIndex();
      if (selected >= 2) {
        ((PluginPanel) pluginPanelMap.get("" + selected)).activated();
      }
    }
  }
示例#9
0
  /**
   * Estimates the mean of array <code>y</code>. <code>robustMu</code> uses a Gaussian model to
   * remove outliers iteratively.
   *
   * @param y an array
   * @return the estimated mean of <code>y</code>
   */
  private double robustMu(double[] y) {

    ArrayList<Double> x = new ArrayList<Double>(y.length);

    for (int i = 0; i < y.length; i++) {
      x.add(y[i]);
    }

    double sigma = 0;
    NormalDist gaussian = new NormalDist();
    double cutoff = 0;
    double cutoff1 = 0;
    double cutoff2 = 0;

    int xSize = x.size();

    sigma = std(x);
    double areaRemoved = 0.5 / xSize;

    cutoff = abs(gaussian.inverseF(areaRemoved));

    cutoff1 = -cutoff * sigma + mean(x);
    cutoff2 = cutoff * sigma + mean(x);

    while (true) {

      Iterator<Double> iter = x.iterator();

      int numRemoved = 0;
      while (iter.hasNext()) {

        double cn = iter.next();
        if (cn < cutoff1 || cn > cutoff2) {
          numRemoved++;
          iter.remove();
        }
      }

      if (numRemoved == 0) {
        break;
      }

      sigma = std(x);
      sigma =
          sigma
              / sqrt(
                  (1 - 2 * areaRemoved - 2 * cutoff * exp(-pow(cutoff, 2) / 2) / sqrt(2 * PI))
                      / (1 - 2 * areaRemoved));

      xSize = x.size();
      areaRemoved = 0.5 / xSize;

      cutoff = abs(gaussian.inverseF(areaRemoved));

      cutoff1 = -cutoff * sigma + mean(x);
      cutoff2 = cutoff * sigma + mean(x);
    }

    return mean(x);
  }
 InstanceListModel(ASDGrammar grammar, String word) {
   ArrayList instanceList = grammar.lookupWord(word);
   for (Iterator it = instanceList.iterator(); it.hasNext(); ) {
     ASDGrammarNode n = (ASDGrammarNode) it.next();
     String instance = (String) n.instance();
     this.addElement(instance);
   }
 }
    @DataProvider(name = "placeOrderCredentials")
    public Iterator<Object[]> readFromExcelIterator() throws FileNotFoundException, IOException {
      //	prop.load(getClass().getResourceAsStream("AutomationEnv.properties"));
      // String sourceXlsFileName=(String)prop.get("signUpAndOrderCard");
      String fileName =
          "C:\\Users\\WINQA\\workspace\\NewHkAutomationSuite\\Excel\\signUpandPlace.xls";
      int sheetNo = 0;
      ArrayList<Object[]> excelDataArray = new ArrayList<Object[]>();
      int cnt = 0;
      try {

        InputStream input = new BufferedInputStream(new FileInputStream(fileName));

        POIFSFileSystem fs = new POIFSFileSystem(input);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(sheetNo);

        Iterator rows = sheet.rowIterator();

        while (rows.hasNext()) {
          int cellCount = 0;
          int flagStop = 0;
          HSSFRow row = (HSSFRow) rows.next();
          System.out.println("\n");
          Iterator cells = row.cellIterator();

          List<String> readExcelData = new LinkedList<String>();

          while (cells.hasNext()) {
            if (cellCount <= 10) {
              int cellValueInt;
              String CellValue;
              HSSFCell cell = (HSSFCell) cells.next();

              if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
                // System.out.print( cell.getNumericCellValue()+"     " );
                cellValueInt = (int) cell.getNumericCellValue();
                CellValue = Integer.toString(cellValueInt);
              } else {
                CellValue = cell.getStringCellValue();
              }
              readExcelData.add(CellValue);
              cnt++;

              cellCount++;
            }

            if (cellCount == 11) break;
          }
          excelDataArray.add(new Object[] {readExcelData});
        }

      } catch (IOException ex) {
        ex.printStackTrace();
      }
      return excelDataArray.iterator();
    }
示例#12
0
 public static double Average(ArrayList l) {
   double accum = 0.0d;
   Iterator i = l.iterator();
   while (i.hasNext()) {
     Double d = (Double) i.next();
     accum += d.doubleValue();
   }
   return (accum / (double) l.size());
 }
 public void addListener(DMoteModelListener listener) {
   if (listeners == null) listeners = new ArrayList();
   Iterator it = listeners.iterator();
   while (it.hasNext()) {
     if (it.next() == listener) return;
   }
   ;
   listeners.add(listener);
 }
 /** Close archive for further access. It should still be possible to get attributes. */
 public void close() {
   if (archives != null) {
     for (Iterator i = archives.iterator(); i.hasNext(); ) {
       ((Archive) i.next()).close();
     }
     archives = null;
   }
   archive.close();
 }
 public static Alumno buscarAlumnoPorMatricula(ArrayList arrayL, int num) {
   Alumno alum = null;
   // Object aux = null;
   Iterator it = arrayL.iterator();
   while (it.hasNext()) {
     alum = (Alumno) it.next();
     if (alum.numeroMatricula == num) return alum;
   }
   return alum;
 }
示例#16
0
 public static String PrintList(ArrayList l) {
   StringBuffer sb = new StringBuffer("[ ");
   Iterator i = l.iterator();
   while (i.hasNext()) {
     Double d = (Double) i.next();
     sb.append(MDP._df.format(d.doubleValue()) + " ");
   }
   sb.append("]");
   return sb.toString();
 }
 public void removeListener(DMoteModelListener listener) {
   if (listeners == null) return;
   Iterator it = listeners.iterator();
   while (it.hasNext()) {
     if (it.next() == listener) {
       it.remove();
       return;
     }
   }
 }
示例#18
0
 public void initAgents(ArrayList machineAgentArray) {
   fUGeneralStrategy = new UBaseAgent("su", "supasswd", "Super User", 0);
   fServer.appendStrategy(fUGeneralStrategy);
   fCProtocol = fUGeneralStrategy.getUmcp();
   fCommandHashMap = fCProtocol.getCommandHashMap();
   Iterator iter = machineAgentArray.iterator();
   while (iter.hasNext()) {
     fServer.appendStrategy((UBaseAgent) iter.next());
   }
 }
示例#19
0
 public long getEstimatedMaximumOutputLength() {
   long estimatedMaximumOutputLength = sourceText.length();
   for (final Iterator i = outputSegments.iterator(); i.hasNext(); ) {
     final OutputSegment outputSegment = (OutputSegment) i.next();
     final int outputSegmentOriginalLength = outputSegment.getEnd() - outputSegment.getBegin();
     estimatedMaximumOutputLength +=
         (outputSegment.getEstimatedMaximumOutputLength() - outputSegmentOriginalLength);
   }
   return estimatedMaximumOutputLength >= 0L ? estimatedMaximumOutputLength : -1L;
 }
示例#20
0
 public static String PrintState(ArrayList state) {
   StringBuffer sb = new StringBuffer();
   Iterator i = state.iterator();
   while (i.hasNext()) {
     Object o = i.next();
     if (o instanceof Boolean) {
       Boolean val = (Boolean) o;
       sb.append((val.booleanValue() ? "." : "X"));
     }
   }
   return sb.toString();
 }
示例#21
0
  public void run() {
    ArrayList<Double> output = new ArrayList();

    while (true) {
      int numStudents = Integer.parseInt(Main.ReadLn(1000000));

      double runningTotal = 0;
      double current = 0;
      double average = 0;
      double runningTransfer = 0;

      if (numStudents == 0) break;
      else if (numStudents > 1000) throw new NumberFormatException();
      else if (numStudents % 2 == 0) throw new NumberFormatException();

      ArrayList<Double> expenses = new ArrayList();

      for (int i = 0; i < numStudents; i++) {
        current = Double.parseDouble(Main.ReadLn(1000000));
        runningTotal = runningTotal + current;

        expenses.add(current);

        if (current > 10000 || current < 0) throw new NumberFormatException();
      }

      average = Math.floor((runningTotal * 100) / numStudents) / 100;

      for (Double d : expenses) {
        if (d.doubleValue() < average) {
          runningTransfer = runningTransfer + (average - d.doubleValue());
        }
      }

      output.add(runningTransfer);
    }

    Iterator it = output.iterator();
    StringBuilder builder = new StringBuilder();

    while (it.hasNext()) {
      builder.append("$" + String.format("%.2f", it.next()));

      if (it.hasNext()) {
        builder.append("\n");
      } else {
        break;
      }
    }

    System.out.println(builder);
  }
示例#22
0
 public void printDebug() {
   Iterator<StringBuilder> it = rows.iterator();
   int i = 0;
   System.out.println(
       "    " + StringUtils.repeatString("0123456789", (int) Math.floor(getWidth() / 10) + 1));
   while (it.hasNext()) {
     String row = it.next().toString();
     String index = Integer.toString(i);
     if (i < 10) index = " " + index;
     System.out.println(index + " (" + row + ")");
     i++;
   }
 }
 private void func_22182_a(ArrayList arraylist, int i, int j, IProgressUpdate iprogressupdate) {
   int k;
   for (Iterator iterator = arraylist.iterator();
       iterator.hasNext();
       iprogressupdate.setLoadingProgress(k)) {
     File file = (File) iterator.next();
     File afile[] = file.listFiles();
     func_22179_a(afile);
     file.delete();
     i++;
     k = (int) Math.round((100D * (double) i) / (double) j);
   }
 }
  public void sendToAll(String msg) {
    Iterator it = clientOutputStream.iterator();

    while (it.hasNext()) {
      try {
        PrintWriter writer = (PrintWriter) it.next();
        writer.println(msg);
        writer.flush();

      } catch (Exception ex) {
      }
    }
  } // end send ToAll
 public static Alumno buscarAlumnoPorNombre(ArrayList arrayL, String nombre) {
   boolean encontrado = false;
   Alumno alum = null;
   // Object aux = null;
   Iterator it = arrayL.iterator(); // Declaro iterator (es como scanner)
   while (it.hasNext() && !encontrado) {
     alum = (Alumno) it.next();
     if (nombre.equalsIgnoreCase(alum.nombre)) {
       encontrado = true;
       return alum;
     }
   }
   return alum;
 }
示例#26
0
 public static void parseDocumentFragment(Reader reader, XMLReceiver xmlReceiver)
     throws SAXException {
   try {
     final XMLReader xmlReader = newSAXParser(XMLUtils.ParserConfiguration.PLAIN).getXMLReader();
     xmlReader.setContentHandler(new XMLFragmentReceiver(xmlReceiver));
     final ArrayList<Reader> readers = new ArrayList<Reader>(3);
     readers.add(new StringReader("<root>"));
     readers.add(reader);
     readers.add(new StringReader("</root>"));
     xmlReader.parse(new InputSource(new SequenceReader(readers.iterator())));
   } catch (IOException e) {
     throw new OXFException(e);
   }
 }
示例#27
0
 private void writeSendingHashMap(PrintWriter pw, String indent, HashMap item, String hashName) {
   String coreClassName = "UC" + fCmdDef.getCmdName() + "Core";
   String type = (String) item.get("TYPE");
   ArrayList contents = (ArrayList) item.get("CONTENTS");
   Iterator itr = contents.iterator();
   while (itr.hasNext()) {
     HashMap item2 = (HashMap) itr.next();
     String type2 = (String) item2.get("TYPE");
     String name2 = (String) item2.get("NAME");
     String key2 = Utility.makeKeyString(type2, name2);
     String comment2 = (String) item2.get("COMMENT");
     String localVariableName = Utility.makeLocalVariable(name2);
     if (type2.equals("HashMap")) {
       pw.print(
           indent
               + "HashMap "
               + localVariableName
               + " = (HashMap)"
               + hashName
               + ".get("
               + coreClassName
               + "."
               + key2
               + ");");
       pw.println(" // " + comment2);
       writeSendingHashMap(pw, indent, item2, localVariableName);
     } else if (type2.equals("ArrayList")) {
       pw.print(
           indent
               + "ArrayList "
               + localVariableName
               + " = (ArrayList)"
               + hashName
               + ".get("
               + coreClassName
               + "."
               + key2
               + ");");
       pw.println(" // " + comment2);
       writeSendingArrayList(pw, indent, item2, localVariableName);
     } else {
       String str = indent + "fAgent.sendMessage(" + hashName + ".get(";
       str += "UC" + fCmdDef.getCmdName() + "Core." + key2 + ").toString());";
       pw.print(str);
       pw.println(" // " + comment2);
     }
   }
 }
示例#28
0
  /**
   * Returns true if the String data contains any of the Strings contained in the ArrayList.
   *
   * @param data - A string that we will search
   * @param matches - An ArrayList that contains only Strings. We will search data to see if any of
   *     the Strings in matches are found in data.
   * @return String - the first string in matches that was found in data, or null if no match was
   *     found.
   */
  public static String containsAnyStrings(String data, ArrayList matches) {
    final String METHOD_NAME = "containsAnyStrings(): ";

    if (null == data || null == matches) {
      return null;
    }

    Iterator iter = matches.iterator();
    while (iter.hasNext()) {
      String test = (String) iter.next();
      if (-1 != data.indexOf(test)) {
        return test;
      }
    }
    return null;
  }
  /** Fire hostDisconnectEvent events. */
  void fireDisconnectedEvents() {
    ArrayList registered = null;
    HostEvent ev = null;

    synchronized (listeners) {
      registered = (ArrayList) listeners.clone();
    }

    for (Iterator i = registered.iterator(); i.hasNext(); /* empty */ ) {
      HostListener l = (HostListener) i.next();
      if (ev == null) {
        ev = new HostEvent(this);
      }
      l.disconnected(ev);
    }
  }
示例#30
0
  /** Print it! */
  public String printClusters(Cluster clustering, float threshold, HTMLFile f) {
    int maxSize = 0;

    ArrayList<Cluster> clusters = getClusters(clustering, threshold);

    for (Iterator<Cluster> i = clusters.iterator(); i.hasNext(); ) {
      Cluster cluster = i.next();
      if (cluster.size() > maxSize) maxSize = cluster.size();
    }

    TreeSet<Cluster> sorted = new TreeSet<Cluster>(clusters);
    clusters = null;

    // Now print them:
    return outputClustering(f, sorted, maxSize);
  }