text
stringlengths
14
410k
label
int32
0
9
@SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.NORMAL) public void mossify(final PlayerInteractEvent evt) { if (evt.getPlayer() != null) { if (evt.getAction() == Action.RIGHT_CLICK_BLOCK) { if (evt.getClickedBlock().getType().equals(Material.COBBLESTONE)) { log("item in hand: " + evt.getPlayer().getItemInHand().getTypeId()); if (evt.getPlayer().getItemInHand().getTypeId() == 1944) { log("Event fired item in hand 1944, Target COBBLE!"); evt.getClickedBlock().setType(Material.MOSSY_COBBLESTONE); evt.getPlayer().getInventory().remove(new ItemStack(1944, 1)); } } } } }
4
private void availablePackagesListSelectionChanged() { int sel[] = getAvailablePackagesList().getSelectedIndices(); boolean useShortName = false; availableRobots.clear(); if (sel.length == 1) { useShortName = true; getAvailablePackagesList().scrollRectToVisible(getAvailablePackagesList().getCellBounds(sel[0], sel[0])); } for (int element : sel) { String selectedPackage = availablePackages.get(element); if (selectedPackage.equals("(All)")) { useShortName = false; availableRobots.clear(); for (IRobotSpecItem robotItem : robotList) { getRobotNameCellRenderer().setUseShortName(useShortName); availableRobots.add(new ItemWrapper(robotItem)); } break; } // Single package. for (IRobotSpecItem robotItem : robotList) { getRobotNameCellRenderer().setUseShortName(useShortName); if ((robotItem.getFullPackage() == null && selectedPackage.equals("(No package)")) || selectedPackage.equals(robotItem.getFullPackage())) { availableRobots.add(new ItemWrapper(robotItem)); } } } ((AvailableRobotsModel) getAvailableRobotsList().getModel()).changed(); if (availableRobots.size() > 0) { availableRobotsList.setSelectedIndex(0); availableRobotsListSelectionChanged(); } }
9
public static void hidePlayerWhereAppropriate(Player client, boolean newPlayer) { for (Player user : Bukkit.getOnlinePlayers()) { if (HyperPVP.getSpectators().containsKey(user.getName()) && HyperPVP.getGameSessions().containsKey(client.getName())) { client.hidePlayer(user); user.showPlayer(client); } else if (HyperPVP.getGameSessions().containsKey(user.getName()) && HyperPVP.getSpectators().containsKey(client.getName())) { user.hidePlayer(client); client.showPlayer(user); } else { client.showPlayer(user); user.showPlayer(client); } } if (HyperPVP.getGameSessions().containsKey(client.getName()) && newPlayer) { resetInventory(client); client.teleport(HyperPVP.getMap().getRandomSpawn(client)); client.setGameMode(GameMode.SURVIVAL); client.sendMessage(HyperPVP.getMap().matchInfoToString(client)); //client.setAllowFlight(false); } }
7
private static void dehoist(OutlinerDocument doc) { try { TextKeyListener.dehoist(doc.tree.getEditingNode()); } catch (Exception e) { System.out.println("Exception: " + e); } }
1
public void actualizaTabla() { System.out.println("insertando :" + getRowCount()); this.setRowCount(0); for (Ticket tic : tickets) { String fec_sal = ""; try { fec_sal = tic.getSegmentos().get(0).getFechaSalida(); } catch (Exception e) { fec_sal = ""; } DecimalFormat format = new DecimalFormat("###,###.##"); String oris = (tic.isOris()) ? "1" : "0"; addRow(new Object[]{tic.getTipo(), tic.getcLineaAerea(), tic.getEstado(), tic.getTicket(), tic.getNumFile(), tic.getFechaEmision(), fec_sal, tic.getRuta(), tic.getNombrePasajero(), tic.getMoneda(), format.format(tic.getValorNeto()), format.format(tic.getValorTasas()), format.format(tic.getValorFinal()), tic.getComision(), tic.getOldTicket(), oris, tic.getGds() }); } }
3
public static List<Message> processMessage(String input) throws QueueNotFoundException{ System.out.println("************************************"); System.out.println("Client received : "+input); Message msg = null; String topic = null; try { msg = new Message(input); topic = msg.topic(); } catch (JSONException e) { e.printStackTrace(); } MBusQueue queue = MBusQueueFactory.getQueue(topic); if(queue != null){ if(msg.containsKey(Constants.MESSAGEBUS_COMMAND)){ try { if(msg.get(Constants.MESSAGEBUS_COMMAND) != null && msg.get(Constants.MESSAGEBUS_COMMAND).equalsIgnoreCase(Constants.FETCH_MESSAGE)){ return queue.fetch(10); } } catch (JSONException e) { e.printStackTrace(); } }else{ queue.add(msg); } } System.out.println("************************************"); return null; }
6
private RegularExpresionNode Symbol() throws ParserException { if (Character.isLetterOrDigit(currentSymbol)) { SymbolNode sNode = new SymbolNode(); sNode.Value = currentSymbol; RegularExpresionNode symbolNode = sNode; currentSymbol = getNextSymbol(); return symbolNode; } else if(currentSymbol=='$') { currentSymbol = getNextSymbol(); return new EpsilonSymbol(); } else { throw new ParserException("Symbol not recognized"); } }
2
public ArrayList<Col> load(String databaseName, String table) { DTDValidator ob = new DTDValidator(); if (ob.validate(databaseName + "_" + table) == false) { System.out.println("table format not correct"); return null; } else { try { File fXmlFile = new File(path + "/" + databaseName + "_" + table + ".xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); // System.out.println("Root element :" + // doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("field"); for (int temp = 0; temp < nList.getLength(); temp++) { Col obj = new Col(); ArrayList<String> elements = new ArrayList<>(); Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; obj.setFieldName(eElement.getElementsByTagName("name") .item(0).getTextContent()); obj.setFieldType(eElement.getElementsByTagName("type") .item(0).getTextContent()); NodeList nList2 = eElement .getElementsByTagName("element"); // System.out.println(nList2.); for (int temp2 = 0; temp2 < nList2.getLength(); temp2++) { Node nNode2 = nList2.item(temp2); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement2 = (Element) nNode2; elements.add(eElement2.getTextContent()); } } // rrr.add(eElement.getElementsByTagName("element").item(1).getTextContent()); obj.setElements(elements); returnedarr.add(obj); // rrr.clear(); } } } catch (Exception e) { return null; } return returnedarr; } }
6
public static void main(String[] args){ Scanner in = new Scanner(System.in); String line = in.nextLine(); HashSet<Character> seen = new HashSet<Character>(); for(char c : line.toCharArray()){ if(c>='a' && c<='z' && !seen.contains(c)){ seen.add(c); } } System.out.println(seen.size()); }
4
private Map getAllMultiInterfaces(MultiType type) { Map map = new HashMap(); Iterator iter = type.interfaces.values().iterator(); while (iter.hasNext()) { CtClass intf = (CtClass)iter.next(); map.put(intf.getName(), intf); getAllInterfaces(intf, map); } return map; }
1
public void suddenChange(State newState){ deltaTime = 0; state = newState; switch (state) { case KKMMM: US.setLamps(true, true, false); Barat.setLamps(true, false, false); Timur.setLamps(true, false, false); TU.setLamp(true); stateTime = Main.time[0]; break; case HHMMM: US.setLamps(false, false, true); Barat.setLamps(true, false, false); Timur.setLamps(true, false, false); TU.setLamp(true); stateTime = Main.time[1]; break; case MMMKM: US.setLamps(true, false, false); Barat.setLamps(true, false, false); Timur.setLamps(true, true, false); TU.setLamp(true); stateTime = Main.time[2]; break; case MMMHH: US.setLamps(true, false, false); Barat.setLamps(true, false, false); Timur.setLamps(false, false, true); TU.setLamp(false); stateTime = Main.time[3]; break; case MMKHH: US.setLamps(true, false, false); Barat.setLamps(true, true, false); Timur.setLamps(false, false, true); TU.setLamp(false); stateTime = Main.time[4]; break; case MMKHM: US.setLamps(true, false, false); Barat.setLamps(true, true, false); Timur.setLamps(false, false, true); TU.setLamp(true); stateTime = Main.time[5]; break; case MMHHM: US.setLamps(true, false, false); Barat.setLamps(false, false, true); Timur.setLamps(false, false, true); TU.setLamp(true); stateTime = Main.time[6]; break; case MMKKM: US.setLamps(true, false, false); Barat.setLamps(true, true, false); Timur.setLamps(true, true, false); TU.setLamp(true); stateTime = Main.time[7]; break; } }
8
public void setjLabelNumeroRapport(JLabel jLabelNumeroRapport) { this.jLabelNumeroRapport = jLabelNumeroRapport; }
0
private void addButtonHandlers() { connectButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //todo :Work on if else if (serverNameText.getText().equals("")) { status.setText("Invalid Server Name"); } else { if (!sentConnection) { controller.connectToServer(); sentConnection = true; } } } }); }
2
public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("[SaleitemsVo:"); buffer.append(" id: "); buffer.append(id); buffer.append(" saleid: "); buffer.append(saleid); buffer.append(" itemcode: "); buffer.append(itemcode); buffer.append(" name: "); buffer.append(name); buffer.append(" price: "); buffer.append(price); buffer.append(" quantity: "); buffer.append(quantity); buffer.append(" suppliercode: "); buffer.append(suppliercode); buffer.append(" bumoncode: "); buffer.append(bumoncode); buffer.append("]"); return buffer.toString(); }
0
public void load(String mp3URL) { this.mp3URL=mp3URL; URL url= this.getClass().getResource(mp3URL); try { in= AudioSystem.getAudioInputStream(url); } catch (UnsupportedAudioFileException | IOException e) { e.printStackTrace(); } din = null; AudioFormat baseFormat = in.getFormat(); decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false); din = AudioSystem.getAudioInputStream(decodedFormat, in); loaded=true; }
1
public static boolean containsCardPlayableOn(ArrayList<Card> cards, Card dest) { for (Card card : cards) { if (dest == null || card.value == Card.EIGHT || card.value == dest.value || card.suite == dest.suite) { return true; } } return false; }
5
private ArrayList<Card> returnThreeSetup() { ArrayList<Card> setup = new ArrayList<>(); if (compareCardFigures(0, 2)) { setup.add(cards.get(0)); setup.add(cards.get(1)); setup.add(cards.get(2)); } else if (compareCardFigures(1, 3)) { setup.add(cards.get(1)); setup.add(cards.get(2)); setup.add(cards.get(3)); } return setup; }
2
public ScalarMultiplicationDialog(final Panel panel) { setBounds(1, 1, 270, 190); Toolkit toolkit = getToolkit(); Dimension size = toolkit.getScreenSize(); setLocation(size.width / 3 - getWidth() / 3, size.height / 3 - getHeight() / 3); this.setResizable(false); setLayout(null); JPanel pan = new JPanel(); pan.setBorder(BorderFactory.createTitledBorder("Value")); pan.setBounds(0, 0, 270, 60); JLabel label = new JLabel("Value = "); final JTextField field = new JTextField("1.0"); field.setColumns(3); JButton okButton = new JButton("OK"); okButton.setSize(270, 40); okButton.setBounds(0, 120, 270, 40); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { double value; try { value = Double.valueOf(field.getText().trim()); } catch (NumberFormatException ex) { new MessageFrame("Invalid data"); return; } if (value < 0 || value > Image.MAX_VAL) { new MessageFrame("Invalid Parameters"); return; } Image original = panel.getImage(); Image img = PunctualOperationsUtils.multiply(original, value); panel.setImage(img); panel.repaint(); dispose(); } }); pan.add(label); pan.add(field); add(pan); this.add(okButton); }
3
public static void main(String[] args) { // TODO Auto-generated method stub cri_dao = DaoFactory.getInstance().getCriteriaDAO(); while (true) { System.out .print("Add Criteria(ac) / Find Criteria(f) / Remove Criteria(rc) / Find All Criteria(fa) / clearDB(clear) : "); String mode = sc.nextLine(); if (mode.equalsIgnoreCase(ADD)) { System.out.print("Add Criteria : "); String name = sc.nextLine(); System.out.println(cri_dao.saveCriteria(name)); } else if (mode.equalsIgnoreCase(FIND)) { System.out.print("Find Criteria : "); String name = sc.nextLine(); System.out.println(cri_dao.saveCriteria(name)); } else if (mode.equalsIgnoreCase(REMOVE)) { System.out.print("Remove Criteria : "); String name = sc.nextLine(); System.out.println(cri_dao.deleteCriteria(name)); } else if (mode.equalsIgnoreCase(FIND_ALL)) { List<Criteria> result = cri_dao.findAllCriteria(); //System.out.println(result.size()); for(int i = 0;i<result.size(); i++) { System.out.println(result.get(i)); } }else if ( mode.equalsIgnoreCase("clear")) { List<Criteria> result = cri_dao.findAllCriteria(); Iterator<Criteria> it = result.iterator(); while(it.hasNext()) { Criteria c = it.next(); System.out.println(cri_dao.deleteCriteria(c.getName())); } } else break; } }
8
public void updateMyImage(){ if(Playtable.myRank == 0){ lbUniqueImage.setIcon(new ImageIcon(getClass().getResource("/dalmuti/image/grDalmuti.jpg"))); lbUniqueImage.setText("<html><div style=\"text-align: center;\">" + Client.mo.users.get(Playtable.myRank).getNickname() + "<br>" + " du bist der " + "<br />" + rank(Playtable.myRank) + "</html>"); }if(Playtable.myRank == 1){ lbUniqueImage.setIcon(new ImageIcon(getClass().getResource("/dalmuti/image/klDalmuti.jpg"))); lbUniqueImage.setText("<html><div style=\"text-align: center;\">" + Client.mo.users.get(Playtable.myRank).getNickname() + "<br>" + " du bist der " + "<br />" + rank(Playtable.myRank) + "</html>"); }if(Playtable.myRank == 2){ lbUniqueImage.setIcon(new ImageIcon(getClass().getResource("/dalmuti/image/klDiener.jpg"))); lbUniqueImage.setText("<html><div style=\"text-align: center;\">" + Client.mo.users.get(Playtable.myRank).getNickname() + "<br>" + " du bist der " + "<br />" + rank(Playtable.myRank) + "</html>"); }if(Playtable.myRank == 3){ lbUniqueImage.setIcon(new ImageIcon(getClass().getResource("/dalmuti/image/grDiener.jpg"))); lbUniqueImage.setText("<html><div style=\"text-align: center;\">" + Client.mo.users.get(Playtable.myRank).getNickname() + "<br>" + " du bist der " + "<br />" + rank(Playtable.myRank) + "</html>"); } }
4
private static void visitFrameTypes(final int n, final Object[] types, final List result) { for (int i = 0; i < n; ++i) { Object type = types[i]; result.add(type); if (type == Opcodes.LONG || type == Opcodes.DOUBLE) { result.add(Opcodes.TOP); } } }
3
public void leesOpdrachtenVanBestand(OpdrachtCatalogus opdrachtCatalogus) { File file = new File("bestanden/opdrachten"); if (file.exists()) { try { Scanner scanner = new Scanner(file); while (scanner.hasNext()) { String lijn = scanner.nextLine(); String[] velden = lijn.split(","); int id = Integer.parseInt(velden[0]); String vraag = velden[1]; String antwoord = velden[2]; int maxAantalPogingen = Integer.parseInt(velden[3]); String antwoordHint = velden[4]; int maxAntwoordTijd = Integer.parseInt(velden[5]); String soortOpdracht = velden[6]; String opdrachtCategorieString = velden[7]; OpdrachtCategorie opdrachtCategorie = OpdrachtCategorie .valueOf(opdrachtCategorieString); Opdracht opdracht = null; if (soortOpdracht.equals("Meerkeuze")) { String alleKeuzes = velden[8]; opdracht = new Meerkeuze(vraag, antwoord, maxAantalPogingen, alleKeuzes, antwoordHint, maxAntwoordTijd, opdrachtCategorie); opdracht.setId(id); } else if (soortOpdracht.equals("Reproductie")) { String trefwoorden = velden[8]; int minAantalJuisteTrefwoorden = Integer .parseInt(velden[9]); opdracht = new Reproductie(vraag, antwoordHint, maxAantalPogingen, antwoordHint, maxAntwoordTijd, trefwoorden, minAantalJuisteTrefwoorden, opdrachtCategorie); } else if (soortOpdracht.equals("Opsomming")) { opdracht = new Opsomming(vraag, antwoord, maxAantalPogingen, antwoordHint, maxAntwoordTijd, opdrachtCategorie); } opdrachtCatalogus.getOpdrachten().add(opdracht); } if (scanner != null) { scanner.close(); } } catch (FileNotFoundException ex) { System.out.println("bestand niet gevonden"); } catch (NullPointerException ex) { System.out.println(ex.getMessage()); } catch (Exception ex) { System.out.println("here"); System.out.println(ex.getMessage()); } } }
9
public static final void visit(String url) { if (Config.getDebug()) Output.printTabLn("besuche: " + url, 2); getString(url); Control.sleep(5); }
1
private static void viewAFacMember(String lName, String gender) { boolean gend = false; if(gender.equals("m")) gend = true; else if(gender.equals("f")) gend = false; int index = getIndexOfFac(lName, gend); String allInfo = new String(); if(index >= 0) { Teacher t = (Teacher)Faculty.get(index); System.out.println(t.getName()); allInfo = "Name: " + t.getName(); allInfo += ("\n" + "Gender: " + convertGender(t.getGender())); allInfo += ("\n" + "Seats Taken: " + t.getSeats()); allInfo += ("\n" + "Table Number: " + t.getTableNum()); } JOptionPane.showMessageDialog(null, allInfo); }
3
public static void main(String[] args) { //TODO: Move command components to separate methods. if (args.length == 1) switch (args[0]) { /***************/ case "start": doLog = false; start(); break; /***************/ case "version": System.out.printf("JamChat Server version %s. Copyright (C) 2013 Pete Wicken.\n", getVersion()); System.exit(0); break; // Unreachable code; here to keep the IDE formatting happy /***************/ case "debug": //TODO implement debug feature. fall through to verbose. /***************/ case "verbose": doLog = true; break; /***************/ default: printUsage(ArgType.PROG_ARGS); break; } else printUsage(ArgType.PROG_ARGS); }
5
@Test public void multiThreadedTest() throws InterruptedException { final AtomicBoolean failed = new AtomicBoolean(false); final AvgTimeCounter c = new AvgTimeCounter(); final AtomicLong index = new AtomicLong(0); final long startTime = System.currentTimeMillis(); ArrayList<Thread> threads = new ArrayList<Thread>(); for (int i = 0; i < 10; i++) { Thread t = new Thread(new Runnable() { public void run() { try { long currentIndex = index.incrementAndGet(); while (currentIndex < 2000000) { c.addTime(startTime); if (currentIndex % 10000 == 0) c.getValue(); currentIndex = index.incrementAndGet(); } } catch (Exception e) { failed.set(true); } } }); threads.add(t); t.setDaemon(true); } for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); } if (failed.get()) Assert.fail(); }
7
private boolean setupEconomy() { if (getServer().getPluginManager().getPlugin("Vault") == null) { return false; } RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class); if (rsp == null) { return false; } econ = rsp.getProvider(); return econ != null; }
2
public static final int StateUpdateMatch(int index) { return index < 7 ? 7 : 10; }
1
private void inviteToParty() { if(mFriends.isEmpty()){ for (Person iPerson : ContactList.sPersonList){ mFriends.add(iPerson); } print("There are "+ContactList.sPersonList.size()+" people in the city"); print("Created "+mFriends.size()+" friends for party host"); } print("First RSVP is sent out"); //party is in 3 days //send RSVP1 and event invite Location partyLocation = getHousingRole().getLocation();//new Location(100, 0); Event party = new EventParty(EnumEventType.PARTY, Time.GetTime()+4, partyLocation, this, mFriends); //Event party = new EventParty(EnumEventType.PARTY, Time.GetTime()+4, ((HousingBaseRole)getHousingRole()).getLocation(), this, mFriends); Event rsvp = new EventParty(EnumEventType.RSVP1, -1, this); //respond immediately if(mName.equals("partyPersonFlake")){ for (Person iFriend : mFriends){ iFriend.msgAddEvent(rsvp); iFriend.msgAddEvent(party); } } else{ //partyPerson or partyPersonNO for (Person iFriend : mFriends){ if(iFriend.getTimeShift()==mTimeShift){ iFriend.msgAddEvent(rsvp); iFriend.msgAddEvent(party); } } } }
6
public void drawTo(PPMEC PPM) { // Must scale x,y to final PPM dimensions // get x-coord int c = (int) (xRatio * PPM.getWidth()); // get y-coord int r = (int) (yRatio * PPM.getHeight()); int radius = (int) (radiusP * PPM.getWidth()); // Radius of R. // Scan through the pixels and try to see if any pixel is within the // range of radius. If found, colored that pixels. for (int i = 0; i < PPM.getHeight(); i++) { for (int j = 0; j < PPM.getWidth(); j++) { // d is the distance between the traversing point and the circle // origin. int d = (r - i) * (r - i) + (c - j) * (c - j); if (d <= radius * radius) { PPM.setPixel(i, j, color); } } } }
3
public void checkReleased(GridUnit gu) { gu.isPressed = false; if (!gu.isFlagged) { if (gu.isMined && !_extralife && !gu.isChecked) { //subtractScore(_scoreBonus); exposeMines(gu); endGame(0); } else { if (_extralife && gu.isMined) { gu.isChecked = true; stateChanged(gu); } else { check(gu); } _extralife = false; } } stateChanged(gu); if(hasWon() && !isGameOver()) { //TODO: game economics endGame(getLevelScoreBonus()); } }
8
public Chunk(int xPos,int zPos ){ this.xPos = xPos; this.zPos = zPos; this.parent = parent; }
0
public static void clearDrugPage(DrugInventoryPage drugP){ for(int i=0;i<2;i++){ drugP.getTable().setValueAt("Drug Name",0,0); drugP.getTable().setValueAt("Quantity",0,1); drugP.getTable().setValueAt("Controlled Flag",0,2); drugP.getTable().setValueAt("Price",0,3); drugP.getTable().setValueAt("",1,0); drugP.getTable().setValueAt("",1,1); drugP.getTable().setValueAt("",1,2); drugP.getTable().setValueAt("",1,3); } drugP.getDName().setText(""); drugP.setGeneralText(""); drugP.setEffectsText(""); }
1
public JSONObject accumulate(String key, Object value) throws JSONException { testValidity(value); Object o = opt(key); if (o == null) { put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); } else if (o instanceof JSONArray) { ((JSONArray)o).put(value); } else { put(key, new JSONArray().put(o).put(value)); } return this; }
3
public StringBuffer startTable(StringBuffer org, MutableAttributeSet attrSet) { originalBuffer = org; ret = new StringBuffer(); tblno = tblcnt++; tc = "" + (char) ('a' + (tblno / (26 * 26))) + (char) ((tblno / 26) + 'a') + (char) ((tblno % 26) + 'a'); String val = (String) attrSet.getAttribute(HTML.Attribute.BORDER); border = false; if (val != null) { border = true; bordwid = 2; if (val.equals("") == false) { try { bordwid = Integer.parseInt(val); } catch (Exception ex) { } if (bordwid == 0) { border = false; } } } String bgcolor = (String) attrSet.getAttribute(HTML.Attribute.BGCOLOR); if (bgcolor != null) { try { if (bgcolor.length() != 7 && bgcolor.charAt(0) == '#') { throw new NumberFormatException(); } red = Integer.decode("#" + bgcolor.substring(1, 3)) .doubleValue(); blue = Integer.decode("#" + bgcolor.substring(3, 5)) .doubleValue(); green = Integer.decode("#" + bgcolor.substring(5, 7)) .doubleValue(); red /= 255.0; blue /= 255.0; green /= 255.0; } catch (NumberFormatException e) { red = 1.0; blue = 1.0; green = 1.0; } } return ret; }
8
public void setTile(int x, int y, int id) { if(x >= width || x < 0 || y >= height || y < 0) return; int oldID = this.map[x][y]; this.map[x][y] = id; if(oldID != id) updateNeighbours(x, y, TileUpdateType.tileChange); }
5
public Pareto(double k, double lambda) throws ParameterException { if (k <= 0 || lambda <= 0) { throw new ParameterException("Pareto parameters k > 0, lambda > 0."); } else { this.k = k; this.lambda = lambda; exp = new Exponential(lambda); } }
2
private void tbProjetosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbProjetosMouseClicked this.btnExcluir.setEnabled(true); this.btnSalvarAlteracao.setEnabled(true); try { preencher(); } catch (Exception ex) { } }//GEN-LAST:event_tbProjetosMouseClicked
1
public void placeBet(Player p) { Scanner in = new Scanner(System.in); System.out.println("\n Please enter amount of bet for this hand!!"); while (!in.hasNextInt()) { System.out .println("\n Invalid $ amount, please bet atleast 1 chip"); in.next(); } Integer playerBet = in.nextInt(); while (((playerBet == null) || (playerBet < 1) || (playerBet > p .getBalanceAmount()))) { if (playerBet < 1) { System.out.println("\n You should bet atleast 1 chip"); } else if (playerBet > p.getBalanceAmount()) { System.out.println("\n Your bet exceeds your balance amount"); } else { System.out .println("\n Invalid bet, please enter a positive bet greater than 1 and less than your balance amount"); } while (!in.hasNextInt()) { System.out .println("\n Invalid $ amount, please bet atleast 1 chip"); in.next(); } playerBet = in.nextInt(); } p.setBet(playerBet); }
7
public void addId(String id) throws Exception { if (null == Id) { Id = new ArrayList<String>(); } else if (999 == notid.size()) { throw new Exception("Too many Ids. 1000 max."); } if (!Id.contains(id)) { Id.add(id); } }
3
public static void save(String filename) { File file = new File(filename); String suffix = filename.substring(filename.lastIndexOf('.') + 1); // png files if (suffix.toLowerCase().equals("png")) { try { ImageIO.write(onscreenImage, suffix, file); } catch (IOException e) { e.printStackTrace(); } } // need to change from ARGB to RGB for jpeg // reference: http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727 else if (suffix.toLowerCase().equals("jpg")) { WritableRaster raster = onscreenImage.getRaster(); WritableRaster newRaster; newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2}); DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel(); DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(), cm.getRedMask(), cm.getGreenMask(), cm.getBlueMask()); BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null); try { ImageIO.write(rgbBuffer, suffix, file); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Invalid image file type: " + suffix); } }
4
public void setFullScreen(DisplayMode displayMode) { final JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setUndecorated(true); frame.setIgnoreRepaint(true); frame.setResizable(false); device.setFullScreenWindow(frame); // if (displayMode != null && // device.isDisplayChangeSupported()) //{ try { device.setDisplayMode(displayMode); } catch (IllegalArgumentException ex) { } // fix for mac os x //frame.setSize(displayMode.getWidth(), // displayMode.getHeight()); //} // avoid potential deadlock in 1.4.1_02 try { EventQueue.invokeAndWait(new Runnable() { public void run() { frame.createBufferStrategy(2); } }); } catch (InterruptedException ex) { // ignore } catch (InvocationTargetException ex) { // ignore } }
3
public int f() { return 1; }
0
private String removeBracket(String str) throws Exception { if (!(str.startsWith("(") && str.endsWith(")")))//括弧で始まっていなければ、そのまま返す return str; int nest = 1; for (int i = 1; i < str.length() - 1; i++) { if (str.charAt(i) == '(') nest++; else if (str.charAt(i) == ')') nest--; if (nest == 0) return str; } if (nest != 1) throw new Exception("unbalanced bracket: " + str); str = str.substring(1, str.length() - 1); if (str.startsWith("(")) return removeBracket(str); else return str; }
8
public Converter(){ Collection<Warp> warps = ButtonWarp.getWarps(); for (Warp warp : warps){ // Check if warp contains bwr if (warp.commands.size() != 0){ String cmd = warp.commands.getFirst(); if (cmd.startsWith("bwr") && !cmd.contains("-")){ String args[] = cmd.split("\\s+"); // Try to parse try{ String newCmd = "bwr randomize " + args[2] + " -min " + args[3] + " -max " + args[4] + " -p <player>"; warp.commands.set(0, newCmd); warp.save(); Bukkit.getLogger().info("[ButtonWarpRandom] Converted old warp '" + warp.name + "'"); }catch (Exception ex){ } } } } }
5
public ArrayList<AlumnoBean> getPage(int intRegsPerPag, int intPage, ArrayList<FilterBean> alFilter, HashMap<String, String> hmOrder) throws Exception { ArrayList<Integer> arrId; ArrayList<AlumnoBean> arrAlumno = new ArrayList<>(); try { oMysql.conexion(enumTipoConexion); arrId = oMysql.getPage("alumno", intRegsPerPag, intPage, alFilter, hmOrder); Iterator<Integer> iterador = arrId.listIterator(); while (iterador.hasNext()) { AlumnoBean oAlumnoBean = new AlumnoBean(iterador.next()); arrAlumno.add(this.get(oAlumnoBean)); } oMysql.desconexion(); return arrAlumno; } catch (Exception e) { throw new Exception("AlumnoDao.getPage: Error: " + e.getMessage()); } finally { oMysql.desconexion(); } }
2
void smbFft(float[] fftBuffer, int fftFrameSize, int sign) /* FFT routine, (C)1996 S.M.Bernsee. Sign = -1 is FFT, 1 is iFFT (inverse) Fills fftBuffer[0...2*fftFrameSize-1] with the Fourier transform of the time domain data in fftBuffer[0...2*fftFrameSize-1]. The FFT array takes and returns the cosine and sine parts in an interleaved manner, ie. fftBuffer[0] = cosPart[0], fftBuffer[1] = sinPart[0], asf. fftFrameSize must be a power of 2. It expects a complex input signal (see footnote 2), ie. when working with 'common' audio signals our input signal has to be passed as {in[0],0.,in[1],0.,in[2],0.,...} asf. In that case, the transform of the frequencies of interest is in fftBuffer[0...fftFrameSize]. */ { float wr, wi, arg, temp; float tr, ti, ur, ui; int i, bitm, j, le, le2, k; int p1, p2, p1r, p1i, p2r, p2i; for (i = 2; i < 2*fftFrameSize-2; i += 2) { for (bitm = 2, j = 0; bitm < 2*fftFrameSize; bitm <<= 1) { if ((i & bitm)!=0) j++; j <<= 1; } if (i < j) { //p1 = fftBuffer+i; p1=i; //p2 = fftBuffer+j; p2=j; //temp = *p1; temp = fftBuffer[p1]; //*(p1++) = *p2; fftBuffer[p1++]=fftBuffer[p2]; //*(p2++) = temp; fftBuffer[p2++] = temp; //temp = *p1; temp = fftBuffer[p1]; //*p1 = *p2; fftBuffer[p1]=fftBuffer[p2]; //*p2 = temp; fftBuffer[p2]=temp; } } for (k = 0, le = 2; k < (long)(Math.log(fftFrameSize)/Math.log(2.)+.5); k++) { le <<= 1; le2 = le>>1; ur = 1.0f; ui = 0.0f; arg = (float) (M_PI / (le2>>1)); wr = (float) Math.cos(arg); wi = (float) (sign*Math.sin(arg)); for (j = 0; j < le2; j += 2) { //p1r = fftBuffer+j; p1r = j; p1i = p1r+1; p2r = p1r+le2; p2i = p2r+1; for (i = j; i < 2*fftFrameSize; i += le) { tr = fftBuffer[p2r] * ur - fftBuffer[p2i] * ui; ti = fftBuffer[p2r] * ui + fftBuffer[p2i] * ur; fftBuffer[p2r] = fftBuffer[p1r] - tr; fftBuffer[p2i] = fftBuffer[p1i] - ti; fftBuffer[p1r] += tr; fftBuffer[p1i] += ti; p1r += le; p1i += le; p2r += le; p2i += le; } tr = ur*wr - ui*wi; ui = ur*wi + ui*wr; ur = tr; } } }
7
@EventHandler public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { if (event.getEntity() instanceof Player) { Player player = (Player) event.getEntity(); ItemStack[] armorSlots = player.getInventory().getArmorContents(); for (int i = 0; i < armorSlots.length; i++) { ItemStack armor = armorSlots[i]; if (armor != null && armor.getTypeId() != 0 && ItemChecker.isArmor(plugin, armor.getType()) && Config.isItemEnabled(plugin, armor.getTypeId())) { Weapon weapon = new Weapon(plugin, armor); int armorBonus = Config.getArmor(WeaponType.ARMOR, weapon.getLevelStats()); event.setDamage(event.getDamage() - armorBonus); int levelState = weapon.getLevel(); weapon.addExperience(Config.EXP_PER_HIT); weapon.update(); if (weapon.getLevel() > levelState) { Util.dropExperience(player.getLocation(), Config.EXP_ON_LEVEL, 3); } } } } }
7
public void connect(TreeLinkNode root) { if (root == null) return; Queue<TreeLinkNode> nq = new LinkedList<TreeLinkNode>(); Queue<Integer> lq = new LinkedList<Integer>(); nq.add(root); lq.add(0); while (nq.size() > 0) { TreeLinkNode node = nq.poll(); int level = lq.poll(); if (nq.size() == 0 || level < lq.peek()) { node.next = null; if (node.left != null) { nq.add(node.left); lq.add(level +1); } if (node.right != null) { nq.add(node.right); lq.add(level + 1); } } } }
6
public void decryptEncryptedHands(final RSAService rsaService, final int numRequests) throws InvalidSubscriptionException, IOException { decryptionCount = 0; decryptSub = elvin.subscribe(NOT_TYPE + " == '" + DECRYPT_HAND_REQUEST + "' && " + GAME_ID + " == '" + gameHost.getID() + "' && " + REQ_USER + " == '" + user.getID() + "'"); decryptSub.addListener(new NotificationListener() { public void notificationReceived(NotificationEvent e) { System.out.println("Got decrypt request."); EncryptedHand encHand = null; Notification not; User userRequesting = findUserByID(e.notification .getString(SOURCE_USER)); if (userRequesting == null) { return; } decryptionCount++; if (decryptionCount > numRequests) { // more decryption requests than expected... someone is // trying to cheat try { callCheat(DECRYPT_REQUEST_ABUSE); } catch (Exception e1) { shutdown(); System.exit(-1); } } byte[] tmpBytes = (byte[]) e.notification.get(ENCRYPTED_HAND); try { encHand = (EncryptedHand) Passable.readObject(tmpBytes); if (!sigServ.validateSignature(encHand, userRequesting.getPublicKey())) { // sig failed! callCheat(SIGNATURE_FAILED); System.exit(0); } // decrypt and sign encHand = rsaService.decyrptEncHand(encHand); sigServ.createSignature(encHand); } catch (Exception e1) { shutdown(); System.exit(0); } not = new Notification(); not.set(NOT_TYPE, DECRYPT_HAND_REPLY); not.set(GAME_ID, gameHost.getID()); not.set(REQ_USER, userRequesting.getID()); try { not.set(ENCRYPTED_HAND, encHand.writeObject()); elvin.send(not); } catch (IOException e1) { shutdown(); System.exit(1); } System.out.println("Finished decryption request"); } }); return; }
6
public static TreeNode getMRCA(TreeNode curn1, TreeNode curn2) { //get path to root for first node ArrayList<TreeNode> path1 = new ArrayList<TreeNode>(); TreeNode parent = curn1; while (parent != null) { path1.add(parent); parent = parent.getParent(); } //find first match between this node and the first one parent = curn2; while (parent != null) { if (path1.contains(parent)) { return parent; } parent = parent.getParent(); } return null; }
3
public void playGameAsPlayer(ArrayList<User> gameUsers, SearchGamesTask jgt) throws InvalidSubscriptionException, InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InterruptedException, IOException { RSAService rsaService = comServ.waitPQ(); gameUser.setDecryptionKey(rsaService.getD()); // if more types of poker were added this would be a parameter and // SwingUI would instantiate it GamePlay thGamePlay = new TexasHoldEmGamePlay(); thGamePlay.init(); try { thGamePlay.playerGamePlay(rsaService, comServ, gameUser, gameUsers, sig, jgt); } catch (Exception e) { System.err.println("Error in player gameplay."); System.exit(0); } comServ.shutdown(); return; }
1
private void exportEnderchest(CompoundTag tag) { List<Tag> list = new ArrayList<Tag>(); for (byte i = 0; i < Enderchest.length; i++) { if (Enderchest[i] == null) continue; Tag t = Tag.fromNBTTag(CraftItemStack.asNMSCopy(Enderchest[i]).save(new NBTTagCompound())); ((CompoundTag) t).getValue().put("Slot", new ByteTag(i)); if (t != null) list.add(t); } tag.getValue().put("EnderItems", new ListTag(CompoundTag.class, list)); }
3
@Override public void initializeLanguage() { Array<Letter> lettersAvailable = this.getLanguage().getLettersAvailable(); char[] letterDistribution = new char[] { 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'd', 'd', 'd', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'f', 'f', 'g', 'g', 'h', 'h', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'l', 'l', 'l', 'l', 'l', 'j', 'k', 'm', 'm', 'm', 'n', 'n', 'n', 'n', 'n', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'p', 'p', 'q', 'r', 'r', 'r', 'r', 'r', 'r', 's', 's', 's', 's', 's', 's', 't', 't', 't', 't', 't', 't', 'u', 'u', 'u', 'u', 'u', 'u', 'v', 'v', 'w', 'x', 'y', 'z'}; for (int i = 0; i < letterDistribution.length; i++) { Random random = new Random(); Letter letter = new Letter(letterDistribution[i], i + random.nextInt() * random.nextInt() * random.nextInt()); lettersAvailable.add(letter); } this.getLanguage().setDictionaryPath(Constants.FRENCH_WORD_LIST_PATH); WordListParser.getInstance().parse(this);// TODO: think a better way // where to put it }
1
private void updateStateAskOrigin(List<Keyword> keywords, List<String> terms) { RecipeLearningState nextState; List<Keyword> countries = keywordsFromType(KeywordType.COUNTRY, keywords); if (countries.size() == 0) { if (terms.size() > 0) { ArrayList<DialogState> states = new ArrayList<DialogState>(); states.add(new RecipeAssistanceState(RecipeAssistance.RA_TELL_COUNTRY_FOUND)); states.add(new RecipeLearningState(RecipeLearning.RL_ASK_FIRST_INGREDIENT)); ArrayList<Data> refs = new ArrayList<Data>(); refs.add(recipe.getRecipeData()); KeywordData newCountry = new KeywordData(terms.get(terms.size() - 1), states, 5, refs, KeywordType.COUNTRY); newCountry.writeFile(); DialogManager.giveDialogManager().getDictionary().addKeyword(terms.get(terms.size() - 1), 5, states, refs, KeywordType.COUNTRY); countryOfOrigin = terms.get(terms.size() - 1); keywords.add(new Keyword(newCountry)); } //theoretically never happens else { DialogManager.giveDialogManager().setInErrorState(true); } } else if(countries.size() == 1) { countryOfOrigin = countries.get(0).getWord(); countries.get(0).getKeywordData().getDataReference().add(recipe.getRecipeData()); countries.get(0).getKeywordData().getDialogState().add(new RecipeAssistanceState(RecipeAssistance.RA_TELL_COUNTRY_FOUND)); countries.get(0).getKeywordData().writeFile(); } else { countryOfOrigin = countries.get(0).getWord(); countries.get(0).getKeywordData().getDataReference().add(recipe.getRecipeData()); countries.get(0).getKeywordData().writeFile(); } nextState = new RecipeLearningState(RecipeLearning.RL_ASK_FIRST_INGREDIENT); setCurrentDialogState(nextState); }
3
int popInt() { return ((Integer) pop()).intValue(); }
0
@Test public void test() { if (!MongoHelper.delete(attachment, "attachments")) { TestHelper.failed("delete failed"); } if (MongoHelper.fetch(attachment, "attachments") != null) { TestHelper.failed("attachment was not deleted"); } System.out.println("Deleted attachment id: " + attachment.getId()); TestHelper.passed(); }
2
@Override public String format(LogRecord record) { StringBuilder sb = new StringBuilder(); sb .append(dateFormat.format(record.getMillis())) .append(" [") .append(record.getLevel()) .append("] "); String msg = record.getMessage(); if (msg != null) { Object[] parameters = record.getParameters(); if (parameters != null) { msg = String.format(msg, parameters); } sb.append(msg); } Throwable thrown = record.getThrown(); if (thrown != null) { PrintWriter pw = null; try { StringWriter sw = new StringWriter(); pw = new PrintWriter(sw); thrown.printStackTrace(pw); sb .append(LINE_SEPARATOR) .append(sw.toString()); } finally { if (pw != null) { pw.close(); } } } return sb.append(LINE_SEPARATOR).toString(); }
4
public MethodInfo findMethod(String name, String typeSig) { if ((status & METHODS) == 0) loadInfo(METHODS); for (int i = 0; i < methods.length; i++) if (methods[i].getName().equals(name) && methods[i].getType().equals(typeSig)) return methods[i]; return null; }
4
@Override public byte[] getFileContent(String filename) { File file = new File("."+filename); if(!file.exists()){ return new byte[0]; }else{ try { InputStream fis = new FileInputStream(file); byte[] content = new byte[(int) file.length()]; fis.read(content); fis.close(); return content; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return new byte[0]; } }
3
public TableControlsModel(Control c){ _data = new String[9][2]; _data[0][0] = "RegDst"; _data[0][1] = c.isRegDst() ? "1" : "0"; _data[1][0] = "Branch"; _data[1][1] = c.isBranch() ? "1" : "0"; _data[2][0] = "MemRead"; _data[2][1] = c.isMemRead() ? "1" : "0"; _data[3][0] = "MemToReg"; _data[3][1] = c.isMemToReg() ? "1" : "0"; _data[4][0] = "AluOP0"; _data[4][1] = c.isAluOp0() ? "1" : "0"; _data[5][0] = "AluOP1"; _data[5][1] = c.isAluOp1() ? "1" : "0"; _data[6][0] = "MemWrite"; _data[6][1] = c.isMemWrite() ? "1" : "0"; _data[7][0] = "AluSrc"; _data[7][1] = c.isAluSrc() ? "1" : "0"; _data[8][0] = "RegWrite"; _data[8][1] = c.isRegWrite() ? "1" : "0"; }
9
public int GetUserID(String email) throws Exception { String s = "-8"; int id = -2; try { // This will load the MySQL driver, each DB has its own driver Class.forName("com.mysql.jdbc.Driver"); // Setup the connection with the DB _connect = DriverManager.getConnection(_url, _user, _password); // PreparedStatements can use variables and are more efficient String sql = "SELECT * FROM users WHERE email = ? "; _preparedStatement = _connect.prepareStatement(sql); _preparedStatement.setString(1, email); _resultSet = _preparedStatement.executeQuery(); if (_resultSet.next()) { s = _resultSet.getString("id"); id = Integer.parseInt(s); } } catch (Exception e) { throw e; } finally { close(); } return id; } // End getUserID
2
public Model getModel() { Model model = (Model) modelCache.get(id); if (model != null) return model; model = Model.getModel(modelId); if (model == null) return null; for (int colour = 0; colour < 6; colour++) if (originalModelColours[0] != 0) model.recolour(originalModelColours[colour], modifiedModelColours[colour]); modelCache.put(model, id); return model; }
4
public Command[] getAgentCommands() { ArrayList<Agent> agents = level.agents; int agentsSize = level.agents.size(); // make sure every agent has a command planned for (int i=0; i<agentsSize; i++) { planForAgent(agents.get(i)); } if(agents.size() > 1){ for(TaskDispenser td : taskDispensers){ td.handleRequests(); } // solve conflicts per TD for (TaskDispenser td : taskDispensers) { HashMap<Field, ArrayList<Object>> conflictingObjects = Utils.isConflict(td); if (!conflictingObjects.isEmpty()) { Utils.resolveConflicts(level, td, conflictingObjects); } td.shouldMakeRequests( false ); } } // at this point all agents have a command // so we can safely ask for commands Command[] cmds = new Command[agentsSize]; for (int i=0; i<agentsSize; i++) { try { cmds[i] = agents.get(i).taskQueue.peek().commandQueue.poll(); } catch (Exception e) { cmds[i] = null; } } return cmds; }
7
public void resize(int w, int h, boolean f) throws Exception { for (DisplayMode d : Display.getAvailableDisplayModes()) { if (d.getWidth() == w && d.getHeight() == h) { if (f && !d.isFullscreenCapable()) { continue; } Display.setDisplayMode(d); full = f; if (isOpen()) { Display.setFullscreen(f); } return; } } throw new Exception(String.format("No such display mode: %dx%d %s fullscreen", w, h, "with" + (f? "" : "out"))); }
7
public void printDT() { System.out.println(); System.out.println(" via"); System.out.println(" D2 | 0 1 3"); System.out.println("----+------------"); for (int i = 0; i < NetworkSimulator.NUMENTITIES; i++) { if (i == 2) { continue; } System.out.print(" " + i + "|"); for (int j = 0; j < NetworkSimulator.NUMENTITIES; j++) { if (j == 2) { continue; } if (distanceTable[i][j] < 10) { System.out.print(" "); } else if (distanceTable[i][j] < 100) { System.out.print(" "); } else { System.out.print(" "); } System.out.print(distanceTable[i][j]); } System.out.println(); } }
6
public void mousePressed(MouseEvent e){ if (e.isPopupTrigger()) doPop(e); }
1
protected int backfillGridlets() { int gridletStarted = 0; // checks the pivot first if(pivot != null && pivot.getStartTime() <= GridSim.clock()) { gridletStarted++; waitingJobs.remove(pivot); // pivots should be at the beginning anyway runningJobs.add(pivot); pivot.setStatus(Gridlet.INEXEC); super.sendInternalEvent(pivot.getActualFinishTime()-GridSim.clock(), UPT_SCHEDULE); pivot = null; //-------------- FOR DEBUGGING PURPOSES ONLY -------------- visualizer.notifyListeners(super.get_id(), ActionType.SCHEDULE_CHANGED, true); //---------------------------------------------------------- } if(jobOrder != null) { Collections.sort(waitingJobs, jobOrder); } // Start the execution of jobs that are queued Iterator<SSGridlet >iter = waitingJobs.iterator(); while (iter.hasNext()) { SSGridlet gridlet = iter.next(); // required to skip pivot if(gridlet == this.pivot) { continue; } boolean success = startGridlet(gridlet); if(success) { iter.remove(); gridletStarted++; } else { success = scheduleGridlet(gridlet); } //-------------- FOR DEBUGGING PURPOSES ONLY -------------- if(success) { visualizer.notifyListeners(super.get_id(), ActionType.ITEM_SCHEDULED, true, gridlet); } //---------------------------------------------------------- } // updates list of free resources available // (hack to be compatible with GridSim's way of maintaining availability) dynamics.resetFreePERanges(profile.checkImmediateAvailability().getAvailRanges()); return gridletStarted; }
7
private synchronized void fillUpHPOTerms(){ if(HPOTerms.size()==0) { File file = new File(hpoFilePath); Scanner scanner = null; try { scanner = new Scanner(file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Pattern p = Pattern.compile("(id:)(\\s+)(HP:)(\\d+)",Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Pattern isa = Pattern.compile("(is_a:)(\\s+)(HP:)(\\d+)",Pattern.CASE_INSENSITIVE | Pattern.DOTALL); while(scanner.hasNextLine()){ String hp= scanner.findInLine(p); if(hp!=null){ //System.out.println( hp); ArrayList<String> parents = new ArrayList<String>(); boolean reachedNext=false; while(!reachedNext){ if(scanner.hasNextLine()){ String startSentence = scanner.nextLine(); if(startSentence.equalsIgnoreCase("[Term]")){ reachedNext=true; break; } String is_a= scanner.findInLine(isa); if(is_a!=null){ //System.out.println( hp + is_a); parents.add(is_a.replace("is_a: HP:", "")); } }else { break;} } HPOTerms.put(hp.replace("id: HP:", ""), parents); } else{ if(scanner.hasNextLine())scanner.nextLine(); } } scanner.close(); } }
9
public Expr AddExpr() throws ParseException { Token tok; Expr e, er; e = MulExpr(); label_11: while (true) { switch (jj_ntk == -1 ? jj_ntk() : jj_ntk) { case 146: case 147: break; default: jj_la1[32] = jj_gen; break label_11; } switch (jj_ntk == -1 ? jj_ntk() : jj_ntk) { case 146: tok = jj_consume_token(146); break; case 147: tok = jj_consume_token(147); break; default: jj_la1[33] = jj_gen; jj_consume_token(-1); throw new ParseException(); } er = MulExpr(); e = new Expr.BinOp(tok, e, er); } return e; }
7
@SuppressWarnings("deprecation") @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(!(sender instanceof Player)) { sender.sendMessage(plugin.prefix + "You have to be a player to use this command"); return true; } Player player = (Player)sender; if(player.hasPermission("NE.mspawner") || player.isOp()) { if(command.getName().equalsIgnoreCase("MSpawner")) { if(player.getTargetBlock(null, 256).equals(Material.MOB_SPAWNER)) { CreatureSpawner spawner = (CreatureSpawner) player.getTargetBlock(null, 256); if(args.length == 0){ player.sendMessage(plugin.prefix + "Please enter a number for delay"); return true; } if(args.length == 1){ try { spawner.setDelay(Integer.parseInt(args[0])); return true; } catch (NumberFormatException e) { player.sendMessage(plugin.prefix + "That isn't a number!"); return true; } } } } } player.sendMessage(plugin.prefix + "You don't have permissions to use MSpawner"); return true; }
8
private String getPostData(final Map<String, Object> map) throws UnsupportedEncodingException { StringBuffer buff = new StringBuffer(); Iterator<String> it = map.keySet().iterator(); while (it.hasNext()) { String keyName = it.next(); Object obj = map.get(keyName); if (obj != null) { String appendStr = null; if (obj instanceof Calendar) { DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss"); appendStr = dateFormat.format(((Calendar)obj).getTime()); buff.append(keyName + "=" + URLEncoder.encode(appendStr, Constants.AW_ENCODE)); } else if (obj instanceof String[]) { String[] strs = (String[])obj; for (int i = 0; i < strs.length; i++) { buff.append(keyName + "=" + URLEncoder.encode(strs[i], Constants.AW_ENCODE)); if (i < strs.length - 1) { buff.append("&"); } } } else { appendStr = obj.toString(); buff.append(keyName + "=" + URLEncoder.encode(appendStr, Constants.AW_ENCODE)); } } if (it.hasNext()) { buff.append("&"); } } log.info("送信内容:" + buff.toString()); return buff.toString(); }
7
public void execute() { int i; if (pins[0].value && !lastClock) { for (i = 0; i != bits; i++) { if (pins[i + 2].value) { break; } } if (i < bits) { pins[i++ + 2].value = false; } i %= bits; pins[i + 2].value = true; } if (!pins[1].value) { for (i = 1; i != bits; i++) { pins[i + 2].value = false; } pins[2].value = true; } lastClock = pins[0].value; }
7
public File[] saveAs(Saveable saveable) { if (saveable == null) { return new File[0]; } String path = saveable.getPreferredSavePath(); File result = StdFileDialog.choose(saveable instanceof Component ? (Component) saveable : null, false, (String) getValue(NAME), PathUtils.getParent(path), PathUtils.getLeafName(path), mExtension); return result != null ? saveable.saveTo(result) : new File[0]; }
3
public void tick() { if (fps == -1) return; timer++; if (timer > 60 / fps) { currentFrame++; timer = 0; } if (currentFrame >= sprites.length) currentFrame = 0; }
3
public static void main(String[] args) { try{ System.out.println("Start time ms:" +System.currentTimeMillis()); if(args.length>=1){ min_support = Integer.parseInt(args[0]); System.out.println("Using Min Support of "+min_support); } Vector<String> candidates = new Vector<String>(); MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("POS"); DBCollection coll = db.getCollection("POSTX"); //BasicDBList eans = (BasicDBList) coll.distinct("LINEITEMS.EAN"); //System.out.println("Unique EANS: "+eans.size()); BasicDBList stores = (BasicDBList) coll.distinct("STORE"); System.out.println("Unique Stores: "+stores.size()); storeQueue = new Vector<String>(); for(int n=0; n<stores.size(); n++){ String store = (String)stores.get(n); System.out.println(store); DBCollection strColl = null; if(db.collectionExists("STORE"+store)){ //AnalysisQueue.addStore(store); //continue; strColl = db.getCollection("STORE"+store); strColl.drop(); } List<DBObject> txs = coll.find(new BasicDBObject("STORE", store)).toArray(); strColl = db.createCollection("STORE"+store, null); strColl.ensureIndex(new BasicDBObject("LINEITEMS.EAN",1)); strColl.insert(txs); // storeQueue.add(store); AnalysisQueue.addStore(store); } db = null; mongoClient.close(); int threadCount = 20; for(int c=0;c<threadCount; c++){ Thread th = new Thread(new AnalysisThread()); th.start(); } Thread th = new Thread(new ResultThread()); th.start(); } catch(Exception e){ e.printStackTrace(); System.exit(-1); } }
5
private void rescale(int capacityIndex) { Array<Array<KeyValueHolder<K, V>>> oldBuckets = buckets; // Change the hash capacity buckets = new Array<Array<KeyValueHolder<K, V>>>(primes[capacityIndex]); KeyValueHolder<K, V> holder; // See the old buckets for (int i = 0; i < oldBuckets.getSize(); ++i) { // See the collisions Array<KeyValueHolder<K, V>> subArray = oldBuckets.getElement(i); if (subArray != null) { for (int j = 0; j < subArray.getSize(); ++j) { holder = subArray.getElement(j); put(holder.key, holder.value); } } } }
3
public static void triangle3(String s) { char c[] = s.toCharArray(); for (int i = 0; i < c.length; i++) { System.out.println(); for (int j = 0; j < c.length; j++) { if (i < j) { System.out.print(" "); } else { System.out.print(c[j]); } } } }
3
public String callCommandGetField(PreparedStatement _sqlCommand, Connection _con) { //Benchmark time start ThreadMXBean threadmxbean = ManagementFactory.getThreadMXBean(); long startTime; long finishTime; if (_enableSqlMonitor) startTime = threadmxbean.getCurrentThreadCpuTime(); String returnVal = ""; ResultSet listData = null; try { listData = callCommandGetResultSetWithOutMonitor(_sqlCommand, _con); if (listData != null && listData.next()) { returnVal = listData.getString(1); } } catch (Exception e) { e.printStackTrace(); } finally { close(listData, null, null); } if (_enableSqlMonitor) { finishTime = threadmxbean.getCurrentThreadCpuTime(); sqlMonitor((finishTime-startTime), "callCommandGetField()"); } return returnVal; }
5
public TestInfo updateTestSettings(String userKey, TestInfo testInfo) { EnginesParameters enginesParameters = EnginesParameters.getEnginesParameters(this.users, testInfo.getNumberOfUsers()); Overrides overrides = testInfo.getOverrides(); // int engines = enginesParameters.getConsoles() + enginesParameters.getEngines(); int engines = enginesParameters.getEngines(); TestInfo ti = rpc.updateTestSettings(userKey, testInfo.getId(), testInfo.getLocation(), engines, enginesParameters.getEngineSize(), enginesParameters.getUserPerEngine(), overrides == null ? 0 : overrides.getIterations(), overrides == null ? 0 : overrides.getRampup(), overrides == null ? 0 : overrides.getDuration(), testInfo.getJmeterProperties() ); return ti; }
3
public static void main(String[] args) { int x = 0; System.out.println((x != 0) && ((10 / x) > 1)); //false }
1
public void update() { if (execute_command) { execute_command = false; movePlayer(Command.commandToDir(currentCommand)); } }
1
public static void printArray(int array_len,int[] array) { for (int i = 0; i < array_len; i++) { if (i % 100 == 0) System.out.println(); System.out.print(array[i] + " "); } System.out.println(); }
2
@Override public int hashCode() { int result; long temp; result = saleId; result = 31 * result + itemId; result = 31 * result + quantityPurchased; result = 31 * result + (itemCostPrice != null ? itemCostPrice.hashCode() : 0); temp = itemUnitPrice != +0.0d ? Double.doubleToLongBits(itemUnitPrice) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + discountPercent; return result; }
2
private void captureAudio() { try { // Get everything set up for // capture audioFormat = getAudioFormat(); DataLine.Info dataLineInfo = new DataLine.Info( TargetDataLine.class, audioFormat); targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo); targetDataLine.open(audioFormat); targetDataLine.start(); // Create a thread to capture the // microphone data and start it // running. It will run until // the Stop button is clicked. Thread captureThread = new Thread(new CaptureThread()); captureThread.start(); } catch (Exception e) { System.out.println(e); System.exit(0); }// end catch }// end captureAudio method
1
private void print_array(int[] a) { if ( 0 == a.length ) return ; System.out.print("["); System.out.print(a[0]); for (int i=1; i<a.length; i++) System.out.print(", " + a[i]); System.out.println("]"); }
2
public void serializza() { try{ JoinList file = new JoinList(); File f = new File("plugins/" + name + "/giocatori.dat"); if(!f.exists()) { f.createNewFile(); System.out.println("File creato"); } FileOutputStream fout = new FileOutputStream("plugins/" + name + "/giocatori.dat"); ObjectOutputStream output = new ObjectOutputStream(fout); output.writeObject(file); output.flush(); output.close(); // System.out.println("Salvato con successo"); } catch (IOException e) { e.printStackTrace(); System.out.println("Impossibile salvare");} }
2
private void gererCollision(ControlleurObjets controlleur) { for (int i = 0; i < controlleur.objets.size(); i++) { ObjetJeu temp = controlleur.objets.get(i); if (temp.getId() == IdObjet.TirNormal) { if (contact().intersects(temp.contact())) { controlleur.enleverObjet(temp); controlleur.enleverObjet(this); } } else if (temp.id == IdObjet.Joueur){ if (getX() + 50f >= temp.getX() && getX() - 50f <= temp.getX() && ready == 0) { controlleur.ajouterObjet(new TirEnnemi(getX() + 20f, getY() + 50f, IdObjet.TirEnnemi)); ready = CADENCE; } } } }
7
public void paintComponent(Graphics g){ super.paintComponent(g); // paints background // OK, paint it ourselves // we need the font... if(fontModel == null){ return; } if(offImg == null){ offImg = createImage(initialWid, initialHgt); Graphics2D offG = (Graphics2D)offImg.getGraphics(); offG.setColor(Color.lightGray); for(int i=8;i<initialWid;i+=8) offG.drawLine(i,0,i,initialHgt); for(int i=8;i<initialHgt;i+=8) offG.drawLine(0,i,initialWid,i); // now draw each char individually so that its CROPPED int charWid =8*fontModel.tilesWide; int charHgt = 8*fontModel.tilesHigh; Image charImg = createImage(charWid,charHgt ); Graphics2D charG = (Graphics2D)charImg.getGraphics(); FontRenderContext frc = charG.getFontRenderContext(); if(fontModel.isAntiAliasing){ charG.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // KEY_DITHERING has no effect // KEY_INTERPOLATION has no effect // KEY_RENDERING has no effect // KEY_TEXT_ANTIALIASING has no effect // KEY_FRACTIONALMETRICS has no effect // KEY_COLOR_RENDERING has no effect } char theChars[] = fontModel.determineText(); for(int i=0;i<theChars.length;i++){ charG.setColor(Color.BLACK); charG.fillRect(0,0, charWid,charHgt); charG.setColor(fontModel.getColor()); TextLayout layout = new TextLayout(""+theChars[i], fontModel.theFont, frc); layout.draw(charG, fontModel.leftSpacing, charHgt-fontModel.bottomSpacing); int semiX = i % 16; int semiY = i / 16; offG.drawImage(charImg,semiX*charWid,semiY*charHgt,null); } } if(offImg != null) { Graphics2D g2d = (Graphics2D) g; AffineTransform tx = AffineTransform.getScaleInstance(scaleAmount,scaleAmount); g2d.drawImage(offImg, tx, null); } }
7
protected void fireServerStopEvent(ServerStopEvent evt) { if (serverStopListenerList != null) { Object[] listeners = serverStopListenerList.getListenerList(); for (int i=0; i<listeners.length; i+=2) { if (listeners[i]==ServerStopListener.class) { ((ServerStopListener)listeners[i+1]).OnServerStopEvent(evt); } } } }
3
private void addActionListeners() { button.addActionListener(e -> { close(); firePropertyChange(DialogWindowController.CANCEL, 0, 1); }); }
0
private void run(){ isRunning = true; int frames = 0; long frameCounter = 0; final double frameTime = 1.0 / frameCap; long lastTime = Time.getTime(); double unprocessedTime = 0; while(isRunning){ boolean render = false; long startTime = Time.getTime(); long passedTime = startTime - lastTime; lastTime = startTime; unprocessedTime += passedTime / (double)Time.second; frameCounter += passedTime; while(unprocessedTime > frameTime){ render = true; unprocessedTime -= frameTime; if(Window.isCloseRequested()) stop(); Time.setDelta(frameTime); Input.update(); game.input(); game.update(); if(frameCounter >= Time.second){ System.out.println(frames); frames = 0; frameCounter = 0; } } if(render){ render(); frames++; }else{ try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } cleanUp(); }
6
public String getResultExec(String exec) { beforeExecute(this); String result = ""; boolean cekWindowsOSName = System.getProperty("os.name").contains("Windows"); if(cekWindowsOSName) { Process p; BufferedReader input = null; try { p = Runtime.getRuntime().exec(exec); input = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while((line = input.readLine()) != null) { result += line; } } catch(IOException ex) { ex.printStackTrace(); } finally { if(input != null) { try { input.close(); } catch(IOException ex) { ex.printStackTrace(); } } } } else { javax.swing.JOptionPane.showMessageDialog(null, "Maaf... Sistem Operasi yang anda gunakan" + " belum didukung oleh Parser Engine", "", 0); } afterExecute(this); return result; }
5
private static int getAdjustedThreshold(int previousThreshold, Image img, ChannelType c) { int amountOfHigher = 0; int amountOfLower = 0; double sumOfHigher = 0; double sumOfLower = 0; for (int x = 0; x < img.getWidth(); x++) { for (int y = 0; y < img.getHeight(); y++) { double aPixel = img.getPixel(x, y, c); if (aPixel >= previousThreshold) { amountOfHigher++; sumOfHigher += (int) aPixel; } else { amountOfLower++; sumOfLower += (int) aPixel; } } } double m1 = sumOfHigher / amountOfHigher; double m2 = sumOfLower / amountOfLower; return (int) ((m1 + m2) / 2); }
3
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (args.length == 0) { if (player == null) { sender.sendMessage(ChatColor.RED+"This command can only be run by a player"); return true; } player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 1200, 2)); sender.sendMessage(ChatColor.GOLD + "* " + ChatColor.WHITE + "You have been given Invisibility for " + ChatColor.GREEN + "1" + ChatColor.WHITE + " minute"); return true; } else if (args.length == 1) { Player target = Bukkit.getPlayer(args[0]); if (target == null) { sender.sendMessage(ChatColor.RED + args[0] + " is not online"); return true; } target.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 1200, 2)); sender.sendMessage(ChatColor.GREEN + "" + target.getDisplayName() + ChatColor.WHITE + " has been given Invisibility for " + ChatColor.GREEN + "1" + ChatColor.WHITE + " minute"); target.sendMessage(ChatColor.GOLD + "* " + ChatColor.WHITE + "You have been given Invisibility for " + ChatColor.GREEN + "1" + ChatColor.WHITE + " minute"); return true; } else if (args.length == 2 && player == null || player.hasPermission("simpleextras.invisible.other")) { Player target = Bukkit.getPlayer(args[0]); // CHECK IF TARGET EXISTS if (target == null) { sender.sendMessage(ChatColor.RED + args[0] + " is not online"); return true; } String min = args[1]; int mintemp = Integer.parseInt( min ); int mins = 1200 * mintemp; target.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, mins, 2)); sender.sendMessage(ChatColor.GREEN + "" + target.getDisplayName() + ChatColor.WHITE + " has been given Invisibility for " + ChatColor.GREEN + min + ChatColor.WHITE + " minutes"); target.sendMessage(ChatColor.GOLD + "* " + ChatColor.WHITE + "You have been given Invisibility for " + ChatColor.GREEN + min + ChatColor.WHITE + " minutes"); return true; } return true; }
9
@Override public void learn(){ nb_neurons = colNumber*rowNumber; int examples = 0; while (examples < epochs && !Options.getOptions().getStopped()) { //We verify the pause checkPause(); //We print the state printState(new Object[]{examples, epochs, Options.getOptions().getElasticity(), Options.getOptions().getEpsilon()}); examples++; //We pick up a piece of data int index_data = (int) (Math.random()*Data.getData().size()); //We get the neuron which is the nearest to this data Neuron current_best = getNearest(index_data); //We compute the distance between this neuron and the data double distance_best = current_best.distance(Data.getData().get(index_data)); //And we get the number of the column in the topological distances' array int num_best = current_best.getRow() * colNumber + current_best.getCol(); //We update the weights of all neurons for(int i = 0 ; i < neurons.size() ; i++) { for(int k=0;k<neurons.get(i).size();k++) { //We get the current neuron... Neuron target = neurons.get(i).get(k); //... and we get its topological distance to the nearest int num_target_topo = target.getRow() * colNumber + target.getCol(); //We compute the topological distance between the two neurons double distance_topo = distancesTopo[num_target_topo][num_best]/(colNumber + rowNumber); //We compute the neighborhood double neighb = Math.exp(-1* Math.pow(distance_topo, 2)/Math.pow(Options.getOptions().getElasticity(), 2)/Math.pow(distance_best, 2)); //We update the weight of the target for(int l = 0; l < target.getPoids().size() ; l++) { //We get the current weight double current_weight = target.getPoids().get(l); //We get the weight of the data double data_weight = Data.getData().get(index_data).getPoids().get(l); //We compute the variations double delta = Math.abs(current_weight - data_weight) * neighb * (data_weight - current_weight); //We change the value of the weight current_weight += Options.getOptions().getEpsilon()*delta; //We set the new weight target.getPoids().set(l, new Float(current_weight)); } } } //We wait a little because it's too fast in other cases sleep(); world.change(); } world.change(); }
5
@Override public float millisecondsPlayed() { // get number of samples played in current buffer float offset = (float)AL10.alGetSourcei( ALSource.get( 0 ), AL11.AL_BYTE_OFFSET ); float bytesPerFrame = 1f; switch( ALformat ) { case AL10.AL_FORMAT_MONO8 : bytesPerFrame = 1f; break; case AL10.AL_FORMAT_MONO16 : bytesPerFrame = 2f; break; case AL10.AL_FORMAT_STEREO8 : bytesPerFrame = 2f; break; case AL10.AL_FORMAT_STEREO16 : bytesPerFrame = 4f; break; default : break; } offset = ( ( (float) offset / bytesPerFrame ) / (float) sampleRate ) * 1000; // add the milliseconds from stream-buffers that played previously if( channelType == SoundSystemConfig.TYPE_STREAMING ) offset += millisPreviouslyPlayed; // Return millis played: return( offset ); }
5
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head = new ListNode(-1); ListNode p = head; while (l1 != null && l2 != null) { if (l1.val > l2.val) { p.next = l2; l2 = l2.next; } else { p.next = l1; l1 = l1.next; } p = p.next; } if (l1 != null) { p.next = l1; } if (l2 != null) { p.next = l2; } return head.next; }
5
public static Cons sysTree(Stella_Object tree, StandardObject typespec, Object [] MV_returnarray) { if (Stella_Object.safePrimaryType(tree) == Stella.SGT_STELLA_CONS) { { Cons tree000 = ((Cons)(tree)); { GeneralizedSymbol testValue000 = ((GeneralizedSymbol)(tree000.value)); if (testValue000 == Stella.SYM_STELLA_VOID_SYS) { if (StandardObject.voidP(typespec)) { { Cons _return_temp = tree000; MV_returnarray[0] = typespec; return (_return_temp); } } } else if (testValue000 == Stella.SYM_STELLA_TYPED_SYS) { if (tree000.rest.rest.value == typespec) { { Cons _return_temp = tree000; MV_returnarray[0] = typespec; return (_return_temp); } } } else if (testValue000 == Stella.SYM_STELLA_VRLET) { { Cons _return_temp = tree000; MV_returnarray[0] = typespec; return (_return_temp); } } else { } } } } else { } if (StandardObject.voidP(typespec)) { { Cons _return_temp = Cons.list$(Cons.cons(Stella.SYM_STELLA_VOID_SYS, Cons.cons(tree, Cons.cons(Stella.NIL, Stella.NIL)))); MV_returnarray[0] = Stella.SGT_STELLA_VOID; return (_return_temp); } } else { { Cons _return_temp = Cons.list$(Cons.cons(Stella.SYM_STELLA_TYPED_SYS, Cons.cons(tree, Cons.cons(Cons.cons(typespec, Stella.NIL), Stella.NIL)))); MV_returnarray[0] = typespec; return (_return_temp); } } }
7
@Override public void mouseClicked(MouseEvent e) { if (!pausa && !perdio) { // si el juego no ha empezado avion.setVelY(10); jump.play(); inicio = true; } if (perdio) { loseSound.stop(); restart(); } }
3