text
stringlengths
14
410k
label
int32
0
9
public int compareTo( Casella casella ) { if ( fila < casella.fila ) { return -1; } else if ( fila > casella.fila ) { return 1; } else if ( columna < casella.columna ) { return -1; } else if ( columna > casella.columna ) { return 1; } else { return 0; } }
4
public int compare(Person p1, Person p2){ int result = p2.getName().compareTo(p1.getName()); if(0==result){ return p2.getId() - p1.getId(); //若姓名相同则按id排序 } return result; }
1
public void test_now_nullDateTimeZone() throws Throwable { try { DateTime.now((DateTimeZone) null); fail(); } catch (NullPointerException ex) {} }
1
public MACMethodType getMACMethod() { return macMethod; }
0
private void run(String[] args) throws Exception { if (args == null || args.length < 1 || args.length >2) { System.out.println(); System.out.println(" ##################################################################################"); System.out.println(" # IMDB Tool, Usage"); System.out.println(" ##################################################################################"); System.out.println(" imdb.sh scan (crawls from current directory searching for nfo-files)"); System.out.println(" or"); System.out.println(" imdb.sh <movie-id> (movie-id format: 0123789)"); System.out.println(" or"); System.out.println(" imdb.sh <time1> <time2> (time format: <hours>[.:]<minutes>[.:]<seconds>)"); System.out.println(); } else { if (args.length==1) { if ("scan".equals(args[0])) { scan(new File(".")); } else { File file = new File("."); ImageProducer ip = new ImageProducer(); ip.run(args[0], file); } } else { System.out.print("Seconds: "); for (int argument=0; argument<2; argument++) { String[] times = args[argument].replaceAll(":", "\\.").split("\\."); ArrayUtils.reverse(times); Integer seconds = 0; for(int index=0; index<times.length; index++) { seconds += ( index>0 ? (int)(Math.pow(60D,(double)index)) : 1) * Integer.parseInt(times[index]); } System.out.print(seconds + " "); } System.out.println(); } } }
8
public Terrain(Map map) { this.mapRenderer = new OrthogonalTiledMapRenderer((TiledMap) map, 1); camera = new OrthographicCamera(960, 640); camera.translate(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2); camera.update(); this.mapRenderer.setView(camera); rocks = new ArrayList<Rock>(); lights = new ArrayList<Light>(); nutrients = new ArrayList<Nutrients>(); waters = new ArrayList<Water>(); plants = new ArrayList<Plant>(); for(int mapLayer = 0; mapLayer < map.getLayers().getCount(); mapLayer ++){ MapLayer mLayer = map.getLayers().get(mapLayer); for(int mapObject = 0; mapObject < mLayer.getObjects().getCount(); mapObject ++){ MapObject mObject = mLayer.getObjects().get(mapObject); if(mObject.getProperties().containsKey("type")){ String type = (String) mObject.getProperties().get("type"); if(type.equals("light")){ double amount = Double.parseDouble((String) mObject.getProperties().get("amount")); Polygon shape = ((PolygonMapObject) mObject).getPolygon(); lights.add(new Light(shape, amount)); } else if(type.equals("water")){ double amount = Double.parseDouble((String) mObject.getProperties().get("amount")); Polygon shape = ((PolygonMapObject) mObject).getPolygon(); waters.add(new Water(shape, amount)); } else if(type.equals("rock")){ Polygon shape = ((PolygonMapObject) mObject).getPolygon(); rocks.add(new Rock(shape)); } else if(type.equals("nutrients")){ double amount = Double.parseDouble((String) mObject.getProperties().get("amount")); Polygon shape = ((PolygonMapObject) mObject).getPolygon(); nutrients.add(new Nutrients(shape, amount)); } } } } this.plants.add(new PlayerPlant(this, new Point(50, 50))); }
7
public static void countUsedHJs(Data data) throws WeFuckedUpException { int usedHJs = 0; for (Subject thisSubject : data.subjects) { for (Semester thisSemester : thisSubject.semesters) { if (thisSemester.usedState != UsedState.none) { usedHJs++; } } } if (usedHJs != 35) { throw new WeFuckedUpException(); } }
4
protected double getAngleFromVelocity() { double angle = 0.0f; float slope = 0.0f; if(velocityX == 0.0f) { if(velocityX > 0.0f) { angle = Math.PI / 2; } else { angle = -Math.PI / 2; } } else { slope = -velocityY / velocityX; angle = Math.atan(slope); if (velocityX < 0) { angle += Math.PI; } } return angle; }
3
public static Graph randomTree3() { int depth = 10; Graph graph = new Graph(depth * 50, depth * 50); int a = 0; int b = 1; int c = 0; graph.addVertex(new Vertex(c++, 25 + 25 * (depth - 1), 25)); for (int i = 1; i < depth; i++) { for (int j = 0; j <= i; j++) { graph.addVertex(new Vertex(c++, 25 + 25 * (depth - i - 1) + 50 * j, 25 + 50 * i)); } graph.addEdge(b, a); for (int j = b + 1; j < c - 1; j++) { if (Math.random() < 0.5) graph.addEdge(j, a + j - b); else graph.addEdge(j, a + j - b - 1); } graph.addEdge(c - 1, a + c - b - 2); a = b; b = c; } return graph; }
4
public void append(String str) { int newsize = this.size + str.length(); // If there's insufficient capacity, make a new array if (newsize >= this.contents.length) { char[] oldcontents = this.contents; this.contents = new char[computeCapacity(newsize)]; for (int i = 0; i < this.size; i++) this.contents[i] = oldcontents[i]; } // if // Copy the characters. for (int i = this.size; i < newsize; i++) this.contents[i] = str.charAt(i - this.size); // Update the size this.size = newsize; } // append(String)
3
public static String getProfile() { StringBuffer sb = new StringBuffer(); sb.append("OS = " + System.getProperty("os.name") + " (" + System.getProperty("os.version") + "), " + System.getProperty("os.arch") + "\n"); sb.append("Java Version = " + System.getProperty("java.version") + "\n"); if (JVM.isMac) { sb.append("apple.awt.graphics.UseQuartz = " + usingQuartz); } return sb.toString(); }
1
public void windowDeactivated(WindowEvent e) { System.out.println("Die Anwendung wurde deaktiviert..."); }
0
public void testGetName_berlin() { DateTimeZone berlin = DateTimeZone.forID("Europe/Berlin"); assertEquals("Central European Time", berlin.getName(TEST_TIME_WINTER, Locale.ENGLISH)); assertEquals("Central European Summer Time", berlin.getName(TEST_TIME_SUMMER, Locale.ENGLISH)); if (JDK6) { assertEquals("Mitteleurop\u00e4ische Zeit", berlin.getName(TEST_TIME_WINTER, Locale.GERMAN)); assertEquals("Mitteleurop\u00e4ische Sommerzeit", berlin.getName(TEST_TIME_SUMMER, Locale.GERMAN)); } else { assertEquals("Zentraleurop\u00e4ische Zeit", berlin.getName(TEST_TIME_WINTER, Locale.GERMAN)); assertEquals("Zentraleurop\u00e4ische Sommerzeit", berlin.getName(TEST_TIME_SUMMER, Locale.GERMAN)); } }
1
private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { boolean isValueNumeric = false; try { if (value.equals("0") || !value.endsWith("0")) { Double.parseDouble(value); isValueNumeric = true; } } catch (NumberFormatException e) { isValueNumeric = false; } if (json.charAt(json.length() - 1) != '{') { json.append(','); } json.append(escapeJSON(key)); json.append(':'); if (isValueNumeric) { json.append(value); } else { json.append(escapeJSON(value)); } }
5
public void makeMovesFromTree(List<Move> moves) { gameOver = false; int moveCount = 0; for (Move move : moves) { if (move instanceof InitialPosition) { InitialPosition initialPosition = (InitialPosition) move; board = new Board(board.boardSize, initialPosition.handicap); } else if (move instanceof PlayerMove) { PlayerMove playerMove = (PlayerMove) move; if (moveCount == moves.size() - 1) { makeMove(playerMove.x, playerMove.y); } else { board = board.makeMove(playerMove.x, playerMove.y); } } else if (move instanceof PlayerPass) { if (moveCount == moves.size() - 1) { passTurn(); } else { board = board.passTurn(); } } activeMove = move; ++moveCount; } }
6
private TileLayer extractData(Node datanode, TileDataEncoding encoding, TileDataCompression compression, int width, int height, String name, Properties properties, boolean visible, float opacity) throws XPathExpressionException, JTMXParseException { int[] data = new int[width * height]; if (encoding.equals(TileDataEncoding.XML) && compression.equals(TileDataCompression.NONE)) { NodeList tilenodes = (NodeList) xpath.evaluate( "./tile", datanode, XPathConstants.NODESET); if (data.length != tilenodes.getLength()) throw new JTMXParseException("Tile count does not match Map Dimensions!"); for (int i = 0; i < tilenodes.getLength(); i++) { Node tilenode = tilenodes.item(i); long gid = prop2ulong(extractAttributes(tilenode), "gid"); data[i] = (int) gid; } } else { throw new JTMXParseException( "Compressed/Encoded Tile Data is not yet supported", new NotImplementedException()); } return new TileLayer(width, height, name, properties, visible, opacity, data); }
4
public void appendLinkedQuestion(LinkedQuestion question) throws Exception { if (question.options.size() == 0) throw new Exception("Question has no options."); for (String target : question.targets) { LinkedList<AbstractQuestion> playersActiveQuestions = activeQuestions.get(target.toLowerCase()); if (playersActiveQuestions == null) { playersActiveQuestions = new LinkedList<AbstractQuestion>(); activeQuestions.put(target.toLowerCase(), playersActiveQuestions); } playersActiveQuestions.add(question); activeQuestions.put(target.toLowerCase(), playersActiveQuestions); } }
3
static String printGuitarStyles(final Program program) { StringBuilder sb = new StringBuilder(); if (program.isAcoustic()) { sb.append("Acoustic, "); } if (program.isBass()) { sb.append("Bass, "); } if (program.isBlues()) { sb.append("Blues, "); } if (program.isClean()) { sb.append("Clean, "); } if (program.isCountry()) { sb.append("Country, "); } if (program.isJazz()) { sb.append("Jazz, "); } if (program.isRock()) { sb.append("Rock, "); } return trimDelimitedList(sb); }
7
private String getNextLine() throws IOException { if (!this.linesSkiped) { for (int i = 0; i < skipLines; i++) { br.readLine(); } this.linesSkiped = true; } String nextLine = br.readLine(); if (nextLine == null) { hasNext = false; } return hasNext ? nextLine : null; }
4
public static void main(String[] args){ Scanner in = new Scanner(System.in); ArrayList<Double> eachTurn = new ArrayList<Double>(); int num_turn = in.nextInt(); double posSum = 0; double negSum = 0; double result = 0.0; double avg = 0.0; double sum = 0.0; System.out.println(Math.round(0.5)); while(num_turn != 0){ sum = 0; posSum = 0; negSum = 0; result = 0; avg = 0; for (int i = 0; i < num_turn; i++){ eachTurn.add((double)Math.round(in.nextDouble()*100.0) / 100.0) ; } for(Double item : eachTurn) { sum += item; } avg = Math.round(sum / eachTurn.size() * 100) / 100.0; for(Double item : eachTurn) { if(item > avg) { posSum += (item - avg); } else { negSum += (avg - item); } } result = (posSum > negSum) ? negSum: posSum; System.out.printf("$%.2f\n",result); num_turn = in.nextInt(); eachTurn = new ArrayList<Double>(); } }
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Cube other = (Cube) obj; if (identifier == null) { if (other.identifier != null) return false; } else if (!identifier.equals(other.identifier)) return false; return true; }
6
public void getEnvironmentData () { ResultSet rs = Main.mysql.getData("SELECT id, name, description FROM `environments`"); try { while (true) { environmentData.put(rs.getInt(1) + ":name", rs.getString(2)); environmentData.put(rs.getInt(1) + ":desc", rs.getString(3)); //System.out.println("Adding (" + rs.getInt(1) + "): " + rs.getString(2)); //System.out.println("Desc: " + rs.getString(3)); rs.next(); } } catch (SQLException e) { if (!e.toString().contains("After end of result set")) { System.err.println("MySQL Error: " + e.toString()); } } finally { System.out.println("Found " + environmentData.size() / 2 + " environment(s)"); } }
3
public void treeStructureChanged(TreeModelEvent e) { invalidate(); }
0
public void IndexReader(String filename) { // create new file reader FileReader fR; try { // Initialise new file reader and give passed in filename fR = new FileReader(filename); //create and initialise buffered reader BufferedReader bR = new BufferedReader(fR); String indexWord; int count = 0; try { // keep reading in each line, assigning it to word, until equal to null while((indexWord = bR.readLine()) != null) { // create empty linked list LinkedList contextAndLines = new LinkedList(); // add word and linked list to hash table by calling add in IndexHashtable class concordanceHash.add(indexWord, contextAndLines); //increment count count++; } bR.close(); } // handle IO Exception catch (IOException e) { System.out.println("There was an error reading in the file"); } } catch (FileNotFoundException e) { System.out.println("Error, file not found"); } }
3
public ManifestReaderImpl() { try { URLClassLoader cl = (URLClassLoader) getClass().getClassLoader(); URL url = cl.findResource("META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(url.openStream()); Attributes attrs = manifest.getMainAttributes(); version = attrs.getValue("version"); } catch (IOException e) { version = "error"; } }
1
public String getPassword() { return password; }
0
RLOGIndividuals() { this.uri = "http://persistence.uni-leipzig.org/nlp2rdf/ontologies/rlog#" + name(); }
0
public static void chooseBiome(Scanner scan, Character player, Random generator) { System.out.println("Select your biome (enter the number): \n"); Biome[] startBiomes = new Biome[5]; for(int i = 0; i < startBiomes.length; i++) { int selection = generator.nextInt(Arrays.biomes.length); startBiomes[i] = new Biome(selection, player.getLevel()); } int j = 0; for(Biome biome: startBiomes) { System.out.println("Option " + j + ":" + "\nThe biome is a : " + biome.getName() + "\nThe difficulty of the biome is: " + biome.getDifficulty() + "\nThe chances of getting better loot: " + biome.getLoot() + "\n"); j++; } System.out.print("Your Selection: "); int selection = scan.nextInt(); if (selection < startBiomes.length) { player.setBiome(startBiomes[selection]); } else { player.setBiome(startBiomes[0]); } }
3
public static int validInput(int choice, int max, int min) throws IOException { int newChoice = choice; BufferedReader r = new BufferedReader (new InputStreamReader(System.in)); boolean valid = false; while (!valid) { if (newChoice >= min && newChoice <= max) { valid = true; } else { System.out.println("Please enter a valid intput: "); newChoice = Integer.parseInt(r.readLine()); } } return newChoice; }
3
public void generateData(int n, TimeComplexity complexity){ super.generateData(n, complexity); if(isHeap) heap.clear(); else bst.clear(); if(complexity.equals(TimeComplexity.AVERAGE) || (!isHeap &&complexity.equals(TimeComplexity.BEST))) data = Helper.permutedInts(n); else if(complexity.equals(TimeComplexity.WORST)) data = Helper.descendingInts(n); else if(complexity.equals(TimeComplexity.BEST) && isHeap) data = Helper.ascendingInts(n); }
7
public static ListNode removeNthFromEnd(ListNode head, int n) { ListNode slow = head; ListNode fast = head; int x = n; while (x >= 0 && fast != null) { fast = fast.next; x--; } if (fast == null && x > 0) { return head; } if (fast == null && x == 0) { return null; } while (fast != null) { slow = slow.next; fast = fast.next; } slow.next = slow.next.next; return head; }
7
private static Method getMethod(int requireMod, int bannedMod, Class<?> clazz, String methodName, Class<?>... params) { for (Method method : clazz.getDeclaredMethods()) { // Limitation: Doesn't handle overloads if ((method.getModifiers() & requireMod) == requireMod && (method.getModifiers() & bannedMod) == 0 && (methodName == null || method.getName().equals(methodName)) && Arrays.equals(method.getParameterTypes(), params)) { method.setAccessible(true); return method; } } // Search in every superclass if (clazz.getSuperclass() != null) return getMethod(requireMod, bannedMod, clazz.getSuperclass(), methodName, params); throw new IllegalStateException(String.format( "Unable to find method %s (%s).", methodName, Arrays.asList(params))); }
9
@Override @SuppressWarnings("unchecked") public T next() { if (hasNext()) { if (mIterator == null) { Row row = mList.get(mIndex++); if (row.hasChildren()) { mIterator = new RowIterator<>(row.getChildren()); } return (T) row; } return mIterator.next(); } throw new NoSuchElementException(); }
3
public ItemQuery<Item> getItemsInTab(BankTab tab) { final int[] count = getTabCount(); switch (tab) { case ONE: int total = 0; for (Integer i : count) { total += i; } return skip(select(), total); default: int skip = 0; int take = 0; int x = 0; while (x < count.length) { take = count[x]; if (x == tab.getI()) { break; } skip += count[x]; x++; } return skip(select(), skip).limit(take); } }
4
public List<Files> Search_file(String projectName, String fileName, String format) { String query1 = "SELECT distinct e.projID from project e WHERE e.projName='"+projectName+"'"; EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenceUnit"); EntityManager manager = emf.createEntityManager(); EntityTransaction transaction = manager.getTransaction(); TypedQuery<Object> q = manager.createQuery(query1, Object.class); List<Object> result = q.getResultList(); String projectID = ""; for(Object data: result) { projectID = (String)data; } System.out.println(projectID); String query = "SELECT e from project_files e WHERE"; String clause = query.substring(query.lastIndexOf(" ")+1); try{ if(!projectID.isEmpty()) { if(clause.equals("WHERE")){ query += " e.projID = '" + projectID + "'"; } else query += " AND e.projID = '" + projectID + "'"; } if(!fileName.isEmpty()) { clause = query.substring(query.lastIndexOf(" ")+1); if(clause.equals("WHERE")) query += " e.fileName = '" + fileName + "'"; else query += " AND e.fileName = '" + fileName + "'"; } if(!format.isEmpty()) { clause = query.substring(query.lastIndexOf(" ")+1); if(clause.equals("WHERE")) query += " e.format = '" + format + "'"; else query += " AND e.format = '" + format + "'"; } TypedQuery<Files> qp = manager.createQuery(query, Files.class); List<Files> results = qp.getResultList(); System.out.println(result); return results; }catch(Exception e){ System.out.println(e.getMessage()); List<Files> results = null; return results; } }
8
public boolean isFPSStatus() { if(frame == null) buildGUI(); return fpsStatus.isSelected(); }
1
public GameSettings GetSettings() { if (this.GetMode() == null) return null; BufferedImage[] Images = new BufferedImage[2]; try { SneekReader Reader = SneekReader.GetReader(new File(FileHelper.GetDataFolder(), this.GetMode() + this.ModeFileSuffix)); String RawData = null; while ((RawData = Reader.readLine()) != null) { if (RawData.split(":")[0].equals("SneekImage")) Images[0] = ImageHelper.GetImage(FileHelper.GetDataFolder().getAbsolutePath(), RawData.split(":")[1] + this.ImageFileSuffix); if (RawData.split(":")[0].equals("FruitImage")) Images[1] = ImageHelper.GetImage(FileHelper.GetDataFolder().getAbsolutePath(), RawData.split(":")[1] + this.ImageFileSuffix); if (Images[0] != null && Images[1] != null) return new GameSettings(Images[0], Images[1]); } return null; } catch (IOException e) { new SPopup(new SPopupData(e)); return null; } }
7
protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove( new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); // do we need to append the filename? if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); // Copy the content from instream to outstream buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } }
7
private void generateHouse(){ int width=(int)Math.round(Math.random()*30)+20; int height=(int)Math.round(Math.random()*30)+20; this.gMap=new Vertex[height][width]; char[][] generatedHouse = new char[height][width]; for(int y=0; y<height; y++){ for(int x=0; x<width; x++){ if(x==0 || y==0 || x==width-1 || y==height-1){ generatedHouse[y][x]='#'; }else{ if(Math.round(Math.random()*3)==1){ generatedHouse[y][x]='#'; }else{ generatedHouse[y][x]='.'; } if(Math.round(Math.random()*6)==1){ generatedHouse[y][x]='P'; this.pipes.push(x+","+y); } } gMap[y][x]=new Vertex(x+","+y); } } this.house=generatedHouse; }
8
public int openSpot(int x, int y) { if (usrGrid[x][y]) return ansGrid[x][y]; usrGrid[x][y] = true; --numSpacesLeft; theGUI.openSpot(x, y, false); if (ansGrid[x][y] == 9) { openBombs(); if (gameState == 0) gameState = 2; else if (gameState == 1) return 9; else { //System.out.println("YOU LOSE!"); theGUI.endGame(false); } return getBombValue(); } if (ansGrid[x][y] == 0) { openSurrounding(x, y); } if (numSpacesLeft == numBombs){ gameState = 1; openBombs(); if (!openingBombs){ //System.out.println("YOU WIN!"); theGUI.endGame(true); } } return ansGrid[x][y]; }
7
@Override public int getYearsExperience() { return super.getYearsExperience(); }
0
public void setPlayerBust(boolean x){ playerBust=x; }
0
@Override public int compareTo(Point that) { if (this.x == that.x && this.z == that.z) { return 0; } if (this.x == that.x) { if (this.z < that.z) { return -1; } return +1; } if (this.x < that.x) { return -1; } return 1; }
5
public int readRawVarInt() throws IOException { byte tmp = readRawByte(); if (tmp >= 0) { return tmp; } int result = tmp & 0x7f; if ((tmp = readRawByte()) >= 0) { result |= tmp << 7; } else { result |= (tmp & 0x7f) << 7; if ((tmp = readRawByte()) >= 0) { result |= tmp << 14; } else { result |= (tmp & 0x7f) << 14; if ((tmp = readRawByte()) >= 0) { result |= tmp << 21; } else { result |= (tmp & 0x7f) << 21; result |= (tmp = readRawByte()) << 28; if (tmp < 0) { // Discard upper 32 bits. for (int i = 0; i < 5; i++) { if (readRawByte() >= 0) { return result; } } throw new IOException( "ZippyBuffer encountered a malformed varint."); } } } } return result; }
7
@Override public boolean delete(Hotelier x) {Statement stm = null; try { stm = cnx.createStatement(); int n= stm.executeUpdate("DELETE FROM hotelier WHERE id='"+x.getHotelierId()+"'"); if (n>0) { stm.close(); return true; } } catch (SQLException exp) { } finally { if (stm!=null) try { stm.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return false; }
4
public void insertGenesOnPos(List<Bin> genes, int y) { if(y >= this.bins.size()){ y = this.bins.size(); } this.bins.addAll(y, genes); }
1
public PacienteFacade() { super(Paciente.class); }
0
@Override public String toString() { String result = "Concepto: " + this.getConcepto() + ", Importe: " + this.getImporte() + ", Fecha: " + this.getFecha(); return result; }
0
public SQLConnection(){ try { BufferedReader br = new BufferedReader(new FileReader("C:/windows/journal.txt")); String buffer, result3 = null , result2 = null, result1 = null , result4 = null; int i=0; while ((buffer = br.readLine()) != null) { i++; if(i == 1){result1 = buffer;} else if(i == 2){result2 = buffer;} else if(i == 3){result3 = buffer;} else if(i == 4){result4 = buffer;} } urlLocal = result1; username = result2; passSQL = result3; port = result4; } catch(IOException e){ System.out.println("I could not read the file"); } }
6
public static void buyTicketsConnect(User usr) { clearConsole(); if (usr == null) { HomePage(); } else { System.out.println ("*******************************"); System.out.println ("**** Tickets Shop ****"); System.out.println ("*******************************"); System.out.println ("Hi "+usr.getUsername()+" ! Choose an event :"); TicketsFactory ticketsFactory = new TicketsFactory(); System.out.println ("1 - "+ticketsFactory.loadTicketsFrom("1995 posse")); System.out.println ("2 - "+ticketsFactory.loadTicketsFrom("Le splendide")); System.out.println ("3 - back to home page"); System.out.println ("Choice number : "); boolean correctchoice = false; while (!correctchoice) { try { switch (Integer.parseInt(sc.nextLine())) { case 1 : transactionWithTicketsAndUsername(ticketsFactory.loadTicketsFrom("1995 posse"),usr.getUsername()); correctchoice = true; break; case 2 : transactionWithTicketsAndUsername(ticketsFactory.loadTicketsFrom("Le splendide"),usr.getUsername()); correctchoice = true; break; case 3 : correctchoice = true; HomePage(); break; default : throw new Exception(); } } catch (Exception e) { System.out.println ("Incorrect choice"); buyTicketsConnect(usr); } } System.out.println ("back to homepage ? (y/n)"); switch (sc.nextLine()) { case "n": buyTicketsConnect(usr); break; case "y": HomePage(); break; default: HomePage(); break; } } }
8
@Override public void startTransfer() throws TransferException { Runnable r = new Runnable() { public void run() { try { ByteWriter writer = new ByteArrayWriter(); // 最开始执行了一个i请求 writer.write("SIPP".getBytes()); if (!tryExecuteRequest("i", requestId++, writer, 1)) raiseException(new TransferException( "Init Http Transfer failed..")); while (!closeFlag) { writer.clear(); BytesEntry entry = bytesEntryQueue.poll(5, TimeUnit.SECONDS); // 等待五秒,如果没有元素也返回 if (entry != null) { writer.writeBytes(entry.getBytes(), entry.getOffset(), entry.getLength()); // while (bytesEntryQueue.size() > 0) { entry = bytesEntryQueue.poll(); writer.writeBytes(entry.getBytes(), entry.getOffset(), entry.getLength()); } } writer.write("SIPP".getBytes()); // 尝试发送这个请求,如果超过指定次数,传递传输异常 if (!tryExecuteRequest("s", requestId++, writer, 3)) { closeFlag = true; raiseException(new TransferException()); } } // 结束 writer.clear(); writer.write("SIPP".getBytes()); tryExecuteRequest("d", requestId++, writer, 1); } catch (Throwable e) { raiseException(new TransferException(e)); } } }; this.runThead = new Thread(r); this.runThead.setName(this.getTransferName()); this.runThead.start(); }
6
public State[] getNondeterministicStates(Automaton automaton) { LambdaTransitionChecker lc = LambdaCheckerFactory .getLambdaChecker(automaton); ArrayList list = new ArrayList(); /* Get all states in automaton. */ State[] states = automaton.getStates(); /* Check each state for nondeterminism. */ for (int k = 0; k < states.length; k++) { State state = states[k]; /* Get all transitions from each state. */ Transition[] transitions = automaton.getTransitionsFromState(state); for (int i = 0; i < transitions.length; i++) { Transition t1 = transitions[i]; /* if is lambda transition. */ if (lc.isLambdaTransition(t1)) { if (!list.contains(state)) list.add(state); } /* * Check all transitions against all other transitions to see if * any are equal. */ else { for (int p = (i + 1); p < transitions.length; p++) { Transition t2 = transitions[p]; if (areNondeterministic(t1, t2)) { if (!list.contains(state)) list.add(state); } } } } } return (State[]) list.toArray(new State[0]); }
7
@Override public boolean equals(Object edge) { if (edge == null) return false; if (edge == this) return true; if (!(edge instanceof Edge))return false; Edge compared = (Edge)edge; if ((compared.getFrom() == this.getFrom() && compared.getTo() == this.getTo()) ||(compared.getTo() == this.getFrom() && compared.getFrom() == this.getTo())) return true; return false; }
7
public void test(){ }
0
public static String extract(String line, String key) { if (line == null) { return null; } String code = extractCode(line); int i = code.indexOf(key + assign); if (i == -1) //key not found { return null; } int end = code.indexOf(seperator, i); if (end == -1) { end = code.length(); } try { String ret = code.substring(code.indexOf(assign, i) + 1, end); if (ret.length() == 0) { return null; } return ret; } catch (IndexOutOfBoundsException e) { return null; } }
5
public TableSwitchInsnNode( final int min, final int max, final LabelNode dflt, final LabelNode[] labels) { super(Opcodes.TABLESWITCH); this.min = min; this.max = max; this.dflt = dflt; this.labels = new ArrayList(); if (labels != null) { this.labels.addAll(Arrays.asList(labels)); } }
1
public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || this.length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; }
4
public long skip(long size) throws IOException { long skipped = super.skip(size); if (skipped > 0L) { this.monitor.addProgress(skipped); } return skipped; }
1
@Override public void actionPerformed(ActionEvent evt) { if (MainWindow.tripDB.getCheckErrors() + MainWindow.tripDB.getCheckWarnings() > 0) if ( JOptionPane.showConfirmDialog(null, "Die Planung enth\u00E4lt\n " + MainWindow.tripDB.getCheckErrors() + " Fehler und\n " + MainWindow.tripDB.getCheckWarnings() + " Warnungen.\n" + "Soll der Ausdruck wirklich erfolgen?", "Die Planung enth\u00E4lt Fehler!", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION ) { return; } if (evt.getActionCommand().equals("PreviewTrips")) { formSheet = new ImageIcon (MainWindow.setupData.getFormFileName(), "Fahrtenzettel"); if (formSheet.getImageLoadStatus() != MediaTracker.COMPLETE) { JOptionPane.showMessageDialog(null, "Die Formularvorlage "+ MainWindow.setupData.getFormFileName() +" wurde nicht gefunden.", "Dateifehler", JOptionPane.OK_OPTION); } PrintPanel previewPanel = new PrintPanel (formSheet, targetDay.getTime()); // PreviewFrame preview = new PreviewFrame ((Frame) SwingUtilities.getRoot(this), testLabel.getPrintable(new MessageFormat("Capitals"), new MessageFormat("{0}")), printerJob.getPageFormat(printAttributes)); PageFormat pf = printerJob.getPageFormat(printAttributes); Paper p = pf.getPaper(); p.setImageableArea(0, 0, p.getWidth(), p.getHeight()); pf.setPaper(p); new TripsPreviewFrame ((Frame) SwingUtilities.getRoot(this), previewPanel, pf, true); } if (evt.getActionCommand().equals("PreviewSummary")) { PrintPanelSummary previewPanel = new PrintPanelSummary (targetDay.getTime()); PageFormat pf = printerJob.getPageFormat(printAttributes); Paper p = pf.getPaper(); p.setImageableArea(0, 0, p.getWidth(), p.getHeight()); pf.setPaper(p); new TripsPreviewFrame ((Frame) SwingUtilities.getRoot(this), previewPanel, pf, false); } }
5
private void spawnRandom(){ Random random = new Random(); boolean notValid = true; while(notValid){ int location = random.nextInt(ROWS * COLS); int row = location / ROWS; int col = location % COLS; Tile current = board[row][col]; if(current == null){ int value = random.nextInt(10) < 9 ? 16 : 32; Tile tile = new Tile(value, getTileX(col), getTileY(row)); board[row][col] = tile; notValid = false; } } }
3
@Override public String execute(SessionRequestContent request) throws ServletLogicException { String page = ConfigurationManager.getProperty("path.page.orders"); String prevPage = (String) request.getSessionAttribute(JSP_PAGE); resaveParamsShowOrder(request); formOrderList(request); if (page == null ? prevPage != null : ! page.equals(prevPage)) { request.setSessionAttribute(JSP_PAGE, page); cleanSessionShowOrder(request); } return page; }
2
public static int solution(int[] A) { int len = A.length; if (len <= 0) { return -1; } int leader = A[0]; int counter = 0; /* Find the Leader */ for (int i = 0; i < len; i++) { if (A[i] == leader) { counter++; } else { if (counter == 0) { leader = A[i]; counter++; } else { counter--; } } } /* * Check that the value of the leader occurs more than half of values in the array */ counter = 0; int lastIndex = -1; for (int i = 0; i < len; i++) { if (A[i] == leader) { counter++; lastIndex = i; } } if (counter <= len / 2) { return -1; } return lastIndex; }
7
public int getAge() { return Age; }
0
public void run() { try { String line; while (!isInterrupted()) { line = in.readLine(); if (line != null) get(line); else close(); } } catch (IOException exc) { close(); } }
3
private HBox getCustomButtons(String[] buttonLabels, T[] buttonValues, boolean addCancelButton) { if (buttonLabels == null || buttonValues == null) throw new NullPointerException("null argument"); if (buttonLabels.length != buttonValues.length) throw new IllegalArgumentException("different length"); HBox box = getButtonsHBox(); for (int i = 0; i < buttonLabels.length; i++) { String label = buttonLabels[i]; final T buttonResult = buttonValues[i]; Button button = new Button(label); button.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { result = Result.OK; customResult = buttonResult; requestClose(); } }); box.getChildren().add(button); } if (addCancelButton) { box.getChildren().add(getCancelButton()); } return box; }
5
public void recusarTema(List<Tema> listaTemas, int temaEscolhido) { Tema escolhido = null; if (listaTemas != null) { for (int i = 0; i < listaTemas.size(); i++) { if (i == temaEscolhido - 1) { escolhido = listaTemas.get(i); break; } } SESSAO.delete(escolhido); carregarDados(listaTemas);//Carrega os temas para que não ocorra um erro } }
3
public void setOptions(String[] options) throws Exception { String tmpStr; setRawOutput(Utils.getFlag('D', options)); setRandomizeData(!Utils.getFlag('R', options)); tmpStr = Utils.getOption('O', options); if (tmpStr.length() != 0) setOutputFile(new File(tmpStr)); tmpStr = Utils.getOption("dir", options); if (tmpStr.length() > 0) setTestsetDir(new File(tmpStr)); else setTestsetDir(new File(System.getProperty("user.dir"))); tmpStr = Utils.getOption("prefix", options); if (tmpStr.length() > 0) setTestsetPrefix(tmpStr); else setTestsetPrefix(""); tmpStr = Utils.getOption("suffix", options); if (tmpStr.length() > 0) setTestsetSuffix(tmpStr); else setTestsetSuffix(DEFAULT_SUFFIX); tmpStr = Utils.getOption("find", options); if (tmpStr.length() > 0) setRelationFind(tmpStr); else setRelationFind(""); tmpStr = Utils.getOption("replace", options); if ((tmpStr.length() > 0) && (getRelationFind().length() > 0)) setRelationReplace(tmpStr); else setRelationReplace(""); tmpStr = Utils.getOption('W', options); if (tmpStr.length() == 0) throw new Exception("A SplitEvaluator must be specified with the -W option."); // Do it first without options, so if an exception is thrown during // the option setting, listOptions will contain options for the actual // SE. setSplitEvaluator((SplitEvaluator)Utils.forName(SplitEvaluator.class, tmpStr, null)); if (getSplitEvaluator() instanceof OptionHandler) ((OptionHandler) getSplitEvaluator()).setOptions(Utils.partitionOptions(options)); }
9
protected static Nodo buscarPrivate(Nodo raiz, int dato) { if(raiz == null) return null; else if(raiz.getDato() == dato) return raiz; else if(raiz.getOpt1() != null) return Arbol.buscarPrivate(raiz.getOpt1(), dato); else if(raiz.getOpt2() != null) return Arbol.buscarPrivate(raiz.getOpt2(), dato); else if(raiz.getOpt3() != null) return Arbol.buscarPrivate(raiz.getOpt3(), dato); else if(raiz.getOpt4() != null) return Arbol.buscarPrivate(raiz.getOpt4(), dato); return null; }
6
public boolean equals(Object ob) { if ( !(ob instanceof PointerBuffer) ) return false; PointerBuffer that = (PointerBuffer)ob; if ( this.remaining() != that.remaining() ) return false; int p = this.position(); for ( int i = this.limit() - 1, j = that.limit() - 1; i >= p; i--, j-- ) { long v1 = this.get(i); long v2 = that.get(j); if ( v1 != v2 ) { return false; } } return true; }
4
public synchronized void receive(File file, boolean resume) { if (!_received) { _received = true; _file = file; if (_type.equals("SEND") && resume) { _progress = file.length(); if (_progress == 0) { doReceive(file, false); } else { _bot.sendCTCPCommand(_nick, "DCC RESUME file.ext " + _port + " " + _progress); _manager.addAwaitingResume(this); } } else { _progress = file.length(); doReceive(file, resume); } } }
4
public static void packMessage(String message, Stream buffer) { // method526 if (message.length() > 80) { message = message.substring(0, 80); } message = message.toLowerCase(); int tmp = -1; for (int i = 0; i < message.length(); i++) { char c = message.charAt(i); int k = 0; for (int j = 0; j < PlayerInput.VALID_CHARACTERS.length; j++) { if (c != PlayerInput.VALID_CHARACTERS[j]) { continue; } k = j; break; } if (k > 12) { k += 195; } if (tmp == -1) { if (k < 13) { tmp = k; } else { buffer.writeByte(k); } } else if (k < 13) { buffer.writeByte((tmp << 4) + k); tmp = -1; } else { buffer.writeByte((tmp << 4) + (k >> 4)); tmp = k & 0xf; } } if (tmp != -1) { buffer.writeByte(tmp << 4); } }
9
public void determineBounds() { double value,min,max; // find maximums minimums over all plots m_minX = ((PlotData2D)m_plots.elementAt(0)).m_minX; m_maxX = ((PlotData2D)m_plots.elementAt(0)).m_maxX; m_minY = ((PlotData2D)m_plots.elementAt(0)).m_minY; m_maxY = ((PlotData2D)m_plots.elementAt(0)).m_maxY; m_minC = ((PlotData2D)m_plots.elementAt(0)).m_minC; m_maxC = ((PlotData2D)m_plots.elementAt(0)).m_maxC; for (int i=1;i<m_plots.size();i++) { value = ((PlotData2D)m_plots.elementAt(i)).m_minX; if (value < m_minX) { m_minX = value; } value = ((PlotData2D)m_plots.elementAt(i)).m_maxX; if (value > m_maxX) { m_maxX = value; } value = ((PlotData2D)m_plots.elementAt(i)).m_minY; if (value < m_minY) { m_minY= value; } value = ((PlotData2D)m_plots.elementAt(i)).m_maxY; if (value > m_maxY) { m_maxY = value; } value = ((PlotData2D)m_plots.elementAt(i)).m_minC; if (value < m_minC) { m_minC = value; } value = ((PlotData2D)m_plots.elementAt(i)).m_maxC; if (value > m_maxC) { m_maxC = value; } } fillLookup(); this.repaint(); }
7
public String getName(){ return name; }
0
static void addTest() { int numBlocks = 100; int[] x = new int[numBlocks]; int[] y = new int[numBlocks]; int[] z = new int[numBlocks]; Set<String> s = new TreeSet<String>(); BlockWorld world = new BlockWorldImpl(); Random r = new Random(1); log.info("Adding blocks"); for (int i = 0; i < numBlocks; i++) { x[i] = r.nextInt(100); y[i] = r.nextInt(100); z[i] = r.nextInt(100); String id = BlockWorldImpl.toString(x[i], y[i], z[i]); s.add(id); try { world.add(new Block(0, x[i], y[i], z[i])); } catch (IllegalArgumentException e) { continue; } } log.info("Checking all valid blocks"); for (int i = 0; i < numBlocks; i++) { // try the block itself. Block b = world.at(x[i], y[i], z[i]); if (b == null) throw new RuntimeException("Was expecting to find a block at " + BlockWorldImpl.toString(x[i], y[i], z[i])); } log.info("Checking a few INvalid blocks"); for(int i = 0; i < 20; ){ x[i] = r.nextInt(100); y[i] = r.nextInt(100); z[i] = r.nextInt(100); String id = BlockWorldImpl.toString(x[i], y[i], z[i]); if (s.contains(id)) continue; Block b = world.at(x[i], y[i], z[i]); if (b != null) { throw new RuntimeException("Expected to NOT find block at " + id + " but I did!"); } i++; } log.info("Success"); }
7
public int eliminarUsuario(String code){ int condicion = 0; tablaDeUsuarios(); for(int i = 0; i < data.size();i++){ String valorEliminar = data.get(i).getCode(); if(valorEliminar.equals(code)){ System.out.println("El registro " + "'" + data.get(i).getName() + "'" + " ha sido eliminado satisfactoriamente"); condicion = 1; data.remove(i); } } if(condicion == 0){ System.out.println("El usuario con código: " + "'" + code + "'" + " no ha sido eliminado"); } return condicion; }
3
public static void main(String[] args) throws IOException { //read in data for different kinds of classes BufferedReader citizenReader = new BufferedReader(new FileReader("citizen.txt")); //BufferedReader resourceReader = new BufferedReader(new FileReader("resourcepool.txt")); BufferedReader govtReader = new BufferedReader(new FileReader("govt.txt")); PrintStream p = new PrintStream(new FileOutputStream("results.txt")); //include resourcepool and govt # in output PrintStream goutput = new PrintStream(new FileOutputStream("govtracker.txt")); //track wealth over time PrintStream coutput = new PrintStream(new FileOutputStream("cittracker.txt")); //ditto //Create population int n = Integer.parseInt(citizenReader.readLine()); Citizen[] people = new Citizen[n]; for(int i = 0; i<people.length;i++) { int x = 0; double[] d = new double[5]; StringTokenizer st = new StringTokenizer(citizenReader.readLine()); while (st.hasMoreTokens()) { String s = st.nextToken(); d[x] = Double.parseDouble(s); x++; } people[i] = new Citizen(d[0], d[1], d[2], d[3], d[4]); } citizenReader.close(); //for now just read one Government, later use more for multiple tests n = Integer.parseInt(govtReader.readLine()); Government[] govts = new Government[n]; for(int y = 0; y<govts.length;y++) { int x = 0; double[] d = new double[10]; StringTokenizer st = new StringTokenizer(govtReader.readLine()); while (st.hasMoreTokens()) { String s = st.nextToken(); d[x] = Double.parseDouble(s); x++; } govts[y] = new Government(d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], d[8]); } govtReader.close(); population = people; iterate(MONTHS, govts,people, p, goutput, coutput); }
4
public void toggleVisibility() { if (isShowing()) { pop(); } else { push(defaultMenu); } }
1
@Test /** * Test if the Queue remains consistent after a deletion */ public void testQueueConsistencyOnDeletion() { //Add elements Memory.put("car1", "ferrari"); Memory.put("car2", "toyota"); Memory.put("car3", "honda"); //Get the first version of the queue LinkedList<Node> list1 = (LinkedList<Node>)Queue.getElements(); //Create a backup listo to compare LinkedList<String> backupList = new LinkedList<String>(); for (Node node2 : list1) { backupList.add(node2.getKey()); } //Delete the element Memory.delete("car1"); //Get the new list of elements LinkedList<Node> list2 = (LinkedList<Node>)Queue.getElements(); //Create the second backup queue LinkedList<String> backupList2 = new LinkedList<String>(); for (Node node2 : list2) { backupList2.add(node2.getKey()); } //Check the queue sizes if ((backupList.size()-backupList2.size())!=1) fail("Incorrect sizes: "+backupList2.size()+", "+backupList.size()); //Remove the previous removed element from the first queue backupList.remove("car1"); //Compare the queue elements for (int i = 0;i<backupList.size();i++) { if (!(backupList.get(i).equals(backupList2.get(i)))) fail("Different Elements"); } }
5
private static void stringSim(String str) { int totalCount = str.length(); for (int i = 1; i < str.length(); i++) { if (kmpSearch(str, str.substring(i))) { System.out.println(str.substring(i)); totalCount += str.substring(i).length(); } } System.out.println(totalCount); }
2
List<IntKeyValuePair> getKeyValuePairs() { List<IntKeyValuePair> kvpList = new ArrayList<IntKeyValuePair>(); iter = bucket.iterator(); while(iter.hasNext()) { kvpList.add(iter.next()); } return kvpList; }
1
public void create(InfoPaciente infoPaciente) { if (infoPaciente.getPypAdmAgendList() == null) { infoPaciente.setPypAdmAgendList(new ArrayList<PypAdmAgend>()); } EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); InfoEntidades contratante = infoPaciente.getContratante(); if (contratante != null) { contratante = em.getReference(contratante.getClass(), contratante.getId()); infoPaciente.setContratante(contratante); } List<PypAdmAgend> attachedPypAdmAgendList = new ArrayList<PypAdmAgend>(); for (PypAdmAgend pypAdmAgendListPypAdmAgendToAttach : infoPaciente.getPypAdmAgendList()) { pypAdmAgendListPypAdmAgendToAttach = em.getReference(pypAdmAgendListPypAdmAgendToAttach.getClass(), pypAdmAgendListPypAdmAgendToAttach.getId()); attachedPypAdmAgendList.add(pypAdmAgendListPypAdmAgendToAttach); } infoPaciente.setPypAdmAgendList(attachedPypAdmAgendList); em.persist(infoPaciente); if (contratante != null) { contratante.getInfoPacienteList().add(infoPaciente); contratante = em.merge(contratante); } for (PypAdmAgend pypAdmAgendListPypAdmAgend : infoPaciente.getPypAdmAgendList()) { InfoPaciente oldIdPacienteOfPypAdmAgendListPypAdmAgend = pypAdmAgendListPypAdmAgend.getIdPaciente(); pypAdmAgendListPypAdmAgend.setIdPaciente(infoPaciente); pypAdmAgendListPypAdmAgend = em.merge(pypAdmAgendListPypAdmAgend); if (oldIdPacienteOfPypAdmAgendListPypAdmAgend != null) { oldIdPacienteOfPypAdmAgendListPypAdmAgend.getPypAdmAgendList().remove(pypAdmAgendListPypAdmAgend); oldIdPacienteOfPypAdmAgendListPypAdmAgend = em.merge(oldIdPacienteOfPypAdmAgendListPypAdmAgend); } } em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
7
private synchronized void sendOutboundData() { mOutboundData.flip(); int limit = mOutboundData.limit(); if (limit > 0) { ByteBuffer buffer = ByteBuffer.allocate(limit); buffer.put(mOutboundData); buffer.flip(); mSession.getServer().send(mSession.getChannel(), buffer); } mOutboundData.clear(); }
1
private void asignarEtiquetas() { _columnas.actualizarPregunta("<html>"+_preguntas.get(_posicion).getPregunta()+"</html>"); for (int i = 0; i < _columnaBRevuelta.size(); i++) { _columnas.asignarColumnaLetrasB("<html>"+_columnaBRevuelta.get(i).getRespuesta()+"</html>", i); _columnas.asignarColumnaLetrasA(_columnaAActual.get(i).getRespuesta(), i); } _columnas.limpiarCampos(); for (int i = 0; i < _respuestaUsuario.get(_posicion).size(); i++) { for (int j = 0; j < _columnaBRevuelta.size(); j++) { if (_respuestaUsuario.get(_posicion).get(i) == _columnaBRevuelta.get(j).getRespuesta()) { _columnas.asignarRespuestas(String.valueOf(i + 1), j); } } } }
4
@SuppressWarnings("deprecation") public void crear(){ if (tFnombre_usuario.getText().isEmpty() || passwordField.getText().isEmpty() || tFemail.getText().isEmpty()){ JOptionPane.showMessageDialog(contentPane,"Algunos campos estan vacios.","Advertencia",JOptionPane.INFORMATION_MESSAGE); }else{ if (chequearContrasenia()){ if (medidador.nuevoUsuario(tFnombre_usuario.getText(), passwordField.getText(), tFemail.getText(),comboBox.getSelectedItem().toString())){ JOptionPane.showMessageDialog(contentPane,"Usuario Agregado.","Notificacion",JOptionPane.INFORMATION_MESSAGE); medidador.actualizarDatosGestion(); dispose(); }else{ JOptionPane.showMessageDialog(contentPane,"Error al agregar. Inente nuevamente.","Error",JOptionPane.ERROR_MESSAGE); } }else{ JOptionPane.showMessageDialog(contentPane,"Las contrase�as no coinciden.","Error",JOptionPane.ERROR_MESSAGE); } } }
5
public Image getImageFor(FieldType fieldType) { switch (Core.TILESIZE) { case 8 : return images8.get(fieldType.name()); case 16 : return images16.get(fieldType.name()); case 24 : return images24.get(fieldType.name()); case 32 : return images32.get(fieldType.name()); } return null; }
4
private void field_cta_nroFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_field_cta_nroFocusLost if (lab_modo.getText().equals("Baja") || (lab_modo.getText().equals("Modificación"))){ if (!field_cta_nro.getText().equals("")){ if(existeCta(Integer.parseInt(field_cta_nro.getText()))){ ocultar_Msj(); cargar_ValoresPorCta(Integer.parseInt(field_cta_nro.getText())); if ((lab_modo.getText().equals("Baja"))){ btn_aceptar.requestFocus(); } } else{ mostrar_Msj_Error("Ingrese una cuenta que se encuentre registrada en el sistema"); field_cta_nro.requestFocus(); } } else{ mostrar_Msj_Error("El numero de cuenta no puede ser vacio"); field_cta_nro.requestFocus(); } } }//GEN-LAST:event_field_cta_nroFocusLost
5
public void testDivisionAndAddition() throws NumberFormatException, MalformedParenthesisException, MalformedDecimalException, InvalidOperandException, MalformedTokenException { List<String> basicStrings = new ArrayList<String>(); basicStrings.add("6.0/3.0 + 1"); basicStrings.add("6.0/3 + 1"); basicStrings.add("6/3.0 + 1"); basicStrings.add("6.000000/3.00000 + 1"); basicStrings.add("6/3 + 1"); for (String basicString : basicStrings) { final List<Token> expectedList = new LinkedList<Token>(); expectedList.add(new Token(Double.valueOf("3"))); List<Token> listUnderTest = Expression.tokenizeImpl(basicString); Expression.performDivisionSubstitution(listUnderTest); Token.equateTokenList(listUnderTest, expectedList); } }
1
@Override public void run() { this.setVisible(true); if (this.GamePanel.getBackground() != this.BackgroundColor) { this.GamePanel.setBackground(this.BackgroundColor); try { Thread.sleep(500L); } catch (InterruptedException e) { new SPopup(new SPopupData(e)); } } while (this.GetGameState()) { try { Thread.sleep(80L); } catch (InterruptedException e) { new SPopup(new SPopupData(e)); } if (this.Direction != GameDirection.PAUSE && this.GameStarted && !this.GameStopped && !(this instanceof MultiSneek)) this.AddScore(); this.setTitle(this.WindowTitle + " - Score: " + this.GameScoreFinal); this.GamePanel.repaint(); } }
8
public static void supprimerReponse(Reponse reponse, Utilisateur utilisateur) { if (!reponse.peutSupprimer(utilisateur)) throw new InterditException("Vous n'avez pas les droits requis pour modifier cette réponse"); if (reponse.getSujet().getReponsePrincipale().equals(reponse)) { supprimerSujet(reponse.getSujet(), utilisateur); return; } EntityTransaction transaction = SujetRepo.get().transaction(); try { transaction.begin(); ReponseRepo.get().supprimer(reponse); transaction.commit(); } catch (Exception e) { if (transaction.isActive()) transaction.rollback(); throw e; } }
4
public String toString() { return "piece" + (this.valid ? "" : "!") + "#" + this.index; }
1
private void stopThreads() { updateEntities.stop(); hitBoxManager.disableCollisions(); for(int i=0; i<invader1.getEntityCount(); i++) {invader1.stopAnimation();} for(int i=0; i<invader2.getEntityCount(); i++) {invader2.stopAnimation();} for(int i=0; i<invader3.getEntityCount(); i++) {invader3.stopAnimation();} //entInvader4 .stopAnimation(); //entPlayer .stopAnimation(); //entBarricade .stopAnimation(); //entProjectile1.stopAnimation(); //entProjectile2.stopAnimation(); //entProjectile3.stopAnimation(); //entExplsoion .stopAnimation(); }
3
@Override public Class<?> getColumnClass(int columnIndex) { Class<?> clazz; switch (columnIndex) { case 0: case 3: case 4: clazz = Integer.class; break; case 1: case 2: clazz = String.class; break; default: throw new IndexOutOfBoundsException("Column index out of bounds: " + columnIndex); } return clazz; }
7
public static void tagger(String devDataFile, String countFile, String trainDataFile) throws IOException { HashMap<String, Integer> wordToCount = HMMHelpers.rareWordMarker( "ner_0.counts", trainDataFile); HashMap<String, TreeMap<Double, String>> emissionParams = HMMHelpers .eParamsCalculator(countFile); FileReader in = new FileReader(devDataFile); BufferedReader br = new BufferedReader(in); File rareCounts = new File("dev_results.dat"); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter( rareCounts)); String input; double logP; String maxTag; while ((input = br.readLine()) != null) { if (input.length() > 0) { if (wordToCount.containsKey(input)) { if (wordToCount.get(input).intValue() < 5) { logP = Math.log(emissionParams.get("_RARE_").lastKey() .doubleValue()) / Math.log(2); maxTag = emissionParams.get("_RARE_").lastEntry() .getValue(); } else { logP = Math.log(emissionParams.get(input).lastKey() .doubleValue()) / Math.log(2); maxTag = emissionParams.get(input).lastEntry() .getValue(); } } else { logP = Math.log(emissionParams.get("_RARE_").lastKey() .doubleValue()) / Math.log(2); maxTag = emissionParams.get("_RARE_").lastEntry() .getValue(); } bufferedWriter.write(input + " " + maxTag + " " + logP + "\n"); } else { bufferedWriter.write("\n"); } } bufferedWriter.close(); }
4
public static Cons yieldStructSlotTrees(Stella_Class renamed_Class) { { Cons structslotdefs = Stella.NIL; { StorageSlot slot = null; Cons iter000 = Stella_Class.clStructSlots(renamed_Class).theConsList; Cons collect000 = null; loop000 : for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { slot = ((StorageSlot)(iter000.value)); if (!(Slot.nativeSlotHome(slot, renamed_Class) == renamed_Class)) { if ((slot.slotBaseType != null) && (!(((Stella_Class)(slot.slotBaseType.surrogateValue)) != null))) { { Stella.STANDARD_WARNING.nativeStream.println("Warning: Can't generate a native slot named `" + slot.slotName + "' for the class `" + Stella_Class.className(renamed_Class) + "'"); Stella.STANDARD_WARNING.nativeStream.println(" because the slot's :type `" + slot.slotBaseType + "' is undefined."); } ; } continue loop000; } if (collect000 == null) { { collect000 = Cons.cons(StorageSlot.yieldStructSlotTree(slot), Stella.NIL); if (structslotdefs == Stella.NIL) { structslotdefs = collect000; } else { Cons.addConsToEndOfConsList(structslotdefs, collect000); } } } else { { collect000.rest = Cons.cons(StorageSlot.yieldStructSlotTree(slot), Stella.NIL); collect000 = collect000.rest; } } } } return (structslotdefs); } }
6
public UUID getId() { return this._id; }
0
public static void main(String[] args){ long result = 0; for(int i=1;i<=1000;i++){ result = (result+selfP(i))%(10000000000L); } System.out.println(result); }
1
private WebDriver getLocalDefaultWebDriver() { return registerLocalWebDrivers.getDefaultWebDriver(); }
0
private void collectUniversityChanges(CourseModel courseModel, ArrayList<Change> changes) { // TODO: is there some API to get university descriptions? They do have // numeric codes in facets. for (String u : universities) { String code = makeIdSafe(u); if (courseModel.getUniversity(Source.EDX, code) == null) changes.add(DescChange.add(DescChange.UNIVERSITY, Source.EDX, code, u, null)); } HashSet<String> newIds = new HashSet<String>(); for (String s : this.universities) newIds.add(makeIdSafe(s)); for (DescRec rec : courseModel.getUniversities(Source.EDX)) { if (!newIds.contains(rec.getId())) { changes.add(DescChange.delete(DescChange.UNIVERSITY, rec)); } else { // TODO Once we get description for universities, diff them. } newIds.remove(rec.getId()); } }
5
public static void main(String[] args) throws IOException { Settings settings = new Settings(); try { JCommander JC = new JCommander(settings, args); } catch (Exception E) { System.err.println("\n" + E.getMessage()); Usage.printUsage(); System.exit(-1); } SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.println( "\n" + ft.format(new Date()) ); /*** * Load all the recombination rate file into map */ Map<String, List<GeneticMarker>> geneticMarkerMap = new HashMap<String, List<GeneticMarker>>(); geneticMarkerMap = Data.LoadLoadGeneticMap(settings.hapMapFolder); /*** * Read query file */ BufferedReader br = new BufferedReader( new FileReader(settings.queryRegionFile)); String sLine; BufferedWriter bw = new BufferedWriter( new FileWriter(settings.outPutFile)); /*** * Process each line */ while( ( sLine = br.readLine())!= null ) { String[] chunks = sLine.split("\t"); if( chunks.length < 3 || ! geneticMarkerMap.containsKey(chunks[0])) { bw.write( sLine + "\t" + "\n"); continue; } String chr = chunks[0]; int start = Integer.parseInt(chunks[1]); int end = Integer.parseInt(chunks[2]); //List<GeneticMarker> geneticMarkerList = geneticMarkerMap.get( chr ); //System.out.println(sLine + "\t" + geneticMarkerList.size()); GeneticMarker queryMarker = new GeneticMarker(chr, start,end,0,0); float rvalue = MyUtils.QueryRecombinationRate(queryMarker, geneticMarkerMap.get(chr)); bw.write( sLine + "\t" + rvalue + "\n"); } br.close(); bw.close(); }
4
private static ObjectType parseObjectType(String sig, Cursor c, boolean dontThrow) throws BadBytecode { int i; int begin = c.position; switch (sig.charAt(begin)) { case 'L' : return parseClassType2(sig, c, null); case 'T' : i = c.indexOf(sig, ';'); return new TypeVariable(sig, begin + 1, i); case '[' : return parseArray(sig, c); default : if (dontThrow) return null; else throw error(sig); } }
4