text
stringlengths
14
410k
label
int32
0
9
public void clear() { try { prefs.clear(); } catch (Exception e) { } }
1
public static float base_score(boolean player, GameState gs) { if (player) { int resources = 0; for (int i = 0; i < gs.getResourceTypes(); i++) { resources += gs.getResources(i); } float score = resources*RESOURCE; for(Unit u:gs.getMyUnits()) { score += u.getResources() * RESOURCE_IN_WORKER; int cost = 0; for (int i = 0; i < u.getCost().size(); i++) { cost += u.getCost(i); } score += UNIT_BONUS_MULTIPLIER * (cost*u.getHP())/(float)u.getMaxHP(); } return score; } int resources = 0; for (int i = 0; i < gs.getNeutralUnits().size(); i++) { resources += gs.getNeutralUnits().get(i).getResources(); } float score = resources*RESOURCE; for(Unit u:gs.getOtherUnits()) { score += u.getResources() * RESOURCE_IN_WORKER; int cost = 0; for (int i = 0; i < u.getCost().size(); i++) { cost += u.getCost(i); } score += UNIT_BONUS_MULTIPLIER * (cost*u.getHP())/(float)u.getMaxHP(); } return score; }
7
public RoomCell(int row, int col, String init) { super(row, col); if (init.length()==1){ doorDirection = DoorDirection.NONE; }else{ room = false; if(init.charAt(1)=='U'){doorDirection = DoorDirection.UP; //System.out.println("Door direction is up " + row + " " + col); } else if(init.charAt(1)=='D'){ doorDirection = DoorDirection.DOWN; //System.out.println("Door direction is down " + row + " " + col); } else if(init.charAt(1)=='R'){ doorDirection = DoorDirection.RIGHT; //System.out.println("Door direction is right " + row + " " + col); } else if(init.charAt(1)=='L'){ doorDirection = DoorDirection.LEFT; //System.out.println("Door direction is left " + row + " " + col); } } initial = init.charAt(0); }
5
@Test public void testGetMessageMultipleSubscribers() { try { int noOfSubscribers = 2; final AtomicInteger msgCount = new AtomicInteger(0); final String message = "TestMessage-testGetMessage_MultipleSubscribers"; final CountDownLatch gate = new CountDownLatch(noOfSubscribers); final Message expected = new MockMessage(message); for (int i = 0; i < noOfSubscribers; i++) { AsyncMessageConsumer testSubscriber = new MockTopicSubscriber() { public void onMessage(Message received) { assertNotNull("Received Null Message", received); assertEquals("Message values are not equal", message, received.getMessage()); msgCount.incrementAndGet(); gate.countDown(); } }; destination.addSubscriber(testSubscriber); } destination.put(expected); boolean messageReceived = gate.await(100, TimeUnit.MILLISECONDS); assertTrue("Did not receive message in 100ms", messageReceived); assertEquals("Unexpected number of messages received", 1 * noOfSubscribers, msgCount.get()); } catch (InterruptedException e) { fail("Wait InterruptedException" + e.getMessage()); } catch (DestinationClosedException e) { fail("DestinationClosedException" + e.getMessage()); } }
3
public static void main(String[] args) { String filename = args[0]; String separator = args[1]; In in = new In(filename); ST<String, Queue<String>> st = new ST<String, Queue<String>>(); ST<String, Queue<String>> ts = new ST<String, Queue<String>>(); while (in.hasNextLine()) { String line = in.readLine(); String[] fields = line.split(separator); String key = fields[0]; for (int i = 1; i < fields.length; i++) { String val = fields[i]; if (!st.contains(key)) st.put(key, new Queue<String>()); if (!ts.contains(val)) ts.put(val, new Queue<String>()); st.get(key).enqueue(val); ts.get(val).enqueue(key); } } StdOut.println("Done indexing"); // read queries from standard input, one per line while (!StdIn.isEmpty()) { String query = StdIn.readLine(); if (st.contains(query)) for (String vals : st.get(query)) StdOut.println(" " + vals); if (ts.contains(query)) for (String keys : ts.get(query)) StdOut.println(" " + keys); } }
9
private void updateEnemyPositions() { nextRow = 0; for(int i = 0; i < enemys.length; i++) { for(int j = 0; j < enemys[i].length; j++) { if(!enemys[i][j].isAlive()) { continue; } //Update all positions and if one reaches the bound the variable is set nextRow |= enemys[i][j].move(ENEMY_MOVEMENT_SPEED, this.getWidth()); } } if(nextRow == 1 || nextRow == -1) { for(int i = 0; i < enemys.length; i++) { for(int j = 0; j < enemys[i].length; j++) { enemys[i][j].oneRowDown(nextRow); enemys[i][j].move(ENEMY_MOVEMENT_SPEED * 2, this.getWidth()); } } } }
7
private void WriteRemoteConf() throws RemoteException{ if(null == localConfPath || "" == localConfPath){ throw new RemoteException("local localConfPath is not correct.please set SetConfpathWithName()"); } try { if(!CanCommitFile()){ throw new RemoteException("the remote Nginx.conf has modified before.Please check remote Nginx.conf timestamp"); } SCPClient scpc=conn.createSCPClient(); String localFile = GetlocalConfFullName(); String remoteConfDirectory = remoteConf.substring(0, remoteConf.lastIndexOf("/")); scpc.put(localFile, remoteConfDirectory); //update local datetimestamp oldConfDatestamp = getFileModifyTime(); } catch (IOException e) { throw new RemoteException(e.getMessage()); } }
4
private void requestBidInfos(TACConnection conn) { Bid bid; int bidID; try { for (int i = 0; i < NO_AUCTIONS; i++) { bid = bids[i]; if (bid != null && ((bidID = bid.getID()) != Bid.NO_ID) && !quotes[i].isAuctionClosed()) { TACMessage msg = new TACMessage("bidInfo"); msg.setParameter("bidID", bidID); msg.setUserData(bid); conn.sendMessage(msg, this); } } } catch (IOException e) { log.log(Level.SEVERE, "could not request bid infos", e); reset(0, conn); } requestTransactions(OP_NOOP); }
5
public Row cancelColumn(final int index, final Row otherrow, final BigInteger useModulus) { // special case: our col[index] is already zero: if (this.isColumnZero(index)) { return this; } boolean samesign = this.sameSign(index, otherrow); BigInteger mult = this.getColumn(index); if (samesign) { mult = mult.negate(); } Row cancel = otherrow.multiplyConstant(mult); mult = otherrow.getColumn(index); Row usethis = this.multiplyConstant(mult); if (! samesign) { usethis = usethis.negate(); } Row ret = null; if (! usethis.sameSign(index, cancel)) { ret = usethis.add(cancel); if (useModulus != null) { if (ret.cols[0].signum() == -1) { // modfix: not proven to reduce errors: mod down the column value //ret.cols[0] = ret.cols[0].mod(useModulus); // modfix: let's try keeping cols[0] positive: usethis = usethis.negate(); cancel = cancel.negate(); ret = usethis.add(cancel); } } } else { throw new SecretShareException("prog error this(" + index + ")=" + this.getColumn(index) + " other(" + index + ")=" + cancel.getColumn(index)); } return ret; }
6
void enviarJugada(PartidaChip partida, InetAddress ip, int puerto) { try { Socket cli = new Socket(ip, puerto); System.out.println("[]-->Enviando: " + partida.getMensaje() + " a " + ip); ObjectOutputStream flujo_objetos = new ObjectOutputStream( cli.getOutputStream()); flujo_objetos.writeObject(partida); cli.close(); } catch (IOException e) { e.printStackTrace(); } }
1
int getSize(){ int size = 8; if(value != 0) { cw.newUTF8("ConstantValue"); size += 8; } if((access & Opcodes.ACC_SYNTHETIC) != 0 && (cw.version & 0xffff) < Opcodes.V1_5) { cw.newUTF8("Synthetic"); size += 6; } if((access & Opcodes.ACC_DEPRECATED) != 0) { cw.newUTF8("Deprecated"); size += 6; } if(signature != 0) { cw.newUTF8("Signature"); size += 8; } if(anns != null) { cw.newUTF8("RuntimeVisibleAnnotations"); size += 8 + anns.getSize(); } if(ianns != null) { cw.newUTF8("RuntimeInvisibleAnnotations"); size += 8 + ianns.getSize(); } if(attrs != null) { size += attrs.getSize(cw, null, 0, -1, -1); } return size; }
8
@Test public void testRoomSetConstructorBadInput() { try { Room r2 = new Room(null); //null test fail("IllegalArgumentException was expected"); } catch (IllegalArgumentException e){ //exception expected } try { Room r2 = new Room(s); //empty set test fail("IllegalArgumentException was expected"); } catch (IllegalArgumentException e){ //exception expected } }
2
void chooseAction(HttpServletRequest request, HttpServletResponse response, HttpSession session, String query, ActionsController a) throws ServletException, IOException, SQLException { switch (request.getParameter("action")) { case "details": int postId = Integer.parseInt(request.getParameter("id")); a.postDetails(request, response, postId); break; case "login": a.login(request, response, session); a.renderAllPosts(request, response); break; case "new_post": a.addToDatabase(request, response); break; case "logout": session.removeAttribute("userLoggedIn"); a.redirectHome(request, response); break; case "edit": int id = Integer.parseInt(request.getParameter("id")); a.editPost(request, response, id); break; case "edit_post": a.replacePost(request, response); break; case "new_comment": a.processComment(request, response); break; case "filter_posts": a.filterPosts(request, response); break; case "delete": a.deletePost(request, response); break; default: // System.out.println("default chooseAction"); } }
9
public static void main(String args[]){ GenericsType<String> g1 = new GenericsType<String>(); g1.set("Pankaj"); GenericsType<String> g2 = new GenericsType<String>(); g2.set("Pankaj"); GenericsType<Integer> g3 = new GenericsType<Integer>(); g3.set(10); GenericsType<Integer> g4 = new GenericsType<Integer>(); g4.set(22); boolean isEqual2 = GenericsMethods.isEqual(g3, g4); System.out.println(isEqual2); boolean isEqual = GenericsMethods.<String>isEqual(g1, g2); //above statement can be written simply as // isEqual = GenericsMethods.isEqual(g1, g2); //This feature, known as type inference, allows you to invoke a generic method as an ordinary method, without specifying a type between angle brackets. //Compiler will infer the type that is needed System.out.println(isEqual); }
0
@Override protected void setColoredExes() { ParametricCurve ermit = new ErmitCurve(allex); coloredEx = ermit.Calculation(); }
0
public void link() { synchronized (ui) { if (parent.lchild != null) parent.lchild.next = this; if (parent.child == null) parent.child = this; this.prev = parent.lchild; parent.lchild = this; } }
2
public int getAnturium() { return anturium; }
0
public String cd(String to) { String name = FilenameUtils.concat(currentDirectory, to); File file = new File(name); if (file.exists() && file.isDirectory()) { currentDirectory = name; log.warn(name); return null; } return "Directory not found"; }
2
public static void setupRace(int raceID) { Player player = new Player(); switch (raceID) { case 1: player.setRace(RaceTypes.GOBLIN); break; case 2: player.setRace(RaceTypes.ELF); break; case 3: player.setRace(RaceTypes.DWARF); break; case 4: player.setRace(RaceTypes.HUMAN); break; case 5: player.setRace(RaceTypes.GNOME); break; case 6: player.setRace(RaceTypes.ORC); break; case 7: player.setRace(RaceTypes.TROLL); break; default: setRace(null); break; } }
7
public static HashMap<String, MetadataTSVParser> getMap() throws Exception { HashMap<String, MetadataTSVParser> map = new LinkedHashMap<String, MetadataTSVParser>(); BufferedReader reader = new BufferedReader(new FileReader(new File(ConfigReader.getMbqcDir() + File.separator + "metadata" + File.separator + "metadata.tsv"))); reader.readLine(); for(String s = reader.readLine(); s != null; s = reader.readLine()) { TabReader tReader = new TabReader(s); MetadataTSVParser tsv = new MetadataTSVParser(); tsv.wetLabId = tReader.nextToken().replaceAll("\"", ""); tsv.blindedID = tReader.nextToken().replaceAll("\"", ""); tsv.bioinformaticsID = tReader.nextToken().trim().replaceAll("\"", ""); if( tsv.bioinformaticsID.length() > 0 ) { String sampleIDString= tReader.nextToken().trim().replaceAll("\"", ""); tsv.sampleType = tReader.nextToken().trim().replaceAll("\"", ""); if( sampleIDString.length() > 0 ) { tsv.sampleID = Integer.parseInt(sampleIDString); } else { tsv.sampleID = -1; } String key = tsv.blindedID + "." + tsv.bioinformaticsID; if( map.containsKey(key)) throw new Exception("Duplicate key"); map.put(key, tsv); String aBioID = tsv.bioinformaticsID; // sometimes ids like conecalo62.0238403120 lose their leading 0 in downstream analysis... // here we allow those ids to be founds without their leading zeros. while(aBioID.startsWith("0")) { aBioID = aBioID.substring(1); key = tsv.blindedID + "." + aBioID; if( map.containsKey(key)) throw new Exception("Duplicate key"); map.put(key, tsv); } } } return map; }
6
private void calcSize() { this.getSize().setWidth(this.ItemSize.getWidth() * this.DisplayItems); this.getSize().setHeight(this.ItemSize.getHeight()); this.Matrix.clear(); for(int x = 0; x < this.DisplayItems; x++) { Rectangle rect = new Rectangle(x * this.getItemSize().getWidth(), 0, this.getItemSize().getWidth(), this.getItemSize().getHeight()); this.Matrix.add(rect); } }
1
public TerritoryAi(GoAiGame game1) { game = game1; squares = new HashSet<Square>(); }
0
@Test public void testCheckValidWorld() throws Exception { System.out.println("checkValidWorld"); World instance = new World(); instance.readInWorld("1.world"); boolean expResult = true; boolean result = instance.checkValidWorld(); assertEquals(expResult, result); instance = new World(); instance.generateRandomContestWorld(); expResult = true; result = instance.checkValidWorld(); assertEquals(expResult, result); }
0
@Test public void boardSize8KingAndRook() { Map<String, Integer> figureQuantityMap = new HashMap<>(); figureQuantityMap.put(KING.toString(), 2); figureQuantityMap.put(ROOK.toString(), 2); int dimension = 8; assertThat("all elements are not present on each board", prepareBoardsWithKingAndRook(figureQuantityMap, dimension) .parallel() .filter(board -> board.contains(KING.getFigureAsString()) && !board.contains(QUEEN.getFigureAsString()) && !board.contains(BISHOP.getFigureAsString()) && board.contains(ROOK.getFigureAsString()) && !board.contains(KNIGHT.getFigureAsString()) && board.contains(FIELD_UNDER_ATTACK_STRING) && leftOnlyFigures(board).length() == 4) .map(e -> 1) .reduce(0, (x, y) -> x + y), is(657390)); }
6
public JsonMap getMap(String key) { Object value = get(key); if (value instanceof JsonMap) { return (JsonMap) value; } return new JsonMap(); }
1
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (args.length == 1 && args[0].equalsIgnoreCase("help")) { showHelp(sender); return true; } if (args.length == 1 && args[0].equalsIgnoreCase("list")) { sender.sendMessage(StringUtils.join(Effect.values(), ", ")); return true; } if (args.length > 0) { try { parseCommand(sender, args); } catch (EffectError e) { sender.sendMessage(ChatColor.RED + e.getMessage()); } return true; } return false; }
6
private void removeDeadParticles() { for (int particleIndex = 0; particleIndex < particleArray.length; particleIndex++) { if (particleArray[particleIndex] != null) { if (particleArray[particleIndex].isParticleAlive() == false) { particleArray[particleIndex] = null; } } } }
3
@Override protected void placeWord(int row, int col) throws FillWordException { if (row < 0 && col < 0 && swaps < swapLimit && (-row > board.length)) { // Swap the word and deduct the points. System.out.println("Grow board, discard word " + wordToPlay + " at a cost of " + ((-row)+wordToPlay.length()) + " points."); int newsize = -row ; int lognew = (int)(Math.ceil(Math.log10((double)newsize) / Math.log10(2.0))); int logold = (int)(Math.ceil(Math.log10((double)board.length) / Math.log10(2.0))); int penalty = newsize ; //(newsize*logold) - (board.length); score -= wordToPlay.length() + penalty ; char [][] newboard = new char[newsize][newsize]; for (int r = 0 ; r < newsize ; r++) { for (int c = 0 ; c < newsize ; c++) { if (r < board.length && c < board.length) { newboard[r][c] = board[r][c] ; } else { newboard[r][c] = EMPTY ; } } } board = newboard ; if (row == col) { wordSizeLimit = newsize ; System.out.println("Word length limit set to " + newsize + "."); } wordToPlay = pickWord(); swaps++ ; isacross = ! isacross ; return ; } placeWord(row, col, true); }
9
private static boolean validateBinaryInput(String input) { int n = input.length(); for (int i = 0; i < n; i++) if (input.charAt(i) != '0' && input.charAt(i) != '1') return false; return true; }
3
public Slot getCellContaining(GUIComponent component) { for (int r = 0; r < grid.getNumRows(); r++) { for (int c = 0; c < grid.getNumColumns(); c++) { if (cells[r][c].getComponent() == component) { return cells[r][c]; } } } return null; }
3
public Color getColor() { Color returnColor = new Color(255, 255, 255); switch (this) { case RED: returnColor = Color.RED; break; case YELLOW: returnColor = Color.YELLOW; break; case GREEN: returnColor = Color.GREEN; break; case BLUE: returnColor = Color.BLUE; break; default: break; } return returnColor; }
4
public List<T> mapRersultSetToObject(ResultSet rset) throws SQLException, NoSuchColumnLabel { List<T> output = new ArrayList<T>(); ResultSetMetaData rsmd = rset.getMetaData(); try { while(rset.next()){ T bean; bean = clazz.newInstance(); for( int i=rsmd.getColumnCount(); i >= 1; i-- ){ String colLabel = rsmd.getColumnLabel(i); Method setter = setters.get(colLabel); Object o = getObjectAs(rset, rsmd, i); try { setter.invoke(bean, o ); } catch (NullPointerException e) { throw new NoSuchColumnLabel(colLabel); } } output.add(bean); } } catch (IllegalArgumentException | InvocationTargetException | InstantiationException | IllegalAccessException e) { e.printStackTrace(); } return output; }
4
@Override public void mouseMove(MouseEvent e) { if(this.getMouseListener() != null) { this.getMouseListener().MouseMove(this, e); } }
1
@Override public void run(){ try{ System.out.println("HireWorkerServer is waiting for new workers on the port: "+this.portNum); while(running){ Socket workerSocket = serverSocket.accept(); System.out.println("worker: "+workerSocket.getInetAddress()+":"+workerSocket.getPort()+" join in"); master.workerSocMap.put(workerCnt, workerSocket); //add the worker soc with workerCnt as the ID //create the specific manage server for the new worker WorkerManagerServer managerServer = new WorkerManagerServer(master,workerCnt,workerSocket); master.workerMangerServerMap.put(workerCnt, managerServer); Thread t = new Thread(managerServer); t.start(); master.workerManagerThreadMap.put(workerCnt,t); workerCnt++; } }catch(IOException e){ e.printStackTrace(); System.out.println("socket server accept failed"); } try { serverSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("socket Server failed to close"); } }
3
private void optFormat(final CommandLine cmd) { if (cmd.hasOption(OPT_FORMAT)) { final String formatOption = cmd.getOptionValue(OPT_FORMAT); if ("tree".equalsIgnoreCase(formatOption)) { options.setOutputFormat(OutputFormat.TREE); } else if ("xml".equalsIgnoreCase(formatOption)) { options.setOutputFormat(OutputFormat.XML); } else if ("jpg".equalsIgnoreCase(formatOption)) { options.setOutputFormat(OutputFormat.JPG); } else if ("gif".equalsIgnoreCase(formatOption)) { options.setOutputFormat(OutputFormat.GIF); } else if ("png".equalsIgnoreCase(formatOption)) { options.setOutputFormat(OutputFormat.PNG); } else { options.setOutputFormat(OutputFormat.JPG); } } }
6
private static void drawSink(Display d) { int max = 10; int max_iter = 50; /* Complex t = new Complex(0,0); Color current = new Color(d,0,0,0);*/ int X = WIDTH/2; int Y = HEIGHT/2; for (int y = -Y; y < Y; ++y) { for (int x = -X; x < X; ++x) { Complex z = new Complex (x*0.005,y*0.005); Complex c = new Complex(z.getRe()*0.001,z.getIm()*0.001); //Complex c = new Complex(z.getRe(),z.getIm()); int n = 0; while ( (Math.pow(z.getRe(),2)+Math.pow(z.getIm(),2) < max) && (n < max_iter) ) { Complex z1 = new Complex(z.getRe(), z.getIm()); Complex c1 = new Complex(c.getRe(),c.getIm()); z.setRe(Math.pow(z1.getRe(),2)-Math.pow(z1.getIm(),2) + c.getRe()); z.setIm(2*z1.getRe()*z1.getIm()+c.getIm()); c.setRe(c1.getRe()/2+z.getRe()); c.setIm(c1.getIm()/2+z.getIm()); n++; } if (n<max_iter) { int col = (n % max); //graph.setAlpha(n * 100); graph.setForeground(set_palette(d,col)); graph.drawPoint(X+x,Y+y); } else { graph.setForeground(set_palette(d,0)); graph.drawPoint(X+x,Y+y); } } } }
5
public double getDouble(String key) throws JSONException { Object object = this.get(key); try { return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); } }
2
protected double[] freqCountsForAggNodesStrategy(double[] instance, Attribute classAtt) throws Exception { double[] counts = new double[classAtt.numValues()]; if (m_childNodes.size() > 0) { // collect the counts for (TreeNode c : m_childNodes) { if (c.getPredicate().evaluate(instance) == Predicate.Eval.TRUE || c.getPredicate().evaluate(instance) == Predicate.Eval.UNKNOWN) { double[] temp = c.freqCountsForAggNodesStrategy(instance, classAtt); for (int i = 0; i < classAtt.numValues(); i++) { counts[i] += temp[i]; } } } } else { // process the score distributions if (m_scoreDistributions.size() == 0) { throw new Exception("[TreeModel] missing value strategy aggregate nodes:" + " no score distributions at leaf " + m_ID); } for (ScoreDistribution s : m_scoreDistributions) { counts[s.getClassLabelIndex()] = s.getRecordCount(); } } return counts; }
7
public DisponibleAreas() { setIconImage(Toolkit.getDefaultToolkit().getImage(DisponibleAreas.class.getResource("/InterfazGrafica/Images/areas.png"))); setTitle("\u00C1REAS DISPONIBLES"); setBounds(10, 50, 623, 741); setLocationRelativeTo(null); setModal(true); getContentPane().setLayout(new BorderLayout()); contentPanel.setBackground(new Color(248, 248, 255)); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); { JPanel panel = new JPanel(); panel.setBackground(new Color(248, 248, 255)); panel.setBorder(new TitledBorder(null, "Ingenier\u00EDas", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel.setBounds(316, 354, 255, 286); contentPanel.add(panel); panel.setLayout(null); { JRadioButton rdbtnIngenieriaCivil = new JRadioButton("Ingenier\u00EDa Civil"); rdbtnIngenieriaCivil.setBackground(new Color(248, 248, 255)); rdbtnIngenieriaCivil.setActionCommand("Ingenier\u00EDa Civil"); rdbtnIngenieriaCivil.setBounds(20, 45, 154, 23); panel.add(rdbtnIngenieriaCivil); } { JRadioButton rdbtnIngenieraElctrica = new JRadioButton("Ingenier\u00EDa El\u00E9ctrica"); rdbtnIngenieraElctrica.setBackground(new Color(248, 248, 255)); rdbtnIngenieraElctrica.setActionCommand("Ingenier\u00EDa Civil"); rdbtnIngenieraElctrica.setBounds(20, 71, 154, 23); panel.add(rdbtnIngenieraElctrica); } { JRadioButton rdbtnIngenieraElectrnica = new JRadioButton("Ingenier\u00EDa Electr\u00F3nica"); rdbtnIngenieraElectrnica.setBackground(new Color(248, 248, 255)); rdbtnIngenieraElectrnica.setActionCommand("Ingenier\u00EDa Civil"); rdbtnIngenieraElectrnica.setBounds(20, 97, 154, 23); panel.add(rdbtnIngenieraElectrnica); } { JRadioButton rdbtnIngenieraIndustrial = new JRadioButton("Ingenier\u00EDa Industrial"); rdbtnIngenieraIndustrial.setBackground(new Color(248, 248, 255)); rdbtnIngenieraIndustrial.setActionCommand("Ingenier\u00EDa Civil"); rdbtnIngenieraIndustrial.setBounds(20, 123, 154, 23); panel.add(rdbtnIngenieraIndustrial); } { JRadioButton rdbtnIngenieraMecnica = new JRadioButton("Ingenier\u00EDa Mec\u00E1nica"); rdbtnIngenieraMecnica.setBackground(new Color(248, 248, 255)); rdbtnIngenieraMecnica.setActionCommand("Ingenier\u00EDa Civil"); rdbtnIngenieraMecnica.setBounds(20, 149, 154, 23); panel.add(rdbtnIngenieraMecnica); } { JRadioButton rdbtnIngenieraQumica = new JRadioButton("Ingenier\u00EDa Qu\u00EDmica"); rdbtnIngenieraQumica.setBackground(new Color(248, 248, 255)); rdbtnIngenieraQumica.setActionCommand("Ingenier\u00EDa Civil"); rdbtnIngenieraQumica.setBounds(20, 175, 154, 23); panel.add(rdbtnIngenieraQumica); } { JRadioButton rdbtnIngenieraSanitaria = new JRadioButton("Ingenier\u00EDa Sanitaria"); rdbtnIngenieraSanitaria.setBackground(new Color(248, 248, 255)); rdbtnIngenieraSanitaria.setActionCommand("Ingenier\u00EDa Civil"); rdbtnIngenieraSanitaria.setBounds(20, 201, 154, 23); panel.add(rdbtnIngenieraSanitaria); } { JRadioButton rdbtnIngenieraEnSistemas = new JRadioButton("Ingenier\u00EDa en Sistemas"); rdbtnIngenieraEnSistemas.setBackground(new Color(248, 248, 255)); rdbtnIngenieraEnSistemas.setActionCommand("Ingenier\u00EDa Civil"); rdbtnIngenieraEnSistemas.setBounds(20, 227, 212, 23); panel.add(rdbtnIngenieraEnSistemas); } { JRadioButton rdbtnIngenieraEnTelecomunicaciones = new JRadioButton("Ingenier\u00EDa en Telecomunicaciones"); rdbtnIngenieraEnTelecomunicaciones.setBackground(new Color(248, 248, 255)); rdbtnIngenieraEnTelecomunicaciones.setActionCommand("Ingenier\u00EDa Civil"); rdbtnIngenieraEnTelecomunicaciones.setBounds(20, 253, 231, 23); panel.add(rdbtnIngenieraEnTelecomunicaciones); } { JRadioButton rdbtnIngenieraAgronmica = new JRadioButton("Ingenier\u00EDa Agron\u00F3mica"); rdbtnIngenieraAgronmica.setBackground(new Color(248, 248, 255)); rdbtnIngenieraAgronmica.setActionCommand("Ingenier\u00EDa Civil"); rdbtnIngenieraAgronmica.setBounds(20, 19, 154, 23); panel.add(rdbtnIngenieraAgronmica); } } { JPanel panel = new JPanel(); panel.setBorder(new TitledBorder(null, "Ciencias", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel.setBackground(new Color(248, 248, 255)); panel.setBounds(317, 11, 254, 214); contentPanel.add(panel); panel.setLayout(null); { JRadioButton rdbtnEconmicas = new JRadioButton("Biol\u00F3gicas"); rdbtnEconmicas.setBackground(new Color(248, 248, 255)); rdbtnEconmicas.setActionCommand("Ingenier\u00EDa Civil"); rdbtnEconmicas.setBounds(20, 46, 154, 23); panel.add(rdbtnEconmicas); } { JRadioButton rdbtnEconmicas_1 = new JRadioButton("Econ\u00F3micas"); rdbtnEconmicas_1.setBackground(new Color(248, 248, 255)); rdbtnEconmicas_1.setActionCommand("Ingenier\u00EDa Civil"); rdbtnEconmicas_1.setBounds(20, 72, 154, 23); panel.add(rdbtnEconmicas_1); } { JRadioButton rdbtnEmpresariales = new JRadioButton("Empresariales"); rdbtnEmpresariales.setBackground(new Color(248, 248, 255)); rdbtnEmpresariales.setActionCommand("Ingenier\u00EDa Civil"); rdbtnEmpresariales.setBounds(20, 98, 154, 23); panel.add(rdbtnEmpresariales); } { JRadioButton rdbtnQumicas = new JRadioButton("Qu\u00EDmicas"); rdbtnQumicas.setBackground(new Color(248, 248, 255)); rdbtnQumicas.setActionCommand("Ingenier\u00EDa Civil"); rdbtnQumicas.setBounds(20, 150, 154, 23); panel.add(rdbtnQumicas); } { JRadioButton rdbtnSociales = new JRadioButton("Sociales"); rdbtnSociales.setBackground(new Color(248, 248, 255)); rdbtnSociales.setActionCommand("Ingenier\u00EDa Civil"); rdbtnSociales.setBounds(20, 176, 154, 23); panel.add(rdbtnSociales); } { JRadioButton rdbtnMedioAmbiente = new JRadioButton("Medio Ambiente"); rdbtnMedioAmbiente.setBackground(new Color(248, 248, 255)); rdbtnMedioAmbiente.setActionCommand("Ingenier\u00EDa Civil"); rdbtnMedioAmbiente.setBounds(20, 124, 154, 23); panel.add(rdbtnMedioAmbiente); } { JRadioButton rdbtnAeronutica = new JRadioButton("Aeron\u00E1utica"); rdbtnAeronutica.setBackground(new Color(248, 248, 255)); rdbtnAeronutica.setActionCommand("Ingenier\u00EDa Civil"); rdbtnAeronutica.setBounds(20, 20, 154, 23); panel.add(rdbtnAeronutica); } } { JPanel panel = new JPanel(); panel.setLayout(null); panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Administraci\u00F3n", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel.setBackground(new Color(248, 248, 255)); panel.setBounds(40, 11, 255, 214); contentPanel.add(panel); { JRadioButton rdbtnAltaGerencia = new JRadioButton("Alta Gerencia"); rdbtnAltaGerencia.setBackground(new Color(248, 248, 255)); rdbtnAltaGerencia.setActionCommand("Ingenier\u00EDa Civil"); rdbtnAltaGerencia.setBounds(20, 20, 231, 23); panel.add(rdbtnAltaGerencia); } { JRadioButton rdbtnContabilidad = new JRadioButton("Contabilidad"); rdbtnContabilidad.setBackground(new Color(248, 248, 255)); rdbtnContabilidad.setActionCommand("Ingenier\u00EDa Civil"); rdbtnContabilidad.setBounds(20, 46, 154, 23); panel.add(rdbtnContabilidad); } { JRadioButton rdbtnDocumentacin = new JRadioButton("Documentaci\u00F3n"); rdbtnDocumentacin.setBackground(new Color(248, 248, 255)); rdbtnDocumentacin.setActionCommand("Ingenier\u00EDa Civil"); rdbtnDocumentacin.setBounds(20, 72, 154, 23); panel.add(rdbtnDocumentacin); } { JRadioButton rdbtnGestin = new JRadioButton("Gesti\u00F3n"); rdbtnGestin.setBackground(new Color(248, 248, 255)); rdbtnGestin.setActionCommand("Ingenier\u00EDa Civil"); rdbtnGestin.setBounds(20, 98, 154, 23); panel.add(rdbtnGestin); } { JRadioButton rdbtnHoteleria = new JRadioButton("Hoteleria"); rdbtnHoteleria.setBackground(new Color(248, 248, 255)); rdbtnHoteleria.setActionCommand("Ingenier\u00EDa Civil"); rdbtnHoteleria.setBounds(20, 124, 154, 23); panel.add(rdbtnHoteleria); } { JRadioButton rdbtnLogstica = new JRadioButton("Log\u00EDstica"); rdbtnLogstica.setBackground(new Color(248, 248, 255)); rdbtnLogstica.setActionCommand("Ingenier\u00EDa Civil"); rdbtnLogstica.setBounds(20, 150, 154, 23); panel.add(rdbtnLogstica); } { JRadioButton rdbtnServiciosFinancieros = new JRadioButton("Servicios Financieros"); rdbtnServiciosFinancieros.setBackground(new Color(248, 248, 255)); rdbtnServiciosFinancieros.setActionCommand("Ingenier\u00EDa Civil"); rdbtnServiciosFinancieros.setBounds(20, 176, 218, 23); panel.add(rdbtnServiciosFinancieros); } } { JPanel panel_1 = new JPanel(); panel_1.setBounds(40, 354, 254, 286); contentPanel.add(panel_1); panel_1.setBorder(new TitledBorder(null, "Diversas", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel_1.setBackground(new Color(248, 248, 255)); panel_1.setLayout(null); { JRadioButton rdbtnDocencia = new JRadioButton("Docencia"); rdbtnDocencia.setBackground(new Color(248, 248, 255)); rdbtnDocencia.setActionCommand("Ingenier\u00EDa Civil"); rdbtnDocencia.setBounds(20, 20, 154, 23); panel_1.add(rdbtnDocencia); } { JRadioButton rdbtnElectricidad = new JRadioButton("Electricidad"); rdbtnElectricidad.setBackground(new Color(248, 248, 255)); rdbtnElectricidad.setActionCommand("Ingenier\u00EDa Civil"); rdbtnElectricidad.setBounds(20, 46, 154, 23); panel_1.add(rdbtnElectricidad); } { JRadioButton rdbtnElectrnica = new JRadioButton("Electr\u00F3nica"); rdbtnElectrnica.setBackground(new Color(248, 248, 255)); rdbtnElectrnica.setActionCommand("Ingenier\u00EDa Civil"); rdbtnElectrnica.setBounds(20, 72, 154, 23); panel_1.add(rdbtnElectrnica); } { JRadioButton rdbtnIdiomas = new JRadioButton("Idiomas"); rdbtnIdiomas.setBackground(new Color(248, 248, 255)); rdbtnIdiomas.setActionCommand("Ingenier\u00EDa Civil"); rdbtnIdiomas.setBounds(20, 98, 154, 23); panel_1.add(rdbtnIdiomas); } { JRadioButton rdbtnPsicologa = new JRadioButton("Psicolog\u00EDa"); rdbtnPsicologa.setBackground(new Color(248, 248, 255)); rdbtnPsicologa.setActionCommand("Ingenier\u00EDa Civil"); rdbtnPsicologa.setBounds(20, 124, 154, 23); panel_1.add(rdbtnPsicologa); } { JRadioButton rdbtnSeguridad = new JRadioButton("Seguridad"); rdbtnSeguridad.setBackground(new Color(248, 248, 255)); rdbtnSeguridad.setActionCommand("Ingenier\u00EDa Civil"); rdbtnSeguridad.setBounds(20, 150, 154, 23); panel_1.add(rdbtnSeguridad); } { JRadioButton rdbtnServiciosDomsticos = new JRadioButton("Servicios Dom\u00E9sticos"); rdbtnServiciosDomsticos.setBackground(new Color(248, 248, 255)); rdbtnServiciosDomsticos.setActionCommand("Ingenier\u00EDa Civil"); rdbtnServiciosDomsticos.setBounds(20, 176, 154, 23); panel_1.add(rdbtnServiciosDomsticos); } { JRadioButton rdbtnSoporteTcnico = new JRadioButton("Soporte T\u00E9cnico"); rdbtnSoporteTcnico.setBackground(new Color(248, 248, 255)); rdbtnSoporteTcnico.setActionCommand("Ingenier\u00EDa Civil"); rdbtnSoporteTcnico.setBounds(20, 202, 154, 23); panel_1.add(rdbtnSoporteTcnico); } { JRadioButton rdbtnTransporte = new JRadioButton("Transporte "); rdbtnTransporte.setBackground(new Color(248, 248, 255)); rdbtnTransporte.setActionCommand("Ingenier\u00EDa Civil"); rdbtnTransporte.setBounds(20, 228, 154, 23); panel_1.add(rdbtnTransporte); } { JRadioButton rdbtnTurismo = new JRadioButton("Turismo"); rdbtnTurismo.setBackground(new Color(248, 248, 255)); rdbtnTurismo.setActionCommand("Ingenier\u00EDa Civil"); rdbtnTurismo.setBounds(20, 254, 154, 23); panel_1.add(rdbtnTurismo); } } { JPanel panel = new JPanel(); panel.setBounds(316, 236, 255, 107); contentPanel.add(panel); panel.setBorder(new TitledBorder(null, "Mercado", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel.setBackground(new Color(248, 248, 255)); panel.setLayout(null); { JRadioButton rdbtnInvestigacinDeMercado = new JRadioButton("Investigaci\u00F3n de Mercado"); rdbtnInvestigacinDeMercado.setBackground(new Color(248, 248, 255)); rdbtnInvestigacinDeMercado.setActionCommand("Ingenier\u00EDa Civil"); rdbtnInvestigacinDeMercado.setBounds(20, 20, 231, 23); panel.add(rdbtnInvestigacinDeMercado); } { JRadioButton rdbtnTelemarketing = new JRadioButton("Telemarketing"); rdbtnTelemarketing.setBackground(new Color(248, 248, 255)); rdbtnTelemarketing.setActionCommand("Ingenier\u00EDa Civil"); rdbtnTelemarketing.setBounds(20, 46, 154, 23); panel.add(rdbtnTelemarketing); } { JRadioButton rdbtnVentas = new JRadioButton("Ventas"); rdbtnVentas.setBackground(new Color(248, 248, 255)); rdbtnVentas.setActionCommand("Ingenier\u00EDa Civil"); rdbtnVentas.setBounds(20, 72, 154, 23); panel.add(rdbtnVentas); } } { JPanel panel_1 = new JPanel(); panel_1.setBounds(40, 236, 255, 107); contentPanel.add(panel_1); panel_1.setLayout(null); panel_1.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Atenci\u00F3n al Cliente", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel_1.setBackground(new Color(248, 248, 255)); { JRadioButton rdbtnRecepcin = new JRadioButton("Secretariado"); rdbtnRecepcin.setBackground(new Color(248, 248, 255)); rdbtnRecepcin.setActionCommand("Ingenier\u00EDa Civil"); rdbtnRecepcin.setBounds(20, 20, 231, 23); panel_1.add(rdbtnRecepcin); } { JRadioButton rdbtnRecepcin_1 = new JRadioButton("Recepci\u00F3n"); rdbtnRecepcin_1.setBackground(new Color(248, 248, 255)); rdbtnRecepcin_1.setActionCommand("Ingenier\u00EDa Civil"); rdbtnRecepcin_1.setBounds(20, 46, 154, 23); panel_1.add(rdbtnRecepcin_1); } { JRadioButton rdbtnRecursosHumanos = new JRadioButton("Recursos Humanos"); rdbtnRecursosHumanos.setBackground(new Color(248, 248, 255)); rdbtnRecursosHumanos.setActionCommand("Ingenier\u00EDa Civil"); rdbtnRecursosHumanos.setBounds(20, 72, 154, 23); panel_1.add(rdbtnRecursosHumanos); } } { JPanel buttonPane = new JPanel(); buttonPane.setBackground(new Color(248, 248, 255)); buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("Aceptar "); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); okButton.setIcon(new ImageIcon(DisponibleAreas.class.getResource("/InterfazGrafica/Images/botonsi.png"))); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } } }
0
public static Double getDouble(Object obj){ if(obj == null) return null; try { Double i = Double.parseDouble(obj.toString()); return i; } catch(Exception e){ return null; } }
2
private List<Command> getMatchingCommands(String arg) { List<Command> result = new ArrayList<Command>(); for (Entry<String, Command> entry : commands.entrySet()) { if (arg.matches(entry.getKey())) { result.add(entry.getValue()); } } return result; }
2
@Override public int hashCode() { int result; long temp; result = hitPoints; result = 31 * result + pixelSpeed; result = 31 * result + dmgToBase; result = 31 * result + gold; result = 31 * result + (alive ? 1 : 0); result = 31 * result + (active ? 1 : 0); result = 31 * result + (board != null ? board.hashCode() : 0); temp = Double.doubleToLongBits(activationTime); result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + experienceToTowers; result = 31 * result + (enemyPathing != null ? enemyPathing.hashCode() : 0); return result; }
4
@Override public int compare(Fetcher f1, Fetcher f2) { return f1.getRequestWrapper().getPriority() - f2.getRequestWrapper().getPriority(); }
0
public Configuration loadEmbeddedConfig(final String resource) { final YamlConfiguration config = new YamlConfiguration(); final InputStream defaults = this.getResource(resource); if (defaults == null) return config; final InputStreamReader reader = new InputStreamReader(defaults, CustomPlugin.CONFIGURATION_SOURCE); final StringBuilder builder = new StringBuilder(); final BufferedReader input = new BufferedReader(reader); try { try { String line; while ((line = input.readLine()) != null) builder.append(line).append(CustomPlugin.LINE_SEPARATOR); } finally { input.close(); } config.loadFromString(builder.toString()); } catch (final Exception e) { throw new RuntimeException("Unable to load embedded configuration: " + resource, e); } return config; }
3
public void createCustomer(String name, String address, String postnr, String by, String email, String nr) { if (name != null && address != null && postnr != null && by != null && email != null && nr != null) { Customer c = new Customer(name, address, postnr, by, email, nr); customerlist.add(c); } }
6
public static boolean extractFile(File zip, File output, String fileName) throws IOException, InterruptedException { if (!zip.exists() || fileName == null) { return false; } ZipFile zipFile = null; try { zipFile = new ZipFile(zip); ZipEntry entry = zipFile.getEntry(fileName); if (entry == null) { Utils.getLogger().log(Level.WARNING, "File " + fileName + " not found in " + zip.getAbsolutePath()); return false; } File outputFile = new File(output, entry.getName()); if (outputFile.getParentFile() != null) { outputFile.getParentFile().mkdirs(); } unzipEntry(zipFile, zipFile.getEntry(fileName), outputFile); return true; } catch (ZipException e) { e.printStackTrace(); throw new ZipException("Error extracting file " + zip.getName()); } catch (IOException e) { Utils.getLogger().log(Level.WARNING, "Error extracting file " + fileName + " from " + zip.getAbsolutePath()); return false; } finally { if (zipFile != null) { zipFile.close(); } } }
7
boolean anyResultMatches(String transcriptId, Variant seqChange, List<ChangeEffect> resultsList, boolean useSimple, StringBuilder resultsSoFar) { boolean ok = false; for (ChangeEffect chEff : resultsList) { String resStr = chEff.toStringSimple(!useSimple); if (verbose) System.out.println(seqChange + "\t'" + resStr + "'"); String effTrId = chEff.getMarker().findParent(Transcript.class).getId(); if ((transcriptId == null) || (transcriptId.equals(effTrId))) { if (!seqChange.getId().equals(resStr)) { // SNP effect does not match this result if (verbose) Gpr.debug("SeqChange: " + seqChange + "\tResult: '" + chEff + "'"); resultsSoFar.append(seqChange + "\t'" + resStr + "'\n"); } else { // SNP effect matches one result ok = true; break; } } } return ok; }
6
private void parseArguments(String[] args) { if (args.length > 0) { config.set("username", args[0]); if (args.length > 1) { config.set("password", args[1]); if (args.length > 2) { String ip = args[2]; String port = "25565"; if (ip.contains(":")) { final String[] split = ip.split(":"); ip = split[0]; port = split[1]; } config.set("server", ip); config.set("port", port); } } } }
4
@Override public List<Vehicule> getVehicules() throws BadResponseException { List<Vehicule> vehicules = new ArrayList<Vehicule>(); JsonRepresentation representation = null; // R�cup�ration de la liste des Vehicules Representation repr = serv.getResource("intervention/" + interId + "/vehicule", null); try { representation = new JsonRepresentation(repr); JSONArray ar = representation.getJsonArray(); for (int i = 0; i < ar.length(); i++) { vehicules.add(new Vehicule(ar.getJSONObject(i))); } } catch (Exception e) { System.out.println("Error: " + e.toString()); } return vehicules; }
2
private int checkBeatOutOfBounds(){ if (beat.getBounds().contains(0, BEAT_START_Y)){ return 0; } if (beat.getBounds().contains(WIDTH, BEAT_START_Y)){ return 1; } return 2; }
2
public void setPanel(AnalysePanel panelCurrent) { if (this.panelCurrent != null) center.remove(this.panelCurrent); center.add(BorderLayout.CENTER, panelCurrent); center.revalidate(); center.repaint(); this.panelCurrent = panelCurrent; }
1
public void compExecTime() { double newExeTime; double newCost; dEval = 0; dTime = 0; dCost = 0; for (int i = 0; i < iClass; i++) { newExeTime = 0; // System.out.print("Cost[" + i + "]"); for (int j = 0; j < iSite; j++) { if (dmAlloc[i][j] != -1) { if (dmAlloc[i][j] < 1) { newExeTime = 0; } else { newExeTime = (dmDist[i][j] * dmPrediction[i][j]) / dmAlloc[i][j]; if (newExeTime > dDeadline + 1) { newExeTime = Double.MAX_VALUE; } } } if (newExeTime > dDeadline + 1) { // System.out.println("newExeTime - dDeadline="+ (newExeTime // - dDeadline -1)); newCost = Double.MAX_VALUE; } else { newCost = dmDist[i][j] * dmPrediction[i][j] * daPrice[j]; } dTime += newExeTime; dCost += newCost; dEval += dmCost[i][j] - dCost; dmExeTime[i][j] = newExeTime; dmCost[i][j] = newCost; // System.out.print(dmCost[i][j] + ", "); } // System.out.println(); } for (int i = 0; i < iClass; i++) { System.out.print("Time[" + i + "]"); for (int j = 0; j < iSite; j++) { System.out.print(dmExeTime[i][j] + ", "); } System.out.println(); } // System.out.println("AllTime = " + dTime + " AllCost = " + dCost); // System.out.println(); }
8
@Override public boolean execute(final CommandSender sender, final String[] split) { if (sender instanceof Player) { if (MonsterIRC.getHandleManager().getPermissionsHandler() != null) { if (!MonsterIRC.getHandleManager().getPermissionsHandler() .hasCommandPerms((Player) sender, this)) { sender.sendMessage("[IRC] You don't have permission to preform that command."); return true; } } else { sender.sendMessage("[IRC] PEX not detected, unable to run any IRC commands."); return true; } } if (split.length < 4) { sender.sendMessage("Invalid usage!"); sender.sendMessage("Proper usage: irc pm [user] [message]"); return true; } else { if (!first.contains(split[2])) { MonsterIRC .getHandleManager() .getIRCHandler() .sendMessage(split[2], "You have revieved a private message from MonsterIRC!"); MonsterIRC .getHandleManager() .getIRCHandler() .sendMessage( split[2], "To reply type \"" + sender.getName() + ":\" (message)"); first.add(split[2]); } final StringBuffer result = new StringBuffer(); result.append("[MC] " + sender.getName() + ": "); for (int i = 3; i < split.length; i++) { result.append(split[i]); result.append(" "); } MonsterIRC.getHandleManager().getIRCHandler() .sendMessage(split[2], result.toString()); sender.sendMessage(ColorUtils.LIGHT_GRAY.getMinecraftColor() + "([IRC] to " + split[2] + "): " + result.toString() .substring(7 + sender.getName().length())); Variables.reply.put((Player) sender, split[2]); return true; } }
6
public void visitLabelStmt(final LabelStmt stmt) { if (stmt.label() != null) { println(stmt.label()); } }
1
private Location findTarget() { Field field = getField(); List<Location> adjacent = field.adjacentLocations(getLocation()); 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(); return where; } } else if (animal instanceof Fox) { Fox fox = (Fox) animal; if(fox.isAlive()) { fox.setDead(); return where; } } else if (animal instanceof Bear) { Bear bear = (Bear) animal; if(bear.isAlive()) { bear.setDead(); return where; } } } return null; }
7
public PosController() { }
0
private ArrayList<String> getWordsFromFile(String fileName) { ArrayList<String> wordsList = new ArrayList<String>(); try { BufferedReader rd = new BufferedReader(new FileReader(fileName)); while (true) { String line = rd.readLine(); if (line == null) { break; } wordsList.add(line); } rd.close(); // close when you’re done! } catch (IOException ex) { // do something in response to exception throw new ErrorException(ex); } return wordsList; }
3
private boolean checkSelf() { boolean isValid = true; if (parent != null) { if (!parent.isExistentInCli() && isExistentInCli()) { selfErrorMessage +="Option " + getName() + " not allowed, " + "if option " + parent.getName() + " not present. "; isValid = false; } if (isValid) { if ( isRequired() && (isExistentInCli() != parent.isExistentInCli()) ) { selfErrorMessage += "Option " + getName() + " is required, " + "but MISSING. "; isValid = false; } else { if (parent.isExistentInCli()) { boolean checkSelfValuesStatus = checkSelfValues(); if ( checkSelfValuesStatus == false ) { selfErrorMessage += "Option " + getName() + " has the following error: " + valuesErrorMessage; isValid = false; } } if (isValid) { useDefaultValuesForNonExistentValues(); } } } return isValid; } else { // parent null return true; } }
9
@Override protected void layoutPlotChildren() { if (getData() == null) { return; } for (int seriesIndex = 0; seriesIndex < getData().size(); seriesIndex++) { XYChart.Series<Number, Number> series = getData().get(seriesIndex); Iterator<XYChart.Data<Number, Number>> iter = getDisplayedDataIterator(series); Path seriesPath = null; if (series.getNode() instanceof Path) { seriesPath = (Path) series.getNode(); seriesPath.getElements().clear(); } while (iter.hasNext()) { XYChart.Data<Number, Number> item = iter.next(); double x = getXAxis().getDisplayPosition(getCurrentDisplayedXValue(item)); double y = getYAxis().getDisplayPosition(getCurrentDisplayedYValue(item)); Node itemNode = item.getNode(); CandleStickValues extra = (CandleStickValues) item.getExtraValue(); if (itemNode instanceof Candle && extra != null) { Candle candle = (Candle) itemNode; double close = getYAxis().getDisplayPosition(extra.getClose()); double high = getYAxis().getDisplayPosition(extra.getHigh()); double low = getYAxis().getDisplayPosition(extra.getLow()); double candleWidth = -1; if (getXAxis() instanceof NumberAxis) { NumberAxis xa = (NumberAxis) getXAxis(); candleWidth = xa.getDisplayPosition(xa.getTickUnit()) * 0.40; } candle.update(close - y, high - y, low - y, candleWidth); candle.setLayoutX(x); candle.setLayoutY(y); } if (seriesPath != null) { if (seriesPath.getElements().isEmpty()) { seriesPath.getElements().add(new MoveTo(x, getYAxis().getDisplayPosition(extra.getAverage()))); } else { seriesPath.getElements().add(new LineTo(x, getYAxis().getDisplayPosition(extra.getAverage()))); } } } } }
9
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Medicamentos)) { return false; } Medicamentos other = (Medicamentos) object; if ((this.idmedicamentos == null && other.idmedicamentos != null) || (this.idmedicamentos != null && !this.idmedicamentos.equals(other.idmedicamentos))) { return false; } return true; }
5
public void doDamage(LivingThing oo) { double hpDamage; double strengthDamage; double intelligenceDamage; double dexterityDamage; double speedDamage; double manaDamage; double baseXpDamage; double remainingHp; double remainingStrength; double remainingIntelligence; double remainingDexterity; double remainingSpeed; double remainingMana; // calculates damages hpDamage = this.getDamage().getBaseHpDamage(); if (strengthMultiplier > 1) hpDamage = hpDamage + (l.getStrength() * strengthMultiplier); if (manaMultiplier > 1) hpDamage = hpDamage + (l.getMana() * manaMultiplier); if (speedMultiplier > 1) hpDamage = hpDamage + (l.getSpeed() * speedMultiplier); if (dexterityMultiplier > 1) hpDamage = hpDamage + (l.getDexterity() * dexterityMultiplier); if (intelligenceMultiplier > 1) hpDamage = hpDamage + (l.getIntelligence() * intelligenceMultiplier); strengthDamage = this.getDamage().getBaseStrengthDamage(); intelligenceDamage = this.getDamage().getBaseIntelligenceDamage(); dexterityDamage = this.getDamage().getBaseDexterityDamage(); speedDamage = this.getDamage().getBaseSpeedDamage(); manaDamage = this.getDamage().getBaseManaDamage(); // Calculates remaining stats remainingHp = oo.getHp() - hpDamage; remainingStrength = oo.getStrength() - strengthDamage; remainingIntelligence = oo.getIntelligence() - intelligenceDamage; remainingDexterity = oo.getDexterity() - dexterityDamage; remainingSpeed = oo.getSpeed() - speedDamage; remainingMana = oo.getMana() - manaDamage; // updates all stats of Character oo.updateHp((int) remainingHp); oo.updateStrength((int) remainingStrength); oo.updateIntelligence((int) remainingIntelligence); oo.updateDexterity((int) remainingIntelligence); oo.updateSpeed((int) remainingSpeed); oo.updateMana((int) remainingMana); }
5
public static void main (String args[]) { try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e0) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } } new CardWriter().setVisible(true); }
7
@Override public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { super.update(container, game, delta); if (alive) { if (World.tickCount % 30 == 0) { energyTick(); } if (energy <= 0 || health <= 0) { setDead(); /*if (size > 50) { size-= 20; energy += 20; } else { setDead(); }*/ } } else { deathTimer++; if (deathTimer < 1800) { col = Colour.setColorByHealth((1800 - deathTimer) / 1800F, col); } else { col = Colour.setColorByHealth(0, col); } if (size > 10) { if (World.rand.nextInt(10) == 0) { size -= Terrain.changeEnergy(x, y, 1); } } else { Terrain.changeEnergy(x, y, size); remove(); } } }
7
public Object getValueAt(int row, int col) { if(null == data) return null; if(col>=columnNames.length || col<0 || row<0) return null; return data[row][col]; }
4
public boolean intersectCube(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { return this.minX < maxX && this.maxX > minX && this.minY < maxY && this.maxY > minY && this.minZ < maxZ && this.maxZ > minZ; }
5
private void parseConfLine(SBConfig conf, String str) { // Parse the config line. String delim = "[ ]"; String [] tokens = str.split(delim); List<String> list = new ArrayList<String>(); for(String s : tokens) { if(s != null && s.length() > 0) { list.add(s); } } // Prune the empty tokens from the string array. tokens = list.toArray(new String[list.size()]); try { // TODO Auto-generated method stub if (tokens[0].equals("FPAdder")) { int i = Integer.parseInt(tokens[1]); conf.setNoOfFPAdder(i); } else if (tokens[0].equals("FPMultiplier")) { int i = Integer.parseInt(tokens[1]); conf.setNoOfFPMultiplier(i); } else if (tokens[0].equals("FPDivider")) { int i = Integer.parseInt(tokens[1]); conf.setNoOfFPDivider(i); } else if (tokens[0].equals("IntegerUnit")) { int i = Integer.parseInt(tokens[1]); conf.setNoOfIntegerUnit(i); } else { log.error("Invalid config option provided"); } } catch (NumberFormatException e) { // TODO Auto-generated catch block log.error("Invalid config value provided"); } }
8
private static Class<?> findMainClass(Iterable<Class<?>> classes) { // find a public class with public static main method for (Class<?> clazz : classes) { int modifiers = clazz.getModifiers(); if (Modifier.isPublic(modifiers)) { Method mainMethod = findMainMethod(clazz); if (mainMethod != null) { return clazz; } } } // okay, try to find package private class that // has public static main method for (Class<?> clazz : classes) { Method mainMethod = findMainMethod(clazz); if (mainMethod != null) { return clazz; } } // no main class found! return null; }
9
public static HttpServletRequest listPatients(HttpServletRequest request) { Models.DatabaseModel.Patient patient = new Models.DatabaseModel.Patient(); ArrayList<Models.DatabaseModel.Patient> patients = patient.listAllPatients(); for (Models.DatabaseModel.Patient thisPatient : patients) { thisPatient.setRemovable(canRemove(thisPatient.getID())); } request.setAttribute("patients", patients); request.setAttribute("view", "patientslist.jsp"); return request; }
1
public Team getTeam(){ if(this == RED) return Team.RED; else if(this == BLUE) return Team.BLUE; else if(this == NOTCHOSEN) return null; else{ Random r = new Random(); if(r.nextBoolean()) return Team.RED; return Team.BLUE; } }
4
public String getCitedIDList(int queryid) { String idList = ""; String query = "select distinct citationid from dblpcitation where indexid=" + queryid + " order by citationid asc"; ResultSet rsSet = null; rsSet = sqLconnection.Query(query); try { while (rsSet.next()) { int id = rsSet.getInt("citationid"); idList += id + ","; } } catch (SQLException e) { e.printStackTrace(); } return idList; }
2
protected CtClass createCtClass(String classname, boolean useCache) { // accept "[L<class name>;" as a class name. if (classname.charAt(0) == '[') classname = Descriptor.toClassName(classname); if (classname.endsWith("[]")) { String base = classname.substring(0, classname.indexOf('[')); if ((!useCache || getCached(base) == null) && find(base) == null) return null; else return new CtArray(classname, this); } else if (find(classname) == null) return null; else return new CtClassType(classname, this); }
6
@Override public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println("Ingrese operacion (SUMAR, RESTAR, MULTIPLICAR, DIVIDIR)"); String operacion = in.readLine(); System.out.println(operacion); out.println("Ingrese primer parametro: "); String parametro1 = in.readLine(); System.out.println(parametro1); out.println("Ingrese segundo parametro: "); String parametro2 = in.readLine(); System.out.println(parametro2); int resultadoOperacion = 0; String mensaje = ""; try { switch (operacion.toUpperCase()) { case "SUMAR": resultadoOperacion = OperadorAritmetico.sumar(Integer.parseInt(parametro1), Integer.parseInt(parametro2)); break; case "RESTAR": resultadoOperacion = OperadorAritmetico.restar(Integer.parseInt(parametro1), Integer.parseInt(parametro2)); break; case "MULTIPLICAR": resultadoOperacion = OperadorAritmetico.multiplicar(Integer.parseInt(parametro1), Integer.parseInt(parametro2)); break; case "DIVIDIR": resultadoOperacion = OperadorAritmetico.dividir(Integer.parseInt(parametro1), Integer.parseInt(parametro2)); break; default: break; } mensaje = "resultado: " + resultadoOperacion; } catch (Exception e) { mensaje = e.getMessage(); System.out.println(e.getMessage()); } out.println(mensaje); } catch (Exception e) { System.out.println(e.getMessage()); } }
6
@Override public int compareTo (@SuppressWarnings("NullableProblems") JavaInfo o) { if (o.major > major) return -1; if (o.major < major) return 1; if (o.minor > minor) return -1; if (o.minor < minor) return 1; if (o.revision > revision) return -1; if (o.revision < revision) return 1; if (o.build > build) return -1; if (o.build < build) return 1; return 0; }
8
public List<List<Integer>> levelOrderBottom(TreeNode root) { if (root == null) return new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); Stack<ArrayList<Integer>> finalStack = new Stack<>(); queue.add(root); int last = 1; int current = 0; ArrayList<Integer> l = new ArrayList<>(); while (!queue.isEmpty()) { TreeNode node = queue.poll(); l.add(node.val); last = last - 1; if (node.left != null) { queue.add(node.left); current = current + 1; } if (node.right != null) { queue.add(node.right); current = current + 1; } if (last == 0) { last = current; current = 0; finalStack.push(l); l = new ArrayList<>(); } } List<List<Integer>> ret = new ArrayList<>(); while (!finalStack.isEmpty()) { ArrayList<Integer> a = finalStack.pop(); ret.add(a); } return ret; }
6
@Override @RequestMapping(value = "/beers/{id}", method = RequestMethod.DELETE) @ResponseBody @Transactional public BeerResponse delete(@PathVariable("id") Long id) { Beer beer = persistenceService.delete(Beer.class, id); return BeerResponse.createBeerResponse(beer); }
0
@Override public void keyReleased(KeyEvent e) { //The code of the released Key int key = e.getKeyCode(); //The direction Direction direction = null; //We check each keycode and relate a direction to it if(key == e.VK_UP) { direction = Direction.UP; } if(key == e.VK_DOWN) { direction = Direction.DOWN; } if(key == e.VK_LEFT) { direction = Direction.LEFT; } if(key == e.VK_RIGHT) { direction = Direction.RIGHT; } if(direction != null) { Controller.Instance().movePlayer(direction); } repaint(); }
5
private TreeSet<Connectable> recursiveDFS(Connectable damOrRiver, TreeSet<Connectable> completedIndexs, TreeSet<Connectable> tmpList){ if(completedIndexs.contains(damOrRiver)){ if(tmpList != null) completedIndexs.addAll(tmpList); return completedIndexs; // If it has already been solved, stop } if(damOrRiver.getDownstream() == null) return completedIndexs; // If it is trivial stop if(damOrRiver.getDownstream().equals(getOcean())){ completedIndexs.add(damOrRiver); if(tmpList != null) completedIndexs.addAll(tmpList); return completedIndexs; } // If this is the first, create the list and check the next one if(tmpList == null){ tmpList = new TreeSet<Connectable>(); tmpList.add(damOrRiver); return recursiveDFS(damOrRiver.getDownstream(), completedIndexs, tmpList); } // tmpList is not null // If damOrRiver has already been checked we can stop if(tmpList.contains(damOrRiver)) return completedIndexs; // There is a loop somewhere so not valid // Not the first and hasn't been checked tmpList.add(damOrRiver); return recursiveDFS(damOrRiver.getDownstream(), completedIndexs, tmpList); }
7
public double messageNode2Factor(int factor, int node, int value) { double result = 1.0; result *= messageFactor2Node(node, node, value); if (factor == potentials.chainLength() + node && factor > potentials.chainLength() + 1) { // right factor f' -> n -> f && this is not the second node result *= messageFactor2Node(factor-1, node, value); } else if (factor == potentials.chainLength() + node -1 && factor <= 2 * potentials.chainLength() - 2) { // left factor f <- n <- f' result *= messageFactor2Node(factor+1, node, value); } else { // they are not connected return result; } return result; }
4
public void changedServerPswd(boolean psw_set){ togglePassword(psw_set); if(psw_set){ // When password is first loaded set fake text serv_pswd.setText("fake"); passChanged=false; } else { serv_pswd.setText(""); } }
1
public double getProportion(String oldUnit, String newUnit) { double result = 0; double numerador = 0; double denominador = 1; if(oldUnit.equalsIgnoreCase("Hours")) { numerador = 1; } else if(oldUnit.equalsIgnoreCase("Days")) { numerador = 24; } else if(oldUnit.equalsIgnoreCase("Months")) { numerador = 24*30; } else if(oldUnit.equalsIgnoreCase("Years")) { numerador = 24*30*12; } if(newUnit.equalsIgnoreCase("Hours")) { denominador = 1; } else if(newUnit.equalsIgnoreCase("Days")) { denominador = 24; } else if(newUnit.equalsIgnoreCase("Months")) { denominador = 24*30; } else if(newUnit.equalsIgnoreCase("Years")) { denominador = 24*30*12; } result = (double)(numerador/denominador); return result; }
8
private void packtiles(Collection<Tile> tiles, Coord tsz) { int min = -1, minw = -1, minh = -1; int nt = tiles.size(); for (int i = 1; i <= nt; i++) { int w = Tex.nextp2(tsz.x * i); int h; if ((nt % i) == 0) h = nt / i; else h = (nt / i) + 1; h = Tex.nextp2(tsz.y * h); int a = w * h; if ((min == -1) || (a < min)) { min = a; minw = w; minh = h; } } TexIM packbuf = new TexIM(new Coord(minw, minh)); Graphics g = packbuf.graphics(); int x = 0, y = 0; for (Tile t : tiles) { g.drawImage(t.img, x, y, null); t.tex = new TexSI(packbuf, new Coord(x, y), tsz); if ((x += tsz.x) > (minw - tsz.x)) { x = 0; if ((y += tsz.y) >= minh) throw (new LoadException( "Could not pack tiles into calculated minimum texture", Resource.this)); } } packbuf.update(); }
7
public void setCode(String code) { this.code = code; }
0
private byte[] crypt_raw(byte password[], byte salt[], int log_rounds) { int rounds, i, j; int cdata[] = (int[])bf_crypt_ciphertext.clone(); int clen = cdata.length; byte ret[]; if (log_rounds < 4 || log_rounds > 31) throw new IllegalArgumentException ("Bad number of rounds"); rounds = 1 << log_rounds; if (salt.length != BCRYPT_SALT_LEN) throw new IllegalArgumentException ("Bad salt length"); init_key(); ekskey(salt, password); for (i = 0; i < rounds; i++) { key(password); key(salt); } for (i = 0; i < 64; i++) { for (j = 0; j < (clen >> 1); j++) encipher(cdata, j << 1); } ret = new byte[clen * 4]; for (i = 0, j = 0; i < clen; i++) { ret[j++] = (byte)((cdata[i] >> 24) & 0xff); ret[j++] = (byte)((cdata[i] >> 16) & 0xff); ret[j++] = (byte)((cdata[i] >> 8) & 0xff); ret[j++] = (byte)(cdata[i] & 0xff); } return ret; }
7
public boolean handleMaterialAcceleration(AxisAlignedBB par1AxisAlignedBB, Material par2Material, Entity par3Entity) { int var4 = MathHelper.floor_double(par1AxisAlignedBB.minX); int var5 = MathHelper.floor_double(par1AxisAlignedBB.maxX + 1.0D); int var6 = MathHelper.floor_double(par1AxisAlignedBB.minY); int var7 = MathHelper.floor_double(par1AxisAlignedBB.maxY + 1.0D); int var8 = MathHelper.floor_double(par1AxisAlignedBB.minZ); int var9 = MathHelper.floor_double(par1AxisAlignedBB.maxZ + 1.0D); if (!this.checkChunksExist(var4, var6, var8, var5, var7, var9)) { return false; } else { boolean var10 = false; Vec3D var11 = Vec3D.createVector(0.0D, 0.0D, 0.0D); for (int var12 = var4; var12 < var5; ++var12) { for (int var13 = var6; var13 < var7; ++var13) { for (int var14 = var8; var14 < var9; ++var14) { Block var15 = Block.blocksList[this.getBlockId(var12, var13, var14)]; if (var15 != null && var15.blockMaterial == par2Material) { double var16 = (double)((float)(var13 + 1) - BlockFluid.getFluidHeightPercent(this.getBlockMetadata(var12, var13, var14))); if ((double)var7 >= var16) { var10 = true; var15.velocityToAddToEntity(this, var12, var13, var14, par3Entity, var11); } } } } } if (var11.lengthVector() > 0.0D) { var11 = var11.normalize(); double var18 = 0.014D; par3Entity.motionX += var11.xCoord * var18; par3Entity.motionY += var11.yCoord * var18; par3Entity.motionZ += var11.zCoord * var18; } return var10; } }
8
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof CleasingTagsHtml)) { return false; } CleasingTagsHtml other = (CleasingTagsHtml) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
5
private ParsedExpression parseShell(String shell) { Assert.notNull(shell, "Shell must not be null"); Set<String> namedParameters = new HashSet<String>(); ParsedExpression parsedShell = new ParsedExpression(shell); char[] shellChars = shell.toCharArray(); int namedParameterCount = 0; // int unnamedParameterCount = 0; // int totalParameterCount = 0; int i = 0; while (i < shellChars.length) { // 获取跳过注释后的有效表达式起始位置 int skipToPosition = skipCommentsAndQuotes(shellChars, i); if (i != skipToPosition) { if (skipToPosition >= shellChars.length) { break; } i = skipToPosition; } char c = shellChars[i]; // 判断当前的字符是否为参数起始符":" if (c == ':') { int j = i + 1; // 如果有连续多个“:”,只有最后一个才会作为参数的起始符 if (j < shellChars.length && shellChars[j] == ':') { i++; continue; } j = endIndexOfParameter(shellChars, j); if (j - i > 1) { String parameter = shell.substring(i + 1, j); namedParameterCount = addNamedParameter(namedParameters, parameter, namedParameterCount); parsedShell.addNamedParameter(parameter, i, j); // totalParameterCount++; } i = j - 1; } i++; } // parsedShell.setNamedParameterCount(namedParameterCount); // parsedShell.setUnnamedParameterCount(unnamedParameterCount); // parsedShell.setTotalParameterCount(totalParameterCount); return parsedShell; }
7
public void actionPerformed(ActionEvent e) { if (e.getSource() == display) { } else if (e.getSource() == ok) { this.setVisible(false); this.dispose(); } else if (e.getSource() == resize) { gridPanel.initFonts(); chineseExample.setFont(gridPanel.getChineseFont()); pinyinExample.setFont(gridPanel.getPinyinFont()); otherExample.setFont(gridPanel.getOtherFont()); gridPanel.repaint(); } else if (e.getSource() == chinese) { Font nf = JFontChooser.showDialog(this, "Choose Chinese Font", chText, gridPanel.getChineseFont()); if (nf == null) { return; } chineseExample.setFont(nf); CharProps.getProperties().setProperty("font.ch.face", nf.getFontName()); CharProps.getProperties().setProperty("font.ch.size", nf.getSize() + ""); CharProps.getProperties().setProperty("font.ch.style", nf.getStyle() + ""); gridPanel.setChineseFont(nf); } else if (e.getSource() == pinyin) { Font nf = JFontChooser.showDialog(this, "Choose Pinyin Font", pinText, gridPanel.getPinyinFont()); if (nf == null) { return; } gridPanel.setPinyinFont(nf); CharProps.getProperties().setProperty("font.pinyin.face", nf.getFontName()); CharProps.getProperties().setProperty("font.pinyin.size", nf.getSize() + ""); CharProps.getProperties().setProperty("font.pinyin.style", nf.getStyle() + ""); pinyinExample.setFont(nf); } else if (e.getSource() == other) { Font nf = JFontChooser.showDialog(this, "Choose other font", enText, gridPanel.getOtherFont()); if (nf == null) { return; } CharProps.getProperties().setProperty("font.other.face", nf.getFontName()); CharProps.getProperties().setProperty("font.other.size", nf.getSize() + ""); CharProps.getProperties().setProperty("font.other.style", nf.getStyle() + ""); gridPanel.setOtherFont(nf); otherExample.setFont(nf); } ListPanel.refreshFonts(); CharApp.getInstance().getListPanel().repaint(); }
9
private float blockWeight(final Block block) { int depth = cfg.loopDepth(block); if (depth > RegisterAllocator.MAX_DEPTH) { return RegisterAllocator.MAX_WEIGHT; } float w = 1.0F; while (depth-- > 0) { w *= RegisterAllocator.LOOP_FACTOR; } return w; }
2
private KmeansLogger() throws LogException { KmeansLogger.log= Logger.getLogger(KmeansLogger.class.getName()); FileHandler fh= null; try { fh = new FileHandler("LogKmeans " + new Date().toString()); KmeansLogger.log.addHandler(fh); KmeansLogger.log.setUseParentHandlers(false); } catch (SecurityException e) { throw new LogException(e.getMessage(), e); } catch (IOException e) { throw new LogException(e.getMessage(), e); } catch (Exception e) { throw new LogException(e.getMessage(), e); } }
3
private void drawMenu() { if (interfaceNumber == 0) { bufferGraphics.drawImage(imageMap.get("missionBackground"), 0, 0, this); drawButtonsFromList(pathwayMissionButtons); } else if (interfaceNumber == 11) { bufferGraphics.drawImage(imageMap.get("chooseBackground"), 0, 0, this); drawButtonsFromList(chooseYourOwnAdventureButtons); } else if (interfaceNumber == 12) { bufferGraphics.drawImage(imageMap.get("missionAccomplished"), 115, 155, this); hosFont = hosFont.deriveFont(18.0f); bufferGraphics.setFont(hosFont); FontMetrics fontMetrics = bufferGraphics.getFontMetrics(hosFont); bufferGraphics.setColor(new Color(51, 51, 51)); bufferGraphics.drawString("" + score, 460 - fontMetrics.stringWidth("" + score), 265); bufferGraphics.drawString("+50", 460 - fontMetrics.stringWidth("+50"), 303); bufferGraphics.drawString("" + (score+50), 460 - fontMetrics.stringWidth("" + (score+50)), 335); drawButtonsFromList(missionButtons); } else if (interfaceNumber == 100) { bufferGraphics.drawImage(imageMap.get("mainBackground"), 0, 0, this); drawButtonsFromList(mainMenuButtons); } }
4
public void update() { if (!blnLoaded) { return; } int x, y, i, i2; x=0; y=0; for (i=0; i<=numMapImages; i++) { gD_p.drawImage(imgMapPalette, x*intImageSizePalette,y*intImageSizePalette, (x+1)*intImageSizePalette,(y+1)*intImageSizePalette, i*intImageSizePalette,0, (i+1)*intImageSizePalette,intImageSizePalette, null); x++; if (x > 24) { y++; x = 0; } } gD_p.setColor(Color.green); gD_p.drawRoundRect((int)(pfX*intImageSizePalette),(int)(pfY*intImageSizePalette), intImageSizePalette-1,intImageSizePalette-1,intImageSizePalette/3,intImageSizePalette/3); gD_f.drawImage(imgOriginalMap, 0,0, intImageOriginalSize,intImageOriginalSize, ForeGroundTile*intImageOriginalSize,0, (ForeGroundTile+1)*intImageOriginalSize,intImageOriginalSize, null); int sx = frame.scrollHorz.getValue(); int sy = frame.scrollVert.getValue(); int sx1 = sx + frame.scrollHorz.getVisibleAmount(); int sy1 = sy + frame.scrollVert.getVisibleAmount(); if ((sx1+sx) >= MapColumns) { sx1 = MapColumns - sx - 1; } if ((sy1+sy) >= MapRows) { sy1 = MapRows - sy - 1; } for (i=0;i<=sx1;i++) { for (i2=0;i2<=sy1;i2++) { //Draw map(background) drawTile(imgMap,i,i2,shrMap[i+sx][i2+sy]); } } if (blnActiveSelection) { Color highlight = new Color(255,255,255,128); gD.setColor(highlight); int rx, ry, startX, startY, stopX, stopY, width, height; startX = min(selectStartX,selectStopX); stopX = max(selectStartX,selectStopX); startY = min(selectStartY,selectStopY); stopY = max(selectStartY,selectStopY); rx = (startX-sx)*intImageSize; width = ((stopX-sx+1)*intImageSize) - rx; ry = (startY-sy)*intImageSize; height = ((stopY-sy+1)*intImageSize) - ry; gD.fillRect(rx,ry,width,height); } }
8
protected Integer calcBPB_ReservedSecCnt() throws UnsupportedEncodingException { byte[] bTemp = new byte[2]; for (int i = 14;i < 16; i++) { bTemp[i-14] = imageBytes[i]; } BPB_ReservedSecCnt = byteArrayToInt(bTemp); System.out.println("Количество секторов в Reserved region = " + BPB_ReservedSecCnt); return BPB_ReservedSecCnt; }
1
private boolean selectCommitMethod(Object obj,int reservID,int src,int tag) { boolean flag = true; try { // A case where a reservation only has 1 Gridlet Gridlet gridlet = (Gridlet) obj; if (checkGridlet(gridlet)) { ( (ARPolicy) policy_).handleCommitReservation(reservID, src, tag, gridlet); } else { flag = false; } } catch (ClassCastException c) { try { // A case where a reservation contains 1 or more Gridlets GridletList list = (GridletList) obj; Gridlet gl = null; // For each Gridlet in the list, check whether it has finished // before or not for (int i = 0; i < list.size(); i++) { gl = (Gridlet) list.get(i); if (!checkGridlet(gl)) { flag = false; break; } } if (flag) { ( (ARPolicy) policy_).handleCommitReservation(reservID, src, tag, list); } } catch (ClassCastException again) { flag = false; } } catch (Exception e) { flag = false; } return flag; }
7
public String getDateEmbauche() { return dateEmbauche; }
0
@EventHandler public void Nicks(AsyncPlayerChatEvent e) { Player p = e.getPlayer(); String name = p.getName(); String nick = NicknamesConfig.getNicknames().getString(name); // To avoid an NPE being thrown if(nick != null) p.setDisplayName(nick + ChatColor.RESET); }
1
private void drawSolutionProgress(Graphics2D g2) { if (numSolutions == 0) { return; } //System.err.println("---- " + currentHelp1Counter + " / " + numSolutions); if (HelpParadigm.Classic.equals(slateComponent.getSlateSettings().getHelpParadigm())) { // Draw circular progress of number of solutions drawCircularProgress(g2, currentCommandObject, numSolutions, currentHelp1Counter); } else if (HelpParadigm.Modern.equals(slateComponent.getSlateSettings().getHelpParadigm())) { // Draw lateral progress through the number of solutions drawLateralProgress(g2, currentCommandObject, numSolutions, currentHelp1Counter); } else if (HelpParadigm.Simple.equals(slateComponent.getSlateSettings().getHelpParadigm())) { // Draw circular progress through number of solutions drawCircularProgress(g2, currentCommandObject, numSolutions, currentHelp1Counter); } if (numSolutionSteps == 0) { return; } if (HelpParadigm.Classic.equals(slateComponent.getSlateSettings().getHelpParadigm())) { // Draw circular progress of steps in the solution drawCircularProgress(g2, currentCommandHelperObject, numSolutionSteps, currentHelp2Counter); } else if (HelpParadigm.Modern.equals(slateComponent.getSlateSettings().getHelpParadigm())) { // Draw circular progress of steps in the solution drawCircularProgress(g2, currentCommandObject, numSolutionSteps, currentHelp2Counter); } // NOTE: no progress indicator for # of pieces for HelpParadigm.Simple }
7
public void setName(String name) { this.name = name; }
0
public SubgroupPanel() { super(); setCellRenderer(new SymmetryListCellRenderer()); setSelectionBackground(SymmetryChooser.SelectionBackground); setBackground(Color.WHITE); addListSelectionListener(new ListSelectionListener() { @SuppressWarnings("unchecked") @Override public void valueChanged(final ListSelectionEvent e) { // Fire event if symmetry was chosen. final SubgroupPanel list = SubgroupPanel.this; Symmetry<?> subgroup = list.getSelectedValue(); if (subgroup != null) { logger.info("SubgroupPanel: Symmetry chosen: " + subgroup.coxeter()); Class<?> type = lastChosenSymmetry.getType(); if (type == Point3D.class) { dispatcher.fireEvent(new Symmetry3DChooseEvent( (Symmetry<Point3D>) subgroup)); } else if (type == Point4D.class) { dispatcher.fireEvent(new Symmetry4DChooseEvent( (Symmetry<Point4D>) subgroup)); } } } }); EventDispatcher.get().addHandler(DimensionSwitchHandler.class, this); }
5
public void enterLoop() { _mainFrame.dispose(); BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); while(true) { try { if(r.ready()) { String s = r.readLine(); if(s.equals("exit")) { _server.kill(); System.out.println("Good Bye"); System.exit(0); } else { String[] split = s.split(" "); //TODO: Remove this!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if(split.length == 2 && split[0].equals("roll")) { Integer i = Integer.parseInt(split[1]); if(i >= 2 && i <= 12) _server.roll(i); } } } } catch (Exception e) { } } }
8
private String safe (String src) { StringBuffer sb = new StringBuffer (); for (int i = 0; i < src.length (); i++) { char c = src.charAt (i); if (c >= 32 && c < 128) { sb.append (c); } else { sb.append ("<" + (int) c + ">"); } } return sb.toString (); }
3