text
stringlengths
14
410k
label
int32
0
9
public CheckResultMessage checkE04(int day) { int r1 = get(13, 5); int c1 = get(14, 5); int r2 = get(17, 5); int c2 = get(18, 5); if (checkVersion(file).equals("2003")) { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); if (0 != getValue(r1 + day, c1, 3).compareTo( getValue(r2 + day, c2 + 3, 4))) { return error("支付机构汇总报表<" + fileName + ">客户资金账户借方发生额 E04:" + day + "日错误"); } in.close(); } catch (Exception e) { } } else { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); if (0 != getValue1(r1 + day, c1, 3).compareTo( getValue1(r2 + day, c2 + 3, 4))) { return error("支付机构汇总报表<" + fileName + ">客户资金账户借方发生额 E04:" + day + "日错误"); } in.close(); } catch (Exception e) { } } return pass("支付机构汇总报表<" + fileName + ">客户资金账户借方发生额 E04:" + day + "日正确"); }
5
public int MovePacket(int inputBufferNumber, int outputBufferNumber, int TIME) { //ONLY ONE BUS PRESENT IN THIS FABRIC //if Active status was successful and the flag is true for having //control of the bus //set packet moved default packetMoved = false; //get the RouterPacket in the InputBuffer selected RouterPacket peekPacket = (RouterPacket)inputBuffers[inputBufferNumber].peek(); //esure there is a packet to move, packet activate bus successfully,bus becomes active if((peekPacket != null) && (sequence[0] == peekPacket.GetSequenceNumber()) && (GetBusActiveStatus(0)== true)) { //ensure there is packet in the buffer if(inputBuffers[inputBufferNumber].size() > 0) { //System.out.println("MOVEPACKET FROM: "+inputBufferNumber+" TO: "+outputBufferNumber); //get RouterPacket from input buffer RouterPacket rPacket = (RouterPacket)inputBuffers[inputBufferNumber].remove(); //update the time delivered rPacket.SetTimeDelivered(TIME); //set the recent packet moved recentPacket = rPacket; //set the recent bus used recentBus = 0; //set the input buffer of the packet rPacket.SetInputBuffer(inputBufferNumber); //set the output buffer of the packet rPacket.SetOutputBuffer(outputBufferNumber); //move the data to the internalMemory buffer this.internalMemory.add(rPacket); //move the data to the output buffer //this.outputBuffers[outputBufferNumber].add(rPacket); //set packet successfully moved packetMoved = true; } } //tell the bus used to send the packet, has only 1 bus return recentBus; }
4
public void addMutations() { for (int i = 0; i < this.population.size(); i++) { this.population.get(i).mutate(66, 2); } }
1
private boolean isConnectedTo(RailLogic var1) { for (int var2 = 0; var2 < this.connectedTracks.size(); ++var2) { ChunkPosition var3 = (ChunkPosition) this.connectedTracks.get(var2); if (var3.x == var1.trackX && var3.z == var1.trackZ) { return true; } } return false; }
3
public HashSet<String> getQueryIDs(String queryString) { HashSet<String> objList = new HashSet<String>(); //System.out.println(queryString); // execute query ItemIterable<QueryResult> results = session.query(queryString, false); for (QueryResult qResult : results) { String objectId = ""; PropertyData<?> propData = qResult.getPropertyById("cmis:objectId"); // Atom // Pub // binding if (propData != null) { objectId = (String) propData.getFirstValue(); } else { objectId = qResult.getPropertyValueByQueryName("d.cmis:objectId"); // Web // Services // binding } objList.add(objectId); } return objList; }
3
public void recordPackage(String jvmClassName) { String classname = jvmToJavaName(jvmClassName); for (;;) { int i = classname.lastIndexOf('.'); if (i > 0) { classname = classname.substring(0, i); classPool.recordInvalidClassName(classname); } else break; } }
2
@Override public String toString() { String result = ""; String newline = "\n"; for (int i = 0; i < colonnes; i++) { for (int j = 0; j < lignes; j++) { if (vampires[i][j] != 0) { result += vampires[i][j] + " vampires " + "sur case " + i + " ," + j + newline; } } } for (int i = 0; i < colonnes; i++) { for (int j = 0; j < lignes; j++) { if (loups[i][j] != 0) { result += loups[i][j] + " loups " + "sur case " + i + " ," + j + newline; } } } for (int i = 0; i < colonnes; i++) { for (int j = 0; j < lignes; j++) { if (humains[i][j] != 0) { result += humains[i][j] + " humains " + "sur case " + i + " ," + j + newline; } } } return result; }
9
public static int indexOfSubString(String str,String sub){ int curIndex=0; int subIndex=0; while(curIndex<str.length() && subIndex<sub.length()){ //If it matches if(str.charAt(curIndex)==sub.charAt(subIndex)){ curIndex++; subIndex++; continue; }else{ //If it doesn't match, calc new curIndex and new subIndex if(subIndex==0){ //The first doesn't match curIndex++; continue; }else{ //Match to some point subIndex=calcNewPos(subIndex,sub); continue; } } } if(subIndex==sub.length()){ return curIndex-subIndex; } return -1; }
5
public static boolean question(String question) { System.out.println(question+"\n I/N?"); boolean correct = false; while(!correct) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { String s1 = br.readLine(); if(s1.equals("I") || s1.equals("i")) return true; else if(s1.equals("N") || s1.equals("n")) return false; } catch (IOException e) { e.printStackTrace(); } } return false; }
6
public void setName(String name) { this.name = name; }
0
public Aukiolo haeAukiolot() throws DAOPoikkeus { // Esitellään olio Aukiolo aukiolo = new Aukiolo(); // Avataan tietokantayhteys: Connection yhteys = avaaYhteys(); // Haetaan tietokannasta aukioloajat: try { String sql = "select arkialku, arkiloppu, vklpalku, vklploppu from Aukiolot"; Statement haku = yhteys.createStatement(); ResultSet tulokset = haku.executeQuery(sql); // Tehdään tietokantahaun tuloksista merkkijonoja while(tulokset.next()) { Date arkialku = tulokset.getTime("arkialku"); Date arkiloppu = tulokset.getTime("arkiloppu"); Date vklpalku = tulokset.getTime("vklpalku"); Date vklploppu = tulokset.getTime("vklploppu"); // Tehdään tuloksista olio aukiolo = new Aukiolo(arkialku, arkiloppu, vklpalku, vklploppu); } } catch(Exception e) { // Tapahtuiko jokin virhe? Heitetään poikkeus ruudulle. throw new DAOPoikkeus("Tietokantahaku aiheutti virheen.", e); } finally { // Lopulta aina suljetaan yhteys! suljeYhteys(yhteys); } return aukiolo; }
2
protected void onSetInviteOnly(String channel, String sourceNick, String sourceLogin, String sourceHostname) {}
0
@Override public void setCell(int x, int y, boolean live) { if (y<0 || y>=getHeight()) return; if (x<0 || x>=getWidth()) return; if (live) world[y][x] = 0; }
5
protected void addLevel2Tree( double cx, double cy, WorldUpdateBuilder ub ) { switch( rand.nextInt(4) ) { case( 0 ): // ring! double rad = 250+rand.nextDouble()*500; double cir = rad * 2 * Math.PI; int count = (int)(cir / 500)+1; double phase = rand.nextDouble(); for( int i=0; i<count; ++i ) { double o = i*2*Math.PI/count + phase; addLevel2Cluster( cx+rad*Math.cos(o), cy+rad*Math.sin(o), ub ); } break; case( 1 ): // star! addLevel2Cluster( cx, cy, ub ); addLevel2Cluster( cx - 300, cy - 400, ub ); addLevel2Cluster( cx + 300, cy + 400, ub ); addLevel2Cluster( cx - 400, cy + 300, ub ); addLevel2Cluster( cx + 400, cy - 300, ub ); break; case( 2 ): // line! double ang = rand.nextDouble()*Math.PI*2; for( int i=rand.nextInt(20); i>=0; --i ) { cx += 450*Math.cos(ang); cy += 450*Math.sin(ang); addLevel2Cluster( cx, cy, ub ); ang += rand.nextGaussian(); } break; case( 3 ): // random! for( int i=rand.nextInt(7); i>=0; --i ) { addLevel2Cluster( cx + rand.nextDouble()*1024-512, cy + rand.nextDouble()*1024-512, ub ); } } }
7
public NoPreviousEmailKontaktFoundException(String message) { super(message); }
0
public boolean controlErroresEmpleado(Empleado empleado) { boolean correcto=false; if(empleado.getDisponible()) { if(!empleado.getApellidos().isEmpty() && !empleado.getNombre().isEmpty()) { if(!empleado.getDireccion().isEmpty() && empleado.getSueldo()>0 && !empleado.getTipo().isEmpty()) { if(empleado.getTipo().equalsIgnoreCase("supervisor")) { Supervisor s =(Supervisor)empleado; if(s.getFactor_productividad()>0) { correcto=true; } } else { Trabajador t =(Trabajador)empleado; if(t.getHoras_trabajadas()>0) { correcto=true; } } } } } return correcto; }
9
public void getInput() { String command; Scanner inFile = new Scanner(System.in); do { this.display(); // display the menu // get commaned entered command = inFile.nextLine(); command = command.trim().toUpperCase(); switch (command) { case "B": this.optionsMenuControl.displayBoardOption(); break; case "M": this.optionsMenuControl.displayMatchingOption(); break; case "N": this.optionsMenuControl.displayNumPlayersOption(); break; case "P": this.optionsMenuControl.displayPlayerNamesOption(); break; case "Q": break; default: new MemoryError().displayError("Invalid command. Please enter a valid command."); continue; } } while (!command.equals("Q")); return; }
6
public void setFixedOrientation(boolean fixedOrientation) { this.fixedOrientation = fixedOrientation; if(fixedOrientation) mouseListener.show(); else mouseListener.hide(); }
1
public JSONObject optJSONObject(String key) { Object object = this.opt(key); return object instanceof JSONObject ? (JSONObject) object : null; }
1
public String getArea() { return Area; }
0
private void loadPoperties() { InputStream resourceFile = null; properties = new Properties(); try { resourceFile = getClass().getResourceAsStream(Constants.PROPERTIES_FILE.toString()); properties.load(resourceFile); LOG.info("Validator Properties are successfully loaded."); } catch (IOException e) { LOG.error("Failed to load Validator Property.", e); } }
1
@Override public boolean equals(Object o) { if (!(o instanceof ElementStAX)) { return false; } else { ElementStAX i = (ElementStAX) o; if(isText() != i.isText()) { return false; } if(isText()) { return i.text.equals(this.text); } else { return i.attributes.equals(this.attributes) && i.name.equals(this.name) && i.hasChildren == hasChildren; } } }
5
static String writeDate(int year, int month, int day, int hour, int minute, int second) { String retu = ""; if (day > 0) { retu += month + "/" + day + "/" + year; } else { retu += month + "/" + year; } String h = "", m = "", s = ""; if (hour >= 0) { if (hour < 10) { h = "0" + hour; } else { h += hour; } } if (minute >= 0) { if (minute < 10) { m = "0" + minute; } else { m += minute; } } if (second >= 0) { if (second < 10) { s = "0" + second; } else { s += second; } } if (m.length() != 0) { h += ":"; } if (s.length() != 0) { m += ":"; } return retu + " " + h + "" + m + "" + s; }
9
public void moveUp(){ switch (polygonPaint) { case 0: line.moveUp(); repaint(); break; case 1: curv.moveUp(); repaint(); break; case 2: triangle.moveUp(); repaint(); break; case 3: rectangle.moveUp(); repaint(); break; case 4: cu.moveUp(); repaint(); break; case 5: elipse.moveUp(); repaint(); break; case 6: arc.moveUp(); repaint(); break; } repaint(); }
7
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(!(sender instanceof Player)){ sender.sendMessage(ChatColor.DARK_RED + "You need to be a Player!"); return true; } Player player = (Player) sender; if(!player.hasPermission(pluginMain.pluginManager.getPermission("thf.location"))){ sender.sendMessage(ChatColor.DARK_RED + "No perm makes server ANGRYYYY"); return true; } if(args.length == 1){ if(args[0].equalsIgnoreCase("serverstatus")){ String location = pluginMain.getLocation(player.getName()); if(location == null){ sender.sendMessage("No location set!"); return true; } pluginMain.getConfig().set("Signs.ServerStatus", location); pluginMain.saveConfig(); sender.sendMessage("Set serverstatus to " + location); pluginMain.serverStatusSigns = true; return true; } } sender.sendMessage("Usable Locations: ServerStatus"); return true; }
5
public boolean accept(File f) { if (f.isDirectory()) { return true; } Utils utils = new Utils() ; String extension = utils.getExtension(f); if (extension != null) { if (extension.equals(Utils.tiff) || extension.equals(Utils.tif) || extension.equals(Utils.gif) || extension.equals(Utils.jpeg) || extension.equals(Utils.jpg) || extension.equals(Utils.png)) { return true; } else { return false; } } return false; }
8
@Override public StateBuffer execute(StateBuffer in) { StateBuffer out = new StateBuffer(); int sumDelay = -1; while(!out.isFull() && (!onlyOneStateNeeded || out.isEmpty())) { sumDelay++; System.out.println("FindShortestSequenceSegment: testing delay "+sumDelay+" size="+out.size()); for(State s : in.getStates()) { curGb.restore(s); rec(s,0,sumDelay,out); } } return out; }
4
@Override public int[] sort(int[] a) { for(int i = 1; i < a.length; i++) { for(int j = i; j > 0; j--) { if(a[j] < a[j-1]) swap(a, j, j-1); } } return a; }
3
private static String getJSON(String url) throws IOException { BufferedReader bis = null; InputStream is = null; try { URLConnection connection = new URL(url).openConnection(); is = connection.getInputStream(); // warning of UTF-8 data bis = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line = null; StringBuffer result = new StringBuffer(); while ((line = bis.readLine()) != null) { result.append(line); } return result.toString(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } }
5
protected boolean colidate(int x1, int y1, int x2, int y2){ int left = getX(); int right = getX()+getSWidth(); int top = getY(); int bottom = getY()+getSHeight(); for (int x = x1+5; x < x2-5; x++) { for (int y = y1+5; y < y2-5; y++) { if (x>=left && x<=right && y>=top && y<=bottom) { return true; } } } return false; }
6
public static Hiscores lookup(String name) { try { final BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(WEBSITE + name).openStream())); final StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) builder.append(line).append(":"); return new Hiscores(name, builder.toString()); } catch (IOException ignored) { } return null; }
2
@Override public double getTemperature(int i, int j) { if (i >= 0 && i < numLongCells && j >= 0 && j < numLatCells) { return cellValues[i][j]; } // Allow overrunning the "size" of the grid. We are on // a sphere, after all. This is convenient for checking neighbors // at boundaries. int jIndex = j % (2 * numLatCells); int iIndex = i % numLongCells; // Translate a negative index to its positive equivalent. if (iIndex < 0) { iIndex += numLongCells; } if (jIndex < 0) { jIndex += 2 * numLatCells; } // If we have not circled past the pole or have circled all the // way back, past two poles, the latitude and longitude are simple. if (jIndex < numLatCells) { return cellValues[iIndex][jIndex]; } else { // Otherwise, we have crossed the poles an odd number of times, and // the latitude and longitude are more complicated. return cellValues[Math.abs(iIndex - (numLongCells / 2))][(2 * numLatCells - 1) - jIndex]; } }
7
public List getMessByTimeAndUser(String beginTme, String endTime, String username,String rescueStatus) { if(beginTme!=null&&!beginTme.trim().equals("")){ if(endTime!=null&&!endTime.trim().equals("")){ String hql = "from Rescueapply r where r.applytime >=:beginTime and r.applytime <=:endTime and r.applyperson=:applyperson" + rescueStatus; return this.sessionFactory.getCurrentSession().createQuery(hql).setParameter("beginTime",beginTme).setParameter("endTime",endTime).setParameter("applyperson", username).list(); } else{ String hql = "from Rescueapply r where r.applytime >=:beginTime and r.applyperson=:applyperson" + rescueStatus; return this.sessionFactory.getCurrentSession().createQuery(hql).setParameter("beginTime",beginTme).setParameter("applyperson", username).list(); } }else{ if(endTime!=null&&!endTime.trim().equals("")){ String hql = "from Rescueapply r where r.applytime <=:endTime and r.applyperson=:applyperson" + rescueStatus; return this.sessionFactory.getCurrentSession().createQuery(hql).setParameter("endTime",endTime).setParameter("applyperson", username).list(); }else{ return null; } } }
6
public static void main(String[] args) throws JAXBException { Worker worker = new Worker(); worker.setName("Sergii"); worker.setAge(25); worker.setId(7); File file = new File("D:\\Java SE\\src\\xml\\jaxb\\worker.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Worker.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(worker, file); marshaller.marshal(worker, System.out); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Worker wprker = (Worker)unmarshaller.unmarshal(file); System.out.println(wprker.getName()); }
0
@Override public void execute() { if (Game.getClientState() != Game.INDEX_MAP_LOADED) { BearFurs.stop = 1000; } if (Game.getClientState() == Game.INDEX_MAP_LOADED && BearFurs.stop == 1000) { BearFurs.stop = 50; } if (BearFurs.client != Bot.client()) { WidgetCache.purge(); Bot.context().getEventManager().addListener(this); BearFurs.client = Bot.client(); } if (Inventory.contains(Constants.NEWSPAPER)) { Inventory.getItem(Constants.NEWSPAPER).getWidgetChild().interact("Drop"); sleep(50, 150); } if (Walking.getEnergy() == 100 && Walking.isRunEnabled()) { Walking.setRun(true); } if (Widgets.get(640, 30).isOnScreen()) { Widgets.get(640, 30).click(true); } }
8
protected JTableExtender initializeTable(Object obj) { // System.out.println("In regular multiple initialize"); boolean multiple = false; int inputCount = 0; if(this.getEnvironment().myObjects!=null){ multiple = true; inputCount = 1; } //System.out.println("In initialize:" + multiple); InputTableModel model = null; if(getObject() instanceof Automaton){ model = InputTableModel.getModel((Automaton)getObject(), multiple); } JTableExtender table = new JTableExtender(model, this); // In this regular multiple simulate pane, we don't care about // the outputs, so get rid of them. TableColumnModel tcmodel = table.getColumnModel(); inputCount += model.getInputCount(); for (int i = model.getInputCount(); i > 0; i--) { tcmodel.removeColumn(tcmodel.getColumn(inputCount)); } if(multiple){ ArrayList autos = this.getEnvironment().myObjects; //System.out.println("In initialize: " + autos.size()); ArrayList strings = this.getEnvironment().myTestStrings; int offset = strings.size(); int row = 0; for(int m = 0; m < autos.size(); m++){ for(int k = 0; k < strings.size(); k++){ row = k+offset*m; Object currentObj = autos.get(m); if(currentObj instanceof Automaton){ model.setValueAt(((Automaton)currentObj).getFileName(), row, 0); model.setValueAt((String)strings.get(k), row, 1); } } } while((model.getRowCount()-1) > (autos.size()*strings.size())){ model.deleteRow(model.getRowCount()-2); } } // Set up the last graphical parameters. table.setShowGrid(true); table.setGridColor(Color.lightGray); return table; }
8
public static void main (String[] args) { int pattern[] = new int[6]; for (int i = 0; i < 4; i++) { initialize(pattern, 0, 5); pattern[i] = 1; for (int j = i+1; j < 5; j++) { initialize(pattern, i+1, 5); pattern[j] = 2; for (int k = j+1; k < 6; k++) { initialize(pattern, j+1, 5); pattern[k] = 3; generate(pattern); execute(pattern); System.out.print(" r1 = "+ r1+" r2 = "+r2+" r3 = "+r3); System.out.println(); } } } }
3
public int login(User loginUser) { // Variable für Anzahl der gefundenen Datensätze int numRows = 0; try { // PreparedStatement für den SQL-Befehl String sqlStatement = "SELECT COUNT(*) FROM bookworm_database.users WHERE username = '" + loginUser.getUserName() + "' AND userpassword = '" + loginUser.getUserPassword() + "';"; // SQL-Befehl wird ausgeführt myResultSet = mySQLDatabase.executeSQLQuery(sqlStatement); // Anzahl der Datensätze ermitteln while (myResultSet.next()) { numRows = myResultSet.getInt("count(*)"); } } catch (Exception e) { System.out.println(e.toString()); // Ein Dialogfenster mit entsprechender Meldung soll erzeugt werden String errorText = "Datenbankabfrage konnte nicht durchgeführt werden."; new InfoError().showMessage(errorText); } finally { // offene Verbindungen werden geschlossen mySQLDatabase.closeConnections(); } return numRows; }
2
public void addShadow(Identifier orig) { if (isPreserved() && !orig.isPreserved()) orig.setPreserved(); else if (!isPreserved() && orig.isPreserved()) setPreserved(); Identifier ptr = this; while (ptr.right != null) ptr = ptr.right; /* Check if orig is already on the ptr chain */ Identifier check = orig; while (check.right != null) check = check.right; if (check == ptr) return; while (orig.left != null) orig = orig.left; ptr.right = orig; orig.left = ptr; }
8
public void setProperties(Object instance, Map map) throws IllegalAccessException, InvocationTargetException { if (map == null) { return; } for (Object object : map.keySet()) { String property = (String) object; Object v = map.get(property); if (isIndexedProperty(property)) { Map m = (Map) v; for (Object object1 : m.keySet()) { Number n = (Number) object1; Object propVal = m.get(n); // System.out.println("Setting Indexed Property: " + property + ": " + n + " = " + propVal); setProperty(instance, property, n, propVal); } } else { setProperty(instance, property, v); } } }
4
public static void main(String[] args) throws ReadItemLineException, IOException { BufferedReader br = null; Reader r = new InputStreamReader(System.in); br = new BufferedReader(r); String str = null; String outStr = null; try { do{ System.out.println("Please select file.(input1, input2, input3)"); str = br.readLine(); if(StringUtils.equalsIgnoreCase(str, "input1") || StringUtils.equalsIgnoreCase(str, "input2") || StringUtils.equalsIgnoreCase(str, "input3")){ outStr = StringUtils.replaceChars(str, 'i', 'o'); File inputFile = new File("."+File.separator +"data"+File.separator + str); File outputFile = new File("."+File.separator +"data"+File.separator + outStr); //Once input file is determined, SaleTaxController is called for purchasing items SaleTaxController saleTaxController = SaleTaxController.getInstance(); saleTaxController.printReceipt(inputFile, outputFile); }else{ System.out.println("Wrong file name"); } } while (!str.equalsIgnoreCase("exit")); } catch (IOException e) { e.printStackTrace(); } finally{ try{ if(br != null) br.close(); }catch(Exception ex){} } }
7
private void araseLine(int lineNumber){ if(lineNumber < fieldSize) { for (int i = 0; i < fieldSize; i++){ field[i][lineNumber] = DEFAULT_CELL_VALUE; } } else { System.out.println("Wrong data in araseLine"); } }
2
public static BoundaryBox clip(BoundaryBox bb, int minX, int minY, int maxX, int maxY){ int newX = Math.min(Math.max(minX, bb.getX()), maxX); int newY = Math.min(Math.max(minY, bb.getY()), maxY); int endX = Math.min(Math.max(minX, bb.getX()+bb.getWidth()), maxX); int endY = Math.min(Math.max(minY, bb.getY()+bb.getHeight()), maxY); return new BoundaryBox(newX, newY, endX-newX, endY-newY); }
0
private void gameListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_gameListMouseClicked // Get the selected game list item int index = gameList.locationToIndex(evt.getPoint()); GameListItem item = (GameListItem) gameModel.get(index); // See if the selected state should be fired if(evt.getClickCount() >= 2 || evt.getX() < 17){ // Enable the apply button because something's state has changed if( !applyBtn.isEnabled()) applyBtn.setEnabled(true); // Toggle selected state boolean selected = ! item.isSelected(); item.setSelected(selected); // Enable/Disable tabs as needed int tabIndex = Utils.getIndex(builtInGames, item.getID()); if(tabIndex != -1 && selected != gameSettingsTabPane.isEnabledAt(tabIndex)) gameSettingsTabPane.setEnabledAt(tabIndex, selected); // Re-build the active games array int len = gameModel.size(), activeCount = 0; activeGames = new byte[len]; for(int i=0; i<len; i++){ item = (GameListItem) gameModel.get(i); if(item.isSelected()){ activeGames[activeCount] = item.getID(); activeCount++; } } activeGames = Arrays.copyOf(activeGames, activeCount); // Save the active games array in the prefs prefs.put(Config.Key.active_tabs.toString(), implode(activeGames)); // Repaint cell gameList.repaint(gameList.getCellBounds(index, index)); } }//GEN-LAST:event_gameListMouseClicked
7
public Board(TicTacUI owner, Game ownerGame) { this.setLayout(new GridBagLayout()); for(int i = 0; i < gameBoard.length; i++) { gameBoard[i] = new Tile(i, this); GridBagConstraints constraint = new GridBagConstraints(); constraint.gridx = i % numCols; constraint.gridy = i / numCols; constraint.ipadx = horizontalPadding; constraint.ipady = verticalPadding; this.add(gameBoard[i], constraint); this.setOpaque(false); } this.ownerGame = ownerGame; this.owner = owner; }
1
public static List<Labo> selectAll(EntityManager em) throws PersistenceException { List<Labo> lesLabos = null; Query query= em.createQuery("select l from Labo l"); lesLabos = query.getResultList(); return lesLabos; }
0
protected static void doPhoneNumbers() { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); String phone = in.next(); Integer dictionarySize = in.nextInt(); for (int i = 0; i < dictionarySize; i++) { String word = in.next(); String number = convertWordToNumber(word); List<Integer> indexes = getAllSubstringIndexes(phone, number); for (int startInd : indexes) addWord(startInd, word); } List<String> sentence = getSentenceRepresentation(phone.length()); Iterator<String> itr = sentence.iterator(); while (itr.hasNext()) { String echo = itr.next(); echo = (itr.hasNext()) ? echo + " " : echo; out.print(echo); } out.flush(); }
4
public static int maxProfit3(int[] prices) { List<Integer> p = maxProfitPoint(prices, 0, prices.length); int profit = p.get(2); List<Integer> p1 = maxProfitPoint(prices, 0, p.get(0)); List<Integer> p2 = maxProfitPoint(prices, p.get(1) + 1, prices.length); profit = profit + (p1.get(2) > p2.get(2) ? p1.get(2) : p2.get(2)); for(int i = p.get(0) + 1; i < p.get(1); i++) { List<Integer> left = maxProfitPoint(prices, p.get(0), i); List<Integer> right = maxProfitPoint(prices, i, p.get(1) + 1); if (left.get(2) + right.get(2) > profit) profit = left.get(2) + right.get(2); } return profit; }
3
public boolean add(Object o) { LocalInfo li = (LocalInfo) o; LocalInfo contained = findSlot(li.getSlot()); if (contained != null) { li.combineWith(contained); return false; } else { grow(1); locals[count++] = li; return true; } }
1
public Pair<List<Sentence>, Double> getBestSnippet(ScoreFunction func, int minLength, int maxLength, int delta, int windowSize) { double highscore = Double.MIN_VALUE; List<Sentence> bestSentences = null; for (Pair<Integer, Integer> boundaries : chooseTwo(sentences.size())) { int start = boundaries.first(); int end = boundaries.second(); if ((end - start) > maxLength || (end - start) < minLength ) continue; List<Sentence> currentSentences = sentences.subList(start, end); int currentLength = 0; boolean seen = false; for (Sentence sentence : currentSentences){ currentLength += sentence.terms.size(); seen |= sentence.isSeen(); } if (seen) continue; if (currentLength > windowSize) continue; //Set<String> uniqueTerms = new HashSet<String>(); List<String> uniqueTerms = new ArrayList<String>(); for (Sentence sentence : currentSentences){ uniqueTerms.addAll(sentence.terms); } double score = func.getScore(uniqueTerms, this.index) / (currentLength + delta); if (score > highscore) { highscore = score; bestSentences = currentSentences; } } return new Pair<List<Sentence>, Double>(bestSentences, highscore); }
8
@Override public boolean equals (Object other) { Edge<?> e = (Edge<?>) other; // warning if use Edge<N> - unchecked method invocation if (other == null) {return false;} if (this.getClass() != other.getClass()) {return false;} if (!this.src.equals(e.src)) {return false;} if (!this.dst.equals(e.dst)) {return false;} if (this.cost != e.cost) {return false;} return true; }
7
public void paint(Graphics pen) { if(myText.length() == 0) return; Graphics2D p = (Graphics2D)pen; FontRenderContext frc = p.getFontRenderContext(); TextLayout layout = new TextLayout(myText, FONT, frc); layout.draw(p, (float)myBottomLeft.getX(), (float)myBottomLeft.getY()); }
1
private static String sqlType2JavaType(int type) { String typeStr = ""; if (Types.INTEGER == type || Types.NUMERIC == type) { typeStr = "int"; } else if (Types.VARCHAR == type || Types.CHAR == type || -1 == type) { typeStr = "String"; } else if (Types.DECIMAL == type) { typeStr = "double"; } else if (Types.TIMESTAMP == type || Types.DATE == type) { typeStr = "Date"; } else if (Types.CLOB == type) { typeStr = "long"; } return typeStr; }
9
@Override public Command planNextMove(Info info) { enemyDistance=null; enemyDistance= new double[info.getEnemies().size()]; enemyAngle=null; enemyAngle= new double[info.getEnemies().size()]; x=info.getX(); y=info.getY(); angle=info.getDirection(); int i=0; for(InfoDetail enemy : info.getEnemies()) { if(enemy.getX() > x) xDis=enemy.getX()-x; else xDis=x-enemy.getX(); if(enemy.getY() > y) yDis=enemy.getY()-y; else yDis=y-enemy.getY(); enemyDistance[i]= Math.sqrt(xDis*xDis+yDis*yDis); enemyAngle[i++]=(double)yDis/xDis; } double delka=1000; int tmp=0; for(int a=0;a<enemyDistance.length;a++) { if(enemyDistance[a]<delka) { tmp=a; delka=enemyDistance[a]; } } angle=(int)Math.toDegrees(Math.atan(enemyAngle[tmp])); int test_cornerx = info.getX(); int test_cornery = info.getY(); if (test_cornerx <= 20 || test_cornerx >= 1900 || test_cornery <= 20 || test_cornery >= 1900) { boolean test = false; int uhel = info.getDirection(); return new Command(CommandType.MOVE_FORWARD, CommandType.TURN_LEFT, 180, CommandType.NONE); } // return new Command(CommandType.MOVE_FORWARD, CommandType.NONE, 0, CommandType.SHOOT); return new Command(CommandType.MOVE_FORWARD, CommandType.TURN_LEFT, (360+info.getDirection()-angle), CommandType.SHOOT); }
9
public boolean hasPlayableCard() { for (Card card : hand) { if (canPlayCard(card)) { return true; } } return false; }
2
public static void main(String[] args) { int i; boolean[] sieve = new boolean[2000000]; long sum = 0; for (i = 2; i < 2000000; sieve[i++] = true) ; for (i = 2; i * i < 2000000; i++) { if (sieve[i]) { System.out.println(i); sum += (long) i; if (sum < 0) { System.out.println("rollover error"); return; } for (int j = i * i; j < 2000000; j += i) { sieve[j] = false; } } } for (; i < 2000000; i++) { if (sieve[i]) { System.out.println(i); sum += (long) i; if (sum < 0) { System.out.println("rolover error"); return; } } } System.out.println(sum); }
8
private void paintEnemies(Graphics2D g2d) { for (Enemy e : gameLogic.getEnemyList()) { if(e.isAlive()){ g2d.drawImage(e.image, e.posX, e.posY, this); } } }
2
public void tableChanged(TableModelEvent e) { Object o = e.getSource(); if (o instanceof TableModel && table.getRowSelectionAllowed()) { int row = e.getFirstRow(); int column = e.getColumn(); // tells which student we are // modifying if (row == -1 || column == -1) return; TableModel model = (TableModel) e.getSource(); String columnName = model.getColumnName(column); Object data = model.getValueAt(row, column); Elev elev_vechi = selected_clasa.getElevi().get(row); Elev elev = selected_clasa.getElevi().get(row); switch (columnName) { case "Nume": System.out.println("NUME MODIFICA"); elev.setNume(data.toString()); break; case "Prenume": elev.setPrenume(data.toString()); break; case "CNP": elev.setCNP(data.toString()); break; case "Data Nasterii": try { elev.setDate(data.toString()); } catch (Exception ex) { ex.printStackTrace(); } break; } secretar.modifyElevFromClasa(selected_clasa, elev_vechi, elev); } }
9
public static Board createCompleteBoard(int count, Device.Type... deviceType) throws IOException { Board newBoard = createBoard(); Device device; for (int i = 0; i < count; i++) { String nameDevise = deviceType[rnd.nextInt(deviceType.length)].name(); switch (nameDevise) { case "DIOD": { device = createDiod(); newBoard.establishElement(device); } break; case "TRANSISTOR": { device = createTransistor(); newBoard.establishElement(device); } break; case "CHIP": { device = createChip(); newBoard.establishElement(device); } break; case "RESISTOR": { device = createResistor(); newBoard.establishElement(device); } break; } } return newBoard; }
5
@SuppressWarnings("unchecked") public void poppulateCriteria(HashMap<String, Object> criteria){ if(criteria.containsKey("endDate")){ this.endDate = new LocalDate((String) criteria.get("endDate")); } if(criteria.containsKey("startDate")){ this.strtDate = new LocalDate((String) criteria.get("startDate")); } if(criteria.containsKey("minAvgRating")){ this.minAvgRating = Integer.parseInt((String) criteria.get("minAvgRating")); } if(criteria.containsKey("facility")){ this.facility = new Facility(); this.facility.addFacility((HashMap<String, String>)criteria.get("facility")); } if(criteria.containsKey("location")){ this.loc = new Location(); this.loc.addLocation((HashMap<String, Object>)criteria.get("location")); } if(criteria.containsKey("features")){ ArrayList<Object> ft = (ArrayList<Object>)criteria.get("features"); for(int i = 0; i<ft.size();i++){ Features ftObject = new Features((String)ft.get(i)); this.features.add(ftObject); } } }
7
public void setPitch(float pitch) { if(pitch <= 90 && pitch >= -90) this.pitch = pitch; else if(pitch > 90) { this.pitch = 90; } else { this.pitch = -90; } }
3
public boolean canEatFish(Fish f) { if (f instanceof Gyarados || f instanceof Magikarp) { return false; } return true; }
2
public void addMessage(ChatMessage message){ try { Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); String url = "jdbc:derby:" + DBName; Connection connection = DriverManager.getConnection(url); Statement statement = connection.createStatement(); DateFormat dtf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String currentDate = dtf.format(new Date()); String sqlStatement = "INSERT INTO chatmessages (user_uid, channel_cid, message, messagedate) VALUES (" + message.getUserID() + ", " + message.getChannelCID() + ", '" + message.getMessage() + "', '" + currentDate + "')"; statement.executeUpdate(sqlStatement); statement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } }
1
private static boolean confirmQuit(String title) { Game.pauseGame(); return !Game.isActive() || JOptionPane.NO_OPTION != JOptionPane.showConfirmDialog(instance, "Quit the Current Game?", "Confirm " + title, JOptionPane.YES_NO_OPTION ); }
1
public boolean equals(TProducto productoB) { return this._id == productoB.getId() && _nombre.equalsIgnoreCase(productoB.getNombre()) && _precio == productoB.getPrecio() && _descripcion.equalsIgnoreCase(productoB.getDescripcion()) && _codigoDeBarras.equalsIgnoreCase(productoB.getCodigoDeBarras()) && _activo == productoB.getActivo(); }
5
@Test public void runTestLocationLeak2() throws IOException { InfoflowResults res = analyzeAPKFile("Callbacks_LocationLeak2.apk"); Assert.assertNotNull(res); Assert.assertEquals(2, res.size()); }
0
public Popup(int width,int height,PopupPosition pos){ if(width == 0){ throw new IllegalArgumentException("Width cannot be 0"); } if(height == 0){ throw new IllegalArgumentException("Height cannot be 0"); } this.width = width; this.height = height; int screenWidth = JEngine.SCREEN_WIDTH; int screenHeight = JEngine.SCREEN_HEIGHT; if(pos == PopupPosition.CENTERED){ this.x = (screenWidth/2) - (width/2); this.y = (screenHeight/2) - (height/2); }else if(pos == PopupPosition.BOTTOM){ this.x = (screenWidth/2) - (width/2); this.y = screenHeight - 100; }else if(pos == PopupPosition.TOP){ this.x = (screenWidth/2) - (width/2); this.y = 25; } }
5
private boolean zzRefill() throws java.io.IOException { /* first: make room (if you can) */ if (zzStartRead > 0) { System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead-zzStartRead); /* translate stored positions */ zzEndRead-= zzStartRead; zzCurrentPos-= zzStartRead; zzMarkedPos-= zzStartRead; zzPushbackPos-= zzStartRead; zzStartRead = 0; } /* is the buffer big enough? */ if (zzCurrentPos >= zzBuffer.length) { /* if not: blow it up */ char newBuffer[] = new char[zzCurrentPos*2]; System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); zzBuffer = newBuffer; } /* finally: fill the buffer with new input */ int numRead = zzReader.read(zzBuffer, zzEndRead, zzBuffer.length-zzEndRead); if (numRead < 0) { return true; } else { zzEndRead+= numRead; return false; } }
3
public boolean removeAt(int index) throws InvalidAccessException { DLNode current = new DLNode(); DLNode next = current.getNext(); DLNode prev = current.getPrev(); if (this.head == null) { throw new InvalidAccessException("Empty List!"); } if (index - 1 < 0) { throw new InvalidAccessException("Index < 0"); } if (this.countElements() < index) { throw new InvalidAccessException("Index > List!"); } try { if (this.elementAt(index - 1) == Integer.MIN_VALUE) { return false; } } catch (ValueException e) { return false; } if (head == tail) { head = null; tail = null; return true; } else if (index - 1 == 0) { current = head; next = current.getNext(); prev = current.getPrev(); head = next; current.setNext(null); next.setPrev(null); return true; } else if (index - 1 == this.countElements() - 1) { current = tail; next = current.getNext(); prev = current.getPrev(); prev.setNext(null); current.setPrev(null); tail = prev; return true; } else { current = runToIndex(index - 1); next = current.getNext(); prev = current.getPrev(); prev.setNext(next); next.setPrev(prev); return true; } }
8
public void ActivateCognitiveGraphEX(String symbol, int matchresult){ if(symbol.equals("红色") || symbol.equals("玫瑰")){ int result; result=matchresult; //1 if(result==0)//前一个词是对象,后一个词是属性值 { //1.建立一个空节点 //2.将这个空节点链接到表示前一个词的节点后面 //3.对节点的Symbol和Relation赋值//注意,在例子中,属性名只有颜色。所以这里就把过程简单化了,否则应该检查属性名是什么 //1 reiMainSpace.ActivateNewNodeInCognitiveGraph(); //2 reiMainSpace.LinkInCognitiveGraph(); //3 reiMainSpace.AssignmentRelation("拥有"); reiMainSpace.AssignmentSymbolInCognitiveGraph(symbol); reiAttributeSpace.ActivateColorSpace(symbol); } else if(result==4)//前一个词是属性(名),后一个词是对象 { //1.将属性(也就是前一个词)的激活状态改为3 //2.找到对象的对应属性(这样说起来,“拥有”和“属于”其实有很大的问题啊),把属性的激活状态改为3 // 2.1找到后一个词的属性,记录Symbol // 2.2根据Symbol将激活状态改为3 //1 int GraphSize=MainSpace.CognitiveGraph.size(); int second=MainSpace.GetCurrentSecondHighActivatedNodeAL(); for(int i=0;i<GraphSize;i++)//广度遍历 { int ListSize=MainSpace.CognitiveGraph.get(i).ObjOrAttri.size(); for(int ii=0;ii<ListSize;ii++) { if(MainSpace.CognitiveGraph.get(i).ObjOrAttri.get(ii).ActivatedLevel==second)//20131024 这里需要修改 { MainSpace.CognitiveGraph.get(i).ObjOrAttri.get(ii).ActivatedLevel=6; } } } reiMainSpace.ActivateCognitiveGraph(symbol,0); } else { ; } } }
7
public void read(Node node) { while (node != null) { if (node instanceof Element) { Element elt = (Element) node; IElementHandler handler = handlers.get(elt.getNodeName()); if (handler != null) { handler.parseElement(elt); } } node = node.getNextSibling(); } }
3
public Player playGame(Player player1, Player player2) { Game game = new Game(player1, player2); Player winner = game.play(); score(winner); return winner; }
0
public boolean search(String word) { if (word == null || word.length() == 0) return false; int len = 0; TrieNode node = root; while (len < word.length()) { boolean found = false; for (int i = 0; i < node.nodes.size(); i++) { if (node.nodes.get(i).val.equals(String.valueOf( word.charAt(len)))) { node = node.nodes.get(i); found = true; break; } } if (!found) return false; len = len + 1; } if (node.nodes.size() == 0) return true; else return false; }
7
public void loadData() { int v = 1; String s = ""; Integer i = 0; Integer l = 1; try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(this.getDataFolder() + "/ControllerBlock.dat"), "UTF-8")); String version = in.readLine().trim(); if (version.equals("# v2")) { v = 2; } else if (version.equals("# v3")) { v = 3; } else if (version.equals("# v4")) { v = 4; } else { --l; } while ((s = in.readLine()) != null) { ++l; if (s.trim().isEmpty()) continue; CBlock newBlock = new CBlock(this, v, s.trim()); if (newBlock.getLoc() != null) { blocks.add(newBlock); ++i; } else { log.severe("Error loading ControllerBlock on line " + l); } } in.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { // Don't do anything if the file wasn't found //e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } log.info("Loaded v" + v + " data - " + i + " ControllerBlocks loaded"); }
9
public String getText(Player other) { if ((other.getCurrentY()+1) == getCurrentY()) { if ((other.getCurrentX()) == getCurrentX()) { return text; } } if ((other.getCurrentY()-1) == getCurrentY()) { if ((other.getCurrentX()) == getCurrentX()) { return text; } } if ((other.getCurrentX()+1) == getCurrentX()) { if ((other.getCurrentY()) == getCurrentY()) { return text; } } if ((other.getCurrentX()-1) == getCurrentX()) { if ((other.getCurrentY()) == getCurrentY()) { return text; } } return ""; }
8
private void carregaVariaveis() { lblNome.setText(at.getNome()); lblNumVisualizacoes.setText("" + (at.getNumeroVisualizacoes() + 1)); if(at.getClassificacao()==0){ lblPontuacao.setText(bundle.getString("Sem_Classificacao")); }else{ lblPontuacao.setText("" + at.getClassificacao()); } if (linguagem.equals("en")) { tpDesc.setText(at.getDescricaoEn()); } else { tpDesc.setText(at.getDescricaoPt()); } pnImagem.setLayout(new BoxLayout(pnImagem, BoxLayout.PAGE_AXIS)); try { PnlConjuntoImagens mostrarImagens = new PnlConjuntoImagens(at); pnImagem.add(mostrarImagens.PnlVisualizadorImagens()); } catch (Exception e) { pnImagem.add(new PnlImagem("/images/default.jpg", 300, 300)); } if (at instanceof Monumento) { pnMini.add(new PnMiniMonumentos(at, linguagem)); } if (at instanceof Hotel) { pnMini.add(new PnMiniHotel(at, linguagem)); } if (at instanceof Restaurante) { pnMini.add(new PnMiniRestaurante(at, linguagem)); } if (at instanceof Evento) { pnMini.add(new PnMiniEvento(at, linguagem)); } if (utilizador != null) { cbPontuacao.setSelectedIndex(at.getClassificacao(utilizador)); } ListaAtracoes lstAtracoes = new ListaAtracoes(); lstAtracoes.adicionarVisualizacao(at); lblLogIn.addMouseListener(new MouseListener() { Font font = lblLogIn.getFont(); Map attributes = font.getAttributes(); @Override public void mouseClicked(MouseEvent e) { JdlLogIn LogIn = new JdlLogIn(linguagem); LogIn.setVisible(true); if (LogIn.getUtilizador() != null) { componentesVisiveis(true); } revalidate(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); lblLogIn.setFont(font.deriveFont(attributes)); setCursor(new Cursor(Cursor.HAND_CURSOR)); } @Override public void mouseExited(MouseEvent e) { lblLogIn.setFont(font); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); lblRegistar.addMouseListener(new MouseListener() { Font font = lblLogIn.getFont(); Map attributes = font.getAttributes(); @Override public void mouseClicked(MouseEvent e) { JdlRegisto registar = new JdlRegisto(linguagem); registar.setVisible(true); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { Map attributes = font.getAttributes(); attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); lblRegistar.setFont(font.deriveFont(attributes)); setCursor(new Cursor(Cursor.HAND_CURSOR)); } @Override public void mouseExited(MouseEvent e) { lblRegistar.setFont(font); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); lblFixoVisualizacoes.setText(bundle.getString("visualizacoes")); lblFixoPontuacao.setText(bundle.getString("Pontuacao")); }
9
@Override public boolean equals(Object object) { if (object == null) return false; if (object == this) return true; if (this.getClass() != object.getClass()) return false; PointGame point = (PointGame) object; if (this.hashCode() == point.hashCode()) return true; return false; }
4
private boolean parseHandshake(JSONObject o) throws ProtocolException { try { if(!(o.get("message").equals("connect"))){ throw new ProtocolException("Expected 'connect' handshake, but got '" + o.get("message") + "' key"); } if(!(o.getInt("revision") == 1)){ throw new ProtocolException("Wrong protocol revision: supporting 1, but got " + o.getInt("revision")); } Util.validateUsername(o.getString("name")); username = o.getString("name"); gotHandshake = true; return true; } catch (JSONException e){ throw new ProtocolException("Invalid or incomplete packet: " + e.getMessage()); } }
3
protected void sort(SimpleFeatureType featureType, SortBy[] sort, String prefix, StringBuilder sql) throws IOException { if ((sort != null) && (sort.length > 0)) { sql.append(" ORDER BY "); for (int i = 0; i < sort.length; i++) { String order; if (sort[i].getSortOrder() == SortOrder.DESCENDING) { order = " DESC"; } else { order = " ASC"; } sql.append(sort[i].getPropertyName()); sql.append(order); sql.append(","); } sql.setLength(sql.length() - 1); } }
4
@Override public void putAll( Map<? extends S, ? extends T> map ) { for (Entry<? extends S, ? extends T> e : map.entrySet()) { put( e.getKey(), e.getValue() ); } }
5
public void addConnection(PlayerMP player, Packet00Login packet){ boolean alreadyConnected = false; for(PlayerMP p : this.connectedPlayers){ if(player.getUsername().equalsIgnoreCase(p.getUsername())){ if(p.ipAddress == null){ p.ipAddress = player.ipAddress; } if(p.port == -1){ p.port = player.port; } alreadyConnected = true; } else { // relay to the current connected player that there is a new player sendData(packet.getData(),p.ipAddress,p.port); // relay to the new player that the currently connected player exists packet = new Packet00Login(p.getUsername(),p.x,p.y); sendData(packet.getData(),player.ipAddress,player.port); } } if(!alreadyConnected){ this.connectedPlayers.add(player); } }
5
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton2ActionPerformed {//GEN-HEADEREND:event_jButton2ActionPerformed if (!gameover) { if (rule.turn()) { if (rule.check(1, 0)) { rule.pressed(1, 0); if (rule.changeTurn()) { ai.takeTurn(this, rule, new Coordinate(1, 0)); if (!rule.winner().equalsIgnoreCase(winner)) { gameover = true; winner = rule.winner(); jLabel1.setText(winner); } } else { gameover = true; winner = rule.winner(); jLabel1.setText(winner); } } } } }//GEN-LAST:event_jButton2ActionPerformed
5
public int minPathSum(int[][] grid) { int m = grid.length; int n = grid[0].length; int[] answer = new int[n]; answer[0] = grid[0][0]; for (int i = 1; i < n; i++) answer[i] = grid[0][i] + answer[i - 1]; for (int j = 1; j < m; j++) { answer[0] = grid[j][0] + answer[0]; for (int i = 1; i < n; i++) { answer[i] = Math.min(answer[i], answer[i - 1]) + grid[j][i]; } } return answer[n - 1]; }
3
@Override public void rotateXMinus() { if(orientation == X) return; orientation = (orientation == Y ? Z : Y); for(int i = 0; i < others.length; i++) { IntPoint p = others[i]; others[i] = new IntPoint(p.getX(), p.getZ(), -p.getY()); } }
3
protected void stepForward(boolean showSteps) { switch (m_currentPhase) { case PHASE_PREPROCESSING: long precSize = getNumPrecomputedBlocs(); if (precSize > Integer.MAX_VALUE) { JOptionPane.showMessageDialog(null, "Number of precompiled matrix too large!", "Error", JOptionPane.ERROR_MESSAGE); return; } // it's about 550 bytes for every matrix.. int megs = (int)((double)(550 * precSize) / 1000000.0); NumberFormat nf = NumberFormat.getInstance(); String precSizeStr = nf.format(precSize); if (precSize > PRECOMPILED_WARNING_LIMIT) { int retVal = JOptionPane.showConfirmDialog(null, "Warning! The number of blocs to compute will be very large (" + precSizeStr + ").\n You will need a huge amount of memory (~" + megs + " MB).\n Do you still want to continue?", "Warning!", JOptionPane.YES_NO_OPTION); if (retVal != JOptionPane.YES_OPTION) { return; } } try { m_preprocTable = new Hashtable( (int) precSize); m_orderedKeys = new ArrayList( (int) precSize); } catch (java.lang.OutOfMemoryError e) { m_preprocTable = null; m_orderedKeys = null; Runtime.getRuntime().gc(); JOptionPane.showMessageDialog(null, "Out of memory!\n (Please give " + "a second to the garbage collector " + "to clean this mess..).\n" + "Note: Il could be unstable anyway", "Didn't I tell you? :)", JOptionPane.ERROR_MESSAGE); Runtime.getRuntime().gc(); Runtime.getRuntime().gc(); return; } PreprocessingFrame prFrm = new PreprocessingFrame(m_preprocTable, m_orderedKeys, m_t, m_encodedAlphSize, this); prFrm.show(); m_currentStep = 0; m_currentPhase = PHASE_CALC_GRID; break; case PHASE_CALC_GRID: if (m_currentStep >= m_nHBlocs * m_nVBlocs) { m_backtrackLastSel = m_dpTable.getLastCell(); // reset result string for (int i = 0; i < 3; i++) { m_resLine[i] = ""; } setInfoMessage("Backtracking Pointers. Policy used: " + CellElement.getPolicyName( m_backtrackingPolicy) + "."); m_currentPhase = PHASE_BACKTRACK; ((FRTable)m_dpTable).setShowBackgroundIndexes(false); m_dpTable.clearHighlightColors(); m_dwPanel.setVisible(true); m_l1Choiche.setVisible(true); m_l2Choiche.setVisible(true); m_l3Choiche.setVisible(true); stepFWDBackTrack(showSteps); } else { setInfoMessage("Applying preprocessed blocs. Step: " + m_currentStep); this.stepFWDCalc(showSteps); } break; case PHASE_BACKTRACK: stepFWDBackTrack(showSteps); break; } }
9
public void mouseDragged(MouseEvent e) { Rectangle bounds = getBounds(); Dimension d = getSize(); Point p = e.getPoint(); SwingUtilities.convertPointToScreen(p, e.getComponent()); int dx = p.x - lastPoint.x; int dy = p.y - lastPoint.y; switch (dragType) { case DRAG_TOP: Point loc = getLocation(); setLocation(loc.x + dx, loc.y + dy); break; case DRAG_TOP | DRAG_LEFT: invalidate(); bounds.x += dx; bounds.y += dy; bounds.width -= dx; bounds.height -= dy; setBounds(bounds); validate(); break; case DRAG_TOP | DRAG_RIGHT: invalidate(); bounds.y += dy; bounds.width += dx; bounds.height -= dy; setBounds(bounds); validate(); break; case DRAG_RIGHT: invalidate(); setSize(d.width + dx, d.height); validate(); break; case DRAG_RIGHT | DRAG_BOTTOM: invalidate(); setSize(d.width + dx, d.height + dy); validate(); break; case DRAG_BOTTOM: invalidate(); setSize(d.width, d.height + dy); validate(); break; case DRAG_BOTTOM | DRAG_LEFT: invalidate(); bounds.x += dx; bounds.width -= dx; bounds.height += dy; setBounds(bounds); validate(); break; case DRAG_LEFT: invalidate(); bounds.x += dx; bounds.width -= dx; setBounds(bounds); validate(); break; } lastPoint = p; }
8
private static List<String> readLines(String path) { ArrayList<String> lines = new ArrayList<String>(); //open file File file = new File(path); //Error if not readable if (!file.canRead()) { System.err.println("File " + file.getAbsolutePath() + " could not be read!"); System.exit(1); } BufferedReader inputStream = null; //Return lines try { inputStream = new BufferedReader(new FileReader(file)); String line; while((line = inputStream.readLine()) != null) { lines.add(line); } inputStream.close(); } catch (FileNotFoundException ex) { System.err.println(file.getAbsolutePath() + " not found!"); System.exit(1); } catch (IOException ex) { System.err.println(ex); System.exit(1); } return lines; }
4
private void displayInfo(ChunkyPlayer chunkyPlayer, CommandSender sender) { String sFirstDate = "NA"; Long lFirstDate = chunkyPlayer.getFirstLoginTime(); if (lFirstDate != 0) { sFirstDate = new Date(lFirstDate).toString(); } String sLastDate = "NA"; Long lLastDate = chunkyPlayer.getLastLoginTime(); if (lLastDate != 0) { sLastDate = new Date(lLastDate).toString(); } Language.PLAYER_MENU_TITLE.normal(sender, chunkyPlayer.getName(), sFirstDate, sLastDate, chunkyPlayer.getOwnables().get(ChunkyChunk.class.getName()).size(), chunkyPlayer.getChunkClaimLimit()); HashSet<ChunkyObject> chunks = chunkyPlayer.getOwnables().get(ChunkyChunk.class.getName()); if (chunks != null && chunks.size() > 0) { Language.PLAYER_MENU_OWNEDCHUNKS.normal(sender); String message = ""; int i = 0; for (ChunkyObject o : chunks) { ChunkyChunk chunk = (ChunkyChunk) o; message += "[" + chunk.getCoord().getX() + "," + chunk.getCoord().getZ() + "] "; i += 1; if (i == 6) { i = 0; message += "n"; } } for (String s : message.split("n")) { Language.sendMessage(chunkyPlayer, s.trim()); } } displayGlobalPermissions(chunkyPlayer, sender); }
7
public boolean fieldContainsThisPlayersPiece(Field field, Player playersTurn) { return field.hasPiece() && field.getPiece().isWhite == playersTurn.isWhite; }
1
public void swap() { Item itm1 = new NoItem(); Item itm2 = new NoItem(); int Itm1W = 0; int Itm1H = 0; int Itm2W = 0; int Itm2H = 1; int amount = 1; for (int h = 0; h < ItemH; h++) { for (int w = 0; w < ItemW; w++) { if (ITEMS[h][w].isSelected) { if (amount == 1) { itm1 = ITEMS[h][w]; Itm1W = w; Itm1H = h; amount++; } else if (amount == 2) { itm2 = ITEMS[h][w]; Itm2W = w; Itm2H = h; amount++; } } } } ITEMS[Itm1H][Itm1W] = itm2; ITEMS[Itm2H][Itm2W] = itm1; // System.out.println("1: "+ITEMS[Itm1H][Itm1W]); // System.out.println("2: "+ITEMS[Itm2H][Itm2W]); for (int h = 0; h < ItemH; h++) { for (int w = 0; w < ItemW; w++) { ITEMS[h][w].isSelected = false; } } swapped = true; }
7
public void mouseDragged(MouseEvent pEvent) { //Only One drag can occur at a time if(currentDragComponent != pEvent.getComponent() || currentDragComponent==null) return; //This info is all in the context of the Current Drag Component Point _point = pEvent.getPoint(); Point _newLoc = null; if(currentDragOffSet == null) { _newLoc = new Point(_point.x - currentDragPoint.x, _point.y - currentDragPoint.y); } else { _newLoc = new Point(_point.x - currentDragPoint.x, _point.y - currentDragPoint.y); _newLoc.translate(currentDragOffSet.x, currentDragOffSet.y); } //Update Drag Window Location SwingUtilities.convertPointToScreen(_newLoc, currentDragComponent); currentDragWindow.setLocation(_newLoc); if(dragStarted == false) { dragStarted = true; currentDragWindow.toFront(); currentDragWindow.setVisible(true); } //Get Drop Target SwingUtilities.convertPointToScreen(_point, currentDragComponent); DropTarget _dropTarget = getDropTarget(_point); //No drop target found just return; if(_dropTarget == null) return; //Convert Point to context of Drop Component Component _dropComp = _dropTarget.getComponent(); //SwingUtilities.convertPointToScreen(_point, currentDragComponent); if(_dropComp != null) { SwingUtilities.convertPointFromScreen(_point, _dropComp); } //Notify Drop Target and Source if((_dropTarget instanceof DCDropTarget) == false) return; DropTargetDragEvent _targetDragEvent = null; if(currentDropTarget != _dropTarget) { //Send Enter to new Drop Target currentDropContext = ((DCDropTarget)_dropTarget).createDropTargetContext(); _targetDragEvent = new DropTargetDragEvent(currentDropContext, _point, DnDConstants.ACTION_MOVE, DnDConstants.ACTION_COPY_OR_MOVE); _dropTarget.dragEnter(_targetDragEvent); //Send Exit to old Drop Target if(currentDropTarget != null) { currentDropTarget.dragExit(new DropTargetEvent(currentDropContext)); } //Update the current target currentDropTarget = _dropTarget; } else { _targetDragEvent = new DropTargetDragEvent(currentDropContext, _point, DnDConstants.ACTION_MOVE, DnDConstants.ACTION_COPY_OR_MOVE); } currentDropTarget.dragOver(_targetDragEvent); }
9
public static MapNode crossing(MapNode from, MapNode to, Set<MapNode> neighbors, double direction) { direction = normalize(direction); if (neighbors.size() == 1) { return from; } else if (neighbors.size() == 2) { Iterator<MapNode> iterator = neighbors.iterator(); MapNode tmp = iterator.next(); if (tmp == from) { return iterator.next(); } else { return tmp; } } else if (neighbors.size() > 2) { Vector2d origin = direction(from, to); MapNode result = null; double min = Double.MAX_VALUE; for (MapNode neighbor : neighbors) { Vector2d way = direction(to, neighbor); double angle = normalize(angle(origin, way)); double distance = distance(direction, angle); if (min > distance) { result = neighbor; min = distance; } } return result; } else { throw new IllegalArgumentException("illegal neighbor count"); } }
6
static void initialize() { try { SHIP = ImageIO.read(SpaceShooter.class.getResourceAsStream("img/player/ship.png")); MISSILE = ImageIO.read(SpaceShooter.class.getResourceAsStream("img/player/missile.png")); PLASMA = ImageIO.read(SpaceShooter.class.getResourceAsStream("img/enemy/plasma.png")); DRONE = ImageIO.read(SpaceShooter.class.getResourceAsStream("img/enemy/drone.png")); ALIEN = ImageIO.read(SpaceShooter.class.getResourceAsStream("img/enemy/alien.png")); MOTHERSHIP = ImageIO.read(SpaceShooter.class.getResourceAsStream("img/enemy/mothership.png")); HEALTH = ImageIO.read(SpaceShooter.class.getResourceAsStream("img/debris/health.png")); for (int i = 0; i < ASTEROID_SPRITES; i++) ASTEROID[i] = ImageIO.read(SpaceShooter.class.getResourceAsStream("img/debris/asteroid" + i + ".png")); for (int i = 0; i < EXPLOSION_SPRITES; i++) EXPLOSION[i] = ImageIO.read(SpaceShooter.class.getResourceAsStream("img/explosions/explosion" + i + ".png")); for (int i = 0; i < ROCK_SPRITES; i++) ROCK[i] = ImageIO.read(SpaceShooter.class.getResourceAsStream("img/debris/rock" + i + ".png")); for (int i = 0; i < METAL_SPRITES; i++) METAL[i] = ImageIO.read(SpaceShooter.class.getResourceAsStream("img/debris/metal" + i + ".png")); } catch (IOException ex) { System.err.println(ex); } }
5
private void addGroupBySelectedFields() { DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) ((BrowserItems.DefaultTreeItem) node.getParent()).getFirstChild(); for (int i = 0; i < selectNode.getChildCount() ; i++) { BrowserItems.DefaultTreeItem item = (BrowserItems.DefaultTreeItem)selectNode.getChildAt(i); if (item.getUserObject() instanceof QueryTokens._Expression) { final QueryTokens._Expression itemToken = (QueryTokens._Expression)item.getUserObject(); // should take all columns and functions/ operations that are not aggregate functions // ( count, sum, avg, min, max ) example: select 1, f(a), 'gg', count(*) from group by 1, // f(a), 'gg' boolean addToGroupby = false; if (itemToken instanceof QueryTokens.Column) { addToGroupby = true; } else if (itemToken instanceof QueryTokens.DefaultExpression) { final String val = ((QueryTokens.DefaultExpression)itemToken).getValue(); if (val!=null) { addToGroupby = true; final String valLower = val.toLowerCase(); for (final String aggregate : QueryBuilderPane.AGGREGATE_FUNCTIONS) { if (valLower.startsWith(aggregate.toLowerCase())) { addToGroupby = false; break; } } } } if (addToGroupby) { queryBuilderPane.sqlBrowserViewPanel.addGroupByClause(new QueryTokens.Group(itemToken)); } } } }
8
public static int[][][] fillTable(String seq1, String seq2, String seq3, Map<String, Integer> matrix, int g) { int[][][] scoreTable = new int[seq1.length()+1][seq2.length()+1][seq3.length()+1]; scoreTable[0][0][0]=0; int[][] score2 = linearAlignment.fillTableLinear(seq1,seq2,matrix,g); for(int i =0; i<=seq1.length();i++){ for(int j = 0;j<=seq2.length();j++){ scoreTable[i][j][0]= score2[i][j]+(i+j)*g; } } score2 = linearAlignment.fillTableLinear(seq1,seq3,matrix,g); for(int i =0; i<=seq1.length();i++){ for(int j = 0;j<=seq3.length();j++){ scoreTable[i][0][j]= score2[i][j]+(i+j)*g; } } score2 = linearAlignment.fillTableLinear(seq2,seq3,matrix,g); for(int i =0; i<=seq3.length();i++){ for(int j = 0;j<=seq2.length();j++){ scoreTable[0][i][j]= score2[i][j]+(i+j)*g; } } for(int i = 1; i<=seq1.length();i++){ for(int j = 1; j<=seq2.length();j++){ for(int k = 1; k<=seq3.length();k++){ int v1,v2,v3,v4,v5,v6,v7; String vij = "" + seq1.charAt(i - 1) + seq2.charAt(j - 1); String vjk = "" + seq2.charAt(j - 1) + seq3.charAt(k - 1); String vik = "" + seq3.charAt(k - 1) + seq1.charAt(i - 1); v1=scoreTable[i-1][j-1][k-1]+matrix.get(vij)+matrix.get(vjk)+matrix.get(vik); v2=scoreTable[i-1][j-1][k]+matrix.get(vij)+2*g; v3=scoreTable[i-1][j][k-1]+matrix.get(vik)+2*g; v4=scoreTable[i][j-1][k-1]+matrix.get(vjk)+2*g; v5=scoreTable[i-1][j][k]+2*g; v6=scoreTable[i][j-1][k]+2*g; v7=scoreTable[i][j][k-1]+2*g; scoreTable[i][j][k] = Util.min7(v1,v2,v3,v4,v5,v6,v7); } } } return scoreTable; }
9
public void createDirectory() { File file = new File(source); if (!file.exists()) { if (file.mkdir()) { System.out.println("Directory is created!"); } else { System.out.println("Failed to create directory!"); } } }
2
public boolean claimAnimal(Player p, Entity animal, ItemMeta meta){ String owner = p.getUniqueId().toString(); String pet = animal.getUniqueId().toString(); if(!plugin.getAnimalData().contains("Farmer." + owner + ".Animals")){ plugin.getAnimalData().set("Farmer."+ owner + ".Name", p.getName() + ".Animals"); plugin.saveAnimalData(); } if(this.canHaveMoreAnimals(p)){ if(this.checkIfHasSameName(owner, meta.getDisplayName())){ plugin.getAnimalData().set("Farmer."+ owner + ".Animals." + pet + ".Name", meta.getDisplayName()); plugin.getAnimalData().set("Farmer."+ owner + ".Animals." + pet + ".Owner", p.getName()); plugin.getAnimalData().set("Farmer."+ owner + ".Animals." + pet + ".OwnerID", owner ); plugin.getAnimalData().set("Farmer."+ owner + ".Animals." + pet + ".HeartPoints", 0 ); plugin.getAnimalData().set("Farmer."+ owner + ".Animals." + pet + ".Hunger", true ); plugin.getAnimalData().set("Farmer."+ owner + ".Animals." + pet + ".Healthy", true ); plugin.getAnimalData().set("Farmer."+ owner + ".Animals." + pet + ".Happy", true ); plugin.getAnimalData().set("Farmer."+ owner + ".Animals." + pet + ".Washed", false ); plugin.getAnimalData().set("Farmer."+ owner + ".Animals." + pet + ".isPet", true ); plugin.getAnimalData().set("Farmer."+ owner + ".Animals." + pet + ".WillDie", false); plugin.getAnimalData().set("Farmer."+ owner + ".Animals." + pet + ".Age", 0); plugin.getAnimalData().set("Farmer."+ owner + ".Animals." + pet + ".Weight", 40); plugin.saveAnimalData(); p.sendMessage(ChatColor.BLUE + "You now own " + meta.getDisplayName() + "!"); return true; }else{ p.sendMessage(ChatColor.RED + "You cannot name two animals the same name"); LivingEntity an = (LivingEntity)animal; an.setCustomName(null); return false; } }else{ p.sendMessage(ChatColor.RED + "You Have to many animals you cannot claim anymore"); return false; } }
3
@Override public boolean equals(Object obj) { if (!(obj instanceof ChunkyCoordinates)) return false; ChunkyCoordinates coords = (ChunkyCoordinates) obj; return coords.getWorld().equals(this.getWorld()) && coords.getX() == this.x && coords.getZ() == this.z; }
3
@Override public void run(){ while(true){ if(running){ try { sleep(500); loadChannel(); } catch (Exception e) { e.printStackTrace(); } } } }
3
@Override public void mouseMove(MouseEvent e) { if(this.getMouseListener() != null) { this.getMouseListener().MouseMove(this, e); } }
1