method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
0c1375d6-e69a-4889-8cb3-cc3ff3f5b20e
5
public void Update(GameTime gameTime) { //HandleExplosions(); mMousePosition = new Vector2(mInput.GetMouseX(), GameProperties.WindowHeight() - mInput.GetMouseY()).DividedBy(GameProperties.Scale()).Minus(mCameraOffset); GameEntity.UpdateList(gameTime, mEnemyList); GameEntity.UpdateList(gameTime, mBulletList); GameEntity.UpdateList(gameTime, mSparkList); GameEntity.UpdateList(gameTime, mLastingGridPushes); mGrid.Pull(mMousePosition, 5000, 10000); mGrid.Update(gameTime); mCameraFocus.SetEqual(new Vector2(GameProperties.SizeX(), GameProperties.SizeY()).DividedBy(2)); MoveCamera(10); mMenu.Update(); if (!mMenu.IsMenuItemSelected()) { mMenu.SelectMenuItem(new Vector2(mInput.GetMouseX(), GameProperties.WindowHeight() - mInput.GetMouseY())); if (mInput.IsMouseHit(0)) { switch(mMenu.GetSelected()) { case 0: { mNextState = new GameState_Game(mGrid, mSparkList, mLastingGridPushes, mCameraOffset); } break; /*case 1: { mNextState = new GameState_GameServer(mGrid, mSparkList, mLastingGridPushes, mCameraOffset); } break; case 2: { mNextState = new GameState_GameClient(mGrid, mSparkList, mLastingGridPushes, mCameraOffset); } break;*/ case 1: { mNextState = new GameState_GraphicsMenu(this); } break; case 2: { UnLoad(); } break; } } } }
dc3d9d40-caea-4659-9202-4a1dda45120a
4
public static void main(String[] argsv) { // Setting op a bank. Bank christmasBank = new Bank(); christmasBank.addAccount(new BankAccount(BigInteger.valueOf(100))); christmasBank.addAccount(new BankAccount(BigInteger.valueOf(50), BigInteger.valueOf(-1000))); BankAccount theAccount = new BankAccount(BigInteger.valueOf(-70), BigInteger.valueOf(-1500)); christmasBank.addAccount(theAccount); // Collect and print all accounts with a positive balance: Static method Set<BankAccount> accountsPositiveBalance = christmasBank.getAccountsSatisfying (account -> Bank.hasPositiveBalance(account)); System.out.println("Static method"); for (BankAccount account: accountsPositiveBalance) System.out.println(account.getBalance()); System.out.println(); // Collect and print all accounts with positive balance: Instance method via class accountsPositiveBalance = christmasBank.getAccountsSatisfying (account -> account.hasPositiveBalance()); System.out.println("Instance method via class"); for (BankAccount account: accountsPositiveBalance) System.out.println(account.getBalance()); System.out.println(); // Collect and print all accounts with a balance not below the balance of theAccount: Instance method via instance accountsPositiveBalance = christmasBank.getAccountsSatisfying (account -> theAccount.hasHigherBalanceThan(account)); System.out.println("Instance method via instance"); for (BankAccount account: accountsPositiveBalance) System.out.println(account.getBalance()); System.out.println(); // Generate and print duplicate accounts with a balance 10 higher than the original account. Set<BankAccount> newAccounts = christmasBank.getReplacingAccounts ((balance,creditLimit) -> new BankAccount(balance,creditLimit)); System.out.println("Constructor"); for (BankAccount account: newAccounts) System.out.println(account.getBalance()); System.out.println(); }
d6bfd3a1-e2fe-43c8-9915-c093667dd9fd
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(Karel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Karel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Karel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Karel.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() { Karel karel = new Karel(); karel.setVisible(true); } }); }
e1fd947b-e258-4eea-a0b9-b253bad153c1
3
public void actionPerformed(ActionEvent e) { // get the strings to be added to the database... String dateStr = dateField.getText(); String startTimeStr = startTimeField.getText(); String endTimeStr = endTimeField.getText(); // Date to indicate the start day (00:00 on that day) Date date = null; // Start and end times for the event: represented as times on Jun 1 1970 // to facilitate arithmetic. Date startTime = null; Date endTime = null; // Time zone to be assigned to Date date. TimeZone timeZone = TimeZone.getDefault(); // set time zones. since sdf1 is already offset by virtue of being adjusted // to the local time, sdf 2, which holds only hours from Unix Epoch 0, should // not be changed. sdf1.setTimeZone(timeZone); sdf2.setTimeZone( TimeZone.getTimeZone("UTC") ); // Using validation functions, initialize the three Date objects from // the strings entered in the fields. date = Validation.validDate(dateStr, sdf1); startTime = Validation.validDate(startTimeStr, sdf2); endTime = Validation.validDate(endTimeStr, sdf2); if(date == null || startTime == null || endTime == null) { // Tell the user they entered an invalid time. Which they did. startTimeField.setText(UI_TIME_ERROR); } else { // Calculate the startSecond and duration of the block, and write them to the db. long startSecond = ( startTime.getTime() / 1000l ) + ( date.getTime() / 1000l ) ; int duration = (int) ( endTime.getTime() - startTime.getTime() ) / 1000; // Add a new row to the database. addDBRow( startSecond, duration, typeField.getText(), commentArea.getText() ); // Also add this data to the table model in the same session // without reading the DB. String[] rowData = new String[4]; rowData[0] = typeField.getText(); rowData[1] = TIME_DISPLAY_FORMAT.format( startSecond * 1000 ); rowData[2] = TIME_DISPLAY_FORMAT.format( ( startSecond + duration ) * 1000 ); rowData[3] = commentArea.getText(); // With a single line of code, we add a row to the table! session.getViewPannel().getTableModel().addRow(rowData); } }
14ebd1e0-7ff2-4196-8079-e7ab311110c1
6
private void handleIOException( SelectionKey key, WebSocket conn, IOException ex ) { onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.closeConnection( CloseFrame.ABNORMAL_CLOSE, ex.getMessage() ); } else if( key != null ) { SelectableChannel channel = key.channel(); if( channel != null && channel.isOpen() ) { // this could be the case if the IOException ex is a SSLException try { channel.close(); } catch ( IOException e ) { // there is nothing that must be done here } if( WebSocketImpl.DEBUG ) System.out.println( "Connection closed because of" + ex ); } } }
ce5916d5-6800-4cb3-a6ef-93820053e5b3
2
public static String implodeArray(final String[] inputArray, final String glueString) { String output = ""; if (inputArray.length > 0) { StringBuilder sb = new StringBuilder(); sb.append(inputArray[0]); for (int i = 1; i < inputArray.length; i++) { sb.append(glueString); sb.append(inputArray[i]); } output = sb.toString(); } return output; }
202ec894-b508-4e79-b684-c480d3d91227
5
public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); StringBuilder out = new StringBuilder(); int boards = in.nextInt(); v = new int[8][8]; allSol = new int[93][9]; nsol = 0; board = new int[9]; queens(1); for (int i = 0; i < boards; i++) { for (int j = 0; j < 8; j++) for (int k = 0; k < 8; k++) v[j][k] = in.nextInt(); int ans = 0, curSum = 0; for (int j = 0; j < nsol; j++) { curSum = 0; for (int k = 1; k <= 8; k++) curSum+=v[k-1][allSol[j][k]-1]; ans = Math.max(ans, curSum); } out.append(String.format("%5d", ans) + "\n"); } System.out.print(out); }
30e65769-a475-4667-b823-e13766c777a5
4
public List<List<Integer>> generate(int numRows) { Integer[][] triangle = new Integer[numRows][]; // error List<List<Integer>> triangle = new // ArrayList<ArrayList<Integer>>(); //o(n*n) for (int i = 1; i <= numRows; i++) { Integer[] row = new Integer[i]; if (i == 1) { row[0] = 1; triangle[i-1] = row; continue; } Integer[] beforeRow = triangle[i-2]; row[0] = 1 ; for (int j = 1; j < i - 1; j++) { row[j] = beforeRow[j-1] + beforeRow[j]; } row[i-1] = 1; triangle[i-1] = row; } //o(n*n) List<List<Integer>> result = new ArrayList<List<Integer>>(); for(int i =0;i <numRows; i++){ ArrayList<Integer> tmp = new ArrayList<Integer>(); Integer[] ii = triangle[i]; result.add(Arrays.asList(ii)); } return result; }
d4bf41fa-2102-41aa-8f1b-bbad674c9310
8
public int agregarProspecto(String name, String surname1, String surname2, String mail, String DNI, String telefono, String contact_date) { boolean Nocaracter = validarFormato(name); boolean Nocaracter2 = validarFormato(surname1); boolean Nocaracter3 = validarFormato(mail); int condicion = 0; //###########Validando existe como prospecto o como cliente?############ tablaDeProspectos(); db_Cliente = clientes.tablaDeClientes(); for (Prospecto prospecto : datos){ if(prospecto.getDNI().equals(DNI)){ condicion = 1; System.out.println("El prospecto ya existe"); } } for (Cliente cliente : db_Cliente){ if(cliente.getDNI().equals(DNI)){ condicion = 1; System.out.println("No puede crear este Prospecto puesto que ya es un Cliente"); } } //Refactorizado name.equals("") || surname1.equals("") || surname2.equals("") if (Nocaracter == true || Nocaracter2==true || mail.isEmpty()){ System.out.println("Hay un error en el ingreso de los campos: 'Nombre', 'Email' o 'Apellido Paterno'" + "\n" + "Recuerde que estos campos son mandatorios"); condicion = 1; } //Si el prospecto ya existe entonces "condicion" será igual a 1 y no ingresará en la sentencia "if" //Ahora agregaremos el usuario: if(condicion == 0){ Prospecto nuevoProspecto = new Prospecto(name, surname1, surname2, mail, DNI, telefono, contact_date); datos.add(nuevoProspecto); System.out.println("\n" + "PROSPECTO AGREGADO CORRECTAMENTE" + "\n" + "Los datos agregados se muestran a continuación:" + "\n"); System.out.println("DNI: \t" + "\t" + "\t" + DNI); System.out.println("Nombre: \t" + "\t" + name); System.out.println("Apellido Paterno: \t" + surname1); System.out.println("Apellido Materno: \t" + surname2); System.out.println("Email: \t" + "\t" + "\t" + mail); System.out.println("Fecha de contacto: \t" + contact_date); System.out.println("Telefono: \t" + "\t" + telefono); System.out.println("\n" + "---------------------------------"); }else { System.out.println("El prospecto no ha sido agregado"); } return condicion; }
8c23c3b1-6dec-413b-a36a-6685cec940c2
2
public void readXMLInputString(String xmlString) { try { saxParser.parse(new InputSource(new StringReader(xmlString)), DPHreader.getInstance()); } catch (final SAXException e) { System.out.println("SAXException: " + e); e.printStackTrace(); } catch (final Throwable e) { System.out.println("Other Exception: " + e); e.printStackTrace(); } }
af3c6837-7124-4e69-9673-b556301059d3
2
public Object clone() { final StackExpr[] t = new StackExpr[target.length]; for (int i = 0; i < target.length; i++) { t[i] = (StackExpr) target[i].clone(); } final StackExpr[] s = new StackExpr[source.length]; for (int i = 0; i < source.length; i++) { s[i] = (StackExpr) source[i].clone(); } return copyInto(new StackManipStmt(t, s, kind)); }
3a518105-84bd-40b9-9765-370ff8ecc4d4
8
public int findMaxScore(String[] grid){ int n = grid.length; if(n==0) return 0; int m = grid[0].length(); int N = n*m; int E = 0; Edge[] edges = new Edge[(n-1)*m+(m-1)*n]; for(int i=0; i<n; i++){ m = grid[i].length(); for(int j=0; j<m; j++){ int u = i*m+j; if(i+1<n){ int v = (i+1)*m+j; int w = Math.abs(getValue(grid[i].charAt(j)) - getValue(grid[i+1].charAt(j))); edges[E++] = new Edge(u,v,w); } if(j+1<m){ int v = i*m+j+1; int w = Math.abs(getValue(grid[i].charAt(j)) - getValue(grid[i].charAt(j+1))); edges[E++] = new Edge(u,v,w); } } } assert E==(n-1)*m+(m-1)*n; parent = new int[N]; for(int i=0; i<N; i++){ parent[i] = i; } Arrays.sort(edges); int result=0; for(int i=0; i<E; i++){ if(find(edges[i].u)!=find(edges[i].v)){ result+=edges[i].w; union(edges[i].u, edges[i].v); } } return result; }
8ef637d0-b6d8-489f-848a-ce4d213e1ae0
2
@Test @Ignore public void test_AssociationListGet() { AssociationList laAssocList = laClient.getAssociationList(5, "2012-01-25-12.36.43.023001", null); System.out.println(laAssocList.getAssociationList().size()); if (laAssocList.getAssociationList().size() > 0) { for (Association laAssoc : laAssocList.getAssociationList()) { System.out.println(laAssoc.toString()); } } }
fcba0475-55f3-445e-b483-97d3b1dd2c1e
6
public WebScraper(String[] args) throws IOException, BadLocationException { ArrayList<URL> urls = new ArrayList<URL>(); //Is URL? if(args[0].matches("^http\\://[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z]{2,3}(/\\S*)?$")) urls.add(new URL(args[0])); //Is file? else if (args[0].matches("^([\\w]\\:)(\\\\[a-z_\\-\\s0-9\\.]+)+\\.(txt)$")) { BufferedReader reader = new BufferedReader(new FileReader(args[0])); while (reader.ready()) { String read = reader.readLine(); //Reading url from file if (read.codePointAt(0) == 65279) //Byte Order Mark read = read.substring(1); urls.add(new URL(read)); } } else { throw new MalformedURLException(); } //Creating array of words String[] words = args[1].split(","); //Executable arguments String[] exargs = new String[args.length - 2]; for (int i = 0; i < exargs.length; i++) { exargs[i] = args[i+2]; } for (URL url: urls) { PageScraper scraper = new PageScraper(url, words, exargs); scrapers.add(scraper.getPage()); } }
e509580a-c9b8-4aff-be9c-9f2af42dede8
1
private static TexturePaint getCheckerPaint() { if (checkerPaint == null) { int t = 8; BufferedImage bi = new BufferedImage(t * 2, t * 2, BufferedImage.TYPE_INT_RGB); Graphics g = bi.createGraphics(); g.setColor(Color.white); g.fillRect(0, 0, 2 * t, 2 * t); g.setColor(Color.lightGray); g.fillRect(0, 0, t, t); g.fillRect(t, t, t, t); checkerPaint = new TexturePaint(bi, new Rectangle(0, 0, bi.getWidth(), bi.getHeight())); } return checkerPaint; }
0f949839-c752-4425-8228-47d1d7bf84d6
3
public static boolean testContainment(double xin, double yin, double[] pointsx, double[] pointsy) { int i, j; boolean result = false; for (i = 0, j = pointsx.length - 1; i < pointsx.length; j = i++) { if ((pointsy[i] > yin) != (pointsy[j] > yin) && (xin < (pointsx[j] - pointsx[i]) * (yin - pointsy[i]) / (pointsy[j] - pointsy[i]) + pointsx[i])) { result = !result; } } return result; } // End testContainment
f28efe59-3b11-4638-99d9-7cc23ceaab54
7
private void playnextsound() { // Only plays the next sound if the track is still playing if (!isPlaying()) return; // The sound is no longer delayed this.delayed = false; // Checks whether more loops are needed // Loops the current sound if needed if (this.currentloopcount > 0 || (this.currentloopcount < 0 && !this.released)) { this.currentloopcount --; this.currentsound = playPhase(this.currentindex); } // Or plays the next sound else { // If the track was released from an infinite loop, remembers it if (this.currentloopcount < 0) this.released = false; // Gathers the information this.currentindex ++; // If the end of the track was reached, either repeats or stops if (this.currentindex >= getMaxPhase()) { if (this.loops) this.currentindex = 0; else { this.delayed = false; this.paused = false; this.released = false; informSoundEnd(); return; } } // Updates loop count this.currentloopcount = getLoopCount(this.currentindex); // And plays the new sound this.currentsound = playPhase(this.currentindex); } }
64aa0bc0-c900-4793-b0c3-58e4f6ac0deb
9
private void donebutton2MouseClicked(java.awt.event.ActionEvent evt) throws SQLException {//GEN-FIRST:event_donebutton2MouseClicked // TODO add your handling code here: //Check title String bank = namefield.getText().toString(); String add = addressfield.getText().toString(); String accnum = accountfield.getText().toString(); String rou_bal = routingfield.getText().toString(); String acctype = acctypefield.getText().toString(); Boolean done = true; if(bank.length() == 0) { JOptionPane.showMessageDialog(null,"Please enter a bank name!"); return; } else if(add.length() == 0) { JOptionPane.showMessageDialog(null,"Please enter an address"); return; } else if(accnum.length() == 0) { JOptionPane.showMessageDialog(null,"Please enter an account number"); return; } else if(rou_bal.length() == 0) { JOptionPane.showMessageDialog(null,"Please enter a routing number"); return; } else if(acctype.length() == 0) { JOptionPane.showMessageDialog(null,"Please enter an account type"); return; } if(!isUpdating){ int result = helpers.newBank(bank, accnum, rou_bal, add, acctype); if(result == -1) { JOptionPane.showMessageDialog(null,"An entry with the given account number already exists"); return; } done = true; } else { if( helpers.updateBank(data_id, bank, accnum, rou_bal, add, acctype) == -1 ) { JOptionPane.showMessageDialog(null, "There was an issue updating the database."); done = false; } else { done = true; } } if(done == true) { //new UserAccount(helpers).setVisible(true); //dispose parent.refreshBanksList(); dispose(); } }//GEN-LAST:event_donebutton2MouseClicked
8ab0ae70-bd9e-4144-aa95-74aa12a1cbe4
1
public void clear() { M = new byte[m]; if(intersectable) { ts.clear(); } }
22ee4e6e-5761-435c-817d-3c607488d71d
3
void appendInstruction(Instruction newInstr, BytecodeInfo codeinfo) { newInstr.addr = nextByAddr.addr; newInstr.nextByAddr = nextByAddr; nextByAddr.prevByAddr = newInstr; newInstr.prevByAddr = this; nextByAddr = newInstr; /* adjust exception handlers end */ Handler[] handlers = codeinfo.getExceptionHandlers(); if (handlers != null) { for (int i = 0; i < handlers.length; i++) { if (handlers[i].end == this) handlers[i].end = newInstr; } } }
38fc6d59-e4e1-453b-abb8-d957bd520059
0
public void setVoornaam(String voornaam) { this.voornaam = voornaam; }
5a331f12-b6ac-45a1-81e3-fb5fc5701ba0
5
public static void sort(Comparable[] a) { int N = a.length; int h = 1; while (h < N/3) { h = 3*h + 1; } while (h >= 1) { for (int i = h; i < N; i++) { for (int j = i; j >= h && less(a[j], a[j-h]); j-= h) { exch(a, j, j-h); } } h = h/3; } }
e5c43485-864e-4318-bf12-624f370b48bd
4
public void tick(EnemyWave allEnemies) { // TODO Move to shootingaction so that we have only data in this class(?) //send action to all objects for (Placeable obj : getPlacablesWithinRangeOfThisTower()) { if (!obj.equals(this)) { for (GameAction currentAction : getGameActions()) { if (currentAction.hasAnAttack()) { obj.addGameActions(currentAction); } } } } super.tick(allEnemies); }
05d31e82-8ad3-4f3c-bc9d-579b4768bdc3
1
public Tree(HuntField field) { this.type = 'T'; synchronized (field) { this.position = new Position(random.nextInt(field.getXLength()), random.nextInt(field.getYLength() + 1)); while (field.isOccupied(position)) { this.position = new Position(random.nextInt(field.getXLength()), random.nextInt(field.getYLength() + 1)); } field.setItem(this, position); } }
cbfb2a8d-e727-4105-9001-f45cd1be14d5
1
protected void checkInitiate() { if (!isInitiate) { throw new IllegalStateException("RemoteClientCall is not initiate. First execute Init()."); } }
5e0e6b58-928a-4ce6-9f5c-c1706a90de43
7
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException { HttpSession sesionOk = request.getSession(); if (sesionOk.getAttribute("usuario") != null) { String alert = ""; response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String evento = request.getParameter("guardar"); if (evento != null) { if (evento.equals("insertar")) { String seriales = request.getParameter("serial"); ArrayList arraySeri = llenararray(seriales); String estado = "Prestamo"; String Identificacion = request.getParameter("identificacion"); String Fecha_prestamo = request.getParameter("Fecha"); String Hora_prestamo = request.getParameter("Hora"); String Fecha_devolucion = "No Asinado"; String Hora_Devolucion = "No Asinado"; String Tipo = request.getParameter("opciones"); String tipoCuenta = "Prestador"; int Cuenta = Integer.parseInt(sesionOk.getAttribute("Id_cuenta").toString()); datosPrestamo.setSeriales(arraySeri); datosPrestamo.setEstado(estado); datosPrestamo.setIdentificacion(Identificacion); datosPrestamo.setFecha_prestamo(Fecha_prestamo); datosPrestamo.setHora_prestamo(Hora_prestamo); datosPrestamo.setTipo(Tipo); datosPrestamo.setId_cuenta(Cuenta); datosPrestamo.setTipocuenta(tipoCuenta); datosPrestamo.setFecha_devolucion(Fecha_devolucion); datosPrestamo.setHora_devolucion(Hora_Devolucion); boolean objejecutar = false; if (seriales.equals("")) { alert += "<script type=\"text/javascript\">"; alert += "alertify.alert(\"No a ingresado seriales\");"; alert += "</script>"; request.setAttribute("alert", alert); getServletConfig().getServletContext().getRequestDispatcher("/registarprestamo.jsp").forward(request, response); } else { if (Pres.insertPrestamo(datosPrestamo)) { //ele.registrarElemento(datos_elemento); alert += "<script type=\"text/javascript\">"; alert += "alertify.alert(\"Registro Exitoso\");"; alert += "</script>"; request.setAttribute("alert", alert); getServletConfig().getServletContext().getRequestDispatcher("/registarprestamo.jsp").forward(request, response); datosPrestamo.setId_prestamo(traerId_prestamo()); if (Tipo.equals("Profesores")) { objejecutar = Pres.insertIdentificacionPro(datosPrestamo); } else if (Tipo.equals("Estudiante")) { objejecutar = Pres.insertIdentificacionEst(datosPrestamo); } Pres.insertId_cuentaxId_cuenta(datosPrestamo); Pres.registrarSeriales(datosPrestamo); Pres.cambiarestadoSeriales(datosPrestamo); } else { alert += "<script type=\"text/javascript\">"; alert += "alertify.alert(\"Error\");"; alert += "</script>"; request.setAttribute("alert", alert); getServletConfig().getServletContext().getRequestDispatcher("/registarprestamo.jsp").forward(request, response); } } } } response.sendRedirect("registarprestamo.jsp"); } } else { response.sendRedirect("index.jsp"); } }
6e085c67-5a2b-4348-b228-50758c163c97
1
@Override public void close() throws XMLStreamException { if (mWriter != null) { try { mWriter.close(); } finally { mWriter = null; } } }
7456fc5f-0c46-4c1d-98ed-00014f0953a4
9
public boolean contestCommand(CommandSender sender, String[] args) { if (args.length != 0) { return false; } else if (sender instanceof Player) { Player player = ((Player) sender).getPlayer(); MCWarClanPlayer mcPlayer = _tc.getPlayer(player.getUniqueId()); Base currentBase = mcPlayer.getCurrentBase(); if (mcPlayer.isBarbarian()) { Messages.sendMessage("You cannot contest a base when you are a member of " + mcPlayer.getColoredTeamName(), Messages.messageType.INGAME, player); } else if (currentBase != null && !currentBase.isEnemyToPlayer(mcPlayer)) { Messages.sendMessage("Use your mind... you cannot attack your own team base !", Messages.messageType.INGAME, player); } else if (!mcPlayer.hasBases()) { Messages.sendMessage("You need at least one Head Quarter, then you could launch any battle you want !", Messages.messageType.INGAME, player); } else if (currentBase == null) { Messages.sendMessage("You're not in an enemy base, you cannot contest this territory.", Messages.messageType.INGAME, player); } else if (!currentBase.hasEnoughTeamMatesToBeAttacked()) { Messages.sendMessage("Not enough players connected in " + currentBase.getTeamColoredName() + " to attack them.", Messages.messageType.INGAME, player); } else if (currentBase.isContested()) { Messages.sendMessage("This team is already attacked by another team. But nothing forbid you to help one of these two...", Messages.messageType.INGAME, player); } else { currentBase.isContested(true); // Inform the two teams ! Team attackedTeam = currentBase.get_team(); Team attackingTeam = mcPlayer.get_team(); attackedTeam.sendMessage(currentBase.get_name() + " is attacked by " + attackingTeam.getColoredName() + " !"); attackingTeam.sendMessage("Your team is attacking " + attackedTeam.getColoredName() + " !"); //Create a new thread in order to check if the enemies are defeated BukkitTask tks = new MCWarClanRoutine.ContestedBaseRoutine(currentBase, attackingTeam).runTaskTimer(_plugin, 0, 100); } } else { Messages.sendMessage("You have to be a player to perform this command !", Messages.messageType.INGAME, sender); } return true; }
099cc8f8-5a0c-439e-862d-826a39db93c3
6
public int calcularAptitud(){ int aptitud = 1; int cromFinX = 0; int cromFinY = 0; for(String mov : codificacion){ if(mov != null){ switch(mov){ case "up": cromFinY -= 1; break; case "down": cromFinY += 1; break; case "left": cromFinX -= 1; break; case "right": cromFinX += 1; break; } } } //Diferencia entre el final deseado y el obtenido por el cromosoma aptitud = (posFinX - cromFinX) + (posFinY - cromFinY); return aptitud; }
786f5df5-4e2f-4760-b12b-202a8d378700
1
private static int countTokens(String template) { int count = 0; Matcher matcher = PATTERN.matcher(template); while (matcher.find()) { count++; } return count; }
307bc90d-56e0-494f-9589-209790fd9119
7
private Vector enemyPixelMovement(Point goal) { // Point goal = board.getCastle().getCenterOfObject(); Point enemyPos = this.getPixelPosition(); int deltaX = goal.getX()-enemyPos.getX(); int deltaY = goal.getY()-enemyPos.getY(); Vector newPos; // kollar vilket håll som enemy ska gå int moveX, moveY; // check for how far it should move and if if the direction should be pos or neg. if (abs(deltaX) > pixelSpeed) { moveX = pixelSpeed; if (deltaX < 0) moveX = -moveX; } else { moveX = deltaX; } if (abs(deltaY) > pixelSpeed) { moveY = pixelSpeed; if (deltaY < 0) moveY = -moveY; } else { moveY = deltaY; } if (deltaX == 0 && deltaY == 0) { newPos = new Vector(0,0); } else { if (abs(deltaX) != 0) { newPos = new Vector(moveX, 0); } else { newPos = new Vector(0, moveY); } } return newPos; }
2fc719f2-79de-4175-912a-db0cb0cfc7dc
7
public void paint(Graphics2D g,boolean draw,boolean fill){ if (calcularVar) { calcular(); calcularVar = false; } if (draw && !fill) { g.draw(path); }else if(fill && !draw){ g.fill(path); }else if(draw && fill){ g.draw(path); g.fill(path); } }
5fe460fc-ff72-4a47-a987-e10b83449ea0
0
private StopForwarder() { // JFormDesigner - Action initialization - DO NOT MODIFY //GEN-BEGIN:initComponents putValue(NAME, "Detener Forwarder"); putValue(SHORT_DESCRIPTION, "Detener Forwarder"); putValue(LONG_DESCRIPTION, "Detener Forwarder"); putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/images/resultset_stopfw.png"))); putValue(ACTION_COMMAND_KEY, "StopForwarder"); // JFormDesigner - End of action initialization //GEN-END:initComponents }
34949896-3336-4a85-894d-b8c450ba99e0
4
public static void filledEllipse(double x, double y, double semiMajorAxis, double semiMinorAxis) { if (semiMajorAxis < 0) throw new RuntimeException("ellipse semimajor axis can't be negative"); if (semiMinorAxis < 0) throw new RuntimeException("ellipse semiminor axis can't be negative"); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*semiMajorAxis); double hs = factorY(2*semiMinorAxis); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs)); draw(); }
b55e8aae-a4a1-4e41-9512-70257756cf97
2
private String apply(String string) { StringBuilder result = new StringBuilder(); for (int i = 0; i < string.length(); ++i) { if (rules.containsKey(string.charAt(i))) { result.append(rules.get(string.charAt(i))); } else { result.append(string.charAt(i)); } } return result.toString(); }
c6bfc939-74cd-4192-b019-c05cf63e09d9
9
protected void paintLineHighlight(Graphics gfx, int line, int y) { int height = fm.getHeight(); y += fm.getLeading() + fm.getMaxDescent(); int selectionStart = textArea.getSelectionStart(); int selectionEnd = textArea.getSelectionEnd(); if(selectionStart == selectionEnd) { if(lineHighlight) { gfx.setColor(lineHighlightColor); gfx.fillRect(0,y,getWidth(),height); } } else { gfx.setColor(selectionColor); int selectionStartLine = textArea.getSelectionStartLine(); int selectionEndLine = textArea.getSelectionEndLine(); int lineStart = textArea.getLineStartOffset(line); int x1, x2; if(textArea.isSelectionRectangular()) { int lineLen = textArea.getLineLength(line); x1 = textArea._offsetToX(line,Math.min(lineLen, selectionStart - textArea.getLineStartOffset( selectionStartLine))); x2 = textArea._offsetToX(line,Math.min(lineLen, selectionEnd - textArea.getLineStartOffset( selectionEndLine))); if(x1 == x2) x2++; } else if(selectionStartLine == selectionEndLine) { x1 = textArea._offsetToX(line, selectionStart - lineStart); x2 = textArea._offsetToX(line, selectionEnd - lineStart); } else if(line == selectionStartLine) { x1 = textArea._offsetToX(line, selectionStart - lineStart); x2 = getWidth(); } else if(line == selectionEndLine) { x1 = 0; x2 = textArea._offsetToX(line, selectionEnd - lineStart); } else { x1 = 0; x2 = getWidth(); } // "inlined" min/max() gfx.fillRect(x1 > x2 ? x2 : x1,y,x1 > x2 ? (x1 - x2) : (x2 - x1),height); } }
3b53ecb9-b8c1-4344-8b4d-00aabe87ea3c
1
public LinkOpener(String uri) { try { this.uri = new URI(uri); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
5927d833-c133-4f68-b53b-9871b90c5c81
8
private static List<String> getIdListInsertStatement(SDNEntry sdne) { List<String> rtn = new ArrayList<>(); for (Map<String, Object> map : sdne.getIdList()) { String cols = SDNConstants.ELEMENT_SDNENTRYID; String vals = sdne.getUid() + ""; for (String key : map.keySet()) { if (key.equals(SDNConstants.ELEMENT_UID)) { cols = addToColsString(cols, key); vals = addToValsString(vals, map.get(key).toString(), false); } if (key.equals(SDNConstants.ELEMENT_TYPE)) { cols = addToColsString(cols, key); vals = addToValsString(vals, map.get(key).toString()); } if (key.equals(SDNConstants.ELEMENT_NUMBER)) { cols = addToColsString(cols, key); vals = addToValsString(vals, map.get(key).toString()); } if (key.equals(SDNConstants.ELEMENT_COUNTRY)) { cols = addToColsString(cols, key); vals = addToValsString(vals, map.get(key).toString()); } if (key.equals(SDNConstants.ELEMENT_ISSUEDATE)) { cols = addToColsString(cols, key); vals = addToValsString(vals, map.get(key).toString()); } if (key.equals(SDNConstants.ELEMENT_EXPIRATIONDATE)) { cols = addToColsString(cols, key); vals = addToValsString(vals, map.get(key).toString()); } } rtn.add("INSERT INTO sdnEntry_idList (" + cols + ") VALUES (" + vals + ");"); } return rtn; }
c70a80b8-aac0-42d4-ab5f-32486bc0a964
1
@Override public Object getValueAt(int arg0, int arg1) { if (arg1 == 0) return (dfa.getStates().get(arg0).getState_Properties().getName()); else return getEntry(arg0, arg1-1); }
0912548f-0e19-4be7-8535-42a546ab766f
4
public void testEqualSubsetIntersection() throws Exception { for (int i = 0; i < 100; i++) { int len = (int)(Math.random() * (10 - 1) + 1); RBtree a = randomRB( len ); RBtree b = a; if (!a.equal( b ) ) { throw new Exception("FAILURE THE TWO SETS ARE NOT EQUAL"); } if (!a.subset( a.intersection( b )) && !b.subset( b.intersection( a ))) { throw new Exception("FAILURE THE TWO SETS ARE NOT SUBSETS OF THE INTERSECTION"); } equalSubsetIntersectionTest++; } }
638f8892-ede2-4ba2-ba81-5ef317c28600
5
static void process_changesets_url_common ( URL passed_url, String passed_display_name, String passed_uid, String passed_id, String passed_min_lat_string, String passed_min_lon_string, String passed_max_lat_string, String passed_max_lon_string, String passed_download_changeset, String passed_building, boolean passed_overlapnodes, String passed_download_nodes ) throws Exception { if ( arg_debug >= Log_Informational_2 ) { System.out.println( "Url: " + passed_url ); } InputStreamReader input; URLConnection urlConn = passed_url.openConnection(); urlConn.setDoInput( true ); urlConn.setDoOutput( false ); urlConn.setUseCaches( false ); try { input = new InputStreamReader( urlConn.getInputStream() ); char[] data = new char[ 256 ]; int len = 0; StringBuffer sb = new StringBuffer(); while ( -1 != ( len = input.read( data, 0, 255 )) ) { sb.append( new String( data, 0, len )); } DocumentBuilderFactory myFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder myBuilder = myFactory.newDocumentBuilder(); ByteArrayInputStream inputStream = new ByteArrayInputStream( sb.toString().getBytes( "UTF-8" )); Document myDocument = myBuilder.parse( inputStream ); Element rootElement = myDocument.getDocumentElement(); process_changesets_xml( rootElement, passed_display_name, passed_uid, passed_min_lat_string, passed_min_lon_string, passed_max_lat_string, passed_max_lon_string, passed_download_changeset, passed_building, passed_overlapnodes, passed_download_nodes ); input.close(); } catch( Exception ex ) { if ( arg_debug >= Log_Error ) { System.out.println( "Error obtaining: " + passed_url ); } if ( arg_out_file != "" ) { myPrintStream.println( passed_display_name + ";" + passed_uid + ";" + passed_id + ";;;;0 changesets, error obtaining" ); } } }
a3cf4ef2-09e3-48ff-8c26-3ee0699e77a0
4
@GET @Path("/{id}") @Produces(MediaType.LIBROS_API_LIBRO) public Libro getLibro(@PathParam("id") int id) { Libro libro = new Libro(); Connection conn = null; Statement stmt = null; String sql; try { conn = ds.getConnection(); } catch (SQLException e) { throw new ServiceUnavailableException(e.getMessage()); } try { stmt = conn.createStatement(); sql = "SELECT * FROM libros WHERE id= '" + id + "'"; ResultSet rs = stmt.executeQuery(sql); if (rs.next()) { libro.setId(rs.getInt("id")); libro.setTitulo(rs.getString("titulo")); libro.setAutor(rs.getString("autor")); libro.setEdicion(rs.getString("edicion")); libro.setEditorial(rs.getString("editorial")); libro.setFecha_ed(rs.getDate("fecha_ed")); libro.setFecha_imp(rs.getDate("fecha_imp")); libro.setLengua(rs.getString("lengua")); libro.add(LibrosAPILinkBuilder.buildURILibroId(uriInfo, libro.getId(), "self")); } } catch (SQLException e) { throw new InternalServerException(e.getMessage()); } finally { try { stmt.close(); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return libro; }
f14abdf8-b6cf-483d-acd0-b55e646f2c64
3
public void readConfig() { /* private boolean useDefaultUQuest = true; * * Database: * private boolean useSQLite = false; * protected boolean broadcastSaving = true; * protected int SaveQuestersInfoIntervalInMinutes = 30; * * PluginSupport: * private String MoneyPlugin = "none"; * >>>protected boolean useiConomy = true; * private boolean usePermissions = true; * >>>private boolean useEssentialsEco = false; * >>>private boolean useBOSEconomy = false; * private String moneyName = "Monies"; * * QuestLevels: * protected int questLevelInterval = 50; * protected boolean scaleQuestLevels = true; * * Announcements: * protected int questAnnounceInterval = 5; * protected int questRewardInterval = 10; * * QuestDropping: * protected int dropQuestInterval = 60; * protected int dropQuestCharge = 5000; * */ FileConfiguration config = getConfig(); // Configuration config = new Configuration(new File(getDataFolder(), "config.yml")); // config.load(); useDefaultUQuest = config.getBoolean("etc.useDefaultUQuest", useDefaultUQuest); hideQuestRewards = config.getBoolean("etc.hideQuestRewards", hideQuestRewards); try{ String[] questRewardsFromFile = config.getString("etc.questRewards", questRewardsDefault).split("~"); setQuestRewards(questRewardsFromFile); //test every reward through a meaningless loop to try and get the catch to run for(int i=0; i<questRewardsFromFile.length; i++){ String rewards[] = questRewardsFromFile[i].split(","); rewards[0] = rewards[0]; rewards[1] = rewards[1]; rewards[2] = rewards[2]; int index = rewards[2].indexOf(':'); if( index != -1 ) { Short.valueOf(rewards[2].substring(index+1, rewards[2].length())); rewards[2] = rewards[2].substring(0, index); } } } catch (Exception e) { log.log(Level.SEVERE, pluginNameBracket() + " Error setting up quest rewards! Fix the config file!"); log.log(Level.SEVERE, pluginNameBracket() + " Quest item rewards are loaded as defaults!"); setQuestRewards(questRewards); } useSQLite = config.getBoolean("Database.useSQLite", useSQLite); broadcastSaving = config.getBoolean("Database.broadcastSaving", broadcastSaving); SaveQuestersInfoIntervalInMinutes = config.getInt("Database.SaveQuestersInfoIntervalInMinutes", SaveQuestersInfoIntervalInMinutes); usePermissions = config.getBoolean("PluginSupport.usePermissions", usePermissions); moneyName = config.getString("PluginSupport.moneyName", moneyName); //*** money plugin stuff ***// // pluginTimerCheck = config.getInt("PluginSupport.pluginTimerCheck", pluginTimerCheck); // Money_Plugin = config.getString("PluginSupport.MoneyPlugin", "none"); // if(Money_Plugin.equalsIgnoreCase("iConomy")) // this.useiConomy = true; // if(Money_Plugin.equalsIgnoreCase("BOSEconomy")) // this.useBOSEconomy = true; // if(Money_Plugin.equalsIgnoreCase("Essentials")) // this.useEssentials = true; questLevelInterval = config.getInt("QuestLevels.questLevelInterval", questLevelInterval); scaleQuestLevels = config.getBoolean("QuestLevels.scaleQuestLevels", scaleQuestLevels); questAnnounceInterval = config.getInt("Announcements.questAnnounceInterval", questAnnounceInterval); questRewardInterval = config.getInt("Announcements.questRewardInterval", questRewardInterval); dropQuestInterval = config.getInt("QuestDropping.dropQuestInterval", dropQuestInterval); dropQuestCharge = config.getInt("QuestDropping.dropQuestCharge", dropQuestCharge); }
8be570f4-f1ed-43b9-b41f-861f1972c9a3
8
@EventHandler public void onRedstoneChange(BlockRedstoneEvent e) { Block block = e.getBlock(); int startX = block.getX()-1; int startY = block.getY()-1; int startZ = block.getZ()-1; int endX = block.getX()+1; int endY = block.getY()+1; int endZ = block.getZ()+1; for(int x = startX; x <= endX; x++) for(int y = startY; y <= endY; y++) for(int z = startZ; z <= endZ; z++) if(block.getWorld().getBlockAt(x,y,z).getTypeId() == 63 || block.getWorld().getBlockAt(x,y,z).getTypeId() == 68) { Block b = block.getWorld().getBlockAt(x,y,z); Sign sign = (Sign) b.getState(); if (b.isBlockPowered()){ if(sign.getLine(0).equalsIgnoreCase("[replace]")) { if (!sign.getLine(1).equalsIgnoreCase("")) { prRegion pr = new prRegion(); pr.place(sign.getLine(1), sign.getWorld()); } } } } }
14e2b706-c70f-4afb-82f0-3c242b39ec1a
3
@Override public void messageReceived(MessageEvent arg0) { final String msg = arg0.getMessage().toLowerCase(); if (msg.contains("you successfully chop away some ivy.")) { chopped++; } if (msg.contains("a bird's nest falls out of the") && !Inventory.isFull()) { System.out.println("A bird's nest fell on the ground!"); nest = true; } }
b73dee4c-f0f9-4aa2-a475-d91cfee2efa3
6
public void moveBothServos(int pos1, int pos2) { if (!isConnected()) { error("Robot is not connected!", "RXTXRobot", "moveBothServos"); return; } debug("Moving both servos to positions " + pos1 + " and " + pos2); if (!getOverrideValidation() && (pos1 < 0 || pos1 > 180 || pos2 < 0 || pos2 > 180)) error("Positions must be >=0 and <=180. You supplied " + pos1 + " and " + pos2 + ". One or more are invalid.", "RXTXRobot", "moveBothServos"); else sendRaw("V " + pos1 + " " + pos2); }
5ac00178-3aa6-4846-9144-40c1fdec4d4e
2
public int[] plusOne(int[] digits) { int carry = 1; for(int i = digits.length - 1; i >= 0; --i){ int tmp = digits[i] + carry; digits[i] = tmp % 10; carry = tmp / 10; } if(carry == 1){ int [] res = new int[digits.length+1]; res[0] = 1; System.arraycopy(digits, 0, res, 1, digits.length); return res; } return digits; }
5c89feab-c1bb-4dec-99b4-81a3c3a07903
3
public void actionPerformed(ActionEvent e) { log(e); if(((JButton)e.getSource()).getText().equals(STARTMENU_BUTTON_START)){ } else if(((JButton)e.getSource()).getText().equals(STARTMENU_BUTTON_ABOUT)){ forwardAction("MyStyles.MyFrames.AboutMenuFrame"); } else if(((JButton)e.getSource()).getText().equals(STARTMENU_BUTTON_EXIT)){ myFrame.dispose(); System.exit(0); } }
a43ea0af-c060-48fd-9101-3a3593fc892f
3
public void Architecture() throws IOException{ bins=new Bin[binNo]; for(int i=0; i<binNo; i++) bins[i]=new Bin(); sortBins(); for(int i=0; i<archL; i++){ hiddenLayersNo=i+1; updateArchNodes(hiddenLayersNo-1); } System.out.print("\nBest architecture:\n"); for(int l=0; l < bestArch.length; l++) System.out.print(bestArch[l]+" "); statistics(bestArchError); }
53389911-e437-4cbf-bde5-a25dde4843ed
2
public void flipVertical() { byte image[] = new byte[width * height]; int off = 0; for (int j = height - 1; j >= 0; j--) { for (int k = 0; k < width; k++) { image[off++] = pixels[k + j * width]; } } pixels = image; offsetY = trimHeight - height - offsetY; }
f91e4cb0-0fc6-4bc2-88f1-98582ecef67b
1
public Display(Alloy alloy, String[] hn, String message) { super(message); this.alloy = alloy; this.hostNames = hn; this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(alloy.getWidth() + 5, alloy.getHeight() + 36); this.setLocationRelativeTo(null); this.setLayout(new BorderLayout()); this.establishCanvas(); this.setColorBenchmarks(); this.tempBuffer = new long[alloy.getWidth()][alloy.getHeight()]; this.futures = new ScheduledFuture<?>[4]; this.sockets = new Socket[4]; this.out = new ObjectOutputStream[4]; this.in = new ObjectInputStream[4]; }
091eb5e7-e5f1-485b-8c75-d2464e3b7e54
7
private AVLNode balance() { switch( heightRightMinusLeft() ) { case 1: case 0: case -1: return this; case -2: if( left.heightRightMinusLeft() > 0 ) { setLeft( left.rotateLeft(), null ); } return rotateRight(); case 2: if( right.heightRightMinusLeft() < 0 ) { setRight( right.rotateRight(), null ); } return rotateLeft(); default: throw new RuntimeException( "tree inconsistent!" ); } }
2f04a57c-12dc-462e-bfc5-2061942bfa3e
4
private void timeOut() { boolean timedOutBeforeConnecting = false; boolean timedOutAfterConnecting = false; synchronized(CONNECTION_LOCK) { if(isAttemptingToConnect) { logger.fine("Connection to " + serverAddress + ":" + serverPort + " timed out"); closeConnection(); timedOutBeforeConnecting = true; } else if(isConnected) { logger.fine("Connect request to " + serverAddress + ":" + serverPort + " timed out"); disconnectQuietly(); timedOutAfterConnecting = true; } //it should be impossible for timedOut() to get called if the // ClientConnection is neither connected nor attempting to connect, // but we'll check for both separately and not assume anything } //once again, exactly one of these could be true, but we're making sure // both don't get run and not assuming one not happening implies the // other happening= if(timedOutBeforeConnecting) { onCouldNotConnect(ClientConnection.CONNECT_REQUEST_TIMED_OUT); } else if(timedOutAfterConnecting) { onDisconnected(ClientConnection.CONNECTION_TIMED_OUT); } }
ad31be05-8265-47bf-b3db-88fb39ceb1a8
3
public static boolean isCollision(Circle c1, Circle c2) { if (c1 == null || c2 == null) return false; int xDist = c1.x - c2.x; int yDist = c1.y - c2.y; int rSum = c1.r + c2.r; if (Math.pow(xDist, 2) + Math.pow(yDist, 2) <= Math.pow(rSum, 2)) { return true; } return false; }
2d35794e-1ffb-402d-a5cd-f2dd212ea586
0
public String allFits(){ return this.fitnessArr.toString(); }
abcc0d56-0b8a-48f0-8a33-aefde1ec58e1
2
public boolean temPermissao(String nome, String senha) { if ((getNome().compareToIgnoreCase(nome) == 0) && (getSenha().compareToIgnoreCase(senha) == 0)) { return true; } return false; }
a7d64164-f3a5-4879-a2e3-fa977af33e21
2
public Integer getPrimaryGroup(Connection con, String user) { /* Compose query. */ String SQL_QUERY = "SELECT user_group_id " + "FROM xf_user " + "WHERE username=?;"; /* Execute query. */ try { PreparedStatement stmt = con.prepareStatement(SQL_QUERY); stmt.setString(1, user); ResultSet rs = stmt.executeQuery(); /* Return first result */ if(rs.next()) { Integer result = rs.getInt("user_group_id"); return result; } } catch (SQLException e) { e.printStackTrace(); } return null; }
a84cca4d-1b36-4f62-8801-9c156071129f
0
protected void onRemoveModerated(String channel, String sourceNick, String sourceLogin, String sourceHostname) {}
3724a11e-d269-4189-956b-8f7ff66c833d
6
private static void configureDevelopmentLogging() { // Configure console logger devConsoleHandler = new ExtendedConsoleHandler(); devConsoleHandler.setFormatter(new DevLogFormatter()); // Configure file logger try { new File("./log").mkdir(); devFileHandler = getFileHandler(true); if (DEV_MODE) { // log everything to the log file if(VERBOSE) { devFileHandler.setLevel(Level.ALL); } else { devFileHandler.setLevel(Level.FINE); } } else { // define the behavior of the development handler in productive // mode // log everything important into the dev log file if(VERBOSE) { devFileHandler.setLevel(Level.CONFIG); } else { devFileHandler.setLevel(Level.INFO); } } } catch (Exception e) { System.out.println("Es wird keine Protokolldatei erzeugt: " + e.getMessage()); } if (DEV_MODE) { // log more information on the console if (VERBOSE) { devConsoleHandler.setLevel(Level.ALL); } else { devConsoleHandler.setLevel(Level.INFO); } } else { // define the behavior of the development handler in productive mode devConsoleHandler.setLevel(Level.SEVERE); // show important errors // on the console } }
d17ba2c9-4a47-4666-ab22-45b060631318
8
public static FileCache foruser() { try { String path = System.getProperty("user.home", null); if(path == null) return(null); File home = new File(path); if(!home.exists() || !home.isDirectory() || !home.canRead() || !home.canWrite()) return(null); File base = new File(new File(home, ".haven"), "cache"); if(!base.exists() && !base.mkdirs()) return(null); return(new FileCache(base)); } catch(SecurityException e) { return(null); } }
8271eadf-f288-45b5-8dc7-751f031bfe89
4
public void update() { up = keys[KeyEvent.VK_UP]; down = keys[KeyEvent.VK_DOWN]; right = keys[KeyEvent.VK_RIGHT]; left = keys[KeyEvent.VK_LEFT]; space = toggle(KeyEvent.VK_SPACE); enter = toggle(KeyEvent.VK_ENTER); escape = toggle(KeyEvent.VK_ESCAPE); if(JudokaComponent.gameState == JudokaComponent.GameState.MENU){ menuUp = toggle(KeyEvent.VK_UP); menuDown = toggle(KeyEvent.VK_DOWN); menuLeft = toggle(KeyEvent.VK_LEFT); menuRight = toggle(KeyEvent.VK_RIGHT); } if(JudokaComponent.gameState == GameState.MENU){ d = toggle(KeyEvent.VK_D); a = toggle(KeyEvent.VK_A); w = toggle(KeyEvent.VK_W); s = toggle(KeyEvent.VK_S); }else{ d = keys[KeyEvent.VK_D]; a = keys[KeyEvent.VK_A]; w = keys[KeyEvent.VK_W]; s = keys[KeyEvent.VK_S]; } q = toggle(KeyEvent.VK_Q); e = toggle(KeyEvent.VK_E); r = toggle(KeyEvent.VK_R); t = toggle(KeyEvent.VK_T); y = toggle(KeyEvent.VK_Y); u = toggle(KeyEvent.VK_U); i = toggle(KeyEvent.VK_I); o = toggle(KeyEvent.VK_O); p = toggle(KeyEvent.VK_P); f = toggle(KeyEvent.VK_F); g = toggle(KeyEvent.VK_G); h = toggle(KeyEvent.VK_H); j = toggle(KeyEvent.VK_J); k = toggle(KeyEvent.VK_K); l = toggle(KeyEvent.VK_L); z = toggle(KeyEvent.VK_Z); x = toggle(KeyEvent.VK_X); c = toggle(KeyEvent.VK_C); v = toggle(KeyEvent.VK_V); b = toggle(KeyEvent.VK_B); n = toggle(KeyEvent.VK_N); m = toggle(KeyEvent.VK_M); k1 = toggle(KeyEvent.VK_1); k2 = toggle(KeyEvent.VK_2); k3 = toggle(KeyEvent.VK_3); k4 = toggle(KeyEvent.VK_4); k5 = toggle(KeyEvent.VK_5); k6 = toggle(KeyEvent.VK_6); k7 = toggle(KeyEvent.VK_7); k8 = toggle(KeyEvent.VK_8); k9 = toggle(KeyEvent.VK_9); k0 = toggle(KeyEvent.VK_0); backSpace = toggle(KeyEvent.VK_BACK_SPACE); period = toggle(KeyEvent.VK_PERIOD); if(toggle(KeyEvent.VK_F3)) { if(Sound.alternativeBattleMusic)Sound.alternativeBattleMusic = false; else Sound.alternativeBattleMusic = true; } }
c62ac90a-2a02-400f-b790-43f63affe174
6
private void overwriteShapeDefault(Attributes attrs) { // loop through all attributes, setting appropriate values for (int i = 0; i < attrs.getLength(); i++) { if (attrs.getQName(i).equals("color")) shapeDef.setColor(new Color(Integer.valueOf(attrs.getValue(i), 16))); else if (attrs.getQName(i).equals("thickness")) shapeDef.setThickness(Integer.valueOf(attrs.getValue(i))); else if (attrs.getQName(i).equals("fill")) shapeDef.setFill(Boolean.valueOf(attrs.getValue(i))); else if (attrs.getQName(i).equals("alpha")) shapeDef.setAlpha(Integer.valueOf(attrs.getValue(i))); else if (attrs.getQName(i).equals("filltype")) shapeDef.setFillType(Integer.valueOf(attrs.getValue(i))); } }
a5b75e17-1b3c-4ee7-a229-24fe1a3fb8e9
9
public HTML addClasses(final String...classtypes) { if ( classtypes == null ) return this; final String classesAsString = this.getOrCreateAttr("class"); final List<String> classesAsArray = new ArrayList<String>( ); for (final String s : classesAsString.split(" ")) classesAsArray.add(s); for (final String classtype : classtypes) { boolean duplicated = false; for (final String sClass : classesAsArray) if ( classtype.equals(sClass) ) duplicated = true; if ( !duplicated ) classesAsArray.add(classtype); } if ( classesAsArray.size( ) > 0 ) { final StringBuilder sb = new StringBuilder( ); sb.append(classesAsArray.get(0)); for (int i = 1; i < classesAsArray.size( ); i++) { sb.append(classesAsArray.get(i)); if ( !(i == classesAsArray.size( ) - 1) ) sb.append(" "); } this.attr.put("class", sb.toString( )); } return this; }
2d8b0534-2ab3-41c5-b26b-66a7c0f3fa59
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(EditionFacture.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EditionFacture.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EditionFacture.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EditionFacture.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 EditionFacture().setVisible(true); } }); }
69ac1df8-95f9-41a2-a54d-265acd93a613
6
public void createScreenShot() { File screenshotFile = null; JFileChooser chooser = new JFileChooser(); UIManager.put("FileChooser.saveDialogTitleText", "Save Michelizer Screenshot"); SwingUtilities.updateComponentTreeUI(chooser); chooser.setSelectedFile(new File("Michelizer_Output.jpg")); screenshotFile = chooser.getSelectedFile(); if(JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(this)) { // Wait for JFileChooser to close! try { Thread.sleep(750); } catch (InterruptedException ie) { ie.printStackTrace(); } screenshotFile = chooser.getSelectedFile(); String path = screenshotFile.getAbsolutePath().substring(0, screenshotFile.getAbsolutePath().length() - screenshotFile.getName().length()); String fileName = screenshotFile.getName().substring(0, screenshotFile.getName().length()-4); String extension = ".jpg"; if(screenshotFile.exists()) { int counter = 1; while(screenshotFile.exists()) screenshotFile = new File(path + fileName + " (" + counter++ + ")" + extension); } try { JComponent j = jT; while(!(j.getParent() instanceof JFrame)) j = (JComponent)j.getParent(); Rectangle r = new Rectangle(j.getParent().getX(), j.getParent().getY(), jT.getWidth(), jT.getHeight()); BufferedImage bi = ScreenImage.createImage(r); ScreenImage.writeImage(bi, screenshotFile.getAbsolutePath()); } catch(Exception exception) { exception.printStackTrace(); } } }
c530a7fe-8c3c-4552-addf-488bd6f46ed5
3
private void cutButtonAction() { // No ads found if (results.isEmpty()) { text.append(String.format("No ads found.%s", newline)); setStateInitial(); return; } // Validate specified cut times if (!validateCutTimes()) { return; } // Print cut info and disable panels for(VideoSectionPanel panel : results) { text.append(String.format("%s%s", panel.getInfo(), newline)); panel.setEnabled(false); } // Initialize progress and start generating output video mediator.startCuttingAds(videoSections, currentFile); setStateFinishing(); }
8ed7fb67-e028-48d1-b587-1c8bf1dea114
0
public double getRad(){ return rad; }
8c0cb09c-65aa-48f5-8cf6-928de9d6032b
8
private void moveComponents( Container target, int x, int y, int width, int height, int columnStart, int columnEnd, boolean ttb) { switch (align) { case TOP: y += ttb ? 0 : height; break; case CENTER: y += height / 2; break; case BOTTOM: y += ttb ? height : 0; break; } for (int i = columnStart ; i < columnEnd ; i++) { Component m = target.getComponent(i); if (m.isVisible()) { int cx; cx = x + (width - m.getSize().width) / 2; if (ttb) { m.setLocation(cx, y); } else { m.setLocation(cx, target.getSize().height - y - m.getSize().height); } y += m.getSize().height + vgap; } } }
4b5372f6-d0e2-4dc3-bd6a-92b873620edd
8
private int countCompletelySolvedTopEdgeCubie() { int count = 0; RubiksCube rc = this.initialRcConfig; // Get the four top layer edge cubies Cubie frontTopFaceEdgeCubie = rc.getCubie(2, 3, 3); Cubie rightTopFaceEdgeCubie = rc.getCubie(3, 3, 2); Cubie backTopFaceEdgeCubie = rc.getCubie(2, 3, 1); Cubie leftTopFaceEdgeCubie = rc.getCubie(1, 3, 2); // Get top color from top face center cubie Facelet topColor = rc.getCubie(2, 3, 2).getTopFace(); // Check front top edge boolean isFrontEdgeSolved = frontTopFaceEdgeCubie.getTopFace().equals(topColor) && frontTopFaceEdgeCubie.getFrontFace().equals(rc.getCubie(1, 3, 3).getFrontFace()); if (isFrontEdgeSolved) { count++; } // Check right top edge boolean isRightEdgeSolved = rightTopFaceEdgeCubie.getTopFace().equals(topColor) && rightTopFaceEdgeCubie.getRightFace().equals(rc.getCubie(3, 3, 3).getRightFace()); if (isRightEdgeSolved) { count++; } // Check back top edge boolean isBackEdgeSolved = backTopFaceEdgeCubie.getTopFace().equals(topColor) && backTopFaceEdgeCubie.getBackFace().equals(rc.getCubie(3, 3, 1).getBackFace()); if (isBackEdgeSolved) { count++; } // Check left top edge boolean isLeftEdgeSolved = leftTopFaceEdgeCubie.getTopFace().equals(topColor) && leftTopFaceEdgeCubie.getLeftFace().equals(rc.getCubie(1, 3, 1).getLeftFace()); if (isLeftEdgeSolved) { count++; } return count; }
6921f147-9f19-4000-b909-14505753a377
2
public void gaFram () { if (aktuell >= 0 && aktuell < Polylinje.this.horn.length - 1) aktuell++; else aktuell = -1; }
1695888e-51b9-448e-aad2-a93e4b54ef3d
8
static private void parseVariables(DodsV parent, Enumeration children) { while (children.hasMoreElements()) { opendap.dap.BaseType bt = (opendap.dap.BaseType) children.nextElement(); if (bt instanceof DList){ String mess = "Variables of type "+bt.getClass().getName()+" are not supported."; logger.warn(mess); continue; } DodsV dodsV = new DodsV(parent, bt); if (bt instanceof DConstructor) { DConstructor dcon = (DConstructor) bt; java.util.Enumeration enumerate2 = dcon.getVariables(); parseVariables(dodsV, enumerate2); } else if (bt instanceof DArray) { DArray da = (DArray) bt; BaseType elemType = da.getPrimitiveVector().getTemplate(); dodsV.bt = elemType; dodsV.darray = da; if ((elemType instanceof DGrid) || (elemType instanceof DSequence) || (elemType instanceof DList)){ String mess = "Arrays of type "+elemType.getClass().getName()+" are not supported."; logger.warn(mess); continue; } if (elemType instanceof DStructure) { // note that for DataDDS, cant traverse this further to find the data. DConstructor dcon = (DConstructor) elemType; java.util.Enumeration nestedVariables = dcon.getVariables(); parseVariables(dodsV, nestedVariables); } } parent.children.add(dodsV); } }
de29d9fe-967d-4afe-9c44-def34a6c7f35
4
public double[] marginalProbability(int x_i) { int n = potentials.chainLength(); int k = potentials.numXValues(); double[] result = new double[k+1]; sum = 0; result[0] = 0; for (int v =1 ; v <= k ; v++) { result[v] = messageFactor2Node(x_i, x_i, v); if (x_i != 1) { // not the first one result[v] *= messageFactor2Node(n+x_i -1, x_i, v); } if (x_i != n) { result[v] *= messageFactor2Node(n+x_i, x_i, v); // not the last one } sum += result[v]; } // normalization for (int v =1 ; v <= k ; v++) { result[v] /= sum; } return result; }
97fa6c75-57ff-4b3e-8388-9b097e42d45d
3
public SingleTreeNode treePolicy() { SingleTreeNode cur = this; while (!cur.state.isGameOver() && cur.m_depth < ROLLOUT_DEPTH) { if (cur.notFullyExpanded()) { return cur.expand(); } else { SingleTreeNode next = cur.uct(); //SingleTreeNode next = cur.egreedy(); cur = next; } } return cur; }
0a32cec8-0e0f-40ef-b3b4-eee9b3f59fb5
4
public Decifra(File arquivo){//construtor try{ //tratamento de erro sobre a read do arquivo arquivoR = new FileReader(arquivo); //abre o arquivo buffer = new BufferedReader(arquivoR); while(buffer.ready()){ code[read]=buffer.readLine();//code recebe o que esta na buffer a cada linha, assim cada posicao do vetor de string tem uma linha code[read]=code[read].replaceAll("\t",""); if(code[read].startsWith("IMPRIMA('")){ } else { code[read]=code[read].replaceAll(" ",""); // retira os espacos das strings } read++;//incremento do vetor countLine++;//contador de linhas } buffer.close();//fecha o arquivo } catch (FileNotFoundException ex){ } catch (IOException er){ } objVariavel.procuraVariavel(code,countLine);//declaracao de variaveis }
7d1ced4e-92b4-49dd-b3e3-70a1804fa810
7
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ Boolean result = (Boolean) resultFututre.get(); if (wasInsert == true) { if (result == true) { request.setAttribute("error", "Item succesfully inserted!"); } else if (result == false) { request.setAttribute("error", "Insertion of item failed!"); } } else if (wasInsert == false) { if (result == true) { request.setAttribute("error", "Item succesfully removed!"); } else if (result == false) { request.setAttribute("error", "Removal of item failed!"); } } request.getRequestDispatcher("/item.jsp").forward(request, response); }catch(NullPointerException ex){} }
f7077feb-ace5-496e-ad77-e418a4c19182
7
public void mouseDragged(MouseEvent e) { if(this.laf.bh.ccol.getState()==false) { Graphics g; Color c=Color.BLACK; g=this.getGraphics(); g.clearRect(0,0,this.getWidth(),this.getHeight()); this.paint(g); xf=e.getX(); yf=e.getY(); switch(this.laf.bh.couleur.getSelectedIndex()) { case 0: c=Color.BLUE;break; case 1: c=Color.ORANGE;break; case 2: c=Color.RED;break; } g=this.getGraphics(); g.setColor(c); switch(this.laf.bh.forme.getSelectedIndex()) { case 0: { Droite d=new Droite(xi,yi,xf,yf,c); d.seDessiner(g); break;} case 1: { Cercle c1=new Cercle(xi,yi,xf,yf,c); c1.seDessiner(g); break;} case 2:{ Rectangle r=new Rectangle(xi,yi,xf,yf,c); r.seDessiner(g); break;} } } }
21b43a6d-2cda-4dcd-9ad6-138046dc93cc
2
private void setTrafficNodes(InterfaceRequiredMethods n, double duration, Distribution dist) { if (dist instanceof UniformDistribution) { int rate = (int) dist.nextSample(); double interval = duration / rate; // uniforme distribuição para escolher um tempo de 0 a 10 minutos para iniciar a sequencia de eventos daquele nodo //UniformDistribution ud = new UniformDistribution(0, 5); //double time = interval + (((int)ud.nextSample()) * 60); double time = 1; System.out.println("########## rate="+rate); System.out.println("########## time="+time); int qntEventos = (int) ((duration / 60) * rate); while (qntEventos > 0) { n.sentEventRelative(time); time += interval; qntEventos -= 1; } } }
ff70f9a3-8c8a-4b03-a208-8b2f6203f1f5
8
public Matrix solve(Matrix B) { if (B.getRowDimension() != n) { throw new IllegalArgumentException("Matrix row dimensions must agree."); } if (!isspd) { throw new RuntimeException("Matrix is not symmetric positive definite."); } // Copy right hand side. double[][] X = B.getArrayCopy(); int nx = B.getColumnDimension(); // Solve L*Y = B; for (int k = 0; k < n; k++) { for (int j = 0; j < nx; j++) { for (int i = 0; i < k ; i++) { X[k][j] -= X[i][j]*L[k][i]; } X[k][j] /= L[k][k]; } } // Solve L'*X = Y; for (int k = n-1; k >= 0; k--) { for (int j = 0; j < nx; j++) { for (int i = k+1; i < n ; i++) { X[k][j] -= X[i][j]*L[i][k]; } X[k][j] /= L[k][k]; } } return new Matrix(X,n,nx); }
7f866078-e91a-4848-a87c-17a024d93c07
6
final void method546(int i, int i_40_, int i_41_) { if (i_41_ == -2) { if (i_40_ == 0) { anInt5280 = -(i >= 0 ? i : -i) + anInt5278; anInt5289 = 4096; anInt5280 = anInt5280 * anInt5280 >> -1109421716; anInt5290 = anInt5280; } else { anInt5289 = anInt5280 * anInt5298 >> -640192180; if ((anInt5289 ^ 0xffffffff) > -1) anInt5289 = 0; else if ((anInt5289 ^ 0xffffffff) < -4097) anInt5289 = 4096; anInt5280 = anInt5278 + -(i < 0 ? -i : i); anInt5280 = anInt5280 * anInt5280 >> 655434060; anInt5280 = anInt5289 * anInt5280 >> 62440396; anInt5290 += anInt5280 * anInt5285 >> 830941324; anInt5285 = anInt5285 * anInt5279 >> 1740894476; } anInt5292++; } }
d1f49844-cc51-4d93-9431-abe9d5f16baa
1
@Override protected void logBindInfo(Method method) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("绑定" + getDescription() + "到方法[" + method + "]成功"); } }
8a77244d-32b0-440c-a3cc-b9fa22d89ec0
9
public void generateDataforCassandraHector(int uID, int noOfReplicas, int minute, int rate) { int tsID = 0; long executedTime = 0; String timeStampOutput = ""; int noOfSamples = minute * rate * 60; try { DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); uconn.cse.cassperf.hectorcassandraclient.InsertRowsForDataCF iRFCF = new uconn.cse.cassperf.hectorcassandraclient.InsertRowsForDataCF(); Double Value = 0.0; // System.out.println(rate); // System.out.println(noOfSamples); // System.out.println(minute); long firstStartTime = System.currentTimeMillis(); // double[] values = new double[rate]; // for (int i = 0; i < rate; i++) { // values[i] = 1; // } Date date = new Date(); String startTime = dateFormat.format(date); // get the time when // sensor starts to put // data to the backend System.out.println("startTime-" + startTime); if (rate > 1000) { // System.out.println("Here"); while (tsID < noOfSamples - rate + 1) { // long timeStart2 = System.currentTimeMillis(); // Random randomGenerator = new Random(); // for (int i = 0; i < rate; i++) { //comment if need to use // the execute2 function long timeStart = System.currentTimeMillis(); // while (System.currentTimeMillis() - timeStart < 1000 / // rate) { // } // System.out.println(timeStart + " " + currentTime + " " + // 1.0*1000 / rate); // System.out.println(1.0*(currentTime - timeStart) + " " + // (1.0)*1000 / rate); // tsID++; // Value = 1.0; // iRFCF.execute(uID, tsID++); // create an array of values then put the whole array to the // backend executedTime += iRFCF.executeMultiColumns(uID, tsID, rate); // test += tsID; tsID += rate; logger.info("ID : " + tsID + "-" + dateFormat.format(new Date())); timeStampOutput += "ID : " + tsID + "-" + dateFormat.format(new Date()) + "\n"; if ((System.currentTimeMillis() - timeStart) < 1000) Thread.sleep(1000 - (System.currentTimeMillis() - timeStart)); // end of this module // } // System.out.println("Took " + (System.currentTimeMillis() // - timeStart2)); // System.out.println(tsID + " " + Value); // if (tsID % 1000 == 0) { // System.out.println(Value); // // break; // } // if (tsID == end) { // break; // } // if ((System.currentTimeMillis() - firstStartTime) > minute * 60 * 1000) { System.out.println(timeStampOutput); System.out.println("Finish putting " + tsID + " " + noOfSamples + " " + rate + " in " + executedTime + " microSec"); System.out.println("rate:" + rate); System.out.println("drop:" + (noOfSamples - tsID)); System.out.println("ratio:" + tsID / noOfSamples); return; } } } else { while (tsID < noOfSamples) { long timeStart = System.currentTimeMillis(); // Random randomGenerator = new Random(); for (int i = 0; i < rate; i++) { // Thread.sleep(1000 / rate); // Value = 1.0; iRFCF.executeOneColumn(uID, tsID++); } // long timeStart2 = System.currentTimeMillis(); while ((System.currentTimeMillis() - timeStart) < 1000) { } // System.out.println("Took " + (System.currentTimeMillis() // - timeStart)); // System.out.println(tsID + " " + Value); // if (tsID % 1000 == 0) { // System.out.println(Value); // // break; // } // if (tsID == end) { // break; // } // if ((System.currentTimeMillis() - firstStartTime) > minute * 60 * 1000) { System.out.println(timeStampOutput); System.out.println("Finish putting " + tsID + " " + noOfSamples + " " + rate + " in " + executedTime + " microSec"); System.out.println("rate:" + rate); System.out.println("drop:" + (noOfSamples - tsID)); System.out.println("ratio:" + tsID / noOfSamples); break; } } } // Close the input stream // System.out.println("Length string is " + test.length()); System.out.println(timeStampOutput); System.out.println("Finish putting " + tsID + " " + noOfSamples + " " + rate + " in " + executedTime + " microSec"); System.out.println("rate:" + rate); System.out.println("drop:" + (noOfSamples - tsID)); System.out.println("ratio:" + tsID / noOfSamples); System.out.println("finishTime ms " + System.currentTimeMillis()); } catch (Exception e) {// Catch exception if any System.out.println(timeStampOutput); System.out.println("Finish putting " + tsID + " " + noOfSamples + " " + rate + " in " + executedTime + " microSec"); System.out.println("rate:" + rate); System.out.println("drop:" + (noOfSamples - tsID)); System.out.println("ratio:" + tsID / noOfSamples); System.err.println("Error: " + e.getMessage()); System.out.println("finishTime ms " + System.currentTimeMillis()); logger.debug("failed to write data to server", e); e.printStackTrace(); } }
1f980432-353a-4216-b99e-d733a9699c41
8
public static MaplePacket charInfo(final MapleCharacter chr) { MaplePacketLittleEndianWriter mplew = new MaplePacketLittleEndianWriter(); mplew.writeShort(SendPacketOpcode.CHAR_INFO); // mplew.writeShort(0x31); mplew.writeInt(chr.getId()); mplew.write(chr.getLevel()); mplew.writeShort(chr.getJob()); mplew.writeShort(chr.getFame()); mplew.write(1); // heart red or gray if (chr.getGuildId() <= 0) { mplew.writeMapleAsciiString("-"); mplew.writeMapleAsciiString("-"); } else { final MapleGuildSummary gs = chr.getClient().getChannelServer().getGuildSummary(chr.getGuildId()); mplew.writeMapleAsciiString(gs.getName()); final MapleAlliance alliance = chr.getGuild().getAlliance(chr.getClient()); if (alliance == null) { mplew.writeMapleAsciiString("-"); } else { mplew.writeMapleAsciiString(alliance.getName()); } } mplew.write(0); final IItem inv = chr.getInventory(MapleInventoryType.EQUIPPED).getItem((byte) -114); final int peteqid = inv != null ? inv.getItemId() : 0; for (final MaplePet pet : chr.getPets()) { if (pet.getSummoned()) { mplew.write(pet.getUniqueId()); mplew.writeInt(pet.getPetItemId()); // petid mplew.writeMapleAsciiString(pet.getName()); mplew.write(pet.getLevel()); // pet level mplew.writeShort(pet.getCloseness()); // pet closeness mplew.write(pet.getFullness()); // pet fullness mplew.writeShort(0); mplew.writeInt(peteqid); } } mplew.write(0); // End of pet if (chr.getInventory(MapleInventoryType.EQUIPPED).getItem((byte) -22) != null) { final MapleMount mount = chr.getMount(); mplew.write(1); mplew.writeInt(mount.getLevel()); mplew.writeInt(mount.getExp()); mplew.writeInt(mount.getFatigue()); } else { mplew.write(0); } final int wishlistSize = chr.getWishlistSize(); mplew.write(wishlistSize); if (wishlistSize > 0) { final int[] wishlist = chr.getWishlist(); for (int i = 0; i < wishlistSize; i++) { mplew.writeInt(wishlist[i]); } } chr.getMonsterBook().addCharInfoPacket(chr.getMonsterBookCover(), mplew); return mplew.getPacket(); }
45c3249a-9d48-4953-950b-4f7df80cd6f9
5
public void read() { if (db.exists()) { if (hasRead) return; try { FileReader f = new FileReader(db); BufferedReader in = new BufferedReader(f); String line; while ((line = in.readLine()) != null) { lines.add(line); } } catch (Exception ex) { ex.printStackTrace(); } hasRead = true; } else { try { db.createNewFile(); } catch (IOException e) { e.printStackTrace(); } read(); } }
3169b03b-048e-4ece-b57b-b495b6e1236f
1
public void SetSolenoidValue(int channel, boolean value){ solenoid[channel - 1] = (byte) (value ? 1:0); }
508ef49b-1f95-40ba-8ee0-87cc8195c7fc
0
@BeforeClass public static void setUpClass() throws Exception { System.out.println("start"); MyUnit.getDriver().get("http://www.google.com"); }
67fc92a8-c141-4b78-a429-8a7d6bee7809
0
public BST() { this.count = 0; root = null; }
a2247dee-48a0-4428-ac74-9976930497e7
3
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String nombre =request.getParameter("usuario"); String clave =request.getParameter("clave"); List<Usuario> lista = usuarioFacade.findByLogin(nombre, clave); RequestDispatcher rd; if(lista.isEmpty()){ rd=this.getServletContext().getRequestDispatcher("/salida.jsp"); }else{ Usuario u = lista.get(0); HttpSession ses = request.getSession(); ses.setAttribute("Usuario", u); if(u.getPerfilidPerfil().getIdPerfil()== 0){ rd=this.getServletContext().getRequestDispatcher("/indexAdmin.jsp"); }else if(u.getPerfilidPerfil().getIdPerfil()== 1){ rd=this.getServletContext().getRequestDispatcher("/indexMedico.jsp"); }else{ rd=this.getServletContext().getRequestDispatcher("/cosultarHistorial.jsp"); } } request.setAttribute("nombre", nombre); rd.forward(request, response); }
df4241d8-9ec9-4990-b656-8d5c4c9d87bb
1
private void newtonAlg(double point) { int count = 1; double step = point; double nextStep = point - calcValue(point)/calcDerivative(point); double epsilon = Math.pow(10, -7); while (Math.abs(nextStep - step) > epsilon) { count++; step = nextStep; nextStep = step - calcValue(step)/calcDerivative(step); } System.out.println("Step №" + count + ", Root = " + nextStep); }
0d071c63-a82e-4cfa-92d6-427604454713
6
public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter the number of lines for the characters to be printed: "); int num = scan.nextInt(); for (int i = 1; i <= num; i++) { for (int j = 1; j <= num; j++) if (i == 1 || i == num || j == 1 || j == num) System.out.print((char)(j + 96)); else System.out.print(" "); System.out.println(); } }
6c288a0f-c261-495c-8310-4a7e191747fb
0
public static String substring(String s, int beginIndex, int endIndex) throws IndexOutOfBoundsException { // Discovered somthing new. String.substring is basically a // memory leak. See: http://developer.java.sun.com/developer/bugParade/bugs/4637640.html for more details. // Use string.getChars to avoid this whenever you will be keeping the substring around for a while. // basically what happens is the substring has a ref to the original string so it doesn't get GC'd. int length = endIndex - beginIndex; char[] charArray = new char[length]; s.getChars(beginIndex, endIndex, charArray, 0); return new String(charArray); }
0019ce16-455e-4539-ae80-1fc619581170
0
public AdjacencyList getAdjacencyList() { return adjacencyList; }
48ca17eb-2792-4620-a5f2-ea50ac9a38f6
5
public CellHandle[] getCells() { List<? extends BiffRec> mycells; try { Boundsheet boundsheet = mySheet.getBoundsheet(); int colFirst = getColFirst(); mycells = boundsheet.getCellsByCol( colFirst ); } catch( CellNotFoundException e ) { return new CellHandle[0]; } CellHandle[] ch = new CellHandle[mycells.size()]; for( int t = 0; t < ch.length; t++ ) { Object o = mycells.get( t ); if( log.isTraceEnabled() ) { log.trace( "getCells() - processing index " + t + ", " + ((o == null) ? "<NULL>" : o.getClass().getName()) ); } ch[t] = new CellHandle( (BiffRec) o, null ); ch[t].setWorkSheetHandle( null ); } return ch; }
3413397b-f900-4798-8ef2-2e381cb18f77
0
public int getBlue(){ return _blue.get(); }
be15a5c2-4573-4e6e-bcc1-395c8ab8e8c7
0
public PumpingLemma getCurrent() { return get(myCurrent); }
7b50826f-c362-4b1b-bea7-66a97663c87d
2
public void set_order_to_idx( String idxFileName ) { if(canIfNoCdx()) { order = "[idx]"; Idx = new idx(); try { Idx.fidx = new RandomAccessFile( new File( g_idxname(idxFileName) ), fmode()); } catch (FileNotFoundException e1) { e1.printStackTrace(); } Idx.read_header(); Idx.recno = recno; updateseek(); } }
0fc41acd-4df7-4806-924b-06455cb0d827
6
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); BufferedImage originalImage = new BufferedImage(85, 85, BufferedImage.TYPE_INT_RGB); try { originalImage = ImageIO.read(getClass().getResource( "/imgs/menu/background.jpg")); } catch (IOException e1) { System.out.println("Error getting map image!"); } catch (IllegalArgumentException e2) { System.out.println("No image found"); } int iw = originalImage.getWidth(this); int ih = originalImage.getHeight(this); if (iw > 0 && ih > 0) { for (int x = 0; x < getWidth(); x += iw) { for (int y = 0; y < getHeight(); y += ih) { g.drawImage(originalImage, x, y, iw, ih, this); } } } }
d6b2a997-ffa0-4501-940f-895f9c03ce66
4
private void makeSit(Chair chair){ pDir = chair.getPlayerSitDir(); setCharLoc(chair.getPlayerX(),chair.getPlayerY()); stopMoveChar(); sitting = true; sittingHigh = chair.isHigh(); sittingLow = chair.isLow(); if(chair.getChairDir() == 0){ sittingDown = true; }else{ sittingDown = false; } if(chair.getChairDir() == 1){ sittingUp = true; }else{ sittingUp = false; } if(chair.getChairDir() == 2){ sittingLeft = true; }else{ sittingLeft = false; } if(chair.getChairDir() == 3){ sittingRight = true; }else{ sittingRight = false; } }
ef9a46d0-c5c7-4e6e-84fb-d93a4af9d13e
2
@Override public boolean equals(Object other) { if (other == null) return false; if (other == this) return true; Cinema otherCinema = (Cinema) other; return this.name.equals(otherCinema.name); }
b3e12b69-a152-49b1-ac73-a7c26e959949
2
@Override public Cible putCible(Cible c) throws JSONException, BadResponseException { Representation r = new JsonRepresentation(c.toJSON()); r = serv.putResource("intervention/" + interId + "/cible", null, r); Cible cible = null; try { JSONObject jobj = new JsonRepresentation(r).getJsonObject(); cible = new Cible(jobj); } catch (IOException e) { e.printStackTrace(); } catch (InvalidJSONException e) { e.printStackTrace(); } return cible; }
b1a27f53-55ef-4401-90b0-8cc9b65ece76
5
@Override protected boolean canRun(ClassNode node) { if (!node.superName.endsWith("Object") || classNodes.containsKey("NodeHashTable")) return false; if (node.fields.size() >= 2) { for (int fni=0; fni < node.fields.size(); fni++) { FieldNode fn = (FieldNode) node.fields.get(fni); if (fn.desc.equals("[L" + classNodes.get("Node").name + ";")) return true; } } return false; }