method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
b9332bea-a232-425d-9211-46a6c0f18a02
2
void loadProject(File folder) { if (!folder.exists()) { return; } workCombo.addItem(new FileDisplayer(folder)); File simDir = new File(folder, SIMULATION_DIR); openChooser.setCurrentDirectory(simDir.exists() ? simDir : folder); currWork = folder; enableProjectControls(true); workCombo.setSelectedIndex(workCombo.getItemCount() - 1); }
84f4d510-b4cd-44f7-9268-25fee0c4810b
1
public byte[] getByteArray( String name ){ XAttribute attribute = getAttribute( name ); if( attribute == null ) throw new XException( "no attribute known with name: " + name ); return attribute.getByteArray(); }
e71fbd64-4ee3-41c1-92fc-02802f431bb1
6
public void repeat(int dist, int len) throws IOException { if (dist < 0 || dist >= full) throw new CorruptedInputException(); int left = Math.min(limit - pos, len); pendingLen = len - left; pendingDist = dist; int back = pos - dist - 1; if (dist >= pos) back += buf.length; do { buf[pos++] = buf[back++]; if (back == buf.length) back = 0; } while (--left > 0); if (full < pos) full = pos; }
a7ff4dcd-acbb-4f9a-ba88-c980787779b7
7
public Set<String> parse(URL pageUrl, Reader reader, String encoding) throws IOException { if (pageUrl == null || reader == null) { throw new IllegalArgumentException("reader an pageUrl shouldn't be null"); } MyHTMLEditorKit kit = new MyHTMLEditorKit(); HTMLEditorKit.Parser parser = kit.getParser(); PageParserCallback callback = new PageParserCallback(); parser.parse(reader, callback, true); HashSet<String> links = new HashSet<>(callback.getLinks().size()); // According to http://www.w3.org/TR/html51/document-metadata.html#the-base-element // it is possible to have relative URL in href attribute of <base> tag. URL baseUrl = makeAbsolute(pageUrl, callback.getBaseLink()); for (String link : callback.getLinks()) { URL url = makeAbsolute(baseUrl, link); // Collect only http links if (url != null) { if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https")) { continue; } url = UrlNormalizer.normalizeURL(url, encoding); } if (url != null) { links.add(url.toString()); } // TODO(Dyatlov): add statistics } return links; }
5a8967f8-184c-4654-a70d-1150a7ce2fae
1
public static String longToStringZeroForEmpty(Long timeLong) { final Long startTime = StringToLong("1970/01/01 09:00:00 000"); if (startTime == timeLong) { return ""; } return longToString(timeLong); }
d44f27cd-090f-4845-9f03-110b65eb0d61
4
private static void createAndShowGUI() { JButton crop = new JButton("Crop"); JFrame frame = new JFrame("Crop image"); JButton load = new JButton("Load"); Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault()); JPanel panel = null; try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); } catch (Exception e) { System.out.println("Could not change the look and feel"); } fileopen = new JFileChooser(String.format("%s/Pictures/%d-%02d/original/", System.getProperty("user.home"), localCalendar.get(Calendar.YEAR), localCalendar.get(Calendar.MONTH) + 1)); filesave = new JFileChooser(String.format("%s/Pictures/%d-%02d/", System.getProperty("user.home"), localCalendar.get(Calendar.YEAR), localCalendar.get(Calendar.MONTH) + 1)); try { panel = new CropImage(); } catch (IOException ioe) { System.out.println("Could not create the panel"); ioe.printStackTrace(); System.exit(1); } initCrop(crop, panel); initLoad(load, panel); if (!USE_PACK) { frame.setLayout(null); crop.setBounds( 10, imageHeight + 10, 80, 30); load.setBounds( 110, imageHeight + 10, 80, 30); imageInfo.setBounds( 10, imageHeight + 50, 500, 30); selectInfo.setBounds(10, imageHeight + 90, 500, 30); frame.setSize(imageWidth + 10, imageHeight + 160); } frame.add(panel); frame.add(crop); frame.add(load); frame.add(imageInfo); frame.add(selectInfo); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); if (USE_PACK) { frame.pack(); } frame.setVisible(true); }
8e9dde7b-10b6-4aea-a232-55a60b51a18e
1
private void toAndroid_adbMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toAndroid_adbMenuActionPerformed try { adbController.rebootDevice(selectedDevice, RebootTo.ANDROID); } catch (IOException ex) { logger.log(Level.ERROR, "An error occurred while rebooting device " + selectedDevice.getSerial() + " to Android: " + ex.toString() + "\n" + "The error stack trace will be printed to the console..."); ex.printStackTrace(System.err); } }//GEN-LAST:event_toAndroid_adbMenuActionPerformed
2f4d5ea4-abae-445f-be06-d1164ce0113b
3
public String getDescription() { String input = getInputToRead(); if (input.length() == 0) input = Universe.curProfile.getEmptyString(); String toPop = getStringToPop(); if (toPop.length() == 0) toPop = Universe.curProfile.getEmptyString(); String toPush = getStringToPush(); if (toPush.length() == 0) toPush = Universe.curProfile.getEmptyString(); return input + " , " + toPop + " ; " + toPush; }
e3c12d62-9eb9-4862-9d27-6223c957dc71
4
@Override public boolean pieceMovement(Point startPosition, Point endPosition) { Point difference = new Point(); difference.setLocation(endPosition.getX() - startPosition.getX(), endPosition.getY() - startPosition.getY()); if((Math.abs(difference.getX()) == 2 && Math.abs(difference.getY()) == 1) || (Math.abs(difference.getX()) == 1 && Math.abs(difference.getY()) == 2)){ return true; } return false; }
656c6719-5359-4a54-93d2-6c6a2e0e9f02
7
public boolean revert() { if (type instanceof Reaction.A2_B2__2AB) { Reaction.A2_B2__2AB r = (Reaction.A2_B2__2AB) type; r.moleFractionA2().setPointer(0); r.moleFractionB2().setPointer(0); r.moleFractionAB().setPointer(0); r.numberOfA2().setPointer(0); r.numberOfB2().setPointer(0); r.numberOfAB().setPointer(0); } else if (type instanceof Reaction.A2_B2_C__2AB_C) { Reaction.A2_B2_C__2AB_C r = (Reaction.A2_B2_C__2AB_C) type; r.moleFractionA2().setPointer(0); r.moleFractionB2().setPointer(0); r.moleFractionAB().setPointer(0); r.numberOfA2().setPointer(0); r.numberOfB2().setPointer(0); r.numberOfAB().setPointer(0); r.numberOfC().setPointer(0); } else if (type instanceof Reaction.O2_2H2__2H2O) { Reaction.O2_2H2__2H2O r = (Reaction.O2_2H2__2H2O) type; r.moleFractionH2().setPointer(0); r.moleFractionO2().setPointer(0); r.moleFractionH2O().setPointer(0); r.numberOfH2().setPointer(0); r.numberOfO2().setPointer(0); r.numberOfH2O().setPointer(0); } bonds.getBondQueue().setPointer(0); for (int i = 0; i < numberOfAtoms; i++) atom[i].moveRadicalPointer(0); List list = stateHolder.getBonds(); if (list == null) return false; synchronized (bonds.getSynchronizationLock()) { for (Iterator it = bonds.iterator(); it.hasNext();) ((RadialBond) it.next()).destroy(); } bonds.clear(); RadialBond.Delegate rbd = null; RadialBond rBond = null; for (Iterator it = list.iterator(); it.hasNext();) { rbd = (RadialBond.Delegate) it.next(); rBond = new RadialBond.Builder(atom[rbd.getAtom1()], atom[rbd.getAtom2()]).bondLength(rbd.getBondLength()) .bondStrength(rbd.getBondStrength()).chemicalEnergy(rbd.getChemicalEnergy()).build(); rBond.setModel(this); bonds.add(rBond); } MoleculeCollection.sort(this); return super.revert(); }
56a0b873-6461-4bfb-8b83-17e35f49932c
5
private int getPrecedence() { int precedence = 0; //All other symbols are precedence 0 switch (operatorSymbol) { case '+': case '-': precedence = 1; break; case '*': case '/': precedence = 2; break; case '^': precedence = 3; break; } return precedence; }
ea8a7c61-0610-4df7-8f7c-524c68225840
5
public void createIndex() { Segmenter seg = new Segmenter(); WordsFilter filter = new WordsFilter(); List<CoreLabel> words; ResultSet resultSet = null; String query = "select distinct indexid from dblpcitation union select distinct citationid from dblpcitation;"; ResultSet rs = sqLconnection.Query(query); try { String insert = "insert into TermInfos(term,indexid,pos) values(?,?,?)"; int count = 0; PreparedStatement statement = sqLconnection.conn .prepareStatement(insert); while (rs.next()) { int index = rs.getInt("indexid"); query = "select title,abstract from dblpbase where indexid=" + index; resultSet = sqLconnection.Query(query); resultSet.next(); String content = resultSet.getString("title"); content += " " + resultSet.getString("abstract"); words = seg.TokenAPI(content); for (int i = 0; i < words.size(); i++) { String word = words.get(i).toString().toLowerCase(); if (!filter.result(word).equals("")) { statement.setString(1, word); statement.setInt(2, index); statement.setInt(3, i); statement.addBatch(); } } if (count % 10000 == 0) { System.out.println("current number: " + count); statement.executeBatch(); statement.clearBatch(); resultSet = null; words.clear(); query = null; } count++; } statement.executeBatch(); sqLconnection.disconnectMySQL(); } catch (SQLException e) { e.printStackTrace(); } }
c5a6e235-4c10-402e-9679-80d4082fad8b
5
@Override public boolean isValid() { boolean isValid = this.no_of_files >=0 && toDownloadFiles != null && maxFileSizes != null && toDownloadFiles.size() == maxFileSizes.size() && toDownloadFiles.size() == this.no_of_files; if(!isValid) { //TODO: cleanup //Do clean up if required } return isValid; }
d9fbc587-7908-49a9-b86d-fd1969c14475
7
@Override public Computer find(long id) { // TODO Auto-generated method stub String query = "SELECT * FROM computer WHERE id="+id; ResultSet results = null; Connection connect = ConnectionMySql.getInstance(); Computer computer = null; try (Statement stmt = connect.createStatement()){ results = stmt.executeQuery(query); computer = new Computer(); while (results.next()) { computer.setId(results.getLong("id")); computer.setName(results.getString("name")); computer.setIntroduced(results.getDate("introduced")); computer.setDiscontinued(results.getDate("discontinued")); long company_id = results.getLong("company_id"); if (company_id!=0) { Company company = CompanyDAO.getInstance().find(company_id); computer.setCompany(company); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (connect!=null) { try { connect.close(); } catch (SQLException e) {} } if (results!=null) { try { results.close(); } catch (SQLException e) {} } } return computer; }
931a2165-db89-4ca1-91ff-3d234ece2ea3
1
public String moveCardOntoTopRowFromRow(int boardIndexFrom, int boardIndexTo) { List<Card> from = topRow.get(boardIndexFrom); String result = moveCardOntoTopRow(from, boardIndexTo, from.size()-1); if (result.isEmpty()) { from.remove(from.size() - 1); } return result; }
00877990-0cb1-4281-ae88-9dad1c1d057a
2
@Override protected AFUNIXOutputStream getOutputStream () throws IOException { if ( !this.connected && !this.bound ) { throw new IOException("Not connected/not bound"); } return this.out; }
65cd27a5-8f14-43f6-b0e4-664d22ac3657
7
private void updateHistogram() { int red, green, blue; double max_red = FindPeak(img_red); double max_green = FindPeak(img_green); double max_blue = FindPeak(img_blue); double max_alpha = FindPeak(img_alpha); max_red = Math.pow(max_red, gradient); max_green = Math.pow(max_green, gradient); max_blue = Math.pow(max_blue, gradient); max_alpha = Math.pow(max_alpha, gradient); for (int i = 0; i < ximlen; i++) { for (int j = 0; j < yimlen; j++) { if (byStructure) { if (img_alpha[i][j] > 0) { double z = Math.pow(img_alpha[i][j], gradient) / max_alpha; red = (int) (img_red[i][j] * z * brightness / img_alpha[i][j]); green = (int) (img_green[i][j] * z * brightness / img_alpha[i][j]); blue = (int) (img_blue[i][j] * z * brightness / img_alpha[i][j]); } else { red = 0; green = 0; blue = 0; } } else { red = (int) ((brightness * Math.pow(img_red[i][j], gradient) / max_red) * 255); green = (int) ((brightness * Math.pow(img_green[i][j], gradient) / max_green) * 255); blue = (int) ((brightness * Math.pow(img_blue[i][j], gradient) / max_blue) * 255); } if (red > 255) red = 255; if (green > 255) green = 255; if (blue > 255) blue = 255; red = red << 16; green = green << 8; int newcolor = 0xff000000 | (red & 0x00ff0000) | (green & 0x0000ff00) | (blue & 0xff); ; pixels[j * ximlen + i] = newcolor; } } graph.drawImage(tools.createImage(screenMem), 0, 0, null); }
76f753d5-d8b2-4766-9512-c1f1c46280e2
1
public String getValue(int place) throws NotExist { ListElement current = head; for (int i = 1; i < place; i++) { current = current.next(); } return current.getValue(); }
f84678d2-e660-415c-8251-0907203d8ea2
3
public static void count1Number(int n){ int count = 0; int factor = 1; int cur = 0; int high = 0; int low = 0; while(n / factor != 0){ low = n - (n / factor ) * factor; cur = (n / factor) % 10; high = n / factor / 10 ; if(cur == 0){ count += (high) * factor; } else if(cur == 1){ count += high * factor + low + 1; } else{ count += (high + 1)*factor; } factor *= 10; } System.out.println(count); }
00d79060-4fb1-40de-89a1-2e59a5248657
6
public void updateToSlide() { if(imageFlow != null) { if(panel.isVisible()){ try{ imageFlow.scrollAndAnimateTo(Engine.getCurrentSlideID() - 1); } catch(NullPointerException e){} catch(IndexOutOfBoundsException e){} } else{ try{ imageFlow.setSelectedIndex(Engine.getCurrentSlideID() - 1); } catch(NullPointerException e){} catch(IndexOutOfBoundsException e){} } } }
dab382bc-c6ce-44f2-8a1a-2ea95e80320a
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); }
ad920539-40f6-4eed-b91e-f0bb7d7bec25
5
public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int[] charCount = new int[33]; //алфавит ArrayList<Character> alphabet = new ArrayList<Character>(); for(int i=0;i<32;i++) { alphabet.add( (char) ('а'+i)); } alphabet.add(6,'ё'); //ввод строк ArrayList<String> list = new ArrayList<String>(); for(int i=0;i<10;i++) { String s = reader.readLine(); list.add( s.toLowerCase()); } TreeMap<Character, Integer> map = new TreeMap<>(); // for (String s : list) { // char[] array = s.toCharArray(); // for (int i = 0; i < array.length; i++) { // for (int j = 0; j < alphabet.size(); j++) { // if (array[i] == alphabet.get(j) && map.containsKey(alphabet.get(j))) { // map.put(alphabet.get(j), map.get(alphabet.get(j)) + 1); // } // else if (array[i] == alphabet.get(j) && !map.containsKey(alphabet.get(j))) { // map.put(alphabet.get(j), 1); // } // // else if (array[i] != alphabet.get(j) && map.containsKey(alphabet.get(j))) { // continue; // } // else { // map.put(alphabet.get(j), 0); // } // // } // } // } for (int i = 0; i < list.size();i++) { char[] nextString = list.get(i).toCharArray(); for (int j = 0; j < nextString.length; j++) { int index = alphabet.indexOf(nextString[j]); //умно. просто для каждого символа в каждой строке, получаем его индекс в алфавите и увеличиваем количество по соответствующему индексу в массиве. charCount[index]++; } } for (int i = 0; i < charCount.length; i++) { System.out.println(alphabet.get(i) + " " + charCount[i]); } // for (Map.Entry<Character, Integer> pair : map.entrySet()) // { // System.out.println(pair.getKey() + " " + pair.getValue()); // } }
3d94c351-190f-4df2-a33a-77b76a8a4b36
9
public void move() { if (type.equals("Quade") || type.equals("Hail")) { x += MISSILE_SPEED; distance++; if (distance >= 150) { visible = false; } //when quade powers up, this code activates his super energyballs if (type.equals("Quade")) { if (Game.p.getpowUp()) { if (Game.p.right) { img = new ImageIcon(Player.PATHWAY + "2D Fighter Quade Folder (Sprites and Shit)\\Random Game Things\\superenergyball.gif").getImage(); } else { img = new ImageIcon(Player.PATHWAY + "2D Fighter Quade Folder (Sprites and Shit)\\Random Game Things\\superenergyball.gif").getImage(); } } } else { //likewise for hail's super ice bolts if (Game.p.getpowUp2()) { if (Game.p.right2) { img = new ImageIcon(Player.PATHWAY + "2D Fighter Quade Folder (Sprites and Shit)\\Random Game Things\\supericeballrt.gif").getImage(); } else { img = new ImageIcon(Player.PATHWAY + "2D Fighter Quade Folder (Sprites and Shit)\\Random Game Things\\supericeball.gif").getImage(); } } } } else { y += MISSILE_SPEED; if (y >= 600) { visible = false; } } }
8aa54599-b3f3-4363-ab51-455f49871db6
9
public static int hg_step4(int step, double[][] cost, int[][] mask, int[] rowCover, int[] colCover, int[] zero_RC) { System.out.println("STEP 4"); //What STEP 4 does: //Find an uncovered zero in cost and prime it (if none go to step 6). Check for star in same row: //if yes, cover the row and uncover the star's column. Repeat until no uncovered zeros are left //and go to step 6. If not, save location of primed zero and go to step 5. // EdgeSet es = new EdgeSet(); // currEdges = new EdgeSet(); /*if(true){/*/if(cameFromStep6 == true){ // adds n^2 cost, so only practical for small values of n. EdgeSet es = new EdgeSet(); for(int i = 0; i < cost.length; i++){ for(int j = 0; j < cost[0].length; j++){ if(cost[i][j] == 0){ if(mask[i][j] == 1){ es.add(new Edge(i, j, Edge.Direction.fromSeller)); // might be j,i... } else {//if(mask[i][j] != 0 && cost[i][j] == 0){ es.add(new Edge(i, j, Edge.Direction.fromBuyer)); // might be j,i... } } } } //es = currEdges.clone(); // uncomment for non-incremental display es.add((ArrayList<Float>) q.clone(), (ArrayList<Float>) p.clone()); esq.push(es); // uncomment for non-incremental display cameFromStep6 = false; } int[] row_col = new int[2]; //Holds row and col of uncovered zero. boolean done = false; while (done == false) { row_col = findUncoveredZero(row_col, cost, rowCover, colCover); if (row_col[0] == -1) { done = true; step = 6; } else { mask[row_col[0]][row_col[1]] = 2; //Prime the found uncovered zero. // currEdges.add(new Edge(row_col[0], row_col[1], Edge.Direction.fromBuyer)); // es = currEdges.clone(); // uncomment for incremental display // esq.push(es); // uncomment for incremental display boolean starInRow = false; for (int j=0; j<mask[row_col[0]].length; j++) { if (mask[row_col[0]][j]==1) //If there is a star in the same row... { starInRow = true; row_col[1] = j; //remember its column. } } if (starInRow==true) { rowCover[row_col[0]] = 1; //Cover the star's row. colCover[row_col[1]] = 0; //Uncover its column. } else { zero_RC[0] = row_col[0]; //Save row of primed zero. zero_RC[1] = row_col[1]; //Save column of primed zero. done = true; step = 5; } }
8de8e5e4-3f2c-46b0-aa24-97dc18842d1e
8
public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { if (!(value instanceof LogEntry)) return new JLabel(); final LogEntry wlr = (LogEntry) value; final JTextArea result = new JTextArea(wlr.formatted); result.setComponentOrientation(list.getComponentOrientation()); result.setFont(list.getFont()); result.setBorder(cellHasFocus || isSelected ? SELECTED_BORDER : EMPTY_BORDER); result.setForeground(Color.WHITE); result.setBackground(BACKGROUND); if (wlr.record.getLevel() == Level.SEVERE) { result.setForeground(Color.red.darker()); } if (wlr.record.getLevel() == Level.WARNING) { result.setForeground(Color.WHITE); } if ((wlr.record.getLevel() == Level.FINE) || (wlr.record.getLevel() == Level.FINER) || (wlr.record.getLevel() == Level.FINEST)) { result.setForeground(Color.WHITE); } return result; }
579d4546-6e86-4b97-b332-8771f1c81a9f
3
@Test public void containsWorks() { boolean test = true; for (int i = 0; i < 1000; i++) { tree.clear(); for (int j = 0; j < 1000; j++) tree.add(j); int r = (int)(Math.random() * 1000); if (!tree.contains(r)) { test = false; break; } } assertTrue(test); }
96fbde5b-5c21-4ec7-8d44-1d22f9b27266
8
public boolean set( int row, int column, int value ){ boolean flag = (0 <= row && row < DIGITS && 0 <= column && column < DIGITS && 0 < value && value <= DIGITS && board[row][column] == 0); if( flag ){ board[row][column] = value; flag = valid(); if( !flag ){ board[row][column] = 0; } } return flag; }
84b01d52-4c8e-4332-afd7-9e75858af31a
4
public void exit(){ int opt = JOptionPane.showConfirmDialog(this, AimConstants.CLOSE_MESSAGE); if (opt == JOptionPane.OK_CANCEL_OPTION) return; if (opt == JOptionPane.NO_OPTION) return; if (opt == JOptionPane.CLOSED_OPTION) return; if(opt == JOptionPane.YES_OPTION){ // TODO, Save transactions if any and release of resource } dispose(); }
9cc00330-8147-4dfd-918a-c441ef59dbe9
3
public void run() { ultimaEscritura(nombre); while (s >= 0) { if (s == 0) { cont--; System.out.println(nombre + " - " + s + " - ultima escritura" + IDanterior); System.out.println("ultima escritura " + nombre + " - " + cont + " Threads activos"); } else { System.out.println(nombre + " - " + s + " - ultima escritura" + IDanterior); } try { Thread.sleep(1000); } catch (InterruptedException interruptedException) { System.out .println("First Thread is interrupted when it is sleeping" + interruptedException); } ultimaEscritura(nombre); s--; } }
2b71e989-f93a-4bb7-a695-8215950033d1
7
private void xmlBuildFloatingNode(NodeList dockables, Rectangle bounds) throws SAXException { // @todo not optimal.. we should refactor it oustide this method Window desktopWindow = SwingUtilities.getWindowAncestor(this); if (desktopWindow != null) { Point windowLocation = desktopWindow.getLocation(); bounds.x += windowLocation.x; // position is relative bounds.y += windowLocation.y; } // JDialog dialog = null; FloatingDockableContainer fdc = null; TabbedDockableContainer tdc = null; if (dockables.getLength() > 1) { // it's a floating tab tdc = DockableContainerFactory.getFactory() .createTabbedDockableContainer(); tdc.installDocking(this); ((JTabbedPane) tdc).addChangeListener(focusHandler); // our best way // to track // selection // (focus) // changes } Dockable baseDockable = null; // used when there are tabs for (int i = 0; i < dockables.getLength(); i++) { Element dockableElt = (Element) dockables.item(i); Element hideElt = (Element) dockableElt.getElementsByTagName( "RelativePosition").item(0); float x = Float.parseFloat(hideElt.getAttribute("x")); float y = Float.parseFloat(hideElt.getAttribute("y")); float w = Float.parseFloat(hideElt.getAttribute("w")); float h = Float.parseFloat(hideElt.getAttribute("h")); RelativeDockablePosition position = new RelativeDockablePosition( dockingPanel, x, y, w, h); Dockable dockable = xmlGetDockable(dockableElt); if (i == 0) { baseDockable = dockable; } Element previousState = (Element) dockableElt.getElementsByTagName( "PreviousState").item(0); int istate = Integer.parseInt(previousState.getAttribute("state")); DockableState state = new DockableState(this, dockable, DockableState.getLocationFromInt(istate), position); storePreviousFloatingState(dockable, state); if (fdc == null) { // if (dialog == null}){ // dialog = (JDialog) createFloatingDockableContainer(dockable); fdc = createFloatingDockableContainer(dockable); } else { // add as a tab if (tdc.getTabCount() == 0) { // first tab : replace the current DetachedDockView by the // tab container // not very efficient... @todo : sort this out DockableContainer base = DockingUtilities .findDockableContainer(baseDockable); DockingUtilities.replaceChild( ((Component) base).getParent(), (Component) base, (Component) tdc); tdc.addDockable(baseDockable, 0); } tdc.addDockable(dockable, tdc.getTabCount()); } context.setDockableState(dockable, new DockableState(this, dockable, DockableState.Location.FLOATING, position)); dockable.getDockKey().setLocation(DockableState.Location.FLOATING); if (dockable instanceof CompoundDockable) { // check for children and build them xmlBuildCompoundDockable((CompoundDockable) dockable, dockableElt, DockableState.Location.FLOATING); } } DockingUtilities.setBounds(fdc, bounds); // dialog.setBounds(bounds); // dialog.validate(); // dialog.setVisible(true); DockingUtilities.validate(fdc); DockingUtilities.setVisible(fdc, true); }
bf864d01-d626-4d97-b82c-b34ad9cf3ac8
7
@Override public void move(int dx,int dy){ if(x+dx>=Level.SIZE || y+dy>=Level.SIZE || x+dx<=0 || y+dy<=0 || (l.world[x+dx][y+dy] != TileType.AIR && l.world[x+dx][y+dy] != TileType.FIRE && l.world[x+dx][y+dy] != TileType.TORCH)){ l.worldDamage[x+dx][y+dy]-=1; }else{ x+=dx; y+=dy; } }
97e34844-687e-4c17-a395-462ffd4ddbcd
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Foul other = (Foul) obj; if (fouler == null) { if (other.fouler != null) return false; } else if (!fouler.equals(other.fouler)) return false; if (target == null) { if (other.target != null) return false; } else if (!target.equals(other.target)) return false; return true; }
c3a841a9-d204-4bc4-addd-7acd2b5f6c20
9
private void calculaTipoPagamento() { PedidoDao pDao = new PedidoDao(); pDao.abreConnection(); List<Pedido> pedidos = pDao.listaPedidosPorCaixa(caixa.getIdCaixa()); pDao.fechaConnection(); if (pedidos != null && !pedidos.isEmpty()) { double totalDinheiro = 0; double totalCredito = 0; double totalDebito = 0; double totalVale = 0; FormaPagamentoDao fpDao = new FormaPagamentoDao(); for (int i = 0; i < pedidos.size(); i++) { fpDao.abreConnection(); if ("Finalizado".equals(pedidos.get(i).getEstadoPedido())) { FormaPagamento fp; fp = fpDao.listaFormaPagamentoPorId(pedidos.get(i).getIdFormaPgto()); if ("Dinheiro".equals(fp.getTipoFormaPgto())) { totalDinheiro = totalDinheiro + pedidos.get(i).getTotPedido(); qtdPedDinheiro += 1; } else if ("Credito".equals(fp.getTipoFormaPgto())) { totalCredito = totalCredito + pedidos.get(i).getTotPedido(); qtdPedCred += 1; } else if ("Debito".equals(fp.getTipoFormaPgto())) { totalDebito = totalDebito + pedidos.get(i).getTotPedido(); qtdPedDeb += 1; } else if ("Vale".equals(fp.getTipoFormaPgto())) { totalVale = totalVale + pedidos.get(i).getTotPedido(); qtdPedVale += 1; } if (pedidos.get(i).getDescPedido() > 0) { descontoTotal += pedidos.get(i).getDescPedido(); qtdPedDesc += 1; } caixa.setTotalCaixa(caixa.getTotalCaixa() + pedidos.get(i).getTotPedido()); } else { qtdPedCanc += 1; } fpDao.fechaConnection(); } textoValorDinheiro.setText(String.format("R$: %.2f", totalDinheiro)); textoValorCartaoDeCredito.setText(String.format("R$: %.2f", totalCredito)); textoValorCartaoDeDebito.setText(String.format("R$: %.2f", totalDebito)); textoValorValeRefeicao.setText(String.format("R$: %.2f", totalVale)); } else { textoValorDinheiro.setText("R$: 0,00"); textoValorCartaoDeCredito.setText("R$: 0,00"); textoValorCartaoDeDebito.setText("R$: 0,00"); textoValorValeRefeicao.setText("R$: 0,00"); } }
91f6bed9-211e-4843-954f-28fcd6169b47
0
public static void main(String[] args) { int a = 0, b = 1; System.out.println(a == b); // false System.out.println(a != b); // true System.out.println(a < b); // true System.out.println(a <= b); // true System.out.println(a >= b); // false }
2a718d5d-d716-41f2-8c45-0f9da4ebf9b3
1
public float getImageHeight() { if(texture != null) { return (float)texture.getImageHeight(); } else { System.err.print("RoyalFlush: Texture2D.getImageHeight - No texture has been loaded.\n"); return -1.0f; } }
db5fd225-d6e6-4b71-a578-74e67a7054e4
4
public String execute() throws CrashException { try { Registry registry = LocateRegistry.getRegistry(destPeer.IPaddr, destPeer.serverPortno); ServerSideInterface stub = (ServerSideInterface) registry.lookup("ServerSide"); return stub.ElectionSetTurnHolder(this.turnHolder); } catch (java.rmi.ConnectException e) { System.out.println("Msg TurnHolder Fallito. QUESTO PEER E' MORTO!"); } catch (java.rmi.ConnectIOException e) { System.out.println("Msg TurnHolder Fallito. QUESTO PEER E' MORTO!"); } catch (java.rmi.UnmarshalException e) { System.out.println("Msg TurnHolder Fallito. QUESTO PEER E' MORTO!"); } catch (Exception e) { e.printStackTrace(); System.exit(1); } throw new CrashException("Impossibile inviare messaggio!"); }
072f3023-8ee1-4f8b-ab12-2593a1e997a2
0
@Override public String getEmail() { return super.getEmail(); }
1a3ea40f-1ba5-4656-949b-6a47ec2c2cd4
5
public void run() { // Applies the running state, and notifies all listeners that the // service has started. notifier.proxy().onServiceStart(this); // While the service is in a runnable state... while (!stopped) { boolean valid = true; // If event processing is active... if (activeEvents) { valid &= invokeEvents(valid); } // If execution is active... if (activeExecute) { valid &= invokeExecute(valid); } // Adjust validation based on remaining iterations valid &= (remainingIterations == -1 || --remainingIterations > 0); // If the service state is not valid, stop service. if (!valid) { stopped = true; } } // Applies the stopped state, and notifies all listeners that the // service has stopped. state.set(Stopped); notifier.proxy().onServiceStop(this, interrupt); }
376b5a3d-a932-4941-8ade-33efe22bfa20
1
public void registerResource(Resource r) { if (!resources.containsKey(r.getId())) { resources.put(r.getId(), r); } }
98816d7b-0545-4be3-8dbe-19ed76a5b937
0
public Worker () { //initial settings results = new int[VALUE_ITERATIONS_NUMBER]; this.keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println(MSG_WELCOME); //start this.lifeCycle(); }
992d650b-acd7-4fd7-b036-893a502b9483
3
public void actionPerformed(ActionEvent e) { String[] args = getArgs(e); String channel = args[0]; String sender = args[1]; String source = args[2]; String message = args[3]; if (isCommand("agdq", message)) { if (acebotCore.hasAccess(channel, sender, channelAccess, userAccess, accessExceptionMap)) { if (message.substring(1).equals("agdq")) { Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); start.set(2016, Calendar.JANUARY, 3, 11, 0, 0); SimpleDateFormat sdf = new SimpleDateFormat("y M d H m s"); String date = sdf.format(new Date()); System.out.println(date); end.set(Integer.parseInt(date.split(" ")[0]), Integer.parseInt(date.split(" ")[1]), Integer.parseInt(date.split(" ")[2]), Integer.parseInt(date.split(" ")[3]), Integer.parseInt(date.split(" ")[4]), Integer.parseInt(date.split(" ")[5])); long milliseconds1 = start.getTimeInMillis(); long milliseconds2 = end.getTimeInMillis(); long diff = milliseconds1 - milliseconds2; long diffDays = (int)(diff / (1000 * 60 * 60 * 24)); //String timeStr = diffHrs + " hours, " + diffMins + " minutes"; /*start.add(Calendar.DAY_OF_MONTH, (int)diffDays); while (start.before(end)) { start.add(Calendar.DAY_OF_MONTH, 1); diffDays++; } while (start.after(end)) { start.add(Calendar.DAY_OF_MONTH, -1); diffDays--; } */ acebotCore.addToQueue(channel, "AGDQ 2016 is live at twitch.tv/gdq - Schedule at https://gamesdonequick.com/schedule", Integer.parseInt(source)); } } } }
5574c30c-30ec-4778-b008-e690d974cc7f
3
private void copyAnimations() { standAnim = new Animation[PlayerEntity.STAND_ANIMATIONS.length]; for(int i = 0; i < PlayerEntity.STAND_ANIMATIONS.length; i++) standAnim[i] = PlayerEntity.STAND_ANIMATIONS[i].copy(); moveAnim = new Animation[PlayerEntity.MOVE_ANIMATIONS.length]; for(int i = 0; i < PlayerEntity.MOVE_ANIMATIONS.length; i++) moveAnim[i] = PlayerEntity.MOVE_ANIMATIONS[i].copy(); bumpAnim = new Animation[PlayerEntity.BUMP_ANIMATIONS.length]; for(int i = 0; i < PlayerEntity.BUMP_ANIMATIONS.length; i++) bumpAnim[i] = PlayerEntity.BUMP_ANIMATIONS[i].copy(); }
e6046e0e-e87c-4b74-b032-82106332c8e9
6
public static GamePhase makeGamePhase(PhaseTag tag, Player playerOne, Player playerTwo, Engine engine) { switch (tag) { case ATTENTION: return new AttentionGamePhase(playerOne, playerTwo, engine); case MEDITATE: return new MeditateGamePhase(playerOne, playerTwo, engine); case HEARTRATE_HIGH: return new HeartRateHighGamePhase(playerOne, playerTwo, engine); case HEARTRATE_LOW: return new HeartRateLowGamePhase(playerOne, playerTwo, engine); case PRESSURE: return new PressureGamePhase(playerOne, playerTwo, engine); case SQUEEZE: return new SqueezeGamePhase(playerOne, playerTwo, engine); default: return null; } }
3e76399d-fda3-477b-9fb4-cad9bbee923c
2
public boolean mouseWithin(int x, int y) { //System.out.println(rectAL.size()); for(int i = 0; i < rectAL.size(); i++) { // the "highness" of y is inversed due to top being considered y = 0 if(x >= rectAL.get(i).getULX() & x <= rectAL.get(i).getURX() & y <= rectAL.get(i).getDLY() & y >= rectAL.get(i).getULY()) { return true; } } return false; }
15ada54d-ebc8-4933-acdf-009d1ddf7faf
2
public void draw(Graphics2D g) { if(highlighted) g.setColor(Color.RED); else g.setColor(Color.BLACK); if(border) g.draw(theBox); g.drawString(text, X, Y+height/2); }
40d5d339-09e9-4e9c-a39b-999abad58bc6
2
public boolean doTransformations() { StructuredBlock last = flowBlock.lastModified; return super.doTransformations() || CombineIfGotoExpressions.transform(this, last) || CreateIfThenElseOperator.createFunny(this, last); }
8121b865-12b9-4f80-adc0-79d946408c71
9
static public void startMethod(int methodNumber, Object o, com.github.danfickle.cppToJavaRpcSvrLibrary.Connection conn) throws Exception { java.lang.Object internal = (java.lang.Object) o; switch (methodNumber) { case 1: { /* public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException */ long var0 = conn.wire.readlong(); internal.wait(var0); conn.wire.writeSuccess(); break; } case 2: { /* public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException */ long var0 = conn.wire.readlong(); int var1 = conn.wire.readint(); internal.wait(var0, var1); conn.wire.writeSuccess(); break; } case 3: { /* public final void java.lang.Object.wait() throws java.lang.InterruptedException */ internal.wait(); conn.wire.writeSuccess(); break; } case 4: { /* public boolean java.lang.Object.equals(java.lang.Object) */ java.lang.Object var0 = (java.lang.Object) conn.wire.readObject(); boolean ret = internal.equals(var0); conn.wire.writeSuccess(); conn.wire.writeboolean(ret); break; } case 5: { /* public java.lang.String java.lang.Object.toString() */ java.lang.String ret = internal.toString(); conn.wire.writeSuccess(); conn.wire.writeString(ret); break; } case 6: { /* public native int java.lang.Object.hashCode() */ int ret = internal.hashCode(); conn.wire.writeSuccess(); conn.wire.writeint(ret); break; } case 7: { /* public final native java.lang.Class<?> java.lang.Object.getClass() */ java.lang.Class ret = internal.getClass(); conn.wire.writeSuccess(); conn.wire.writeObject(ret); break; } case 8: { /* public final native void java.lang.Object.notify() */ internal.notify(); conn.wire.writeSuccess(); break; } case 9: { /* public final native void java.lang.Object.notifyAll() */ internal.notifyAll(); conn.wire.writeSuccess(); break; } default: { throw new NoSuchMethodException("Method " + methodNumber + " does not exist"); } } }
246d6e49-f7e9-43c0-9fe2-0b227e602a5e
7
static public String doubleToString(double d) { if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String s = Double.toString(d); if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { while (s.endsWith("0")) { s = s.substring(0, s.length() - 1); } if (s.endsWith(".")) { s = s.substring(0, s.length() - 1); } } return s; }
7edb44a6-8f92-4c20-995b-8079f6052137
1
public void visit_if_acmpne(final Instruction inst) { stackHeight -= 2; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } }
92f5fec9-6a71-4634-9454-99538f9339bf
8
private void startSocketHandler() { socketHandler = new Thread() { @Override public void run() { XMLStreamReader parser = connection.getParser(); try { while(socketHandler != null) { if(parser.next() != XMLStreamConstants.START_ELEMENT) continue; socketHandlerLatch = new CountDownLatch(1); postMessage(MessageType.STANZA, parser); socketHandlerLatch.await(); } } catch (XMLStreamException e) { //confirm if it is due to socket boolean disconnected = false; try { disconnected = connection.getSocket().getInputStream().read() == -1; } catch (IOException _) { disconnected = true; } if(disconnected) { try { postMessage(MessageType.DISCONNECTED); } catch (InterruptedException e1) { } } else { try { postMessage(MessageType.ERROR, e); } catch (InterruptedException e1) { } } } catch (InterruptedException _) { } } }; socketHandler.start(); }
87ca0fe7-6d91-47ef-adf4-b3e9e87e2166
9
public JSONObject getCityList(String filter, Integer countryCode, Integer regionCode, Integer limit, Integer offset, String orderBy, String direction) { StringBuilder uriBuilder = new StringBuilder("/api/getCityList?") ; log.debug("Setting API Token") ; uriBuilder.append("AUTH_TOKEN="+apiToken) ; if (filter!=null) { uriBuilder.append("&filter=").append(filter) ; } if (countryCode!=null) { uriBuilder.append("&countryCode=").append(countryCode) ; } if (regionCode!=null) { uriBuilder.append("&regionCode=").append(regionCode) ; } if (limit!=null) { uriBuilder.append("&limit=").append(limit) ; } if (offset!=null) { uriBuilder.append("&offset=").append(offset) ; } if (orderBy!=null) { uriBuilder.append("&order_by=").append(orderBy) ; } if (direction!=null) { if (direction.toLowerCase().contentEquals("ASC") || direction.toLowerCase().contentEquals("DESC")) { uriBuilder.append("&direction=").append(direction.toUpperCase()) ; } } return makeHttpRequest(uriBuilder.toString()) ; }
470d917a-9147-432a-85bf-478eb8b51a8c
5
private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed name=(String)jComboBox2.getSelectedItem(); try { try { try { try { try { // TODO add your handling code here: patientRemarks.setText(myLogicLayer.getHistory(name)); } catch (SQLException ex) { Logger.getLogger(PatientDiagnoseForm.class.getName()).log(Level.SEVERE, null, ex); } patientPrescription.setText(myLogicLayer.getPrescription(name)); } catch (SQLException ex) { Logger.getLogger(PatientDiagnoseForm.class.getName()).log(Level.SEVERE, null, ex); } patientRemarksEntry.setText(myLogicLayer.getHistory(name)); } catch (SQLException ex) { Logger.getLogger(PatientDiagnoseForm.class.getName()).log(Level.SEVERE, null, ex); } patientBStext.setText(myLogicLayer.getBloodSugarLevel(name)); } catch (SQLException ex) { Logger.getLogger(PatientDiagnoseForm.class.getName()).log(Level.SEVERE, null, ex); } patientBPLtext.setText(myLogicLayer.getBloodPressureLevel(name)); } catch (SQLException ex) { Logger.getLogger(PatientDiagnoseForm.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jComboBox2ActionPerformed
9ac8e982-fc4a-42f1-9d67-07ad680ee023
8
@Override public double getCategoryJava2DCoordinate(CategoryAnchor anchor, int category, int categoryCount, Rectangle2D area, RectangleEdge edge) { double result = 0.0; Rectangle2D adjustedArea = area; CategoryPlot plot = (CategoryPlot) getPlot(); CategoryItemRenderer renderer = plot.getRenderer(); if (renderer instanceof Effect3D) { Effect3D e3D = (Effect3D) renderer; double adjustedX = area.getMinX(); double adjustedY = area.getMinY(); double adjustedW = area.getWidth() - e3D.getXOffset(); double adjustedH = area.getHeight() - e3D.getYOffset(); if (edge == RectangleEdge.LEFT || edge == RectangleEdge.BOTTOM) { adjustedY += e3D.getYOffset(); } else if (edge == RectangleEdge.RIGHT || edge == RectangleEdge.TOP) { adjustedX += e3D.getXOffset(); } adjustedArea = new Rectangle2D.Double(adjustedX, adjustedY, adjustedW, adjustedH); } if (anchor == CategoryAnchor.START) { result = getCategoryStart(category, categoryCount, adjustedArea, edge); } else if (anchor == CategoryAnchor.MIDDLE) { result = getCategoryMiddle(category, categoryCount, adjustedArea, edge); } else if (anchor == CategoryAnchor.END) { result = getCategoryEnd(category, categoryCount, adjustedArea, edge); } return result; }
fd561da7-f7e5-4231-a454-229d034e5836
8
private RouteLabel labelReroute(int startNode, int endNode, int maxRisk){ // Initialization RouteLabel bestRoute = null; // Keeps track of so far best finishing label ArrayList<RouteLabel> activeLabels = new ArrayList<RouteLabel>(); // Keeps track of all labels RouteLabel initialLabel = new RouteLabel(startNode); // Starting base from start node activeLabels.add(initialLabel); int index = 0; // as long as there are more labels to explore while(activeLabels.size() > index){ // fetch current label RouteLabel currentLabel = activeLabels.get(index); // if current label has not been dominated by other label - explore it if(!currentLabel.isDominated()){ // expand current label along paths that is within max risk and not longer than current best complete path ArrayList<RouteLabel> newLabels = expand(currentLabel, maxRisk, bestRoute != null ? bestRoute.getCost() : Integer.MAX_VALUE); // for all resulting new labels for (RouteLabel newLabel : newLabels) { // try dominate against all labels in active labels this.dominateLabels(newLabel, activeLabels); // if new label was not it self dominated if(!newLabel.isDominated()){ // add label to list of active labels activeLabels.add(newLabel); // check if route is complete and if better than current best if(newLabel.getLastNode() == endNode && (bestRoute == null || newLabel.getCost() < bestRoute.getCost())){ bestRoute = newLabel; } } } } index++; } System.out.println(String.format(" - rerouting finished after expanding %,d labels", activeLabels.size())); return bestRoute; }
b355dce4-7089-4328-b3d7-f9c1c1189db7
9
@Override public boolean equals(final Object obj) { if (obj == null) return false; if (obj == this) return true; if (obj.getClass() != getClass()) return false; PartialCKDoor otherPCKDoor = (PartialCKDoor) obj; if (new EqualsBuilder() .append(isValid, otherPCKDoor.isValid) .append(isDouble, otherPCKDoor.isDouble) .isEquals()) { if (!isValid) //At this point both isValid and isDouble (in either instance) match their respective selves. return false; if (isDouble) { //The mumbo-jumbo here is cause both wool blocks could be flip-flopped in the different instances AND either wool block (in either instance) could be null. return ((woolBaseBlock.equals(otherPCKDoor.woolBaseBlock) || woolBaseBlock.equals(otherPCKDoor.otherWoolBaseBlock)) && (otherWoolBaseBlock.equals(otherPCKDoor.otherWoolBaseBlock) || otherWoolBaseBlock.equals(otherPCKDoor.woolBaseBlock))); } else { return (woolBaseBlock.equals(otherPCKDoor.woolBaseBlock)); } } return false; }
2e422b96-eefb-4491-b54f-c517be9dae79
1
public void attacked(int dmg) { subtractHitpoints(dmg); if (getHitpoints() <= 0) { setToDead(); // tower.addKills(1); } }
1143e529-a263-4b22-a9b7-ddbce0611c02
4
public static void main(String[] args) { long start = System.nanoTime(); int count = 0; for (int i = 1; i <= 10000; i++) { BigInteger newNum = BigInteger.valueOf(i); boolean isLychrel = true; for (int k = 0; k < 50; k++) { newNum = reverseAdd(newNum); if (isPalindromic(newNum)) { isLychrel = false; } } if (isLychrel) { count += 1; } } System.out.println(count); System.out.println("Done in " + (double) (System.nanoTime() - start) / 1000000000 + " seconds."); }
beddf6cc-bdf0-4ddd-bca8-1e3e95b2f9ce
3
private void RemoverEscola_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoverEscola_ButtonActionPerformed try { String escola = Escola_ComboBox2.getSelectedItem().toString(); a.RemoverEscola(escola); EscolaSelecionada_Label.setText("nenhuma"); equipa = escola; Escola_ComboBox1.removeItem(Escola_ComboBox2.getSelectedItem().toString()); } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro!", JOptionPane.ERROR_MESSAGE); } //Atualiza comboboxes Escola Escola_ComboBox.removeAllItems(); for (Escola escola : a.getDAOEscola().values()) { Escola_ComboBox.addItem(escola.getNome()); } /* Escola_ComboBox1.removeAllItems(); for(Escola escola : a.getDAOEscola().values()) Escola_ComboBox1.addItem(escola.getNome()); */ Escola_ComboBox2.removeAllItems(); for (Escola escola : a.getDAOEscola().values()) { Escola_ComboBox2.addItem(escola.getNome()); } }//GEN-LAST:event_RemoverEscola_ButtonActionPerformed
57fd87d7-542c-4ebd-901a-b3dd82c7bb2b
4
public byte[] unpack() { if (compression == 0) { return buffer; } byte[] result = new byte[size]; if (compression == 1) { try { DataInputStream stream = new DataInputStream(new BZip2CompressorInputStream( new ByteArrayInputStream(buffer))); stream.readFully(result); stream.close(); } catch (IOException ioex) { ioex.printStackTrace(); return null; } } else { try { DataInputStream stream = new DataInputStream(new GZIPInputStream( new ByteArrayInputStream(buffer))); stream.readFully(result); stream.close(); } catch (IOException ioex) { ioex.printStackTrace(); return null; } } return result; }
74acb6ad-b130-4c77-8a31-484fc8ff9d7d
9
void headerOnMouseDoubleClick (Event event) { if (!isFocusControl ()) setFocus (); if (columns.length == 0) return; CTableColumn[] orderedColumns = getOrderedColumns (); int x = -horizontalOffset; for (int i = 0; i < orderedColumns.length; i++) { CTableColumn column = orderedColumns [i]; x += column.width; if (event.x < x) { /* found the clicked column */ CTableColumn packColumn = null; if (x - event.x <= TOLLERANCE_COLUMNRESIZE) { /* clicked on column bound for this column */ packColumn = column; } else { if (i > 0 && event.x - column.getX () <= TOLLERANCE_COLUMNRESIZE) { /* clicked on column bound that applies to previous column */ packColumn = orderedColumns [i - 1]; } } if (packColumn != null) { packColumn.pack (); resizeColumn = null; if (Math.abs (packColumn.getX () + packColumn.width - event.x) > TOLLERANCE_COLUMNRESIZE) { /* column separator has relocated away from pointer location */ setCursor (null); } return; } /* did not click on column separator, so just fire column event */ Event newEvent = new Event (); newEvent.widget = column; column.notifyListeners (SWT.DefaultSelection, newEvent); return; } } }
9cd73057-59d4-4b55-8c54-9a49e59c0312
4
public UsuarioBean type(UsuarioBean oUsuarioBean) throws Exception { try { oMysql.conexion(enumTipoConexion); Boolean isAlumno = oMysql.typeUser("alumno", "usuario", "alumno.id_usuario", "alumno.id_usuario", oUsuarioBean.getId()); Boolean isProfesor = oMysql.typeUser("profesor", "usuario", "profesor.id_usuario", "profesor.id_usuario", oUsuarioBean.getId()); Boolean isEmpresa = oMysql.typeUser("empresa", "usuario", "empresa.id_usuario", "empresa.id_usuario", oUsuarioBean.getId()); if (isAlumno) { oUsuarioBean.setTipoUsuario(Enum.TipoUsuario.Alumno); } else if (isProfesor) { oUsuarioBean.setTipoUsuario(Enum.TipoUsuario.Profesor); } else if (isEmpresa) { oUsuarioBean.setTipoUsuario(Enum.TipoUsuario.Empresa); } } catch (Exception e) { throw new Exception("UsuarioDao.getUsuario: Error: " + e.getMessage()); } finally { oMysql.desconexion(); } return oUsuarioBean; }
ace58478-2652-49db-924f-9efc558c141c
3
@Override public void run() { ByteBuffer buf = ByteBuffer.allocate(8196); try { int bytesRead = channel.read(buf); while (bytesRead > 0) { bytesRead = channel.read(buf); System.out.println(bytesRead); } } catch (IOException ex) { System.out.println(ex.getMessage() + this.toString()); } try { buf.flip(); ObjectInputStream ois; Message message = null; try (ByteArrayInputStream bias = new ByteArrayInputStream(buf.array(), 0, buf.limit())) { ois = new ObjectInputStream(bias); message = (Message) ois.readObject(); ois.close(); } queue.add(message); } catch (IOException | ClassNotFoundException ex) { } Thread.currentThread().interrupt(); }
8c18119b-f4b0-402a-85b0-f73bd914c331
9
public void method389(boolean flag1, int i, int j, String s, int k) { aBoolean1499 = false; int l = i; if(s == null) return; k -= anInt1497; for(int i1 = 0; i1 < s.length(); i1++) if(s.charAt(i1) == '@' && i1 + 4 < s.length() && s.charAt(i1 + 4) == '@') { int j1 = getColorByName(s.substring(i1 + 1, i1 + 4)); if(j1 != -1) j = j1; i1 += 4; } else { char c = s.charAt(i1); if(c != ' ') { if(flag1) method392(aByteArrayArray1491[c], i + anIntArray1494[c] + 1, k + anIntArray1495[c] + 1, anIntArray1492[c], anIntArray1493[c], 0); method392(aByteArrayArray1491[c], i + anIntArray1494[c], k + anIntArray1495[c], anIntArray1492[c], anIntArray1493[c], j); } i += anIntArray1496[c]; } if(aBoolean1499) DrawingArea.method339(k + (int)((double)anInt1497 * 0.69999999999999996D), 0x800000, i - l, l); }
5f3d71c9-400d-4d68-a3a9-7e6db2471fdf
7
protected static void initFilters(boolean loader, Vector<String> classnames) { int i; int n; String classname; Class cls; String[] ext; String desc; FileSourcedConverter converter; ExtensionFileFilter filter; if (loader) m_LoaderFileFilters = new Vector<ExtensionFileFilter>(); else m_SaverFileFilters = new Vector<ExtensionFileFilter>(); for (i = 0; i < classnames.size(); i++) { classname = (String) classnames.get(i); // get data from converter try { cls = Class.forName(classname); converter = (FileSourcedConverter) cls.newInstance(); ext = converter.getFileExtensions(); desc = converter.getFileDescription(); } catch (Exception e) { cls = null; converter = null; ext = new String[0]; desc = ""; } if (converter == null) continue; // loader? if (loader) { for (n = 0; n < ext.length; n++) { filter = new ExtensionFileFilter(ext[n], desc + " (*" + ext[n] + ")"); m_LoaderFileFilters.add(filter); } } else { for (n = 0; n < ext.length; n++) { filter = new ExtensionFileFilter(ext[n], desc + " (*" + ext[n] + ")"); m_SaverFileFilters.add(filter); } } } }
930fdae9-e015-496c-a7f8-70ab2586b5f7
5
public NexTServer(){ try { serverSocket = new ServerSocket(port_number); } catch (IOException e) {System.out.println(e);} while(true){ try { clientSocket = serverSocket.accept(); for(int i=0; i<=max_clients; i++){ if(t[i]==null) { (t[i] = new clientThread(clientSocket)).start(); break; } } } catch (IOException e) { System.out.println(e);} } }
44df7ffb-75f8-4253-9a11-a55074dab5aa
8
public void convertGeodeticToGeocentric(ProjCoordinate p) { double Longitude = p.x; double Latitude = p.y; double Height = p.hasValidZOrdinate() ? p.z : 0; //Z value not always supplied double X, Y, Z; // output double Rn; /* Earth radius at location */ double Sin_Lat; /* Math.sin(Latitude) */ double Sin2_Lat; /* Square of Math.sin(Latitude) */ double Cos_Lat; /* Math.cos(Latitude) */ /* ** Don't blow up if Latitude is just a little out of the value ** range as it may just be a rounding issue. Also removed longitude ** test, it should be wrapped by Math.cos() and Math.sin(). NFW for PROJ.4, Sep/2001. */ if (Latitude < -ProjectionMath.HALFPI && Latitude > -1.001 * ProjectionMath.HALFPI) { Latitude = -ProjectionMath.HALFPI; } else if (Latitude > ProjectionMath.HALFPI && Latitude < 1.001 * ProjectionMath.HALFPI) { Latitude = ProjectionMath.HALFPI; } else if ((Latitude < -ProjectionMath.HALFPI) || (Latitude > ProjectionMath.HALFPI)) { /* Latitude out of range */ throw new IllegalStateException("Latitude is out of range: " + Latitude); } if (Longitude > ProjectionMath.PI) { Longitude -= (2 * ProjectionMath.PI); } Sin_Lat = Math.sin(Latitude); Cos_Lat = Math.cos(Latitude); Sin2_Lat = Sin_Lat * Sin_Lat; Rn = a / (Math.sqrt(1.0e0 - e2 * Sin2_Lat)); X = (Rn + Height) * Cos_Lat * Math.cos(Longitude); Y = (Rn + Height) * Cos_Lat * Math.sin(Longitude); Z = ((Rn * (1 - e2)) + Height) * Sin_Lat; p.x = X; p.y = Y; p.z = Z; }
2db21796-8164-4c43-901d-91378550f3f8
2
public static int fibonacci (int n) { if (n == 0) return 0; if (n == 1) return 1; return fibonacci(n - 1) + fibonacci(n - 2); }
93b1a42a-d0b0-4c89-91cf-03199e9a5eef
6
static final int method2253(int i, int i_0_) { anInt3814++; int i_1_ = -124 % ((i_0_ - 55) / 63); int i_2_ = 0; if (i < 0 || i >= 65536) { i_2_ += 16; i >>>= 16; } if ((i ^ 0xffffffff) <= -257) { i >>>= 8; i_2_ += 8; } if (i >= 16) { i_2_ += 4; i >>>= 4; } if ((i ^ 0xffffffff) <= -5) { i_2_ += 2; i >>>= 2; } if (i >= 1) { i >>>= 1; i_2_++; } return i_2_ - -i; }
acbdab7d-c4e3-49bf-a336-48120e8419d7
5
public static int getIndex(String type) { switch (type) { case "water_turbine": return WATER; case "wind_turbine": return WIND; case "solar_plant": return SOLAR; case "nuclear": return NUCLEAR; case "coal_fired_plant": return COAL; } return -1; }
0c8ee85b-e16d-4c99-af68-be675e8a0837
8
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((created == null) ? 0 : created.hashCode()); result = prime * result + ((emagVoucherId == null) ? 0 : emagVoucherId.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((modified == null) ? 0 : modified.hashCode()); result = prime * result + ((salePrice == null) ? 0 : salePrice.hashCode()); result = prime * result + ((salePriceVAT == null) ? 0 : salePriceVAT.hashCode()); result = prime * result + ((status == null) ? 0 : status.hashCode()); result = prime * result + ((vatRate == null) ? 0 : vatRate.hashCode()); return result; }
c9803df5-e6ac-48b7-adaf-7be8f0461c07
5
public List<Integer> preorderTraversal1(TreeNode root) { if (root == null) return list; Stack<TreeNode> st = new Stack<TreeNode>(); Queue<TreeNode> qu = new LinkedList<TreeNode>(); st.add(root); while(!st.isEmpty()) { root = st.pop(); qu.add(root); if (root.right != null) st.push(root.right); if (root.left != null) st.push(root.left); } while (!qu.isEmpty()) { root = qu.poll(); list.add(root.val); } return list; }
27206175-a1d6-4682-968f-bc6d8a2810db
6
public int ladderLength(String start, String end, HashSet<String> dict) { if (start == null || end == null) return 0; if (start.equals(end)) return 1; dict.remove(start); dict.add(end); Queue<String> queue = new LinkedList<String>(); Queue<Integer> levelqueue = new LinkedList<Integer>(); queue.add(start); levelqueue.add(1); while (queue.size() > 0 ) { String current = queue.poll(); Integer level = levelqueue.poll(); Set<String> nextSet = getNeighbour(current, dict); for (String next : nextSet) { if (next.equals(end)) return level +1; queue.add(next); levelqueue.add(level +1); dict.remove(next); } } return 0; }
0adcff8e-f073-425c-a372-fc825e64520c
9
private void prebox(TypeDesc from, TypeDesc to) { // Wouldn't it be cool if I could walk backwards in the instruction // list and insert the new-dup pair before the value to box was even // put on the stack? switch (from.getTypeCode()) { default: break; case TypeDesc.BOOLEAN_CODE: if (to.toPrimitiveType().getTypeCode() == TypeDesc.BOOLEAN_CODE) { break; } // fall through case TypeDesc.CHAR_CODE: case TypeDesc.FLOAT_CODE: case TypeDesc.BYTE_CODE: case TypeDesc.SHORT_CODE: case TypeDesc.INT_CODE: newObject(to); dupX1(); swap(); break; case TypeDesc.DOUBLE_CODE: case TypeDesc.LONG_CODE: newObject(to); dupX2(); dupX2(); pop(); break; } }
9a41fc2a-114b-418d-9ebb-d91902cb81f7
3
private <T> int altezza(AlberoBin<T> a) { int h1 = 0, h2 = 0; if (a.sin() != null) h1 = 1 + altezza(a.sin()); if (a.des() != null) h2 = 1 + altezza(a.des()); return h1 > h2 ? h1 : h2; }
2be188c8-aa5f-4533-a9b6-c0d7613ddc65
3
private void tastendruckBenachrichtigen(String ergebnis) { try { for (Object o : tastaturListener) { try { o.getClass().getMethod(TASTE, String.class) // .invoke(o, "" + ev.getKeyChar()); .invoke(o, "" + ergebnis); } catch (Exception e1) { e1.printStackTrace(); } } } catch (Exception e) { // wegen // ConcurrentModificationException } }
b78bbd5b-8eea-4b98-b773-d69fdd6da9e7
6
public static final boolean contentEquals( Object c1, Object c2 ) { if( c1 == null && c2 == null ) return true; if( c1 == null || c2 == null ) return false; if( c1 instanceof byte[] && c2 instanceof byte[] ) { return equals( (byte[])c1, (byte[])c2 ); } return c1.equals(c2); }
c17d5050-6429-4e17-80c6-20ad32e5b1fc
9
public void locateEntities(EntitySet set, Point point) { radarSize.setSize(this.size); radarSize.width -= insets.left + insets.right; radarSize.height -= insets.top + insets.bottom; int x = point.x - insets.left; int y = point.y - insets.top; set.clear(); Point point1 = new Point(); int dist2 = Integer.MAX_VALUE; List<Plane> planes = new ArrayList<>(); for (Plane plane : atcHandler.retrievePlanes()) { Position p = plane.getPosition(); computePoint(point1, p); point1.translate(-x, -y); int d2 = point1.x * point1.x + point1.y * point1.y; if (d2 < dist2) { planes.clear(); dist2 = d2; planes.add(plane); } else if (d2 == dist2) { planes.add(plane); } } set.addPlanes(planes); set.setPlanesDistance((int) Math.round(Math.sqrt(dist2))); dist2 = Integer.MAX_VALUE; List<Location> locations = new ArrayList<>(); for (Location location : atcHandler.retrieveMapLocations()) { Position p = location.getPosition(); computePoint(point1, p); point1.translate(-x, -y); int d2 = point1.x * point1.x + point1.y * point1.y; if (d2 < dist2) { locations.clear(); dist2 = d2; locations.add(location); } else if (d2 == dist2) { locations.add(location); } } set.addLocations(locations); set.setLocationDistance((int) Math.round(Math.sqrt(dist2))); dist2 = Integer.MAX_VALUE; List<DefaultRunway> runways = new ArrayList<>(); for (DefaultRunway runway : atcHandler.retrieveRunways()) { Position p = runway.getPosition(); computePoint(point1, p); point1.translate(-x, -y); int d2 = point1.x * point1.x + point1.y * point1.y; if (d2 < dist2) { runways.clear(); dist2 = d2; runways.add(runway); } else if (d2 == dist2) { runways.add(runway); } } set.addRunways(runways); set.setRunwayDistance((int) Math.round(Math.sqrt(dist2))); }
e10908e6-3d52-4672-b29c-c933121eafd5
7
@SuppressWarnings("resource") public void promptPatientFieldSelection(DataSource ds, int health_care_no) { while (true) { Patient patient = ds.getPatient(health_care_no); if (patient == null) { System.out.println("Could not find a patient with Health Care No. " + health_care_no); return; } System.out.println("Patient with Health Care No. " + health_care_no +" found:"); System.out.println("1.Name: " + patient.getName()); System.out.println("2.Address: " + patient.getAddress()); System.out.println("3.Phone: " + patient.getPhone()); System.out.println("4.Birthday: " + patient.getBirth_day()); System.out.println("0.Go back"); System.out.println("Select a field to edit: "); Scanner input = new Scanner(System.in); int selection = input.nextInt(); switch(selection) { case 1: promptPatientFieldUpdate(ds, health_care_no, "name"); break; case 2: promptPatientFieldUpdate(ds, health_care_no, "address"); break; case 3: promptPatientFieldUpdate(ds, health_care_no, "phone"); break; case 4: promptPatientFieldUpdate(ds, health_care_no, "birth_day"); break; case 0: return; default: System.out.println("Please select a number from the given options."); continue; } } }
b50ed8d8-93f1-4a90-8850-262a69a0f269
4
private void RealizeOsServicosPrincipais () { int flag = 0; for (int i = 0; i < numeroGeracoes; i++) { if ( flag == 1) { minhaGeracao = new MinhaGeneracao(taxaSelecao, tamanhoPopulacao, mecanismoSelecao, mutacao.getPopulacaoDaPonteControladora()); } else { minhaGeracao = new MinhaGeneracao(taxaSelecao, tamanhoPopulacao, mecanismoSelecao, populacao.listaPopulacional); flag = 1; } listaPopulacaoDaPonteControladora = new ArrayList<Caminho>(); listaPopulacaoDaPonteControladora = minhaGeracao.getListaPopulation(); mutacao = new Mutacao(taxaMutacao, taxaSelecao, tamanhoPopulacao, listaPopulacaoDaPonteControladora); System.out.print("\n\n\tMelhor Individuo Da Geração " + (i + 1) + ": \n"); System.out.print(mutacao.getPopulacaoDaPonteControladora().get(0)); if ( mutacao.getPopulacaoDaPonteControladora().get(0).retorneFitnessDiretoDoCaminho() <= custoOtimo ) { System.out.print("\n\n\t ----> Paramos Por Ter Encontrado o Melhor Caminho na Geração " + ( i + 1 ) + "\n\n"); geracaoParou = i + 1; break; } if ( i == numeroGeracoes - 1 ) { System.out.print("\n\n\t ---> Paramos Por Ter Alcançado O Número De Gerações Limite\n\n"); geracaoParou = i + 1; } } }
e67417f1-9cb4-40d2-8dfd-8afce4994f16
2
public static boolean isPalindrome(int n) { String numString = Integer.toString(n); String revString = ""; for (int i = numString.length() - 1; i >= 0; i--) { revString = revString + numString.charAt(i); } if (numString.equals(revString)) { return true; } return false; }
e89aed3a-5ef5-402f-8206-727d6c521061
2
@Override public void executeAll() { try { for(IUsersCommand c : _usersCommandLog) { c.setExecutor(users); c.execute(); } } catch (CommandException e) { System.err.println("Error: Illegal/Invalid command was stored in UsersCommandLog"); e.printStackTrace(); } }
868f6efa-4a07-4683-9ec0-48195ae619c2
7
private void update() { if (!ball.isMoving()) { ball.setX(board.getX() + (board.getWidth() - ball.getWidth()) / 2); } else { if (ball.getX() <= 0 || ball.getX() >= WIDTH) { System.out.println("bang!"); ball_vx = - ball_vx; } if (ball.getY() <= 0) { System.out.println("bang!"); ball_vy = - ball_vy; } if (ball.getX() <= board.getX() + board.getWidth() / 2 && ball.getX() >= board.getX() - board.getWidth() / 2) { if (ball.getY() > board.getY()) { ball_vy = - ball_vy; } } ball.setX(ball.getX() + ball_vx); ball.setY(ball.getY() - ball_vy); } }
89763bb4-da9a-420c-9ca8-67dc307c6916
7
public static GetSampleImage_Result getSampleImage(Database database, GetSampleImage_Param params) { Logger.getLogger(API.class.getName()).log(Level.FINE, "Entering API.getSampleImage()"); GetSampleImage_Result result; try { ValidateUser_Result vResult = validateUser(database, new ValidateUser_Param(params.username(), params.password())); if (vResult == null || !vResult.validated()) { result = null; } else { // Get all Images from this Project Image tImage = new Image(); tImage.setProjectId(params.projectId()); ArrayList<Image> images = (ArrayList) database.get(tImage); // Get an unassigned Image String imagePath = null; int index = 0; while (imagePath == null && index < images.size()) { Image currentImage = images.get(index); if (currentImage.currentUser() == 0) { imagePath = currentImage.path(); } ++index; } if (imagePath == null) { result = null; } else { result = new GetSampleImage_Result(imagePath); } } } catch (DatabaseException | GetFailedException ex) { result = null; Logger.getLogger(API.class.getName()).log(Level.WARNING, "getSampleImage request failed.", ex); } Logger.getLogger(API.class.getName()).log(Level.FINE, "Exiting API.getSampleImage()"); return result; }
523e9515-1842-4376-ae82-80079e4c0ef7
0
@Before public void setUp() throws Exception { validadorUsuarios = new ValidadorUsuarios(); }
aa3e6ca4-54ae-4e1e-90ed-38931502c1c7
5
public static double getSimilarDegree(String str1, String str2) { //���������ռ�ģ�ͣ�ʹ��mapʵ�֣�����Ϊ���ֵΪ����Ϊ2�����飬����Ŷ�Ӧ�������ַ��еij��ִ��� Map<String, int[]> vectorSpace = new HashMap<String, int[]>(); int[] itemCountArray = null;//Ϊ�˱���Ƶ������ֲ����������Խ�itemCountArray�����ڴ� //�Կո�Ϊ�ָ���ֽ��ַ� String strArray[] = str1.split(" "); for(int i=0; i<strArray.length; ++i) { if(vectorSpace.containsKey(strArray[i])) ++(vectorSpace.get(strArray[i])[0]); else { itemCountArray = new int[2]; itemCountArray[0] = 1; itemCountArray[1] = 0; vectorSpace.put(strArray[i], itemCountArray); } } strArray = str2.split(" "); for(int i=0; i<strArray.length; ++i) { if(vectorSpace.containsKey(strArray[i])) ++(vectorSpace.get(strArray[i])[1]); else { itemCountArray = new int[2]; itemCountArray[0] = 0; itemCountArray[1] = 1; vectorSpace.put(strArray[i], itemCountArray); } } //�������ƶ� double vector1Modulo = 0.00;//����1��ģ double vector2Modulo = 0.00;//����2��ģ double vectorProduct = 0.00; //������ Iterator iter = vectorSpace.entrySet().iterator(); while(iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); itemCountArray = (int[])entry.getValue(); vector1Modulo += itemCountArray[0]*itemCountArray[0]; vector2Modulo += itemCountArray[1]*itemCountArray[1]; vectorProduct += itemCountArray[0]*itemCountArray[1]; } vector1Modulo = Math.sqrt(vector1Modulo); vector2Modulo = Math.sqrt(vector2Modulo); //�������ƶ� return (vectorProduct/(vector1Modulo*vector2Modulo)); }
1ee4f2e4-c1ae-4f65-9b39-7f258343ade9
0
public String getEWord(){ return eWord; }
403c82e8-39e3-4839-aec1-ca9e0a7cd471
3
public void run(){ DataOutputStream output; DataInputStream input; GameManager.gameIsRunning = true; int[] message = new int[2]; int[] action = new int[2]; try { output = new DataOutputStream(socket.getOutputStream()); input = new DataInputStream(socket.getInputStream()); GameManager.endRoom = input.readInt(); //reads the endRoom, to put it at the same spot. while(true){ message[0]= input.readInt(); message[1] = input.readInt(); //Reads the message from the server. //System.out.println("client : " + message[0]); if(message[0]!=28792){ TurnManager.turn = false; GameManager.buffer.consume(); GameManager.updateActor(message); }else{ TurnManager.turn = true; //receives monsters moves message[0]= input.readInt(); message[1] = input.readInt(); GameManager.updateActor(message); //sends hero's moves action = GameManager.buffer.consume(); output.writeInt(action[0]); output.writeInt(action[1]); } } } catch (IOException | InterruptedException e) { e.printStackTrace(); } }
9b1323c8-baf8-4786-8731-36cb7d5a8753
8
public void paintComponent(Graphics g) { for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { Point point = new Point(j, i); if (maze.isOpen(point)) drawBox(j, i, SIDE, openColor, g); if (maze.isClosed(point)) drawBox(j, i, SIDE, closedColor, g); if (maze.isStart(point)) drawBox(j, i, SIDE, startColor, g); if (maze.isGoal(point)) drawBox(j, i, SIDE, goalColor, g); if (maze.isVisited(point)) drawDot(j, i, SIDE / 2, visitedColor, g); if (maze.isCurrent(point)) drawDot(j, i, SIDE / 2, turtleColor, g); } } }
55c84fc0-0d99-4766-a793-44dd71a5a098
2
private void fireClientConnectEvent(ConnectEvent evt) { //throws Exception { connected = true; Object[] listeners = connectEventListenerList.getListenerList(); for (int i=0; i<listeners.length; i+=2) { if (listeners[i]==ConnectListener.class) { ((ConnectListener)listeners[i+1]).OnConnectEvent(evt); } } }
9e188f63-4f34-4e60-8ad2-df6f6df66222
1
private static double narrow(final double d) { if (d < 0) { return d - 0.1; } else { return d + 0.1; } }
3601d491-259d-4735-ae8b-799b6f1e0377
1
public StockCUDialog() { this.setTitle("Stock manager"); this.setModal(true); this.setResizable(true); this.setSize(new Dimension(300, 300)); this.setLocationRelativeTo(this.getRootPane()); this.setLayout(new BorderLayout(5, 5)); JPanel pnlMain = new JPanel(); this.add(pnlMain, BorderLayout.CENTER); pnlMain.setLayout(new GridLayout(0, 1, 5, 0)); JLabel lblName = new JLabel("Name:"); pnlMain.add(lblName); txfName = new JTextField(); pnlMain.add(txfName); JLabel lblType = new JLabel("Type:"); pnlMain.add(lblType); cbxType = new JComboBox(); cbxType.removeAllItems(); for (StockType type : StockType.values()) { cbxType.addItem(type); } pnlMain.add(cbxType); JLabel lblCapacity = new JLabel("Capacity:"); pnlMain.add(lblCapacity); txfCapacity = new JTextField(); txfCapacity.setText("64"); pnlMain.add(txfCapacity); JLabel lblMaxTrays = new JLabel("Maximum trays per storage unit: "); pnlMain.add(lblMaxTrays); txfMaxTrays = new JTextField(); txfMaxTrays.setText("16"); pnlMain.add(txfMaxTrays); JLabel lblUnitsPerRow = new JLabel("Storage units per row:"); pnlMain.add(lblUnitsPerRow); txfUnitsPerRow = new JTextField(); txfUnitsPerRow.setText("8"); pnlMain.add(txfUnitsPerRow); JPanel pnlSouth = new JPanel(); pnlSouth.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 5)); this.add(pnlSouth, BorderLayout.SOUTH); btnOK = new JButton("OK"); btnOK.addActionListener(controller); pnlSouth.add(btnOK); btnCancel = new JButton("Cancel"); btnCancel.addActionListener(controller); pnlSouth.add(btnCancel); this.updateDisplay(); }
feb31c29-ea92-40ce-8dbe-312e768e6cce
9
private void solve() { for (int i = 0; i < vertices.length; i++) { vertices[i].setDistance(Integer.MIN_VALUE); vertices[i].setPrevious(null); } vertices[0].setDistance(0); PriorityQueue<Vertex> queue = new PriorityQueue<>(Arrays.asList(vertices)); while (!queue.isEmpty()) { Vertex<Integer> v = queue.poll(); if (v.getDistance() == Integer.MIN_VALUE) { break; } for (Edge e : v.getEdges()) { int alt = v.getDistance() + ((int) e.getV2().getData() - v.getData()); if (alt > e.getV2().getDistance()) { queue.remove(e.getV2()); e.getV2().setDistance(alt); e.getV2().setPrevious(v); queue.add(e.getV2()); } } } int greatest = Integer.MIN_VALUE; List<Vertex<Integer>> greatestPath = null; for (int i = vertices.length - lines; i < vertices.length; i++) { Vertex<Integer> v = vertices[i]; ArrayList<Vertex<Integer>> path = new ArrayList<>(100); int size = 0; while (v != null) { path.add(v); size += v.data; v = v.getPrevious(); } if (size > greatest) { greatest = size; Collections.reverse(path); greatestPath = path; } } if (greatestPath != null) { results.add(String.valueOf(greatestPath)); results.add(String.valueOf(greatestPath.stream().map(Vertex::getData).reduce(0, (a, b) -> a + b))); } }
83713daa-d7b8-46c1-aa79-4694ba97b002
4
private void setImageDefault(Attributes attrs) { // find the value to be set, then set it if (attrs.getValue(0).equals("starttime")) imageDef.setStartTime(Integer.valueOf(attrs.getValue(1))); else if (attrs.getValue(0).equals("endtime")) imageDef.setEndTime(Integer.valueOf(attrs.getValue(1))); else if (attrs.getValue(0).equals("onclick")) { imageDef.setOnClick(Integer.valueOf(attrs.getValue(1))); } else if (attrs.getValue(0).equals("onclickurl")) imageDef.setOnClickUrl(attrs.getValue(1)); }
65d88a75-65eb-4047-8023-f80187fb354c
2
public static void handleTransferFailed(SerializableTransferFailed pack) { SelectionKey key; String seller; if (pack.commandInfo.isEmpty()) { Server.loggerServer.error("The packet doesn't contain seller's name"); return; } seller = pack.commandInfo.get(0); key = Server.registeredUsersChannels.get(seller); if (null == key) { Server.loggerServer.error("[Server] The user " + seller + " is no longer" + " logged in => No transfer failed message sent"); return; } //send packet "transfer failed" to the seller Server.sendData(key, pack); }
b5bf851c-d3f9-4981-8e71-dfe284e2e785
7
public static void floodFill(int r, int c) { for (int i = 0; i < dir.length; i++) if (r + dir[i][0] >= 0 && r + dir[i][0] < n + 2 && c + dir[i][1] >= 0 && c + dir[i][1] < m + 2 && map[r + dir[i][0]][c + dir[i][1]] != 'X' && map[r + dir[i][0]][c + dir[i][1]] != '#') { map[r + dir[i][0]][c + dir[i][1]] = '#'; floodFill(r + dir[i][0], c + dir[i][1]); } }
800c0349-1eed-426b-80dd-a5c2121b49cd
8
public int func_27297_a(StatCrafting par1StatCrafting, StatCrafting par2StatCrafting) { int var3 = par1StatCrafting.getItemID(); int var4 = par2StatCrafting.getItemID(); StatBase var5 = null; StatBase var6 = null; if (this.slotStatsBlockGUI.field_27271_e == 2) { var5 = StatList.mineBlockStatArray[var3]; var6 = StatList.mineBlockStatArray[var4]; } else if (this.slotStatsBlockGUI.field_27271_e == 0) { var5 = StatList.objectCraftStats[var3]; var6 = StatList.objectCraftStats[var4]; } else if (this.slotStatsBlockGUI.field_27271_e == 1) { var5 = StatList.objectUseStats[var3]; var6 = StatList.objectUseStats[var4]; } if (var5 != null || var6 != null) { if (var5 == null) { return 1; } if (var6 == null) { return -1; } int var7 = GuiStats.getStatsFileWriter(this.slotStatsBlockGUI.field_27274_a).writeStat(var5); int var8 = GuiStats.getStatsFileWriter(this.slotStatsBlockGUI.field_27274_a).writeStat(var6); if (var7 != var8) { return (var7 - var8) * this.slotStatsBlockGUI.field_27270_f; } } return var3 - var4; }
5eda7835-8af5-4a07-a2ba-8a767ff243bb
7
public static void main(String[] args) { final int limit = 10000; final SieveOfAtkin sieve = new SieveOfAtkin(limit); final ArrayList<Integer> list = sieve.run(); final HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int p : list) { map.put(p, map.size()); } int maxlength = 0; int amax = 0; int bmax = 0; for (int a = -999; a < 1000; a++) { for (int i = 0; i < list.size(); i++) { final int b = list.get(i); if (b > 999) { break; } // System.out.println("# a = " + a + "; b = " + b); int length = 0; for (int n = 0; n < 1000; n++) { final int fn = n * n + a * n + b; if (map.containsKey(fn)) { length++; // System.out.println(n + "\t" + fn); } else { break; } } if (length > maxlength) { maxlength = length; amax = a; bmax = b; System.out.println("# a = " + amax + "; b = " + bmax + "; length = " + maxlength); } } } System.out.println("# a = " + amax + "; b = " + bmax + "; length = " + maxlength + "; a x b = " + (amax * bmax)); }
9c4df74d-7994-4199-af4b-5be9797d0802
3
@Override public Loja ListById(int id_loja) { Connection conn = null; PreparedStatement pstm = null; ResultSet rs = null; Loja l = new Loja(); try{ conn = ConnectionFactory.getConnection(); pstm = conn.prepareStatement(LISTBYID); pstm.setInt(1, id_loja); rs = pstm.executeQuery(); while (rs.next()){ l.setId_loja(rs.getInt("id_loja")); l.setNome(rs.getString("nome_lj")); l.setEndereco(rs.getString("endereco_lj")); l.setTelefone(rs.getString("telefone_lj")); l.setCep(rs.getString("cep_lj")); } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao listar lojas " + e); }finally{ try{ ConnectionFactory.closeConnection(conn, pstm, rs); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao desconectar com o banco " + e); } } return l; }
5b54a3ff-3219-43e6-8e23-3dd740a90b55
0
@BeforeClass public static void setUpClass() { }
a349eb70-5756-4e25-9e71-5099fab080e3
7
public static String[] readfileTxt(String fileName){ String [] s = new String [0]; String direccion = System.getProperty("user.dir")+"/"+ fileName; // Try to load the file (archive) File archive; FileReader fr = null; BufferedReader br = null; try { // Open the file and create BufferedReader in order to // reading easier (disposing the method readLine()). archive = new File (direccion); fr = new FileReader (archive); br = new BufferedReader(fr); // Reading the file String line; while((line=br.readLine())!=null){ int n; String [] s2 = new String[s.length+1]; for(n=0;n<s.length;n++)s2[n] = s[n]; s2[n]=line.trim(); s=s2; } }catch(Exception e){ System.err.println("File not found"); System.exit(-1); }finally{ // In the "finally" block, try to close the file and ensure // that it closes, otherwise, throw an exception try{ if( null != fr ){ fr.close(); } }catch (Exception e2){ e2.printStackTrace(); } try{ if( br != null ){ br.close(); } }catch (Exception e2){ e2.printStackTrace(); } } return s; }