method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
b72e7745-a7af-4f61-b0ae-f4d1b25dc564
2
public void advance(long milliseconds) { // Check to make sure we are given a positive amount of time. if (milliseconds < 0) { throw new IllegalArgumentException("Time interval cannot be less than 1."); } else if (milliseconds == 0) { return; } else { /* Critical Region */ synchronized (this) { // Calculate new position. double newX = xPosition + (milliseconds * 0.001 * BALL_VELOCITY * Math.cos(theta)); double newY = yPosition + (milliseconds * 0.001 * BALL_VELOCITY * Math.sin(theta)); xPosition = (int) newX; yPosition = (int) newY; } } }
45cbb719-3c57-48e7-9755-982fed2f7013
2
public static Transformer newTransformer(String xsltFileName) throws TransformerConfigurationException { File xsltFile = new File(xsltFileName); Templates template = cache.get(xsltFileName); if (template == null) { lock.writeLock().lock(); try { if (!cache.containsKey(xsltFileName)) { Source xslSource = new StreamSource(xsltFile); TransformerFactory transFact = TransformerFactory.newInstance(); Templates templates = transFact.newTemplates(xslSource); template = templates; cache.put(xsltFileName, template); } else { template = cache.get(xsltFileName); } } finally { lock.writeLock().unlock(); } } return template.newTransformer(); }
34f24124-83c6-496b-86e0-eafd58fab591
2
@Override public void run(final String... args) { final CommandLine line = parseArguments(args); final String configFile = getConfigFile(line); final SyncConfig config = readConfig(configFile); for (final FolderConfig folderConfig : config.getConfigs()) { if (!folderConfig.isSyncOn()) { System.out.println("Sync is turned off for artist URL " + folderConfig.getArtistUrl() + ". Will not run sync for this artist."); continue; } final Syncer syncer = SCUtilFactory.getSyncer(folderConfig.getArtistUrl()); syncer.sync(folderConfig); } save(config, configFile); }
2d4db090-7595-4e43-8252-3f493b533d38
0
@Override public void gameRenderObjects() { }
0ea3cf19-e163-4e67-9fd8-2c0896656a7a
2
public ResultSet read(String query){ try { ResultSet result = this.statement.executeQuery(query); result.last(); int rows = result.getRow(); if(rows < 1){ return null; } result.beforeFirst(); return result; } catch (SQLException ex) { Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, "" + "SQL-String: "+query, ex); return null; } }
53d1c6c7-c018-4a70-8964-ac4d7776dca3
6
public static void main(String[] args)throws IOException { File directory = new File("/home/garth/Desktop/stock"); //directory of program files File[] files = directory.listFiles(); List<String> allMatches = new ArrayList<String>(); for(int i=0;i<files.length;i++){ Matcher m = Pattern.compile(".*csv.*").matcher(files[i].toString()); //finds all files that match the regex while (m.find()) { allMatches.add(m.group()); } } File[] stockFiles = new File[allMatches.toArray().length]; for(int i =0;i<allMatches.toArray().length;i++) { File temp=new File(allMatches.toArray()[i].toString()); stockFiles[i]=temp; } for(int f=0;f<allMatches.toArray().length;f++){ double money=100; double shares=0; double sharePrice=0; String fileName=stockFiles[f].getAbsolutePath(); double finalAnswer=-99; final XYSeriesCollection dataset = new XYSeriesCollection(); XYSeries portfolio = new XYSeries("Portfolio"); XYSeries base = new XYSeries("Base"); double[] bestParams= new double[2]; int lineNumber = findNumDays(fileName); String line = new String(); String[] stringArray =new String[7]; double[] Prices = new double[lineNumber]; BufferedReader br = new BufferedReader( new FileReader(fileName)); line = br.readLine(); for(int i =0;i<lineNumber-1;i++) { line = br.readLine(); stringArray = line.toString().split(","); Prices[lineNumber-1-i]= Double.parseDouble(stringArray[3]); //initialise array of daily lows } double Base=100/Prices[100]; for(int day=100;day<400;day++){ bestParams=getOptimalParams(day,dataset,fileName,lineNumber,Prices); double[] Money=new double[3]; Money=takePosition(day+1,bestParams,fileName,lineNumber,Prices,money,shares); money=Money[0]; shares=Money[1]; sharePrice=Money[2]; //System.err.println("money"+money+" shares"+shares); } Base=Base*Prices[400]; System.out.println("Portfolio: "+(money+shares*sharePrice)); System.out.println("base: "+Base); dataset.removeAllSeries(); dataset.addSeries(portfolio); dataset.addSeries(base); //JFreeChart chart = createChart(dataset); //final ChartPanel chartPanel = new ChartPanel(chart); //chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); //final CalcWithJFreeChart demo = new CalcWithJFreeChart(dataset,"Line Chart Demo 6"); //demo.pack(); //RefineryUtilities.centerFrameOnScreen(demo); //demo.setVisible(true); } System.out.println("The best parameters are : "); }
16a72edc-7577-4ae1-be52-4e1d779325db
6
* @return Returns true if the cell is a valid drop target for the given * cells. */ public boolean isValidDropTarget(Object cell, Object[] cells) { return cell != null && ((isSplitEnabled() && isSplitTarget(cell, cells)) || (!model .isEdge(cell) && (isSwimlane(cell) || (model .getChildCount(cell) > 0 && !isCellCollapsed(cell))))); }
e57f1e30-1413-4dd4-92c1-4bd481343cf0
4
@Override public void process(Map<String, Object> jsonrpc2Params) throws Exception { if(method.equals(Constants.Method.LOGIN)){ login(jsonrpc2Params); } else if(method.equals(Constants.Method.GET_ACCOUNT)){ getAccount(jsonrpc2Params); } else if(method.equals(Constants.Method.UPDATE_ACCOUNT)){ updateAccount(jsonrpc2Params); } else if(method.equals(Constants.Method.REGISTER)){ register(jsonrpc2Params); } else{ throwJSONRPC2Error(JSONRPC2Error.METHOD_NOT_FOUND, Constants.Errors.METHOD_NOT_FOUND, method); } }
9d2d3732-0e99-4c0b-bdd8-6c9cb02757a2
3
public Font(Library library, Hashtable entries) { super(library, entries); // name of object "Font" name = library.getName(entries, "Name"); // Type of the font, type 0, 1, 2, 3 etc. subtype = library.getName(entries, "Subtype"); // figure out type subTypeFormat = (subtype.equalsIgnoreCase("type0") | subtype.toLowerCase().indexOf("cid") != -1) ? CID_FORMAT : SIMPLE_FORMAT; // font name, SanSerif is used as it has a a robust CID, and it // is the most commonly used font family for pdfs basefont = "Serif"; if (entries.containsKey("BaseFont")) { Object o = entries.get("BaseFont"); if (o instanceof Name) { basefont = ((Name) o).getName(); } } }
1a50d86f-2728-4df8-b2e6-b415c8c448e5
9
public double[] distributionForInstance(BayesNet bayesNet, Instance instance) throws Exception { Instances instances = bayesNet.m_Instances; int nNumClasses = instances.numClasses(); double[] fProbs = new double[nNumClasses]; for (int iClass = 0; iClass < nNumClasses; iClass++) { fProbs[iClass] = 1.0; } for (int iClass = 0; iClass < nNumClasses; iClass++) { double logfP = 0; for (int iAttribute = 0; iAttribute < instances.numAttributes(); iAttribute++) { double iCPT = 0; for (int iParent = 0; iParent < bayesNet.getParentSet(iAttribute).getNrOfParents(); iParent++) { int nParent = bayesNet.getParentSet(iAttribute).getParent(iParent); if (nParent == instances.classIndex()) { iCPT = iCPT * nNumClasses + iClass; } else { iCPT = iCPT * instances.attribute(nParent).numValues() + instance.value(nParent); } } if (iAttribute == instances.classIndex()) { logfP += Math.log(bayesNet.m_Distributions[iAttribute][(int) iCPT].getProbability(iClass)); } else { logfP += instance.value(iAttribute) * Math.log( bayesNet.m_Distributions[iAttribute][(int) iCPT].getProbability(instance.value(1))); } } fProbs[iClass] += logfP; } // Find maximum double fMax = fProbs[0]; for (int iClass = 0; iClass < nNumClasses; iClass++) { if (fProbs[iClass] > fMax) { fMax = fProbs[iClass]; } } // transform from log-space to normal-space for (int iClass = 0; iClass < nNumClasses; iClass++) { fProbs[iClass] = Math.exp(fProbs[iClass] - fMax); } // Display probabilities Utils.normalize(fProbs); return fProbs; } // distributionForInstance
f2d4708e-12fc-4f0e-b03d-651379e6b9f6
3
public void saveConfig() { if (config == null || configFile == null) { return; } try { getConfig().save(configFile); } catch (final IOException ex) { plugin.getLogger().log(Level.SEVERE, "Could not save config to " + configFile, ex); } }
f5218381-1d96-43bd-a42c-eae772a1b77c
4
public Team getTeam(int teamID, Connection con) { Team t = null; String SQLString = "SELECT * " + "FROM TEAMS " + "WHERE teamID = ?"; PreparedStatement statement = null; try { statement = con.prepareStatement(SQLString); statement.setInt(1, teamID); //Debug if(domain.Controller.debugMode) System.out.println("DebugMode (TeamMapper.java): " + "TeamID" + teamID); ResultSet rs = statement.executeQuery(); while (rs.next()) { t = new Team(teamID, rs.getInt(2), rs.getInt(3)); } } catch (SQLException e) { System.out.println("Error in TeamMapper - getTeam " + e); } finally { try { statement.close(); } catch (SQLException e) { System.out.println("Error in TeamMapper - getTeam.Finally.Statement.close() " + e); } } return t; }
0e75e1b4-829f-4405-99a5-67d30242a780
5
public double computeMax(){ double max_revenue = 0; for(int switch2 = 2; switch2 <= no_weeks+1; switch2++){ for(int switch3 =2; switch3 <= no_weeks+1; switch3++){ for(int switch4=2; switch4 <= no_weeks+1; switch4++){ if(switch4>=switch3 && switch3>=switch2){ double thisrev = getSimRevenue(switch2,switch3,switch4); max_revenue = Math.max(max_revenue, thisrev); } } } } return max_revenue; }
689abd58-dc2b-440c-8ad8-0174c7a8f204
1
private void initComponentsNorth() { northPanel = new JPanel(); ActionListener myActionListener = new UserGUIActionListener(this, loginUser); searchLabel = new JLabel("Suchkriterium auswählen "); searchLabel.setFont(new Font(textFont, labelStyle, 14)); searchCombo = new JComboBox<String>(); searchCombo.setBackground(Color.white); searchCombo.setFont(new Font(textFont, textStyle, textSize)); // Festlegung des Inhalts der Combo-Box "searchCombo" String[] search = { "Anwender", "Rolle" }; for (int i = 0; i < search.length; i++) { searchCombo.addItem(search[i]); } searchCombo.addActionListener(myActionListener); searchText = new JTextField("Bitte Suchbegriff eingeben", 20); searchText.setFont(new Font(textFont, textStyle, textSize)); searchText.setSelectionStart(0); searchText.setSelectionEnd(30); // Icon für den Buttton "suchen" final Icon searchIcon = new ImageIcon( BookGUI.class.getResource("/view/images/searchIcon.png")); searchButton = new JButton("suchen ", searchIcon); searchButton.setFont(new Font(labelFont, labelStyle, labelSize)); searchButton.setBackground(Color.lightGray); searchButton.setBorder(BorderFactory.createRaisedBevelBorder()); searchButton.addActionListener(myActionListener); // Icon für den Buttton "alle anzeigen" final Icon showAllIcon = new ImageIcon( BookGUI.class.getResource("/view/images/peopleIcon.png")); allButton = new JButton("alle anzeigen ", showAllIcon); allButton.setFont(new Font(labelFont, labelStyle, labelSize)); allButton.setBackground(Color.lightGray); allButton.setBorder(BorderFactory.createRaisedBevelBorder()); allButton.addActionListener(myActionListener); // Hinzufügen der einzelnen Komponenten zum NorthPanel northPanel.add(searchLabel); northPanel.add(searchCombo); northPanel.add(searchText); northPanel.add(searchButton); northPanel.add(allButton); // Hinzufügen des NorthPanel zum Frame this.getContentPane().add(northPanel, BorderLayout.NORTH); }
88dc73a9-d11a-4446-9545-721fb0227395
3
public static boolean registerLog(String addr) { try { Class.forName("com.mysql.jdbc.Driver"); } catch (Exception e) { e.printStackTrace(); return false; } Connection c = null; try { c = DriverManager.getConnection( url, login, pass); } catch (Exception e) { e.printStackTrace(); return false; } String query = "INSERT INTO logs (ip) VALUES (" + "'" + addr + "')"; try { Statement s = c.createStatement(); s.executeUpdate(query); System.out.println("LOG: Register log - " + query); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
8d6d607f-abc4-4280-8348-71d7d1830dbd
4
public static Promotion addPromotion(Promotion p) { if (p == null) return null; // We check if the promotion doesn't still exist in the Professor List. boolean exist = false; int pos = 0; for (int i = 0; i < FileReadService.pList.size(); i++) { if (FileReadService.pList.get(i).equals(p)) { exist = true; pos = i; } } if (!exist) { FileReadService.pList.add(p); return p; } return FileReadService.pList.get(pos); }
034f4b84-4f91-4202-8931-4edf3951051c
2
@Override public void contextInitialized(ServletContextEvent sce) { logger.info("Initialize JdbcRealm database"); Connection cnn = null; try { if (dataSource == null) { throw new IllegalStateException("DataSource not injected, verify in web.xml that 'metadata-complete' is not set to 'true'"); } cnn = dataSource.getConnection(); testDatabaseConnectivity(cnn); createTablesIfNotExist(cnn); insertUserIfNotExists("john", "doe", "user", cnn); insertUserIfNotExists("cloudbees", "beescloud", "user", cnn); } catch (Exception e) { logger.log(Level.SEVERE, "Exception starting app", e); } finally { closeQuietly(cnn); } }
cdef775f-603c-44fb-9d20-1606e110748a
1
public void testFormatAppend_PrinterParser_Printer_null() { PeriodPrinter printer = new PeriodFormatterBuilder().appendYears().appendLiteral("-").toPrinter(); PeriodFormatterBuilder bld = new PeriodFormatterBuilder().append(printer, null).appendMonths(); assertNotNull(bld.toPrinter()); assertNull(bld.toParser()); PeriodFormatter f = bld.toFormatter(); assertEquals("1-2", f.print(PERIOD)); try { f.parsePeriod("1-2"); fail(); } catch (UnsupportedOperationException ex) {} }
c5ea7a39-3794-4720-852a-af9e61ccbda9
7
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Book book = (Book) o; if (id != book.id) return false; if (!author.equals(book.author)) return false; if (!genre.equals(book.genre)) return false; if (!name.equals(book.name)) return false; return true; }
68ce76e8-2a5e-49a6-8aef-129a2785fd5b
4
public String constructOrder(){ StringBuffer order = new StringBuffer(); int forCommands = 0; int numberOfPersonsForCommand = 0; String mealForCommand = null; if(this.isEveryOneOrdered()==0){ for(Command command: this.commands){ if(command.isForCommand()){ forCommands ++; numberOfPersonsForCommand = command.numberOfPersonsForCommand(); mealForCommand = command.mealOfPersonsForCommand(); order.append(command.addCommandToOrder()); } else order.append(command.addCommandToOrder()); } if(forCommands != numberOfPersonsForCommand){ order = new StringBuffer(); order.append("MISSING ").append(numberOfPersonsForCommand - forCommands).append(" for").append(mealForCommand); order.append("for ").append(numberOfPersonsForCommand); return order.toString(); } else { order = order.deleteCharAt(order.lastIndexOf(",")); return order.substring(1); } } else { order.append("MISSING "+this.isEveryOneOrdered()); return order.toString(); } }
0c4750b8-dc9d-4bba-839a-4f3b3f74d607
7
public void setImage(String fileName) { boolean old = true; if( image != null && ((isHovered && fileName.equals("hover" + name)) || (!isHovered && fileName.equals(name))) ) return; try { if(old) image = ImageIO.read( new File("Images\\"+ fileName +".png") ); else image = getImageResource(fileName +".png"); } catch(Exception e) { System.out.println(e); System.exit(1); } isHovered = !isHovered; }
c56aac3c-6fa9-4667-ab0b-c146148e8451
6
void exportXmlTemplate( XmlWriter xml, String legend ) { if(yVal1 == yVal2 && xVal1 != xVal2) { // hrule xml.startTag("hrule"); xml.writeTag("value", yVal1); xml.writeTag("color", color); xml.writeTag("legend", legend); xml.writeTag("width", lineWidth); xml.closeTag(); // hrule } else if(yVal1 != yVal2 && xVal1 == xVal2) { // vrule xml.startTag("vrule"); xml.writeTag("time", xVal1); xml.writeTag("color", color); xml.writeTag("legend", legend); xml.writeTag("width", lineWidth); xml.closeTag(); // vrule } else if(yVal1 != yVal2 && xVal1 != xVal2) { // general line xml.startTag("line"); xml.writeTag("time1", xVal1); xml.writeTag("value1", yVal1); xml.writeTag("time2", xVal2); xml.writeTag("value2", yVal2); xml.writeTag("color", color); xml.writeTag("legend", legend); xml.writeTag("width", lineWidth); xml.closeTag(); //line } }
70ab6f9a-b00f-4712-bb56-e8c09c72f748
4
@Override public boolean equals(Object object) { if (object == null) { return false; } if (object == this) { return true; } Course course = (Course) object; if (!classCode.equals(course.getClassCode())) { return false; } if (!section.equals(course.getSection())) { return false; } return true; }
1f9d398d-8887-4071-9820-6cc17e1c7496
5
public static String removeFormatting(String line) { int length = line.length(); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < length; i++) { char ch = line.charAt(i); if (ch == '\u000f' || ch == '\u0002' || ch == '\u001f' || ch == '\u0016') { // Don't add this character. } else { buffer.append(ch); } } return buffer.toString(); }
fc28ca5d-bdc7-4c77-9a19-5accbb2920f5
3
public static void main(String args[]) { String filename = ""; String pattern = "*"; if(args.length == 2){ filename = args[0]; pattern = args[1]; } else if(args.length == 1){ filename = args[0]; } else { System.out.println("Usage: java -jar " + System.getProperty("sun.java.command") + " zipFile [pattern]"); return; } ListedZip listedZip = new ListedZip(args[0]); ArrayList<ZipEntry> zeList = listedZip.list(pattern); for(ZipEntry ze: zeList){ System.out.println(ze.getName()); } }
f64064f4-3e6f-458f-a547-6e9f34e5bc54
7
public static Set<PDFInfoHolder> getSimplePDFInfoHolders(File pdfs1, File pdfs2, String prefix) { Set<PDFInfoHolder> pdfInfoHolders = new HashSet<PDFInfoHolder>(); // are those valid pathes if(pdfs1 != null && pdfs2 != null && pdfs1.isDirectory() && pdfs2.isDirectory()) { // create a filter to only get pdf files List<FilenameFilter> filters = new ArrayList<FilenameFilter>(); if (null != prefix && prefix.length() > 0 ) { PrefixFileFilter filter = new PrefixFileFilter(prefix, IOCase.SYSTEM); filters.add(filter); } filters.add(new SuffixFileFilter(".pdf", IOCase.INSENSITIVE)); FilenameFilter filter = new AndFileFilter(filters); //get all pdf file sin this folder String[] pdfDocuments1 = pdfs1.list(filter); for (int i=0; i<pdfDocuments1.length; i++) { // get the pdf file name String pdfFilename1 = pdfDocuments1[i]; // get the path for both pdf files File pdfFile1 = new File(pdfs1, pdfFilename1); File pdfFile2 = new File(pdfs2, pdfFilename1); // bind them together in a PDFInfoHolder objects PDFInfoHolder newPDFInfoHolder = new PDFInfoHolder(pdfFile1, pdfFile2); // remember them all pdfInfoHolders.add(newPDFInfoHolder); } // TODO what should happen if there are less reference documents than new generated ones } else { log.error("The path is not valid."); } return pdfInfoHolders; }
5365923e-3a4f-4ec4-8a57-ff6dc132fc60
7
public String tooltip(Coord c, boolean again) { if ((c.x >= 10) && (c.x < 10 + prof.hist.length) && (c.y >= 10) && (c.y < 10 + h)) { int x = c.x - 10; int y = c.y - 10; long t = (h - y) * (mt / h); Profile.Frame f = prof.hist[x]; if (f != null) { for (int i = 0; i < f.prt.length; i++) { if ((t -= f.prt[i]) < 0) return (String.format("%.2f ms, %s: %.2f ms", (((double) f.total) / 1000000), f.nm[i], (((double) f.prt[i]) / 1000000))); } } } return (""); }
95db434b-90c7-4c49-b800-082bb6a6ffc7
7
public void moveRandom() { if(getTimeStamp() == 0) // If clock is reset.. { setTimeStamp(TimeHandler.getTime()); // Set clock setActionTime(random.nextInt(1500) + 500); // Set a random duration (500-2000 ms) to move/stay switch(random.nextInt(4)) // Randomize a direction { case 0: moveY(-1); break; case 1: moveY(1); break; case 2: moveX(1); break; case 3: moveX(-1); break; } } if( !TimeHandler.timePassed(getTimeStamp(), getActionTime()) ) // If time hasn't expired, move or stand still.. { if(isMoving()) { move(); } else resetDirection(); } else // ..else reset clock and invert isMoving state { setMoving(); setTimeStamp(0); } }
e79bd8a7-d375-4496-ad6f-8804e7f12f3e
6
public void focusGained(FocusEvent e) { if (e.getSource() == InchesInput) { InchesInput.setText(" "); } else if (e.getSource() == FeetInput) { FeetInput.setText(" "); } else if (e.getSource() == YardsInput) { YardsInput.setText(" "); } else if (e.getSource() == MillimetersInput) { MillimetersInput.setText(" "); } else if (e.getSource() == CentimetersInput) { CentimetersInput.setText(" "); } else if (e.getSource() == MetersInput) { MetersInput.setText(" "); } }
8032af77-c0c5-4df4-83a8-21a88f05e346
3
static double NetwonRaphson() { if (f(v, 0) == 0) return 0; double xn = 0.5, x = 0; while (true) { x = xn - f(v, xn) / ff(v, xn); if (Math.abs(x - xn) < EPS) return xn; xn = x; } }
5b54d0bd-88de-4830-83b8-b4626d4a08b9
8
public ArrayList<ZoomDataRecord> getZoomData(RPChromosomeRegion selectionRegion, boolean contained) { int chromID, chromStart, chromEnd, validCount; float minVal, maxVal, sumData, sumSquares; int itemHitValue; int recordNumber = 0; // allocate the bed feature array list zoomDataList = new ArrayList<ZoomDataRecord>(); // check if all leaf items are selection hits RPChromosomeRegion itemRegion = new RPChromosomeRegion(leafHitItem.getChromosomeBounds()); int leafHitValue = itemRegion.compareRegions(selectionRegion); try { //for(int index = 0; mRemDataSize >= ZoomDataRecord.RECORD_SIZE; ++index) { for (int index = 0; remDataSize > 0; ++index) { recordNumber = index + 1; if (isLowToHigh) { // buffer stream arranged low to high bytes chromID = lbdis.readInt(); chromStart = lbdis.readInt(); chromEnd = lbdis.readInt(); validCount = lbdis.readInt(); minVal = lbdis.readFloat(); maxVal = lbdis.readFloat(); sumData = lbdis.readFloat(); sumSquares = lbdis.readFloat(); } else { // buffer stream arranged high to low bytes chromID = dis.readInt(); chromStart = dis.readInt(); chromEnd = dis.readInt(); validCount = dis.readInt(); minVal = dis.readFloat(); maxVal = dis.readFloat(); sumData = dis.readFloat(); sumSquares = dis.readFloat(); } if (leafHitValue == 0) { // contained leaf region always a hit String chromName = chromosomeMap.get(chromID); ZoomDataRecord zoomRecord = new ZoomDataRecord(zoomLevel, recordNumber, chromName, chromID, chromStart, chromEnd, validCount, minVal, maxVal, sumData, sumSquares); zoomDataList.add(zoomRecord); } else { // test for hit itemRegion = new RPChromosomeRegion(chromID, chromStart, chromID, chromEnd); itemHitValue = itemRegion.compareRegions(selectionRegion); // itemHitValue < 2 for intersection; itemHitValue == 0 for is contained if (!contained && Math.abs(itemHitValue) < 2 || itemHitValue == 0) { String chromName = chromosomeMap.get(chromID); ZoomDataRecord zoomRecord = new ZoomDataRecord(zoomLevel, recordNumber, chromName, chromID, chromStart, chromEnd, validCount, minVal, maxVal, sumData, sumSquares); zoomDataList.add(zoomRecord); } } // compute data block remainder fom size item read remDataSize -= ZoomDataRecord.RECORD_SIZE; } } catch (IOException ex) { log.error("Read error for zoom level " + zoomLevel + " leaf item " ); // accept this as an end of block condition unless no items were read if (recordNumber == 1) throw new RuntimeException("Read error for zoom level " + zoomLevel + " leaf item "); } return zoomDataList; }
da30d6ad-17d0-4b18-b67f-c232a5cce799
6
void addDevice(Device device) { // if device was in list of saved localhost devices, copy saved // preferences to this device for (Device d : model.getDevices()) { if (device.getSerialNumber().equals(d.getSerialNumber())) { device.copyProperties(d); break; } } // if user previously preferred not to delete local device from list, // avoids creating two entries for same device for (DevicePanel panel : panelList) { if (panel.getDevice().getSerialNumber() .equals(device.getSerialNumber())) { panel.setCaptureButton(true); return; } } DevicePanel devicePanel = new DevicePanel(model, device); ClientConnectionManager.getInstance().addClientChangedListener( devicePanel); GridBagConstraints devicePanelConstraints = new GridBagConstraints(); devicePanelConstraints.gridx = 0; devicePanelConstraints.anchor = GridBagConstraints.PAGE_START; devicePanelConstraints.gridwidth = GridBagConstraints.REMAINDER; devicePanelConstraints.weightx = 1; devicePanelConstraints.fill = GridBagConstraints.HORIZONTAL; devicePanelConstraints.insets = new Insets(1, 1, 1, 1); if (panelList.size() > 0) { GridBagConstraints lastConstraints = deviceListLayout .getConstraints(panelList.get(panelList.size() - 1)); lastConstraints.weighty = 0; deviceListLayout.setConstraints( panelList.get(panelList.size() - 1), lastConstraints); } devicePanelConstraints.weighty = 1; if (devicesMap.isEmpty()) { GridBagConstraints headerC = deviceListLayout .getConstraints(headerPanel); headerC.weighty = 0; deviceListLayout.setConstraints(headerPanel, headerC); } deviceListLayout .addLayoutComponent(devicePanel, devicePanelConstraints); add(devicePanel); devicesMap.put(device.getName(), devicePanel); panelList.add(devicePanel); revalidate(); repaint(); }
bf9187cb-b494-4bf2-8a4c-0a9d0c043ebf
4
@Override public void render(float interpolation) { Vector2 pos = Interpolator.linearInterpolate(oldPos, this.pos, interpolation); Renderer.drawRect(pos, new Vector2(dim.x,20), isSelected ? windowTopColor : windowMainColor, 1.0f); Renderer.drawRect(pos.add(new Vector2(0,20)), dim, windowMainColor, 1.0f); if(hoverX) Renderer.drawRect(new Vector2(pos.x+dim.x-20,pos.y), new Vector2(20), 0x000000, 1); Renderer.drawLineRect(new Vector2(pos.x+dim.x-20,pos.y), new Vector2(20), 0x000000, 1); Renderer.drawLine(new Vector2(pos.x+dim.x-20,pos.y), new Vector2(pos.x+dim.x,pos.y+20), 0xffffff, 1); Renderer.drawLine(new Vector2(pos.x+dim.x,pos.y), new Vector2(pos.x+dim.x-20,pos.y+20), 0xffffff, 1); Fonts.get("Arial").drawString(title, pos.x+10, pos.y+1, 20, 0xffffff); Renderer.startScissor(new Vector2(pos.x,pos.y+20), dim); Renderer.pushMatrix(); Renderer.translate(new Vector2(pos.x,pos.y+20)); renderContents(interpolation); for(int x=0;x<buttonList.size();x++) buttonList.get(x).render(interpolation); Renderer.translate(new Vector2(-pos.x,-pos.y-20)); Renderer.popMatrix(); Renderer.endScissor(); Renderer.drawLineRect(pos, dim.add(new Vector2(0,20)), 0x000000, 1.0f); Renderer.drawLine(new Vector2(pos.x, pos.y+20),new Vector2(pos.x+dim.x, pos.y+20),0.4f,0.4f,0.4f,1.0f); if(canResize()) { Renderer.drawLine(new Vector2(pos.x+dim.x-15,pos.y+dim.y+20), new Vector2(pos.x+dim.x,pos.y+dim.y+5), 0x000000, 1); Renderer.drawLine(new Vector2(pos.x+dim.x-9,pos.y+dim.y+20), new Vector2(pos.x+dim.x,pos.y+dim.y+11), 0x000000, 1); } }
c8bead16-9a4f-43d5-ada9-eb96524ff1db
2
private void fillInCounterParty() { for(Statement m : movementDataModel.getAllStatements()) { String name; if (newCounterParty == null) { name = null; } else { name = newCounterParty.getName(); } TmpCounterParty tmp = new TmpCounterParty(); tmp.setName(name); tmp.setCounterParty(newCounterParty); m.setTmpCounterParty(tmp); } movementDataModel.fireTableDataChanged(); }
c1e811dd-ccc9-425b-bbaf-0c225e821853
1
public boolean SetPlayerBirthday(String player, Date bdate) { String datestr; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); datestr = sdf.format(bdate); BirthdayRecord birthday = getPlayerRecord(player); String query; if (birthday == null) { query = "INSERT INTO birthdaygift (birthdayDate, player, lastGiftDate, lastAnnouncedDate) VALUES (?, ?, '', '')"; } else { query = "UPDATE birthdaygift SET birthdayDate=? WHERE player=?"; } dbcon.PreparedUpdate(query, new String[]{datestr, player.toLowerCase()}); return true; }
42ce8ffd-3702-4512-8e7f-72b9c7a6ee8a
3
public boolean havePointInBound( AABB aabb ) { Matrix4f transformation = getTransform().getTransformation(); Vector3f p1 = transformation.transform( point1 ); Vector3f p2 = transformation.transform( point2 ); Vector3f p3 = transformation.transform( point3 ); if ( p1.isInBound( aabb ) || p2.isInBound( aabb ) || p3.isInBound( aabb ) ) return true; return false; }
bdb47cec-c526-4994-b95e-02995354b9c1
1
public void initLevel(int l) throws SlickException{ if(currentLevel <= 10){ pickables = new ArrayList<Pickable>(); mobs = new ArrayList<Mob>(); level = new Level(l); player = new Player(level.startX, level.startY); respawnCounter = 0; } }
a35520f4-b6fa-4f8e-af64-bf683e353050
4
public static boolean testerPrimalite(long n) { boolean trouve=false; int i=0; long temp=0; while(!trouve && i<NB_TESTS) { temp=(int)((Math.random()*n)); if(temp==0) { temp++; } if(calculSoloStras(temp,n)!=syJacobi(temp,n)) { trouve=true; } i++; } return !trouve; }
e5caa0b2-66a7-457e-9778-368296f667e4
6
public static String getMCTimeString(long var0, long var2) { long var4 = (long)((int)((var0 / 1000L + 6L) % 24L)); int var6 = (int)((double)(var0 % 1000L) / 1000.0D * 60.0D); boolean var7 = var4 < 12L; var4 %= var2; String var8 = ""; if (var2 == 24L) { var8 = (var4 < 10L ? "0" : "") + String.valueOf(var4); } else { var8 = String.valueOf(var4 == 0L ? 12L : var4); } String var9 = (var6 < 10 ? "0" : "") + String.valueOf(var6); return var8 + ":" + var9 + (var2 == 12L ? (var7 ? "AM" : "PM") : ""); }
68c8832e-2718-4b88-abbd-1c68bc1fa9db
6
public void refreshCaches() throws RegistryErrorException { if(isCachingActive()) { if(caches != null && caches.size() > 0) { List tmpCache = (List) caches.clone(); caches = new ArrayList(); for (int x = 0; tmpCache != null && x != tmpCache.size(); x++) { CachedEntry entry = (CachedEntry) tmpCache.get(x); if (entry != null) { String key = entry.getKey(); cacheKeys(key, 1); } } } } }
239e2c3c-1485-4926-ab63-f1ac8acd9ecd
5
public SecuredMessageTriggerBean execute(SecuredMessageTriggerBean message) throws GranException { SecuredTaskBean task = message.getTask(); String text = message.getDescription(); EggBasket<SecuredUDFValueBean, SecuredTaskBean> refs = AdapterManager.getInstance().getSecuredIndexAdapterManager().getReferencedTasksForTask(task); SecuredUDFBean relatedUdf = AdapterManager.getInstance().getSecuredFindAdapterManager().findUDFById(task.getSecure(), PROBLEM_RFC_UDFID); if (refs!=null ) { for (Entry<SecuredUDFValueBean, List<SecuredTaskBean>> entry : refs.entrySet()){ if (entry.getKey().getUdfId().equals(relatedUdf.getId())){ List<SecuredTaskBean> incidentsInvolved = entry.getValue(); if (incidentsInvolved != null) { for (SecuredTaskBean p : incidentsInvolved) { executeOperation(PROBLEM_CLOSE_OPERATION, p, text, message.getUdfValues()); } } } } } return message; }
5ee570e8-2f22-42b3-be3f-6563dd2f7042
8
public void update(String msg) { if (msg.startsWith("CUL:")) { String[] users = msg.substring(4).split("\\|"); userListPanel.removeAll(); userListPanel.add(userLabel); JSeparator separator = new JSeparator(SwingConstants.HORIZONTAL); separator.setMaximumSize(new Dimension(32767, 2)); separator.setAlignmentY(Component.TOP_ALIGNMENT); userListPanel.add(separator); userLabels.clear(); for (int i = 0; i < users.length; i++) { UserLabel l = new UserLabel(users[i]); userLabels.add(l); l.setBorder(new EmptyBorder(3,3,3,5)); l.setAlignmentY(Component.TOP_ALIGNMENT); userListPanel.add(l); } userListPanel.repaint(); validate(); } else if (msg.startsWith("CON:")) { UserLabel l = new UserLabel(msg.substring(4)); if (userLabels.contains(l)) { l = null; return; } else { l.setBorder(new EmptyBorder(3,3,3,5)); l.setAlignmentY(Component.TOP_ALIGNMENT); userLabels.add(l); userListPanel.add(l); userListPanel.repaint(); validate(); console(l.getText() + " has connected."); } } else if (msg.startsWith("DIS:")) { String name = msg.substring(4); for (UserLabel l : userLabels) { if (l.getText().equals(name)) { userListPanel.remove(l); userLabels.remove(l); userListPanel.repaint(); validate(); console(name + " has disconnected."); break; } } } else if (msg.startsWith("MSG:")) { console(msg.substring(4)); } else { console(msg); } }
87565570-0733-4ae4-ad5e-ffc6ba294812
3
private void setPiece(int row, int col, Piece p) { if (p == EMP && get(col, row) != EMP) { Piece n = get(col, row); numPiecesRow[row - 1] -= 1; numPiecesCol[col - 1] -= 1; numPiecesDownDiag[row + col - 2] -= 1; numPiecesUpDiag[col - row + 7] -= 1; _contents[row - 1][col - 1] = p; changeSetMap(n.side(), cellNumber(col, row), false); } else { if (get(col, row) != EMP) { setPiece(row, col, EMP); } numPiecesRow[row - 1] += 1; numPiecesCol[col - 1] += 1; numPiecesDownDiag[row + col - 2] += 1; numPiecesUpDiag[col - row + 7] += 1; _contents[row - 1][col - 1] = p; changeSetMap(p.side(), cellNumber(col, row), true); } }
d4d832f4-00d3-4fab-bd0d-e4dd51cc4300
6
void print(Node t, int n, boolean p) { if (p) { t.print(n, true); } else { if (n > 0) { for (int i = 0; i < n; i++) System.out.print(" "); } System.out.print("("); if (t.isPair() && t.getCdr() != null) { t.getCar().print(n, true); t.getCdr().print(-n, true); } else if (!t.isPair()) t.print(-n, true); else System.err.println("Null Pointer"); } }
c05e7561-42a5-448b-89f5-fe62614bc427
9
public static Map<String, String> uriToMap(String uri) { if (StringUtils.isBlank(uri)) { return null; } try { // LinkedHashMap is our impl choice, because order of params is awesome sometimes Map<String, String> params = new LinkedHashMap<String, String>(); String query = ""; // remove '/?' from uri if need if (uri.contains("?")) { String[] urlParts = uri.split("\\?"); if (urlParts.length > 1) { query = urlParts[1].trim(); } } else { query = uri; } // split string to key value pair and put to map for (String param : query.split("&")) { String[] pair = param.split("="); String key; try { key = URLDecoder.decode(pair[0], "UTF-8"); } catch (IllegalArgumentException e) { key = pair[0]; } String value = ""; if (pair.length > 1) { try { value = URLDecoder.decode(pair[1], "UTF-8"); } catch (IllegalArgumentException e) { key = pair[1]; } } boolean isValueExist = params.get(key) != null; if (!isValueExist) { params.put(key, value); } } return params; } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } }
22132022-0d05-436c-9061-aae98f27d073
0
public String getCp() { return cp; }
1f4be285-a3d5-4ecf-8bd3-8cacd6b5fffc
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(VueInterlocuteur.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VueInterlocuteur.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VueInterlocuteur.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VueInterlocuteur.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 VueInterlocuteur().setVisible(true); } }); }
df7a5d36-ee64-4bed-a2ac-f17a0e6e7786
7
private void jTable8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable8MouseClicked System.out.println("Count:" + evt.getClickCount()); if (evt.getButton() == java.awt.event.MouseEvent.BUTTON3) { System.out.println("Right Click"); int r = jTable8.rowAtPoint(evt.getPoint()); if (r >= 0 && r < jTable8.getRowCount()) { jTable8.setRowSelectionInterval(r, r); } else { jTable8.clearSelection(); } if (jTable8.getSelectedRow() > -1) { JPopupMenu popupMenu = new JPopupMenu(); PaymentInboxRightClickListener menuListener = new PaymentInboxRightClickListener(); JMenuItem menuItem = new JMenuItem("Test"); popupMenu.add(menuItem); menuItem.addActionListener(menuListener); menuItem = new JMenuItem("Test1"); popupMenu.add(menuItem); menuItem.addActionListener(menuListener); popupMenu.show(evt.getComponent(), evt.getX(), evt.getY()); } } if (evt.getClickCount() == 2) { String key = (String) jTable8.getModel().getValueAt(jTable8.getSelectedRow(), 3); String subject = (String) jTable8.getModel().getValueAt(jTable8.getSelectedRow(), 0); System.out.println("In NYMBOX double clcik, key:" + key); String[] row = (String[]) nymBox.get(key); if (row != null) { NymBoxDetailsDialog nymDialog = new NymBoxDetailsDialog(this, true, row[7] == "true" ? "Verified" : "Not Verified", row[6], subject); nymDialog.setVisible(true); } } }
3c4db87f-e0f0-4a48-b8ad-5d8319666838
8
@Override public void setValueAt(Object valor, int rowIndex, int columnIndex) { // Pega o contato referente a linha especificada. Contato contato = linhas.get(rowIndex); switch (columnIndex) { case ID: contato.setId((String) valor); case NOME: contato.setNome((String) valor); break; case APELIDO: contato.setApelido((String) valor); break; case DATANASCIMENTO: contato.setDataNascimento((String) valor); break; case TELEFONERES: contato.setTelefoneResidencial((String) valor); break; case TELEFONECEL: contato.setTelefoneCelular((String) valor); break; case CIDADE: contato.setCidade((String) valor); break; case ESTADO: contato.setEstado((String) valor); break; default: // Não deve ocorrer, pois só existem 4 colunas throw new IndexOutOfBoundsException("Número excedido de colunas"); } fireTableCellUpdated(rowIndex, columnIndex); // Notifica a atualização da célula }
04bd1fae-c214-4d5e-b3a0-3bbe9aaeda0d
2
protected void processPreBlocks(List<String> preBlocks) { if(generateStatistics) { for(String block : preBlocks) { statistics.setPreservedSize(statistics.getPreservedSize() + block.length()); } } }
d0aef274-1496-42d9-94af-f82fce1dc4f0
6
@Override public void onEnable() { instance = this; c = new Config(this); if (Config.defaultConfig) { getLogger().warning("RoyalIRC is disabled until the config is edited."); setEnabled(false); return; } version = getDescription().getVersion(); bh = new BotHandler(this); bh.createBots(); final PluginManager pm = getServer().getPluginManager(); pm.registerEvents(new BChatListener(this), this); pm.registerEvents(new BServerListener(this), this); getCommand("royalirc").setExecutor(new CmdRoyalIRC(this)); getCommand("ircmessage").setExecutor(new CmdIRCMessage(this)); getCommand("irckick").setExecutor(new CmdIRCKick(this)); getCommand("ircrestartbots").setExecutor(new CmdIRCRestartBots(this)); //-- Hidendra's Metrics --// try { Matcher matcher = versionPattern.matcher(version); matcher.matches(); // 1 = base version // 2 = -SNAPSHOT // 5 = build # String versionMinusBuild = (matcher.group(1) == null) ? "Unknown" : matcher.group(1); String build = (matcher.group(5) == null) ? "local build" : matcher.group(5); if (matcher.group(2) == null) build = "release"; final Metrics m = new Metrics(this); Metrics.Graph g = m.createGraph("Version"); // get our custom version graph g.addPlotter( new Metrics.Plotter(versionMinusBuild + "~=~" + build) { @Override public int getValue() { return 1; // this value doesn't matter } } ); // add the donut graph with major version inside and build outside m.addGraph(g); // add the graph if (!m.start()) getLogger().info("You have Metrics off! I like to keep accurate usage statistics, but okay. :("); else getLogger().info("Metrics enabled. Thank you!"); } catch (Exception ignore) { getLogger().warning("Could not start Metrics!"); } }
e5457f33-940c-4887-9f46-e284421a64c2
1
public long getLong(Object key) { Number n = get(key); if (n == null) { return (long) 0; } return n.longValue(); }
95b1da57-b2ff-4015-be26-61d234698a8d
0
public void IncrementLeftByBus() { this.leftByBus += 1; }
a24f8d8f-dc33-4469-8e0c-b7352320fd51
1
public static void main(String[] args) { try { Window fenetre = new Window(); } catch (Exception e) { e.printStackTrace(); } }
0624451a-4d83-446d-8357-aa59caa3196d
5
private ArrayList addCustomer(HttpServletRequest request) { ArrayList al = new ArrayList(); String passport = request.getParameter("passport"); String name = request.getParameter("name"); String password = request.getParameter("password"); String postal = request.getParameter("postal"); int phone = Integer.parseInt(request.getParameter("phone")); String email = request.getParameter("email"); if (passport.equals(null) || name.equals(null) || password.equals(null) || email.equals(null)) { return al; } password = hashpw(password); boolean ctl = shsmb.createMember(passport, name, password, postal, phone, email); if (ctl==true) { al.add(passport); al.add(name); al.add(password); al.add("Customer added successfully."); return al; } else { al.add("nil"); al.add("nil"); al.add("nil"); al.add("Registatration fail, passport is already registered. pls use another one."); return al; } }
0439f6ab-7c7f-45ce-9309-df4779878c40
5
@Override public void run() { logger.info("Starting announce thread for " + torrent.getName() + " to " + torrent.getAnnounceUrl() + "..."); // Set an initial announce interval to 5 seconds. This will be updated // in real-time by the tracker's responses to our announce requests. this.interval = 5; this.initial = true; while (!this.stop) { this.announce(this.initial ? AnnounceEvent.STARTED : AnnounceEvent.NONE); try { logger.trace("Sending next announce in " + this.interval + " seconds."); Thread.sleep(this.interval * 1000); } catch (InterruptedException ie) { // Ignore } } if (!this.forceStop) { // Send the final 'stopped' event to the tracker after a little // while. try { Thread.sleep(500); } catch (InterruptedException ie) { // Ignore } this.announce(AnnounceEvent.STOPPED, true); } }
ba669dca-04da-42ef-9e03-03397df88495
5
private void pop(char c) throws JSONException { if (this.top <= 0) { throw new JSONException("Nesting error."); } char m = this.stack[this.top - 1] == null ? 'a' : 'k'; if (m != c) { throw new JSONException("Nesting error."); } this.top -= 1; this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; }
5266186c-faee-4439-a929-93f88d7d05d4
9
@Override public void unInvoke() { if((pit!=null) &&(canBeUninvoked()) &&(pit.size()>1)) { final Room R1=pit.get(0); final Room R2=pit.get(pit.size()-1); while(R1.numInhabitants()>0) { final MOB M=R1.fetchInhabitant(0); if(M!=null) { M.killMeDead(false); R1.delInhabitant(M); } } while(R2.numInhabitants()>0) { final MOB M=R2.fetchInhabitant(0); if(M!=null) { M.killMeDead(false); R2.delInhabitant(M); } } final Room R=R2.getRoomInDir(Directions.UP); if((R!=null)&&(R.getRoomInDir(Directions.DOWN)==R2)) { R.rawDoors()[Directions.DOWN]=null; R.setRawExit(Directions.DOWN,null); } R2.rawDoors()[Directions.UP]=null; R2.setRawExit(Directions.UP,null); R2.rawDoors()[Directions.DOWN]=null; R2.setRawExit(Directions.DOWN,null); R1.rawDoors()[Directions.UP]=null; R1.setRawExit(Directions.UP,null); pit=null; R1.destroy(); R2.destroy(); super.unInvoke(); } else { pit=null; super.unInvoke(); } }
b4614eeb-0886-47f1-9ed7-7f874a128162
5
public static int getY(RSInterface parent, RSInterface child) { if (parent == null || parent.children == null || child == null) { return -1; } for (int index = 0; index < parent.children.size(); index++) { if (parent.children.get(index) == child.id) { return parent.childY.get(index); } } return -1; }
c97169cd-8619-40b4-a0c5-f96760d48c75
1
public void setStackDepth(int depth) { stackDepth = depth; if (stackDepth > maxStack) maxStack = stackDepth; }
3fab7113-bff3-4c68-8a0c-2a291793a35b
7
public void dragDropEnd(DragSourceDropEvent dsde) { Canvas canvas = (Canvas) dsde.getDragSourceContext().getComponent(); CanvasModel canvasModel = canvas.getCanvasModel(); Rectangle bounds = null; try { bounds = (Rectangle) dsde.getDragSourceContext().getTransferable().getTransferData(widgetFlavor); } catch (UnsupportedFlavorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if ( dsde.getDropSuccess() ) { if ( dsde.getDropAction() == DnDConstants.ACTION_MOVE) { // we need to remove the source element now Point p = new Point(bounds.x,bounds.y); CanvasWidget widget = null; for ( CanvasWidget searchWidget : canvasModel.widgetList ) { if ( searchWidget.getBounds().getLocation().equals(p) ) widget = searchWidget; } if ( widget != null) canvasModel.remove(widget); } } else { // we need to mark it as no longer moving Point p = new Point(bounds.x,bounds.y); CanvasWidget widget = canvasModel.getWidgetAt(p); widget.setMoving(false); canvasModel.notifyModelChanged(); } }
22688f2c-8138-4647-874f-d55f789e8365
2
@Test public void testPlayerUsesTeleport() throws InvalidActionException { factory.addFlagOfPlayerToPlayerOneInventory(); ElementInfo flag = game.getActivePlayerInfo().getInventoryItems().get(0); game.moveAction(Direction.RIGHTUP); boolean containsFlag = false; for (Position pos : grid.getPositionsAround(new Position(1, 8))) { if (containsElement(game.getElementsOnPosition(pos), flag)) { containsFlag = true; break; } } assertTrue(containsFlag); }
53af492b-de38-4a97-a019-6827c2a37f88
8
@SuppressWarnings("unchecked") private void writeData(Collection<T> data) { try { Set<Col> columnsToAdd = Sets.newTreeSet(); for (T t : data) { if (anyColumn != null) { appendAnyColumns(t, columnsToAdd); } } addColumns(columnsToAdd, true); for (T t : data) { org.apache.poi.ss.usermodel.Row row = sheet.getNativeSheet().createRow(rowIndex); int i = 0; for (Col col : columns) { Set<Field> fields = ReflectionUtils.getAllFields(t.getClass(), withName(col.getFieldName())); Field field = fields.iterator().next(); field.setAccessible(true); Object fieldValueObj = null; if (col.isAnyColumn()) { Map<String, Object> anyColumnMap = (Map<String, Object>) field.get(t); fieldValueObj = anyColumnMap.get(col.getName()); } else { fieldValueObj = field.get(t); } Cell cell = row.createCell(i); writeToCell(cell, col, fieldValueObj); i++; } rowIndex++; } } catch (SecurityException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
5e352271-8a53-4928-88f5-9ee6b23614d0
1
public void testStoreRawData() { DataSet ds; final String cols = "column1,column2,column3\r\nVAL1,VAL2,VAL3"; Parser p = DefaultParserFactory.getInstance().newDelimitedParser(new StringReader(cols), ',', FPConstants.NO_QUALIFIER); p.setStoreRawDataToDataSet(true); ds = p.parse(); ds.next(); assertEquals("VAL1,VAL2,VAL3", ds.getRawData()); p = DefaultParserFactory.getInstance().newDelimitedParser(new StringReader(cols), ',', FPConstants.NO_QUALIFIER); ds = p.parse(); ds.next(); try { ds.getRawData(); fail("Should have received an FPExcpetion..."); } catch (final FPInvalidUsageException e) { } }
40cec72d-bb3c-4122-93a5-681559c6a6b8
4
public static boolean borarr(String cod){ try { //creación de un fichero auxiliar donde iremos colocando todos los productos excepto el que queramos borrar BufferedWriter escribe=Files.newBufferedWriter(path2, java.nio.charset.StandardCharsets.UTF_8, java.nio.file.StandardOpenOption.CREATE); //abrimos en modo lectura el fichero donde tenemos la bbdd de productos BufferedReader stdin=Files.newBufferedReader(path, java.nio.charset.StandardCharsets.UTF_8); String linea=""; while((linea=stdin.readLine())!=null){ String part[]=linea.split(";"); if(part[0].equalsIgnoreCase(cod)){//si el cod , es el mismo al que queremos borrar no copia en el fichero auxiliar }else{//si el cod, es distinto copia en el fichero auxiliar. escribe.write(part[0]+";"+part[1]+";"+part[2]+";"+part[3]); escribe.newLine(); } } //mueve el contenido del fichero auxiliar al fichero principal Files.move(path2, path, java.nio.file.StandardCopyOption.REPLACE_EXISTING); //eliminamos el fichero auxiliar Files.deleteIfExists(path2); escribe.close(); stdin.close(); }catch(InvalidPathException e){ System.out.println("Error en leer la ruta del fichero "+e); return false; }catch (IOException e) { e.printStackTrace(); return false; } return true; }
86656032-e0c5-40db-aa9e-c1af6f38424a
8
protected double distance(Instance first, Instance second) { double distance = 0; int firstI, secondI; for (int p1 = 0, p2 = 0; p1 < first.numValues() || p2 < second.numValues();) { if (p1 >= first.numValues()) { firstI = m_instances.numAttributes(); } else { firstI = first.index(p1); } if (p2 >= second.numValues()) { secondI = m_instances.numAttributes(); } else { secondI = second.index(p2); } if (firstI == m_instances.classIndex()) { p1++; continue; } if (secondI == m_instances.classIndex()) { p2++; continue; } double diff; if (firstI == secondI) { diff = difference(firstI, first.valueSparse(p1), second.valueSparse(p2)); p1++; p2++; } else if (firstI > secondI) { diff = difference(secondI, 0, second.valueSparse(p2)); p2++; } else { diff = difference(firstI, first.valueSparse(p1), 0); p1++; } distance += diff * diff; } return Math.sqrt(distance / m_instances.numAttributes()); }
1469d472-78c9-4677-90f9-9e9f3e02e50e
9
private void switchActvLabelTxtFieldVisibility(final Component comp, final boolean saveLabelChange){ final boolean visible = true; if( comp instanceof JLabel ){ JLabel jl = (JLabel)comp; jl.setVisible( !visible ); final JTextField jtf = jTextFieldsArr[ Integer.parseInt(comp.getName()) ]; jtf.setText( jl.getText() ); jtf.setVisible( visible ); jtf.requestFocus(); } if( comp instanceof JTextField ){ //If not visible, exit. if( !comp.isVisible() ) { return; } final JTextField jtxtf = (JTextField)comp; jtxtf.setVisible(!visible); final MyActvJLabel myjl = jLabelsActvArr[Integer.parseInt(comp.getName())]; myjl.setVisible(visible); //Set text if (saveLabelChange) { final String jTextFieldTxt = jtxtf.getText(); if (jTextFieldTxt != null && !"".equals(jTextFieldTxt)) { //check if text changed... if (jTextFieldTxt.equals(myjl.getText())) { return; } int actvLabelId = getFromDBActvLabelId(jTextFieldTxt); if (isActvIdRepeatToday(actvLabelId)) { JOptionPane.showInternalMessageDialog(jPanel1, recursosTexto.getString("msgErrIsRepActvLbl"), recursosTexto.getString("msgErrIsRepActvLblT"), JOptionPane.ERROR_MESSAGE); return; } //First check if the label's text already exists in the DB. if (actvLabelId == ACTV_CAT_UNSPECIFIED_ID) { updateScreenResetRowValues(currentlyShownActivityRowsNum); //Reset values of default component ONLY if NEW label, else use DBs value... actvLabelId = updateInDBActvLabelDesc(jTextFieldTxt, COMPONENT_TYPE_DEFAULT); } myjl.setId(actvLabelId); myjl.setText(jTextFieldTxt); //update probable missmatch //updateScreenActvIdDayMissMatch(); //Fix to save label changes to DB updateInDBDayEntry( DAYS_TO_ROLL_TODAY_STR ); } } } }
863d4d48-ced8-4000-bcdc-89807f4131a5
1
public APacket copy() { log.finer("Copying a Packet!"); APacket p = null; try { p = this.getClass().newInstance(); DataOut dataOut = DataOut.newInstance(); writeToData(dataOut); byte[] b = dataOut.getBytes(); p.readFromData(DataIn.newInstance(b)); } catch(InstantiationException | IllegalAccessException | IOException e) { e.printStackTrace(); } return p; }
62db64fb-dba6-4154-ab48-4a4fc4dd68f6
5
public Display() { System.out.println("Display::Display();"); setForeground(UIManager.getColor("Button.highlight")); setBackground(Color.WHITE); setTitle("Modelowanie Wielkoskalowe - Rozrost ziaren"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 1100, 700); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu mnPlik = new JMenu("Plik"); menuBar.add(mnPlik); JMenuItem mntmZamknij = new JMenuItem("Zamknij"); mntmZamknij.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { System.exit(0); } }); chckbxmntmPamitajRozmieszczenieZiaren = new JCheckBoxMenuItem("Pamiętaj rozmieszczenie ziaren"); chckbxmntmPamitajRozmieszczenieZiaren.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { Core.Config.menuSaveMap = !Display.this.chckbxmntmPamitajRozmieszczenieZiaren.isSelected(); } }); chckbxmntmCzyPlanszePrzed = new JCheckBoxMenuItem("Czyść plansze przed startem"); chckbxmntmCzyPlanszePrzed.setSelected(true); chckbxmntmCzyPlanszePrzed.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { Core.Config.menuClean = !Display.this.chckbxmntmCzyPlanszePrzed.isSelected(); } }); mnPlik.add(chckbxmntmCzyPlanszePrzed); mnPlik.add(chckbxmntmPamitajRozmieszczenieZiaren); mnPlik.add(mntmZamknij); JMenu mnRozmieszczenieZarodkw = new JMenu("Rozmieszczenie zarodków"); menuBar.add(mnRozmieszczenieZarodkw); rdbtnmntmRwnomierne = new JRadioButtonMenuItem("Równomierne"); rdbtnmntmRwnomierne.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent arg0) { Core.Config.rozmieszczenie = 1; } }); mnRozmieszczenieZarodkw.add(rdbtnmntmRwnomierne); rdbtnmntmLosowepromieKoa = new JRadioButtonMenuItem("Losowe (promień koła)"); rdbtnmntmLosowepromieKoa.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent arg0) { Core.Config.rozmieszczenie = 2; } }); rdbtnmntmLosowepromieKoa.setSelected(true); mnRozmieszczenieZarodkw.add(rdbtnmntmLosowepromieKoa); rdbtnmntmLosowePrzypadkowe = new JRadioButtonMenuItem("Losowe przypadkowe"); rdbtnmntmLosowePrzypadkowe.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent arg0) { Core.Config.rozmieszczenie = 3; } }); mnRozmieszczenieZarodkw.add(rdbtnmntmLosowePrzypadkowe); JRadioButtonMenuItem rdbtnmntmLosoweZPromieniem = new JRadioButtonMenuItem("Losowe z promieniem"); rdbtnmntmLosoweZPromieniem.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { Core.Config.rozmieszczenie = 4; } }); mnRozmieszczenieZarodkw.add(rdbtnmntmLosoweZPromieniem); JRadioButtonMenuItem rdbtnmntmMonteCarlo = new JRadioButtonMenuItem("Monte Carlo"); rdbtnmntmMonteCarlo.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { Core.Config.rozmieszczenie = 5; } }); mnRozmieszczenieZarodkw.add(rdbtnmntmMonteCarlo); roz_zarodkow = new ButtonGroup(); roz_zarodkow.add(rdbtnmntmRwnomierne); roz_zarodkow.add(rdbtnmntmLosowepromieKoa); roz_zarodkow.add(rdbtnmntmLosowePrzypadkowe); roz_zarodkow.add(rdbtnmntmLosoweZPromieniem); roz_zarodkow.add(rdbtnmntmMonteCarlo); //=========================== JMenu mnPeriodyczno = new JMenu("Periodyczność"); menuBar.add(mnPeriodyczno); JRadioButtonMenuItem rdbtnmntmTak = new JRadioButtonMenuItem("Tak"); rdbtnmntmTak.setSelected(true); rdbtnmntmTak.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { Core.Config.bc = 0; } }); mnPeriodyczno.add(rdbtnmntmTak); JRadioButtonMenuItem rdbtnmntmNie = new JRadioButtonMenuItem("Nie"); rdbtnmntmNie.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { Core.Config.bc=1; } }); mnPeriodyczno.add(rdbtnmntmNie); bg_periodycznosc = new ButtonGroup(); bg_periodycznosc.add(rdbtnmntmTak); bg_periodycznosc.add(rdbtnmntmNie); /*JMenu mnMetodaRozrostu = new JMenu("Metoda rozrostu ziaren"); menuBar.add(mnMetodaRozrostu); JRadioButtonMenuItem rdbtnmntmNaiwnyRozrostZiaren = new JRadioButtonMenuItem("Naiwny rozrost ziaren"); rdbtnmntmNaiwnyRozrostZiaren.setSelected(true); rdbtnmntmNaiwnyRozrostZiaren.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent arg0) { Core.Config.metoda = 0; } }); mnMetodaRozrostu.add(rdbtnmntmNaiwnyRozrostZiaren); JRadioButtonMenuItem rdbtnmntmZarodkowanie = new JRadioButtonMenuItem("Zarodkowanie"); rdbtnmntmZarodkowanie.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { Core.Config.metoda = 1; } }); rdbtnmntmZarodkowanie.setSelected(true); mnMetodaRozrostu.add(rdbtnmntmZarodkowanie); ButtonGroup bg_metoda = new ButtonGroup(); bg_metoda.add(rdbtnmntmNaiwnyRozrostZiaren); bg_metoda.add(rdbtnmntmZarodkowanie); */ //ButtonGroup rek_metoda = new ButtonGroup(); //================================================ contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); JPanel panel = new JPanel(); contentPane.add(panel, BorderLayout.NORTH); panel.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { System.out.println("KeyPressed: "+e.getKeyCode()+", ts="+e.getWhen()); } @Override public void keyReleased(KeyEvent e) { System.out.println("keyReleased: "+e.getKeyCode()+", ts="+e.getWhen()); } }); JLabel lblPdzel = new JLabel("Sąsiedztwo:"); panel.add(lblPdzel); final JComboBox comboBox_1 = new JComboBox(); comboBox_1.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent argP) { Core.Config.sasiedztwo = comboBox_1.getSelectedIndex(); //System.out.println("Wybrano pedzel: "+Core.Config.pedzel+" "); } }); comboBox_1.setBackground(new Color(255, 255, 255)); comboBox_1.setModel(new DefaultComboBoxModel(this.pedzle)); panel.add(comboBox_1); // ================================= generuj grafike ================================ panel_1 = new Plansza(); panel_1.setBackground(SystemColor.text); contentPane.add(panel_1, BorderLayout.CENTER); new Thread(panel_1).start(); // ================================= akcja generowania ================================ this.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { panel_1.refresh(); } }); JButton btnGeneruj = new JButton("START"); btnGeneruj.setBackground(Color.GREEN); btnGeneruj.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (Core.Config.menuClean) Display.this.panel_1.clean(); if (Core.Config.menuSaveMap) { if (!Core.pkts.isEmpty()) { Display.this.panel_1.clean(); Display.this.panel_1.loadMap(); } else { Display.this.panel_1.random(); Display.this.panel_1.saveMap(); } } else { Display.this.panel_1.random(); } Display.this.panel_1.refresh(); Core.Config.StatusStart = 1; } }); JLabel label_1 = new JLabel(" "); panel.add(label_1); JLabel lblIloZiaren = new JLabel("Ziarna:"); panel.add(lblIloZiaren); final JSpinner spinner = new JSpinner(); spinner.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent arg0) { Core.Config.punkty = (Integer) spinner.getValue(); } }); spinner.setModel(new SpinnerNumberModel(Core.Config.punkty, 1, 360, 1)); panel.add(spinner); JLabel label = new JLabel(" "); panel.add(label); JLabel lblCzas = new JLabel("Czas"); panel.add(lblCzas); spinner_1 = new JSpinner(); spinner_1.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent arg0) { Core.Config.delay = (Integer) spinner_1.getValue(); } }); spinner_1.setModel(new SpinnerNumberModel(20, 1, 9999, 1)); panel.add(spinner_1); JLabel lblMs = new JLabel("ms"); panel.add(lblMs); JLabel label_2 = new JLabel(" "); panel.add(label_2); panel.add(btnGeneruj); JButton btnKoniec = new JButton("STOP"); btnKoniec.setBackground(Color.RED); btnKoniec.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { Core.Config.StatusStart = 0; } }); panel.add(btnKoniec); JButton btnReset = new JButton("RESET"); btnReset.setBackground(Color.BLACK); btnReset.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { Display.this.panel_1.clean(); Display.this.panel_1.refresh(); } }); panel.add(btnReset); JButton btnRekrystalizacja = new JButton("REKRYSTALIZACJA"); btnRekrystalizacja.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { Core.Config.rekrystalizacja = (Core.Config.rekrystalizacja==1)?0:1; } }); panel.add(btnRekrystalizacja); JButton btnMc = new JButton("MC"); btnMc.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { Core.Config.mc = (Core.Config.mc==1)?0:1; } }); panel.add(btnMc); }
f7d28b0e-0378-4043-95f8-d4f906feecbb
3
public void perform(Action a) { try { //System.out.println(this + " " + a + " go"); a.go(); } catch (NoSuchMethodException impossible) { } catch (InvocationTargetException impossible) { } catch (IllegalAccessException impossible) { } }
f87c8757-bc0f-4ff2-abc4-3906e1214da2
0
public void setjButtonSuiv(JButton jButtonSuiv) { this.jButtonSuiv = jButtonSuiv; }
3615a876-d1af-46fe-9058-e3d19afc831a
6
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(); }
a9ca624c-32dc-4f4d-8f6a-37380bbbb3bd
5
public int getWidth(String text) { if (text == null) { return 0; } int width = 0; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '@' && i + 4 < text.length() && text.charAt(i + 4) == '@') { i += 4; } else { width += charWidths[text.charAt(i)]; } } return width; }
aa1c9935-0cbd-4400-b295-e02299b7077d
2
@Override public void display(Boolean showCorrect) { System.out.println(prompt); if (answer!=null && showCorrect){ System.out.println("The answer is: " + answer); } }
55791db1-52a1-4b94-906e-f4a4d29c5db2
2
public void testWithers() { DateTime test = new DateTime(1970, 6, 9, 10, 20, 30, 40, GJ_DEFAULT); check(test.withYear(2000), 2000, 6, 9, 10, 20, 30, 40); check(test.withMonthOfYear(2), 1970, 2, 9, 10, 20, 30, 40); check(test.withDayOfMonth(2), 1970, 6, 2, 10, 20, 30, 40); check(test.withDayOfYear(6), 1970, 1, 6, 10, 20, 30, 40); check(test.withDayOfWeek(6), 1970, 6, 13, 10, 20, 30, 40); check(test.withWeekOfWeekyear(6), 1970, 2, 3, 10, 20, 30, 40); check(test.withWeekyear(1971), 1971, 6, 15, 10, 20, 30, 40); check(test.withYearOfCentury(60), 1960, 6, 9, 10, 20, 30, 40); check(test.withCenturyOfEra(21), 2070, 6, 9, 10, 20, 30, 40); check(test.withYearOfEra(1066), 1066, 6, 9, 10, 20, 30, 40); check(test.withEra(DateTimeConstants.BC), -1970, 6, 9, 10, 20, 30, 40); check(test.withHourOfDay(6), 1970, 6, 9, 6, 20, 30, 40); check(test.withMinuteOfHour(6), 1970, 6, 9, 10, 6, 30, 40); check(test.withSecondOfMinute(6), 1970, 6, 9, 10, 20, 6, 40); check(test.withMillisOfSecond(6), 1970, 6, 9, 10, 20, 30, 6); check(test.withMillisOfDay(61234), 1970, 6, 9, 0, 1, 1, 234); try { test.withMonthOfYear(0); fail(); } catch (IllegalArgumentException ex) {} try { test.withMonthOfYear(13); fail(); } catch (IllegalArgumentException ex) {} }
e9ad05bb-2387-4d31-9960-139c34d805f1
9
public void AIMove(){ if (this._winGFX != null) return; int numAI = this.currPlayers - 1; try { Thread.sleep(1500); } catch (Exception e){ //do nothing } for (int i = 0; i < numAI; i++){ this.diceRoll(); //wait for 1500 try { Thread.sleep(1500); } catch (Exception e){ //do nothing } if (educationalMode){ if (Math.random() > .75 ){ //25% chance to fail the question Player _currPlayer = (Player)this.getPlayerList().get(playerTurnNum); JOptionPane.showMessageDialog(null, "Player " + _currPlayer.getPlayerName() + " failed to answer question correctly!"); playerTurnNum = ++playerTurnNum % currPlayers; _scoreBoard.updateCurrTurn(playerTurnNum); continue; } else { this.educationalMode = false; this.movePlayer(); this.educationalMode = true; } } else { this.movePlayer(); } if (i == numAI){ try { Thread.sleep(500); } catch (Exception e){ //do nothing } } else { try { Thread.sleep(2000); } catch (Exception e){ //do nothing } } } }
12e50a83-dc5c-4336-8fa1-8b573dca710c
0
private int method1() { return value; }
90e91ef2-fd09-4d03-bf0a-e2c3ea186a76
6
public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; }
d1338e81-0748-4f4a-a3ef-6a7df356d166
9
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Contacts)) { return false; } Contacts other = (Contacts) obj; if (emails == null) { if (other.emails != null) { return false; } } else if (!emails.equals(other.emails)) { return false; } if (phones == null) { if (other.phones != null) { return false; } } else if (!phones.equals(other.phones)) { return false; } return true; }
84ce4467-a306-42eb-9582-4ff5cd6d800a
4
public void loadGame(File file) { FileInputStream fileStream; ObjectInputStream objectStream; try { fileStream = new FileInputStream(file); objectStream = new ObjectInputStream(fileStream); // read IGame object from file game = (IGame) objectStream.readObject(); objectStream.close(); } catch (Exception ex) { ex.printStackTrace(); } // Switch to GameMenu window.setMenu(new GameMenu(window, game)); // Make sure the Game has an Observer if (game instanceof Game) { ((Game) game).addObserver((Observer) window); } else if (game instanceof GameCoop) { ((GameCoop) game).addObserver((Observer) window); } // Enable game specific menu items window.getSaveItem().setEnabled(true); window.getSurrenderItem().setEnabled(true); window.getQuitItem().setEnabled(true); // Make sure all Window and Game references are up to date game.setWindow(window); game.getCurrentState().setGame(game); game.getCurrentState().setWindow(window); game.getCurrentState().enter(); // Update the View game.update(Update.PlayerChange); game.update(Update.StateChanged); game.update(Update.PlayerMoved); if (game.getCurrentTile() != null) { game.update(Update.TileDrawn); } }
7a4a8e71-7b06-47e8-9ff5-35ce623b030c
9
public boolean containsTx(){ if(len<2) return false; for (int i = 0; i < len-1; i++) { if(array[i]==84 && array[i+1]==58) return true; } //look for T0: if(len<3) return false; for (int i = 0; i < len-1; i++) { if(array[i]==84 && array[i+1]==48 && array[i+2]==58) return true; } return false; //ASCII }
bfdc015f-8815-4fbe-a0b3-0c1f31738801
7
private void packFields() { // Method Instances DiagramFieldPanel fieldPanel; boolean changed; changed = false; if(isPack()) { for(int i = 0; i < fieldsPanel.getComponentCount(); i++) { fieldPanel = (DiagramFieldPanel) fieldsPanel.getComponent(i); if(!fieldPanel.isSelected() && !fieldPanel.isJoined() && !fieldPanel.isWhereClause()) { filterdDiagramFieldPanels.add(fieldPanel); fieldsPanel.remove(fieldPanel); i--; changed = true; } } } else { while(filterdDiagramFieldPanels.size() > 0) { fieldsPanel.add(filterdDiagramFieldPanels.get(0)); filterdDiagramFieldPanels.remove(0); changed = true; } sortFields(); } if(changed) { pack(); queryBuilderPane.sqlDiagramViewPanel.doResize(); } }
b3535717-69e4-4ed9-b024-cc88b42fba38
2
@Override public boolean update(Object item) { conn = SQLconnect.getConnection(); String sql = "UPDATE `worlds` SET `name`='%s', `time_headnode`='%s' WHERE `id`='%s'"; if (item instanceof Worldnode) { Worldnode newitem = (Worldnode) item; try { sql = String.format(sql, newitem.getName(), newitem.getTime_headnode(), newitem.getId()); Statement st = (Statement) conn.createStatement(); // 创建用于执行静态sql语句的Statement对象 System.out.println(sql); int count = st.executeUpdate(sql); // 执行插入操作的sql语句,并返回插入数据的个数 System.out.println("insert " + count + " entries"); // 输出插入操作的处理结果 conn.close(); // 关闭数据库连接 return true; } catch (SQLException e) { System.out.println("插入数据失败 " + e.getMessage()); return false; } } return false; }
717d958c-ff2a-49db-8661-ee169bfb76d8
0
public void push(Object e) { ensureCapacity(); elements[size++] = e; }
61a74600-6215-4f51-9be7-391e6a2000ca
4
public <T extends Component> List<T> getAllComponentsOnEntity(UUID entity) { synchronized (componentStores) { LinkedList<T> components = new LinkedList<>(); for (HashMap<UUID, ? extends Component> store : componentStores.values()) { if (store == null) { continue; } T componentFromThisEntity = (T) store.get(entity); if (componentFromThisEntity != null) { components.addLast(componentFromThisEntity); } } return components; } }
e3121441-16f6-4d63-88d4-523e7d3c2f90
8
private void initQuery(QueryType queryType) { switch (queryType) { case DELETE: if (this.deleteQuery == null) { this.deleteQuery = new DeleteQuery(_db); } break; case SELECT: if (this.selectQuery == null) { this.selectQuery = new SelectQuery(_db); } break; case UPDATE: if (this.updateQuery == null) { this.updateQuery = new UpdateQuery(_db); } break; case INSERT: if (this.insertQuery == null) { this.insertQuery = new InsertQuery(_db); } break; } }
e0455879-c65c-470a-a8f1-4ad8d21c5e44
3
private boolean userInputChecker(String input) { boolean matchesInput = false; if(userInputList.size() > 0) { for(int loopCount = 0; loopCount < userInputList.size(); loopCount++) { if(input.equalsIgnoreCase(userInputList.get(loopCount))) { matchesInput = true; userInputList.remove(loopCount); loopCount--; } } } return matchesInput; }
7c3bc3c3-523a-4d95-bc24-b0065aff2fb9
5
private final synchronized void method2846(boolean bool, boolean bool_34_, MidiLoader class348_sub2, boolean bool_35_) { do { try { method2840(bool_34_, (byte) -127); anInt8889++; aClass204_8944.initialize(((MidiLoader) class348_sub2) .aByteArray6564); aLong8959 = 0L; aBoolean8961 = bool_35_; int i = aClass204_8944.method1483(); for (int i_36_ = 0; i_36_ < i; i_36_++) { aClass204_8944.method1492(i_36_); aClass204_8944.method1485(i_36_); aClass204_8944.method1486(i_36_); } anInt8960 = aClass204_8944.method1490(); anInt8956 = ((MidiFile) aClass204_8944).anIntArray2681[anInt8960]; aLong8957 = aClass204_8944.method1488(anInt8956); if (bool == false) break; aClass348_Sub16_Sub1_8958 = null; } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("ma.T(" + bool + ',' + bool_34_ + ',' + (class348_sub2 != null ? "{...}" : "null") + ',' + bool_35_ + ')')); } break; } while (false); }
32e0bd98-c721-411c-aad8-03f402ec1379
2
public void doGet(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html");//设置服务器响应的内容格式 // response.setCharacterEncoding("gb2312");//设置服务器响应的字符编码格式。 DButil ab = new DButil(); try { PrintWriter pw = response.getWriter(); // String tep=new String(request.getParameter("id").getBytes("ISO-8859-1")); String name = new String(request.getParameter("name").getBytes("ISO-8859-1"));//能显示中文 // int id=Integer.valueOf(tep); if( ab.addstudent(name)==true) { request.getRequestDispatcher("succ.jsp?info='add succ'").forward(request, response); } } catch (Exception e) { } }
48726cff-6e2c-4924-b2d7-c20857840f5a
8
public static void main(String[] args) { String action = args[0]; Properties props = new Properties(); try { props.load(new FileInputStream(new File("migrator.properties"))); } catch (FileNotFoundException e) { throw new RuntimeException( "No migrator.properties file found. Make sure it's in the same dir as the jar file.", e); } catch (IOException e) { throw new RuntimeException( "Can't read migrator.properties file. Make sure it's readable.", e); } String driver = props.getProperty("db.driver"); String url = props.getProperty("db.url"); String user = props.getProperty("db.username"); String password = props.getProperty("db.password"); String scripts = props.getProperty("migration.scripts.are.in"); Migrator migrator = new Migrator(url, driver, user, password, scripts); if (action != null) { if (action.equals("upgrade")) { System.out.println("upgrade action started"); migrator.migrateUp(); System.out.println("\nupgrade action ended"); } else if (action.equals("upgrade-all")) { System.out.println("upgrade-all action started"); migrator.migrateUpAll(); System.out.println("\nupgrade-all action ended"); } else if (action.equals("rollback")) { System.out.println("rollback action started"); migrator.migrateDown(); System.out.println("\nrollback action ended"); } else if (action.equals("init")) { System.out.println("init action started"); migrator.initDb(); System.out.println("\ninit action ended"); } else if (action.equals("status")) { System.out.println("status action started"); migrator.printAfterDiagnostics(); System.out.println("\nstatus action ended"); } else { throw new IllegalArgumentException("don't kow what " + action + " is. Must be one of: upgrade-all upgrade rollback init status"); } } }
d674c876-b3cf-4cf5-8f1e-ef2fa0eaee2c
6
@EventHandler public void EndermanFastDigging(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getEndermanConfig().getDouble("Enderman.FastDigging.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getEndermanConfig().getBoolean("Enderman.FastDigging.Enabled", true) && damager instanceof Enderman && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, plugin.getEndermanConfig().getInt("Enderman.FastDigging.Time"), plugin.getEndermanConfig().getInt("Enderman.FastDigging.Power"))); } }
0d12ce21-2d00-4de1-a4b3-91a23b381db6
5
@Override public <T> T processLine2D(int x0, int y0, int x1, int y1, PointHandler2D<T> handler) { int x = x0; int y = y0; T result = handler.handlePoint(x, y); if (result != null) return result; final int dx = x1 - x0; final int dy = y1 - y0; final int sign_dx = sign(dx); final int sign_dy = sign(dy); final int abs_dx = Math.abs(dx); final int abs_dy = Math.abs(dy); final int px, py, d0, d1; if (abs_dx > abs_dy) { px = sign_dx; py = 0; d0 = abs_dx; d1 = abs_dy; } else { px = 0; py = sign_dy; d0 = abs_dy; d1 = abs_dx; } int delta = d0/2; for (int p = 0; p < d0; p++) { delta -= d1; if (delta < 0) { delta += d0; x += sign_dx; y += sign_dy; } else { x += px; y += py; } result = handler.handlePoint(x, y); if (result != null) return result; } return null; }
075521ae-b3c8-4b45-bc53-c4e0ac2fbbbe
7
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(GUI_Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GUI_Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GUI_Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GUI_Principal.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() { System.out.println("COMENZO EL PROGRAMA"); GUI_Conexion gui = new GUI_Conexion(); if (gui.validarConexion()){ Conexion r_con = gui.getConexion(); gui.dispose(); gui=null; GUI_Inicio_Sesion IS = new GUI_Inicio_Sesion(r_con); IS.setVisible(true); } else{ gui.setVisible(true); gui.generarConexion (); } } }); }
66e0bd0a-549c-4359-b787-3834b5483e06
3
public void evaluate() { List<Thread> threads = new ArrayList<>(); Input input = parser.getData(Input.class, "example1.xml"); Masterdata masterData = parser.getData(Masterdata.class, "metadata.xml"); Flight flight = input.getFlight(); Aircraft aircraft = new Finder().inList(masterData.getAircrafts().getAircraft(), input.getFlight()); AircraftType aircraftType = new Finder().inList(masterData.getAircraftTypes().getAircraftType(), aircraft); Airline airline = new Finder().inList(masterData.getAirlines().getAirline(), aircraft); ExchangeData cDOW = new ExchangeData(new CancalableCountDownLatch(1), BigDecimal.ONE); ExchangeData cZFW = new ExchangeData(new CancalableCountDownLatch(3), BigDecimal.ONE); ExchangeData cTOW = new ExchangeData(new CancalableCountDownLatch(2), BigDecimal.ONE); ExchangeData cTXW = new ExchangeData(new CancalableCountDownLatch(1), BigDecimal.ONE); ExchangeData cLAW = new ExchangeData(new CancalableCountDownLatch(1), BigDecimal.ONE); ThreadGroup tg = new ThreadGroup("LH"); Thread caluculationDOW = new Thread(tg, new CalculationDOW(aircraft, flight, aircraftType, cDOW), "DOW"); threads.add(caluculationDOW); Thread caluculationZFW = new Thread(tg, new CalculationZFW(flight, aircraftType, cDOW, cZFW), "ZFW"); threads.add(caluculationZFW); Thread caluculationTOW = new Thread(tg, new CalculationTOW(flight, aircraftType, cZFW, cTOW), "TOW"); threads.add(caluculationTOW); Thread caluculationTXW = new Thread(tg, new CalculationTXW(flight, aircraftType, cZFW, cTXW), "TXW"); threads.add(caluculationTXW); Thread caluculationLAW = new Thread(tg, new CalculationLAW(flight, aircraftType, cTOW, cLAW), "LAW"); threads.add(caluculationLAW); Thread caluculationUnderload = new Thread(tg, new CalculationUnderload(aircraftType, airline, cZFW, cTXW, cTOW, cLAW), "Underload"); threads.add(caluculationUnderload); for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { logger.error(thread.getName() + " is inperrupted", e); } } result.clear(); result = ThreadProcessor.getResult(); }
bfb0a150-e4f2-41fd-b077-66fd4b1bef6a
7
public static void habilitaCampos(Container container) { for (Component component : container.getComponents()) { if (component instanceof JTextComponent) habilitaTextField((JTextComponent) component); else if (component instanceof JComboBox) habilitaComponent(component); else if (component instanceof JCheckBox) habilitaComponent(component); else if (component instanceof JRadioButton) habilitaComponent(component); else if (component instanceof JPanel) habilitaCampos((JPanel) component); else if (component instanceof JScrollPane) habilitaComponent((JScrollPane) component); } }
70dc93a4-1f96-4b0f-acb5-023b278a6f61
2
public void run() { try { while (true) { String message = producer.getMessage(); System.out.println("Got message: " + message); Thread.sleep(1500); } } catch (InterruptedException e) { } }
96cb5607-6e1d-406c-a16d-174ee768a2dd
7
public static void main(String[] args) throws Throwable { Scanner in = new Scanner( new InputStreamReader( System.in ) ); StringBuilder sb = new StringBuilder(); sb.append("SHIPPING ROUTES OUTPUT\n\n"); int tc = Integer.parseInt(in.nextLine()); for (int t = 0; t < tc; t++) { sb.append("DATA SET "+(t+1)+"\n\n"); int m = in.nextInt(); int n = in.nextInt(); int p = in.nextInt(); ware = new boolean[m]; tree = new TreeMap<String, Integer>(); for (int i = 0; i < m; i++) { tree.put(in.next(), i); } mAdy = new int[m][m]; for (int i = 0; i < n; i++) { String s = in.next(); String d = in.next(); for (int j = 0; j < m; j++) { if(i==j) mAdy[i][j]=-1; else{ mAdy[tree.get(s)][tree.get(d)] = 1; mAdy[tree.get(d)][tree.get(s)] = 1; } } } for (int i = 0; i < p; i++) { int shipment = in.nextInt(); int s = tree.get(in.next()); int d = tree.get(in.next()); int total = bfs( s,d,shipment ); String cosa ="$"+total; if(total == -1){ cosa = "NO SHIPMENT POSSIBLE"; } sb.append(cosa+"\n"); Arrays.fill(ware, false); } sb.append("\n"); } sb.append("END OF OUTPUT\n"); System.out.print(new String(sb)); }
61296c3c-384b-4a30-9e7a-d93ec39914bb
9
public static List<Class<?>> getTypes(final String str) throws IOException { List<Class<?>> result = new ArrayList<>(); byte[] s = str.trim().getBytes(); if (!(s[0] == '(' && s[str.length() - 1] == ')')) { throw new IOException("wrong type (no brackets)"); } for (int i = 1; i < str.length() - 1; ++i) { if (s[i] == ' ') { continue; } boolean flag = false; for (int j = 0; j < TYPES.length; ++j) { if (new String(s, i, Math.min(TYPES[j].length(), str.length() - i)).equals(TYPES[j])) { result.add(CLASSES[j]); i += TYPES[j].length(); flag = true; break; } } if (!flag) { throw new IOException("Cannot read type! position: " + i); } } return result; }
248ddbb0-3e90-45e5-92c6-55a44706f919
9
@Override public String toString() { String returnVal = ""; switch(suit) { case CLUBS: returnVal = "C"; break; case SPADES: returnVal = "S"; break; case DIAMONDS: returnVal = "D"; break; case HEARTS: returnVal = "H"; break; } switch(value) { case JOKER: returnVal = "JR"; break; case ACE: returnVal += "A"; break; case JACK: returnVal += "J"; break; case QUEEN: returnVal += "Q"; break; case KING: returnVal += "K"; break; default: returnVal += value.ordinal(); } return returnVal; }
195e4905-f8bc-478a-b14b-a7a45be87653
3
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { List<Category> categories = null; Hashtable<Long, Boolean> canDelete = null; HttpSession session = req.getSession(true); User user = (User)session.getAttribute("currentSessionUser"); // Checks if there is a user present, as well as if the user is an owner if (user == null || !user.isOwner()) { // If not then let the .jsp file know that the user doesn't have permission to view this page req.setAttribute("permission", false); req.getRequestDispatcher("categories.jsp").forward(req, res); return; } else { // Else everything goes as planned try { categories = CategoryDAO.list(); canDelete = ProductDAO.categories(); } catch (SQLException e){res.sendRedirect("products"); } req.setAttribute("list", categories); req.setAttribute("permission", true); req.setAttribute("delete", canDelete); req.getRequestDispatcher("categories.jsp").forward(req, res); return; } }