text
stringlengths
14
410k
label
int32
0
9
public LocalInfo getLocalInfo() { if (shadow != null) { while (shadow.shadow != null) { shadow = shadow.shadow; } return shadow; } return this; }
2
public MeasureKitInteger(DataStructures inData){ this.inData = inData; outData = new DataArrays<Integer[]>(); }
0
public boolean interact(Level level, int xt, int yt, Player player, Item item, int attackDir) { if (item instanceof ToolItem) { ToolItem tool = (ToolItem) item; if (tool.type == ToolType.shovel) { if (player.payStamina(4 - tool.level)) { level.setTile(xt, yt, Tile.dirt, 0); return true; } } } return false; }
3
private void update(DocumentEvent e) { try { int value = Integer.valueOf(textField.getText()); if (value < 0 || value > 255) { throw new NumberFormatException(); } if (value != slider.getValue()) { slider.setValue(value); } textField.setForeground(Color.BLACK); } catch (NumberFormatException e1) { textField.setForeground(Color.RED); } }
4
protected void addPossibleMovesInDirection(final List<Move> result, final int fileStep, final int fileBorder, final int rankStep, final int rankBorder) { // Catch the condition for infinite loops. // IMPROVE add additional sanity checking if necessary if (fileStep == 0 && rankStep == 0) { throw new IllegalArgumentException( "Passing only zeros to the directional parameters would make this method run infinitely"); } for (int file = this.getCoord().getFile(), rank = this.getCoord() .getRank(); file - fileStep != fileBorder && rank - rankStep != rankBorder; file += fileStep, rank += rankStep) { final Move possibleMove = defaultCorrectMoveTypeForValidCoord(Coords .coord(file, rank)); if (possibleMove != null) { result.add(possibleMove); } final Piece targetCoordPiece = pos.getPieceAt(file, rank); if (targetCoordPiece != null) { break; } } }
6
private boolean parseDay() { boolean parsingSuccessful = true; d = new Day(); if(existing) { d.setDayID(id); } try { d.setDate(StrUtil.dateParser(dateF.getText())); } catch (Exception ex) { parsingSuccessful = false; MesDial.dateError(this); Logger.getLogger(DayFrame.class.getName()).log(Level.SEVERE, null, ex); } try { d.setExpenses(Double.valueOf(expensesF.getText())); } catch (Exception x) { parsingSuccessful = false; MesDial.doubleError(this); Logger.getLogger(DayFrame.class.getName()).log(Level.SEVERE, null, x); } d.setSummary(summaryArea.getText()); if (sexChk.isSelected()) { d.setSex(1); } else { d.setSex(0); } if (workChk.isSelected()) { d.setWork(1); } else { d.setWork(0); } if (funChk.isSelected()) { d.setFun(1); } else { d.setFun(0); } if (specialChk.isSelected()) { d.setSpecial(1); } else { d.setSpecial(0); } if (alcoholChk.isSelected()) { d.setAlcohol(1); } else { d.setAlcohol(0); } if (practiceChk.isSelected()) { d.setPractice(1); } else { d.setPractice(0); } return parsingSuccessful; }
9
public void listWhispers(){ ChannelTree tmp; Channel chan; String str; for(long id : channelManager.getTree().keySet()){ tmp = channelManager.getChannel(id); if(tmp instanceof Channel){ str = ""; if(((Channel) tmp).isWhisper()){ chan = (Channel)tmp; str += " " + id + " - " + chan.getName() + " - owner : " + chan.getOwner().getUsername() +" - users : "; for(String username : chan.getUsers()){ str += "\n" + getUser(username).getId()+ " - "+getUser(username); } System.out.println(str); } } } }
4
@Override protected void runChild(final FrameworkMethod method, RunNotifier notifier) { Description description = describeChild(method); CompilationUnit compilationUnit = getCompilationUnit(description); if(compilationUnit == null){ throw new KoanError("Failed to load Koan"); } String classSource = KoanReader.getSourceByClass(description.getTestClass()); KoanExecution koanExecution = new KoanExecution(method, classSource); if (koanExecution.isToBeEnlightened() && koanExecution.isToBeVexed()) { notifier.fireTestFailure(new Failure(description, new KoanError("@Vex and @Enlighten are mutually exclusive"))); ignoreTest(notifier, description); return; } if (!isValidKoan(compilationUnit, koanExecution)) { notifier.fireTestFailure(new Failure(description, new KoanError("Koan is missing start " +START_MARKER+ " and end " +END_MARKER+ " markers"))); ignoreTest(notifier, description); return; } if (koanExecution.isToBeEnlightened()) { determineSolution(description.getTestClass(), koanExecution); updateKoanSource(koanExecution, description); System.out.println("Koan "+method.getName()+" is ignored as currently marked with @Enlighten"); } if (koanExecution.isToBeVexed()) { determineProblem(description.getTestClass(), koanExecution); updateKoanSource(koanExecution, description); System.out.println("Koan "+method.getName()+" is ignored as currently marked with @Vex"); } if (koanExecution.isIgnored()) { ignoreTest(notifier, description); } else { runLeaf(methodBlock(method), description, notifier); } }
7
@Override public void mouseMoved(MouseEvent e) { positionMouse = new Point2D.Float(e.getX() - offset, e.getY() - offset); if (selectedObject != null) { DragDirection cursorDir = selectedObject.isInsideBorder(positionMouse); if (cursorDir == DragDirection.EAST) { this.setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR)); } else if (cursorDir == DragDirection.WEST) { this.setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR)); } else if (cursorDir == DragDirection.NORTH) { this.setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR)); } else if (cursorDir == DragDirection.SOUTH) { this.setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); } else if (cursorDir == DragDirection.SOUTHEAST || cursorDir == DragDirection.NORTHWEST) { this.setCursor(Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR)); } else if (cursorDir == DragDirection.SOUTHWEST || cursorDir == DragDirection.NORTHEAST) { this.setCursor(Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR)); } else { this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } }
9
public void getNeighbours(final ArrayList<Space> spaces, final Space center, final Criterion criterion) { if(intersects(center)) { if(!criterion.permitDiagonal) { final float epsilon = 0.01f; Rectangle i = intersection(center); if(i.width < epsilon && i.height < epsilon) { return; } } switch(getCriterionReponse(criterion)) { case PASS: if(this != center) { spaces.add(this); } break; case DISBURSE: disburse(); assert !isLeaf(); for(Space space : nodes) { space.getNeighbours(spaces, center, criterion); } break; } } }
8
public void run(){ try { String response; this.write("NEW " + user); if(this.read().equals("OK")){ while (! isInterrupted()) { this.write("INFO"); response = this.read(); if(response.startsWith("ERROR")){ break; }else if(response.startsWith("LIST")){ this.hostList = new HashSet<String>(); this.userList = new ArrayList<String>(); String user = ""; String[] splited = response.substring(7).split(" "); for(Integer i=0; i<splited.length; i++){ if(i%2 == 0){ this.hostList.add(splited[i]); }else{ user += splited[i] + "\n"; this.userList.add(splited[i]); } } this.chat.setUsers(user); } try { this.sleep(5000); } catch (InterruptedException e) { interrupt(); } } } this.write("BYE"); this.read(); this.socket.close(); System.exit(0); } catch (IOException e) {} }
8
private Vector<Utils.Identifier> getIdentifiers(Vector<Utils.Identifier> v1, Vector<Utils.Identifier> v2) { Vector<Utils.Identifier> res = new Vector<Utils.Identifier>(); if (v1.isEmpty()) { for (Utils.Identifier iden : v2) { Vector<Utils.Identifier> vect = new Vector<Utils.Identifier>(); vect.add(iden); res.add(rules.getKey(vect)); } } else if (v2.isEmpty()){ for (Utils.Identifier identifier : v1) { Vector<Utils.Identifier> vect = new Vector<Utils.Identifier>(); vect.add(identifier); res.add(rules.getKey(vect)); } } for (Utils.Identifier identifier : v1) { for (Utils.Identifier iden : v2) { Vector<Utils.Identifier> vect = new Vector<Utils.Identifier>(); vect.add(identifier); vect.add(iden); res.add(rules.getKey(vect)); } } return res; }
6
public void setGeometries(List<GeoJsonObject> geometries) { this.geometries = geometries; }
0
protected void dataAttributeChanged(final BPKeyWords keyWord, final Object value) { if (value != null) { if (keyWord == BPKeyWords.UNIQUE_NAME) { this.uniqueNameTf.setText((String) value); } else if (keyWord == BPKeyWords.NAME) { this.nameTf.setText((String) value); } else if (keyWord == BPKeyWords.DESCRIPTION) { this.descriptionTa.setText((String) value); } else if (keyWord == BPKeyWords.DATA) { this.dataTa.setText((String) value); } } }
5
public static boolean adjustOutputPath(File outputDir, Object comp, Logger log) { boolean adjusted = false; ComponentAccess cp = new ComponentAccess(comp); for (Access in : cp.inputs()) { String fieldName = in.getField().getName(); Class fieldType = in.getField().getType(); if (fieldType == File.class) { Role role = in.getField().getAnnotation(Role.class); if (role != null && Annotations.plays(role, Role.OUTPUT)) { try { File f = (File) in.getField().get(comp); if (f != null && !f.isAbsolute()) { f = new File(outputDir, f.getName()); in.setFieldValue(f); adjusted = true; if (log.isLoggable(Level.CONFIG)) { log.config("Adjusting output for '" + fieldName + "' to " + f); } } } catch (Exception ex) { throw new ComponentException("Failed adjusting output path for '" + fieldName); } } } } return adjusted; }
8
@Override public final boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof UniqueID) { UniqueID other = (UniqueID) obj; return mSubID == other.mSubID && mTimeStamp == other.mTimeStamp; } return false; }
3
public void visit_ior(final Instruction inst) { stackHeight -= 2; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } stackHeight += 1; }
1
private void setBombs() { int x, y; final Random random = new Random(); final Tiles tiles = mField.getTiles(); final byte bombId = tiles.getBomb().getId(); for (int i = 0; i < mBombs; i++ ) { x = random.nextInt(mWidth); y = random.nextInt(mHeight); if (mField.getTileValue(x, y).isBomb()) i-- ; else { mField.setTile(x, y, bombId); for (int tile : mField.getBorderOf(x, y)) { byte tileId = mField.getTile(tile); mField.setTile(tile, tiles.get(tileId).getNextId()); } } } }
3
private void addTypeAdaptersForDate(String datePattern, int dateStyle, int timeStyle, List<TypeAdapterFactory> factories) { DefaultDateTypeAdapter dateTypeAdapter; if (datePattern != null && !"".equals(datePattern.trim())) { dateTypeAdapter = new DefaultDateTypeAdapter(datePattern); } else if (dateStyle != DateFormat.DEFAULT && timeStyle != DateFormat.DEFAULT) { dateTypeAdapter = new DefaultDateTypeAdapter(dateStyle, timeStyle); } else { return; } factories.add(TreeTypeAdapter.newFactory(TypeToken.get(Date.class), dateTypeAdapter)); factories.add(TreeTypeAdapter.newFactory(TypeToken.get(Timestamp.class), dateTypeAdapter)); factories.add(TreeTypeAdapter.newFactory(TypeToken.get(java.sql.Date.class), dateTypeAdapter)); }
4
@Override public void removerIntNota(ItensNota intensNot) throws ClassNotFoundException, SQLException,Exception { dados.removerIntNota(intensNot); if(intensNot.getQtdComprada()<=0){ throw new ItensNotaException("Quantidade Comprada nao pode ser menor ou igual zero"); } if(intensNot.getValorUnit()<0){ throw new ItensNotaException(" Valor unitario Não poder ser Zero"); } if(intensNot.getProduto().getCodProduto()<0){ throw new ItensNotaException(" o Codigo do Produto não Pode ser menor que zero"); } }
3
public static MessageQueue getInstance() { if (uniqueInstance == null) { synchronized (MessageQueue.class) { if (uniqueInstance == null) { uniqueInstance = new MessageQueue(); } } } return uniqueInstance; }
2
private void init(){ // Focus on the screen automatically requestFocus(); BufferedImageLoader loader = new BufferedImageLoader(); try{ BufferedImage headers_image = loader.loadImage("/sprite_sheet_header.png"); header_ss = new SpriteSheet(headers_image); background = loader.loadImage("/background.jpg"); } catch(IOException e){ System.out.println("error loading background and spritesheet"); } menu = new Menu(this); mRegion = new Rectangle(10,10); game = new Game(this, header_ss, h); addMouseListener(new MouseInput(this)); }
1
static final void method2181(long l, int i, int i_13_, int i_14_, int i_15_, Widget class46, int i_16_, int i_17_, aa var_aa) { try { anInt3686++; int i_18_ = i_14_ * i_14_ + i_16_ * i_16_; if (((long) i_18_ ^ 0xffffffffffffffffL) >= (l ^ 0xffffffffffffffffL)) { if (i_13_ > -49) method2178(null, -119, null, 58); int i_19_ = Math.min(((Widget) class46).anInt709 / 2, ((Widget) class46).anInt789 / 2); if (i_18_ > i_19_ * i_19_) { i_19_ -= 10; int i_20_; if (Class348_Sub40_Sub21.anInt9282 == 4) i_20_ = (int) AbtractArchiveLoader.aFloat3938 & 0x3fff; else i_20_ = 0x3fff & ((int) AbtractArchiveLoader.aFloat3938 + r_Sub2.anInt10483); int i_21_ = Class70.sineTable[i_20_]; int i_22_ = Class70.cosineTable[i_20_]; if ((Class348_Sub40_Sub21.anInt9282 ^ 0xffffffff) != -5) { i_22_ = i_22_ * 256 / (FloatBuffer.anInt9750 - -256); i_21_ = 256 * i_21_ / (FloatBuffer.anInt9750 - -256); } int i_23_ = i_22_ * i_16_ + i_21_ * i_14_ >> 1642038190; int i_24_ = i_22_ * i_14_ + -(i_21_ * i_16_) >> -1022541042; double d = Math.atan2((double) i_23_, (double) i_24_); int i_25_ = (int) ((double) i_19_ * Math.sin(d)); int i_26_ = (int) (Math.cos(d) * (double) i_19_); Class200.aClass105Array2640[i_17_].method981 (((float) ((Widget) class46).anInt709 / 2.0F + (float) i_15_ + (float) i_25_), ((float) i + (float) ((Widget) class46).anInt789 / 2.0F - (float) i_26_), 4096, (int) (65535.0 * (-d / 6.283185307179586))); } else Class151.method1211(i, Class59_Sub1.aClass105Array5294[i_17_], i_15_, class46, var_aa, i_14_, 2, i_16_); } } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("vp.D(" + l + ',' + i + ',' + i_13_ + ',' + i_14_ + ',' + i_15_ + ',' + (class46 != null ? "{...}" : "null") + ',' + i_16_ + ',' + i_17_ + ',' + (var_aa != null ? "{...}" : "null") + ')')); } }
8
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(PFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PFrame.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 PFrame().setVisible(true); } }); }
6
public static void main(String[] args) { MaxSubArray msa = new MaxSubArray(); int[] msa1 = { 2, 6, -5, 7, -9, -3 }; System.out.println(msa.maxSubArray(msa1)); System.out.println(msa.maxSubArray2(msa1)); System.out.println(msa.maxSubArray3(msa1)); BestTimeToBuyAndSell bttbas = new BestTimeToBuyAndSell(); int[] btta = { 8, 4, 9, 10, 13 }; System.out.println("maxProfit " + bttbas.maxProfit(btta)); System.out.println("maxProfit " + bttbas.maxProfit2(btta)); System.out.println("maxProfit " + bttbas.maxProfit3(btta)); System.out.println("maxProfit " + bttbas.maxProfit4(btta)); LongestCommonSequence lcs = new LongestCommonSequence(); int[] lcsa1 = { 8, 4, 9, 10, 7, 0 }; int[] lcsa2 = { 8, 1, 4, 6, 10, 9, 5 }; int[] lcsr = lcs.getLongestCommonSequence(lcsa1, lcsa2); for (int tmp : lcsr) System.out.print(tmp + " "); System.out.println(); LongestCommonSubstring lcsub = new LongestCommonSubstring(); lcsub.getLongestCommonSubstring("abcaedf", "wvscaedfgkl"); LongestIncreasingSequence lis = new LongestIncreasingSequence(); int[] lisa1 = { 8, 1, 2, 4, 3, 10, 0, 5 }; int[] lisr = lis.getLongestIncreasingSequence(lisa1); for (int tmp : lisr) System.out.print(tmp + " "); System.out.println(); int[] lisa2 = { 8, 1, 2, 4, 3, 10, 0, 5 }; int lisr2 = lis.getLongestIncreasingSequenceDP(lisa2); System.out.println("LIS: " + lisr2); JumpGame jg = new JumpGame(); int[] jg1 = { 2, 3, 1, 1, 4 }; System.out.println("can jump? " + jg.canJump(jg1)); System.out.println("min jump: " + jg.jump(jg1)); }
2
@Override protected Interactable.Result unhandledKeyboardEvent(Key key) { if(getSelectedIndex() == -1) return Interactable.Result.DO_NOTHING; if(key.getKind() == Key.Kind.Enter || key.getCharacter() == ' ') { checkedIndex = getSelectedIndex(); } return Interactable.Result.DO_NOTHING; }
3
public boolean analyze(String str){ if(!stack.isEmpty()){ stack = new Stack(stackSize); } for (int i = 0; i < str.length(); i++){ if (str.charAt(i) == '('){ stack.push('('); } if (str.charAt(i) == ')') { if (stack.isEmpty()){ System.out.print("Invalid balance (close bracket without open bracket)"); return false; } else { stack.pop(); } } } if (!stack.isEmpty()){ System.out.print("Invalid balance (open bracket without close bracket)"); return false; } return true; }
6
@Override public Move[] getMoves(Location l, Peice[][] board) { Location[] loc = new Location[8]; loc[0]= new Location(l.x-1,l.y-2); loc[1]= new Location(l.x-2,l.y-1); loc[2]= new Location(l.x+1,l.y-2); loc[3]= new Location(l.x+2,l.y-1); loc[4]= new Location(l.x-1,l.y+2); loc[5]= new Location(l.x-2,l.y+1); loc[6]= new Location(l.x+1,l.y+2); loc[7]= new Location(l.x+2,l.y+1); int k=0; for(int i =0;i<8;i++){ if(loc[i].x>=0&&loc[i].x<8 && loc[i].y>=0&&loc[i].y<8 && (board[loc[i].x][loc[i].y]==null || board[loc[i].x][loc[i].y].top()!=top) )loc[k++]=loc[i]; } if(k==0)return null; Move[] moves = new Move[k]; for(int j=0;j<k;j++){ Location[] h= {l}; Location[] g= {loc[j]}; moves[j]=new Move(h,g); } return moves; }
9
public int libraryUpdate(Network A, Molecule Asub, Molecule Bsub){ int index=-1; int i = 0; while (index==-1 && i<library.size()){ index = (A.equals(library.get(i))) ? i : -1; i++; } if(index == -1){ library.add(A); index = library.size()-1; library.get(index).setMol(new Molecule( index, Asub, Bsub ) ); } return index; }
4
public static void main(String[] args) { Connection dbConnection = null; try { // Establish connection and display information about the database System.out.println("Database Information\n-----------------------------"); dbConnection = ConnectionManager.getConnection(); ConnectionManager.displayDatabaseMetadata(dbConnection); System.out.println(""); System.out.println("Database Tables\n-----------------------------"); for (String tableName : ConnectionManager.retrieveDatabaseTables(dbConnection)) { System.out.println(tableName); } System.out.println(""); // Print out summary statistics EmployeeRetriever retriever = new EmployeeRetriever(dbConnection); System.out.println("Summary Statistics\n-----------------------------"); System.out.println("Average Number of Hours Worked: " + retriever.averageNumHoursWorked()); System.out.println("Average Base Pay Rate: " + retriever.averagePayRate()); System.out.println(""); // Ask user for surname of employee to search for System.out.print("Enter surname of employee to retrieve (or \"--ALL\" for all employees): "); BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in)); String surname = inputReader.readLine(); // Based on input, retrieve all employees or look for // employees with a specific surname List<Employee> employees = null; if (surname.equals("--ALL")) { employees = retriever.allEmployees(); } else { employees = retriever.getEmployees(surname); } // Output result of query System.out.println("Found Employees\n-----------------------------"); for (Employee employee : employees) { System.out.println(employee); } } catch (Exception ex) { ex.printStackTrace(); } finally { // Ensure the connection to the database is closed if (dbConnection != null) { try { dbConnection.close(); } catch (Exception closeError) { // silently ignore connection close error } } } }
6
@Override public void keyPressed(KeyEvent e) { //To change body of implemented methods use File | Settings | File Templates. switch (e.getKeyCode()) { case KeyEvent.VK_UP: snake.setDirection(Direction.Up); break; case KeyEvent.VK_DOWN: snake.setDirection(Direction.Down); break; case KeyEvent.VK_LEFT: snake.setDirection(Direction.Left); break; case KeyEvent.VK_RIGHT: snake.setDirection(Direction.Right); break; } }
4
public static void main(String[] args){ int a = -1; int b = 1; int c = 1; int d = -1; CyberusAI ai = new CyberusAI(); for(a = -1; a > -11; a --){ for(b = 1; b < 11; b++){ for(c = 1; c < 11; c++){ for(d = -1; d > -11; d--){ int average = 0; for(int i = 0; i < 200; i ++){ AvgCyberusAI tetris = new AvgCyberusAIHelper(); ai.FACTORS = new double[]{a,b,c,d}; tetris.brains = ai; tetris.startGame(); while(tetris.tc.gameOn){System.out.print("");} average = i != 0 ? tetris.tc.rowsCleared / i : 0; sort(average, new int[]{a, b, c, d}); } System.out.println("Average: "+average+" a: "+a+" b: "+b+" c: "+c+" d: "+d); } } } } System.out.println(Arrays.toString(averages)); System.out.println(Arrays.toString(best1)); System.out.println(Arrays.toString(best2)); System.out.println(Arrays.toString(best3)); System.out.println(Arrays.toString(best4)); System.out.println(Arrays.toString(best5)); }
7
public void UpdateGame(long gameTime, Point mousePosition) { // adds a new duck to a random position if, enough time has past between the last duck if(System.nanoTime() - Duck.lastDuckTime >= Duck.timeBetweenDucks) { ducks.add(new Duck(Duck.duckLines[Duck.nextDuckLines][0] + random.nextInt(200), Duck.duckLines[Duck.nextDuckLines][1], Duck.duckLines[Duck.nextDuckLines][2], Duck.duckLines[Duck.nextDuckLines][3], duckImg)); Duck.nextDuckLines++; if(Duck.nextDuckLines >= Duck.duckLines.length) Duck.nextDuckLines = 0; Duck.lastDuckTime = System.nanoTime(); } // checks the position of each duck, if a duck passes over the frame it is being removed for(int i = 0; i < ducks.size(); i++) { ducks.get(i).Update(); if(ducks.get(i).x < 0 - duckImg.getWidth()) { ducks.remove(i); runawayDucks++; } } // checks if the mouse has been pressed if(Canvas.mouseButtonState(MouseEvent.BUTTON1)) { // handles the reload time of the gun if(System.nanoTime() - lastTimeShoot >= timeBetweenShots) { shoots++; //compares the position of the mouse with the position of each duck, if true it removes the Duck for(int i = 0; i < ducks.size(); i++) { if(new Rectangle(ducks.get(i).x + 18, ducks.get(i).y , 100, 180).contains(mousePosition)) { killedDucks++; score += ducks.get(i).score; ducks.remove(i); break; } } lastTimeShoot = System.nanoTime(); } } // handles how many ducks have escaped if(runawayDucks >= 200) Framework.gameState = Framework.GameState.GAMEOVER; }
9
@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 Student)) { return false; } Student other = (Student) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
5
public static String successOrFailure(boolean b) { if (b) return "Success"; return "Failure"; }
1
private final long ktol(final K key) { long k; if (key instanceof Long) k = (Long)key; else if (key instanceof Number) k = ((Number)key).longValue(); else if (key instanceof String) k = new BigInteger(((String)key).getBytes()).longValue(); else { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); try { ObjectOutputStream objectout = new ObjectOutputStream(byteout); objectout.writeObject( key ); } catch(IOException e) { k = 0L; } k = new BigInteger(byteout.toByteArray()).longValue(); } return k; }
4
public static void main(String args[]) { BitSet bits1 = new BitSet(16); BitSet bits2 = new BitSet(16); // set some bits for(int i=0; i<16; i++) { if((i%2) == 0) bits1.set(i); if((i%5) != 0) bits2.set(i); } System.out.println("Initial pattern in bits1: "); System.out.println(bits1); System.out.println("\nInitial pattern in bits2: "); System.out.println(bits2); // AND bits bits2.and(bits1); System.out.println("\nbits2 AND bits1: "); System.out.println(bits2); // OR bits bits2.or(bits1); System.out.println("\nbits2 OR bits1: "); System.out.println(bits2); // XOR bits bits2.xor(bits1); System.out.println("\nbits2 XOR bits1: "); System.out.println(bits2); }
3
@Override protected Object doTaskImpl(TaskMonitor monitor, ObjectRepository repository) { InstanceStream stream = (InstanceStream) getPreparedClassOption(this.streamOption); Instances cache = new Instances(stream.getHeader(), 0); monitor.setCurrentActivity("Caching instances...", -1.0); while ((cache.numInstances() < this.maximumCacheSizeOption.getValue()) && stream.hasMoreInstances()) { cache.add(stream.nextInstance()); if (cache.numInstances() % MainTask.INSTANCES_BETWEEN_MONITOR_UPDATES == 0) { if (monitor.taskShouldAbort()) { return null; } long estimatedRemainingInstances = stream .estimatedRemainingInstances(); long maxRemaining = this.maximumCacheSizeOption.getValue() - cache.numInstances(); if ((estimatedRemainingInstances < 0) || (maxRemaining < estimatedRemainingInstances)) { estimatedRemainingInstances = maxRemaining; } monitor .setCurrentActivityFractionComplete(estimatedRemainingInstances < 0 ? -1.0 : (double) cache.numInstances() / (double) (cache.numInstances() + estimatedRemainingInstances)); } } monitor.setCurrentActivity("Shuffling instances...", -1.0); cache.randomize(new Random(this.shuffleRandomSeedOption.getValue())); return new CachedInstancesStream(cache); }
7
@Override public void actionPerformed(ActionEvent e) { Object source=e.getSource(); while(((Case) source).getEstOccupe()){ this.actionPerformed(e); //genere erreur dans le console mais fonctionne } ArrayList<ArrayList<Case>> tabLignes = cartePan.getTabLignes(); Chevalier chev=cartePan.getChev(); //On cherche sur quel bouton l'utilisateur a cliqué for(int i=0;i<tabLignes.size();i++){ for(int j=0;j<tabLignes.get(0).size();j++){ if(source==tabLignes.get(i).get(j)){ tabLignes.get(chev.getPositionX()).get(chev.getPositionY()).enleverPositionChevalier(chev.getNom()); tabLignes.get(chev.getPositionX()).get(chev.getPositionY()).setEstOccupe(false); chev.setPositionX(i); chev.setPositionY(j); tabLignes.get(i).get(j).marquerPositionChevalier(chev.getNom(), Color.blue); cartePan.deplacementPossible(chev); }//fin if } } ((Case) source).setEstOccupe(true); }
4
public static void main(String[] args){ Player pl = null; try { pl = Manager.createRealizedPlayer(new URL("file:///D:\\Muzyka\\05.Pray!.mp3")); pl.getGainControl().setLevel(0.0f); } catch (NoPlayerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CannotRealizeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } float x = 1.0f; pl.start(); pl.getGainControl().setLevel(1.0f); while (true) { // x-=0.0000002f; // pl.getGainControl().setLevel(x); } }
5
public void update(double dt, int x, int y, Input ip, Vector2 camPos) throws SlickException { level.Update(camPos); if (inEditor) { if (level.UpdateEditor(new Vector2(x + camPos.X, y + camPos.Y), ip)) lightManager.init(level.getAllRooms()); } player.HandleInput(ip, dt); player.Update(); // ennemy.HandleMoves(dt, waypoints.getClosestWaypoint(player.getPos()), waypoints.getClosestWaypoints(ennemy.getPos())); // ennemy.Update(player.getCollision(), player.getVisibility()); if (ip.isKeyPressed(Input.KEY_I)) lightEnabled = !lightEnabled; else if (ip.isKeyPressed(Input.KEY_F12) && inEditor) { level.Init(); this.collision = level.Load("level.cfg"); } if (lightEnabled) lightManager.update(dt, level.getCurrentRoom(player.getPos())); }
6
private Boolean getConsoleNodeValue(final Document doc) { Node outputsNode = this.getFirstLevelNodeByTag(doc, OUTPUTS_TAG); if (outputsNode == null) { return DEFAULT_CONSOLE; } Node consoleNode = this.getNodeByTagInNode(outputsNode, CONSOLE_TAG); if (consoleNode == null) { return DEFAULT_CONSOLE; } String value = this.getNodeValue(consoleNode); if (value.isEmpty()) { return DEFAULT_CONSOLE; } return Boolean.valueOf(value); }
3
public void poistaTiedote(Tiedote t) throws DAOPoikkeus { try { TiedoteDAO tDao = new TiedoteDAO(); // Kutsutaan daoluokan poistaTiedote-metodia tDao.poistaTiedote(t.getTiedoteId()); } catch (DAOPoikkeus p) { throw new DAOPoikkeus("Tietokannasta poistaminen ei onnistunut", p); } }
1
private void readPreferences(final BufferedReader reader) throws IOException, InvalidPreferencesFormatException { final String kvPid = _application.getConnection().getLocalConfigurationAuthority().getPid(); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(byteArrayOutputStream)); String line; boolean replaceNextLine = false; boolean replaced = false; while(true){ line = reader.readLine(); if (line == null) break; if(replaced){ writer.write(line + "\n"); } else if(!replaceNextLine && line.matches("\\s*<node name=\"gtm\">")) { replaceNextLine = true; writer.write(line + "\n"); } else if(replaceNextLine && line.matches("\\s*<node name=\".+\">")) { writer.write("<node name=\"" + kvPid + "\">\n"); replaceNextLine = false; replaced = true; } else{ writer.write(line + "\n"); } } writer.close(); final byte[] buf = byteArrayOutputStream.toByteArray(); final ByteArrayInputStream inputStream = new ByteArrayInputStream(buf); Preferences.importPreferences(inputStream); }
7
public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException ex) { throw new IncompatibleClassChangeError(getClass().getName()); } }
1
public synchronized static void writeStockValues(ArrayList<Stock> stocks) { File f = new File("stocks.txt"); FileWriter fr = null; try { fr = new FileWriter(f); BufferedWriter br = new BufferedWriter(fr); String s = ""; for (Stock e : stocks) { s += e.getTickername() + " " + e.getNo() + " " + e.getPrice(); s += "\n"; } br.write(s); br.close(); } catch (IOException e) { e.printStackTrace(); } }
2
private void inhibitAdjacentOtherShapeRecognizers(int shape,int otherShape){ //System.out.println(" inhibadgy " + shape); int shapeOffset = 2500 * shape; for (int neuron = 0; neuron < 2500; neuron += 5) { int fromNeuron = neuron + shapeOffset; int fromRow = neuron / 50; if ((fromRow % 10) >= 5) {// only for bottom half. int fromBigRow = neuron / 500; int fromCol = neuron % 50; int fromBigCol = fromCol / 10; // account for other shape for (int toBigRow = fromBigRow-1; toBigRow<=fromBigRow+1; toBigRow++){ for (int toBigCol=fromBigCol-1;toBigCol<=fromBigCol+1; toBigCol++) { // not off the edge if ((toBigCol >= 0) && (toBigCol < 5) && (toBigRow >= 0) && (toBigRow < 5)) { int toBigBaseRow = toBigRow + (otherShape * 5); int toNeuron = (toBigBaseRow * 500)+((toBigCol-fromBigCol)*10); toNeuron += ((fromRow % 10) * 50) + (fromNeuron % 50); double inhibWeight = 2.0; addConnection(fromNeuron, toNeuron, inhibWeight); addConnection(fromNeuron, toNeuron + 1, inhibWeight); addConnection(fromNeuron, toNeuron + 2, inhibWeight); addConnection(fromNeuron, toNeuron + 3, inhibWeight); addConnection(fromNeuron, toNeuron + 4, inhibWeight); } } } } } }
8
private void gripperDragged(MouseEvent e) { // where are we ? @SuppressWarnings("unused") Component gripper = e.getComponent(); ToolBarPanel panel = (ToolBarPanel) this.getParent(); if(! (panel.getParent() instanceof ToolBarContainer)) { //2006/12/01 // this is a safety for users willing to include toolbar panels outside // a toolbar container (in that case, these toolbars aren't draggable). return; } ToolBarContainer container = (ToolBarContainer) panel.getParent(); Point tbPanelPoint = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), panel); if(panel.contains(tbPanelPoint)) { // we're dragging inside the same ToolbarPanel ToolBarPanelLayout layout = (ToolBarPanelLayout) panel.getLayout(); ToolBarConstraints constraints = layout.getInsertionContraintsAt(this, tbPanelPoint); if(constraints != null) { panel.remove(this); panel.add(this, constraints); panel.revalidate(); } } else { // we're outside this toolbar panel, check if we're above another toolbar // or near an empty one Rectangle containerBounds = container.getBounds(); Rectangle invisiblePanelBounds = new Rectangle(containerBounds); ToolBarPanel topPanel = (ToolBarPanel) container.getComponentAt(BorderLayout.NORTH); invisiblePanelBounds.height = 10; if(checkGripperOnOtherPanel(topPanel, e, invisiblePanelBounds)) { return; } invisiblePanelBounds.y = containerBounds.y + containerBounds.height - 10; ToolBarPanel bottomPanel = (ToolBarPanel) container.getComponentAt(BorderLayout.SOUTH); if(checkGripperOnOtherPanel(bottomPanel, e, invisiblePanelBounds)) { return; } invisiblePanelBounds.y = containerBounds.y; invisiblePanelBounds.height = containerBounds.height; invisiblePanelBounds.width = 10; ToolBarPanel leftPanel = (ToolBarPanel) container.getComponentAt(BorderLayout.WEST); if(checkGripperOnOtherPanel(leftPanel, e, invisiblePanelBounds)) { return; } invisiblePanelBounds.x = containerBounds.x + containerBounds.width - 10; ToolBarPanel rightPanel = (ToolBarPanel) container.getComponentAt(BorderLayout.EAST); if(checkGripperOnOtherPanel(rightPanel, e, invisiblePanelBounds)) { return; } } }
7
public void setFrontLeftTrim(int frontLeftTrim) { this.frontLeftTrim = frontLeftTrim; if ( ccDialog != null ) { ccDialog.getTrim1().setText( Integer.toString(frontLeftTrim) ); } }
1
private static void extractGrid(String recurso, File destino) throws IOException { if (destino.exists()){ return; } InputStream inputStream = Config.class.getClassLoader().getResourceAsStream("cat2osm/grids/"+recurso); OutputStream outputStream = new FileOutputStream(destino); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); }
1
public static boolean userOK(String input) { /* * Funktion som kollar om nickname som är angivet är ok. * Null, Server eller något som redan finns är dåligt. */ boolean svar = false; for(int i = 0; i < Main.users.size(); i++) { if(input.equalsIgnoreCase(Main.users.get(i).getNickname()) || input.equals("") || input.equalsIgnoreCase("server") || input.equalsIgnoreCase("null")) { svar = true; } } return svar; }
5
public Map<Point, List<Point>> cluster() { // 随即选取k个点作为中心点 List<Point> keys = Random.choice(points, k); while (true) { // 根据中心点对属性点聚类 clusters = clusterPoints(keys); // 根据聚类结果计算中心点 ArrayList<Point> tmpKeys = new ArrayList<Point>(); for (List<Point> pointList : clusters.values()) { tmpKeys.add(getKey(pointList)); } // 如果重新计算的中心点没有变化,则迭代结束 if (keys.containsAll(tmpKeys)) { break; } // 如果中心点变化了,则更新中心点 keys = tmpKeys; } return clusters; }
3
private void copyToClipboard(String selectString){ if (selectString != null){ StringSelection stringSelection = new StringSelection (selectString); Clipboard clipboard = Toolkit.getDefaultToolkit ().getSystemClipboard (); clipboard.setContents (stringSelection, null); } }
1
private void print(Employee[] e) { for (int i = 0; i < e.length; i++) System.out.println(e[i].surName + "," + e[i].givenName); }
1
private void set(String type, int id_tank, int id) throws Exception{ int tankTypeID = garage.getTankID(id_tank); if(type == null){ close(); }else if(type.equals("$armor$")){ if(tankTypeID == dataBaseConnector.getTankIDForArmor(id)){ garage.setArmor(id_tank, id); dataBaseConnector.setTankArmor(id_tank,id); } else throw new Exception(); }else if(type.equals("$engine$")){ if(tankTypeID == dataBaseConnector.getTankIDForEngine(id)){ garage.setEngine(id_tank, id); dataBaseConnector.setTankEngine(id_tank, id); } else throw new Exception(); }else if(type.equals("$first_weapon$")){ if(tankTypeID == dataBaseConnector.getTankIDForFirstWeapon(id)){ garage.setFirstWeapon(id_tank, id); dataBaseConnector.setTankFirstWeapon(id_tank, id); } else throw new Exception(); }else if(type.equals("$second_weapon$")){ if(tankTypeID == dataBaseConnector.getTankIDForSecondWeapon(id)){ garage.setSecondWeapon(id_tank, id); dataBaseConnector.setTankSecondWeapon(id_tank, id); } else throw new Exception(); }else close(); }
9
@Override public void run() { options.status = "Open bank"; for (Item item : ctx.equipment.select().id(Banking.ALWAYS_DEPOSIT)) { if (ctx.backpack.isFull()) { break; } ctx.equipment.unequip(item.id()); } if (!ctx.bank.open()) { final Locatable nearest = ctx.bank.nearest(); if (nearest instanceof Npc) { ctx.camera.prepare((Npc) nearest); } else if (nearest instanceof GameObject) { ctx.camera.prepare((GameObject) nearest); } } }
5
protected NoDiscountStrategy(double price, int copies) { super(price, copies); }
0
private EnumSoundLoadError getALErrorAsErrorEnum(int err) { switch (err) { case AL_NO_ERROR: return EnumSoundLoadError.ERROR_NULL; case AL_INVALID_NAME: return EnumSoundLoadError.ERROR_INVALID_NAME; case AL_INVALID_ENUM: return EnumSoundLoadError.ERROR_INVALID_ENUM; case AL_INVALID_VALUE: return EnumSoundLoadError.ERROR_INVALID_VALUE; case AL_INVALID_OPERATION: return EnumSoundLoadError.ERROR_INVALID_OPERATION; case AL_OUT_OF_MEMORY: return EnumSoundLoadError.ERROR_MEMORY_OUT; default: return null; } }
6
public String getExportEncoding() { return (String) exportEncodingComboBox.getSelectedItem(); }
0
public static void main(String[ ] args) { String[ ][ ] animals = { { "DanaDog", "WallyDog", "JessieDog", "AlexisDog", "LuckyDog" }, { "BibsCat", "DoodleCat", "MillieCat", "SimonCat" }, { "ElyFish", "CloieFish", "GoldieFish", "OscarFish", "ZippyFish", "TedFish"}, { "RascalMule", "GeorgeMule", "GracieMule", "MontyMule", "BuckMule", "RosieMule" } }; for (int i = 0; i < animals.length; i++) { System.out.print(animals[ i ] [ 0 ] + ": "); for (int j = 1; j < animals[ i ].length; j++) { System.out.print(animals[ i ][ j ] + " "); } System.out.println( ); } }
2
public boolean looseEquals(Object keyObj) { boolean isEqual = false; if (key != null) { // Checks a compound key (ObjectKey[] or String[] // based) with the delimited String created by the // toString() method. Slightly expensive, but should be less // than parsing the String into its constituents. if (keyObj instanceof String) { isEqual = toString().equals(keyObj); } // check against a ObjectKey. Two keys are equal, if their // internal keys equivalent. else if (keyObj instanceof ComboKey) { SimpleKey[] obj = (SimpleKey[]) ((ComboKey) keyObj).getValue(); SimpleKey[] keys1 = key; SimpleKey[] keys2 = obj; isEqual = keys1.length == keys2.length; for (int i = 0; i < keys1.length && isEqual; i++) { isEqual &= ObjectUtils.equals(keys1[i], keys2[i]); } } else if (keyObj instanceof SimpleKey[]) { SimpleKey[] keys1 = key; SimpleKey[] keys2 = (SimpleKey[]) keyObj; isEqual = keys1.length == keys2.length; for (int i = 0; i < keys1.length && isEqual; i++) { isEqual &= ObjectUtils.equals(keys1[i], keys2[i]); } } } return isEqual; }
8
public static List<Presente> corte(List<Presente> p1, List<Presente> p2, int posCorteInicial, int posCorteFinal, int tamanho) { System.out.println("----"); System.out.println(posCorteInicial + " " + posCorteFinal); imprimirPresentes(new Cromossomo(p1)); imprimirPresentes(new Cromossomo(p2)); System.out.println("----"); List<Integer> genesPreDefinidos = new ArrayList<>(); //int metade = (int) Math.floor(tamanho / 2); List<Presente> f1 = new ArrayList<>(); for (Presente presente : p1) { try { f1.add(presente.clone()); } catch (CloneNotSupportedException ex) { Logger.getLogger(Cruzamento.class.getName()).log(Level.SEVERE, null, ex); } } // int k = 0; for (int i = posCorteInicial; i < posCorteFinal; i++) { genesPreDefinidos.add(p1.get(i).getId()); } int i = posCorteFinal - posCorteInicial; int j = 0; for (Presente presente : p2) { if (genesPreDefinidos.contains(presente.getId())) { continue; } if (j == posCorteInicial) { j = posCorteFinal; } try { f1.set(j, presente.clone()); } catch (CloneNotSupportedException ex) { Logger.getLogger(Cruzamento.class.getName()).log(Level.SEVERE, null, ex); } j++; } // while (j < tamanho) { // if (!genesPreDefinidos.contains(p2.get(j).getId())) { // try { // f1.set(i, p2.get(j).clone()); // } catch (CloneNotSupportedException ex) { // Logger.getLogger(Cruzamento.class.getName()).log(Level.SEVERE, null, ex); // } // i++; // } // j++; // } imprimirPresentes(new Cromossomo(f1)); return f1; }
7
@Override public void update(int delta) { if (!active) { return; } // calculate x x = entity.getX() - (Globals.APP_WIDTH / 2); if (x < 0) { x = 0; } if (x >= Engine.getMap().getWidth() - Globals.APP_WIDTH) { x = Engine.getMap().getWidth() - Globals.APP_WIDTH; } // calculate y y = entity.getY() - (Globals.APP_HEIGHT / 2); if (y < 0) { y = 0; } if (y >= Engine.getMap().getHeight() - Globals.APP_HEIGHT) { y = Engine.getMap().getHeight() - Globals.APP_HEIGHT; } // play the queued effect if there is one if (nextEffect != null) { if (!nextEffect.isFinished()) { nextEffect.update(delta); } else { nextEffect = null; } } }
7
public static int getCopies(PrintService service, PrintRequestAttributeSet set) { Copies copies = (Copies) PrintUtilities.getSetting(service, set, Copies.class, false); return copies == null ? 1 : copies.getValue(); }
1
public static char nine(int r, int c, int f) { if (s1(r, c, f) || s4(r, c, f) || s5(r, c, f)) return '|'; else if (s3(r, c, f) || s6(r, c, f) || s7(r, c, f)) return '_'; return '.'; }
6
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final Item target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_ANY); if(target==null) { final String str=CMParms.combine(commands,0).toUpperCase(); if(str.equals("MONEY")||str.equals("GOLD")||str.equals("COINS")) mob.tell(L("You can't cast this spell on your own coins.")); return false; } if(target.fetchEffect(this.ID())!=null) { mob.tell(L("@x1 is already light!",target.name(mob))); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,somanticCastCode(mob,target,auto),auto?"":L("^S<S-NAME> wave(s) <S-HIS-HER> hands around <T-NAMESELF>, incanting.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); mob.location().show(mob,target,CMMsg.MSG_OK_ACTION,L("<T-NAME> grow(s) much lighter.")); beneficialAffect(mob,target,asLevel,100); target.recoverPhyStats(); mob.recoverPhyStats(); mob.location().recoverRoomStats(); } } else beneficialVisualFizzle(mob,target,L("<S-NAME> wave(s) <S-HIS-HER> hands around <T-NAMESELF>, incanting, but nothing happens.")); // return whether it worked return success; }
9
public void setItemId(int itemId) { this.itemId = itemId; }
0
public static String dump(Object comp) throws Exception { StringBuilder b = new StringBuilder(); b.append("//" + comp.toString() + ":\n"); b.append("// In\n"); ComponentAccess cp = new ComponentAccess(comp); for (Access in : cp.inputs()) { String name = in.getField().getName(); Object val = in.getFieldValue(); b.append(" " + name + ": " + Conversions.convert(val, String.class) + "\n"); } b.append("// Out\n"); for (Access in : cp.outputs()) { String name = in.getField().getName(); Object val = in.getFieldValue(); b.append(" " + name + ": " + Conversions.convert(val, String.class) + "\n"); } b.append("\n"); return b.toString(); }
2
public static Res combine (Res l, Res r, char op) { int total = ( l.cTrue + l.cFalse ) * (r.cTrue + r.cFalse); int t = 0; int f = 0; if ( op == '^' ){ t = l.cFalse * r.cTrue + l.cTrue * r.cFalse; f = total - t; } else if ( op == '&' ) { t = l.cTrue * r.cTrue; f = total - t; } else { f = l.cFalse * r.cFalse; t = total - f; } return new Res(t, f); }
2
private Task getResponse(HttpURLConnection connection) throws Exception { int responseCode = connection.getResponseCode(); if (responseCode == 200) { InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader( inputStream)); return new Task(reader); } else if (responseCode == 401) { throw new Exception( "HTTP 401 Unauthorized. Please check your application id and password"); } else if (responseCode == 407) { throw new Exception("HTTP 407. Proxy authentication error"); } else { String message = ""; try { InputStream errorStream = connection.getErrorStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(errorStream)); // Parse xml error response InputSource source = new InputSource(); source.setCharacterStream(reader); DocumentBuilder builder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document doc = builder.parse(source); NodeList error = doc.getElementsByTagName("error"); Element err = (Element) error.item(0); message = err.getTextContent(); } catch (Exception e) { throw new Exception("Error getting server response"); } throw new Exception("Error: " + message); } }
4
public static boolean containsAtLeastOneNonBlank(List<String> list){ for(String str : list){ if(StringUtils.isNotBlank(str)){ return true; } } return false; }
2
public static void main(String[] args) { String s2 = "Akroma, Angel of Wrath"; System.out.println(s2.replaceAll("[',]", "")); String s = "2 Pack Rat [RTR] "; Matcher m = linePattern.matcher(s); System.out.println(m.matches()); System.out.println(Integer.parseInt(m.group(1))); for(int i = 0; i < 4; i++) { System.out.println(i + ": " + m.group(i)); } }
1
public void mapRender(int scale, int xOff, int yOff){ if(texture == null) texture = tile.getTexture(); texture.bind(); // or GL11.glBind(texture.getTextureID()); GL11.glBegin(GL11.GL_QUADS); GL11.glTexCoord2f(0, 1); GL11.glVertex2f(x/scale + Game.PLAYER.getCameraX() + xOff, y/scale + Game.PLAYER.getCameraY() + yOff); GL11.glTexCoord2f(1,1); GL11.glVertex2f(x/scale+texture.getImageWidth()/scale + Game.PLAYER.getCameraX() + xOff, y/scale + Game.PLAYER.getCameraY() + yOff); GL11.glTexCoord2f(1,0); GL11.glVertex2f(x/scale+texture.getImageWidth()/scale + Game.PLAYER.getCameraX() + xOff, y/scale+texture.getImageHeight()/scale + Game.PLAYER.getCameraY() + yOff); GL11.glTexCoord2f(0,0); GL11.glVertex2f(x/scale + Game.PLAYER.getCameraX() + xOff, y/scale+texture.getImageHeight()/scale + Game.PLAYER.getCameraY() + yOff); GL11.glEnd(); }
1
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(Items.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Items.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Items.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Items.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 Items().setVisible(true); } }); }
6
public void setAsset_id(String asset_id) { this.asset_id = asset_id; }
0
void lisaaKentalle(List<Palikka> palikat) { for (int i = 0; i < palikat.size(); i++) { this.pelipalikat[palikat.get(i).getY()][palikat.get(i).getX()] = palikat.get(i); } }
1
public List<String> query(String st) { List<String> returnList = new ArrayList<>(); //System.out.println("SQL: "+st); try { PreparedStatement statement = conn.prepareStatement(st); ResultSet rs = statement.executeQuery(); if (rs == null) { return returnList; } int columnCount = rs.getMetaData().getColumnCount(); while (rs.next()) { StringBuilder rowString = new StringBuilder(); for (int i = 1; i <= columnCount; i++) { rowString.append(rs.getString(i)); rowString.append(DELIMETER); } //separates records returnList.add(rowString.toString()); } //stuff rs.close(); statement.close(); } catch (SQLException se) { System.err.println("Error querying database: " + se.getMessage()); } return returnList; }
4
@Override public int hashCode() { int hash = 0; hash += (idHospital != null ? idHospital.hashCode() : 0); return hash; }
1
@Override public void render() { for (int i = 0; i < pixels.length; i++) { pixels[i] = i + ticks; } renderSprite(Assets.GRASS, x, y, 0, false); }
1
private static boolean[] primeBoolArray(int limit) { boolean[] nums = new boolean[limit]; for (int i = 2; i < nums.length; i++) nums[i] = true; int nextPrime = 2; while (nextPrime < nums.length / 2) { int i = nextPrime; for (; i < nums.length; i += nextPrime) nums[i] = false; nums[nextPrime] = true; for (int j = nextPrime + 1; j < nums.length; j++) { if (nums[j] == true) { nextPrime = j; break; } } } return nums; }
5
protected String getRequirementsDescription(String values) { if(values==null) return ""; if(values.equalsIgnoreCase("integer")||values.equalsIgnoreCase("int")) return " as an integer or integer expression"; else if(values.equalsIgnoreCase("double")||values.equalsIgnoreCase("#")||values.equalsIgnoreCase("number")) return " as a number or numeric expression"; else if(values.equalsIgnoreCase("string")||values.equalsIgnoreCase("$")) return " as an open string"; else if(values.trim().length()>0) return " as one of the following values: "+values; return ""; }
9
public void SetLampColorAndMessage(String s, int c) { switch( c ) { case 0: IluminationColor = Color.black; break; case 1: IluminationColor = Color.green; break; case 2: IluminationColor = Color.yellow; break; case 3: IluminationColor = Color.red; break; } // switch MessageLabel = s; repaint(); } // SetLampColor
4
public IVPBoolean greaterThan(IVPNumber num, Context c, HashMap map, DataFactory factory) { IVPBoolean result = factory.createIVPBoolean(); map.put(result.getUniqueID(), result); boolean resultBoolean = false; if(getValueType().equals(IVPValue.INTEGER_TYPE) && num.getValueType().equals(IVPValue.INTEGER_TYPE)){ resultBoolean = c.getInt(getUniqueID()) > c.getInt(num.getUniqueID()); }else{ if(getValueType().equals(IVPValue.DOUBLE_TYPE) && num.getValueType().equals(IVPValue.DOUBLE_TYPE)){ resultBoolean = c.getDouble(getUniqueID()) > c.getDouble(num.getUniqueID()); }else{ if(getValueType().equals(IVPValue.DOUBLE_TYPE)){ resultBoolean = c.getDouble(getUniqueID()) > c.getInt(num.getUniqueID()); }else{ resultBoolean = c.getInt(getUniqueID()) > c.getDouble(num.getUniqueID()); } } } c.addBoolean(result.getUniqueID(), resultBoolean); return result; }
5
public void generateInitialPopulation(int size){ population = new String[size][]; prevPopulation = new String[size][]; fitness = new Double[size]; for(int i = 0; i < size; i++){ population[i] = this.generateDeck("random"); fitness[i] = 0.0; } }
1
public static Property getPropertyByName(String name) { Property p=null; try { p=MediaProperty.valueOf(name); } catch (IllegalArgumentException e) { p=extendedProperties.get(name.toUpperCase()); } return p; }
1
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(OverviewTeacher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(OverviewTeacher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(OverviewTeacher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(OverviewTeacher.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 OverviewTeacher().setVisible(true); } }); }
6
public void addView(AbstractView view) { if ("CONNECTION".equals(view.getType())){ this.getContentPane().add(view.getPanel()); } else { this.getContentPane().add(contentPanel); String type = view.getType(); if (type.equals("WEST")) { contentPanel.add(view.getPanel(), BorderLayout.WEST); } else if (type.equals("SOUTH")) { contentPanel.add(view.getPanel(), BorderLayout.SOUTH); } else if(type.equals("NORTH")) { if (view.getClass().getSimpleName().equalsIgnoreCase("MyProfileView")) { gridBagConstraints.fill = GridBagConstraints.NONE; gridBagConstraints.anchor = GridBagConstraints.LINE_END; gridBagConstraints.weightx = 1; jpanelNorth.add(view.getPanel(), gridBagConstraints); } if (view.getClass().getSimpleName().equalsIgnoreCase("SearchBarView")) { gridBagConstraints.fill = GridBagConstraints.NONE; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1; jpanelNorth.add(view.getPanel(), gridBagConstraints); } } else if(type.equals("EAST")) { contentPanel.add(view.getPanel(), BorderLayout.EAST); } else if(type.equals("CENTER")) { contentPanel.add(view.getPanel(), BorderLayout.CENTER); } else { System.out.println("Error : type du panel (north, south, east...) non défini !"); } } this.pack(); this.setVisible(true); this.setLocationRelativeTo(null); }
8
protected void randomizeFolders(String romId, ByteStream rom, ChipLibrary library) { // Randomize Folder ItemProducer chipProducer = new BN456RewardProducer(library); FolderProducer producer = new FolderProducer(chipProducer); FolderProvider provider = new FolderProvider(this, producer); PointerListStrategy processListStrat = new PointerListStrategy(provider, 6); rom.setRealPosition(getVersionAddress(0x1344EC, romId)); rom.setPosition(rom.readInt32()); processListStrat.execute(rom); runProvider(provider, rom); // Fix tutorial folders. FolderProvider tutorialProvider = new FolderProvider(this, producer); PointerListStrategy tutorialPtrStrat = new PointerListStrategy(tutorialProvider, 1); FilterStrategy filterEmptyStrat = new FilterStrategy(tutorialPtrStrat, new byte[]{ 0, 0, 0, 0 }, new byte[]{ -1, -1, -1, -1 }, true); RepeatStrategy tutorialPtrArrayStrat = new RepeatStrategy(filterEmptyStrat, 8); rom.setRealPosition(getVersionAddress(0x008D44, romId)); rom.setPosition(rom.readInt32()); tutorialPtrArrayStrat.execute(rom); byte[] codesWideSwrd = library.getElement(49).getCodes(); byte[] codesAreaGrab = library.getElement(117).getCodes(); List<Byte> possibleCodes = new ArrayList<>(4); for (byte a : codesWideSwrd) { for (byte b : codesAreaGrab) { if (a == b) { possibleCodes.add(a); } } } byte comboCode = possibleCodes.get(next(possibleCodes.size())); for (Folder folder : tutorialProvider.allData()) { for (Item chip : folder.getChips()) { if (chip.getChip().index() == 49 || chip.getChip().index() == 117) { chip.setChipCode(chip.getChip(), comboCode); } else { byte[] codes = chip.getChip().getCodes(); byte code = codes[next(codes.length)]; chip.setChipCode(chip.getChip(), code); } } tutorialProvider.produce(rom); } }
7
public void addText(String text) { combatLog = combatLog + "\n" + text; updateLog(combatLog); }
0
private static void buildTimelineBackward(List<SmaliBlock> blockList, SmaliMethod method) { //TODO: implement backward timeline scanning SmaliBlock block = null; RegisterTimeline timeline = null; List<SmaliBlock> sortedList = new LinkedList<SmaliBlock>(); List<SmaliBlock> tmpList = new LinkedList<SmaliBlock>(); tmpList.addAll(blockList); while(tmpList.size() > 0) { block = tmpList.remove(0); if(block.isEndsByReturn) { sortedList.add(block); } else if(block.isEndsByCondition && sortedList.contains(block.nextBlockIfTrue) && sortedList.contains(block.nextBlockIfFalse)) { sortedList.add(block); } else if(block.nextBlockIfTrue != null && sortedList.contains(block.nextBlockIfTrue)) { sortedList.add(block); } else { tmpList.add(block); } } ArrayList<Instruction> lines = new ArrayList<Instruction>(128); for(int i = 0; i < sortedList.size(); i++) { block = sortedList.get(i); initTimeline(block, method, lines); timeline = block.registerTimeline; buildBlockTimelineBackward(lines, timeline); lines.clear(); } }
8
public static void main(String[] args){ while(true){ AvgCyberusAI tetris = new AvgCyberusAIHelper(); tetris.startGame(); while(tetris.tc.gameOn){ System.out.print(""); } } }
2
public static ArrayList<Student> loadStu() { ArrayList<Student> list = new ArrayList<>(); Student stu = new Student(); FileReader fr = null; BufferedReader br = null; try { fr = new FileReader("d:/object.txt"); br = new BufferedReader(fr); int ch = 0; String tmp = ""; while (true) { while (((char) (ch = br.read()) != '\n') && ch != -1) { tmp += (char) ch; } if (ch == -1) { break; } String[] sp = tmp.split(":"); tmp = ""; stu.setName(sp[0]); stu.setId(Integer.parseInt(sp[1])); list.add(stu); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } if (fr != null) { fr.close(); } } catch (IOException e) { e.printStackTrace(); } } return list; }
8
public List<Aplicacion> ObtenerAplicacion(String consulta){ List<Aplicacion> lista=new ArrayList<Aplicacion>(); if (!consulta.equals("")) { lista=cx.getObjects(consulta); }else { lista=null; } return lista; }
1
public int readInt() { int ch1 = readByte(); int ch2 = readByte(); int ch3 = readByte(); int ch4 = readByte(); if(ch1 < 0) ch1 = BYTE_MAX + ch1; if(ch2 < 0) ch2 = BYTE_MAX + ch2; if(ch3 < 0) ch3 = BYTE_MAX + ch3; if(ch4 < 0) ch4 = BYTE_MAX + ch4; //position += INT_SIZE; return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4)); }
4
public Move promoteSelf(boolean color) { Move m = null; for (Entry<Point, ChessSquare> e : potentialMoves.entrySet()) { if (e.getKey().getY() == 0 && color) { for (Entry<Point, Piece> f : e.getValue().getInbound(color).entrySet()) { if (f.getValue().toString().equals("WP")) { m = new Move(f.getKey(), e.getKey(), new Queen(color)); // System.out.println(m.toString()); return m; } } } if (e.getKey().getY() == 7 && !color) { for (Entry<Point, Piece> f : e.getValue().getInbound(color).entrySet()) { if (f.getValue().toString().equals("BP")) { m = new Move(f.getKey(), e.getKey(), new Queen(color)); // System.out.println(m.toString()); return m; } } } } return prioritizedAggressiveMove(color); }
9
public int getCharTextureID(char c) { if (c < FIRST_STANDARD_CHAR || c > FIRST_STANDARD_CHAR + NUM_STANDARD_CHARS) { System.out.println("Unsupported character: " + c + " (\\u" + Integer.toHexString(c) + ")"); return -1; } return TextureManager.getTextureID(name + "." + c); }
2
public static void loadAllAchievements() { String statement = new String("SELECT * FROM " + DBTable + " WHERE type = ?"); PreparedStatement stmt; try { stmt = DBConnection.con.prepareStatement(statement); stmt.setInt(1, QUIZ_CREATED_TYPE); ResultSet rs = stmt.executeQuery(); while (rs.next()) { QuizCreatedAchievement achievement = new QuizCreatedAchievement(rs.getInt("aid"), rs.getString("name"), rs.getString("url"), rs.getString("description"), rs.getInt("threshold")); allAchievements.add(achievement); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } }
2
public Nutzer setUser(String name, String password, String password_repeat) throws Exception { if (password == null || password.equals("")) throw new PasswordEmptyException("Bitte ein Passwort eingeben"); if (password_repeat == null || password_repeat.equals("")) throw new PasswordEmptyException("Bitte wiederhole Sie ihr Passwort eingeben"); if (!password_repeat.equals(password)) throw new IllegalArgumentException("Ihre Passwörter stimmen nicht überein"); if (password.length() < 5) throw new PasswordToShortException("Minimum password length is five characters"); if (name == null || name.equals("")) throw new UsernameEmptyException("Bitte einen Namen eingeben"); Nutzer n = new Nutzer(name, this.hash(password)); try { em.getTransaction().begin(); em.persist(n); em.getTransaction().commit(); } catch (Exception e) { throw new Exception("Nutzer konnte nicht angelegt werden"); } return n; }
9
public boolean ajouterSignalisation(Signalisation s) { if (s instanceof Feu && this.getNbFeu() <= NOMBRE_MAX_FEUX) { return signalisations.add(s); } else if (s instanceof PanneauCedezLePassage && this.getNbCedezLePassage() <= NOMBRE_MAX_CEDEZLEPASSAGE) { return signalisations.add(s); } else if (s instanceof PanneauStop && this.getNbFeu() <= NOMBRE_MAX_FEUX) { return signalisations.add(s); } return false; }
6
private boolean newEntry() { try { rs.moveToInsertRow(); return true; } catch (SQLException ex) { System.out.println(ex.getMessage()); } return false; }
1