text
stringlengths
14
410k
label
int32
0
9
public void moveCell(int aFromIndex, int aToIndex) { if (aFromIndex < aToIndex) aToIndex --; if ( aFromIndex >= 0 && aFromIndex < cellList.size() && aToIndex >= 0 && aToIndex < cellList.size() ) { // swap AnimationCell cell = cellList.get(aFromIndex); cellList.remove(aFromIndex); if (aToIndex < cellList.size()) cellList.add(aToIndex, cell); else cellList.add(cell); for (int i=0; i<animationListeners.size(); ++i) animationListeners.get(i).cellOrderChanged(this); } }
7
public void fillIndexes(String... indexes) { if (indexes == null || indexes.length > MAX_IDX) { throw new IllegalArgumentException("Indexes are incorrect"); } for (int i = 0; i < indexes.length; i++) { switch (i) { case IDX_1: index1 = indexes[i].hashCode(); break; case IDX_2: index2 = indexes[i].hashCode(); break; case IDX_3: index3 = indexes[i].hashCode(); break; case IDX_4: index4 = indexes[i].hashCode(); break; case IDX_5: index5 = indexes[i].hashCode(); break; default: index6 = indexes[i].hashCode(); break; } } }
8
@EventHandler(priority = EventPriority.LOWEST) public void onPlayerCommand(PlayerCommandPreprocessEvent e){ Player player = e.getPlayer(); String[] args = e.getMessage().split(" "); if(e.getMessage().equalsIgnoreCase("/oitc")) return; if(e.getMessage().equalsIgnoreCase("/oitc help")) return; if(e.getMessage().equalsIgnoreCase("/oitc leave")) return; if(e.getMessage().equalsIgnoreCase("/oitc reload")) return; if(args[0].equalsIgnoreCase("/oitc") && args[1].equalsIgnoreCase("stop")) return; if(ArenaManager.getArenaManager().isInArena(player)){ e.setCancelled(true); File fichier_language = new File(OneInTheChamber.instance.getDataFolder() + File.separator + "Language.yml"); FileConfiguration Language = YamlConfiguration.loadConfiguration(fichier_language); String noCommands = Language.getString("Language.Error.No_commands"); UtilSendMessage.sendMessage(player, noCommands); } }
7
public FlowNetwork(int V) { this.V = V; adj = (Bag<FlowEdge>[]) new Bag[V]; for (int v = 0; v < V; v++) adj[v] = new Bag<FlowEdge>(); }
1
public void sendGamestate(int turnNumber, int dimension, String mapData[][], AIConnection playerlist[]){ JSONObject root = new JSONObject(); try { root.put("message", "gamestate"); root.put("turn", turnNumber); JSONArray players = new JSONArray(); for(AIConnection ai: playerlist){ JSONObject playerObject = new JSONObject(); playerObject.put("name", ai.username); if(turnNumber != 0){ playerObject.put("health", ai.health); playerObject.put("score", ai.score); playerObject.put("position", ai.position.coords.getCompactString()); JSONObject primaryWeaponObject = new JSONObject(); primaryWeaponObject.put("name", ai.primaryWeapon); primaryWeaponObject.put("level", ai.primaryWeaponLevel); playerObject.put("primary-weapon", primaryWeaponObject); JSONObject secondaryWeaponObject = new JSONObject(); secondaryWeaponObject.put("name", ai.secondaryWeapon); secondaryWeaponObject.put("level", ai.secondaryWeaponLevel); playerObject.put("secondary-weapon", secondaryWeaponObject); } players.put(playerObject); } root.put("players", players); JSONObject map = new JSONObject(); map.put("j-length", dimension); map.put("k-length", dimension); map.put("data", new JSONArray(mapData)); root.put("map", map); } catch (JSONException e){} try { sendMessage(root); } catch (IOException e) { Debug.error("Error writing to '" + username + "': " + e.getMessage()); } }
4
public DragonBaneSword(){ this.name = Constants.DRAGONBANE_SWORD; this.attackScore = 15; this.attackSpeed = 10; this.money = 789; }
0
public boolean attack(Unit enemy) { //this != enemy: this cannot be enemy if different teams, should be redundant check if(canAttack(enemy)) { int expGain = Calculator.expGain(lv, enemy.getLV()); int tDmg = Calculator.dmgAmt(atk + wepATK(), enemy.getDEF()) * 0; enemy.damage(tDmg); attacking = false; addEXP(expGain + 50); done(); return true; } return false; }
1
public double[][] rankedAttributes () throws Exception { int i, j; if (m_attributeList == null || m_attributeMerit == null) { throw new Exception("Search must be performed before a ranked " + "attribute list can be obtained"); } int[] ranked = Utils.sort(m_attributeMerit); // reverse the order of the ranked indexes double[][] bestToWorst = new double[ranked.length][2]; for (i = ranked.length - 1, j = 0; i >= 0; i--) { bestToWorst[j++][0] = ranked[i]; } // convert the indexes to attribute indexes for (i = 0; i < bestToWorst.length; i++) { int temp = ((int)bestToWorst[i][0]); bestToWorst[i][0] = m_attributeList[temp]; bestToWorst[i][1] = m_attributeMerit[temp]; } if (m_numToSelect > bestToWorst.length) { throw new Exception("More attributes requested than exist in the data"); } if (m_numToSelect <= 0) { if (m_threshold == -Double.MAX_VALUE) { m_calculatedNumToSelect = bestToWorst.length; } else { determineNumToSelectFromThreshold(bestToWorst); } } /* if (m_numToSelect > 0) { determineThreshFromNumToSelect(bestToWorst); } */ return bestToWorst; }
7
public void parseAndExecute(String[] args) { initOptions(options); // create the parser CommandLineParser parser = new GnuParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); parse(line); } catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); return; } try { execute(); } catch (Exception e) { // oops, something went wrong System.err.println("Execution failed. Reason: " + e.getMessage()); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(out); } }
2
public void paint1(Graphics g) { // g.drawImage(fondo.getImage(), 0, 0,1300,700, this); g.setFont(new Font("default", Font.BOLD, 16)); g.setColor(Color.white); if (vidas > 0) { if (bola != null) { g.drawImage(fondo, 0, 0, 1024, 640, this); //Dibuja la imagen en la posicion actualizada g.drawImage(bola.getImagenI(), bola.getPosX(), bola.getPosY(), this); //Dibuja la imagen en la posicion actualizada g.drawImage(barra.getImagenI(), barra.getPosX(), barra.getPosY(),this); g.drawImage(barra2.getImagenI(), barra2.getPosX(), barra2.getPosY(),this); g.drawImage(barra3.getImagenI(), barra3.getPosX(), barra3.getPosY(),this); g.drawImage(barra4.getImagenI(), barra4.getPosX(), barra4.getPosY(),this); // g.drawString("Puntos : " + list.get(0).getNum(), 10, 10); //Muestra las vidas g.drawString("Vidas: " + vidas, getWidth() / 2 - 10, 80); //Muestra el puntaje g.drawString("Puntaje: " + score, bola.getAncho(), 80); if (isPause()) { g.drawString(bola.getPAUSE(), bola.getPosX() + 15, bola.getPosY() + 30); } if (isChoca()) { g.drawString(bola.getDISP(), bola.getPosX() + 15, bola.getPosY() + 30); choca = false; } if (!presionaEnter) { g.drawImage(fondo, 0, 0, 1024, 640, this); g.setColor(Color.white); g.drawImage(title, 260, 120, this); g.setFont(new Font("defalut", Font.BOLD, 16)); //g.drawString("Presiona ENTER para iniciar el juego",370 ,600 ); g.drawImage(enter, 325, 580, this); } if(presionaF){ g.drawString("Puntaje:", getWidth() / 4 + getWidth() / 8, 200); BufferedReader fileIn; try { fileIn = new BufferedReader(new FileReader("puntaje.txt")); String dato = fileIn.readLine(); setArr(dato.split(",")); for(int x=0; x<arr.length;x=x+2){ g.drawString(arr[x]+ " : "+ arr[x+1], getWidth() / 4 + getWidth() / 8, 220+ (20*x)); } fileIn.close(); // actualiza(); } catch (IOException ioe) { System.out.println("Se arrojo una excepcion " + ioe.toString()); } } if (presionaI) { g.drawString("Instrucciones:", getWidth() / 4 + getWidth() / 8, 200); g.drawString("Presiona la barra espaciadora para elevar el", getWidth() / 4 + getWidth() / 8, 220); g.drawString("pajaro y esqiva los obstaculos que se mueven.", getWidth() / 4 + getWidth() / 8, 240); g.drawString("Teclas: ", getWidth() / 4 + getWidth() / 8, 300); /* g.drawString("Flecha izquierda - se mueve a la izquierda", getWidth() / 4 + getWidth() / 8, 320); g.drawString("Flecha derecha - se mueve a la derecha", getWidth() / 4 + getWidth() / 8, 340); */ g.drawString("I - muestra/oculta instrucciones", getWidth() / 4 + getWidth() / 8, 320); /* g.drawString("G - guarda el juego", getWidth() / 4 + getWidth() / 8, 380); g.drawString("C - carga el juego", getWidth() / 4 + getWidth() / 8, 400); */ g.drawString("P - pausa el juego", getWidth() / 4 + getWidth() / 8, 340); g.drawString("S - activa/desactiva el sonido del juego", getWidth() / 4 + getWidth() / 8, 360); g.drawString("F - muestra el nombre y los scores guardados", getWidth() / 4 + getWidth() / 8, 380); g.drawString("SPACE - eleva el pajaro", getWidth() / 4 + getWidth() / 8, 400); } } else { //Da un mensaje mientras se carga el dibujo g.drawString("No se cargo la imagen..", 20, 20); } } else { g.drawImage(fondo, 0,0, 1024, 640, this); g.setFont(new Font("Helvetica", Font.BOLD, 40)); g.drawImage(gameover, 350, 120, this); g.drawImage(won,390, 370, this); g.setColor(Color.white); g.drawString("" + score, 620, 410); g.drawImage(restart, 120, 550, this); } }
9
public static void main(String[] args) { boolean l = false; //left right disabled by default. If enabled, even => right handed | odd => left handed int numPhilosophers = 4; // also the number of forks int numCycles = 10; //num think/eat cycles long thinkTime = 0; // milliseconds long eatTime = 0; // milliseconds if (args.length == 5) { if (args[0] == "-l") { l = true; } numPhilosophers = Integer.valueOf(args[1]); numCycles = Integer.valueOf(args[2]); thinkTime = Integer.valueOf(args[3]); eatTime = Integer.valueOf(args[4]); } else if (args.length == 4) { numPhilosophers = Integer.valueOf(args[0]); numCycles = Integer.valueOf(args[1]); thinkTime = Integer.valueOf(args[2]); eatTime = Integer.valueOf(args[3]); } else { System.out.println("Invalid command line args. Expected numPhilosophers, numCycles, thinkTime, eatTime. Resorting to default values."); } ArrayList<IFork> forks = new ArrayList<IFork>(); ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>(); for (int i = 0; i < numPhilosophers; i++) { forks.add(new Fork()); } for (int i = 0; i < numPhilosophers; i++) { philosophers.add(new Philosopher(i, forks.get(i), forks.get((numPhilosophers + i - 1) % numPhilosophers), (l ? (i % 2 == 0 ? true : false) : true), numCycles, thinkTime, eatTime)); philosophers.get(i).start(); } }
7
private double getExchangeRateFromDB(Currency toCurrency, Currency fromCurrency, Connection connection, Date date) { try { String query = "select cambio from historico_cambios " + "where divisa_desde='" + fromCurrency.getCode() + "' and divisa_a='" + toCurrency.getCode() + "'"; ResultSet resulSet; resulSet = connection.createStatement().executeQuery(query); while (resulSet.next()) return resulSet.getDouble(1); } catch (SQLException ex){ ex.getMessage(); } return 0; }
2
public Rectangular(int length, int width) { this.length = length; this.width = width; }
0
public boolean deleteElementField(ElementField element) { if (element instanceof Ball) { return _balls.remove((Ball) element); } else if (element instanceof DestructibleBrick) { return _dBricks.remove((DestructibleBrick) element); } else if (element instanceof BoundaryField) { return _bondarysField.remove((BoundaryField) element); } else if (element instanceof Swarm) { return _swarms.remove((Swarm) element); } else if (element instanceof IndestructibleBrick) { return _iBricks.remove((IndestructibleBrick) element); } else if (element instanceof Racket) { _racket = null; return true; } return false; }
6
private void initSearch() { for (Map.Entry<String, String> entry: conditions.entrySet()) { ArrayList<Long> conditionIds = generateIdsForCondition(entry.getKey(), entry.getValue()); intersect(conditionIds); } }
1
void rehash() { int oldCapacity = table.length; Entry oldMap[] = table; int i; for (i = oldCapacity; --i >= 0;) { Entry e, next, prev; for (prev = null, e = oldMap[i]; e != null; e = next) { next = e.next; Object obj = e.ref.get(); if ((obj == null || db.isDeleted(obj)) && e.dirty == 0) { count -= 1; e.clear(); if (prev == null) { oldMap[i] = next; } else { prev.next = next; } } else { prev = e; } } } if (count <= (threshold >>> 1)) { return; } int newCapacity = oldCapacity * 2 + 1; Entry newMap[] = new Entry[newCapacity]; threshold = (int)(newCapacity * loadFactor); table = newMap; for (i = oldCapacity; --i >= 0 ;) { for (Entry old = oldMap[i]; old != null; ) { Entry e = old; old = old.next; int index = (e.oid & 0x7FFFFFFF) % newCapacity; e.next = newMap[index]; newMap[index] = e; } } }
9
public Object[][] readExcel(String fileName, String sheetNumber) throws IOException { Object[][] data = null; FileInputStream file = new FileInputStream(new File(fileName)); HSSFWorkbook workbook = new HSSFWorkbook(file); HSSFSheet sheet = workbook.getSheet(sheetNumber); HSSFRow row = sheet.getRow(0); int numberOfRows = sheet.getLastRowNum(); int numberOfColumns = row.getLastCellNum(); data = new Object[numberOfRows][numberOfColumns]; for (int rowNum = 1; rowNum < numberOfRows + 1; rowNum++) { for (int cellNum = 0; cellNum < numberOfColumns; cellNum++) { Cell cell = sheet.getRow(rowNum).getCell(cellNum); if (cell.getCellType() == Cell.CELL_TYPE_BLANK) { data[rowNum - 1][cellNum] = " "; } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { data[rowNum - 1][cellNum] = cell.getNumericCellValue(); } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) { data[rowNum - 1][cellNum] = cell.getStringCellValue(); } } } file.close(); return data; }
5
public Rectangle( int h, int w, int t, int l) { height = h; width = w; top = t; left = l; }
0
public File getImage() { return image; }
0
public final int getPort() { return _port; }
0
@Override public ArrayList<Excel> getColoredExes() { return coloredEx; }
0
public static Set<String> getDomainSet() { return config.keySet(); }
0
public Value newValue(final Type type) { if (type == null) { return BasicValue.UNINITIALIZED_VALUE; } boolean isArray = type.getSort() == Type.ARRAY; if (isArray) { switch (type.getElementType().getSort()) { case Type.BOOLEAN: case Type.CHAR: case Type.BYTE: case Type.SHORT: return new BasicValue(type); } } Value v = super.newValue(type); if (v == BasicValue.REFERENCE_VALUE) { if (isArray) { v = newValue(type.getElementType()); String desc = ((BasicValue) v).getType().getDescriptor(); for (int i = 0; i < type.getDimensions(); ++i) { desc = '[' + desc; } v = new BasicValue(Type.getType(desc)); } else { v = new BasicValue(type); } } return v; }
9
public static boolean isdni(String dni){ boolean aux=false; if(dni.length()!=9){//tiene que tener 9 caracteres aux=false; }else if((dni.charAt(dni.length()-1))>90 ||(dni.charAt(dni.length()-1))<65){//mirar si el ultimo es letra aux=false; }else{//mirar que los 8 primeros sean numeros int i=0; do{ i++; }while(dni.charAt(i)>47 && dni.charAt(i)<58); if(i!=8){ aux=false; }else{ aux=true; } } return aux; }
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(administrateur_Ajout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(administrateur_Ajout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(administrateur_Ajout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(administrateur_Ajout.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 administrateur_Ajout().setVisible(true); } }); }
6
public WordReader(String dictPath) { super(); loadDict(dictPath); }
0
private Faction buildFactionFromXML(StringBuffer buf, String factionID) { final Faction F=(Faction)CMClass.getCommon("DefaultFaction"); F.initializeFaction(buf,factionID); for(final Enumeration<FRange> e=F.ranges();e.hasMoreElements();) { final Faction.FRange FR=e.nextElement(); final String CodeName=(FR.codeName().length()>0)?FR.codeName().toUpperCase():FR.name().toUpperCase(); if(!hashedFactionRanges.containsKey(CodeName)) hashedFactionRanges.put(CodeName,FR); final String SimpleUniqueCodeName = F.name().toUpperCase()+"."+FR.name().toUpperCase(); if(!hashedFactionRanges.containsKey(SimpleUniqueCodeName)) hashedFactionRanges.put(SimpleUniqueCodeName,FR); final String UniqueCodeName = SimpleUniqueCodeName.replace(' ','_'); if(!hashedFactionRanges.containsKey(UniqueCodeName)) hashedFactionRanges.put(UniqueCodeName,FR); final String SimpleUniqueIDName = F.factionID().toUpperCase()+"."+FR.name().toUpperCase(); if(!hashedFactionRanges.containsKey(SimpleUniqueIDName)) hashedFactionRanges.put(SimpleUniqueIDName,FR); } return addFaction(F) ? F : null; }
7
public static ArrayList<ItemSet<String>> readFile(String filename) throws IOException { BufferedReader reader=new BufferedReader(new FileReader(new File(filename))); ArrayList<String> attributeNames=new ArrayList<String>(); ArrayList<ItemSet<String>> itemSets=new ArrayList<ItemSet<String>>(); String line=reader.readLine(); line=reader.readLine(); while(line!=null) { if (line.contains("#") || line.length()<2) { line=reader.readLine(); continue; } if(line.contains("attribute")) { int startIndex=line.indexOf("'"); if(startIndex>0) { int endIndex=line.indexOf("'", startIndex+1); attributeNames.add(line.substring(startIndex+1,endIndex )); } } else { ItemSet<String> is=new ItemSet<String>(); StringTokenizer tokenizer=new StringTokenizer(line,","); int attributeCounter=0; String itemSet=""; while(tokenizer.hasMoreTokens()) { String token=tokenizer.nextToken().trim(); if(token.equalsIgnoreCase("t")) { String attribute=attributeNames.get(attributeCounter); itemSet+=attribute+","; is.addItem(attribute); } attributeCounter++; } itemSets.add(is); } line=reader.readLine(); } reader.close(); return itemSets; }
7
@Override public Element generateDataElement(LauncherAction action) { JavaAppDesc desc = (JavaAppDesc)action.getLaunchDesc(); org.w3c.dom.Element e = createInitialElement(desc); //check to see if we used an AppDescURL if(desc.getAppDescURL() != null) { e.setAttribute("app-desc-href", desc.getAppDescURL().toString()); return e; } //Main Class e.setAttribute("main-class", desc.getMainClass()); //Arguments String[] args = desc.getMainArgs(); StringBuffer argLine = new StringBuffer(); if(args != null) { for(int i=0;i<args.length;i++) { argLine.append(args[i] + " "); } } e.setAttribute("args", argLine.toString().trim()); //Permissions if(desc.getPermissions() != null) { e.setAttribute("permissions", "all-permissions"); } else { e.setAttribute("permissions", "restricted-permissions"); } //Use WebStart if(desc.useWebStart()) { e.setAttribute("use-webstart", "true"); } else { e.setAttribute("use-webstart", "false"); } //Use Separate VM if(desc.useSeperateVM()) { e.setAttribute("separate-vm", "true"); } else { e.setAttribute("separate-vm", "false"); } //Shared ClassLoader if(desc.useSharedClassLoader()) { e.setAttribute("shared-classloader", "true"); } else { e.setAttribute("shared-classloader", "false"); } //Java Archives org.w3c.dom.Element resources = e.getOwnerDocument().createElement("resources"); e.appendChild(resources); Iterator it = desc.getJavaArchives().iterator(); while(it.hasNext()) { URL javaResource = (URL)it.next(); org.w3c.dom.Element jarElement = e.getOwnerDocument().createElement("jar"); jarElement.setAttribute("href", javaResource.toString()); resources.appendChild(jarElement); } //Native Archives it = desc.getNativeArchives().iterator(); while(it.hasNext()) { NativeLibDesc nativeLib = (NativeLibDesc)it.next(); org.w3c.dom.Element nativeElement = e.getOwnerDocument().createElement("nativelib"); nativeElement.setAttribute("href", nativeLib.getPath().toString()); nativeElement.setAttribute("os", nativeLib.getOS()); resources.appendChild(nativeElement); } return e; }
9
public Image loadImage (String file) // this method reads and loads the image { try { InputStream m = this.getClass().getResourceAsStream(file); return (ImageIO.read (m)); } catch (IOException e) { System.out.println ("Error: File " + file + " not found."); return null; } }
1
private boolean open() { boolean result = false; if (!isValid()) { try { Class.forName("com.mysql.jdbc.Driver"); this.connection = DriverManager.getConnection(this.url, this.user, this.password); if (isValid()) if (isDBExisted() || createDB()) if (isTableExisted() || createTable()) result = true; else System.err.println("Table failed."); else System.err.println("Database failed."); else System.err.println("Connection Failed."); } catch (Exception e) { System.err.println(e.toString()); } } return result; }
7
public ControlPanel(ConfigurationController controller) { this.controller = controller; initView(); }
0
@Override public Usuario ListById(int id_usuario) { Connection conn = null; PreparedStatement pstm = null; ResultSet rs = null; Usuario u = new Usuario(); try{ conn = ConnectionFactory.getConnection(); pstm = conn.prepareStatement(LISTBYID); pstm.setInt(1, id_usuario); rs = pstm.executeQuery(); while (rs.next()){ u.setId_usuario(rs.getInt("id_usuario")); u.setNome_us(rs.getString("nome_us")); u.setUsuario_us(rs.getString("usuario_us")); u.setSenha_us(rs.getString("senha_us")); u.setNivelAcesso_us(rs.getString("nivelAcesso_us")); } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao listar por código " + e); }finally{ try{ ConnectionFactory.closeConnection(conn, pstm, rs); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao desconctar com o banco " + e); } } return u; }
3
public static Test suite() { return new TestSuite(AppTest.class); }
0
void processFile(File file){ if(file.exists() == false){ return ; } if(file.isDirectory()){ for(String path : file.list()){ processFile(new File(path)); } } else{ try { FileInputStream fis = new FileInputStream(file); FileChannel channel = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1000000); channel.read(buffer); buffer.flip(); String encoding = System.getProperty("file.encoding"); CharBuffer res = Charset.forName(encoding).decode(buffer); String content = res.toString(); String[] lines = content.split("\\n"); for(String line : lines) { if(this.pat.matcher(line).find()) System.out.println(line); } /* while(buffer.hasRemaining()) System.out.print((char)buffer.get()); */ // } catch (FileNotFoundException e) { // e.printStackTrack(); } catch (IOException e) { e.printStackTrace(); } } }
6
public List<IceCream> produceAllKnownIceCream(){ List<IceCream> list = new ArrayList<IceCream>(); for(Class<? extends IceCream> ice: getAllIceCreamTypes()){ for(Taste taste: getSomeTaste()){ //IceCream ice = new IceCream(taste, type); try { list.add(ice.getDeclaredConstructor(Taste.class).newInstance(taste)); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return list; }
9
@Override public boolean equals(Object o) { if (this.getClass() != o.getClass()){ return false; } PlayedNoteToken oPlayed = (PlayedNoteToken) o; if (this.getType().equals(oPlayed.getType()) && this.getNumerator().equals(oPlayed.getNumerator()) && this.getDenominator().equals(oPlayed.getDenominator()) && this.getBaseNote().equals(oPlayed.getBaseNote()) && this.getAccidental().equals(oPlayed.getAccidental()) && this.hasAccidental().equals(oPlayed.hasAccidental()) && this.getOctave().equals(oPlayed.getOctave()) ) { return true; } return false; }
8
@Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("Start the Match Scouting Server")) { //Check for Valid Data if(wG.validData()) { //Start the MainGUI wG.pullThePlug(); JPanel p = new JPanel(null); MainGUI mG = new MainGUI(p); mG.setVisible(true); //Start the Bluetooth Connection Thread connThreadMatch = new Thread(new ConnectionListener(mG)); connThreadMatch.start(); } else { //Show Error Screen JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame,"Please Enter a Valid Number as a Team Number","Team Number Error",JOptionPane.ERROR_MESSAGE); } } else if(e.getActionCommand().equals("Start the Saved Match Upload Server")) { //Check for Valid Data if(wG.validData()) { //Start Match Upload GUI wG.pullThePlug(); JPanel p = new JPanel(null); MainUploadGUI mG = new MainUploadGUI(p); mG.setVisible(true); //Start Match Upload Connection Thread connThreadSMatch = new Thread(new ConnectionListenerSavedMatch(mG)); connThreadSMatch.start(); } else { //Show Error Screen JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame,"Please Enter a Valid Number as a Team Number","Team Number Error",JOptionPane.ERROR_MESSAGE); } } else if(e.getActionCommand().equals("Start the Saved Pit Upload Server")) { //Check for Valid Data if(wG.validData()) { //Start Match Upload GUI wG.pullThePlug(); JPanel p = new JPanel(null); MainPitUploadGUI mG = new MainPitUploadGUI(p); mG.setVisible(true); //Start Match Upload Connection Thread connThreadSPit = new Thread(new ConnectionListenerSavedPit(mG)); connThreadSPit.start(); } else { //Show Error Screen JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame,"Please Enter a Valid Number as a Team Number","Team Number Error",JOptionPane.ERROR_MESSAGE); } } }
6
public static void main(String[] args) { JFrame frame = new JFrame("Realms of Caelum"); Canvas canvas = new Canvas(); Dimension size = new Dimension(1280, 720); //TODO add size to settings later canvas.setMinimumSize(size); canvas.setMaximumSize(size); canvas.setPreferredSize(size); canvas.setSize(size); frame.add(canvas); frame.setVisible(true); frame.pack(); frame.setResizable(false); game = new RoC(canvas, "realmsofcaelum/res/"); frame.addWindowListener(game); canvas.requestFocus(); if (!game.startGame()) { System.exit(0); } else { RoC.log("Game did not exit cleanly!"); System.exit(1); } }
1
void Statement() { printer.startProduction("Statement"); if (la.kind == 8) { Get(); this.generator.startIf(); Expect(9); this.enterParenthesis(BOOLEAN); Expr(); Expect(10); if (this.currentType != BOOLEAN) { // ERROR, non-boolean expression in conditional printer.print("Error in if-statement: " + this.currentType); this.SemErr("incorrect if-declaration"); } else { printer.print("if ok"); } this.exitParenthesis(); this.resetContext(); Expect(11); this.generator.startThen(); printer.print("then"); Statement(); Expect(12); this.generator.startElse(); printer.print("else"); // @SLX: log current line of SLX program and make a conditional jump to here Statement(); Expect(13); this.generator.startFi(); printer.print("fi"); expected = UNDEFINED; printer.endProduction("Statement"); } else if (la.kind == 14) { Get(); printer.print("while"); stack.push(BOOLEAN); this.generator.startWhile(); Expect(9); this.enterParenthesis(BOOLEAN); Expr(); Expect(10); if (stack.peek() != BOOLEAN) { // ERROR, non-boolean expression this.SemErr("incorrect while-declaration"); } else { printer.print("while ok"); } this.generator.endWhileConditional(); this.exitParenthesis(); this.resetContext(); Statement(); printer.endProduction("Statement"); this.generator.endWhileBody(); } else if (la.kind == 15) { Get(); printer.print("print"); Expect(9); Expr(); Expect(10); this.generator.commandPrint(); Expect(6); printer.endProduction("Statement"); } else if (la.kind == 4) { Get(); StatementList(); Expect(5); printer.endProduction("Statement"); } else if (la.kind == 1) { IdAccess(); Expect(16); this.currentContext.previousOp = CodeGenerator.ops.ASG; this.enterParenthesis(this.currentType); Expr(); if (this.lastType == this.expected) { this.generator.commandAssignment(); } Expect(6); this.exitParenthesis(); this.resetContext(); printer.endProduction("Statement"); } else SynErr(33); }
8
private void btOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btOkActionPerformed String nome = txPesqNome.getText(); ConsultaController pc = new ConsultaController(); modelo.setNumRows(0); for (Consulta p : pc.listByNome(nome)) { String data = ""; String hora = ""; String linome = ""; try { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); hora = sdf.format(p.getHorario()); } catch (Exception ex) { System.out.println("Entrou na excessão Hora: " + ex.getMessage()); hora = ""; } try { SimpleDateFormat sdfd = new SimpleDateFormat("dd/MM/yyyy"); data = sdfd.format(p.getDataDaConsulta().getTime()); } catch (Exception e) { System.out.println("entrou na excessão data nula: " + e.getMessage()); data = ""; } try { linome = p.getPaciente().getNome(); } catch (Exception e) { System.out.println("entrou na excessão data nula: " + e.getMessage()); } if(!linome.equals(" ")){ System.out.println("Nome:"+linome+":"); modelo.addRow(new Object[]{p.getCodigo(), hora, data, linome, p.getTipoConsulta()}); } } }//GEN-LAST:event_btOkActionPerformed
5
public void handle(Input input, Robot robot) { // jumpForce applique pour faire sauter le personnage float jumpForce = 50000; if (robot.auSol()) { if ((input.isKeyPressed(get_key()) && robot.getEnergie() > 0 && !robot .getPlusEnergie()) || (input.isKeyPressed(get_key()))) { if (robot.getDirectionDroite()) { robot.applyForce(0, -jumpForce); } else { robot.applyForce(0, -jumpForce); } } } // si on n'appuye pas sur la touche saut et que le perso est en train de // sauter, on le fait redescendre doucement if (!input.isKeyDown(get_key())) { if (robot.getSaut()) { robot.setVelocity(robot.getVelX(), robot.getVelY() * 0.99f); } } }
8
private String getSelectedText(){ String text = ""; if(activField.equals("textArea")) text = textArea.getSelectedText(); if(activField.equals("fieldNameFile")) text = fieldNameFile.getSelectedText(); if(activField.equals("fieldCommandLine")) text = fieldCommandLine.getSelectedText(); return text; }
3
public static void addJarsInDir(String dirPath) { File dir = new File(dirPath); if (!dir.exists()) { return; } File[] files = dir.listFiles(); if (files == null) { return; } for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { continue; } else { addClasspath(files[i].getAbsolutePath()); } } }
4
public static BufferedImage readImage(String remoteurl) { BufferedImage image = null; boolean flag = false; long startTime = System.currentTimeMillis(); do { try { URLConnection connection = getURLConnection(remoteurl); image = ImageIO.read(connection.getInputStream()); if (flag) System.out.println("it takes about " + (System.currentTimeMillis() - startTime) / 1000 + " seconds to download " + remoteurl); } catch (MalformedURLException e) { System.out.println(e.getMessage()); flag = true; pause(); } catch (IOException e) { System.out.println(e.getMessage()); flag = true; pause(); } } while (image == null); return image; }
4
public void printGraph(Writer w) throws Exception { for(Entry<Value, HashSet<Value>> v : adjacencyList.entrySet()) { Value node = v.getKey(); HashSet<Value> edges = v.getValue(); // first write the node so that nodes that have no edges // connecting them will be drawn. w.write("\""); node.printAsArg(w); w.write("\";\n"); for(Value endpoint : edges) { w.write("\""); node.printAsArg(w); w.write("\" -- \""); endpoint.printAsArg(w); w.write("\";\n"); } } }
2
public boolean esPotAfegir(CjtRestAssignatura cjtResAssig,CjtRestGrupSessio cjtResGS) { ArrayList<Restriccio> llista = new ArrayList(); llista = cjtResAssig.getCjtRes(); int size = llista.size(); for(int i = 0; i < size; ++i){ Restriccio res = llista.get(i); RestAssignatura resdw = (RestAssignatura) res; if(resdw.getAssignatura().equals(this.assignatura) && resdw.getGrup () == this.grup && resdw.getDia().equals(this.dia) && resdw.getHora() == this.hora) return false; } llista = cjtResGS.getCjtRes(); size = llista.size(); for(int i = 0; i < size; ++i){ Restriccio res = llista.get(i); RestGrupSessio resdw = (RestGrupSessio) res; if( (resdw.getAssignatura().equals(this.assignatura.getNom())) && (resdw.getGrup() == this.grup) && (resdw.getHora() == this.hora) ) return false; } return true; }
9
public void run() { ServerMessage m; try { m = (ServerMessage) input.readObject(); String message = m.getCommand(); if(message.equals("JOIN")) { //Add to the list of users this.dataAccess.join(m.getUser()); System.out.println("got join request"); }else if(message.equals("LEAVE")) { //Remove from list of users this.dataAccess.leave(m.getUser()); System.out.println("got leave request"); }else if(message.equals("LIST")) { //Returns a list of online users System.out.println("Got list request"); ArrayList<UserBean> toSend = this.dataAccess.list(); output.writeObject(toSend); }else if(message.equals("TEST")) { //Responds to connection tests when a client starts System.out.println("Got connection test msg"); output.writeObject("ACTIVE"); } socket.close(); } catch (ClassNotFoundException e1) { e1.printStackTrace(); System.out.println("Class not found exception"); } catch (IOException e1) { e1.printStackTrace(); }catch (InterruptedException e) { e.printStackTrace(); } }
7
public static String encodeFromFile(String filename) throws java.io.IOException { String encodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File(filename); byte[] buffer = new byte[Math.max((int) (file.length() * 1.4 + 1), 40)]; // Need max() for math on small files (v2.2.1); Need // +1 for a few corner cases (v2.3.5) int length = 0; int numBytes = 0; // Open a stream bis = new Base64.InputStream(new java.io.BufferedInputStream( new java.io.FileInputStream(file)), Base64.ENCODE); // Read until done while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } // end while // Save in a variable to return encodedData = new String(buffer, 0, length, Base64.PREFERRED_ENCODING); } // end try catch (java.io.IOException e) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try { bis.close(); } catch (Exception e) { } } // end finally return encodedData; } // end encodeFromFile
3
public boolean floorAdjacent(int x, int y) { //this doesn't check diagonals cause it would look ugly if (getTile(x + 1, y).isPassable()) { return true; } if (getTile(x - 1, y).isPassable()) { return true; } if (getTile(x, y + 1).isPassable()) { return true; } if (getTile(x, y - 1).isPassable()) { return true; } return false; }
4
public boolean getSeenFossil() { return this.seenFossil; }
0
public void fusionWithAdd(CPLayer fusion, CPRect rc) { CPRect rect = new CPRect(0, 0, width, height); rect.clip(rc); for (int j = rect.top; j < rect.bottom; j++) { int off = rect.left + j * width; for (int i = rect.left; i < rect.right; i++, off++) { int color1 = data[off]; int alpha = (color1 >>> 24) * this.alpha / 100; if (alpha == 0) { continue; } else { int color2 = fusion.data[off]; int r = Math.min(255, (color2 >>> 16 & 0xff) + alpha * (color1 >>> 16 & 0xff) / 255); int g = Math.min(255, (color2 >>> 8 & 0xff) + alpha * (color1 >>> 8 & 0xff) / 255); int b = Math.min(255, (color2 & 0xff) + alpha * (color1 & 0xff) / 255); fusion.data[off] = 0xff000000 | r << 16 | g << 8 | b; } } } }
3
private void addCharacter(char c) { switch(style) { case PLAIN_TEXT: text = text + c; break; case INTEGERS: try { Integer.parseInt(text + c); text = text + c; } catch (NumberFormatException e) {} break; default: break; } }
3
private void buildAntTask(String AntDirectory, ArrayList<TDeployLine> DeployLines, Integer orgindex) { TStringList packagexml = new TStringList(); packagexml.add("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); packagexml.add("<Package xmlns=\"http://soap.sforce.com/2006/04/metadata\">"); TStringList classesxml = new TStringList(); classesxml.AllowDuplicates = false; classesxml.Sorted = true; TStringList componentsxml = new TStringList(); componentsxml.AllowDuplicates = false; componentsxml.Sorted = true; TStringList pagesxml = new TStringList(); pagesxml.AllowDuplicates = false; pagesxml.Sorted = true; TStringList staticresourcesxml = new TStringList(); staticresourcesxml.AllowDuplicates = false; staticresourcesxml.Sorted = true; TStringList triggersxml = new TStringList(); triggersxml.AllowDuplicates = false; triggersxml.Sorted = true; Integer DeployResourcesCount = 0; for (Integer i = 0; i < DeployLines.size(); i++) { TDeployLine deployLine = DeployLines.get(i); TDeployItem deployItem = deployLine.DeployItems.get(orgindex); if (deployItem.getIsIncludedToDeploy()) { String res1 = deployLine.ResourcePath; String res2 = deployLine.getMetaXmlPath(); copyResource(res1, DeployOrganizations.get(orgindex).Directory); if (res2 != null) { copyResource(res2, DeployOrganizations.get(orgindex).Directory); } String resname = res1.substring(res1.indexOf(FILE_SEPARATOR)+1, res1.indexOf(".")); if (res1.indexOf("classes"+FILE_SEPARATOR) != -1) { classesxml.add(resname); } if (res1.indexOf("components"+FILE_SEPARATOR) != -1) { componentsxml.add(resname); } if (res1.indexOf("pages"+FILE_SEPARATOR) != -1) { pagesxml.add(resname); } if (res1.indexOf("staticresources"+FILE_SEPARATOR) != -1) { staticresourcesxml.add(resname); } if (res1.indexOf("triggers"+FILE_SEPARATOR) != -1) { triggersxml.add(resname); } DeployResourcesCount++; } } addTypes(packagexml, classesxml, "ApexClass"); addTypes(packagexml, componentsxml, "ApexComponent"); addTypes(packagexml, pagesxml, "ApexPage"); addTypes(packagexml, staticresourcesxml, "StaticResource"); addTypes(packagexml, triggersxml, "ApexTrigger"); DeployOrganizations.get(orgindex).DeployResourcesCount = DeployResourcesCount; packagexml.add(" <version>31.0</version>"); packagexml.add("</Package>"); packagexml.SaveToFile(AntDirectory + FILE_SEPARATOR + "package.xml"); }
8
Destination getDefaultDestination() { final Unit carrier = getUnit(); PathNode path = null; // If in Europe, stay in Europe if (carrier.getLocation() instanceof Europe) { return new Destination(); } // Otherwise should be on the map if (carrier.getTile() == null) { throw new IllegalStateException("Unit not on the map: " + carrier.getId()); } // Already at a settlement if (carrier.getSettlement() != null) { return new Destination(); } // Try nearest colony if ((path = carrier.findOurNearestOtherSettlement()) != null) { return new Destination(false, path); } // Try Europe if (carrier.isNaval() && carrier.getOwner().canMoveToEurope()) { if (carrier.canMoveToHighSeas()) { return new Destination(true, null); } if ((path = findPathToEurope(carrier)) != null) { return new Destination(true, path); } } // Can fail intermittantly. For example: up river and blocked in. logger.warning(tag + " could not get default destination: " + carrier); return null; }
8
public void paint(Graphics g) { if (bounds != null) { if (connectIcon != null) { g.drawImage(connectIcon.getImage(), bounds.x, bounds.y, bounds.width, bounds.height, null); } else if (handleEnabled) { g.setColor(Color.BLACK); g.draw3DRect(bounds.x, bounds.y, bounds.width - 1, bounds.height - 1, true); g.setColor(Color.GREEN); g.fill3DRect(bounds.x + 1, bounds.y + 1, bounds.width - 2, bounds.height - 2, true); g.setColor(Color.BLUE); g.drawRect(bounds.x + bounds.width / 2 - 1, bounds.y + bounds.height / 2 - 1, 1, 1); } } }
3
@Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_W: System.out.println("Move up!"); break; case KeyEvent.VK_S: currentSprite = characterDown; if (robot.isJumped() == false) { robot.setDucked(true); robot.setSpeedX(0); } break; case KeyEvent.VK_A: robot.moveLeft(); robot.setMovingLeft(true); break; case KeyEvent.VK_D: robot.moveRight(); robot.setMovingRight(true); break; case KeyEvent.VK_SPACE: robot.jump(); break; case KeyEvent.VK_CONTROL: // remove isjumped if (robot.isDucked() == false && robot.isJumped() == false) { robot.shoot(); robot.setReadyToFire(false); } break; } }
9
public Graphics2D clearOffscreenAndReturn() { Dimension d = getSize(); Graphics offG = getOffScreenGraphics(); offG.setColor(getBackground()); offG.fillRect(0, 0, d.width, d.height); return (Graphics2D)offG; }
0
protected final void setCurrentFailure(Failure currentFailure) { this.currentFailure.set(currentFailure); }
0
@Override public Color colorReprisentation(int value) { // if(colorMap.containsKey(value)){ // return colorMap.get(value); // } if(value == 6){ return Color.red; } if(value == 5){ return Color.yellow; } if (isTileTypeSolid(value)) { return Color.black; } return Color.white; }
3
@RequestMapping(value = {"/posts"}, method = RequestMethod.GET) public String posts(Model model, @RequestParam(required = false) String isPostCreated, @RequestParam(required = false) String isPostUpdated, @RequestParam(required = false) String isError) { UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User currentUser = this.userService.getUserByName(userDetails.getUsername()); List<Post> posts; if (currentUser.getRole().getId() == 1) { //ROLE_ADMIN posts = this.postService.getAllPosts(); } else { //ROLE_MODERATOR posts = this.userService.getAllUserPosts(currentUser); } model.addAttribute("posts", posts); model.addAttribute("title", "Admin | Helix"); if (posts.size() == 0) { model.addAttribute("isEmpty", true); } else { model.addAttribute("isEmpty", false); } if (isPostCreated != null && isPostCreated.equals("yes")) { model.addAttribute("isPostCreated", true); } else { model.addAttribute("isPostCreated", false); } if (isPostUpdated != null && isPostUpdated.equals("yes")) { model.addAttribute("isPostUpdated", true); } else { model.addAttribute("isPostUpdated", false); } if (isError != null && isError.equals("yes")) { model.addAttribute("isError", true); } else { model.addAttribute("isError", false); } return "admin/posts"; }
8
public static void uploadJMX() { Thread jmxUploader = new Thread(new JMXUploader()); jmxUploader.start(); try { jmxUploader.join(); } catch (InterruptedException ie) { BmLog.debug("JMX Uploader was interrupted"); } }
1
public int numberOfStudents(String name) { try{ openDatabase(); }catch(Exception e){} String query = "SELECT COUNT(*) FROM t8005t2 .takes WHERE ID IN (SELECT ID FROM t8005t2 .modules WHERE name= '" + name + "')"; int count = 0; try { stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { count = rs.getInt("COUNT(*)"); } } catch (Exception e) { System.err.println("Problem executing numberOfStudents query"); System.err.println(e.getMessage()); } try{ closeDatabase(); }catch(Exception e){} return count; }
4
public int getProperty(Ability.Property property) { if (properties.containsKey(property)) { return properties.get(property); } else { return property.getDefaultValue(); } }
1
public void run() { while (true) { // Bob needs his rest. try { Thread.sleep(sleepTime); } catch (Exception e) { e.printStackTrace(); } // Bob needs info on his paddle. int paddlePosition = paddle.getPosition()[0]; int mySize = Paddle.getSize()[0]; // Bob needs info on the ball's location. int[] ballPosition = ball.getPosition(); if (ballPosition[0]> paddlePosition + (mySize * 0.75)) { paddle.moveRight(); } if (ballPosition[0]< paddlePosition + (mySize * 0.25)) { paddle.moveLeft(); } q.offer(new Position(paddle.getPosition())); } }
4
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final OutputSpEmployeeTargetPK other = (OutputSpEmployeeTargetPK) obj; if (!Objects.equals(this.szMonth, other.szMonth)) { return false; } if (!Objects.equals(this.szYear, other.szYear)) { return false; } return true; }
4
public QueueSysResult calculate(int m) { double p0 = 0.0; double rho = lambda / mu; double[] rho_pow = new double[N + 1]; rho_pow[0] = 1.0; for (int i = 1; i < rho_pow.length; ++i) { rho_pow[i] = rho_pow[i - 1] * rho; } double[] m_pow = new double[N + 1 - m]; m_pow[0] = 1.0; for (int i = 1; i < m_pow.length; ++i) { m_pow[i] = m_pow[i - 1] * m; } double[] sum_components = new double[N + 1]; for (int i = 0; i <= m; ++i) { sum_components[i] = rho_pow[i] * factorialsQuotient(new int[] { N }, new int[] { i, N - i }); p0 += sum_components[i]; } for (int i = m + 1; i <= N; ++i) { sum_components[i] = rho_pow[i] / m_pow[i - m] * factorialsQuotient(new int[] { N }, new int[] { N - i, m }); p0 += sum_components[i]; } p0 = 1.0 / p0; double averageSystemCalls = 0.0; for (int i = 0; i < N; ++i) { averageSystemCalls += sum_components[i] * i; } averageSystemCalls *= p0; double averageSystemTime = averageSystemCalls / (lambda * (N - averageSystemCalls)); double averageQueueTime = averageSystemTime - 1 / mu; double averageQueueCalls = 0.0; double averageOccupiedServicePoints = (N - averageSystemCalls) * rho; double value = c1 * m + c2 * averageSystemCalls; QueueSysResult result = new QueueSysResult(value, averageSystemCalls, averageQueueCalls, averageSystemTime, averageQueueTime, averageOccupiedServicePoints); cachedResults.put(m, result); return result; }
5
private Boolean evalBracketClose(CalculatorReader expressionReader) throws BinaryOperatorException, CalculatorException { String el = expressionReader.getSymbol(); if (el.equals(")")) { //System.out.println("--evalBracketClose = " + el); if (0 == expressionStack.bracketStack.size()) { throw new CalculatorException("Open bracket is missing", expressionReader.getPosition()); } expressionReader.incPosition(); int lastOperatorSize = expressionStack.bracketStack.pop(); int operatorSize = expressionStack.operatorStack.size(); if (operatorSize == lastOperatorSize) { return true; } else { evaluateOperatorByCount(operatorSize - lastOperatorSize); return true; } } return false; }
3
public void setPrpValorTotal(Integer prpValorTotal) { this.prpValorTotal = prpValorTotal; }
0
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { pm = Common.getPM(); //getBuses(); try { User googler = Common.getGoogleUser(); if (googler == null) resp.sendRedirect(Common.getGoogleLoginUrl()); else { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); u = LinkedUser.loadOrCreate(pm, Common.getGoogleUser().getUserId()); FoursquareApi api = null; if (u.foursquareAuth() != null) { api = Common.getApi(u.foursquareAuth()); } else { code = req.getParameter("code"); log.info(code); if (code != null) { api = Common.getApi(); try { api.authenticateCode(code); if (api.getOAuthToken() != null) { u = LinkedUser.loadOrCreate(pm, Common.getGoogleUser().getUserId()); u.foursquareAuth = api.getOAuthToken(); getUserID(u.foursquareAuth); u.save(pm); } else api = null; } catch (FoursquareApiException e) { log.warning(e.toString()); api = null; } } } if (api == null || api.getOAuthToken() == null || api.getOAuthToken().length() <= 0) { writeHead(out, "Connect to foursquare"); writeConnectPrompt(out); writeFoot(out, null, null); } else { writeHead(out, "Welcome to " + Common.TARGET_VENUE_NAME); writePage(out, Common.TARGET_VENUE_NAME); writeFoot(out, Common.TARGET_VENUE, Common.createChannelToken(Common.TARGET_VENUE)); } } } finally { pm.close(); } }
8
@Override public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == controls.get(MappableAction.PLAYER1_UP)) { g.firstPlayerShip.setAccelerating(false); } else if (keyCode == controls.get(MappableAction.PLAYER1_LEFT)) { g.firstPlayerShip.setTurningLeft(false); } else if (keyCode == controls.get(MappableAction.PLAYER1_RIGHT)) { g.firstPlayerShip.setTurningRight(false); } else if (keyCode == controls.get(MappableAction.PLAYER1_SHOOT)) { g.firstPlayer.isShooting = false; } else if (keyCode == controls.get(MappableAction.PLAYER2_UP)) { g.secondPlayerShip.setAccelerating(false); } else if (keyCode == controls.get(MappableAction.PLAYER2_LEFT)) { g.secondPlayerShip.setTurningLeft(false); } else if (keyCode == controls.get(MappableAction.PLAYER2_RIGHT)) { g.secondPlayerShip.setTurningRight(false); } else if (keyCode == controls.get(MappableAction.PLAYER2_SHOOT)) { g.secondPlayer.isShooting = false; } else if (keyCode == controls.get(MappableAction.BACK)) { goToMainMenu(); } }
9
public static boolean delID(String c_id) { String sql = "delete from member where id=?"; boolean flag=false; Connection conn = null; PreparedStatement psmt = null; FileOutputStream fos = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://" + Server.DBIP + ":3306/po_tweeter", "POMA", "9353"); psmt = conn.prepareStatement(sql); psmt.setString(1, c_id); int rs = psmt.executeUpdate(); if(rs==1) return flag=true; } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if (psmt != null) { try { psmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } return flag; }
9
public static boolean removeContactNym(String contactID,int index){ boolean status = false; AddressBook addressBook = Helpers.getAddressBook(); if (addressBook == null) { System.out.println("removeContactNym - addressBook returns null"); return false; } for(int i=0;i<addressBook.GetContactCount();i++){ Contact contact = addressBook.GetContact(i); if(contact==null) continue; if(contactID.equals(contact.getContact_id())){ status = contact.RemoveContactNym(index); System.out.println("removeContactNym status contact.RemoveContactNym:" + status); if(status) status = otapi.StoreObject(addressBook, "moneychanger", "gui_contacts.dat"); System.out.println("removeContactNym status addressBook otapi.StoreObject:" + status); break; } } return status; }
5
private List<DBObject> ConstructFinvizObj(List<String> finvizReturn) { LinkedList<DBObject> MongoObjList = new LinkedList<DBObject>(); int headerFlag = 0; String[] headers = new String[]{""}; for (String finvizValues : finvizReturn){ finvizValues = finvizValues.replaceAll("\"",""); if (headerFlag == 0){ //extract headers headers = finvizValues.split(","); headerFlag++; headers[1] = "_id"; }else { BasicDBObject FinvizEntry = new BasicDBObject(); String[] FinvizRec = finvizValues.split(","); int counter = 0; for (String header : headers){ if (counter >= 1){ //ignore finviz table id if(NumericalUtil.isDouble(FinvizRec[counter])){ FinvizEntry.put(header,Double.parseDouble(FinvizRec[counter])); }else{ FinvizEntry.put(header,FinvizRec[counter]); } } counter ++; } MongoObjList.add(new BasicDBObject("$set", FinvizEntry)); } } return MongoObjList; }
5
public static String numberToString(Number number) throws JSONException { if (number == null) { throw new JSONException("Null pointer"); } testValidity(number); // Shave off trailing zeros and decimal point, if possible. String string = number.toString(); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; }
6
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IndexRange that = (IndexRange) o; if (empty != that.empty) return false; if (fromIndex != that.fromIndex) return false; if (toIndex != that.toIndex) return false; return true; }
6
public void viderListeJoueur(){ int indice=list.size(); list.clear(); fireTableRowsDeleted(0,indice-1); //l'�criture dans le fichier PrintWriter out=null; try{ out=new PrintWriter(new FileWriter("Ressources/Data/score.dat")); out.print(""); out.close(); }catch(Exception e){ JOptionPane.showMessageDialog(null,e.getMessage(),"Erreur",JOptionPane.ERROR_MESSAGE); }// }
1
@Override public boolean visitObject(Map<?, ?> map) { print('{'); boolean first = true; for (Map.Entry<?, ?> entry : map.entrySet()) { if (ignoreNull && entry.getValue() == null) { continue; } if (!first) { print(','); } acceptEntry(entry); first = false; } print('}'); return false; }
8
@Override public void run() { try { while(true) { HttpsURLConnection connection = (HttpsURLConnection)url.openConnection(); connection.setHostnameVerifier( DO_NOT_VERIFY ); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, null, new java.security.SecureRandom()); connection.setSSLSocketFactory(context.getSocketFactory()); connection.connect(); connection.setInstanceFollowRedirects(true); InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = reader.readLine(); if( line != null ) processor.update( line ); reader.close(); Thread.sleep( 10 * 60 * 1000 ); } } catch (Exception e) { LOGGER.log( Level.SEVERE, e.toString() ); } finally { for( Handler h : LOGGER.getHandlers() ) h.close(); } }
4
public String selectSingleParameter(String objectName,String parameter) { StringBuilder sb = new StringBuilder(); Object o= list.get(objectName); if(o!=null){ if(o.getName()[0]==parameter){ sb.append("Name- "+o.getObjectName()+" "); if(o.getType()[0].equals("int")) { sb.append(""+o.getNumber()[0]+""); } else if(o.getType()[0].equals("string")) { sb.append(""+o.getCharacters()[0]+""); } else if(o.getType()[0].equals("bool")) { sb.append(""+o.getBooleans()[0]+""); } }else if(o.getName()[1]==parameter) { sb.append("Name- "+o.getObjectName()+" "); if(o.getType()[1]=="int") { sb.append(""+o.getNumber()[1]+""); } else if(o.getType()[1]=="string") { sb.append(""+o.getNumber()[1]+""); } else if(o.getType()[1]=="bool") { sb.append(""+o.getBooleans()[1]+""); } } }else{ sb.append("The object:"+objectName+" dont exist.."); } return sb.toString(); }
9
public void updatePotentialSolutionsBar(final List<String> answers) { final int a = answers.size(); final String[] answersToPrint = new String[5]; for(int i = 0; i < a && i < 5; i++){ final double z = Math.random(); answersToPrint[i] = answers.get((int)(answers.size()*z)); answers.remove((int)(answers.size()*z)); } if(a == 1){ GUI.couldveHadText.setText("You Could've Had: " + answersToPrint[0] ); } else if(a == 2){ GUI.couldveHadText.setText("You Could've Had: " + answersToPrint[0] + ", " + answersToPrint[1] ); } else if(a == 3){ GUI.couldveHadText.setText("You Could've Had: " + answersToPrint[0] + ", " + answersToPrint[1] + ", " + answersToPrint[2] ); } else if(a == 4){ GUI.couldveHadText.setText("You Could've Had: " + answersToPrint[0] + ", " + answersToPrint[1] + ", " + answersToPrint[2] + ", " + answersToPrint[3] ); } else if(a >= 5){ GUI.couldveHadText.setText("You Could've Had: " + answersToPrint[0] + ", " + answersToPrint[1] + ", " + answersToPrint[2] + ", " + answersToPrint[3] + ", " + answersToPrint[4]); } }
7
public ArrayList<WorkloadJob> generateWorkload() { if(jobs == null) { jobs = new ArrayList<WorkloadJob>(); // create a temp array fieldArray = new String[MAX_FIELD]; try { if (fileName.endsWith(".gz")) { readGZIPFile(fileName); } else if (fileName.endsWith(".zip")) { readZipFile(fileName); } else { readFile(fileName); } } catch (FileNotFoundException e) { logger.log(Level.SEVERE, "File not found", e); } catch (IOException e) { logger.log(Level.SEVERE, "Error reading file", e); } } return jobs; }
5
@Override public List<DataRow> select(DataRow parameters) { List<DataRow> wynik = new ArrayList<>(); try { con = DriverManager.getConnection(url, login, password); String stm; String tabelName = parameters.getTableName(); List<DataCell> select = parameters.row; String kolumny = ""; for (DataCell x : select) { kolumny += x.name + " = " + x.value + " AND "; } kolumny = kolumny.substring(0, kolumny.length() - 5); stm = "SELECT * FROM " + tabelName + " WHERE " + kolumny; pst = con.prepareStatement(stm); rs = pst.executeQuery(); while(rs.next()) { DataRow x = new DataRow(); x.setTableName(tabelName); ResultSetMetaData meta = rs.getMetaData(); for(int i=0; i<meta.getColumnCount(); i++) { String attrname = meta.getColumnName(i); String attrvalue = rs.getString(i); x.addAttribute(attrname, attrvalue); if(attrname.equals("name")) { x.setName(attrvalue); } } wynik.add(x); } } catch (Exception ex) { ErrorDialog errorDialog = new ErrorDialog(true, "Błąd operacji w lokalnej bazie danych: \n" + ex.getMessage(), "LocalDatabaseConnectorPostgre", "select(DataRow parameters)", "con, stm, rs, pst"); errorDialog.setVisible(true); } return wynik; }
5
public void buildConnectionCSV(String outputFilename) throws UnsupportedEncodingException, FileNotFoundException, IOException { String regexp = "^\\(" + "\\(" + "(?:\\(\\(\\(([^ )]+)?(?: ([^ )]+))?(?: ([^ )]+))?(?: ([^ )]+))?\\)(?: ?([^ )]+)?(?: ([^ )]+))?(?: ([^ )]+))?)\\)\\) )?" + "\\(\\(\\(([^ )]+)?(?: ([^ )]+))?(?: ([^ )]+))?(?: ([^ )]+))?\\)(?: ?([^ )]+)?(?: ([^ )]+))?(?: ([^ )]+))?)\\)\\) " + "\\(\\(\\(([^ )]+)?(?: ([^ )]+))?(?: ([^ )]+))?(?: ([^ )]+))?\\)(?: ?([^ )]+)?(?: ([^ )]+))?(?: ([^ )]+))?)\\)\\)" + "\\)" + " (\\d+)" + "\\)$"; Pattern pattern = Pattern.compile(regexp); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(this.inputDirectory + "/connect.cha"), this.charset)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFilename), "UTF-8")); String line = null; StringBuilder builder = new StringBuilder(); while (((line = reader.readLine()) != null)) { Matcher matcher = pattern.matcher(line); matcher.find(); builder.replace(0, builder.length(), "\""); int i; if (matcher.group(1) == null) { builder.append("*,*,*,*,*,*,*\",\""); i = 8; } else { i = 1; } for (; i <= 21; i++) { String group = matcher.group(i); if ((group == null) || group.equals("")) { builder.append("*"); } else { builder.append(group); } if ((i == 7) || (i == 14)) { builder.append("\",\""); } else if (i != 21) { builder.append(","); } } builder.append("\","); builder.append(matcher.group(22)); builder.append("\n"); writer.write(builder.toString()); } writer.close(); }
8
public static RemoteResourcesServer newInstance(String[] args, boolean local) { // Disable chimpchat log java.util.logging.Logger.getLogger("com.android.chimpchat").setLevel( //$NON-NLS-1$ java.util.logging.Level.OFF); // load configuration file loadConfigurationFile(); // process command line arguments - command line defined arguments will // overwrite configuration file if (args != null) { processCommandLine(args); } // get basic needed arguments String adbPath = RemoteResourcesConfiguration.getInstance().get( RemoteResourcesConfiguration.ADB_PATH, "adb"); //$NON-NLS-1$ int port = IConnectionConstants.CONTROL_SERVER_DEFAULT_PORT; try { String portStr = RemoteResourcesConfiguration.getInstance().get( RemoteResourcesConfiguration.SERVER_PORT); if (portStr != null) { port = Integer.parseInt(portStr); } } catch (NumberFormatException e) { // do nothing } // initialize jvm debug bridge instance ServerConnectionManager.getInstance().initializeDebugBridge(adbPath); return new RemoteResourcesServer(port, local); }
3
@Override public void remove_child(Sentence_tree child){ Sentence_tree[] new_children = new Sentence_tree[this.children.length - 1]; int j = 0; for(int i = 0; i < this.children.length; i++){ if(this.children[i] != child){ new_children[j] = this.children[i]; j++; } } this.children = new_children; }
2
private void cleanUpTable() { for (int i = 0; i < commands.size(); ++i) { commands.get(i).name = commands.get(i).name.toLowerCase(); if ( commands.get(i).name.isEmpty() ) { commands.remove(i); tableModel.removeRow(i); --i; } } }
2
private static void clinit() { _disabled = true; final ArrayList<Package> list = new ArrayList<Package>(); for (final Package p : Package.getPackages()) if (p.getName().startsWith("net.minecraft.server")) list.add(p); if (list.size() == 1) { _minecraft = list.get(0).getName(); _craftbukkit = "org.bukkit.craftbukkit" + _minecraft.substring(20); if (Package.getPackage(_craftbukkit) == null) _log.severe("[NBTLib] Can't find Craftbukkit package! (" + _minecraft + "/" + _craftbukkit + ")"); else { _minecraft += "."; _craftbukkit += "."; _disabled = false; } } else { _log.severe("[NBTLib] Can't find Minecraft package! " + list.size() + " possible packages found:"); for (final Package p : list.toArray(new Package[0])) _log.severe("[NBTLib] " + p.getName()); } }
5
@After public void dbRestore(){ Main.clearTable(); int c=0; for (Item i : originalItemList){ i.setQuantity(quantityList.get(c)); Main.modifyItem(i); c++; } }
1
public static long getLongBE(final byte[] array, final int index, final int size) { switch (size) { case 0: return 0; case 1: return Bytes.getInt1(array, index); case 2: return Bytes.getInt2BE(array, index); case 3: return Bytes.getInt3BE(array, index); case 4: return Bytes.getInt4BE(array, index); case 5: return Bytes.getLong5BE(array, index); case 6: return Bytes.getLong6BE(array, index); case 7: return Bytes.getLong7BE(array, index); case 8: return Bytes.getLong8BE(array, index); default: throw new IllegalArgumentException(); } }
9
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((comment == null) ? 0 : comment.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; }
3
private void loadRoads() { File file = null; for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].getName().equals("roadID-roadInfo.tab")) { file = listOfFiles[i]; break; } } try { Scanner sc = new Scanner(file); sc.nextLine(); while (sc.hasNextLine()) { String line = sc.nextLine(); String[] values = line.split("\\t"); int id = Integer.parseInt(values[0]); int type = Integer.parseInt(values[1]); String label = values[2]; String city = values[3]; int oneway = Integer.parseInt(values[4]); int speed = Integer.parseInt(values[5]); int roadclass = Integer.parseInt(values[6]); int notforcar = Integer.parseInt(values[7]); int notforped = Integer.parseInt(values[8]); int norforbicy = Integer.parseInt(values[9]); Road r = new Road(id, type, label, city, oneway, speed, roadclass, notforcar, notforped, norforbicy); roads.add(r); // sc.nextLine(); } } catch (FileNotFoundException e) { e.printStackTrace(); } }
4
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final TMasterSalesman other = (TMasterSalesman) obj; if (!Objects.equals(this.salesIdScy, other.salesIdScy)) { return false; } return true; }
3
private String getToolTipText(Component component, ComponentAdapter adapter) { if ((stringValues == null) || stringValues.isEmpty()) { return null; } String text = ""; for (int i = 0; i < stringValues.size(); i++) { int modelIndex = adapter.getColumnIndex(sourceColumns.get(i)); if (modelIndex >= 0) { text += stringValues.get(i).getString(adapter.getValue(modelIndex)); if ((i != stringValues.size() - 1) && !isEmpty(text)) { text += delimiter; } } } return isEmpty(text) ? null : text; }
7
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Question)) { return false; } Question other = (Question) object; if ((this.idQuestion == null && other.idQuestion != null) || (this.idQuestion != null && !this.idQuestion.equals(other.idQuestion))) { return false; } return true; }
5
public void checkTripleBuffer() { mxRectangle bounds = graph.getGraphBounds(); int width = (int) Math.ceil(bounds.getX() + bounds.getWidth() + 2); int height = (int) Math.ceil(bounds.getY() + bounds.getHeight() + 2); if (tripleBuffer != null) { if (tripleBuffer.getWidth() != width || tripleBuffer.getHeight() != height) { // Resizes the buffer (destroys existing and creates new) destroyTripleBuffer(); } } if (tripleBuffer == null) { createTripleBuffer(width, height); } }
4
double getIntegralValue(Range boundaries) { List<Range> valueRanges = new ArrayList<Range>(); for (Range range : ranges) { if (range.includes(boundaries.getLeft()) || range.includes(boundaries.getRight()) || boundaries.includes(range.getLeft()) || boundaries.includes(range.getRight())) { valueRanges.add(range); } } Double value = 0d; for (Range range : valueRanges) { Long rangeValue = data.get(range); if (rangeValue == null) { continue; } if (boundaries.includes(range)) { value += rangeValue; } else { value += getPartialValue(range, rangeValue, boundaries); } } return value; }
8
public FooObject(String name, int id, long age, FooObject friend) { this.name = name; this.id = id; this.age = age; this.friend = friend; }
0
public int getBlackjackValue() { int val; // The value computed for the hand. boolean ace; // This will be set to true if the // hand contains an ace. int cards; // Number of cards in the hand. val = 0; ace = false; cards = getCardCount(); for ( int i = 0; i < cards; i++ ) { // Add the value of the i-th card in the hand. Card card; // The i-th card; int cardVal; // The blackjack value of the i-th card. card = getCard(i); cardVal = card.getValue(); // The normal value, 1 to 13. if (cardVal > 10) { cardVal = 10; // For a Jack, Queen, or King. } if (cardVal == 1) { ace = true; // There is at least one ace. } val = val + cardVal; } // Now, val is the value of the hand, counting any ace as 1. // If there is an ace, and if changing its value from 1 to // 11 would leave the score less than or equal to 21, // then do so by adding the extra 10 points to val. if ( ace == true && val + 10 <= 21 ) val = val + 10; return val; } // end getBlackjackValue()
5
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(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainWindow.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 MainWindow().setVisible(true); } }); }
6