Example #1
0
 public final Seq Seq() throws ParseException {
   Cp cp;
   ArrayList<Cp> list0 = new ArrayList<Cp>();
   Cp cp1;
   ArrayList<Cp> cp1List = new ArrayList<Cp>();
   Token firstToken = token;
   jj_consume_token(OB);
   cp = Cp();
   list0.add(cp);
   label_3:
   while (true) {
     switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
       case 33:;
         break;
       default:
         jj_la1[6] = jj_gen;
         break label_3;
     }
     jj_consume_token(33);
     cp1 = Cp();
     list0.add(cp1);
   }
   jj_consume_token(CB);
   {
     if (true) return new Seq(list0, firstToken.next, token);
   }
   throw new Error("Missing return statement in function");
 }
Example #2
0
  public static void main(String[] args) throws FileNotFoundException {
    String s;

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

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

    System.out.println(ml);
    Iterator<Integer> mlit = ml.iterator();
    while (mlit.hasNext()) {
      System.out.println(mlit.next());
    }
  }
 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 #4
0
  public WDBObject[] search(SimpleNode expression, Adapter scda) throws Exception {
    boolean hasWhereClause = (expression != null);
    WDBObject[] matchesArray = new WDBObject[0];
    ArrayList<WDBObject> matchesList = new ArrayList<WDBObject>();
    WDBObject[] indexFilteredArray;
    if (hasWhereClause) {
      indexFilteredArray =
          expression
              .filterObjectsWithIndexes(scda, this.indexes)
              .getFilteredResults(scda, this.indexes);
    } else {
      indexFilteredArray = null;
    }
    if (indexFilteredArray == null) {
      // Simple for loop for search
      WDBObject object;
      for (int i = 0; i < this.instances.size(); i++) {
        object = this.getInstance(i, scda);
        if (!hasWhereClause || (hasWhereClause && expression.eval(scda, object))) {
          matchesList.add(object);
        }
      }
    } else {
      // Simple for loop for search
      for (int i = 0; i < indexFilteredArray.length; i++) {
        if (!hasWhereClause || (hasWhereClause && expression.eval(scda, indexFilteredArray[i]))) {
          matchesList.add(indexFilteredArray[i]);
        }
      }
    }

    return (WDBObject[]) matchesList.toArray(matchesArray);
  }
Example #5
0
 public void dfs(int v) {
   if (hasCycle) {
     return;
   }
   if (color[v] != 2) {
     color[v] = 1;
     if (graph[v] == null) {
       color[v] = 2;
       answer.add(v);
       return;
     }
     for (int i = 0; i < graph[v].size(); i++) {
       int to = graph[v].get(i);
       if (color[to] == 0) {
         dfs(to);
       }
       if (color[to] == 1) {
         hasCycle = true;
         return;
       }
     }
     color[v] = 2;
     answer.add(v);
   }
 }
Example #6
0
  /*
   * return an arraylist with elements:
   * 0: placeName
   * 1: lives
   * 2: name
   * 3: description
   * 4: strength
   */
  public ArrayList<String> getHero() {
    ArrayList<String> hero = new ArrayList<String>();
    // extract place
    int index = game.indexOf("\n");
    hero.add(game.substring(7, index));
    game = game.substring(index + 1);
    // extract lives
    index = game.indexOf("\n");
    String info = game.substring(7, index);
    game = game.substring(index + 1);
    hero.add(info);
    // extract name & description
    index = game.indexOf("\n");
    info = game.substring(0, index);
    game = game.substring(index + 1);
    index = info.indexOf(":");
    hero.add(info.substring(0, index));
    hero.add(info.substring(index + 2));
    // extract strength
    index = game.indexOf("\n");
    info = game.substring(10, index);
    game = game.substring(index + 1);
    hero.add(info);
    // remove next 2 lines of file
    game = game.substring(game.indexOf("\n") + 1);
    game = game.substring(game.indexOf("\n") + 1);
    // extract weapons

    // extract treasures

    return hero;
  }
  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);
    }
  }
Example #8
0
  private InstanceList readFile() throws IOException {

    String NL = System.getProperty("line.separator");
    Scanner scanner = new Scanner(new FileInputStream(fileName), encoding);

    ArrayList<Pipe> pipeList = new ArrayList<Pipe>();
    pipeList.add(new CharSequence2TokenSequence(Pattern.compile("\\p{L}\\p{L}+")));
    pipeList.add(new TokenSequence2FeatureSequence());

    InstanceList testing = new InstanceList(new SerialPipes(pipeList));

    try {
      while (scanner.hasNextLine()) {

        String text = scanner.nextLine();
        text = text.replaceAll("\\x0d", "");

        Pattern patten = Pattern.compile("^(.*?),(.*?),(.*)$");
        Matcher matcher = patten.matcher(text);

        if (matcher.find()) {
          docIds.add(matcher.group(1));
          testing.addThruPipe(new Instance(matcher.group(3), null, "test instance", null));
        }
      }
    } finally {
      scanner.close();
    }

    return testing;
  }
Example #9
0
 protected List<MappingWithDirection> findApplicable(MappingKey key) {
   ArrayList<MappingWithDirection> result = new ArrayList<MappingWithDirection>();
   for (ParsedMapping pm : mappings) {
     if ((pm.mappingCase == null && key.mappingCase == null)
         ^ (pm.mappingCase != null && pm.mappingCase.equals(key.mappingCase))) {
       if (pm.sideA.isAssignableFrom(key.source) && pm.sideB.isAssignableFrom(key.target))
         result.add(new MappingWithDirection(pm, true));
       else if (pm.sideB.isAssignableFrom(key.source) && pm.sideA.isAssignableFrom(key.target))
         result.add(new MappingWithDirection(pm, false));
     }
   }
   if (!result.isEmpty()) {
     Collections.sort(result, new MappingComparator(key.target));
   } else if (automappingEnabled) {
     logger.info(
         "Could not find applicable mappings between {} and {}. A mapping will be created using automapping facility",
         key.source.getName(),
         key.target.getName());
     ParsedMapping pm = new Mapping(key.source, key.target, this).automap().parse();
     logger.debug("Automatically created {}", pm);
     mappings.add(pm);
     result.add(new MappingWithDirection(pm, true));
   } else
     logger.warn(
         "Could not find applicable mappings between {} and {}!",
         key.source.getName(),
         key.target.getName());
   return result;
 }
Example #10
0
 public void testComplexSelectWithOrdering() throws Exception {
   removeAll(Book.class);
   ArrayList authors = new ArrayList();
   authors.add(new Author("Tom", "Petty"));
   authors.add(new Author("Lynyrd", "Skynyrd"));
   Book b1 = new Book("Book of Bokonon", "1-2-3-4");
   b1.setAuthors(authors);
   b1.setMainAuthor(new Author("Bokonon Jr.", ""));
   Book b2 = new Book("Book of Bokonon", "4-3-2-1");
   authors = new ArrayList();
   authors.add(new Author("Tom", "Petty"));
   b2.setAuthors(authors);
   b2.setMainAuthor(new Author("Bokonon", ""));
   Book b3 = new Book("Starhip design", "2-2-2-2");
   Book b4 = new Book("NetMind Persistence tutorial", "0-0-0-0");
   // Save
   getStore().save(b1);
   getStore().save(b2);
   getStore().save(b3);
   getStore().save(b4);
   // Get
   List result =
       getStore()
           .find(
               "find book where (book.authors contains tom(author)) "
                   + "and tom.firstname='Tom' and book.authors contains lynyrd(author) and lynyrd.firstname='Lynyrd' and book.mainauthor.firstname like 'Bokonon%'");
   Assert.assertEquals(result.size(), 1);
   Assert.assertEquals(result.get(0), b1);
 }
Example #11
0
  /** Generates array of XContour from local contours and modules. Used for TTF building. */
  private XContour[] toContours() {
    XContour[] retval;
    ArrayList<XContour> list = new ArrayList<>();
    XContour[] contours = m_glyph.getBody().getContour();
    for (int i = 0; i < contours.length; i++) {
      EContour contour = (EContour) contours[i];
      list.add(contour.toQuadratic());
    } // for i

    XModule[] modules = m_glyph.getBody().getModule();
    for (int i = 0; i < modules.length; i++) {
      EModuleInvoke module = (EModuleInvoke) modules[i];

      // push and pop happens inside toContour
      list.add(module.toContour(new AffineTransform()));
    } // for i

    if (list.size() == 0) return null;

    retval = new XContour[list.size()];
    for (int i = 0; i < list.size(); i++) {
      retval[i] = list.get(i);
    } // for i

    return retval;
  }
Example #12
0
 public void testInOperatorWithList() throws Exception {
   // Create test setup
   removeAll(Book.class);
   removeAll(Author.class);
   // Create
   Author author1 = new Author("Geordi", "LaForge");
   Author author2 = new Author("Data", "");
   Author author3 = new Author("Scott", "Montgomery");
   Book book = new Book("Starship internals", "1-3-5-7");
   book.setMainAuthor(author1);
   // Save
   getStore().save(book);
   getStore().save(author1);
   getStore().save(author2);
   getStore().save(author3);
   // Create list
   ArrayList authorList = new ArrayList();
   authorList.add(author1);
   authorList.add(author2);
   authorList.add(author3);
   // Select
   List result =
       getStore().find("find book where book.mainauthor in ?", new Object[] {authorList});
   logger.debug("result is: " + result);
   Assert.assertEquals(result.size(), 1);
 }
 private URLClassLoader buildClassLoader() throws PluginException {
   ClassLoader parent = JarPluginProviderLoader.class.getClassLoader();
   try {
     final URL url = getCachedJar().toURI().toURL();
     final URL[] urlarray;
     if (null != getDepLibs() && getDepLibs().size() > 0) {
       final ArrayList<URL> urls = new ArrayList<URL>();
       urls.add(url);
       for (final File extlib : getDepLibs()) {
         urls.add(extlib.toURI().toURL());
       }
       urlarray = urls.toArray(new URL[urls.size()]);
     } else {
       urlarray = new URL[] {url};
     }
     URLClassLoader loaded =
         loadLibsFirst
             ? LocalFirstClassLoader.newInstance(urlarray, parent)
             : URLClassLoader.newInstance(urlarray, parent);
     classLoaders.put(getCachedJar(), loaded);
     return loaded;
   } catch (MalformedURLException e) {
     throw new PluginException("Error creating classloader for " + cachedJar, e);
   }
 }
Example #14
0
 @Override
 public HSDeck getDeckDetail(final HSDeck hsDeck, final float n) {
   try {
     final Document value = Jsoup.connect(HPDeckSource.BASE_URL + hsDeck.getUrl()).get();
     final Elements select = value.select("section.class-listing table.listing td.col-name");
     final HashMap<String, String> classHsItemMap = new HashMap<String, String>();
     final ArrayList<String> list = new ArrayList<String>();
     for (int i = 0; i < select.size(); ++i) {
       final String text = select.get(i).select("a").get(0).text();
       classHsItemMap.put(
           text, select.get(i).text().trim().substring(select.get(i).text().trim().length() - 1));
       list.add(text);
     }
     hsDeck.setClassHsItemMap(classHsItemMap);
     hsDeck.setClassHsItemList(DataBaseManager.getInstance().getAllCardsByNames(list));
     final Elements select2 = value.select("section.neutral-listing table.listing td.col-name");
     final HashMap<String, String> neutralHsItemMap = new HashMap<String, String>();
     final ArrayList<String> list2 = new ArrayList<String>();
     for (int j = 0; j < select2.size(); ++j) {
       final String text2 = select2.get(j).select("a").get(0).text();
       neutralHsItemMap.put(
           text2,
           select2.get(j).text().trim().substring(select2.get(j).text().trim().length() - 1));
       list2.add(text2);
     }
     hsDeck.setNeutralHsItemMap(neutralHsItemMap);
     hsDeck.setNeutralHsItemList(DataBaseManager.getInstance().getAllCardsByNames(list2));
     hsDeck.setDescription(
         HtmlHelper.parseDescription(value.select("div.deck-description").html(), n, false));
     return hsDeck;
   } catch (IOException ex) {
     ex.printStackTrace();
     return hsDeck;
   }
 }
Example #15
0
  /**
   * Creates a java process that executes the given main class and waits for the process to
   * terminate.
   *
   * @return a {@link ProcessOutputReader} that can be used to get the exit code and stdout+stderr
   *     of the terminated process.
   */
  public static ProcessOutputReader fg(Class main, String[] vmArgs, String[] mainArgs)
      throws IOException {
    File javabindir = new File(System.getProperty("java.home"), "bin");
    File javaexe = new File(javabindir, "java");

    int bits = Integer.getInteger("sun.arch.data.model", 0).intValue();
    String vmKindArg = (bits == 64) ? "-d64" : null;

    ArrayList argList = new ArrayList();
    argList.add(javaexe.getPath());
    if (vmKindArg != null) {
      argList.add(vmKindArg);
    }
    // argList.add("-Dgemfire.systemDirectory=" +
    // GemFireConnectionFactory.getDefaultSystemDirectory());
    argList.add("-Djava.class.path=" + System.getProperty("java.class.path"));
    argList.add("-Djava.library.path=" + System.getProperty("java.library.path"));
    if (vmArgs != null) {
      argList.addAll(Arrays.asList(vmArgs));
    }
    argList.add(main.getName());
    if (mainArgs != null) {
      argList.addAll(Arrays.asList(mainArgs));
    }
    String[] cmd = (String[]) argList.toArray(new String[argList.size()]);
    return new ProcessOutputReader(Runtime.getRuntime().exec(cmd));
  }
Example #16
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 #17
0
 public final Export Export() throws ParseException {
   Token t;
   ASTStringNode packagedcl;
   ArrayList<ASTStringNode> list0 = new ArrayList<ASTStringNode>();
   ASTStringNode packagedcl1;
   ArrayList<ASTStringNode> packagedcl1List = new ArrayList<ASTStringNode>();
   ASTStringNode packageend;
   Token firstToken = token;
   jj_consume_token(EXPORTPACKAGE);
   t = jj_consume_token(PACKAGEDCL);
   packagedcl = new ASTStringNode(t.image, new WToken(t));
   list0.add(packagedcl);
   label_3:
   while (true) {
     switch (jj_nt.kind) {
       case 12:;
         break;
       default:
         jj_la1[3] = jj_gen;
         break label_3;
     }
     jj_consume_token(12);
     t = jj_consume_token(PACKAGEDCL);
     packagedcl1 = new ASTStringNode(t.image, new WToken(t));
     list0.add(packagedcl1);
   }
   t = jj_consume_token(PACKAGEEND);
   packageend = new ASTStringNode(t.image, new WToken(t));
   {
     if (true) return new Export(list0, packageend, firstToken.next, token);
   }
   throw new Error("Missing return statement in function");
 }
Example #18
0
 public static void main(String[] args) throws IOException {
   // Use BufferedReader rather than RandomAccessFile; it's much faster
   BufferedReader f = new BufferedReader(new FileReader("badrand.in"));
   // input file name goes above
   PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("badrand.out")));
   // Use StringTokenizer vs. readLine/split -- lots faster
   StringTokenizer st = new StringTokenizer(f.readLine());
   // Get line, break into tokens
   int i1 = Integer.parseInt(st.nextToken()); // first integer
   ArrayList squares = new ArrayList<Integer>(10000);
   int mark = 0;
   i1 = middleSquare(i1);
   while (i1 > 0) {
     if (squares.contains(i1)) {
       squares.add(i1);
       squares.set(squares.indexOf(i1), 10000);
       mark = i1;
       i1 = 0;
     } else {
       squares.add(i1);
       i1 = middleSquare(i1);
     }
   }
   squares.add(10000);
   squares.add(0);
   out.println(squares.indexOf(mark) + 1);
   out.close(); // close the output file
   System.exit(0); // don't omit this!
 }
Example #19
0
  /**
   * BFS algorith
   *
   * @param: print boolean if to print node during traversal
   * @return List of nodes in order visited
   */
  public ArrayList<String> bfs(boolean print) {

    ArrayList<String> ops = new ArrayList<>();

    GraphNode v = source;
    ArrayList<GraphNode> Q = new ArrayList<>();
    Q.add(v);
    v.setVisited(true);
    while (Q.size() != 0) {
      v = Q.remove(0);
      if (print) System.out.println(v);
      ops.add(v.toString());
      //      if(checkStoppingCondition(v, getN())) {
      //        return;
      //      }
      List<Integer> edgeTarget = matrix.get(v.getID());
      for (int i = 0; i < edgeTarget.size(); ++i) {
        if (edgeTarget.get(i) == 1) {
          GraphNode w = info.get(i + 1);
          if (!w.getVisited()) {
            Q.add(w);
            w.setVisited(true);
          }
        }
      }
    }
    return ops;
  }
Example #20
0
  private boolean invokeMethod(String line, PrintWriter out, Method method, String[] fields)
      throws IllegalAccessException, InvocationTargetException {
    ArrayList<Object> methodArguments = new ArrayList<Object>();

    Class<?>[] parameterTypes = method.getParameterTypes();
    if (parameterTypes.length == 2
        && parameterTypes[0] == PrintWriter.class
        && parameterTypes[1] == String.class) {
      // FIXME: there must be a better way to say "I want to parse the line myself."
      methodArguments.add(out);
      methodArguments.add(line);
    } else {
      int nextField = 1;
      for (Class<?> parameterType : parameterTypes) {
        if (parameterType == PrintWriter.class) {
          methodArguments.add(out);
        } else if (parameterType == String.class) {
          methodArguments.add(fields[nextField++]);
        }
        // FIXME: support other common types. "int" seems a likely first candidate.
      }
    }

    method.invoke(handler, methodArguments.toArray());
    return true;
  }
 public boolean comparePrefix(String prefixCode, String prefixCodeWithProc) {
   try {
     boolean flag = false;
     String prefixBreak[] = prefixCode.split("#");
     String prefixProcBreak[] = prefixCodeWithProc.split("#");
     for (String str : prefixBreak) {
       flag = false;
       for (int i = 0; i < prefixProcBreak.length; i++) {
         if (prefixProcBreak[i].equals(str)) {
           flag = true;
           prefixProcBreak[i] = "-1";
           break;
         }
       }
       if (!flag) return false;
     }
     if (prefixCode.length() == prefixCodeWithProc.length()) {
       procList.clear();
       procList.add(prefixCodeWithProc);
       return true;
     } else procList.add(prefixCodeWithProc);
   } catch (Exception ed) {
   }
   return false;
 }
Example #22
0
  public static ArrayList getFjList(String sid) {
    ArrayList result = new ArrayList();
    String strSql =
        "select SID,File_Name,Ext_Name,File_Size from  t_docs_fj where state='1' and parent_sid="
            + sid;
    CommonDao dao = CommonDao.GetOldDatabaseDao();
    List lst = dao.fetchAll(strSql);
    if (lst != null && lst.size() > 0) {
      for (int i = 0; i < lst.size(); i++) {
        Object[] arr = (Object[]) lst.get(i);
        result.add(arr[1]);
        result.add(arr[2]);
        if (arr[3] != null) {
          Float fileSize = Float.parseFloat(arr[3].toString()) * 1000;
          result.add(fileSize);
        } else {
          result.add(0);
        }
        result.add(arr[0]);
      }
    }
    dao.getSessionFactory().close();
    return result;
    /*Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    ArrayList result = new ArrayList();
    String strSql = "select * from  t_docs_fj where state='1' and parent_sid="
    		+ sid;
    try {
    	conn = DataManager.getConnection();
    	stmt = conn.createStatement();
    	rs = stmt.executeQuery(strSql);
    	while (rs.next()) {
    		result.add(rs.getString("File_Name"));
    		result.add(rs.getString("Ext_Name"));
    		result.add(""
    				+ Float.valueOf(rs.getString("File_Size")).floatValue()
    				* 1000.0);
    		result.add(rs.getString("SID"));
    		result.add(FileUtil.getDocumentPath());
    	}
    } catch (Exception ex) {
    	ex.printStackTrace();
    }

    finally {
    	try {
    		if (rs != null)
    			rs.close();
    		if (stmt != null)
    			stmt.close();
    		if (conn != null)
    			conn.close();
    	} catch (Exception ex) {
    		ex.printStackTrace();
    	}
    }*/

  }
 public static void findMaxCut() {
   int arrayCut = Integer.MAX_VALUE;
   int indexCut = Integer.MAX_VALUE;
   int max = Integer.MIN_VALUE;
   int numArrays = occupied.size();
   for (int i = 0; i < numArrays; i++) {
     ArrayList<Integer> arr = occupied.get(i);
     int len = arr.size();
     for (int j = 0; j < len - 1; j++) {
       if (arr.get(j + 1) - arr.get(j) > max) {
         max = arr.get(j + 1) - arr.get(j);
         indexCut = j;
         arrayCut = i;
       }
     }
   }
   ArrayList<Integer> arr1 = new ArrayList<Integer>();
   ArrayList<Integer> arr2 = new ArrayList<Integer>();
   ArrayList<Integer> arr = occupied.get(arrayCut);
   for (int i = 0; i <= indexCut; i++) {
     arr1.add(arr.get(i));
   }
   for (int i = indexCut + 1; i < arr.size(); i++) {
     arr2.add(arr.get(i));
   }
   occupied.remove(arrayCut);
   occupied.add(arr1);
   occupied.add(arr2);
 }
  /* 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);
  }
Example #25
0
  private Collection<Modifier> generateModifiers(int modifiers) {
    ArrayList<Modifier> mods = new ArrayList<Modifier>();

    // first, protection modifiers
    switch (modifiers & WyilFileWriter.MODIFIER_PROTECTION_MASK) {
      case WyilFileWriter.MODIFIER_Public:
        mods.add(Modifier.PUBLIC);
        break;
      case WyilFileWriter.MODIFIER_Protected:
        mods.add(Modifier.PROTECTED);
        break;
      case WyilFileWriter.MODIFIER_Private:
        mods.add(Modifier.PRIVATE);
        break;
      default:
        throw new RuntimeException("Unknown modifier");
    }

    // second, mangle modifiers
    switch (modifiers & WyilFileWriter.MODIFIER_MANGLE_MASK) {
      case WyilFileWriter.MODIFIER_Native:
        mods.add(Modifier.NATIVE);
        break;
      case WyilFileWriter.MODIFIER_Export:
        mods.add(Modifier.EXPORT);
        break;
    }

    return mods;
  }
Example #26
0
  public static void main(String args[]) {
    int N;
    Scanner in = new Scanner(System.in);
    N = in.nextInt();
    int arr[] = new int[N];
    ArrayList even = new ArrayList();
    ArrayList odd = new ArrayList();
    ArrayList list = new ArrayList();

    for (int i = 0; i < N; i++) {
      arr[i] = in.nextInt();
    }
    int evenSum = 0;
    int oddSum = 0;
    for (int i = 0; i < N; i++) {
      if (arr[i] % 2 == 0) {
        even.add(arr[i]);
        evenSum = evenSum + arr[i];
      } else {
        odd.add(arr[i]);
        oddSum = oddSum + arr[i];
      }
    }
    even.add(evenSum);
    odd.add(oddSum);
    Collections.sort(even);
    Collections.sort(odd);
    list.addAll(even);
    list.addAll(odd);
    Iterator itr = list.iterator();
    while (itr.hasNext()) {
      System.out.println(itr.next());
    }
  }
Example #27
0
  public MoquiStart(ClassLoader parent, boolean loadWebInf) {
    super(parent);
    this.loadWebInf = loadWebInf;

    URL wrapperWarUrl = null;
    try {
      // get outer file (the war file)
      pd = getClass().getProtectionDomain();
      CodeSource cs = pd.getCodeSource();
      wrapperWarUrl = cs.getLocation();
      outerFile = new JarFile(new File(wrapperWarUrl.toURI()));

      // allow for classes in the outerFile as well
      jarFileList.add(outerFile);

      Enumeration<JarEntry> jarEntries = outerFile.entries();
      while (jarEntries.hasMoreElements()) {
        JarEntry je = jarEntries.nextElement();
        if (je.isDirectory()) continue;
        // if we aren't loading the WEB-INF files and it is one, skip it
        if (!loadWebInf && je.getName().startsWith("WEB-INF")) continue;
        // get jars, can be anywhere in the file
        String jeName = je.getName().toLowerCase();
        if (jeName.lastIndexOf(".jar") == jeName.length() - 4) {
          File file = createTempFile(je);
          jarFileList.add(new JarFile(file));
        }
      }
    } catch (Exception e) {
      System.out.println("Error loading jars in war file [" + wrapperWarUrl + "]: " + e.toString());
    }
  }
Example #28
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();
  }
  public void createBuildings() {
    bList = new ArrayList<Building>();

    // resource
    bList.add(new Building("Gold Mine", 3, 3, 960, 7));
    bList.add(new Building("Elixir Collector", 3, 3, 960, 7));
    // bList.add(new Building("Dark Elixir Drill", 3, 3, 1160, 3));
    bList.add(new Building("Gold Storage", 3, 3, 2100, 4));
    bList.add(new Building("Elixir Storage", 3, 3, 2100, 4));
    // bList.add(new Building("Dark Elixir Storage", 3, 3, 3200, 1));
    // bList.add(new Building("Builder Hut", 2, 2, 250, 5));

    // army
    bList.add(new Building("Army Camp", 5, 5, 500, 4));
    bList.add(new Building("Barracks", 3, 3, 860, 4));
    // bList.add(new Building("Dark Barracks", 3, 3, 900, 2));
    // bList.add(new Building("Laboratory", 4, 4, 950, 1));
    // bList.add(new Building("Spell Factory", 3, 3, 615, 1));
    // bList.add(new Building("Barbarian King Altar", 3, 3, 250, 1));
    // bList.add(new Building("Dark Spell Factory", 3, 3, 750, 1));
    // bList.add(new Building("Archer Queen Altar", 3, 3, 250, 1));

    // other
    bList.add(new Building("Town Hall", 4, 4, 5500, 1));
    bList.add(new Building("Clan Castle", 3, 3, 3400, 1));

    // defense
    bList.add(new Building("Archer Tower", 3, 3, 1050, 7));
    bList.add(new Building("Cannon", 3, 3, 1260, 6));
    bList.add(new Building("Wall", 1, 1, 7000, 275));
    // bList.add(new Building("Air Sweeper", 2, 2, 1000, 2));
    // bList.add(new Building("Cannon", 3, 3, 1260, 6));
    // bList.add(new Building("Cannon", 3, 3, 1260, 6));
  }
Example #30
0
  /*Constructor*/
  public MemCheck(TorrentInfo tInfo, RandomAccessFile file) {
    this.tInfo = tInfo;
    this.file = file;
    this.left = tInfo.file_length;
    this.last_piece_size = tInfo.file_length % tInfo.piece_length;
    System.out.println("Last piece size is " + this.last_piece_size);
    // INITIALIZE THE Queue, worry about everything else later
    for (int i = 0; i < tInfo.piece_hashes.length; i++) {
      neededPieces.add(i);
    }
    this.finished_pieces = new boolean[tInfo.piece_hashes.length];

    // INITIALIZE Pieces
    for (int i = 0; i < tInfo.piece_hashes.length; i++) {
      if (i != tInfo.piece_hashes.length - 1) {
        Piece p = new Piece(16384, tInfo.piece_length, i);
        pieces.add(p);
      } // last piece
      else {
        int lastPieceSize = tInfo.file_length % tInfo.piece_length;
        int lastBlockSize = lastPieceSize % 16384;
        if (lastPieceSize == lastBlockSize) {
          Piece p = new Piece(lastBlockSize, lastPieceSize, i, 0);
          pieces.add(p);
        } else {
          Piece p = new Piece(16384, lastPieceSize, i, lastBlockSize);
          pieces.add(p);
        }
      }
    }
  }