method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
343931ec-198d-4e0f-b8e6-d7f0cf0574ba
8
protected void containerItemSwappingLogic(){ //put stack from one inventory to another if(secondairyInventory != null) if(KeyHandler.isValidationKeyPressed()) if(isNotPlayerInventory() && secondairyInventory != null){ System.out.println(slot_index); if(secondairyInventory.getStackInSlot(slot_index) != null) if(playerInventory.setStackInNextAvailableSlot(secondairyInventory.getStackInSlot(slot_index))) secondairyInventory.setStackInSlot(slot_index, null); }else{ int slot = slotIndex[0]+ (slotIndex[1]*(rowsX())); System.out.println(slot); if(playerInventory.getStackInSlot(slot) != null) if(secondairyInventory.setStackInNextAvailableSlot(playerInventory.getStackInSlot(slot))) playerInventory.setStackInSlot(slot, null); } }
09241321-58b5-4504-8170-d1b8db270f00
4
public void extractConfig(final String resource, final boolean replace) { final File config = new File(this.getDataFolder(), resource); if (config.exists() && !replace) return; this.getLogger().log(Level.FINE, "Extracting configuration file {1} {0} as {2}", new Object[] { resource, CustomPlugin.CONFIGURATION_SOURCE.name(), CustomPlugin.CONFIGURATION_TARGET.name() }); config.getParentFile().mkdirs(); final char[] cbuf = new char[1024]; int read; try { final Reader in = new BufferedReader(new InputStreamReader(this.getResource(resource), CustomPlugin.CONFIGURATION_SOURCE)); final Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(config), CustomPlugin.CONFIGURATION_TARGET)); while((read = in.read(cbuf)) > 0) out.write(cbuf, 0, read); out.close(); in.close(); } catch (final Exception e) { throw new IllegalArgumentException("Could not extract configuration file \"" + resource + "\" to " + config.getPath() + "\"", e); } }
5441cf19-b73d-447d-9b5d-3d57739de103
4
@Override public void initProvider(Plugin plugin) { this.plugin = plugin; this.configFile = new File(plugin.getDataFolder(), "mods.yml"); this.config = YamlConfiguration.loadConfiguration(this.configFile); if (!this.configFile.exists()) { this.plugin.getLogger().warning("No mods.yml was found in the data directory"); } this.config.addDefault("mods", new ArrayList<String>()); this.modList = this.config.getStringList("mods"); ConfigurationSection versions = this.config.getConfigurationSection("versions"); if (versions != null) { for (String key : versions.getKeys(false)) { if (this.modList.contains(key)) { this.modVersions.put(key, (float)this.config.getDouble("versions." + key)); } } } saveConfig(); }
272e0836-273f-47bd-a889-c54daef3d6fd
1
public void testPlus_int() { Weeks test2 = Weeks.weeks(2); Weeks result = test2.plus(3); assertEquals(2, test2.getWeeks()); assertEquals(5, result.getWeeks()); assertEquals(1, Weeks.ONE.plus(0).getWeeks()); try { Weeks.MAX_VALUE.plus(1); fail(); } catch (ArithmeticException ex) { // expected } }
ace51eb4-2b3d-4d5a-8073-3cc378cd2e7e
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GroupData other = (GroupData) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
60ab3297-ae0a-4616-a5de-8a5252800c67
3
public boolean DiagonalSuperior() { boolean validar=false; for (int i = 1; i < matrizA.length; i++) { for (int j = 1; j < i; j++) { if(matrizA[i][j]==0) { validar=true; } else { validar=false; break; } } } return validar; }
6cf9f30f-570a-4d67-9c9e-98cc6ecd9014
1
public void printMapping() { Logger log = Bukkit.getServer().getLogger(); for (Entry<String, Subcommand> ent : cmdMap.entrySet()) { log.info(ent.getKey() + " : " + ent.getValue()); } }
473d1a4d-8ac7-4609-84c4-3532d92a910d
3
@SuppressWarnings("unchecked") private ArrayList<String> getUniversityShortNames( HashMap<String, Object> map) { ArrayList<Object> ids = (ArrayList<Object>) map.get("partnerIds"); ArrayList<String> result = new ArrayList<String>(); for (Object id : ids) { Object uni = universities.get(id); if (uni == null) { System.out.println("Unkown university id " + id); continue; } uni = ((HashMap<String, Object>) uni).get("shortName"); if (uni == null) { System.out.println("No short name for partner " + id); } else { result.add((String) uni); } } return result; }
4c417e6b-1f71-417e-8a5c-285ca1b3892c
9
public void FillColumn(int columna){ //llenado automatico por columna for(int y = 0;y<14;y++){ //revisa en una columna desde abajo hacia arriba String colorpresente = this.blocks[columna][y].getColor(); //obtiene color if (colorpresente.equals("-") ){ //significa que esta en blanco...hay que reemplazar color // System.out.println("Colorenblanco, reemplazar x:"+columna+"y:"+y+"."); //hacer algo, en el caso que arriba aun queden colores... for(int j = y+1;j<15;j++){ if(!this.blocks[columna][j].getColor().equals("-")){ this.blocks[columna][y].setColor(this.blocks[columna][j].getColor()); //se hizo un reemplazo this.blocks[columna][j].setColor("-"); // el que tenia color ahora es blanco..! this.blocks[columna][y].paintColor(); System.out.println("bloque:["+columna+"]["+y+"]color nuevo: "+this.blocks[columna][y].getColor()+"."); } if(j ==14 && this.blocks[columna][j].getColor().equals("-")){ //Si llego a la cima y es blanco hay que sacar colores nuevos for(int z = y;z<15;z++){ //aqui volvemos a revisar desde abajo.. //crear nuevo bloque.. sacar el color //revisar si sigue cumplienado propiedad de comodin. if(this.blocks[columna][z].equals("-")){ Random rand1 = new Random(); int n = rand1.nextInt(100); if( n < 95 ) { //Lo que use aqui fue el metodo de la estrategia en wikipedia //Lee lo que sale ahi para entender como funciona esta parte Bloque b1 = BloqueFactory.crearBloque( new ColorCreator() ); this.blocks[columna][z].setColor(b1.getColor()); this.blocks[columna][z].paintColor(); System.out.println("bloque:["+columna+"]["+y+"]color nuevo: "+this.blocks[columna][y].getColor()+"."); } else { Bloque b1 = BloqueFactory.crearBloque( new ComodinCreator() ); this.blocks[columna][z].setColor(b1.getColor()); this.blocks[columna][z].paintColor(); System.out.println("bloque:["+columna+"]["+y+"]color nuevo: "+this.blocks[columna][y].getColor()+"."); } } } } } } } }
38ac746e-94e3-4ab0-b33d-656441726a48
9
private boolean confirm() { if (!checkAndSetUid(uidField.getText(), pageComboBox, dialog)) return false; String s = scriptArea.getText(); if (s != null && !s.trim().equals("")) { if (!checkBraceBalance(s)) { JOptionPane.showMessageDialog(dialog, "Unbalanced balances are found.", "Menu text-script pair error", JOptionPane.ERROR_MESSAGE); return false; } } Object o = modelComboBox.getSelectedItem(); BasicModel m = (BasicModel) o; m.addModelListener(pageComboBox); pageComboBox.setModelClass(m.getClass().getName()); if (o instanceof MDModel) { pageComboBox.setModelID(pageComboBox.page.getComponentPool().getIndex(m)); } else if (o instanceof Embeddable) { pageComboBox.setModelID(((Embeddable) o).getIndex()); } o = actionComboBox.getSelectedItem(); if (o instanceof Action) pageComboBox.setAction((Action) o); pageComboBox.setOptionGroup(optionField.getText()); if (scriptArea.getText() != null && !scriptArea.getText().trim().equals("")) { pageComboBox.putClientProperty("Script", scriptArea.getText()); pageComboBox.setupScripts(scriptArea.getText()); } else { pageComboBox.putClientProperty("Script", null); } pageComboBox.setToolTipText(toolTipField.getText()); pageComboBox.setDisabledAtRun(disabledAtRunCheckBox.isSelected()); pageComboBox.setDisabledAtScript(disabledAtScriptCheckBox.isSelected()); pageComboBox.page.getSaveReminder().setChanged(true); pageComboBox.page.settleComponentSize(); return true; }
a40e5d7b-4887-4dd3-b734-b23ff0351a79
4
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } HasherTable<K, V> h = (HasherTable<K, V>) obj; Set<Entry<K, V>> otherSet = h.entrySet(); for (Entry<K, V> e : this.entrySet()) if (!otherSet.contains(e)) return false; return true; }
a6216e57-9f4d-474f-92dd-94091b6ae565
9
public static void main(String... args) throws IOException, DateFormatException, URISyntaxException { String load = ""; Replacer r = null; System.out.println("\nYou've just run LogAnalyst v1.0"); if (args.length == 0) { System.out.println("Default configuration is loaded, since there's not path to other configuration.\n"); load = "default.properties"; } else { load = args[0]; System.out.println("Trying to load configuration specified in argument: " + load + "\n"); } // initialization of settings new Settings(load); Log log = LogReader.read(); // TODO: zmien co chcesz. Wazne, zeby pozniej dalej log byl logiem ;) no i zalozenie jest takie, ze analiza jest zawsze przed zamiana w replacerze :) if (Settings.getSetting("doAnalyze").equals("true")) { LogAnalyst.analyze(log); } // replacement on each line separately if (Settings.getSetting("replace").equals("true") && Settings.getSetting("replacementPerLine").equals("true")) { TreeSet<LogLine> tmpLog = new TreeSet<LogLine>(); r = new Replacer(); Iterator it = log.getLogAsSet().descendingSet().descendingIterator(); while (it.hasNext()) { LogLine line = (LogLine) it.next(); String content = r.replace(line.getContent()); if (!content.equals("")) { line.setContent(content); tmpLog.add(line); } } log.setLog(tmpLog); } // replacement on whole log is possible only when there's no other action after it if (Settings.getSetting("replace").equals("true") && Settings.getSetting("replacementPerLog").equals("true")) { r = new Replacer(); LogWriter.write(r.replace(log.toString())); } LogWriter.write(log); System.out.println("\nAll the output files are available in direcotry: " + Settings.getSetting("outputLogDir")); if (Settings.getSetting("replace").equals("true")) { System.out.println("Lines in merged log were replaced using rules: " + r.getDescriptionOfRules()); } System.out.println("While parsing, got " + LogLineParser.getNoOfErrorsOnParsing() + " errors. Those lines are not added to merged log."); System.out.println("Your merged log is available in file: " + Settings.getSetting("outputLogName")); System.out.println("\nDone!\n"); }
00f59a2e-f690-4dd9-b15e-4761936881b6
8
public boolean checkOut(Book b, Timestamp startTime, int cardNumber, int idNumber) throws Exception { if(b == null || b.getCurrentQuantity() == 0){ return false; } Connection connect = null; Statement statement = null; ResultSet resultSet = null; PreparedStatement preparedStatement = null; try { // First connect to the database connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/librarysystem?user=admin&password=123456"); statement = connect.createStatement(); resultSet = statement.executeQuery("SELECT maxReservation FROM BookType WHERE typeName = '" + b.getTypeName() + "'"); // Get the first result (max number of days for the rental) of the query if(resultSet.next()){ int reserveLength = resultSet.getInt("maxReservation"); long oneDay = 1 * 24 * 60 * 60 * 1000; // Calculate the return date of the book rental Timestamp endTime = new Timestamp(startTime.getTime() + reserveLength * oneDay); preparedStatement = connect.prepareStatement("INSERT INTO CheckOut " + "(isbn, start, end, cardNumber, idNumber) " + "VALUES (?, ?, ?, ?, ?)"); preparedStatement.setLong(1, b.getIsbn()); preparedStatement.setTimestamp(2, startTime); preparedStatement.setTimestamp(3, endTime); preparedStatement.setInt(4, cardNumber); preparedStatement.setInt(5, idNumber); // Store the checkout transaction in the database preparedStatement.executeUpdate(); // Decrement the current quantity by 1 preparedStatement = connect.prepareStatement("UPDATE Book " + "SET currentQuantity = currentQuantity - 1 " + "WHERE isbn = ?"); preparedStatement.setLong(1, b.getIsbn()); preparedStatement.executeUpdate(); return true; } return false; } catch (Exception e) { System.out.println(e.getMessage()); throw e; } finally { try { if(connect != null){ connect.close(); } if(statement != null){ statement.close(); } if(resultSet != null){ resultSet.close(); } } catch (Exception e) { } } }
d2363f02-889a-41af-9b8a-2ede9c41ba64
4
private void loadDatFile() throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(inputFile), "GBK")); String data = null; int index = 0; while ((data = br.readLine()) != null) { // 第一行不要,是中文 if (index == 0) { index++; continue; } // 第二行,是所有标签的名字 // 按照顺序用list存储 if (index == 1) { tabList = data.split("\\t"); if (inputFile.getName().equals("global.dat")) { tabList = ("name" + "\t" + "Key\tValue").split("\\t"); } index++; continue; } index++; String[] lines = data.split("\\t"); dataList.add(lines); } br.close(); }
d1bd1028-83f7-423e-bf23-3306e0fbfd9e
0
public int size() { return this.instances.size(); }
6f858b0f-76d3-4d89-8086-76fde93ac676
2
public Expression simplify() { Expression expr = simplifyAccess(); if (expr != null) return expr.simplify(); expr = simplifyString(); if (expr != this) return expr.simplify(); return super.simplify(); }
5f951409-c648-49a3-bec3-ec4403aa8376
9
private static void reconcileHints(GC gc, int applied, int hints) { int changes = hints ^ applied; if ((changes & XOR_MASK) != 0) { gc.setXORMode((hints & XOR_MASK) != 0); } // Check to see if there is anything remaining changes &= ~XOR_MASK; if (changes != 0) { if ((changes & INTERPOLATION_MASK) != 0) { gc.setInterpolation(((hints & INTERPOLATION_MASK) >> INTERPOLATION_SHIFT) - INTERPOLATION_WHOLE_NUMBER); } if ((changes & FILL_RULE_MASK) != 0) { gc.setFillRule(((hints & FILL_RULE_MASK) >> FILL_RULE_SHIFT) - FILL_RULE_WHOLE_NUMBER); } if ((changes & AA_MASK) != 0) { gc.setAntialias(((hints & AA_MASK) >> AA_SHIFT) - AA_WHOLE_NUMBER); } if ((changes & TEXT_AA_MASK) != 0) { gc.setTextAntialias(((hints & TEXT_AA_MASK) >> TEXT_AA_SHIFT) - AA_WHOLE_NUMBER); } // If advanced was flagged, but none of the conditions which trigger // advanced // actually got applied, force advanced graphics on. if ((changes & ADVANCED_GRAPHICS_MASK) != 0) { if ((hints & ADVANCED_GRAPHICS_MASK) != 0 && !gc.getAdvanced()) { gc.setAdvanced(true); } } } }
b10f49ce-3aea-4fa3-8c29-13441d1cf984
0
@Override public void startSetup(Attributes atts) { super.startSetup(atts); addActionListener(this); Outliner.documents.addTreeSelectionListener(this); setEnabled(false); }
510ab2f8-0a89-4d15-9cb4-43eccbc02d6b
8
@Override protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { System.out.println(HeaderType.valueOf( key.toString().trim().replaceAll("\\ ", "")).toString()); switch (HeaderType.valueOf( key.toString().trim().replaceAll("\\ ", "")).toString()) { case "number": System.out.println("number me for key ="+key.toString()); double max = Integer.MIN_VALUE; double min = Integer.MAX_VALUE; double avg = 0.0; Integer count = 0; for (Text value : values) { double curr = Double.parseDouble(value.toString().trim()); max = max <= curr ? curr : max; min = min >= curr ? curr : min; avg += curr; count++; } context.write( key, new Text("max=" + String.valueOf(max) + "\t min=" + String.valueOf(min) + "\t AVg=" + String.valueOf(avg / count))); break; case "words": System.out.println("words me for key="+key.toString()); Map<String, Integer> countOfCat=new HashMap<String, Integer>(); count=0; for (Text word : values) { if (countOfCat.containsKey(word.toString())) { count=countOfCat.get(word.toString()) ; countOfCat.put(word.toString(), ++count); }else{ countOfCat.put(word.toString(), 1); } } String tmp=new String(); for (Entry<String, Integer> entry : countOfCat.entrySet()) { tmp+=entry.getKey()+"="+entry.getValue()+"\t"; } context.write(key, new Text(tmp)); break; default: break; } }
5fa0604d-f777-4ad9-a49d-2476b1d83bf6
5
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final EmbeddedType other = (EmbeddedType) obj; if (this.schema != other.schema && (this.schema == null || !this.schema.equals(other.schema))) { return false; } return true; }
40d1ef3c-bb33-4df3-8b14-c577a29283a9
8
public void initRenderTargets(int[] attachments) { if (attachments == null) return; int[] drawBuffers = new int[id.length]; boolean hasDepth = false; for (int i = 0; i < id.length; i++) { if (attachments[i] == GL_DEPTH_ATTACHMENT) { drawBuffers[i] = GL_NONE; hasDepth = true; } else drawBuffers[i] = attachments[i]; if (attachments[i] == GL_NONE) continue; if (frameBuffer == 0) { frameBuffer = glGenFramebuffers(); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffer); } glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attachments[i], textureTarget, id[i], 0); } if (frameBuffer == 0) { return; } if (!hasDepth) { renderBuffer = glGenRenderbuffers(); glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER, renderBuffer); } glDrawBuffers(Util.createIntBuffer(drawBuffers.length).put(drawBuffers)); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { Util.err("Framebuffer creation failed!"); System.exit(-1); } glBindFramebuffer(GL_FRAMEBUFFER, 0); }
062ed54f-1262-4c38-875c-de5dbafa40b5
0
public void setCalle(String calle) { addressCompany.setCalle(calle); }
45b65c5f-c405-4ac3-b386-8957bba83b00
0
public CFGToPDALLConverter() { }
2043e283-055c-4874-8c8f-109046a2ce64
5
public void draw(Graphics2D g) { for( int row = rowOffset; row < rowOffset + numRowsToDraw; row++) { if(row >= numRows) break; for( int col = colOffset; col < colOffset + numColsToDraw; col++) { if(col >= numCols) break; if(map[row][col] == 0) continue; int rc = map[row][col]; int r = rc / numTilesAcross; int c = rc % numTilesAcross; g.drawImage( tiles[r][c].getImage(), (int)x + col * tileSize, (int)y + row * tileSize, null ); } } }
48124b08-56a9-450c-b3a7-58a55375ae61
5
public ActivityItemProperties addActivityItem(ActivityItem actItem) { // get the dimensions for the component Dimension activityItemDimens = new Dimension(actItem.getActivityItemDimensions().width, actItem.getActivityItemDimensions().height) ; // calculate the location for the component Point greatestTracklocation = new Point(0, 0) ; for (int activityItemsCounter = 0 ; activityItemsCounter < activityProperties.size() ; activityItemsCounter ++) { // get the currActivity ActivityItem currItem = activityProperties .get(activityItemsCounter).getActivityItem() ; // get its location Point currItemLocation = currItem.getTrackLocation() ; // stores whether or not there exists a component // at the desired location for the component // find out if there is an overlapping component // at that location and return false // this checks if any of the left coordinates of // the left coords are within the item proposed // to be added // !+ (TRICKY SECTION :- CHANGE AT YOUR OWN PERIL !+ if ((currItem.getTrackLocation().y >= actItem.getTrackLocation().y && currItem.getTrackLocation().y <= (actItem.getTrackLocation().y + actItem.getActivityItemDimensions().height)) || ( (currItem.getTrackLocation().y + currItem.getActivityItemDimensions().height) >= actItem.getTrackLocation().y && (currItem.getTrackLocation().y + currItem.getActivityItemDimensions().height) <= (actItem.getTrackLocation().y + actItem.getActivityItemDimensions().height) )) { // do not allow the component to be added to this track return null ; } else { // increment the coordinates for the lowermost location // for the component greatestTracklocation.x = currItemLocation.x ; greatestTracklocation.y = currItemLocation.y + currItem.getActivityItemDimensions().height ; } } // create the ActivityItemProperties object ActivityItemProperties acProperties = new ActivityItemProperties(actItem, activityItemDimens, greatestTracklocation); // add it to the main container activityProperties.add(acProperties); // return the activities item properties return acProperties ; }
143e0cb4-2ddf-4146-b463-e977e6bf9766
9
private int jjMoveStringLiteralDfa5_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(3, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(4, active0); return 5; } switch(curChar) { case 88: return jjMoveStringLiteralDfa6_0(active0, 0x20000L); case 99: return jjMoveStringLiteralDfa6_0(active0, 0x1000L); case 101: if ((active0 & 0x2000L) != 0L) return jjStartNfaWithStates_0(5, 13, 4); else if ((active0 & 0x80000L) != 0L) return jjStartNfaWithStates_0(5, 19, 4); break; case 116: if ((active0 & 0x40000L) != 0L) return jjStartNfaWithStates_0(5, 18, 4); return jjMoveStringLiteralDfa6_0(active0, 0x4000L); default : break; } return jjStartNfa_0(4, active0); }
8bdae3eb-80d1-48ac-b074-cbf509747028
7
private JMenu getFileMenu(boolean webstart){ JMenu file = new JMenu("File"); file.setMnemonic('f'); JMenuItem newImageItem = new JMenuItem("New"); newImageItem.setMnemonic('n'); ActionListener newImage = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { BufferedImage bi = new BufferedImage( 360, 300, BufferedImage.TYPE_INT_ARGB); clear(bi); setImage(bi); } }; newImageItem.addActionListener(newImage); file.add(newImageItem); if (webstart) { //TODO Add open/save functionality using JNLP API } else { //TODO Add save functionality using J2SE API file.addSeparator(); ActionListener openListener = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (!dirty) { JFileChooser ch = getFileChooser(); int result = ch.showOpenDialog(gui); if (result==JFileChooser.APPROVE_OPTION ) { try { BufferedImage bi = ImageIO.read( ch.getSelectedFile()); setImage(bi); } catch (IOException e) { showError(e); e.printStackTrace(); } } } else { // TODO JOptionPane.showMessageDialog( gui, "TODO - prompt save image.."); } } }; JMenuItem openItem = new JMenuItem("Open"); openItem.setMnemonic('o'); openItem.addActionListener(openListener); file.add(openItem); ActionListener saveListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFileChooser ch = getFileChooser(); int result = ch.showSaveDialog(gui); if (result==JFileChooser.APPROVE_OPTION ) { try { File f = ch.getSelectedFile(); ImageIO.write(SmartBoard_Paint.this.canvasImage, "png", f); SmartBoard_Paint.this.originalImage = SmartBoard_Paint.this.canvasImage; dirty = false; } catch (IOException ioe) { showError(ioe); ioe.printStackTrace(); } } } }; JMenuItem saveItem = new JMenuItem("Save"); saveItem.addActionListener(saveListener); saveItem.setMnemonic('s'); file.add(saveItem); } if (canExit()) { ActionListener exit = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub System.exit(0); } }; JMenuItem exitItem = new JMenuItem("Exit"); exitItem.setMnemonic('x'); file.addSeparator(); exitItem.addActionListener(exit); file.add(exitItem); } return file; }
b044dbe9-4bb6-45b0-9753-d819d3cf91fc
6
@Command(aliases = {"list", "l"}, usage = "[page]", flags = "", desc = "Lists all ports", help = "Lists all JumpPorts", min = 0, max = 1) @CommandPermissions("jumpports.list") @Console public static void list(CommandContext args, CommandSender sender) throws CommandException { List<JumpPort> ports = JumpPorts.getList(); Collections.sort(ports, new JumpPortsComparator()); final int totalSize = ports.size(); final int pageSize = 6; final int pages = (int) Math.ceil(totalSize / (float) pageSize); int page = args.getInteger(0, 1) - 1; if (page < 0) { page = 0; } if (page < pages) { sender.sendMessage(Lang.get("list.ports") .replaceAll("%P", "" + (page + 1)) .replaceAll("%T", "" + pages)); for (int i = page * pageSize; i < page * pageSize + pageSize; i++) { if (i >= totalSize) { break; } JumpPort port = ports.get(i); String price = "" + port.getPrice(); if (port.getPrice() == 0.00) { price = "Free"; } if (port.isEnabled()) { sender.sendMessage(Lang.get("list.entryEnabled") .replaceAll("%N", port.getName()) .replaceAll("%D", port.getDescription()) .replaceAll("%P", "" + price)); } else { sender.sendMessage(Lang.get("list.entryDisabled") .replaceAll("%N", port.getName()) .replaceAll("%D", port.getDescription()) .replaceAll("%P", "" + price)); } } } else { sender.sendMessage(Lang.get("exceptions.invalidPage")); } }
ba807c06-9a58-4080-8644-2d76583475a8
3
public static String string2UnicodeNumber(String s) { try { StringBuffer out = new StringBuffer(""); StringBuffer temp = null; StringBuffer number = null; byte[] bytes = s.getBytes("unicode"); for (int i = 2; i < bytes.length - 1; i += 2) { temp = new StringBuffer("&#"); number = new StringBuffer(""); String str = Integer.toHexString(bytes[i + 1] & 0xff); for (int j = str.length(); j < 2; j++) { temp.append("0"); } String str1 = Integer.toHexString(bytes[i] & 0xff); // 十进制转化为十六进制,结果为C8。 // Integer.toHexString(200); // 十六进制转化为十进制,结果140。 // Integer.parseInt("8C",16); number.append(str1); number.append(str); BigInteger bi = new BigInteger(number.toString(), 16); String show = bi.toString(10); temp.append(show + ";"); out.append(temp.toString()); } return out.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } }
d1a8f8b6-e400-4903-a832-31c8f6d4c235
6
public int contains(String std) { String anterior; NodoListaDiccionario aux = ultimo; //Mira si esta std o su anterior if(std.length()>4) { while(aux!=null) { anterior= std.substring(std.length()-2); if(aux.getPalabra().equals(std)) return aux.getIndex(); else if(aux.getPalabra().equals(anterior)) return aux.getIndex(); else aux = aux.getAnterior(); } //Solo busca std } else { while(aux!=null) { if(aux.getPalabra().equals(std)) return aux.getIndex(); else aux = aux.getAnterior(); } } return -1; }
b13f79ed-b2f2-47f0-9a68-486775027fd3
4
private long parseTime(String timeString) { long result = 0; if (classicTime) { String[] time = timeString.split(timeDelimiter); //HOUR, MINUTE, SECOND, MILLISECOND result = Integer.parseInt(time[0]); result *= 60; //now in minutes result += Integer.parseInt(time[1]); result *= 60; // now in seconds result += Integer.parseInt(time[2]); if (videoSection.getTimeUnit() == TimeUnit.MILLISECONDS) { result *= 1000; // now in milliseconds result += Integer.parseInt(time[3]); } } else { String[] time = timeString.split(" "); for (int i = 0; i < time.length; ++i) { result += parseValue(time[i]); } if (videoSection.getTimeUnit() == TimeUnit.SECONDS) { result /= 1000; } } return result; }
32756efb-6a39-4be4-8a6e-0f7e68ab0f7a
1
private void printPath( String file ) { fileCount++; if ( file == null ) { System.out.println( fileCount + ". MyBatis configuration already exists." ); return; } System.out.println( fileCount + ". " + file ); }
fba7ac11-4ebd-4485-9b4e-cf35ed6a08e9
6
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); Class.forName("oracle.jdbc.OracleDriver") ; out.write('\n'); String name = request.getParameter( "v9" ); session.setAttribute( "theValue", name ); out.write("\n"); out.write("<html>\n"); out.write(" <HEAD>\n"); out.write(" <TITLE>Trips booked by a specific Client</TITLE>\n"); out.write(" </HEAD>\n"); out.write("\n"); out.write(" <BODY>\n"); out.write(" <H1>Number of resorts in a given city </H1>\n"); out.write("\n"); out.write(" "); //String a=session.getAttribute("theValue"); Connection connection = DriverManager.getConnection( "jdbc:oracle:thin:@fourier.cs.iit.edu:1521:orcl", "mkhan12", "sourov345"); Statement statement = connection.createStatement() ; ResultSet resultset = statement.executeQuery("SELECT City,Country,COUNT(*)FROM Resort where City ='"+session.getAttribute("theValue")+"'"+"OR Country='"+session.getAttribute("theValue")+"'" ) ; out.write("\n"); out.write("\n"); out.write(" <TABLE BORDER=\"1\">\n"); out.write(" <TR>\n"); out.write(" <TH>City</TH>\n"); out.write(" <TH>City</TH>\n"); out.write(" <TH>Number of Resorts</TH>\n"); out.write(" \n"); out.write(" \n"); out.write(" \n"); out.write(" \n"); out.write(" \n"); out.write(" \n"); out.write(" </TR>\n"); out.write(" "); while(resultset.next()){ out.write("\n"); out.write(" <TR>\n"); out.write(" <TD> "); out.print( resultset.getString(1) ); out.write("</td>\n"); out.write(" <TD> "); out.print( resultset.getString(2) ); out.write("</td>\n"); out.write(" <TD> "); out.print( resultset.getString(2) ); out.write("</td>\n"); out.write(" \n"); out.write(" \n"); out.write(" \n"); out.write(" \n"); out.write(" </TR>\n"); out.write(" "); } out.write("\n"); out.write(" </TABLE>\n"); out.write(" </BODY>\n"); out.write("</html>\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
64e0b9fe-94a6-474d-b386-b3eb4d6a870f
6
public void setTime(int h, int m, int s) { if((h>=0 && h<24) && (m>=0 && m<60) && (s>=0 && s<60)) { hour = h; minute = m; second = s; } else throw new IllegalArgumentException( "hour, minute and/or second was out of range"); }
61e66273-9684-45b6-9332-3d232b19914a
1
private boolean jj_3_10() { if (jj_3R_28()) return true; return false; }
31e98dc7-909e-4510-ab4c-a9419f64c321
4
@Override public void execute() { seq(new WalkToSegment(0, 8)); seq(new WalkToSegment(-1, 8)); seq(new WalkToSegment(36, 16)); seqMove(new OverworldInteract(5)); seq(new SkipTextsSegment(4)); // pewter skip text for (int i=0;i<36;i++) { seqMove(new PressButton(Move.LEFT), 0); } for (int i=0;i<100;i++) { seqMove(new PressButton(Move.DOWN), 0); } seqMove(new PressButton(Move.LEFT), 0); seqMove(new PressButton(Move.UP), 0); for (int i=0;i<44;i++) { seqMove(new PressButton(Move.UP), 0); } for (int i=0;i<4;i++) { seqMove(new PressButton(Move.LEFT), 0); } // seq(new WalkToSegment(15,9)); // seq(new WalkToSegment(15,8, false)); // correct facing direction // seq(Segment.press(Move.A)); // use PC // seq(new SkipTextsSegment(1)); // booted PC // seq(Segment.press(Move.A)); // someones PC // seq(new SkipTextsSegment(2)); // someones PC, mon storage system // seq(Segment.scroll(1)); // deposit // seq(new DepositMonSegment(1)); // Charmander // seq(Segment.menu(Move.B)); // leave // seq(Segment.menu(Move.B)); // leave seq(new WalkToSegment(8,0)); }
f38fe8a4-8983-4de8-a5e6-9c8f6ea79be6
1
public static void updateCommandeClient(int idcommandeclient, int identreprise,int idinterlocuteur, Date datecommandeclient,String referencecommandeclient,Float totalhtcommandeclient,Float totalttccommandeclient, Float remisecommandeclient) throws SQLException { String query = ""; try { query = " UPDATE COMMANDE_CLIENT SET ID_ENTREPRISE=?,ID_INTERLOCUTEUR=?,COMDATE=?,COMREF=?,COMHT=?,COMTTC=?,COMREMISE=? where ID_COMMANDE=? "; PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query); pStatement.setInt(6, idcommandeclient); pStatement.setInt(1, identreprise); pStatement.setInt(2, idinterlocuteur); pStatement.setObject(3, datecommandeclient); pStatement.setString(4, referencecommandeclient); pStatement.setFloat(5, totalhtcommandeclient); pStatement.setFloat(6, totalttccommandeclient); pStatement.setFloat(7, remisecommandeclient); pStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(RequetesCommandeClient.class.getName()).log(Level.SEVERE, null, ex); } }
7b37d302-7bbe-4895-bce5-2f1f57837012
8
public void mouseDown(MouseEvent me) { guiUsedMouseDown = false; if (getWindows().mouseDown(me)) { guiUsedMouseDown = true; return; } int chx = (-getWorld().getScreenX()) + lastmx; int chy = (-getWorld().getScreenY()) + lastmy; chx /= 50; chy /= 50; if (chx < PavoHelper.getGameWidth(getWorld().getWorldSize()) * 2 && chy < PavoHelper.getGameHeight(getWorld().getWorldSize()) * 2 && chx >= 0 && chy >= 0) { Tile<Entity> e = getWorld().getEntityManager().getTile(chy,chx); if (e != null) { int acuratex = (-getWorld().getScreenX()) + lastmx - (chx*50); int acuratey = (-getWorld().getScreenY()) + lastmy - (chy*50); Location l = e.getEntity().getLocation(); acuratex += (chx - l.getCol())*50; acuratey += (chy - l.getRow())*50; e.getEntity().onMouseDown(acuratex,acuratey,me.getButton() == MouseEvent.BUTTON1); } } if (chx == yearf && chy == yearl) { gJsiw = !gJsiw; RoketUtils.submitAchievement(RoketGamerData.ACHIEVEMENT_DAVE); } }
59c00c8c-13bc-41f8-a2cb-9cd9780a54fd
5
public static byte [] generate() { // create ethernet header byte [] packet = HeaderGenerator.generateRandomEthernetHeader(); int eProto = ArrayHelper.extractInteger(packet, ETH_CODE_POS, ETH_CODE_LEN); // figure out what type of packet should be encapsulated after the // newly generated ethernet header. switch(eProto) { case EthernetProtocols.IP: // encapsulate IP byte [] ipHeader = HeaderGenerator.generateRandomIPHeader(); packet = ArrayHelper.join(packet, ipHeader); // figure out what type of protocol should be encapsulated after the // newly generated IP header. int ipProto = ArrayHelper.extractInteger(ipHeader, IP_CODE_POS, IP_CODE_LEN); switch(ipProto) { case IPProtocols.UDP: // encapsulate UDP inside IP byte [] udpHeader = HeaderGenerator.generateRandomUDPHeader(); packet = ArrayHelper.join(packet, udpHeader); break; case IPProtocols.ICMP: // encapsulate ICMP inside IP byte [] icmpHeader = HeaderGenerator.generateRandomICMPHeader(); packet = ArrayHelper.join(packet, icmpHeader); break; case IPProtocols.TCP: // encapsulate TCP inside IP byte [] tcpHeader = HeaderGenerator.generateRandomTCPHeader(); packet = ArrayHelper.join(packet, tcpHeader); break; default: // if the IP protocol isn't known, leave the data payload empty break; } break; case EthernetProtocols.ARP: byte [] arpHeader = HeaderGenerator.generateRandomARPHeader(); packet = ArrayHelper.join(packet, arpHeader); break; default: // if the ethernet protocol isn't known, leave the data payload empty break; } return packet; }
95911b93-e563-4301-88b0-290a3eec0f87
1
@Override public boolean isObstacle(Element e) { if (e instanceof Player) return true; return false; }
4eb4eaee-60c3-474e-8581-f7db7003475c
8
public AngryFriend() { JFrame frame = new JFrame("Start Angry Game"); frame.setLocationRelativeTo(null); frame.setMinimumSize(new Dimension(300, 400)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (x == e.getX() && y == e.getY()) { win = true; } // TODO Auto-generated method stub } }); addMouseMotionListener(new MouseAdapter() { @Override public void mouseMoved(MouseEvent e) { // TODO Auto-generated method stub Random r = new Random(); int xAnother = r.nextInt(50); int yAnother = r.nextInt(50); if (xAnother < 26) xAnother = 26; if (yAnother < 26) yAnother = 26; int random = r.nextInt(4); if (random == 0) { x = e.getX() + xAnother; y = e.getY() + yAnother; } else if (random == 1) { x = e.getX() + xAnother; y = e.getY() - yAnother; } else if (random == 2) { x = e.getX() - xAnother; y = e.getY() + yAnother; } else { x = e.getX() - xAnother; y = e.getY() - yAnother; } try { Thread.sleep(100); } catch (InterruptedException ex) { ex.printStackTrace(); } repaint(); } }); frame.getContentPane().add(this); frame.pack(); frame.setVisible(true); }
1d3f773a-e589-4ca8-819b-3e35c483b765
9
public List<PfamToGoMapping> parse() throws IOException { final String error = ForesterUtil.isReadableFile( getInputFile() ); if ( !ForesterUtil.isEmpty( error ) ) { throw new IOException( error ); } final BufferedReader br = new BufferedReader( new FileReader( getInputFile() ) ); String line; final List<PfamToGoMapping> mappings = new ArrayList<PfamToGoMapping>(); int line_number = 0; try { while ( ( line = br.readLine() ) != null ) { line_number++; line = line.trim(); if ( ( line.length() > 0 ) && !line.startsWith( "!" ) ) { final Matcher m = PFAM_TO_GO_PATTERN.matcher( line ); if ( !m.matches() ) { throw new IOException( "unexpected format [\"" + line + "\"]" ); } if ( m.groupCount() != 2 ) { throw new IOException( "unexpected format [\"" + line + "\"]" ); } final String pfam = m.group( 1 ); final String go = m.group( 2 ); if ( ForesterUtil.isEmpty( pfam ) || ForesterUtil.isEmpty( go ) ) { throw new IOException( "unexpected format [\"" + line + "\"]" ); } final PfamToGoMapping map = new PfamToGoMapping( new DomainId( pfam ), new GoId( go ) ); ++_mapping_count; mappings.add( map ); } } // while ( ( line = br.readLine() ) != null ) } catch ( final Exception e ) { throw new IOException( "parsing problem: " + e.getMessage() + " [at line " + line_number + "]" ); } return mappings; }
a8b7bfa2-1623-499d-b04e-9a57a318a2a4
8
public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (obj.getClass() != this.getClass()) return false; Picture that = (Picture) obj; if (this.width() != that.width()) return false; if (this.height() != that.height()) return false; for (int x = 0; x < width(); x++) for (int y = 0; y < height(); y++) if (!this.get(x, y).equals(that.get(x, y))) return false; return true; }
bcf2e5a6-4aa8-4b0c-aecf-22ad15ae4923
0
public SaltAlgorithmIdentifierType createSaltAlgorithmIdentifierType() { return new SaltAlgorithmIdentifierType(); }
eea28e9d-d5f3-4e2c-906c-aaaef52bfc60
7
public void InputSymbol(int input){ for (int i = 0; i < mStates.size(); ++i) if (mStates.get(i).mUsed && mTransitions.containsKey(mStates.get(i))){ List<Transition> temp = mTransitions.get(mStates.get(i)); for (int j = 0; j < temp.size(); ++j){ if (temp.get(j).mInput == input){ List<StateNFA> tempNS = temp.get(j).mNextStates; for (int k = 0; k < tempNS.size(); ++k){ tempNS.get(k).mUsedInNextStep = true; } } } } for (int i = 0; i < mStates.size(); ++i){ mStates.get(i).mUsed = mStates.get(i).mUsedInNextStep; mStates.get(i).mUsedInNextStep = false; } }
c919fec2-9e0f-4666-9849-e3ebcf8a1470
1
public static String showCommandHistory(boolean direction) { String cmd = ""; if (!lastCommands.isEmpty()) { cmd = lastCommands.pop().toString(); } return cmd.trim(); }
4fa84ddf-3f59-4bba-bfaf-6979567a4413
8
public static int countNeighbours(boolean [][] world, int col, int row){ int total = 0; total = getCell(world, col-1, row-1) ? total + 1 : total; total = getCell(world, col , row-1) ? total + 1 : total; total = getCell(world, col+1, row-1) ? total + 1 : total; total = getCell(world, col-1, row ) ? total + 1 : total; total = getCell(world, col+1, row ) ? total + 1 : total; total = getCell(world, col-1, row+1) ? total + 1 : total; total = getCell(world, col , row+1) ? total + 1 : total; total = getCell(world, col+1, row+1) ? total + 1 : total; return total; }
94bd6af5-506b-480f-9f9d-28edfb96276c
8
void fdump(int _depth, Instruction i, boolean clone) { final String label = i.getByteCode().getName();// InstructionHelper.getLabel(i, false, false, false); if (i instanceof CloneInstruction) { fdump(_depth, ((CloneInstruction) i).getReal(), true); } else { if (_depth == 0) { if (i.producesStack()) { System.out.print(" "); } else { System.out.print("! "); } } if (clone) { System.out.print("*"); } else if (_depth == 0) { System.out.print(" "); } System.out.print(i.getThisPC() + ":" + label); } if (i.getFirstChild() != null) { // int child=0; System.out.print("{"); boolean comma = false; for (Instruction ii = i.getFirstChild(); ii != null; ii = ii.getNextExpr()) { if (comma) { System.out.print(" ,"); } // System.out.print("<"+child+">"); fdump(_depth + 1, ii, false); comma = true; // child++; } System.out.print("}"); } }
74c05947-e234-4457-8f12-7cff19193ee7
8
public int compare(String o1, String o2) { String s1 = (String)o1; String s2 = (String)o2; int thisMarker = 0; int thatMarker = 0; int s1Length = s1.length(); int s2Length = s2.length(); while (thisMarker < s1Length && thatMarker < s2Length) { String thisChunk = getChunk(s1, s1Length, thisMarker); thisMarker += thisChunk.length(); String thatChunk = getChunk(s2, s2Length, thatMarker); thatMarker += thatChunk.length(); // If both chunks contain numeric characters, sort them numerically int result = 0; if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // Simple chunk comparison by length. int thisChunkLength = thisChunk.length(); result = thisChunkLength - thatChunk.length(); // If equal, the first different number counts if (result == 0) { for (int i = 0; i < thisChunkLength; i++) { result = thisChunk.charAt(i) - thatChunk.charAt(i); if (result != 0) { return result; } } } } else { result = thisChunk.compareTo(thatChunk); } if (result != 0) return result; } return s1Length - s2Length; }
5f21a6f5-6727-40d6-a1d0-294b76096ee8
0
public void setSenha(String senha) { this.senha = senha; }
910ef0a5-0785-4849-b6e1-dd65dac2e49a
2
private static ApparentPlace createApparentPlace(JPLEphemeris ephemeris, int kBody) { MovingPoint planet = null; if (kBody == JPLEphemeris.MOON) planet = new MoonCentre(ephemeris); else planet = new PlanetCentre(ephemeris, kBody); EarthCentre earth = new EarthCentre(ephemeris); MovingPoint sun = null; if (kBody == JPLEphemeris.SUN) sun = planet; else sun = new PlanetCentre(ephemeris, JPLEphemeris.SUN); EarthRotationModel erm = new IAUEarthRotationModel(); return new ApparentPlace(earth, planet, sun, erm); }
f20f752f-dbef-4482-a0e2-cb368a7981f7
0
public Parser(Scanner scanner) { this.scanner = scanner; this.error = new ErrorReport(); initSymbolTable(); }
2c1377bd-0133-4a73-b347-d654e7f34487
1
Coordinate calcRelativePosition(final Subject subject) { Coordinate abs = calcAbsPosition(subject); if (abs.x == 0) { return abs; } final double scale = getRadiusScale(subject); return new Coordinate(abs.x * scale, abs.y * scale); }
8a2f6b87-2b7c-4596-a288-a9d1cc7e64c0
1
public JPanel getUsertileImageframeMenu() { if (!isInitialized()) { IllegalStateException e = new IllegalStateException("Call init first!"); throw e; } return this.usermenuImageframeMenu; }
287ef7c7-85a2-474d-8e36-6c2bbdbb75e2
8
@Override public Object evaluate(DeferredObject[] arguments) throws HiveException { List<?> value_array = arrayOI.getList(arguments[0].get()); List<?> index_array = (List<?>)converter.convert(arguments[1].get()); if (value_array == null || index_array == null) { return null; } // Avoid using addAll or the constructor here because that will cause // an unchecked cast warning on List<?>. HashSet<Integer> indices = new HashSet<Integer>(); for (int ii = 0; ii < index_array.size(); ++ii) { indices.add((Integer)index_array.get(ii)); } ArrayList<Object> result = new ArrayList<Object>(); for (int ii = 0; ii < value_array.size(); ++ii) { if (!indices.contains(ii)) { result.add(value_array.get(ii)); } } return result; }
fa7e5418-4d5d-4838-822c-5f97895383a5
2
public Stmt lastStmt() { final ListIterator iter = stmts.listIterator(stmts.size()); while (iter.hasPrevious()) { final Stmt s = (Stmt) iter.previous(); if (s instanceof LabelStmt) { continue; } return s; } return null; }
8154aa41-1e2c-4fd2-a020-a40f657eec33
0
public void addSelectionListener(ConfigurationSelectionListener listener) { selectionListeners.add(listener); }
ff171623-bea5-4a05-b8cd-784f3e30e734
4
public static Fst<Pair<Character, Character>> formTo(CharSequence in, CharSequence out) { Fst<Pair<Character, Character>> bla = new Fst<>(); if (in.length() == 0) { bla.addState(StateFlag.ACCEPT, StateFlag.INITIAL); return bla; } State previous = null; for (int i = 0; i < in.length(); i++) { State source = previous == null ? bla.addStateInitial() : previous; State target = i + 1 == in.length() ? bla.addStateAccept() : bla .addState(); Transition<Pair<Character, Character>> transition = bla .addTransition(Pair.of(in.charAt(i), out.charAt(i)), source, target); previous = target; } return bla; }
2cf55760-2b35-463a-bec6-ddce69bb5d85
1
public String getLocationpath(String xpathExpression){ if (xpathExpression.contains("/")){ int pos = xpathExpression.indexOf("/"); return xpathExpression.substring(pos); }else{ return xpathExpression; } }
b263fde3-9ab6-423b-a9d1-f6beabceba86
5
protected Family findFamily(String xref) { xref = xref.substring(1, xref.length() - 1); if (isDebugging()) System.out.print(">>> Looking for family " + xref + " ... "); Family family = (Family)getObjectByXref(xref); if (family != null && isDebugging()) System.out.println("found " + family); if (family == null) { if (isDebugging()) System.out.println("not found, creating new family"); family = new Family(); putObjectByXref(xref, family); } return family; }
08c6369d-6374-4d40-af3a-61a43a787723
1
private double calcMLat () { double add = 0; for (int i = 0; i < nbrPoints; i++) { add = add + positions.get(i).getLatitude(); } double result = add / nbrPoints; return (result); }
cc40b1a9-d98b-4016-af99-4fb6cad59482
4
public void dispatchCommand(String command) { if (command == null || command.isEmpty()) throw new IllegalArgumentException("The coommand cannot be null or empty"); String[] args = command.split("\\s+"); String cmd = args[0]; args = StringUtils.removeFirstArg(args); for (CommandHandler c : _commands) { if (c.hasAlias(cmd)) { c.onCommand(cmd, args); return; } } System.out.println("Unknown command \"" + cmd + "\""); }
c794be29-bf77-4ecd-9ea0-c16df5d70a02
0
private Combination<Colors> generateTargetCombination() { List<Token<Colors>> targetTokens = new ArrayList<Token<Colors>>(); targetTokens.add(new Token<Colors>(Colors.R)); targetTokens.add(new Token<Colors>(Colors.O)); targetTokens.add(new Token<Colors>(Colors.Y)); targetTokens.add(new Token<Colors>(Colors.G)); targetTokens.add(new Token<Colors>(Colors.B)); return new Combination<Colors>(targetTokens); }
ef15b82c-991d-42ff-9301-61d0ce132a67
7
@Override public void execute() throws MojoExecutionException { NodeJsMojoBase.NodeInstallInformation info = super.run(filter); if (info == null) { return; } for (Task task : tasks) { try { if (task.watch) { addWatchForTask(task); } } catch (IOException ex) { throw new MojoExecutionException("Error adding watch for task " + task, ex); } } getLog().info("Starting watch vigil"); try { watch(info); } catch (CommandLineException ex) { throw new MojoExecutionException("Error during watch", ex); } catch (InterruptedException ex) { throw new MojoExecutionException("Error during watch", ex); } catch (IOException ex) { throw new MojoExecutionException("Error during watch", ex); } }
a01f75fc-951d-4100-a41e-e953619a1e26
9
private void button2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button2ActionPerformed if (order1code2tf.getText().equals("1001")) { o1c2destf.setText("Chicken Nugget"); } if (order1code2tf.getText().equals("1002")) { o1c2destf.setText("Fries"); } if (order1code2tf.getText().equals("1003")) { o1c2destf.setText("Salad"); } if (order1code2tf.getText().equals("1004")) { o1c2destf.setText("Cheese Burger"); } if (order1code2tf.getText().equals("1005")) { o1c2destf.setText("Bacon Cheese Burger"); } if (order1code2tf.getText().equals("1006")) { o1c2destf.setText("Hamburger"); } if (order1code2tf.getText().equals("1007")) { o1c2destf.setText("Soda"); } if (order1code2tf.getText().equals("1008")) { o1c2destf.setText("Tea"); } if (order1code2tf.getText().equals("1009")) { o1c2destf.setText("Coffee"); } }//GEN-LAST:event_button2ActionPerformed
4c038841-36c8-44cf-a172-d7bc627d0386
6
public static int getDeltaX(int dir) { if(dir == LEFT || dir == UP_LEFT || dir == DOWN_LEFT) return -1; if(dir == RIGHT || dir == UP_RIGHT || dir == DOWN_RIGHT) return 1; return 0; }
f5fd5753-6101-4273-8e31-c3479123c76d
0
public Date getDate() { return date; }
4c01e358-409f-4af3-8f48-89c05fbd2a7f
9
private void saveAsCSV(final File csvFile, final CSVManager csvManager) { if(csvFile == null) { JOptionPane.showMessageDialog( null, "Fehler in DataViewFrame.saveAsCSV: es wurde keine CSV-Datei übergeben.", "Fehlermeldung", JOptionPane.ERROR_MESSAGE ); return; } if(csvManager == null) { JOptionPane.showMessageDialog( null, "Fehler in DataViewFrame.saveAsCSV: es wurde kein CSV-Manager übergeben.", "Fehlermeldung", JOptionPane.ERROR_MESSAGE ); return; } final OutputStreamWriter fileWriter; final SortedMap<String, Charset> availableCharsets = Charset.availableCharsets(); Charset charset = null; if(_isoEncoding.isSelected()) { charset = availableCharsets.get("ISO-8859-1"); } else if(_macEncoding.isSelected()) { charset = availableCharsets.get("MacRoman"); if(charset == null) { charset = availableCharsets.get("x-MacRoman"); } } if(charset == null) { charset = Charset.defaultCharset(); } try { fileWriter = new OutputStreamWriter(new FileOutputStream(csvFile), charset); } catch(IOException e) { System.err.println("Es wurde eine IOException beim Öffnen der Datei " + csvFile.getName() + " ausgelöst."); System.err.println("Möglicherweise wird die Datei von einem anderen Programm verwendet."); System.err.println("Die Nachricht der IOException ist: " + e.getMessage()); JOptionPane.showMessageDialog( null, "Fehler beim Öffnen der Datei " + csvFile.getName(), "Fehlermeldung", JOptionPane.ERROR_MESSAGE ); return; } try { fileWriter.write(csvManager.getCSVHeaderLine(_rowHeaderButtonForCSVExport.isSelected())); fileWriter.write(csvManager.getCSVLines(_rowHeaderButtonForCSVExport.isSelected())); } catch(IOException e) { System.err.println("Es wurde eine IOException beim Schreiben der Datei " + csvFile.getName() + " ausgelöst."); System.err.println("Die Nachricht der IOException ist: " + e.getMessage()); JOptionPane.showMessageDialog( null, "Fehler beim Schreiben der Datei " + csvFile.getName(), "Fehlermeldung", JOptionPane.ERROR_MESSAGE ); return; } try { fileWriter.close(); } catch(IOException e) { System.err.println("Es wurde eine IOException beim Schließen der Datei " + csvFile.getName() + " ausgelöst."); System.err.println("Die Nachricht der IOException ist: " + e.getMessage()); JOptionPane.showMessageDialog( null, "Fehler beim Schließen der Datei " + csvFile.getName(), "Fehlermeldung", JOptionPane.ERROR_MESSAGE ); } }
5cfab785-7966-493a-a10c-517d35a990d4
6
public ResultSet preencherTabela(String Departamento) throws SQLException { Connection conexao = null; PreparedStatement comando = null; ResultSet resultado = null; try { conexao = BancoDadosUtil.getConnection(); comando = conexao.prepareStatement(SQL_TODOS_PROJETOS_TABELA); comando.setString(1, Departamento); resultado = comando.executeQuery(); conexao.commit(); } catch (Exception e) { if (conexao != null) { conexao.rollback(); } throw new RuntimeException(e); } finally { if (comando != null && !comando.isClosed()) { comando.close(); } if (conexao != null && !conexao.isClosed()) { conexao.close(); } } return resultado; }
e3760f5b-cc17-4a8e-a607-d79552acdf34
9
public static void bottomUpRuleInduction(List examples, boolean simplifyRuleP) { { List positive = List.newList(); List negative = List.newList(); List allPositive = null; List allNegative = null; List rules = List.newList(); Symbol concept = ((TrainingExample)(examples.first())).concept; Cons rule = Stella.NIL; { TrainingExample example = null; Cons iter000 = examples.theConsList; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { example = ((TrainingExample)(iter000.value)); if (BooleanWrapper.coerceWrappedBooleanToBoolean(((BooleanWrapper)(example.output)))) { positive.push(example); } else { negative.push(example); } } } allPositive = positive.copy(); allNegative = negative.copy(); Logic.collectFactsInExamples(positive); { TrainingExample example = null; Cons iter001 = positive.theConsList; for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) { example = ((TrainingExample)(iter001.value)); example.facts = ((Cons)(Stella_Object.substituteConsTree(example.facts, Logic.SYM_LOGIC_pY, example.name))); } } System.out.println("Starting rule induction with " + positive.length() + " positive and " + negative.length() + " negative examples"); loop002 : while (!positive.emptyP()) { rule = Logic.learnOneRuleBottomUp(positive, negative); if (rule == Stella.NIL) { System.out.println("Quiting with " + positive.length() + " examples uncovered"); break loop002; } else if (simplifyRuleP && allNegative.nonEmptyP()) { rule = Logic.simplifyAntecedent(rule, Stella.getQuotedTree("((?Y) \"/LOGIC\")", "/LOGIC"), allPositive, allNegative); } else { } rules.push(Cons.list$(Cons.cons(Logic.SYM_STELLA_eg, Cons.cons(Cons.cons(Logic.SYM_STELLA_AND, ((Cons)(Stella_Object.copyConsTree(rule))).concatenate(Stella.NIL, Stella.NIL)), Cons.cons(Cons.cons(concept, Cons.cons(Logic.SYM_LOGIC_pY, Stella.NIL)), Cons.cons(Stella.NIL, Stella.NIL)))))); } { System.out.println(); System.out.println("PowerLoom has induced the following rules"); System.out.println(); } ; if (rules != null) { { Cons rule000 = null; Cons iter002 = rules.theConsList; for (;!(iter002 == Stella.NIL); iter002 = iter002.rest) { rule000 = ((Cons)(iter002.value)); System.out.println(rule000); } } Logic.$INDUCED_DECISION_RULES$ = rules; } } }
de8540ab-f408-41e3-9c86-e2531e9ffd51
6
public TuringMachineFrame(String title, boolean status, TuringMachine model, TuringMachineMenuPanel view0, TuringMachineLoadPanel view1, TuringMachineStartPanel view2, TuringMachineTransitionPanel view3, TuringMachineInputPanel view4, TuringMachineSimulationPanel view5){ super(title); isChild = status; aTuringMachine = model; cards = new CardLayout(); mainPanel = new JPanel(); mainPanel.setLayout(cards); menuView = view0; loadView = view1; startView = view2; transitionView = view3; inputView = view4; simulationView = view5; mainWindow = this; mainPanel.add(menuView,"0"); mainPanel.add(loadView,"1"); mainPanel.add(startView,"2"); mainPanel.add(transitionView,"3"); mainPanel.add(inputView,"4"); mainPanel.add(simulationView,"5"); add(mainPanel); cards.show(mainPanel,"0"); // add listeners in menuView menuView.getLoadButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleLoadButton(); } }); menuView.getLoadButton().addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent e) { menuView.setCurrentButton(1); } }); menuView.getCreateButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCreateButton(); } }); menuView.getCreateButton().addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent e) { menuView.setCurrentButton(2); } }); // add listeners in loadView loadView.getLoadMachineButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleLoadMachineButton(); } }); loadView.getRemoveMachineButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRemoveMachineButton(); } }); loadView.getLoadBackButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleLoadBackButton(); } }); // add listeners in startView startView.getAddTapeAlphabetButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleAddTapeAlphabetButton(); } }); startView.getAddInputAlphabetButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleAddInputAlphabetButton(); } }); startView.getAddStateButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleAddStateButton(); } }); startView.getRemoveTapeAlphabetButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRemoveTapeAlphabetButton(); } }); startView.getRemoveInputAlphabetButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRemoveInputAlphabetButton(); } }); startView.getRemoveStateButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRemoveStateButton(); } }); startView.getNextButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleNextButton(); } }); startView.getStartBackButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleStartBackButton(); } }); // add listeners in transitionView transitionView.getBackButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleBackButton(); } }); transitionView.getSaveButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSaveButton(); } }); transitionView.getNextButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSecondNextButton(); } }); transitionView.getTransitionList().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { handleSelectedListItem(); } }); transitionView.getStateComboBox().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleComboBoxSelection(); } }); // add listeners in inputView inputView.getAddButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleAddInputButton(); } }); inputView.getRemoveButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleDeleteInputButton(); } }); inputView.getClearButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleClearInputButton(); } }); inputView.getBackButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSecondBackButton(); } }); inputView.getBuildButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleBuildButton(); } }); // add listeners in simulationView simulationView.getRunButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRunButton(); } }); simulationView.getSaveMachineButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSaveMachineButton(); } }); simulationView.getChangeInputButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleChangeInputButton(); } }); simulationView.getResetButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleResetButton(); } }); simulationView.getSlider().addChangeListener(new ChangeListener(){ public void stateChanged(ChangeEvent e){ handleSlider((JSlider)e.getSource()); } }); simulationView.getSpinner().addChangeListener(new ChangeListener(){ public void stateChanged(ChangeEvent e){ handleSpinner((JSpinner)e.getSource()); } }); // add timer listeners aTimer = new Timer(1000 ,new ActionListener(){ public void actionPerformed(ActionEvent e){ handleTimerTick(); } }); // add menu bar menuBar = new JMenuBar(); fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); mainItem = new JMenuItem("Main Menu", KeyEvent.VK_M); mainItem.setEnabled(false); fileMenu.add(mainItem); exitItem =new JMenuItem("Exit", KeyEvent.VK_X); fileMenu.add(exitItem); menuBar.add(fileMenu); helpMenu = new JMenu("Help"); helpMenu.setMnemonic(KeyEvent.VK_H); aboutItem = new JMenuItem("About", KeyEvent.VK_A); helpMenu.add(aboutItem); menuBar.add(helpMenu); setJMenuBar(menuBar); // add menu item listeners mainItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { handleSecondBackButton(); handleBackButton(); handleStartBackButton(); } }); exitItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ int result = JOptionPane.showConfirmDialog(mainWindow,"Are you sure you want to exit?","Exit",JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) System.exit(0); } }); aboutItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { if(Desktop.isDesktopSupported()){ try { Desktop.getDesktop().browse(new URL("https://github.com/Enixma/Turing-Machine-Simulation").toURI()); }catch (Exception ex) { } } } }); // set frame properties setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent e){ if(isChild){ JFrame frame = (JFrame)e.getSource(); int result = JOptionPane.showConfirmDialog(frame,"Are you sure you want to close this window?","Close Window",JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) setDefaultCloseOperation(DISPOSE_ON_CLOSE); } else{ int result = JOptionPane.showConfirmDialog(mainWindow,"Are you sure you want to exit?","Exit",JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) setDefaultCloseOperation(EXIT_ON_CLOSE); } } }); setSize(1000,720); setResizable(false); setChildProperties(); }
150a821c-0c70-437c-9e19-a08031339e6c
2
public int clockSequence() { if (version() != 1) { throw new UnsupportedOperationException("Not a time-based UUID"); } if (sequence < 0) { sequence = (int)((leastSigBits & 0x3FFF000000000000L) >>> 48); } return sequence; }
e4873ae8-7c6e-44f2-a3c6-a57a0c4c5963
3
public Status getStatus() { int state = alGetSourcei(source, AL_SOURCE_STATE); switch (state) { case AL_PLAYING: return Status.Playing; case AL_STOPPED: return Status.Stopped; case AL_PAUSED: return Status.Paused; } return Status.Stopped; }
4577b5c8-295c-4390-8a70-0df7921a8da0
2
@BeforeTest @Parameters("browser") public void setUp(String browser) throws Exception { if(browser.equalsIgnoreCase("firefox")) { app.driver = new FirefoxDriver(); } else if(browser.equalsIgnoreCase("chrome")) { System.setProperty("webdriver.chrome.driver", "./src/resourses/chromedriver"); app.driver = new ChromeDriver(); } //app.driver = new FirefoxDriver(); String baseUrl = "http://www.openforbeta.com"; app.driver.get(baseUrl); app.driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); }
dfceeb69-8553-4239-b48a-9cbcf11710b4
3
void parseMisc() throws java.lang.Exception { while (true) { skipWhitespace(); if (tryRead("<?")) { parsePI(); } else if (tryRead("<!--")) { parseComment(); } else { return; } } }
34ddbb49-3fac-4650-8b7a-3f31b1f549cf
7
public static void loadVocab() { System.out.print("Enter the absolute path to where your vocab file will be created.\n >"); String input; while (true) { input = Game.scanner.nextLine(); file = new File(input); if (file.exists()) break; else System.out.println("File not found!"); } try { if (!file.exists()) { file.createNewFile(); write("# Please enter vocab in format 'm/f:french:english', or just french:english if it is not a noun", "# Add as many as you want!", "m:chien:dog", "f:table:table"); log("Could not find vocab file! Creating..."); } BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) { if (line.startsWith("#")) continue; Vocab.createVocab(line); } if (Vocab.vocabList.isEmpty()) exit("No vocab was found!"); log("Loaded " + Vocab.vocabList.size() + " items of vocab."); } catch (IOException e) { System.out.println("Could not load vocab: " + e.getMessage()); System.exit(0); } }
e70eff52-ac51-4209-84c8-d25b9df5c6f7
9
protected void recompute() { // System.out.println("pnCal::recompute: " + yy + ":" + mm + ":" + dd); if (mm < 0 || mm > 11) throw new IllegalArgumentException("Month " + mm + " bad, must be 0-11"); clearDayActive(); calendar = new GregorianCalendar(yy, mm, dd); // Compute how much to leave before the first. // getDay() returns 0 for Sunday, which is just right. leadGap = new GregorianCalendar(yy, mm, 1).get(Calendar.DAY_OF_WEEK) - 1; // System.out.println("leadGap = " + leadGap); int daysInMonth = dom[mm]; if (isLeap(calendar.get(Calendar.YEAR)) && mm == 1) // if (isLeap(calendar.get(Calendar.YEAR)) && mm > 1) ++daysInMonth; // Blank out the labels before 1st day of month for (int i = 0; i < leadGap; i++) { labs[0][i].setText(""); } // Fill in numbers for the day of month. for (int i = 1; i <= daysInMonth; i++) { JButton b = labs[(leadGap + i - 1) / 7][(leadGap + i - 1) % 7]; b.setText(Integer.toString(i)); } // 7 days/week * up to 6 rows for (int i = leadGap + 1 + daysInMonth; i < 6 * 7; i++) { labs[(i) / 7][(i) % 7].setText(""); } // Shade current day, only if current month if (thisYear == yy && mm == thisMonth) setDayActive(dd); // shade the box for today // Say we need to be drawn on the screen repaint(); }
812f91b7-a4a2-40ac-8f38-e67968511d52
8
public static void nodeToBlockArray( RSTNode n, int nx, int ny, int nsize, BlockStack[] blockStacks, int bx, int by, int bw, int bh, int bo ) { if( nx >= bx + bw || nx + nsize <= bx || ny >= by + bh || ny + nsize <= by ) return; switch( n.getNodeType() ) { case BLOCKSTACK: int rx = nx - bx; int ry = ny - by; blockStacks[rx + ry*bw + bo] = n; break; case QUADTREE: int subSize = nsize>>1; RSTNode[] subNodes = n.getSubNodes(); for( int sy=0, si=0; sy<2; ++sy) for( int sx=0; sx<2; ++sx, ++si ) { nodeToBlockArray( subNodes[si], nx+(sx*subSize), ny+(sy*subSize), subSize, blockStacks, bx, by, bw, bh, bo ); } break; default: throw new RuntimeException("Don't know how to nodeToBlockArray "+n.getNodeType()+" node"); } }
bb2a4241-dbba-4f77-94a9-7335c51d7491
3
private static Object getGtkStyle(Object styleFactory, JComponent component, String regionName) throws Exception { Class<?> regionClass = Class.forName("javax.swing.plaf.synth.Region"); Field field = regionClass.getField(regionName); Object region = field.get(regionClass); Class<?> styleFactoryClass = styleFactory.getClass(); Method method = styleFactoryClass.getMethod("getStyle", new Class<?>[] { JComponent.class, regionClass }); boolean accessible = method.isAccessible(); method.setAccessible(true); Object style = method.invoke(styleFactory, component, region); method.setAccessible(accessible); return style; }
d42587d0-78a4-4d58-b2e8-6472f120d219
7
protected DVD readDVD() throws Exception { if ( mainReadHandle == null ) { throw new Exception("Read Handle is null."); } Read in = mainReadHandle; if ( !in.nextLine().isEmpty()) { throw new Exception("Read Error."); } if ( !in.nextLine().equals("DVDObjectB")) { throw new Exception("Read Error."); } // String title, long iD, int year, ArrayList<Long> style, int amount, boolean sell, boolean rent, double byprice, double rentPrice, int rentAmount // Ϊ乹캯׼ String title = in.nextLine(); long iD = in.nextLong(); int year = in.nextInt(); int amount = in.nextInt(); double buyprice = in.nextDouble(); double rentPrice = in.nextDouble(); int rentAmount = in.nextInt(); boolean sell = in.nextBoolean(); boolean rent = in.nextBoolean(); if ( !in.nextLine().equals("DVDObjectSB")) { throw new Exception("Read Error."); } // Ϊ׼ ArrayList<Long> style = new ArrayList<Long>(); int iTemp = in.nextInt(); for (int i = 0; i < iTemp; i++) { style.add(in.nextLong()); } if ( !in.nextLine().equals("DVDObjectSE")) { throw new Exception("Read Error."); } if ( !in.nextLine().equals("DVDObjectE")) { throw new Exception("Read Error."); } return new DVD(title, iD, year, style, amount, sell, rent, buyprice, rentPrice, rentAmount); }
440a0360-b16b-4a59-bf8d-5b78b867b1a2
7
public Grid(String name) { mapName = name; String fileName = new File("").getAbsolutePath() + "\\readIn\\" + mapName + ".txt"; try { FileReader file = new FileReader(fileName); Scanner in = new Scanner(file); gridX = in.nextInt(); gridY = in.nextInt(); in.nextLine(); textGrid = new char[gridX][gridY]; tiles = new Tile[gridX][gridY]; String temp = ""; for (int a = 0; a < gridY && in.hasNext(); a++) { temp = in.next(); for (int c = 0; c < gridX; c++) { textGrid[c][a] = temp.charAt(c); } temp = ""; } in.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } setMap(); try { tileSheetBig = ImageIO.read(new File("sprites/tiles.png")); } catch (IOException e) { e.printStackTrace(); } tileSheet = new BufferedImage[tileRows * tileCols]; for (int i = 0; i < tileCols; i++) { for (int j = 0; j < tileRows; j++) { tileSheet[i * tileRows + j] = tileSheetBig.getSubimage(i * tileWidth, j * tileHeight, tileWidth, tileHeight); } } }
3b084893-644c-4dc1-8cda-60813d0f27a6
6
private void loadIniFile() { if (this.inifile.exists()) { try { this.ini = new Ini(this.inifile); } catch (InvalidFileFormatException e) { System.out.println("Config.ini Fehler"); } catch (IOException e) { System.out.println("Config.ini Fehler"); } } else { try { this.createIniFile(); } catch (IOException e) { throw new NoConfigFileException(e); } try { this.ini = new Ini(this.inifile); } catch (InvalidFileFormatException e) { throw new NoConfigFileException(e); } catch (IOException e) { throw new NoConfigFileException(e); } } }
1425e0e4-0d9e-4164-9c7c-a4012ae8f8a2
1
@Override public void mouseDragged(MouseEvent e) { if (activeMove != null) { activeX = e.getX(); activeY = e.getY(); } else { activeX = -1; activeY = -1; } BufferedImage copyImage = new BufferedImage(lastImage.getWidth(), lastImage.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g = copyImage.createGraphics(); g.drawImage(lastImage, 0, 0, null); renderDragCards(g, game.getBoard()); Graphics panelGraphics = getGraphics(); panelGraphics.drawImage(copyImage, 0, 0, null); panelGraphics.dispose(); g.dispose(); }
cbb1f393-2a3e-4cea-aebb-51f1c98016d6
6
void autoFillName(String input, KeyEvent e){ try{ int pos = ((JTextField)e.getSource()).getCaretPosition(); if(pos > 0){ boolean whiteflag = false; String crumb = ""; String left = input.substring(0,pos); if(left.indexOf(" ")!=-1){ crumb = input.substring(left.lastIndexOf(" "), pos).trim(); left = input.substring(0,left.lastIndexOf(" ")+1); whiteflag = true; }else{ crumb = input.substring(0,pos); } ListIterator<String> it = client.users.listIterator(); while(it.hasNext()){ String name = (String)it.next(); if(name.toLowerCase().startsWith(crumb.toLowerCase().trim())){ String line = ""; if(whiteflag){ line = left+name; }else{ line = name; } ((JTextField)e.getSource()).setText(line+" "); break; } } } }catch(Exception ex){ ex.printStackTrace(); } }
f3cf67d2-9597-4846-91c8-09fda5c48044
9
public static void loadLibraryFromJar(String path) throws IOException { if (!path.startsWith("/")) { throw new IllegalArgumentException("The path to be absolute (start with '/')."); } // Obtain filename from path String[] parts = path.split("/"); String filename = (parts.length > 1) ? parts[parts.length - 1] : null; // Split filename to prexif and suffix (extension) String prefix = ""; String suffix = null; if (filename != null) { parts = filename.split("\\.", 2); prefix = parts[0]; suffix = (parts.length > 1) ? "." + parts[parts.length - 1] : null; // Thanks, davs! :-) } // Check if the filename is okay if (filename == null || prefix.length() < 3) { throw new IllegalArgumentException("The filename has to be at least 3 characters long."); } // Prepare temporary file File temp = File.createTempFile(prefix, suffix); temp.deleteOnExit(); if (!temp.exists()) { throw new FileNotFoundException("File " + temp.getAbsolutePath() + " does not exist."); } // Prepare buffer for data copying byte[] buffer = new byte[1024]; int readBytes; // Open and check input stream InputStream is = NativeUtils.class.getResourceAsStream(path); if (is == null) { throw new FileNotFoundException("File " + path + " was not found inside JAR."); } // Open output stream and copy data between source file in JAR and the temporary file OutputStream os = new FileOutputStream(temp); try { while ((readBytes = is.read(buffer)) != -1) { os.write(buffer, 0, readBytes); } } finally { // If read/write fails, close streams safely before throwing an exception os.close(); is.close(); } // Finally, load the library System.load(temp.getAbsolutePath()); }
21ee8ef5-fc39-435f-a191-79224e3b9885
5
public Iterable<Periodical> findPeriodicals(SearchFilter filter) { Statement stmt = null; List<Periodical> periodicals = new LinkedList<Periodical>(); try { stmt = con.createStatement(); String constraints = ""; for (String attributeName : filter.getAttributeNames()) { constraints += attributeName + " LIKE " + "'%" + filter.getValueForAttribute(attributeName) + "%'" + " AND "; } constraints = constraints.substring(0, constraints.length() - 5); ResultSet results = stmt .executeQuery("Select * from Periodical where " + constraints); while (results.next()) { String itemID = results.getString("ISSN"); String title = results.getString("Title"); String publisher = results.getString("Publisher"); String volume = results.getString("Volume"); double number = Double.valueOf(results.getString("Number")); Calendar date = Calendar.getInstance(); Date tableDate = results.getDate("Date"); date.setTime(tableDate); periodicals.add(factory.createPeriodical(itemID, title, publisher, date, volume, number)); } return periodicals; } catch (SQLException e) { e.printStackTrace(); return periodicals; } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
303ad09f-f856-4658-923e-d369d53f94dc
4
public boolean isLive() { if(x > Parameter.FRAME_WIDTH || x < 0 || y < 0 || y > Parameter.FRAME_HEIGHT) { bLive = false; sv.mls.remove(this); } return bLive; }
7ea7ba57-40e9-4b01-adde-3395d3137f39
5
public static boolean verifyCellContent(UIObject obj, int rowIndex, int columnIndex, String content){ boolean contentPresent = false; WebElement element = action(obj); List<WebElement> rows = element.findElements(By.tagName("tr")); for(int r=0;r<rows.size();r++){ if(r==rowIndex){ List<WebElement> columns = rows.get(r).findElements(By.tagName("td")); for(int c =0;c<columns.size();c++){ if(c==columnIndex){ WebElement column = columns.get(c); if(content.equalsIgnoreCase(column.getText())){ contentPresent = true; } } } } } return contentPresent; }
7fda4d8a-9b72-48ca-bcd5-7ba7cedc3198
8
private void readFile() { if (audioFileSpecified) { try { this.is = AudioSystem.getAudioInputStream(this.file); byte[] tmp = new byte[(int) this.duration * this.sampleSize]; this.is.read(tmp); this.is.close(); ByteArrayInputStream bis = new ByteArrayInputStream(tmp); // convert to floats this.sampleData = new float[(int) this.duration]; byte[] sampleWord = new byte[sampleSize]; for (int i = 0; i < this.duration; i++) { if (bis.read(sampleWord) == -1) { //this.finished = true; System.out.println("Ran out of samples to read"); } else { sampleData[i] = this.getFloat(sampleWord); } } bis.close(); } catch (UnsupportedAudioFileException uafe) { //?? } catch (IOException ioe) { ioe.printStackTrace(); } } else { // read any file as raw byte=sample data Vector buffer = new Vector(); try { FileInputStream fis = new FileInputStream(this.fileName); int val = fis.read(); while (val != -1) { buffer.addElement(new Float((float) val / 255f)); val = fis.read(); } fis.close(); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(1); } // convert to float array int max = buffer.size(); this.sampleData = new float[max]; for (int i = 0; i < max; i++) { sampleData[i] = (((Float) buffer.elementAt(i)).floatValue()); } } }
c0c4c71e-dbe8-4415-a4c9-c19f20f4b590
0
public double getPrecio() { return precio; }
65967417-005a-4820-b115-7328b25bd99f
8
public static Class[] getClassesIn(String _package, boolean recursive) throws URISyntaxException, ClassNotFoundException { List<Class> classes = new Vector<>(); String s = (_package.replace('.', '/')); if (!s.startsWith("/")) s = "/" + s; if (!s.endsWith("/")) s += "/"; URL res = LocalClassLoader.class.getResource(s); if (res.getFile().contains("jar!/")) { getClassesInJar(classes, res, s); } else { File dir = new File(res.toURI()); File[] files = dir.listFiles(); if (files != null) { for (File f : files) { if (f.isFile()) { if (f.getName().endsWith(".class")) { classes.add(Class.forName(_package + '.' + f.getName().split(".class")[0])); } } else if (recursive) { Collections.addAll(classes, getClassesIn(_package + '.' + f.getName(), true)); } } } } return classes.toArray(new Class[classes.size()]); }
b31ab29b-6da1-4daf-9de7-1bbf58196d08
6
private synchronized void checkCompleted(){ for(int i = 0; i < this.blockOffsets.length; i++){ if(!blocks.containsKey(this.blockOffsets[i])){ return; } } if(this.isValid()){ this.completed = true; this.data = new byte[this.length]; for(int key : this.blocks.keySet()){ Block b = this.blocks.get(key); int offset = b.getOffset(); byte[] bdata = b.getData(); for(int j = 0; j < bdata.length && offset + j < this.length; j++ ){ this.data[offset + j] = bdata[j]; } } }else this.blocks = new HashMap<Integer, Block>(); }
9d74c018-213a-469e-bb9a-5cda345f313b
4
public static byte[] decodeImage(BufferedImage img) { //convert image to byte array byte[] bImg = getBytes(img); //offset definieren voor later int offset = 32; //retrieve lengths from the first bytes. 0-> 31 bits int length = 0; for (int i = 0; i < offset; i++) { //de lengte byte doorschuiven naar links en de laatste bit van de image byte op de eerste plaats zetten dmv OR // //0000 0000 0000 0000 0000 0000 0000 0000 //0000 0000 0000 0000 0000 0000 0000 0000 = doorschuiven naar links // // [0001 0011 = image byte i] // [0000 0001 ] // --------- & = AND // 0000 0001 = laatste bit // //--------------------------------------- | = OR tussen doogeschoven lengte en laatste bit //0000 0000 0000 0000 0000 0000 0000 0001 length = (length << 1) | bImg[i] & 1; } //byte array aanmaken voor de tekst nu we de lengte weten byte[] bMsg = new byte[length]; //elke byte van de tekst loopen om de laatste bits op de halen van de tekst for (int i = 0; i < bMsg.length; i++) { //8 keer de laatste bit ophalen van de byte van de foto om zo de tekst byte op te bouwen for (int bit = 0; bit < 8; ++bit, ++offset) { //zelfde principe als de lengte bMsg[i] = (byte) ((bMsg[i] << 1) | (bImg[offset] & 1)); } if (DEBUG) { ConsoleHelper.append("\t" + "value byte " + i + ": " + Integer.toBinaryString(bMsg[i])); } } //converteer message byte array naar string return bMsg; }
fca08d6e-837f-4359-abbb-63cc6e6d9c95
3
@EventHandler(priority = EventPriority.NORMAL) public void onBlockBreak(BlockBreakEvent event) { if (event.getPlayer() != null) { if (!event.getPlayer().isOp() && event.getBlock().getType() != Material.LEAVES) { event.setCancelled(true); } } }
6578105b-c933-450b-8dd4-60a0d6355f93
5
public void switcher(){ switch(scene){ case 0: scene++; break; case 1: scene++; break; case 2: scene++; break; case 3: scene++; break; case 4: gsm.setState(GameStateManager.LEVEL1STATE); } }
0a13b591-0d12-48c2-bd2f-0248682845fd
7
public static void main(String args[]) throws Exception { List<Module> list = new ArrayList<Module>(); Module m1 = new Module(1); Module m2 = new Module(1); Module m5 = new Module(2); Module m3 = new Module(1); Module m4 = new Module(2); Module m6 = new Module(3); list.add(m1); list.add(m2); list.add(m3); list.add(m4); list.add(m5); list.add(m6); Collections.sort(list, new ModuleComparator()); int count = 0; Domain domain = null; Module lastM = null; List<Domain> domains = new ArrayList<Domain>(); for (int i = 0; i < list.size(); i++) { if (i == 0) { domain = new Domain(); domains.add(domain); lastM = list.get(i); if (count == 0) { domain.setModule1(list.get(i)); count++; } } else { Module thisM = list.get(i); if (lastM != null) { if (thisM.getId() == lastM.getId()) { if (count == 0) { domain = new Domain(); domain.setModule1(thisM); domains.add(domain); count++; } else if (count == 1) { domain.setModule2(thisM); count++; } else { domain.setModule3(thisM); count = 0; } } else { count = 1; domain = new Domain(); lastM = thisM; domain.setModule1(thisM); domains.add(domain); } } } } System.out.println("a"); }
a66f5dbb-e7be-47c7-b359-3e60e99955b9
8
@Override public void setTimelineEvent(){ KeyFrame kf = new KeyFrame(Duration.millis(10), new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent){ time+=1; switch(switchInt){ case 1: if(Double.parseDouble(df_2. format(line_pendulum.getStartX())) == 500){ switchInt = 2; break; } line_pendulum.setStartY(line_pendulum.getStartY()+1); line_pendulum.setStartX(pivotX + Math.sqrt(Math.pow(currentLength,2) - Math.pow(stringY,2))); break; case 2: if(line_pendulum.getStartY() == highestY){ switchInt = 3; break; } line_pendulum.setStartY(line_pendulum.getStartY()-1); line_pendulum.setStartX(pivotX - Math.sqrt(Math.pow(currentLength,2) - Math.pow(stringY,2))); break; case 3: if(line_pendulum.getStartX() == 500){ switchInt = 4; break; } line_pendulum.setStartY(line_pendulum.getStartY()+1); line_pendulum.setStartX(pivotX - Math.sqrt(Math.pow(currentLength,2) - Math.pow(stringY,2))); break; case 4: if(line_pendulum.getStartY() == highestY){ switchInt = 1; break; } line_pendulum.setStartY(line_pendulum.getStartY()-1); line_pendulum.setStartX(pivotX + Math.sqrt(Math.pow(currentLength,2) - Math.pow(stringY,2))); break; } stringY = line_pendulum.getStartY()-pivotY; circle_pendulum.setCenterX(line_pendulum.getStartX()); circle_pendulum.setCenterY(line_pendulum.getStartY()); potentialE = (zeroPosition-line_pendulum.getStartY()) *(mass/1000)*ACCELERATION; kinecticE = mechanicalE - potentialE; graphK.addDataToSeries(time, kinecticE, 1); graphP.addDataToSeries(time, potentialE, 1); } }); pendulumAnimationTimeline.setCycleCount(Timeline.INDEFINITE); pendulumAnimationTimeline.getKeyFrames().add(kf); }
06f1a21d-e4cd-4981-bcfd-037236e09adf
9
public void render(Screen screen) { if (getDir() == 0) sprite = Sprite.spider_up; if (getDir() == 1) sprite = Sprite.spider_right; if (getDir() == 2) sprite = Sprite.spider_down; if (getDir() == 3) sprite = Sprite.spider_left; if (dead) sprite = Sprite.spider_dead; screen.renderItem(x - 16, y - 16, sprite); if (hit) { screen.renderBar(xL - Screen.xOffset, yT - 4 - Screen.yOffset, getHealthPercent(32), LargeSprite.floatingHealth); } if (Player.target == this) { screen.renderAbsolute((screen.width / 2) - 62, 5, Sprite.spider_head); screen.renderBar((screen.width / 2) - 46, 13, 97.0, LargeSprite.back); screen.renderBar((screen.width / 2) - 46, 14, getHealthPercent(100), LargeSprite.health); screen.renderAbsolute((screen.width / 2) - 64, 5, LargeSprite.enemy_health); } if (frozen && !dead) { screen.renderItem(x - 16, y - 16, Sprite.freeze); } }
d79361bc-9dd3-41d3-a039-6f05df58dfca
0
@Override public void setPhone(String phone) { super.setPhone(phone); }
45446e88-04a1-4d32-9938-36fada613849
4
@Override public ColorRGB shade(Raytracer tracer, HitInfo hit) { ColorRGB totalColor = ColorRGB.BLACK; for (Light light: hit.getWorld().getLights()) { Vector3 lightPos = light.Sample(); Vector3 inDirection = lightPos.minus(hit.getHitPoint()).normalized(); double diffuseFactor = inDirection.dot(hit.getNormal()); if (diffuseFactor < 0) { continue; } if (hit.getWorld().anyObstacleBetween(hit.getHitPoint(), lightPos)) { continue; } ColorRGB result = light.getColor().mult(materialColor).mult(diffuseFactor).mult(diffuseCoeff); double phongFactor = phongFactor(inDirection, hit.getNormal(), hit.getRay().getDirection().reverse()); if (phongFactor != 0) { result = result.plus(materialColor.mult(specular).mult(phongFactor)); } totalColor = totalColor.plus(result); } return totalColor; }