text
stringlengths
14
410k
label
int32
0
9
public void disconnected(Connection c) { Player buff = null; /* buscamos que el player se elimine de la lista de players del servidor */ for( Player p : GeoConflictServer.playerList ){ /* si no esta conectado sacamos una referencia a el */ if( !p.getConnection().isConnected() ){ buff = p; break; } } /* si la referencia no es nula */ if( buff != null ){ /* se pone en estado DEAD */ buff.setAlive(false); /* si es que esta en alguna sala */ if( buff.getRoom() != null ){ List<Room> rooms = new ArrayList<Room>(); /* buscamos cualquier sala que tenga su nombre */ for(Room r : GeoConflictServer.roomList){ if( r.getRoomName().equals(buff.getRoom().getRoomName() ) ){ rooms.add(r); } } /* y las eliminamos del servidor */ for(Room r : rooms){ GeoConflictServer.roomList.remove(r); } /* se elimina de la sala en que este */ buff.getRoom().removePlayer(buff); } GeoConflictServer.playerList.remove(buff); logger.info("Cliente " + buff.getUser().getUsername() + " desconectado."); } // Para debug logger.debug("Lista de usuarios: "); for( Player p : GeoConflictServer.playerList ){ logger.debug( p.getUser().getUsername() ); } logger.debug("Fin lista"); }
8
@Override public int castingQuality(MOB mob, Physical target) { if(mob!=null) { if(mob.isInCombat()&&(mob.rangeToTarget()>0)) return Ability.QUALITY_INDIFFERENT; if(!Druid_ShapeShift.isShapeShifted(mob)) return Ability.QUALITY_INDIFFERENT; if(mob.charStats().getBodyPart(Race.BODY_LEG)<=0) return Ability.QUALITY_INDIFFERENT; if(target instanceof MOB) { if(CMLib.flags().isStanding((MOB)target)) return Ability.QUALITY_INDIFFERENT; } } return super.castingQuality(mob,target); }
7
public CurrentQuest(UQuest plugin, LoadedQuest theQuest, int level) { this.name = theQuest.getName(); this.startInfo = theQuest.getStartInfo(); this.finishInfo = theQuest.getFinishInfo(); for(Reward reward : theQuest.getRewards()){ this.rewards.add(new Reward(reward)); } for(Objective objective : theQuest.getObjectives()){ this.objectives.add(new Objective(objective)); } this.changeQuestLevel(level); }
2
public void addLink(GraphNode destiny, int weight) { //adds the link with the param destiny and its weight or price. if (actual_links == -1) {//if there are not links. links.append(new Link(this, destiny, weight));//creates new link and adds it to the list of links of this node. actual_links++; } else { boolean pos = existLink(destiny);//if param exists in the list. if (pos == false) { links.append(new Link(this, destiny, weight));//creates and adds link to list. actual_links++; } } }
2
public int GetTime() { return time; }
0
public void compareRoomInventoryItems() { int ArrayListID = 0; if(player.getInventorySize() > 0) { for (Iterator it = rooms.get(player.getCurrentRoomID()).getItems().iterator(); it.hasNext();) { Item roomItem = (Item) it.next(); for (Iterator inventoryIterator = player.getInventory().iterator(); inventoryIterator.hasNext();) { Item inventoryItem = (Item) inventoryIterator.next(); if(inventoryItem.getItemName().equals(roomItem.getItemName())) { it.remove(); //If room item compares with inventory item remove it } } ArrayListID++; } } }
4
private Student statsLE(Student s) { double creditsSci = 0.0; double creditsUpper = 0.0; double credits_NonCSEMath = 0.0; ArrayList<Course> courses = s.getCourses(); for (Course course : courses) { String grade = course.getGrade(); if (YORK_GRADES.containsKey(grade)) { double gradeValue = YORK_GRADES.get(grade); if (gradeValue >= YORK_GRADES.get("D") || gradeValue == YORK_GRADES.get("P")) { String faculty = course.getFaculty(); String department = course.getDepartment(); int courseCode = course.getCode(); double courseCredits = course.getCredits(); // Get 3xxx/4xxx credits if (courseCode >= 3000) { creditsUpper += courseCredits; } // Get non-CSE/MATH credits if (!department.equals("MATH") && !department.equals("CSE")) { credits_NonCSEMath += courseCredits; } /* * Get science credits * * TODO: Math courses used to fall under AS (Art's & * Science) */ if (faculty.equals("SC") || faculty.equals("LE")) { creditsSci += courseCredits; } } } } s.setCreditsSci(creditsSci); s.setCreditsUpper(creditsUpper); s.setCredits_NonCSEMath(credits_NonCSEMath); return s; }
9
@Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (commandLabel.equalsIgnoreCase("mcrp")) { if (args.length == 0) { commands.get(2).run(sender, args); return true; } if (args.length >= 1) { String command = args[0]; // Shift args down String[] newArgs = new String[args.length-1]; for (int i = 1; i < args.length; i++) { newArgs[i-1] = args[i]; } for (SubCommand subCmd : commands) { if (subCmd.getCommand().equalsIgnoreCase(command)) { subCmd.run(sender, newArgs); return true; } } // Command not found, send help commands.get(0).run(sender, null); return true; } else { // Send help commands.get(0).run(sender, null); return true; } } if (commandLabel.equalsIgnoreCase("skillinfo")) { commands.get(5).run(sender, args); return true; } if (commandLabel.equalsIgnoreCase("skills")) { commands.get(6).run(sender, args); return true; } if (commandLabel.equalsIgnoreCase("binds")) { commands.get(1).run(sender, args); return true; } return false; }
9
private String getScoreList(int position) throws Finished { StatisticsInterface stats = d.getUIData().getStats(); int c = stats.getCurrentRoundNo(); if (position + 1 > c) { throw new Finished(); } else if (c > MAX_SCORE_LINES) { c = c - MAX_SCORE_LINES + position + 1; } else { c = position + 1; } StringBuilder sb = new StringBuilder(String.format("%3d", c)); if (c >= stats.getStartingRoundNo()) { String points; String forecast; for (PlayerInterface player : d.getUIData().getPlayers()) { if (c == stats.getCurrentRoundNo()) { points = ""; } else { points = String.valueOf(stats.getPointsIn(player, c)); } try { forecast = String.valueOf(stats.getForecastIn(player, c)); } catch (IllegalArgumentException e) { forecast = "-"; } sb.append(String.format("| %-5s | %2s ", points, forecast)); } sb.append('|'); return sb.toString(); } else { sb.append(" No data for this round available!"); return sb.toString(); } }
6
public CodeEditor(){ JMenu jMenu1 = new JMenu("File"); jMenu1.add(jmiOpen); jMenu1.add(jmiSave); jMenu1.add(jmiClear); jMenu1.addSeparator(); jMenu1.add(jmiExit); JMenu jMenu2 = new JMenu("Edit"); jMenu2.add(jmiBackground); jMenu2.add(jmiForeground); jMenu2.add(jmiCaret); JMenuBar jMenuBar1 = new JMenuBar(); jMenuBar1.add(jMenu1); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); jmiOpen.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ open(); } }); jmiSave.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ save(); } }); jmiClear.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ jta.setText(null); } }); jmiExit.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ System.exit(1); } }); jmiForeground.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ Color selectedColor = JColorChooser.showDialog(null, "Choose Foreground Color", jta.getForeground()); if(selectedColor != null) jta.setForeground(selectedColor); } }); jmiBackground.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ Color selectedColor = JColorChooser.showDialog(null, "Choose Background Color", jta.getBackground()); if(selectedColor != null) jta.setBackground(selectedColor); } }); jmiCaret.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ Color selectedColor = JColorChooser.showDialog(null, "Choose Caret Color", jta.getCaretColor()); if(selectedColor != null) jta.setCaretColor(selectedColor); } }); Font f = new Font("Courier", Font.PLAIN, 12); jta.setFont(f); jta.setTabSize(4); add(jlblStatus, BorderLayout.SOUTH); add(new JScrollPane(jta), BorderLayout.CENTER); }
3
public JTextField getjTextFieldNum() { return jTextFieldNum; }
0
public void paintSillasArriba(Graphics g) { //Color c = new Color(6, 100, 6, 100); //g.setColor(c); //g.fillRect(getPosX() - 25, getPosY() - 30, getAncho() + 50, getAlto() + 40); if (tipo == 2) { paintMonitoArriba(g); } else if (tipo == 1 || tipo == 3 || tipo == 4 || tipo == 5 || tipo == 7) { for (int x = 0; x < sillas.size() - 1; x++) { Silla aux = (Silla) sillas.get(x); aux.paint(g); } paintMonitoIzqDer(g); paintMonitoArriba(g); } else if (tipo == 6) { for (int x = 0; x < sillas.size(); x++) { Silla aux = (Silla) sillas.get(x); aux.paint(g); } paintMonitoIzqDer(g); } }
9
@Override public void serialize(Buffer buf) { buf.writeInt(mapId); buf.writeUShort(npcsIdsWithQuest.length); for (int entry : npcsIdsWithQuest) { buf.writeInt(entry); } buf.writeUShort(questFlags.length); for (GameRolePlayNpcQuestFlag entry : questFlags) { entry.serialize(buf); } buf.writeUShort(npcsIdsWithoutQuest.length); for (int entry : npcsIdsWithoutQuest) { buf.writeInt(entry); } }
3
public List<Entry> searchEntries(String searchItem, List<Entry> journal) { List<Entry> includedEntries = new ArrayList<Entry>(); for (Entry entrie : journal) { if (searchItem.matches("\\d{4}-\\d{1,2}-\\d{1,2}")) { if (searchItem.equals(entrie.getDate().stringDate())) { includedEntries.add(entrie); } } else { for (Scripture entryScriptures : entrie.getScriptures()) { String compareScripture = entryScriptures.getBookName().getBookName() + " " + entryScriptures.getChapter(); if (searchItem.matches("(?i)" + compareScripture)) { includedEntries.add(entrie); break; } if (searchItem.matches("(?i)" + entryScriptures.getBookName().getBookName())) { includedEntries.add(entrie); break; } } for (String compareTopic : entrie.getTopics()) { if (searchItem.matches("(?i)" + compareTopic)) { includedEntries.add(entrie); break; } } } } return includedEntries; }
8
public MenuConsulter() { initComponents(); if (MainProjet.lesOffres.size() != 0){ OffreStage OS = MainProjet.lesOffres.get(0); jTextNom.setText(OS.getEntreprise().getNom()); jTextVilleStage.setText(OS.getEntreprise().getAdresseVilleEntreprise()); jTextMail.setText(OS.getEntreprise().getMailEntreprise()); jTextDomaine.setText(OS.getDomaineOffre()); jTextLibelle.setText(OS.getLibelléOffre()); jTextDateD.setText(OS.getDateDébutOffre()); jTextDateF.setText(OS.getDuréeOffre()); jTextDescriptif.setText(OS.getDesciptifOffre()); } }
1
* integer. */ public static float floor_f(final float a) { // Derived from StrictMath.floor(double): // Inline call to Math.getExponent(a) to // compute only once Float.floatToRawIntBits(a) final int doppel = Float.floatToRawIntBits(a); final int exponent = ((doppel & FloatConsts.EXP_BIT_MASK) >> (FloatConsts.SIGNIFICAND_WIDTH - 1)) - FloatConsts.EXP_BIAS; if (exponent < 0) { /* * Absolute value of argument is less than 1. * floorOrceil(-0.0) => -0.0 * floorOrceil(+0.0) => +0.0 */ return ((a == 0) ? a : ( (a < 0f) ? -1f : 0f) ); } if (CHECK_OVERFLOW && (exponent >= 23)) { // 52 for double /* * Infinity, NaN, or a value so large it must be integral. */ return a; } // Else the argument is either an integral value already XOR it // has to be rounded to one. assert exponent >= 0 && exponent <= 22; // 51 for double final int intpart = doppel & (~(FloatConsts.SIGNIF_BIT_MASK >> exponent)); if (intpart == doppel) { return a; // integral value (including 0) } // 0 handled above as an integer // sign: 1 for negative, 0 for positive numbers // add : -1 for negative and 0 for positive numbers return Float.intBitsToFloat(intpart) + (intpart >> 31); }
7
protected Module addAnnotation(String name, Map env) throws SignatureException { if (modName.op == ModuleName.ANNOTATE) { return (Module)this.clone(); } Module result = new Module(type, modName.addAnnotation(name)); // clone module parts result.protectImportList = (ArrayList)(protectImportList.clone()); result.paraModules = (ArrayList)(paraModules.clone()); result.paraNames = (ArrayList)(paraNames.clone()); result.levels = this.levels; // sorts for (int i=0; i<sorts.size(); i++) { Sort sort = (Sort)sorts.elementAt(i); sort = sort.addAnnotation(name, env); result.addSort(sort); } // subsorts result.addSubsorts(subsorts.addAnnotation(name, env)); // variable for (int i=0; i<vars.size(); i++) { Variable var = (Variable)vars.elementAt(i); var = var.addAnnotation(name, env); result.addVariable(var); } //operations for (int i=0; i<operations.size(); i++) { Operation op = (Operation)operations.elementAt(i); op = op.addAnnotation(name, env); result.addOperation(op); } // import equations Iterator itor = equations.iterator(); while (itor.hasNext()){ Equation eq = (Equation)itor.next(); eq = eq.addAnnotation(name, result, env); if (!result.equations.contains(eq)) result.addEquation(eq); } // import general equations itor = generalEquations.iterator(); while (itor.hasNext()){ Equation eq = (Equation)itor.next(); eq = eq.addAnnotation(name, result, env); if (!result.generalEquations.contains(eq)) result.generalEquations.add(eq); } if (bindings != null) { result.bindings = (Hashtable)this.bindings.clone(); } return result; }
9
public static void main(String[] args) { ArrayToolBox tool = new ArrayToolBox(); int[] A = {1,4,72,65,23,17,57,94,54,10,100,3,22,1001,34,8}; boolean flag = tool.search(A,3,0); boolean flag2 = tool.searchRecurse(A,1001,0); if(flag) System.out.println(3+ " was found!"); else System.out.println(3+" was not found!"); if(flag2) System.out.println(1001+ " was found!"); else System.out.println(1001+" was not found!"); boolean flag3 = tool.searchRecurse(A,6,0); if(flag3) System.out.println(6+ " was found!"); else System.out.println(6+" was not found!"); }
3
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (hashCode() == o.hashCode()) return true; InhabitedPlanet that = (InhabitedPlanet) o; if (population != that.population) return false; if (spacePorts != null ? !spacePorts.equals(that.spacePorts) : that.spacePorts != null) return false; return true; }
7
private ScriptRunner(CommandLineWrapper pCommandLineWrapper) { mCommandLineWrapper = pCommandLineWrapper; String lSourceLocation = mCommandLineWrapper.getOption(CommandLineOption.RUN); //Validate source location is not null if(XFUtil.isNull(lSourceLocation)){ throw new ExFatalError("-" + CommandLineOption.RUN.getArgString() + " argument must be specified"); } File lSourceFile = new File(lSourceLocation); if(!lSourceFile.exists()){ throw new ExFatalError("Failed to locate source file at " + lSourceLocation); } if(lSourceFile.isDirectory()){ mIsBaseDirectoryTemp = false; mBaseDirectory = lSourceFile; } else { mIsBaseDirectoryTemp = true; mBaseDirectory = Files.createTempDir(); try { Logger.logInfo("Extracting archive " + lSourceLocation); int lFileCount = ArchiveUtil.extractZipToFolder(lSourceFile, mBaseDirectory); Logger.logInfo("Extracted " + lFileCount + " files"); } catch (ZipException e) { throw new ExInternal("Zip error extracting zip to " + mBaseDirectory.getAbsolutePath(), e); } catch (IOException e) { throw new ExInternal("IO error extracting zip to " + mBaseDirectory.getAbsolutePath(), e); } } Logger.logInfo("Base directory is " + mBaseDirectory.getAbsolutePath()); }
5
public String toString() { if (m_weights == null) { return "SPegasos: No model built yet.\n"; } StringBuffer buff = new StringBuffer(); buff.append("Loss function: "); if (m_loss == HINGE) { buff.append("Hinge loss (SVM)\n\n"); } else { buff.append("Log loss (logistic regression)\n\n"); } int printed = 0; for (int i = 0 ; i < m_weights.length - 1; i++) { if (i != m_data.classIndex()) { if (printed > 0) { buff.append(" + "); } else { buff.append(" "); } buff.append(Utils.doubleToString(m_weights[i], 12, 4) + " " + ((m_normalize != null) ? "(normalized) " : "") + m_data.attribute(i).name() + "\n"); printed++; } } if (m_weights[m_weights.length - 1] > 0) { buff.append(" + " + Utils.doubleToString(m_weights[m_weights.length - 1], 12, 4)); } else { buff.append(" - " + Utils.doubleToString(-m_weights[m_weights.length - 1], 12, 4)); } return buff.toString(); }
7
public static boolean entreDate(Calendar ajdh, Calendar dateDebut, Calendar dateFin) { return ajdh.equals(dateDebut) || ajdh.equals(dateFin) || (ajdh.after(dateDebut) && ajdh.before(dateFin)); }
3
public void receive(){ boolean tcpComplete = false; ArrayList<byte[]> fileParts = new ArrayList<byte[]>(); byte responseBuffer[]; DatagramPacket responsePacket; Packet responsePacketData; int currentSequenceNumber = 1; try { if(logFileName.equals("stdout")){ this.logger = new PrintWriter(System.out); } else{ this.logger = new PrintWriter(new BufferedWriter(new FileWriter(this.logFileName, true))); } while(!tcpComplete){ packetSocket.receive(bufferPacket); logPacket(bufferPacket, false); if (Packet.getPurpose(bufferPacket.getData()[12]) == "FIN"){ tcpComplete = true; } //Structure needs refactoring else if (Packet.getSequenceNumber(bufferPacket.getData()) != currentSequenceNumber){//wrong packet sequence number //send ACK responsePacketData = new Packet(listenPort, remotePort, 0, currentSequenceNumber, "ACK", null); responseBuffer = responsePacketData.getPacketLoad(); responsePacket = new DatagramPacket(responseBuffer, responseBuffer.length, remoteIP, remotePort); packetSocket.send(responsePacket); logPacket(responsePacket, true); } else if (Packet.isCorrupt(bufferPacket.getData())){//is corrupt data packet //send CORR response responsePacketData = new Packet(listenPort, remotePort, 0, 0, "CORR", null); responseBuffer = responsePacketData.getPacketLoad(); responsePacket = new DatagramPacket(responseBuffer, responseBuffer.length, remoteIP, remotePort); packetSocket.send(responsePacket); logPacket(responsePacket, true); } else{//Packet is not corrupt and is correct one fileParts.add(bufferPacket.getData()); currentSequenceNumber = Packet.getACKNumber(bufferPacket.getData()); //send ACK response responsePacketData = new Packet(listenPort, remotePort, 0, currentSequenceNumber, "ACK", null); responseBuffer = responsePacketData.getPacketLoad(); responsePacket = new DatagramPacket(responseBuffer, responseBuffer.length, remoteIP, remotePort); packetSocket.send(responsePacket); logPacket(responsePacket, true); } //flush buffer and packet this.buffer = new byte[576]; this.bufferPacket = new DatagramPacket(buffer, buffer.length); } } catch (IOException e) { System.out.println("Error has occurred with packet receiving."); } catch (NoSuchAlgorithmException e) { System.out.println("Error has occurred with checksum calculations."); } compileFile(fileParts); if(!logFileName.equals("stdout")){ logger.close(); } packetSocket.close(); System.out.println(" Delivery completed successfully"); }
8
public static void main(String[] args) throws Exception { FileReader fr = new FileReader("src\\ioTest\\FileReader1.java"); BufferedReader br = new BufferedReader(fr); String str; while(null != (str = br.readLine())) { System.out.println(str); } br.close(); }
1
private int findNombreSousClasse(Model m, String c) { for(Generalization g : m.getGeneralization()){ if(g.getIdentifier().equals(c)){ for(String sousclasse : g.getArrayIdent()){ return findNombreSousClasse(m, sousclasse) + 1; } } } return 1; }
3
static boolean buildTree() { double min1, min2; int i, j, minat1, minat2; HuffmanNode[] work = new HuffmanNode[256]; HuffmanNode tmp = new HuffmanNode(); for(i = 0;i < 256;i++) { work[i] = myWork[i]; work[i].val = (char) i; work[i].freq = freq[i]; work[i].zero = null; work[i].one = null; huffLookup[i].len = 0; } for(i = 0;i < 255;i++) { minat1 = -1; minat2 = -1; min1 = 1E30; min2 = 1E30; for(j = 0;j < 256;j++) { if(work[j] == null) continue; if(work[j].freq < min1) { minat2 = minat1; min2 = min1; minat1 = j; min1 = work[j].freq; } else if(work[j].freq < min2) { minat2 = j; min2 = work[j].freq; } } if(minat1 < 0) { System.out.println("Huffman init error: minat1: " + minat1); return false; } if(minat2 < 0) { System.out.println("Huffman init error: minat2: " + minat2); return false; } tmp = myTmp[i]; tmp.zero = work[minat2]; tmp.one = work[minat1]; tmp.freq = work[minat2].freq + work[minat1].freq; tmp.val = 0xFF; work[minat1] = tmp; work[minat2] = null; } huffTree = tmp; return findTab(huffTree, 0, 0); }
8
public int maxSubArray(int[] A) { if(A.length == 0) return 0; int max = A[0]; int cur = A[0]; for(int i = 1; i< A.length;i++){ cur = Math.max(cur + A[i],A[i]); // 如果 cur + A[i] < A[i]的时候,表示cur 为负数,负数不可能是最大值的前缀。 max = Math.max(cur,max); } return max; }
2
public CloseView() { setTitle("Algorithme Close"); setLocation(150, 250); setSize(1000, 290); setDefaultCloseOperation(EXIT_ON_CLOSE); //Création des éléments pour importer un fichier tfParcourir = new JTextField(20); btParcourir = new JButton("Parcourir"); filePanel = new JPanel(); { filePanel.add(lbFile); filePanel.add(tfParcourir); filePanel.add(btParcourir); } //Création des éléments pour choisir le support minimal tfSupport = new JTextField(5); tfConfidence = new JTextField(5); supportPanel = new JPanel(); { supportPanel.add(lbSupport); supportPanel.add(tfSupport); supportPanel.add(lbConfidence); supportPanel.add(tfConfidence); } //Création des éléments pour exécuter l'algorithme btExecuter = new JButton("Exécuter l'algorithme"); btExecuter.setPreferredSize(new Dimension(250, 40)); execPanel = new JPanel(); { execPanel.add(btExecuter); } center = new JPanel(new GridLayout(3, 1)); { center.add(filePanel); center.add(supportPanel); center.add(execPanel); } textArea = new JTextArea(); areaPanel = new JPanel(new BorderLayout()); { scrollPane = new JScrollPane(textArea); areaPanel.add(scrollPane); } bottom = new JPanel(); { bottom.setLayout(new BoxLayout(bottom, BoxLayout.PAGE_AXIS)); bottom.add(new JLabel("Règles :")); bottom.add(areaPanel); } spPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, center, bottom); btParcourir.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { chooser = new JFileChooser(); chooser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (chooser.getSelectedFile() != null) { if (!(chooser.getSelectedFile().getName().matches("\\S+.txt"))) { JOptionPane.showMessageDialog(container, "Type de fichier " + "incorrect : txt necessaire"); } else { fileSelected = chooser.getSelectedFile(); tfParcourir.setText(fileSelected.getName()); } } } }); chooser.showOpenDialog(container); } }); btExecuter.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if ((tfParcourir.getText()).trim().equals("")) { JOptionPane.showMessageDialog(container, "Erreur : Nom de fichier vide"); } else { if ((tfSupport.getText()).trim().equals("") || Float.valueOf(tfSupport.getText()) > 1.0 || Float.valueOf(tfSupport.getText()) < 0.0) { JOptionPane.showMessageDialog(container, "Valeur de support incorrecte : " + " elle doit être entre 0.0 et 1.0"); } else { parser = new CloseParser(fileSelected); Close c = new Close(Double.valueOf(tfSupport.getText()), Double.valueOf(tfConfidence.getText())); c.loadData(parser); textArea.append(c.generateRelations()); textArea.append("-----------------------------------------------------------\n"); } } } }); container.add(spPane, BorderLayout.CENTER); setVisible(true); }
6
public void onInvite(String targetNick, String sourceNick, String sourceLogin, String sourceHostname, String channel) { if (targetNick.equalsIgnoreCase(getNick())) { if (sourceNick.equalsIgnoreCase("ChanServ")) { channel = channel.replace("ChanServ!ChanServ@Services.GameSurge.net INVITE Meowzy ", ""); } Log.consoleLog("Invite", "Being invited to " + channel + " by " + sourceNick + " (" + sourceLogin + "@" + sourceHostname + ")"); if (sourceHostname.equalsIgnoreCase("irc.kieraan.co.uk") || sourceNick.equalsIgnoreCase("ChanServ")) { Log.consoleLog("Invite", "Accepting " + sourceNick + "'s invite to " + channel); joinChannel(channel); } } }
4
@Override public void run() { startFood(); while(true){ moreFood(); envi.repaint(); if(envi.getCritters().size() == 0){ break; } try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3
private void writeMethods(final DataOutputStream out, final Set onlyMethods) throws IOException { if (onlyMethods != null) { out.writeShort(onlyMethods.size()); } else { if (Method.DEBUG) { System.out.println("Writing " + methods.length + " methods"); } out.writeShort(methods.length); } for (int i = 0; i < methods.length; i++) { if ((onlyMethods != null) && onlyMethods.contains(methods[i])) { continue; } methods[i].write(out); } }
5
public boolean checkPassword(int accountId, String checkPass) { String realPass = ""; PasswordType type = PasswordType.DEFAULT; Connection conn = plugin.getDbCtrl().getConnection(); PreparedStatement ps = null; ResultSet rs = null; try { String sql = String.format("SELECT `password`, `pwtype` FROM `%s` WHERE `id` = ?", plugin.getDbCtrl().getTable(Table.ACCOUNT)); ps = conn.prepareStatement(sql); ps.setInt(1, accountId); rs = ps.executeQuery(); if (!rs.next()) return false; realPass = rs.getString("password"); type = PasswordType.getType(rs.getInt("pwtype")); } catch (SQLException e) { xAuthLog.severe("Failed to retrieve password hash for account: " + accountId, e); return false; } finally { plugin.getDbCtrl().close(conn, ps, rs); } String checkPassHash = ""; if (type == PasswordType.DEFAULT) { int saltPos = (checkPass.length() >= realPass.length() ? realPass.length() - 1 : checkPass.length()); String salt = realPass.substring(saltPos, saltPos + 12); String hash = whirlpool(salt + checkPass); checkPassHash = hash.substring(0, saltPos) + salt + hash.substring(saltPos); } else if (type == PasswordType.WHIRLPOOL) { checkPassHash = whirlpool(checkPass); } else if (type == PasswordType.AUTHME_SHA256) { String salt = realPass.split("\\$")[2]; checkPassHash = "$SHA$" + salt + "$" + hash(hash(checkPass, "SHA-256") + salt, "SHA-256"); } else checkPassHash = hash(checkPass, type.getAlgorithm()); if (checkPassHash.equals(realPass)) { // update hash in database to use xAuth's hashing method String newHash = hash(checkPass); conn = plugin.getDbCtrl().getConnection(); try { String sql = String.format("UPDATE `%s` SET `password` = ?, `pwtype` = ? WHERE `id` = ?", plugin.getDbCtrl().getTable(Table.ACCOUNT)); ps = conn.prepareStatement(sql); ps.setString(1, newHash); ps.setInt(2, 0); ps.setInt(3, accountId); ps.executeUpdate(); } catch (SQLException e) { xAuthLog.severe("Failed to update password hash for account: " + accountId, e); } finally { plugin.getDbCtrl().close(conn, ps); } return true; } else return false; }
8
void initializeSortState (final Tree tree) { /* Reset to known state: 'down' on column 0. */ tree.setSortDirection (SWT.DOWN); TreeColumn [] columns = tree.getColumns(); for (int i = 0; i < columns.length; i++) { TreeColumn column = columns[i]; if (i == 0) tree.setSortColumn(column); SelectionListener listener = new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { int sortDirection = SWT.DOWN; if (e.widget == tree.getSortColumn()) { /* If the sort column hasn't changed, cycle down -> up -> none. */ switch (tree.getSortDirection ()) { case SWT.DOWN: sortDirection = SWT.UP; break; case SWT.UP: sortDirection = SWT.NONE; break; } } else { tree.setSortColumn((TreeColumn)e.widget); } tree.setSortDirection (sortDirection); } }; column.addSelectionListener(listener); column.setData("SortListener", listener); //$NON-NLS-1$ } }
5
private void beforeCall(String command) { if (remoteClientCall == null) { throw new IllegalStateException("RemoteClientConnection is not initial."); } if (command == null) { throw new IllegalArgumentException("aMethodName is null"); } }
2
@Override public int classDurationModifier(MOB myChar, Ability skill, int duration) { if(myChar==null) return duration; if((((skill.classificationCode()&Ability.ALL_DOMAINS)==Ability.DOMAIN_CRAFTINGSKILL) ||((skill.classificationCode()&Ability.ALL_DOMAINS)==Ability.DOMAIN_BUILDINGSKILL)) &&(!skill.ID().equals("FoodPrep")) &&(!skill.ID().equals("Cooking")) &&(!skill.ID().equals("Sculpting")) &&(!skill.ID().equals("Herbalism")) &&(!skill.ID().equals("Masonry")) &&(!skill.ID().equals("Excavation"))) return duration*2; return duration; }
9
@RequestMapping(value="/{tripID}/editTravelTripForm", method=RequestMethod.GET) public String ediTravelTripForm(@PathVariable("tripID") String tripID, Model model){ TravelTrip tempTravelTrip = travelTripService.findById(Integer.parseInt(tripID)); if(tempTravelTrip == null){ return "index"; } model.addAttribute("editTravelTrip", tempTravelTrip); return "/editTravelTrip"; }
1
public static BigInteger sqrtMod(BigInteger val, BigInteger modulus) { BigInteger b, x, y, exp, exp2; BigInteger[] lm; int i, n; int K[] = new int[300]; val = val.mod(modulus); if (val.equals(ZERO)) return ZERO; if (modulus.equals(TWO)) return ONE; do { b = randomBetween(ONE, modulus); // Choose random number b with 1 <= b < p. } while ((b.modPow(modulus.subtract(ONE).shiftRight(1), modulus)).compareTo(ONE) == 0); /* Erfolg hat der Algorithmus bei Nichterfuellung der while-Bedingung */ // Im Erfolgsfalle bestimme l, m aus N, m ungerade, mit "p-1 = (2^l)*m" lm = sucheLM(modulus); y = val; n = 1; // Suche das kleinste K[n] >= 0 mit y^((2^k[n])*m) mod modulus = 1 K[n] = sucheKN(y, lm[1], modulus); while (K[n] != 0) { exp = ONE.shiftLeft((lm[0].subtract(BigInteger.valueOf(K[n]))).intValue()); y = (y.multiply(b.modPow(exp, modulus))).mod(modulus); K[++n] = sucheKN(y, lm[1], modulus); } x = y.modPow(lm[1].add(ONE).shiftRight(1), modulus); for (i = n; i > 1; i--) { exp = ONE.shiftLeft((lm[0].subtract(BigInteger.valueOf(K[i - 1])).subtract(ONE)).intValue()); exp2 = b.pow(exp.intValue()); x = (x.multiply(exp2.modInverse(modulus))).mod(modulus); } return x; }
5
private void appendDecimalSeparator(String str) { switch (StringUtils.countMatches(str, ".")) { case 0: return; case 1: if (!ds) { ds = true; return; } } throw new IllegalArgumentException("Cannot append more than one decimal separator"); }
3
private void statement() throws Exception { if(scan.sym == Token.let) { scan.next(); assignment_rest(); } else if(scan.sym == Token.call) { scan.next(); funcCall_rest(); } else if(scan.sym == Token.if_t) { scan.next(); ifStatement_rest(); } else if(scan.sym == Token.while_t) { scan.next(); whileStatement_rest(); } else if(scan.sym == Token.return_t) { // after a return statement, you can eliminate any // following code in the stat sequence. scan.next(); returnStatement_rest(); } else { throw new Exception("Statement: unrecognized statement type"); } }
5
private boolean isPrime(Integer number) { if ( (number > 2 && number % 2 == 0) || number < 2) { return false; } for (long i = 3; i <= Math.sqrt(number); i += 2) { if (number % i == 0) { return false; } } return true; }
5
private double medianOfFour(ArrayList<double[]> puntos, int axis, int start){ if(puntos.get(start)[axis]>puntos.get(start+1)[axis]) swap(puntos,start,start+1); if(puntos.get(start+2)[axis]>puntos.get(start+3)[axis]) swap(puntos,start+2,start+3); if(puntos.get(start)[axis]>puntos.get(start+2)[axis]) swap(puntos,start,start+2); if(puntos.get(start+1)[axis]>puntos.get(start+3)[axis]) swap(puntos,start+1,start+3); return (puntos.get(start+1)[axis]+puntos.get(start+2)[axis])/2; }
4
public static String largestNumber(int[] nums) { StringBuffer sb = new StringBuffer(); qsort(nums); int i = 0; for (i = 0; i < nums.length; i++) { if (nums[i] != 0) break; } for (; i < nums.length; i++) { sb.append(nums[i]); } String res = sb.toString(); return (res == null || res.compareTo("") == 0) ? "0" : res; }
5
private void processPatBlt(RdpPacket_Localised data, PatBltOrder patblt, int present, boolean delta) { if ((present & 0x01) != 0) patblt.setX(setCoordinate(data, patblt.getX(), delta)); if ((present & 0x02) != 0) patblt.setY(setCoordinate(data, patblt.getY(), delta)); if ((present & 0x04) != 0) patblt.setCX(setCoordinate(data, patblt.getCX(), delta)); if ((present & 0x08) != 0) patblt.setCY(setCoordinate(data, patblt.getCY(), delta)); if ((present & 0x10) != 0) patblt.setOpcode(ROP2_P(data.get8())); if ((present & 0x20) != 0) patblt.setBackgroundColor(setColor(data)); if ((present & 0x40) != 0) patblt.setForegroundColor(setColor(data)); parseBrush(data, patblt.getBrush(), present >> 7); // if(//logger.isInfoEnabled()) //logger.info("opcode="+patblt.getOpcode()); surface.drawPatBltOrder(patblt); }
7
public void split(Component newComp, Component child, DockingConstants.Split position) { SplitContainer split; if(position == DockingConstants.SPLIT_TOP || position == DockingConstants.SPLIT_BOTTOM) { split = new SplitContainer(JSplitPane.VERTICAL_SPLIT); } else /*if (position == DockingConstants.SPLIT_LEFT || position == DockingConstants.SPLIT_RIGHT)*/{ split = new SplitContainer(JSplitPane.HORIZONTAL_SPLIT); } if(getLeftComponent() == child) { remove(child); setLeftComponent(split); if(position == DockingConstants.SPLIT_TOP || position == DockingConstants.SPLIT_LEFT) { split.setLeftComponent(newComp); // for splitpane, left == top split.setRightComponent(child); } else { split.setLeftComponent(child); // for splitpane, left == top split.setRightComponent(newComp); } } else { remove(child); setRightComponent(split); if(position == DockingConstants.SPLIT_TOP || position == DockingConstants.SPLIT_LEFT) { split.setLeftComponent(newComp); // for splitpane, left == top split.setRightComponent(child); } else { split.setLeftComponent(child); // for splitpane, left == top split.setRightComponent(newComp); } } }
7
private boolean jj_scan_token(int kind) { if (jj_scanpos == jj_lastpos) { jj_la--; if (jj_scanpos.next == null) { jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken(); } else { jj_lastpos = jj_scanpos = jj_scanpos.next; } } else { jj_scanpos = jj_scanpos.next; } if (jj_rescan) { int i = 0; Token tok = token; while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; } if (tok != null) jj_add_error_token(kind, i); } if (jj_scanpos.kind != kind) return true; if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; return false; }
9
public boolean isInverted() { return inverted; }
0
public Boolean matchNameExists(String hostName){ try { cs = con.prepareCall("{call GET_MATCHNAME(?)}"); cs.setString(1, hostName); if(!cs.executeQuery().next()){ return false; } } catch (SQLException e) { e.printStackTrace(); } return true; }
2
protected void buildWhirl() { int[] curXY=new int[]{xsize-1,0}; int dirs[]=new int[]{Directions.WEST,Directions.SOUTH,Directions.EAST,Directions.NORTH}; int num=xsize-1; Room lastRoom=null; while(num>0) { for(int dir : dirs) { for(int i=0;i<num;i++) { if(!linkRoomOpen(curXY,dir)) { num--; break; } else { lastRoom=subMap[curXY[0]][curXY[1]]; } } } } int dir = Directions.DOWN; while(lastRoom != null) { lastRoom.giveASky(0); Room downRoom = lastRoom.getRoomInDir(dir); if(downRoom != null) { Behavior currents=CMClass.getBehavior("WaterCurrents"); if(currents != null) { currents.setParms("minticks=1 maxticks=2 chance=75 BOATS "+CMLib.directions().getDirectionName(dir)); currents.setSavable(true); lastRoom.addBehavior(currents); lastRoom.setDescription(lastRoom.description() +L("%0D^HThe swirling waters are pulling you "+CMLib.directions().getDirectionName(dir)+".^?")); } } lastRoom=downRoom; } }
7
public boolean canPlaceBlockOnSide(World par1World, int par2, int par3, int par4, int par5) { if (disableValidation) { return true; } if (par5 == 0) { return false; } else if (par5 == 1) { return false; } else { if (par5 == 2) { ++par4; } if (par5 == 3) { --par4; } if (par5 == 4) { ++par2; } if (par5 == 5) { --par2; } return isValidSupportBlock(par1World.getBlockId(par2, par3, par4)) || par1World.isBlockSolidOnSide(par2, par3, par4, 1); } }
8
private void updateCritereList(boolean selectEnd) { critereList.setModel(new CritereListModel(domaine.getCriteres())); try { critereList.setSelectedIndex((selectEnd)?critereList.getModel().getSize()-1:0); } catch (IllegalArgumentException e) { System.err.println("Erreur lors du chargement des critères, sans doute il n'en existe pas."); } }
2
private int getPing(Player player) { try { Class<?> entityCraftPlayer = Class.forName(plugin.craftBukkitClassName.concat(".entity.CraftPlayer")); Method getHandle = entityCraftPlayer.getMethod("getHandle", new Class[0]); Object playerHandle = getHandle.invoke(player); Object craftPlayer = craftBukkitEntityField.get(player); return playerHandle.getClass().getField(pingFieldName).getInt(craftPlayer); } catch (NoSuchFieldException e) { if (pingFieldName == "ping") { pingFieldName = "field_71138_i"; plugin.getLogger().info("Failed to get ping from field \"ping\", field does not exist! Attempting \"field_71138_i\" as ping field name."); } else if (pingFieldName == "field_71138_i") { pingFieldName = "lastPing"; plugin.getLogger() .warning( "Failed to find \"field_71138_i\" field! Attempting fallback to \"lastPing\" field name. This field has a drawback and it takes long to update but should always exist."); } else if (pingFieldName == plugin.fallbackField) { plugin.getLogger().info("Parsing player: ".concat(player.getName())); plugin.getLogger().log(Level.SEVERE, "Unable to determine ping field. Can't continue!", e); plugin.getServer().getPluginManager().disablePlugin(plugin); ; } return 0; } catch (Exception e) { plugin.getLogger().info("Parsing player: ".concat(player.getName())); plugin.getLogger() .log(Level.SEVERE, "VG Scoreboard Ping was unable to find the NMS player class. In rought words the bukkit version you use is not supported. Please report this on the tracker so the plugin can be updated!", e); plugin.getServer().getPluginManager().disablePlugin(plugin); ; return 0; } }
6
@Override public double playLevel(Map toPlay, boolean visuals) { int w = toPlay.getWidthInTiles(); int h = toPlay.getHeightInTiles(); int noSolid = 0; for (int x = 0; x < w; x++) for (int y = 0; y < h; y++) noSolid += toPlay.blocked(null, x, y) ? 1 : 0; double solidRatio = (double) noSolid / (double) (w * h); AStarPathFinder pathfinder = new AStarPathFinder(toPlay, 500, false); return pathLengthFromLocation(0,0,pathfinder,toPlay); }
3
public PlayerSettings(Game game, boolean isOthello) { boolean test = false; if (test || m_test) { System.out.println("PlayerSettings :: PlayerSettings() BEGIN"); } ISOTHELLO = isOthello; if (isOthello) { PLAYERCOLOUR_A1 = new JRadioButton("Black"); PLAYERCOLOUR_B1 = new JRadioButton("White"); PLAYERCOLOUR_A2 = new JRadioButton("Black"); PLAYERCOLOUR_B2 = new JRadioButton("White"); } else { PLAYERCOLOUR_A1 = new JRadioButton("Red"); PLAYERCOLOUR_B1 = new JRadioButton("Yellow"); PLAYERCOLOUR_A2 = new JRadioButton("Red"); PLAYERCOLOUR_B2 = new JRadioButton("Yellow"); } m_game = game; windowInitialise(); buttonGroups(); listeners(); listenersPlayers(); listenersControls(); PLAYERCOLOUR_A1.doClick(); HUMAN.doClick(); HUMAN2.doClick(); setTitle("Player settings"); pack(); setLocationRelativeTo(null); if (test || m_test) { System.out.println("PlayerSettings :: PlayerSettings() END"); } }
5
//@Test(expected=ReaderException.class) public void testReadCastFail() throws ReaderException { ConfigurationManager.init("src/test/resources/test.json"); // Cast exceptions expected ConfigurationManager.read.getIntegerItem("test", "double"); }
0
@Override public String getTmp() {return String.valueOf(tmp);}
0
private static PixImage array2PixImage(int[][] pixels) { int width = pixels.length; int height = pixels[0].length; PixImage image = new PixImage(width, height); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setPixel(x, y, (short) pixels[x][y], (short) pixels[x][y], (short) pixels[x][y]); } } return image; }
2
public static boolean isValidBST(TreeNode root) { if (root == null) { return true; } TreeNode nodeL = root.left; TreeNode nodeR = root.right; if (nodeL != null) { if (nodeL.val >= root.val) return false; else { if (!isValidBSTHelper(nodeL, root, true)) return false; } } if (nodeR != null) { if (nodeR.val <= root.val) return false; else { if (!isValidBSTHelper(nodeR, root, false)) return false; ; } } return true; }
7
public void earnBonus() { int bonus = numGen.nextInt(100)+101; this.setTotal(this.getTotal()+bonus); }
0
public void compFinalResult() { do { iStage++; compAllocation(); if (compDistribution()) { /* deadline can not be satisfied */ if (!bDeadline) { System.out.println("THE DEADLINE CAN NOT BE SATISFIED!"); return; } else { System.out.println("\nNEW ROUND WITHOUT CHECKING:"); dEval = 1; } } else { compExecTime(); } // System.out.println("Evaluation Value =========="+dEval); } while (dEval > 0); // while (evaluateResults()); // System.out.println("==================Distribution====================="); for (int i = 0; i < iClass; i++) { // System.out.print("FinalDistribution[" + i + "] "); for (int j = 0; j < iSite; j++) { dmDist[i][j] = Math.round(dmDist[i][j]); // System.out.print(dmDistribution[i][j] + ","); } // System.out.println(); } // System.out.println("==================Allocation====================="); for (int i = 0; i < iClass; i++) { System.out.print("FinalAllocation[" + i + "] "); for (int j = 0; j < iSite; j++) { dmAlloc[i][j] = Math.round(dmAlloc[i][j]); // System.out.print(dmAllocation[i][j] + ","); } // System.out.println(); } // System.out.println("Stage = " + iStage); }
7
private void Upload(ByteBuffer packet) throws RuntimeException, IOException{ // given packet w/no header! // (for uploading request c->s) [header | filesize(8) | filename(?)] // (for upload acknowledgement s->c) [header | already exists (1) | file id (4)] // parse the req if (packet.capacity() < 4) throw new RuntimeException( "filename not correctly uploaded"); long buf_size = packet.getLong(0); String buf_name = ""; for (int i = 0; i < buf.capacity(); i++){ if (buf.get(8 +i) == '\0') break; buf_name += (char)buf.get(8 + i); } if (buf_name.length() == 0) throw new RuntimeException( "filename not correctly uploaded"); int id = buf_name.hashCode() + (int)buf_size; boolean add = true; for (ClientObj c : clients) if (c.hasFile(id)) // Check for duplicate id's, which would be problematic add = false; byte exists = 0; if (add) client.addUpload(new ServerFile(buf_name, buf_size, id)); else { for (ServerFile f : totalFiles().keySet()) if (f.id() == id) client.addUpload(f); exists = 1; } System.out.println(client.getAddress() + ": Correctly processed upload req for " + buf_name + " with size " + buf_size + " bytes and id " + id); //construct/send response buf = Utility.addHeader(3, 5, client.getId()); buf.put(Constants.HEADER_LEN, exists); buf.putInt(Constants.HEADER_LEN + 1, id); byte[] sendData = buf.array(); // send response out.write(sendData); out.flush(); }
9
public File getRessourceFile(int id) { String req; Statement st = null; ResultSet result; File f = null; try { req = "SELECT * FROM t_medias WHERE id='"+id+"'"; st = cnx(); if(st == null) return null; result = st.executeQuery(req); if(result.last() && result.getRow() == 1) { String name = result.getString("name"); f = new File(System.getProperty("java.io.tmpdir")+File.separator+"name"); FileOutputStream fos = new FileOutputStream(f); byte[] buffer = new byte[1]; InputStream is = result.getBinaryStream("binaryBlob"); while (is.read(buffer) > 0) { fos.write(buffer); } fos.close(); } result.close(); st.close(); } catch (SQLException | IOException e) { e.printStackTrace(); } return f; }
5
public void setOptions(String[] options) throws Exception { String tmpStr; super.setOptions(options); tmpStr = Utils.getOption('N', options); if (tmpStr.length() != 0) setNumInstances(Integer.parseInt(tmpStr)); else setNumInstances(20); tmpStr = Utils.getOption("nominal", options); if (tmpStr.length() != 0) setNumNominal(Integer.parseInt(tmpStr)); else setNumNominal(2); tmpStr = Utils.getOption("numeric", options); if (tmpStr.length() != 0) setNumNumeric(Integer.parseInt(tmpStr)); else setNumNumeric(1); tmpStr = Utils.getOption("string", options); if (tmpStr.length() != 0) setNumString(Integer.parseInt(tmpStr)); else setNumString(1); tmpStr = Utils.getOption("date", options); if (tmpStr.length() != 0) setNumDate(Integer.parseInt(tmpStr)); else setNumDate(1); tmpStr = Utils.getOption("relational", options); if (tmpStr.length() != 0) setNumRelational(Integer.parseInt(tmpStr)); else setNumRelational(1); tmpStr = Utils.getOption("num-instances-relational", options); if (tmpStr.length() != 0) setNumInstancesRelational(Integer.parseInt(tmpStr)); else setNumInstancesRelational(10); tmpStr = Utils.getOption("words", options); if (tmpStr.length() != 0) setWords(tmpStr); else setWords(new TestInstances().getWords()); if (Utils.getOptionPos("word-separators", options) > -1) { tmpStr = Utils.getOption("word-separators", options); setWordSeparators(tmpStr); } else { setWordSeparators(TestInstances.DEFAULT_SEPARATORS); } }
9
@Override public double[] updatePlanes(ArrayList<Plane> planes, int round, double[] bearings) { // if any plane is in the air, then just keep things as-is for (Plane p : planes) { if (p.getBearing() != -1 && p.getBearing() != -2) return bearings; } // if no plane is in the air, find the one with the earliest // departure time and move that one in the right direction int minTime = 10000; int minIndex = 10000; for (int i = 0; i < planes.size(); i++) { Plane p = planes.get(i); if (p.getDepartureTime() < minTime && p.getBearing() == -1) { minIndex = i; minTime = p.getDepartureTime(); } } // if it's not too early, then take off! if (round >= minTime) { Plane p = planes.get(minIndex); bearings[minIndex] = calculateBearing(p.getLocation(), p.getDestination()); } return bearings; }
7
public static void main(String[] args) throws IOException { File activeUsersFile = new File("activeUser.txt"); if (!activeUsersFile.exists()) { throw new IOException("Active users file does not Exists!!"); } String outDIr = "./Users-trimmed/"; if (!new File(outDIr).exists()) { new File(outDIr).mkdir(); } GraphTrimmer graphTrimmer = new GraphTrimmer("./Users/", outDIr, new File("activeUser.txt"), 800000000); graphTrimmer.start(); }
2
public long nextLong() throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } if (p == PEEKED_LONG) { peeked = PEEKED_NONE; return peekedLong; } if (p == PEEKED_NUMBER) { peekedString = new String(buffer, pos, peekedNumberLength); pos += peekedNumberLength; } else if (p == PEEKED_SINGLE_QUOTED || p == PEEKED_DOUBLE_QUOTED) { peekedString = nextQuotedValue(p == PEEKED_SINGLE_QUOTED ? '\'' : '"'); try { long result = Long.parseLong(peekedString); peeked = PEEKED_NONE; return result; } catch (NumberFormatException ignored) { // Fall back to parse as a double below. } } else { throw new IllegalStateException("Expected a long but was " + peek() + " at line " + getLineNumber() + " column " + getColumnNumber()); } peeked = PEEKED_BUFFERED; double asDouble = Double.parseDouble(peekedString); // don't catch this NumberFormatException. long result = (long) asDouble; if (result != asDouble) { // Make sure no precision was lost casting to 'long'. throw new NumberFormatException("Expected a long but was " + peekedString + " at line " + getLineNumber() + " column " + getColumnNumber()); } peekedString = null; peeked = PEEKED_NONE; return result; }
8
private void preCalculateHeuristics() { heuristics = new double[adjacency.length]; for (int i = 0; i < heuristics.length; i++) { double minimum = Double.MAX_VALUE; for (int j = 0; j < adjacency[i].length; j++) { if (i != j && adjacency[i][j] >= 0 && adjacency[i][j] < minimum) { minimum = adjacency[i][j]; } } heuristics[i] = minimum; } }
5
public void destroy() { if (homeAction == null) return; // already destroyed if (Modeler.isMac()) { enabledComponentsWhenRemote.clear(); enabledComponentsWhenLocal.clear(); } actionMap.clear(); deadLinks.clear(); popupMenu.destroy(); PopupMenuListener[] pml = comboBox.getPopupMenuListeners(); if (pml != null) { for (PopupMenuListener l : pml) comboBox.removePopupMenuListener(l); } MouseListener[] ml = getTextField().getMouseListeners(); if (ml != null) { for (MouseListener l : ml) getTextField().removeMouseListener(l); } ActionListener[] al = getTextField().getActionListeners(); if (al != null) { for (ActionListener l : al) getTextField().removeActionListener(l); } comboBox.setBorder(null); actionListener = null; itemListener = null; backAction = null; forwardAction = null; homeAction = null; navigable = null; popupMenu = null; }
8
private CFGResult ifStatement(Block lastBlock) throws IOException, SyntaxFormatException { if (checkCurrentType(TokenType.IF)) { moveToNextToken(); ArithmeticResult cond = relation(lastBlock); if (cond == null) { throwFormatException("if statement relation expression expected"); } assertAndMoveNext(TokenType.THEN); Block thenBlock = new Block(lastBlock.getLocalVarTable(), lastBlock.getGlobalVarTable()); CFGResult thenResult = statSequence(thenBlock); if (thenResult == null) { throwFormatException("if statement statSequence expected"); } CFGResult elseResult = null; if (checkCurrentType(TokenType.ELSE)) { moveToNextToken(); Block elseBlock = new Block(lastBlock.getLocalVarTable(), lastBlock.getGlobalVarTable()); elseResult = statSequence(elseBlock); if (elseResult == null) { throwFormatException("if statement else statSequence expected"); } } assertAndMoveNext(TokenType.FI); return inter.computeIf(lastBlock, cond, thenResult, elseResult); } return null; }
5
@Override public DataTable generateDataTable (Query query, HttpServletRequest request) throws DataSourceException { DataTable dataTable = null; try (final Reader reader = new FilterCsv (new BufferedReader (new InputStreamReader (new URL (this.urlYahoo).openStream())))) { TableRow row = new TableRow (); dataTable = CsvDataSourceHelper.read(reader, this.column, false); dataTable.addColumn(new ColumnDescription (FieldETF.GLD.toString(), ValueType.TEXT, FieldETF.GLD.toString())); dataTable.addColumn(new ColumnDescription (FieldETF.SLV.toString(), ValueType.TEXT, FieldETF.SLV.toString())); for (int i = 0; i < dataTable.getNumberOfRows(); i++) { String lastPriceDataTable = dataTable.getCell(i, 0).toString(); String changePercentDataTable = dataTable.getCell(i, 1).toString(); String volumeDataTable = dataTable.getCell(i, 2).toString(); String averageVolumeDataTable = dataTable.getCell(i, 3).toString(); if (! lastPriceDataTable.matches(".*\\d.*")) lastPriceDataTable = "0"; if (! changePercentDataTable.matches(".*\\d.*")) changePercentDataTable = "0"; if (! volumeDataTable.matches(".*\\d.*")) volumeDataTable = "0"; if (! averageVolumeDataTable.matches(".*\\d.*")) averageVolumeDataTable = "0"; String lastPriceString = this.formatter.format(Double.parseDouble(lastPriceDataTable)); String changePercentString = this.formatter.format(Double.parseDouble(changePercentDataTable)); String volumeString = this.formatter.format(Double.parseDouble(volumeDataTable)); String averageVolumeString = this.formatter.format(Double.parseDouble(averageVolumeDataTable)); row.addCell(lastPriceString + " (" + changePercentString + "%) " + volumeString + " (" + averageVolumeString + ")"); } dataTable.addRow(row); } catch (MalformedURLException e) { System.out.println("TableETF generateDataTable() MalformedURLException " + "URL : " + this.urlYahoo + " " + e); } catch (IOException e) { System.out.println("TableETF generateDataTable() IOException " + e); } return dataTable; }
7
public static final synchronized StdImage createFadedImage(StdImage image, int percentage, boolean useWhite) { String name = REVERSE_MAP.get(image); StdImage img = null; if (name != null) { name = name + percentage + useWhite + FADED_POSTFIX; img = get(name); } if (img == null) { img = FadeFilter.createFadedImage(image, percentage, useWhite); if (img != null && name != null) { MAP.put(name, img); REVERSE_MAP.put(img, name); } } return img; }
4
private boolean checkAndSaveGroup() { boolean check = true; String error = ""; if(txtName.getText().length() < 1) { lblName.setForeground(Color.RED); error += " - Name \n"; check = false; }else lblName.setForeground(Color.BLACK); if(txtCapacity.getText().length() < 1) { lblCapacity.setForeground(Color.RED); error += " - Capacity \n"; check = false; }else lblCapacity.setForeground(Color.BLACK); if(((Level)cbLevel.getSelectedItem()).getId() < 1) { lblLevel.setForeground(Color.RED); error += " - Level \n"; check = false; }else lblLevel.setForeground(Color.BLACK); if(check) { fillGroup(); GroupDAO groupDAO = new GroupDAO(db.connection); groupDAO.updateGroup(this.group, this.schedule_list); } else { JOptionPane.showMessageDialog(this, "Please select: \n" + error); } return check; }
4
@Override public boolean isManagingFocus() {return true;}
0
private static void setField(Message msg, String str) { String[] strs = str.split(":"); strs[1] = strs[1].trim(); if(strs[0].equals("Host")) { msg.setHost(strs[1]); } else if(strs[0].equals("Port")) { msg.setPort( Integer.valueOf(strs[1]) ); } else if(strs[0].equals("Title")) { msg.setTitle(strs[1]); } else if(strs[0].equals("Date")) { // msg.set(strs[1]); } else if(strs[0].equals("OS")) { msg.setOS(strs[1]); } else if(strs[0].equals("Last Modified")) { // msg.setTitle(strs[1]); } else if(strs[0].equals("Content Length")) { msg.setContentLength(Integer.valueOf(strs[1])); } else if(strs[0].equals("Content Type")) { msg.setContentType(strs[1]); } }
8
@Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(getClass() != obj.getClass()) return false; Semaphore other = (Semaphore) obj; if(id == null) { if(other.id != null) return false; } else { if(!id.equals(other.id)) return false; } return true; }
6
public void setMaxLength(Long value) { this.maxLength = value; }
0
public static boolean run(CommandSender sender, boolean isPlayer, String[] args, Logger log) { if (!isPlayer){sender.sendMessage(notPlayer);return false;} if (args.length < 1) {sender.sendMessage(ChatColor.RED+"Needs a World argument");return false;} Player p = (Player)sender; Location to = p.getLocation(); World world = Utils.getCmdWorld(sender, args[0]); if (world==null){return true;}//it failed and the error message was allready sent for (Player v : world.getPlayers()){ if( !p.hasPermission(Utils.exemptPerm) | !v.getDisplayName().equalsIgnoreCase(p.getDisplayName()) ){ v.teleport(to); v.sendMessage( (tellVictum+p.getDisplayName()).replace("%world", to.getWorld().getName()) ); } } log.info( (tellLog+p.getDisplayName()+" "+Utils.locToString(to)).replace("%world", to.getWorld().getName()) ); return true; }
5
static final void setHslTable() { anInt6112++; if (Class126.hslColorTable == null) Class126.hslColorTable = new int[65536]; else return; double d = 0.7 + (0.03 * Math.random() - 0.015); int i_5_ = 0; for (int i_6_ = 0; (i_6_ ^ 0xffffffff) > -513; i_6_++) { float f = (((float) (i_6_ >> -1851515709) / 64.0F + 0.0078125F) * 360.0F); float f_7_ = (float) (i_6_ & 0x7) / 8.0F + 0.0625F; for (int i_8_ = 0; i_8_ < 128; i_8_++) { float f_9_ = (float) i_8_ / 128.0F; float f_10_ = 0.0F; float f_11_ = 0.0F; float f_12_ = 0.0F; float f_13_ = f / 60.0F; int i_14_ = (int) f_13_; int i_15_ = i_14_ % 6; float f_16_ = (float) -i_14_ + f_13_; float f_17_ = f_9_ * (-f_7_ + 1.0F); float f_18_ = f_9_ * (1.0F - f_16_ * f_7_); float f_19_ = (1.0F - (1.0F - f_16_) * f_7_) * f_9_; if ((i_15_ ^ 0xffffffff) != -1) { if ((i_15_ ^ 0xffffffff) != -2) { if ((i_15_ ^ 0xffffffff) != -3) { if (i_15_ != 3) { if (i_15_ != 4) { if ((i_15_ ^ 0xffffffff) == -6) { f_10_ = f_9_; f_11_ = f_17_; f_12_ = f_18_; } } else { f_12_ = f_9_; f_11_ = f_17_; f_10_ = f_19_; } } else { f_12_ = f_9_; f_11_ = f_18_; f_10_ = f_17_; } } else { f_12_ = f_19_; f_10_ = f_17_; f_11_ = f_9_; } } else { f_11_ = f_9_; f_10_ = f_18_; f_12_ = f_17_; } } else { f_10_ = f_9_; f_11_ = f_19_; f_12_ = f_17_; } f_10_ = (float) Math.pow((double) f_10_, d); f_11_ = (float) Math.pow((double) f_11_, d); f_12_ = (float) Math.pow((double) f_12_, d); int i_20_ = (int) (f_10_ * 256.0F); int i_21_ = (int) (256.0F * f_11_); int i_22_ = (int) (256.0F * f_12_); int i_23_ = ((i_21_ << -142238264) + ((i_20_ << 1415665776) + (-16777216 + i_22_))); Class126.hslColorTable[i_5_++] = i_23_; } } }
9
public SingleTreeNode expand() { int bestAction = 0; double bestValue = -1; for (int i = 0; i < children.length; i++) { double x = m_rnd.nextDouble(); if (x > bestValue && children[i] == null) { bestAction = i; bestValue = x; } } /** * Advance state. */ StateObservationMulti nextState = state.copy(); //need to provide actions for all players to advance the forward model Types.ACTIONS[] acts = new Types.ACTIONS[no_players]; //set this agent's action acts[id] = actions[id][bestAction]; //get actions available to the opponent and assume they will do a random action Types.ACTIONS[] oppActions = actions[oppID]; acts[oppID] = oppActions[new Random().nextInt(oppActions.length)]; nextState.advance(acts); SingleTreeNode tn = new SingleTreeNode(nextState, this, this.m_rnd, NUM_ACTIONS, actions, id, oppID, no_players); children[bestAction] = tn; return tn; }
3
private void openFile(int fileIndex){ if(quick_launch_files[fileIndex].canExecute()){ try { System.out.println("Attempting to open: "+quick_launch_files[fileIndex].getAbsolutePath()); Desktop.getDesktop().open( quick_launch_files[fileIndex] ); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Can't open file: "+ quick_launch_files[fileIndex].getName()); } }
2
private void actionAdd( ) { DefaultMutableTreeNode selNd = getSelectedNode(); if ( selNd == null ) { audioVectors.add(new LinkedList<double[]>()); DefaultMutableTreeNode newNd = new DefaultMutableTreeNode("Collection"); dataRootNd.add(newNd); dataTr.scrollPathToVisible(new TreePath(newNd.getPath())); dataTr.updateUI(); } else { int[] selIdxs = getNodeIndexList(selNd); if ( selIdxs.length == 1 ) { JFileChooser fileDl = new JFileChooser(FastICAApp.getPreference(FastICAApp.PREF_DIR_ADD)); if ( fileDl.showOpenDialog(this) == JFileChooser.APPROVE_OPTION ) { try { File selFile = fileDl.getSelectedFile(); FastICAApp.setPreference(FastICAApp.PREF_DIR_ADD, selFile.getParentFile().getAbsolutePath()); double[] audioVector = AudioVector.readAudioFile(selFile, audioSampleRate); audioVectors.get(selIdxs[0]).add(audioVector); DefaultMutableTreeNode newNd = new DefaultMutableTreeNode(selFile.getName()); selNd.add(newNd); dataTr.scrollPathToVisible(new TreePath(newNd.getPath())); dataTr.updateUI(); } catch( Exception exc ) { FastICAApp.exceptionDialog(exc); } } } } }
4
private String getTripleListFromTripleVector( Vector<Vector<String>> tripleVector ) {String tripleList="<triple_list>"; for(int i=0; i< tripleVector.size() ;i++) {String s=tripleVector.elementAt(i).elementAt(0); String p=tripleVector.elementAt(i).elementAt(1); String o=tripleVector.elementAt(i).elementAt(2); String st=s==null?"URI":tripleVector.elementAt(i).elementAt(3); String ot=o==null?"URI":tripleVector.elementAt(i).elementAt(4); tripleList=tripleList +"<triple>" +"<subject type=\""+st+"\">"+ (s==null?ANYURI:s)+"</subject>" +"<predicate>"+ (p==null?ANYURI:p)+"</predicate>" +"<object type=\"" +ot+"\">"+ (o==null?ANYURI:o)+"</object>" +"</triple>"; } return tripleList+"</triple_list>"; }//private String getTripleListFromTripleVector( Vector<Vector<String>> tripleList )
6
public void run() { MensajeServidor("Procesando conexion"); try { //Entrada es el input del cliente, es decir la request en su respectivo formato. BufferedReader entrada = new BufferedReader(new InputStreamReader(cliente.getInputStream())); //Salida es para enviar la response. salida = new PrintWriter(new OutputStreamWriter(cliente.getOutputStream(), "8859_1"), true); String cadena="" ; // Con i se puede reconocer la primera linea, que indica el metodo y version del protocolo int i = 0; do { //Se leen las lineas y se imprimen en orden, para ver que esta haciendo cada thread. cadena = entrada.readLine(); if (cadena != null) { MensajeServidor("--" + cadena); // Si es la primera linea se reconoce que metodo es y segun esto se maneja la peticion. if (i == 0) { i++; StringTokenizer st = new StringTokenizer(cadena); String metodo=st.nextToken(); if ((st.countTokens() >= 2) && (metodo.equals("GET"))) { //Si es get se retorna el archivo indicado en la linea principal. RetornarArchivo(st.nextToken()); } else if((st.countTokens() >= 2) && (metodo.equals("POST"))){ //Si es post se le pasa la entrada y la direccion. ManejoPost(entrada,st.nextToken()); } //Si el archivo no existe se devuelve not found en la salida al cliente (cliente.getOutputStream()). else { salida.println("HTTP/1.1 400 Not Found"); } } } } while (cadena != null && cadena.length() != 0); } catch (IOException| NullPointerException e) { //En el caso que no se pueda establecer conexion con la salida, se retorna not found, en teoria debiera ser 501. salida.println("HTTP/1.1 400 Not Found"); salida.close(); } //Si todo va correctamente, se termina la peticion y se finaliza. MensajeServidor("Peticion Finalizada"); salida.close(); }
9
public static String doubleToString(double d) { if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String string = Double.toString(d); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; }
7
public void init(String className) { imports = new TreeMap(comparator); /* java.lang is always imported */ imports.put("java.lang.*", new Integer(Integer.MAX_VALUE)); int pkgdelim = className.lastIndexOf('.'); pkg = (pkgdelim == -1) ? "" : className.substring(0, pkgdelim); this.className = (pkgdelim == -1) ? className : className .substring(pkgdelim + 1); }
2
@Override public Answer getAnswer(String gameid, Combination<Colors> combi) { HttpGet request; try { request = new HttpGet(new URI("http", null, SERVER, PORT, TRY_URL, String.format("gameid=%s&combi=%s", gameid, combi.toString()), null)); } catch (URISyntaxException e) { throw new RuntimeException(e); } HttpResponse response; try { response = client.execute(request); } catch (ClientProtocolException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } String json; try { json = CharStreams.toString(new InputStreamReader(response.getEntity() .getContent())); } catch (IOException e) { throw new RuntimeException(e); } return Answer.fromJson(json); }
4
public returnTypes deleteChunk(byte[] fileID, int chunkNo) { String recID = Packet.bytesToHex(fileID); for(BackupChunk chunk : backedUpChunks) { String comID = Packet.bytesToHex(chunk.getFileID()); if(comID.equals(recID) && chunk.getChunkNo() == chunkNo) { String filepath = "storage/"; filepath += chunk.getFilename(); boolean success = (new File (filepath)).delete(); if (success) { currSize -= chunk.getSize(); success = backedUpChunks.remove(chunk); if(success) {System.out.println("The file has been successfully deleted");updateLog();} else {System.out.println("Error occurred while deleting the file."); return returnTypes.FAILURE;} } else {System.out.println("Error occurred while deleting the file"); return returnTypes.FAILURE;} return returnTypes.SUCCESS; } } return returnTypes.FILE_DOES_NOT_EXIST; }
5
private void encodePositions(int number,int posS,int posE,int[] encoding) { String bin = Integer.toBinaryString(number); System.out.println("In encodePositions "+bin); System.out.println("start"+posE); while(bin.length()<=posE-posS) { bin = 0+bin; } for(int i=posE-posS,j=posS;i>=0;i--,j++) { System.out.println("h"+j); encoding[j] = Integer.parseInt(bin.charAt(i)+""); System.out.println(encoding[j]); } }
2
private static void compareListToMvd( byte[] list, MVD mvd ) throws MVDTestException { String response = new String( list ); String[] parts = response.split("\n"); if ( parts.length==0 ||parts[0].indexOf('\t')!=-1 ) throw new MVDTestException("Invalid list versions header"); for ( int i=1;i<parts.length;i++ ) readLine( parts[i], mvd ); }
3
public void testPlus_Days() { Days test2 = Days.days(2); Days test3 = Days.days(3); Days result = test2.plus(test3); assertEquals(2, test2.getDays()); assertEquals(3, test3.getDays()); assertEquals(5, result.getDays()); assertEquals(1, Days.ONE.plus(Days.ZERO).getDays()); assertEquals(1, Days.ONE.plus((Days) null).getDays()); try { Days.MAX_VALUE.plus(Days.ONE); fail(); } catch (ArithmeticException ex) { // expected } }
1
public static void defineFloors(int level){ if (level == 1){ createFloor(0, 600, 800, level); createFloor(700, 475, 800, level); createFloor(1650, 500, 500, level); createFloor(2300, 650, 1000, level); createFloor(3400, 500, 600, level); createFloor(4050, 600, 900, level); levelEnd = new Rectangle(4950, 600 - 250 + floorHeight, 50, 250); } }
1
public static String getCState(char c, HTTPRequest httpReq) { boolean changes = false; final CharState adjCState=(CharState)CMClass.getCommon("DefaultCharState"); adjCState.setAllValues(0); if(httpReq.isUrlParameter(c+"CSTATE1")) { int num=1; String behav=httpReq.getUrlParameter(c+"CSTATE"+num); while(behav!=null) { if((behav.length()>0) && (new XVector<String>(adjCState.getStatCodes()).contains(behav.toUpperCase().trim()))) { String prof=httpReq.getUrlParameter(c+"CSTATEV"+num); if(prof==null) prof="0"; if(CMath.s_int(prof)!=0) { adjCState.setStat(behav.toUpperCase().trim(), prof); changes = true; } } num++; behav=httpReq.getUrlParameter(c+"CSTATE"+num); } } if(!changes) return ""; return CMLib.coffeeMaker().getCharStateStr(adjCState); }
7
@Override public void deserialize(Buffer buf) { short flag1 = buf.readUByte(); isOnSale = BooleanByteWrapper.getFlag(flag1, 0); isSaleLocked = BooleanByteWrapper.getFlag(flag1, 1); houseId = buf.readInt(); if (houseId < 0) throw new RuntimeException("Forbidden value on houseId = " + houseId + ", it doesn't respect the following condition : houseId < 0"); int limit = buf.readUShort(); doorsOnMap = new int[limit]; for (int i = 0; i < limit; i++) { doorsOnMap[i] = buf.readInt(); } ownerName = buf.readString(); modelId = buf.readShort(); if (modelId < 0) throw new RuntimeException("Forbidden value on modelId = " + modelId + ", it doesn't respect the following condition : modelId < 0"); }
3
public ClassBuilder method( MethodBuilder methodBuilder ) { if ( methodBuilder == null ) { return this ; } MethodMetadata metadata = methodBuilder.build() ; for ( MethodMetadataBuilder method : builder.getDeclaredMethods() ) { if ( metadata.getMethodName().equals( method.getMethodName())) return this ; } builder.addMethod(metadata) ; return this ; }
3
@Override protected Void doInBackground() throws Exception { // Convert known data text files to treeset dictionaries // (because String.hashCode() is really slow) dictionaries = new ArrayList<>(); if (fields != null && !fields.isEmpty()) { for (int i = 0; i < fields.size(); ++i) { Field f = fields.get(i); TreeSet<String> dictionary = new TreeSet<>(); if (f.knownData() != null) { if (communicationNotifier != null) { String s = communicationNotifier.downloadHtml(f.knownData()).toLowerCase(); List<String> list = Arrays.asList(s.split(",")); dictionary.addAll(list); } } dictionaries.add(dictionary); } } return null; }
5
public void actionPerformed(ActionEvent e){ if(e.getSource() == midiMuteButton){ // test case if(Debug.sound)System.out.println("Mute Button Pressed"); if(isMidiMute() == false){ midiMuteButton.setIcon(new ImageIcon("icons/grey/Midi off.png")); SlideRenderer.muteBackground(); setMidiMute(true); }else if(isMidiMute() == true){ midiMuteButton.setIcon(new ImageIcon("icons/grey/Midi on.png")); SlideRenderer.unMuteBackground(); setMidiMute(false); } } else if(e.getSource() == muteAllButton){ // Test case if(Debug.sound)System.out.println("Mute All Button Pressed"); if(isAllMute() == false){ muteAllButton.setIcon(new ImageIcon("icons/grey/Sound off.png")); SlideRenderer.muteAll(); setAllMute(true); } else if(isAllMute() == true){ muteAllButton.setIcon(new ImageIcon("icons/grey/Sound on.png")); SlideRenderer.unMuteAll(); setAllMute(false); } } }
8
public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) return true; if (p == null && q != null) return false; if (p != null && q == null) return false; if (p.val != q.val) return false; return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); }
8
public int size() { return N; }
0
private void checkAnswer(){ if(tabIndex == 0){//Tab <code> TAB_MAIN </code> is chosen if(index == -1){ index++; setQuestion(); } String trueAnswer = words.get(index).getEWord().toLowerCase().trim(); String thisAnswer = answer.getText().toLowerCase().trim(); if (thisAnswer.equals(trueAnswer)&&(index<words.size())){ index++; setQuestion(); } progressBar.setValue(index); }else if(tabIndex == 1){//Tab <code>TAB_REPETITION</code> is chosen if(indRepet == -1){ indRepet++; setQuestion(); } String trueAnswer = repetitionWords.get(indRepet).getEWord().toLowerCase().trim(); String thisAnswer = answer.getText().toLowerCase().trim(); if (thisAnswer.equals(trueAnswer)&&(indRepet<repetitionWords.size())){ indRepet++; setQuestion(); } progressBar.setValue(indRepet); } }
8
public static MapleReactorStats getReactor(int rid) { MapleReactorStats stats = reactorStats.get(Integer.valueOf(rid)); if (stats == null) { int infoId = rid; MapleData reactorData = data.getData(StringUtil.getLeftPaddedStr(Integer.toString(infoId) + ".img", '0', 11)); MapleData link = reactorData.getChildByPath("info/link"); if (link != null) { infoId = MapleDataTool.getIntConvert("info/link",reactorData); stats = reactorStats.get(Integer.valueOf(infoId)); } if (stats == null) { reactorData = data.getData(StringUtil.getLeftPaddedStr(Integer.toString(infoId) + ".img", '0', 11)); MapleData reactorInfoData = reactorData.getChildByPath("0/event/0"); stats = new MapleReactorStats(); if (reactorInfoData != null) { boolean areaSet = false; int i = 0; while (reactorInfoData != null) { Pair<Integer,Integer> reactItem = null; int type = MapleDataTool.getIntConvert("type",reactorInfoData); if (type == 100) { //reactor waits for item reactItem = new Pair<Integer,Integer>(MapleDataTool.getIntConvert("0",reactorInfoData),MapleDataTool.getIntConvert("1",reactorInfoData)); if (!areaSet) { //only set area of effect for item-triggered reactors once stats.setTL(MapleDataTool.getPoint("lt",reactorInfoData)); stats.setBR(MapleDataTool.getPoint("rb",reactorInfoData)); areaSet = true; } } byte nextState = (byte)MapleDataTool.getIntConvert("state",reactorInfoData); stats.addState((byte) i, type, reactItem, nextState); i++; reactorInfoData = reactorData.getChildByPath(i + "/event/0"); } } else { //sit there and look pretty; likely a reactor such as Zakum/Papulatus doors that shows if player can enter stats.addState((byte) 0, 999, null, (byte) 0); } reactorStats.put(Integer.valueOf(infoId), stats); if (rid != infoId) { reactorStats.put(Integer.valueOf(rid), stats); } } else { // stats exist at infoId but not rid; add to map reactorStats.put(Integer.valueOf(rid), stats); } } return stats; }
8
public static String escape(String string) { StringBuffer sb = new StringBuffer(); for (int i = 0, length = string.length(); i < length; i++) { char c = string.charAt(i); switch (c) { case '&': sb.append("&amp;"); break; case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '"': sb.append("&quot;"); break; case '\'': sb.append("&apos;"); break; default: sb.append(c); } } return sb.toString(); }
6