Beispiel #1
1
  protected void computeEdgeAndThreadNo() {
    Iterator it = iterator();
    int numberOfEdge = 0;
    while (it.hasNext()) {
      List succList = (List) getSuccsOf(it.next());

      numberOfEdge = numberOfEdge + succList.size();
    }
    numberOfEdge = numberOfEdge + startToThread.size();

    System.err.println("**number of edges: " + numberOfEdge);

    System.err.println("**number of threads: " + (startToThread.size() + 1));

    /*	Set keySet = startToThread.keySet();
    Iterator keyIt = keySet.iterator();
    while (keyIt.hasNext()){
    List list = (List)startToThread.get(keyIt.next());
    System.out.println("********start thread:");
    Iterator itit = list.iterator();
    while (itit.hasNext()){
    System.out.println(it.next());
    }
    }
    */

  }
Beispiel #2
1
  /**
   * Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and values themselves are
   * not cloned.
   *
   * @return a shallow copy of this map
   */
  public Object clone() {
    HashMap<K, V> result = null;
    try {
      result = (HashMap<K, V>) super.clone();
    } catch (CloneNotSupportedException e) {
      // assert false;
    }
    result.table = new Entry[table.length];
    result.entrySet = null;
    result.modCount = 0;
    result.size = 0;
    result.init();
    result.putAllForCreate(this);

    return result;
  }
 public Bed2Bar(String[] args) {
   try {
     processArgs(args);
     // load Window[]
     for (int i = 0; i < bedFiles.length; i++) {
       bedFile = bedFiles[i];
       System.out.println("Parsing " + bedFile.getName());
       bedLinesHash = Bed.parseBedFile(bedFile, true, false);
       if (bedLinesHash == null || bedLinesHash.size() == 0) {
         System.out.println("Problem parsing bed file, skipping!");
         continue;
       }
       barDirectory = IO.makeDirectory(bedFile, "");
       File bedOutFile =
           new File(Misc.removeExtension(bedFile.toString()) + "_" + threshold + "_Filt.bed");
       bedOut = new PrintWriter(new FileWriter(bedOutFile));
       makeStairStepBarFiles();
     }
     bedOut.close();
     System.out.println("\nDone!\n");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  public final String correct(String word) {
    if (nWords.containsKey(word)) return word;
    ArrayList<String> list = edits(word);
    HashMap<Integer, String> candidates = new HashMap<Integer, String>();
    for (String s : list) if (nWords.containsKey(s)) candidates.put(nWords.get(s), s);

    if (candidates.size() > 0) return candidates.get(Collections.max(candidates.keySet()));
    return candidates.size() > 0 ? candidates.get(Collections.max(candidates.keySet())) : word;
  }
  /**
   * Return top K authorities (result from SALSA), but do not include users in the removeList
   *
   * @param K
   * @param removeList
   * @return
   */
  public ArrayList<SalsaVertex> topAuthorities(int K, HashSet<Integer> removeList) {
    // TODO: faster top-K implementation
    ArrayList<SalsaVertex> all = new ArrayList<SalsaVertex>(authorities.size());
    all.addAll(authorities.values());
    Collections.sort(
        all,
        new Comparator<SalsaVertex>() {
          @Override
          public int compare(SalsaVertex salsaVertex, SalsaVertex salsaVertex1) {
            if (salsaVertex.value < salsaVertex1.value) return 1;
            else return (salsaVertex.value > salsaVertex1.value ? -1 : 0);
          }
        });

    ArrayList<SalsaVertex> result = new ArrayList<SalsaVertex>(K);
    int i = 0;
    while (result.size() < K) {
      if (i < all.size()) {
        SalsaVertex x = all.get(i);
        if (!removeList.contains(x.id)) result.add(x);
      } else {
        break;
      }
      i++;
    }
    return result;
  }
Beispiel #6
0
  private static void convertToInlinkMap(
      HashMap<String, Set<String>> outlinkmapping, HashMap<String, JSONArray> inlinkmapping)
      throws Exception, FileNotFoundException {
    Iterator<String> keys = outlinkmapping.keySet().iterator();
    System.out.println("outlink map count " + outlinkmapping.size());
    while (keys.hasNext()) {
      String key = (String) keys.next();
      Set<String> s = outlinkmapping.get(key);
      ArrayList<String> a = new ArrayList<String>(s);
      // System.out.println("Started for "+count++ + + outlinkmapping.size() +a.size());

      for (int i = 0; i < a.size(); i++) {
        String inlink = a.get(i);
        if (outlinkmapping.containsKey(inlink)) {
          Object inlinks =
              inlinkmapping.containsKey(inlink) ? inlinkmapping.get(inlink) : new JSONArray();
          ((JSONArray) inlinks).add(key);
          inlinkmapping.put(inlink, (JSONArray) inlinks);
        }
      }
      // System.out.println("Endded for "+count++  + "  " + outlinkmapping.size() +"  "+a.size());
    }
    System.out.println("inlink map count " + inlinkmapping.size());

    System.out.println("Done");
  }
Beispiel #7
0
 public void disconnect(boolean hard) throws IOException {
   synchronized (setupDiscoLock) {
     synchronized (this) {
       switch (state) {
         case 0: /* not connected - just return */
           return;
         case 2:
           hard = true;
         case 3: /* connected - go ahead and disconnect */
           if (response_map.size() != 0 && !hard) {
             break; /* outstanding requests */
           }
           doDisconnect(hard);
         case 4: /* in error - reset the transport */
           thread = null;
           state = 0;
           break;
         default:
           if (log.level >= 1) log.println("Invalid state: " + state);
           thread = null;
           state = 0;
           break;
       }
     }
   }
 }
  /**
   * This method is used to get String[] of the propertise file name that are cached.
   *
   * @return String[].
   */
  public static String[] getCachedPropertiesFilenames() {
    synchronized (cachedPropertyFiles) {
      int i = 0;
      String[] filenames = new String[cachedPropertyFiles.size()];

      for (Iterator e = cachedPropertyFiles.keySet().iterator(); e.hasNext(); i++) {
        filenames[i++] = (String) e.next();
      }
      return filenames;
    }
  }
Beispiel #9
0
  /**
   * Reads the data from database and writes into detectors hashmap
   *
   * @throws SQLException
   */
  public void readDataIntoDetectorListFromDatabase() throws SQLException {

    // TestConfiguration.dbSetup();

    PeMSStationAggregateReader stationAggregateReader =
        new PeMSStationAggregateReader(oraDatabase.doConnect());
    ArrayList<Long> vdsIDs = new ArrayList<Long>();

    for (int key : detectors.keySet()) {
      vdsIDs.add((long) key);
    }
    List<PeMSStationAggregate> stationsAggregate =
        stationAggregateReader.read(
            this.timeInterval, vdsIDs, PeMSAggregate.AggregationLevel.PEMS_5MIN);

    // Read absolute detector info into the hashmap
    VDSReader stationReader = new VDSReader(oraDatabase.doConnect());
    for (int key : detectors.keySet()) {
      VDS station = stationReader.read((long) key);
      Detector d = detectors.get(key);
      d.setAbsolutePM(station.getAbsolutePostmile());
      d.setDetectorLength(station.getDetectorLength());
      d.setDetectorName(station.getDetectorName());
      d.setFreewayDirection(station.getDirection());
      d.setFreewayNumber(station.getFreewayNum());
      d.setLatitude(station.getPosition().getPoint().get(0).getLat());
      d.setLongitude(station.getPosition().getPoint().get(0).getLng());
      d.setNumberOfLanes(station.getLaneCount());
    }

    // Read 5 minute data into the hashmap
    for (int i = 0; i < stationsAggregate.size(); i++) {
      // find the detector corresponding to the current ID in the data vector and fill the fields
      // accordingly
      Detector d = detectors.get((int) stationsAggregate.get(i).getVdsId());
      d.addDatumToSpeed(stationsAggregate.get(i).getTotal().getAvgSpeed());
      d.addDatumToFlow(
          stationsAggregate.get(i).getTotal().getFlow()
              * 12
              / d
                  .getNumberOfLanes()); // to get the hourly rate at 5 minute granularity, multiply
                                        // by 12
      d.addDatumToDensity(
          stationsAggregate.get(i).getTotal().getFlow()
              * 12
              / stationsAggregate.get(i).getTotal().getAvgSpeed()
              / d.getNumberOfLanes());
      if (i < detectors.size()) {
        d.setHealthStatus(stationsAggregate.get(i).getTotal().getObserved());
      }
    }
  }
  public void dump() throws RemoteException {
    int num_ins = instances.size();

    System.out.println(getServerName() + ":");

    for (int i = 1; i <= num_ins; i++) {
      Instance tmp = instances.get(i);

      System.out.println(i + ": " + tmp.toString());
    }

    return;
  }
Beispiel #11
0
  private boolean equalsAccessPoints(HashMap<String, AccessPoint> accessPoints) {
    if (this.accessPoints == null && accessPoints == null) {
      return true;
    } else if (this.accessPoints == null
        || accessPoints == null
        || this.accessPoints.size() != accessPoints.size()) {
      return false;
    }

    Set<String> localAccessPointsIds = this.accessPoints.keySet();
    Set<String> otherAccessPointsIds = accessPoints.keySet();

    return localAccessPointsIds.containsAll(otherAccessPointsIds);
  }
  /**
   * skip initialGuarded
   *
   * @param offset
   * @param length
   * @return true if skip
   */
  protected boolean skipInitialGuarded(int offset) {
    Debug.log(
        this,
        "CollabJavaHandler, skipInitialGuarded, "
            + "	otherGuardedSections size: "
            + otherGuardedSections.size()); // NoI18n

    Iterator it = this.otherGuardedSections.values().iterator();
    while (it.hasNext()) {
      GuardedSection sect = (GuardedSection) it.next();
      int beginOffset = sect.getStartPosition().getOffset();
      int endOffset = sect.getEndPosition().getOffset();
      if ((offset >= beginOffset) && (offset <= endOffset)) return true;
    }
    return false;
  }
Beispiel #13
0
    void bundleAndSend() {
      Map.Entry entry;
      IpAddress dest;
      ObjectOutputStream out;
      InetAddress addr;
      int port;
      byte[] data;
      List l;

      if (Trace.trace) {
        Trace.info(
            "UDP.BundlingOutgoingPacketHandler.bundleAndSend()",
            "\nsending msgs:\n" + dumpMessages(msgs));
      }
      synchronized (msgs) {
        stopTimer();

        if (msgs.size() == 0) {
          return;
        }

        for (Iterator it = msgs.entrySet().iterator(); it.hasNext(); ) {
          entry = (Map.Entry) it.next();
          dest = (IpAddress) entry.getKey();
          addr = dest.getIpAddress();
          port = dest.getPort();
          l = (List) entry.getValue();
          try {
            out_stream.reset();
            // BufferedOutputStream bos=new BufferedOutputStream(out_stream);
            out_stream.write(Version.version_id, 0, Version.version_id.length); // write the version
            // bos.write(Version.version_id, 0, Version.version_id.length); // write the version
            out = new ObjectOutputStream(out_stream);
            // out=new ObjectOutputStream(bos);
            l.writeExternal(out);
            out.close(); // needed if out buffers its output to out_stream
            data = out_stream.toByteArray();
            doSend(data, addr, port);
          } catch (IOException e) {
            Trace.error(
                "UDP.BundlingOutgoingPacketHandle.bundleAndSend()",
                "exception sending msg (to dest=" + dest + "): " + e);
          }
        }
        msgs.clear();
      }
    }
  public void apply(Node.Nodes page, ErrorDispatcher err, PageInfo pageInfo)
      throws JasperException {

    init(err);
    if (tagPlugins == null || tagPlugins.size() == 0) {
      return;
    }

    this.pageInfo = pageInfo;

    page.visit(
        new Node.Visitor() {
          public void visit(Node.CustomTag n) throws JasperException {
            invokePlugin(n);
            visitBody(n);
          }
        });
  }
 public static void reportGeneratorMap(HashMap map, String topic, File reportFile)
     throws FileNotFoundException, UnsupportedEncodingException {
   boolean fileCreation = false;
   if (!reportFile.exists()) {
     try {
       fileCreation = reportFile.createNewFile();
     } catch (IOException e) {
       log.error("Report file creation failure", e);
     }
     log.info("Report file creation status " + fileCreation);
   }
   OutputStreamWriter writer =
       new OutputStreamWriter(new FileOutputStream(reportFile, true), "UTF-8");
   BufferedWriter outStream = new BufferedWriter(writer);
   try {
     outStream.write(topic);
     outStream.write("\n");
     outStream.write("----------------------------------------------------------");
     outStream.write("\n");
     if (map.size() == 0) {
       outStream.write("None" + "\n");
     } else {
       Set set = map.entrySet();
       for (Object item : set) {
         Map.Entry me = (Map.Entry) item;
         outStream.write(me.getKey().toString());
         outStream.write("\n");
         outStream.write(" - " + me.getValue());
         outStream.write("\n");
       }
     }
     outStream.write("----------------------------------------------------------");
     outStream.write("\n");
     outStream.write("\n");
   } catch (IOException e) {
     log.error("Report Generator Map - error while writing to file" + e);
   } finally {
     try {
       outStream.close();
     } catch (IOException e) {
       log.error("Report Generator Map - error while closing the stream" + e);
     }
   }
 }
    public void draw() {
      if (_pointLists.size() <= 0) return;

      pushStyle();
      noFill();

      PVector vec;
      PVector firstVec;
      PVector screenPos = new PVector();
      int colorIndex = 0;

      // draw the hand lists
      Iterator<Map.Entry> itrList = _pointLists.entrySet().iterator();
      while (itrList.hasNext()) {
        strokeWeight(2);
        stroke(_colorList[colorIndex % (_colorList.length - 1)]);

        ArrayList curList = (ArrayList) itrList.next().getValue();

        // draw line
        firstVec = null;
        Iterator<PVector> itr = curList.iterator();
        beginShape();
        while (itr.hasNext()) {
          vec = itr.next();
          if (firstVec == null) firstVec = vec;
          // calc the screen pos
          context.convertRealWorldToProjective(vec, screenPos);
          vertex(screenPos.x, screenPos.y);
        }
        endShape();

        // draw current pos of the hand
        if (firstVec != null) {
          strokeWeight(8);
          context.convertRealWorldToProjective(firstVec, screenPos);
          point(screenPos.x, screenPos.y);
        }
        colorIndex++;
      }

      popStyle();
    }
  /**
   * Add multiple new nodes (SpeciesZoneType objects) to a manipulation and then submit. HJR
   *
   * @param manipSpeciesMap - species being added
   * @param fullSpeciesMap - full list; for predator/prey info
   * @param timestep
   * @param isFirstManipulation
   * @param networkOrManipulationId
   * @return manipulation ID (String)
   * @throws SimulationException
   */
  public String addMultipleSpeciesType(
      HashMap<Integer, SpeciesZoneType> manipSpeciesMap,
      HashMap<Integer, SpeciesZoneType> fullSpeciesMap,
      int timestep,
      boolean isFirstManipulation,
      String networkOrManipulationId) {

    // job.setNode_Config("5,
    // [5],2000,1.000,1,K=9431.818,0,
    // [14],1751,20.000,1,X=0.273,0,
    // [31],1415,0.008,1,X=1.000,0,
    // [42],240,0.205,1,X=0.437,0,
    // [70],2494,13.000,1,X=0.155,0");

    //		  		  In addMultipleSpeciesType: node [70], biomass 2494, K = -1, R = -1.0000, X = 0.1233
    //				  In addMultipleSpeciesType: node [5], biomass 2000, K = 10000, R = 1.0000, X = 0.5000
    //				  In addMultipleSpeciesType: node [42], biomass 240, K = -1, R = -1.0000, X = 0.3478
    //				  In addMultipleSpeciesType: node [31], biomass 1415, K = -1, R = -1.0000, X = 0.7953
    //				  In addMultipleSpeciesType: node [14], biomass 1752, K = -1, R = -1.0000, X = 0.0010
    StringBuilder builder = new StringBuilder();
    builder.append(fullSpeciesMap.size()).append(",");
    for (SpeciesZoneType species : fullSpeciesMap.values()) {
      System.out.printf(
          "In addMultipleSpeciesType: node [%d], " + "biomass %d, K = %d, R = %6.4f, X = %6.4f\n",
          species.getNodeIndex(),
          +(int) species.getCurrentBiomass(),
          (int) species.getParamK(),
          species.getParamR(),
          species.getParamX());

      builder.append("[").append(species.getNodeIndex()).append("]").append(",");
      builder.append((int) species.getCurrentBiomass()).append(",");
      builder.append(roundToThreeDigits(species.getPerSpeciesBiomass())).append(",");

      String systemParam = this.setSystemParameters(species, fullSpeciesMap, timestep);
      builder.append(systemParam);
      System.out.println(builder);
    }
    String node_config = builder.substring(0, builder.length() - 1);
    // call processsim job here
    return node_config;
  }
Beispiel #18
0
  public Conversation removeConversation(long rmt_ip, int lcl_port, int rmt_port) {
    modLong.setLong(rmt_ip);
    modInt.setInt((lcl_port << 16) | (rmt_port & 0xFFFF));

    HashMap portsMap = (HashMap) hostsMap.get(modLong);
    Conversation conv = null;

    if (portsMap != null) {
      conv = (Conversation) portsMap.remove(modInt);
      if (conv != null) {
        if (portsMap.size() == 0) {
          hostsMap.remove(modLong);
        }
      }
    }

    allConversations.remove(conv);

    return conv;
  }
 /**
  * List the fonts known to the PDF renderer. This is like PFont.list(), however not all those
  * fonts are available by default.
  */
 @SuppressWarnings("unchecked")
 public static String[] listFonts() {
   if (fontList == null) {
     HashMap<?, ?> map = getMapper().getAliases();
     //      Set entries = map.entrySet();
     //      fontList = new String[entries.size()];
     fontList = new String[map.size()];
     int count = 0;
     for (Object entry : map.entrySet()) {
       fontList[count++] = (String) ((Map.Entry) entry).getKey();
     }
     //      Iterator it = entries.iterator();
     //      int count = 0;
     //      while (it.hasNext()) {
     //        Map.Entry entry = (Map.Entry) it.next();
     //        //System.out.println(entry.getKey() + "-->" + entry.getValue());
     //        fontList[count++] = (String) entry.getKey();
     //      }
     fontList = PApplet.sort(fontList);
   }
   return fontList;
 }
Beispiel #20
0
  /**
   * @param transcriptFile
   * @return Hashmap of (timestamp, transcriptword) pair
   */
  public static HashMap<Double, String> getTrList(File transcriptFile) {
    HashMap<Double, String> trList = new HashMap<Double, String>();

    String line = null;
    BufferedReader br = null;
    try {

      mylogger.log(
          Level.INFO, "Parsing transcript file:{0}", new Object[] {transcriptFile.getName()});
      br = new BufferedReader(new FileReader(transcriptFile));
      while ((line = br.readLine()) != null) {

        String parts[] = line.split(" ");

        Double ts = Double.parseDouble(parts[0]);

        String word = parts[1];
        trList.put(ts * 1000, word); // store the timestamps as ms

        //  System.out.println("Contains key:" + trList.containsKey(ts) + ":" + trList.get(ts));
      }
      // System.out.println(trList);
      mylogger.log(Level.INFO, "Parsing done; trlist size:{0}", trList.size());

    } catch (FileNotFoundException ex) {
      mylogger.log(Level.SEVERE, "Error:", ex);
    } finally {

      try {

        br.close();
      } catch (IOException ex) {
        mylogger.log(Level.SEVERE, "Error:", ex);
      }

      return trList;
    }
  }
Beispiel #21
0
  public static void testDecode(String input, String[] encodings) throws XcodeException {
    byte[] inputarray = null;
    HashMap output = null;
    String variant = null;

    if (input == null) {
      Debug.pass("");
      return;
    }
    input = input.trim();

    if (input.length() == 0 || input.charAt(0) == '#') {
      Debug.pass(input);
      return;
    }

    try {
      inputarray = Hex.decodeBytes(input);
      if (encodings == null || encodings.length == 0) {
        output = Native.decode(inputarray);
      } else {
        output = Native.decode(inputarray, encodings);
      }
    } catch (XcodeException x) {
      Debug.fail(input + "	ERROR:" + x.getCode() + "	" + x.getMessage());
      return;
    }

    System.out.println(input);
    Iterator i = output.keySet().iterator();
    String encoding = null;
    while (i.hasNext()) {
      encoding = (String) i.next();
      variant = (String) output.get(encoding);
      System.out.println("	" + encoding + "	" + Hex.encode(variant.toCharArray()));
    }
    System.out.println(output.size());
  }
Beispiel #22
0
  /**
   * Create mod instances from the enumerated classes
   *
   * @param modsToLoad List of mods to load
   */
  private void loadMods(HashMap<String, Class> modsToLoad) {
    if (modsToLoad == null) {
      logger.info("Mod class discovery failed. Not loading any mods!");
      return;
    }

    logger.info("Discovered " + modsToLoad.size() + " total mod(s)");

    for (Class mod : modsToLoad.values()) {
      try {
        logger.info("Loading mod from " + mod.getName());

        LiteMod newMod = (LiteMod) mod.newInstance();
        mods.add(newMod);

        logger.info(
            "Successfully added mod " + newMod.getName() + " version " + newMod.getVersion());
      } catch (Throwable th) {
        logger.warning(th.toString());
        th.printStackTrace();
      }
    }
  }
  public static void main(String[] args) throws IOException {

    System.out.println("AuctionClient starting");
    Socket auctSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;

    String hostName = "192.168.40.1"; // IP of host (may be local IP)
    int socketNum = 7; // the luckiest socket

    SeqSSMDPAgent agent = null;
    Valuation valuationMethod = null;
    String agent_name = "Anonymous";
    List<SBAuction> auctions = null;

    List<Agent> agents = null;
    int agent_id = 0;
    int auction_index_number = 0;

    // Try reading in the IP and socket number from the text file...
    try {
      in = new BufferedReader(new FileReader("./src/IP_and_Port.txt"));
      // two lines in this file. First is hostName/IP address, and second
      // is socket number of host
      hostName = in.readLine();
      socketNum = Integer.valueOf(in.readLine());
      in.close();
    } catch (IOException e) {
    }

    // These are values the agent should remember and use
    // Values are initialized when Server sends parameters
    int numSlotsNeeded = -1;
    int deadline = -1;
    double[] valuations = null;

    try {
      auctSocket = new Socket(hostName, socketNum);
      out = new PrintWriter(auctSocket.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(auctSocket.getInputStream()));
    } catch (UnknownHostException e) {
      System.err.println("Don't know about host: " + hostName + ".");
      System.exit(1);
    } catch (IOException e) {
      System.err.println("Couldn't get I/O for the connection to: host.");
      System.exit(1);
    }
    System.out.println("Connection to host established");

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
    String fromServer;

    // continue to prompt commands from host and respond
    while ((fromServer = in.readLine()) != null) {
      System.out.println("\n\nServer: " + fromServer);

      // Send host this client's unique ID
      if (fromServer.equalsIgnoreCase("Send client name")) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a unique ID string...");
        agent_name = "WJJSIM" + (int) (Math.random() * 100); // br.readLine();
        out.println(agent_name); // prompt user for an ID string
        System.out.println(agent_name);
        // OPTIONAL CHANGE:
        // YOU MAY CHOOSE TO REPLACE THE LINE ABOVE WITH THE LINE BELOW
        // out.println("My_Hardcoded_Name");

        System.out.println("User ID sent.  If prompted again, choose another ID/Name string.");
        System.out.println("Waiting for server to start auction...");
      }

      // ***********************************************************************

      else if (fromServer.startsWith("agent-parameters:")) {
        String[] params = fromServer.split("[ ]"); // tokens delimited
        // with spaces
        numSlotsNeeded = Integer.valueOf(params[1]); // 1st param is
        // number of slots
        // needed

        deadline = Integer.valueOf(params[2]); // 2nd param is deadline
        // DEADLINE IS INDEX OF LAST AUCTION OF VALUE (0-indexed).
        // example: deadline = 1 --> first two time-slots can be used

        valuations = new double[params.length - 3]; // first 3 stings
        // aren't valuations
        for (int i = 3; i < params.length; i++) valuations[i - 3] = Double.valueOf(params[i]);

        // /////////////////////////////////////////////
        // YOUR CODE HERE
        // You probably want to store the parameters sent from host.
        // For example, you could store them in global variables,
        // or use them to initialize an agent class you wrote.
        // /////////////////////////////////////////////
        valuationMethod = new SchedulingValuation(numSlotsNeeded, valuations);
        agents = new ArrayList<Agent>();
        auctions = new ArrayList<SBAuction>(valuations.length);

        // Let's feed everyone the same input price prediction
        ArrayList<Double> weight = new ArrayList<Double>(); // dummy
        // weights
        ArrayList<DiscreteDistribution> pp = genPrediction(8, 5, false, weight);

        agent = new SeqSSMDPAgent(agent_id, valuationMethod, pp);
        agents.add(agent);

        // int ask_price=0;
        // int ask_epsilon=1;
        int nth_price = 2;
        double reserve_price = 0;
        // int auction_id=0;

        for (int auction_id = 0; auction_id < valuations.length; auction_id++) {
          SBAuction auction = new SBNPAuction(auction_id, reserve_price, 0, 0, agents, nth_price);
          auctions.add(auction);
          // agent.postResult(new Result(auctions.get(auction_id),
          // false, 0, ask_price, 0, ask_epsilon));
        }

        // /////////////////////////////////////////////
        out.println("Parameters accepted");
      }

      // ***********************************************************************

      else if (fromServer.equalsIgnoreCase("submit-bid")) {
        // Here are values you should use... be more clever than random!
        // numSlotsNeeded (int)
        // deadline (int) index of last timeSlot of value (starts at 0)
        // valuations (double[numSlots])

        // /////////////////////////////////////////////
        // YOUR CODE HERE
        // Create a string, like myBids, with your bid(s).
        // If placing multiple bids, separate bids with spaces spaces.
        // If multiple bids, order bids as follows:
        // myBids = "timeSlot1Bid  timeSlot2Bid ... timeslot5Bid";
        //
        // Note: bids get rounded to 2 decimal places by host. 5.031 ->
        // 5.03
        // /////////////////////////////////////////////

        // EDIT HERE!

        /*
         * Random r = new Random();//make random bids...String myBid =
         * ""+ (r.nextDouble()*10);
         */
        HashMap<Integer, Double> a_bids = agent.getBids();
        String myBids = "";

        if (a_bids.size() == 1) {
          // this is one item, as expected
          for (int r : a_bids.keySet()) myBids = "" + a_bids.get(r);

        } else if (a_bids.size() == 0) {
          // there are no items, bid 0.
          myBids = "0.0";
        } else {
          System.out.println("ERROR: agent submitted wrong number of bids: " + a_bids.size());
          System.exit(-1);
        }

        // /////////////////////////////////////////////
        out.println("" + myBids); // Send agent's bids to server (as a
        // string)
        System.out.println("My bid: " + myBids);
      }

      // ***********************************************************************

      // Observe the state of auction variables. Store information locally
      else if (fromServer.startsWith("observe-auction-state:")) {
        auction_index_number++;
        System.out.println("The auction command has come " + auction_index_number);

        String[] stateVars = fromServer.split("[ ]"); // tokens delimited
        // with spaces

        int numAgents = Integer.valueOf(stateVars[1]);
        int numTimeSlots = Integer.valueOf(stateVars[2]);
        int currentRound = Integer.valueOf(stateVars[3]); // 1st round ->
        // 0
        // currentRound is 0-indexed, so currentRound = 0 for first
        // round

        String[] winnerIDs = new String[currentRound]; //
        double[] prices = new double[currentRound];
        double[] winBids = new double[currentRound];

        for (int i = 0; i < (currentRound * 3); i += 3) { // 3 records
          // per
          // round:
          // winnerID,
          // pricePaid,
          // bid
          winnerIDs[i / 3] = stateVars[4 + i];
          prices[i / 3] = Double.valueOf(stateVars[5 + i]);
          winBids[i / 3] = Double.valueOf(stateVars[6 + i]);
        }

        agent.closeAllOpenAuctions();
        agent.openAuction(currentRound);

        System.out.println(
            "+++++++++++Opening current round: " + currentRound + "++++++++++++++++++++\n");

        System.out.println(
            "Observing state:\nCurrent round = "
                + currentRound
                + "\nNumber of agents = "
                + numAgents
                + "\nNumber of time slots = "
                + numTimeSlots);
        System.out.println("Previous round results:");
        for (int i = 0; i < winnerIDs.length; i++)
          System.out.println(
              "Round "
                  + i
                  + ": winner: "
                  + winnerIDs[i]
                  + ", price paid = "
                  + prices[i]
                  + ", with bid = "
                  + winBids[i]);

        // /////////////////////////////////////////////
        // YOUR CODE HERE
        // You may want to record some of the state
        // information here, especially the results
        // from previous auction rounds in winnerIDs
        // and prices. The for round i (0-indexed),
        // winnerIDs[i] is a unique string ID for the
        // agent who won the time-slot and paid prices[i].
        // /////////////////////////////////////////////

        // EDIT HERE
        if (currentRound > 0) {

          boolean is_winner = false;
          if (winnerIDs[currentRound - 1].equals(agent_name)) {
            is_winner = true;
          }

          int ask_epsilon = 1;
          double cur_price = prices[currentRound - 1];
          double ask_price = cur_price + ask_epsilon;
          double payment = 0;

          if (is_winner) payment = cur_price; // payment =
          // prices[currentRound-1];
          else payment = 0;

          agent.postResult(
              new Result(
                  auctions.get(currentRound - 1),
                  is_winner,
                  payment,
                  ask_price,
                  cur_price,
                  ask_epsilon));
          System.out.println(agent.information());
        }

        // /////////////////////////////////////////////
        out.println("State Observed"); // let the server know client
        // received state info
      }

      // ***********************************************************************

      else if (fromServer.startsWith("observe-final-outcome:")) {
        String[] outcomeVars = fromServer.split("[ ]"); // tokens
        // delimited
        // with spaces
        // for each slot, announce winner's ID, price paid, and their
        // bid
        if (outcomeVars.length - 1 < valuations.length * 3) {
          out.println("incomplete state"); // let server know state was
          // incomplete
        } else {
          for (int i = 1; i < outcomeVars.length; i += 3) {
            // for ith time-slot, winner and price
            String winnerID = outcomeVars[i];
            double winPrice = Double.valueOf(outcomeVars[i + 1]);
            double winBid = Double.valueOf(outcomeVars[i + 2]);
            System.out.println(
                "Time Slot "
                    + (1 + (i / 3))
                    + " awarded to ["
                    + winnerID
                    + "] for price = "
                    + winPrice
                    + "  with bid = "
                    + winBid);
          }
          out.println("Final Outcome Observed"); // let the server know
          // client received
          // state info
        }
      }

      // ***********************************************************************

      // The server says to end the connection
      else if (fromServer.equals("END")) {
        System.out.println("END called.  closing");
        break;
      }

      // ***********************************************************************

      else System.out.println("Unexpected input: " + fromServer);
    }

    out.close();
    in.close();
    stdIn.close();
    auctSocket.close();
  }
  public void solve() {
    //		Scanner sc = new Scanner(System.in);
    //		int n = Integer.parseInt(sc.nextLine());
    //		n = 10000;
    pr("\n".getBytes());
    int n = ni();
    //		int xx=100000;
    while (n != 0) {
      String s = ns1();
      //			int size = (int)(Math.random()*10000);
      //			char [] axx = new char[size];
      //			for (int i = 0; i < axx.length; i++) {
      //				char ccc = (char)((Math.random()*('z'-'a'))+'a');
      ////				pr(ccc);
      //				axx[i]=ccc;
      //			}
      //			String s =new String(axx);
      //			for (int i = 0; i < 1000000; i++) {
      //				s+='x';
      //			}
      //			int[] xa = new int[1000000000];
      //			pr(s);
      int a = 0;
      HashMap<Character, Integer> set = new HashMap<Character, Integer>();
      //			int [] alf= new int[128];
      int r = 0;
      for (int i = 0; i < s.length(); i++) {
        //				pr(set);
        //				char that = s.charAt(a);
        char thix = s.charAt(i);
        if (set.size() < n) {
          Integer ax = set.get(thix);
          if (ax == null) {
            set.put(thix, 1);
          } else set.put(thix, ax + 1);

        } else if (set.size() == n) {
          if (!set.containsKey(thix)) {
            while (set.size() == n && a < s.length()) {
              char that = s.charAt(a);
              if (set.containsKey(that) && set.get(that) > 1) set.put(that, set.get(that) - 1);
              else set.remove(that);
              a++;
            }
            set.put(thix, 1);
          } else set.put(thix, set.get(thix) + 1);
        }
        int newr = i - a + 1;
        //				pr(newr, set,a,i,s.substring(a,i));
        if (newr > r) {
          //					pr()
          //					pr(set,a,i,s.substring(a,i));
          r = newr;
        }
        //				r=max(r,);
      }
      out.println(r);
      //			n = (int)(Math.random()*128);
      n = ni();
    }
  }
 public int getConnectionCount() {
   return Connections.size() + Acceptors.size();
 }
Beispiel #26
0
  public void computeHits() throws IOException, ParseException {
    int d = 50;
    // String index = "maritime_disaster";
    // String type = "document";
    String query = "maritime accidents";

    String hitslocation = "/Users/prachibhansali/Documents/IR/Assignment4/hits/";
    String fileext = ".json";

    String location = "/Users/prachibhansali/Documents/IR/Assignment4/saved/";
    // String fileext = ".txt";

    HashMap<String, Set<String>> outlinkmapping = new HashMap<String, Set<String>>();
    HashMap<String, JSONArray> inlinkmapping = new HashMap<String, JSONArray>();

    System.out.println("fetching outlinks");

    // HashMap<String,Boolean> rootset = fetchTopDocuments(index,type,query,outlinkmapping);
    HashMap<String, Boolean> rootset = fetchTopDocumentsFromFile(hitslocation, fileext, query);

    System.out.println("Root size " + rootset.size());

    Set<String> crawledDocuments = new HashSet<String>();
    fetchCrawledDocumentsOnly(location, crawledDocuments);

    fetchOutlinksFromFiles(location, outlinkmapping, fileext, inlinkmapping, crawledDocuments);
    System.out.println("done fetching outlinks " + outlinkmapping.size());

    HashMap<String, Float> authority = new HashMap<String, Float>();
    HashMap<String, Float> hub = new HashMap<String, Float>();

    System.out.println("done");
    Iterator<String> itr = new HashMap<String, Boolean>(rootset).keySet().iterator();
    Iterator<String> oitr = new HashMap<String, Boolean>(rootset).keySet().iterator();

    while (oitr.hasNext()) {
      String url = oitr.next();
      Set<String> a = outlinkmapping.get(url);
      for (String s : a) rootset.put(s, false);
    }

    while (itr.hasNext()) {
      String url = itr.next();
      if (inlinkmapping.containsKey(url)) {
        JSONArray arr = inlinkmapping.get(url);
        for (int i = 0; i < arr.size() && i < d; i++) rootset.put((String) arr.get(i), false);
      }
    }
    System.out.println(rootset.size());

    PrintWriter pw = new PrintWriter("rootset");
    Set<String> rs = rootset.keySet();
    for (String s : rs) pw.println(s);
    pw.close();

    HashMap<String, Set<String>> outlinks = new HashMap<String, Set<String>>();
    HashMap<String, Set<String>> inlinks = new HashMap<String, Set<String>>();
    itr = new HashMap<String, Boolean>(rootset).keySet().iterator();

    while (itr.hasNext()) {
      String url = itr.next();
      if (outlinkmapping.containsKey(url)) outlinks.put(url, outlinkmapping.get(url));
      if (inlinkmapping.containsKey(url))
        inlinks.put(url, fetchSetFromJSON(inlinkmapping.get(url)));
    }
    clearNonLinksFromRoot(outlinks, rootset);
    System.out.println("Cleared non links for outlinks");

    clearNonInLinksFromRoot(inlinks, rootset);
    System.out.println("Cleared non links for inlinks");

    System.out.println("here" + inlinks.size());
    System.out.println("here" + outlinks.size());

    initialize(authority, rootset);
    initialize(hub, rootset);

    compute(inlinks, outlinks, authority, hub);
  }
 /**
  * Returns an array of DataFlavor objects indicating the flavors the data can be provided in. The
  * array should be ordered according to preference for providing the data (from most richly
  * descriptive to least descriptive).
  *
  * @return an array of data flavors in which this data can be transferred
  */
 @Override
 public DataFlavor[] getTransferDataFlavors() {
   return (DataFlavor[]) flavors.toArray(new DataFlavor[transferables.size()]);
 }
		private void list() throws IOException {
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			formparams.add(new BasicNameValuePair("type", "album"));
			formparams.add(new BasicNameValuePair("scope", "all"));

			BufferedReader entityReader = sendRequest(g.getUrlString() + api + "item/1", "get", formparams);

			JSONParser parser = new JSONParser();
			ListContentHandler lch = new ListContentHandler();

			HashMap<String,String> url2parentUrl = new HashMap<String,String>();
			HashMap<String,Album> url2album = new HashMap<String,Album>();
			ArrayList<Album> albums = new ArrayList<Album>();

			try {
				Album rootAlbum = g.createRootAlbum();
				rootAlbum.setUrl(g.getUrlString() + api + "item/1");
				rootAlbum.setSuppressEvents(true);
				lch.setAlbum(rootAlbum);
				parser.parse(entityReader, lch, true);
				rootAlbum.setSuppressEvents(false);
				// map album names to albums
				url2album.put(rootAlbum.getUrl(), rootAlbum);
				url2parentUrl.put(rootAlbum.getUrl(), lch.getParentUrl());

				while (!lch.isEnd()) {
					Album a = g.newAlbum();
					a.setSuppressEvents(true);
					lch.setAlbum(a);
					parser.parse(entityReader, lch, true);
					a.setSuppressEvents(false);

					albums.add(a);

					// map album names to albums
					url2album.put(a.getUrl(), a);
					url2parentUrl.put(a.getUrl(), lch.getParentUrl());
				}
			} catch (ParseException e) {
				Log.logException(Log.LEVEL_CRITICAL, MODULE, e);
			}

			Log.log(Log.LEVEL_TRACE, MODULE, "Created " + albums.size() + " albums");

			// link albums to parents
			for (Object o : url2parentUrl.keySet()) {
				String name = (String) o;
				String parentName = url2parentUrl.get(name);
				Album child = url2album.get(name);
				Album parent = url2album.get(parentName);

				if (child != null && parent != null) {
					parent.add(child);
				}
			}

			Log.log(Log.LEVEL_TRACE, MODULE, "Linked " + url2parentUrl.size() + " albums to their parents");

			// reorder
			Collections.sort(albums, new NaturalOrderComparator<Album>());
			Collections.reverse(albums);
			ArrayList<Album> orderedAlbums = new ArrayList<Album>();
			int depth = 0;
			while (!albums.isEmpty()) {
				Iterator<Album> it = albums.iterator();
				while (it.hasNext()) {
					Album a = it.next();

					try {
						if (a.getAlbumDepth() == depth) {
							it.remove();
							a.sortSubAlbums();

							Album parentAlbum = a.getParentAlbum();
							if (parentAlbum == null) {
								orderedAlbums.add(0, a);
							} else {
								int i = orderedAlbums.indexOf(parentAlbum);
								orderedAlbums.add(i + 1, a);
							}
						}
					} catch (IllegalArgumentException e) {
						it.remove();
						Log.log(Log.LEVEL_TRACE, MODULE, "Gallery server album list is corrupted: " +
								"album " + a.getName() + " has a bad containment hierarchy.");
					}
				}

				depth++;
			}

			Log.log(Log.LEVEL_TRACE, MODULE, "Ordered " + orderedAlbums.size() + " albums");

			status(su, StatusUpdate.LEVEL_BACKGROUND, GRI18n.getString(MODULE, "ftchdAlbms"));
		}
Beispiel #29
0
  public PDMStateSpace calculateSimpleStateSpace(
      boolean root, boolean failure, boolean input, boolean colored, int numStates, int breadth) {
    PDMStateSpace result = new PDMStateSpace(this, colored);
    HashSet states = new HashSet();
    int j = (operations.size() + 1);

    if (!input) {
      HashSet empty = new HashSet();
      PDMState st = new PDMState(result, "state" + i, empty, empty, empty);
      result.addState(st);
      states.add(st);
      i++;
    } else {
      // Start with the complete set of input data elements available
      HashSet empty = new HashSet();
      String name = new String("state" + i);
      HashSet ins = new HashSet(); // this hashSet contains the input
      // elements to the process (input
      // elements of PDM)
      HashSet execOps = new HashSet();
      // Fill the hashSet with the leaf elements
      HashMap leafs = getLeafElements();
      Object[] leafElts = leafs.values().toArray();
      for (int i = 0; i < leafElts.length; i++) {
        PDMDataElement d = (PDMDataElement) leafElts[i];
        ins.add(d);
      }
      HashSet leafOps = getLeafOperations();
      Iterator it = leafOps.iterator();
      while (it.hasNext()) {
        PDMOperation op = (PDMOperation) it.next();
        execOps.add(op);
      }

      PDMState start = new PDMState(result, name, ins, execOps, empty); // start
      // state
      // of
      // the
      // statespace
      result.addState(start);
      i++;
      states.add(start);
    }
    while (!states.isEmpty()) {
      HashSet states2 = (HashSet) states.clone();
      Iterator it = states2.iterator();
      while (it.hasNext()) {
        PDMState state = (PDMState) it.next();
        HashSet nextStates = calculateNextStates(state, result, root, failure, numStates, breadth);
        Iterator it2 = nextStates.iterator();
        // Add the new states to iterator
        while (it2.hasNext()) {
          PDMState st = (PDMState) it2.next();
          states.add(st);
        }
        states.remove(state);
      }
    }
    i = 0;
    j = 0;
    Message.add("<PDMMDPStateSpace>", Message.TEST);
    Message.add("<NumberOfStates = " + result.getNumberOfStates() + " >", Message.TEST);
    Message.add("</PDMMDPStateSpace>", Message.TEST);
    return result;
  }
Beispiel #30
0
 /**
  * Returns the number of Ms2 queries in the file.
  *
  * @return The number of MS2 queries.
  */
 public int getMs2QueryCount() {
   return (sourceFile != null) ? index.size() : ms2Queries.size();
 }