text
stringlengths
14
410k
label
int32
0
9
public static void unpackConfig(Archive container) { Stream buffer = new Stream(container.get("spotanim.dat")); int len = buffer.getUnsignedShort(); if (SpotAnimation.spotAnimationCache == null) { SpotAnimation.spotAnimationCache = new SpotAnimation[len]; } for (int i = 0; i < len; i++) { if (SpotAnimation.spotAnimationCache[i] == null) { SpotAnimation.spotAnimationCache[i] = new SpotAnimation(); } SpotAnimation.spotAnimationCache[i].id = i; SpotAnimation.spotAnimationCache[i].readValues(buffer); } }
3
private boolean checkDirection(GameBoard gb, int player, Coordinates coord, int x, int y) { try { Coordinates newCoord = new Coordinates(coord.getRow() + x, coord.getCol() + y); if (gb.getOccupation(newCoord) == EMPTY) { return false; } if (gb.getOccupation(coord) == reversi.Utils.other(player) && gb.getOccupation(newCoord) == player) { return true; } if (gb.getOccupation(newCoord) == reversi.Utils.other(player)) { return checkDirection(gb, player, newCoord, x, y); } } catch (OutOfBoundsException e) { return false; } return false; }
5
@Override public void draw(Graphics g, Display d, int bottomPixelX, int bottomPixelY, boolean drawHealth){ double percentMoved = count * 0.25; // Tile coordinates of The Dude (x,y) double x, y; if(attacking == null) { x = this.oldX + (this.x - this.oldX) * percentMoved; y = this.oldY + (this.y - this.oldY) * percentMoved; } else { double dist = (count % 2 == 1) ? 0.2 : 0.1; x = this.x + (facing == LEFT ? -1 : facing == RIGHT ? 1 : 0) * dist; y = this.y + (facing == UP ? -1 : facing == DOWN ? 1 : 0) * dist; } // Pixel coordinates (on screen) of the Dude (i,j) Point pt = d.tileToDisplayCoordinates(x, y); int height = world.getTile(this.x, this.y).getHeight(); int oldHeight = world.getTile(oldX, oldY).getHeight(); pt.y -= TILE_HEIGHT * (oldHeight + (height - oldHeight) * percentMoved); //pt.y -= TILE_HEIGHT / 2; Image i = img[(facing + d.getRotation()) % 4]; // Draw image at (i,j) int posX = pt.x - i.getWidth(null) / 2; int posY = pt.y - i.getHeight(null); g.drawImage(i, posX, posY, null); if (drawHealth) { int tall = 10; int hHeight = 4; int hWidth = 16; g.setColor(Color.red); g.fillRect(posX, posY - tall, hWidth, hHeight); g.setColor(Color.green); g.fillRect(posX, posY - tall, (int)(hWidth * currentHealth / (float)maxHealth), hHeight); } }
7
public void addPosition(Position position) { if (position == null) throw new IllegalArgumentException("Position can't be null"); if (position.xCoordinate < 0 || position.yCoordinate < 0) throw new IllegalArgumentException("The given position is invalid!"); otherPositions.add(position); if (otherPositions.size() > 2) { Position newHeadPosition = otherPositions.remove(0); setPosition(newHeadPosition); } notifyObservers(); }
4
public Teleport(int x, int y, boolean tagurpidi) throws SlickException { this.x = x; this.y = y; this.tagurpidi = tagurpidi; pildid = new Image[11]; if (!tagurpidi) { for (int i = 0; i < pildid.length; i++) { pildid[i] = new Image("disintegrate0" + i + ".png"); } animation = new Animation(pildid, 50); } else { pildidT = new Image[11]; for (int i = pildidT.length - 1; i >= 0; i--) { pildidT[Math.abs(i-10)] = new Image("disintegrate0" + i + ".png"); } animation = new Animation(pildidT, 50); } animation.setLooping(false); imageH = animation.getImage(0).getHeight(); imageW = animation.getImage(0).getWidth(); }
3
public void setUnit(Unit u) { unit = u; }
0
@Override public V get(K key) { int elementIndex = findKeyIndex(key); if (elementIndex == -1) { return null; } return mapArray[elementIndex].getValue(); }
1
@Override public Bus driverBus() { return new BmwBus(); }
0
public static Color textHighlight(int type){ //if the message is encrypted, compressed or both, add different backgrounds switch(type){ case 1: //compress return new Color(206, 255, 185); case 2: //crypt return new Color(255, 252, 130); case 3: //compress + crypt return new Color(255, 169, 170); } return new Color(255, 255, 255); }
3
private JButton getJButton0() { if (jButton0 == null) { jButton0 = new JButton(); jButton0.setText("ok"); jButton0.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent event) { jButton0MouseMouseClicked(event); } }); } return jButton0; }
1
private String checkExists(String downloadName) { File fx = new File(opt.getDownloadPath()+File.separator+downloadName+".mp3"); if (fx.exists()){ if (ifExist.equalsIgnoreCase("Overwrite")){ fx.delete(); return downloadName; }else if (ifExist.equalsIgnoreCase("Skip")){ return null; }else{ Object[] options = {"Don't download", "Overwrite", "Rename"}; int n = JOptionPane.showOptionDialog(frmGroovejaar, "The file you want do download already exists, What should I do??", downloadName, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, //do not use a custom Icon options, //the titles of buttons options[0]); //default button title if (n==0||n==-1) return null; else if (n==1){ fx.delete(); return downloadName; } else if (n==2){ downloadName = JOptionPane.showInputDialog(null, "Rename File", "Enter new name for the file", JOptionPane.QUESTION_MESSAGE); return downloadName; } } }else return downloadName; return null; }
7
private void expand1(byte[] src, byte[] dst) { for(int i=1,n=dst.length ; i<n ; i+=8) { int val = src[1 + (i >> 3)] & 255; switch(n-i) { default: dst[i+7] = (byte)((val ) & 1); case 7: dst[i+6] = (byte)((val >> 1) & 1); case 6: dst[i+5] = (byte)((val >> 2) & 1); case 5: dst[i+4] = (byte)((val >> 3) & 1); case 4: dst[i+3] = (byte)((val >> 4) & 1); case 3: dst[i+2] = (byte)((val >> 5) & 1); case 2: dst[i+1] = (byte)((val >> 6) & 1); case 1: dst[i ] = (byte)((val >> 7) ); } } }
8
public void stop() throws BITalinoException { try { socket.write(0); Thread.sleep(SLEEP); close(); } catch (Exception e) { throw new BITalinoException(BITalinoErrorTypes.BT_DEVICE_NOT_CONNECTED); } }
1
public static boolean isNum(String str){ return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$"); }
0
public static double newtonRaphson(double x0, double epsilon, int cantIter, Funcion fun) throws Exception { double x1; int iter = 0; x1 = x0 - (fun.f(x0) / fun.fd(x0)); while ((iter < cantIter) && (Math.abs(x1 - x0) >= epsilon)) { x0 = x1; x1 = x0 - (fun.f(x0) / fun.fd(x0)); iter++; } if (iter == cantIter && (Math.abs(x1 - x0) >= epsilon) ) { throw new Exception("Maximas iteraciones alcanzadas"); } else { return x1; } }
4
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(Login_form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Login_form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Login_form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Login_form.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 Login_form().setVisible(true); } }); }
6
public List < AState > search() { if(!this.calculated) { this.stateOpened = 0; List < AState > opened = new LinkedList < AState >(); AState current = this.map.getStartState(); long start = System.currentTimeMillis(); while(!current.isGoal()) { current.setClosed(true); List < AState > neighbors = this.map.getAllNeighbors(current); for(AState state : neighbors) { double cost = this.map.getCost(current, state); if(state.getG() <= current.getG() + cost) continue; state.setG(current.getG() + cost); state.setFather(current); state.setClosed(false); this.insertInOpened(opened, state); } if(opened.isEmpty()) break; current = opened.get(0); opened.remove(current); this.stateOpened++; if(System.currentTimeMillis() - start > 10000) break; } if(current.isGoal()) { this.resolved = true; this.road.add(current); while(!current.equals(this.map.getStartState())) { current = current.getFather(); this.road.add(0, current); } } this.calculated = true; } return this.road; }
8
public void makeVisible(Component com) { if(TargetSet) { return; } int ht = com.getHeight(), vy = com.y; int WindowTransition = parent.TranselateY; int ActualPosition = WindowTransition + vy; if(ActualPosition + ht > y+height) { if(ActualPosition < y) { return; } parentTarget = y + height - (ht + vy); int target = y - (int)((parentTarget)/ratio); // System.out.println("\nTargetY:"+parentTarget); Target = target; moveTo = TARGET; TargetSet = true; int interval = (Target - my)/3; scrollInterval = (interval > 0) ? interval : 1; } else if(ActualPosition < y) { if(com.getHeight() > height) { return; } parentTarget = y - vy; Target = y - (int)(parentTarget/ratio); moveTo = TARGET; TargetSet = true; // System.out.println("TargetY:"+parentTarget); int interval = (my - Target)/3; scrollInterval = (interval > 0) ? interval : 1; } }
7
private final String getChunk(String s, int slength, int marker) { StringBuilder chunk = new StringBuilder(); char c = s.charAt(marker); chunk.append(c); marker++; if (isDigit(c)) { while (marker < slength) { c = s.charAt(marker); if (!isDigit(c)) break; chunk.append(c); marker++; } } else { while (marker < slength) { c = s.charAt(marker); if (isDigit(c)) break; chunk.append(c); marker++; } } return chunk.toString(); }
5
@Override public AbstractActionPanel getAction() { if ( owner.getSelected() ) { return new ActionPanelWorker(); } else { return new ActionPanelBlank(); } }
1
private void updateVillainMissiles3() { ArrayList<VillainMissile3> deadVillainMissiles = new ArrayList<VillainMissile3>(); for(int i = 0; i < villainMissiles3.size(); i++) { VillainMissile3 v = villainMissiles3.get(i); v.move(); if(CollisionDetector.isColliding(v, sc)) { if(!sc.isShieldActive()) sc.damaged(v.getStrength()); deadVillainMissiles.add(v); } if(!v.isOnScreen()) { deadVillainMissiles.add(v); } } for(int i = 0; i < deadVillainMissiles.size(); i++) { VillainMissile3 v = deadVillainMissiles.get(i); villainMissiles3.remove(v); } }
5
public ArrondissementVille find(int id) { ArrondissementVille arrondissement = new ArrondissementVille(); try { ResultSet result = this.connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY).executeQuery("SELECT * FROM eleve WHERE elv_id = " + id); if (result.first()) { arrondissement = null;//station = new Station(id, result.getString("elv_nom"), result.getString("elv_prenom")); } } catch (SQLException e) { e.printStackTrace(); } return arrondissement; }
2
public static int tileColour(int[] bands, Raster r) { final int[] co = new int[] {6,4,0,1,2,3,5,6}; int[] pCount = { 0, 0, 0, 0, 0, 0, 0 }; final int w = r.getWidth(); final int h = r.getHeight(); for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) { int[] hsv = argbToHSV(r, x, y); // First check if the pixel is reasonably saturated if (hsv[1] > 50) { int col = hsv[0]; for (int i = 0; i < 8; i++) { if(col < bands[i]) { pCount[co[i]]++; break; } } } } } int winner = 0; int max = 0; for (int i = 0; i < 7; i++) { if (pCount[i] > max) { winner = i; max = pCount[i]; } } return winner; }
7
private void doRepeat() { // Repeat the previous 1, 4, 8, 16 beats switch (REPEAT_STATE) { case BEAT: if (OUTPUT_BEATS.size() >= 1) { LAST_BEAT = OUTPUT_BEATS.get(OUTPUT_BEATS.size() - 1); OUTPUT_BEATS.add(LAST_BEAT); DURATION -= LAST_BEAT.getBeat()[0].length; } break; case MEASURE: if (OUTPUT_BEATS.size() >= 4) for (int i = 4; i > 0; i--) { LAST_BEAT = OUTPUT_BEATS.get(OUTPUT_BEATS.size() - i); OUTPUT_BEATS.add(LAST_BEAT); DURATION -= LAST_BEAT.getBeat()[0].length; } break; case DOUBLE_MEASURE: if (OUTPUT_BEATS.size() >= 8) for (int i = 8; i > 0; i--) { LAST_BEAT = OUTPUT_BEATS.get(OUTPUT_BEATS.size() - i); OUTPUT_BEATS.add(LAST_BEAT); DURATION -= LAST_BEAT.getBeat()[0].length; } break; // case QUAD_MEASURE: // for (int i = 16; i > 0; i--) // { // LAST_BEAT = OUTPUT_BEATS.get(OUTPUT_BEATS.size() - i); // OUTPUT_BEATS.add(LAST_BEAT); // DURATION -= LAST_BEAT.getBeat()[0].length; // } // break; } BEATS_SINCE_REPEAT = 0; }
8
private void replicateCards(Card remoteCard, String typeofCard) { if (typeofCard.equals("remotePlayer")) { remoteCards.newCard(remoteCard); pcardPanel.removeAll(); pcardPanel.add(playerlabel); Iterator<Card> pscan = (player.inHand).iterator(); while (pscan.hasNext()) { pcardPanel.add(new JLabel(pscan.next().getimage())); } pcardPanel.add(remotelabel); Iterator<Card> rscan = (remoteCards).iterator(); while (rscan.hasNext()) { pcardPanel.add(new JLabel(rscan.next().getimage())); } playerlabel.setText(" Player: " + game.handValue(player)); remotelabel.setText(" Remote: " + game.handValue(remoteCards)); dealerlabel.setText(" Dealer: " + game.handValue(dealer)); winlosebox.setText(" "); // THIS IS A HACK: container JPanel doesnt // redraw without this :( Need to find // proper fix - MV } else if (typeofCard.equals("dealer")) { game.hit(dealer, remoteCard); dcardPanel.add(new JLabel(remoteCard.getimage())); dealerlabel.setText(" Dealer: " + game.handValue(dealer)); serialCount++; if (serialCount > 0) winlosebox.setText(game.winner()); else winlosebox.setText(" "); // THIS IS A HACK: container JPanel // doesnt redraw without this :( // Need to find proper fix - MV } else if (typeofCard.equals("player")) { game.hit(player, remoteCard); // redraw lower panel pcardPanel.removeAll(); pcardPanel.add(playerlabel); Iterator<Card> pscan = (player.inHand).iterator(); while (pscan.hasNext()) { pcardPanel.add(new JLabel(pscan.next().getimage())); } pcardPanel.add(remotelabel); Iterator<Card> rscan = remoteCards.iterator(); while (rscan.hasNext()) { pcardPanel.add(new JLabel(rscan.next().getimage())); } playerlabel.setText(" Player: " + game.handValue(player)); remotelabel.setText(" Remote: " + game.handValue(remoteCards)); dealerlabel.setText(" Dealer: " + game.handValue(dealer)); winlosebox.setText(" "); // THIS IS A HACK: container JPanel doesnt // redraw without this :( Need to find // proper fix - MV } else if (typeofCard.equals("request")) { tempCard = remoteCard; } }
9
public void testToStandardMinutes() { Period test = new Period(0, 0, 0, 0, 0, 6, 7, 8); assertEquals(6, test.toStandardMinutes().getMinutes()); test = new Period(0, 0, 0, 0, 1, 6, 0, 0); assertEquals(66, test.toStandardMinutes().getMinutes()); test = new Period(0, 0, 0, 0, 0, 0, 59, 1000); assertEquals(1, test.toStandardMinutes().getMinutes()); test = new Period(0, 0, 0, 0, 0, Integer.MAX_VALUE, 0, 0); assertEquals(Integer.MAX_VALUE, test.toStandardMinutes().getMinutes()); test = new Period(0, 0, 0, 0, 0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE); long intMax = Integer.MAX_VALUE; BigInteger expected = BigInteger.valueOf(intMax); expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_SECOND)); expected = expected.divide(BigInteger.valueOf(DateTimeConstants.MILLIS_PER_MINUTE)); assertTrue(expected.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) < 0); assertEquals(expected.longValue(), test.toStandardMinutes().getMinutes()); test = new Period(0, 0, 0, 0, 0, Integer.MAX_VALUE, 60, 0); try { test.toStandardMinutes(); fail(); } catch (ArithmeticException ex) {} }
1
public void startElement(String name) { stack.addFirst(name); if (name.equals("module")) { currentModule = org.analyse.main.Main.getModule(id.toUpperCase()); asiModuleHandler = ((FilterASIModule) (currentModule .getFiltre("ASI"))).getASIHandler(); } else if (currentModule != null) { asiModuleHandler.startElement(name); } }
2
private Location findFood(Location location) { Field field = getField(); List<Location> adjacent = closestPrey(field.adjacentLocations(getLocation(), 2)); Iterator<Location> it = adjacent.iterator(); while(it.hasNext()) { Location where = it.next(); Object animal = field.getObjectAt(where); if(animal instanceof Rabbit) { Rabbit rabbit = (Rabbit) animal; if(rabbit.isAlive()) { rabbit.setDead(); foodLevel = RABBIT_FOOD_VALUE; // Remove the dead rabbit from the field. return where; } } if(animal instanceof Fox) { Fox fox = (Fox) animal; if(fox.isAlive()) { fox.setDead(); foodLevel = FOX_FOOD_VALUE; // Remove the dead rabbit from the field. return where; } } } return null; }
5
@Override /** * Returns a String representation of the Item. */ public String toString() { StringBuilder returnString = new StringBuilder(); // Append quantity if it is there. if (this.quantity > 0) { returnString.append(this.quantity + " "); } // If has name, use it. if (!this.name.equals("")) { if (this.quantity > 1) { returnString.append(Generator.pluralize(this.name)); } else { returnString.append(this.name); } returnString.append(" "); if (this.value.size() > 0) { returnString.append("for "); } Generator.appendCommaList(this.value, returnString, "and"); return returnString.toString().trim(); } // Otherwise use type if it has it. else if (!this.type.equals("")) { if (!this.rarity.equals("")) { returnString.append(this.rarity.toLowerCase() + " "); } if (this.level > -1) { returnString.append("Item Level " + this.level + " "); } if (this.quantity > 1) { returnString.append(Generator.pluralize(this.type.toLowerCase())); } else { returnString.append(this.type.toLowerCase()); } returnString.append(" "); if (this.value.size() > 0) { returnString.append("for "); } Generator.appendCommaList(this.value, returnString, "and"); return returnString.toString().trim(); } // Item needs a name or type to be complete. else { return "< Error: Incomplete item encountered >"; } }
9
public void replaceBreakContinue(BreakableBlock block) { java.util.Stack todo = new java.util.Stack(); todo.push(block); while (!todo.isEmpty()) { StructuredBlock[] subs = ((StructuredBlock) todo.pop()) .getSubBlocks(); for (int i = 0; i < subs.length; i++) { if (subs[i] instanceof BreakBlock) { BreakBlock breakblk = (BreakBlock) subs[i]; if (breakblk.breaksBlock == block) { new ContinueBlock(this, breakblk.label != null) .replace(breakblk); } } todo.push(subs[i]); } } }
4
private Boolean validParameterType(Class<?> type) { if(type == int.class) { return true; } else if(type == float.class) { return true; } else if(type == String.class) { return true; } else if(type == String[].class) { return true; } return false; }
5
@Basic @Column(name = "FUN_ID") public Integer getFunId() { return funId; }
0
public synchronized List<Turnstile> init() { if (turnstiles == null) { turnstiles = new MyArrayList<Turnstile>(NUM_TURNSTILES); for (int i = 0; i < NUM_TURNSTILES; ++i) { Turnstile turnstile = new Turnstile(); turnstile.connect(this); turnstiles.add(turnstile); } } return turnstiles; }
2
Message receiveMessageFromSocket (FragmentProcessor fp, ByteArrayOutputStream baos) throws IOException { baos.reset (); int currentOpcode = 0; do { fp.readHeader (); if (!fp.mask) throw new IOException ("unmasked fragment"); if (currentOpcode == 0) { if (fp.opcode != 0) currentOpcode = fp.opcode; else throw new IOException ("first fragment of message is continuation fragment"); if (isControlOpcode (fp.opcode) && !fp.fin) throw new IOException ("fragmented control packet"); } else { if (fp.opcode != 0) throw new IOException ("fragment with opcode after first fragment"); } if (fp.payloadLength > maximumPayloadSize) throw new IOException ("payload too large (" + fp.payloadLength + " > " + maximumPayloadSize + ")"); if (baos.size () + fp.payloadLength > maximumMessageSize) throw new IOException ("message too large"); fp.readPayload (baos); } while (!fp.fin); return new Message (currentOpcode, baos.toByteArray ()); }
9
public int getNumMappedReads(String path){ int numReads = 0; try { TextFile filtSam; if (alnFnamePattern.isEmpty()) filtSam = new TextFile(path.replace(fnamePattern, "accepted_hits.filtered.sam"), false); else filtSam = new TextFile(path.replace(fnamePattern, alnFnamePattern), false); String line =""; while ( (line = filtSam.readLine()) != null){ if (! line.startsWith("@")){ numReads++; } } filtSam.close(); //System.out.println("number of mapped reads: " + numReads); } catch (IOException ex) { Logger.getLogger(processreadcounts.ProcessTranscriptCounts.class.getName()).log(Level.SEVERE, null, ex); } return numReads; }
4
public List<List<Integer>> subsets(int[] s){ Arrays.sort(s); int num = s.length ; int total = (int)Math.pow(2,num); List<List<Integer>> result= new ArrayList<List<Integer>>(); for(int i=0;i < total;i++) result.add(new ArrayList<Integer>()); for(int i =0;i < num;i++) for(int j=0;j < total;j++) if(((j >> i) & 1)==1) result.get(j).add(s[i]); return result; }
4
public String nextString() throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } String result; if (p == PEEKED_UNQUOTED) { result = nextUnquotedValue(); } else if (p == PEEKED_SINGLE_QUOTED) { result = nextQuotedValue('\''); } else if (p == PEEKED_DOUBLE_QUOTED) { result = nextQuotedValue('"'); } else if (p == PEEKED_BUFFERED) { result = peekedString; peekedString = null; } else if (p == PEEKED_LONG) { result = Long.toString(peekedLong); } else if (p == PEEKED_NUMBER) { result = new String(buffer, pos, peekedNumberLength); pos += peekedNumberLength; } else { throw new IllegalStateException("Expected a string but was " + peek() + " at line " + getLineNumber() + " column " + getColumnNumber()); } peeked = PEEKED_NONE; return result; }
7
@Test public void gameIsOverWhenNoMorePlayers() { rp.resetGame(); boolean b1 = !rp.isGameOver(); rp.getEntities().addEntity(new TestRat()); rp.getScore().resetScore(rp.getPlayers()); boolean b2 = !rp.isGameOver(); for (int i = 0; i < Const.initialLifeAmount; i++) rp.playerDied(1); boolean b3 = !rp.isGameOver(); for (int i = 0; i < Const.initialLifeAmount; i++) rp.playerDied(2); boolean b4 = rp.isGameOver(); assertTrue(b1 && b2 && b3 && b4); }
5
private void harvestColor(){ //OPCIONAL CREAR CLASE DE SOURCE TAMBIEN switch(env.getMapObjectInPosition(positionX, positionY)){ case Environment.REDSOURCE: if(currentColor == COLORRED){ if(capacity<amountToHarvest){ colorAmount = capacity; } else{ colorAmount = amountToHarvest; } amountToHarvest-=colorAmount; } else{ //FAIL } break; case Environment.GREENSOURCE: if(currentColor == COLORGREEN){ if(capacity<amountToHarvest){ colorAmount = capacity; } else{ colorAmount = amountToHarvest; } amountToHarvest-=colorAmount; } else{ //FAIL } break; case Environment.BLUESOURCE: if(currentColor == COLORBLUE){ if(capacity<amountToHarvest){ colorAmount = capacity; } else{ colorAmount = amountToHarvest; } amountToHarvest-=colorAmount; } else{ //FAIL } break; default: //FAIL break; } }
9
private ValueMatcher buildValueMatcher(String str, ValueParser parser) throws Exception { if (str.length() == 1 && str.equals("*")) { return new AlwaysTrueValueMatcher(); } ArrayList values = new ArrayList(); StringTokenizer st = new StringTokenizer(str, ","); while (st.hasMoreTokens()) { String element = st.nextToken(); ArrayList local; try { local = parseListElement(element, parser); } catch (Exception e) { throw new Exception("invalid field \"" + str + "\", invalid element \"" + element + "\", " + e.getMessage()); } for (Iterator i = local.iterator(); i.hasNext();) { Object value = i.next(); if (!values.contains(value)) { values.add(value); } } } if (values.size() == 0) { throw new Exception("invalid field \"" + str + "\""); } if (parser == DAY_OF_MONTH_VALUE_PARSER) { return new DayOfMonthValueMatcher(values); } else { return new IntArrayValueMatcher(values); } }
8
private void registerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_registerButtonActionPerformed String password = new String(passwordField.getPassword()); String confirmPassword = new String(confirmPasswordField.getPassword()); if(password.equals(confirmPassword)){ int response = server.register(usernameField.getText(), password); if(response == 100){ JOptionPane.showMessageDialog(rootPane, "Error " + response + " - A user with that name already exists."); } else if(response == 101){ JOptionPane.showMessageDialog(rootPane, "Successfully added " + usernameField.getText() + " to the user list."); setVisible(false); LoginDialog logInDialog = new LoginDialog(parent, true, server); logInDialog.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); logInDialog.setVisible(true); } else{ JOptionPane.showMessageDialog(rootPane, "Did not get a response from the server."); } } else{ JOptionPane.showMessageDialog(rootPane, "The passwords did not match, please try again."); } }//GEN-LAST:event_registerButtonActionPerformed
3
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StudentContact other = (StudentContact) obj; if (internalID == null) { if (other.internalID != null) return false; } else if (!internalID.equals(other.internalID)) return false; return true; }
6
private void doSignCommand(CommandSender sender, Command cmd, String label, String[] args) { if(sender instanceof Player) { ItemStack item = ((Player) sender).getItemInHand(); BookMeta meta = null; Matcher titleMatcher = null; if(item.getType() == Material.WRITTEN_BOOK) { meta = (BookMeta) item.getItemMeta(); titleMatcher = TITLE_REGEX.matcher(meta.getTitle()); } if(meta != null && titleMatcher != null && titleMatcher.matches()) { String title = titleMatcher.group(1); PetitionData petition = plugin.getPetitionStorage().getPetitionData(title); if(petition != null) { if(petition.addSignature((Player) sender)) { plugin.updateOnlinePlayersInventories(); sender.sendMessage("§aSuccessfully added your signature to the petition!"); } else { sender.sendMessage("§3You have already signed that petition!"); } } else { sender.sendMessage("§4Couldn't find petition (probably has been deleted)"); } } else { sender.sendMessage("§4You must have the petition you want to sign in your hand!"); } } else { sender.sendMessage("§4Sorry you must be a player to sign petitions"); } }
7
public void handlePark(Park park) { park.setManaged(true); this.parkList.add(park); }
0
public static String getByteString( byte[] bt, boolean pad ) { if( bt.length == 0 ) { return "null"; } StringBuffer ret = new StringBuffer(); for( int x = 0; x < bt.length; x++ ) { if( ((x % 8) == 0) && (x > 0) ) { ret.append( "\r\n" ); } //String bstr = Integer.toOctalString(bt[x]); // toBinaryString(bt[x]); // Byte.toString(bt[x]); String bstr = Byte.toString( bt[x] ); // toBinaryString(bt[x]); // Byte.toString(bt[x]); if( pad ) { while( bstr.length() < 4 ) { bstr = " " + bstr; } } ret.append( bstr ); ret.append( "," ); } ret.setLength( ret.length() - 1 ); //ret.append(); return ret.toString(); }
6
public boolean replaceSubBlock(StructuredBlock oldBlock, StructuredBlock newBlock) { if (subBlock == oldBlock) subBlock = newBlock; else return false; return true; }
1
public List<Command> getCommands() { List<Command> list = new ArrayList<>(); Match commands = rootElement.xpath("commands").children(); for ( Match command : commands.each() ) { String name = command.attr("name"); String content = command.text(); list.add( new Command(name, content) ); } return list; }
1
public void formGraph() { a = new ArrayList<>(); for (int i = 0; i < size; i++) { a.add(new HashSet<Integer>()); for (int j = 0; j < size; j++) { if (i != j && matr[i][j] == 1) { a.get(i).add(j); } } } }
4
@Override public void finalize() throws IOException { fileWriter.close(); }
0
@Override public void start() { run = true; if(firstStart) { firstStart = false; super.start(); } }
1
public void saveConfig(String configString, File file) { String configuration = this.prepareConfigString(configString); try { BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(configuration); writer.flush(); writer.close(); } catch (IOException e){e.printStackTrace();} }
1
public AlgorythmFile(String name, String type, File file){ algorythmName = name; algorythmType = type; algorythmFile = file; }
0
public boolean registerCommand(ChunkyCommand command) throws ChunkyUnregisteredException { if (command.getParent() == null) { if (!registeredCommands.containsKey(command.getFullName())) { registeredCommands.put(command.getFullName(), command); registerSuperAliases(command); return true; } return false; } else { ChunkyCommand parentCommand = Chunky.getModuleManager().getCommandByName(command.getParent().getFullName()); if (command.inheritsPermission() && command.getPermission() == null) { command.setPermission(parentCommand.getPermission()); } if (parentCommand != null) { registerSuperAliases(command); return parentCommand.addChild(command); } else { throw new ChunkyUnregisteredException("Parent command not registered!"); } } }
5
public static boolean isValidSolution(Team heroes){ if(useBudget && heroes.getCost() > budget){ return false; } if(heroes.getDurability() < Helper.villains.getDurability()) return false; if(heroes.getEnergy() < Helper.villains.getEnergy()) return false; if(heroes.getFightingSkills() < Helper.villains.getFightingSkills()) return false; if(heroes.getIntelligence() < Helper.villains.getIntelligence()) return false; if(heroes.getSpeed() < Helper.villains.getSpeed()) return false; if(heroes.getStrength() < Helper.villains.getStrength()) return false; return true; }
8
@Override public void handle(IHttpRequest httpRequest,IHttpResponse httpResponse) throws IOException { try{ String command = httpRequest.getParametro("command"); String[] comandi =command.split("_"); for (int i = 0; i < comandi.length; i++) { String comando = comandi[i]; if(!comando.isEmpty()){ String key = comando.substring(0,2); String value = comando.substring(2); if("KP".equals(key)){ kp.handle(value); }else if("KD".equals(key)){ kd.handle(value); }else if("KU".equals(key)){ ku.handle(value); }else if("MU".equals(key)){ mu.handle(value); }else if("MD".equals(key)){ md.handle(value); }else if("RC".equals(key)){ rc.handle(value); } } } }catch(Exception e){ e.printStackTrace(); } httpResponse.sendOK(); }
9
public byte[] getP() { return p; }
0
private void moveRow(Board b, int caller) { int posNr = 0; Position tmp = null; int i, j; int foundPos = -1; i = 1; j = 1; while (j <= b.getHeight()) { i = 1; while (i + 1 <= b.getWidth()) { if (b.isFree(i, j) && b.isFree(i + 1, j)) { b.set(i, j); b.set(i + 1, j); foundPos = pos.search(b.flatten()); tmp = new Position(b); if (isSymmetrien() && foundPos == -1) { foundPos = findSymmetricPosition(b); } if (foundPos == -1) { if (!pos.get(caller).hasChildren(tmp)) { posNr = pos.add(tmp); pos.get(caller).addChild(pos.get(posNr)); move(b, posNr); } } else { if (!pos.get(caller).hasChildren(pos.get(foundPos))) pos.get(caller).addChild(pos.get(foundPos)); } b.clear(i, j); b.clear(i + 1, j); } i++; } j++; } }
9
public void lancerMatchs() throws IOException, ClassNotFoundException, InterruptedException { ArrayList<Partie> match; match = new ArrayList<Partie>(); for(int i=0;i<IA.size();i++) { for(int j=0;j<IA.size();j++) { if(i!=j) { //System.out.println("i: "+i+" j: "+j); match.add(new Partie(IA.get(i),IA.get(j))); if(match.get(match.size()-1).nbPion_gagnant==match.get(match.size()-1).nbPion_perdant) { points.set(i, points.get(i)+1); points.set(j, points.get(j)+1); pionPlus.set(i,(pionPlus.get(i)+match.get(match.size()-1).nbPion_gagnant)); pionMoin.set(i,(pionMoin.get(i)+match.get(match.size()-1).nbPion_perdant)); pionPlus.set(j,(pionPlus.get(j)+match.get(match.size()-1).nbPion_perdant)); pionMoin.set(j,(pionMoin.get(j)+match.get(match.size()-1).nbPion_gagnant)); nul.set(i, nul.get(i)+1); nul.set(j, nul.get(j)+1); } else if(match.get(match.size()-1).gagnant==IA.get(i)) { points.set(i, points.get(i)+3); pionPlus.set(i,(pionPlus.get(i)+match.get(match.size()-1).nbPion_gagnant)); pionMoin.set(i,(pionMoin.get(i)+match.get(match.size()-1).nbPion_perdant)); pionPlus.set(j,(pionPlus.get(j)+match.get(match.size()-1).nbPion_perdant)); pionMoin.set(j,(pionMoin.get(j)+match.get(match.size()-1).nbPion_gagnant)); gagne.set(i, gagne.get(i)+1); perd.set(j, perd.get(j)+1); } else if(match.get(match.size()-1).gagnant==IA.get(j)) { points.set(j, points.get(j)+3); pionPlus.set(j,(pionPlus.get(j)+match.get(match.size()-1).nbPion_gagnant)); pionMoin.set(j,(pionMoin.get(j)+match.get(match.size()-1).nbPion_perdant)); pionPlus.set(i,(pionPlus.get(i)+match.get(match.size()-1).nbPion_perdant)); pionMoin.set(i,(pionMoin.get(i)+match.get(match.size()-1).nbPion_gagnant)); gagne.set(j, gagne.get(j)+1); perd.set(i, perd.get(i)+1); } } } } }
6
private byte[] writeDataIndex(DataIndex dataIndex) throws IOException, XmlException { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getPersister().write(dataIndex, outputStream, "UTF-8"); return outputStream.toByteArray(); } catch (Exception ex) { throw new XmlException(ex); } }
1
private int getLengthHelper(Node<T> node) { if (node == null) { return 0; } else { return 1 + getLengthHelper(node.getTail()); } }
1
public void setLivePanel() { if (livePanel != null) { livePanel.set(mp3list.getSong()); } }
1
public List<ClusterType> getCluster() { if (cluster == null) { cluster = new ArrayList<ClusterType>(); } return this.cluster; }
1
public void save(BufferedWriter out, Object object) throws IOException { IConfig config = (IConfig) object; try { beginConfigTag(out); for (Method method : config.getClass().getMethods()) { if (method.getDeclaringClass().equals(Config.class)) { writeStartTag(method.getName(), out); out.write(String.valueOf(method.invoke(config))); writeEndTag(method.getName(), out); } } endConfigTag(out); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
4
public void paint(Graphics g) { BufferedImage image = new BufferedImage(SCREEN_W, SCREEN_H, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics(); super.paint(g2d); if(loading) return; synchronized(this){ int xOffset = getOffset(player.getColumn(), 13,COLUMNS); int yOffset = getOffset(player.getRow(), 9, ROWS); g2d.drawImage(gridLayers.get(GridType.FLOOR).getImage(), -xOffset, -yOffset, null); g2d.drawImage(gridLayers.get(GridType.WALLS).getImage(), -xOffset, -yOffset, null); g2d.drawImage(gridLayers.get(GridType.TRAPS).getImage(), -xOffset, -yOffset, null); g2d.drawImage(gridLayers.get(GridType.BONUS).getImage(), -xOffset, -yOffset, null); // g2d.drawImage(gridLayers.get(GridType.ITEMS).getImage(), -xOffset, -yOffset, null); g2d.drawImage(gridLayers.get(GridType.MONSTERS).getImage(), -xOffset, -yOffset, null); g2d.drawImage(gridLayers.get(GridType.PLAYERS).getImage(), -xOffset, -yOffset, null); } g2d.setColor(Color.GRAY); g2d.drawLine(0, SCREEN_H-40, SCREEN_W, SCREEN_H-40); g2d.drawImage(heartIcon, 4, SCREEN_H-36, null); g2d.setColor(Color.RED); g2d.fill(new Rectangle2D.Double(40, SCREEN_H-30, 100, 20)); g2d.setColor(Color.GREEN); g2d.fill(new Rectangle2D.Double(40, SCREEN_H-30, 100*(player.getHP()/player.getMaxHP()), 20)); g2d.setColor(Color.BLACK); g2d.drawString((int)player.getHP()+"/"+(int)player.getMaxHP(), 65, SCREEN_H-15); if(minimapEnabled) g2d.drawImage(minimap.getImage(), minimap.getX(), minimap.getY(), null); ArrayList<Bag> bags = player.getBags(); for (int i = 0; i < bags.size(); i ++) { Bag<?> bag = bags.get(i); int x = 700-i*bagSize; if (bag.isOpen()) { int rows = bag.getRows(); int columns = bag.getColumns(); g2d.drawImage(bagPanelImage, x, 500, null); g2d.setColor(new Color(0,0,0,128)); g2d.fill(new Rectangle(x, 500, bagSize, bagSize)); g2d.setColor(new Color(0,0,255,128)); g2d.fill(new Rectangle(x-columns*bagSize+bagSize, 500-rows*bagSize, columns*bagSize, rows*bagSize)); ArrayList<Item>[][] items = bag.getItems(); for (int row = 0; row < items.length; row++) { for (int column = 0; column < items[row].length; column++) { ArrayList<Item> item = items[row][column]; g2d.setColor(new Color(row*25,column*25,row*column*15, 128)); g2d.fill(new Rectangle(x-column*64, 500-row*64-64, bagSize, bagSize)); if(item.size() > 0) { g2d.drawImage(item.get(0).getImage(), x-column*64, 500-row*64-64, null); if(item.size() >1) { g2d.setColor(Color.WHITE); g2d.drawString(item.size()+"", x-column*64, 500-row*64); } } } } } else { g2d.drawImage(bagPanelImage, x, 500, null); } } Graphics2D g2d_final = (Graphics2D) g; g2d_final.drawImage(image, 0, 0, null); }
9
public void print(int n) { if (n > 0) { for (int i = 0;i < n; i++) System.out.print(" "); } System.out.print(intVal + " "); }
2
public void setLatestPreview(Object preview) { if ((this.previewedThread != null) && this.previewedThread.isComplete()) { this.previewLabel.setText("Final result"); Object finalResult = this.previewedThread.getFinalResult(); this.textViewerPanel.setText(finalResult != null ? finalResult .toString() : null); disableRefresh(); } else { double grabTime = this.previewedThread != null ? this.previewedThread .getLatestPreviewGrabTimeSeconds() : 0.0; String grabString = grabTime > 0.0 ? (" (" + StringUtils.secondsToDHMSString(grabTime) + ")") : ""; this.textViewerPanel.setText(preview != null ? preview.toString() : null); if (preview == null) { this.previewLabel.setText("No preview available" + grabString); } else { this.previewLabel.setText("Preview" + grabString); } } }
7
public static void DoTurn(PlanetWars pw) { // (1) Find my strongest planet. Planet source = null; double sourceScore = Double.MIN_VALUE; for (Planet myPlanet : pw.MyPlanets()) { // skip planets with only one ship if (myPlanet.NumShips() <= 1) continue; //This score is one way of defining how 'good' my planet is. double score = (double) myPlanet.NumShips(); if (score > sourceScore) { //we want to maximize the score, so store the planet with the best score sourceScore = score; source = myPlanet; } } // (2) Find the weakest enemy or neutral planet. Planet dest = null; double destScore = Double.MAX_VALUE; for (Planet notMyPlanet : pw.NotMyPlanets()) { //This score is one way of defining how 'good' the planet is. // You can change it to something different and experiment with it. double score = (double) (notMyPlanet.NumShips()); //if you want to debug how the score is computed, decomment the System.err.instructions // System.err.println("Planet: " +notMyPlanet.PlanetID()+ " Score: "+ score); // System.err.flush(); if (score < destScore) { //We want to select the planet with the lowest score destScore = score; dest = notMyPlanet; } } // (3) Attack! if (source != null && dest != null) { pw.IssueOrder(source, dest); } }
7
private boolean readRomanPageBackwards() { ArrayList<Character> saved = new ArrayList<Character>(); char token = prevChar(); // if ( token=='p') // System.out.println("p"); int len = 0; // saved leading newline chars while ( token=='\n'||token=='\r' ) { saved.add(token); token = prevChar(); } while ( roman.contains(token) ) { saved.add(token); token = prevChar(); len++; } // ensure we have read all LFs or CRs (may be DOS) char mismatched = token; while ( token=='\r' || token=='\n' ) { saved.add(token); token = prevChar(); } // save last char - probably a letter saved.add(token); while (saved.size()>0 ) unpush( saved.remove(saved.size()-1) ); return len>0&&(mismatched=='\n'||mismatched=='\r'); }
8
public ScreenArea getMenuBounds() { int color = 6116423; Point mouse = Mouse.getMousePosition(); int x = mouse.x; int y = mouse.y; int lastX = 0; int lastY = 0; int lastXX = 0; int lastYY = 0; for(int i = 0; i < 200; i++) { if(ImageTool.isInTolerance(color, ImageTool.getPixel(x, y), 0)) { lastX = x; } x--; } x = mouse.x; for(int i = 0; i < 200; i++) { if(ImageTool.isInTolerance(color, ImageTool.getPixel(x, y), 0)) { lastXX = x; } x++; } x = mouse.x; for(int i = 0; i < 200; i++) { if(ImageTool.isInTolerance(color, ImageTool.getPixel(x, y), 0)) { lastY = y; } y--; } y = mouse.y; for(int i = 0; i < 200; i++) { if(ImageTool.isInTolerance(color, ImageTool.getPixel(x, y), 0)) { lastYY = y; } y++; } return new ScreenArea(lastX, lastY, lastXX, lastYY); }
8
@Override public void processInput(ByteBuffer buffer) throws IOException { while (buffer.hasRemaining()) { if (parse(buffer.get())) { processRequest(); reset(); } } }
2
private static boolean comparerTabProduitsCode (Produit[] tab, int[] tabTest, int n) { boolean pareil = true; int i = 0; try { if (tab == null && tabTest == null) { pareil = true; } else if (tab != null && tabTest != null && tabTest.length == n){ while (i < n && pareil) { if (tab[i].getCode() != tabTest[i]) { pareil = false; } i++; } } else { pareil = false; } } catch (Exception e) { pareil = false; } return pareil; }
9
@Override public boolean equals(Object object) { if(!(object instanceof Edge<?>)) { return false; } Edge<?> edge = (Edge<?>) object; return from.equals(edge.from) && to.equals(edge.to); }
5
private void postPlugin(Plugin plugin, boolean isPing) throws IOException { // The plugin's description file containg all of the plugin data such as name, version, author, etc PluginDescriptionFile description = plugin.getDescription(); // Construct the post data String data = encode("guid") + '=' + encode(guid) + encodeDataPair("version", description.getVersion()) + encodeDataPair("server", Bukkit.getVersion()) + encodeDataPair("players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length)) + encodeDataPair("revision", String.valueOf(REVISION)); // If we're pinging, append it if (isPing) { data += encodeDataPair("ping", "true"); } // Add any custom data available for the plugin Set<Graph> graphs = getOrCreateGraphs(plugin); // Acquire a lock on the graphs, which lets us make the assumption we also lock everything // inside of the graph (e.g plotters) synchronized(graphs) { Iterator<Graph> iter = graphs.iterator(); while (iter.hasNext()) { Graph graph = iter.next(); // Because we have a lock on the graphs set already, it is reasonable to assume // that our lock transcends down to the individual plotters in the graphs also. // Because our methods are private, no one but us can reasonably access this list // without reflection so this is a safe assumption without adding more code. for (Plotter plotter : graph.getPlotters()) { // The key name to send to the metrics server // The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top // Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME String key = String.format("C%s%s%s%s", CUSTOM_DATA_SEPARATOR, graph.getName(), CUSTOM_DATA_SEPARATOR, plotter.getColumnName()); // The value to send, which for the foreseeable future is just the string // value of plotter.getValue() String value = Integer.toString(plotter.getValue()); // Add it to the http post data :) data += encodeDataPair(key, value); } } } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, plugin.getDescription().getName())); // Connect to the website URLConnection connection; // Mineshafter creates a socks proxy, so we can safely bypass it // It does not reroute POST requests so we need to go around it if (isMineshafterPresent()) { connection = url.openConnection(Proxy.NO_PROXY); } else { connection = url.openConnection(); } connection.setDoOutput(true); // Write the data OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data); writer.flush(); // Now read the response BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String response = reader.readLine(); // close resources writer.close(); reader.close(); if (response.startsWith("ERR")) { throw new IOException(response); //Throw the exception } else { // Is this the first update this hour? if (response.contains("OK This is your first update this hour")) { synchronized (graphs) { Iterator<Graph> iter = graphs.iterator(); while (iter.hasNext()) { Graph graph = iter.next(); for (Plotter plotter : graph.getPlotters()) { plotter.reset(); } } } } } //if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right }
8
public IFilter buildFilterChain() { List<Class<? extends IFilter>> list = getConfiguredFilters(); ListIterator<Class<? extends IFilter>> listIterator = list.listIterator(list.size()); IFilter innerFilter = null; while (listIterator.hasPrevious()) { Class<? extends IFilter> filterClass = listIterator.previous(); Class args[] = new Class[]{IFilter.class}; try { Constructor constructor = filterClass.getDeclaredConstructor(args); IFilter filter = (IFilter) constructor.newInstance(innerFilter); innerFilter = filter; } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return innerFilter; }
8
public Vector AStarSearch(Agent agent) { PQ openQ = new PQ(); // initialize a start node Node startNode = new Node(); startNode.location = startLoc; startNode.costFromStart = 0; startNode.costToGoal = pathCostEstimate(startLoc, goalLoc, agent); startNode.totalCost = startNode.costFromStart + startNode.costToGoal; startNode.parent = null; openQ.add(startNode); open.put(startNode.location, startNode); // process the list until success or failure while (openQ.size() > 0) { Node node = openQ.pop(); open.remove(node.location); // if at a goal, we're done if (node.location.equals(goalLoc)) { return solve(node); } else { Vector neighbors = getNeighbors(node); for (int i = 0; i < neighbors.size(); i++) { Node newNode = (Node) neighbors.elementAt(i); double newCostEstimate = pathCostEstimate(newNode.location, goalLoc, agent); double newCost = node.costFromStart + traverseCost(node, newNode, agent); double newTotal = newCost + newCostEstimate; Location nnLoc = newNode.location; Node holderO, holderC; holderO = (Node) open.get(nnLoc); holderC = (Node) closed.get(nnLoc); if (holderO != null && holderO.totalCost <= newTotal) { continue; } else if (holderC != null && holderC.totalCost <= newTotal) { continue; } else { // store the new or improved info newNode.parent = node; newNode.costFromStart = newCost; newNode.costToGoal = newCostEstimate; newNode.totalCost = newNode.costFromStart + newNode.costToGoal; if (closed.get(nnLoc) != null) { closed.remove(nnLoc); } Node check = (Node) open.get(nnLoc); if (check != null) { openQ.remove(check); open.remove(nnLoc); } openQ.add(newNode); open.put(nnLoc, newNode); } // now done with node } closed.put(node.location, node); } } return null; // failure }
9
public Produtos buscaProdutos(int idProduto){ produtos = this.getProdutos(); this.getConectaBanco(); try { if (this.getConn() != null || !this.getConn().isClosed()) { this.getConn().setAutoCommit(false); this.setStmt(this.getBuscaProdutos()); this.getStmt().setInt(1, idProduto); this.setResultSetProdutos(this.getStmt().executeQuery()); if ( this.getResultSetProdutos().next() ) { produtos.setIdProduto(this.getResultSetProdutos().getInt("idProduto")); produtos.setNomeProduto(this.getResultSetProdutos().getString("nomeProduto")); produtos.setDescricaoProduto(this.getResultSetProdutos().getString("descricaoProduto")); produtos.setImagemProduto(this.getResultSetProdutos().getString("imagemProduto")); produtos.setTipoProduto(this.getResultSetProdutos().getInt("tipoProduto")); produtos.setCategoriaProduto(this.getResultSetProdutos().getInt("categoriaProduto")); produtos.setEmpresaProduto(this.getResultSetProdutos().getInt("empresaProduto")); } this.getConn().commit(); } } catch (SQLException e) { e.printStackTrace(); } finally { if (this.getConn()!= null ){ try { this.getConn().rollback(); } catch (SQLException e) { e.printStackTrace(); } } this.stopConectaBanco(); } return produtos; }
6
public static void cantPass(){ System.out.println("パスできません!おける場所があります。"); }
0
public Program() { days = new Day[7]; for (int i = 0; i < 7; i++) { days[i] = new Day(); } }
1
private boolean method66(int i, int j, int k) { int i1 = i >> 14 & 0x7fff; int j1 = worldController.method304(plane, k, j, i); if(j1 == -1) return false; int k1 = j1 & 0x1f; int l1 = j1 >> 6 & 3; if(k1 == 10 || k1 == 11 || k1 == 22) { ObjectDef class46 = ObjectDef.forID(i1); int i2; int j2; if(l1 == 0 || l1 == 2) { i2 = class46.anInt744; j2 = class46.anInt761; } else { i2 = class46.anInt761; j2 = class46.anInt744; } int k2 = class46.anInt768; if(l1 != 0) k2 = (k2 << l1 & 0xf) + (k2 >> 4 - l1); doWalkTo(2, 0, j2, 0, myPlayer.smallY[0], i2, k2, j, myPlayer.smallX[0], false, k); } else { doWalkTo(2, l1, 0, k1 + 1, myPlayer.smallY[0], 0, 0, j, myPlayer.smallX[0], false, k); } crossX = super.saveClickX; crossY = super.saveClickY; crossType = 2; crossIndex = 0; return true; }
7
@Override public boolean equals(Object otherObj) { if(this == otherObj) return true; if(otherObj == null) return false; if(getClass() != otherObj.getClass()) return false; ExpressionItem other = (ExpressionItem)otherObj; String val = value.toString(); return val.equals(other.getValue()) && type == other.getType(); }
4
public UpdateListener(String message) { this.message = message; }
0
@Override public void run() { try { nouvelleConnexion(); } catch (IOException e1) { System.err.println("Erreur E/S sur l'utilisation des flux lors d'une nouvelle connexion" + e1); } while (true) { try { byte code = fluxEntree.readByte(); if (code == DESACTIVE_BOUTON_PARAMETRE) { FacadeReseau.getInstance().getServeurJeu().avertirTousClientDesactiverParametrer(); } else if (code == OUVRIR_JEU_MASTERMIND) { String chaineRecu = fluxEntree.readUTF(); FacadeReseau.getInstance().getServeurJeu().avertirTousClientOuvrirJeuMastermind(chaineRecu); } else if (code == COPIER_LISTE_JOUEURS) { FacadeReseau.getInstance().getServeurJeu().avertirTousClientCopierListeJoueurs(); } else if (code == COUP_JOUE_SUPPLEMENTAIRE) { String nomClientCoupJoue = fluxEntree.readUTF(); FacadeReseau.getInstance().getServeurJeu().avertirTousClientNouveauCoupJoue(nomClientCoupJoue); } } catch (IOException e) { System.err.println("Erreur E/S sur la reception d'un message du client par le TraitementClient" + e); break; } } }
7
public void setTime(){ if(morningTime){setInterfaceWalkable(65535);} if(afternoonTime){setInterfaceWalkable(12416);} if(eveningTime){setInterfaceWalkable(12418);} if(nightTime){setInterfaceWalkable(12414);}}
4
public void create(Date bookingDate, Date checkinDate, Date checkoutDate, String status) { this.setBookingDate(bookingDate); this.setCheckinDate(checkinDate); this.setCheckoutDate(checkoutDate); this.setStatus(status); }
0
public AbsenceValidator(String msg) { if (msg != null && !msg.isEmpty()) this.msg = msg; }
2
private void writeHref(JspWriter out) throws IOException { if (href != null && !href.isEmpty()) { out.write("href='" + href + "' "); } out.write(">"); }
2
public static boolean checkArticle(String article){ if(!checkSemicolon(article)){ System.out.println("semicolon problem"); return false; } String[] fields = article.split(";"); if(fields.length!=4){ System.out.println("Format not accept"); return false; } if(fields[0]==null||fields[0].isEmpty()){ // No content is not allowed to publish if(fields[3]==null || fields[3].isEmpty()){ System.out.println("content can't be empty"); return false; } return true; } // if has category, then it must match given categroy if(!searchCategory(fields[0])){ System.out.println("category doesn't match"); return false; } // No content is not allowed to publish if(fields[3]==null || fields[3].isEmpty()){ System.out.println(fields[3]); return false; } return true; }
9
protected Object[] handleRemove(Object[] cells) { Set removedRoots = new HashSet(); if (cells != null && cells.length > 0) { Set rootsSet = new HashSet(roots); for (int i = 0; i < cells.length; i++){ if (getParent(cells[i]) == null && rootsSet.contains(cells[i])) { removedRoots.add(cells[i]); } } if (removedRoots.size() > 0) { // If any roots have been removed, reform the roots // lists appropriately, keeping the order the same int newRootsSize = roots.size() - removedRoots.size(); if (newRootsSize < 8) { newRootsSize = 8; } List newRoots = new ArrayList(newRootsSize); Iterator iter = roots.iterator(); while (iter.hasNext()) { Object cell = iter.next(); if (!removedRoots.contains(cell)) { newRoots.add(cell); } } roots = newRoots; } } return removedRoots.toArray(); }
9
public static double scaleTMP(final int port, final int raw, boolean celsius){ double result = (((raw/getResolution(port))*VCC) - 0.5)*100; if (!celsius) // Convert to fahrenheit result = result*((double)9/5) + 32; return new BigDecimal(result).setScale(2, RoundingMode.HALF_UP) .doubleValue(); }
1
public static long getCastleMoves(int player, State4 s){ if(!s.kingMoved[player] && (!s.rookMoved[player][0] || !s.rookMoved[player][1])){ long moves = 0; final long agg = s.pieces[0]|s.pieces[1]; if(!s.rookMoved[player][0] && (Masks.castleBlockedMask[player][0] & agg) == 0 && !maskIsAttacked(Masks.castleThroughCheck[player][0], 1 - player, s)){ moves |= Masks.castleMask[player][0]; } if(!s.rookMoved[player][1] && (Masks.castleBlockedMask[player][1] & agg) == 0 && !maskIsAttacked(Masks.castleThroughCheck[player][1], 1 - player, s)){ moves |= Masks.castleMask[player][1]; } return moves; } return 0; }
9
public void checkCollisions() { for(int i = 0;i<world.entities.size();i++) { Entity e = world.entities.get(i); if(e != this) if(e != null && !alreadyCollisionsChecked.contains(e)) { if(e.clipAABB().collide(clipAABB())) { e.onCollide(this); this.onCollide(e); } e.alreadyCollisionsChecked.add(this); } } doBlockCollisions(); alreadyCollisionsChecked.clear(); }
5
public String authenticate(String supplied) { if(!supplied.equals(password)) { return "Protection proxy: No access"; } else { subject = new Subject(); return "Protection Proxy: Authenticated"; } }
1
private static void putClasses(final List<File> classes, final File directory) { for (final File file : directory.listFiles()) { if (file.isDirectory()) { putClasses(classes, file); } else if (file.toString().endsWith(".class")) { classes.add(file); } } }
3
@Override public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, LogicException { String subcategory = request.getParameter(ParameterName.SUBCATEGORY); String category = request.getParameter(ParameterName.CATEGORY); PrintWriter out; try { out = response.getWriter(); lock.readLock().lock(); Source xmlSource = new StreamSource(PathName.PATH + PathName.XML_PRODUCTS); Transformer transformer; if (subcategory == null) { transformer = StylesheetCache.newTransformer(PathName.PATH + PathName.XSL_CATEGORY); } else { transformer = StylesheetCache.newTransformer(PathName.PATH + PathName.XSL_SUBCATEGORY); transformer.setParameter(ParameterName.NAME_CATEGORY, category); } transformer.transform(xmlSource, new StreamResult(out)); } catch (Exception e) { throw new LogicException(e); } finally { lock.readLock().unlock(); } return null; }
2
@Override public void paint(Graphics g, Component game) { if (gameState == GameState.RUNNING) { // draw background g.drawImage(background, bg1.getBgX(), bg1.getBgY(), game); g.drawImage(background, bg2.getBgX(), bg2.getBgY(), game); // draw tiles paintTiles(g, game); // paint projectiles ArrayList<Bullet> projectiles = hero.getProjectiles(); for (int i = 0; i < projectiles.size(); i++) { Bullet p = projectiles.get(i); g.setColor(Color.YELLOW); g.fillRect(p.getX(), p.getY(), 10, 5); } // draw player currentPlayerImage = hero.getSprite().getAnimation().getImage(); g.drawImage(currentPlayerImage, hero.getCenterX() - 20, hero.getCenterY() - 20, game); // draw enemies for (Enemy enemy : enemies) { currentEnemyImage = enemy.getSprite().getAnimation().getImage(); g.drawImage(currentEnemyImage, enemy.getCenterX() - 48, enemy.getCenterY() - 48, game); } // draw score g.setFont(font); g.setColor(Color.WHITE); g.drawString("Score :" + Integer.toString(score), 700, 30); if (DEBUG_ENABLED) { showDebug(g); // draw boundaries around player g.setColor(Color.LIGHT_GRAY); for (Rectangle rect : boundaries) { g.drawRect((int) rect.getX(), (int) rect.getY(), (int) rect.getWidth(), (int) rect.getHeight()); } } } else if (gameState == GameState.DEAD) { g.setColor(Color.BLACK); g.fillRect(0, 0, 800, 480); g.setColor(Color.WHITE); g.drawString("Game Over!!!", 320, 240); g.setColor(Color.BLUE); g.drawString("Hit ENTER to try again", 270, 290); } }
6
public ConcreteColleagueA(String name) { super(name); }
0
@Override public synchronized void beginW(Actor arg0) throws InterruptedException, DeadLockException { /*Si redacteur ou lecture ou nb minimal de lecture non atteint */ while(writers>0 || readers>0 || N_R>0){ wait(); } writers++; System.out.println("(REDACTEUR) L'Acteur n°"+arg0.ident()+" accède à la rsc n°"+this.ident); this.observator.acquireResource(arg0,this); // Event acquire rsc }
3
private void findCDSSplitLocations(){ //There are no split locations if there is only one/zero CDS if(CDS.size() < 2){ return; } //Forward strand //The CDS are in nucleic acid lengths, but the code needs the lengths in amino acids, so each length must be divided by 3. //Get the first CDS split location exonSplitLocations.add(((double)(CDS.get(0).getLength()) + 1) / 3); //Add in two-last cds split locations. for(int i = 1; i < CDS.size() - 1; i++){ exonSplitLocations.add((((double)(CDS.get(i).getLength()) + 1) / 3) + exonSplitLocations.get(i - 1)); } if(strand == Definitions.genomicStrandNEGATIVE){ //The reverse strand calculates the split locations backwards because the protein is formed backwards. double finalLocation = ((double)CDS.get(CDS.size() - 1).getLength() + 1)/3 + exonSplitLocations.get(CDS.size() - 1 - 1); //Reverse the values based on the length //Work backwards to populate the split temp list. ArrayList<Double> temp = new ArrayList<Double>(); for(Double val: exonSplitLocations){ temp.add(finalLocation - val); } exonSplitLocations = temp; //Reverse the split locations so they are ascending relative to the start of the protein. Collections.sort(exonSplitLocations); }//Reverse //Error check to ensure each location has the exact value that it needs. Rounding with doubles can be funny. ArrayList<Double> tempAdjust = new ArrayList<Double>(); for(int i = 0; i < exonSplitLocations.size() ; i++){ //Deal with truncated numbers becuase comp does not recognize 69.999999999999 = 70 double val = exonSplitLocations.get(i).doubleValue(); int floor = (int)val; int ceiling = floor + 1; double minValue = floor + .9; if(val < ceiling && val >= minValue ){ val = ceiling; }else{ if(val < (int)val + .1){ val = (int)val; } } tempAdjust.add(val); } exonSplitLocations = tempAdjust; }
8
private boolean checkWeight(Item item){ if (item == null){ int weight = 0; for (Weapon weapon : weapons) { weight += weapon.getWeight(); } for (NormalItem object : inventory) { weight += object.getWeight(); } for (Map.Entry<Armor.Type, Armor> entry : protections.entrySet()) { Armor armor = entry.getValue(); weight += armor.getWeight(); } Attribute att = secondary_attr.get("Peso"); att.fillUp(); att.waste(weight); modifySecondaryMap("Peso", att); checkState("Peso"); } else{ int total = secondary_attr.get("Peso").getRemaining() - item.getWeight(); if (total < 0){ MessageControl.showErrorMessage("No puedes coger el objeto " + item.getName(), null); return false; } secondary_attr.get("Peso").waste(item.getWeight()); checkState("Peso"); } return true; }
5
protected String getProperty(String key) { return properties.get(key); }
0