text
stringlengths
14
410k
label
int32
0
9
public final void des_set_key(byte[] key, int[] schedule) throws SecurityException { int c,d,t,s; int inIndex; int kIndex; int i; if (des_check_key) { if (!check_parity(key)) { throw new SecurityException("des_set_key attempted with incorrect parity"); } if (des_is_weak_key(key)) { throw new SecurityException("des_set_key attempted with weak key"); } } inIndex=0; kIndex=0; c =Get32bits(key, inIndex); d =Get32bits(key, inIndex+4); t=(((d>>>4)^c)&0x0f0f0f0f); c^=t; d^=(t<<4); t=(((c<<(16-(-2)))^c)&0xcccc0000); c=c^t^(t>>>(16-(-2))); t=((d<<(16-(-2)))^d)&0xcccc0000; d=d^t^(t>>>(16-(-2))); t=((d>>>1)^c)&0x55555555; c^=t; d^=(t<<1); t=((c>>>8)^d)&0x00ff00ff; d^=t; c^=(t<<8); t=((d>>>1)^c)&0x55555555; c^=t; d^=(t<<1); d= (((d&0x000000ff)<<16)| (d&0x0000ff00) |((d&0x00ff0000)>>>16)|((c&0xf0000000)>>>4)); c&=0x0fffffff; for (i=0; i < 16; i++) { if (shifts2[i]) { c=((c>>>2)|(c<<26)); d=((d>>>2)|(d<<26)); } else { c=((c>>>1)|(c<<27)); d=((d>>>1)|(d<<27)); } c&=0x0fffffff; d&=0x0fffffff; s= des_skb[0][ (c )&0x3f ]| des_skb[1][((c>>> 6)&0x03)|((c>>> 7)&0x3c)]| des_skb[2][((c>>>13)&0x0f)|((c>>>14)&0x30)]| des_skb[3][((c>>>20)&0x01)|((c>>>21)&0x06) | ((c>>>22)&0x38)]; t= des_skb[4][ (d )&0x3f ]| des_skb[5][((d>>> 7)&0x03)|((d>>> 8)&0x3c)]| des_skb[6][ (d>>>15)&0x3f ]| des_skb[7][((d>>>21)&0x0f)|((d>>>22)&0x30)]; schedule[kIndex++]=((t<<16)|(s&0x0000ffff))&0xffffffff; s=((s>>>16)|(t&0xffff0000)); s=(s<<4)|(s>>>28); schedule[kIndex++]=s&0xffffffff; } }
5
public Matrix minus(Matrix B) { Matrix A = this; if (B.M != A.M || B.N != A.N) { throw new RuntimeException("Illegal matrix dimensions."); } Matrix C = new Matrix(M, N); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { C.data[i][j] = A.data[i][j] - B.data[i][j]; } } return C; }
4
@Override protected int runTest(StdConverter.Operation oper) throws Exception { if (oper == null) { throw new RuntimeException("Internal exception: no operation passed"); } final boolean doRead = (oper != StdConverter.Operation.WRITE); final boolean doWrite = (oper != StdConverter.Operation.READ); // read or read-write? if (doRead) { int result = 0; final ByteArrayOutputStream bos = new ByteArrayOutputStream(16000); for (byte[] input : _readableData) { DbData dd = (DbData) _converter.readData(new ByteArrayInputStream(input)); if (dd == null) { throw new IllegalStateException("Deserialized doc to null"); } result += dd.size(); _totalLength += input.length; if (doWrite) { result += _converter.writeData(bos, dd); _totalLength += bos.size(); bos.reset(); } } return result; } // write-only: final ByteArrayOutputStream bos = new ByteArrayOutputStream(16000); int result = 0; for (DbData input : _writableData) { result += _converter.writeData(bos, input); _totalLength += bos.size(); bos.reset(); } return result; }
6
public boolean _setName(String name) { if(name != null) { sprite._setSpriteLabel(name); return true; } else { return false; } }
1
@Test(expected=NotEnoughOperandsException.class) public void evaluatePostfix5() throws DAIndexOutOfBoundsException, DAIllegalArgumentException, NumberFormatException, NotEnoughOperandsException, BadPostfixException { try { postfix.removeFront(); String result = calc.evaluatePostfix(postfix); } catch (DAIndexOutOfBoundsException e) { throw new DAIndexOutOfBoundsException(); } catch (DAIllegalArgumentException e) { throw new DAIllegalArgumentException(); } catch (NumberFormatException e) { throw new NumberFormatException(); } catch (NotEnoughOperandsException e) { throw new NotEnoughOperandsException(); } catch (BadPostfixException e) { throw new BadPostfixException(); } }
5
protected static boolean writeFile(Path file, List<String> lines, boolean append) { assert (file != null) && (lines != null) && (lines.size() > 0); OpenOption[] options; Charset charset = Charset.defaultCharset(); if (append) { options = new OpenOption[] { StandardOpenOption.WRITE, StandardOpenOption.APPEND, StandardOpenOption.CREATE }; } else { options = new OpenOption[] { StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING }; } try (BufferedWriter writer = Files.newBufferedWriter(file, charset, options)) { String separator = System.getProperty("line.separator"); if ((lines == null) || (lines.size() <= 0)) { writer.write(""); } else { for (String line : lines) { writer.write(line + separator); } } writer.flush(); writer.close(); } catch (IOException e) { return false; } assert FileUtil.control(file); return true; }
7
* @param iRow index of row in table * @param iCol index of column in table */ public void setValueAt(Object oProb, int iRow, int iCol) { Double fProb = (Double) oProb; if (fProb < 0 || fProb > 1) { return; } m_fProbs[iRow][iCol] = (double) fProb; double sum = 0; for (int i = 0; i < m_fProbs[iRow].length; i++) { sum += m_fProbs[iRow][i]; } if (sum > 1) { // handle overflow int i = m_fProbs[iRow].length - 1; while (sum > 1) { if (i != iCol) { if (m_fProbs[iRow][i] > sum - 1) { m_fProbs[iRow][i] -= sum - 1; sum = 1; } else { sum -= m_fProbs[iRow][i]; m_fProbs[iRow][i] = 0; } } i--; } } else { // handle underflow int i = m_fProbs[iRow].length - 1; while (sum < 1) { if (i != iCol) { m_fProbs[iRow][i] += 1 - sum; sum = 1; } i--; } } validate(); }
9
public static void drawEmptyCircle(Graphics g, int x, int y){ // d = EMPTY_CIRCLE // center (x + EMPTY_CIRCLE) / 2 , (y + EMPTY_CIRCLE) / 2 // for (int i = 255; i >= 0; i-= (255/10)){ // g.setColor(new Color(i,0,255)); // // } for (int i = 10; i >= -10; i--){ g.setColor(new Color(Math.abs(i * (127 / 10))+127,0,255)); // g.fillOval((x + EMPTY_CIRCLE) / 2 + (EMPTY_CIRCLE / 2) - EMPTY_CIRCLE_THK / 2 + i * EMPTY_CIRCLE_THK / 20, // (y + EMPTY_CIRCLE) / 2 + (EMPTY_CIRCLE / 2) - EMPTY_CIRCLE_THK / 2 + i * EMPTY_CIRCLE_THK / 20, // EMPTY_CIRCLE - EMPTY_CIRCLE_THK / 2 + i * EMPTY_CIRCLE_THK / 20, // EMPTY_CIRCLE - EMPTY_CIRCLE_THK / 2 + i * EMPTY_CIRCLE_THK / 20); g.drawOval(x - i * EMPTY_CIRCLE_THK / 20, y - i * EMPTY_CIRCLE_THK / 20, EMPTY_CIRCLE + i * EMPTY_CIRCLE_THK / 10, EMPTY_CIRCLE + i * EMPTY_CIRCLE_THK / 10); } //g.setColor(MainFrame.getContentPane().getBackground()); //g.fillOval(x + EMPTY_CIRCLE_THK / 2, y + EMPTY_CIRCLE_THK / 2, EMPTY_CIRCLE - EMPTY_CIRCLE_THK, EMPTY_CIRCLE - EMPTY_CIRCLE_THK); }
1
protected ArrayList<Placement> densityMapping(Field[][] map, int c) { shootDensity.clear(); for (int y = 0; y < map.length; ++y) { for (int x = 0; x < map[y].length - shipValue + 1; ++x) { int tmp = 0; for (int z = 0; z < shipValue; ++z) { //tmp = tmp + map[x + z][y].getOppShotTrend(); int tmp2 = map[x + z][y].getOppShotTrend(); if(tmp2 > tmp){ tmp = tmp2; } } Placement temp = new Placement(new Position(x, y), false, tmp); shootDensity.add(temp); } } for (int y = 0; y < map.length - shipValue; ++y) { for (int x = 0; x < map[y].length; ++x) { int tmp = 0; for (int z = 0; z < shipValue; ++z) { //tmp = tmp + map[x][y + z].getOppShotTrend(); int tmp2 = map[x][y + z].getOppShotTrend(); if(tmp2 > tmp){ tmp = tmp2; } } Placement temp = new Placement(new Position(x, y), true, tmp); shootDensity.add(temp); } } if (c > 5) { Collections.sort(shootDensity); } else { Collections.shuffle(shootDensity); } return shootDensity; }
9
@Override public int update(Integer idMetier, Secteur objetMetier) throws Exception { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. }
0
public static boolean compare(Node lhs, Node rhs) { // search each node in trees Depth first. if (lhs == null) { return (rhs == null) ? true : false; } else { if (rhs == null) { return false; } } if (lhs.data == rhs.data) { if (compare(lhs.left, rhs.left)) { return compare(lhs.right, rhs.right); } else { return false; } } else { return false; } }
5
private boolean extraEntity(String outputString, int charToMap) { boolean extra = false; if (charToMap < ASCII_MAX) { switch (charToMap) { case '"' : // quot if (!outputString.equals("&quot;")) extra = true; break; case '&' : // amp if (!outputString.equals("&amp;")) extra = true; break; case '<' : // lt if (!outputString.equals("&lt;")) extra = true; break; case '>' : // gt if (!outputString.equals("&gt;")) extra = true; break; default : // other entity in range 0 to 127 extra = true; } } return extra; }
9
static void generate() { String[] players = {"mosquito.g1.WalkTowardsTheLight", "mosquito.g2.G2Dragonfly", "mosquito.g3.G3Player", "mosquito.g4.Exterminator", "mosquito.g5.G5Player", "mosquito.g6.MosquitoBuster", "mosquito.g7.ZapperPlayer"}; String[] boards = { "Blank", "BoxesAndLines", "Cage", "Caged", "G5.H", "Steps", "W", "spiralMaze", "Sunrise", "Satan++" }; String[] lights = { "3", "5", "8", "13", "100" }; Random r =new Random(); // String[] seeds = new String for(String b : boards) { long[] seeds = new long[20]; for(String p : players) { for(String l : lights) { Statement s; try { s = conn.createStatement(); s.execute("INSERT INTO jobs (job) VALUES (\""+(tpl.replace("PLAYER", p). replace("NUMLIGHTS", l).replace("BOARD", b))+"\")"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
4
public void reapplyRowFilter() { if (mRowFilter != null) { ArrayList<Row> list = new ArrayList<>(mSelection.getCount()); int index = mSelection.firstSelectedIndex(); while (index != -1) { Row row = getRowAtIndex(index); if (mRowFilter.isRowFiltered(row)) { list.add(row); } index = mSelection.nextSelectedIndex(index + 1); } if (!list.isEmpty()) { int anchor = mSelection.getAnchor(); deselect(list); mSelection.setAnchor(anchor); } } }
4
private void insertClientToRouteThatMinimizesTheIncreaseInActualCost(int client,int depot,int period) { double min = 99999999; int chosenVehicle =- 1; int chosenInsertPosition =- 1; double cost; double [][]costMatrix = problemInstance.costMatrix; int depotCount = problemInstance.depotCount; ArrayList<Integer> vehiclesUnderThisDepot = problemInstance.vehiclesUnderThisDepot.get(depot); for(int i=0; i<vehiclesUnderThisDepot.size(); i++) { int vehicle = vehiclesUnderThisDepot.get(i); ArrayList<Integer> route = routes.get(period).get(vehicle); if(route.size()==0) { cost = costMatrix[depot][depotCount+client] + costMatrix[depotCount+client][depot]; if(cost<min) { min=cost; chosenVehicle = vehicle; chosenInsertPosition = 0; } continue; } cost = costMatrix[depot][depotCount+client] + costMatrix[depotCount+client][depotCount+route.get(0)]; cost -= (costMatrix[depot][depotCount+route.get(0)]); if(cost<min) { min=cost; chosenVehicle = vehicle; chosenInsertPosition = 0; } for(int insertPosition=1;insertPosition<route.size();insertPosition++) { //insert the client between insertPosition-1 and insertPosition and check cost = costMatrix[depotCount+route.get(insertPosition-1)][depotCount+client] + costMatrix[depotCount+client][depotCount+route.get(insertPosition)]; cost -= (costMatrix[depotCount+route.get(insertPosition-1)][depotCount+route.get(insertPosition)]); if(cost<min) { min=cost; chosenVehicle = vehicle; chosenInsertPosition = insertPosition; } } cost = costMatrix[depotCount+route.get(route.size()-1)][depotCount+client] + costMatrix[depotCount+client][depot]; cost-=(costMatrix[depotCount+route.get(route.size()-1)][depot]); if(cost<min) { min=cost; chosenVehicle = vehicle; chosenInsertPosition = route.size(); } } routes.get(period).get(chosenVehicle).add(chosenInsertPosition, client); }
7
@Override public List<Autor> ListBySobrenome(String Sobrenome) { Connection conn = null; PreparedStatement pstm = null; ResultSet rs = null; List<Autor> autores = new ArrayList<>(); try{ conn = ConnectionFactory.getConnection(); pstm = conn.prepareStatement(LISTBYSOBRENOME); pstm.setString(1, "%" + Sobrenome + "%"); rs = pstm.executeQuery(); while(rs.next()){ Autor a = new Autor(); a.setId_autor(rs.getInt("id_autor")); a.setNome(rs.getString("nome_au")); a.setSobrenome(rs.getString("sobrenome_au")); a.setEmail(rs.getString("email_au")); autores.add(a); } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao listar autores por sobrenome " + e); }finally{ try{ ConnectionFactory.closeConnection(conn, pstm, rs); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao desconectar do banco " + e); } } return autores; }
3
@Test public void depthest01opponent5() { for(int i = 0; i < BIG_INT; i++) { int numPlayers = 6; //assume/require > 1, < 7 Player[] playerList = new Player[numPlayers]; ArrayList<Color> factionList = Faction.allFactions(); playerList[0] = new Player(chooseFaction(factionList), new SimpleAI()); playerList[1] = new Player(chooseFaction(factionList), new DepthEstAI(0,1,new StandardEstimator())); playerList[2] = new Player(chooseFaction(factionList), new SimpleAI()); playerList[3] = new Player(chooseFaction(factionList), new SimpleAI()); playerList[4] = new Player(chooseFaction(factionList), new SimpleAI()); playerList[5] = new Player(chooseFaction(factionList), new SimpleAI()); Color check = playerList[1].getFaction(); GameState state = new GameState(playerList, new Board(), gameDeck, gameBag, score); Set<Player> winners = Game.run(state, new StandardSettings()); boolean won = false; for(Player p : winners) { if(p.getFaction().equals(check)) { won = true; wins++; if(winners.size() > 1) { tie++; } } } if(!won) { loss++; } } assertEquals(true, wins/(wins+loss) > .8); }
5
private Planet generateNewPlanet() { if(++planetNameIndex >= PLANET_NAMES.length) planetNameIndex = 0; String name = PLANET_NAMES[planetNameIndex]; int bottom = 5000; if(Math.random() <= 0.5) bottom = 3000; else if(Math.random() <= 0.5) bottom = 7000; return new Planet(model, name, false, Planet.getStandardWidth(), bottom); }
3
public boolean isJoined(String a, String b) { ArrayList<String> aList = joinedTables.get(a); if (aList != null) { if (aList.contains(b)) { return true; } } return false; }
2
public static String escapeHTML(String s) { if (s==null) return ""; StringBuffer sb=new StringBuffer(s.length()+100); int length=s.length(); for (int i=0; i<length; i++) { char ch=s.charAt(i); if ('<'==ch) { sb.append("&lt;"); } else if ('>'==ch) { sb.append("&gt;"); } else if ('&'==ch) { sb.append("&amp;"); } else if ('\''==ch) { sb.append("&#39;"); } else if ('"'==ch) { sb.append("&quot;"); } else { sb.append(ch); } } return sb.toString(); }
7
protected boolean arvoreBinariaBuscaValidaAux(Nodo nodo){ if(nodo != null){ Nodo left = nodo.getLeft(); Nodo right = nodo.getRight(); if((left != null && left.getKey() > nodo.getKey()) || (right != null && right.getKey() < nodo.getKey())){ return false; } else{ return (true && arvoreBinariaBuscaValidaAux(left) && arvoreBinariaBuscaValidaAux(right)); } } else{ return true; } }
7
public void writeObject(Object obj, AbstractHessianOutput out) throws IOException { if (out.addRef(obj)) { return; } Class cl = obj.getClass(); try { if (_writeReplace != null) { Object repl; if (_writeReplaceFactory != null) repl = _writeReplace.invoke(_writeReplaceFactory, obj); else repl = _writeReplace.invoke(obj); out.removeRef(obj); out.writeObject(repl); out.replaceRef(repl, obj); return; } } catch (RuntimeException e) { throw e; } catch (Exception e) { // log.log(Level.FINE, e.toString(), e); throw new RuntimeException(e); } int ref = out.writeObjectBegin(cl.getName()); if (ref < -1) { writeObject10(obj, out); } else { if (ref == -1) { writeDefinition20(out); out.writeObjectBegin(cl.getName()); } writeInstance(obj, out); } }
7
private static void objectArrayAppend(StringBuilder sbuf, Object[] a, Set<Object> seenSet) { if (!seenSet.contains(a)) { seenSet.add(a); final int len = a.length; for (int i = 0; i < len; i++) { deeplyAppendParameter(sbuf, a[i], seenSet); if (i != len - 1) { sbuf.append(ARRAY_JOIN_STR); } } // allow repeats in siblings seenSet.remove(a); } else { sbuf.append("..."); } }
3
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if ( this.isEnabled() ) { if ( command.getName().equals("sheepfeed") ) { // check for permission if ( !this.canInfo(sender) ) { sender.sendMessage("You are not allowed to use this command."); return true; } // show naked/regrowing sheep counts sender.sendMessage("There are "+ this.woolGrowingSheep.size() +" sheep regrowing their coat."); // show food info sender.sendMessage("Valid food is: "); List<Integer> foodIDs = this.config.getFoodIDs(); Iterator<Integer> foodIDsIterator = foodIDs.iterator(); while ( foodIDsIterator.hasNext() ) { Integer foodID = foodIDsIterator.next(); SheepFoodData foodData = this.config.getFoodData(foodID); sender.sendMessage(foodData.name +" ("+ foodID +") minticks: "+ foodData.minticks + " maxticks: "+ foodData.maxticks +" healing: "+ foodData.healamount); } return true; } } return super.onCommand(sender, command, label, args); }
4
void clean(QNode pred, QNode s) { Thread w = s.waiter; if (w != null) { // Wake up thread s.waiter = null; if (w != Thread.currentThread()) { LockSupport.unpark(w); } } /* * At any given time, exactly one node on list cannot be deleted -- the * last inserted node. To accommodate this, if we cannot delete s, we * save its predecessor as "cleanMe", processing the previously saved * version first. At least one of node s or the node previously saved * can always be processed, so this always terminates. */ while (pred.next == s) { QNode oldpred = reclean(); // First, help get rid of cleanMe QNode t = getValidatedTail(); if (s != t) { // If not tail, try to unsplice QNode sn = s.next; // s.next == s means s already off list if (sn == s || pred.casNext(s, sn)) { break; } } else if (oldpred == pred || // Already saved oldpred == null && this.cleanMe.compareAndSet(null, pred)) { break; // Postpone cleaning } } }
9
public void gameRun() //gameRun is the true core of the game, this method is called in Main. { boolean gameQuit = false; // player initialization process, below. playerControl.setPlayers(); //Ask for player names //---------------------------------------------- // Main game loop below. while(gameQuit != true) { if(playerTurns()) // if player turns return true, ask for a new game. { if(cout.printNewGame() == "Ja") // if printNewGame returns "No" then quit the game. { gameQuit = true; // set gameQuit to true, so it'll quit. } playerControl.CURRENT_PLAYER_AMOUNT = PLAYER_AMOUNT; // to reset and ensure that the previous winner won't instantly win again. }// end of if(playerTurns()) //---------------------------------------------- } //-------------------END OF MAIN GAME LOOP ------------- }
3
private BufferedImage load(String file){ if(textureMap.get(file) != null) return textureMap.get(file); BufferedImage image = null; try { image = ImageIO.read(getClass().getResourceAsStream(file)); } catch (IOException e) { try { image = ImageIO.read(getClass().getResourceAsStream("/textures/missing_texture.png")); } catch (IOException e1) { e1.printStackTrace(); System.exit(1); } } textureMap.put(file, image); return image; }
3
public AST V() { // V -> D | W | ( L ) List<String> emp = Collections.<String>emptyList(); // an empty list String next = toks.peek(); if ( isNumber(next) ) { // D double d1 = D(); return new Value(new Quantity(d1, emp, emp)); } else if ( isAlphabetic(next) ) { // W String unitName = toks.pop(); return new Value(new Quantity(1.0, Arrays.asList(unitName), emp)); } else if ( "(".equals(next) ) { // ( L ) toks.pop(); // Skip the left parenthesis AST l = L(); // Recursively grab the contents, which should match L. String after_l = toks.peek(); // Immediately following that L should be a right parenthesis. Check if ( ")".equals(after_l) ) { // It's there, so get rid of it (since we want to remove all // the tokens corresponding to V) toks.pop(); return l; // A parenthesized L has the same tree as a non-parenthesized L // (Since the tree structure *already* tells us the way that // our subexpressions are grouped, keeping around these // parentheses in the AST is unnecessary; they wouldn't affect // the final answer.) } else { throw new ParseError("Expected close-parenthesis, but found: '" + next + "'"); } } else { // The first token can't possibly be part of a V. throw new ParseError("Expected number or identifier or subexpression, but found: '" + next + "'"); } }
4
public void update(long dt) { Widget next; for (Widget wdg = child; wdg != null; wdg = next) { next = wdg.next; wdg.update(dt); } }
1
public AlgorythmFile deleteFile(int index){ AlgorythmFile file = dataBaseFiles.remove(index); if(file != null) return file; else return null; }
1
@Test public void testSetRock() { System.out.println("setRock"); Cell instance = new Cell(0,0); instance.setRock(false); boolean expResult = false; boolean result = instance.getRock(); assertEquals(expResult, result); instance.setRock(true); expResult = true; result = instance.getRock(); assertEquals(expResult, result); }
0
private void generateChests() { Random rand = new Random(); Point[] chests = new Point[rand.nextInt(5) + 1]; for (int i = 0; i < chests.length; i++) { boolean a = rand.nextBoolean(); chests[i] = new Point(); chests[i].x = ((a) ? rand.nextInt(w - 2) + 1 : ((rand.nextBoolean()) ? 1 : w - 2)); chests[i].y = ((a) ? ((rand.nextBoolean()) ? 1 : h - 2) : (rand.nextInt(h - 2) + 1)); if (level.getTile(chests[i].x + x, chests[i].y + y) != Tile.DUNGEON_BACK) i--; else { level.generateChest(chests[i].x + x, chests[i].y + y); int r = rand.nextInt(5); for(int j = 0; j < r; j++) InventoryManager.addItem("CHEST_" + (chests[i].x + x) + "_" + (chests[i].y + y), RandomItem.genRanItem()); } } }
7
public boolean isAdmin() { return _prefix.indexOf('a') >= 0; }
0
public Vue(Joueur[] joueurs, org.polytech.nantes.monopoly.manager.Case[] cases) throws Exception { // controle des paramètres if(!(joueurs.length == 2 || joueurs.length == 4)) { throw new Exception("nombre de joueurs renseigné incorrect"); } this.setTitle("Monopoly"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); zoneDesJoueurs = new JoueurArea[joueurs.length]; if(joueurs.length == 4) { this.setSize(1300,700); } else { this.setSize(930,700); } this.setLocationRelativeTo(null); this.setResizable(false); // container principal Container main = this.getContentPane(); main.setLayout(new BorderLayout()); // zone haut et bas zoneDesJoueurs[0] = new JoueurArea(new GridLayout(1,6), joueurs[0]); main.add(zoneDesJoueurs[0],BorderLayout.SOUTH); if(joueurs.length == 2) { zoneDesJoueurs[1] = new JoueurArea(new GridLayout(1,6), joueurs[1]); main.add(zoneDesJoueurs[1],BorderLayout.NORTH); } // zone gauche et droite if(joueurs.length == 4) { zoneDesJoueurs[1] = new JoueurArea(new GridLayout(6,1), joueurs[1]); main.add(zoneDesJoueurs[1],BorderLayout.WEST); zoneDesJoueurs[2] = new JoueurArea(new GridLayout(1,6), joueurs[2]); main.add(zoneDesJoueurs[2],BorderLayout.NORTH); zoneDesJoueurs[3] = new JoueurArea(new GridLayout(6,1), joueurs[3]); main.add(zoneDesJoueurs[3],BorderLayout.EAST); } // clignotement du joueur actif clignotementJoueur = new Timer(500,zoneDesJoueurs[0].getActionClignotement()); clignotementJoueur.start(); // ajout du plateau plateau = new Plateau(joueurs,cases); main.add(plateau, BorderLayout.CENTER); this.setFocusable(true); this.setVisible(true); }
5
static final void method1903(int i, int i_0_, int i_1_, int i_2_, int i_3_, int i_4_, int i_5_, int i_6_) { anInt6866++; int i_7_ = 0; int i_8_ = i_2_; int i_9_ = 0; int i_10_ = -i_3_ + i_0_; int i_11_ = i_2_ + -i_3_; int i_12_ = i_0_ * i_0_; int i_13_ = i_2_ * i_2_; int i_14_ = i_10_ * i_10_; int i_15_ = i_11_ * i_11_; int i_16_ = i_13_ << 1; int i_17_ = i_12_ << 1; int i_18_ = i_15_ << 1; int i_19_ = i_14_ << 1; int i_20_ = i_2_ << 1; int i_21_ = i_11_ << 1; int i_22_ = (-i_20_ + 1) * i_12_ - -i_16_; int i_23_ = -(i_17_ * (-1 + i_20_)) + i_13_; int i_24_ = (-i_21_ + 1) * i_14_ + i_18_; int i_25_ = i_15_ + -(i_19_ * (-1 + i_21_)); int i_26_ = i_12_ << 2; int i_27_ = i_13_ << 2; int i_28_ = i_14_ << 2; int i_29_ = i_15_ << 2; int i_30_ = 3 * i_16_; int i_31_ = (i_20_ + -3) * i_17_; int i_32_ = i_18_ * i_4_; int i_33_ = (-3 + i_21_) * i_19_; int i_34_ = i_27_; int i_35_ = (-1 + i_2_) * i_26_; int i_36_ = i_29_; int i_37_ = (-1 + i_11_) * i_28_; int[] is = Class169_Sub4.anIntArrayArray8826[i_5_]; Class369.method4086(-i_10_ + i_6_, i_1_, i_6_ + -i_0_, is, 0); Class369.method4086(i_10_ + i_6_, i, i_6_ - i_10_, is, 0); Class369.method4086(i_6_ + i_0_, i_1_, i_10_ + i_6_, is, 0); while ((i_8_ ^ 0xffffffff) < -1) { boolean bool = i_8_ <= i_11_; if (bool) { if ((i_24_ ^ 0xffffffff) > -1) { while ((i_24_ ^ 0xffffffff) > -1) { i_24_ += i_32_; i_25_ += i_36_; i_9_++; i_36_ += i_29_; i_32_ += i_29_; } } if (i_25_ < 0) { i_24_ += i_32_; i_25_ += i_36_; i_36_ += i_29_; i_32_ += i_29_; i_9_++; } i_25_ += -i_33_; i_24_ += -i_37_; i_37_ -= i_28_; i_33_ -= i_28_; } if (i_22_ < 0) { while (i_22_ < 0) { i_22_ += i_30_; i_23_ += i_34_; i_7_++; i_34_ += i_27_; i_30_ += i_27_; } } if (i_23_ < 0) { i_23_ += i_34_; i_22_ += i_30_; i_34_ += i_27_; i_7_++; i_30_ += i_27_; } i_22_ += -i_35_; i_23_ += -i_31_; i_8_--; i_35_ -= i_26_; i_31_ -= i_26_; int i_38_ = i_5_ - i_8_; int i_39_ = i_8_ + i_5_; int i_40_ = i_7_ + i_6_; int i_41_ = -i_7_ + i_6_; if (bool) { int i_42_ = i_9_ + i_6_; int i_43_ = i_6_ + -i_9_; Class369.method4086(i_43_, i_1_, i_41_, Class169_Sub4.anIntArrayArray8826[i_38_], 0); Class369.method4086(i_42_, i, i_43_, Class169_Sub4.anIntArrayArray8826[i_38_], 0); Class369.method4086(i_40_, i_1_, i_42_, Class169_Sub4.anIntArrayArray8826[i_38_], 0); Class369.method4086(i_43_, i_1_, i_41_, Class169_Sub4.anIntArrayArray8826[i_39_], 0); Class369.method4086(i_42_, i, i_43_, Class169_Sub4.anIntArrayArray8826[i_39_], 0); Class369.method4086(i_40_, i_1_, i_42_, Class169_Sub4.anIntArrayArray8826[i_39_], 0); } else { Class369.method4086(i_40_, i_1_, i_41_, Class169_Sub4.anIntArrayArray8826[i_38_], 0); Class369.method4086(i_40_, i_1_, i_41_, Class169_Sub4.anIntArrayArray8826[i_39_], 0); } } }
9
private static String exec(String ...cmd) { try { ProcessBuilder pb = new ProcessBuilder(cmd); Process process = pb.start(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream stdout = process.getInputStream(); int readByte = stdout.read(); while(readByte >= 0) { baos.write(readByte); readByte = stdout.read(); } ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); BufferedReader reader = new BufferedReader(new InputStreamReader(bais)); StringBuilder builder = new StringBuilder(); while(reader.ready()) { builder.append(reader.readLine()); } reader.close(); return builder.toString(); } catch(IOException e) { throw new LanternaException(e); } }
3
@Override public Object getRequiredService2(Class serviceType) throws Exception { Object rs = this.getService2(serviceType); if (rs == null) { throw new MissingRequiredServiceException(serviceType); } return rs; }
1
void snapshot() { if (Page.isApplet()) return; boolean b = false; if (implementMwService()) { Method method; Object c = null; try { method = applet.getClass().getMethod("getSnapshotComponent", (Class[]) null); if (method != null) { c = method.invoke(applet, (Object[]) null); } } catch (Exception e1) { e1.printStackTrace(); return; } if (c instanceof Component && ((Component) c).isShowing()) { SnapshotGallery.sharedInstance().takeSnapshot(page.getAddress(), c); b = true; } } if (!b) { SnapshotGallery.sharedInstance().takeSnapshot(page.getAddress(), applet.isShowing() ? applet : PageApplet.this); } }
8
public void visitZeroCheckExpr(final ZeroCheckExpr expr) { if (expr.expr == from) { expr.expr = (Expr) to; ((Expr) to).setParent(expr); } else { expr.visitChildren(this); } }
1
public void actionPerformed(ActionEvent e){ Object object = e.getSource(); if(object == button_calc) { this.supsendBenchmarkLog(); SwingUtilities.invokeLater(new Runnable() { public void run(){attack.outerAttack(key);} }); } else if(object == button_key_length) { key = new BsGs_Key(((key_length)combo_key_length.getSelectedItem()).length); label_public.setText("<html><div style='margin:0px 10px;'><h3>Gegeben:</h3>p = "+key.p+"<br /> g = "+key.g+"<br /> y = "+key.y+"</div></html>"); } else if(object == button_heapsize){ BsGs_HeapUsage_Thread.getInstance(); } }
3
public boolean canEncode(Serializable structure) { return true; }
0
@Override public Multiple build() { try { Multiple record = new Multiple(); record.intField = fieldSetFlags()[0] ? this.intField : (java.lang.Integer) defaultValue(fields()[0]); record.floatField = fieldSetFlags()[1] ? this.floatField : (java.lang.Float) defaultValue(fields()[1]); record.stringField = fieldSetFlags()[2] ? this.stringField : (java.lang.CharSequence) defaultValue(fields()[2]); return record; } catch (Exception e) { throw new org.apache.avro.AvroRuntimeException(e); } }
4
private void markExploredCell(String descriptor) throws ArenaTemplateException { String binStr = null; try{ binStr = hexToBinaryStr(descriptor); }catch(NumberFormatException e){ throw new ArenaTemplateException(2, "The descriptor contains some non-hex digit"); } if(binStr.length() != this.rowCount * this.columnCount + 4){ throw new ArenaTemplateException(3, "Invalid Map Descriptor"); } if(!(binStr.charAt(0) == '1' && binStr.charAt(0) == '1' && binStr.charAt(302) == '1' && binStr.charAt(303) == '1')){ throw new ArenaTemplateException(3, "Invalid Map Descriptor"); } // System.out.println("Original in Hex: " + descriptor); // System.out.println("Original in Binary: " + binStr); // System.out.println("No header & trailer: " + binStr); //Cut the header and trailer 11 binStr = binStr.substring(2, 302); for(int rowIndex = this.rowCount - 1; rowIndex >= 0;rowIndex--){ for(int colIndex = 0;colIndex < this.columnCount;colIndex++){ int strIndex = this.columnCount * (this.rowCount - 1 - rowIndex) + colIndex; if(binStr.charAt(strIndex) == '1'){ this.arena[rowIndex][colIndex] = CellState.EMPTY; }else{ this.arena[rowIndex][colIndex] = CellState.UNEXPLORED; } } } }
9
static void downloadFailedFile(final String url) throws IOException { synchronized (downloadedUrls) { if (downloadedUrls.contains(url)) { SparkUtils.getLogger().info("url already downloaded:" + url); return; } else { downloadedUrls.add(url); synchronized (downloadedUrlWriter) { downloadedUrlWriter.write(url); downloadedUrlWriter.write("\n"); } } } EXECUTOR_SERVICE.execute(new Runnable() { @Override public void run() { try { HttpService httpService = new HttpService(); String[] ems = url.split("/"); String saveUrl = GutenbergCrawler.GUTENBERG_FAILED_ZIP_DIR + ems[ems.length - 1]; httpService.downloadFile(url, saveUrl); // SparkUtils.unzipFile(saveUrl, // GutenbergCrawler.GUTENBERG_TXT_DIR); } catch (IOException e) { try { synchronized (failedUrls) { failedUrls.add(url); synchronized (failedUrlWriter) { failedUrlWriter.write(url); failedUrlWriter.write("\n"); } } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }); }
3
public void validate() throws InvalidMenuException{ if(style == null || mainColor == null || titleColor == null || pageColor == null || title == null){ throw new InvalidMenuException("Property null"); } if(usePrefix && prefix == null){ throw new InvalidMenuException("Prefix null and enabled"); } }
7
public static void main(String[] args) { Random r = new Random(); ArrayList<Integer> ArrayA = new ArrayList<Integer>(); ArrayList<Integer> ArrayB = new ArrayList<Integer>(); ArrayList<Integer> ArrayC = new ArrayList<Integer>(); ArrayA.add(r.nextInt(10)); ArrayA.add(r.nextInt(10)); ArrayA.add(r.nextInt(10)); ArrayA.add(r.nextInt(10)); ArrayA.add(r.nextInt(10)); ArrayA.add(r.nextInt(10)); ArrayA.add(r.nextInt(10)); ArrayB.add(r.nextInt(10)); ArrayB.add(r.nextInt(10)); ArrayB.add(r.nextInt(10)); ArrayB.add(r.nextInt(10)); ArrayB.add(r.nextInt(10)); ArrayB.add(r.nextInt(10)); System.out.println("ArrayA :"+ArrayA.toString()); System.out.println("ArrayB :"+ArrayB.toString()); for (int i = 0; i < ArrayA.size(); i++) { for (int j = 0; j < ArrayB.size(); j++) { if (ArrayA.get(i) == ArrayB.get(j) && !ArrayC.contains(ArrayA.get(i))) { ArrayC.add(ArrayA.get(i)); } } } System.out.println("ArrayC :"+ArrayC.toString()); }
4
public int FindRouterPacket(int seq) { int result = -1; //search for the sequence number for(int x=0; x<internalMemory.size();x++) { //compare each packet sequence with the sequence number if(internalMemory.get(x).GetSequenceNumber() == seq) { //set the index of packet if sequence matches result = x; } } //return index of packet return result; }
2
public String getString(String expression, Object context) throws XPathExpressionException { assert(expression != null); if(context == null) { assert(document != null); context = document; } return (String) xpath.evaluate(expression, context, XPathConstants.STRING); }
1
public void compileShader() { glLinkProgram(program); if (glGetProgram(program, GL_LINK_STATUS) == 0) { System.err.println(glGetShaderInfoLog(program, 2024)); System.exit(1); } glValidateProgram(program); if (glGetProgram(program, GL_VALIDATE_STATUS) == 0) { System.err.println(glGetShaderInfoLog(program, 2024)); System.exit(1); } }
2
public static void main (String[] args) throws IOException { // starts the REPL boolean repl = true; while (repl) { try { // split input on semicolons, only grab and interpret statements before the first semicolon Scanner scan = new Scanner(System.in).useDelimiter(";"); System.out.print("TrajDB > "); String input = scan.next(); input = input.replaceAll("\\s+"," "); String[] argu = input.split(" "); // different function calls - requires statement to terminate with a semicolon (no previous break) if (input.matches("^(CREATE \\w+)$")) { System.out.println("create"); CreateTraj.create(argu[1]); } else if (input.matches("^(INSERT INTO \\w+ VALUES (([\\d.]+,[\\d.]+,[\\d.]+,[\\d.]+,[\\d.]" + "+,\\d\\d\\d\\d-\\d\\d-\\d\\d,\\d\\d:\\d\\d:\\d\\d)\\s?)+)$")) { System.out.println("insert"); String[] trajs = Arrays.copyOfRange(argu, 4, argu.length); int ret = InsertTraj.insert(argu[2], trajs); System.out.println(ret); } else if (input.matches("^(DELETE FROM \\w+ TRAJECTORY \\d+)$")) { System.out.println("delete"); // System.out.println("args: " + argu[2] + ", " + argu[4]); String result = DeleteTraj.delete(argu[2],argu[4]); System.out.println(result); } else if (input.matches("^(RETRIEVE FROM \\w+ TRAJECTORY \\d+)$")) { System.out.println("retrieve trajectory set"); // System.out.println("args: " + argu[2] + ", " + argu[4]); String traj = RetrieveTraj.retrieve(argu[2], argu[4]); System.out.println("Trajectory: " + traj); } else if (input.matches("^(RETRIEVE FROM \\w+ COUNT OF \\d+)$")) { System.out.println("retrieve trajectory count"); // System.out.println("args: " + argu[2] + ", " + argu[5]); int count = RetrieveTraj.getCount(argu[2],argu[5]); System.out.println("Number of measures: " + count); } else if (input.matches("^(EXIT)$")) { System.out.println("exit"); repl = false; } else { throw new SyntaxException("Syntax Error Detected"); } } catch (Exception e) {e.printStackTrace();} } }
8
int getDifference(Image image, Colour q, int x1, int y1, int x2, int y2) throws ImageTooSmallException { if (image.getWidth() <= x1 || image.getHeight() <= y1 || image.getWidth() <= x2 || image.getHeight() <= y2 || x1 < 0 || x2 < 0 || y1 < 0 || y2 < 0) { throw new ImageTooSmallException(); } return image.getPixel(y2, x2, q) - image.getPixel(y1, x1, q); }
8
@Override protected void doRemoveAll() { try { cache.removeAll(); } catch (Throwable e) { CacheErrorHandler.handleError(e); } }
1
public Vector2 GetLightPos(int j) { int i = 0; ComputedPlace p = null; while ((p = places[i++][j]) == null) ; double max = p.h * p.w; for (; i < places.length; i++) { ComputedPlace t1 = places[i][j]; if (t1 != null) { double t2 = t1.h * t1.w; if (t2 > max) { max = t2; p = t1; } } } return (new Vector2(p.getX(), p.getY())); }
4
public double getAttenuationConstant(){ if(this.distributedResistance==0.0D && this.distributedConductance==0.0D){ this.generalAttenuationConstant = 0.0D; } else{ this.generalAttenuationConstant = Complex.sqrt(this.getDistributedImpedance().times(this.getDistributedAdmittance())).getReal(); } return this.generalAttenuationConstant; }
2
protected boolean[] datasetIntegrity( boolean nominalPredictor, boolean numericPredictor, boolean stringPredictor, boolean datePredictor, boolean relationalPredictor, boolean multiInstance, int classType, boolean predictorMissing, boolean classMissing) { print("scheme doesn't alter original datasets"); printAttributeSummary( nominalPredictor, numericPredictor, stringPredictor, datePredictor, relationalPredictor, multiInstance, classType); print("..."); int numTrain = getNumInstances(), numClasses = 2, missingLevel = 20; boolean[] result = new boolean[2]; Instances train = null; Instances trainCopy = null; ASSearch search = null; ASEvaluation evaluation = null; try { train = makeTestDataset(42, numTrain, nominalPredictor ? getNumNominal() : 0, numericPredictor ? getNumNumeric() : 0, stringPredictor ? getNumString() : 0, datePredictor ? getNumDate() : 0, relationalPredictor ? getNumRelational() : 0, numClasses, classType, multiInstance); if (missingLevel > 0) addMissing(train, missingLevel, predictorMissing, classMissing); search = ASSearch.makeCopies(getSearch(), 1)[0]; evaluation = ASEvaluation.makeCopies(getEvaluator(), 1)[0]; trainCopy = new Instances(train); } catch (Exception ex) { throw new Error("Error setting up for tests: " + ex.getMessage()); } try { search(search, evaluation, trainCopy); compareDatasets(train, trainCopy); println("yes"); result[0] = true; } catch (Exception ex) { println("no"); result[0] = false; if (m_Debug) { println("\n=== Full Report ==="); print("Problem during training"); println(": " + ex.getMessage() + "\n"); println("Here are the datasets:\n"); println("=== Train Dataset (original) ===\n" + trainCopy.toString() + "\n"); println("=== Train Dataset ===\n" + train.toString() + "\n"); } } return result; }
9
private boolean containsExcludeToken(String agentString) { if (excludeList != null) { for (String exclude : excludeList) { if (agentString != null && agentString.toLowerCase().indexOf(exclude.toLowerCase()) != -1) return true; } } return false; }
4
private void parseID3v1ExtendedTag(byte[] tagInput) { int runningIndex = -1; // find header "TAG" for (int i = 0; i < tagInput.length; i++) { boolean foundT = tagInput[i] == (byte) 'T'; boolean foundA = (tagInput.length > i + 1 && tagInput[i + 1] == (byte) 'A'); boolean foundG = (tagInput.length > i + 2 && tagInput[i + 2] == (byte) 'G'); boolean foundPlus = (tagInput.length > i + 3 && tagInput[i + 3] == (byte) '+'); if (foundT && foundA && foundG && foundPlus) { runningIndex = i; break; } } if (runningIndex > 0) { byte[] tagData = new byte[bufferLength]; System.arraycopy(tagInput, runningIndex, tagData, 0, bufferLength); // System.out.println("tag data= " + new String(tagData)); runningIndex = 4; title = new String(tagData, runningIndex, 60); runningIndex += 60; artist = new String(tagData, runningIndex, 60); runningIndex += 60; album = new String(tagData, runningIndex, 60); runningIndex += 60; speed = tagData[runningIndex++]; genre = new String(tagData, runningIndex, 30); runningIndex += 30; startTime = new String(tagData, runningIndex, 6); runningIndex += 6; endTime = new String(tagData, runningIndex, 6); cleanUpData(); } }
9
void compress(int init_bits, OutputStream outs) throws IOException { int fcode; int i /* = 0 */; int c; int ent; int disp; int hsize_reg; int hshift; // Set up the globals: g_init_bits - initial number of bits g_init_bits = init_bits; // Set up the necessary values clear_flg = false; n_bits = g_init_bits; maxcode = MAXCODE(n_bits); ClearCode = 1 << (init_bits - 1); EOFCode = ClearCode + 1; free_ent = ClearCode + 2; a_count = 0; // clear packet ent = nextPixel(); hshift = 0; for (fcode = hsize; fcode < 65536; fcode *= 2) ++hshift; hshift = 8 - hshift; // set hash code range bound hsize_reg = hsize; cl_hash(hsize_reg); // clear hash table output(ClearCode, outs); outer_loop: while ((c = nextPixel()) != EOF) { fcode = (c << maxbits) + ent; i = (c << hshift) ^ ent; // xor hashing if (htab[i] == fcode) { ent = codetab[i]; continue; } else if (htab[i] >= 0) // non-empty slot { disp = hsize_reg - i; // secondary hash (after G. Knott) if (i == 0) disp = 1; do { if ((i -= disp) < 0) i += hsize_reg; if (htab[i] == fcode) { ent = codetab[i]; continue outer_loop; } } while (htab[i] >= 0); } output(ent, outs); ent = c; if (free_ent < maxmaxcode) { codetab[i] = free_ent++; // code -> hashtable htab[i] = fcode; } else cl_block(outs); } // Put out the final code. output(ent, outs); output(EOFCode, outs); }
9
public boolean hasNext() { if (iit == null || !iit.hasNext()) { if (!it.hasNext()) { return false; } Map.Entry<K, ArrayList<Long>> item = it.next(); key = item.getKey(); iit = item.getValue().iterator(); } return true; }
3
protected void loadResource(ResourceSpecs<T> specs) { if (specs == null) return; String uri = specs.getUri(); if (uri == null || uri.length() == 0) { if (isVerbose()) Log.d(TAG, "1. Resource was not loaded, uri is empty"); specs.onLoaded(null, true, false); return; } T res = getFromMemoryCache(toCacheKey(uri)); if (res != null) { if (isVerbose()) Log.d(TAG, "1. Resource is loaded from memory cache in same moment: " + uri); specs.onLoaded(res, true, false); } else { if (isVerbose()) Log.d(TAG, "1. Resource is posted to the queue: " + uri); specs.onPrepare(); mLoadingManager.addSpecs(specs); } if (mManagerThread == null) { mManagerThread = new Thread(new ManagerTask()); mManagerThread.start(); } }
8
public String printLineNumber(boolean printAlso){ currentLineNumber = lineNumber++; return printLineNumber && printAlso ? String.valueOf(currentLineNumber) + ". " : ""; }
2
public static boolean exportHover(double xPos,double yPos) { int check = 0; if((xPos > exportXborderL) && (xPos < exportXborderR)) check+=1; if((yPos > exportYborderT) && (yPos < exportYborderB)) check+=1; return check == 2; }
4
private void serialize(OutputStream out) throws IOException { LinkFlags lf = header.getLinkFlags(); ByteWriter bw = new ByteWriter(out); header.serialize(bw); if (lf.hasLinkTargetIDList()) idlist.serialize(bw); if (lf.hasLinkInfo()) info.serialize(bw); if (lf.hasName()) bw.writeUnicodeString(name); if (lf.hasRelativePath()) bw.writeUnicodeString(relativePath); if (lf.hasWorkingDir()) bw.writeUnicodeString(workingDir); if (lf.hasArguments()) bw.writeUnicodeString(cmdArgs); if (lf.hasIconLocation()) bw.writeUnicodeString(iconLocation); for (Serializable i : extra.values()) i.serialize(bw); bw.write4bytes(0); out.close(); }
8
public void gridletSubmit(Gridlet gl, boolean ack) { // update the current Gridlets in exec list up to this point in time updateGridletProcessing(); // reset number of PE since at the moment, it is not supported if (gl.getNumPE() > 1) { String userName = GridSim.getEntityName( gl.getUserID() ); System.out.println(); System.out.println(super.get_name() + ".gridletSubmit(): " + " Gridlet #" + gl.getGridletID() + " from " + userName + " user requires " + gl.getNumPE() + " PEs."); System.out.println("--> Process this Gridlet to 1 PE only."); System.out.println(); // also adjusted the length because the number of PEs are reduced int numPE = gl.getNumPE(); double len = gl.getGridletLength(); gl.setGridletLength(len*numPE); gl.setNumPE(1); } ResGridlet rgl = new ResGridlet(gl); boolean success = false; // if there is an available PE slot, then allocate immediately if (gridletInExecList_.size() < super.totalPE_) { success = allocatePEtoGridlet(rgl); } // if no available PE then put the ResGridlet into a Queue list if (!success) { rgl.setGridletStatus(Gridlet.QUEUED); gridletQueueList_.add(rgl); } // sends back an ack if required if (ack) { super.sendAck(GridSimTags.GRIDLET_SUBMIT_ACK, true, gl.getGridletID(), gl.getUserID() ); } }
4
void insert(String key, T value) { if (key.isEmpty()) { this.value = value; return; } char c = key.charAt(0); String substr = key.substring(1); if (c < character) { if (left == 0) { left = createNode(buffer, c, substr.isEmpty() ? value : null); } buffer.get(left).insert(key, value); } else if (c > character) { if (right == 0) { right = createNode(buffer, c, substr.isEmpty() ? value : null); } buffer.get(right).insert(key, value); } else { if (substr.isEmpty()) { this.value = value; } else { if (center == 0) { center = createNode(buffer, substr.charAt(0), null); } buffer.get(center).insert(substr, value); } } }
9
public boolean isValidMove(Direction d) { if(d == Direction.DOWN) { if(compare(currentBlock, blockRow, blockCol, 1, 0) == true) return true; else return false; } else if(d == Direction.RIGHT) { if(compare(currentBlock, blockRow, blockCol, 0, 1) == true) return true; else return false; } else if(d == Direction.LEFT) { if(compare(currentBlock, blockRow, blockCol, 0, -1) == true) return true; else return false; } else if(d == Direction.ROTATE) { // Potential bug fix, still test of currentBlock not modified // TO-DO: try catch for null pointer exception try { tempBlock = currentBlock.clone(); tempBlock.rotate(); if(compare(tempBlock, blockRow, blockCol, 0, 0) == true) return true; else return false; } catch(Exception e) { System.out.println(e); return false; } } else return false; }
9
@org.junit.Test public void testBlocking() throws com.grey.base.GreyException, java.io.IOException { FileOps.deleteDirectory(rootdir); final com.grey.naf.BufferSpec bufspec = new com.grey.naf.BufferSpec(0, 10); final String rdwrdata = "This goes into an xmtpool buffer"; //deliberately larger than IOExecWriter's buffer-size final String rdonlydata = "This is a read-only buffer"; //deliberately larger than IOExecWriter's buffer-size final String initialchar = "z"; final java.nio.ByteBuffer rdonlybuf = com.grey.base.utils.NIOBuffers.encode(rdonlydata, null, false).asReadOnlyBuffer(); com.grey.naf.DispatcherDef def = new com.grey.naf.DispatcherDef(); def.hasNafman = false; def.surviveHandlers = false; Dispatcher dsptch = Dispatcher.create(def, null, com.grey.logging.Factory.getLogger("no-such-logger")); java.nio.channels.Pipe pipe = java.nio.channels.Pipe.open(); java.nio.channels.Pipe.SourceChannel rep = pipe.source(); java.nio.channels.Pipe.SinkChannel wep = pipe.sink(); rep.configureBlocking(false); CMW cm = new CMW(dsptch, wep, bufspec); org.junit.Assert.assertTrue(cm.isConnected()); // write to the pipe till it blocks org.junit.Assert.assertFalse(cm.chanwriter.isBlocked()); int pipesize = 0; while (cm.write(initialchar)) pipesize++; org.junit.Assert.assertTrue(cm.chanwriter.isBlocked()); String expectdata = initialchar; // pipe has now blocked, so do some more sends for (int loop = 0; loop != 3; loop++) { cm.chanwriter.transmit(rdonlybuf); org.junit.Assert.assertTrue(cm.chanwriter.isBlocked()); expectdata += rdonlydata; } com.grey.base.utils.ByteChars bc = new com.grey.base.utils.ByteChars(rdwrdata); for (int loop = 0; loop != 10; loop++) { boolean done = cm.write(bc); org.junit.Assert.assertFalse(done); org.junit.Assert.assertTrue(cm.chanwriter.isBlocked()); expectdata += rdwrdata; } //need to do this send to test main enqueue() loop java.nio.ByteBuffer niobuf = com.grey.base.utils.NIOBuffers.encode(rdwrdata, null, false); boolean done = cm.write(niobuf); org.junit.Assert.assertFalse(done); org.junit.Assert.assertTrue(cm.chanwriter.isBlocked()); expectdata += rdwrdata; int xmitcnt = pipesize + expectdata.length(); // Read the first pipe-load of data. // Even though we allocate a big enough rcvbuf, we're not guaranteed to read it all in one go. java.nio.ByteBuffer rcvbuf = com.grey.base.utils.NIOBuffers.create(xmitcnt+10, false); //a few bytes to spare int rcvcnt = 0; while (rcvcnt < pipesize) { int nbytes = rep.read(rcvbuf); rcvcnt += nbytes; org.junit.Assert.assertTrue("Last read="+nbytes, rcvcnt <= pipesize); for (int idx = 0; idx != nbytes; idx++) { org.junit.Assert.assertEquals(initialchar.charAt(0), rcvbuf.get(idx)); } } //there will be no more data to read till Dispatcher triggers the Writer int nbytes = rep.read(rcvbuf); org.junit.Assert.assertEquals(0, nbytes); org.junit.Assert.assertTrue(cm.chanwriter.isBlocked()); done = cm.disconnect(); //should be delayed by linger org.junit.Assert.assertFalse(done); // start the Dispatcher and wait for writer to drain its backlog dsptch.start(); bc = new com.grey.base.utils.ByteChars(); int rdbytes = 0; rcvbuf.clear(); while ((nbytes = rep.read(rcvbuf)) != -1) { if (nbytes == 0) continue; for (int idx = 0; idx != nbytes; idx++) { bc.append(rcvbuf.get(idx)); } rcvbuf.clear(); rdbytes += nbytes; } org.junit.Assert.assertEquals(xmitcnt - pipesize, rdbytes); org.junit.Assert.assertTrue(StringOps.sameSeq(expectdata, bc)); dsptch.stop(); dsptch.waitStopped(); synchronized (cm) { org.junit.Assert.assertTrue(cm.completed); } rep.close(); org.junit.Assert.assertFalse(cm.isConnected()); org.junit.Assert.assertFalse(dsptch.isRunning()); org.junit.Assert.assertEquals(bufspec.xmtpool.size(), bufspec.xmtpool.population()); }
8
public boolean open( ) { state = State.PROCESSING; setVisible(true); while (state == State.PROCESSING); return(state == State.OKAY); }
1
@Override public boolean tick(final Tickable ticking, final int tickID) { if((flag==State.STOPPED)||(amDestroyed())) return false; tickStatus=Tickable.STATUS_START; if(tickID==Tickable.TICKID_AREA) { tickStatus=Tickable.STATUS_BEHAVIOR; if (numBehaviors() > 0) { eachBehavior(new EachApplicable<Behavior>() { @Override public final void apply(final Behavior B) { B.tick(ticking, tickID); } }); } tickStatus = Tickable.STATUS_SCRIPT; if (numScripts() > 0) { eachScript(new EachApplicable<ScriptingEngine>() { @Override public final void apply(final ScriptingEngine S) { S.tick(ticking, tickID); } }); } tickStatus = Tickable.STATUS_AFFECT; if (numEffects() > 0) { eachEffect(new EachApplicable<Ability>() { @Override public final void apply(final Ability A) { if (!A.tick(ticking, tickID)) A.unInvoke(); } }); } if(shipItem != null) shipItem.tick(ticking, tickID); } tickStatus=Tickable.STATUS_NOT; return true; }
8
public void scaleUp(){ switch (polygonPaint) { case 0: line.ScaleUp(); repaint(); break; case 1: curv.ScaleUp(); repaint(); break; case 2: triangle.ScaleUp(); repaint(); break; case 3: rectangle.ScaleUp(); repaint(); break; case 4: cu.ScaleUp(); repaint(); break; case 5: elipse.ScaleUp(); repaint(); break; case 6: arc.ScaleUp(); repaint(); break; } repaint(); }
7
public void getCurrentRooms(CommandSender sender) { ArrayList <String> current = new ArrayList <String> (); Player [] player = Bukkit.getServer().getOnlinePlayers(); for (int i = 0; i < player.length; i++) { if (current.contains(config.getConfig().getString("Player."+player[i].getName()+".CR"))) { } else { if (new isPrivate().IsPrivate(config.getConfig().getString("Player."+player[i].getName()+".CR"))) current.add(ChatColor.LIGHT_PURPLE+config.getConfig().getString("Player."+player[i].getName()+".CR")); else current.add(ChatColor.DARK_AQUA+config.getConfig().getString("Player."+player[i].getName()+".CR")); } }//close for int x = 0; for (int i = 0; i < current.size(); i++) { x+=i; for (x += 1; x < current.size(); x++) if (current.get(i).equalsIgnoreCase(current.get(x))) current.remove(x); }//close for sender.sendMessage(ChatColor.GRAY+"Current chatrooms in use: ("+ChatColor.DARK_AQUA+"public"+ChatColor.GRAY+","+ChatColor.LIGHT_PURPLE+" private"+ChatColor.GRAY+")"); String subed = (current.toString()).substring(1,current.toString().length()-1); sender.sendMessage(subed); } //close get current rooms
6
public static Tetromino generatePiece() { Random r = new Random(); Tetromino t; switch (r.nextInt(7)) { case 0: t = TypeI; break; case 1: t = TypeL; break; case 2: t = TypeJ; break; case 3: t = TypeO; break; case 4: t = TypeT; break; case 5: t = TypeZ; break; case 6: t = TypeS; break; default: t = null; } return t; }
7
public static void loadWhitelistConfigYAML(MainClass mainClass) { File file = new File(path + "Whitelist/config.yml"); FileConfiguration f = YamlConfiguration.loadConfiguration(file); for(String str : f.getStringList("Whitelist")) { mainClass.whitelist.add(str.toLowerCase()); } }
1
private String getNbrString() { String r = ""; for (NbrCostPair ncp : nbrList) { if (r.length() > 0) r += ", "; r += ncp.getNbr().getId() + "[" + ncp.getCost() + "]"; } return r; }
2
private String getErrors(String algChoice, String matroidChoice, String oracleType) { error = new String[] {"", "", "", ""}; boolean runFailed = false; if (algChoice.length()==0) { error[0] = "an algorithm,\r"; runFailed = true; } if (matroidChoice==null) { runFailed = matroidIsRunFailed(error); } else if (matroidChoice.length()==0) { runFailed = matroidIsRunFailed(error); } if (oracleType==null) { runFailed = oracleIsRunFailed(error); } else if (oracleType.length()==0) { runFailed = oracleIsRunFailed(error); } if (runFailed) { return ("You must select\r" + error[0] + error[1] + error[2] + error[3] + "to run."); } return null; }
6
private void list_movesMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_list_movesMousePressed current_move=null; current_sprite=null; hitbox_index_selected=-1; frame_index_selected=-1; //Add frames listOfMoves_main_file = main_doc.getElementsByTagName("Move"); DefaultListModel model = new DefaultListModel(); for(int s=0; s<listOfMoves_main_file.getLength() ; s++) { Node move_node = listOfMoves_main_file.item(s); Element move_element = (Element)move_node; if(move_element.getAttribute("name").equals(list_moves.getSelectedValue())) { int frames = Integer.parseInt(move_element.getAttribute("frames")); for(int i=0;i<frames;i++) { model.add(i, "frame "+(i+1)); } break; } } list_frames.setModel(model); //Clear hitboxes list DefaultListModel clean_model = new DefaultListModel(); //Upadate current_move listOfMoves_sprites_file = sprites_doc.getElementsByTagName("Move"); for(int s=0; s<listOfMoves_sprites_file.getLength() ; s++)//Move loop { Node move_node = listOfMoves_sprites_file.item(s); Element move_element = (Element)move_node; if(move_element.getAttribute("name").equals(list_moves.getSelectedValue())) { current_move=move_element; } } }//GEN-LAST:event_list_movesMousePressed
5
public boolean avoidAsteroid(){ boolean hit=false; for(int b=0;b<objects.size();b++){ if(objects.get(b).kind!=0) continue; boolean obstacle = collisionCircle((int)(x+vx),(int)(y+vy),h/2,(int)(objects.get(b).x),(int)(objects.get(b).y),(int)(objects.get(b).h/2)); if(obstacle) { hit=true; } } return hit; }
3
private JPanel createSortingPane() { JPanel sorting = new JPanel(); sorting.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); sorting.setLayout(new BoxLayout(sorting, BoxLayout.PAGE_AXIS)); JSlider slider; String[] props = controller.getParametersBean().getSortingProperties(); for (String property : props) { sorting.add(new JLabel(property)); slider = new JSlider(new BeanControlledModel(property)); sorting.add(slider); } return sorting; }
1
public void setRenderer(int row, int column) { if(column == 0) setHorizontalAlignment(SwingConstants.CENTER); else if (column == 1) { setHorizontalAlignment(SwingConstants.RIGHT); for (int i=0;i<highlightIndex.size(); i++) { if(row == ((Integer)highlightIndex.elementAt(i)).intValue()) { setForeground(Color.blue); break; } } if (row == flashIndex) setBackground(Color.orange); } if (row < startEnabling || row > endEnabling && grayDisabledRange) setForeground(Color.lightGray); }
8
private void handleSelectedAction() { if (!Commons.get().isKeyPressed() && (Keyboard.isKeyDown(Keyboard.KEY_RETURN) || Mouse .isButtonDown(0) && isMouseOnSelection(currentSelection))) { Commons.get().setKeyPressed(true); switch (currentSelection) { case YES: Sounds.get().playAccept(); doYes(); break; case NO: Sounds.get().playDecline(); doNo(); break; } } }
6
public static void main(String[] args) { Scanner input = new Scanner(System.in); String[] words = input.nextLine().toLowerCase().split("[\\W\\d]+"); TreeMap<String, Integer> wordsHashMap = new TreeMap<>(); for (String word: words) { if (wordsHashMap.containsKey(word)) { wordsHashMap.put(word, wordsHashMap.get(word) + 1); } else { wordsHashMap.put(word, 1); } } Set<String> keys = wordsHashMap.keySet(); int maxNumber = 0; for (String key : keys) { if (wordsHashMap.get(key) > maxNumber) { maxNumber = wordsHashMap.get(key); } } for (String key : keys) { if (maxNumber == wordsHashMap.get(key)) { System.out.printf("%s - > %d times%n", key, maxNumber); } } }
6
public boolean existeCliente(String nick, String email){ getLista g = new getLista(); ListaClientes = g.getListaCliente(); ListaProveedores = g.getListaProveedor(); for(int i = 0;i<ListaClientes.size();i++){ if(ListaClientes.get(i).getNick().equals(nick) || ListaClientes.get(i).getEmail().equals(email)){ return true; } } for(int i = 0;i<ListaProveedores.size();i++){ if(ListaProveedores.get(i).getNick().equals(nick) || ListaProveedores.get(i).getEmail().equals(email)){ return true; } } return false; }
6
public static String md5(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] byteDigest = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < byteDigest.length; offset++) { i = byteDigest[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } // 32位加密 return buf.toString(); // 16位的加密 // return buf.toString().substring(8, 24); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
4
public String XMLtoResources (int number){ try { String path = new File(".").getCanonicalPath(); FileInputStream file = new FileInputStream(new File(path + "/xml/resources.xml")); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document xmlDocument = builder.parse(file); XPath xPath = XPathFactory.newInstance().newXPath(); System.out.println("************************************"); String expression01 = "/Levels/level[@stage=" + Integer.toString(number) + "]/firstname"; NodeList nodeList01 = (NodeList) xPath.compile(expression01) .evaluate(xmlDocument, XPathConstants.NODESET); for (int i = 0; i < nodeList01.getLength(); i++) { System.out.println(nodeList01.item(i).getFirstChild() .getNodeValue()); resources = nodeList01.item(i).getFirstChild() .getNodeValue(); } System.out.println("************************************"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } return resources; }
6
public boolean symmetricalEqual(TreeNode a, TreeNode b){ if(a == null && b == null) return true; else if(a != null && b == null || a == null && b != null) return false; else if(a.val == b.val) return true && symmetricalEqual(a.right, b.left) && symmetricalEqual(a.left, b.right); else return false; }
9
private TableData join(HashMap<String, TableData> result) { //Queue<String> todo=new LinkedList<String>(); //Queue<String> temp=new LinkedList<String>(); String leftId=idsTobeJoin.remove(idsTobeJoin.size()-1); int index=idsTobeJoin.size()-1; String rightId; ArrayList<String> finishedId=new ArrayList<String>(); finishedId.add(leftId); //left Table Data: TableData tdLeft;//get it from result or primary table depending //left is primary boolean leftIsPrimary; if(result.containsKey(leftId)) { tdLeft=result.get(leftId); leftIsPrimary=false; } else { tdLeft=primarytables.get(from.get(leftId)); leftIsPrimary=true; } while( !idsTobeJoin.isEmpty()) { rightId=idsTobeJoin.remove(index); //System.out.println("id "+rightId+" will be joined!\nFinishedId will contain: "); //join the two tables below: //Joins todo: get from multiTableJoins,need to search which one has it JoinsTodo jtd=findExpression(finishedId, rightId); ArrayList<Expression> exprs; if(jtd==null) { idsTobeJoin.add(idsTobeJoin.size(), rightId); index--; continue; } else { exprs=jtd.getExpression(); String id1=jtd.getID().getId1(); //leftId=(rightId==id1)? jtd.getID().getId2():id1; if(rightId.equals(id1)) { leftId=jtd.getID().getId2(); } else { leftId=jtd.getID().getId1(); } //System.out.println("Find the match: LeftId="+leftId+" RightId="+rightId); index=idsTobeJoin.size()-1; } //right Table Data: TableData tdRight; //right is primary boolean rightIsPrimary; if(result.containsKey(rightId)) { tdRight=result.get(rightId); rightIsPrimary=false; } else { tdRight=primarytables.get(from.get(rightId)); rightIsPrimary=true; } tdLeft=doJoin(leftId, tdLeft, leftIsPrimary, rightId, tdRight, rightIsPrimary, exprs); leftIsPrimary=false; finishedId.add(rightId); /* Iterator<String> iter=finishedId.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } */ } return tdLeft; }
5
@EventHandler public void onPlayerInteract(PlayerInteractEvent event) { if (event.getPlayer().getItemInHand().getType() == Material.SLIME_BALL && event.getAction() == Action.RIGHT_CLICK_BLOCK) { plugin.debugMessage("Block name: " + event.getClickedBlock().getType()); plugin.debugMessage("Block location: " + event.getClickedBlock().getX() + ", " + event.getClickedBlock().getY() + ", " + event.getClickedBlock().getZ()); plugin.debugMessage("Block data: " + event.getClickedBlock().getData()); plugin.debugMessage("Block LightLevel: " + event.getClickedBlock().getLightLevel()); plugin.debugMessage("Block Chunk: " + event.getClickedBlock().getChunk().toString()); } plugin.cancelEvent(event); plugin.debugMessage(event); plugin.godMode(event); }
2
public static List<Venue> createFromResultSet(ResultSet result) throws SQLException { List<Venue> rtn = new ArrayList<Venue>(); while(result.next()) { rtn.add(createOneFromResultSet(result)); } return rtn; }
1
public int calcPayment() { return ((int)(this.getEffMult()*this.getBase())); }
0
public void setRASOutput() throws BadLocationException { if (rasChecker.isSimpleNet()) { simplePNLabel.setText("OK"); simplePNLabel.setForeground(RASConst.greenColor); } else { simplePNLabel.setText("False"); simplePNLabel.setForeground(RASConst.redColor); } //-------------------------------------------- if (rasChecker.getNumbOfPlacesWithTokens() == 1) { idleStateLabel.setText("OK"); idleStateLabel.setForeground(RASConst.greenColor); } else { idleStateLabel.setText("False"); idleStateLabel.setForeground(RASConst.redColor); } //-------------------------------------------- if (rasChecker.getNumbOfPlacesWithoutTokens() > 0) { processStateLabel.setText("OK"); processStateLabel.setForeground(RASConst.greenColor); } else { processStateLabel.setText("False"); processStateLabel.setForeground(RASConst.redColor); } //---------------------resourceLabel----------- if (rasChecker.getNumbOfRecources() > 0) { resourceLabel.setText("OK"); resourceLabel.setForeground(RASConst.greenColor); } else { resourceLabel.setText("False"); resourceLabel.setForeground(RASConst.redColor); } //-------------------------------------------- if (rasChecker.getListOfOwnCyclePairs().isEmpty()) { ownCycleLabel.setText("OK"); ownCycleLabel.setForeground(RASConst.greenColor); ownCycleLabel.setToolTipText(null); } else { ownCycleLabel.setText("False"); ownCycleLabel.setForeground(RASConst.redColor); String tooltipString = ""; for (OwnCyclePair ocp : rasChecker.getListOfOwnCyclePairs()) { tooltipString = tooltipString + ocp.getPlace().getName() + " - " + ocp.getTransition().getName() + "\n"; } ownCycleLabel.setToolTipText(tooltipString); } //---------------------resourceIniLabel----------- if (rasChecker.getNumbOfRecources() > 0) { resIniLabel.setText("OK"); resIniLabel.setForeground(RASConst.greenColor); } else { resIniLabel.setText("False"); resIniLabel.setForeground(RASConst.redColor); } //---------------------idleIniLabel----------- if (rasChecker.getNumbOfPlacesWithTokens() > 0) { idleIniLabel.setText("OK"); idleIniLabel.setForeground(RASConst.greenColor); } else { idleIniLabel.setText("False"); idleIniLabel.setForeground(RASConst.redColor); } //---------------------resourceLabel----------- if (rasChecker.isProcessPlacesIni()) { procIniLabel.setText("OK"); procIniLabel.setForeground(RASConst.greenColor); } else { procIniLabel.setText("False"); procIniLabel.setForeground(RASConst.redColor); } }
9
private boolean isContactAdded(Contact contact) { for(int i=0; i<addedContactCount; i++) { Contact addedContact = contacts[i]; if(addedContact.getFirstName().equalsIgnoreCase(contact.getFirstName())) { if(addedContact.getLastName().equalsIgnoreCase(contact.getLastName())) { if(addedContact.getMiddleName().equalsIgnoreCase(contact.getMiddleName())) { return true; } } } } return false; }
4
@Override public File execute(File wd, String[] cmd) { // TODO Auto-generated method stub try { if (cmd.length == 3) { File f1 = new File(wd, cmd[1]); if (!f1.exists()) throw new FileNotFoundException(); File f2 = new File(wd, cmd[2]); if (f2.exists()) throw new IOException(); boolean success = f1.renameTo(f2); if (!success) throw new RuntimeException(); System.out.println("Operation rename was successful!"); } else { System.err.println("Not enoguh parameters."); } } catch (FileNotFoundException e) { System.err.print("First parameter doesnt exist."); e.printStackTrace(); } catch (IOException e) { System.err.print("Cannot rename beacuse a file with that name already exist."); e.printStackTrace(); } catch(RuntimeException e) { System.err.print("Something went wrong while renaming the file."); e.printStackTrace(); } return null; }
7
protected Class getTransitionClass() { return MealyTransition.class; }
0
public static int indexOf(final String s, final char searchChar, final int beginIndex, final int endIndex) { for (int i = beginIndex; i < endIndex; i++) { if (s.charAt(i) == searchChar) { return i; } } return -1; }
2
public static void testDomainTheory(Symbol relationName, Symbol className) { { Surrogate renamed_Class = Logic.getDescription(className).surrogateValueInverse; Proposition prop = null; Cons consQuery = Stella.NIL; QueryIterator query = null; List instances = Logic.allClassInstances(renamed_Class).listify(); boolean correctP = true; int numCorrect = 0; { Stella_Object instance = null; Cons iter000 = instances.theConsList; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { instance = iter000.value; consQuery = Cons.consList(Cons.cons(relationName, Cons.cons(Logic.objectName(instance), Stella.NIL))); prop = ((Proposition)(Logic.conceiveFormula(((Cons)(Stella_Object.copyConsTree(consQuery)))))); correctP = true; if (Proposition.trueP(prop)) { System.out.println(consQuery + " is true"); Proposition.helpUpdateTopLevelProposition(prop, Logic.KWD_RETRACT_TRUE); query = Logic.makeQuery(Stella.NIL, ((Cons)(Stella_Object.copyConsTree(Cons.list$(Cons.cons(Logic.SYM_STELLA_NOT, Cons.cons(consQuery, Cons.cons(Stella.NIL, Stella.NIL))))))), Stella.NIL, Stella.NIL); if (TruthValue.trueTruthValueP(Logic.callAsk(query))) { correctP = false; System.out.println(" **Theory disproves " + consQuery + " true"); } query = Logic.makeQuery(Stella.NIL, ((Cons)(Stella_Object.copyConsTree(consQuery))), Stella.NIL, Stella.NIL); if (TruthValue.unknownTruthValueP(Logic.callAsk(query))) { correctP = false; System.out.println(" **Theory cannot prove " + consQuery); } Proposition.helpUpdateTopLevelProposition(prop, Logic.KWD_ASSERT_TRUE); } if (Proposition.falseP(prop)) { System.out.println(consQuery + " is false"); Proposition.helpUpdateTopLevelProposition(prop, Logic.KWD_RETRACT_FALSE); query = Logic.makeQuery(Stella.NIL, ((Cons)(Stella_Object.copyConsTree(consQuery))), Stella.NIL, Stella.NIL); if (TruthValue.trueTruthValueP(Logic.callAsk(query))) { correctP = false; System.out.println(" **Theory proves " + consQuery + "true"); } query = Logic.makeQuery(Stella.NIL, ((Cons)(Stella_Object.copyConsTree(Cons.list$(Cons.cons(Logic.SYM_STELLA_NOT, Cons.cons(consQuery, Cons.cons(Stella.NIL, Stella.NIL))))))), Stella.NIL, Stella.NIL); if (TruthValue.unknownTruthValueP(Logic.callAsk(query))) { correctP = false; System.out.println(" **Theory cannot disprove " + consQuery); } Proposition.helpUpdateTopLevelProposition(prop, Logic.KWD_ASSERT_FALSE); } if (correctP) { numCorrect = numCorrect + 1; } } } { System.out.println(); System.out.println("Theory got " + numCorrect + " out of " + instances.length()); } ; } }
8
public void setSizeY(int y) { ySize = y; image = new BufferedImage(xSize, ySize, BufferedImage.TYPE_INT_RGB); for (int i = 0; i < xSize; i++) { for (int j = 0; j < ySize; j++) { image.setRGB(i, j, 0xffffff); } } }
2
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); final List<Ability> offensiveAffects=returnOffensiveAffects(mob,target); if((success)&&(offensiveAffects.size()>0)) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("A visible glow surrounds <T-NAME>."):L("^S<S-NAME> @x1 for <T-NAMESELF> to speak.^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); for(int a=offensiveAffects.size()-1;a>=0;a--) offensiveAffects.get(a).unInvoke(); } } else beneficialWordsFizzle(mob,target,auto?"":L("<S-NAME> @x1 for <T-NAMESELF>, but nothing happens.",prayWord(mob))); // return whether it worked return success; }
8
private void generate() { rand = new Random(); MazeNode initial = grid[rand.nextInt(x_Dim)][rand.nextInt(y_Dim)][rand .nextInt(z_Dim)]; MazeNode current = initial; current.setVisited(true); int count = 1; int size = x_Dim * y_Dim * z_Dim; // checks if all nodes in maze have been visited; continues of not while (count < size) { // checks if all nodes adjacent to current have been visited; // continues if so if (!allVisited(current)) { MazeNode chosen = null; int dir = 0; // randomly chooses an unvisited adjacent node and moves to it while (chosen == null || chosen.isVisited()) { dir = rand.nextInt(6); chosen = current.getNeighbors()[dir]; } // current node is pushed onto stack theStack.push(current); // wall is removed between current node and chosen node current.setWalls(false, dir); chosen.setWalls(false, oppDir(dir)); // chosen node becomes current node and visited flag is set current = chosen; current.setVisited(true); // count is incremented count++; // checks if stack is empty; continues if so } else if (!theStack.isEmpty()) { // a node is popped from the stack and becomes current node current = theStack.pop(); // if all adjacent nodes to current have been visited and the // stack is empty // a random unvisited node becomes the current node } else { MazeNode temp = current; while (temp.isVisited()) { temp = grid[rand.nextInt(x_Dim)][rand.nextInt(y_Dim)][rand .nextInt(z_Dim)]; } current = temp; current.setVisited(true); count++; } } // start node is chosen startNode(); }
6
private void showCommandPrompt() { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print(localName + "# "); String inputCommand; try { while ((inputCommand = in.readLine()) != null) { String[] tokens = inputCommand.split(" "); if ("show".equals(tokens[0])) { ArrayList<TimeStampedMessage> tmpLogs= new ArrayList<TimeStampedMessage>(); TimeStampedMessage message; while ((message = (TimeStampedMessage) receive()) != null) { tmpLogs.add(message); // System.out.println(message); } Collections.sort(tmpLogs, new TimeStampedMessageComparator()); this.sortedLogs.addAll(tmpLogs); if(tokens.length == 1){ this.displayLogs(this.sortedLogs); } else if("new".equals(tokens[1])){ this.displayLogs(tmpLogs); } } else if ("q".equals(tokens[0])) { System.exit(0); } else { // Invalid command System.out.println("Couldn't recognize this command."); } } System.out.print(localName + "# "); } catch (IOException e) { e.printStackTrace(); } }
7
@Test public void testPropertiesFile() { String[] testPropsAFF = {"duration", "title", "author", "album", "date", "comment", "copyright", "ogg.bitrate.min", "ogg.bitrate.nominal", "ogg.bitrate.max"}; String[] testPropsAF = {"vbr", "bitrate"}; try { File file = new File(filename); AudioFileFormat baseFileFormat = AudioSystem.getAudioFileFormat(file); System.out.println("-> Filename : " + filename + " <-"); System.out.println(baseFileFormat); Map<String, Object> properties = baseFileFormat.properties(); System.out.println(properties); for (String key : testPropsAFF) { if (properties.get(key) != null) { String val = (properties.get(key)).toString(); System.out.println(key + "=" + val); } } for (String key : testPropsAF) { if (properties.get(key) != null) { String val = (properties.get(key)).toString(); System.out.println(key + "=" + val); } } } catch (UnsupportedAudioFileException | IOException e) { Assert.fail("testPropertiesFile : " + e.getMessage()); } }
5