Пример #1
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;
  }
Пример #2
0
  public ReaderHandler(LowLevelDbAccess lowLevelDbAccess, String webDir) {

    loginInfoDb = new LoginInfo.DB(lowLevelDbAccess);
    userDb = new User.DB(lowLevelDbAccess);
    feedDb = new Feed.DB(lowLevelDbAccess);
    articleDb = new Article.DB(lowLevelDbAccess);
    readArticlesCollDb = new ReadArticlesColl.DB(lowLevelDbAccess);
    userHelpers = new UserHelpers(loginInfoDb, userDb);

    setContextPath("/");

    File warPath = new File(webDir);
    setWar(warPath.getAbsolutePath());

    if (isInJar) {
      for (Map.Entry<String, String> entry : PATH_MAPPING.entrySet()) {
        addPrebuiltJsp(entry.getKey(), "jsp." + entry.getValue().replaceAll("_", "_005f") + "_jsp");
      }
    } else {
      for (Map.Entry<String, String> entry : PATH_MAPPING.entrySet()) {
        addServlet(
            new ServletHolder(new RedirectServlet("/" + entry.getValue() + ".jsp")),
            entry.getKey());
      }
    }

    setErrorHandler(new ReaderErrorHandler());
  }
  public static void main(String[] args) {
    String testDataLocation = "testData/HighResolutionTerrain/";
    HashMap<String, Sector> sectors = new HashMap<String, Sector>();
    sectors.put(
        testDataLocation + "HRTOutputTest01.txt", Sector.fromDegrees(37.8, 38.3, -120, -119.3));
    sectors.put(
        testDataLocation + "HRTOutputTest02.txt",
        Sector.fromDegrees(32.34767, 32.77991, 70.88239, 71.47658));
    sectors.put(
        testDataLocation + "HRTOutputTest03.txt",
        Sector.fromDegrees(32.37825, 71.21130, 32.50050, 71.37926));

    try {
      if (args.length > 0 && args[0].equals("-generateTestData")) {
        for (Map.Entry<String, Sector> sector : sectors.entrySet()) {
          String filePath = sector.getKey();

          generateReferenceValues(filePath, sector.getValue());
        }
      }

      for (Map.Entry<String, Sector> sector : sectors.entrySet()) {
        String filePath = sector.getKey();

        ArrayList<Position> referencePositions = readReferencePositions(filePath);
        ArrayList<Position> computedPositions = computeElevations(referencePositions);
        testPositions(filePath, referencePositions, computedPositions);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
Пример #4
0
  ///////////
  // Methods//
  ///////////
  public void createServerFile(
      HashMap<String, DataObj> dataObjsMap, HashMap<String, PageObj> pageObjsMap) {
    // Copy files over
    try {
      FileUtils.copyFile(sourceConfig, new File("Output/config.js"));
    } catch (IOException e) {
      System.out.println("Error copying over config file for");
      System.out.println(e);
    }
    out.write(genDbConnection());
    // For each data object, get object by ID
    Iterator it = dataObjsMap.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry one = (Map.Entry) it.next();
      DataObj curDataObj = (DataObj) one.getValue();
      String name = curDataObj.getName();
      out.write("\n /* " + name + ": CRUD GET, DELETE, UPDATE, POST BY ID*/\n");
      out.write(genGetById(curDataObj));
      out.write(genDelById(curDataObj));
      out.write(genUpdateById(curDataObj));
      out.write(genAdd(curDataObj));
    }
    // Hack to get a necessary API call for OAuth stuff
    out.write(
        genGetByPageParam(
            null,
            new Section(
                "View",
                new ArrayList<String>(Arrays.asList(new String[] {"OAuthID"})),
                new ArrayList<String>(Arrays.asList(new String[] {"User"}))),
            dataObjsMap));

    // For each page, generate the calls necessery to make
    // the view/create params work
    it = pageObjsMap.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry one = (Map.Entry) it.next();
      PageObj curPageObj = (PageObj) one.getValue();
      String name = curPageObj.getName();
      out.write("\n /* " + name + ": CRUD GET,DELETE,UPDATE,POST *NOT* BY ID */\n");
      List<Section> sections = curPageObj.getSections();
      for (Section section : sections) {
        switch ((Section.Type) section.getType()) {
          case VIEW:
            out.write(genGetByPageParam(curPageObj, section, dataObjsMap));
            break;
          case CREATE:
            // out.write(genPostByPageParam(curPageObj, section));
            break;
          case MODIFY:
            break;
          case DELETE:
            break;
        }
      }
    }
    out.write(genServerListen());
  }
Пример #5
0
  protected void testStartToThread() {
    System.out.println("=====test startToThread ");
    Set maps = startToThread.entrySet();
    for (Iterator iter = maps.iterator(); iter.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iter.next();
      JPegStmt key = (JPegStmt) entry.getKey();
      Tag tag = (Tag) key.getTags().get(0);
      System.out.println("---key=  " + tag + " " + key);
      /*	    List list = (List)entry.getValue();
      if (list.size()>0){

      System.out.println("**thread set:");
      Iterator it = list.iterator();
      while (it.hasNext()){
      Chain chain =(Chain)it.next();
      Iterator chainIt = chain.iterator();

      System.out.println("the size of chain is: "+chain.size());
      while (chainIt.hasNext()){
      JPegStmt stmt = (JPegStmt)chainIt.next();
      System.out.println(stmt);
      }
      }
      }
      */
    }
    System.out.println("=========startToThread--ends--------");
  }
  protected void writeAttributes(DOMOutput out) throws IOException {
    Figure prototype = (Figure) out.getPrototype();

    boolean isElementOpen = false;
    for (Map.Entry<AttributeKey, Object> entry : attributes.entrySet()) {
      AttributeKey key = entry.getKey();
      if (forbiddenAttributes == null || !forbiddenAttributes.contains(key)) {
        Object prototypeValue = key.get(prototype);
        Object attributeValue = key.get(this);
        if (prototypeValue != attributeValue
            || (prototypeValue != null
                && attributeValue != null
                && !prototypeValue.equals(attributeValue))) {
          if (!isElementOpen) {
            out.openElement("a");
            isElementOpen = true;
          }
          out.openElement(key.getKey());
          out.writeObject(entry.getValue());
          out.closeElement();
        }
      }
    }
    if (isElementOpen) {
      out.closeElement();
    }
  }
Пример #7
0
    public static void printViewPatterns() {
      processedViewsForPatterns = new HashSet<ViewTrace>();
      HashMap<String, Integer> viewPatterns = new HashMap<String, Integer>();

      ps.println("ViewPatterns ------------------- \n");
      for (ViewTrace trace : viewsRegistry) {
        if (processedViewsForPatterns.contains(trace)) {
          continue;
        }
        ViewTrace v = trace.getRootView();
        StringBuilder p = new StringBuilder();
        p.append("PATTERN ");
        extractViewPattern(0, v, p);
        p.append("\n");
        String pattern = p.toString();
        Integer count = viewPatterns.get(pattern);
        if (count == null) {
          viewPatterns.put(pattern, 1);
        } else {
          viewPatterns.put(pattern, count + 1);
        }
      }
      processedViewsForPatterns = null;
      for (Map.Entry<String, Integer> e : viewPatterns.entrySet()) {
        ps.print("(" + e.getValue() + ") ");
        ps.println(e.getKey());
      }
    }
Пример #8
0
 /* Retorna um Map com os utilizadores existentes no sistema */
 public HashMap<String, User> getUsers() {
   HashMap<String, User> r = new HashMap<>();
   for (Map.Entry<String, User> entry : users.entrySet()) {
     r.put(entry.getKey(), entry.getValue());
   }
   return r;
 }
Пример #9
0
  private static HttpURLConnection createConnection(
      ConnectorConfig config,
      URL url,
      HashMap<String, String> httpHeaders,
      boolean enableCompression)
      throws IOException {

    if (config.isTraceMessage()) {
      config
          .getTraceStream()
          .println(
              "WSC: Creating a new connection to "
                  + url
                  + " Proxy = "
                  + config.getProxy()
                  + " username "
                  + config.getProxyUsername());
    }

    HttpURLConnection connection = (HttpURLConnection) url.openConnection(config.getProxy());
    connection.addRequestProperty("User-Agent", VersionInfo.info());

    /*
     * Add all the client specific headers here
     */
    if (config.getHeaders() != null) {
      for (Entry<String, String> ent : config.getHeaders().entrySet()) {
        connection.setRequestProperty(ent.getKey(), ent.getValue());
      }
    }

    if (enableCompression && config.isCompression()) {
      connection.addRequestProperty("Content-Encoding", "gzip");
      connection.addRequestProperty("Accept-Encoding", "gzip");
    }

    if (config.getProxyUsername() != null) {
      String token = config.getProxyUsername() + ":" + config.getProxyPassword();
      String auth = "Basic " + new String(Base64.encode(token.getBytes()));
      connection.addRequestProperty("Proxy-Authorization", auth);
      connection.addRequestProperty("Https-Proxy-Authorization", auth);
    }

    if (httpHeaders != null) {
      for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
        connection.addRequestProperty(entry.getKey(), entry.getValue());
      }
    }

    if (config.getReadTimeout() != 0) {
      connection.setReadTimeout(config.getReadTimeout());
    }

    if (config.getConnectionTimeout() != 0) {
      connection.setConnectTimeout(config.getConnectionTimeout());
    }

    return connection;
  }
Пример #10
0
 public Map.Entry<Region, Double> getMaxFromHashMap(HashMap<Region, Double> input) {
   Map.Entry<Region, Double> maxEntry = null;
   for (Map.Entry<Region, Double> entry : input.entrySet()) {
     if (maxEntry == null || entry.getValue() > maxEntry.getValue()) {
       maxEntry = entry;
     }
   }
   return maxEntry;
 }
Пример #11
0
  private boolean validateTables(TSelectSqlStatement stmt) {
    HashMap<String, Integer> present = new HashMap<String, Integer>();
    if (!stmt.getResultColumnList().getResultColumn(0).toString().equals("*")) {

      int cols = stmt.getResultColumnList().size();
      for (int a = 0; a < cols; a++) {
        present.put(
            stmt.getResultColumnList()
                .getResultColumn(a)
                .toString()
                .toLowerCase()
                .replace("(", "")
                .replace(")", ""),
            0);
      }
    }

    TJoinList joins = stmt.joins;
    int j = joins.size();
    int invalid = 1;
    for (int i = 0; i < j; i++) {
      Iterator<Table> it = DBSystem.tableList.iterator();
      Table table = null;
      while (it.hasNext()) {
        table = it.next();
        if (table.getName().equalsIgnoreCase(joins.getJoin(i).toString())) {
          invalid = 0;
          if (!stmt.getResultColumnList().getResultColumn(0).toString().equals("*")) {
            Iterator it1 = table.getColumnData().entrySet().iterator();

            while (it1.hasNext()) {
              Map.Entry pairs = (Map.Entry) it1.next();
              if (present.get(pairs.getKey().toString().toLowerCase()) != null
                  && present.get(pairs.getKey().toString().toLowerCase()) == 0) {
                present.put(pairs.getKey().toString(), 1);
              } else if (present.get(pairs.getKey().toString().toLowerCase()) != null
                  && present.get(pairs.getKey().toString().toLowerCase()) == 1) return false;
            }
          }
        }
      }
      if (invalid == 1) return false;
      else {
        invalid = 1;
      }
    }
    if (!stmt.getResultColumnList().getResultColumn(0).toString().equals("*")) {
      Iterator it2 = present.entrySet().iterator();
      while (it2.hasNext()) {
        Map.Entry pairs = (Map.Entry) it2.next();
        if ((Integer) pairs.getValue() == 0) {
          return false;
        }
      }
    }
    return true;
  }
Пример #12
0
 protected void testUnitToPeg(HashMap unitToPeg) {
   System.out.println("=====test unitToPeg ");
   Set maps = unitToPeg.entrySet();
   for (Iterator iter = maps.iterator(); iter.hasNext(); ) {
     Map.Entry entry = (Map.Entry) iter.next();
     System.out.println("---key=  " + entry.getKey());
     JPegStmt s = (JPegStmt) entry.getValue();
     System.out.println("--value= " + s);
   }
   System.out.println("=========unitToPeg--ends--------");
 }
Пример #13
0
 /**
  * 把数据源HashMap转换成json
  *
  * @param map
  */
 public static String hashMapToJson(HashMap map) {
   String string = "{";
   for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
     Entry e = (Entry) it.next();
     string += "'" + e.getKey() + "':";
     string += "'" + e.getValue() + "',";
   }
   string = string.substring(0, string.lastIndexOf(","));
   string += "}";
   return string;
 }
Пример #14
0
 /**
  * Parses the query.
  *
  * @param p performance
  * @throws QueryException query exception
  */
 private void parse(final Performance p) throws QueryException {
   qp.http(http);
   for (final Entry<String, String[]> entry : vars.entrySet()) {
     final String name = entry.getKey();
     final String[] value = entry.getValue();
     if (name == null) qp.context(value[0], value[1]);
     else qp.bind(name, value[0], value[1]);
   }
   qp.parse();
   if (p != null) info.parsing += p.time();
 }
 public static void addCookies(HttpPost request, HashMap<String, String> cookieContiner) {
   StringBuilder sb = new StringBuilder();
   Iterator iter = cookieContiner.entrySet().iterator();
   while (iter.hasNext()) {
     Map.Entry entry = (Map.Entry) iter.next();
     String key = entry.getKey().toString();
     String val = entry.getValue().toString();
     sb.append(key);
     sb.append("=");
     sb.append(val);
     sb.append(";");
   }
   request.addHeader(COOKIE, sb.toString());
 }
Пример #16
0
 String dumpMessages(HashMap map) {
   StringBuffer sb = new StringBuffer();
   Map.Entry entry;
   List l;
   if (map != null) {
     synchronized (map) {
       for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
         entry = (Map.Entry) it.next();
         l = (List) entry.getValue();
         sb.append(entry.getKey()).append(": ");
         sb.append(l.size()).append(" msgs\n");
       }
     }
   }
   return sb.toString();
 }
Пример #17
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 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);
     }
   }
 }
Пример #19
0
  public static void main(String[] args) throws FileNotFoundException {
    TruthFile truthFile = new TruthFile("EntityRecognitionDataset/truth2.txt");
    HashMap<String, ArrayList<Annotation>> truthTables = truthFile.parse();

    truthFile.log("There are " + truthTables.size() + "truth files.");
    Iterator itr1 = truthTables.entrySet().iterator();
    while (itr1.hasNext()) {
      Map.Entry truthTable = (Map.Entry) itr1.next();
      //			 truthFile.log("\nFile \"" + truthTable.getKey() + "\":");
      HashMap tableContents = (HashMap) truthTable.getValue();
      Iterator itr2 = tableContents.entrySet().iterator();
      while (itr2.hasNext()) {
        Map.Entry tableEntry = (Map.Entry) itr2.next();
        truthFile.log(
            tableEntry.getKey().toString().toLowerCase() + ","); // + ": " + tableEntry.getValue());
      }
      System.out.println();
    }
  }
    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();
    }
Пример #21
0
  // 輸入DF,每個term給他一個t_index
  public static HashMap<String, Integer> tID(HashMap<String, Integer> DF) {
    HashMap<String, Integer> tID = new HashMap<String, Integer>();
    List<Map.Entry<String, Integer>> list_Data =
        new ArrayList<Map.Entry<String, Integer>>(DF.entrySet());
    Collections.sort(
        list_Data,
        new Comparator<Map.Entry<String, Integer>>() {
          public int compare(Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) {
            return (entry1.getKey().compareTo(entry2.getKey()));
          }
        });
    int ID = 1;
    for (Map.Entry<String, Integer> entry : list_Data) {
      tID.put(entry.getKey(), ID);
      ID++;
    }

    return tID;
  }
Пример #22
0
  // this method basically will chop up the blocks and get their frequencies
  private static void getBlockFrequency() throws Exception {
    directory = "../../thesis-datasets/morph_file_100MB/";
    ReadFile.readFile(directory, fileList); // read the two files
    HashMap<Integer, Integer> blockFreq =
        new HashMap<Integer, Integer>(); // this stores the block in the map along there frequencies
    int start = 0; // start of the sliding window
    int end = start + window - 1; // ending boundary
    preliminaryStep(directory);
    // System.out.println("Choping the document TDDD " + fileList.get(0));
    long[] divisorArray = {
      1000
    }; // run the frequency code for these divisor values (AKA expected block Size)
    for (long i : divisorArray) {

      long divisor1 = i;
      long divisor2 = i / 2;
      long divisor3 = i / 4;
      long remainder = 7;
      long minBoundary = min_multiplier * i;
      long maxBoundary = max_multiplier * i;
      // System.out.println("Running Likelihood for " + i + " " + divisor2 + " " + divisor3);
      int totalBlocks =
          chopDocument(
              fileArray.get(0),
              hashed_File_List.get(0),
              divisor1,
              divisor2,
              divisor3,
              remainder,
              minBoundary,
              maxBoundary,
              blockFreq);
      // now output the block sizes, along with there frequencies and probilities
      for (Map.Entry<Integer, Integer> tuple : blockFreq.entrySet()) {
        // output the block freq
        double prob = (double) tuple.getValue() / (double) totalBlocks;
        System.out.println(tuple.getKey() + " " + tuple.getValue() + " " + prob);
      }

      blockFreq.clear();
    }
  }
Пример #23
0
  public void testWaitingNodes() {
    System.out.println("------waiting---begin");
    Set maps = waitingNodes.entrySet();
    for (Iterator iter = maps.iterator(); iter.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iter.next();
      System.out.println("---key=  " + entry.getKey());
      FlowSet fs = (FlowSet) entry.getValue();
      if (fs.size() > 0) {

        System.out.println("**waiting nodes set:");
        Iterator it = fs.iterator();
        while (it.hasNext()) {
          JPegStmt unit = (JPegStmt) it.next();

          System.out.println(unit.toString());
        }
      }
    }
    System.out.println("------------waitingnodes---ends--------");
  }
Пример #24
0
 public void save() {
   HashMap<String, RestorationObject> restorationsForDisk = new HashMap<>();
   for (Map.Entry<String, Restoration> entry : RESTORATIONS.entrySet()) {
     String key = entry.getKey();
     Restoration value = entry.getValue();
     RestorationObject tmpRestoration = new RestorationObject();
     for (ItemStack i : value.inventory) {
       if (i instanceof ItemStack) {
         plugin.logDebug("Serializing inventory: " + i.toString());
         tmpRestoration.inventory.add(new ScavengerItem(i));
       }
     }
     for (ItemStack i : value.armour) {
       if (i instanceof ItemStack) {
         plugin.logDebug("Serializing armour: " + i.toString());
         tmpRestoration.armour.add(new ScavengerItem(i));
       }
     }
     if (plugin.isMc19or110()) {
       if (value.offHand instanceof ItemStack) {
         plugin.logDebug("Serializing offhand: " + value.offHand.toString());
         tmpRestoration.offHand = new ScavengerItem(value.offHand);
       }
     }
     tmpRestoration.enabled = value.enabled;
     tmpRestoration.level = value.level;
     tmpRestoration.exp = value.exp;
     tmpRestoration.playerName = value.playerName;
     restorationsForDisk.put(key, tmpRestoration);
     plugin.logInfo("Saving " + tmpRestoration.playerName + "'s inventory to disk.");
   }
   try {
     File file = new File("plugins/Scavenger/inv3.ser");
     FileOutputStream f_out = new FileOutputStream(file);
     try (ObjectOutputStream obj_out = new ObjectOutputStream(f_out)) {
       obj_out.writeObject(restorationsForDisk);
     }
   } catch (IOException e) {
     plugin.logError(e.getMessage());
   }
 }
Пример #25
0
  protected void testUnitToSucc() {
    System.out.println("=====test unitToSucc ");
    Set maps = unitToSuccs.entrySet();
    for (Iterator iter = maps.iterator(); iter.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iter.next();
      JPegStmt key = (JPegStmt) entry.getKey();
      Tag tag = (Tag) key.getTags().get(0);
      System.out.println("---key=  " + tag + " " + key);
      List list = (List) entry.getValue();
      if (list.size() > 0) {

        System.out.println("**succ set: size: " + list.size());
        Iterator it = list.iterator();
        while (it.hasNext()) {
          JPegStmt stmt = (JPegStmt) it.next();
          Tag tag1 = (Tag) stmt.getTags().get(0);
          System.out.println(tag1 + " " + stmt);
        }
      }
    }
    System.out.println("=========unitToSucc--ends--------");
  }
Пример #26
0
 /**
  * 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;
 }
Пример #27
0
  /*
   * Cria uma nova Tarefa.
   * Retorna true se foi criada com sucesso false caso contrário
   */
  public boolean newTask(String type, Packet objects) {
    if (type.equals("")) return false;
    lock.lock();
    try {
      if (this.tasks.containsKey(type)) {
        return false;
      } else {
        HashMap<String, String> aux = objects.getArgs();
        HashMap<String, Integer> objs = new HashMap<>();
        for (Map.Entry<String, String> entry : aux.entrySet()) {
          objs.put(entry.getKey(), Integer.parseInt((entry.getValue())));
        }
        Task t = new Task(type, objs, lock);

        this.tasks.put(type, t);

        return true;
      }
    } finally {
      lock.unlock();
    }
  }
Пример #28
0
  public FunctionalTest() throws IOException {
    Vector v = new Vector();
    for (Enumeration e = v.elements(); e.hasMoreElements(); ) {}
    IOException e = new IOException();

    // this is to test excluding literals
    String buz = "text/plain";

    // this is to test array handling
    ArrayList[] foo = new ArrayList[0];
    ArrayList bar = new ArrayList();
    bar.add(HashSet.class);
    bar.add(Integer.class);
    File[] files = (File[]) bar.toArray(new File[0]);

    // this is to test imports of inner classes
    HashMap biv = new HashMap();
    Set set = biv.entrySet();
    Iterator iter = set.iterator();
    bar.add((Entry) iter.next());

    // this is to test inclusion of classes from java.lang.reflect
    Modifier m = new Modifier();

    // This next one can't be picked up by importscrubber because the compiler inlines it
    // System.out.println("A JOptionPane thingy " + JOptionPane.CANCEL_OPTION);
    // bummer!

    // this is to test importing a class and only calling a static method on it
    // Buz.doSomething();

    // this is to test NOT importing classes which are fully qualified in the class body
    // java.sql.Date sqlDate = new java.sql.Date(20);
    // Date javaDate = new Date();

    throw new IllegalArgumentException();
  }
Пример #29
0
  // This method adds the monitorenter/exit statements into whichever pegChain contains the
  // corresponding node statement
  protected void addMonitorStmt() {
    // System.out.println("====entering addMonitorStmt");
    if (synch.size() > 0) {
      // System.out.println("synch: "+synch);
      Iterator<List> it = synch.iterator();
      while (it.hasNext()) {
        List list = it.next();

        JPegStmt node = (JPegStmt) list.get(0);
        JPegStmt enter = (JPegStmt) list.get(1);
        JPegStmt exit = (JPegStmt) list.get(2);
        //		System.out.println("monitor node: "+node);
        // System.out.println("monitor enter: "+enter);
        // System.out.println("monitor exit: "+exit);
        // add for test
        // System.out.println("allNodes contains node: "+allNodes.contains(node));
        // end add for test

        {
          if (!mainPegChain.contains(node)) {

            boolean find = false;
            // System.out.println("main chain does not contain node");
            Set maps = startToThread.entrySet();
            // System.out.println("size of startToThread: "+startToThread.size());
            for (Iterator iter = maps.iterator(); iter.hasNext(); ) {
              Map.Entry entry = (Map.Entry) iter.next();
              Object startNode = entry.getKey();
              Iterator runIt = ((List) entry.getValue()).iterator();
              while (runIt.hasNext()) {
                Chain chain = (Chain) runIt.next();
                //	testPegChain(chain);
                if (chain.contains(node)) {
                  find = true;
                  // System.out.println("---find it---");
                  chain.add(enter);
                  chain.add(exit);
                  break;
                }
              }
            }
            if (find == false) {
              System.err.println("fail to find stmt: " + node + " in chains!");
              System.exit(1);
            }

            // this.toString();
          } else {
            mainPegChain.add(enter);
            mainPegChain.add(exit);
          }
        }

        allNodes.add(enter);
        allNodes.add(exit);

        insertBefore(node, enter);
        insertAfter(node, exit);
      }
    }
    // add for test
    /*
    {
    // System.out.println("===main peg chain===");
     //testPegChain(mainPegChain);
      //System.out.println("===end main peg chain===");
       Set maps = startToThread.entrySet();
       for(Iterator iter=maps.iterator(); iter.hasNext();){
       Map.Entry entry = (Map.Entry)iter.next();
       Object startNode = entry.getKey();
       Iterator runIt  = ((List)entry.getValue()).iterator();
       while (runIt.hasNext()){
       Chain chain=(Chain)runIt.next();
       testPegChain(chain);
       }
       }
       }
       */
    //	System.out.println(this.toString());
    // end add for test
  }
Пример #30
0
  public static void main(String[] args) {

    Scanner readStop = null;
    try {
      readStop = new Scanner(new FileInputStream("stoplist.txt"));
    } catch (FileNotFoundException e) {
      System.out.println("File not found.");
      System.exit(0);
    }
    while (readStop.hasNext()) {
      stopList.add(readStop.next());
    }

    HashMap<String, Integer> DF = new HashMap<String, Integer>(); // 存term與DF的對照
    HashMap<String, Double> IDF = new HashMap<String, Double>(); // 存term與IDF的對照
    HashMap<String, Integer> tID = new HashMap<String, Integer>(); // 存term與t_index的對照
    HashMap<String, Double> TFIDF = new HashMap<String, Double>(); // 存term的TFIDF

    // 這三個可以先算好以節省時間,時間就是金錢啊
    DF = DF();
    IDF = IDF(DF());
    tID = tID(DF());

    // 將Dictionary轉成List,並按字母順序重新排列
    List<Map.Entry<String, Integer>> list_Data =
        new ArrayList<Map.Entry<String, Integer>>(tID.entrySet());
    Collections.sort(
        list_Data,
        new Comparator<Map.Entry<String, Integer>>() {
          public int compare(Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) {
            return (entry1.getKey().compareTo(entry2.getKey()));
          }
        });
    try {
      // Create file
      FileWriter fstream = new FileWriter("dictionary.txt");
      BufferedWriter fileOut = new BufferedWriter(fstream);
      fileOut.write("t_index term df\r\n");
      for (Map.Entry<String, Integer> entry : list_Data) {
        fileOut.write(entry.getValue() + " " + entry.getKey() + " " + DF.get(entry.getKey()));
        fileOut.write("\r\n");
      }

      fileOut.close();
    } catch (Exception e) { // Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }

    // 把每篇文章每個term的TFIDF算出來照順序排好
    for (int i = 1; i <= 1095; i++) {
      TFIDF = TFIDF(normalTF(tokenize(i)), IDF);
      List<Map.Entry<String, Double>> list_Data2 =
          new ArrayList<Map.Entry<String, Double>>(TFIDF.entrySet());
      Collections.sort(
          list_Data2,
          new Comparator<Map.Entry<String, Double>>() {
            public int compare(Map.Entry<String, Double> entry1, Map.Entry<String, Double> entry2) {
              return (entry1.getKey().compareTo(entry2.getKey()));
            }
          });
      try {
        // Create file
        FileWriter fstream = new FileWriter("TFIDF/" + i + ".txt");
        BufferedWriter fileOut = new BufferedWriter(fstream);

        for (Map.Entry<String, Double> entry : list_Data2) {
          fileOut.write(tID.get(entry.getKey()) + " " + entry.getValue());
          fileOut.write("\r\n");
        }

        fileOut.close();
      } catch (Exception e) { // Catch exception if any
        System.err.println("Error: " + e.getMessage());
      }
    }
    System.out.println(cosine(1, 2, IDF));
  }