method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
43fc8f06-2d4a-411e-8c70-5b7e0365c372
2
@Override public void salvar(Cliente cliente) { try { conn = ConnectionFactory.getConnection(); String sql = "INSERT INTO cliente (id, nome, cpf) " + "VALUES ((SELECT NVL(MAX(id),0)+1 FROM cliente), ?, ?)"; ps = conn.prepareStatement(sql); ps.setString(1, cliente.getNome()); ps.setString(2, cliente.getCpf()); ps.executeUpdate(); } catch(SQLException e){ throw new RuntimeException("Erro " + e.getSQLState() + " ao atualizar objeto: " + e.getLocalizedMessage()); } catch (ClassNotFoundException e) { throw new RuntimeException("Erro ao conectar no banco: " + e.getMessage()); } finally { close(); } }
306752e0-134b-484c-82d7-79464d1b03ef
8
@Override public void run() { String recieve; while (running) { boolean isSended = this.clientVerbindung.send("INFO"); if (!isSended) { this.close(); continue; } recieve = this.clientVerbindung.recieve(); if (recieve == null || recieve.startsWith("ERROR") || recieve.startsWith("BYE")) { this.close(); } else { this.addHostToList(recieve); //Hier Kommunikation mit der GUI // Angepasst an GUI Abhaengigkeit // Nur ausgabe der Usernamen String user = ""; String[] splitted = recieve.substring(6).split(" "); for (int i = 1; i < splitted.length; i++) { if (i % 2 == 0) { user += splitted[i] + "\n"; } } this.guiView.setUsers(user); // System.out.println(recieve); try { Thread.sleep(5000); } catch (InterruptedException ex) { Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex); } } } }
623efc77-3a04-4cc4-ab9b-9a4e1b5e4d63
9
public Location getAdjacentLocation(int direction) { // reduce mod 360 and round to closest multiple of 45 int adjustedDirection = (direction + HALF_RIGHT / 2) % FULL_CIRCLE; if (adjustedDirection < 0) adjustedDirection += FULL_CIRCLE; adjustedDirection = (adjustedDirection / HALF_RIGHT) * HALF_RIGHT; int dc = 0; int dr = 0; if (adjustedDirection == EAST) dc = 1; else if (adjustedDirection == SOUTHEAST) { dc = 1; dr = 1; } else if (adjustedDirection == SOUTH) dr = 1; else if (adjustedDirection == SOUTHWEST) { dc = -1; dr = 1; } else if (adjustedDirection == WEST) dc = -1; else if (adjustedDirection == NORTHWEST) { dc = -1; dr = -1; } else if (adjustedDirection == NORTH) dr = -1; else if (adjustedDirection == NORTHEAST) { dc = 1; dr = -1; } return new Location(getRow() + dr, getCol() + dc); }
65a1366a-421e-4d58-92f7-1f5faa5ce186
7
@SuppressWarnings("unchecked") @Override public boolean put(final String key, final Object data, final String... indexes) throws DataException, InvalidKeyException, DataClassException { if (key == null) { throw new InvalidKeyException("Null is not a valid key."); } if (data == null) { throw new DataException("Null is not a valid object to store."); } ClassUtils.typeValidation(data); KeyedId keyedId = new KeyedId(data.getClass(), key); String[] idxes = indexes; if (indexes.length == 0) { idxes = getIndexes(data); } validateIndexes(idxes); KeyedObject ko; try { byte[] value = serialize(data); if (value == null || value.length == 0) { LOG.debug("No data -> failing"); throw new DataException("No data to store"); } if (data instanceof LargeData) { ko = new LargeKeyedObject(keyedId, value, idxes); } else { ko = new SmallKeyedObject(keyedId, value, idxes); } ko = dao.create(ko); } catch (IOException e) { throw new DataException("Failed to serialize data with error: " + e.getMessage(), e); } return ko != null; }
47fcaa58-c881-4c4c-a497-506163bd9086
3
private void parseReference(Component parentNode, String sectionName, int level) throws TemplateException { try { // look for section XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate("/grammar/define[@name='" + sectionName + "']", template.getXml(), XPathConstants.NODESET); for (int i = 0, len = nodeList.getLength(); i < len; i++) { Node currentNode = nodeList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { parseReportSectionLevel(parentNode, currentNode, level + 1); } } } catch (XPathExpressionException e) { throw new TemplateException("XPathExpressionException", e); } }
3b08e5c9-bdff-4f9f-8fce-146a4823e4d9
2
public void run() { while (true) { repaint(); JokemonDriver.manageTime(); frames++; framerateManager(); try { Thread.sleep(slp); } catch(Exception ignored){} } }
217502f0-d3de-4dd5-b59b-ff4446e26ee6
6
public boolean chargeForCity() { if (! resForCity()) return false; for (int i = 0; i < BRICK_CITY; i++) _hand.remove(Resource.Brick); for (int i = 0; i < ORE_CITY; i++) _hand.remove(Resource.Ore); for (int i = 0; i < SHEEP_CITY; i++) _hand.remove(Resource.Sheep); for (int i = 0; i < TIMBER_CITY; i++) _hand.remove(Resource.Timber); for (int i = 0; i < WHEAT_CITY; i++) _hand.remove(Resource.Wheat); return true; }
e571a928-85ff-4d1e-9bfe-bd7c1216fd17
4
@Override public String toString() { StringBuilder albumString = new StringBuilder(); Iterator<String> it = keywords.iterator(); Iterator<String> bandIterator = bandMembers.iterator(); albumString.append("-Music Album- \n").append("band: ").append(bandName).append('\n'); albumString.append("# songs: ").append(nSongs).append('\n'); albumString.append("members: "); while (bandIterator.hasNext()) { String s = bandIterator.next(); albumString.append(s); if (bandIterator.hasNext()) { albumString.append(','); } } albumString.append('\n'); albumString.append("title: ").append(title).append('\n'); albumString.append("keywords: "); while (it.hasNext()) { String s = it.next(); albumString.append(s); if (it.hasNext()) { albumString.append(','); } } albumString.append('\n'); albumString.append('\n'); return albumString.toString(); }
c832bc7d-ab92-419d-9ac0-510222aa0ce2
6
public static final long mul(long x, long y) { long moflo = (1L<<31); // multiply without overflow if operands < moflo if (x >= 0 && x < moflo && y >= 0 && y < moflo) return (x * y) % p; long res = 0; while (x != 0) { if ((x & 1) == 1) res = (res + y) % p; x >>= 1; y = (y << 1) % p; } return res; }
a11297ae-d0cf-489d-b630-0c15b25d8b34
8
private static int method524(char ac[]) { if(ac.length > 6) return 0; int k = 0; for(int l = 0; l < ac.length; l++) { char c = ac[ac.length - l - 1]; if(c >= 'a' && c <= 'z') k = k * 38 + ((c - 97) + 1); else if(c == '\'') k = k * 38 + 27; else if(c >= '0' && c <= '9') k = k * 38 + ((c - 48) + 28); else if(c != 0) return 0; } return k; }
cc4e52be-e646-464a-92d3-17558e3968b4
8
public static List<String> unban(String playerName) { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps; int done = 0; int accountid = 0; List<String> ret = new LinkedList<String>(); try { ps = con.prepareStatement("SELECT accountid FROM characters WHERE name = ?"); ps.setString(1, playerName); ResultSet rs = ps.executeQuery(); if (!rs.next()) { ps.close(); ret.add("There are two many of these characters or the Character does not exist."); } accountid = rs.getInt("accountid"); ret.add("[Account ID Exists] Initating Unban Request"); done = 0; ps.close(); } catch (SQLException e) { ret.add("Account ID or Character fails to exist. Error : " + e); } try { ps = con.prepareStatement("update accounts set greason = null, banned = 0, banreason = null, tempban = '0000-00-00 00:00:00' where id = ? and tempban <> '0000-00-00 00:00:00'"); ps.setInt(1, accountid); int results = ps.executeUpdate(); if (results > 0) { ret.add("[Untempbanned] Account has been untempbanned. Command execution is over. If still banned, repeat command."); done = 1; } ps.close(); } catch (SQLException e) { // not a tempba, moved on. } if (done != 1) { try { ps = con.prepareStatement("UPDATE accounts SET banned = -1, banreason = null WHERE id = " + accountid); ps.executeUpdate(); ps.close(); done = 1; ret.add("[Account Unbanned] ID: " + accountid); ret.add("Macs and Ips will be unbanned when the person logs in"); } catch (SQLException e) { ret.add("Account failed to be unbanned or banreason is unfound. Error : " + e); } } if (done == 1) { ret.add("Unban command has been completed successfully."); } else if (done == 0) { ret.add("The unban has epic failed."); } return ret; }
4e5e9077-48e4-47fb-9d71-8e5acda3a9d1
2
public static String checkLevels(double level) { String message = ""; if (level < 0.0) { message = " below acceptable range."; } if (level > 1.0) { message = " above acceptable range."; } return message; }
97fde14d-8fc8-46a9-a569-8796d0eae095
6
public XMLNode(String XMLText) { // Figure out where the next tag begins and ends: int lBracket = XMLText.indexOf("<"); int rBracket = XMLText.indexOf(">"); // If we reached the end of the file, we are done: if (lBracket == -1 || rBracket == -1) return; // Sanity check: Is this really XML we're looking at?) if (rBracket <= lBracket) { errorMessage("Invalid XML syntax: '>' before '<'"); return; } // Create a hash map for the parameters: parameters = new HashMap<String, String>(); // Process everything inside this tag: contents = XMLText.substring(lBracket + 1, rBracket); processTagContents(contents); if (verbose) displayParameters(); // Check if there is more after this tag: if (rBracket + 1 >= XMLText.length()) return; String XMLRemainder = XMLText.substring(rBracket + 1); // If there are no more tags, we are done: lBracket = XMLRemainder.indexOf("<"); if (lBracket == -1) return; // Create the next node: next = new XMLNode(XMLRemainder.substring(lBracket)); }
bf64d61a-a5fd-47f4-b86b-ea5e1429be20
0
public void onComplete(){ updateButton.setEnabled(true); delMinecraft.setEnabled(true); serverBox.setEnabled(true); txtrn.setText("готово"); }
1312b169-b9aa-4594-b44b-549c09bad543
1
@Override public InputStream openInputStream() throws IOException { if (outputStream != null) { return new ByteArrayInputStream(outputStream.toByteArray()); } else { return new ByteArrayInputStream(new byte[0]); } }
c3933f05-245d-4111-aa27-db5342a2c977
9
private void getfields() { fcount = 0; for(int k=0;;) { k+=32; try { fdbf.seek(k); } catch (IOException e) {} String fn = readChars(0,1); if(fn.charAt(0)==0xd) break; fn+=readChars(0,10); field y = new field(); y.fname = fn.replace((char)0,' ').trim(); char f = readChars(0,1).charAt(0); y.ftype = f; validateFieldType(f); if(f=='M' || f=='G') fpt_file = true; y.fpos = readNumber(0,4); y.fsize = (int) readNumber(0,1); if(f=='B' || f=='Y') y.fsize = 30; // just increase enough to see if(f=='T') y.fsize = 22; y.fsize_dec = (int) readNumber(0,1); if(f=='Y') y.fsize_dec = currency_dec; y.binflag = (readNumber(0,1) == 4); Field[ fcount++ ] = y; } }
5269e4eb-bf93-4f83-ae26-1024e4dfa20b
2
@Override protected Integer doInBackground() throws Exception { while(true){ jLabel1.setText(ChatBox.receiverStatus); if (jLabel1.getText().equals("DAFUQ")) { break; } } return 666; }
19800750-d6cb-473b-9ade-aa92b0d793d4
2
@Test public void passed() { for(int i=1;i<10;i++){ TestResult result = tester.test(StringGenerator.genString(i), 0,i); if(!result.passed){ System.err.println(result.message); } Assert.assertTrue(result.passed); } }
456b8614-ea73-478f-b9e3-90ad80f23e1e
3
public static Class<?> getReturnGenericType(Method method) { Type genericType = method.getGenericReturnType(); Class<?>[] classes = getActualClass(genericType); if (classes.length == 0) { return null; } else { return classes[0]; } }
0a3262b6-5d33-4a64-bdc9-e48059560927
3
static boolean isAllowed(final CommandSender sender, final String permission, final String targetName) { // Always allowed for self if (sender.getName().equalsIgnoreCase(targetName)) return true; // Check if sender is allowed for all players if (sender.hasPermission(permission + ".player.*")) return true; // Check if sender is allowed for specific player if (sender.hasPermission(permission + ".player." + targetName)) return true; return false; }
e3257cab-82e0-4493-b0e3-7401eb3a5b35
0
public void setCurconnected(int curconnected) { this.curconnected = curconnected; }
98b19424-b4d1-4497-916c-04d3c6e10a36
7
private void unzip(String file) { final File fSourceZip = new File(file); try { final String zipPath = file.substring(0, file.length() - 4); ZipFile zipFile = new ZipFile(fSourceZip); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName()); this.fileIOOrError(destinationFilePath.getParentFile(), destinationFilePath.getParentFile().mkdirs(), true); if (!entry.isDirectory()) { final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; final byte[] buffer = new byte[Updater.BYTE_SIZE]; final FileOutputStream fos = new FileOutputStream(destinationFilePath); final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE); while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) { bos.write(buffer, 0, b); } bos.flush(); bos.close(); bis.close(); final String name = destinationFilePath.getName(); if (name.endsWith(".jar") && this.pluginExists(name)) { File output = new File(this.updateFolder, name); this.fileIOOrError(output, destinationFilePath.renameTo(output), true); } } } zipFile.close(); // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. moveNewZipFiles(zipPath); } catch (final IOException e) { this.plugin.getLogger().log(Level.SEVERE, "The auto-updater tried to unzip a new update file, but was unsuccessful.", e); this.result = Updater.UpdateResult.FAIL_DOWNLOAD; } finally { this.fileIOOrError(fSourceZip, fSourceZip.delete(), false); } }
742a9cf2-ac11-4e51-bd92-c7aaef15bfa5
3
protected synchronized boolean insertPacketIntoQueue(Packet pnp) { int srcID = pnp.getSrcID(); // source entity id int destID = pnp.getDestID(); // destination entity id int type = pnp.getNetServiceType(); // packet service type Double nextTime = (Double) flowTable.get("" + srcID + destID + type); if (nextTime == null) { nextTime = new Double(CF); flowTable.put("" + srcID + destID + type, nextTime); } double pktTime = calculateFinishTime(pnp, nextTime.doubleValue()); flowTable.put("" + srcID + destID + type, new Double(pktTime)); insert(pnp, pktTime); // Sort the queue list // Keep an statistic regarding the size of the buffers. int bufferSize = this.size(); if (storeStats) { if (bufferSize > maxBufferSize) { maxBufferSize = bufferSize; fw_write(GridSim.clock() + ", " + bufferSize + ", " + getAvg() + ", " + maxBufferSize + "\n", this.getSchedName() + "_MaxBufferSize.csv"); } } return true; }
e6628428-4590-4573-8999-175c5a256988
0
public void configure(Binder binder) { // Singleton Implementations binder.bind(ValidatorJNotifyListener.class).asEagerSingleton(); binder.bind(Watchers.class).asEagerSingleton(); binder.bind(JNotifier.class).asEagerSingleton(); binder.bind(XmlManager.class).asEagerSingleton(); // Interface Implementations binder.bind(Notifier.class).to(JNotifier.class); binder.bind(FileOperationMask.class).to(JNotifierFileOperationMask.class); }
ffc2c51b-0117-4969-9dcc-7631af96bd7a
9
private void checkRobots(){ MyRobot tempMyRobot = null; synchronized(robots){ for(MyRobot r:robots){ if (r.robotState == RobotState.idle && !r.broken){ tempMyRobot = r; break; } } } if (tempMyRobot == null || (glassProcessing != 0)){ if (popUpStatus == PopUpStatus.notRaised){ Integer[] args = new Integer[1]; args[0] = conveyorFamilyID; popUpStatus = PopUpStatus.moving; transducer.fireEvent(TChannel.POPUP, TEvent.POPUP_DO_MOVE_UP, args); try { popUpMovingHold.acquire(); }catch(Exception e){ //print("Unexpected exception caught in "+this.toString()); } } } else{ if (popUpStatus == PopUpStatus.raised){ Integer[] args = new Integer[1]; args[0] = conveyorFamilyID; popUpStatus = PopUpStatus.moving; transducer.fireEvent(TChannel.POPUP, TEvent.POPUP_DO_MOVE_DOWN, args); try { popUpMovingHold.acquire(); }catch(Exception e){ //print("Unexpected exception caught in "+this.toString()); } } } checkIfRobotsWorking = false; stateChanged(); }
ba44f81e-6829-45f5-9791-e558bdd68b3b
5
public boolean utrFromCds(boolean verbose) { if (cdss.size() <= 0) return false; // Cannot do this if we don't have CDS information // All exons minus all UTRs and CDS should give us the missing UTRs Markers exons = new Markers(); Markers minus = new Markers(); // Add all exons for (Exon e : this) exons.add(e); // Add all UTRs and CDSs to the 'minus' set for (Utr uint : getUtrs()) minus.add(uint); for (Cds cint : cdss) minus.add(cint); Markers missingUtrs = exons.minus(minus); // Perform interval minus if (missingUtrs.size() > 0) return addMissingUtrs(missingUtrs, verbose); // Anything left? => There was a missing UTR return false; }
23307b40-c941-4d2f-80d2-b22fe2532c7c
6
public void reserveOneWayTicket() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Where is your MySQL JDBC Driver?"); e.printStackTrace(); } PreparedStatement ps = null; Connection con = null; ResultSet rs; try { con = DriverManager.getConnection("jdbc:mysql://mysql2.cs.stonybrook.edu:3306/mlavina", "mlavina", "108262940"); if (con != null) { con.setAutoCommit(false); String sql = "SELECT max(ResrNo) FROM reservation;"; ps = con.prepareStatement(sql); try { ps.execute(); rs = ps.getResultSet(); int resrNo = -1; if (rs.next()) { resrNo = rs.getInt(1) + 1; } sql = "Insert into passenger (Id, AccountNo) values (?,?) ON DUPLICATE KEY UPDATE Id=Id;"; ps = con.prepareStatement(sql); ps.setInt(1, personID); ps.setInt(2, accountNo); ps.execute(); sql = "INSERT INTO Reservation VALUES (?, ?, ?, ?, ?,?); "; ps = con.prepareStatement(sql); ps.setInt(1, resrNo); ps.setTimestamp(2, new java.sql.Timestamp(new Date().getTime())); ps.setDouble(3, (selectedFlight.fare * .10)); ps.setDouble(4, selectedFlight.fare); ps.setInt(5, employeeSSN); ps.setInt(6, accountNo); ps.execute(); sql = "INSERT INTO Includes VALUES (?, ?, ?, ?, ?);"; ps = con.prepareStatement(sql); ps.setInt(1, resrNo); ps.setString(2, selectedFlight.airlineID); ps.setInt(3, selectedFlight.flightNo); ps.setInt(4, selectedFlight.legNo); ps.setDate(5, new java.sql.Date(selectedFlight.deptTime.getTime())); ps.execute(); sql = "INSERT INTO ReservationPassenger VALUES(?, ?, ?, ?, ?, ?);"; ps = con.prepareStatement(sql); ps.setInt(1, resrNo); ps.setInt(2, personID); ps.setInt(3, accountNo); ps.setString(4, ("" + seatNo)); ps.setString(5, selectedFlight.seatClass); ps.setString(6, mealPreference); ps.execute(); con.commit(); } catch (Exception e) { con.rollback(); } } } catch (Exception e) { System.out.println(e); } finally { try { con.setAutoCommit(true); con.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } }
6751a290-abfa-482d-8c5d-1be3155705f0
7
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component returnValue = null; if ((value != null) && (value instanceof DefaultMutableTreeNode)) { Object userObject = ((DefaultMutableTreeNode) value).getUserObject(); if (userObject instanceof Actions) { Actions action = (Actions) userObject; label.setText(action.getDescription()); if (selected) { renderer.setBackground(backgroundSelectionColor); } else { renderer.setBackground(backgroundNonSelectionColor); } if (action.getClass().equals(StartAction.class)) { label.setForeground(Color.RED); } else if (action.getClass().equals(CheckColour.class)) { label.setForeground(Color.BLUE); } else { label.setForeground(Color.BLACK); } renderer.setEnabled(tree.isEnabled()); returnValue = renderer; } } if (returnValue == null) { returnValue = defaultRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); } return returnValue; }
099ba749-51e7-4818-af5e-ded84820b8f0
2
@Override public List<String> callUserServices(String username) { List<String> services = null; System.out.println("[WSClient][callUserServices] Username is "+username); try { Service service = new Service(); Call call = (Call)service.createCall(); QName string = new QName("http://echo.demo.oracle/", "string"); Object[] inParams = {username}; call.setTargetEndpointAddress(new URL(SERVICES_URL)); call.setOperationName(new QName(USER_SERVICES)); call.addParameter("username", string, String.class, ParameterMode.IN); call.setReturnClass(String[].class); System.out.println("Call object is "+call+", in params are "+inParams); Object result = call.invoke(inParams); if (result == null) return null; services = Arrays.asList((String[]) result); } catch (Exception e) { e.printStackTrace(); } return services; }
4f91cdc6-b899-45d9-b011-fe37667c2772
5
public static void menuRemoveVisit(HousePetList hpArray) { int userChipID = 0; HousePet tempHousePet = new HousePet(); /* new HP created with default chipID */ @SuppressWarnings("resource") Scanner console = new Scanner(System.in); boolean containsHousePet = false; String visitID = ""; String visitDate = ""; boolean hasBeenRemoved = false; /* prompt for chipID */ System.out.println("Please enter the chipID of the HousePet you would like to " + "cancel a visit for."); try { userChipID = console.nextInt(); tempHousePet.setChipId(userChipID); } catch(InputMismatchException e) { System.out.println("Error: a non-int was entered " + e); } catch(NoSuchElementException e) { System.out.println("Error: no console input found " + e); } catch(IllegalStateException e) { System.out.println("Error: Scanner is closed " + e); } /* check if hpArray contains a HousePet with chipID matching that of tempHousePet */ containsHousePet = hpArray.contains(tempHousePet); /* if HousePet with matching chipID not found in hpArray, display msg to user; * otherwise, display the HousePet's data so user can more easily decide which * visit they want to remove, then ask them for visitID and date for the visit * they want removed from visitList for that HousePet */ if(containsHousePet == false) { System.out.println("Invalid chipID entered: no HousePet with chipID " + userChipID + " in the list"); }//end IF(containsHousePet == false) else //if(containsHousePet == true) { VetVisit visitToRemove = new VetVisitStandard(); //just assigning a type /* prompt user to specify which visit theyd like removed from the visitList */ System.out.println("All attributes for the HousePet with chipID " + tempHousePet.getChipId() + " are shown below."); ((HousePetListImpl) hpArray).displayHousePet(tempHousePet); System.out.print("Please enter the visitID for the visit you wish to cancel: "); visitID = console.next(); console.nextLine(); System.out.print("Please enter the date for the visit you wish to cancel: "); visitDate = console.next(); console.nextLine(); System.out.println(); visitToRemove.setVisitID(visitID); visitToRemove.setDate(visitDate); /* try to remove the VetVisit from HousePet's visitList; callee method will * see to it that visitCount is decremented if removal successful, and that * the info for the removed visit is written to to cancellations file * 'cancel.txt' */ hasBeenRemoved = hpArray.removeVetVisit(tempHousePet.getChipId(), visitToRemove); }//end ELSE(IF(containsHousePet == true)) /* determine message to display to user depending on whether visit has been * removed from visitList */ if(hasBeenRemoved == true) //hasBeenRemoved still false if HP not found in list { System.out.println("The visit has been added to the cancellations file " + "\"cancel.txt\". The modified HousePet data is shown below."); ((HousePetListImpl) hpArray).displayHousePet(tempHousePet); } else //if(hasBeenRemoved == false) { System.out.println("Unable to remove VetVisit."); } return; }//end menuRemoveVisit()
4cc8efde-6a3c-4fec-a809-fcfcc8bdb73a
1
public void visitLocalVariable( final String name, final String desc, final String signature, final Label start, final Label end, final int index) { AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute("", "name", "name", "", name); attrs.addAttribute("", "desc", "desc", "", desc); if (signature != null) { attrs.addAttribute("", "signature", "signature", "", SAXClassAdapter.encode(signature)); } attrs.addAttribute("", "start", "start", "", getLabel(start)); attrs.addAttribute("", "end", "end", "", getLabel(end)); attrs.addAttribute("", "var", "var", "", Integer.toString(index)); addElement("LocalVar", attrs); }
dcdb2dbe-2023-4b72-84ad-2e09400be545
5
public static void unwrap(Message message, CoreMessageListener coreMessageListener) { if (!(message instanceof ObjectMessage)) return; Object messagePayload = null; try { messagePayload = ((ObjectMessage) message).getObject(); } catch (JMSException e) { e.printStackTrace(); } if (!(messagePayload instanceof CoreMessage)) return; final CoreMessage coreMessage = (CoreMessage) messagePayload; switch (coreMessage.getType()) { case GetRoomRequest: coreMessageListener.onGetRoomRequest((GetRoomRequest) coreMessage); break; case GetRoomReply: coreMessageListener.onGetRoomReply((GetRoomReply) coreMessage); break; default: break; } }
b2f22bb3-139a-442a-b879-dbcf1ef99db9
1
public void setPeuplesPris(List<Class<? extends Peuple>> peuplesPris) { this.peuplesPris = peuplesPris; }
2c969b2e-079f-4ae6-81c5-02a757eb9792
0
public GUIManager(PermWriter project) { this.project = project; }
5149676b-6551-401e-b925-971ff531d7bf
1
public void doCSVPerformanceTest() { try { final String mapping = ConsoleMenu.getString("CSV File ", "SampleCSV.csv"); final boolean data = ConsoleMenu.getBoolean("Traverse the entire parsed file", true); final boolean verbose = ConsoleMenu.getBoolean("Verbose", false); CSVPerformanceTest.call(mapping, verbose, data); } catch (final Exception e) { e.printStackTrace(); } }
f2f8ed27-b933-4bc7-beb1-4084f2845b27
5
static final void method1301(r var_r, int i, int i_0_, int i_1_, boolean[] bools) { if (aa_Sub1.aSArray5191 != Class332.aSArray4142) { int i_2_ = Class348_Sub1_Sub1.aSArray8801[i].method3986(i_0_, i_1_, (byte) -93); for (int i_3_ = 0; i_3_ <= i; i_3_++) { if (bools == null || bools[i_3_]) { s var_s = Class348_Sub1_Sub1.aSArray8801[i_3_]; if (var_s != null) var_s.wa(var_r, i_0_, i_2_ - var_s.method3986(i_0_, i_1_, (byte) -103), i_1_, 0, false); } } } }
ce2c0e7d-5be1-4494-9292-505c631bb0f2
9
@SuppressWarnings("unchecked") private void listen() throws InterruptedException { WatchKey watchKey = watcher.poll(5L, TimeUnit.SECONDS); if (stop || watchKey == null) { return; } for (WatchEvent<?> event : watchKey.pollEvents()) { if (stop || event.kind() == OVERFLOW) { continue; } File file = new File(cacheDir, ((WatchEvent<Path>)event).context().toFile().getName()); if (event.kind() == ENTRY_CREATE) { if (file.getName().endsWith(WritePageFactory.PAGEFILE_POSTFIX)) { register(new ReadPage(file)); } continue; } } // reset the key boolean valid = watchKey.reset(); if (!valid) { throw new CacheException("watch key became invalid"); } }
8b3345a1-9397-4dd6-841a-24e6a937a4ca
1
@Override public Boolean getBooleanProp(String key, Boolean value){ Boolean result = value; String propValue = getProperty(key); if (null != propValue){ result = new Boolean(propValue); } return result; }
4863e4a8-c9de-4cd2-b9de-2db733c25792
9
public static void handle ( String input, JTextPane console ) { GUI.commandHistory.add ( input ) ; GUI.commandHistoryLocation = GUI.commandHistory.size ( ) ; GUI.write ( "Processing... [ " + console.getText ( ).replaceAll ( "\r", "" ).replaceAll ( "\n", "" ) + " ]" ) ; console.setText ( "" ) ; input = input.replaceAll ( "\r", "" ).replaceAll ( "\n", "" ) ; try { if ( input.equalsIgnoreCase ( "quit" ) || input.equalsIgnoreCase ( "exit" ) || input.equalsIgnoreCase ( "close" ) ) { Core.fileLogger.flush ( ) ; System.exit ( 0 ) ; } else { final String inp[] = input.split ( "(\\s)+" ) ; if ( inp.length == 0 ) { return ; } final Class<?> cmdClass = Class.forName ( "net.mokon.scrabble.cmd.CMD_" + inp[ 0 ].toLowerCase ( ) ) ; final Constructor<?> cmdConstructor = cmdClass .getDeclaredConstructors ( )[ 0 ] ; final Command toRun = (Command) cmdConstructor.newInstance ( inp, console, Core.scrabbleBoard, Core.main, Core.moves, Core.scrabbleBoard.bag ) ; if ( inp[ 0 ].equalsIgnoreCase ( "word" ) ) { final Method method = cmdClass.getMethod ( "setFrame", JFrame.class ) ; method.invoke ( toRun, Core.showWorkingScreen ( ) ) ; } toRun.start ( ) ; } } catch ( final ClassNotFoundException e ) { GUI.write ( "Unknown Command - Valid are [ help, word, use, draw," + " place, set, unset, grid, size, fill, lookup ]" ) ; } catch ( final Throwable e ) { GUI.write ( "An error has been enountered [ " + e.toString ( ) + " ]. Attempting to continue..." ) ; e.printStackTrace ( ) ; e.printStackTrace ( Core.fileLogger ) ; } }
25143e4a-4ea1-45f3-b47a-330257e16a2f
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Node<?> other = (Node<?>) obj; if (data == null) { if (other.data != null) return false; } else if (!data.equals(other.data)) return false; return true; }
265366e2-2709-426a-af9d-a7aaee54b3cd
5
public CheckResultMessage check10(int day) { int r = get(27, 5); int c = get(28, 5); BigDecimal b = new BigDecimal(0); if (checkVersion(file).equals("2003")) { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); b = getValue(r + 3 + day, c, 6).add( getValue(r + 3 + day, c + 1, 6)).subtract( getValue(r + 3 + day, c + 2, 6)); if (0 != getValue(r + 3 + day, c + 3, 6).compareTo(b)) { return error("支付机构汇总报表<" + fileName + ">变动额核对H:" + day + "日错误"); } } catch (Exception e) { } } else { try { in = new FileInputStream(file); xWorkbook = new XSSFWorkbook(in); b = getValue1(r + 3 + day, c, 6).add( getValue1(r + 3 + day, c + 1, 6)).subtract( getValue1(r + 3 + day, c + 2, 6)); if (0 != getValue1(r + 3 + day, c + 3, 6).compareTo(b)) { return error("支付机构汇总报表<" + fileName + ">变动额核对H:" + day + "日错误"); } } catch (Exception e) { } } return pass("支付机构汇总报表<" + fileName + ">变动额核对H:" + day + "日正确"); }
e73af62a-daac-4c3e-86dc-49f2615afecd
8
public void eliminarGrafico( Figura figura ){ if ( figura!=null ){ if ( figura instanceof ClaseGrafica ){ Figura graf ; if ( listaFigura!=null ){ LinkedList<Figura> listaEliminar = new LinkedList<Figura>(); for (int i=0; i<listaFigura.size() ; i++ ) { graf = listaFigura.get(i); if ( graf instanceof RelacionGrafica ){ RelacionGrafica r = (RelacionGrafica)graf; String nrA=r.getRelacion().getClaseOrigen().getNombre(); String nrB=r.getRelacion().getClaseDestino().getNombre(); String ncg=( (ClaseGrafica)figura ).getNombre(); if ( nrA.equals( ncg )|| nrB.equals( ncg ) ) listaEliminar.add(r); } } for ( int i=0 ; i<listaEliminar.size() ; i++ ) { listaEliminar.get(i).borrar(); listaFigura.remove(listaEliminar.get(i)); } } } figura.borrar(); listaFigura.remove( figura ); repaint(); } }
6ed3e04d-b7a2-48c1-9da3-73b4a4e355e6
6
private String map(int depth50m, int depth10m, int depth1m) throws NodeMeaningKeyErrorException { if (depth50m < min50m || depth50m > max50m) { throw new NodeMeaningKeyErrorException(); } if (depth10m < min10m || depth10m > max10m) { throw new NodeMeaningKeyErrorException(); } if (depth1m < min1m || depth1m > max1m) { throw new NodeMeaningKeyErrorException(); } depth50m -= min50m; depth10m -= min10m; depth1m -= min1m; int depth10mLength = max10m - min10m + 1; int depth1mLength = max1m - min1m + 1; int value = depth50m * depth10mLength * depth1mLength + depth10m * depth1mLength + depth1m; return String.valueOf(value); }
c1cd4178-e35d-4e52-a126-7967a6d90b84
0
public int GetAveragePersonsWaitTime() { return averagePersonsWaitTime; }
b4d13fab-c160-4595-bd35-528455f2b69c
2
public synchronized boolean frameCorrection() { // Copy frame information form CDSs to Exons (if missing) frameFromCds(); // First exon is corrected by adding a fake 5'UTR boolean changedFirst = frameCorrectionFirstCodingExon(); // Other exons are corrected by changing the start (or end) coordinates. // boolean changedNonFirst = false; // Gpr.debug("UNCOMMENT!"); boolean changedNonFirst = frameCorrectionNonFirstCodingExon(); boolean changed = changedFirst || changedNonFirst; // We have to reset cached CDS data if anything changed if (changed) resetCdsCache(); // Return true if there was any adjustment return changed; }
f93d683c-cae3-4c4b-a6a6-8c80a259080b
6
public void add( ChunkState state ) { if ( !containsState(state) ) { if ( states == null ) states = new ChunkState[1]; else if ( containsState(ChunkState.none) ) { for ( int i=0;i<states.length;i++ ) { if ( states[i] == ChunkState.none ) { states[i] = state; break; } } } else { // expand ChunkState[] newStates = new ChunkState[states.length+1]; for ( int i=0;i<states.length;i++ ) newStates[i] = states[i]; states = newStates; } states[states.length-1] = state; } }
f132d6aa-a337-4b2d-91ec-93d55fa97b2c
0
public String getChannel(){ return Channel; }
e63a010d-3f43-48bd-bb09-46f8b24608cc
7
public void processOrder(OrderTransaction orderTransaction) throws PointOfSaleSystemException { orderTransaction.setCashier(cashier); Transaction transaction = daoFactory.createTransaction(orderTransactionManager, inventoryDAO, creditManager, feeDAO); try { transaction.start(); feeDAO.saveBillingFees(orderTransaction.getStudent(), orderTransaction.getOrder()); orderTransaction = orderTransactionManager.save(orderTransaction); for (OrderItem orderItem : orderTransaction.getOrder().getOrderItems()) { inventoryDAO.deleteItemFromInventory(orderItem.getDBID()); } hotbarDAO.updateHotbar(orderTransaction.getOrder().getOrderItems(), cashier); if (orderTransaction.getCredit().compareTo(BigDecimal.ZERO) > 0) { // must update student credit information creditManager.saveCreditTransaction(orderTransaction); } transaction.commit(); } catch (TransactionManagerException ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); rollBack(transaction); throw new PointOfSaleSystemException("Error occured during Writting of Transaction Master Record.", ex); } catch (CreditManagerException e) { logger.log(Level.SEVERE, e.getMessage(), e); rollBack(transaction); throw new PointOfSaleSystemException("Error cccured during saving credit record", e); } catch (DAOException e) { logger.log(Level.SEVERE, e.getMessage(), e); rollBack(transaction); throw new PointOfSaleSystemException("Error occured during updating database", e); } catch (TransactionException e) { logger.log(Level.SEVERE, e.getMessage(), e); rollBack(transaction); throw new PointOfSaleSystemException("Critical Error: couldn't commit changes!", e); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); rollBack(transaction); throw new PointOfSaleSystemException(e); } //To change body of implemented methods use File | Settings | File Templates. }
b4f6575e-2898-4500-a5e7-bee85a757298
6
public int getPriority() { switch (getOperatorIndex()) { case 26: case 27: return 500; case 28: case 29: case 30: case 31: return 550; } throw new RuntimeException("Illegal operator"); }
44f0e997-0be2-4840-9e41-6e03a5088ed7
0
@Override public int getType() { return BuildingType.CITYHALL.ordinal(); }
4cbf0925-e6cc-47cf-ac19-78238b9db74f
2
@Override public boolean accept(File f) { String extension = this.getExtension(f); if (extension.equals("txt") || f.isDirectory()) { //Accept only txt files or directories (to allow navigation) return true; } return false; }
58f7cab1-50af-451f-b6a2-29829b2ec6c8
6
private boolean criteriaCheck3( String field, Ptg[] curRow, DB db ) { boolean critRowMatch = false; // for each value check all the criteria in a row // multiple rows of criteria are combined for( int x = 0; x < rows.length; x++ ) { critRowMatch = true; // reset // for each row of criteria, iterate criteria cols for( String critField : colHeaders ) { List r = getCriteria( x, critField ); Iterator tx = r.iterator(); int dv = db.getCol( critField ); String valcheck = curRow[dv].getValue().toString(); // this criteria row may pass/fail subsequent rows may pass/fail // only one has to pass OK to return true all crit in this row must pass while( tx.hasNext() && critRowMatch ) { // stop if row failure Ptg cv = ((Ptg) tx.next()); String vc = cv.getValue().toString(); if( !vc.equals( "" ) ) { critRowMatch = matches( valcheck, vc ); /* fast fail is not OK because we * may pass one row OR another * AND criteria across criteria rows * OR criteria down cols */ } } } if( critRowMatch ) // fast succeed here, a row passed { return true; } } return critRowMatch; }
e53954f6-33d0-4ade-b18d-8659835cfa5d
7
@Override public void restoreLimb(String gone) { if (affected != null) { if (affected instanceof MOB) { ((MOB)affected).location().show(((MOB)affected), null, CMMsg.MSG_OK_VISUAL, L("^G<S-YOUPOSS> @x1 miraculously regrows!!^?",gone)); } else if ((affected instanceof DeadBody) && (((Item)affected).owner() instanceof Room)) { ((Room)((Item)affected).owner()).showHappens(CMMsg.MSG_OK_VISUAL, L("^G@x1's @x2 miraculously regrows!!^?",affected.name(),gone)); } } final List<String> theRest = affectedLimbNameSet(); if (theRest.contains(gone)) theRest.remove(gone); if((theRest.size()==0)&&(affected!=null)) affected.delEffect(this); else { setMiscText(CMParms.combineWith(theRest,';')); } }
2d49c203-ce29-4d33-b0c8-9f8de4e8d2d2
0
@Override public PropertyFilterChain removePropertyFilterChain(String key, int index) { return (PropertyFilterChain) filter_chains.remove(key); }
d78424e8-f296-4dc1-9dcc-3c246f9599a5
8
private void registerUser(HttpServletRequest request, HttpServletResponse response) { String key = request.getParameter(CommunityConstants.BASE64_PUBLIC_KEY); String nick = request.getParameter(CommunityConstants.NICKNAME); String remote_ip = request.getRemoteAddr(); String username = request.getRemoteUser(); logger.info("Registration request, username: "+ username + " / nick: " + nick); if (key == null) { logger.warning("Dropping registration request with null key from " + remote_ip); return; } if (nick == null) { logger.warning("Dropping registration request with null nick from " + remote_ip); return; } if( username == null) { logger.finer("Open server, using admin to register"); username = "admin"; } if (nick.length() > CommunityConstants.MAX_NICK_LENGTH) { logger.warning("Truncating lengthy nick: " + nick); nick = nick.substring(0, CommunityConstants.MAX_NICK_LENGTH); } logger.finer("Registration request: key=" + key + " remote_ip=" + remote_ip); try { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream())); try { CommunityDAO.get().registerUser(key, nick, remote_ip, username); response.setStatus(HttpServletResponse.SC_OK); out.append(CommunityConstants.REGISTRATION_SUCCESS); logger.finer("Successfully registered " + nick + " from " + request.getRemoteAddr()); } catch (DuplicateRegistrationException e) { logger.finer("Duplicate registration " + nick + " from " + request.getRemoteAddr()); response.setStatus(HttpServletResponse.SC_CONFLICT); out.append(CommunityConstants.REGISTRATION_DUPLICATE); } catch( TooManyRegistrationsException e ) { logger.finer(e.toString() + " / " + remote_ip); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); out.append(e.toString()); } catch (Exception e) { e.printStackTrace(); logger.warning(e.toString()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { out.flush(); out.close(); } } catch (IOException e) { e.printStackTrace(); } }
5f3972e0-1f92-4999-8c6f-2a65524f4177
7
private static boolean getDeleteDecisionFromConsole() throws CancelOperationException { boolean validInput; char[] result = null; do { validInput = true; System.out.print("Delete the message after retrieving it [Y/N]? "); try { String input = in.nextLine().trim(); System.out.println(); // Check if the input signifies a return to the main menu if (isReturnToMainMenu(input)) { throw new CancelOperationException(); } result = input.toLowerCase().toCharArray(); if (result.length == 0 || (result[0] != 'y' && result[0] != 'n')) { throw new IllegalArgumentException(); } } catch (IllegalArgumentException ex) { System.out.println("Invalid entry, please re-enter your selection."); validInput = false; } } while (!validInput); return result[0] == 'y' ? true : false; }
5f65ec55-b89e-425c-8ad7-71010513d410
1
public HomePage getHomePage() { if (homePage == null) { homePage = new HomePage(this); } return homePage; }
31b475a2-2b42-4e1e-a4d7-aaf6f1a71fd5
0
@Override public String toString() { return this.getID() + ""; }
b4bf6f3d-cf9f-4c3d-854a-3f7c5be72746
3
private ByteBuffer convertImageData(BufferedImage bufferedImage, Texture texture) { ByteBuffer imageBuffer; WritableRaster raster; BufferedImage texImage; int texWidth = 2; int texHeight = 2; // find the closest power of 2 for the width and height // of the produced texture while (texWidth < bufferedImage.getWidth()) { texWidth *= 2; } while (texHeight < bufferedImage.getHeight()) { texHeight *= 2; } texture.setTextureHeight(texHeight); texture.setTextureWidth(texWidth); // create a raster that can be used by OpenGL as a source // for a texture if (bufferedImage.getColorModel().hasAlpha()) { raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, texWidth, texHeight, 4, null); texImage = new BufferedImage(glAlphaColorModel, raster, false, new Hashtable()); } else { raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, texWidth, texHeight, 3, null); texImage = new BufferedImage(glColorModel, raster, false, new Hashtable()); } // copy the source image into the produced image Graphics g = texImage.getGraphics(); g.setColor(new Color(0f, 0f, 0f, 0f)); g.fillRect(0, 0, texWidth, texHeight); g.drawImage(bufferedImage, 0, 0, null); // build a byte buffer from the temporary image // that be used by OpenGL to produce a texture. byte[] data = ((DataBufferByte) texImage.getRaster().getDataBuffer()) .getData(); imageBuffer = ByteBuffer.allocateDirect(data.length); imageBuffer.order(ByteOrder.nativeOrder()); imageBuffer.put(data, 0, data.length); imageBuffer.flip(); return imageBuffer; }
10687173-77db-4439-b957-0f4351dd874e
9
private void handleQuery(int userLevel, String[] keywords) { if (isAccountTypeOf(userLevel, ADMIN, MODERATOR, REGISTERED)) { if (keywords.length == 2) { String[] ipFragment = keywords[1].split(":"); if (ipFragment.length == 2) { if (ipFragment[0].length() > 0 && ipFragment[1].length() > 0 && Functions.isNumeric(ipFragment[1])) { int port = Integer.parseInt(ipFragment[1]); if (port > 0 && port < 65535) { sendMessageToChannel("Attempting to query " + keywords[1] + ", please wait..."); ServerQueryRequest request = new ServerQueryRequest(ipFragment[0], port); if (!queryManager.addRequest(request)) sendMessageToChannel("Too many people requesting queries. Please try again later."); } else sendMessageToChannel("Port value is not between 0 - 65536 (ends exclusive), please fix your IP:port and try again."); } else sendMessageToChannel("Missing (or too many) port delimiters, Usage: .query <ip:port> (example: .query 98.173.12.44:20555)"); } else sendMessageToChannel("Missing (or too many) port delimiters, Usage: .query <ip:port> (example: .query 98.173.12.44:20555)"); } else sendMessageToChannel("Usage: .query <ip:port> (example: .query 98.173.12.44:20555)"); } }
0941d43c-b3ed-40d6-b994-5734e83a4890
0
private void initButtons(){ JButton buttonCancel = new JButton("Cancel"); buttonCancel.setBounds(getWidth() - 135, getHeight() - 65 , Main.buttonSize.width, Main.buttonSize.height); buttonCancel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { dispose(); } }); JButton buttonOk = new JButton("OK"); buttonOk.setBounds(getWidth()-260, getHeight()-65, Main.buttonSize.width,Main.buttonSize.height); buttonOk.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { Main.setStructureBase(dataList); dispose(); } }); JButton buttonGenerate = new JButton("Generate"); buttonGenerate.setSize(Main.buttonSize); buttonGenerate.setLocation(STEP_LEFT, getHeight()-65); buttonGenerate.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { generateData(); } }); add(buttonCancel); add(buttonOk); add(buttonGenerate); }
ccc56f8b-3a21-4379-b50d-b461db9280d9
2
public int getStartNodeId(){ Iterator<Node> _iter = this._nodes.values().iterator(); while(_iter.hasNext()){ Node _node = _iter.next(); if(_node.isStartpoint()){ return _node.getId(); } } return -1; }
c5e52315-2cdd-424e-8e57-7054d4084a79
1
public boolean _setSprite(Sprite sprite) { if(sprite != null) { this.sprite = sprite; return true; } else { return false; } }
f24fe502-ddea-4ea5-94f2-09c57bd8dfc8
0
public void setG(int g) { this.g = g; }
12796d49-ddfc-4acc-b8e4-6363daeffdc6
5
private void searchLevelExact(ResultSet resultSet, double[] query, Node node, double mindist, float epsError) { // If this is a leaf node. if (node.child1 == null && node.child2 == null) { int index = node.cutDimension; double dist = metric.distance(node.point, query); resultSet.addPoint(dist, index); return; } // Which child branch should be taken first? double val = query[node.cutDimension]; double diff = val - node.cutDimensionValue; Node bestChild = diff < 0 ? node.child1 : node.child2; Node otherChild = diff < 0 ? node.child2 : node.child1; double newDistSq = mindist + metric.distance(val, node.cutDimensionValue); // Call recursively to search next level down. searchLevelExact(resultSet, query, bestChild, mindist, epsError); if (mindist * epsError <= resultSet.worstDistance()) { searchLevelExact(resultSet, query, otherChild, newDistSq, epsError); } }
d732980c-1f50-4e01-adef-629dd30f2807
1
public static void main(String [] args){ if (args.length!=2){ args = new String[2]; args[0] = "localhost"; args[1] = "9000"; } String arg1 = args[1]; final String[] args2 = new String[1]; args2[0] = arg1; final String[] args2final = args2; final String[] argsfinal = args; new Thread(){ public void run(){ ChatServerMain.main(args2final); } }.start(); new Thread(){ public void run(){ ChatClient.main(argsfinal); } }.start(); new Thread(){ public void run(){ ChatClient.main(argsfinal); } }.start(); new Thread(){ public void run(){ ChatClient.main(argsfinal); } }.start(); }
3461c4b9-8e2c-430a-a33d-b66a6bb4d95c
3
public void save(){ int i=0; synchronized(options){ options.clear(); synchronized (timers){ for (Timer timer : timers){ options.setProperty("Timer"+i, String.format("%d,%d",timer.getStart(), timer.getTime())); options.setProperty("Timer"+i+"Name", timer.getName()); i++; } } try { options.store(new FileOutputStream("timers.conf"), "Timers config"); } catch (FileNotFoundException e) { } catch (IOException e) { } } }
c008df12-f871-41d9-949c-56e53aa34f03
1
public static boolean isThis(Expression thisExpr, ClassInfo clazz) { return ((thisExpr instanceof ThisOperator) && (((ThisOperator) thisExpr) .getClassInfo() == clazz)); }
81dcd36d-7e88-46a6-9283-098e3fbf4407
7
@Override public void mouseClicked(MouseEvent e) { int mouse = e.getButton(); Rectangle rect = new Rectangle(e.getX(), e.getY(), 1, 1); pressed = true; if(mouse == MouseEvent.BUTTON1) { switch(Game.state) { case GAME: break; case MENU: if(rect.intersects(Game.getInstance().getMenu().play)) { Game.state = GameState.GAME; } else if(rect.intersects(Game.getInstance().getMenu().quit)) { System.exit(1); } break; case OPTIONS: break; case PAUSE: break; default: break; } } }
e9414e41-11f6-4708-9ada-92a63486ff71
1
protected void execute() { double time = _timer.get(); if (time >= _period){ Color c = colors[_rand.nextInt(colors.length)]; Robot.ledStrip.setColor(c.getRed(),c.getBlue(),c.getGreen()); _timer.reset(); } }
58e6b827-eaa5-4088-a67d-ccd96da2f4c9
2
private ListNode findMover( ListNode head ) { ListNode p1 = head; // move 1 step each step ListNode p2 = head; // move 2 steps each step while ( p2 != null && p2.next != null ) { p1 = p1.next; p2 = p2.next.next; } // 1. cut down the list ListNode ret = p1.next; p1.next = null; // 2. return the next element of p1 return ret; }
5d67da25-827a-4c48-aa2d-ab75747f59f6
3
public int getUniqueWindowID(){ int id = 0; boolean unique = false; while (!unique){ unique = true; for (int x = 0; x < windowslist.size(); x++){ if (id == windowslist.get(x).getID()){ unique = false; id++; } } } return id; }
557a616c-bc12-481f-9ce0-0ef58e47fb64
4
public void createOpdracht() { try { String vraag = opdrCreatieView.getVraagT().getText(); String antwoord = opdrCreatieView.getAntwoordT().getText(); int maxAantalPogingen = Integer.valueOf((String) opdrCreatieView .getMaxAantalPogingenC().getSelectedItem()); String antwoordHint = opdrCreatieView.getAntwoordHintT().getText(); int maxAntwoordTijd = Integer.valueOf((String) opdrCreatieView .getMaxAntwoordTijdC().getSelectedItem()); String opdrachtCategorieString = opdrCreatieView .getOpdrachtCategorie().getSelectedItem().toString(); OpdrachtCategorie opdrachtCategorie = OpdrachtCategorie .valueOf(opdrachtCategorieString); String soortOpdrachtString = opdrCreatieView.getCategorie() .getSelectedItem().toString(); Categorie categorie = Categorie.valueOf(soortOpdrachtString); if (Categorie.Reproductie.equals(categorie)) { String trefwoorden = opdrCreatieView.getTrefwoordenT() .getText(); int minAantalJuisteTrefwoorden = Integer .valueOf((String) opdrCreatieView .getMinAantalJuisteTrefwoordenC() .getSelectedItem()); opdracht = new Reproductie(vraag, antwoordHint, maxAantalPogingen, antwoordHint, maxAntwoordTijd, trefwoorden, minAantalJuisteTrefwoorden, opdrachtCategorie); } else if (Categorie.Meerkeuze.equals(categorie)) { String alleKeuzes = opdrCreatieView.getAlleKeuzesT().getText(); opdracht = new Meerkeuze(vraag, antwoord, maxAantalPogingen, alleKeuzes, antwoordHint, maxAntwoordTijd, opdrachtCategorie); } else if (Categorie.Opsomming.equals(categorie)) { opdracht = new Opsomming(vraag, antwoord, maxAantalPogingen, antwoordHint, maxAntwoordTijd, opdrachtCategorie); } } catch (Exception ex) { System.out.println(ex.getMessage()); } }
8d6338b8-9ecf-4a26-95ae-298267508957
6
@EventHandler public void ZombieHarm(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.getZombieConfig().getDouble("Zombie.Harm.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getZombieConfig().getBoolean("Zombie.Harm.Enabled", true) && damager instanceof Zombie && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.HARM, plugin.getZombieConfig().getInt("Zombie.Harm.Time"), plugin.getZombieConfig().getInt("Zombie.Harm.Power"))); } }
8abf1acb-3118-4975-bae6-4df68af027dd
7
AIMove onTestHockeyistFriction(AIHockeyist hockeyist) { AIManager manager = AIManager.getInstance(); AIRectangle rink = manager.getRink(); AIPoint center = manager.getCenter(); AIMove move = new AIMove(); if (!visitedOrigin) { double d = hockeyist.angleTo(rink.origin); move.setTurn(d); move.setSpeedUp(1); if (hockeyist.distanceTo(rink.origin) < 2*AIHockeyist.RADIUS) { move.setSpeedUp(0); if (hockeyist.getSpeedScalar() < 0.1) { move.setTurn(hockeyist.angleTo(rink.getRight(), hockeyist.getY())); if (hockeyist.angleTo(rink.getRight(), hockeyist.getY()) < AI.DEGREE) { visitedOrigin = true; } } } } else { move.setSpeedUp(1); } if (visitedOrigin && hockeyist.getX() > center.x) { move.setSpeedUp(0); if (hockeyist.getSpeedScalar() > 0.005) { System.out.println(String.format("%.2f,%.2f;", hockeyist.getSpeedScalar(), hockeyist.distanceTo(center.x, hockeyist.getY()))); } } return move; }
3855d046-1e1b-4e00-9e8f-b40a85c817c7
4
public static void test2(int a, int aa, int bb, String op, boolean carry) { String op2 = "("+Integer.toHexString(aa)+" "+op+" "+Integer.toHexString(bb)+") "; a &= 0xFF; // if(a == 0) // return; if(a == aa) return; for(int j=0;j<A.length; j++) { int b = A[j]; test(a+b,a,b,op2+"add",aa); if(carry) test(a+b+1,a,b,op2+"adc",aa); test(a-b,a,b,op2+"sub",aa); if(carry) test(a-b-1,a,b,op2+"sbc",aa); test(a&b,a,b,op2+"and",aa); test(a|b,a,b,op2+"or",aa); test(a^b,a,b,op2+"xor",aa); } }
6cfe6b3d-2fd9-4f38-80db-a97717826f40
9
public final void execute() { boolean start = false; try { start = valid(); } catch (Exception e) { Logger.getLogger("CONCURRENT-VALIDATION").severe(e.getMessage()); e.printStackTrace(); } catch (ThreadDeath td) { Logger.getLogger("CONCURRENT-VALIDATION").severe(td.getMessage()); td.printStackTrace(); } try { while (start) { if (halting) break; int timeout = 100; if (!paused) { try { timeout = loop(); } catch (Exception e) { Logger.getLogger("CONCURRENT-LOOP").severe( e.getMessage()); e.printStackTrace(); timeout = -1; } } if (timeout == -1) break; sleep(timeout); } } catch (Exception e) { Logger.getLogger("CONCURRENT").severe(e.getMessage()); e.printStackTrace(); } catch (ThreadDeath td) { Logger.getLogger("CONCURRENT").severe(td.getMessage()); td.printStackTrace(); } }
14f1233f-e05b-4590-8b2d-97a9b80210bc
4
@Override public StateBuffer executeInternal(StateBuffer sb, int minValue) { sb = new UnboundedSegment(new TextSegment(Move.A,false)).execute(sb); // player mon uses attack sb = new CheckMetricSegment(new CheckMoveDamage(isCrit, effectMiss, numEndTexts == 0, false, !player, ignoreDamage, thrashAdditionalTurns),GREATER_EQUAL,ignoreDamage ? 0 : minValue,player ? KillEnemyMonSegment.PLAYER_ATTRIBUTE : KillEnemyMonSegment.ENEMY_ATTRIBUTE).execute(sb); sb = new UnboundedSegment(new MoveSegment(new Wait(1), 0)).execute(sb); // skip last frame of text box for(int i=0;i<numEndTexts-1;i++) { // skip messages sb = new TextSegment().execute(sb); // critical hit! message sb = new MoveSegment(new PressButton(Move.B)).execute(sb); // close message } if(numEndTexts > 0) // skip last message if any sb = new TextSegment().execute(sb); // critical hit! or very/not effective message return sb; }
3686871f-625b-4fa9-967b-e644758f5557
9
@Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking,tickID)) return false; if(tickID==Tickable.TICKID_MOB) { if(nextDirection==-999) return true; if((theTrail==null) ||(affected == null) ||(!(affected instanceof MOB))) return false; final MOB mob=(MOB)affected; if(nextDirection==999) { mob.tell(L("The trail seems to pause here.")); nextDirection=-2; unInvoke(); } else if(nextDirection==-1) { mob.tell(L("The trail dries up here.")); nextDirection=-999; unInvoke(); } else if(nextDirection>=0) { mob.tell(L("The trail seems to continue @x1.",CMLib.directions().getDirectionName(nextDirection))); nextDirection=-2; } } return true; }
d51f7410-99fb-4495-b4ed-c5860a4f938c
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JsonArray other = (JsonArray) obj; if (other.hasComments() ^ hasComments()) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; if (hasComments() && !getComments().equals(other.getComments())) return false; return true; }
94f2ec37-20ef-4196-a149-dd9d791d1d25
7
public DFSTree(Set<Node> nodeList) { removables = new HashSet<Node>(); if (nodeList.isEmpty()) { root = null; return; } nodeMap = new HashMap<Node, DFSNode>(); int labelCount = 0; Set<Node> visitedNodes = new HashSet<Node>(); Node n = nodeList.iterator().next(); visitedNodes.add(n); root = new DFSNode(n, null, labelCount++); nodeMap.put(n, root); DFSNode currentNode = root; while (currentNode != null) { Set<Node> toVisitNodes = new HashSet<Node>(currentNode.node.neighbors); toVisitNodes.retainAll(nodeList); toVisitNodes.removeAll(visitedNodes); if (toVisitNodes.isEmpty()) { currentNode = currentNode.parent; } else { n = toVisitNodes.iterator().next(); visitedNodes.add(n); DFSNode newNode = new DFSNode(n, currentNode, labelCount++); currentNode.children.add(newNode); currentNode = newNode; nodeMap.put(n, currentNode); } } // build all the non-tree edges for (Node _node : nodeList) { DFSNode dfsNode = nodeMap.get(_node); if (dfsNode.parent != null) { Set<Node> neighbors = new HashSet<Node>(_node.neighbors); neighbors.retainAll(nodeList); neighbors.remove(dfsNode.parent.node); for (Node _n : neighbors) { dfsNode.nonTreeNeighbors.add(nodeMap.get(_n)); } } } // calculate lower and find removable vertices calcLower(root); if (root.children.size() <= 1) { removables.add(root.node); } }
2152c550-6f3e-4412-92e3-eaab80a742c2
8
private void seekString(StringBuilder strBuilder) { char ch = 0; boolean isEscape = false; ch = jsonStr.charAt(index); if (ch != '"') { vali.disPass(index); } else { while (true) { index++; if (index >= length) { break; } ch = jsonStr.charAt(index); if (isEscape) { isEscape = false; seekEscape(strBuilder); } else { if (ch == '\\') { isEscape = true; continue; } if (ch == '"') { break; } else { strBuilder.append(ch); } } if (!vali.isPass()) { break; } } } if (ch != '"') { vali.disPass(index); strBuilder.setLength(0); } }
185db849-40b2-4c15-9c59-44671a55ce3c
2
public ArrayList<BESong> getAllByPlaylist(int searchWord) throws Exception { try { if (m_songs == null) { m_songs = ds.getAllByPlaylist(searchWord); } return m_songs; } catch (SQLException ex) { throw new Exception("Could not find all songs..."); } }
42d7e7ac-0946-4bca-9468-44216bc1648a
2
public boolean findStartPos(Level level) { while (true) { int x = random.nextInt(level.w); int y = random.nextInt(level.h); if (level.getTile(x, y) == Tile.grass) { this.x = x * 16 + 8; this.y = y * 16 + 8; return true; } } }
10b0ee54-4e76-4c60-87b4-320c5f6c4617
8
protected void replaceAll() { init(); if( !replace ) return; txt.setRedraw(false); if( parser != null) parser.setReparse(false); if( wrapButton.getSelection() && replaceText.getText().contains(findText.getText())) wrapButton.setSelection(false); while(true){ if( !find() ) break; if( !replace() ) break; } if( parser != null){ parser.setReparse(true); parser.reparseAll(); } txt.setRedraw(true); }
fdcd609b-3ebe-4fa8-8638-d547846e5b5d
6
public void sendTo(CommandSender s, int page, int perPage) { List<HelpScreenEntry> toSend = toSend(s); int maxpage = (int) (toSend.size() / (float) perPage + 0.999); int from = (page - 1) * perPage; int to = from + perPage; if (from >= toSend.size()) { from = to = 0; } if (to > toSend.size()) { to = toSend.size(); } toSend = from == to || toSend.size() == 0 ? new ArrayList<HelpScreenEntry>() : toSend.subList(from, to); String[] msg = new String[toSend.size() + 1]; msg[0] = header.replaceAll("<name>", NAME).replaceAll("<page>", page + "").replaceAll("<maxpage>", maxpage + ""); int i = 1; boolean col = false; for (HelpScreenEntry e : toSend) { msg[i++] = ((col = !col) ? c1 : c2) + e.fromFormat(format); } s.sendMessage(msg); }
43159c2f-986b-446c-8edb-c113fa65bf16
7
public boolean pickAndExecuteAnAction() { try{ for(int i =0; i < Bills.size(); i++){ //print("" + Customers.get(i).s ); if(Bills.get(i).s == OrderState.needToCompute){ Compute(Bills.get(i)); return true; } } for(int i =0; i < Bills.size(); i++){ if(Bills.get(i).s == OrderState.needChange){ makeChange(Bills.get(i), i); return true; } } for(int i =0; i < MarketBills.size(); i++){ if(MarketBills.get(i).s == mBillState.OutStanding){ payMarket(MarketBills.get(i)); return true; } } return false;} catch (ConcurrentModificationException e) { return false; } }
dae3e2b7-9c39-419e-a32b-206523fc498c
3
public void caretUpdate(CaretEvent e) { ASection s; s = aDoc.getASectionThatStartsAt(textPane.getCaretPosition()); if (textPane.getText().length()<=0)setText("Откройте сохраненный документ или вставтьте анализируемый текст в центральное окно"); else if(s !=null){ setText(aDoc.getAData(s).toString());} else if (e.getDot()==e.getMark()) setText("Выделите область текста чтобы начать анализ..."); else setText("Выберите аспект и параметры обработки, используя панель справа..."); } //caretUpdate()
5c786cfa-b959-4a01-af49-8dfb4183bd91
0
public PageNotFoundException(Exception e, String name){ super(e, name); }
1f6c8fe8-b515-4340-8941-365abc49649a
1
public String getDiccionario(){ String dic = ""; for(int i=0; i<diccionario.size(); i++){ dic = dic + diccionario.get(i).getPalabra() + "<BR> "; } return dic; }
309f3620-d53f-4e9a-8120-185ba19bfe6e
7
public static StringWrapper javaTranslateTypeSpecHelper(StandardObject typeSpec, boolean functionP) { { Surrogate finalType = null; String typeName = ""; { Surrogate testValue000 = Stella_Object.safePrimaryType(typeSpec); if (Surrogate.subtypeOfParametricTypeSpecifierP(testValue000)) { { ParametricTypeSpecifier typeSpec000 = ((ParametricTypeSpecifier)(typeSpec)); if (StandardObject.arrayTypeSpecifierP(typeSpec000)) { return (ParametricTypeSpecifier.javaTranslateArrayType(typeSpec000)); } else { return (StandardObject.javaTranslateTypeSpec(typeSpec000.specifierBaseType)); } } } else if (Surrogate.subtypeOfSurrogateP(testValue000)) { { Surrogate typeSpec000 = ((Surrogate)(typeSpec)); if (((StringWrapper)(KeyValueList.dynamicSlotValue(((Stella_Class)(typeSpec000.surrogateValue)).dynamicSlots, Stella.SYM_STELLA_CLASS_JAVA_NATIVE_TYPE, Stella.NULL_STRING_WRAPPER))).wrapperValue != null) { return (StringWrapper.wrapString(((Stella_Class)(typeSpec000.surrogateValue)).javaNativeType())); } else { finalType = ((Stella_Class)(typeSpec000.surrogateValue)).classType; typeName = StringWrapper.javaTranslateClassNamestring(StringWrapper.wrapString(finalType.symbolName)).wrapperValue; if (!Module.omitJavaPackagePrefixP(finalType.homeModule(), finalType.symbolName)) { return (StringWrapper.wrapString(Module.javaPackagePrefix(finalType.homeModule(), ".") + typeName)); } else if (functionP && Stella_Class.classNameConflictsWithSlotNameP(((Stella_Class)(Stella.$CURRENT_JAVA_OUTPUT_CLASS$.get())), typeName)) { return (StringWrapper.wrapString(Module.javaPackagePrefix(finalType.homeModule(), ".") + typeName)); } else { return (StringWrapper.wrapString(typeName)); } } } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + testValue000 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } } } }
059cc48e-4856-451a-ba52-97644415ace1
2
public int getHyperPeriod() { if (workload.size() <= 0) return 0; int hp = workload.get(0).getPeriod(); for (int i = 1; i < workload.size(); i++) { hp = MathUtils.lcm(hp, workload.get(i).getPeriod()); } return hp / 2; }
8634569d-9c0b-411b-9d23-e491fef400f3
5
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Node node = (Node) o; if (id != null ? !id.equals(node.id) : node.id != null) return false; return true; }
f90578c3-b91f-47ae-ae29-af2136e07e7c
6
public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(new File( ConfigReader.getKylie16SDir() + File.separator + "PCA_PIVOT_16Sfamily.txt"))); BufferedWriter writer = new BufferedWriter(new FileWriter(new File( ConfigReader.getKylie16SDir() + File.separator + "PCA_PIVOT_16SfamilyWithOldYoung.txt"))); String[] firstHeaders = reader.readLine().split("\t"); for( int x=0; x < 4; x++) writer.write( firstHeaders[x] + "\t"); writer.write("age"); for( int x=4; x < firstHeaders.length; x++) writer.write("\t" + firstHeaders[x]); writer.write("\n"); for(String s = reader.readLine(); s != null; s= reader.readLine()) { String[] splits = s.split("\t"); for( int x=0; x < 4; x++) writer.write( splits[x] + "\t"); String old_young = getAgeMap().get(splits[2]); if(old_young == null) throw new Exception("No " + splits[2]); writer.write(old_young); for( int x=4; x < firstHeaders.length; x++) writer.write("\t" + splits[x]); writer.write("\n"); } writer.flush(); writer.close(); }
5c565675-6ef3-4c9f-bae7-44b968687936
1
private int root(int i) { while (i != id[i]) { id[i] = id[id[i]]; // to compress the path i = id[i]; } return i; }
eacf34d7-1712-418e-b308-e84935dec3b7
5
public Object [][] getDatos(){ Object[][] data = new String[getCantidad_Cuentas ()][colum_names.length]; //realizamos la consulta sql y llenamos los datos en "Object" try{ if (colum_names.length>=0){ r_con.Connection(); String campos = colum_names[0]; for (int i = 1; i < colum_names.length; i++) { campos+=","; campos+=colum_names[i]; } String consulta = ("SELECT "+campos+" "+ "FROM "+name_tabla+" WITH (INDEX("+indices_tabla[numero_ordenamiento_elegido]+"))"); PreparedStatement pstm = r_con.getConn().prepareStatement(consulta); ResultSet res = pstm.executeQuery(); int i = 0; while(res.next()){ for (int j = 0; j < colum_names.length; j++) { data[i][j] = res.getString(j+1); } i++; } res.close(); } } catch(SQLException e){ System.out.println(e); } finally { r_con.cierraConexion(); } return data; }
3351bb4f-84f0-4a41-8ff3-542a940f7097
6
public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; }
511640b4-959d-48f4-afba-4bb8506d8c9d
6
public static Vector<Ticket> valideCaddie (Vector<Caddie> caddies) throws BDException, ParseException { ArrayList<Vector<Place>> placesToChoice = new ArrayList<Vector<Place>>(); ArrayList<Integer> placesPrice = new ArrayList<Integer>(); Vector<Ticket> toReturn = new Vector<Ticket>(); int finalPrice = 0 ; // Test et récupération des places disponibles. for(Caddie caddie : caddies){ Vector<Place> places = getPlacesDisponiblesFromZone(Integer.toString(caddie.getNumS()), caddie.getDate(), caddie.getZone()); // Test si le nombre de places est bon. if(places.size() < caddie.getQt()) throw new BDException("Il ne reste plus assez de places !!!!"); // Choix des places. placesToChoice.add(choicePlaces(places, caddie.getQt())); // Ajout au prix de la commande. int prix =getPriceOfAPlace(caddie.getZone()); finalPrice+=prix*caddie.getQt(); placesPrice.add(prix); } // Insertion. PreparedStatement stmt = null; Connection conn = null; String requete = null; try { conn = BDConnexion.getConnexion(); conn.setAutoCommit(false); // Création d'une nouvelle commande. int numDossier = BDRequetesTest.testNouveauDossier(conn,finalPrice); // Ajout de tous les tickets for(int i = 0 ; i< caddies.size() ; i++){ Caddie caddie = caddies.get(i); Vector<Place> places = placesToChoice.get(i); int prixDelaPlace = placesPrice.get(i); for(Place place : places){ // Get le nouveau num de serie. int noserie = BDRequetesTest.testNouveauTicket(conn); requete = "insert into lestickets values (?, ?, ?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(requete); stmt.setInt(1,noserie); stmt.setInt(2,caddie.getNumS()); stmt.setTimestamp(3,new Timestamp((new SimpleDateFormat("dd/MM/yyyy HH:mm")).parse(caddie.getDate()).getTime())); stmt.setInt(4,place.getNum()); stmt.setInt(5,place.getRang()); Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("dd/MM/yyyy HH:mm"); stmt.setTimestamp(6,new Timestamp((new SimpleDateFormat("dd/MM/yyyy HH:mm")).parse(ft.format(dNow)).getTime())); stmt.setInt(7,numDossier); int nb_insert = stmt.executeUpdate(); if(nb_insert != 1) { // ERREUR CRITIQUE .... conn.rollback(); throw new BDException("Impossible de valider la commande"); } else { // Ajout d'un ticket à retourner. Ticket tik = new Ticket(); tik.setDateEmission(ft.format(dNow)); tik.setDateRep(caddie.getDate()); tik.setNomS(caddie.getNom()); tik.setNumDossier(numDossier); tik.setNumPlace(place.getNum()); tik.setNumS(caddie.getNumS()); tik.setNumTicket(noserie); tik.setRangPlace(place.getRang()); tik.setZonePlace(place.getZone()); tik.setPrix(prixDelaPlace); toReturn.add(tik); } } } // To c'est normalement passé. conn.commit(); } catch (SQLException e) { throw new BDException("Problème de création de commande (Code Oracle : "+e.getErrorCode()+")"); } finally { BDConnexion.FermerTout(conn, stmt, null); } return toReturn ; }
d5abe9c3-e814-4495-8a9a-e1c306833445
2
public boolean saveFile(ArrayList<Game> liste) { PrintWriter pw; try { pw = new PrintWriter("words.txt"); for (int i = 0; i < liste.size(); i++) { pw.print(liste.get(i).toSaveString()); System.out.println(liste.get(i).toSaveString()); } pw.close(); } catch (FileNotFoundException ex) { System.out.println("Fejl: " + ex.getMessage()); return false; } return true;}
e5fcf6a7-53ac-43e5-8329-6eb7a60abcbb
7
private int getDownPos(String text, int cpos) { String[] lines = text.split("\n"); int line = 0; int tmp = cpos; while(tmp > 0) { tmp -= lines[line].length() + 1; line++; } line--; int all = 0; for(int i = 0; i < line; i++) { all += lines[i].length()+1; } int dif = cpos - all; if(line == -1) line++; if(line == lines.length-1) return cpos; if(dif == lines[line].length()+1) { dif = 0; line++; } else if(dif >= lines[line+1].length()+1) { dif = lines[line+1].length(); } int t = 0; for(int i = 0; i < line+1; i++) { t += lines[i].length()+1; } return t+dif; }