text
stringlengths
14
410k
label
int32
0
9
public void loadVisOp(String visOpName) { Department visOp = DataBase.departments[DataBase.findDeptPos(visOpName)]; if (visOp != null) { for (int index = 0; index<visOpsPanel.getComponentCount(); index++) { try { ((JSpinner) visOpsPanel.getComponent(index)).setValue("1"); ((JSpinner) visOpsPanel.getComponent(index)).setValue("0"); }catch(ClassCastException cCE){} } for (int index = 0, levelNum = 0; index<visOpsPanel.getComponentCount(); index++) { try { if(((LevelSpinner) visOpsPanel.getComponent(index)).isLevelSpinner()) { System.out.println(((JSpinner) visOpsPanel.getComponent(index)) + " Spinner set to: " + visOp.colVis[levelNum]); ((JSpinner) visOpsPanel.getComponent(index)).setValue(Integer.toString(visOp.colVis[levelNum])); levelNum++; } }catch(ClassCastException cCE){} catch(Exception e){e.printStackTrace();} } colorTables(visOp.backGroundColor, visOp.foreGroundColor); } }
7
public void setExpiryDate(XMLGregorianCalendar value) { this.expiryDate = value; }
0
public void testSet(Set<Object> set) { // first test add and contains set.clear(); assertTrue("Clear should make it empty", set.isEmpty()); Object[] items=new Object[itemCount]; for (int i =0; i < itemCount; i++) { Integer o =Integer.valueOf(i); items[i]=o; set.add(o); assertTrue("add/contains", set.contains(o)); assertEquals("Size check", i + 1, set.size()); } for (int i =0; i < itemCount; i++) { Object o =items[i]; boolean mod =set.remove(o); assertTrue("remove returns true", mod); assertFalse("remove/contains", set.contains(o)); assertEquals("Size check", itemCount - i - 1, set.size()); } set.clear(); assertTrue("Clear should make it empty", set.isEmpty()); for (int i =0; i < itemCount; i++) { Integer o =Integer.valueOf(random.nextInt()); items[i]=o; set.add(o); assertTrue("add/contains Random:" + set.size() + "\t" + o, set.contains(o)); } set.clear(); assertTrue("Clear should make it empty", set.isEmpty()); // now for the iterators part... int count =0; for (Object o : set) { assertTrue("iterator contains", set.contains(o)); count++; } assertEquals("iterator size check", count, set.size()); Iterator<Object> iterator =set.iterator(); while (iterator.hasNext()) { Object o =iterator.next(); assertTrue("iterator contains", set.contains(o)); iterator.remove(); assertFalse("iterator removed", set.contains(o)); } assertTrue("everything removed with an iterator", set.isEmpty()); // now for collections of add and remove... HashSet<Object> hashSet =new HashSet<Object>(); for (int i =0; i < itemCount; i++) { hashSet.add(random.nextDouble()); } set.clear(); assertTrue("Clear should make it empty", set.isEmpty()); set.addAll(hashSet); assertTrue("contains All", set.containsAll(hashSet)); set.remove(set.iterator().next()); assertFalse("!contains All", set.containsAll(hashSet)); HashSet<Object> hashSet2 =new HashSet<Object>(); count =0; for (Object o : hashSet) { hashSet2.add(o); count++; if (count >= set.size() / 2) break; } set.addAll(hashSet); set.removeAll(hashSet2); assertEquals("remove all", hashSet.size() - hashSet2.size(), set.size()); set.addAll(hashSet); set.retainAll(hashSet2); assertEquals("retain all", hashSet2.size(), set.size()); assertTrue("retain all", set.containsAll(hashSet2)); assertFalse("retain all", set.containsAll(hashSet)); Object hash1=new Object(){ @Override public int hashCode() { return 1; } }; Object one=1; set.clear(); set.add(hash1); set.add(one); assertEquals(2, set.size()); set.remove(hash1); set.add(one); assertEquals(1, set.size()); }
8
synchronized boolean frameCorrectionFirstCodingExon() { List<Exon> exons = sortedStrand(); // No exons? Nothing to do if ((exons == null) || exons.isEmpty()) return false; Exon exonFirst = getFirstCodingExon(); // Get first exon // Exon exonFirst = exons.get(0); // Get first exon if (exonFirst.getFrame() <= 0) return false; // Frame OK (or missing), nothing to do // First exon is not zero? => Create a UTR5 prime to compensate Utr5prime utr5 = null; int frame = exonFirst.getFrame(); if (isStrandPlus()) { int end = exonFirst.getStart() + (frame - 1); utr5 = new Utr5prime(exonFirst, exonFirst.getStart(), end, getStrand(), exonFirst.getId()); } else { int start = exonFirst.getEnd() - (frame - 1); utr5 = new Utr5prime(exonFirst, start, exonFirst.getEnd(), getStrand(), exonFirst.getId()); } // Reset frame, since it was already corrected exonFirst.setFrame(0); Cds cds = findMatchingCds(exonFirst); if (cds != null) cds.frameCorrection(cds.getFrame()); // Add UTR5' add(utr5); // Update counter return true; }
5
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); ArrayList<CompRequest> comp = new ArrayList<CompRequest>(); ArrayList<PaidRequest> paid = new ArrayList<PaidRequest>(); ArrayList<Game> games = new ArrayList<Game>(); ArrayList<Section> section = new ArrayList<Section>(); String acctNum = request.getParameter("acct_num"); String password = request.getParameter("pass"); request.getSession().invalidate(); Employee emp = new Employee(); String message, url="/index.jsp"; String dbURL = "jdbc:mysql://localhost:3306/itrs"; String username = "root"; String dbpassword = "sesame"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { } try { Connection conn = DriverManager.getConnection(dbURL,username,dbpassword); Statement s = conn.createStatement(); ResultSet r = s.executeQuery("SELECT * FROM employee NATURAL JOIN department WHERE emp_acctnum ='" + acctNum + "'"); if (r.next()) { emp = new Employee(); emp.setEmployee(r); emp.setLoggedIn(password); message = "Employee found: " + emp.getFName() + " " + emp.getLName(); r.close(); r = null; s.close(); s = null; if (emp.getLoggedIn()) { url="/Main.jsp"; s = conn.createStatement(); r = s.executeQuery("SELECT * FROM comprequest NATURAL JOIN department NATURAL JOIN games " + "NATURAL JOIN seating NATURAL JOIN employee " + "WHERE emp_acctnum =" + emp.getAcctNum() ); while (r.next()) { CompRequest c = new CompRequest(); c.setRequest(r); comp.add(c); } r.close(); r = null; s.close(); s = null; s = conn.createStatement(); r = s.executeQuery("SELECT * FROM paidrequest NATURAL JOIN department NATURAL JOIN games " + "NATURAL JOIN seating NATURAL JOIN employee " + "WHERE emp_acctnum =" + emp.getAcctNum() ); while (r.next()) { PaidRequest p = new PaidRequest(); p.setRequest(r); paid.add(p); } r.close(); r = null; s.close(); s = null; s = conn.createStatement(); r = s.executeQuery("SELECT * FROM games ORDER BY game_date"); Date date = new Date(); while(r.next()) { Game g = new Game(); g.setGame(r); if(date.compareTo(g.getGameDay()) >= 0) g.setSoldOut(true); games.add(g); } r.close(); r = null; s.close(); s = null; s = conn.createStatement(); r = s.executeQuery("SELECT * FROM seating ORDER BY sec_num"); while(r.next()) { Section x = new Section(); x.setSection(r); section.add(x); } request.getSession().setAttribute("games", games); request.getSession().setAttribute("sections", section); request.getSession().setAttribute("comp", comp); request.getSession().setAttribute("paid", paid); } else { message = "Invalid Password "; } } else { message = "Unknown user: " + acctNum + ". UserID not found."; } } catch (SQLException e) { message = "SQL Error: " + e.getMessage(); } request.setAttribute("message", message); request.getSession().setAttribute("emp", emp); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forward(request, response); }
9
private boolean follows(Gob g1, Gob g2) { Following flw; if ((flw = g1.getattr(Following.class)) != null) { if (flw.tgt() == g2) return (true); } if ((flw = g2.getattr(Following.class)) != null) { if (flw.tgt() == g1) return (true); } return (false); }
4
public int read(final int[] docs, final int[] freqs) throws IOException { while (true) { while (current == null) { if (pointer < readers.length) { // try next segment if (tenum != null) { smi = tenum.matchingSegments[matchingSegmentPos++]; if (smi==null) { pointer = readers.length; return 0; } pointer = smi.ord; } base = starts[pointer]; current = termDocs(pointer++); } else { return 0; } } int end = current.read(docs, freqs); if (end == 0) { // none left in segment current = null; } else { // got some final int b = base; // adjust doc numbers for (int i = 0; i < end; i++) docs[i] += b; return end; } } }
7
public void replaceTile(Tile find, Tile replace) { for (int y = bounds.y; y < bounds.y + bounds.height; y++) { for (int x = bounds.x; x < bounds.x + bounds.width; x++) { if(getTileAt(x,y) == find) { setTileAt(x, y, replace); } } } }
3
public Object getValueAt(int row, int col) { try { return audienceResultList.get(row).getColumnData(col); } catch (Exception e) { e.getMessage(); return null; } }
1
public static void openURL(String url) { try { // attempt to use Desktop library from JDK 1.6+ Class<?> d = Class.forName("java.awt.Desktop"); d.getDeclaredMethod("browse", new Class[] { java.net.URI.class }).invoke( d.getDeclaredMethod("getDesktop").invoke(null), new Object[] { java.net.URI.create(url) }); // above code mimicks: java.awt.Desktop.getDesktop().browse() } catch (Exception ignore) { // library not available or failed String osName = System.getProperty("os.name"); try { if (osName.startsWith("Mac OS")) { Class.forName("com.apple.eio.FileManager") .getDeclaredMethod("openURL", new Class[] { String.class }) .invoke(null, new Object[] { url }); } else if (osName.startsWith("Windows")) Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url); else { // assume Unix or Linux String browser = null; for (String b : browsers) if (browser == null && Runtime.getRuntime().exec(new String[] { "which", b }).getInputStream().read() != -1) Runtime .getRuntime().exec(new String[] { browser = b, url }); if (browser == null) throw new Exception(Arrays.toString(browsers)); } } catch (Exception e) { e.printStackTrace(); } } }
9
public PDAToCFGConverter() { initializeConverter(); }
0
public void addProduction(Production production) { if (myProductions.size() == 0 && !ProductionChecker.isRestrictedOnLHS(production)) throw new IllegalArgumentException( "The first production must be restricted."); super.addProduction(production); }
2
private static UnitTypes defineUnitToBuild(int freeMinerals, int freeGas) { // boolean arbiterAllowed = // UnitCounter.weHaveBuilding(UnitTypes.Protoss_Arbiter_Tribunal); boolean valkyrieAllowed = UnitCounter.weHaveBuilding(UnitTypes.Terran_Control_Tower); boolean scienceVesselAllowed = UnitCounter .weHaveBuilding(UnitTypes.Terran_Science_Facility); // // BATTLECRUISER // if (arbiterAllowed && xvr.countUnitsOfType(BATTLECRUISER) < // MINIMUM_BATTLECRUISERS) { // return BATTLECRUISER; // } // SCIENCE VESSEL if (scienceVesselAllowed && TerranScienceVessel.getNumberOfUnits() < MIN_VESSELS) { return SCIENCE_VESSEL; } // VALKYRIE if (valkyrieAllowed && UnitCounter.getNumberOfUnitsCompleted(UnitTypes.Terran_Valkyrie) <= 3) { return VALKYRIE; } // WRAITH if (UnitCounter.getNumberOfUnits(WRAITH) > MAX_WRAITHS) { return WRAITH; } return null; // // VALKYRIE // if (UnitCounter.getNumberOfUnits(VALKYRIE) < MINIMUM_VALKYRIES // || (UnitCounter.countAirUnitsNonValkyrie() * // VALKYRIES_PER_OTHER_AIR_UNIT < UnitCounter // .getNumberOfUnits(VALKYRIE))) { // return VALKYRIE; // } // return null; }
5
@Override public int hashCode() { return Objects.hash(terminalID); }
0
public Sprite(String texture) { try { this.texture = load(texture); } catch (IOException e) { loadError(); } }
1
private void genPostponed(final Node node) { final Instruction inst = (Instruction) postponedInstructions.get(node); if (inst != null) { method.addInstruction(inst); // Luckily, the rc and aupdate don't change the stack! postponedInstructions.remove(node); } }
1
public void addResidualFlowTo(int v, double delta) { if (v == from) // backward edge flow -= delta; else if (v == to) // forward edge flow += delta; throw new IllegalArgumentException(); }
2
public void checkGroups(boolean includeManual, CommandSender sender) { CheckReport report = new CheckReport(sender); for(GroupSettings settings : getGroups(includeManual)) checkGroup(settings, report); }
1
public final boolean completeTask() { if (this.complete) { return true; } if (this.triesLeft == 0) { return true; } boolean finish = false; try { finish = this.finishTask(); } catch (Throwable e) { Logger.err(e); } if (finish) { synchronized (this) { this.complete = true; } if (this.listener != null) { this.listener.onTaskComplete(this); } } else { if (this.doTryAgain()) { this.triesLeft--; } else { this.triesLeft = 0; } } return this.complete; }
6
private void initContentNumber() { contentNumber = 0; if (content.length() == 0) return; // check to already get exception during parsing rather than during // checking (later). we keep these // values already in long form rather than executing Long.parseLong(...) // many times (during check). switch (type) { case BYTE_TYPE: case SHORT_TYPE: case BESHORT_TYPE: case LESHORT_TYPE: case LELONG_TYPE: case BELONG_TYPE: { if (content.startsWith("0x")) { contentNumber = Long.parseLong(content.substring(2).trim(), 16); // Without // the // trim(), // I // got // some // NumberFormatExceptions // here. // Added // trim() // below, // as // well. // Marco. } else if (content.startsWith("0")) { contentNumber = Long.parseLong(content.trim(), 8); } else { contentNumber = Long.parseLong(content.trim()); } } } }
9
private static void showAllUser() throws Exception { System.out.println("Users..."); UserDAO dao = new UserDAO(); ArrayList users = (ArrayList) dao.findAll(); User o; for (int i = 0; i < users.size(); i++) { o = (User) users.get(i); System.out.println("ID: " + o.getId() + " - " + "Name: " + o.getName()); } User admin = (User) dao.getNewInstance(); }
1
private List<QCProjectSet> getProjectSetList(File dir, int negDepth) { List<QCProjectSet> result = new ArrayList<>(); if (negDepth > 0) { List<File> folder = dirFolderlist(dir); for (File f : folder) { if (isProjectSetDirectory(f)) { result.add(new QCProjectSet(f, getProjectList(f, MAX_SET_SCAN_DEPTH))); } else if (isSingleProjectDirectory(f)) { result.add(new QCProjectSet(f, new QCProject(f))); } else { result.addAll(getProjectSetList(f, negDepth - 1)); } } } return result; }
4
public void load(ProBotGame game){ this.setPosition ( new Point ( (int)Math.floor(this.getCurrentWorld().getWidth()/2*POSITION_MULTIPLYER), (int)Math.floor(this.getCurrentWorld().getHeight()/2*POSITION_MULTIPLYER-60) ) ); this.setHead(game.getUpgradeManager().getHeadByName("Head 2")); this.setBody(game.getUpgradeManager().getBodyByName("Body 1")); this.setLimbs(game.getUpgradeManager().getLimbsByName("Limbs 1")); }
0
public int getInboxNumber(){ int number=0; String requete= "select count(*) from message"; try { Statement statement = MyConnection.getInstance().createStatement(); ResultSet resultat = statement.executeQuery(requete); while(resultat.next()){ number=resultat.getInt(1); } } catch (SQLException ex) { System.out.println("Error in message statistics "+ex.getMessage()); } return number; }
2
@Test public void testStringArrays() throws Exception { PersistenceManager pm1 = new PersistenceManager(driver,database,login,password); StringArrayContainer sac = new StringArrayContainer(); sac.setValues(new String[]{"Foo","bar","BAZ"}); pm1.saveObject(sac); //get the object from another PersistenceManager. PersistenceManager pm2 = new PersistenceManager(driver,database,login,password); List<StringArrayContainer> list = pm2.getObjects(StringArrayContainer.class,new All()); assertEquals(1,list.size()); StringArrayContainer copy = list.get(0); assertEquals(sac.getValues().length,copy.getValues().length); for(int x = 0;x<sac.getValues().length;x++) { assertEquals(sac.getValues()[x],copy.getValues()[x]); } //change the original object's array contents sac.getValues()[0]="Nonsense"; pm1.saveObject(sac); //check that the change propagates assertTrue(pm2.hasChanged(copy)); //get the refreshed copy pm2.refresh(copy); assertEquals(sac.getValues().length,copy.getValues().length); for(int x = 0;x<sac.getValues().length;x++) { assertEquals(sac.getValues()[x],copy.getValues()[x]); } //change the original object's length sac.setValues(new String[]{"one","two","three","four"}); pm1.saveObject(sac); //check that the change propagates assertTrue(pm2.hasChanged(copy)); //get the refreshed copy pm2.refresh(copy); assertEquals(sac.getValues().length,copy.getValues().length); for(int x = 0;x<sac.getValues().length;x++) { assertEquals(sac.getValues()[x],copy.getValues()[x]); } pm2.close(); pm1.close(); }
3
public List<Clan> load() { List<Clan> list = new ArrayList<Clan>(); // Check if folder exists if (plugin.clanClassFolder == null) { plugin.logger.warning("No clans found in the classes folder. This plugin will only use the default clans."); return list; } // Create Class Loader Instance ClassLoader loader; try { loader = new URLClassLoader(new URL[] { plugin.clanClassFolder.toURI().toURL() }, Clan.class.getClassLoader()); } catch (MalformedURLException ex) { plugin.logger.warning("Clans have failed to load."); return list; } // Load the class files for (File f : plugin.clanClassFolder.listFiles()) { if (!f.getName().endsWith(".class")) { // Make Sure to only load class files continue; } String name = f.getName().substring(0, f.getName().lastIndexOf(".")); try { Class<?> clazz = loader.loadClass(name); Object object = clazz.newInstance(); if (!(object instanceof Clan)) { plugin.logger.info("This file is not a valid Clan file: " + clazz.getSimpleName()); continue; } Clan clan = (Clan) object; clan.onEnable(); list.add(clan); plugin.logger.info("Loaded clan: "+ list.getClass().getSimpleName()); /* * Used to catch any errors with loading * It will skip the clan */ } catch (Exception ex) { ex.printStackTrace(); plugin.logger.info("Error loading '" + name + "' clan! Clan disabled."); } catch (Error ex) { ex.printStackTrace(); plugin.logger.info("Error loading '" + name + "' clan! Clan disabled."); } } return list; }
8
public static String replaceExtension(String filename, String newExtention) { int i = filename.lastIndexOf('.'); return (i > 0 && i < filename.length() - 1) ? filename.substring(0, i + 1) + newExtention : filename; }
2
public static String periodToFormat(long period) { long elapsedYears = getYears(period); period = period % yearInMillis; long elapsedDays = getDays(period); period = period % dayInMillis; long elapsedHours = getHours(period); period = period % hourInMillis; long elapsedMinutes = getMinutes(period); period = period % minuteInMillis; long elapsedSeconds = getSeconds(period); String ret = ""; if (elapsedYears != 0) { ret += elapsedYears + " years "; } if (elapsedDays != 0) { ret += elapsedDays + " days "; } if (elapsedHours != 0) { if (elapsedMinutes > 9) { ret += elapsedHours + ":"; } else { ret += "0" + elapsedHours + ":"; } } else { ret += "00:"; } if (elapsedMinutes != 0) { if (elapsedMinutes > 9) { ret += elapsedMinutes + ":"; } else { ret += "0" + elapsedMinutes + ":"; } } else { ret += "00:"; } if (elapsedSeconds != 0) { if (elapsedSeconds > 9) { ret += elapsedSeconds + " hrs"; } else { ret += "0" + elapsedSeconds + " hrs"; } } else { ret += "00 hrs"; } return ret; }
8
public void drawarrows(GOut g) { Coord oc = viewoffset(sz, mc); Coord hsz = sz.div(2); //half size double ca = -Coord.z.angle(hsz); for (Party.Member partyMember : glob.party.memb.values()) { // Gob gob = glob.oc.getgob(id); Coord memberCoords = partyMember.getc(); if (memberCoords == null) continue; Coord sc = m2s(memberCoords).add(oc); if (!sc.isect(Coord.z, sz)) { double a = -hsz.angle(sc); Coord ac; if ((a > ca) && (a < -ca)) { ac = new Coord(sz.x, hsz.y - (int) (Math.tan(a) * hsz.x)); } else if ((a > -ca) && (a < Math.PI + ca)) { ac = new Coord(hsz.x - (int) (Math.tan(a - Math.PI / 2) * hsz.y), 0); } else if ((a > -Math.PI - ca) && (a < ca)) { ac = new Coord(hsz.x + (int) (Math.tan(a + Math.PI / 2) * hsz.y), sz.y); } else { ac = new Coord(0, hsz.y + (int) (Math.tan(a) * hsz.x)); } g.chcolor(partyMember.col); Coord bc = ac.add(Coord.sc(a, -10)); g.line(bc, bc.add(Coord.sc(a, -40)), 2); g.line(bc, bc.add(Coord.sc(a + Math.PI / 4, -10)), 2); g.line(bc, bc.add(Coord.sc(a - Math.PI / 4, -10)), 2); g.chcolor(Color.WHITE); } } }
9
public static void printAll() { try { PreparedStatement stmt = Main.EMART_CONNECTION.prepareStatement("select * " + "from ReplenishmentOrder"); ResultSet rs = stmt.executeQuery(); System.out.println("Replenishment Order:"); while (rs.next()) { System.out.println(rs.getInt("order_id") + "|" + rs.getString("mname")); System.out.println("in order:"); PreparedStatement ordstmt = Main.EMART_CONNECTION.prepareStatement("select order_id, stock_number, amount from InReplenishmentOrder where order_id = ?"); ordstmt.setString(1, rs.getString("order_id")); ResultSet ordrs = ordstmt.executeQuery(); while (ordrs.next()) { System.out.println(ordrs.getString("order_id") + "|" + ordrs.getString("stock_number") + "|" + ordrs.getString("amount")); } } } catch (SQLException e) { e.printStackTrace(); } }
3
@SuppressWarnings("unchecked") public static <T extends Number> T[][] array2DArraySorter(T[][] tab, int sortColumn) { int tabLength = tab.length; if (tabLength == 0) return tab; for (int i = 0; i < tabLength; ++i) { if (sortColumn > tab[i].length - 1) throw new ArrayIndexOutOfBoundsException( "Array sort column is too high"); } T[] order = (T[]) new Number[tabLength]; for (int i = 0; i < tabLength; ++i) order[i] = tab[i][sortColumn]; Arrays.sort(order); T[][] out = (T[][]) new Number[tabLength][]; for (int i = 0; i < tabLength; ++i) { for (int j = 0; j < tabLength; ++j) { if (order[i] == tab[i][sortColumn]) out[i] = tab[i]; } } return out; }
7
public static Cons buildOneTableAssertion(NamedDescription tableRelation, Cons tuple, Module dbModule) { { Cons assertion = Stella.NIL; int colno = -1; { int i = Stella.NULL_INTEGER; int iter000 = 0; int upperBound000 = tableRelation.arity(); boolean unboundedP000 = upperBound000 == Stella.NULL_INTEGER; Cons collect000 = null; for (;unboundedP000 || (iter000 <= upperBound000); iter000 = iter000 + 1) { i = iter000; if (collect000 == null) { { collect000 = Cons.cons(Stella.NULL_STRING_WRAPPER, Stella.NIL); if (assertion == Stella.NIL) { assertion = collect000; } else { Cons.addConsToEndOfConsList(assertion, collect000); } } } else { { collect000.rest = Cons.cons(Stella.NULL_STRING_WRAPPER, Stella.NIL); collect000 = collect000.rest; } } } } { Stella_Object item = null; Cons iter001 = tuple; for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) { item = iter001.value; colno = RDBMS.getTableColumnIndex(tableRelation, ((XmlElement)(((Cons)(item)).value)).name, dbModule); if (colno < 0) { Stella.STANDARD_WARNING.nativeStream.println("Warning: Couldn't find column number for `" + item + "' on relation `" + tableRelation + "'"); } else { assertion.nthSetter(((Cons)(item)).rest.rest.value, colno); } if (!(((Cons)(item)).rest.rest.rest == Stella.NIL)) { Stella.STANDARD_WARNING.nativeStream.println("Warning: Extra elements found in `" + item + "'"); } } } { Stella_Object item = null; Cons iter002 = assertion.rest; loop002 : for (;!(iter002 == Stella.NIL); iter002 = iter002.rest) { item = iter002.value; if (StringWrapper.unwrapString(((StringWrapper)(item))) == null) { Stella.STANDARD_WARNING.nativeStream.println("Warning: Some table relation values not set: `" + assertion + "'"); break loop002; } } } assertion.rest = RDBMS.coerceValues(((Cons)(assertion.rest)), RDBMS.getRelationTableInfo(tableRelation)); assertion.nthSetter(tableRelation, 0); return (assertion); } }
9
public boolean similar(Object other) { try { if (!(other instanceof JSONObject)) { return false; } Set<String> set = this.keySet(); if (!set.equals(((JSONObject) other).keySet())) { return false; } Iterator<String> iterator = set.iterator(); while (iterator.hasNext()) { String name = iterator.next(); Object valueThis = this.get(name); Object valueOther = ((JSONObject) other).get(name); if (valueThis instanceof JSONObject) { if (!((JSONObject) valueThis).similar(valueOther)) { return false; } } else if (valueThis instanceof JSONArray) { if (!((JSONArray) valueThis).similar(valueOther)) { return false; } } else if (!valueThis.equals(valueOther)) { return false; } } return true; } catch (Throwable exception) { return false; } }
9
@SuppressWarnings({ "unchecked", "rawtypes" }) public void initializeComponents() { regionCombobox = new JComboBox<String>(); progressBar = new JProgressBar(); contentPane = new JPanel(); coverLabel = new JLabel(""); lolPath = new JTextField(); openButton = new JButton("Open"); ButtonPatch = new JButton("Patch"); btnUnpatch = new JButton("Unpatch"); menuBar = new JMenuBar(); oeffnen = new JMenuItem("EU thread"); Links = new JMenu("Links"); mntmUsThread = new JMenuItem("US thread"); mntmGerThread = new JMenuItem("Ger thread"); separator_2 = new JSeparator(); mntmGetMoreSoundpacks = new JMenuItem("Get more Soundpacks"); mntmHowToUse = new JMenuItem("How to use"); mntmHowToInstall = new JMenuItem("How to install custom Soundpacks"); mntmHowToCreate = new JMenuItem("How to create an own Soundpacks"); mnAbout = new JMenu("About"); mntmInfo = new JMenuItem("Info"); mntmCheckForUpdates = new JMenuItem("Check for Updates"); mntmMenuitem = new JMenuItem("Logfiles"); Play = new JMenuItem("Play League of Legends"); lblSelectSoundpack = new JLabel(); lblSelectYourRegion = new JLabel(); separatorLeft = new JSeparator(); separatorRight = new JSeparator(); lblPatchUnpatch = new JLabel(); infoButton = new JButton("Info"); model = new DefaultComboBoxModel(); comboBox = new JComboBox(model); con = new Console(this); new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("ErhoeheProgressbarWert")) { Object obj = evt.getNewValue(); int value = ((Integer) (obj)).intValue(); progressBar.setValue(value); } else if (evt.getPropertyName().equals("ErstelleMessagebox")) { ShowMessagebox(evt.getNewValue().toString()); } else if (evt.getPropertyName().equals("ERROR")) { new RADSSoundPatcher.GUI.ErrorScreen( (Exception) evt.getNewValue()); } } }; }
3
public Segment getIntersection(GeometricModel model) { /*if (centre.getBrutalLength(model.centre) > this.maxLength + model.maxLength) return null;*/ float maxLength = this.maxLength + model.maxLength; maxLength *= maxLength; if (centre.getLengthSquared(model.centre) > maxLength) return null; for (int i = 0; i < model.getPointCount(); i++) { for (int j = 0; j < getPointCount(); j++) { Point p = Point.getIntersection(getPoint(j), getPoint(j + 1), model.getPoint(i), model.getPoint(i + 1)); if (p != null) { double d1 = p.getDistanceToPoint(model.getPoint(i)) + p.getDistanceToPoint(model.getPoint(i + 1)); double d2 = p.getDistanceToPoint(getPoint(j)) + p.getDistanceToPoint(getPoint(j + 1)); if (d1 < d2) { return new Segment(p, Point.getNormal(model.getPoint(i), model.getPoint(i + 1))); } else { return new Segment(p, Point.getNormal(getPoint(j), getPoint(j + 1))); } } } } /* for (int i=0; i<model.getPointCount(); i++) if (contains(model.getPoint(i))) { return model.getPoint(i); } for (int i=0; i<getPointCount(); i++) if (model.contains(getPoint(i))) { return getPoint(i); } */ return null; }
5
public void run() { try { while (running) { if(IsConnectedToServer == true){ String message = null; try{ message = din.readUTF(); LatestServerReply = message; GetServerMessages.CheckServerMessages(message); waitingforreply = false; }catch(Exception e){ IsConnectedToServer = false; Main.DisconnectFromServer(); } } } }catch( Exception ie ){ ie.printStackTrace(); IsConnectedToServer = false; running = false; Main.DisconnectFromServer(); } finally { try{ if(dout != null){ dout.close(); } if(din != null){ din.close(); } if(socket != null){ socket.close(); } }catch(Exception e){ e.printStackTrace(); } } }
8
public static void main(String[] args) throws IOException { // TODO Auto-generated method stub out.println("Please enter the maze you would like to run:"); String input = "src/MazeReadIn/trickysearch2";//console().readLine(); String output = input+"Solution"; Maze myMaze = ReadMaze.parseMaze(input); // className.methodName ArrayList<String> result = new ArrayList<String>(); boolean firstLoop = true; ArrayList<Integer> counter = new ArrayList<Integer>(); counter.add(new Integer(0)); counter.add(new Integer(0)); ArrayList<Pair<Integer, Integer>> reachedGoals = new ArrayList<Pair<Integer, Integer>>(); while(myMaze.goals.size()>0){ ArrayList<String> partialResult = BFS(myMaze, counter, reachedGoals); if(firstLoop){ result = ArrayListHelper.add(partialResult, result); firstLoop = false; } else { result = ArrayListHelper.add(partialResult.subList(0, partialResult.size()-1), result); } } out.println("SOLUTION:"); double cost = 0; for(int i = result.size() - 1; i >= 0; i--){ out.println(result.get(i)); } for(int i = result.size() - 2; i >= 0; i--){ int currFirst = Integer.parseInt(result.get(i).split(",")[0]); double thisCost = getCost(currFirst); //System.out.println("2^" + currFirst + " = " + thisCost); cost += thisCost; } out.println("PATH COST: " + cost); //out.println("PATH LEN:" + (result.size() - 1)); out.println("MAX TREE DEPTH:"+ (result.size() - 1)); out.println("VISITED:"+ counter.get(0)); out.println("FRONTIER COUNT:"+ counter.get(1)); WriteMaze.writeSolution(input, result, output); //WriteMaze.writeSolution(input, result, output, reachedGoals); }
4
public void drawWorldMap(){ worldMap[1] = super.mouseX >= 522 && super.mouseX <= 558 && super.mouseY >= 124 && super.mouseY < 161; if (worldMap[0] && worldMap[1]) { WorldOrb[1].drawSprite(10, 123); } else if (worldMap[1]) { WorldOrb[1].drawSprite(10, 123); } else { WorldOrb[0].drawSprite(10, 123); } }
6
public static boolean getBooleanValue(String value) { if(value != null) if(value.equals("true")) return true; else if(value.equals("false")) return false; throw new IllegalArgumentException("Invalid value"); }
3
public void judge() { int d = dealer.score(); int p = player.score(); if ((d > 21 && p > 21) || d == p) { System.out.println(EVEN); } else if (p <= 21 && (d > 21 || d < p)) { System.out.println(WIN); } else { System.out.println(LOST); } }
6
public boolean skipPast(String to) throws JSONException { boolean b; char c; int i; int j; int offset = 0; int length = to.length(); char[] circle = new char[length]; /* * First fill the circle buffer with as many characters as are in the * to string. If we reach an early end, bail. */ for (i = 0; i < length; i += 1) { c = next(); if (c == 0) { return false; } circle[i] = c; } /* We will loop, possibly for all of the remaining characters. */ for (;;) { j = offset; b = true; /* Compare the circle buffer with the to string. */ for (i = 0; i < length; i += 1) { if (circle[j] != to.charAt(i)) { b = false; break; } j += 1; if (j >= length) { j -= length; } } /* If we exit the loop with b intact, then victory is ours. */ if (b) { return true; } /* Get the next character. If there isn't one, then defeat is ours. */ c = next(); if (c == 0) { return false; } /* * Shove the character in the circle buffer and advance the * circle offset. The offset is mod n. */ circle[offset] = c; offset += 1; if (offset >= length) { offset -= length; } } }
9
public void provideFontChar(char chr, RSFontChar fontChar) { if (disposed) return; if (fontChar == null) fontChar = DUMMY_FONT_CHAR; int sector = chr >>> 8; int index = chr & 0xff; RSFontChar[][] charCache = this.charCache; RSFontChar[] cacheSector = charCache[sector]; if (cacheSector != null) { cacheSector[index] = fontChar; return; } cacheSector = charCache[sector] = new RSFontChar[256]; cacheSector[index] = fontChar; }
3
public static int maxProfit2(int[] prices) { BestTimetoBuyandSellStockIII main = new BestTimetoBuyandSellStockIII(); Queue<Integer> profitQueue = new PriorityQueue<Integer>(1000, main.new OwnComparator()); Stack<Integer> stack = new Stack<Integer>(); int lowPos = 0; int tempLowPos = 0; int highPos = 0; int max = 0; boolean continueSeq = false; for (int i = 0; i < prices.length; i++) { if (prices[i] < prices[lowPos]) { lowPos = i; tempLowPos = i; } int diff = prices[i] - prices[lowPos]; if (diff > max) { max = diff; // highPos = i; if (continueSeq) { } if (i + 1 < prices.length && prices[i + 1] < prices[i]) { } } } if (max <= 0) { return 0; } else { max = profitQueue.poll(); if (profitQueue.peek() != null) max += profitQueue.poll(); return max; } }
8
private void listaDeclaraciones() { if(aux.getTipo()!=Nodo.tipoToken.EOF){ Nodo tem = this.declaracion(); if (tem != null) { tip.add(tem); if (aux.getTipo()==Nodo.tipoToken.PuntoyComa) { aux=(Tokens2)tok.next(); this.listaDeclaraciones(); } else { error(" Se esperaba ;"); } } if (aux.getTipo()!=Nodo.tipoToken.EOF) { if(aux.getTipo()!=Nodo.tipoToken.Identificador && aux.getTipo()!=Nodo.tipoToken.LlaveDer) { if (!(aux.getToken().equals("int") || aux.getToken().equals("float") || aux.getToken().equals("bool"))) { error("Token invalido: "+aux.getToken()+" Revise sintaxis listaDeclaraciones"); aux=(Tokens2)tok.next(); } this.listaDeclaraciones(); } } } }
9
public void visitInRange(int id, AABB range, IEntityVisitor visitor) { Set<Entity> entities = structure.queryRange(new HashSet<Entity>(), range); Iterator<Entity> it = entities.iterator(); while (it.hasNext()) { Entity entity = it.next(); if (entity.isRemoved) { continue; } EntityComponent component = id == -1 ? null : entity .getComponent(id); if (component != null || id == -1) { visitor.visit(entity, component); } } }
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Servidor)) { return false; } Servidor other = (Servidor) object; if ((this.idServidor == null && other.idServidor != null) || (this.idServidor != null && !this.idServidor.equals(other.idServidor))) { return false; } return true; }
5
private static String readResponse(URLConnection connection, String encoding) throws IOException { if ( !isValidContentType(connection) ) throw new IOException("Invalid content type for " + connection.getURL()); BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream(), encoding) ); String line, lines = ""; while (( line = reader.readLine() ) != null) lines += line + "\n"; reader.close(); return lines; }
2
public void Update() { for (int i = 0; i < yPositions.length; i++) { // Move image yPositions[i] += speed; // If image moving left if (speed < 0) { // If image is out of the screen, it moves it to the end of line of images. if (yPositions[i] <= -image.getHeight()) { yPositions[i] = image.getHeight() * (yPositions.length - 1); } } // If image moving right else { // If image is out of the screen, it moves it to the end of line of images. if (yPositions[i] >= image.getHeight() * (yPositions.length - 1)) { yPositions[i] = -image.getHeight(); } } } }
4
public static int[] rotate(int[] pix, float beta, int iw, int ih, int owh) { int[] opix = new int[owh * owh]; double t = beta / 180; float cos_beta = (float) Math.cos(t * Math.PI); float sin_beta = (float) Math.sin(t * Math.PI); for (int i = 0; i < owh; i++) { for (int j = 0; j < owh; j++) { float u = (j - owh / 2) * cos_beta + (i - owh / 2) * sin_beta; float v = (i - owh / 2) * cos_beta + (j - owh / 2) * sin_beta; u += iw / 2; v += ih / 2; int x = (int) u; int y = (int) v; int index = i * owh + j; if (x >= 0 && x <= iw - 1 && y >= 0 && y <= ih - 1) { opix[index] = pix[y * iw + x]; } } } return opix; }
6
public Object getParameterValue(Object parameter) { if (parameter == null || parameter instanceof Number || parameter instanceof String || parameter instanceof Character || parameter instanceof Boolean || parameter instanceof Date || parameter instanceof Object[][] || parameter instanceof UserTypeInstance) return parameter; else throw new IllegalArgumentException( "Parameter " + parameter + " of type " + parameter.getClass() + " not an instance of Number, String, Character, Boolean or Date"); }
8
public static void main(String[] args) { Factual factual = factual(); // Get all entities that are possibly a match ReadResponse resp = factual.resolves(new ResolveQuery() .add("name", "Buena Vista") .add("latitude", 34.06) .add("longitude", -118.40)); for(Map<?, ?> rec : resp.getData()) { System.out.println(rec); } System.out.println("---"); // Get the entity that is a full match, or null: System.out.println( factual.resolve(new ResolveQuery() .add("name", "Buena Vista") .add("latitude", 34.06) .add("longitude", -118.40))); }
3
public void test_toPrinter() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); try { bld.toPrinter(); fail(); } catch (UnsupportedOperationException ex) {} bld.appendLiteral('X'); assertNotNull(bld.toPrinter()); }
1
public List getModelChildren() { List modelChildren; if (getModel() instanceof PaletteContainer) modelChildren = new ArrayList( ((PaletteContainer) getModel()).getChildren()); else return Collections.EMPTY_LIST; PaletteEntry prevVisibleEntry = null; for (Iterator iter = modelChildren.iterator(); iter.hasNext();) { PaletteEntry entry = (PaletteEntry) iter.next(); if (!entry.isVisible()) // not visible iter.remove(); else if (entry instanceof PaletteSeparator && prevVisibleEntry == null) // first visible item in a group is a separator, don't need it iter.remove(); else if (entry instanceof PaletteSeparator && prevVisibleEntry instanceof PaletteSeparator) // previous visible entry was a separator, don't need it iter.remove(); else prevVisibleEntry = entry; } // check to see if last visible entry was a separator, and thus should // be hidden if (prevVisibleEntry instanceof PaletteSeparator) modelChildren.remove(prevVisibleEntry); return modelChildren; }
8
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final PrintWriter out = response.getWriter(); long startTime = System.currentTimeMillis(); out.println("Checking WEB-INF/classes..."); out.println(); WebScanner scanner = new WebScanner(); scanner.add(this.getServletContext(), "/WEB-INF/classes"); ScanFilter allowAll = new ScanFilter() { @Override public boolean accept(PathElement resource) { return true; } }; Set<PathElement> classes = scanner.scan(allowAll); for (PathElement found : classes) { out.println(found.getClass().getName() + " " + found); } out.println(); out.println("WEB-INF/lib search list:"); out.println(); scanner = new WebScanner(); scanner.add(this.getServletContext(), "/WEB-INF/lib"); for(PathElement search : scanner.getScanPath()) { out.println(search.getClass().getName() +" "+ search); } out.println(); out.println("WEB-INF/lib result list:"); out.println(); Set<PathElement> lib = scanner.scan(allowAll); for (PathElement path : lib) { out.println(path.getClass().getName() + path); } scanner = new WebScanner(); scanner.addPrivateResources(this.getServletContext()); out.println(); out.println("Scanning WEB-INF/ private..."); out.println(); Set<PathElement> priv = scanner.scan(allowAll); for (PathElement found : priv) { out.println(found.getClass().getName() + " " + found); } scanner = new WebScanner(); scanner.addPublicResources(this.getServletContext()); out.println(); out.println("Scanning public..."); out.println(); Set<PathElement> publik = scanner.scan(allowAll); for (PathElement found : publik) { out.println(found.getClass().getName() + " " + found); } out.println(); out.println("Finished. Elapsed time: " + (System.currentTimeMillis() - startTime)); }
5
public void testGetSetNextSegment() { VehicleAcceptor[] roads = new VehicleAcceptor[10]; for (int i = 0; i < 10; i++) { VehicleAcceptor r = VehicleAcceptorFactory.newRoad(); roads[i] = r; if (i > 0) { roads[i-1].setNextSeg(r); } } for (int i =0; i < 9; i++) { Assert.assertTrue(roads[i].getNextSeg(null) != null); } Assert.assertTrue(roads[9].getNextSeg(null) == null); }
3
@Override public void loadFromFile(String trainFile, String testFile, String quizFile, String featureFile) { System.out.print("Loading dataset... "); try { if(trainFile != null && trainFile.length() > 0); loadDataFromFile(trainFile, InstanceType.Train); if(testFile != null && testFile.length() > 0) loadDataFromFile(testFile, InstanceType.Test); if(quizFile != null && quizFile.length() > 0) loadDataFromFile(quizFile, InstanceType.Quiz); if(featureFile != null && featureFile.length() > 0) loadFeatureFromFile(featureFile); } catch (IOException e) { e.printStackTrace(); } System.out.println(this.toString()); }
9
public boolean detectAmbiguities() { iteration = 0; int maxpairs = 0; int prevSize; int size = nfa.items.size() + 2 + nfa.transitions.size(); do { ++iteration; monitor.println("\nBuilding pair graph:"); if (!traverse()) { // aborted by user return false; } monitor.println(done.usageStatistics()); if (maxpairs == 0 ) { maxpairs = done.size(); } if (AmbiDexterConfig.outputGraphs) { toDot(nfa.grammar.name + ".pp" + iteration + ".dot"); } if (AmbiDexterConfig.outputDistMap) { computeDistanceMap(nfa.grammar.name + ".distmap" + iteration + ".png"); //computeUsageMap(nfa.grammar.name + ".pairmap" + iterations + ".png"); } filter(); nfa.printSize("\nNFA " + iteration, monitor); monitor.println("Used productions: " + nfa.getUsedProductions().size()); if (AmbiDexterConfig.outputGraphs) { nfa.toDot(nfa.grammar.name + ".nfa" + iteration + ".dot"); } prevSize = size; size = nfa.items.size() + 2 + nfa.transitions.size(); } while (size > 3 && size != prevSize); // 3 are always used: startstate, endstate, and shift between the two monitor.println("\nIterations: " + iteration + ", max pairs: " + maxpairs); return true; }
7
public static String getNoteName(int i) { if(i<0) return "Paus"; return NOTE_NAMES[i % 12]; }
1
public ShellLinkHeader setShowCommand(int n) throws ShellLinkException { if (n == SW_SHOWNORMAL || n == SW_SHOWMAXIMIZED || n == SW_SHOWMINNOACTIVE) { showCommand = n; return this; } else throw new ShellLinkException(); }
3
@Override public void reactToChanges(ObservationEvent ev) { if (ev instanceof CheckBoxEvent) { CheckBoxEvent event = (CheckBoxEvent) ev; this.setThoricity(event.isChecked()); this.notifyObserver(); } else if (ev instanceof OptionLineEvent) { OptionLineEvent event = (OptionLineEvent) ev; String label = ((CustomOptionLine) (event.getSource())).getLabel(); switch (label) { case rowsLabel: this.setHeight(event.getValue()); break; case columnsLabel: this.setWidth(event.getValue()); break; case minesLabel: this.setMinesNumber(event.getValue()); break; } this.notifyObserver(); } else if (ev instanceof NewGamePanelEvent) { GameDifficulty gD = ((NewGamePanel) ev.getSource()).getDifficulty(); if (gD != GameDifficulty.CUSTOM) { this.setWidth(gD.getWidth()); this.setHeight(gD.getHeight()); this.setMinesNumber((int) Math.floor(gD.getBombPercentage() * this.width * this.height / 100)); this.setThoricity(gD.isThorique()); } } }
7
private void updateGame() { handler.updateObjects(); for (int i = 0; i < handler.objects.size(); i++) { if (handler.objects.get(i).getID() == ObjectID.Player) { cam.updateCam(handler.objects.get(i)); } } }
2
public void handleNonGeometricAttributes(SimpleFeatureImpl feature) throws UnsupportedEncodingException, FileNotFoundException { try { String featureAttribute = "featureWithoutID"; String featureName = "featureWithoutName"; String featureClass = "featureWithoutClass"; //Feature id if (feature.getAttribute(configuration.attribute) != null) { featureAttribute = feature.getAttribute(configuration.attribute).toString(); } //Feature name if (feature.getAttribute(configuration.featname) != null) { featureName = feature.getAttribute(configuration.featname).toString(); } //Feature classification if (feature.getAttribute(configuration.featclass) != null) { featureClass = feature.getAttribute(configuration.featclass).toString(); } if (!featureAttribute.equals(configuration.ignore)) { String encodingType = URLEncoder.encode(configuration.type, UtilsConstants.UTF_8).replace(STRING_TO_REPLACE, REPLACEMENT); String encodingResource = URLEncoder.encode(featureAttribute, UtilsConstants.UTF_8).replace(STRING_TO_REPLACE, REPLACEMENT); String aux = encodingType + SEPARATOR + encodingResource; //Insert literal for name (name of feature) if ((!featureName.equals(configuration.ignore)) && (!featureName.equals(""))) //NOT NULL values only { insertResourceNameLiteral( configuration.nsUri + aux, configuration.nsUri + Constants.NAME, featureName, configuration.defaultLang ); } //Insert literal for class (type of feature) if ((!featureClass.equals(configuration.ignore)) && (!featureClass.equals(""))) //NOT NULL values only { encodingResource = URLEncoder.encode(featureClass, UtilsConstants.UTF_8).replace(STRING_TO_REPLACE, REPLACEMENT); //Type according to application schema insertResourceTypeResource( configuration.nsUri + aux, configuration.nsUri + encodingResource); } } } catch(Exception e) {} }
9
public Type getHint() { Type bottomHint = bottomType.getHint(); Type topHint = topType.getHint(); if (topType == tNull && bottomType.equals(bottomHint)) return bottomHint; return topHint; }
2
public int compare(ByteBuffer o1, ByteBuffer o2) { byte[] byteString1 = o1.array(); byte[] byteString2 = o2.array(); int minLength = byteString1.length > byteString2.length ? byteString2.length : byteString1.length; for (int i = 0; i < minLength; i++) { int bitCompare = bitCompare(byteString1[i], byteString2[i]); if (bitCompare != 0) { return bitCompare; } } if (byteString1.length > byteString2.length) { return 1; } else if (byteString1.length < byteString2.length) { return -1; } return 0; }
5
private Builder setStackTrace(Throwable t) { // view button stage.viewStacktraceButton = new ToggleButton("View stacktrace"); // copy button stage.copyStacktraceButton = new Button("Copy to clipboard"); HBox.setMargin(stage.copyStacktraceButton, new Insets(0, 0, 0, MARGIN)); stage.stacktraceButtonsPanel = new HBox(); stage.stacktraceButtonsPanel.getChildren().addAll( stage.viewStacktraceButton, stage.copyStacktraceButton); VBox.setMargin(stage.stacktraceButtonsPanel, new Insets(MARGIN, MARGIN, MARGIN, 0)); stage.messageBox.getChildren().add(stage.stacktraceButtonsPanel); // stacktrace text stage.stackTraceLabel = new Label(); stage.stackTraceLabel.widthProperty().addListener(new ChangeListener<Number>() { public void changed(ObservableValue<? extends Number> ov, Number oldValue, Number newValue) { alignScrollPane(); } }); stage.stackTraceLabel.heightProperty().addListener(new ChangeListener<Number>() { public void changed(ObservableValue<? extends Number> ov, Number oldValue, Number newValue) { alignScrollPane(); } }); StacktraceExtractor extractor = new StacktraceExtractor(); stage.stacktrace = extractor.extract(t); stage.scrollPane = new ScrollPane(); stage.scrollPane.setContent(stage.stackTraceLabel); stage.viewStacktraceButton.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent t) { stage.stacktraceVisible = !stage.stacktraceVisible; if (stage.stacktraceVisible) { stage.messageBox.getChildren().add(stage.scrollPane); stage.stackTraceLabel.setText(stage.stacktrace); alignScrollPane(); } else { stage.messageBox.getChildren().remove(stage.scrollPane); //alignScrollPane(); stage.setWidth(stage.originalWidth); stage.setHeight(stage.originalHeight); stage.stackTraceLabel.setText(null); stage.centerOnScreen(); } stage.messageBox.layout(); } }); stage.copyStacktraceButton.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent t) { Clipboard clipboard = Clipboard.getSystemClipboard(); Map<DataFormat, Object> map = new HashMap<DataFormat, Object>(); map.put(DataFormat.PLAIN_TEXT, stage.stacktrace); clipboard.setContent(map); } }); stage.showingProperty().addListener(new ChangeListener<Boolean>() { public void changed(ObservableValue<? extends Boolean> ov, Boolean oldValue, Boolean newValue) { if (newValue) { stage.originalWidth = stage.getWidth(); stage.originalHeight = stage.getHeight(); } } }); return this; }
5
public static float[][] convertToFloatArray2D(String string) { float[][] theData = null; String[] segments = string.split(" "); theData = new float[segments.length][]; for (int i = 0; i < theData.length; i++) { theData[i] = convertToFloatArray1D(segments[i], i); } return theData; }
1
public static long fatorial(long number) { if (number == 0 || number ==1) { return 1; } return number * fatorial(number - 1); }
2
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(EditSongPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EditSongPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EditSongPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EditSongPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ }
6
public void setOptions(String[] options) throws Exception { setDebug(Utils.getFlag('D', options)); String classIndex = Utils.getOption('c', options); if (classIndex.length() != 0) { if (classIndex.toLowerCase().equals("last")) { setClassIndex(0); } else if (classIndex.toLowerCase().equals("first")) { setClassIndex(1); } else { setClassIndex(Integer.parseInt(classIndex)); } } else { setClassIndex(0); } String trainIterations = Utils.getOption('x', options); if (trainIterations.length() != 0) { setTrainIterations(Integer.parseInt(trainIterations)); } else { setTrainIterations(50); } String trainPoolSize = Utils.getOption('T', options); if (trainPoolSize.length() != 0) { setTrainPoolSize(Integer.parseInt(trainPoolSize)); } else { setTrainPoolSize(100); } String seedString = Utils.getOption('s', options); if (seedString.length() != 0) { setSeed(Integer.parseInt(seedString)); } else { setSeed(1); } String dataFile = Utils.getOption('t', options); if (dataFile.length() == 0) { throw new Exception("An arff file must be specified" + " with the -t option."); } setDataFileName(dataFile); String classifierName = Utils.getOption('W', options); if (classifierName.length() == 0) { throw new Exception("A learner must be specified with the -W option."); } setClassifier(Classifier.forName(classifierName, Utils.partitionOptions(options))); }
8
private static void writeTable(PdfWriter __writer) throws BadElementException, DocumentException, IOException { PdfContentByte canvas = __writer.getDirectContent(); canvas.saveState(); canvas.setLineWidth(0.1f); float origin_x = 50f; float origin_y = 700f; float cell_width = 40f; float cell_height = 40f; // the gap size between each cell borders. float separator = 3f; for (int i=0; i <= 5; i++) { for (int j=0; j <= 3; j++) { if (i < 5) { // Horizontal line canvas.moveTo( origin_x+separator+ i*cell_width, origin_y+j*cell_height); canvas.lineTo( origin_x-separator+(i+1)*cell_width, origin_y+j*cell_height); canvas.stroke(); } if (j < 3) { // Vertical Line canvas.moveTo( origin_x+i*cell_width, origin_y+separator+ j*cell_height); canvas.lineTo( origin_x+i*cell_width, origin_y-separator+(j+1)*cell_height); canvas.stroke(); } } } BaseFont bf = BaseFont.createFont(); canvas.beginText(); canvas.setFontAndSize(bf, 12); for (int i=0; i<5; i++) { for (int j=0; j<3; j++) { canvas.showTextAligned(Element.ALIGN_CENTER, (3-j)+""+(i+1), origin_x+cell_width*i+cell_width/2f, origin_y+cell_height*j+cell_height/2.5f, 0); } } canvas.endText(); canvas.restoreState(); }
6
public static void flush() { if(mStream != null) mStream.flush(); }
1
public void enterQueue(Vehicle v) throws SimulationException, VehicleException { if(v.isParked() || v.isQueued() || v.wasParked() || v.wasQueued()){ throw new VehicleException("Vehicle not in correct state"); } if(queueFull()){ throw new SimulationException("Queue is full"); } status += setVehicleMsg(v, "N", "Q"); queue.add(v); v.enterQueuedState(); }
5
public void hitEnemy(String name, int damage) { // vind de juiste enemy in de array for (Enemy E : myEnemies) { String[] namesplit = E.getName().split(" "); if (namesplit[0].toLowerCase().equals(name) || E.getName().toLowerCase().equals(name)) { // Als de enemy levend is if (E.isAlive()) { System.out .println("Goggan: Thats it master! hit the sucker!"); // Maak een random damage getal Random rnd_dmg = new Random(); int dmg = rnd_dmg.nextInt(damage + 1); // Als de current hp - het gemaakte damage getal 1 of hoger is dan if (E.getHp() - dmg > 0) { // breng de schade in rekening E.setHp(E.getHp() - dmg); // Print wat leuke info System.out.println(E.getName() + " has received " + dmg + " points of damage"); System.out.println(E.getName() + " has got "+ E.getHp() + " health points left."); break; } else {// Waarde < 1 , dus dood E.setHp(E.getHp() - dmg); E.setAlive(false); items.add(E.getloot()); System.out.println("You killed " + E.getName()); } } else {// Hij is al lang dood :P System.out.println("You already killed " + E.getName()); } } else{// naam van villain niet goed getypt System.out.println("You have to type at least the monsters first name to attack"); } } }
5
private int valueValidator(int value, JTextField field) { if (!field.equals(minesField) && value < 8) { value = 8; } else if (field.equals(heightField) && value > 16) { value = 16; } else if (field.equals(widthField) && value > 30) { value = 30; } else if (field.equals(minesField) && value < 1 || value > (height * width)) { value = 10; } return value; }
9
public void escape(KeyEvent e) { if (selectionCellsHandler != null) { selectionCellsHandler.reset(); } if (connectionHandler != null) { connectionHandler.reset(); } if (graphHandler != null) { graphHandler.reset(); } if (cellEditor != null) { cellEditor.stopEditing(true); } }
4
@RequestMapping(value = "/buildQuestion", method = RequestMethod.POST) public @ResponseBody String buildQuestion(@RequestParam int count) { ObjectWriter mapper = new ObjectMapper().writer().withDefaultPrettyPrinter(); List<Question> listQuestions = questionService.getQuestions(); String json = ""; try { if(count != 5) json = mapper.writeValueAsString(listQuestions.get(count)); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return json; }
4
public static void deleteByAppt(long apptId) throws SQLException { PreparedStatement statement = connect.prepareStatement( "delete from Reminder where appointmentId = ? "); statement.setLong(1, apptId); statement.executeUpdate(); }
0
private void doTheDamnThing(RandomAccessFile fp) throws IOException { byte[] b = new byte[26]; // Load IMPM header fp.read(b, 0, 4); if(b[0] == 'I' && b[1] == 'M' && b[2] == 'P' && b[3] == 'M') { loadDataIT(fp); return; } // Attempt to load XM fp.seek(0); if(Util.readStringNoNul(fp,b,17).equals("Extended Module: ")) { fp.seek(17+20); if(fp.read() == 0x1A) { fp.seek(17); loadDataXM(fp); return; } } // Attempt to load ST3 module fp.seek(0x1C); if(fp.readUnsignedShort() == 0x1A10) { fp.seek(0); loadDataS3M(fp); return; } fp.seek(0); // Assume this is a .mod file if(true) { loadDataMOD(fp); return; } throw new RuntimeException("module format not supported"); }
8
private List<HantoCell> getContiguousCells(List<HantoCell> board, HantoCell aCell){ List<HantoCell> contigCells = new ArrayList<HantoCell>(); if (aCell != null){ int x = aCell.getX(); int y = aCell.getY(); if (isCellOccupied(x, y + 1)){ contigCells.add(findCell(x, y + 1, board)); } if (isCellOccupied(x + 1, y)){ contigCells.add(findCell(x + 1, y, board)); } if (isCellOccupied(x - 1, y)){ contigCells.add(findCell(x - 1, y, board)); } if (isCellOccupied(x, y - 1)){ contigCells.add(findCell(x, y - 1, board)); } if (isCellOccupied(x + 1, y - 1)){ contigCells.add(findCell(x + 1, y - 1, board)); } if (isCellOccupied(x - 1, y + 1)){ contigCells.add(findCell(x - 1, y + 1, board)); } } return contigCells; }
7
public static ArrayList<Integer> numerosPrimos(int n) { if (n < 2) return new ArrayList<Integer>(); char[] is_composite = new char[(n - 2 >> 5) + 1]; final int limit_i = n - 2 >> 1, limit_j = 2 * limit_i + 3; ArrayList<Integer> results = new ArrayList<>((int) Math.ceil(1.25506 * n / Math.log(n))); results.add(1); results.add(2); for (int i = 0; i < limit_i; ++i) if ((is_composite[i >> 4] & 1 << (i & 0xF)) == 0) { results.add(2 * i + 3); for (long j = 4L * i * i + 12L * i + 9; j < limit_j; j += 4 * i + 6) is_composite[(int) (j - 3L >> 5)] |= 1 << (j - 3L >> 1 & 0xF); } return results; }
4
public int getParameter(String paramname){ if(paramname == "HoodSize"){return 0;} if(paramname == "NextX"){return -1;} if(paramname == "NextY"){return -1;} if(paramname == "Age"){ return age;} if(paramname == "Mat"){ return mat;} if(paramname == "Matcount"){ return matcount;} if(paramname == "InMode"){return inmode;} if(paramname == "OutMode"){return outmode;} return -1;}
8
public String toInfoString() { StringBuffer sb = new StringBuffer(); for (int i = 0; i < total; i++) { sb.append("LinkedList[" + i + "] = " + findElement(i).toInfoString()); if (i < total - 1) { sb.append("\n"); } } return sb.toString(); }
2
public static void main(String[] args) throws InterruptedException, IOException { TCounter messagesReceived = new DropwizardTCounter(); messagesReceived.register("DEBUG.ClientPusb.MessagesReceiced"); ClientTurtleEnvironment nioClientMT = new ClientTurtleEnvironment(); nioClientMT.open(); Thread.sleep(500); System.out.println("Client Connected"); System.out.println("1- subscribe"); System.out.println("2- publish"); System.out.println("3- both"); Scanner scanner = new Scanner(System.in); int value = 3; try { value = scanner.nextInt(); } catch (Exception e) { value = 3; } switch (value) { case 1: { System.out.println("Remote Subscribe"); try { nioClientMT.remoteSubscribe((header, body, firstMatchTag,sourceSubscriber) -> { log.info(" ClientTurtleEnvironment " + new String(body) + " - firstMatch" + firstMatchTag); messagesReceived.inc(); }, "testtag"); } catch (IOException e) { e.printStackTrace(); } break; } case 2: { try { System.out.println("pub count"); value = scanner.nextInt(); } catch (Exception e) { value = 1; } System.out.println("Remote Publish"); for (int i = 0; i < value; i++) { nioClientMT.remotePublish("ciao".getBytes(), "testtag"); } break; } } ConsoleReporter reporter = ConsoleReporter.forRegistry(nioClientMT.getMetrics()) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build(); reporter.start(10, TimeUnit.SECONDS); log.info("press key to stop"); scanner = new Scanner(System.in); scanner.nextLine(); reporter.close(); nioClientMT.close(); }
6
protected boolean isFinished() { return false; }
0
CtField getField2(String name) { CtField df = getDeclaredField2(name); if (df != null) return df; try { CtClass[] ifs = getInterfaces(); int num = ifs.length; for (int i = 0; i < num; ++i) { CtField f = ifs[i].getField2(name); if (f != null) return f; } CtClass s = getSuperclass(); if (s != null) return s.getField2(name); } catch (NotFoundException e) {} return null; }
5
@Override public void actionPerformed(ActionEvent e) { //System.out.println("CutAction"); OutlinerCellRendererImpl textArea = null; boolean isIconFocused = true; Component c = (Component) e.getSource(); if (c instanceof OutlineButton) { textArea = ((OutlineButton) c).renderer; } else if (c instanceof OutlineLineNumber) { textArea = ((OutlineLineNumber) c).renderer; } else if (c instanceof OutlineCommentIndicator) { textArea = ((OutlineCommentIndicator) c).renderer; } else if (c instanceof OutlinerCellRendererImpl) { textArea = (OutlinerCellRendererImpl) c; isIconFocused = false; } // Shorthand Node node = textArea.node; JoeTree tree = node.getTree(); OutlineLayoutManager layout = tree.getDocument().panel.layout; //System.out.println(e.getModifiers()); switch (e.getModifiers()) { case 2: if (isIconFocused) { cut(tree, layout); } else { cutText(textArea, tree, layout); } break; } }
6
@Test public void testGetFileContentHash_CalculatesHashCorrectly_Succeeds() { Path tempFile = null; try { try { tempFile = Files.createTempFile("Photons_test_CalculatesHashCorrectly", ".txt"); } catch (IOException e) { e.printStackTrace(); fail("Could not create temp file."); } // Write something into the file BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(tempFile.toString(), false)); writer.write("Test string..."); } catch (Exception e) { e.printStackTrace(); fail(String.format("Failed to write to file [%s].", tempFile)); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); fail("Failed to close file writer."); } } } // Check hash try { String hash = FileUtil.getFileContentHash(tempFile.toString()); // Reference hash checked at: http://www.md5calc.com/ if (!hash.equals("247a74b52cfe95532fd652242d94ac0029f8dda1346a8cf0cc0874e274b3a2a0")) { fail(String.format("Incorrect hash string retrieved: [%s].", hash)); } } catch (Exception e) { e.printStackTrace(); fail("Failed to get hash string."); } } finally { try { if (tempFile != null) { Files.delete(tempFile); } } catch (IOException e) { e.printStackTrace(); fail(String.format("Failed to delete temporary file [%s]", tempFile)); } } }
8
public void testCsvTools() { String filePath = "C:\\Users\\tdhuang\\Desktop\\功夫baby数据表格1(未加数值)\\关卡对应图片\\high_level_picture.csv"; CsvFile csvFile = new CsvFile(filePath, 0, 4, 1); List<CsvDataLine> data = CsvTools.parse(csvFile); System.out.println(data); assertNotNull(data); }
0
public void query(String query, boolean instant) { if (!instant) { m_thread.query(query); } else { final Connection connection = getConnection(); try { if (connection == null) { Utilities.outputError("Could not connect to database '" + m_databaseName + "'"); return; } m_statement = connection.createStatement(); m_statement.executeUpdate(query); connection.close(); } catch (SQLException e) { e.printStackTrace(); try { m_statement.close(); connection.close(); } catch (SQLException ce) {} } } }
4
public String toString(){ String tmp = ""; for (int r = 1; r <= 17; r++) { // for every row int c = ((r % 2 == 0) ? 2 : 1); // what col to start? for (; c <= 9; c += 2) { Hexpos h = new Hexpos(r, c); if (h.onBoard()){ tmp += "[ " + h.hashCode() + " : " + owner(h ) + "] " ; } } } return tmp; }
4
@Override public void sayToBomberman(String message) throws IOException { writer.append(message).append("\n"); writer.flush(); //possibly not needed as the writer may autoflush after linebreak }
0
public void save(XMLWriter out, LengthUnits units) { double[] size = getPaperSize(units); double[] margins = getPaperMargins(units); PrintService service = getPrintService(); out.startTag(TAG_ROOT); if (service != null) { out.writeAttribute(ATTRIBUTE_PRINTER, service.getName()); } out.writeAttribute(ATTRIBUTE_UNITS, Enums.toId(units)); out.finishTagEOL(); out.simpleTag(TAG_ORIENTATION, Enums.toId(getPageOrientation())); out.simpleTag(TAG_WIDTH, size[0]); out.simpleTag(TAG_HEIGHT, size[1]); out.simpleTag(TAG_TOP_MARGIN, margins[0]); out.simpleTag(TAG_LEFT_MARGIN, margins[1]); out.simpleTag(TAG_BOTTOM_MARGIN, margins[2]); out.simpleTag(TAG_RIGHT_MARGIN, margins[3]); out.simpleTag(TAG_CHROMATICITY, Enums.toId(getChromaticity(false))); out.simpleTag(TAG_SIDES, Enums.toId(getSides())); out.simpleTag(TAG_NUMBER_UP, getNumberUp()); out.simpleTag(TAG_QUALITY, Enums.toId(getPrintQuality(false))); out.simpleTagNotEmpty(TAG_RESOLUTION, createResolutionString(getResolution(false))); out.endTagEOL(TAG_ROOT, true); }
1
public static boolean nameIsOnlyUpperCase(Variable variable) { String name = variable.getName(); for (int i = 0; i < name.length(); i++) { if (!Character.isUpperCase(name.charAt(i)) && name.charAt(i) != '_') { return false; } } return true; }
3
public static final long extractLong(String buffer, long def, boolean localized) { buffer = normalizeNumber(buffer, localized); if (hasDecimalSeparator(buffer, localized)) { return (int) extractDouble(buffer, def, localized); } long multiplier = 1; if (hasBillionsSuffix(buffer)) { multiplier = 1000000000; buffer = removeSuffix(buffer); } else if (hasMillionsSuffix(buffer)) { multiplier = 1000000; buffer = removeSuffix(buffer); } else if (hasThousandsSuffix(buffer)) { multiplier = 1000; buffer = removeSuffix(buffer); } long max = Long.MAX_VALUE / multiplier; long min = Long.MIN_VALUE / multiplier; try { long value = Long.parseLong(buffer); if (value > max) { value = max; } else if (value < min) { value = min; } return value * multiplier; } catch (Exception exception) { return def; } }
7
public void run () { running = true; while (running) { try { Thread.sleep (timeInterval); } catch (Exception e) { break; } if (paused) { running=MoveOn(); if (running) { setChanged (); //modelul a fost updatat, se va notifica View-ul notifyObservers (); //notificam toti observer-i acestui element } else { //highscore Checkscore(); int a=JOptionPane.showConfirmDialog (null,"Play again!","GAME OVER!", JOptionPane.INFORMATION_MESSAGE); if(a==0) { JOptionPane.showMessageDialog(null, "Press Space to play!", "Play", JOptionPane.WARNING_MESSAGE); reset(); //daca s-a apasat OK, jocul se va restarta si trebuie apasata tasta Space pentru a incepe } else System.exit(1); } } } // running = false; // sau aici }
5
@SuppressWarnings("unchecked") public void saveTabData(ArrayList<Section> list) { for (Section s : list) { for (Object o : s.getQuestions()) { if (o != null) { for (Object tab : (ArrayList<Object>) o) { if (tab != null) { if (tab instanceof TabularData) { TabularData d = (TabularData) tab; if (d != null) { if (tabManager.find(d.getFormId(), d.getSectionId(), d.getRowId(), d.getColId(), d.getType()) != null) { tabManager.merge(d); } else { tabManager.persist(d); } } } } } } } } }
8
public ArrayList<Collidable[]> checkCollisions() { ArrayList<Collidable[]> collisions = new ArrayList<Collidable[]>(); for(int a = 0; a < entities.size() - 1; a++) { for(int b = a + 1; b < entities.size(); b++) { Collidable[] current = new Collidable[2]; current[0] = entities.get(a); current[1] = entities.get(b); if(entities.get(a).getHitbox().intersects(entities.get(b).getHitbox())) { collisions.add(current); } } } return collisions; }
3
public DownloadXML(String weburl) { HttpClient client = HttpClients.createDefault(); HttpGet get = new HttpGet(weburl); get.setHeader("Content-Type", "application/xml"); HttpResponse response; try { response = client.execute(get); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream is = entity.getContent(); BufferedReader in = new BufferedReader( new InputStreamReader(is)); //获取文本 buffer = new StringBuffer(); String line = ""; while ((line = in.readLine()) != null) buffer.append(line + "\n"); // System.out.println(buffer); writeXMLFile(); } } catch (IOException e) { e.printStackTrace(); } }
3
@Test public void testPersonenEnRelaties() { assertNotNull(pietEnTeuntje); assertSame(pietEnTeuntje, adm.getGezin(pietEnTeuntje.getNr())); Iterator<Gezin> it = teuntje.getGezinnen(); Gezin teuntjeEnPiet = it.next(); assertFalse(it.hasNext()); assertSame(pietEnTeuntje, teuntjeEnPiet); adm.addPersoon(Geslacht.MAN, new String[]{"tom", "JACOBUS"}, "sWinkelS", "", new GregorianCalendar(1971, Calendar.APRIL, 13), pietEnTeuntje); ArrayList<Persoon> swinkelsen = adm.getPersonen("Swinkels"); assertEquals(2, swinkelsen.size()); Persoon tom = swinkelsen.get(0); if (!tom.getVoornamen().equals("Tom Jacobus")){ tom = swinkelsen.get(1); assertEquals(tom.getVoornamen(),"Tom Jacobus"); } Iterator<Persoon> itKinderen = pietEnTeuntje.getKinderen(); assertSame(tom, itKinderen.next()); assertFalse(itKinderen.hasNext()); adm.addPersoon(Geslacht.VROUW, new String[]{"Anouk"}, "sWinkelS", "", new GregorianCalendar(1972, Calendar.JUNE, 5), null); swinkelsen = adm.getPersonen("swinkels"); assertEquals(3, swinkelsen.size()); Persoon anouk = swinkelsen.get(0); if (!anouk.getVoornamen().equals("Anouk")){ anouk = swinkelsen.get(1); if (!anouk.getVoornamen().equals("Anouk")){ anouk = swinkelsen.get(2); assertEquals(anouk.getVoornamen(),"Anouk"); } } assertNull(anouk.getOuders()); anouk.setOuders(teuntjeEnPiet); assertSame(teuntjeEnPiet,anouk.getOuders()); itKinderen = pietEnTeuntje.getKinderen(); Persoon kind1 = itKinderen.next(); if (kind1 != tom){ assertSame(anouk,kind1); assertSame(tom,itKinderen.next()); } else { assertSame(anouk,itKinderen.next()); } assertFalse(itKinderen.hasNext()); }
4
public void removeElement (klasse o) { int i=indexOf(o); if (i<0) return; O[i]=null; ON--; if (Gap<0 || Gap>i) Gap=i; if (i==OLast-1) OLast--; while (OLast>0 && O[OLast-1]==null) OLast--; if (Gap>=OLast) Gap=-1; }
7