text
stringlengths
14
410k
label
int32
0
9
public synchronized void stop(){ listening=false; try { is.close(); con.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("handler stopping"); }
1
@Override public void focusLost(FocusEvent evt) { if (evt.getSource().equals(tripFormFileNameLabel)) { MainWindow.setupData.setFormFileName (tripFormFileNameLabel.getText()); } if (evt.getSource().equals(dataFileFileNameLabel)) { MainWindow.setupData.setDataFileName (dataFileFileNameLabel.getText()); } }
2
@Test public void testEj2_e(){ final int max = 10; final Grafo grafo = new Grafo(max); for (int i = 0; i < max; i++) grafo.agregarCiudad(CIUDADES.get(i)); final List<Vuelo> todosVuelos = new ArrayList<Vuelo>(); final Vuelo vuelo1 = new Vuelo(CIUDADES.get(1), CIUDADES.get(3), 100); final Vuelo vuelo2 = new Vuelo(CIUDADES.get(0), CIUDADES.get(4), 365); final Vuelo vuelo3 = new Vuelo(CIUDADES.get(2), CIUDADES.get(8), 104); final Vuelo vuelo4 = new Vuelo(CIUDADES.get(9), CIUDADES.get(4), 225); final Vuelo vuelo5 = new Vuelo(CIUDADES.get(5), CIUDADES.get(6), 489); final Vuelo vuelo6 = new Vuelo(CIUDADES.get(2), CIUDADES.get(0), 214); final Vuelo vuelo7 = new Vuelo(CIUDADES.get(7), CIUDADES.get(5), 229); final Vuelo vuelo8 = new Vuelo(CIUDADES.get(3), CIUDADES.get(4), 199); final Vuelo vuelo9 = new Vuelo(CIUDADES.get(9), CIUDADES.get(1), 364); final int idCiudadAQuitar = 2; // bs as todosVuelos.add(vuelo1); // bs as - asu todosVuelos.add(vuelo2); // mvd- san todosVuelos.add(vuelo3); // bra - la paz todosVuelos.add(vuelo4); // car - san todosVuelos.add(vuelo5); // lima - quito todosVuelos.add(vuelo6); // bra - mvd todosVuelos.add(vuelo7); // bog - lima todosVuelos.add(vuelo8); // asu - san todosVuelos.add(vuelo9); // car - bs as for(int x=0;x<todosVuelos.size();x++) grafo.agregarVuelo(todosVuelos.get(x)); List<Vuelo> esperadoVuelos = new ArrayList<Vuelo>(); for(int x=0;x<todosVuelos.size();x++){ Vuelo v = todosVuelos.get(x); if (!(v.getCiudad1().getIdentificador()==idCiudadAQuitar || v.getCiudad2().getIdentificador()==idCiudadAQuitar)){ esperadoVuelos.add(v); } } grafo.eliminarCiudad(CIUDADES.get(idCiudadAQuitar-1)); final List<Ciudad> esperado = new ArrayList<Ciudad>(); for(int x=0;x<max;x++) if (x!=idCiudadAQuitar-1) esperado.add(CIUDADES.get(x)); final List<Ciudad> actual = grafo.getCiudades(); assertEquals(esperado, actual); /* List<Vuelo> actualVuelos = grafo.getVuelos(); Collections.sort(esperadoVuelos, Vuelo.comparadorDeVuelos); Collections.sort(actualVuelos, Vuelo.comparadorDeVuelos); System.out.println("TODOS: " + todosVuelos); System.out.println("ESPERADO: " + esperadoVuelos); System.out.println("ACTUAL: " + actualVuelos); assertEquals(esperadoVuelos,actualVuelos); */ }
7
public int getSerializedSize() { int size = memoizedSize; if (size != -1) { return size; } size = 0; final boolean isMessageSet = getDescriptorForType().getOptions().getMessageSetWireFormat(); for (final Map.Entry<FieldDescriptor, Object> entry : getAllFields().entrySet()) { final FieldDescriptor field = entry.getKey(); final Object value = entry.getValue(); if (isMessageSet && field.isExtension() && field.getType() == FieldDescriptor.Type.MESSAGE && !field.isRepeated()) { size += CodedOutputStream.computeMessageSetExtensionSize( field.getNumber(), (Message) value); } else { size += FieldSet.computeFieldSize(field, value); } } final UnknownFieldSet unknownFields = getUnknownFields(); if (isMessageSet) { size += unknownFields.getSerializedSizeAsMessageSet(); } else { size += unknownFields.getSerializedSize(); } memoizedSize = size; return size; }
7
public static void analyzePath(String path) { File name = new File(path); if(name.exists()) { System.out.println(""+name.getName()+"\n" + "exists "+(name.isFile() ? "is a file": "is not a file")+"\n" + ""+(name.isDirectory() ? "is a directory" : "is not a directory")+"\n" + ""+(name.isAbsolute() ? "is absolute path" : "is not absolut path")+"\n" + "Last modified: "+name.lastModified() +"\n" + "Length : "+name.length()+"\n" + "Absolute path :" +name.getAbsolutePath()+"\n" + "Parent : " + name.getParent()); } if(name.isDirectory()) { String[] directory = name.list(); System.out.println("\n\nDirectory contents: \n"); for(String directoryName : directory) { System.out.println(""+directoryName); } } else { System.out.println(""+path+" does not exit"); } }
6
private void readFile(InputStream in, File outFolder) throws IOException { log.trace("Reading packaged file"); int dataSize = readInt(in); String fileName = readString(in); log.trace("Filename: " + fileName + " ("+dataSize+"b)"); File outFile = new File( outFolder, fileName ); outFile.getParentFile().mkdirs(); OutputStream out = new FileOutputStream(outFile); while( dataSize > 0 ) { int count = in.read(buf, 0, dataSize > buf.length ? buf.length : dataSize); if( count < 0 ) throw new EOFException("Unexpected end of stream"); dataSize -= count; out.write(buf, 0, count); } out.close(); }
3
public double doubleValue() // returns Double type value of data N,F { String s = value.trim(); return ( s.length()==0 || s.indexOf("*")>=0 ? 0 : Double.parseDouble(s) ); }
2
private void handleMouseEvent(final MouseEvent MOUSE_EVENT) { final Object SRC = MOUSE_EVENT.getSource(); final EventType TYPE = MOUSE_EVENT.getEventType(); if (SRC.equals(targetIndicator)) { if (MouseEvent.MOUSE_PRESSED == TYPE) { userAction = true; value.setText(String.format(Locale.US, "%." + getSkinnable().getDecimals() + "f", getSkinnable().getTarget())); resizeText(); } else if (MouseEvent.MOUSE_DRAGGED == TYPE) { touchRotate(MOUSE_EVENT.getSceneX() - getSkinnable().getLayoutX(), MOUSE_EVENT.getSceneY() - getSkinnable().getLayoutY(), targetIndicatorRotate); } else if (MouseEvent.MOUSE_RELEASED == TYPE) { getSkinnable().setTarget(Double.parseDouble(newTarget)); fadeBack(); } } }
4
public Object process(Cache highLevelCache) { if (isHighLevelCacheEnable()) { try { Object result = doInCache(highLevelCache); setHighLevelCacheEnable(); return result; } catch (CacheUnreachableException e) { setHighLevelCacheDisable(); } } return null; }
2
public static void concatenateFile(String... filename) { String str = null; // use try-with-resources // so no need to worry about closing the resources try (BufferedWriter writer = new BufferedWriter(new FileWriter( "CombinedFile.txt"));) { for (String name : filename) { try (BufferedReader reader = new BufferedReader(new FileReader( name));) { while ((str = reader.readLine()) != null) { writer.write(str); writer.newLine(); } } catch (IOException e) { System.out.println("Error reading/writing file"); } } } catch (Exception e) { e.printStackTrace(); } }
4
protected void initDefaultCommand() { setDefaultCommand(new SetModeMoving()); }
0
public static Tile nearestOpenTile(Monster movingMonster, char direction){ char left=direction; char right=direction; while(!canMove(movingMonster, direction)){ switch(randGenerator.nextInt(2)){ //at random, choose one of two actions: case(0): //action 1: try moving left. otherwise, move right. left=leftOf(left); if(canMove(movingMonster, left)) return tileInDirection(movingMonster, left); else{ right=rightOf(right); if(canMove(movingMonster, right)) return tileInDirection(movingMonster, right); } case(1): right=rightOf(right); if(canMove(movingMonster, right)) return tileInDirection(movingMonster, right); else{ left=leftOf(left); if(canMove(movingMonster, left)) return tileInDirection(movingMonster, left); } if(left==direction||right==direction) //this indicates a full cirlce, meaning the monster is surrounded and cannot move. return movingMonster.currentTile; } } return tileInDirection(movingMonster, direction); }
9
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(LoginSingUp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(LoginSingUp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(LoginSingUp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(LoginSingUp.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 LoginSingUp().setVisible(true); } }); }
6
@Override public int[] decodeQuality(String quality) throws QualityFormatException { int[] qual = new int[quality.length()]; for (int i = 0; i < qual.length; i++) { int c = quality.charAt(i); int q = c - encoding.getOffset(); if ((q < encoding.lowerBound) || (q > encoding.upperBoud)) { throw new QualityFormatException(quality); } qual[i] = c - encoding.getOffset(); } return qual; }
3
public static void sendSay(MapleCharacter player, String msg) { MaplePacket packet; switch (player.getGMLevel()) { case 0: packet = MaplePacketCreator.serverNotice(5, "[Rookie ~ " + player.getName() + "] " + msg); break; case 1: packet = MaplePacketCreator.serverNotice(5, "[Genin ~ " + player.getName() + "] " + msg); break; case 2: packet = MaplePacketCreator.serverNotice(5, "[Chunin ~ " + player.getName() + "] " + msg); break; case 3: packet = MaplePacketCreator.serverNotice(6, "[Jounin ~ " + player.getName() + "] " + msg); break; case 4: packet = MaplePacketCreator.serverNotice(6, "[Sannin ~ " + player.getName() + "] " + msg); break; default: packet = MaplePacketCreator.sendYellowTip("[Hokage] " + msg); } player.getClient().getChannelServer().broadcastPacket(packet); MainIRC.getInstance().sendIrcMessage(Colors.BOLD + "#SAY : " + player.getName() + " - " + Colors.RED + msg); }
5
synchronized public static ProcessManager getInstance() { if (singleton == null) { singleton = new ProcessManager(); } return singleton; }
1
@Override public void callback(DiscreteEventSimulator DES) throws SimulatorException { // Currently, the presence of a guest thread *always* preempts the native thread Machine machine = context.sim.getMachine(); CoreModel coreModel = machine.getCore(context); // Quit trying to simulate if disabled. if (!context.isEnabled()){ return; // without scheduling the next contextEvent } // Wait if stalled if (context.isStalled()){ //System.out.println("s (" + context.getContextID() + ") @" + coreModel.getCoreID() + ", PC=" + context.getPC()); DES.schedule(new ContextEvent(context), 1); return; } if (null == coreModel){ throw new SimulatorException("Context has no core associated with it"); } boolean isNative = (context == coreModel.getNative()); assert (isNative || (coreModel.getGuest()==context)); // Execute the instruction! // the context has a core associated with it, is enabled, and is not stalled Instruction inst; try { inst = machine.fetch(context.getPC()); } catch (ParserException e) { throw new SimulatorException("Failed to parse an instruction on fetch at PC=" + coreModel.getGuest().getPC()); } try{ System.out.print("i (" + context.getContextID() + ") @" + coreModel.getCoreID() + ", PC=" + context.getPC() + " : "); System.out.println(inst.toString()); System.out.println(coreModel.getStack(0, context)); System.out.println(); inst.execute(context, coreModel); } catch (OverflowException oe){ if (isNative){ throw new SimulatorException("Something bad happened - the native core shouldn't overflow"); } else { // Evict, reexecute on native Context evicted = coreModel.switchGuestContext(null, 0, 0, 0, 0); CoreModel homeCore = coreModel.getMachine().getNativeCore(evicted); coreModel.migrate(coreModel, homeCore, new MigrationEvent(evicted, coreModel, homeCore, MessageType.Overflow, -1, -1)); } } catch (UnderflowException ue){ if (isNative){ throw new SimulatorException("Stack underflow on native core! : context # " + coreModel.getNative().getContextID()); } else { // Evict, reexecute on native Context evicted = coreModel.switchGuestContext(null, 0, 0, 0, 0); CoreModel homeCore = coreModel.getMachine().getNativeCore(evicted); coreModel.migrate(coreModel, homeCore, new MigrationEvent(evicted, coreModel, homeCore, MessageType.Underflow, -1, -1)); } } // schedule the next event. DES.schedule(new ContextEvent(context), 1); }
9
@Override public void move() { super.move(); this.age += 1; }
0
private static void expandNode (final Problem problem, final Node node, final PriorityQueue<Node> frontier, final HashSet<Object> explored) { // Get all successors of the node. final List<Successor> successorSet = problem.getSuccessors(node.getState()); for (Successor successor : successorSet) { if (!explored.contains(successor.getState())) { /* The successor has not been explored. * Then check whether the successor is in the frontier. */ Node nodeInFrontier = null; for (Node fNode : frontier) { if (fNode.getState().equals(successor.getState())) { // The successor has already existed in frontier. nodeInFrontier = fNode; break; } } // Generate child node. final Node childNode = generateChildNode(problem, node, successor); if (nodeInFrontier == null) { // The successor is not in frontier nor explored, so add it. frontier.add(childNode); } else if (Double.compare(childNode.getTotalCost(), nodeInFrontier.getTotalCost()) < 0) { /* The successor has lower cost than the same one in the * frontier, so replace it. */ frontier.remove(nodeInFrontier); frontier.add(childNode); } } // if (!explored.contains(successorState)) { } // for (Successor successor : successorSet) { }
6
public void deleteOldValues(final long now) { this.checkTime(now); final long minTime = now - this.windowLength; boolean deleted = false; while (this.size > 0) { if (this.times[this.ringTail] < minTime) { final float value = this.values[this.ringTail]; this.delete(); deleted = true; this.sum -= value; this.sumquadrat -= value * value; if ((this.cachedMaximum != null) && (this.cachedMaximum != Ring.CLEARED) && FloatHelper.equals(value, this.cachedMaximum.value(), AFixedTimeWindowTest.PRECISION)) { this.cachedMaximum = Ring.CLEARED; // we lost the maximum. we have to check all values to find the new minimum. } if ((this.cachedMinimum != null) && (this.cachedMinimum != Ring.CLEARED) && FloatHelper.equals(value, this.cachedMinimum.value(), AFixedTimeWindowTest.PRECISION)) { this.cachedMinimum = Ring.CLEARED; // we lost the minimum. we have to check all values to find the new minimum. } } else { break; } } if (deleted == true) { this.cachedAvergage = Float.POSITIVE_INFINITY; this.cachedVariance = Float.POSITIVE_INFINITY; this.cachedDeviation = Float.POSITIVE_INFINITY; this.cachedMedian = Float.POSITIVE_INFINITY; } }
9
private boolean[] checkNeighbours(int row, int col) { boolean isUp = false; boolean isDown = false; boolean isLeft = false; boolean isRight = false; if (row == 0) { isDown = true; } if (col == 0) { isRight = true; } if (row == this.getFieldWidth() - 1) { isUp = true; isDown = false; } if (col == this.getFieldHeight() - 1) { isLeft = true; isRight = false; } if ((row < this.getFieldWidth() - 1) && (row != 0)) { isDown = true; isUp = true; } if ((col < this.getFieldHeight() - 1) && (col != 0)) { isLeft = true; isRight = true; } return new boolean[] { isUp, isDown, isLeft, isRight }; }
8
public String getData(String email){ JSONArray result = new JSONArray(); ResultSet resultSet = null; try { // Get Connection and Statement connection = dataSource.getConnection(); statement = connection.createStatement(); String query2 = "select * from usuarios where email= '" + email + "'"; resultSet = statement.executeQuery(query2); resultSet.next(); int id_usuario =resultSet.getInt("id_usuario"); String query = "SELECT * FROM farmacias WHERE id_admin='" + id_usuario+ "'"; resultSet = statement.executeQuery(query); while (resultSet.next()) { Farmacia farm = new Farmacia(); farm.setId(resultSet.getInt("id_farmacia")); if (resultSet.getString("nombre") != null) farm.setName(resultSet.getString("nombre")); farm.setciudad(resultSet.getString("ciudad")); farm.setdireccion(resultSet.getString("direccion")); farm.sethorario(resultSet.getString("horario")); farm.setlongitud(resultSet.getString("longitud")); farm.setlatitud(resultSet.getString("latitud")); //result = "{\"status\":\"OK\", \"result\":" // + farm.toJSONString() + "}"; result.add(farm); } } catch (SQLException e) { return "{\"status\":\"KO\", \"result\": \"Error en el acceso a la base de datos.\"}"; } finally { try { if (null != resultSet) resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (null != statement) statement.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (null != connection) connection.close(); } catch (SQLException e) { e.printStackTrace(); } } return result.toString(); }
9
public static String lookupColumnName(ResultSetMetaData resultSetMetaData, int columnIndex) throws SQLException { String name = resultSetMetaData.getColumnLabel(columnIndex); if (name == null || name.length() < 1) { name = resultSetMetaData.getColumnName(columnIndex); } return name; }
2
public static DisplayMode getPreferredDisplay() throws LWJGLException { DisplayMode chosen = Display.getDisplayMode(); DisplayMode[] modes = Display.getAvailableDisplayModes(); for(DisplayMode display : modes){ if(isDisplayModeBetter(chosen, display) == true){ chosen = display; } } return chosen; }
2
private static int toIndex(Direction dir) { switch(dir) { case SOUTH: return 0; case NORTH: return 1; case WEST: return 2; case EAST: return 3; } return 0; }
4
@Override public boolean init(List<String> argumentList, DebuggerVirtualMachine dvm) { breakpointLinesToSet = new ArrayList<String>(); breakableLineNumbers = new ArrayList<String>(); for (int i = 1; i < dvm.getSourceLinesSize(); i++) { if (dvm.isBreakableLine(i)) { breakableLineNumbers.add(new Integer(i).toString()); } } for (String arg : argumentList) { if (!breakableLineNumbers.contains(arg)) { UserInterface.println( arg + " is not a valid breakpoint line number."); UserInterface.print("Breakpoints can be set on lines: "); for (String lineNum : breakableLineNumbers) { UserInterface.print(lineNum + " "); } UserInterface.println("\n"); return false; } breakpointLinesToSet.add(arg); } return true; }
5
private final String getChunk(String s, int slength, int marker) { StringBuilder chunk = new StringBuilder(); char c = s.charAt(marker); chunk.append(c); marker++; if (isDigit(c)) { while (marker < slength) { c = s.charAt(marker); if (!isDigit(c)) break; chunk.append(c); marker++; } } else { while (marker < slength) { c = s.charAt(marker); if (isDigit(c)) break; chunk.append(c); marker++; } } return chunk.toString(); }
5
private boolean userInputChecker(String userInput) { boolean matchesInput = false; for (int loopCount = 0; loopCount < userInputList.size(); loopCount++) { if (userInput.equalsIgnoreCase(userInputList.get(loopCount))) { matchesInput = true; userInputList.remove(loopCount); loopCount--; } } return matchesInput; }
2
protected void do_button_actionPerformed(ActionEvent e) throws UnknownHostException, IOException, InterruptedException { String ip = textIpRede.getText(); if (ip.length() < 4) { JOptionPane.showMessageDialog(null, "Informe um IP válido!"); } else { try { Utils utils = new Utils(); InputStream ping = utils.verificaComunicacao(ip); Scanner sc = new Scanner(ping); new Thread() { @Override public void run() { try { sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } String texto = sc.nextLine() + "\n"; while (sc.hasNextLine()) { textTerminal.setText(texto += sc.nextLine() + "\n"); } // Finaliza o While } }.start(); // Finaliza a Thread } catch (UnknownHostException e1) { e1.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } } }
5
static void draw_edges(List<AsciiEdge> edges, List<String> nodeline, List<String> interline) { int index = 0; for (AsciiEdge edge : edges) { if (edge.mStart == edge.mEnd + 1) { interline.set(2 * edge.mEnd + 1, "/"); } else if (edge.mStart == edge.mEnd - 1) { interline.set(2 * edge.mStart + 1, "\\"); } else if (edge.mStart == edge.mEnd) { interline.set(2 * edge.mStart, "|"); } else { nodeline.set(2 * edge.mEnd, "+"); if (edge.mStart > edge.mEnd) { edge = new AsciiEdge(edge.mEnd, edge.mStart); } for (int j = 2 * edge.mStart + 1; j < 2 * edge.mEnd; j++) { if (!nodeline.get(j).equals("+")) { nodeline.set(j, "-"); } } } index++; } }
7
private static boolean equals(byte[] foo, byte[] bar){ if(foo.length!=bar.length)return false; for(int i=0; i<foo.length; i++){ if(foo[i]!=bar[i])return false; } return true; }
3
public int countRows(String query) { ResultSet rs = null; int rowCount = 0; try { Statement statement = conn.createStatement(); // select the number of rows in the table rs = statement.executeQuery(query); // get the number of rows from the result set if (rs.next()) { if (rs.getInt("userCount") > 0) { rowCount = 1; } } else { rowCount = 0; } statement.close(); return rowCount; } catch (SQLException e) { e.printStackTrace(); if (rs != null) { try { rs.close(); } catch (SQLException e1) { System.err.println ("MySQL Error (2): " + e1.toString()); } } return rowCount; } }
5
public E dequeue() { if (dequeue >= 0 && dequeue < queue.getSize()) { final E returnValue = (E) queue.get(dequeue); dequeue++; return returnValue; } else { return null; } }
2
public static Matrix read(Configuration conf, Path... modelPaths) throws IOException { int numRows = -1; int numCols = -1; boolean sparse = false; List<Pair<Integer, Vector>> rows = Lists.newArrayList(); for(Path modelPath : modelPaths) { for(Pair<IntWritable, VectorWritable> row : new SequenceFileIterable<IntWritable, VectorWritable>(modelPath, true, conf)) { rows.add(Pair.of(row.getFirst().get(), row.getSecond().get())); numRows = Math.max(numRows, row.getFirst().get()); sparse = !row.getSecond().get().isDense(); if(numCols < 0) { numCols = row.getSecond().get().size(); } } } if(rows.isEmpty()) { throw new IOException(Arrays.toString(modelPaths) + " have no vectors in it"); } numRows++; Vector[] arrayOfRows = new Vector[numRows]; for(Pair<Integer, Vector> pair : rows) { arrayOfRows[pair.getFirst()] = pair.getSecond(); } Matrix matrix; if(sparse) { matrix = new SparseRowMatrix(numRows, numCols, arrayOfRows); } else { matrix = new DenseMatrix(numRows, numCols); for(int i = 0; i < numRows; i++) { matrix.assignRow(i, arrayOfRows[i]); } } return matrix; }
7
public void actionPerformed (ActionEvent e) { // On test si le pseudo fait un minimum 3 caractere et s'il est disponible via // program.availableNickname if (nickname.getText().length() > 2 && program.availableNickname(nickname.getText())) { program.setNickname(nickname.getText()); // On envoi un signal pour que tout le monde nous rajoute dans la liste de contact String my_contact = Cast.getAddress() + ";" + program.getNickname(); Message message = new Message(my_contact, null, 2, my_contact); program.getCast().sendBroadcast(message); // On met a jour le titre du programme program.changeTitle(Cast.getAddress(), program.getNickname()); // On supprime le popup setVisible(false); } else if (nickname.getText().length() < 3) { label_error.setText("Nickname trop court"); } else label_error.setText("Nickname déjà utilisé"); }
3
private Object[][][] toCompressedArray(List<Locatable>[][] grid) { Object[][][] newGrid = new Object[this.xNumCells][this.yNumCells][]; for (int xi = 0; xi < grid.length; xi++) { List<Locatable>[] xar = grid[xi]; for (int yi = 0; yi < xar.length; yi++) { List<Locatable> cell = xar[yi]; if (cell != null) { newGrid[xi][yi] = cell.toArray(); } } } return newGrid; }
3
private final String htmlFilter( String line ) { if ( line == null || line.equals( "" ) ) { return ""; } line = replace( line, "&", "&amp;" ); line = replace( line, "<", "&lt;" ); line = replace( line, ">", "&gt;" ); line = replace( line, "\\\\", "&#92;&#92;" ); line = replace( line, "\\\"", "\\&quot;" ); line = replace( line, "'\"'", "'&quot;'" ); return ongoingMultiLineCommentFilter( line ); }
2
private Object lookupItem(String pattern) { Object selectedItem = model.getSelectedItem(); // only search for a different item if the currently selected does not match if (selectedItem != null && startsWithIgnoreCase(selectedItem.toString(), pattern)) { return selectedItem; } else { // iterate over all items for (int i = 0, n = model.getSize(); i < n; i++) { Object currentItem = model.getElementAt(i); // current item starts with the pattern? if (currentItem != null && startsWithIgnoreCase(currentItem.toString(), pattern)) { return currentItem; } } } // no item starts with the pattern => return null return null; }
5
public String preReportBySubmitted() { List<ClassObj> lstClass = mdClass.getAll(); List<ObjectiveObj> lstObjective = mdObjective.getAll(); List<TopicObj> lstTopic = new LinkedList<TopicObj>(); if(lstObjective.size() > 0){ lstTopic = mdTopic.getByObjective(lstObjective.get(0).getObjId()); } //validate boolean check = true; if(lstClass.isEmpty()){ check = false; addFieldError("clo.classname", "Class List is empty"); } if(lstObjective.isEmpty()){ check = false; addFieldError("ojto.objName", "Objective List is empty"); } if(lstTopic.isEmpty()){ check = false; addFieldError("tpo.name", "Topic List is empty"); } if(check){ mClass.put(ALL, ALL); for (ClassObj classObj : lstClass) { mClass.put(classObj.getClassname(), classObj.getClassname()); } for (ObjectiveObj objectiveObj : lstObjective) { mObjective.put(objectiveObj.getObjId(), objectiveObj.getObjName()); } for (TopicObj topicObj : lstTopic) { mTopic.put(topicObj.getTopicId(), topicObj.getName()); } mStatus.put(0, "Not submitted"); mStatus.put(1, "Submitted"); return SUCCESS; }else{ return ERROR; } }
8
public void setSelected(MoleculeComponent e) { System.out.println(">>>>>>>>> Set selected called for " + e); if (e == null) // If null, clear selection { if (selected != null) { if (selected.getClass() == Element.class) { elements.get(selected.getKey()).setSelected(false); // set the internal selection flag to true } else if (selected.getClass() == Bond.class) { bonds.get(selected.getKey()).setSelected(false); // set the internal selection flag to true } else if (selected.getClass() == Arrow.class) { arrows.get(selected.getKey()).setSelected(false); } } selected = null; return; } if (e.getClass() == Element.class) { selected = elements.get(e.getKey()); // set selected to the newest Element selected elements.get(selected.getKey()).setSelected(true); // set the internal selection flag to true } else if (e.getClass() == Bond.class) { selected = bonds.get(e.getKey()); bonds.get(selected.getKey()).setSelected(true); } else if (e.getClass() == Arrow.class) { selected = arrows.get(e.getKey()); arrows.get(selected.getKey()).setSelected(true); } }
8
public Scoreboard(GUIComponentGroup superGroup) { super(superGroup); winnerText = new TextComponent(this, "You Win!"); winnerText.setFont(GraphicalFont.HugeFont); winnerText.setAlignment(TextComponent.H_CENTER, TextComponent.V_CENTER); winnerText.setBounds(this.getLocationX(), this.getLocationY(), this.getWidth(), this.getHeight()/3); this.addComponent(winnerText); Grid grid = new Grid(3, Game.MAX_PLAYERS); grid.setColumnWidth(this.getWidth()/2/3); grid.setRowHeight(this.getHeight()/3/Game.MAX_PLAYERS); this.setGrid(grid); TextComponent textComponent; playerNames = new TextComponent[Game.MAX_PLAYERS]; for (int i = 0; i < Game.MAX_PLAYERS; i++) { textComponent = new TextComponent(this, "nobody " + i); playerNames[i] = textComponent; textComponent.setFont(GraphicalFont.StandardFont); textComponent.setAlignment(TextComponent.H_RIGHT, TextComponent.V_CENTER); this.addComponent(textComponent, 0, i); } playerNames[0].setFont(GraphicalFont.BigFont); dots = new TextComponent[Game.MAX_PLAYERS]; for (int i = 0; i < Game.MAX_PLAYERS; i++) { textComponent = new TextComponent(this, ". . . . . . . . . . . . . . ."); dots[i] = textComponent; textComponent.setFont(GraphicalFont.BigFont); textComponent.setAlignment(TextComponent.H_CENTER, TextComponent.V_CENTER); this.addComponent(textComponent, 1, i); } scores = new TextComponent[Game.MAX_PLAYERS]; for (int i = 0; i < Game.MAX_PLAYERS; i++) { textComponent = new TextComponent(this, "x" + i*1000); scores[i] = textComponent; textComponent.setFont(GraphicalFont.StandardFont); textComponent.setAlignment(TextComponent.H_LEFT, TextComponent.V_CENTER); this.addComponent(textComponent, 2, i); } scores[0].setFont(GraphicalFont.BigFont); newGameButton = new ButtonComponent(this, "New Game"); newGameButton.setSize(this.getWidth()/2*7/8, this.getHeight()/3/2); newGameButton.setLocationC(this.getWidth()/4, this.getHeight()*5/6); newGameButton.addActionListener(this); this.addComponent(newGameButton); quitButton = new ButtonComponent(this, "Quit"); quitButton.setSize(this.getWidth()/2*7/8, this.getHeight()/3/2); quitButton.setLocationC(this.getWidth()*3/4, this.getHeight()*5/6); quitButton.addActionListener(this); this.addComponent(quitButton); }
3
@Override public void paint(Graphics g) { super.paint(g); int dDibuixRobot = 30; int dRec = 10; int dGetL = 60; int dGetB = 35; int dGetBd = 42; int dBpro = 30; int dBpro2 = dBpro-2; int dBliv = 49; int dBrec = 65; int interlinieat = 90; ImageIcon reloadButton; ImageIcon plate; ImageIcon velo; ImageIcon fle; switch(Board.getTheme()){ case "Desert": plate = new ImageIcon(this.getClass().getResource("/resources/images/panel/plate.png")); break; case "Forest": plate = new ImageIcon(this.getClass().getResource("/resources/images/panel/plate.png")); break; case "Spacial": plate = new ImageIcon(this.getClass().getResource("/resources/images/panel/plate.png")); break; case "Sea": plate = new ImageIcon(this.getClass().getResource("/resources/images/panel/seaState.png")); break; default: plate = new ImageIcon(this.getClass().getResource("/resources/images/panel/plate.png")); break; } for (int i = 0; i < Board.robots.size(); i++) { g.drawImage(plate.getImage(), 5, dRec, null); //Marcador bullets restants int angle = (int) (((float)Board.robots.get(i).getBulletsLoad() / (float)Board.robots.get(i).getStartBulletsLoad()) * 180); // g.setColor(Color.black); // g.fillArc(58, dBpro2, 29, 29, 0, 180); // g.setColor(Color.red); // g.fillArc(60, dBpro, 25, 25, 0, angle); velo = new ImageIcon(this.getClass().getResource("/resources/images/panel/velos.png")); g.drawImage(velo.getImage(), 55, dBpro, null); Graphics2D g2d = (Graphics2D) g; fle = new ImageIcon(this.getClass().getResource("/resources/images/panel/fletxa.png")); AffineTransform at = new AffineTransform(); at.translate(71, dBpro+15); at.rotate(Math.toRadians(angle-180),3,3); // g.fillArc(60, dBpro, 25, 25, 0, angle); g2d.drawImage(fle.getImage(),at,null); //Bullets String br1 = String.valueOf(Board.robots.get(i).getBulletsLoad()); g.setColor(Color.white); g.drawString(br1, 68, dBpro+33); g.setColor(Color.black); //Vides int lr1 = Board.robots.get(i).getLives(); int vides = ((lr1*70)/Board.robots.get(i).getStartLives()); g.setColor(Color.red); g.fillRect(100, dBliv, 70, 5); g.setColor(Color.green); g.fillRect(100, dBliv, vides, 5); g.setColor(Color.black); //Reload if (Board.robots.get(i).getLastReload()+Board.robots.get(i).getReloadTime()<System.currentTimeMillis()){ reloadButton = new ImageIcon(this.getClass().getResource("/resources/images/panel/buttonGreen.png")); } else { reloadButton = new ImageIcon(this.getClass().getResource("/resources/images/panel/buttonRed.png")); } g.drawImage(reloadButton.getImage(), 68, dBpro-15, null); //Robots g.drawImage(Board.robots.get(i).getBody().getImage(), 10, dDibuixRobot, null); //Desplaçament del Turret + turret double dxt = Board.robots.get(i).getTurret().getDx(); int dxtf = (int)dxt; double dxy = Board.robots.get(i).getTurret().getDy(); int dytf = (int)dxy; g.drawImage(Board.robots.get(i).getTurret().getImage(), 10+dxtf, dDibuixRobot+dytf, null); //Desplaçament del radar + radar double dxr = Board.robots.get(i).getRadar().getDx(); int dxrf = (int)dxr; double dyr = Board.robots.get(i).getRadar().getDy(); int dyrf = (int)dyr; g.drawImage(Board.robots.get(i).getRadar().getImage(), 10+dxrf, dDibuixRobot+dyrf, null); //Suma posicio dRec = dRec + interlinieat; dDibuixRobot = dDibuixRobot + interlinieat; dGetL = dGetL + interlinieat; dGetB = dGetB + interlinieat; dBpro = dBpro + interlinieat; dBpro2 = dBpro2 + interlinieat; dBliv = dBliv + interlinieat; dBrec = dBrec + interlinieat; dGetBd = dGetBd +interlinieat; } }
6
@SuppressWarnings("rawtypes") public Validator createValidator(final Annotation annotation) { try { final Object validatorValue = ReflectionUtils.getAnnotationValue( annotation, "validator"); /* * Validator attribute exists on annotation, so try to instantiate * it and create a validator. If there is no validator attribute, a null value * will be returned as part of the interface contract. */ if (validatorValue != null) { final Class<?> validatorClass = (Class<?>) validatorValue; final Object o = validatorClass.newInstance(); if (o instanceof Validator) { return (Validator) validatorClass.newInstance(); } } return null; } catch (final NoSuchMethodException e) { return null; } catch (final Exception e) { throw new ValidationException(e); } }
6
public ArrayList<String> getTxtContent(File file){ ArrayList<String> txtList=new ArrayList<String>(); if ((!file.exists())||file==null) { return txtList; } String line=null; System.out.println(file); File[] files=file.listFiles(); if (files==null||files.length==0) { return txtList; } for (int i = 0; i < files.length; i++) { try { inputStream=new FileInputStream(files[i]); bufferedReader=new BufferedReader(new InputStreamReader(inputStream)); while ((line = bufferedReader.readLine()) != null) { txtList.add(line); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return txtList; }
7
public List<String> playerWorlds(Player player){ List<String> worldList = new ArrayList<String>(); for (String worldN : plugin.mainWorlds){ String worldName = worldN + "_" + player.getName(); String currentdir = plugin.minecraft_folder; File folder = new File(currentdir + "/inactive/" + worldName); File folder_root = new File(currentdir + "/" + worldName); if (folder.exists()){ worldList.add(currentdir + "/inactive/" + worldName); }else if(folder_root.exists()){ worldList.add(currentdir + "/" + worldName); } } return worldList; }
3
@Override public void onMessage(MutableWebSocketFrame aFrame, WebSocketContext aContext) { SocketIoMessage message = decoder.decode(aFrame); if (LOG.isDebugEnabled()) { if (SocketIoMessage.Type.EVENT.equals(message.type) && message.data != null) { final JsonElement event = json.parse(message.data); LOG.debug("S-IN:\n{}", json.toPrettyJson(event)); } else { LOG.debug("S-IN: {}", message); } } switch (message.type) { case HEARTBEAT: listener.onHeartbeat(); sendHeartBeat(); break; case EVENT: processEvent(listener, message); break; case CONNECT: // just skip it break; case DISCONNECT: sendConnectionClose(aContext); break; // do nothing case NOOP: break; // not supported yet case ACK: break; default: LOG.error("Unknown message type: {}", message); } }
9
public String getIp() { return this.ip; }
0
private void jList1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jList1KeyPressed if (evt.getKeyCode() == KeyEvent.VK_ESCAPE && jList1.getSelectedValue() != null) { logger.log(Level.INFO, "Resetting backup selection..."); jList1.clearSelection(); } }//GEN-LAST:event_jList1KeyPressed
2
private void btn_loginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_loginActionPerformed String id, senha; id = txt_id.getText(); senha = txt_senha.getText(); if(id.isEmpty() || senha.isEmpty()){ JOptionPane.showMessageDialog(rootPane, "Por favor, preencha todos os campos!!"); } if(id.equals("123") && senha.equals("aaa")){ new inicio().setVisible(true); Login.this.dispose(); } // TODO add your handling code here: }//GEN-LAST:event_btn_loginActionPerformed
4
public CheckController1(File file) { String fileType = file.getName().split("\\.")[0].split("_")[0]; int fileNameSectionNumber = file.getName().split("\\.")[0].split("_").length; try { checkReport1 = new CheckReport1(file); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if (fileType.equals(BaseReport.TYPE_A) && fileNameSectionNumber == 4) { report = new PaySingleExcelReport1(file); } else if (fileType.equals(BaseReport.TYPE_A) && fileNameSectionNumber == 3) { report = new PayTotalExcelReport1(file); } else if (fileType.equals(BaseReport.TYPE_B) && fileNameSectionNumber == 4) { report = new BankSingleExcelReport1(file); } else { report = new UnknownExcelReport1(file); } }
7
public Warehouse getWarehouse(long itemid, int branchid) { Warehouse warehouse = null; 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(); String query="Select wrh_id,wrh_quantity,wrh_salerentprice,wrh_minlimit,wrh_maxlimit,wrh_isavailable,wrh_isactive,item_id,branch_id " +"From warehouse where item_id="+itemid+" and branch_id="+branchid; ResultSet rs = stmt.executeQuery(query); if (rs.next()) { warehouse=new Warehouse(); warehouse.setId(rs.getLong(1)); warehouse.setQuantity(rs.getInt(2)); warehouse.setSaleRentPrice(rs.getDouble(3)); warehouse.setMinLimit(rs.getInt(4)); warehouse.setMaxLimit(rs.getInt(5)); warehouse.setIsAvailable(rs.getBoolean(6)); warehouse.setIsActive(rs.getBoolean(7)); warehouse.setItem(rs.getInt(8)); warehouse.setBranch(rs.getInt(9)); } } 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()); } } return warehouse; }
5
private ArrayList<String> getTreeLeafs(){ ArrayList<String> leafs = new ArrayList<>(); for(ArrayList<String> valueList : _tree.values()){ for(String value : valueList){ if(_tree.containsKey(value)) continue; if(leafs.contains(value)) continue; leafs.add(value); } } return leafs; }
4
private boolean getTWSUserNameAndPasswordFromArguments(String[] args) { if (isFIX()) { if (args.length == 5 || args.length == 6) { IBAPIUserName = args[3]; IBAPIPassword = args[4]; return true; } else { return false; } } else if (args.length == 3 || args.length == 4) { IBAPIUserName = args[1]; IBAPIPassword = args[2]; return true; } else if (args.length == 5 || args.length == 6) { Utils.logError("Incorrect number of arguments passed. quitting..."); Utils.logRawToConsole("Number of arguments = " +args.length + " which is only permitted if FIX=yes"); for (String arg : args) { Utils.logRawToConsole(arg); } System.exit(1); return false; } else { return false; } }
8
public static void main(String[] args){ Boat.createBoat("RaceBoat"); Boat boat = Boat.getInstance(); for(int i = 90; i<=270; i+=10){ try{ System.out.print("Setting rudder to " + i + " degrees."); boat.com.sendMessage("set rudder " + i); Thread.sleep(1000); }catch(Exception e){ e.printStackTrace(); } } }
2
final void method996(int i, int i_86_, int i_87_, int i_88_, boolean bool, int i_89_, boolean bool_90_) { anInt1151++; int i_91_ = 256; if (bool_90_) { i_91_ |= 0x20000; } if (bool) { i_91_ |= 0x40000000; } i_88_ -= anInt1135; if (i_87_ == 1) { i -= anInt1139; for (int i_92_ = i; (i_92_ ^ 0xffffffff) > (i + i_89_ ^ 0xffffffff); i_92_++) { if ((i_92_ ^ 0xffffffff) <= -1 && (anInt1133 ^ 0xffffffff) < (i_92_ ^ 0xffffffff)) { for (int i_93_ = i_88_; (i_86_ + i_88_ ^ 0xffffffff) < (i_93_ ^ 0xffffffff); i_93_++) { if (i_93_ >= 0 && (anInt1146 ^ 0xffffffff) < (i_93_ ^ 0xffffffff)) { method995(i_92_, i_93_, i_91_, i_87_ ^ ~0x63); } } } } } }
9
public static Obligation getInstance(Node root) throws ParsingException { URI id; int fulfillOn = -1; List assignments = new ArrayList(); AttributeFactory attrFactory = AttributeFactory.getInstance(); NamedNodeMap attrs = root.getAttributes(); try { id = new URI(attrs.getNamedItem("ObligationId").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required attriubte " + "ObligationId", e); } String effect = null; try { effect = attrs.getNamedItem("FulfillOn").getNodeValue(); } catch (Exception e) { throw new ParsingException("Error parsing required attriubte " + "FulfillOn", e); } if (effect.equals("Permit")) { fulfillOn = Result.DECISION_PERMIT; } else if (effect.equals("Deny")) { fulfillOn = Result.DECISION_DENY; } else { throw new ParsingException("Invlid Effect type: " + effect); } NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeName().equals("AttributeAssignment")) { try { URI attrId = new URI(node.getAttributes(). getNamedItem("AttributeId").getNodeValue()); AttributeValue attrValue = attrFactory.createValue(node); assignments.add(new Attribute(attrId, null, null, attrValue)); } catch (URISyntaxException use) { throw new ParsingException("Error parsing URI", use); } catch (UnknownIdentifierException uie) { throw new ParsingException("Unknown AttributeId", uie); } catch (Exception e) { throw new ParsingException("Error parsing attribute " + "assignments", e); } } } return new Obligation(id, fulfillOn, assignments); }
9
public PropertyList lookupHandler(String path) { { HttpServer server = this; if (Http.$HTTP_SERVER_IMPLEMENTATION$ == null) { throw ((StellaException)(StellaException.newStellaException("lookup-handler: no HTTP server implementation loaded").fillInStackTrace())); } { PropertyList handler = ((PropertyList)(Http.$HTTP_HANDLER_REGISTRY$.lookup(StringWrapper.wrapString(path)))); String handlerpath = null; int handlerpathlength = 0; if (handler != null) { return (handler); } { StringWrapper p = null; PropertyList h = null; DictionaryIterator iter000 = ((DictionaryIterator)(Http.$HTTP_HANDLER_REGISTRY$.allocateIterator())); while (iter000.nextP()) { p = ((StringWrapper)(iter000.key)); h = ((PropertyList)(iter000.value)); if (Stella.startsWithP(path, p.wrapperValue, 0)) { if ((handler == null) || ((StringWrapper.unwrapString(p)).length() > handlerpathlength)) { handler = h; handlerpath = p.wrapperValue; handlerpathlength = handlerpath.length(); } } } } return (handler); } } }
6
public final void with_stmt() throws RecognitionException { try { // Python.g:274:10: ( 'with' test ( with_var )? COLON suite ) // Python.g:274:12: 'with' test ( with_var )? COLON suite { match(input,96,FOLLOW_96_in_with_stmt2191); if (state.failed) return; pushFollow(FOLLOW_test_in_with_stmt2193); test(); state._fsp--; if (state.failed) return; // Python.g:274:24: ( with_var )? int alt61=2; int LA61_0 = input.LA(1); if ( (LA61_0==NAME||LA61_0==70) ) { alt61=1; } switch (alt61) { case 1 : // Python.g:274:25: with_var { pushFollow(FOLLOW_with_var_in_with_stmt2196); with_var(); state._fsp--; if (state.failed) return; } break; } match(input,COLON,FOLLOW_COLON_in_with_stmt2200); if (state.failed) return; pushFollow(FOLLOW_suite_in_with_stmt2202); suite(); state._fsp--; if (state.failed) return; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } }
9
@SuppressWarnings("unchecked") public void initializeConfigValues() { Ore_Gin_Properties = new HashMap<Integer,OreGinProperties>(); Cloaker_Properties = new HashMap<Integer,CloakerProperties>(); //Load general config MachineFactoryPlugin.CITADEL_ENABLED = getConfig().getBoolean("general.citadel_enabled"); MachineFactoryPlugin.OREGIN_ENABLED = getConfig().getBoolean("general.oregin_enabled"); MachineFactoryPlugin.SMELTER_ENABLED = getConfig().getBoolean("general.smelter_enabled"); MachineFactoryPlugin.CLOAKER_ENABLED = getConfig().getBoolean("general.cloaker_enabled"); MachineFactoryPlugin.SAVE_CYCLE = getConfig().getInt("general.save_cycle"); //Load general config values MachineFactoryPlugin.OREGIN_UPDATE_CYCLE = getConfig().getInt("oregin_general.update_cycle"); MachineFactoryPlugin.CLOAKER_UPDATE_CYCLE = getConfig().getInt("cloaker_general.update_cycle"); MachineFactoryPlugin.MAXIMUM_BLOCK_BREAKS_PER_CYCLE = getConfig().getInt("oregin_general.maximum_block_breaks_per_cycle"); MachineFactoryPlugin.OREGIN_UPGRADE_WAND = Material.valueOf(getConfig().getString("oregin_general.oregin_upgrade_wand")); MachineFactoryPlugin.OREGIN_ACTIVATION_WAND = Material.valueOf(getConfig().getString("oregin_general.oregin_activation_wand")); MachineFactoryPlugin.OREGIN_REPAIR_WAND = Material.valueOf(getConfig().getString("oregin_general.oregin_repair_wand")); MachineFactoryPlugin.LIGHT_ON = Material.valueOf(getConfig().getString("oregin_general.oregin_light_on")); MachineFactoryPlugin.LIGHT_OFF = Material.valueOf(getConfig().getString("oregin_general.oregin_light_off")); MachineFactoryPlugin.MAX_OREGIN_TIERS = getConfig().getInt("oregin_general.max_tiers"); MachineFactoryPlugin.MAX_CLOAKER_TIERS = getConfig().getInt("cloaker_general.max_tiers"); MachineFactoryPlugin.REDSTONE_ACTIVATION_ENABLED = getConfig().getBoolean("oregin_general.redstone_activation_enabled"); MachineFactoryPlugin.LAVA_MINING_ENABLED = getConfig().getBoolean("oregin_general.lava_mining_enabled"); MachineFactoryPlugin.WATER_MINING_ENABLED = getConfig().getBoolean("oregin_general.water_mining_enabled"); MachineFactoryPlugin.JUNK_DESTRUCTION_ENABLED = getConfig().getBoolean("oregin_general.junk_destruction_enabled"); MachineFactoryPlugin.CLOAKER_ACTIVATED = Material.valueOf(getConfig().getString("cloaker_general.cloaker_activated")); MachineFactoryPlugin.CLOAKER_DEACTIVATED = Material.valueOf(getConfig().getString("cloaker_general.cloaker_deactivated")); MachineFactoryPlugin.CLOAKER_UPGRADE_WAND = Material.valueOf(getConfig().getString("cloaker_general.cloaker_upgrade_wand")); MachineFactoryPlugin.CLOAKER_ACTIVATION_WAND = Material.valueOf(getConfig().getString("cloaker_general.cloaker_activation_wand")); MachineFactoryPlugin.CLOAKER_CHUNK_RANGE = getServer().getViewDistance(); //Load valuables List<String> valuablesMaterialStrings = (List<String>) getConfig().getList("oregin_general.valuables"); VALUABLES = new ArrayList<Material>(); for (String string : valuablesMaterialStrings) { if (Material.valueOf(string) != null) { VALUABLES.add(Material.valueOf(string)); } } //Load junk List<String> junkMaterialStrings = (List<String>) getConfig().getList("oregin_general.junk"); JUNK = new ArrayList<Material>(); for (String string : junkMaterialStrings) { if (Material.valueOf(string) != null) { JUNK.add(Material.valueOf(string)); } } //Load indestructible List<String> indestructibleMaterialStrings = (List<String>) getConfig().getList("oregin_general.indestructible"); INDESTRUCTIBLE = new ArrayList<Material>(); for (String string : indestructibleMaterialStrings) { if (Material.valueOf(string) != null) { INDESTRUCTIBLE.add(Material.valueOf(string)); } } //Load OreGin tier properties for (int i = 1; i <= MachineFactoryPlugin.MAX_OREGIN_TIERS; i++) { int max_mining_distance = getConfig().getInt(getOreGinPropertiesPathStart(i) + "max_mining_distance"); int max_block_breaks= getConfig().getInt(getOreGinPropertiesPathStart(i) + "max_block_breaks"); int mining_delay= getConfig().getInt(getOreGinPropertiesPathStart(i) + "mining_delay"); boolean retrieve_valuables = getConfig().getBoolean(getOreGinPropertiesPathStart(i) + "retrieve_valuables"); Material fuel_type = Material.valueOf(getConfig().getString(getOreGinPropertiesPathStart(i) + "fuel_type")); int fuel_amount= getConfig().getInt(getOreGinPropertiesPathStart(i) + "fuel_amount"); Material upgrade_material = Material.valueOf(getConfig().getString(getOreGinPropertiesPathStart(i) + "upgrade_material")); int upgrade_amount = getConfig().getInt(getOreGinPropertiesPathStart(i) + "upgrade_amount"); Material repair_material = Material.valueOf(getConfig().getString(getOreGinPropertiesPathStart(i) + "repair_material")); int repair_amount = getConfig().getInt(getOreGinPropertiesPathStart(i) + "repair_amount"); int shaft_width = getConfig().getInt(getOreGinPropertiesPathStart(i) + "shaft_width"); int shaft_height = getConfig().getInt(getOreGinPropertiesPathStart(i) + "shaft_height"); Ore_Gin_Properties.put(i, new OreGinProperties(max_mining_distance, max_block_breaks, mining_delay, retrieve_valuables, fuel_amount, fuel_type, shaft_width, shaft_height, upgrade_material, upgrade_amount, repair_material, repair_amount)); } //Load Cloaker tier properties for (int i = 1; i <= MachineFactoryPlugin.MAX_CLOAKER_TIERS; i++) { Material upgrade_type = Material.valueOf(getConfig().getString(getCloakerPropertiesPathStart(i) + "upgrade_type")); int upgrade_amount = getConfig().getInt(getCloakerPropertiesPathStart(i) + "upgrade_amount"); int fuel_time_duration = getConfig().getInt(getCloakerPropertiesPathStart(i) + "fuel_time_duration"); Material fuel_type = Material.valueOf(getConfig().getString(getCloakerPropertiesPathStart(i) + "fuel_type")); int fuel_amount = getConfig().getInt(getCloakerPropertiesPathStart(i) + "fuel_amount"); int cloak_width = getConfig().getInt(getCloakerPropertiesPathStart(i) + "cloak_width"); int cloak_height = getConfig().getInt(getCloakerPropertiesPathStart(i) + "cloak_height"); int cloak_depth = getConfig().getInt(getCloakerPropertiesPathStart(i) + "cloak_depth"); int visibility_range = getConfig().getInt(getCloakerPropertiesPathStart(i) + "visibility_range"); Cloaker_Properties.put(i, new CloakerProperties(upgrade_type, upgrade_amount, fuel_time_duration, fuel_type, fuel_amount, cloak_width, cloak_height, cloak_depth, visibility_range)); } MachineFactoryPlugin.sendConsoleMessage("Config values successfully loaded!"); saveConfig(); }
8
public static Object getObject( Object in ) { // do not record -- only called from other methods if( !(in instanceof String) ) { return in; } String input = String.valueOf( in ); Object ret = input; // default is the original string try { ret = new Double( input ); return ret; } catch( NumberFormatException ex ) { try { ret = new Float( input ); return ret; } catch( NumberFormatException ex2 ) { try { ret = Integer.valueOf( input ); return ret; } catch( NumberFormatException ex3 ) { // ret Is set outside of loop incase no match is ever found. } } } // list of formatting chars to check for String[][] fmtlist = { { "$", "," }, { ",", "," }, { "%", "," } }; // strip the formatting for( String[] aFmtlist : fmtlist ) { if( input.contains( aFmtlist[0] ) ) { // contains! String converted = StringTool.replaceText( input, aFmtlist[0], "" ); // strip first token (ie: '$') converted = StringTool.replaceText( converted, aFmtlist[1], "" ); // strip // second // token // (ie: ',') try { ret = new Double( converted ); return ret; } catch( NumberFormatException ex ) { try { ret = new Float( converted ); return ret; } catch( NumberFormatException ex2 ) { try { ret = Integer.valueOf( converted ); return ret; } catch( NumberFormatException ex3 ) { // ret Is set outside of loop incase no match is // ever found. } } } } } return ret; }
9
public void wyslijWiadomosc(String _wiadomosc, String _typWiadomosci) { try { if(socket != null) out = new PrintWriter(socket.getOutputStream()); } catch (IOException e) {System.out.println("Błąd WysWiad: "+e.getMessage()); } String str=""; if(czyWyslacZakonczenie) str = "KONIEC"; else { if(this != null) { if(_typWiadomosci.equals("#WP#")) { str=_typWiadomosci+nickGracza+": "+wiadomosc.getText()+"\n"; czat.setText(czat.getText()+str.substring(4)); } else str = _typWiadomosci+_wiadomosc; } } if(out != null) { out.println(str); out.flush(); } }
6
public void run() { DNSOutgoing out = null; try { // send probes for JmDNS itself if (this.jmDNSImpl.getState() == taskState) { if (out == null) { out = new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA); } this.jmDNSImpl.getLocalHost().addAddressRecords(out, false); this.jmDNSImpl.advanceState(); } // send announces for services // Defensively copy the services into a local list, // to prevent race conditions with methods registerService // and unregisterService. List list; synchronized (this.jmDNSImpl) { list = new ArrayList(this.jmDNSImpl.getServices().values()); } for (Iterator i = list.iterator(); i.hasNext();) { ServiceInfoImpl info = (ServiceInfoImpl) i.next(); synchronized (info) { if (info.getState() == taskState && info.getTask() == this) { info.advanceState(); logger.finer("run() JmDNS announced " + info.getQualifiedName() + " state " + info.getState()); if (out == null) { out = new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA); } info.addAnswers(out, DNSConstants.DNS_TTL, this.jmDNSImpl.getLocalHost()); } } } if (out != null) { logger.finer("run() JmDNS announced"); this.jmDNSImpl.send(out); } else { // If we have nothing to send, another timer taskState ahead // of us has done the job for us. We can cancel. cancel(); } } catch (Throwable e) { logger.log(Level.WARNING, "run() exception ", e); this.jmDNSImpl.recover(); } taskState = taskState.advance(); if (!taskState.isAnnounced()) { cancel(); } }
9
public void setInputParamInteger(final int paramIndex, final Object array) throws IllegalArgumentException, NullPointerException { if (array==null) throw new NullPointerException(ARRAY_IS_NULL); InputParameterInfo param = getInputParameterInfo(paramIndex); if ((param==null) || (param.type()!=InputParameterType.TA_Input_Integer)) throw new InternalError(CONTACT_DEVELOPERS); if (! (array instanceof int[]) ) throw new IllegalArgumentException(INT_ARRAY_EXPECTED); if (callInputParams==null) callInputParams = new Object[getFuncInfo().nbInput()]; callInputParams[paramIndex] = array; }
5
private String getDirectory() { if ((config.getDirectory() == null) || (config.getDirectory().isEmpty())) return "logfiles/"; else return config.getDirectory() + "/"; }
2
@PostConstruct @Schedule( year="*", dayOfWeek="*" , hour="*" , minute="*/5" , persistent=false ) @Timeout @AccessTimeout(unit=TimeUnit.MINUTES, value=1) private void loadFeaturedItem(Timer timer){ System.out.println(" #### Iniciando el FeaturedItemBean.loadFeaturedItem() "); this.featuredItems = new ArrayList<Item_DTO>(); Item_DTO fitem = null; String CONSULTA = "SELECT i.ItemId, i.itemName, i.bidStartDate, i.bidEndTime, i.CreateDate " + "FROM FeturedItems f, Item i "+ "WHERE f.itemId = i.ItemId"; try{ Statement stmt = connection.createStatement( ); ResultSet rs = stmt.executeQuery( CONSULTA ); while ( rs.next()){ fitem = new Item_DTO( rs.getString( "itemName" ), (java.sql.Date)rs.getDate( "bidStartDate" ), (java.sql.Date)rs.getDate( "bidEndTime" ) , (java.sql.Date)rs.getDate( "CreateDate" ), rs.getLong( "itemId" ) ); this.featuredItems.add( fitem ); } } catch ( SQLException e) { e.printStackTrace(); } }
2
private void registerNew() { if (registerQueue.isEmpty()) return; Selector selector = this.selector; for (;;) { RegistrationRequest req = registerQueue.poll(); if (req == null) break; DatagramSessionImpl session = new DatagramSessionImpl(wrapper, this, req.config, req.channel, req.handler, req.channel .socket().getRemoteSocketAddress(), req.channel .socket().getLocalSocketAddress()); // AbstractIoFilterChain will notify the connect future. session.setAttribute(AbstractIoFilterChain.CONNECT_FUTURE, req); boolean success = false; try { SelectionKey key = req.channel.register(selector, SelectionKey.OP_READ, session); session.setSelectionKey(key); buildFilterChain(req, session); getSessionRecycler(session).put(session); // The CONNECT_FUTURE attribute is cleared and notified here. getListeners().fireSessionCreated(session); success = true; } catch (Throwable t) { // The CONNECT_FUTURE attribute is cleared and notified here. session.getFilterChain().fireExceptionCaught(session, t); } finally { if (!success) { try { req.channel.disconnect(); req.channel.close(); } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } } }
6
private boolean jj_2_51(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_51(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(50, xla); } }
1
private void connect() { do { try { connection = (TACConnection) Class.forName(connectionClassName). newInstance(); } catch (Exception e) { log.log(Level.SEVERE, "could not create TACConnection object of class " + connectionClassName, e); fatalError("no TACConnection available"); } try { connection.init(this); } catch (Exception e) { log.log(Level.SEVERE, "Connection failure:", e); } if (!connection.isConnected()) { log.warning("could not connect to server " + host + " at port " + port + " (will retry in 5 seconds)"); try { Thread.sleep(5000); } catch (Exception e) { } } } while (!connection.isConnected()); }
5
@AfterTest @Test(groups = "Deletion") public void testRandomBSTDeletion() throws KeyNotFoundException, EmptyCollectionException { Reporter.log("[ ** Random BST Deletion ** ]\n"); Integer count = 0; timeKeeper = System.currentTimeMillis(); for (Integer i = -seed; i < 0; i++) { try { randomBST.delete(i); } catch (KeyNotFoundException e) { count++; } } if (count == seed) { Reporter.log("False deletion -- Passed : " + (System.currentTimeMillis() - timeKeeper) + " ms\n"); } else { throw new KeyNotFoundException(); } timeKeeper = System.currentTimeMillis(); for (Integer i = 0; i < seed; i++) { try { randomBST.delete(i); } catch (KeyNotFoundException e) { Reporter.log("Deletion -- Failed!!!\n"); throw e; } } try { randomBST.delete(0); } catch (EmptyCollectionException e) { Reporter.log("Deletion -- Passed : " + (System.currentTimeMillis() - timeKeeper) + " ms\n"); } }
6
public static void startupUtilitiesSystem() { synchronized (Stella.$BOOTSTRAP_LOCK$) { if (Stella.currentStartupTimePhaseP(0)) { if (!(Stella.systemStartedUpP("stella", "/STELLA"))) { StartupStellaSystem.startupStellaSystem(); } } if (Stella.currentStartupTimePhaseP(1)) { Module.defineModuleFromStringifiedSource("/UTILITIES", "(:LISP-PACKAGE \"STELLA\" :JAVA-PACKAGE \"edu.isi.stella.utilities\" :USES (\"STELLA\") :NICKNAME \"UTIL\" :CODE-ONLY? TRUE)"); } { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/UTILITIES", Stella.$STARTUP_TIME_PHASE$ > 1)); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); if (Stella.currentStartupTimePhaseP(2)) { Utilities.SYM_UTILITIES_STARTUP_UTILITIES_SYSTEM = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("STARTUP-UTILITIES-SYSTEM", null, 0))); } if (Stella.currentStartupTimePhaseP(6)) { Stella.finalizeClasses(); } if (Stella.currentStartupTimePhaseP(7)) { Stella.defineFunctionObject("STARTUP-UTILITIES-SYSTEM", "(DEFUN STARTUP-UTILITIES-SYSTEM () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.utilities.StartupUtilitiesSystem", "startupUtilitiesSystem", new java.lang.Class [] {}), null); { MethodSlot function = Symbol.lookupFunction(Utilities.SYM_UTILITIES_STARTUP_UTILITIES_SYSTEM); KeyValueList.setDynamicSlotValue(function.dynamicSlots, Utilities.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("StartupUtilitiesSystem"), Stella.NULL_STRING_WRAPPER); } } if (Stella.currentStartupTimePhaseP(8)) { Stella.finalizeSlots(); Stella.cleanupUnfinalizedClasses(); } if (Stella.currentStartupTimePhaseP(9)) { Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("/UTILITIES"))))); { int phase = Stella.NULL_INTEGER; int iter006 = 0; int upperBound007 = 9; for (;iter006 <= upperBound007; iter006 = iter006 + 1) { phase = iter006; Stella.$STARTUP_TIME_PHASE$ = phase; _StartupManuals.startupManuals(); _StartupUnits.startupUnits(); _StartupUnitDefs.startupUnitDefs(); } } Stella.$STARTUP_TIME_PHASE$ = 999; } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } } }
9
public Method findMethod(String prefix, String methodName, Class<?> ... paramType) { if(methodName == null || methodName.isEmpty()) return null; methodName = createMethodName(prefix, methodName); try { return getInspectedClass().getDeclaredMethod(methodName, paramType); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } return null; }
5
public void visitLocalExpr(final LocalExpr expr) { if (expr.fromStack()) { print("T"); } else { print("L"); } print(expr.type().shortName().toLowerCase()); print(Integer.toString(expr.index())); final DefExpr def = expr.def(); if ((def == null) || (def.version() == -1)) { print("_undef"); } else { print("_" + def.version()); } }
3
public void update() { statusPanel.setText(status.getText()); repaint(); if(player.hasWon() && !player.getWinnerMessageHasBeenShown() && !grid.getIsTest()){ showWinMessage(); } }
3
public boolean unequip(final int... ids) { // Disable when bank open if (ctx.bank.opened()) { return false; } if (ctx.hud.open(Hud.Window.WORN_EQUIPMENT)) { final Item item = ctx.equipment.select().id(ids).poll(); if (item.valid()) { if (item.interact("Remove")) { return Condition.wait(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return !ctx.equipment.select().id(ids).poll().valid(); } }); } } else { return true; } } return false; }
4
private String scanDirectiveIgnoredLine(Mark startMark) { // See the specification for details. int ff = 0; while (reader.peek(ff) == ' ') { ff++; } if (ff > 0) { reader.forward(ff); } if (reader.peek() == '#') { ff = 0; while (Constant.NULL_OR_LINEBR.hasNo(reader.peek(ff))) { ff++; } reader.forward(ff); } char ch = reader.peek(); String lineBreak = scanLineBreak(); if (lineBreak.length() == 0 && ch != '\0') { throw new ScannerException("while scanning a directive", startMark, "expected a comment or a line break, but found " + ch + "(" + ((int) ch) + ")", reader.getMark()); } return lineBreak; }
6
private void showEduFw() { content = null; head = null; Object fb = logic.showEduFwHead(); if (fb instanceof Feedback) { JOptionPane.showMessageDialog(null, ((Feedback) fb).getContent()); } else if (fb instanceof String[]) { head = (String[]) fb; fb = logic.showEduFwContent(); if ((fb instanceof Feedback) && fb != Feedback.LIST_EMPTY) { JOptionPane.showMessageDialog(null, ((Feedback) fb).getContent()); } else if (fb instanceof String[][]) { content = (String[][]) fb; } } if (content == null) { fBtn[0].setEnabled(true); fBtn[1].setEnabled(true); fBtn[2].setEnabled(false); DefaultTableModel dtm1 = new DefaultTableModel(1, 1); dtm1.setValueAt("教学框架策略未提交。", 0, 0); table1 = new CommonTable(dtm1); table1.setEnabled(false); js1.setViewportView(table1); cl.show(cardp, "1"); } else { fBtn[0].setEnabled(false); fBtn[1].setEnabled(false); fBtn[2].setEnabled(true); map = new EduFrameworkMap(content); dtm = new DefaultTableModel(content.length, head.length); table2 = new CTable(map, dtm); dtm.setColumnIdentifiers(head); for (int i = 0; i < content.length; i++) { for (int j = 0; j < content[i].length; j++) { if (content[i][j].contains("null-null")) { content[i][j] = content[i][j].replaceAll("null-null", ""); } dtm.setValueAt(content[i][j], i, j); } } table2.setEnabled(false); js2.setViewportView(table2); cl.show(cardp, "2"); } this.repaint(); this.validate(); }
9
public static int getLevenshteinDistance(String s, String t) { if (s == null || t == null) { throw new IllegalArgumentException("Strings must not be null"); } /* The difference between this impl. and the previous is that, rather than creating and retaining a matrix of size s.length()+1 by t.length()+1, we maintain two single-dimensional arrays of length s.length()+1. The first, d, is the 'current working' distance array that maintains the newest distance cost counts as we iterate through the characters of String s. Each time we increment the index of String t we are comparing, d is copied to p, the second int[]. Doing so allows us to retain the previous cost counts as required by the algorithm (taking the minimum of the cost count to the left, up one, and diagonally up and to the left of the current cost count being calculated). (Note that the arrays aren't really copied anymore, just switched...this is clearly much better than cloning an array or doing a System.arraycopy() each time through the outer loop.) Effectively, the difference between the two implementations is this one does not cause an out of memory condition when calculating the LD over two very large strings. */ int n = s.length(); // length of s int m = t.length(); // length of t if (n == 0) { return m; } else if (m == 0) { return n; } int p[] = new int[n + 1]; //'previous' cost array, horizontally int d[] = new int[n + 1]; // cost array, horizontally int _d[]; //placeholder to assist in swapping p and d // indexes into strings s and t int i; // iterates through s int j; // iterates through t char t_j; // jth character of t int cost; // cost for (i = 0; i <= n; i++) { p[i] = i; } for (j = 1; j <= m; j++) { t_j = t.charAt(j - 1); d[0] = j; for (i = 1; i <= n; i++) { cost = s.charAt(i - 1) == t_j ? 0 : 1; // minimum of cell to the left+1, to the top+1, diagonally left and up +cost d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost); } // copy current distance counts to 'previous row' distance counts _d = p; p = d; d = _d; } // our last action in the above loop was to switch d and p, so p now // actually has the most recent cost counts return p[n]; }
8
public EncryptedHand decyrptEncHand(EncryptedHand hand) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException { EncryptedHand ret = new EncryptedHand(); for (int i = 0; i < Hand.NUM_CARDS; i++) { EncryptedCard tmp = hand.data.get(i); ret.data.add(decryptEncCard(tmp)); } return ret; }
1
public static boolean isInteger(String str) { if (str == null) { return false; } int length = str.length(); if (length == 0) { return false; } int i = 0; if (str.charAt(0) == '-') { if (length == 1) { return false; } i = 1; } for (; i < length; i++) { char c = str.charAt(i); if (c <= '/' || c >= ':') { return false; } } return true; }
7
public void save() { if (config == null || file == null) { return; } try { get().save(file); } catch (IOException ex) { InstaScatter.ins.getLogger().log(Level.SEVERE, "Could not save config to " + file, ex); } }
3
public String printTree(int depth) { String print = ""; for (int i = 0; i < depth; i++) { print = print + " "; } print = print + toString() + "\n"; Binomialnode a = child; while (a != null) { print = print + a.printTree(depth + 1); a = a.sibling; } return print; }
2
@Override public Key next() { if (!hasNext()) throw new NoSuchElementException(); Node node = stack.pop(); if (node.right != null) stack.push(node.right); if (node.left != null) stack.push(node.left); return node.key; }
3
public void removeByFileName(String song) { if(playList != null) { GameSong gs; for(int i = 0; i < playList.size(); i++) { gs = playList.get(i); if(gs.getFilePath().equals(song)) { if(currentSongIndex == i) { if(transitionTime > 0.0f) { gs.fadeOut(); } else { gs.stop(); } } playList.remove(i); if(currentSongIndex > i && i > 0) { currentSongIndex--; } } } } }
7
public synchronized void threadInc(SimThread t, DataHolder d) { if (Constants.muCheck) { if ((Constants.muIncS += Constants.muIncUp) < .75) { t.Constants._epsilon = this.epsilon; t.Constants._SIM_epsilon_start = this.epsilon; t.Constants._SIM_epsilon_final = this.epsilon; t.setRunNum(runNum); runNum++; d.init(t); } else { threadCheck(t); } } else if (Constants.ConstantEp) { threadCheck(t); /*if (runNum < 1) { t.Constants._epsilon = this.epsilon; t.Constants._SIM_epsilon_start = t.Constants._epsilon; t.Constants._SIM_epsilon_final = t.Constants._epsilon; t.setRunNum(runNum); runNum++; if (this.epsilon > 1) { this.epsilon = 1; } d.init(t); }*/ } else if ((this.epsilon < constants._SIM_epsilon_final)) { t.Constants._epsilon = this.epsilon; t.Constants._SIM_epsilon_start = t.Constants._epsilon; t.Constants._SIM_epsilon_final = t.Constants._epsilon; this.epsilon += this.constants._SIM_epsilon_step; t.setRunNum(runNum); runNum++; if (this.epsilon > 1) { this.epsilon = 1; } d.init(t); } else { threadCheck(t); } }
5
public Meeting getMeeting(int id) { MeetingImpl tempM = null; for(Meeting m : meetingList) { tempM = (MeetingImpl) m; if(tempM.meetingID==id) { return m; } } return null; }
2
public LongCount(int bak, int kat, int tun, int win, int ki) { if(bak < 0) { throw new IllegalArgumentException("Baktuns must be greater than or equal to 0."); } if(kat < 0 || kat > 19) { throw new IllegalArgumentException("Katuns must be a number 0-19 inclusive."); } if(tun < 0 || tun > 19) { throw new IllegalArgumentException("Tuns must be a number 0-19 inclusive."); } if(win < 0 || win > 17) { throw new IllegalArgumentException("Winals must be a number 0-17 inclusive."); } if(ki < 0 || ki > 19) { throw new IllegalArgumentException("Kin must be a number 0-19 inclusive."); } baktuns = bak; katuns = kat; tuns = tun; winals = win; kin = ki; }
9
private void toNote() { ItemDefinition noteTemplateDefinition = getDefinition(noteTemplateId); modelId = noteTemplateDefinition.modelId; modelZoom = noteTemplateDefinition.modelZoom; modelRotationX = noteTemplateDefinition.modelRotationX; modelRotationY = noteTemplateDefinition.modelRotationY; modelRotationZ = noteTemplateDefinition.modelRotationZ; modelOffset1 = noteTemplateDefinition.modelOffset1; modelOffset2 = noteTemplateDefinition.modelOffset2; modifiedModelColors = noteTemplateDefinition.modifiedModelColors; originalModelColors = noteTemplateDefinition.originalModelColors; ItemDefinition noteDefinition = getDefinition(noteId); name = noteDefinition.name; membersObject = noteDefinition.membersObject; value = noteDefinition.value; String prefix = "a"; char firstCharacter = noteDefinition.name.charAt(0); if (firstCharacter == 'A' || firstCharacter == 'E' || firstCharacter == 'I' || firstCharacter == 'O' || firstCharacter == 'U') prefix = "an"; description = ("Swap this note at any bank for " + prefix + " " + noteDefinition.name + ".").getBytes(); stackable = true; }
5
public static double getDistance(ClusterPoint p1, ClusterPoint p2, int distanceType) { double sum = 0.0; switch(distanceType) { case MANHATTEN: for(int i = 0; i < p1.getDimensionSize(); i++) sum += Math.abs(p2.getValueAtDimension(i) - p1.getValueAtDimension(i)); return sum; case EUCLIDEAN: for(int i = 0; i < p1.getDimensionSize(); i++) sum += Math.pow(p2.getValueAtDimension(i) - p1.getValueAtDimension(i), 2); return Math.sqrt(sum); default: return -1.0; } }
4
public final void run() throws FatalError { printJump("(" + count + ")"); // cut it into parts to safe session int c = count; while (c > 10) { // sleep for 10 min Control.sleep(6000, 2); c -= 10; Control.current.getCharacter(); } Control.sleep(600 * c, 2); }
1
public Object nextValue() throws JSONException { char c = nextClean(); String string; switch (c) { case '"': case '\'': return nextString(c); case '{': back(); return new JSONObject(this); case '[': back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = next(); } back(); string = sb.toString().trim(); if (string.equals("")) { throw syntaxError("Missing value"); } return JSONObject.stringToValue(string); }
7
public final TLParser.assignment_return assignment() throws RecognitionException { TLParser.assignment_return retval = new TLParser.assignment_return(); retval.start = input.LT(1); Object root_0 = null; Token Identifier15=null; Token char_literal17=null; TLParser.indexes_return indexes16 = null; TLParser.expression_return expression18 = null; Object Identifier15_tree=null; Object char_literal17_tree=null; RewriteRuleTokenStream stream_Assign=new RewriteRuleTokenStream(adaptor,"token Assign"); RewriteRuleTokenStream stream_Identifier=new RewriteRuleTokenStream(adaptor,"token Identifier"); RewriteRuleSubtreeStream stream_expression=new RewriteRuleSubtreeStream(adaptor,"rule expression"); RewriteRuleSubtreeStream stream_indexes=new RewriteRuleSubtreeStream(adaptor,"rule indexes"); try { // src/grammar/TL.g:73:3: ( Identifier ( indexes )? '=' expression -> ^( ASSIGNMENT Identifier ( indexes )? expression ) ) // src/grammar/TL.g:73:6: Identifier ( indexes )? '=' expression { Identifier15=(Token)match(input,Identifier,FOLLOW_Identifier_in_assignment270); stream_Identifier.add(Identifier15); // src/grammar/TL.g:73:17: ( indexes )? int alt4=2; int LA4_0 = input.LA(1); if ( (LA4_0==OBracket) ) { alt4=1; } switch (alt4) { case 1 : // src/grammar/TL.g:73:17: indexes { pushFollow(FOLLOW_indexes_in_assignment272); indexes16=indexes(); state._fsp--; stream_indexes.add(indexes16.getTree()); } break; } char_literal17=(Token)match(input,Assign,FOLLOW_Assign_in_assignment275); stream_Assign.add(char_literal17); pushFollow(FOLLOW_expression_in_assignment277); expression18=expression(); state._fsp--; stream_expression.add(expression18.getTree()); // AST REWRITE // elements: expression, Identifier, indexes // token labels: // rule labels: retval // token list labels: // rule list labels: // wildcard labels: retval.tree = root_0; RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); root_0 = (Object)adaptor.nil(); // 74:6: -> ^( ASSIGNMENT Identifier ( indexes )? expression ) { // src/grammar/TL.g:74:9: ^( ASSIGNMENT Identifier ( indexes )? expression ) { Object root_1 = (Object)adaptor.nil(); root_1 = (Object)adaptor.becomeRoot((Object)adaptor.create(ASSIGNMENT, "ASSIGNMENT"), root_1); adaptor.addChild(root_1, stream_Identifier.nextNode()); // src/grammar/TL.g:74:33: ( indexes )? if ( stream_indexes.hasNext() ) { adaptor.addChild(root_1, stream_indexes.nextTree()); } stream_indexes.reset(); adaptor.addChild(root_1, stream_expression.nextTree()); adaptor.addChild(root_0, root_1); } } retval.tree = root_0; } retval.stop = input.LT(-1); retval.tree = (Object)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; }
5
public boolean skipPast(String to) throws JSONException { boolean b; char c; int i; int j; int offset = 0; int length = to.length(); char[] circle = new char[length]; /* * First fill the circle buffer with as many characters as are in the * to string. If we reach an early end, bail. */ for (i = 0; i < length; i += 1) { c = next(); if (c == 0) { return false; } circle[i] = c; } /* We will loop, possibly for all of the remaining characters. */ for (;;) { j = offset; b = true; /* Compare the circle buffer with the to string. */ for (i = 0; i < length; i += 1) { if (circle[j] != to.charAt(i)) { b = false; break; } j += 1; if (j >= length) { j -= length; } } /* If we exit the loop with b intact, then victory is ours. */ if (b) { return true; } /* Get the next character. If there isn't one, then defeat is ours. */ c = next(); if (c == 0) { return false; } /* * Shove the character in the circle buffer and advance the * circle offset. The offset is mod n. */ circle[offset] = c; offset += 1; if (offset >= length) { offset -= length; } } }
9
public void printScreen(byte[] screen, int width){ int bytesPerLine = width/8; int height = screen.length / bytesPerLine; for(int i = 0; i < height; i++){ //print each line; int startByteIndex = i*bytesPerLine; int endByteIndex = startByteIndex + bytesPerLine-1; for(int j = startByteIndex; j<=endByteIndex; j++){ //print each byte; String s = String.format("%8s", Integer.toBinaryString(screen[j])).replace(' ', '0'); System.out.print(s); } System.out.println(); } }
2
private Thread searchThreadsInSubGroup(final String threadName, final ThreadGroup group, final int level) { ThreadGroup[] groups = new ThreadGroup[group.activeGroupCount() * 2]; int numGroups = group.enumerate(groups, false); Thread thread = null; for (int i = 0; i < numGroups && thread == null; i++) { thread = searchThreadsInGroup(threadName, groups[i], level + 1); } return thread; }
2
public static int uniquePaths(int m, int n) { int[][] path = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (0 == i && 0 == j) path[i][j] = 1; else if (0 == i) path[i][j] = path[0][j - 1]; else if (0 == j) path[i][j] = path[i - 1][0]; else path[i][j] = path[i][j - 1] + path[i - 1][j]; } } return path[m - 1][n - 1]; }
6
public static S3Bucket[] listAllBuckets(RestS3Service s){ S3Bucket[] s3buckets= null; try { s3buckets = s.listAllBuckets(); } catch (S3ServiceException e) { e.printStackTrace(); } return s3buckets; }
1
private void makeFlushStates() { for (int cn0 = 0; cn0 < RANK_SIZE; cn0++) { for (int cn1 = cn0 + 1; cn1 < RANK_SIZE; cn1++) { for (int cn2 = cn1 + 1; cn2 < RANK_SIZE; cn2++) { for (int cn3 = cn2 + 1; cn3 < RANK_SIZE; cn3++) { for (int cn4 = cn3 + 1; cn4 < RANK_SIZE; cn4++) { int[] cards5 = {cn0, cn1, cn2, cn3, cn4}; makeFlush(cards5); if (_handLength > 5) { for (int cn5 = cn4 + 1; cn5 < RANK_SIZE; cn5++) { int[] cards6 = {cn0, cn1, cn2, cn3, cn4, cn5}; makeFlush(cards6); if (_handLength > 6) { for (int cn6 = cn4 + 1; cn6 < RANK_SIZE; cn6++) { int[] cards7 = {cn0, cn1, cn2, cn3, cn4, cn5, cn6}; makeFlush(cards7); } } } } } } } } } }
9
public String[] mapTypes(String[] types) { String[] newTypes = null; boolean needMapping = false; for (int i = 0; i < types.length; i++) { String type = types[i]; String newType = map(type); if (newType != null && newTypes == null) { newTypes = new String[types.length]; if (i > 0) { System.arraycopy(types, 0, newTypes, 0, i); } needMapping = true; } if (needMapping) { newTypes[i] = newType == null ? type : newType; } } return needMapping ? newTypes : types; }
7
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String del = (String) req.getParameter("del"); if(del != null && del.equals("yes")){ log.info("remove file"); MatchUtil.removeFile(); } String time = (String) req.getParameter("time"); if(time == null){ time = DateFormat.getDateInstance().format(new Date()); } log.info("time is " + time); if(MatchUtil.isFileExist()){ Match match = MatchUtil.readMatch(); try { match.setTime(DateFormat.getDateInstance().parse(time)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } match.setMatchCount((match.getMatchCount())+1); MatchUtil.writeMatch(match); }else{ Match match = new Match(); try { match.setTime(DateFormat.getDateInstance().parse(time)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } match.setMatchCount((match.getMatchCount())+1); MatchUtil.writeMatch(match); } log.info((MatchUtil.readMatch()).toString()); String s = (String) req.getParameter("echostr"); PrintWriter writer = resp.getWriter(); writer.print(s); writer.close(); }
6
public void settle(){ int buyquant = Integer.parseInt(buynumber.getText()); int sellquant = Integer.parseInt(sellnumber.getText()); int type_int = type.getSelectedIndex()+1; int current = sector.getQuantity(type_int); int checkCap = Empous.Gov.getStat("reserve") - sum[0][0]; int checkWood = Empous.Gov.getStat("woodstock") - sum[0][1]; int checkOil = Empous.Gov.getStat("oiltank") - sum[0][2]; // If they have enough resources, perform the transaction if (checkCap >= 0 && checkWood >= 0 && checkOil >= 0){ Empous.Gov.setStat("reserve", checkCap); Empous.Gov.setStat("woodstock", checkWood); Empous.Gov.setStat("oiltank", checkOil); sector.setQuantity(type_int, current+buyquant-sellquant); } // If they don't, give a warning else{ System.out.println("Not enough resources!"); } }
3