text
stringlengths
14
410k
label
int32
0
9
public boolean hitRight() { if(nextX() >= xMin+xMax) return true; return false; }
1
private void updateForces() { keyForce.set(0.0, 0.0); if (up && !down) { keyForce.offset(0, SPEED); } else if (down && !up) { keyForce.offset(0, -SPEED); } if (left && !right) { keyForce.offset(-SPEED, 0); } else if (right && !left) { keyForce.offset(SPEED, 0); } }
8
@Override public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors erros = new ActionErrors(); if(contato.getNome() == null || contato.getNome().isEmpty()) { erros.add("nome", new ActionMessage("erro.campoNome")); } if(contato.getEndereco() == null || contato.getEndereco().isEmpty()) { erros.add("endereco", new ActionMessage("erro.campoEndereco")); } if(contato.getEmail() == null || contato.getEmail().isEmpty()) { erros.add("email", new ActionMessage("erro.campoEmail")); } return erros; }
6
public void testWithField3() { YearMonthDay test = new YearMonthDay(2004, 6, 9); try { test.withField(DateTimeFieldType.hourOfDay(), 6); fail(); } catch (IllegalArgumentException ex) {} }
1
private void readConfig() { Properties p = new Properties(); try { p.load(this.getClass().getClassLoader().getResourceAsStream("application.properties")); clientVersion = p.getProperty("version"); } catch (IOException e) { log.error(e.getMessage()); } }
1
public void run(){ try{ String msgIn = ""; //initialize board for(i=0; i<4; i++){ for(j=0; j<10; j++){ this.board[i][j] = new Character(); } } while(true){ msgIn = conn.getMessage(); if(msgIn.equals("DONE")){ //get player's board receiveBoard(conn, this.board, playerNum); //update copy of board for both players updateBoards(clientsList, this.board, playerNum); done[playerNum] = true; if(done[PLAYER1] && done[PLAYER2]){ //get a copy of combined board copyBoard(clientsList, this.board); //send copy of board to both players sendToAll(); fightStart(board, conn, clientsList); } } } //msgIn syntax: CREATE charactername rowNum colNum /* System.out.println("nag exit ako"); done[playerNum] = true; if(done[PLAYER1] && done[PLAYER2]) fightStart(board); */ }catch(Exception e){e.printStackTrace();} }
7
@Override public boolean supportsAttributes() {return true;}
0
private void turnAction(Player user, TurnData data) { synchronized(turnThread) { if(!user.isTurnEnd()) { if(data.isTurnAction()) { if(user.getThrewDice() < 3) { user.move(); } else { user.setPosition(jail); user.setInJail(true); user.setTurnEnd(true); turnThread.notify(); } } else { user.setTurnEnd(true); turnThread.notify(); } } } }
3
public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_CONTROL) { pressed = false; } }
1
public int getIndexOfChild(Object parent, Object child) { TreeElement[] childrens = getChildrens((TreeElement) parent); int i = Arrays.binarySearch(childrens, child); if (i >= 0) return i; throw new NoSuchElementException(((TreeElement) parent).getFullName() + "." + child); }
1
public static void main(String[] args) { final Conditions conditions = new Conditions(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { conditions.put(i); } } }).start(); new Thread(new Runnable() { @Override public void run() { for (int i = 10; i < 20; i++) { conditions.put(i); } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { for (int i = 0; i < 10; i++) { conditions.get(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { for (int i = 0; i < 10; i++) { conditions.get(); } } } }).start(); }
6
public static void main(String[] args) { String inputGenomeFilePath; int kmerLength, kmerOverlapLength, deBruijnGraphDegree; if (args.length == 4) { inputGenomeFilePath = args[0]; if(!doesFileExist(inputGenomeFilePath)) { System.out.println("Invalid input genome file path!"); printClosingAppMessage(); return; } try { kmerLength = parseIntArgument(args[1]); } catch (Exception e) { System.out.println("Kmer length must be an integer!"); printClosingAppMessage(); return; } try { kmerOverlapLength = parseIntArgument(args[2]); } catch (Exception e) { System.out.println("Kmer overlap length must be an integer!"); printClosingAppMessage(); return; } try { deBruijnGraphDegree = parseIntArgument(args[3]); } catch (Exception e) { System.out.println("Kmer length must be an integer!"); printClosingAppMessage(); return; } String inputGenomeSequence = null; String assembledSequence = null; try { inputGenomeSequence = oneLineFileToString(inputGenomeFilePath); assembledSequence = DnaAssembler.assemble(inputGenomeFilePath, kmerLength, kmerOverlapLength, deBruijnGraphDegree); } catch (IOException e) { handleException(e); } catch (MbiException e) { handleException(e); } createFileWithText("output.txt", assembledSequence); StringBuilder logBuilder = new StringBuilder(); if(inputGenomeSequence.equals(assembledSequence)) { logBuilder.append("INPUT equals RESULT"); } else { logBuilder.append("INPUT differs from RESULT\n"); logBuilder.append("Longest common subsequence length: " + Helpers.longestSubstringLength(inputGenomeSequence, assembledSequence)); // startTime = System.nanoTime(); // int longestCommonSubstringLength = longestSubstring(inputSequence, resultSequence); // Logger.log("longest: " + longestCommonSubstringLength); // Logger.logLongestCommonSubstringLength(Integer.toString(longestCommonSubstringLength)); // elapsedTime = System.nanoTime() - startTime; // elapsedTimeInSeconds = (double)elapsedTime / 1000000000.0; // Logger.log("longest substring searching", Double.toString(elapsedTimeInSeconds)); } createFileWithText("log.txt", logBuilder.toString()); } else { System.out.println("Incorrect number of arguments!"); } }
8
public Login(LoginMessage loginMessage,String ipaddress){ this.sequence_Id =loginMessage.getSequence_Id(); this.Account = loginMessage.getClientID(); this.Version = loginMessage.getClientVersion(); this.LoginMode = loginMessage.getLoginMode(); this.ipaddress = ipaddress; this.timestamp = loginMessage.getTimeStamp(); this.AuthenticatorClient = loginMessage.getAuthenticatorClient(); }
0
public int getPopulationSize() {return population.size();}
0
public static boolean isReservedNot(String candidate) { int START_STATE = 0; int TERMINAL_STATE = 3; char next; if (candidate.length()!=3){ return false; } int state = START_STATE; for (int i = 0; i < candidate.length(); i++) { next = candidate.charAt(i); switch (state) { case 0: switch ( next ) { case 'n': state++; break; default : state = -1; } break; case 1: switch ( next ) { case 'o': state++; break; default : state = -1; } break; case 2: switch ( next ) { case 't': state++; break; default : state = -1; } break; } } if ( state == TERMINAL_STATE ) return true; else return false; }
9
public void paint1(Graphics g) { if (carro != null && popo != null) { g.drawImage(carro.getImagen(), carro.getPosX(), carro.getPosY(), this); if (choco) { popo.setMovimiento(false); choco = false; } g.drawImage(pajaro.getImagen(), pajaro.getPosX(), pajaro.getPosY(), this); g.drawImage(popo.getImagen(), popo.getPosX(), popo.getPosY(), this); //pinta los popos en la lista g.drawImage(popo.getImagen(), popo.getPosX(), popo.getPosY(), this); //score = popo.getConteo(); g.drawString("SCORE: " + popo.getConteo(), 20, 40); g.drawString("PERDIDAS: " + perdidas, 20, 60); g.drawString("VIDAS: " + vidas, 20, 80); if (instrucciones) { g.drawString(" INSTRUCCIONES ", getWidth() / 2 - 80, getHeight() / 2); g.drawString("P - Pausar/Jugar", getWidth() / 2 - 80, getHeight() / 2 + 20); g.drawString("I - Instrucciones", getWidth() / 2 - 80, getHeight() / 2 + 40); g.drawString("G - Grabar juego", getWidth() / 2 - 80, getHeight() / 2 + 60); g.drawString("C - Cargar juego", getWidth() / 2 - 80, getHeight() / 2 + 80); g.drawString("S - Activar/Desactivar sonido", getWidth() / 2 - 80, getHeight() / 2 + 100); } if (pausa) { g.drawString("" + carro.getPausa(), carro.getPosX() + carro.getAncho(), carro.getPosY()); } if (desaparece && colisiono && tiempoColision <= 30 && !pausa) { g.drawString("" + carro.getDesaparece(), carro.getPosX() + carro.getAncho(), carro.getPosY()); } } else { //Da un mensaje mientras se carga el dibujo g.drawString("No se cargo la imagen..", 20, 20); } }
9
public UserRole login(String userName, String password) { UserRole userRole = null; String query = "SELECT * FROM USER_ROLE WHERE USERNAME=? AND PASSWORD=?"; try { PreparedStatement statement = connection.prepareStatement(query); statement.setString(1, userName); statement.setString(2, password); ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { userRole = new UserRole(); userRole.setId(resultSet.getInt("ID")); userRole.setHakAkses(resultSet.getString("HAK_AKSES")); userRole.setUserName(resultSet.getString("USERNAME")); userRole.setPassword(resultSet.getString("PASSWORD")); } } catch (SQLException ex) { } finally { return userRole; } }
2
@Override public String getMCstring(){ String s = ""; for (int i = 0; i < mc.length; i++) { if(mc[i] == true) s = s.concat("1"); else s = s.concat("0"); if (i == 5 || i == 10 || i == 15) s = s.concat(" "); } return s; }
5
public void run() { boolean properConnect = true; boolean initName = false; try { inClient = new BufferedReader(new InputStreamReader(connect.getInputStream())); outClient = new DataOutputStream(connect.getOutputStream()); } catch(IOException e) { System.out.println("Could not establish proper IO at the beginning"); properConnect = false; } if(properConnect) { while(this.connect.isConnected() && (!this.tellQuit)) { if(!initName){ //establishing of players names and the pieces that that they are assigned. Happens once. initNameStats(); initName = true; try { this.connect.setSoTimeout(1000); } catch (SocketException e) { System.out.println("Cannot set timeout"); } } //first part of the loop is finding out state of board and sending messages //to the player. And then receiving their response if(this.myPlayNum < 2) { if(this.sharedBoard.getFullVic() > 0) { this.vict = true; } else { this.vict = false; } this.yourTurn = myTurn(); serverSendMessages(); serverReceiveMessages(); } else { this.tellQuit = true; } } } else { System.out.println("Could not establish IO with this connectio"); } try { inClient.close(); outClient.close(); this.connect.close(); } catch(IOException clo) { System.out.println("Could not close connection properly"); } }
9
public static boolean writeFile(String filePath, String file) { //Declares new Buffered Writer object BufferedWriter writer = null; File textFile = new File(filePath); try { //Sets the value of the buffered writer object, including the name of the output file writer = new BufferedWriter(new FileWriter(textFile)); writer.write(file); } //Tidies up any errors occurring in the try block, and prints 'Write Error' only if there were errors catch(IOException e) { System.err.println("Write Error"); return false; } finally { //Closes the writer, ending the file try { if(writer != null) writer.close(); } //Prints 'A different write error' if the writer cannot be closed catch(IOException e) { System.err.println("A different write error"); return false; } } return true; }
3
public static void main(String[] args) { // TODO Auto-generated method stub if(args.length<4) { System.err.println("Argument error"); System.err.println("Argument: input_file output_file uni_gram_file bi_tri_gram"); System.exit(1); } SVMExtractor se=new SVMExtractor(args[2],args[3]); try { BufferedReader bf=new BufferedReader(new FileReader(args[0])); String line; BufferedWriter bw=new BufferedWriter(new FileWriter(args[1])); int count=0; while((line=bf.readLine())!=null) { // System.out.println(count); String[] parts=line.trim().split("\t"); if(parts.length!=2) { System.err.println("Erroneous format"); System.exit(1); } String tag=parts[0]; // c.print_test_data(tag,parts[1]); SVMFeature f=se.extract_feature(parts[1]); ArrayList<Double> feat_vec=se.build_feature_vec(f); se.print_feature(tag, feat_vec, bw); count++; System.err.println(count); } bw.close(); bf.close(); } catch(Exception e) { System.err.println(e.getMessage()); } }
4
private static int format(final StringBuilder sb, final String s, int lineLength) { if (s.isEmpty()) { return 0; } int l = lineLength; final String[] parts = s.split(" "); boolean front = sb.length() != 0; for (final String part : parts) { if ((l > 0) && ((l + part.length() + 1) >= Main.MAX_LENGTH_INFO)) { sb.append("\n"); l = 0; } else if (!front) { ++l; sb.append(" "); } front = false; sb.append(part); l += part.length(); } return l; }
5
public static String readFile(String name) { StringBuilder b = new StringBuilder(); try { BufferedReader r = new BufferedReader(new FileReader(name)); String line; while ((line = r.readLine()) != null) { b.append(line).append('\n'); } r.close(); } catch (IOException E) { throw new ComponentException(E.getMessage()); } return b.toString(); }
2
private static void imprimir_lexema(Token token, int i) { String lexema = token.getLexema(); //Formateamos de manera legible el EOF if (token.getLexema().contains("\uffff") ) { lexema = "eof"; } //Formateamos de manera legible el salto de línea if (token.getLexema().contains("\n") ) { lexema = "\\n"; } //Imprime de acuerdo a lo parametrizado if (i == 1) { System.out.print(token.getComponenteLexico()); } else if (i == 2) { System.out.print(token.getComponenteLexico() + "{" + lexema + "}"); } //A modo de que sea igual la salida del ejemplo provisto, forzamos //un salto de línea cuando el componente léxico es un TERMINADOR_ENTER //y para los demás, se añade un espacio para la legibilidad. if (token.getComponenteLexico() == TERMINADOR_ENTER) { System.out.println(); } else { System.out.print(' '); } }
5
public void addClickableFunction(final JFrame frame, int xLoc, int yLoc,int width, int height, final String type){ JLabel label = new JLabel(); label.setBounds(xLoc, yLoc, width, height); label.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { if(type.equalsIgnoreCase("nextDialogEntry")){ if(getNextDeId() <=getMaxDeSize()-1){ frame.getContentPane().removeAll(); JTextArea dialog = getDialogEntry(frame, getConv(), actors, false); frame.add(dialog); frame.repaint(); setDialogBackground(frame, backgroundImage); } else { BuildRoom r = new BuildRoom(getRoomId(), frame); System.out.println("I built room "+getRoomId()); } } if(type.equalsIgnoreCase("option:1")){ setNextDeId(getOptionOne()); frame.getContentPane().removeAll(); JTextArea dialog = getDialogEntry(frame, getConv(), actors, false); frame.add(dialog); frame.repaint(); setDialogBackground(frame, backgroundImage); } if(type.equalsIgnoreCase("option:2")){ setNextDeId(getOptionTwo()); frame.getContentPane().removeAll(); JTextArea dialog = getDialogEntry(frame, getConv(), actors, false); frame.add(dialog); frame.repaint(); setDialogBackground(frame, backgroundImage); } if(type.equalsIgnoreCase("option:3")){ setNextDeId(getOptionThree()); frame.getContentPane().removeAll(); JTextArea dialog = getDialogEntry(frame, getConv(), actors, false); frame.add(dialog); frame.repaint(); setDialogBackground(frame, backgroundImage); } }}); frame.add(label); }
5
private static void sellToStation(AIPlayer player) { Station station = player.getCurrentStar().getStation(); CargoHoldComponent hold = player.getShip().getCargoHold().get(); // find best value item to sell that player has in cargo and wasn't just // bought if (hold.getCargoSpaceUsage() > 0) { int greatestDifference = 0; CargoEnum bestCargoEnum = null; for (CargoEnum cargoEnum : CargoEnum.getList()) { if (hold.getCargoAmount(cargoEnum) > 0) { int s = station.getTransactionPrice(cargoEnum); int p = player.getTransactionPrice(cargoEnum); int difference = s - p; if (difference > greatestDifference && !player.isRecentlyPurchased(cargoEnum)) { greatestDifference = difference; bestCargoEnum = cargoEnum; } } } // sell max of that item if (bestCargoEnum != null && player.isBestSellPrice(bestCargoEnum, station.getTransactionPrice(bestCargoEnum))) { int maxSaleAmount = TransactionManager.getMaximumAmount(station.getWallet().getCredits(), station.getTransactionPrice(bestCargoEnum), station.getShip().getCargoHold().get().getRemainingCargoSpace(), bestCargoEnum.getSize(), hold.getCargoAmount(bestCargoEnum)); if (TransactionManager.validateSellToStationTransaction(player, station, bestCargoEnum, maxSaleAmount) == 0) { TransactionManager.performSellToStationTransaction(player, station, bestCargoEnum, maxSaleAmount); player.addRecentlyPurchased(bestCargoEnum); // //System.out.println("sold " + maxSaleAmount + " " + // bestCargoEnum); } } } }
8
void guess(int a, int b){ for (int i = 0; i < checkSet.length; i++) { if (!checkSet[i]) { continue; } int count = 0; for (int j = 0; j < checkSet.length; j++) { if (checkSet[j]) { count++; } } System.out.print("\ncheckSet is: " + count); if (count == 0){ outcome = "You've entered wrong response, please check it again and click 'figure out' button."; break; } else { guessNumber = answerSet[i]; outcome = answerSet[i] + " "; if (a == 4) { outcome = "The Goal Number is: " + answerSet[i] + "."; finish = true; break; } break; } } }
6
public void applyBridgeMode(int x, int y) { Ground tile = groundArray[0][x][y]; for (int z = 0; z < 3; z++) { Ground _tile = groundArray[z][x][y] = groundArray[z + 1][x][y]; if (_tile != null) { _tile.z--; for (int e = 0; e < _tile.entityCount; e++) { InteractiveObject entity = _tile.interactiveObjects[e]; if ((entity.uid >> 29 & 3) == 2 && entity.tileLeft == x && entity.tileTop == y) entity.z--; } } } if (groundArray[0][x][y] == null) groundArray[0][x][y] = new Ground(0, x, y); groundArray[0][x][y].tileBelow = tile; groundArray[3][x][y] = null; }
7
public ROb<CompanyPerson> registerRelation (Long personCedule, Long companyId, String rolPerson, String passwordCompany){ System.out.println("++++++++++++ Registar relacion: Me han invocado"); ROb<CompanyPerson> rob = new ROb<CompanyPerson>(); try{ Person person = (Person) personFacade.findByCedule(personCedule).getData(); Company company = (Company) companyFacade.findById(companyId).getData(); if(person!=null && company!=null && person.getDeath()==null){ if(company.getPassword().equals(passwordCompany)){ CompanyPerson companyPerson = new CompanyPerson(); CompanyPersonPK pk = new CompanyPersonPK(); pk.setPersonsCedule(personCedule); pk.setCompaniesId(companyId); companyPerson.setCompanyPersonPK(pk); company.getCompanyPersonCollection().add(companyPerson); companyPerson.setCompany(company); person.getCompanyPersonCollection().add(companyPerson); companyPerson.setPerson(person); companyPerson.setRol(rolPerson); create(companyPerson); rob.setSuccess(true); rob.setData(companyPerson); return rob; } } rob.setSuccess(false); rob.setErr_message("Cant find that Object!"); return rob; }catch(Exception e){ rob.setSuccess(false); rob.setErr_message("Failed transaction!"); return rob; } }
5
public void setClick(int ttype, String tid, int twhichone) { type=ttype; id=tid; whichOne=twhichone; }
0
public int findRightPositionOf(int i) { for (int j = i; j < this.permutArray.length; j++) { if (permutArray[j] == i || -permutArray[j] == i) { return j; } } return 0; }
3
public int getLevel() { if(level < 1) { level = 1; } return level; }
1
private void startButtonActionPerformed() { startPressed = true; final LogArtisanWorkshopOptions options = script.options; options.status = "Setup finished"; //Context.get().getScriptHandler().log.info("Mode: " + tabbedPane.getTitleAt(tabbedPane.getSelectedIndex())); String s = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex()); if (s.equals("Burial Armour")) { options.mode = Mode.BURIAL_ARMOUR; options.ingotType = (IngotType) burialIngotType.getSelectedItem(); options.ingotGrade = (IngotGrade) burialIngotGrade.getSelectedItem(); options.respectRepairPipes = burialRespectPipes.isSelected(); options.respectAncestors = respectKill.isSelected(); options.followInstructions = followInstructions.isSelected(); } else if (s.equals("Ceremonial Swords")) { options.mode = Mode.CEREMONIAL_SWORDS; options.ingotType = (IngotType) swordIngotType.getSelectedItem(); options.ingotGrade = IngotGrade.FOUR; options.respectRepairPipes = swordRespectPipes.isSelected(); } else if (s.equals("Track room")) { options.mode = Mode.REPAIR_TRACK; options.ingotType = (IngotType) trackIngotType.getSelectedItem(); script.ctx.controller.offer(new Task<LogArtisanWorkshop>(script) { @Override public void run() { if (!ctx.backpack.select().isEmpty()) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { new ErrorDialog("Backpack not empty", "It is recommended to start the script with an empty backpack, if the script messes up restart with an empty backpack"); } catch (Exception ignored) { } } }); } } }); } else { script.ctx.controller.stop(); } script.createTree(); dispose(); }
5
private String[] quoteAwareLineSplit(String line) { boolean ignoreCommas = false; // used when quotes are found StringBuffer buff = new StringBuffer(); List<String> data = new ArrayList<String>(); char prevChar = 0; for (int i = 0; i < line.length(); i++) { if (line.charAt(i) == '\"') { ignoreCommas = !ignoreCommas; if (ignoreCommas && prevChar == '\"') { buff.append(line.charAt(i)); } } else { if (!ignoreCommas && line.charAt(i) == ',') { data.add(buff.toString()); buff.delete(0, buff.length()); } else { buff.append(line.charAt(i)); } } prevChar = line.charAt(i); } if (buff.length() > 0) { data.add(buff.toString()); } return data.toArray(new String[0]); }
7
@Override public void setDef(String value) {this.def = value;}
0
private void doubleClick(MouseEvent e) { System.out.println("DOUBLE CLICK"); if (clickedOnDeck(e)) { if (!game.getDeck().isEmpty()) { Card toSendUp = game.getDeck().peek(); int pileIndex = pileIndexToSendTo(toSendUp); if (pileIndex != -1) { CardMove toMove = new CardMove(game); toMove.cardReleased(pileIndex, true); String result = toMove.makeMove(game); processMoveResult(result, toMove); } else { //Send to dragon's tail CardMove toMove = new CardMove(game); toMove.cardReleased(0, false); String result = toMove.makeMove(game); processMoveResult(result, toMove); } } } else if (e.getY() > Y_BOARD_OFFSET) { int col = findCol(e.getX()); List<Card> cardList = game.getBoard().get(col); Card toSendUp = cardList.get(cardList.size() - 1); int pileIndex = pileIndexToSendTo(toSendUp); System.out.println("sending to pile " + pileIndex); if (pileIndex != -1) { CardMove toMove = new CardMove(cardList.size() - 1, col, game); toMove.cardReleased(pileIndex, true); String result = toMove.makeMove(game); processMoveResult(result, toMove); } else { storeError("Cannot send that to the top"); } } }
5
@Override public void rawUpdate() throws Throwable { if (this.isPaused() || this.tasks.isEmpty()) { Thread.sleep(1L); return; } for (Task t : this.tasks) { if (t.completeTask()) { this.tasks.remove(t); } } }
4
private Direction getDirection(String inputCommand) { Keys key = Keys.valueOf(inputCommand); switch(key) { case UP: return Direction.NORTH; case DOWN: return Direction.SOUTH; case LEFT: return Direction.WEST; case RIGHT: return Direction.EAST; default: return Direction.NONE; } }
4
PageUnitGUI() { final JFrame jf = new JFrame("PageUnit Runner"); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final Container cp = new JPanel(); jf.add(cp, BorderLayout.CENTER); cp.setLayout(new FlowLayout()); cp.add(new JLabel("PageUnit Test File:")); final JTextField tf = new JTextField(20); cp.add(tf); String rememberedCurrentDirectory = p.get("directory", null); if (rememberedCurrentDirectory != null) { fileChooser.setCurrentDirectory(new File(rememberedCurrentDirectory)); } final JButton browseButton = new JButton("..."); cp.add(browseButton); browseButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int ret = fileChooser.showOpenDialog(tf); // blocking wait // XXX should use invokeLater()? if (ret != JFileChooser.APPROVE_OPTION) { return; } p.put("directory", fileChooser.getCurrentDirectory().getAbsolutePath()); tf.setText(fileChooser.getSelectedFile().getAbsolutePath()); } }); final JButton testButton = new JButton("Test"); cp.add(testButton); testButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { final String fileName = tf.getText(); if (fileName == null || fileName.length() == 0) { return; } final File f = new File(fileName); if (!f.canRead()) { error(jf, "Can't read file " + f); } // Run rest of this under a new Thread, so we don't block the EventDispatch thread... new Thread() { public void run() { try { TestResult results = new TestResult() { @Override public void startTest(Test test) { super.startTest(test); crank(); } @Override public synchronized void addError(Test test, Throwable t) { super.addError(test, t); seeRed(); } @Override public synchronized void addFailure(Test test, AssertionFailedError t) { super.addFailure(test, t); seeRed(); } }; TestCase t = new ScriptTestCase(f.getAbsolutePath()); int max = t.countTestCases(); System.out.printf("Starting %d tests%n", max); bar.setMaximum(max); t.run(results); } catch (Exception e) { error(jf, e.toString()); } } }.start(); } }); jf.add(bar, BorderLayout.SOUTH); seeGreen(); jf.pack(); UtilGUI.monitorWindowPosition(jf, p); jf.setVisible(true); }
6
public static boolean checkSpare(Frame frame) throws UnexpectedTypeException { Integer firstScore = frame.getScore(ScoreType.FIRST); Integer secondScore = frame.getScore(ScoreType.SECOND); if(firstScore == null || secondScore == null) { return false; } if((firstScore + secondScore) == IConstants.FRAME_PER_PERSON) { return true; } return false; }
3
public void zerarQuantidadeVendido(){ for (Produto p : produtos) { p.setQuantidedeVendido(0.0); } }
1
public static boolean validChoice(int row, int column) { boolean isValid = true; if (row < 0 || row > 2 || column < 0 || column > 2) { isValid = false; } else if (board[row][column] != '.') { isValid = false; } return isValid; }
5
@Override public void setDescription(String description) { this.description = description; }
0
boolean isExist(char[][] matrix, boolean[][] flag, int i, int j, String word) { if (word.equals("")) return true; char x = word.charAt(0); word = word.substring(1); for (int k = 0; k < 4; k++) { int m = i + d[k][0]; int n = j + d[k][1]; if (isValid(matrix, m, n) && matrix[m][n] == x && !flag[m][n]) { flag[m][n] = true; if (isExist(matrix, flag, m, n, word)) return true; flag[m][n] = false; } } return false; }
6
private static void calcPercentages() { percentages = new ArrayList<Float>(); long sum = 0; for (Long l : sums) { sum += l; } for (int i = 0; i < sums.size(); i++) { percentages.add(((float)sums.get(i))/((float)sum)); } }
2
public void shoot() { this.performance = this.performance -1; if (this.hasArrow){ this.setArrow(false); this.performance = this.performance -10; } }
1
private void jump(int S) { Color playerColor = _board[S].getColor(); if (_board[S].getSpots() > neighbors(S) && getWinner() == null) { _board[S].setSpots(1); if (col(S) < size()) { jumpAddSpot(playerColor, row(S), col(S) + 1); } if (row(S) > 1) { jumpAddSpot(playerColor, row(S) - 1, col(S)); } if (row(S) < size()) { jumpAddSpot(playerColor, row(S) + 1, col(S)); } if (col(S) > 1) { jumpAddSpot(playerColor, row(S), col(S) - 1); } } }
6
Set(LegacyRegister[] regs) { registerSet = new HashSet(2 * regs.length); for (int cntr = 0; cntr < regs.length; cntr++) { registerSet.add(regs[cntr]); } StringBuffer buf = new StringBuffer("{"); for (int cntr = 0; cntr < regs.length; cntr++) { registerSet.add(regs[cntr]); // abreviate large sets if (cntr == 2 && regs.length > 4) buf.append("..., "); // print first two, and last, or all if the set is fewer than five if (cntr < 2 || cntr == regs.length - 1 || regs.length < 5) { buf.append(regs[cntr]); if (cntr < regs.length - 1) buf.append(", "); } } buf.append('}'); contents = buf.toString(); }
8
static final void method358(int i, int i_3_, int i_4_, int i_5_, int i_6_, int i_7_, int i_8_) { if (i_8_ != -29494) amountClanChatUsers = 32; if (((Class348_Sub51) BitmapTable.aClass348_Sub51_3959) .aClass239_Sub26_7272.method1838(-32350) != 0 && i != 0 && Message.anInt2021 < 50 && (i_7_ ^ 0xffffffff) != 0) Class258_Sub2.aClass10Array8531[Message.anInt2021++] = new Class10((byte) 1, i_7_, i, i_4_, i_5_, i_3_, i_6_, null); anInt490++; }
5
private static Product ProductObject(ResultSet rs) { Product newProduct = null; try { newProduct = new Product(rs.getInt(rs.getMetaData().getColumnName(1)), rs.getString(rs.getMetaData().getColumnName(2)), rs.getString(rs.getMetaData().getColumnName(3))); } catch (SQLException e) { Error_Frame.Error(e.toString()); } return newProduct; }
1
static boolean hascontained(ArrayList<Pair> list, Pair pr) { for (int j=0; j<list.size(); j++){ if (list.get(j).equals(pr)) { return true; } } return false; }
2
public boolean isEmpty() { return first == null; }
0
public void parseExpression(CharSequence expression, Handler handler) { Matcher matcherMeta = EXPR_META.matcher(expression); if(matcherMeta.find()) { Map<String,String> meta = new HashMap<String, String>(); String inlined = matcherMeta.group(1); parseStyles(meta, inlined); handler.emit(meta); return; } Id leftId = null; String relationExpr = null; Matcher matcher = EXPR_LEFTSIDE.matcher(expression); while(matcher.find()) { Element element = parseElement(matcher.group(1)); Id rightId = handler.emit(element); if(relationExpr!=null) { handler.emit(parseRelation(leftId, rightId, relationExpr)); } relationExpr = matcher.group(2); leftId = rightId; } }
3
@Override public void nextCard(){ CardImpl nextCard = null; int boxToCheck = this.curBox; boolean firstLoop = true; while (nextCard == null){ nextCard = this.model.getTopic().getRandomCard(boxToCheck); if (firstLoop){ boxToCheck = 0; firstLoop = false; } else { boxToCheck +=1; } if (boxToCheck > Application.boxCount){ break;//boxToCheck = 1; } } this.model = nextCard; this.cardShown = new Date().getTime(); this.view.cardChanged(); }
3
private boolean func_151636_a(int[] p_151636_1_, int[] p_151636_2_, int p_151636_3_, int p_151636_4_, int p_151636_5_, int p_151636_6_, int p_151636_7_, int p_151636_8_) { if (!compareBiomesById(p_151636_6_, p_151636_7_)) { return false; } else { int k1 = p_151636_1_[p_151636_3_ + 1 + (p_151636_4_ + 1 - 1) * (p_151636_5_ + 2)]; int l1 = p_151636_1_[p_151636_3_ + 1 + 1 + (p_151636_4_ + 1) * (p_151636_5_ + 2)]; int i2 = p_151636_1_[p_151636_3_ + 1 - 1 + (p_151636_4_ + 1) * (p_151636_5_ + 2)]; int j2 = p_151636_1_[p_151636_3_ + 1 + (p_151636_4_ + 1 + 1) * (p_151636_5_ + 2)]; if (this.func_151634_b(k1, p_151636_7_) && this.func_151634_b(l1, p_151636_7_) && this.func_151634_b(i2, p_151636_7_) && this.func_151634_b(j2, p_151636_7_)) { p_151636_2_[p_151636_3_ + p_151636_4_ * p_151636_5_] = p_151636_6_; } else { p_151636_2_[p_151636_3_ + p_151636_4_ * p_151636_5_] = p_151636_8_; } return true; } }
5
static int[] heapSort(int[] A){ TreeSet<Integer> heap = new TreeSet<Integer>(); int[] ret = new int[A.length]; for(int i=0;i<A.length;i++){ heap.add(A[i]); } for(int i=0;i<A.length;i++){ ret[i]=heap.pollFirst(); } return ret; }
2
public void visitExprStmt(final ExprStmt stmt) { if (stmt.expr == from) { stmt.expr = (Expr) to; ((Expr) to).setParent(stmt); } else { stmt.visitChildren(this); } }
1
public int[] getInts(int par1, int par2, int par3, int par4) { int i = par1 - 1; int j = par2 - 1; int k = par3 + 2; int l = par4 + 2; int ai[] = parent.getInts(i, j, k, l); int ai1[] = IntCache.getIntCache(par3 * par4); for (int i1 = 0; i1 < par4; i1++) { for (int j1 = 0; j1 < par3; j1++) { int k1 = ai[j1 + 0 + (i1 + 0) * k]; int l1 = ai[j1 + 2 + (i1 + 0) * k]; int i2 = ai[j1 + 0 + (i1 + 2) * k]; int j2 = ai[j1 + 2 + (i1 + 2) * k]; int k2 = ai[j1 + 1 + (i1 + 1) * k]; initChunkSeed(j1 + par1, i1 + par2); if (k2 == 0 && k1 == 0 && l1 == 0 && i2 == 0 && j2 == 0 && nextInt(100) == 0) { ai1[j1 + i1 * par3] = BiomeGenBase.mushroomIsland.biomeID; } else { ai1[j1 + i1 * par3] = k2; } } } return ai1; }
8
@Override public void getOptions() { for (Component p : getParent().getComponents()) { if (p instanceof OptionsPanel) { matrixOn = ((OptionsPanel) p).isMatrixOn(); type = ((OptionsPanel) p).getType(); } } if (matrixOn) { startMatrix(); } else { stopMatrix(); } }
3
public void extendSchema() { // Recursive method to add 1-1 Relationships from vicinity up to a // defined level System.out.println("Extending schema..."); logger.info("Extending schema"); for (Table table : schema.getTables()) { Set<ColumnFamily> extendedColumnFamilies = extendAndMerge(table, 1, "", table); for (ColumnFamily columnFamily : extendedColumnFamilies) { // Nested families are added as a special type EXT table.addColumnFamily(columnFamily.getName(), columnFamily.getBaseRelationalTable(), ColumnFamily.Type.EXT); table.getColumnFamily(columnFamily.getName()).setManyKey(columnFamily.getManyKey()); String[] pieces = columnFamily.getBaseRelationalTable().split( conf.getExtColFamilyDelimiter()); String tableName = pieces[pieces.length - 1]; for (Column col : columnFamily.getColumns()) { boolean checked = false; if (usage.isColumnUsedInTheSameQueryWithTable(tableName, col.getName(), table.getName())) { checked = true; } if (Main.ENV.equals("DEBUG")) { checked = true; } if (columnFamily.getBaseRelationalTable().equals( "products") && !table.getName().equals("products") && !(col.getName().equals("PROD_ID") || col.getName().equals("TITLE"))) { checked = false; } table.addColumn(columnFamily.getName(), col.getTable(), col.getName(), col.getType(), checked); } } } }
9
protected void performChoice(int choice) { if (choice == 1) { HMMDefaultsMenu menu = new HMMDefaultsMenu(); menu.run(); } else if (choice == 2) { HMMConstructionMenu menu = new HMMConstructionMenu(); menu.run(); hmm = menu.getHMM(); } else if (choice == 3) { if (this.hmm != null) { HMMUpdateMenu menu = new HMMUpdateMenu(this.hmm); menu.run(); hmm = menu.getHMM(); } } else if (choice == 4) { if (this.hmm != null) { int count = getInteger("How many entries?"); HMMSequenceGenerator.createSequenceFromHMM(hmm, count); } } else if (choice == 5) { if (this.hmm != null && this.hmm.getStateSequence() != null) { HMMDecodingMenu menu = new HMMDecodingMenu(this.hmm); menu.run(); } } }
9
@Override public String toString() { final StringBuilder sb = new StringBuilder("Student{"); sb.append("number='").append(number).append('\''); sb.append(", scores=").append(scores); sb.append('}'); return sb.toString(); }
0
static String[] loadPlayerNames(String txtPath) { ArrayList<String> namelist = new ArrayList<String>(); try { // get file of players BufferedReader in = new BufferedReader(new FileReader(new File(txtPath))); String line; while ( (line = in.readLine()) != null) if (line.trim() != "") namelist.add(line); } catch (Exception e) { e.printStackTrace(); System.exit(1); } return namelist.toArray(new String[0]); }
3
public void list() { //get all values for(Exit e:exits.values()) { //get pairs of keys and values for (Entry<String, Exit> entry : exits.entrySet()) { //if key is equal to the value if (e.equals(entry.getValue())) { if(e.isVisible())//and is visible System.out.println("Exit: "+entry.getKey()+" "+e.getName());//spit it out break;//continue with next value } } } //get all values for(Item e:items.values()) { //get pairs of keys and values for (Entry<String, Item> entry : items.entrySet()) { if (e.equals(entry.getValue())) {//if key is equal to the value if(e.isVisible())//and is visible System.out.println("Item: "+entry.getKey()+" "+e.getName());//spit it out break;//continue with next value } } } }
8
public char getWinner() { char result; if(gameOver) return winner; int blackCount=0; int whiteCount=0; if(surrendering){ for(char c : grid) { if(c=='B') blackCount++; if(c=='W') whiteCount++; } if(blackCount>whiteCount) setWinner('B'); else if(whiteCount>blackCount) setWinner('W'); else setWinner(' '); } return winner; }
7
public void compute() { if (opponent == null) return; // Calculate the relative velocity between ourselves and the opponent // This is called the closing velocity. Vector3D velocityClosing = Vector3D.subtract(opponent.getVelocityVector(), getVelocityVector()); System.out.println("velocityClosing = " + velocityClosing); if (velocityClosing.getMagnitude() < Utility.nearZero) return; // Now calculate the range to close, which is the relative distance between // us and the opponent. Vector3D rangeToClose = Vector3D.subtract(opponent.getLocation(), getLocation()); System.out.println("rangeToClose = " + rangeToClose); // This is the time to close, which is the average time it will take to // travel a distance equal to rangeToClose while travelling at a // velocityClosing speed. float timeToClose = rangeToClose.getMagnitude() / velocityClosing.getMagnitude(); System.out.println("timeToClose = " + timeToClose); // Now that we know the timeToClose, we can predict where the opponent will // be at timeToClose in the future. The current position of the opponent // is opponent.getLocation(), and it is travelling at opponent.getVelocityVector() // speed. Because speed times time gives an average distance, we can calculate // how far the opponent will travel over timeToClose, travelling at // opponent.getVelocityVector() speed, and add it to its current position to // get its predicted position. Vector3D predictedPosition = Vector3D.add(opponent.getLocation(), Vector3D.multiply(opponent.getVelocityVector(), timeToClose)); System.out.println("InterceptionChaser: current posn=" + opponent.getLocation() + " predicted posn=" + predictedPosition); // Obtain angle between us and the prey's predicted position double angleToPrey = getLocation().orientTo(predictedPosition); // Fire as continuously as gun heating will allow. if (getGunCurrentTemp() < getGunUnjamTemp()) fire((float)angleToPrey); // Steer toward prey's predicted position. setDirection(angleToPrey, 1.0f); }
3
@Test public void testNeighbour() { // test Parameters n = getSettings().getParameters().neighbour(); assertNotNull(n); assertTrue( "The neighbour of current Settings must not be the same object as Settings. - Expecting a slightly changed CLONE!", !n.equals(getSettings().getParameters())); // assert "slight difference" to currently set Parameters: Settings s = getSettings(); boolean blastParamDiff = false; for (String blastDbName : getSettings().getBlastDatabases()) { blastParamDiff = blastParamDiff || (!n.getBlastDbWeight(blastDbName).equals( s.getBlastDbWeight(blastDbName)) || !n .getDescriptionScoreBitScoreWeight(blastDbName) .equals(s .getDescriptionScoreBitScoreWeight(blastDbName))); } assertTrue( "The cloned neighbour must differ in exactly one AHRD-parameter-field from the currently set Settings.", (!n.getTokenScoreBitScoreWeight().equals( s.getTokenScoreBitScoreWeight()) || !n.getTokenScoreDatabaseScoreWeight().equals( s.getTokenScoreDatabaseScoreWeight()) || !n .getTokenScoreOverlapScoreWeight().equals( s.getTokenScoreOverlapScoreWeight())) || !n.getDescriptionScorePatternFactorWeight().equals( s.getDescriptionScorePatternFactorWeight()) || blastParamDiff); }
7
private void save() { if (script == null) { return; } final Properties settings = new Properties(); LinkedHashMap<Integer, List<String>> map = getTabContents(1); JsonObject object = new JsonObject(); int i = 1; for (Map.Entry<Integer, List<String>> entry : map.entrySet()) { JsonArray values = new JsonArray(); for (String s : entry.getValue()) { values.add(s); } object.add(String.valueOf(i), values); i++; } settings.put("Tabs", object.toString()); try { settings.store(new FileOutputStream(new File(script.getStorageDirectory(), SETTINGS_INI)), "Log Bank Organiser"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
5
@Override public String toString() { return String.valueOf(name); }
0
public void start() throws LWJGLException { Display.create(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, Display.getWidth(), Display.getHeight(), 0, 1, -1); glMatrixMode(GL_MODELVIEW); glEnable(GL_ALPHA_TEST); //glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); try { manager.init(this); long lastTime = System.currentTimeMillis(); int frames = 0; long lastSecond = System.currentTimeMillis(); while (!Display.isCloseRequested() && !isCloseRequested) { long now = System.currentTimeMillis(); glClear(GL_COLOR_BUFFER_BIT); long deltaTime = System.currentTimeMillis()-lastTime; lastTime += System.currentTimeMillis()-lastTime; manager.update(deltaTime); //System.out.println(deltaTime); manager.render(); Display.update(); frames++; if(System.currentTimeMillis()-lastSecond >= 1e3) { System.out.println(frames); frames = 0; lastSecond += 1e3; } long sleepTime = (int)Math.round(1e3/60.0 - (System.currentTimeMillis() - now)); if(sleepTime > 0) { long time = System.currentTimeMillis(); long timePassed; while((timePassed = System.currentTimeMillis() - time) < sleepTime) { if(timePassed < sleepTime * 0.8) try{ Thread.sleep(1); } catch(Exception exc) {} else Thread.yield(); } } } } catch(Exception exc) { exc.printStackTrace(); } finally { Display.destroy(); } }
8
private static void testBoxAddPosition(State state, Queue<State> nodes, Position player, int boxX, int boxY, int boxX2, int boxY2, Direction move, int index) { if (state.isFree(boxX, boxY) && state.isFree(boxX2, boxY2)) { Position boxPos = state.boxes.get(index); Result result = Search.bfs(state, new IsAtPosition(move, boxPos.x, boxPos.y), player.x, player.y); if (result != null) { ArrayList<Position> boxes = new ArrayList<Position>(state.boxes); boxes.set(index, new Position(boxX, boxY)); // Sort the boxes with a stable sort since we want that two configurations of boxes which are permutations // of each other are equal Collections.sort(boxes, comparePoints); State possibleStep = new State(state.map, new Position(boxX2, boxY2), boxes, result.path, state); Collections.reverse(possibleStep.playerPath); possibleStep.playerPath.add(move); if (!inHistory(possibleStep)){ nodes.add(possibleStep); } } } }
4
public static CommonClassLib getInstance() { if (commonClassLib == null) { commonClassLib = new CommonClassLib(); } return commonClassLib; }
1
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // COLLECTIONS (START) if (qName.equalsIgnoreCase("collections")) { readCollections = true; } // COLLECTIONS :: COLLECTION (START) else if (readCollections && qName.equalsIgnoreCase("collection")) { readCollection = true; // find current collection name currentCollectionName = attributes.getValue("name"); // create new collection fieldCollections.put(currentCollectionName, new FieldCollection()); } // COLLECTIONS :: COLLECTION :: COLOR (START) else if (readCollection && qName.equalsIgnoreCase("color")) { FieldCollection currentCollection = fieldCollections.get(currentCollectionName); int red = Integer.parseInt(attributes.getValue("red")); int green = Integer.parseInt(attributes.getValue("green")); int blue = Integer.parseInt(attributes.getValue("blue")); currentCollection.setColor(red, green, blue); } // FIELDS (START) else if (qName.equalsIgnoreCase("fields")) { readFields = true; } // FIELDS :: FIELD (START) else if (readFields && qName.equalsIgnoreCase("field")) { readField = true; currentFieldData = new HashMap<String, String>(); currentFieldData.put("class", attributes.getValue("class")); } // FIELDS :: FIELD :: <KEY> (START) else if (readFields) { currentFieldKey = qName; } }
9
public static boolean isLatinLetterOrDigit(char c) { return (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9'); }
5
public int getMaxRange(String minMatch, String maxMatch, int dataContentLength) { if (maxMatch != null) { if (minMatch == null) { return dataContentLength; } else { return Integer.parseInt(maxMatch) + 1; } } else { return dataContentLength; } }
2
public boolean isNan() { return Double.isNaN(re) || Double.isNaN(im); }
1
public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("We are going to calculate Pie using the Leibniz formula."); System.out.print("How many terms do you wish to use? "); int termsCount = s.nextInt(); int termsSoFar = 1; double divider = 3; double pie = 4 / 1; while(termsSoFar < termsCount){ if(termsSoFar%2 == 1){ pie -= (4 / divider); } else{ pie += (4 / divider); } termsSoFar++; divider += 2; } System.out.println(pie); }
2
public BufferedImage getImage(int animation){ if(this.animation != animation){ this.animation = animation; index = 0; lastChange = System.currentTimeMillis(); } else if(System.currentTimeMillis() > lastChange + delay[animation]){ lastChange += delay[animation]; index = (index + 1) % length[animation]; } return images[animation][index]; }
2
public boolean canInfo(CommandSender sender) { if ( sender instanceof Player ) { return this.hasPermission((Player)sender, "SheepFeed.info"); } return true; // can info from console }
1
public void run() { long lastTime = System.nanoTime(); long timer = System.currentTimeMillis(); final double ns = 1000000000.0 / 60.0; double delta = 0; int frames = 0; int updates = 0; requestFocus(); while (running) { int missedUpdates = 0; int missedRenders = 0; long now = System.nanoTime(); delta += (now - lastTime) / ns; lastTime = now; while (delta >= 1) { try{ update(); updates++; delta--; }catch (Exception e){ e.printStackTrace(); missedUpdates++; System.out.println("Missed Update! " + missedUpdates); } } try{ render(); frames++; }catch (Exception e){ e.printStackTrace(); missedUpdates++; System.out.println("Missed Render! " + missedUpdates); } if (System.currentTimeMillis() - timer > 1000) { timer += 1000; frame.setTitle(title + " | " + updates + " ups, " + frames + " fps"); updates = 0; frames = 0; } } stop(); }
5
public static String getExecTime() { return String.format("%.3f", (float)(new Date().getTime() - startedAt.getTime()) / 1000); }
0
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PersonAnnotated person2 = (PersonAnnotated) o; if (age != person2.age) return false; if (firstName != null ? !firstName.equals(person2.firstName) : person2.firstName != null) return false; if (lastName != null ? !lastName.equals(person2.lastName) : person2.lastName != null) return false; return true; }
8
public static byte[] Xdecode(String base64) { // how many padding digits? int pad = 0; for (int i = base64.length() - 1; base64.charAt(i) == '='; i--) pad++; // we know know the lenght of the target byte array. int length = base64.length() * 6 / 8 - pad; byte[] raw = new byte[length]; int rawIndex = 0; // loop through the base64 value. A correctly formed // base64 string always has a multiple of 4 characters. for (int i = 0; i < base64.length(); i += 4) { int block = (getValue(base64.charAt(i)) << 18) + (getValue(base64.charAt(i + 1)) << 12) + (getValue(base64.charAt(i + 2)) << 6) + (getValue(base64.charAt(i + 3))); // based on the block, the byte array is filled with the // appropriate 8 bit values for (int j = 0; j < 3 && rawIndex + j < raw.length; j++) raw[rawIndex + j] = (byte)((block >> (8 * (2 - j))) & 0xff); rawIndex += 3; } return raw; }
4
public void playSong(Song song) throws NetworkException { ApiMusicImpl apiMusic = Controller.getInstance().getApiMusic(); ApiProfileImpl apiProfile = ApiProfileImpl.getApiProfile(); SongLibrary localSongLibrary = ApiProfileImpl.getApiProfile().getSongLibrary(); SongLoader songLoader = new SongLoader(); String path = null; boolean isLocal = false; // Get the path of the local song. if (localSongLibrary.islocal(song.getSongId())) { path = songLoader.getSongPath(song.getSongId()); isLocal = true; } else if (isTmp(song)) { path = songLoader.generateTempSongPath(song.getOwnerId(), song.getSongId()); isLocal = true; } // If the song is local play the temporary file else call the network. if (isLocal) { try { BitMusicPlayer.getInstance().play(path); } catch (JavaLayerException ex) { Logger.getLogger(SongPlayer.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(SongPlayer.class.getName()).log(Level.SEVERE, null, ex); } } else { apiMusic.getSongFile(apiProfile.getCurrentUser().getUserId(), song.getOwnerId(), song.getSongId(), true); } }
5
public static void main(String[] args) { char letter[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; double frequency[] = { 0.45, 0.13, 0.12, 0.16, 0.09, 0.05 }; PrefixTree pt = new PrefixTree(letter, frequency); for (int i = 0; i < letter.length; i++) System.out.println(letter[i] + " : " + pt.getCode(letter[i])); }
1
public void decoder(int[] octets_data){ }
0
@Override public ArrayList<String> getColumnsNames() throws Exception { ArrayList<String> alColumns = null; try { oMysql.conexion(enumTipoConexion); alColumns = oMysql.getColumnsName("cliente", Conexion.getDatabaseName()); oMysql.desconexion(); } catch (Exception e) { throw new Exception("ClienteDao.removeCliente: Error: " + e.getMessage()); } finally { oMysql.desconexion(); } return alColumns; }
1
@Override public boolean equals(final Object o) { if (!(o instanceof Color)) return false; final Color c = (Color) o; return r == c.r && g == c.g && b == c.b; }
3
public int getNumberResourcesType(String str) { if (str == null || str.equals("DESERT")) return 0; return resources.get(str).intValue(); }
2
private void btn_GuardarEnunciadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_GuardarEnunciadoActionPerformed Autor autor1 = new Autor(); autor1.setCodigo((cbAutor.getSelectedIndex() +1)); en1.setAutor(autor1); Area area = new Area(); area.setCodigo(cb_ListaAreas.getSelectedIndex() + 1); en1.setArea(area); //String fecha = fechaCreacion.getDate().toString(); // String fecha =new SimpleDateFormat("YYYY-MM-dd").format(fechaCreacion.getDate()); Calendar c = new GregorianCalendar(); String dia = Integer.toString(c.get(Calendar.DATE)); String mes = Integer.toString(c.get(Calendar.MONTH)); String annio = Integer.toString(c.get(Calendar.YEAR)); en1.setFechaCreacion(annio + "/" + mes + "/" + dia); Enunciado enaux = new Enunciado(); if (cb_ListaEnunciados.getSelectedItem().equals("Ninguno")) { enaux.setCodigo(0); } else { if ((cb_OrdenEnunciados.getSelectedIndex()) != 0) { JOptionPane.showMessageDialog(this, "Verifique sus condiciones, no pueden ingresar dos condicionamientos diferentes"); return; } enaux.setCodigo(cb_ListaEnunciados.getSelectedIndex() + 1); } en1.setDespuesDe(enaux); en1.setOrden(cb_OrdenEnunciados.getSelectedIndex() + 1); latex lt = new latex(); try { if (lt.crearEnunciado(en1) == 1) { // enunciadoDAO enDAO = new enunciadoDAO(); if (seleccion == 2) { //Duplicar ls backSlashh! if (ctrlEn.crearEnunciado(en1) == 1) { lblInformacion.setText("Enunciado "+en1.getCodigo()+ " almacenado correctamente!"); // JOptionPane.showMessageDialog(this, "Enunciado almacenado correctamente!"); btn_AgregarPregunta.setEnabled(true); } } else { if (ctrlEn.modificarEnunciado(en1) == 1) { lblInformacion.setText("Enunciado "+en1.getCodigo()+ " modificado correctamente!"); // JOptionPane.showMessageDialog(this, "Enunciado modificado correctamente!"); } } } } catch (IOException ex) { Logger.getLogger(administrarEnunciado.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(administrarEnunciado.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_btn_GuardarEnunciadoActionPerformed
8
public Destination destination(String s) { // Local inner class class PDestination implements Destination { private String label; private PDestination(String whereTo) { label = whereTo; } public String readLabel() { return label; } } return new PDestination(s); }
0
public void actionPerformed(ActionEvent e) { if(e.getSource()==timerRandOper) { cleanList(Schedule.completeList); cleanList(deadList); int i=0; int m=(int)(Math.random()*3); if(m==0) i=1; switch (i) { case 0://创建进程 creatProc(); break; case 1://唤醒进程 wakeupProc(); break; } } else if(e.getSource()==timerCrtProc) { if(newPcb!=null)//有新进程创建,执行动画 { //根据进程的优先级访问其应在优先级队列的元素个数,从而确定pcb最终位置,描绘沿途的点数组 //getPriorListSize(int prior) //计算路径//确定创建进程的动画路径 LinkedList ps=new LinkedList(); ps.add(new Point(640,15)); ps.add(new Point(640,135)); ps.add(new Point(585,135)); int n=scdl.getPriorListSize(newPcb.prior); ps.add(new Point(585,135+50*newPcb.prior)); ps.add(new Point(90+n*55,135+50*newPcb.prior)); boolean finish=newPcb.moveLines(ps); if(newPcb.getX()<90)//避免出现一直走不停地bug finish=true; if(finish)//动画完成 { scdl.loadProc(newPcb);//加入就绪队列 newPcb=null; } repaint(); } } }
8
@Override public void onDisable() { try { TreasureManager.getInstance().savePossibleTreasure(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { TreasureManager.getInstance().saveTreasureSpots(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
2
private void initializeRocks() { for(int i = 0; i < 250; i++) { Point point = getRandomLocationOnGrid(525); if(model.getElements().contains(new Rectangle(point.x, point.y, GameModel.UNIT, GameModel.UNIT))) { i++; continue; } else { model.addRock(point); } } int UNIT4 = GameModel.UNIT * 4; // Should be 100 if UNIT is 25 model.addRock(new Point(UNIT4 * 3, UNIT4 * 2)); // Below the Shop model.addRock(new Point(UNIT4 * 3 + GameModel.UNIT, UNIT4 * 2)); model.addRock(new Point(UNIT4 * 3 + GameModel.UNIT * 2, UNIT4 * 2)); }
2
public void run() { projectileDie(); characterDie(); collision(); for (int i = 0; i < characters.size(); i++) { characters.get(i).move(); } for (int i = 0; i < projectiles.size(); i++) { projectiles.get(i).move(); } if (!characters.contains(player)) { JOptionPane.showMessageDialog(null, "GAME OVER. Please enter another coin to continue."); System.exit(0); } if (characters.size() == 1 || player.cheatKeyPressed) { levelIndex++; levelStart(); } if (player.powerUp == 0){ powerUpTime++; if (powerUpTime == player.health + 80){ if ((int) (Math.random() * 2) == 1){ powerUps.add(new PowerUp( (int) Math.random() * 980 + 300, (int) Math.random() * 660 + 300, 100, 100, 1)); } else { powerUps.add(new PowerUp( (int) Math.random() * 980 + 300, (int) Math.random() * 660 + 300, 100, 100, 2)); } } } }
8
public static int findNewLine(byte[] arr, int offset) { int len = arr.length - 1; int i = offset; for (; i < len; i++) if (arr[i] == (byte) '\r' && arr[i + 1] == (byte) '\n') return i; return i;// the end of input will be handled like newline }
3
private static HashMap<Integer, Integer> mapCorners(char[] state) { HashMap<Integer, Integer> result = new HashMap<Integer, Integer>(); int[][] corners = Cube.CORNERS; HashMap<String, Integer> goalCorners = initGoalCorners(); for(int j = 0; j < corners.length; j++) { String needle = ""; for (int s : corners[j]) { needle += state[s]; } char[] chars = needle.toCharArray(); Arrays.sort(chars); result.put(goalCorners.get(new String(chars)), j); } return result; }
2
public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); fillDP(); d: do { line = br.readLine(); if (line == null || line.length() == 0) break d; int n = Integer.parseInt(line); out.append("TERM " + n + " IS " + ((char) dp[n])).append("\n"); } while (line != null && line.length() != 0); System.out.print(out); }
4
public void search(CharSequence text, int start, WordDic wdic, List<ViterbiNode> result) { final char ch = text.charAt(start); final CharCategory.Category ct = category.category(ch); if(result.isEmpty()==false && ct.invoke==false) return; final boolean isSpace = ct.id==spaceId; final int limit = Math.min(text.length(), ct.length+start); int i=start; for(; i < limit; i++) { wdic.searchFromTrieId(ct.id, start, (i-start)+1, isSpace, result); if(i+1!=limit && category.isCompatible(ch, text.charAt(i+1)) == false) return; } if(ct.group && i < text.length()) { for(; i < text.length(); i++) if(category.isCompatible(ch, text.charAt(i)) == false) { wdic.searchFromTrieId(ct.id, start, i-start, isSpace, result); return; } wdic.searchFromTrieId(ct.id, start, text.length()-start, isSpace, result); } }
9
public static Connection getConnection() throws SQLException, IOException { Properties props = new Properties(); FileInputStream in = null; try { in = new FileInputStream("C:\\JavaProjects\\TelephoneBook-v2\\src\\com\\woolfer\\telephonebook\\db\\database.properties"); props.load(in); in.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String drivers = props.getProperty("jdbc.drivers"); if (drivers != null) System.setProperty("jdbc.drivers", drivers); String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); try { Class.forName ("com.mysql.jdbc.Driver").newInstance (); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return DriverManager.getConnection(url, username, password); }
5