method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
2d129369-5a4c-4c78-bed5-06979fecb1f3
6
@Override public void printBPB(javax.swing.JTextArea a, javax.swing.JTextArea b) { b.append("\t\t 0\t 1\t 2\t 3\t 4\t 5\t 6\t 7\t\t 8\t 9\t A\t B\t C\t D\t E\t F"); for (i = 0; i < bytes_per_Sector; i++) { if (i % 16 == 0) { b.append(String.format("\n%07X0\t", address++)); } else if (i % 8 == 0) { b.append("\t"); } b.append(Utils.hex(content[i]) + "\t"); } a.append(String.format("%-22s\t%s", "Jump Instruction", jump_instruction)); a.append(String.format("\n%-22s\t\t%s", "OEM", OEM_name)); a.append(String.format("\n%-22s\t%d", "Bytes per Sector", bytes_per_Sector)); a.append(String.format("\n%-22s\t%d", "Sectors per Cluster", sectors_per_cluster)); a.append(String.format("\n%-22s\t%d", "Reserved Sectors", reserved_sectors)); a.append(String.format("\n%-22s\t%d", "Number of FAT Copies", number_of_FAT_copies)); a.append(String.format("\n%-22s\t%d", "Root Directory Entries", number_of_root_directory_entries)); if (total_sectors == 0) { a.append(String.format("\n%-22s\t%d", "Total Sectors", total_sectorsL)); } else { a.append(String.format("\n%-22s\t%d", "Total Sectors", total_sectors)); } a.append(String.format("\n%-22s\t%s", "Media Descriptor", media_descriptor)); if (sectors_per_FAT == 0) { a.append(String.format("\n%-22s\t%d", "Sectors per FAT", sectors_per_FATL)); } else { a.append(String.format("\n%-22s\t%d", "Sectors per FAT", sectors_per_FAT)); } a.append(String.format("\n%-22s\t%d", "Sectors per Track", sectors_per_track)); a.append(String.format("\n%-22s\t%d", "Number of Heads", number_of_heads)); if (hidden_sectors == 0) { a.append(String.format("\n%-22s\t%d", "Hidden Sectors", hidden_sectorsL)); } else { a.append(String.format("\n%-22s\t%d", "Hidden Sectors", hidden_sectors)); } a.append(String.format("\n%-22s\t%d", "FAT Mirroring disabled", mirror_flags)); a.append(String.format("\n%-22s\t%d", "FileSystem Version", fs_version)); a.append(String.format("\n%-22s\t%d", "First Cluster Location", first_cluster)); a.append(String.format("\n%-22s\t%d", "FileSystem Info Sector", fs_info)); a.append(String.format("\n%-22s\t%d", "Backup BootSector", backup_bootsector)); a.append(String.format("\n%-22s\t%d", "Logical Drive Number", logical_drive_number)); a.append(String.format("\n%-22s\t%X", "Extended Signature", extened_signature)); a.append(String.format("\n%-22s\t%d", "Serial Number", serial_number)); a.append(String.format("\n%-22s\t\t%s", "Signature", signature)); }
2290a05e-63ba-4d3a-a6db-69ac119274fb
0
public CheckExit() { super("Are you sure?"); this.setResizable(false); this.setLayout(new BorderLayout()); JLabel label=new JLabel("Do you really want to exit?"); label.setHorizontalAlignment(SwingConstants.CENTER); this.add(label, BorderLayout.CENTER); JPanel yesNo = new JPanel(); yesNo.setLayout(new FlowLayout()); JButton yes = new JButton("Yes"); yes.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); yesNo.add(yes); JButton no= new JButton("No"); no.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); } }); yesNo.add(no); this.add(yesNo, BorderLayout.SOUTH); this.setSize(300, 100); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setLocationRelativeTo(null); }
93c4e22a-4b3b-4128-a2ff-2fec5439cf47
5
public void run() { while (true) { try { //get the data from the client byte[] receivedData = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receivedData, receivedData.length); datagramSocket.receive(receivePacket); String clientRequest = new String(receivePacket.getData()); System.out.println(clientRequest); //send the client the size of the message byte[] sendData = new byte[1024]; sendData = ("" + clientRequest.length()).getBytes(); //get the ip and port InetAddress clientIpAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientIpAddress, port); datagramSocket.send(sendPacket); //start sending the message int offset = 0; int length = (int) clientRequest.length(); sendData = new byte[1024]; datagramSocket.setSoTimeout(500); while (offset <= length) { offset += 1024; byte[] ack = new byte[0]; while (ack.length == 0) { /* * this is going to try and send the same data packet over * and over again until it receives an "acknowledgment" from * the client. The ack, in this case, is simply a non-empty * byte array; If nothing is received from the * client within the specified timeout (ms), we catch an * exception and try again. */ try { sendPacket = new DatagramPacket(sendData, sendData.length, clientIpAddress, port); datagramSocket.send(sendPacket); System.out.println("packet#: " + offset / 1024); datagramSocket.receive(receivePacket); ack = receivePacket.getData(); } catch (SocketTimeoutException ste) { System.out.println("Ack not received, resending..."); } } } datagramSocket.setSoTimeout(0); System.out.println("Message transfer complete: " + clientRequest); } catch (IOException ex) { ex.printStackTrace(); } } }
0b6aa6dd-9987-43a3-a4ec-1ac7cbe30bde
5
public static void printFields(Class<?> c){ display2.append("フィールド\r\n"); Field[] declaredfields = c.getDeclaredFields(); Field[] fields = c.getFields(); ArrayList<Field> fieldList = new ArrayList<Field>(fields.length); for(int i = 0; i < fields.length; i++){ fieldList.add(fields[i]); } for(int i = 0; i < declaredfields.length; i++){ if(!fieldList.contains(declaredfields[i])){ fieldList.add(declaredfields[i]); } } Field[] allFields = new Field[fieldList.size()]; for(int i = 0; i < allFields.length; i++){ allFields[i] = fieldList.get(i); } printMembers(allFields); }
44951903-3e46-4c70-9243-0c545211839d
2
public void setRectXOR(int[] buffer, CPRect rect) { CPRect r = new CPRect(0, 0, width, height); r.clip(rect); int w = r.getWidth(); int h = r.getHeight(); for (int j = 0; j < h; j++) { for (int i = 0; i < w; i++) { data[(j + r.top) * width + i + r.left] = data[(j + r.top) * width + i + r.left] ^ buffer[i + j * w]; } } }
0e8ff842-c279-4475-897d-34b37229e07b
6
public boolean execute(CommandSender sender, String[] args) { if (!(sender instanceof ConsoleCommandSender)) { return true; } String command = args[0]; if (command.equalsIgnoreCase("getconfig")) { return GetConfig((ConsoleCommandSender)sender, args); } else if (command.equalsIgnoreCase("setconfig")) { return SetConfig((ConsoleCommandSender)sender, args); } else if (command.equalsIgnoreCase("daocachestats")) { return GetDaoCacheStats((ConsoleCommandSender)sender, args); } else if (command.equalsIgnoreCase("daocachestatsslow")) { return GetSlowDaoCacheStats((ConsoleCommandSender)sender, args); } else if (command.equalsIgnoreCase("forcecacheflush")) { return ForceCacheFlush((ConsoleCommandSender)sender, args); } return false; }
6e90a0c7-f70b-49eb-86b1-ab3833715722
8
private void shutdown(){ // Escribo archivo pozos if(!getNombreArchivoPozos().equals("")){ escribirArchivoPozos(); } // Escribo archivo multilang if(!getNombreArchivoMultilang().equals("")){ escribirArchivoMultilang(); } imprimirDebug("Links encontrados:\n"); imprimirDebug(LinksToString()); // Imprimo motivo de fin if(recursosAgotados) { System.out.print("\nPrograma finalizado por agotar recursos (memoria)\n"); } else { System.out.print("\nPrograma finalizado por no tener mas links para evaluar\n"); } // Imprimo mails if(mails.isEmpty()) { System.out.print("No se detectaron mails\n"); } else{ System.out.print("Mails detectados (" + getMails().size() + "):\n"); for(String mail : getMails()) { System.out.println(mail); } } imprimirDebug("Links recorridos: " + (allLinks.size() - pendingLinks.size())); if(recursosAgotados) { imprimirDebug("Links que quedaron pendientes: " + pendingLinks.size()); } imprimirDebug("Links repetidos: " + cantidadRepetidos); imprimirDebug("Links que no son HTML: " + cantidadNoPagina); if (!nombreArchivoPozos.isEmpty()) imprimirDebug("Links que son pozos: " + pozos.size()); if (!nombreArchivoMultilang.isEmpty()) imprimirDebug("Links que son multilang: " + multilang.size()); // TODO llamar imprimirDebug con estadisticas, lista errores, etc }
1ce97608-c57f-4e7b-a77e-1ce7aa1747f4
7
protected static String getLine() throws IOException{ String input; if (replayIn != null && controlInput) { // get a packet from the replay input file Packet line; try { line = getPacket(); } catch (CorruptPacketException e) { throw new ReplayException("Error while reading replay file"); } // verify that the packet is a user packet if (Replay.isUserPacket(line)) { input = Utility.byteArrayToString(line.getPayload()); } else { throw new Replay.ReplayException("Expected user input, got: " + line.toString()); } System.out.println("Replaying user input: '" + input + "'"); } else { // get a line from the keyboard input = keyboard.readLine(); } if (replayOut != null) { // record the user input to the replay output file try { if (input != null) { replayOut.write(Replay.getUserPacket(input).pack()); } else { replayOut.write(Replay.getUserPacket("").pack()); } } catch (IOException e) { throw new ReplayException("Error while writing replay file"); } } return input; }
f59cd7bd-c28c-4f4b-992d-c4066352bab2
2
@Test public void testNonExistingClass() throws Exception { PersistenceManager pm = new PersistenceManager(driver, database, login, password); // drop all tables pm.dropTable(Object.class); pm.close(); pm = new PersistenceManager(driver, database, login, password); // test deleting object of non-existing class assertEquals(0, pm.deleteObjects(NonExistingClass.class, new All())); // test counting objects of non-existing class assertEquals(0, pm.getCount(NonExistingClass.class, new All())); assertEquals(0, pm.getCount(new NonExistingClass())); // test sum of object of non-existing class assertEquals(0.0,pm.calculateAggregate(NonExistingClass.class, new Sum("getFoo"), new All())); //test max, min, avg of non-existing class AggregateFunction[] functions = new AggregateFunction[]{new Maximum("getFoo"),new Minimum("getFoo"),new Average("getFoo")}; Number[] numbers = pm.calculateAggregate(NonExistingClass.class, functions, new All()); assertEquals(3,numbers.length); for(int x = 0;x<numbers.length;x++) { assertTrue("Result is not Double but "+ numbers[x].getClass(),numbers[x] instanceof Double); assertTrue(((Double)numbers[x]).isNaN()); } functions = new AggregateFunction[]{new Maximum("getBar"),new Minimum("getBar"),new Average("getBar")}; numbers = pm.calculateAggregate(NonExistingClass.class, functions, new All()); assertEquals(3,numbers.length); for(int x = 0;x<numbers.length-1;x++) { assertTrue("Result is not Float but "+ numbers[x].getClass(),numbers[x] instanceof Float); assertTrue(((Float)numbers[x]).isNaN()); } assertTrue("Result is not Double but "+ numbers[2].getClass(),numbers[2] instanceof Double); assertTrue(((Double)numbers[2]).isNaN()); // test getting objects of non-existing class List<NonExistingClass> res = pm.getObjects(NonExistingClass.class, new All()); assertEquals(0, res.size()); res = pm.getObjects(new NonExistingClass()); assertEquals(0, res.size()); pm.close(); }
62250c64-8fac-4353-8e66-9e98b7f77f27
4
private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); for (PropertyChangeListener l : getPropertyChangeListeners()) { if (l instanceof Serializable) { s.writeObject(l); } } for (VetoableChangeListener l : getVetoableChangeListeners()) { if (l instanceof Serializable) { s.writeObject(l); } } s.writeObject(null); }
29ae7510-11a9-4918-ba9f-601aaf5855a3
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SpeciesReference other = (SpeciesReference) obj; if (species == null) { if (other.species != null) return false; } else if (!species.equals(other.species)) return false; return true; }
7658a9c6-67cb-4dd6-b794-143a80a3b559
7
public Room getStep(String direction){ Room locRoom = (Room) getLoc(); Map map = getWorld().getMap(); Cell locCell = map.getCell(locRoom); int x = locCell.getX(); int y = locCell.getY(); int z = locCell.getZ(); switch (direction){ case "north": y += 1; break; case "south": y -= 1; break; case "east": x += 1; break; case "west": x -= 1; break; case "up": z += 1; break; case "down": z -= 1; break; } Cell newCell = new Cell(x,y,z); Room newRoom = map.getRoom(newCell); if(newRoom != null){ return newRoom; } else { GameHelper.output("Null room"); return null; } };
b7b6fc23-bdac-49e5-bfd6-2643375f1b23
7
public boolean clickContinue() { final Component component = getContinue(); if (!component.valid()) { return false; } if (component.valid() && ((Random.nextBoolean() && component.contains(ctx.input.getLocation()) && ctx.input.click(true)) || component.click())) { if (Condition.wait(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return visible("Please wait..."); } }, 50, 5)) { Condition.wait(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return !visible("Please wait..."); } }, 25, 10); } else { Condition.sleep(250); } return true; } return false; }
5718e17b-9f5e-4a0d-8c26-080137704321
7
private static void zipSingleFile(ZipOutputStream out, File file, String entryName, WithProgressAdapter progress, Progress zipProgress) throws ZipException, IOException { ZipEntry entry = new ZipEntry(entryName); if (file.isDirectory()) { entryName += "/"; out.putNextEntry(entry); out.closeEntry(); for (File f : file.listFiles()) { zipSingleFile(out, f, entryName + f.getName(), progress, zipProgress); } if (zipProgress != null) { zipProgress.onFolder(entry, file); } } else { if (zipProgress != null) { zipProgress.onStart(entry, file); } out.putNextEntry(entry); // "Copy" the file InputStream is = new BufferedInputStream(new FileInputStream(file)); try { int len = 0; byte[] buffer = new byte[8192]; while ((len = is.read(buffer)) >= 0) { if (progress != null) { progress.increment(len); } out.write(buffer, 0, len); } } finally { is.close(); } out.closeEntry(); if (zipProgress != null) { zipProgress.onFinish(entry, file); } } }
c926d42c-3227-4c53-89b9-8ea27b796817
1
public void print() { for (int i = 0; i < id.length; i++) { System.out.print(id[i] + " "); } System.out.println(); }
c8329914-5e2a-476d-9f94-71e0e428d754
3
private boolean zzRefill() throws java.io.IOException { /* first: make room (if you can) */ if (zzStartRead > 0) { System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead-zzStartRead); /* translate stored positions */ zzEndRead-= zzStartRead; zzCurrentPos-= zzStartRead; zzMarkedPos-= zzStartRead; zzPushbackPos-= zzStartRead; zzStartRead = 0; } /* is the buffer big enough? */ if (zzCurrentPos >= zzBuffer.length) { /* if not: blow it up */ char newBuffer[] = new char[zzCurrentPos*2]; System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); zzBuffer = newBuffer; } /* finally: fill the buffer with new input */ int numRead = zzReader.read(zzBuffer, zzEndRead, zzBuffer.length-zzEndRead); if (numRead < 0) { return true; } else { zzEndRead+= numRead; return false; } }
e98f3a0c-cf47-49a2-825c-dc36f544957c
2
public static boolean checkLibrary(Library library) throws ModelingException { for(String elementName : library.library.keySet()) { Element element = library.library.get(elementName); if(!element.check()) { throw new ModelingException(0x50, elementName); } } return true; }
de8a1483-84b4-476d-ba0b-036a089a4bbb
0
public static CarListJsonConverter getInstance() { return instance; }
62389be1-404f-48b2-85a3-5b7c44788ac1
9
@Override public void actionPerformed(ActionEvent e) { Object s = e.getSource(); if (s==Return) { MenuHandler.CloseMenu(); } else if (s==Prev) { Game.edit.ChangePlayer(false); } else if (s==Next) { Game.edit.ChangePlayer(true); } for (int i = 0; i < Game.displayU.size(); i++) { if (s==Units[i]) { Game.edit.pick = engine.Editor.Type.UNIT; Game.edit.id = i; MenuHandler.CloseMenu(); } } for (int i = 0; i < Game.displayB.size(); i++) { if (s==Cities[i]) { Game.edit.pick = engine.Editor.Type.CITY; Game.edit.id = i; MenuHandler.CloseMenu(); } } for (int i = 0; i < Game.map.tiles.size(); i++) { if (s==Tiles[i]) { Game.edit.pick = engine.Editor.Type.TILE; Game.edit.id = i; MenuHandler.CloseMenu(); } } }
668dd5a1-a56c-45e1-a073-425667d9b842
1
public void showDebugGrid(boolean draw) { if(draw == true) { DRAW_DEBUG_GRID = true; } else { DRAW_DEBUG_GRID = false; } }
0c8e42c9-2937-4221-abd2-9876b4081d1e
3
void parseDocument() throws DaoException { try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = null; parser = factory.newSAXParser(); if (file != null) { parser.parse(file, this); } } catch (Exception e) { if (log.isEnabledFor(Level.ERROR)) { log.error(e); } throw new DaoException(e); } }
a93347e9-fd49-4911-8924-94a922c19a4e
3
@Override public boolean validateAndStartScriptExecutable(ScriptExecutable pScriptExecutable, int pStatementSequence) { if(pScriptExecutable instanceof ScriptSQL && isRerun()){ try { ScriptSQL lSQL = (ScriptSQL) pScriptExecutable; boolean lRunAllowed = validateScriptExecutable(lSQL); mScriptRunner.addNoExecPatchStatementLog(lSQL, lRunAllowed); } catch (SQLException e) { throw new ExFatalError("Failed when validating script executable", e); } } //AWLAYS RETURN FALSE HERE - otherwise statement will actually run return false; }
3d104905-0077-45c8-ae80-0a9c37efd5be
6
private void setCell(int c, int x, int y, BufferedImage myBoard) { Point pos = window.getPos(x, y);new Point(x, y); if(Color.isBlue(c) && Color.isOne(pos, myBoard)) { //Cell is 1 board[x][y] = 1; } else if(Color.isTwo(pos, myBoard)) { //Cell is 2 board[x][y] = 2; } else if(Color.isThree(pos, myBoard)) { //Cell is 3 board[x][y] = 3; } else if(Color.isFour(pos, myBoard)) { //Cell is 4 board[x][y] = 4; } else if(Color.isGray(c)) //Empty Cell board[x][y] = -1; }
3d5692f2-79dc-4c6a-b4d5-b1c811b5cf38
9
public int longestConsecutive(int[] num) { if (num == null || num.length == 0) return 0; if (num.length == 1) return 1; HashMap<Integer, Boundary> map = new HashMap<Integer, Boundary>(); int maxlen = 0; for (int i = 0; i < num.length; i++) { if (map.containsKey(num[i])) continue; else { Boundary left = map.get(num[i] - 1); Boundary right = map.get(num[i] + 1); Boundary cur = new Boundary(); if (left != null) cur.left = left.left; else cur.left = num[i]; if (right != null) cur.right = right.right; else cur.right = num[i]; if (left != null) map.get(left.left).right = cur.right; if (right != null) map.get(right.right).left = cur.left; maxlen = Math.max(maxlen, cur.right - cur.left + 1); map.put(num[i], cur); } } return maxlen; }
5a545e09-c378-45db-b82d-2a005bf2c483
5
@Override public void run() { List<File> rawFiles = null; Processor processor = null; while (true) { if (null != (rawFiles = rawEntityStore.getRawFiles())) { for (File file : rawFiles) { processor = new EmployeeProcessor(file); if (null != processor.getEntityList()) { PoolExecutor.addProcessor(processor); } } } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
043f5e5e-3106-40cc-8f3e-02bcbc948056
0
public User getUser() { return user; }
341570f2-f8f5-4989-b874-b4719cee3b57
1
private void display_list_content(myDataList myLink_list) { data my_Data; for (int i = 0; i < myLink_list.size(); i++) { my_Data = ((data) myLink_list.get(i)); System.out.println(my_Data.getChar() + " " + my_Data.get_probability() + " " + my_Data.isFlag() + " " + my_Data.getBinary_Code()); } }
c6a38d7f-174f-4c48-afef-c3d6803349c0
0
public synchronized boolean stopped() { debug("Route.stopped() returning " + stopped); return stopped; }
672fc62a-53ab-4a13-b733-48eb09ea2f01
3
public void insertSupplierData(order tempOrder) throws SQLException{ try { databaseConnector = myConnector.getConnection(); SQLQuery = "INSERT INTO familydoctor.order "+"VALUES(?,?,?,?,?)"; PreparedStatement preparedStatement = databaseConnector.prepareStatement(SQLQuery); preparedStatement.setInt(1, 0); preparedStatement.setString(2, tempOrder.getSupplierName()); preparedStatement.setString(3, tempOrder.getCurrentDate()); preparedStatement.setString(4, tempOrder.getOrderInfo()); preparedStatement.setFloat(5,tempOrder.getOrderAmount()); preparedStatement.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { if (stmnt != null) { stmnt.close(); } if (databaseConnector != null) { databaseConnector.close(); } } }
381b2d41-ac34-451d-bffd-6e8affbebeff
8
boolean isReference(String ent) { if (!(ent.charAt(0) == '&') || !ent.endsWith(";")) { return false; } if (ent.charAt(1) == '#') { if (ent.charAt(2) == 'x') { try { // CheckStyle:MagicNumber OFF Integer.parseInt(ent.substring(3, ent.length() - 1), HEX); // CheckStyle:MagicNumber ON return true; } catch (NumberFormatException nfe) { return false; } } else { try { Integer.parseInt(ent.substring(2, ent.length() - 1)); return true; } catch (NumberFormatException nfe) { return false; } } } String name = ent.substring(1, ent.length() - 1); for (int i = 0; i < knownEntities.length; i++) { if (name.equals(knownEntities[i])) { return true; } } return false; }
29627216-80ff-43c3-b48c-b78eb6799295
4
private void notifyListeners(final CycLeaseManagerReason cycLeaseManagerReason) { //// Preconditions assert cycLeaseManagerReason != null : "cycLeaseManagerReason must not be null"; assert listeners != null : "listeners must not be null"; assert cycAccess != null : "cycAccess must not be null"; if ((cycLeaseManagerReason == CycLeaseManager.CYC_COMMUNICATION_ERROR) || (cycLeaseManagerReason == CycLeaseManager.CYC_DENIES_THE_LEASE_REQUEST) || (cycLeaseManagerReason == CycLeaseManager.CYC_DOES_NOT_RESPOND_TO_LEASE_REQUEST)) { hasValidLease = false; } else { hasValidLease = true; } final int listeners_size = listeners.size(); for (int i = 0; i < listeners_size; i++) { final CycLeaseManagerListener cycLeaseManagerListener = (CycLeaseManagerListener) listeners.get(i); cycLeaseManagerListener.notifyCycLeaseEvent(new CycLeaseEventObject(cycAccess, cycLeaseManagerReason)); } }
3ad32d04-3b85-40e0-810a-d5f311fc9f89
7
public static void main(String[] args) throws Exception { ChessMan a = new ChessMan(1); ChessMan b = new ChessMan(2); ChessMan c = new ChessMan(3); ChessMan d = new ChessMan(4); ChessMan e = new ChessMan(5); ChessMan f = new ChessMan(6); List<ChessMan> list= new ArrayList<ChessMan>(); list.add(a); list.add(b); list.add(c); list.add(d); list.add(e); list.add(f); int x=6; int y=6; ChessBoard board = new ChessBoard(x,y,list); board.init(); board.printChessBoard(); Action action = new Action(board); //启动监听 BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str=""; //2,3;4,2 while(!(str=br.readLine()).equals("quit")){ //调用处理程序 int result = action.excute(str); if(result==0){ System.out.println("消除成功"); }else if(result==1){ System.out.println("输入格式错误,例如:1,2;1,3"); }else if(result==2){ System.out.println("输入错误"); }else if(result==3){ System.out.println("不可消除"); }else if(result==4){ System.out.println("输入的棋子不在棋盘范围内"); }else if(result==100){ System.out.println("全部消除,游戏结束"); board.printChessBoard(); break; } board.printChessBoard(); } }
c8df4f59-d62c-4939-984c-251dbc3c5208
6
private void updateTableColor(Thread t, int index) { switch (t.getState().toString()) { case "NEW": colors.set(index, Color.GREEN); break; case "RUNNABLE": colors.set(index, Color.CYAN); break; case "BLOCKED": colors.set(index, Color.RED); break; case "WAITING": colors.set(index, Color.YELLOW); break; case "TIMED_WAITING": colors.set(index, Color.YELLOW); break; case "TERMINATED": colors.set(index, Color.BLACK); break; default: break; } }
c97d911d-30cd-4c34-a095-9d599ef49136
4
@Override public int loop() { if(startscript) { if(task == null || !task.hasNext()) { task = container.iterator(); } else { final Node curr = task.next(); if(curr.activate()) { curr.execute(); } } } return stop; }
e56e3cd3-3a1c-447c-b814-ec00105b4b69
5
public int algorithm(List<Integer> L, int k, Callback iteration, Callback comparison){ int pivot = L.get(r.nextInt(L.size())); iteration.callback(0); ArrayList<Integer> l1 = new ArrayList<Integer>(); ArrayList<Integer> l2 = new ArrayList<Integer>(); for(int element : L){ if( element < pivot){ l1.add(element); } else if( element > pivot ){ l2.add(element); } comparison.callback(1); } if(l1.size() == k-1){ comparison.callback(1); return pivot; } else if(l1.size() > k-1){ comparison.callback(1);comparison.callback(1); return algorithm(l1,k,iteration,comparison); } else { comparison.callback(1);comparison.callback(1); return algorithm(l2,k-1-l1.size(),iteration,comparison); } }
14ed71cc-b58b-42bd-b480-2b8519a346c0
8
@Override public boolean execute(MOB mob, List<String> commands, int metaFlags) throws java.io.IOException { String parm = (commands.size() > 1) ? CMParms.combine(commands,1) : ""; if((mob.isAttributeSet(MOB.Attrib.AUTOMAP) && (parm.length()==0))||(parm.equalsIgnoreCase("ON"))) { mob.setAttribute(MOB.Attrib.AUTOMAP,false); mob.tell(L("Automap has been turned on.")); } else if((mob.isAttributeSet(MOB.Attrib.AUTOMAP) && (parm.length()==0))||(parm.equalsIgnoreCase("OFF"))) { mob.setAttribute(MOB.Attrib.AUTOMAP,true); mob.tell(L("Automap has been turned off.")); } else if(parm.length() > 0) { mob.tell(L("Illegal @x1 argument: '@x2'. Try ON or OFF, or nothing to toggle.",getAccessWords()[0],parm)); } return false; }
5a249684-2200-4a02-b1f3-48c95311615c
6
private void addType(final Type type) { if (type.isMethod()) { // Add all of the types of the parameters and the return type final Type[] paramTypes = type.paramTypes(); for (int i = 0; i < paramTypes.length; i++) { // db("typeref " + type + " -> " + paramTypes[i]); addType(paramTypes[i]); } final Type returnType = type.returnType(); // db("typeref " + type + " -> " + returnType); addType(returnType); return; } if (type.isArray()) { // TODO: Add the supertypes of the array and make it implement // SERIALIZABLE and CLONEABLE. Since we're only concerned with // fields and since arrays have no fields, we can ignore this // for now. // db("typeref " + type + " -> " + type.elementType()); addType(type.elementType()); return; } if (!type.isObject()) { return; } if (classes.contains(type)) { return; } if (inWorklist.contains(type)) { return; } worklist.add(type); inWorklist.add(type); }
c5a93ef0-30ef-4bda-9e52-2d8318d54f07
8
protected void addRandomNucleotide() { double dr = 4 * Math.random(); Nucleotide nn = null; if (dr >= 0 && dr < 1) nn = Nucleotide.ADENINE; else if (dr >= 1 && dr < 2) nn = Nucleotide.GUANINE; else if (dr >= 2 && dr < 3) nn = Nucleotide.CYTOSINE; else if (dr >= 3 && dr < 4) nn = Nucleotide.URACIL; addNucleotide(nn); }
524ae480-e31e-42eb-b51c-599d21832c71
4
public void fixCamera() { if (fc_yaw >= 360) { fc_yaw -= 360; } if (fc_yaw < 0) { fc_yaw += 360; } if (fc_pitch < -75) { fc_pitch = -75; } if (fc_pitch > -10) { fc_pitch = -10; } }
97f2a967-e526-4072-8f25-63d44a9c786b
8
@Override public Iterable<ExtendedAttribute> listExtendedAttributes(String path) throws PathNotFoundException, AccessDeniedException, UnsupportedFeatureException { if (extendedAttributes) { try { String[] lines = FileSystemUtils.readLines(attributeFs, getAttributePath(path)); List<ExtendedAttribute> attributes = new LinkedList<ExtendedAttribute>(); for (String line : lines) { if (line.isEmpty()) continue; byte[] content; try { content = FileSystemUtils.readWhole(attributeFs, getAttributePath(path, line)); } catch (Exception e) { content = new byte[0]; } attributes.add(new ExtendedAttribute(line, content)); } return attributes; } catch (AccessDeniedException e) { e.printStackTrace(); } catch (NotAFileException e) { e.printStackTrace(); } catch (PathNotFoundException e) { if (!innerFs.pathExists(path)) throw e; } return new LinkedList<ExtendedAttribute>(); } return innerFs.listExtendedAttributes(path); }
ca0a4d6d-606b-4a66-a049-624ccc82f090
9
public static void main(String[] args) throws Exception{ SOP("==========Chapter 9 Recursion And Dynamic Programming==="); SOP("To run: java c9 [function name] [function arguments]"); SOP("Example: java c9 fib 10"); SOP(""); SOP("Possible functions:"); SOP("fib\tCompute nth fibonacci number"); SOP("q1\tQuestion 1"); SOP("q2\tQuestion 2"); SOP("q3\tQuestion 3"); SOP("q4\tQuestion 4"); SOP("q5\tQuestion 5"); SOP("q6\tQuestion 6"); SOP("q8\tQuestion 8"); SOP("==============================="); SOP(""); if(args.length < 1){ SOP("ERROR: Must specify function to run"); return; } String function = args[0]; if(function.equals("fib")) fibRunner(args); else if(function.equals("q1")) q1(args); else if(function.equals("q2")) q2(args); else if(function.equals("q3")) q3(args); else if(function.equals("q4")) q4(args); else if(function.equals("q5")) q5(args); else if(function.equals("q6")) q6(args); else if(function.equals("q8")) q8(args); else SOP("ERROR: Unknown function"); }
44bec2e0-a691-4d84-b006-0b66b4992429
5
@Override public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { if (getWidth() <= 0 && (infoflags & WIDTH) != 0) { // The image's width has been finalized. setWidth(width); } if (getHeight() <= 0 && (infoflags & HEIGHT) != 0) { // The image's height has been finalized. setHeight(height); } return getWidth() > 0 && getHeight() > 0; }
64095018-33de-4d5c-89a5-de0300ded1eb
1
public Animator getAnimator() { if (_painter == null) { throw new IllegalStateException(); } Animator returnValue = new SwingAnimator(_painter, "Traffic Simulator", VP.displayWidth, VP.displayHeight, VP.displayDelay); _painter = null; return returnValue; }
5a5815d3-5cea-4248-a58e-fa5ee1354cb1
5
@Override public boolean equals(Object obj) { if (obj instanceof Command) { Command cmd = (Command) obj; if (this.thrust == cmd.getThrustCommand()) { if (this.direction == cmd.getDirectionCommand()) { if (this.speed == cmd.getSpeedCommand()) { if (this.misc == cmd.getMiscCommand()) { return true; } } } } } return false; }
fe262e71-75ac-44ee-a73f-be6273dedde2
4
public float getWidth(char code, String name) { int idx = (code & 0xff) - getFirstChar(); // make sure we're in range if (idx < 0 || widths == null || idx >= widths.length) { // try to get the missing width from the font descriptor if (getDescriptor() != null) { return getDescriptor().getMissingWidth(); } else { return 0; } } return widths[idx]; }
dcaf5d2e-ae88-4e62-b6be-db95f28affc6
6
@Override public void run() { if (ctx.bank.opened() && ctx.bank.close()) { if (!Condition.wait(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return !ctx.bank.opened(); } }, Random.nextInt(100, 200), 15)) { return; } } final Item potion = ItemHelper.getFirst(ctx.backpack, SUMMONING_POTION, 1); if (ctx.hud.open(Hud.Window.BACKPACK)) { if (potion.valid() && potion.interact("Drink")) { Condition.wait(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return !script.summoningTask.branch(); } }, Random.nextInt(200, 500), Random.nextInt(5, 10)); } } Condition.sleep(500); }
5c48334c-d395-4019-81e6-81d796794c95
0
public BaseDO update(final BaseDO baseDO) { return getEntityManager().merge(baseDO); }
98a3396c-be45-4f87-976c-3130e2012b63
4
public void close() throws IOException { if (DEBUG) { dbg.printf("%s closed%n", this); } out.close(); try { eth.join(); if (DEBUG) { dbg.printf("%s joined %s%n", this, eth); } } catch (final InterruptedException exn) { throw new InterruptedIOException(exn.getMessage()); } if (eth.exn != null) { throw eth.exn; } }
b9d214b6-b098-4402-a324-ff864fa6c566
1
public void doDelimitedFileExportToExcel() { try { final String mapping = ConsoleMenu.getString("Mapping ", DelimitedFileExportToExcel.getDefaultMapping()); final String data = ConsoleMenu.getString("Data ", DelimitedFileExportToExcel.getDefaultDataFile()); DelimitedFileExportToExcel.call(mapping, data); } catch (final Exception e) { e.printStackTrace(); } }
2f4bd26a-2227-4f1c-981d-0781362a4eca
0
public static Persist getPersist() { return new Persist(getConnection()); }
744db685-dcda-4e0e-b3e8-4e280376fbc2
9
public int FindHighestPrec(LinkedList<Element> linkedList, int startPos, int endPos) { int elmWithHighPrec = startPos; int highestPrec = 8; int currPos = startPos; int parenMatcher = 0; Element currObj; Operator currOp = new Operator(); currObj = (Element) list.get(currPos); for (currPos = startPos; currPos <= endPos; currPos++) { //System.out.println("currPrec:" + currObj.getPrec() + " highPrec:" + highestPrec); currObj = (Element) list.get(currPos); if (currObj.getPrec() < highestPrec) { elmWithHighPrec = currPos; highestPrec = currObj.getPrec(); //System.out.println("chengedElmWithPrec: " + elmWithHighPrec); } if (currObj instanceof Operator) { currOp = (Operator) currObj; if ("(".equals(currOp.getOp())) { parenMatcher++; // System.out.println("if openParen@@@@@@@@@@@@@@@@@@@@@@@@@"); lastOpenParen = currPos; } else if (")".equals(currOp.getOp())) { // System.out.println("if closeparen!!!!!!!!!!!!!!!!!!!!!!!!"); if (parenMatcher == 1 && firstCloseParen == Integer.MAX_VALUE) { firstCloseParen = currPos; parenMatcher--; break; } if (firstCloseParen == Integer.MAX_VALUE) { firstCloseParen = currPos; } parenMatcher--; } // System.out.println("parenMathcer: " + parenMatcher); } //System.out.println(list.get(currPos).toString() + " forloopPos:" + currPos + "\n"); } if (parenMatcher != 0){ System.out.println("match parens properly!"); calcComplete = true; finalResult = Double.MAX_VALUE; } // System.out.println("emlwithprec:" + // list.get(elmWithHighPrec)); return elmWithHighPrec; }
c30c8955-61cc-4d15-8b5e-34679541bc36
0
public SimpleStringProperty lastNameProperty() { return lastName; }
e2433698-0d87-4cc2-9aef-e7b60a357d9f
3
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((majorVersion == null) ? 0 : majorVersion.hashCode()); result = prime * result + ((minorVersion == null) ? 0 : minorVersion.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; }
461b706b-a931-461d-947b-707dc3d078e3
8
void highlightGuide(Integer pos, Color color, int offset) { if (pos == null) { if (guide[offset] != null) { removeFeedback(guide[offset]); guide[offset] = null; } location[offset] = pos; return; } // pos is an integer relative to target's client area. // translate pos to absolute, and then make it relative to fig. int position = pos.intValue(); PrecisionPoint loc = new PrecisionPoint(position, position); IFigure contentPane = ((GraphicalEditPart) getHost()).getContentPane(); contentPane.translateToParent(loc); contentPane.translateToAbsolute(loc); if (location[offset] == null || !location[offset].equals(pos)) { location[offset] = pos; if (guide[offset] != null) { removeFeedback(guide[offset]); guide[offset] = null; } IFigure fig = new FadeIn(color); guide[offset] = fig; addFeedback(fig); fig.translateToRelative(loc); position = offset % 2 == 0 ? (int) Math.round(loc.preciseX()) : (int) Math.round(loc.preciseY()); Rectangle figBounds = getFeedbackLayer().getBounds().getCopy(); if ((offset % 2) == 1) { figBounds.height = 1; figBounds.y = position; } else { figBounds.x = position; figBounds.width = 1; } fig.setBounds(figBounds); } else { // The feedback layer could have grown (if auto-scrolling), so // resize the fade-in // line. IFigure fig = guide[offset]; Rectangle figBounds = fig.getBounds().getCopy(); Rectangle feedbackBounds = getFeedbackLayer().getBounds(); if ((offset % 2) == 1) { figBounds.x = feedbackBounds.x; figBounds.width = feedbackBounds.width; } else { figBounds.y = feedbackBounds.y; figBounds.height = feedbackBounds.height; } fig.setBounds(figBounds); } }
9c38d984-d976-4138-b6ce-cda6e8c0f0ed
6
public int getMinMaand(int jaar) { int maand = 12; // Itereer de datasets for (DataSet set: this.datasets) { for (Category cat: set.categories) { for (SubCategory scat: cat.subcategories) { SubCategory subcat = new SubCategory(scat.id, scat.naam, scat.datatype, scat.weight, scat.red, scat.green, scat.blue, false); for (Period per: scat.periods) { if (per.year == jaar) { if (per.month < maand) { maand = per.month; } } } } } } return maand; }
333415b7-781f-46fe-a7aa-6dcb6cf64eb1
2
static int findColumn(TableModel model, String name) { for (int i = 0; i<model.getColumnCount(); i++) { if (name.equals(model.getColumnName(i))) { return i; } } return -1; }
4558f4fe-2331-478c-ac48-2c6e522e7728
6
public void searchByBookTitle (LYNXsys system, String query, int page) { // search for books by Title for (int i = 0; i < system.getBooks().size(); i ++) { // loop through arraylist of books if (system.getBooks().get(i).getTitle().equalsIgnoreCase(query)){ // check if book title matches search query displayedSearchResults.add(new BookSearchResult (system.getBooks().get(i), system.getBooks().get(i).getTitle() + ", " + system.getBooks().get(i).getAuthorFirstName() + " " + system.getBooks().get(i).getAuthorLastName() + ". " + system.getBooks().get(i).getCategory() + ". ISBN: " + system.getBooks().get(i).getIsbn() + ". Available: " + system.getBooks().get(i).getAvailable())); } } for(int i = ((page-1)*13); i < page*13; i++){ if (i < displayedSearchResults.size()) { displayedSearchResults.get(i).getDisplayText().setEditable(false); displayedSearchResults.get(i).getDisplayText().setBackground(Color.pink); displayedSearchResults.get(i).getDisplayText().setBounds(500,270 + (21*(i-(13*(page-1)))),450,20); displayedSearchResults.get(i).getBook().setBounds(460,270 + (21*(i-(13*(page-1)))),32,20); add(displayedSearchResults.get(i).getDisplayText(),0); add(displayedSearchResults.get(i).getBook(),0); } } for (int i = 12; i < displayedSearchResults.size(); i = i + 13) { if (displayedSearchResults.size() > i) { pages.add(new JButton()); pages.get(pages.size() - 1).setBounds(620 + (45*(((i-12)/13)+1)),547,43,19); add(pages.get((((i-12)/13)+1)),0); pages.get((((i-12)/13)+1)).addActionListener(getAction()); } } repaint(460,270,510,500); lastSearch = 1; }
43c2f12b-08b0-4294-b812-9c6959ccda22
4
@Override public boolean contains(Object o) { if (o != null) { int i = index(o.hashCode()); synchronized (table[i]) { Node<E> c = table[i].next; while (c != null) { if (c.element == o || c.element.equals(o)) { return true; } c = c.next; } } } return false; }
cc97cf77-8a7d-420b-821f-1e189b51e082
5
public void paintComponent(Graphics g){ for(int x = 0; x < 500; x += 50){ for(int y = 0; y < 500; y += 50){ g.setColor(Color.WHITE); g.fillRect(x, y, 50, 50); g.setColor(Color.BLACK); g.drawLine(x, y, x + 50, y); g.drawLine(x, y, x, y + 50); if(player.xPos == x/50 && player.yPos == y/50){ g.setColor(Color.GRAY); g.fillRect(x + 10, y + 10, 30, 30); g.setColor(Color.BLACK); g.drawRect(x + 10, y + 10, 30, 30); } else if(garden.isAppleOnField(x/50, y/50)){ g.setColor(Color.RED); g.fillRect(x + 10, y + 10, 30, 30); g.setColor(Color.BLACK); g.drawRect(x + 10, y + 10, 30, 30); } else { g.setColor(Color.WHITE); g.fillRect(x + 10, y + 10, 30, 30); } } } g.setColor(Color.BLACK); g.drawLine(0, 499, 499, 499); g.drawLine(499, 0, 499, 499); }
c6af0434-2185-4e7c-a41d-aac7ffcaf553
7
@Override public MarkovChain constructChain() throws Exception { // @debug sampleValueIndices = new ArrayList<>(); MarkovChain mcResultante = new MarkovChain(stats); transitionResultante = new double[stats.length][stats.length]; MarkovChain mcSimulation = new MarkovChain(stats); // on crée la matrice de transition pour la simulation mcSimulation.intializeTransitionMatrix(typeDensiteInstrumentale); // on choisit l'état de départ au hasard int x_previous = Alea.getRand().nextInt(stats.length); mcSimulation.setCurrentStateIndice(x_previous); /* @debug */ sampleValueIndices.add(x_previous); // i <- 0 i = 0; double[][] transitionMatrixSimulation = mcSimulation.getTransitionMatrix(); int totalWalk = 0; // on boucle pour remplire la matrice de transition de mcResultante while (!conditionArret()) { // On simule xtilte <- q(x|xi-1) int xtilde = mcSimulation.walk(); // @debug tempsParEtat[xtilde]++; totalWalk++; sampleValueIndices.add(x_previous); // on calcul alpha double diviseur = (transitionMatrixSimulation[x_previous][xtilde] / (double) transitionMatrixSimulation[xtilde][x_previous]); /* @debug if (Math.abs(diviseur - 1) > 0.001) { System.err.println("Diviseur : " + diviseur); System.err.println("Matrice de simulation non symetrique"); System.exit(-1); } if (diviseur < 0.00001) { System.err.println("Dans la mesure où la matrice est symétrique, il n'y a pas de raison qu'on ait un d == 0"); System.exit(-4); }*/ double d = (distribution[xtilde] / (double) distribution[x_previous]) * diviseur; // == 1 si symétrique (ou zero) double alpha = Math.min(1., d); // acceptation ou rejet ? // on met à jouer la matrice de transition de mcResultante (i.e. on construit la châine de markov) if (Alea.bernouilli(alpha)) { //acceptation transitionResultante[x_previous][xtilde]++;// = alpha; // pas sur de ça en faite // transitionResultante[xtilde][x_previous] = alpha; x_previous = xtilde; } else { //rejet on fait rien } i++; } /** * normalisation */ for (int j = 0; j < transitionResultante.length; j++) { double somme = 0.0; for (int k = 0; k < transitionMatrixSimulation[j].length; k++) { somme += transitionResultante[j][k]; } for (int k = 0; k < transitionMatrixSimulation[j].length; k++) { transitionResultante[j][k] /= somme; } } // on définit la matrice de transition de la mc généré avec la matrice transition resultante mcResultante.setTransitionMatrix(transitionResultante); //@debug // System.out.println("" + sampleValueIndices); /** * @debug on vérifie que la matrice resultante est une matrice de proba * (à enlever à l'avenir) */ if (!Alea.isProbabilistMatrix(transitionResultante, 0.01)) { System.err.print("La matrice générée n'est pas une matrice probabiliste : "); System.err.println(""+Myst.toStringMatrix(transitionResultante)); System.exit(-2); } /** * @debug */ for (int j = 0; j < tempsParEtat.length; j++) { tempsParEtat[j] /= totalWalk; } return mcResultante; }
e02d9bf7-8560-4bb4-92f5-60e27df95412
5
public InputStream send() { //Prepare parameters prepare(); try { HttpURLConnection con = prepareConnection(new URL(String.format(URL_FORMAT, this.url, this.parameters))); int responseCode = con.getResponseCode(); String responseMessage = con.getResponseMessage(); if (responseCode == HttpURLConnection.HTTP_OK && responseMessage.equals("OK")) return con.getInputStream(); } catch (UnknownHostException e) { //unable to connect e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
a414df29-ff75-48a5-8180-d2cabf6321f9
3
public static JScanner getInstance(Component component) { Container parent = component.getParent(); if (parent instanceof JPopupMenu) return getInstance(((JPopupMenu) parent).getInvoker()); while (parent != null) { if (parent instanceof JScanner) return (JScanner) parent; parent = parent.getParent(); } return null; }
a77b2e5c-cc9d-4f1a-a87b-8a3ee15a07f3
3
public static TopQueue search(String target, String dictFile) throws IOException { BufferedReader reader; reader = new BufferedReader(new FileReader(dictFile)); TopQueue topQueue = new TopQueue(); String word; int distance; while((word = reader.readLine()) != null) { // get the number of edit distance distance = Edit_distance.edit3(target,word); if(!topQueue.isEmpty()){ if(distance < topQueue.getEntryDistance()){ topQueue.add(word,distance); } } else { topQueue.add(word,distance); } } return topQueue; }
69cefc7b-f172-478c-90dc-303e3ce2c6ef
5
public void keyPressed(KeyEvent e) { System.out.println("KeyPressed "+e.getKeyCode()); try { switch (e.getKeyCode()) { case KeyEvent.VK_UP : { System.out.println("UP"); model.move(Directions.UP, score); break; } case KeyEvent.VK_DOWN : { System.out.println("DOWN"); model.move(Directions.DOWN, score); break; } case KeyEvent.VK_LEFT : { System.out.println("LEFT"); model.move(Directions.LEFT, score); break; } case KeyEvent.VK_RIGHT : { System.out.println("RIGHT"); model.move(Directions.RIGHT, score); break; } } } catch (PusherException ex) { ex.printStackTrace(); } }
0a8ab96d-f512-40bc-9280-6726a96aade8
5
public double[] evaluateNeuralNetwork(double[] inputVector){ ArrayList<Node> inputLayer = networkLayers.get(0).getNodes(); ArrayList<Node> outputLayer = networkLayers.get(networkLayers.size()-1).getNodes(); //If the input vector is not of the same size as the input layer return null. if(inputVector.length != inputLayer.size()){ return null; } for(int i = 0; i < inputVector.length;i++){ inputLayer.get(i).setValue(inputVector[i]); } ArrayList<Node> currentLayer; for(int i = 1; i < networkLayers.size();i++){ currentLayer = networkLayers.get(i).getNodes(); for(Node n: currentLayer){ n.evaluateNode(); } } double[] outputVector = new double[outputLayer.size()]; for(int i = 0; i < outputLayer.size();i++){ outputVector[i] = outputLayer.get(i).getValue(); } return outputVector; }
b58707d7-0cdb-46a5-bd67-3efa675b5982
0
public void mouseDragged(MouseEvent event) { return; }
caa84bfb-e48f-47f9-8366-720a4504c1aa
2
public void update() { List<Zombie> zombies = house.zombieList; Rectangle2D box; int x, y, width, height; charactersGraphics.clearRect(0, 0, characters.getWidth(), characters.getHeight()); backgroundGraphics.setColor(Color.BLUE); for (Tile t : house.tileList) { x = (int) t.getX() * 50; y = (int) t.getY() * 50; width = (int) t.getWidth() * 50; height = (int) t.getHeight() * 50; backgroundGraphics.fillRect(x, y, width, height); } charactersGraphics.setColor(Color.RED); for (Zombie z : zombies) { box = z.getHitbox(); x = (int) box.getX(); y = (int) box.getY(); charactersGraphics.fillRect(x, y, 50, 50); } Point p = house.player.getPosition(); x = p.x; y = p.y; HUDGraphics.clearRect(0, 0, this.getWidth(), this.getHeight()); HUDGraphics.setColor(Color.ORANGE); HUDGraphics.fillRect(10, this.getHeight() - 40, 20, 20); // HUDGraphics.drawString(Integer.toString(house.player.getFireTrapCount()), 40, this.getHeight() - 40); charactersGraphics.setColor(Color.GREEN); charactersGraphics.fillRoundRect(x, y, 50, 50, 10, 10); // charactersGraphics.fillRect(x, y, 50, 50); updateLight(); repaint(); }
cb3d03eb-fb29-4b88-a436-2b2ec766f0d5
0
public static void main(String[] args) throws Exception { new HelloWorldOGL().loop(); }
78dce577-a5fa-460f-baf9-6fd155906e1b
0
public Flooder(String host) throws java.net.UnknownHostException, java.net.SocketException { t = new Thread((Runnable) this); this.host = InetAddress.getByName(host); sock = new DatagramSocket(); stop = false; //t.start(); }
35c2e1ec-5d0b-4f28-8f6e-ccd9626fca50
8
public void updatePlayer() { if (userRace.equalsIgnoreCase("human")) user = new Human(this, userName, null, -1); else if (userRace.equalsIgnoreCase("cyborg") && userColor.equalsIgnoreCase("purple")) user = new Cyborg(this, "purple", userName, null, -1); else if (userRace.equalsIgnoreCase("cyborg") && userColor.equalsIgnoreCase("blue")) user = new Cyborg(this, "blue", userName, null, -1); else if (userRace.equalsIgnoreCase("cyborg")) user = new Cyborg(this, userName, -1, null, -1); else user = new Human(this, userName, null, -1); if (userMelee.equalsIgnoreCase("sword")) user.setMelee(new Sword(user)); if (userRanged.equalsIgnoreCase("bow")) user.setRanged(new Bow(user)); user.setInHand(user.getMelee()); }
b59c14db-80da-45cd-820c-b4edd957ce57
3
public static ArrayList<bDefeito> getDefeitos(String arg_serial) throws SQLException, ClassNotFoundException { ArrayList<bDefeito> sts = new ArrayList<bDefeito>(); bDefeito bObj; ResultSet rs; Connection conPol = conMgr.getConnection("PD"); if (conPol == null) { throw new SQLException("Numero Maximo de Conexoes Atingida!"); } try { call = conPol.prepareCall("SELECT " + " tb_operador.str_nome, " + " tb_defeito.cod_prod, " + " tb_defeito.serial, " + " tb_defeito.tipo_montagem, " + " tb_defeito.cod_comp, " + " tb_defeito.pos_comp, " + " tb_defeito.datahora, " + " tb_defeito.cod_cr, " + " tb_defeito.str_obs, " + " tb_tp_defeito.str_defeito " + "FROM " + " public.tb_operador, " + " public.tb_defeito, " + " public.tb_tp_defeito " + "WHERE " + " serial = ? AND " + " tb_operador.cod_cr = tb_defeito.cod_cr AND " + " tb_defeito.cod_tp_defeito = tb_tp_defeito.cod_tp_defeito; "); call.setString(1, arg_serial); rs = call.executeQuery(); while (rs.next()) { bObj = new bDefeito(); bObj.setCod_prod(rs.getString("cod_prod")); bObj.setSerial(rs.getString("serial")); bObj.setStr_tp_defeito(rs.getString("str_defeito")); bObj.setTipo_montagem(rs.getString("tipo_montagem").charAt(0)); bObj.setCod_comp(rs.getString("cod_comp")); bObj.setPos_comp(rs.getInt("pos_comp")); bObj.setDatahora(rs.getTimestamp("datahora")); bObj.setCod_cr(rs.getInt("cod_cr")); bObj.setStr_cr_operador(rs.getString("str_nome")); bObj.setStr_obs(rs.getString("str_obs")); sts.add(bObj); } return sts; } finally { if (conPol != null) { conMgr.freeConnection("PD", conPol); } } }
057bcab3-e38a-4565-88a0-41add121c232
3
public HalfEdge findEdge (Vertex vt, Vertex vh) { HalfEdge he = he0; do { if (he.head() == vh && he.tail() == vt) { return he; } he = he.next; } while (he != he0); return null; }
d89d93fd-6138-45ee-94df-023174d0898b
3
void buttonClicked(final String answer) { state.setPictureChanged(false); state.setResultFromButton(true); List<String> currentRightAnswers = state.getRightAnswers(); //если верно: увеличиваем счет и показывем картинку. если неверно: уменьшаем счет if (currentRightAnswers.contains(answer.toLowerCase())) { state.setPictureChanged(true); showPicture(); if (state.getIfScore()) { increaseScore(); } } else { if (state.getIfScore()) { decreaseScore(); } } //оповещаем слушателей notifyObservers(); }
2025acdd-c5ed-458c-a6fb-4cdd8735416e
9
public static boolean rectIntersection(CvRect rect1, CvRect rect2) { if (rect1.isNull() || rect2.isNull() || rect1.width() <= 0 || rect1.height() <= 0 || rect2.width() <= 0 || rect2.height() <= 0) { return false; } int x0 = rect1.x(); int y0 = rect1.y(); int w0 = rect1.width(); int h0 = rect1.height(); int x1 = rect2.x(); int y1 = rect2.y(); int w1 = rect2.width(); int h1 = rect2.height(); return (x1 + w1 > x0 && y1 + h1 > y0 && x1 < x0 + w0 && y1 < y0 + h0); }
8597dfe3-e5df-4d86-9702-b9a3f257bbf0
1
public String status() { return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff!") + "), "; }
a5a8adb8-505e-4394-9bf2-91326a1ddf0b
8
public static void set_connect(_YM2151 chip,int op_offset, int v, int cha) { OscilRec om1 = chip.Oscils[op_offset]; OscilRec om2 = chip.Oscils[op_offset+8]; OscilRec oc1 = chip.Oscils[op_offset+16]; /*OscilRec *oc2 = om1+24;*/ /*oc2->connect = &chanout[cha];*/ /* set connect algorithm */ switch( v & 7 ) { case 0: /* M1---C1---M2---C2---OUT */ om1.connect = c1; oc1.connect = m2; om2.connect = c2; break; case 1: /* M1-+-M2---C2---OUT */ /* C1-+ */ om1.connect = m2; oc1.connect = m2; om2.connect = c2; break; case 2: /* M1------+-C2---OUT */ /* C1---M2-+ */ om1.connect = c2; oc1.connect = m2; om2.connect = c2; break; case 3: /* M1---C1-+-C2---OUT */ /* M2------+ */ om1.connect = c1; oc1.connect = c2; om2.connect = c2; break; case 4: /* M1---C1-+--OUT */ /* M2---C2-+ */ om1.connect = c1; oc1.connect = chanout[cha]; om2.connect = c2; break; case 5: /* +-C1-+ */ /* M1-+-M2-+-OUT */ /* +-C2-+ */ om1.connect = null; /* special mark */ oc1.connect = chanout[cha]; om2.connect = chanout[cha]; break; case 6: /* M1---C1-+ */ /* M2-+-OUT */ /* C2-+ */ om1.connect = c1; oc1.connect = chanout[cha]; om2.connect = chanout[cha]; break; case 7: /* M1-+ */ /* C1-+-OUT */ /* M2-+ */ /* C2-+ */ om1.connect = chanout[cha]; oc1.connect = chanout[cha]; om2.connect = chanout[cha]; break; } }
d73d36a2-41a5-41a4-aae2-c8e41735812c
1
public void outputAllGameScreenStatistics() { for (GameScreen gameScreen : gameScreens.values()) { logger.info(gameScreen.toString()); } }
f9af5927-d246-46ec-b0d4-c6c33fb77b70
1
public static void getStrings(String... text) { for(String s:text) { System.out.println(s); } }
9ea831e1-cc20-4ea1-8bf5-416fc9f18137
6
@Override public Screen respondToInput(KeyEvent key) { switch (key.getKeyCode()) { case KeyEvent.VK_1: return new LoadGameScreen(slot, 1); case KeyEvent.VK_2: return new LoadGameScreen(slot, 2); case KeyEvent.VK_3: return new LoadGameScreen(slot, 3); case KeyEvent.VK_4: return new LoadGameScreen(slot, 4); case KeyEvent.VK_5: return new LoadGameScreen(slot, 5); case KeyEvent.VK_ESCAPE: return new WorldScreen(); default: return this; } }
a5f9aa03-027b-4d7b-9ec4-fa13a8f82a5a
0
public static float getMaxDestToRad() { return MaxDestToRad; }
26853916-08f8-49f0-b81e-c00aaf1c4a1b
1
public void remover(long id) throws Exception { String sql = "DELETE FROM Pesquisacolaboradores WHERE id1 = ?"; try { PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql); stmt.setLong(1, id); } catch (SQLException e) { throw e; } }
085cff1c-b4cf-4420-ac16-f91a7761d1d6
1
public void setHTML(String html, String base_url) { Graphics2D graphics = (Graphics2D) xhtml_panel.getGraphics(); // graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, Joculus.settings.getFontSmoothingValue()); try { xhtml_panel.setDocumentFromString(html, base_url, new XhtmlNamespaceHandler()); } catch(org.xhtmlrenderer.util.XRRuntimeException ex) { Joculus.showError("XML Renderer runtime exception:\n" + ex.getMessage()); } }
3285a5d3-fb51-40f5-8f6a-c65880efb559
5
public static boolean isUpdated(ClassNode cached, String jarLink) { try { URL url = new URL("jar:"+jarLink+"!/"); JarURLConnection conn = (JarURLConnection)url.openConnection(); conn.setDoOutput(true); JarFile jar = conn.getJarFile(); Enumeration<?> enumeration = jar.entries(); while (enumeration.hasMoreElements()) { JarEntry entry = (JarEntry) enumeration.nextElement(); if (entry.getName().equals("client.class")) { ClassReader classReader = new ClassReader(jar.getInputStream(entry)); ClassNode classNode = new ClassNode(); classReader.accept(classNode, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); return getRevision(cached) != getRevision(classNode); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
908597be-3bc2-4980-bc14-58345d140251
2
private int muokkaaTuote(ArrayList<Tilausrivi> tilausrivit, String action) throws IOException { // otetaan tuoteID irti valuesta int tilausriviNumero = Integer.parseInt(action.substring(5)); // etsitään tuote tilausriveistä ja asetetaan tuoteID url:n parametriksi int numero = 0; for (int i = 0; i < tilausrivit.size(); i++) { if (i == tilausriviNumero) { numero = i; break; } } return numero; }
c0a02e93-2d34-4efc-a645-6a3e954db589
5
public synchronized void deposer(Site n) { // Compteur du nombre de personnes descendues pour le print. int cpt = 0; for (int i = 0; i < tfest.length; i++) { if ((tfest[i] != null) && (n.equals(tfest[i].destination))){ cpt++; // On "reveille" le festivalier tfest[i].setStop(true); delFestivalier(i); } } if (cpt == 1) System.out.println("Navette " + nNavette + " a depose 1 Festivalier au Site " + n.nSite); else if (cpt != 0) System.out.println("Navette " + nNavette + " a depose " + cpt + " Festivaliers au Site " + n.nSite); }
0d77298f-5028-4430-b86c-31b410fa5f34
9
public void fire_shot(double v, double angle, double height, int team) { double i=0.0, x=0.0, y=1.0, vx, vy, maxY=0.0, a=0.0; final int fixed_angle = 100; mydata.clear(); vx = v * (Math.cos(angle * (3.1416 / 180))); vy = v * (Math.sin(angle * (3.1416 / 180))); while(y>0.0) { mydata.add(new shot_data()); i+= step; x = vx*i; y = (-(5 * (i*i)) + (vy * i)) + height + 2; if(y>maxY) { maxY=y; if(i<fixed_angle){ a=Math.toDegrees(Math.atan(y/x)); } else if(i==fixed_angle) { a=Math.toDegrees(Math.atan(y/x)); for(int j = 0; j < mydata.size(); j++){ mydata.get(j).tempangle=a; } } else { a=Math.toDegrees(Math.atan(y/x)); } } else { if(i<fixed_angle){ a=Math.toDegrees(Math.atan(y/x)); } else if(i==fixed_angle) { a=Math.toDegrees(Math.atan(y/x)); for(int j = 0; j < mydata.size(); j++){ mydata.get(j).tempangle=a; } } else { a=Math.toDegrees(Math.atan(y/x)); } } if (team==1) { x *= -1; } mydata.get(mydata.size()-1).width = x; mydata.get(mydata.size()-1).height=y; mydata.get(mydata.size()-1).time=i; mydata.get(mydata.size()-1).team=team; mydata.get(mydata.size()-1).tempangle=a; mydata.get(mydata.size()-1).hit=false; } }
b8c6e2d5-6d8d-4d06-93dd-28c2feb797f1
9
public void updatePos(){ xspeed += xacc / speedDivider; yspeed += (yacc + gravity) / speedDivider; xspeed *= friction; yspeed *= friction; x += xspeed; y += yspeed; if(x < 0){ x = 0; xspeed = -xspeed * elasticity; ballColour = new Color(r(), r(), r()); } else if(x + ballRadius * 2 > wScreen){ x = wScreen - ballRadius * 2; xspeed = -xspeed * elasticity; ballColour = new Color(r(), r(), r()); } if(y < 0){ y = 0; yspeed = -yspeed * elasticity; ballColour = new Color(r(), r(), r()); } else if(y + ballRadius * 2 > hScreen){ y = hScreen - ballRadius * 2; yspeed = -yspeed * elasticity; ballColour = new Color(r(), r(), r()); } double s = particleSpeed; for(int i = 0; i < 5; i++){ if(yacc == -acc) flames.add(new Flame((int) (x + ballRadius), (int) (y + 2*ballRadius), 0, s, gravity)); if(yacc == acc) flames.add(new Flame((int) (x + ballRadius), (int) y, 0, -s, gravity)); if(xacc == acc) flames.add(new Flame((int) x, (int) (y + ballRadius), -s, 0, gravity)); if(xacc == -acc) flames.add(new Flame((int) (x + 2 * ballRadius), (int) (y + ballRadius), s, 0, gravity)); } }
c21f27eb-832c-47a9-a6d7-693f8df0b2a8
9
public static boolean isTokenDelimiter(int c) { switch (c) { case 'ä': case 'ö': case 'ü': case 'ß': case 'Ö': case 'Ä': case 'Ü': return false; } return c < 10 || c > 126 || DELIMITER_TOKEN.contains(String.valueOf((char) c)); }
b6e1c391-af37-45c2-bc35-aad6e7bd6f25
2
private void addSchema(Document doc) throws IOException, XPathExpressionException { if(doc != null) { Node srcSchemaNode = Utilities.selectSingleNode(doc, "/xsd:schema", this.namespaces); String name = Utilities.getAttributeValue(srcSchemaNode, "targetNamespace"); if(!this.schemas.containsKey(name)) { logger.info(" schema: " + name); this.schemas.put(name, new DOMSource(doc)); } else { logger.warn("Schema already loaded: " + name); } } }
09b9fee2-8fb7-4fa2-882e-23ee371e5eb2
3
public void calculcate() { Rectangle r = this.getBounds(); float width = (float) r.getWidth(); float height = (float) r.getHeight(); // System.out.println("Width : " + width + " Height : " + height); float xScale = width / (bX + sX); float yScale = height / (bY + sY); scale = 0.0F; if (xScale > yScale) { scale = yScale; } else if (yScale > xScale) { scale = xScale; } else if (xScale == yScale) { scale = xScale; } // System.out.println("Biggest X " + bX + " Biggest Y : " + bY); // System.out.println("Smalest X : " + sX + " Smalest Y : " + sY); // System.out.println("Scale ; x : " + xScale + " y : " + yScale); // System.out.println("Scale : " + scale); }
cfc74c1c-c32a-4c28-860d-635aedfa7b39
3
public XmlNode CreateReplica(XmlNode parent, XmlNode node, String name) { if (parent == null || node == null || name == null) return null; XmlNode replicanode = new XmlNode(XmlNodeType.REPLICA, name); parent.addChild(replicanode); String path = tree.getPath(replicanode, node); replicanode.setAttribute(PATH, path); //tree.addReplica(replicanode); return replicanode; }
114f4b72-8556-45e7-896b-d955f90f9078
1
public static void right() { if(viewX + 100 < WIDTH - 100) { viewX += 1; } }
4444526c-8632-481a-a796-fe244562f1c9
1
public static PeerID generateMagic() throws java.security.NoSuchAlgorithmException { boolean notFound = true; Random random = new Random(System.currentTimeMillis()); byte[] peerid = new byte[20]; int tries = 0; while (notFound) { tries++; random.nextBytes(peerid); notFound = isMagic(peerid); } //return tries; return new PeerID(peerid,tries); }
98c32ba3-1b59-4f75-b1ed-3820bed8b314
7
public static void paint(Ocean sea) { if (sea != null) { int width = sea.width(); int height = sea.height(); /* Draw the ocean. */ for (int x = 0; x < width + 2; x++) { System.out.print("-"); } System.out.println(); for (int y = 0; y < height; y++) { System.out.print("|"); for (int x = 0; x < width; x++) { int contents = sea.cellContents(x, y); if (contents == Ocean.SHARK) { System.out.print('S'); } else if (contents == Ocean.FISH) { System.out.print('~'); } else { System.out.print(' '); } } System.out.println("|"); } for (int x = 0; x < width + 2; x++) { System.out.print("-"); } System.out.println(); } }
77ffb2c7-aade-493f-9751-c1f344b84c20
3
public void addFile(String directory) throws IOException { Path path = Paths.get(directory); String ZipDirectory = path.getFileName().toString(); zipEntry = new ZipEntry(ZipDirectory); byte[] buffer = new byte[1024]; int bytesRead=0; CRC32 crc = new CRC32(); File tempFile = new File(directory); if(tempFile.exists()){ BufferedInputStream bufferedInput = new BufferedInputStream(new FileInputStream(tempFile)); crc.reset(); while ((bytesRead = bufferedInput.read(buffer))!=-1){ crc.update(buffer, 0, bytesRead); } bufferedInput.close(); bufferedInput = new BufferedInputStream(new FileInputStream(tempFile)); zipEntry.setMethod(ZipEntry.STORED); zipEntry.setCompressedSize(tempFile.length()); zipEntry.setSize(tempFile.length()); zipEntry.setCrc(crc.getValue()); output.putNextEntry(zipEntry); while((bytesRead = bufferedInput.read(buffer))!=-1) { output.write(buffer,0,bytesRead); } bufferedInput.close(); output.closeEntry();} }
c4a2a7a6-23fa-4f1b-9cba-21f321c67ef0
1
private void sendMessageToChat_Lobby() { // TODO Auto-generated meth od stub String message = lobby.fetchJTextValue("lobbyChat_message"); String result = sendMessageToSomeSocket(ChatSocketServer.MESSAGE, ",message=" + message, chatSocket); if (result.contains(ChatSocketServer.MESSAGE_RECEIVED)) { updateChat_Lobby("Me", message); } }
d809229a-e574-4b8d-94cf-24e6e59c92b1
4
public void deleteAuthHeaderByToken(String token){ Connection con = null; Statement stmt = null; try { DBconnection dbCon = new DBconnection(); Class.forName(dbCon.getJDBC_DRIVER()); con = DriverManager.getConnection(dbCon.getDATABASE_URL(), dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD()); stmt = con.createStatement(); stmt.execute("Delete From auth_tokens Where auth_token ='" + token+"'"); } catch (SQLException | ClassNotFoundException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } finally { try { if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } } }
a22e4a65-1067-4b94-9668-16c818ece235
9
public void enviarPecasParaJogador(Socket[] lista,int player) throws Exception{ for(int i =0;i<player;i++){ DataOutputStream info = new DataOutputStream(lista[i].getOutputStream()); if(player==1){ for(i=0; i<jogo.pecas1.size(); i++){ info.writeBytes(jogo.pecas1.get(i).getLadoDireito()+"|"+jogo.pecas1.get(i).getLadoEsquerdo()); System.out.println(jogo.pecas1.get(i).getLadoDireito()+"|"+jogo.pecas1.get(i).getLadoEsquerdo());//Vai enviar isso } } if(player==2){ for(i=0; i<jogo.pecas2.size(); i++){ info.writeBytes(jogo.pecas2.get(i).getLadoDireito()+"|"+jogo.pecas2.get(i).getLadoEsquerdo()); System.out.println(jogo.pecas2.get(i).getLadoDireito()+"|"+jogo.pecas2.get(i).getLadoEsquerdo());//Vai enviar isso } } if(player==3){ for(i=0; i<jogo.pecas3.size(); i++){ info.writeBytes(jogo.pecas3.get(i).getLadoDireito()+"|"+jogo.pecas3.get(i).getLadoEsquerdo()); System.out.println(jogo.pecas3.get(i).getLadoDireito()+"|"+jogo.pecas3.get(i).getLadoEsquerdo());//Vai enviar isso } } if(player==4){ for(i=0; i<jogo.pecas4.size(); i++){ info.writeBytes(jogo.pecas4.get(i).getLadoDireito()+"|"+jogo.pecas4.get(i).getLadoEsquerdo()); System.out.println(jogo.pecas4.get(i).getLadoDireito()+"|"+jogo.pecas4.get(i).getLadoEsquerdo());//Vai enviar isso } } } }
190b8a6a-2569-4b2c-be49-61d0a5face0d
3
private JSONWriter end(char mode, char c) throws JSONException { if (this.mode != mode) { throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); } this.pop(mode); try { this.writer.write(c); } catch (IOException e) { throw new JSONException(e); } this.comma = true; return this; }
48978574-b391-45fe-8dd8-a3a5ee14556c
7
public String toSource(String className) throws Exception { StringBuffer result; int i; result = new StringBuffer(); if (m_ZeroR != null) { result.append(((ZeroR) m_ZeroR).toSource(className)); } else { result.append("class " + className + " {\n"); result.append(" public static double classify(Object[] i) {\n"); result.append(" // chosen attribute: " + m_rule.m_attr.name() + " (" + m_rule.m_attr.index() + ")\n"); result.append("\n"); // missing values result.append(" // missing value?\n"); result.append(" if (i[" + m_rule.m_attr.index() + "] == null)\n"); if (m_rule.m_missingValueClass != -1) result.append(" return Double.NaN;\n"); else result.append(" return 0;\n"); result.append("\n"); // actual prediction result.append(" // prediction\n"); result.append(" double v = 0;\n"); result.append(" double[] classifications = new double[]{" + Utils.arrayToString(m_rule.m_classifications) + "};"); result.append(" // "); for (i = 0; i < m_rule.m_classifications.length; i++) { if (i > 0) result.append(", "); result.append(m_rule.m_class.value(m_rule.m_classifications[i])); } result.append("\n"); if (m_rule.m_attr.isNominal()) { for (i = 0; i < m_rule.m_attr.numValues(); i++) { result.append(" "); if (i > 0) result.append("else "); result.append("if (((String) i[" + m_rule.m_attr.index() + "]).equals(\"" + m_rule.m_attr.value(i) + "\"))\n"); result.append(" v = " + i + "; // " + m_rule.m_class.value(m_rule.m_classifications[i]) + "\n"); } } else { result.append(" double[] breakpoints = new double[]{" + Utils.arrayToString(m_rule.m_breakpoints) + "};\n"); result.append(" while (v < breakpoints.length && \n"); result.append(" ((Double) i[" + m_rule.m_attr.index() + "]) >= breakpoints[(int) v]) {\n"); result.append(" v++;\n"); result.append(" }\n"); } result.append(" return classifications[(int) v];\n"); result.append(" }\n"); result.append("}\n"); } return result.toString(); }