Example #1
0
  public static void qsHelp(int lo, int hi, ArrayList<Book> d) {

    if (lo >= hi) return;

    int tmpLo = lo;
    int tmpHi = hi;
    Book pivot = d.get(lo);

    while (tmpLo < tmpHi) {
      // first, slide markers in as far as possible without swaps
      while (d.get(tmpLo).compareTo(pivot) < 0) {
        // System.out.println("2");
        tmpLo++;
      }
      while (d.get(tmpHi).compareTo(pivot) > 0) {
        // System.out.println("3");
        tmpHi--;
      }

      swap(tmpLo, tmpHi, d);
    }

    // pivot has been floating around... plant it where it belongs
    d.set(tmpLo, pivot);

    // recurse on lower and upper ranges
    qsHelp(lo, tmpLo - 1, d);
    qsHelp(tmpLo + 1, hi, d);
  } // end qsHelp
  public static ArrayList<TaggedWord> StopWordRemoval(ArrayList<TaggedWord> taggedWords) {
    ArrayList<TaggedWord> newList = new ArrayList<TaggedWord>();

    try {
      String path = "data/nltk_stoplist.txt";
      File textFile = new File(path);
      BufferedReader br = new BufferedReader(new FileReader(textFile));
      String stopwordsLine = br.readLine();
      br.close();

      String[] stopwords = stopwordsLine.split(",");
      HashMap<String, String> stopwordsDict = new HashMap<String, String>();
      for (int i = 0; i < stopwords.length; i++) {
        stopwordsDict.put(stopwords[i], stopwords[i]);
      }

      for (int i = 0; i < taggedWords.size(); i++) {
        String word = taggedWords.get(i).word();
        String posTag = taggedWords.get(i).tag();

        if (!stopwordsDict.containsKey(word.toLowerCase())) {
          String newWord, newPosTag;
          newWord = word;
          newPosTag = posTag;
          newList.add(new TaggedWord(newWord, newPosTag));
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return newList;
  }
 public static void main(String[] args) throws IOException {
   BufferedReader f = new BufferedReader(new FileReader("barn1.in"));
   out = new PrintWriter(new BufferedWriter(new FileWriter("barn1.out")));
   StringTokenizer nstr = new StringTokenizer(f.readLine());
   int m = Integer.parseInt(nstr.nextToken());
   int s = Integer.parseInt(nstr.nextToken());
   occupied = new ArrayList<ArrayList<Integer>>();
   occupied.add(new ArrayList<Integer>());
   for (int i = 0; i < s; i++) {
     try {
       nstr = new StringTokenizer(f.readLine());
       occupied.get(0).add(Integer.parseInt(nstr.nextToken()));
     } catch (NullPointerException e) {
       break;
     }
   }
   Collections.sort(occupied.get(0));
   int bound = m - 1;
   if (occupied.get(0).size() - 1 < bound) {
     bound = occupied.get(0).size() - 1;
   }
   for (int i = 0; i < bound; i++) {
     findMaxCut();
   }
   int total = 0;
   int len = occupied.size();
   for (int i = 0; i < len; i++) {
     ArrayList<Integer> arr = occupied.get(i);
     int len2 = arr.size();
     total += arr.get(len2 - 1) - arr.get(0) + 1;
   }
   out.println(total);
   out.close();
   System.exit(0);
 }
Example #4
0
  private static void getTopDocuments(int num, HashMap<String, Float> scoremap, String filename)
      throws FileNotFoundException {
    PrintWriter out = new PrintWriter(filename);
    Iterator<String> itr = scoremap.keySet().iterator();
    ArrayList<String> urls = new ArrayList<String>();
    ArrayList<Float> scores = new ArrayList<Float>();

    while (itr.hasNext()) {
      String key = itr.next();
      if (scores.size() < num) {
        scores.add(scoremap.get(key));
        urls.add(key);
      } else {
        int index = scores.indexOf(Collections.min(scores));
        if (scores.get(index) < scoremap.get(key)) {
          scores.set(index, scoremap.get(key));
          urls.set(index, key);
        }
      }
    }

    while (scores.size() > 0) {
      int index = scores.indexOf(Collections.max(scores));
      out.println(urls.get(index) + "\t" + scores.get(index));
      urls.remove(index);
      scores.remove(index);
    }
    out.close();
  }
 private boolean processURL(URL url, String baseDir, StatusWindow status) throws IOException {
   if (processedLinks.contains(url)) {
     return false;
   } else {
     processedLinks.add(url);
   }
   URLConnection connection = url.openConnection();
   InputStream in = new BufferedInputStream(connection.getInputStream());
   ArrayList list = processPage(in, baseDir, url);
   if ((status != null) && (list.size() > 0)) {
     status.setMaximum(list.size());
   }
   for (int i = 0; i < list.size(); i++) {
     if (status != null) {
       status.setMessage(Utils.trimFileName(list.get(i).toString(), 40), i);
     }
     if ((!((String) list.get(i)).startsWith("RUN"))
         && (!((String) list.get(i)).startsWith("SAVE"))
         && (!((String) list.get(i)).startsWith("LOAD"))) {
       processURL(
           new URL(url.getProtocol(), url.getHost(), url.getPort(), (String) list.get(i)),
           baseDir,
           status);
     }
   }
   in.close();
   return true;
 }
Example #6
0
  /*
  	-- This is a helper methid to run the morph files
  */
  private static void runMorphDataSet() throws Exception {

    String morph_directory =
        "../../thesis-datasets/morph/"; // directory where all the morph code is stored
    File d = new File(morph_directory);
    // get all the files from a directory
    File[] fList = d.listFiles();
    List<String> dir_list = new ArrayList<String>();
    for (File file : fList) {
      if (file.isDirectory()) {
        dir_list.add(file.getName());
      }
    }
    for (String dir : dir_list) {
      directory = morph_directory + dir + "/";
      System.out.println("Running TDDD " + directory);
      ReadFile.readFile(directory, fileList); // read the two files
      System.out.println(fileList.get(0) + " " + fileList.get(1));
      preliminaryStep(directory);
      startCDC();
      fileList.clear();
      fileArray.clear();
      hashed_File_List.clear();
    }
  }
Example #7
0
 public static void main(String... orange) throws IOException {
   Scanner scan = new Scanner(new File("barn1.in"));
   PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("barn1.out")));
   int bars = scan.nextInt();
   int total = scan.nextInt();
   int have = scan.nextInt();
   ArrayList<Integer> values = new ArrayList<Integer>();
   ArrayList<Integer> locations = new ArrayList<Integer>();
   for (int i = 0; i < have; i++) {
     values.add(scan.nextInt());
   }
   Collections.sort(values);
   int first = values.get(0);
   for (int i = 1; i < have; i++) {
     int current = values.get(i);
     locations.add(current - first);
     first = current;
   }
   if (bars >= have) {
     out.println(have);
   } else {
     for (int i = 0; i < bars - 1; i++) {
       locations.remove(Collections.max(locations));
     }
     int sum = 0;
     for (int i = 0; i < locations.size(); i++) sum += locations.get(i);
     sum += bars;
     out.println(sum);
   }
   out.close();
   System.exit(0);
 }
Example #8
0
  /**
   * The constructor creates a new empty Sudoku puzzle containing 81 unset clues.
   *
   * <p>A new puzzle will have a cardinality of 0, will be unmodified, and will contain 0 conflicts.
   */
  public Puzzle() {

    rows = new ArrayList<Unit>(9);
    cols = new ArrayList<Unit>(9);
    boxes = new ArrayList<Unit>(9);

    for (int i = 0; i < 9; i++) {
      rows.add(new Unit());
      cols.add(new Unit());
      boxes.add(new Unit());
    }

    for (int r = 0; r < 9; r++) {
      for (int c = 0; c < 9; c++) {
        int b = this.boxNumber(r, c);
        Cell thisCell = new Cell(r, b, c);
        rows.get(r).setCell(c, thisCell);
        cols.get(c).setCell(r, thisCell);
        boxes.get(b).setCell(this.boxPosition(r, c), thisCell);
      }
    }

    cardinality = 0;
    modified = false;
    conflicts = 0;
  }
Example #9
0
 public boolean onPartAll(String sender, String reason) {
   int d = channels.size();
   d--;
   for (int i = 0; i <= channels.size(); i++) {
     boolean f = inChannel(channels.get(d));
     if (!f) {
       return true;
     } else {
       try {
         if (reason == null) {
           this.partChannel(
               channels.get(i),
               config.getProperty("disconnect-message") + "  (Requested by " + sender + ")");
         } else {
           this.partChannel(
               channels.get(i),
               config.getProperty("disconnect-message")
                   + " (Reason: "
                   + reason
                   + "  (Requested by "
                   + sender
                   + "))");
         }
       } catch (Exception ex) {
         return true;
       }
     }
   }
   return false;
 }
Example #10
0
 public static void main(String[] args) throws IOException {
   Scanner scan = new Scanner(/*System.in*/ new File("ariprog.in"));
   PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("ariprog.out")));
   int length = scan.nextInt();
   int max = scan.nextInt();
   int[] squares = new int[(max) * max * 2 + 1];
   // ArrayList<Integer> squares = new ArrayList<Integer>();
   for (int i = 0; i <= max; i++) {
     for (int j = i; j <= max; j++) {
       squares[i * i + j * j] = 1;
     }
   }
   ArrayList<Integer> starts = new ArrayList<Integer>();
   ArrayList<Integer> diffs = new ArrayList<Integer>();
   boolean has = false;
   for (int diff = 1; diff <= ((max * max * 2 / (length - 1))); diff++) {
     for (int start = 0; start < squares.length - length; start++) {
       if (squares[start] == 1) {
         if (check(diff, start, squares, length)) {
           starts.add(start);
           diffs.add(diff);
           // out.println(squares[start] + " " + diff);
           has = true;
         }
       }
     }
   }
   remove(starts, diffs);
   for (int i = 0; i < starts.size(); i++) {
     /*System.*/ out.println(starts.get(i) + " " + diffs.get(i));
   }
   if (!has) /*System.*/ out.println("NONE");
   out.close();
   System.exit(0);
 }
Example #11
0
 static void printAnswer(String nameFile) throws Exception {
   FileWriter out = null;
   File file = null;
   try {
     if (isO) {
       file = new File(nameFile);
       out = new FileWriter(file);
       for (int i = 0; i < ans.size(); i++) {
         if (!isU || i == 0) {
           out.write(ans.get(i).toString() + "\n");
         } else {
           String last = ans.get(i - 1).toString();
           String now = ans.get(i).toString();
           if (isI) {
             last = last.toLowerCase();
             now = now.toLowerCase();
           }
           if (!last.equals(now)) {
             out.write(ans.get(i).toString() + "\n");
           }
         }
       }
     } else {
       for (int i = 0; i < ans.size(); i++) {
         System.out.println(ans.get(i).toString());
       }
     }
   } finally {
     if (out != null) {
       out.close();
     }
   }
 }
  /** Get the panel for a given form. * */
  public JPanel getPanelFor(ArrayList elements) {
    JPanel p = new JPanel(new GridBagLayout());
    int maxCols = 1;
    int elementSize = elements.size();
    for (int i = 0; i < elementSize; i++) { // count max number of cols
      // ((XmlUIElement)elements.get(i)).setEditable(true);//by jai
      int cols = ((XmlUIElement) elements.get(i)).getNumberOfColumns();
      if (cols > maxCols) {
        maxCols = cols;
      }
    }
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.gridx = 0;
    c.gridy = 0;
    if (elementSize < 5) c.insets = new Insets(8, 8, 8, 14);
    else if (elementSize < 20) c.insets = new Insets(4, 4, 4, 10);
    else if ((elementSize > 40 && maxCols == 2) || (elementSize > 80 && maxCols == 4))
      c.insets = new Insets(1, 1, 1, 8);
    else c.insets = new Insets(2, 2, 2, 8);

    int rowsAdded = 0;
    for (int i = 0; i < elementSize; i++) {
      elementsAndPanels.put(elements.get(i), p);
      rowsAdded += ((XmlUIElement) elements.get(i)).addComponents(p, c, 0, rowsAdded, maxCols);
    }
    return p;
  }
Example #13
0
  @Override
  public BoundingBox getBounds() {
    // If there are no charges, return an empty box.
    if (charges.size() <= 0) return new BoundingBox(0, 0, 0, 0, 0, 0);

    if (cachedBounds == null) {
      // Start with the box of the first charge.
      Charge c = charges.get(0);
      double ext = Math.abs(c.w);
      double corr = 1.0 + (0.1 / hardness); // see note
      cachedBounds =
          new BoundingBox(
              new Vec3(c.x - ext, c.y - ext, c.z - ext).times(corr),
              new Vec3(c.x + ext, c.y + ext, c.z + ext).times(corr));

      // A note on "corr":
      // As blobs are blobby, we can't use their weight/radius
      // directly. This would result in unwanted cut-off's. To
      // correct this, we extend the bounding box of a charge "a
      // bit". That "bit" can be smaller if the charge is harder.

      // Iteratively add the remaining charges.
      for (int i = 1; i < charges.size(); i++) {
        c = charges.get(i);
        ext = Math.abs(c.w);
        corr = 1.0 + (0.1 / hardness);
        cachedBounds.extend(
            new BoundingBox(
                new Vec3(c.x - ext, c.y - ext, c.z - ext).times(corr),
                new Vec3(c.x + ext, c.y + ext, c.z + ext).times(corr)));
      }
    }

    return cachedBounds;
  }
Example #14
0
  private static void processMapDump(Scanner mapScan) {
    String line = "";

    ArrayList<String> threeF = new ArrayList<String>();
    ArrayList<String> oneF = new ArrayList<String>();

    while (mapScan.hasNextLine()) {
      line = mapScan.nextLine();
      String tokens[] = line.split(" ");
      if (tokens[1].equals("3f")) {
        threeF.add(line);
      }
      if (tokens[1].equals("1f")) {
        oneF.add(line);
      }
    }
    if (line.charAt(line.length() - 1) == '0') {
      line = threeF.get(threeF.size() - 1);
    } else {
      line = oneF.get(oneF.size() - 1);
    }
    String delims = "[ ]+";
    String[] tokens = line.split(delims);
    for (int i = 2; i < tokens.length - 1; i++) {
      log2phyMAP.put(hexToDec(tokens[i].substring(4, 5)), hexToDec(tokens[i].substring(1, 3)));
    }
    // System.out.println(log2phyMAP.toString());
  }
Example #15
0
 public static void main(String[] args) throws IOException {
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   String[] temp = in.readLine().split(" ");
   int n = Integer.parseInt(temp[0]);
   int s = Integer.parseInt(temp[1]);
   HashMap<Integer, Integer> buy = new HashMap<>();
   HashMap<Integer, Integer> sell = new HashMap<>();
   for (int i = 1; i <= n; i++) {
     temp = in.readLine().split(" ");
     int p = Integer.parseInt(temp[1]);
     int q = Integer.parseInt(temp[2]);
     if (temp[0].charAt(0) == 'B') {
       if (buy.containsKey(p)) buy.put(p, buy.get(p) + q);
       else buy.put(p, q);
     } else {
       if (sell.containsKey(p)) sell.put(p, sell.get(p) + q);
       else sell.put(p, q);
     }
   }
   ArrayList<Integer> buyArr = new ArrayList<>();
   ArrayList<Integer> sellArr = new ArrayList<>();
   for (Integer i : buy.keySet()) buyArr.add(i);
   for (Integer i : sell.keySet()) sellArr.add(i);
   Collections.sort(buyArr, Comparator.reverseOrder());
   Collections.sort(sellArr);
   for (int i = Math.min(s, sellArr.size()) - 1; i >= 0; i--)
     System.out.println("S " + sellArr.get(i) + " " + sell.get(sellArr.get(i)));
   for (int i = 0; i < s && i < buyArr.size(); i++)
     System.out.println("B " + buyArr.get(i) + " " + buy.get(buyArr.get(i)));
 }
  public void draw() {
    background(255);

    // Turn off highlighting for all obstalces
    for (int i = 0; i < obstacles.size(); i++) {
      Obstacle o = (Obstacle) obstacles.get(i);
      o.highlight(false);
    }

    // Act on all boids
    for (int i = 0; i < boids.size(); i++) {
      Boid b = (Boid) boids.get(i);
      b.avoid(obstacles);
      b.run();
    }

    // Display the obstacles
    for (int i = 0; i < obstacles.size(); i++) {
      Obstacle o = (Obstacle) obstacles.get(i);
      o.display();
    }

    // Instructions
    textFont(f);
    fill(0);
    text(
        "Hit space bar to toggle debugging lines.\nClick the mouse to generate a new boids.",
        10,
        height - 30);
  }
Example #17
0
  /*
  	-- This is a helper method run datasets such as emacs, gcc etc

  */
  private static void runOtherDataSets() throws Exception {
    System.out.println("Running tddd " + directory);
    ReadFile.readFile(directory, fileList); // read the two files
    System.out.println(fileList.get(0) + " " + fileList.get(1));
    preliminaryStep(directory);
    startCDC();
  }
Example #18
0
 /** generate mention annotations (with entity numbers) based on the ACE entities and mentions. */
 static void addMentionTags(Document doc, AceDocument aceDoc) {
   ArrayList<AceEntity> entities = aceDoc.entities;
   for (int i = 0; i < entities.size(); i++) {
     AceEntity entity = entities.get(i);
     ArrayList<AceEntityMention> mentions = entity.mentions;
     for (int j = 0; j < mentions.size(); j++) {
       AceEntityMention mention = (AceEntityMention) mentions.get(j);
       // we compute a jetSpan not including trailing whitespace
       Span aceSpan = mention.head;
       // skip mentions in ChEnglish APF not aligned to any English text
       if (aceSpan.start() < 0) continue;
       Span jetSpan = new Span(aceSpan.start(), aceSpan.end() + 1);
       FeatureSet features = new FeatureSet("entity", new Integer(i));
       if (flags.contains("types")) {
         features.put("type", entity.type.substring(0, 3));
         if (entity.subtype != null) features.put("subtype", entity.subtype);
       }
       if (flags.contains("extents")) {
         String cleanExtent = mention.text.replaceAll("\n", " ");
         features.put("extent", AceEntityMention.addXmlEscapes(cleanExtent));
       }
       doc.annotate("mention", jetSpan, features);
     }
   }
 }
Example #19
0
  /*
  	Read in all the files and loop through all the files
  	We already have the hashed version of the documents
  	First, we cut up the first document into chunks (using the CDC algorhtim) and store it
  	Then we cut up the second document (usually a different version of the same document) and see how many chunks match
  */
  private static void runBytes(
      int window,
      long divisor1,
      long divisor2,
      long divisor3,
      long remainder,
      Long minBoundary,
      Long maxBoundary)
      throws Exception {

    storeChunks(
        fileArray.get(0),
        hashed_File_List.get(0),
        divisor1,
        divisor2,
        divisor3,
        remainder,
        minBoundary,
        maxBoundary); // here we run 2min, ck how similar the documents are to the one already in
                      // the system
    runTddd(
        fileArray.get(1),
        hashed_File_List.get(1),
        divisor1,
        divisor2,
        divisor3,
        remainder,
        minBoundary,
        maxBoundary); // here we run 2min, ck how similar the documents are to the one already in
                      // the system
  } // end of the function
 public static void apply_splits_to_stock_hashtable(
     Hashtable<String, ArrayList<DayDataXv>> hashtable) {
   // Get all the stock names.
   Set<String> all_keys = hashtable.keySet();
   // Go through each stock.
   for (String key : all_keys) {
     // If the stock has splits...
     if (SplitsXv.does_stock_have_splits(StockXv.get_stock_name_purged(key))) {
       // Get the splits.
       ArrayList<SplitXv> splits =
           SplitsXv.get_all_splits_for_stock(StockXv.get_stock_name_purged(key));
       // Go through each split.
       for (SplitXv s : splits) {
         // Get the days from the stock.
         ArrayList<DayDataXv> all_days = hashtable.get(key);
         // Make sure the split fits in the time range.
         if (!DayDataXv.is_date_before_date(s.getDate(), all_days.get(0).get_date())) {
           // Do nothing if it is not in the time range.
         } else if (s.getDate().equals(all_days.get(0).get_date())) {
           all_days.get(0).multiply_all_by(s.getAmount());
         } else {
           // Go through each day.
           for (DayDataXv d : all_days) {
             // Apply "reverse-split" until split date is reached.
             d.multiply_all_by(s.getAmount());
             if (d.get_date().equals(s.getDate())) {
               break;
             }
           }
         }
       }
     }
   }
 }
  /* Scan the files in the new directory, and store them in the filelist.
   * Update the UI by refreshing the list adapter.
   */
  private void loadDirectory(String newdirectory) {
    if (newdirectory.equals("../")) {
      try {
        directory = new File(directory).getParent();
      } catch (Exception e) {
      }
    } else {
      directory = newdirectory;
    }
    SharedPreferences.Editor editor = getPreferences(0).edit();
    editor.putString("lastBrowsedDirectory", directory);
    editor.commit();
    directoryView.setText(directory);

    filelist = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedDirs = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedFiles = new ArrayList<FileUri>();
    if (!newdirectory.equals(rootdir)) {
      String parentDirectory = new File(directory).getParent() + "/";
      Uri uri = Uri.parse("file://" + parentDirectory);
      sortedDirs.add(new FileUri(uri, parentDirectory));
    }
    try {
      File dir = new File(directory);
      File[] files = dir.listFiles();
      if (files != null) {
        for (File file : files) {
          if (file == null) {
            continue;
          }
          String filename = file.getName();
          if (file.isDirectory()) {
            Uri uri = Uri.parse("file://" + file.getAbsolutePath() + "/");
            FileUri fileuri = new FileUri(uri, uri.getPath());
            sortedDirs.add(fileuri);
          } else if (filename.endsWith(".mid")
              || filename.endsWith(".MID")
              || filename.endsWith(".midi")
              || filename.endsWith(".MIDI")) {

            Uri uri = Uri.parse("file://" + file.getAbsolutePath());
            FileUri fileuri = new FileUri(uri, uri.getLastPathSegment());
            sortedFiles.add(fileuri);
          }
        }
      }
    } catch (Exception e) {
    }

    if (sortedDirs.size() > 0) {
      Collections.sort(sortedDirs, sortedDirs.get(0));
    }
    if (sortedFiles.size() > 0) {
      Collections.sort(sortedFiles, sortedFiles.get(0));
    }
    filelist.addAll(sortedDirs);
    filelist.addAll(sortedFiles);
    adapter = new IconArrayAdapter<FileUri>(this, android.R.layout.simple_list_item_1, filelist);
    this.setListAdapter(adapter);
  }
 private static void displayPhoneBooks(ArrayList<String> phoneBooks)
     throws IOException, ParseException {
   if (phoneBooks.size() == 0) {
     System.out.println("\nNO PHONEBOOK AVAILABLE.CREATE A NEW PHONEBOOK.\n");
     return;
   } else {
     System.out.println("FOLLOWING ARE THE AVAILABLE PHONEBOOKS.");
     System.out.println("----------------------------------------\n");
     Scanner sc = new Scanner(System.in);
     for (int i = 0; i < phoneBooks.size(); i++) {
       String s = phoneBooks.get(i);
       System.out.println(s + "\t->PRESS " + (i + 1) + " LOAD THIS.");
     }
     System.out.println("TO GO BACK TO THE PREVIOUS MENU->PRESS " + (phoneBooks.size() + 1));
     int ch = 0;
     while (ch < 1 || ch > (phoneBooks.size() + 1)) {
       while (!sc.hasNextInt()) {
         System.out.println("\nONLY NUMBERS LISTED ABOVE SHOULD BE ENTERED..RETRY..");
         sc.nextLine();
       }
       ch = sc.nextInt();
       if (ch < 1 || ch > phoneBooks.size())
         System.out.println("\nONLY NUMBERS LISTED ABOVE SHOULD BE ENTERED..RETRY..");
     }
     if (ch == (phoneBooks.size() + 1)) return;
     contactBookOperations(phoneBooks.get(ch - 1) + ".txt");
   }
 }
Example #23
0
 private int min(ArrayList<Integer> points) {
   int res = points.get(0);
   for (int i = 1; i < points.size(); i++) {
     res = Math.min(res, points.get(i));
   }
   return res;
 }
Example #24
0
  /** When a new set of saved statements come in, refresh the menu of saved statements. */
  private void refreshSaveMenu() {
    ArrayList list;
    // first, delete what's already there
    for (; ; ) {
      Component comp = popup.getComponent(1);
      if (!(comp instanceof JMenuItem)) break;

      JMenuItem item = (JMenuItem) comp;
      if (item.getActionCommand().startsWith("save:")) popup.remove(1);
      else break;
    }
    StatementHistory history;
    history = sshare.statementHistory();
    // now insert the new list of saved statements
    list = history.getNamedStatementList();
    Color bgColor = Util.getBgColor();
    for (int i = 0; i < list.size(); i++) {
      ArrayList nameNlabel = (ArrayList) list.get(i);
      JMenuItem item = new JMenuItem("  " + (String) nameNlabel.get(1));
      item.setActionCommand("save:" + (String) nameNlabel.get(0));
      popup.add(item, 1);
      //	    item.setBackground(bgColor);
      item.addActionListener(popActionListener);
    }
  } // refreshSaveMenu()
  public static ArrayList<ArrayList<TaggedWord>> getPhrasesNaive(
      String sentence, LexicalizedParser lp, AbstractSequenceClassifier<CoreLabel> classifier) {
    ArrayList<ArrayList<TaggedWord>> newList = new ArrayList<ArrayList<TaggedWord>>();
    ArrayList<TaggedWord> taggedWords = StanfordNER.parse(sentence, lp, classifier);
    HashMap<String, String> phraseBoundaries = new HashMap<String, String>();
    phraseBoundaries.put(",", ",");
    phraseBoundaries.put("\"", "\"");
    phraseBoundaries.put("''", "''");
    phraseBoundaries.put("``", "``");
    phraseBoundaries.put("--", "--");
    // List<Tree> leaves = parse.getLeaves();
    ArrayList<TaggedWord> temp = new ArrayList<TaggedWord>();
    int index = 0;
    while (index < taggedWords.size()) {
      if ((phraseBoundaries.containsKey(taggedWords.get(index).word()))) {
        if (temp.size() > 0) {
          // System.out.println(temp);
          ArrayList<TaggedWord> tempCopy = new ArrayList<TaggedWord>(temp);
          newList.add(Preprocess(tempCopy));
        }
        temp.clear();
      } else {
        // System.out.println(taggedWords.get(index).toString());
        temp.add(taggedWords.get(index));
      }
      index += 1;
    }
    if (temp.size() > 0) {
      ArrayList<TaggedWord> tempCopy = new ArrayList<TaggedWord>(temp);
      newList.add(Preprocess(tempCopy));
    }

    // System.out.println(newList);
    return newList;
  }
Example #26
0
 public void drawOrbits(ArrayList alObjectsArchive) {
   //  println("SIZE:" + alObjectsArchive.size());
   //  ArrayList alObjectsArchive = timeline.getObjectStateArchive();
   ArrayList alPrevPos = new ArrayList();
   ArrayList alColors = new ArrayList();
   alColors.add(color(255, 0, 0));
   alColors.add(color(255, 255, 0));
   alColors.add(color(255, 0, 255));
   //  for (int i = timeline.getTimeIdx(); i >= 0 && i > (timeline.getTimeIdx() - 1 - 100); i--)
   for (int i = 0; i < alObjectsArchive.size(); i++) {
     ArrayList objects = (ArrayList) alObjectsArchive.get(i);
     for (int j = 0; j < objects.size(); j++) {
       CelestialObject obj = (CelestialObject) objects.get(j);
       //      CelestialObject obj = (CelestialObject)objects.get(1);
       PVector pos = obj.getPosition();
       //      stroke(0, 0, 255);
       stroke((Integer) alColors.get(j));
       if (alPrevPos.size() == objects.size()) {
         PVector prevPos = (PVector) alPrevPos.get(j);
         line(prevPos.x, prevPos.y, pos.x, pos.y);
         alPrevPos.set(j, pos);
       } else alPrevPos.add(pos);
     }
   }
 }
  public static void main(String[] args) {
    ArrayList<Pattern> patterns = new ArrayList<Pattern>();
    ArrayList<Cut> cuts;
    ArrayList<Garment> garments;

    patterns.add(new Pattern(2, 2, 1, "Tie"));
    patterns.add(new Pattern(2, 6, 4, "Skirt"));
    patterns.add(new Pattern(4, 2, 3, "Blouse"));
    patterns.add(new Pattern(5, 3, 5, "Dress"));
    int width = 30;
    int height = 15;
    ClothCutter cutter = new ClothCutter(width, height, patterns);
    System.out.println("Optimized value: " + cutter.optimize());
    cuts = cutter.getCuts();
    garments = cutter.getGarments();

    ClothPanel panel = new ClothPanel(width, height);
    JFrame frame = new JFrame("A luxurious bolt of fabric");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true);
    sleep(1000);
    for (int i = 0; i < cuts.size(); i++) {
      panel.drawCut(cuts.get(i));
      sleep(100);
    }
    for (int i = 0; i < garments.size(); i++) {
      System.out.println(garments.get(i));
      panel.drawGarment(garments.get(i));
      sleep(100);
    }
  }
 /**
  * setupConnectedCards.
  *
  * @param connectedCards a {@link java.util.ArrayList} object.
  */
 public static void setupConnectedCards(ArrayList<CardPanel> connectedCards) {
   for (int i = connectedCards.size() - 1; i > 0; i--) {
     // System.out.println("We should have a stack");
     CardPanel cp = connectedCards.get(i);
     cp.connectedCard = connectedCards.get(i - 1);
   }
 }
 public void init() {
   Scanner scan = new Scanner(System.in);
   count = scan.nextInt();
   x0 = scan.nextLong();
   y0 = scan.nextLong();
   int result = 0;
   boolean special = false;
   for (int i = 0; i < count; i++) {
     long tempx = scan.nextLong();
     long tempy = scan.nextLong();
     if (tempx == x0 && tempy == y0) {
       special = true;
       continue;
     }
     boolean isDuplicate = false;
     for (int j = 0; j < result; j++) {
       long x1 = xList.get(j);
       long y1 = yList.get(j);
       if ((x1 - x0) * (tempy - y0) == (y1 - y0) * (tempx - x0)) {
         isDuplicate = true;
         break;
       }
     }
     if (!isDuplicate) {
       xList.add(tempx);
       yList.add(tempy);
       result++;
     }
   }
   if (special && result == 0) result = 1;
   System.out.println(result);
   scan.close();
 }
Example #30
0
  public static boolean searchBook(ArrayList<Book> o, Book target, int lo, int hi) {
    boolean found = false;
    // int m = (lo + hi) / 2;

    while (lo <= hi) {
      int m = (lo + hi) / 2;
      if (o.get(m).compareTo(target) == 0) {
        // System.out.println("Book has been found");
        found = true;
        if (o.get(m).getStatus() == true) {
          o.get(m).setStatus(false);
          System.out.print(
              "Thank you for checking out " + target.getTitle() + ". We hope you enjoy it!");
          return found;
        } else {
          System.out.println(
              "We are sorry to inform you that the book that you requested has already been checked out. Would you like to be added to the waiList for the book?");
          return found;
        }
      } else if (o.get(m).compareTo(target) > 0) {
        // System.out.println("searching in the lower range");
        hi = m - 1;
      } else if (o.get(m).compareTo(target) < 0) {
        // System.out.println("searching in the upper range");
        lo = m + 1;
      } else {
      }
    }

    return found;
  }