method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
81dea93e-09f7-487d-a33b-296bbc4fbd83
1
public AdminClient() { this.getContentPane().setPreferredSize(new Dimension(width, height)); this.setBackground(Color.BLACK); if(System.getProperty("os.name").startsWith("Mac")) { System.setProperty("apple.laf.useScreenMenuBar", "true"); acceleratorKey = ActionEvent.META_MASK; } else { acceleratorKey = ActionEvent.CTRL_MASK; } //Window's menu bar. JMenuBar menubar = new JMenuBar(); JMenu file = new JMenu("File"); JMenu server = new JMenu("Server"); serverLocator = new JMenuItem("Switch Server"); closeWindow = new JMenuItem("Close Window"); signout = new JMenuItem("Sign Out"); signout.setEnabled(false); file.add(closeWindow); server.add(serverLocator); server.add(signout); menubar.add(file); menubar.add(server); this.setJMenuBar(menubar); signout.setMnemonic(KeyEvent.VK_E); signout.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_E, acceleratorKey)); signout.addActionListener(this); serverLocator.setMnemonic(KeyEvent.VK_S); serverLocator.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_S, acceleratorKey)); closeWindow.setMnemonic(KeyEvent.VK_W); closeWindow.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_W, acceleratorKey)); serverLocator.addActionListener(this); closeWindow.addActionListener(this); //Window's components. this.add(new Authentication(this), 0); //Window's Properties. this.pack(); this.setLocation(deviceWidth/2 - width/2, deviceHeight/2 - height/2); this.setVisible(true); this.setResizable(false); this.setDefaultCloseOperation(EXIT_ON_CLOSE); }
051aab19-b357-4b6a-97cc-51a64ca0e02a
3
protected boolean isImageFlavor(DataFlavor flavor) { int nFlavors = (imageFlavors != null) ? imageFlavors.length : 0; for (int i = 0; i < nFlavors; i++) { if (imageFlavors[i].equals(flavor)) { return true; } } return false; }
baf80289-af26-4ce8-8f6c-29183c9db524
6
public void getInput() { if (Keyboard.isKeyDown(Keyboard.KEY_W) || Keyboard.isKeyDown(Keyboard.KEY_UP)) { if (player.yPos < ((Display.getHeight() - topWall.getSizeY()) - player.sizeY)) player.move(1); } else if (Keyboard.isKeyDown(Keyboard.KEY_S) || Keyboard.isKeyDown(Keyboard.KEY_DOWN)) { if (player.yPos > bottomWall.getSizeY()) player.move(-1); } }
08adab29-c968-4a31-9386-efe5a1cb8407
3
@Test public void getMaxDiagonal2Product() { String expected = "[0, 0][1, 1] [0, 1][1, 2] [1, 0][2, 1] [1, 1][2, 2] "; int numbers = 2; String actual = ""; for (int x = 0; x + numbers <= DATA.length; x++) { for (int y = 0; y + numbers <= DATA.length; y++) { for (int offset = 0; offset < numbers; offset++) { actual += ("[" + (x + offset) + ", " + (y + offset) + "]"); } actual += " "; } } assertThat(actual).isEqualTo(expected); }
c8371e74-6b2e-4fba-82c4-3c254bf0d06b
9
public void close () { Connection[] connections = this.connections; if (INFO && connections.length > 0) info("kryonet", "Closing server connections..."); for (int i = 0, n = connections.length; i < n; i++) connections[i].close(); connections = new Connection[0]; ServerSocketChannel serverChannel = this.serverChannel; if (serverChannel != null) { try { serverChannel.close(); if (INFO) info("kryonet", "Server closed."); } catch (IOException ex) { if (DEBUG) debug("kryonet", "Unable to close server.", ex); } this.serverChannel = null; } UdpConnection udp = this.udp; if (udp != null) { udp.close(); this.udp = null; } // Select one last time to complete closing the socket. synchronized (updateLock) { selector.wakeup(); try { selector.selectNow(); } catch (IOException ignored) { } } }
649d4897-4a97-428b-bd7f-da662c674b27
2
private ArrayList<Integer> factor(long n) { ArrayList<Integer> ret = new ArrayList<>(); int i = 0; while (n > 1) { int prime = nthPrime(i); while (n % prime == 0) { ret.add(prime); n /= prime; } ++i; } return ret; }
dd729559-190b-4c85-81f5-eafdb8f24994
1
public void keyPressed(KeyEvent e) { if (e.getKeyCode() == 10) { setVisible(false); } }
adf4869a-d7d3-4463-960a-6e9a8dac1f7b
3
public void deleteElement(int value) { ListElement current = head.next; ListElement previous = head; if (previous.value == value) { head = head.next; count--; } else { while (current != tail.next) { if (current.value == value) { ListElement help = current.next; previous.next = help; previous = help; current = help.next; count--; } else { previous = current; current = current.next; } } } }
42e5114b-639f-467d-a1ea-20b1cdfb37c2
9
public void move(Room r, int deltaTime) { if (tl.isLocked() == false) { randomizeDirection(); } switch (getDirection()) { case LEFT: if (moveX(-1, r, false, deltaTime) == -1) { randomizeDirection(); } break; case RIGHT: if (moveX(1, r, true, deltaTime) == -1) { randomizeDirection(); } break; case UP: if (moveY(-1, r, false, deltaTime) == -1) { randomizeDirection(); } break; case DOWN: if (moveY(1, r, true, deltaTime) == -1) { randomizeDirection(); } break; default: setDirection(AnimationManager.directions.LEFT); } }
60f502f7-e18a-4d80-9814-bb0475e61d9c
8
public static void dcopy_f77 (int n, double dx[], int incx, double dy[], int incy) { double dtemp; int i,ix,iy,m; if (n <= 0) return; if ((incx == 1) && (incy == 1)) { // both increments equal to 1 m = n%7; for (i = 1; i <= m; i++) { dy[i] = dx[i]; } for (i = m+1; i <= n; i += 7) { dy[i] = dx[i]; dy[i+1] = dx[i+1]; dy[i+2] = dx[i+2]; dy[i+3] = dx[i+3]; dy[i+4] = dx[i+4]; dy[i+5] = dx[i+5]; dy[i+6] = dx[i+6]; } return; } else { // at least one increment not equal to 1 ix = 1; iy = 1; if (incx < 0) ix = (-n+1)*incx + 1; if (incy < 0) iy = (-n+1)*incy + 1; for (i = 1; i <= n; i++) { dy[iy] = dx[ix]; ix += incx; iy += incy; } return; } }
b0a043fc-7128-465a-b498-565ecb45e42b
7
public boolean isImpassable(Position position, double radius) { double step = 0.1 * radius; //scale = meter per pixel => row&column = pixels double startRow = (position.getY() - radius); double startColumn = (position.getX() - radius); double endRow = (position.getY() + radius); double endColumn = (position.getX() + radius); for (double row = Math.max(startRow, 0); Math.floor(row) <= Math.floor(endRow) && Math.floor(row/this.getScale()) < passableMap.length; row += step) { for (double column = Math.max(startColumn, 0); Math.floor(column) <= Math.floor(endColumn) && Math.floor(column/this.getScale()) < passableMap[0].length; column += step) { if (!passableMap[(int) Math.floor(row/this.getScale())][(int) Math.floor(column/this.getScale())]) { if(Util.fuzzyLessThanOrEqualTo(Math.pow(row - position.getY(), 2) + Math.pow(column - position.getX(), 2), Math.pow(radius, 2), 1E-15) && !Util.fuzzyEquals(Math.pow(row - position.getY(), 2) + Math.pow(column - position.getX(), 2), Math.pow(radius, 2), 1E-16)) { return true; } } else { //Skip to the next 'tile'. column = column + step*Math.floor((Math.ceil(column/this.getScale()) - column/this.getScale()) / step); } } } return false; }
8cb04927-e976-4f12-9b72-d9e841fe4417
8
public static void main(String[] args) { int contCandidate = 0, contEntry = 0, contReserved = 0, contReject = 0, contDisputed = 0, contEqual = 0; String last = ""; try { File csvData = new File("dataset/base_dados_cve.csv"); // File csvDataOut = new File("dataset/cve_out.csv"); // FileWriter outFile = new FileWriter(csvDataOut); // CSVPrinter csvPrinter = new CSVPrinter((Appendable) outFile, CSVFormat.RFC4180); CSVParser parser = CSVParser.parse(csvData, Charset.forName("ISO-8859-1"),CSVFormat.RFC4180); for (CSVRecord csvRecord : parser) { //System.out.println("Número de campos: " + csvRecord.size()); //System.out.println(csvRecord.get(0)); if (csvRecord.get(1).equals("Candidate")) { contCandidate++; } else if (csvRecord.get(1).equals("Entry")) { contEntry++; } if (csvRecord.get(2).startsWith("** RESERVED **")) { contReserved++; } else if (csvRecord.get(2).startsWith("** REJECT **")) { contReject++; } else if (csvRecord.get(2).startsWith("** DISPUTED **")) { contDisputed++; } else { if (last.equals(csvRecord.get(2))) { contEqual++; } else { // csvPrinter.printRecord(csvRecord); } last = csvRecord.get(2); } } System.out.println("Número de Registros: " + parser.getRecordNumber()); //csvPrinter.close(); } catch (IOException ex) { Logger.getLogger(CveCsvReader.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Número CANDIDATE: " + contCandidate); System.out.println("Número ENTRY: " + contEntry); System.out.println("Número REJECT: " + contReject); System.out.println("Número RESERVED: " + contReserved); System.out.println("Número DISPUTED: " + contDisputed); System.out.println("Número IGUAIS: " + contEqual); }
2ddbd56a-d829-44ad-84ad-f86d9cc52668
0
public static void main(String[] args) { Node1 node1 = new Node1("node1"); Node1 node2 = new Node1("node2"); Node1 node3 = new Node1("node3"); node1.next = node2; node2.previous = node1; node2.next = node3; node3.previous = node2; node3.next = node1; node1.previous = node3; System.out.println(node1.next.next.data); System.out.println("-------------"); Node1 node4 = new Node1("node4"); node1.next = node4; node4.previous = node1; node4.next = node2; node2.previous = node4; System.out.println(node1.next.next.next.data); node1.next = node2; node2.previous = node1; node4.next = null; node4.previous = null; System.out.println(node1.next.next.data); System.out.println(node1.next + "node1:" + node1 ); System.out.println(node2.next ); System.out.println(node3.next); System.out.println(node4.next); Node1 node5 = new Node1("node5"); node5.next.previous = node5; node5.previous.next = node5; System.out.println(node1.next.next.data); }
65f4d127-29c0-4b7f-9d89-d05619a2b23e
1
public boolean encryptSerializedTable(){ //In a real world application, we could use a smartcard as the source of the pass, this is a just a proof of concept String smartcard="verysecurepassword"; try { File f = new File(TABLE_FILE); File fe = new File(ENCRYPTED_TABLE_FILE); f.createNewFile(); fe.createNewFile(); FileInputStream fis = new FileInputStream(TABLE_FILE); FileOutputStream fos = new FileOutputStream(ENCRYPTED_TABLE_FILE); encrypt(smartcard, fis, fos); f.delete(); } catch (Throwable e) { e.printStackTrace(); } return true; }
9bd5e73b-2fb6-4286-9b74-6c508bc34994
2
public void addParticleEffect(String effectName, ParticleEffect effect) { if (effectName == null || effect == null) { throw new IllegalArgumentException("Cannot add a null ParticleEffect!"); } particleEffects.put(effectName, effect); }
1372371e-5325-4184-8fde-ba91a377922e
1
public AnnotationVisitor visitAnnotationDefault() { if (!ClassReader.ANNOTATIONS) { return null; } annd = new ByteVector(); return new AnnotationWriter(cw, false, annd, null, 0); }
e16892a1-4007-4545-a304-48c8dca46bc4
2
public ArrayList<Ticket> getTicket(Ticket tic_in) throws SQLException{ Statement stm = getConnection().createStatement(); String campos = "id,pnr,num_file,ticket,old_ticket,cod_emd,convert(varchar, fecha_emision, 103) as fecha_emisionb,convert(varchar, fecha_anula, 103) as fecha_anula ,convert(varchar, fecha_remision, 103) as fecha_remision ,posicion_pasajero,nombre_pasajero,tipo_pasajero,cod_linea_aerea,ruta,moneda,valor_neto,valor_tasas,valor_final,comision,forma_pago,tipo,estado,oris,gds"; String sql = "SELECT "+campos+" FROM TICKET WHERE ticket='"+tic_in.getTicket()+"' "; System.out.println(sql); ArrayList<Ticket> tickets = new ArrayList(); ResultSet rs = stm.executeQuery(sql); while (rs.next()) { Ticket tic = new Ticket(rs.getString("ticket")); tic.setPnr(rs.getString("pnr")); tic.setNumFile(rs.getString("num_file")); tic.setOldTicket(rs.getString("old_ticket")); tic.setCodEmd(rs.getString("cod_emd")); tic.setFechaEmision(rs.getString("fecha_emisionb")); tic.setFechaAnulacion(rs.getString("fecha_anula")); tic.setFechaRemision(rs.getString("fecha_remision")); tic.setPosicion(rs.getInt("posicion_pasajero")); tic.setNombrePasajero(rs.getString("nombre_pasajero")); tic.setTipoPasajero(rs.getString("tipo_pasajero")); tic.setcLineaAerea(rs.getString("cod_linea_aerea")); tic.setRuta(rs.getString("ruta")); tic.setMoneda(rs.getString("moneda")); tic.setValorNeto(rs.getDouble("valor_neto")); tic.setValorTasas(rs.getDouble("valor_tasas")); tic.setValorFinal(rs.getDouble("valor_final")); tic.setComision(rs.getDouble("comision")); tic.setfPago(rs.getString("forma_pago")); tic.setTipo(rs.getString("tipo")); tic.setEstado(rs.getString("estado")); if (rs.getInt("oris")==1) { tic.setOris(true); }else{ tic.setOris(false); } tic.setGds(rs.getString("gds")); tic.setSegmentos(SegmentoDAO.getInstance().getSegmentoPorId(tic.getTicket())); tickets.add(tic); } return tickets; }
50644ac4-4674-434c-91c9-ceb2c8785acf
5
public Edge getEdge(int i) { Edge retval; if (i < 0 || i > 5) throw new IllegalArgumentException( "Requested hex edge must be in range [0,5], was " + i); else if (myEdge[i] != null) { retval = myEdge[i]; } else { Edge cur; boolean enteredViaE0minus; // True iff we entered cur from prev via cur's e0minus edge. cur = getEdge( i - 1); // Crazy recursion to handle caching. enteredViaE0minus = enteredViaVertex0( i-1); // enteredViaEdge0Minus( i-1); retval = (enteredViaE0minus ? cur.getEdge1Plus() : cur.getEdge0Plus()); myEdge[i] = retval; if (i > myHighestCachedEdge) myHighestCachedEdge = i; } return retval; }
4f350fbc-d781-4c5a-a307-1890e02ef43b
9
private int maxLength() { HashMap <Integer,Integer> lengths = new HashMap<Integer,Integer>(); SimpleQueue<Node> queue = new SimpleQueue<Node>(); HashSet<Node> printed = new HashSet<Node>(); queue.add( start ); while ( !queue.isEmpty() ) { Node node = queue.poll(); ListIterator<Arc> iter = node.outgoingArcs( this ); while ( iter.hasNext() ) { Arc a = iter.next(); char[] data = a.getData(); // calculate total length totalLen += data.length; BitSet bs = a.versions; for ( int i=bs.nextSetBit(0);i>=0;i=bs.nextSetBit(i+1) ) { if ( lengths.containsKey(i) ) { Integer value = lengths.get( i ); lengths.put( i, value.intValue()+data.length ); } else lengths.put( i, data.length ); } a.to.printArc( a ); printed.add( a.to ); if ( a.to != end && a.to.allPrintedIncoming(constraint) ) { queue.add( a.to ); a.to.reset(); } } } // clear printed Iterator<Node> iter2 = printed.iterator(); while ( iter2.hasNext() ) { Node n = iter2.next(); n.reset(); } /// Find the maximum length version Integer max = new Integer( 0 ); Set<Integer> keys = lengths.keySet(); Iterator<Integer> iter = keys.iterator(); while ( iter.hasNext() ) { Integer key = iter.next(); Integer value = lengths.get( key ); if ( value.intValue() > max.intValue() ) max = value; } return max.intValue(); }
ed4d7d86-64db-48ef-9ce4-1e9be2540fbe
2
public int getPriParkChargeByPID(Statement statement,String PID)//根据PID获取优惠后停车费用 { int result = -1; sql = "select priparkcharge from Park where PID = '" + PID +"'"; try { ResultSet rs = statement.executeQuery(sql); while (rs.next()) { result = rs.getInt("priparkcharge"); } } catch (SQLException e) { System.out.println("Error! (from src/Fetch/Park.getPriParkChargeByPID()"); // TODO Auto-generated catch block e.printStackTrace(); } return result; }
ee1fc103-fd86-47bd-b892-5349e4b60710
2
public static void botones(int valor){ switch(valor){ case 1: Interfaz.delD.setEnabled(true); Interfaz.bajar.setEnabled(false); Interfaz.del.setEnabled(false); break; case 2: Interfaz.delD.setEnabled(false); Interfaz.bajar.setEnabled(true); Interfaz.del.setEnabled(true); break; default: Interfaz.delD.setEnabled(false); Interfaz.bajar.setEnabled(false); Interfaz.del.setEnabled(false); break; } }
6692331f-43c7-41cf-afe5-706fed4be001
7
public void stopNPCGather(Player p) { if (registry.getGameController().multiplayerMode != registry.getGameController().multiplayerMode.CLIENT) { Resource resource = null; try { for (String key : resources.keySet()) { resource = (Resource) resources.get(key); if (resource != null) { if (resource.getIsCollecting()) { if (resource.getCollectingPlayer() == p && resource.isNPCCollecting()) { resource.setCollecting(p, false); collectingResources.remove(resource.getId()); } } } } } catch (ConcurrentModificationException concEx) { //another thread was trying to modify resources while iterating //we'll continue and the new item can be grabbed on the next update } } }
683b90b1-a4fd-4dc0-a502-37c4e391d1b0
7
public void loadArenas() { XMLConfig arenaConfig = new XMLConfig("plugins/lmsArenas.xml"); XMLNode node = arenaConfig.getRootNode(); if (!node.nodeExists("defaults")) { XMLNode defaults = new XMLNode("defaults"); XMLNode cubePadding = new XMLNode("option"); cubePadding.addAttribute("name", "cubePadding"); cubePadding.addAttribute("value", "10"); XMLNode cubeDiameter = new XMLNode("option"); cubeDiameter.addAttribute("name", "cubeDiameter"); cubeDiameter.addAttribute("value", "5"); XMLNode cubeDistance = new XMLNode("option"); cubeDistance.addAttribute("name", "cubeDistance"); cubeDistance.addAttribute("value", "10"); defaults.addChild(cubePadding); defaults.addChild(cubeDiameter); defaults.addChild(cubeDistance); node.addChild(defaults); arenaConfig.save("plugins/lmsArenas.xml"); } if (node.getName().equalsIgnoreCase("arenas") && node.nodeExists("defaults")) { if (node.nodeExists("arena")) { for (XMLNode subNode : node.getChilds()) { if (subNode.getName().equalsIgnoreCase("arena")) { if (subNode.attributeExists("name")) { System.out.println("Found arena : " + (String) subNode.getAttribute("name").getAttributeValue()); loadArena(subNode, node.getChild("defaults")); } } } } } }
310daa0a-4a65-4bb4-8d38-c5592a914e5b
4
@Override public void execute() { String msg = Widgets.get(13, 28).getText(); if (msg.contains("FIRST")) { Widgets.get(13, Character.getNumericValue(Settings.pin[0]) + 6).click(true); Task.sleep(750, 1200); } if (msg.contains("SECOND")) { Widgets.get(13, Character.getNumericValue(Settings.pin[1]) + 6).click(true); Task.sleep(750, 1200); } if (msg.contains("THIRD")) { Widgets.get(13, Character.getNumericValue(Settings.pin[2]) + 6).click(true); Task.sleep(750, 1200); } if (msg.contains("FOURTH")) { Widgets.get(13, Character.getNumericValue(Settings.pin[3]) + 6).click(true); Task.sleep(750, 1200); } }
ebc25194-97d0-4037-8aff-83e8539e8c3e
3
public static void main(String[] args) { try { Display.setDisplayMode(new DisplayMode(800, 600)); Display.create(); Display.setTitle("TWL Login Panel Demo"); Display.setVSyncEnabled(true); TestGui demo = new TestGui(); LWJGLRenderer renderer = new LWJGLRenderer(); GUI gui = new GUI(demo, renderer); ThemeManager theme = ThemeManager.createThemeManager( TestGui.class.getResource("login.xml"), renderer); gui.applyTheme(theme); while(!Display.isCloseRequested() && !demo.quit) { GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); gui.update(); Display.update(); } gui.destroy(); theme.destroy(); } catch (Exception ex) { ex.printStackTrace(); } Display.destroy(); }
561ff012-0c6b-4556-98f1-237f4269d42f
8
public static HashSet<Point> getAnthillPoints() { /* * The first part of the algorithm traces the outline of a hexagon on * the grid */ // Pull out side length int sideLength = AntGame.CONFIG.CONTEST_MAP_ANTHILL_SIDE_LENGTH; // Height of hexagon = (2n - 1) where n = side length int height = ( 2 * sideLength ) - 1; // Initialise collection of points to be included in the anthill HashSet<Point> targetCells = new HashSet<Point>(); // First cell is the one [sidelength - 1] units vertically ( -1 as we // start at 0) int drawYOffset = sideLength - 1; targetCells.add(new Point(0, drawYOffset)); int curX = 0; int maxY = drawYOffset + 1; int minY = drawYOffset - 1; /* * I started writing a good algorithm, it turned ugly, and this is the result. * I don't even follow it but it seems to work. */ // Open angled bit boolean done = false; while (!done) { if ( (maxY - minY) >= height ) { done = true; maxY--; minY++; } for (int curY = minY; curY <= maxY; curY++) { targetCells.add(new Point(curX, curY)); } maxY += 2; minY -= 2; curX++; } maxY -= 2; minY += 2; // Straight bit int i; for (i = curX; i < ( (sideLength - 1) + curX ); i++) { for (int curY = minY; curY <= maxY; curY++) { targetCells.add(new Point(i, curY)); } } curX = i; done = false; maxY = height - 3; minY = 2; // Closed angle bit while (!done) { if ( (maxY - minY) <= 1 ) { done = true; } for (int curY = minY; curY <= maxY; curY++) { targetCells.add(new Point(curX, curY)); } maxY -= 2; minY += 2; curX++; } return targetCells; /* // Make a note of peak x and y offsets reached (to be used later) int peakX = -1; int peakY = -1; for (int i = 0; i < sideLength - 1; i++) { targetCells.add(new Point((i / 2), drawYOffset - i)); targetCells.add(new Point((i / 2), drawYOffset + i)); // If this is the last time the loop will run, record the peak // offsets if ((i + 1) == sideLength) { peakX = (i / 2); peakY = drawYOffset + i; } } for (int i = 0; i < sideLength - 1; i++) { targetCells.add(new Point(peakX + i, 0)); targetCells.add(new Point(peakX + i, peakY)); } // Record the new "peak x" peakX = peakX + (sideLength - 1); // Record our current x-position int curX = -1; for (int i = 0; i < sideLength - 1; i++) { curX = peakX + (i / 2); // If our two tracelines have converged, draw one point (convergence // point) if (i == (peakY - i)) { targetCells.add(new Point(curX, i)); // Otherwise, continue to trace the lines } else { targetCells.add(new Point(curX, i)); targetCells.add(new Point(curX, (peakY - i))); } } // Update peakX to reflect the maximum x-position reached peakX = curX; for (int y = 0; y <= peakY; y++) { // Flag to see if we're filling in the cells we're coming across boolean filling = false; // Flag to see if we're done filling in anthill cells in this row boolean reachedEnd = false; // We use a while loop as we may not iterate to the end of the row int x = 0; while (!reachedEnd) { // Check if this cell is already part of the anthill if (targetCells.contains(new Point(x, y))) { // If we weren't already filling, this cell is the start of // the anthill on this row, // so let's start filling if (!filling) { filling = true; // If we've already been filling, we've reached the end // of the row } else { reachedEnd = true; } // If this cell is empty and we're filling in cells, fill // this one } else if (filling) { targetCells.add(new Point(x, y)); } // Increment loop counter x++; } } // Return the target cells return targetCells;*/ }
14dd84c1-236e-4cec-85dc-cbf2cd02d56b
1
public ArrayList<String> lista() throws RemoteException, NenhumServidorDisponivelException { ArrayList<String> list = new ArrayList<String>(); Set<String> objs = objects.keySet(); //Add all object names into 'list' for(String s: objs) { list.add(s); } return list; }
3b0d2e26-53f2-411e-b853-5b839652deb2
2
public static void endAllWithName(String name){ for(ScheduleData data : schedules){ if(data.getName().equalsIgnoreCase(name)) endSchedule(data.getScheduleID()); } }
6ba1a34c-fe25-4668-a9bb-cdaed049382a
4
void a1(int p1, int p2) { boolean invite = false; if (p1 + p2 > 120 || p1 + p2 < 15 || p1 > 85 || p2 > 85) { invite = true; } }
752483cf-2480-4c75-ad4e-e03493232f8a
2
public static int readInt() { String line = null; int value = 0; try { BufferedReader is = new BufferedReader(new InputStreamReader( System.in)); line = is.readLine(); value = Integer.parseInt(line); } catch (NumberFormatException ex) { System.err.println("Not a valid number: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } return value; }
28378270-47eb-4d92-beec-9f414407fc85
8
public void displayRoomInfo(Player player) { RoomType roomType = grid[player.getLocationX()][player.getLocationY()] .getRoomType(); if (roomType.equals(RoomType.entrance)) { System.out .println("This is the entrance. You leaving already? Head inside!"); grid[player.getLocationX()][player.getLocationY()] .setExplored(true); } else if (roomType.equals(RoomType.wumpus)) { if (player.weapon) { System.out .println("There's a wumpus! You charge him and slay him with your weapon."); player.addScore(10); grid[player.getLocationX()][player.getLocationY()] .setRoomType(RoomType.empty); grid[player.getLocationX()][player.getLocationY()] .setExplored(true); } else { System.out.println("Chomp. A wumpus swallows you whole."); System.out.println("**** GAME OVER ****"); System.out.println("You scored " + player.getScore() + " points!"); grid[player.getLocationX()][player.getLocationY()] .setExplored(true); System.exit(1); } } else if (roomType.equals(RoomType.pit)) { System.out .println("You place your foot through the door, only to find there is no floor... falling for infinity, you are."); System.out.println("**** GAME OVER ****"); System.out.println("You scored " + player.getScore() + " points!"); grid[player.getLocationX()][player.getLocationY()] .setExplored(true); System.exit(1); } else if (roomType.equals(RoomType.gold)) { System.out .println("Oooh, delicious delicious gold! Loot it by typing \"L\"."); grid[player.getLocationX()][player.getLocationY()] .setExplored(true); } else if (roomType.equals(RoomType.weapon)) { System.out.println("You found a weapon. Type \"L\" to pick it up!"); grid[player.getLocationX()][player.getLocationY()] .setExplored(true); } else if (roomType.equals(RoomType.empty)) { System.out.println("There's nothing here."); if (!grid[player.getLocationX()][player.getLocationY()] .isExplored()) { player.addScore(1); grid[player.getLocationX()][player.getLocationY()] .setExplored(true); } } }
2f002e15-d1c5-445e-b524-02e210c145dd
8
private static String treat(final String line) { int cpt = 0; int cpt2 = line.length() - 1; char prov; //System.out.println(line); prov = line.charAt(cpt); while ((prov == ' ' || prov == '\t') && cpt != cpt2) { prov = line.charAt(++cpt); } //System.out.println("1 ok"); prov = line.charAt(cpt); while ((prov == ' ' || prov == '\t') && cpt2 != 0) { prov = line.charAt(--cpt2); } if (cpt == 0 && cpt2 == (line.length() - 1)) { return line; } else { return line.substring(cpt, cpt2); } }
be93f7ae-3955-4900-a5f3-610f790f9f98
6
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(CCManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CCManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CCManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CCManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new CCManager().setVisible(true); } }); }
eb35f50a-8328-4829-a4d1-3a7dea178f3c
2
private void setImage(String name) { BufferedImage im = registry.getImageLoader().getImage(name); if (im != null) { AffineTransform tx = null; AffineTransformOp op = null; if (direction == Direction.LEFT) { //rotate the image based on where you're shooting tx = new AffineTransform(); tx.rotate(Math.atan(slope), im.getWidth() / 2, im.getHeight() / 2); op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR); image = op.filter(im, null); width = im.getWidth(); height = im.getHeight(); //flip horizontally tx = new AffineTransform(); tx = AffineTransform.getScaleInstance(-1, 1); tx.translate(-width, 0); op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR); image = op.filter(image, null); } else { //rotate the image based on where you're shooting tx = new AffineTransform(); tx.rotate(-Math.atan(slope), im.getWidth() / 2, im.getHeight() / 2); op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR); image = op.filter(im, null); width = im.getWidth(); height = im.getHeight(); } } }
53323b45-4090-4a6d-82a7-4b3f54e02737
1
public void draw(GOut g) { super.draw(g); if(busy) { g.chcolor(busycolor); g.frect(Coord.z, sz); g.chcolor(); } }
27b0e0a8-61cf-469f-9dd9-01536dcc24d6
5
public static void savePomo() throws DataFileNotFoundException { File dataStore = new File("PomoData"); try { if(dataStore.exists()) { String line; FileReader fileReader = new FileReader(dataStore); BufferedReader bufferedReader = new BufferedReader(fileReader); while( (line=bufferedReader.readLine()) != null ) { System.out.println("Line!" + line); if (line.contains("LifeTimePomo")) { bufferedReader.close(); FileWriter writer = new FileWriter(dataStore); BufferedWriter bufferedWriter = new BufferedWriter(writer); int number = Integer.parseInt(line.substring(line.lastIndexOf(":") + 1)); number++; String putData = "LifeTimePomo:" + number; bufferedWriter.write(putData); bufferedWriter.newLine(); System.out.println("Writing..."); bufferedWriter.close(); break; } } } else { throw new DataFileNotFoundException("Could not find the required data file."); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
19a05577-227e-421f-9577-d7539b0c15fb
5
public boolean onCommand(Player player, String[] args) { File fichier_language = new File(OneInTheChamber.instance.getDataFolder() + File.separator + "Language.yml"); FileConfiguration Language = YamlConfiguration.loadConfiguration(fichier_language); if(player.hasPermission(getPermission())){ if(args.length < 2){ String notEnoughArgs = Language.getString("Language.Error.Not_enough_args"); UtilSendMessage.sendMessage(player, notEnoughArgs); return true; } if(args.length > 1){ String arenaName = args[1]; if(ArenaManager.getArenaManager().getArenaByName(arenaName) != null){ try{ Integer.parseInt(args[0]); }catch(NumberFormatException e){ String badArg = Language.getString("Language.Error.Bad_args"); UtilSendMessage.sendMessage(player, badArg); return true; } int points = Integer.parseInt(args[0]); Arena arena = ArenaManager.getArenaManager().getArenaByName(arenaName); arena.setMaxPoints(points); arena.saveConfig(); String succes = Language.getString("Language.Setup.Points").replaceAll("%arena", arenaName); UtilSendMessage.sendMessage(player, succes); return true; }else{ String doesntExist = Language.getString("Language.Error.Arena_does_not_exist").replaceAll("%arena", arenaName); UtilSendMessage.sendMessage(player, doesntExist); return true; } } }else{ String notPerm = Language.getString("Language.Error.Not_permission"); UtilSendMessage.sendMessage(player, notPerm); return true; } return true; }
2eeea8b4-f765-4898-a054-b8e7e10854a3
7
@Override public void update(float dt) { if (speed.x > 0) { speed.x -= drag; } else if (speed.x < 0) { speed.x += drag; } if (Math.abs(speed.x) <= drag / 2f) { speed.x = 0; } speed.y -= universe.gravity; if (Math.abs(speed.x) > topSpeed.x) { speed.x = speed.x > 0 ? topSpeed.x : -topSpeed.x; } if (Math.abs(speed.y) > topSpeed.y) { speed.y = speed.y > 0 ? topSpeed.y : -topSpeed.y; } position.x += speed.x * dt; position.y += speed.y * dt; }
459600c4-9875-4a5a-bfb9-3b7cbae4ebb1
8
private static Integer createPostingList(long featureId, StringTokenizer tokenizer, File postingFile, File compressedPostingFile) { TreeMap<Integer, Integer> postingInput = new TreeMap<Integer, Integer>(); BasicPostingList posting = new BasicPostingList(featureId); CompressedPostingList compressedPosting = new CompressedPostingList(featureId); int j = 0; int maxWeight = 0; int did = 0; while (tokenizer.hasMoreElements()) { Integer token = Integer.parseInt(tokenizer.nextToken()); if (j % 2 == 0 && token != 0) { did = token; postingInput.put(token, 0); } else if (j % 2 == 1 && token != 0) { if (token > maxWeight) { maxWeight = token; } postingInput.put(did, token); } j++; } Iterator<Integer> iter = postingInput.keySet().iterator(); int key; while (iter.hasNext()) { key = iter.next(); posting.addDoc(key); posting.addWeight(postingInput.get(key)); compressedPosting.addDoc(key); compressedPosting.addWeight(postingInput.get(key)); } // System.out.println(posting); // System.out.println(compressedPosting); try { FileOutputStream postingStream = new FileOutputStream(postingFile, true); FileOutputStream compressedPostingStream = new FileOutputStream(compressedPostingFile, true); ObjectOutputStream postingOut = new ObjectOutputStream(postingStream); ObjectOutputStream compressedPostingOut = new ObjectOutputStream(compressedPostingStream); postingOut.writeObject(posting); postingOut.flush(); postingOut.close(); postingStream.close(); compressedPostingOut.writeObject(compressedPosting); compressedPostingOut.flush(); compressedPostingOut.close(); compressedPostingStream.close(); } catch (IOException e) { e.printStackTrace(); } return maxWeight; }
d1940984-d86e-45c3-86ad-51fe14e01baf
3
public int posMax() { int MaxValPos = -1; //position of maximum value char MaxVal; //maximum value char []SeqArray; //array of chars for looping through if(SeqValue.length() == 0) //if sequence is empty return MaxValPos; SeqArray= SeqValue.toCharArray(); MaxVal = SeqArray[0]; //initialize max value as first value MaxValPos = 0; //initialize max value position as first position for(int i = 1; i < SeqValue.length(); i++) { //loop through the sequence if(SeqArray[i] > MaxVal) //if current value > value in MaxVal { MaxVal = SeqArray[i]; //our new MaxVal is the current value MaxValPos = i; //our new MaxValPos is the current position }//end if }//end for return MaxValPos; }//end PosMax
8cddd4b5-fb71-4e08-81d1-6b3814706015
0
public HandlerList getHandlers() { return handlers; }
3a93277d-a415-4deb-96f1-893b37c1e58b
3
private void isGreaterThanEqualsToDate(Date param, Object value) { if (value instanceof Date) { if (!(param.after((Date) value) || param.equals(value))) { throw new IllegalStateException("Given Date does not lie after the supplied date."); } } else { throw new IllegalArgumentException(); } }
428c76b4-52c4-44f5-82db-262f09c4846c
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProcDescriptor other = (ProcDescriptor) obj; if (labelInAssembler != other.labelInAssembler) return false; if (lokal == null) { if (other.lokal != null) return false; } else if (!lokal.equals(other.lokal)) return false; return true; }
05032a3d-8992-4c9b-b75b-3968b14693ff
3
void iterateArrayList() { try { System.out.println("starting iterate"); Iterator b= al.iterator(); while(b.hasNext()) { try { Thread.sleep(5000); b.next(); } catch (InterruptedException e) { System.out.println(e); } } System.out.println("ending iterate"); } catch(Exception e) { System.out.println(e); } }
f375706c-64a7-4dd1-ac11-bb6a2d73cc59
4
public void putScenery(Scenery scenery, int x, int y) { if ((x < width && y < height) && (x >= 0 && y >= 0)) { data[y][x] = scenery; } else { throw new AssertionError("placed a scenery off the map"); } }
6051cc9b-6a4d-4483-9811-d239688f2c5c
5
public boolean subsEquals(Operator other) { if (this == other) return true; if (other.subExpressions == null) return (subExpressions == null); if (subExpressions.length != other.subExpressions.length) return false; for (int i = 0; i < subExpressions.length; i++) { if (!subExpressions[i].equals(other.subExpressions[i])) return false; } return true; }
f2577d03-39ba-4f9c-9b43-48b4acc79db2
7
final private boolean jj_3R_95() { if (jj_3R_42()) return true; Token xsp; xsp = jj_scanpos; if (jj_3R_130()) { jj_scanpos = xsp; if (jj_3R_131()) return true; } if (jj_3R_44()) return true; xsp = jj_scanpos; if (jj_3R_180()) jj_scanpos = xsp; xsp = jj_scanpos; if (jj_3R_181()) { jj_scanpos = xsp; if (jj_scan_token(79)) return true; } return false; }
cb7f9e46-84a5-40e4-8c13-409c69c17601
3
private boolean isWinner() { Player[][] locations = this.board.getBoardLocations(); for (int row = 0; row < locations.length; row++) { Player[] rowLocations = locations[row]; for (int col = 0; col < rowLocations.length; col++) { if (fourInARow(row, col, locations)) { return true; } } } return false; }
6dc7a9b6-5675-405b-b8b7-1578153d0db2
4
public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); ArrayList<Future<String>> results = new ArrayList<Future<String>>(); for (int i = 0; i < 10; i++) results.add(exec.submit(new TaskWithResult(i))); for (Future<String> fs : results) try { System.out.println(fs.get()); } catch(InterruptedException e) { System.out.println(e); return; } catch(ExecutionException e) { System.out.println(e); } finally { exec.shutdown(); } }
232cb75a-03d1-463a-b8a1-15f82ba8289d
7
public static File getAppDir(String dirname) { String s = System.getProperty("user.home", "."); File file; switch (getOs()) { case linux: case solaris: file = new File(s, "." + dirname + '/'); break; case windows: String s1 = System.getenv("APPDATA"); if (s1 != null) { file = new File(s1, "." + dirname + '/'); } else { file = new File(s, "." + dirname + '/'); } break; case macos: file = new File(s, "Library/Application Support/" + dirname); break; default: file = new File(s, dirname + "/"); break; } if (!file.exists() && !file.mkdirs()) { throw new RuntimeException((new StringBuilder()).append("The working directory could not be created: ").append(file).toString()); } else { return file; } }
28fe98d9-09b8-4b19-bbab-657731272c30
5
@Override public void motorsCommand(boolean sideBrush, boolean sideBrushClockwise, boolean mainBrush, boolean mainBrushOutward, boolean vacuum) throws RoombaIFException { checkIsOpened("driveCommand"); byte d = 0; d += ((sideBrush) ? 0 : 1); d += ((vacuum) ? 0 : 2); d += ((mainBrush) ? 0 : 4); d += ((sideBrushClockwise) ? 0 : 8); d += ((mainBrushOutward) ? 0 : 16); byte[] c = {MOTORS_COMMAND, d}; writeBytes(c); }
15c1ea02-9d9e-4df0-a903-fc0d25f8bee0
5
String getMissingChannelsMsg() { if (MissingChannels.isEmpty()) { return null; } String msg = null; if (MissingChannels.size() == 1) { msg = "Channel " + MissingChannels.first() + " is"; } else { msg = "Channels "; for (Integer i : MissingChannels) { if (i == MissingChannels.last()) { msg += ", and "; } else if (i != MissingChannels.first()) { msg += ", "; } msg += i; } msg += " are"; } msg += " not in any group."; return msg; }
b0679071-0f7d-4949-8b02-2053fddde6a0
8
public void extendTreeHeight() { //build the alloweChars array String[] allowedChars = new String[Oracle.allowedChars.length - globalPrefix.length()]; int index = 0; for (String e : Oracle.allowedChars) { if (!globalPrefix.contains(e)) { allowedChars[index++] = e; } } //get all combinations for the remaining char set ArrayList<String> allCombinations = (new CombinationGenerator()).GetAllCombinationsUptoN(allowedChars, maxCombLen); //generate suffixes, check for tree balance, and expand //ArrayList<Prefix> nextPrefixes = new ArrayList<Prefix>(); String selectedCombination = ""; int minScore = Integer.MAX_VALUE; for (String com : allCombinations) { //Prefix[] prefixes = new Prefix[((int) Math.pow(2, com.length()))]; int max = Integer.MIN_VALUE, avg = 0, b = 0; ArrayList<Prefix> allPrefix = GetPrefixes(globalPrefix + com); int[] prefixMatches = new int[allPrefix.size()]; for (; b < allPrefix.size(); b++) { //calculate count prefixMatches[b] = 0; //create a new prefix Prefix prefix = new Prefix(); prefix.add(allPrefix.get(b)); //add global prefix and current prefix to prefix for (String name : allNames) { if (prefix.isMatch(name)) { prefixMatches[b]++; } } if (prefixMatches[b] > max) { max = prefixMatches[b]; } avg += prefixMatches[b]; } avg /= b; //calculate score if (minScore > (max - avg)) { minScore = max - avg; selectedCombination = com; } } //System.out.println(selectedCombination); H2C.add(currentHeight++, selectedCombination); globalPrefix += selectedCombination; //expand the tree //generate the prefixes and create the leaf nodes // for (int b = 0; b < Math.pow(2, selectedCombination.length()); b++) { // // check for bits // int c = (1 << (selectedCombination.length() - 1)); // Prefix prefix = new Prefix(); // //prefix.add(node.prefix); // VERY IMPORTANT STEP // for (int l = 0; l < selectedCombination.length(); l++) { // if ((b & c) == 0) { // prefix.addLetter(selectedCombination.charAt(l), '-'); // } else { // prefix.addLetter(selectedCombination.charAt(l), '+'); // } // c = (c >> 1); // } // //prefix is ready, now create node and add names // TreeNode lf = new TreeNode(); // lf.parent = node; // lf.prefix = prefix; // node.addChild(lf); // for (String name : node.names) { // if (prefix.isMatch(name)) { // lf.addName(name); // } // } // } // node.names.clear(); // very important }
b494e862-7c33-43f9-8b90-989bd2485690
4
protected static String getListTagForString(String str) { char chr = str.charAt(0); switch (chr) { case '#': return "ol"; case '*': return "ul"; case ':': case ';': return "dl"; } return null; }
b6396967-22eb-47ee-a5dc-2e66cfce4ab1
5
public void update(int delta) { if(switchedWaypoints) { if(targetWaypoint == null) { //done finished = true; return; } else { //recalculate dx and dy float diffX, diffY; diffX = targetWaypoint.getX() - this.x; diffY = targetWaypoint.getY() - this.y; float magnitude = (float)Math.sqrt(diffX*diffX + diffY*diffY); dx = diffX / magnitude; dy = diffY / magnitude; //System.out.println("dx: " + dx + ", dy: " + dy); switchedWaypoints = false; } } else { //if the enemy has reached it's next waypoint if(Game.circlesCollide(this.x, this.y, 1, this.targetWaypoint.getX(), this.targetWaypoint.getY(), 1)) { switchedWaypoints = true; this.targetWaypoint = this.targetWaypoint.getNext(); return; } this.x += dx * speed * (delta/1000.0); this.y += dy * speed * (delta/1000.0); /* * Determine if we have moved out of range of any towers and alert those towers. */ int size = attackers.size(); for(int i = 0; i < size; i++) { if(!Game.enemyInRange(attackers.get(i), this)) { attackers.get(i).outOfRange(this); attackers.remove(i); i--; size--; } } } }
8705bbb9-e738-4891-a369-9e9cc1cc7813
8
public static final void main( String[] args ) throws Exception { try { String output_file = "mets.zip"; String metadata_file = "metadata.txt"; Vector input_filenames = new Vector(); Vector input_filetypes = new Vector(); Vector archive_filenames = new Vector(); Hashtable metadata = new Hashtable(); for( int i=0; i<args.length; i++ ) { if( args[i].equals( "-o" ) ) { i++; output_file = args[i]; } if( args[i].equals( "-m" ) ) { i++; metadata_file = args[i]; } if( args[i].equals( "-i" ) ) { i++; input_filenames.addElement( args[i] ); i++; input_filetypes.addElement( args[i] ); i++; archive_filenames.addElement( args[i] ); } if (args[i].equals( "-h" ) ) { System.out.println( "Syntax: METSWriter\n\t\t[-o output-zip-file]\n\t\t[ [-i input-file-name input-mime-type mets-archive-filename] ]\n\t\t[-m metadata-file]\n" ); System.out.println( "Supported mimetypes:" ); ParserFactory.list(); System.exit(1); } } DataParser dp = new DataParser( metadata_file ); METSMetadata md = readMetadata( dp ); METSWriter hate = new METSWriter( output_file ); for( int i=0; i<input_filenames.size(); i++ ) { String fn = (String) input_filenames.elementAt(i); String ft = (String) input_filetypes.elementAt(i); String afn= (String) archive_filenames.elementAt(i); try { //Parser p = ParserFactory.createParser( fn, ft, md ); METSMetadata md2 = ParserFactory.parse( fn, ft, md ); //p.parse(); hate.addFile(fn , afn, ft, md2 ); } catch ( Exception ex ) { System.out.println("Failed to parse "+fn ); ex.printStackTrace( System.out ); } } hate.setMetadata( md ); hate.write(); } catch ( Exception e ) { e.printStackTrace( System.err ); System.exit(2); } System.exit(0); }
b10e3863-a80a-4cb8-aa58-521caf230992
8
private void jButton_ExchangeActionPerformed1(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ExchangeActionPerformed1 try { if(true){ JOptionPane.showMessageDialog(null, "Exchange is currently not supported","Error",JOptionPane.ERROR_MESSAGE); return; } CashPurseAccount cashPurseAccount = new CashPurseAccount(); ArrayList selectedIndices = new ArrayList(); for (int i = 0; i < jTable5.getRowCount(); i++) { String id = (String) jTable5.getModel().getValueAt(i, 3); if ((Boolean) jTable5.getModel().getValueAt(i, 5)) { selectedIndices.add(id); } } System.out.println("selectedIndices:" + selectedIndices); if(selectedIndices.isEmpty()){ int selected = JOptionPane.showConfirmDialog(this, "This will exchange all of the tokens in the purse", "Warning", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if(selected==2) return; } setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); boolean isSuccess = cashPurseAccount.exchangeCashPurse(details.getServerID(), details.getAssetID(), details.getNymID(), details.getPurse(), selectedIndices); if (isSuccess) { JOptionPane.showMessageDialog(this, "Cash exchanged successfully", "Exchange Success", JOptionPane.INFORMATION_MESSAGE); CashPurseDetails cashDetails = new CashPurseAccount().getCashPurseDetails(details.getServerID()+":"+details.getAssetID()+":"+details.getNymID()); CashPurseAccountBottomPanel.populateCashPurseDetails(cashDetails); CashPurseAccountTopPanel.populateCashPurseDetails(cashDetails, cashDetails.getBalance()); MainPage.reLoadAccount(); //((CashPurseTableModel) jTable5.getModel()).setValue(cashPurseAccount.refreshGridData(details.getServerID(), details.getAssetID(), details.getNymID()), jTable5); } else { if(Helpers.getObj()!=null){ new CashPurseExportDetails(null, true,(String)Helpers.getObj(),false).setVisible(true); }else JOptionPane.showMessageDialog(this, "Error in cash purse exchange", "Server Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { e.printStackTrace(); } finally { setCursor(Cursor.getDefaultCursor()); } }//GEN-LAST:event_jButton_ExchangeActionPerformed1
d8f85d6a-789e-4a7f-8982-00137ee4348a
9
public static AbstractEvent parse(ObjectNode node) { final String method = node.get("method").getTextValue(); final ObjectNode params = (ObjectNode)node.get("params"); if (method.equals(PlayerEvent.Play.METHOD)) { return new PlayerEvent.Play(params); } else if (method.equals(PlayerEvent.Pause.METHOD)) { return new PlayerEvent.Pause(params); } else if (method.equals(PlayerEvent.Stop.METHOD)) { return new PlayerEvent.Stop(params); } else if (method.equals(PlayerEvent.SpeedChanged.METHOD)) { return new PlayerEvent.SpeedChanged(params); } else if (method.equals(PlayerEvent.Seek.METHOD)) { return new PlayerEvent.Seek(params); } else if (method.equals(SystemEvent.Quit.METHOD)) { return new SystemEvent.Quit(params); } else if (method.equals(SystemEvent.Restart.METHOD)) { return new SystemEvent.Restart(params); } else if (method.equals(SystemEvent.Wake.METHOD)) { return new SystemEvent.Wake(params); } else if (method.equals(SystemEvent.LowBattery.METHOD)) { return new SystemEvent.LowBattery(params); } else{ return null; } }
5fc4499b-7936-4823-9bc3-3c952e551407
8
public Shell[] getShells() { checkWidget(); int count = 0; Shell[] shells = display.getShells(); for (int i = 0; i < shells.length; i++) { Control shell = shells[i]; do { shell = shell.getParent(); } while (shell != null && shell != this); if (shell == this) count++; } int index = 0; Shell[] result = new Shell[count]; for (int i = 0; i < shells.length; i++) { Control shell = shells[i]; do { shell = shell.getParent(); } while (shell != null && shell != this); if (shell == this) { result[index++] = shells[i]; } } return result; }
a52b63e4-b042-4103-ad3b-c1ef07168cc2
8
public void uploadImage(){ try { //Print out the image path when debugging if(debug){ System.out.println("Image path: "+image_path); } //Initialize the string name to null String fileName =""; //Get the file name from windows file system if(image_path.lastIndexOf("\\")>0){ //Remove the last backslash fileName = image_path.substring(image_path.lastIndexOf("\\")+1); } //Get the file name from unix file system else if(image_path.lastIndexOf("/")>0){ //Remove the last slash fileName = image_path.substring(image_path.lastIndexOf("/")+1); } //Print out the stripped image path when debugging if(debug){ System.out.println("Stripped image path: "+fileName); } //Encode the URL to ensure that all the characters send are valid String data = URLEncoder.encode("file_name", "UTF-8") + "=" + URLEncoder.encode(fileName, "UTF-8"); data += "&" + URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8"); //Construct URL URL url = new URL(baseURL+"upload.php?"+data); //Open HttpURLConnection from the URL HttpURLConnection huc = (HttpURLConnection) url.openConnection(); //Set output to true huc.setDoOutput(true); //Set method to post to upload to the server, PHP will receive it as $_POST huc.setRequestMethod("POST"); //Create outputstream object to write the file OutputStream outs = huc.getOutputStream(); //Create the file File f =new File(image_path); //Create bufferedInputStream to read the file by its bytes BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f)); //Send each byte to the server for (int i = 0; i < f.length(); i++) { outs.write(bis.read()); } outs.close(); /* * BufferedReader is mandatory, * otherwise this method does not execute * The feedback from the server must be read */ BufferedReader in = new BufferedReader( new InputStreamReader( huc.getInputStream())); //Read the feedback from the server String out = ""; while (in.ready()) { //Reading the output is mandatory out += in.readLine()+"\r\n"; } if(debug){ System.out.println(out); } in.close(); bis.close(); } catch (IOException ex) { Logger.getLogger(ProfilePicture.class.getName()).log(Level.SEVERE, null, ex); } }
ae648520-47de-478d-bd1e-790a29184c99
6
public String getMobName(LivingEntity entity) { if (showMobName) { String name = entity.getCustomName(); if (name != null) return name; if (entity instanceof Player) return ((Player) entity).getName(); } if (showAbilitySetName && MMComponent.getAbilities().isEnabled()) { String name = AbilitySet.getMeta(entity); if (name != null) return Character.toUpperCase(name.charAt(0)) + name.substring(1); } return null; }
7b0f38de-567f-443a-821a-17593c2a3391
5
private synchronized void dropPacketFIFO(Packet pnp) { // If the queue is full, we have to drop a packet, giving priority to the control packets // Control packets will be those packets sent between the broker or the GIS. // Normal packets are those belonging to a gridlet. // Control packets can only be dropped when the wue is full of control packets increaseDroppedPktCounter(); // increase the counter of dropped packets // First: check if the new incoming packet is a control packet or not. // Check the source of the packet int src_outputPort = ((FnbNetPacket) pnp).getSrcID(); boolean isFile = ((FnbNetPacket) pnp).isFile(); String src_outputPort_str = GridSim.getEntityName(src_outputPort); // for example, src_outputPort_str = Output_SIM_0_User_0 // Check the destination, as I'm not sure if it works like that int dst_inputPort = ((FnbNetPacket) pnp).getDestID(); String dst_inputPort_str = GridSim.getEntityName(dst_inputPort); // if neither the src or the dest of the packet are in the whitelist, then drop the packet FnbWhiteList whiteList = FnbWhiteList.getInstance(); if (!whiteList.checkList(dst_inputPort) && !whiteList.checkList(src_outputPort)) { /*********** // This was the very first version of the Fnbs insertPacketIntoQueue(pnp); return true; ***********/ if (makeRoomForPacket()) { // If we have been able of dropping a data packet, then we have room for this control packet insertPacketIntoQueue(pnp); } else { System.out.println("\n" + super.get_name() + ": 271 A control packet has been dropped.\n" + "src_output: " + src_outputPort_str + ". dst_inputPort: " + dst_inputPort_str + "\nHENCE, SIMULATION FINISHED AT SIM. TIME " + GridSim.clock()); //fw_write("MaxBufferSizeDuringSim, " + getMaxBufferSize() + "\n", // this.get_name() + "_MaxBufferSize.csv"); System.exit(1); // super.shutdownUserEntity(); // super.terminateIOEntities(); } } // If u want more info on the progress of sims, uncomment this. /******************** System.out.println(super.get_name() + ": packet dropped. Src: " + src_outputPort_str + ", Dst: " + dst_inputPort_str + ". Pkt num: " + ((FnbNetPacket) pnp).getPacketNum()); ********************/ // In this case, we will have to remove the packet, and // also, we will have to tell the source of the packet what has happened. // The source of a packet is the user/resource which sent it. // So, in order to contact the entity, we do it through its output port. // This is done through an event, not through the network int entity; if (src_outputPort_str.indexOf("User") != -1) { // if the src of the packet is an user, tell him what has happened // NOTE: this is a HACK job. "Output_" has 7 chars. So, // the idea is to get only the entity name by removing // "Output_" word in the outName string. String src_str = src_outputPort_str.substring(7); // for example, src_str = SIM_0_User_0 entity = GridSim.getEntityId(src_str); } else { // If the destination of the packet is the user, tell the user entity = GridSim.getEntityId(dst_inputPort_str); } int pktID = ((FnbNetPacket) pnp).getID(); // String input_src_str = "Input_" + src_str; // for example, input_src_str = Input_SIM_0_User_0 // int input_src = GridSim.getEntityId(input_src_str); int glID; if (pnp instanceof InfoPacket) { glID = 99999; } else { // check the user and the gl this packet belongs to glID = ((FnbNetPacket) pnp).getObjectID(); //filename = ((FnbNetPacket) pnp).getFileName(); } //super.send(src_outputPort, GridSimTags.SCHEDULE_NOW, super.sim_schedule(src_outputPort, GridSimTags.SCHEDULE_NOW, GridSimTags.FNB_PACKET_DROPPED, new FnbDroppedUserObject(entity, glID, isFile)); // We tell the output entity of the sender of this packet // that the packet has been dropped. pnp = null; // remove the packet. }
c3694ca1-1d38-492d-926e-ee666a12e7b5
4
@Override public void run() { while (!stopped && worker.isAlive()) { int nextLen = list.size(); if (lastLen != nextLen) { model.refreshDisplay(lastLen); lastLen = nextLen; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } model.refreshDisplay(-1); }
c2bcbd9d-0c96-48ce-9e3e-8ea778c7c2bb
5
@Test public void testServerSetQueueTimeoutErrorIndividualHashEx() { LOGGER.log(Level.INFO, "----- STARTING TEST testServerSetQueueTimeoutErrorIndividualHashEx -----"); boolean exception_other = false; String client_hash = ""; try { server2.setUseMessageQueues(true); } catch (TimeoutException e) { exception_other = true; } try { server1.startThread(); } catch (IOException | ServerSocketCloseException | FeatureNotUsedException e) { exception_other = true; } waitListenThreadStart(server1); try { client_hash = server2.addSocket("127.0.0.1", port); } catch (IOException | TimeoutException e) { exception_other = true; } waitSocketThreadAddNotEmpty(server2); waitSocketThreadState(server2, client_hash, SocketThread.CONFIRMED); waitMessageQueueAddNotEmpty(server2); waitMessageQueueState(server2, client_hash, MessageQueue.RUNNING); try { server2.setQueueTimeoutErrorIndividual("TEST", -1); } catch (HashNotFoundException e) { exception = true; } catch (FeatureNotUsedException | NullException | InvalidArgumentException e) { exception_other = true; } Assert.assertFalse(exception_other, "Caught an unexpected exception"); Assert.assertTrue(exception, "Successfully ran setQueueTimeoutErrorIndividual on server, should have received an exception"); LOGGER.log(Level.INFO, "----- TEST testServerSetQueueTimeoutErrorIndividualHashEx COMPLETED -----"); }
5c659fec-a51d-485b-afe9-0398f5b418e5
3
public void zipIt(String zipFile) { byte[] buffer = new byte[1024]; try { FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); System.out.println("[ZIP] Output to Zip : " + zipFile); for (String file : this.fileList) { //System.out.println("[ZIP] File Added : " + file); ZipEntry ze = new ZipEntry(file); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + file); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); } zos.closeEntry(); zos.close(); System.out.println("[ZIP] Done"); } catch (IOException ex) { System.err.println("[ZIP] [ERROR] " + ex); } }
a4116a16-2aad-4c3e-87ae-34c4e545b5ad
6
public void checkReproduce() { int currFishsSize = fishies.size(); //you may want to add additional new baby reproduction limits for (int i = 0; i < currFishsSize; i++) { for (int j = i + 1; j < currFishsSize; j++) { //don't want double reproduction if (fishies.get(i).collidesWithFish(fishies.get(j))) { if (fishies.get(i).canReproduceWithFish(fishies.get(j))) { ArrayList<Fish> babies = fishies.get(i).reproduceWithFish(fishies.get(j)); if (babies != null) { //Only add non-null babies if there is room if (fishies.size() < 1000) { // prevent heapsize crashes - limit # of fishies fishies.addAll(babies); } i++; // prevent current parent from having too much fun } } } } } }
29270dea-793f-4821-9f97-97bcecb9719d
9
public void exportItems(EDCHARACTER edCharakter, File outFile) throws IOException { CharacterContainer character = new CharacterContainer(edCharakter); PrintStream out = new PrintStream(new FileOutputStream(outFile), false, encoding); int pursecounter=0; String[] header = {"Name","Location","Weight","In Use","Kind","Class"}; out.println(generaterow(header)); for( ITEMType item : character.getAllNonVirtualItems() ) { List<String> row = new ArrayList<String>(); if( item instanceof COINSType ) { COINSType coins = (COINSType)item; String name = coins.getName(); if( name == null ) { name = "Purse #"+String.valueOf(++pursecounter); } else { if( name.isEmpty() ) name = "Purse #"+String.valueOf(++pursecounter); else name = "Purse "+name; } name += " (c:"+coins.getCopper()+" s:"+coins.getSilver()+" g:"+coins.getGold(); if( coins.getEarth()>0 ) name += " e:"+coins.getEarth(); if( coins.getWater()>0 ) name += " w:"+coins.getWater(); if( coins.getAir()>0 ) name += " a:"+coins.getAir(); if( coins.getFire()>0 ) name += " f:"+coins.getFire(); if( coins.getOrichalcum()>0 ) name += " o:"+coins.getOrichalcum(); name +=")"; row.add( name ); } else row.add( item.getName() ); row.add( item.getLocation() ); row.add( String.valueOf(item.getWeight()) ); row.add( item.getUsed().value() ); row.add( item.getKind().value() ); row.add( item.getClass().getSimpleName() ); out.println(generaterow(row)); } out.close(); }
001e05bc-549e-4123-952e-731bfb7c6795
8
@Override public BasicValue naryOperation(AbstractInsnNode insn, List<? extends BasicValue> values) throws AnalyzerException { BasicValue value = super.naryOperation(insn, values); int opcode = insn.getOpcode(); if (opcode == Opcodes.INVOKESTATIC && isClassBox(((MethodInsnNode) insn).owner) && ((MethodInsnNode) insn).name.equals("valueOf")) { int index = insnList.indexOf(insn); if (!boxingPlaces.containsKey(index)) { BoxedBasicValue boxedBasicValue = new BoxedBasicValue(value.getType(), values.get(0).getType(), insn); candidatesBoxedValues.add(boxedBasicValue); boxingPlaces.put(index, boxedBasicValue); } return boxingPlaces.get(index); } if (isUnboxing(insn) && values.get(0) instanceof BoxedBasicValue && value.getType().equals(((BoxedBasicValue)values.get(0)).getBoxedType())) { BoxedBasicValue boxedBasicValue = (BoxedBasicValue) values.get(0); boxedBasicValue.addInsn(insn); boxedBasicValue.setWasUnboxed(true); } return value; }
79efc248-6072-47d8-848a-84a350257ee8
2
public static boolean isFactorial(int n) { int i, j; i=1; j=1; do { if (i==n) return true; j++; i = i*j; } while (i<=n); return false; }
2acac7a0-7afa-4c52-8f8b-cb4b4e9e181a
8
public static int angleFromDirection(Utility.Direction direction){ switch(direction){ case NORTH: return 0; case NORTHEAST: return 45; case EAST: return 90; case SOUTHEAST: return 135; case SOUTH: return 180; case SOUTHWEST: return 225; case WEST: return 270; case NORTHWEST: return 315; default: System.out.println("******************INVALID ANGLE (angleFromDirection, Entity.java)*************"); return -1; } }
4f16d096-5160-461b-aaff-124f57a39766
2
public float getY(float x) { if (isVertical) { return Float.NaN; } else if (isHorizontal) { return value; } else { return this.k * x + b; } }
dfe5d4d5-f0dc-4219-ae71-8c33e918329f
9
private String getLine(int index) { // get the line that contains input[index]. Assume input[index] is at a // token, not // a white space or newline int i; if (input.length <= 1) { return ""; } i = index; if (i <= 0) { i = 1; } else if (i >= input.length) { i = input.length; } StringBuffer line = new StringBuffer(); // go to the beginning of the line while (i >= 1 && input[i] != '\n') { i--; } if (input[i] == '\n') { i++; } // go to the end of the line putting it in variable line while (input[i] != '\0' && input[i] != '\n' && input[i] != '\r') { line.append(input[i]); i++; } return line.toString(); }
2a6fba68-5feb-4db5-9dbd-169bef65bb13
4
@Override public boolean containsAll(Collection<?> c) { Iterator<?> iterator = c.iterator(); while (iterator.hasNext()) { if (!contains(iterator.next())) { return false; } } return true; }
625584d7-1a1a-4d67-8b1a-3c58a502aa3f
3
public void remove(int id) throws SQLException { Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.delete(this.getById(id)); session.getTransaction().commit(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка данных", JOptionPane.OK_OPTION); } finally { if (session != null && session.isOpen()) { session.close(); } } }
78571d25-30c3-4564-9841-c52629deef7d
5
private void boutonMondeDesTenebresMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_boutonMondeDesTenebresMouseClicked // TODO add your handling code here: if (partie.getMdt().isActif()) { if (!partie.getDieuActuel().isaJouerEnMondeDesTenebres() || ((partie.getDieuActuel().getNom().compareTo("Freyja") == 0 && ((Freyja) partie.getDieuActuel()).getaJouerEnMondeDesTenebres() < 2)&&Dieu.pouvoirDieu)) { partie.jouerMondeDesTenebres(page); verifFinTour(); } else { JOptionPane.showMessageDialog(page, "Vous avez déjà joué dans ce monde", "Yggdrasil", JOptionPane.INFORMATION_MESSAGE); } } else { JOptionPane.showMessageDialog(page, "Un géant bloc l'accés à ce monde", "Yggdrasil", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_boutonMondeDesTenebresMouseClicked
526b25f6-1e0a-4017-9faa-b430bb962783
1
private void loadImage(String path) { try { Image img = new Image(path); img.setFilter(Image.FILTER_NEAREST); spriteSheet = new SpriteSheet(img, x, y); } catch (SlickException e) { System.out.println("Cannot find Image for SpriteMap!...or maybe there's a problem with the filter, idk."); System.exit(0); } }
002f0863-9692-47c8-b80d-ad34de6ac2cd
9
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final Set<MOB> h=properTargets(mob,givenTarget,false); if(h==null) { mob.tell(L("There doesn't appear to be anyone here worth speeding up.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { if(mob.location().show(mob,null,this,somanticCastCode(mob,null,auto),auto?"":L("^S<S-NAME> wave(s) <S-HIS-HER> arms and speak(s) quickly.^?"))) for (final Object element : h) { final MOB target=(MOB)element; final CMMsg msg=CMClass.getMsg(mob,target,this,somanticCastCode(mob,target,auto),null); if((mob.location().okMessage(mob,msg)) &&(target.fetchEffect("Spell_Haste")==null) &&(target.fetchEffect("Spell_MassHaste")==null)) { mob.location().send(mob,msg); mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> speed(s) up!")); final Spell_Haste haste=new Spell_Haste(); haste.setProficiency(proficiency()); haste.beneficialAffect(mob,target,asLevel,0); } } } else return beneficialVisualFizzle(mob,null,L("<S-NAME> wave(s) <S-HIS-HER> arms and speak(s) quickly, but the spell fizzles.")); // return whether it worked return success; }
2a319549-18c4-4928-850e-3a890e93deb2
7
private static Map<String, Field> commontField(Cg cg, Map<String, Field> fieldMap){ Pattern commentPattern = Pattern.compile("\\s*COMMENT\\s+?ON\\s+?COLUMN\\s+?.*\\.(.*) IS '(.*)'\\s*;"); String tableSql = formartSql(cg.getTableSql()); String[] temps=tableSql.split("\r|\n"); List<String> tempList = new ArrayList<String>(); for(int i=0;i<temps.length;i++){ if(!(temps[i].trim().length()==0)){ tempList.add(temps[i]); } } for(int i=0;i<tempList.size();i++){ // System.out.println(temps[i].trim()); String commentStr = tempList.get(i); //判断注释是否折行 String temp = tempList.get(i).trim().toLowerCase(); if(temp.startsWith("comment")){ if(!temp.endsWith(";")){ // System.out.println("tempList.get(i+1)---------" + tempList.get(i+1)); commentStr = commentStr + " " +tempList.get(i+1); // System.out.println("----xxx-----" + commentStr); i++; } } // System.out.println("commentStr---------" + commentStr); Matcher matcher = commentPattern.matcher(commentStr.trim().toUpperCase()); if(matcher.matches()){ String name = matcher.group(1).trim(); String comment = matcher.group(2); System.out.println(name + " -----comment----- " + comment); if(fieldMap.containsKey(name)){ Field field = fieldMap.get(name); field.setComment(comment); fieldMap.put(name, field); } } } return fieldMap; }
6f9e7612-0ff7-4600-8841-49219cf0ef9d
0
private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(execCommand); stream.writeObject(remoteCallObjectType); }
ae468ec7-79f3-49b0-b706-575e4d2667d0
4
@Override public void run() { ResultSet ids = GetCitedIDS(); String insert = "insert into citedList(paperid,citedlist) values(?,?)"; int num = 0; try { PreparedStatement statement = sqLconnection.conn .prepareStatement(insert); while (ids.next()) { int id = ids.getInt("citationid"); if(!isIDexist(id)) { String list = getCitedList(id); statement.setInt(1, id); statement.setString(2, list); statement.addBatch(); num++; if (num % 1000 == 0) { statement.executeBatch(); statement.clearBatch(); System.out.println("current num: " + num); } }else continue; } statement.executeBatch(); statement.clearBatch(); statement.close(); ids.close(); this.sqLconnection.disconnectMySQL(); } catch (SQLException e) { e.printStackTrace(); } }
cccc856f-f117-4ac1-a89e-0a726bb786ad
2
public void deleteItem(int slot) { if(slot >= 0 && slot < items.length) items[slot] = null; }
9af76934-4880-4f5e-8d2d-6ba61b0a1e57
7
public void setSID(int sid) { switch (sid) { case RESID_6581: case RESID_8580: if (!(sidChip instanceof RESIDChip)) { if (sidChip != null) sidChip.stop(); sidChip = new RESIDChip(cpu, audioDriver); } ((RESIDChip) sidChip).setChipVersion(sid); break; case JACSID: if (!(sidChip instanceof SIDChip)) { if (sidChip != null) sidChip.stop(); sidChip = new SIDChip(cpu, audioDriver); } break; } }
7072a6c5-cd3b-4bcb-8d81-6e4911111aee
4
@Override public ArrayList<STTPoint> getWrappedData() { ArrayList<STTPoint> pointList = new ArrayList<STTPoint>(); try{ URL url = new URL(getWrapperParams().getSource()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String fileLine; while((fileLine = in.readLine()) != null){ if (fileLine.contains(",")){ String[] filePieces = fileLine.split(","); //assuming the file is in this <lat, long, timestamp, theme, value> specified format LatLong location = new LatLong(Double.parseDouble(filePieces[0]),Double.parseDouble(filePieces[1])); Timestamp time = Timestamp.valueOf(filePieces[2]); //this depends on how the time is formatted as a string, here I'm assuming JDBC timestamp escape format for simplicity double value = Double.parseDouble(filePieces[4]); WrapperParams params = new WrapperParams(getWrapperParams().getSource(),filePieces[3]); STTPoint point = new STTPoint(value,time,location,params); pointList.add(point); }else{ throw new IllegalArgumentException("The file is not in CSV format."); } } in.close(); }catch(IllegalArgumentException e){ System.out.println("Cannot open this kind of file."); }catch(Exception ex){ System.out.println("The file could not be opened. The URL may be bad or busy."); } return pointList; }
f3993324-5329-41e2-b75c-c2be70aaaa11
0
public static void main(String[] args) { new Run(); }
129295d8-5b15-4158-9941-f283286682b5
2
public Item dequeue() { if (isEmpty()) throw new NoSuchElementException(); if (size() < N / 2) q = resize(N / 2); // Remove from the front. Item t = q[front]; front = (front + 1) % N; nItems--; return t; }
272ccf9b-9251-404d-ba62-f22de2c18328
5
@Override public final void mouseReleased(final MouseEvent e) { synchronized (this.abcMapPlugin.state) { if (this.abcMapPlugin.state.loadingMap) { return; } while (this.abcMapPlugin.state.running) { try { this.abcMapPlugin.state.wait(); } catch (final InterruptedException ie) { ie.printStackTrace(); } } if (this.abcMapPlugin.state.upToDate) { this.abcMapPlugin.state.io.endProgress("Creating abc"); } this.abcMapPlugin.state.upToDate = false; this.abcMapPlugin.state.running = true; } this.abcMapPlugin.taskPool.addTask(new Runnable() { @Override public void run() { final Object result = TestButtonMouseListener.this.abcMapPlugin.caller .call_back(null, null, TestButtonMouseListener.this.abcMapPlugin .size()); final boolean success = result != null; synchronized (TestButtonMouseListener.this.abcMapPlugin.state) { TestButtonMouseListener.this.abcMapPlugin.state.notifyAll(); TestButtonMouseListener.this.abcMapPlugin.state.upToDate = success; TestButtonMouseListener.this.abcMapPlugin.state.running = false; if (!success) { TestButtonMouseListener.this.abcMapPlugin.state.label .setText("Creating abc failed"); } else { assert result != null; final String critical = result.toString(); TestButtonMouseListener.this.abcMapPlugin.state.label .setText("The abc is up-to-date - " + critical); } } } }); e.consume(); }
a3217498-c87c-4fe8-9bc8-bb8933e38c19
0
public void giveWarning(Account account){ account.giveWarning(); }
f33a3b12-7d64-4ba1-95a7-02cf83d997f3
1
@Test public void branchInstrInvalidFormatSKZ() { //Tests SKZ won't accept fields try { instr = new BranchInstr(Opcode.SKZ, 70); } catch (IllegalStateException e) { System.out.println(e.getMessage()); } assertNull(instr); //Instruction should not be instantiated with invalid arguments }
b8c7c3f3-1848-4329-8eb0-16d761503bba
1
public static ArrayList<QuizTakenAchievement> getAllAchievements() { if (allAchievements.isEmpty()) loadAllAchievements(); return allAchievements; }
06eda4f0-f7a7-4c1a-ad94-d2b72abe2163
0
public Dictionary(String path) { this.path = path; this.trie = new Trie(); this.sortedTrie = new Trie(); }
9e2c807d-a24a-40d3-8d7f-7bf7a2ec2615
1
private void fireIOException(IOException ioe) { for (PeerActivityListener listener : this.listeners) { listener.handleIOException(this, ioe); } }
8abf5fca-d8cf-49e2-ac19-28f05165471a
8
public void simulateOneStep() { Random randomgetal = new Random(); step++; if(randomgetal.nextDouble() <= getHunterCreationProb()) { createHunter(); } createHunter(); // Provide space for newborn animals. List<Actor> newActors = new ArrayList<Actor>(); // Let all rabbits act. for(Iterator<Actor> it = actors.iterator(); it.hasNext(); ) { Actor actor = it.next(); actor.act(newActors); if(! actor.isAlive()) { it.remove(); } } // Add the newly born foxes, rabbits, hunters and Korenwolfs to the main lists. actors.addAll(newActors); int Number_of_rabbits = 0; int Number_of_foxes = 0; int Number_of_korenwolfs = 0; int Number_of_hunters = 0; for(Iterator<Actor> it = actors.iterator(); it.hasNext(); ) { Actor actor = it.next(); if(actor instanceof Rabbit){ Number_of_rabbits++; } else if(actor instanceof Fox){ Number_of_foxes++; } else if(actor instanceof Korenwolf){ Number_of_korenwolfs++; } else if(actor instanceof Hunter){ Number_of_hunters++; } } Rabbit.NUMBER_OF_RABBITS = Number_of_rabbits; Fox.NUMBER_OF_FOXES = Number_of_foxes; Korenwolf.NUMBER_OF_KORENWOLFS = Number_of_korenwolfs; Hunter.NUMBER_OF_HUNTERS = Number_of_hunters; view.showStatus(step, field); }
d0c108fe-6b0a-4dc3-9685-fb9bebe5e399
2
private static Integer getNextInstanceOfNegation(LinkedList<Token> tokens, int startingAtIndex) { for(int i=startingAtIndex; i<tokens.size();i++) { Token t = tokens.get(i); if(t.getUnderlyingObject()==Operation.NEGATION) { return i; } } return null; }
0476d5b2-d222-4844-986c-dd8af854601a
1
private void readbuttonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_readbuttonMouseClicked // TODO add your handling code here: int address=dec.NumberParser(readaddress.getText()); if(address!=-100000){ readvalue.setText(""+mm.readMemory(address)); readaddress.setText(""+address%65536); } }//GEN-LAST:event_readbuttonMouseClicked
a9f67adb-227a-4b25-b5e1-523e19f35ba9
1
public boolean equals(Object configuration) { Configuration config = (Configuration) configuration; if (parent != config.parent) return false; return config.myCurrentState == myCurrentState; }
672d8d81-6752-4498-bc4d-d2dde62ac207
5
public double calculateProbability(String s) { int stringLength = s.length(); double probability = 1; for (int i = 0; i < stringLength; i++) { Character character = s.charAt(i); switch (character) { case 'A': probability = probability * this.A.get(i); break; case 'C': probability = probability * this.C.get(i); break; case 'G': probability = probability * this.G.get(i); break; case 'T': probability = probability * this.T.get(i); break; } } return probability; }
22a219eb-e812-45cc-ad03-8468c346b1ce
8
@Override public Problem parse(String URL) throws ParserException, InterruptedException { URL = URL.trim(); FilterBean fb = new FilterBean(); fb.setURL(URL); // extract problem name fb.setFilters(new NodeFilter[] { new CssSelectorNodeFilter("div.header"), new CssSelectorNodeFilter("div.title")}); String problemName = fb.getText(); if (problemName.isEmpty()) { throw new ParserException("Problem name not extracted (probably incorrect url)."); } problemName = String.valueOf(problemName.charAt(0)); if (Thread.interrupted()) { throw new InterruptedException(); } // extract inputs ArrayList<String> inputs = extractInputsOrOutputs(fb, "div.input"); if (Thread.interrupted()) { throw new InterruptedException(); } // extract outputs ArrayList<String> outputs = extractInputsOrOutputs(fb, "div.output"); if (inputs.size() != outputs.size()) { throw new ParserException("Number of inputs is not equal to number of outputs."); } if (Thread.interrupted()) { throw new InterruptedException(); } // extract time limit fb.setFilters(new NodeFilter[] {new CssSelectorNodeFilter("div.time-limit")}); String timeLimitText = fb.getText(); // should be "time limit per testXXX second" Pattern pattern = Pattern.compile("\\d+(\\.\\d+)?"); Matcher matcher = pattern.matcher(timeLimitText); int timeLimit = Testcase.DEFAULT_TIME_LIMIT; if (matcher.find()) { timeLimit = (int) (Double.valueOf(matcher.group()) * 1000); } TestcaseSet testcaseSet = new TestcaseSet(); for (int i = 0; i < inputs.size(); ++i) { testcaseSet.add(new Testcase(inputs.get(i).trim(), outputs.get(i).trim(), timeLimit)); } if (Thread.interrupted()) { throw new InterruptedException(); } Problem problem = new Problem(problemName, testcaseSet, SupportedSites.CodeForces); return problem; }
0dead3d8-78cb-4eb7-9356-cc5d4cbf4114
1
public void visit_ifnull(final Instruction inst) { stackHeight -= 1; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } }
63d887b1-8611-4b37-a684-5ff0c1df27a1
0
@Before public void setUp() throws Exception { createInjector( new QuartzModule() { @Override protected void schedule() { scheduleJob( TimedTask.class ); } } ).getMembersInjector( GuartzTimerTestCase.class ).injectMembers( this ); }
b981868e-dcc6-45b1-9832-f9b411dcf771
5
public String toString() { String res = this.a==0? "": ""+this.a; switch(this.b) { case 0: return res; case 1: return res + "+w"; case -1: return res + "-w"; default: return res + (this.b>0? "+": "") + this.b + "w"; } }