method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
2512fb71-3d3e-49b0-b5d4-42c0bd785efb
2
@Override public void update(GameContainer gc, int delta) { if (gc.getInput().isMousePressed(Input.MOUSE_LEFT_BUTTON)) { if (playItem.isSelected(gc)) { parent.changeScreen(parent.getPlayScreen()); } } }
0868b928-7b4c-4324-8ddc-afa26cfef873
4
@Override protected ReferencedEnvelope getBoundsInternal(Query query) throws IOException { Filter filter = query.getFilter(); // handle query filter if (filter instanceof IncludeFilter) { // don't care about this filter, ignore it } else if (filter instanceof BBOX) { LOGGER.severe("HANDLE BBOX FILTER!!"); } else { throw new UnsupportedOperationException("Filter of type " + filter.getClass().getName() + " is not supported by getBoundsInteral!"); } ReferencedEnvelope bounds = null; try { Statement q = getDataStore().getConnection().createStatement(); ResultSet res = q.executeQuery( "SELECT " + "MIN(" + geometryColumn + "_x) AS minx, " + "MAX(" + geometryColumn + "_x) AS maxx, " + "MIN(" + geometryColumn + "_y) AS miny, " + "MAX(" + geometryColumn + "_y) AS maxy " + "FROM " + typeName ); if (res.next() == false) throw new IOException("unable to fetch bounds"); bounds = new ReferencedEnvelope( res.getDouble("minx"), res.getDouble("maxx"), res.getDouble("miny"), res.getDouble("maxy"), getSchema().getCoordinateReferenceSystem() ); res.close(); q.close(); } catch (SQLException ex) { throw new IOException(ex); } return bounds; }
87d9d5f5-0a0d-4b77-a4b3-c63cd14055c5
4
public boolean poll() { boolean result = target.poll(); Event event = new Event(); EventQueue queue = target.getEventQueue(); while (queue.getNextEvent(event)) { // handle button event if (buttons.contains(event.getComponent())) { Component button = event.getComponent(); int buttonIndex = buttons.indexOf(button); buttonState[buttonIndex] = event.getValue() != 0; } // handle pov events if (pov.contains(event.getComponent())) { Component povComponent = event.getComponent(); int povIndex = pov.indexOf(povComponent); povValues[povIndex] = event.getValue(); } // handle axis updates if (axes.contains(event.getComponent())) { Component axis = event.getComponent(); int axisIndex = axes.indexOf(axis); float value = axis.getPollData(); // fixed dead zone since most axis don't report it :( /*if (Math.abs(value) < deadZones[axisIndex]) { value = 0; } if (Math.abs(value) < axis.getDeadZone()) { value = 0; } if (Math.abs(value) > axesMax[axisIndex]) { axesMax[axisIndex] = Math.abs(value); }*/ // normalize the value based on maximum value read in the past // value /= axesMax[axisIndex]; axesValue[axisIndex] = value; } } return result; }
1bcf00f1-84e2-4ece-8b8e-9259fe1aaf26
5
public static int isPan( String s ) { boolean[] digits = new boolean[9]; for(char c : s.toCharArray()) { if( c == '0' || digits[c-'0'-1] ) return -1; digits[c-'0'-1] = true; } for(boolean b : digits) if(!b) return 0; return 1; }
5d30d69a-97c9-4f66-b561-6ec5e36e4ca1
2
private void refresh() { if (currState == State.step1) { //Enable step 1 components editorBN.setBackground(Color.white); editorBN.setEnabled(true); optionsBN.setEnabled(true); optionsDicts.setEnabled(true); lockButton.setEnabled(true); //Disable step 2 components editorText.setBackground(Color.lightGray); editorText.setEnabled(false); optionsTexts.setEnabled(false); optionsSymbols.setEnabled(false); analyzeButton.setEnabled(false); //Display status statusLabel.setText("Status: Ready"); } else if (currState == State.step2) { //Disable step 1 components editorBN.setBackground(Color.lightGray); editorBN.setEnabled(false); optionsBN.setEnabled(false); optionsDicts.setEnabled(false); lockButton.setEnabled(false); //Enable step 2 components editorText.setBackground(Color.white); editorText.setEnabled(true); optionsTexts.setEnabled(true); optionsSymbols.setEnabled(true); analyzeButton.setEnabled(true); } }
63af161a-2f40-4a12-9270-50b79a85e48b
9
private boolean doesTouchInternal(Polyline other) { for (int i = 0; i < nbSegments(); i++) { final LineSegmentInt seg1 = segments().get(i); for (int j = 0; j < other.nbSegments(); j++) { final LineSegmentInt seg2 = other.segments().get(j); final boolean ignoreExtremities = i == 0 || i == nbSegments() - 1 || j == 0 || j == other.nbSegments() - 1; if (ignoreExtremities == false && seg1.doesIntersect(seg2)) { return true; } if (ignoreExtremities && seg1.doesIntersectButNotSameExtremity(seg2)) { return true; } } } return false; }
cfa34066-f0fd-40a2-907d-c4490945c2d1
1
public InterfaceSelector(InterfaceSelectorReceiver callbackHandler) throws SocketException { setDefaultCloseOperation(EXIT_ON_CLOSE); this.callbackHandler = callbackHandler; ButtonGroup buttons = new ButtonGroup(); setLayout(new GridLayout(0,1)); setSize(100, 500); Enumeration<NetworkInterface> interfacelist = NetworkInterface.getNetworkInterfaces(); while ( interfacelist.hasMoreElements() ) { NetworkInterface thisInterface = interfacelist.nextElement(); JRadioButton button = new JRadioButton(thisInterface.getName()); buttons.add(button); add(button); buttonlist.add(button); } Button okButton = new Button("OK"); okButton.addActionListener(this); add(okButton); setVisible(true); }
ba1c595b-cdeb-43db-af49-a87ff643489b
4
public ByteOrderMark(String charsetName, int... bytes) { if (charsetName == null || charsetName.length() == 0) { throw new IllegalArgumentException("No charsetName specified"); } if (bytes == null || bytes.length == 0) { throw new IllegalArgumentException("No bytes specified"); } this.charsetName = charsetName; this.bytes = new int[bytes.length]; System.arraycopy(bytes, 0, this.bytes, 0, bytes.length); }
7c6d69d4-358a-4c7f-b9c5-42a2d6c56b3c
5
public void run () { try { String inputLine; socketOutput = new PrintWriter(clientSocket.getOutputStream(), true); socketInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); Scanner netScanner; String instType; System.out.print ("[SERVER] A new client has joined from the following address: "); System.out.println (clientSocket.getInetAddress().getHostAddress()); //Handle client input here while (!hashFound) { inputLine = socketInput.readLine(); System.out.println ("[CLIENT->SERVER] Message received from client: \"" + inputLine + "\"."); //Determine command type here netScanner = new Scanner (inputLine); netScanner.next(); //Skip the [COMMAND] part instType = netScanner.next(); //Read in the instruction type if ("GiveWork".equals(instType)) { giveWork(netScanner); System.out.println ("[SERVER] Waiting for inbound traffic from the client..."); //Wait for more Client communications at the top of this loop } else if ("Found!".equals(instType)) { //Scan the answer in netScanner.next(); //Skip over the "Answer is" part netScanner.next(); //Display the answer answer = netScanner.next(); System.out.print ("[SYSTEM] Answer has been found! "); System.out.println ("Hash value was \"" + TARGET + "\" and plaintext was \"" + answer + "\""); hashFound = true; //Exit the ServerThread from here } else { System.out.println ("[NETERROR] Received an invalid command via network!"); } } //Wait for one last connection, tell the client it's time to leave if (null == answer) { System.out.println ("[SYNCERROR] ServerThread is terminating without having found an answer!"); } else { giveAnswer(); } clientSocket.close(); socketOutput.close(); socketInput.close(); System.out.print ("[SERVER] A client with the following address has been disconnected: "); System.out.println (clientSocket.getInetAddress().getHostAddress()); } catch (IOException ioe) { System.out.print ("[ERROR] IO error when maintaining a client's connection at "); System.out.println ("address \"" + clientSocket.getInetAddress().getHostAddress() + "\"."); } }
ed3d1815-81d4-464e-9d72-fa0abf869aba
9
public static void printContext(Context self, PrintableStringWriter stream) { { String typestring = null; String name = null; int number = self.contextNumber; if (!Stella.$CLASS_HIERARCHY_BOOTEDp$) { stream.print("|MDL|" + ((Module)(self)).moduleName); return; } { Surrogate testValue000 = Stella_Object.safePrimaryType(self); if (Surrogate.subtypeOfP(testValue000, Stella.SGT_STELLA_MODULE)) { { Module self000 = ((Module)(self)); name = self000.moduleFullName; if ((((self000.contextNumber) % 2) == 1)) { typestring = "|DeLeTeD MDL|"; } else { typestring = "|MDL|"; } } } else if (Surrogate.subtypeOfP(testValue000, Stella.SGT_STELLA_WORLD)) { { World self000 = ((World)(self)); name = ((StringWrapper)(KeyValueList.dynamicSlotValue(self000.dynamicSlots, Stella.SYM_STELLA_WORLD_NAME, Stella.NULL_STRING_WRAPPER))).wrapperValue; if ((((self000.contextNumber) % 2) == 1)) { typestring = "|DeLeTeD WLD|"; } else { typestring = "|WLD|"; } } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + testValue000 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } } if ((((self.contextNumber) % 2) == 1)) { number = number + 1; } if (((Boolean)(Stella.$PRINTREADABLYp$.get())).booleanValue()) { if (name != null) { stream.print(name); } else { stream.print("#<" + typestring + number + ">"); } } else { if (name != null) { stream.print(typestring + name); } else { stream.print(typestring + number); } } } }
5670847f-61ab-48f1-8e36-1c78936f2eb2
8
public void excecuteCommand(String channel, String sender, String message) throws Exception { if(message.startsWith("!etip")) { sendMessage(channel, "Such " + sender + " tipped much Ɖ" + message.split(" ")[2] + " to " + message.split(" ")[1] + "! (to claim /msg Doger help)"); sendMessage("Doger", "!tip " + message.split(" ")[1] + " " + message.split(" ")[2]); } else if(message.startsWith("!esoak")) { int val = Integer.parseInt(message.split(" ")[1]); int usercount = 0; String userlist = ""; for(User u : bot.getUsers(channel)) { if(!u.getNick().toLowerCase().startsWith("eduardog") && !u.getNick().equalsIgnoreCase("ejavabot")) { usercount++; userlist = userlist + ", " + u.getNick(); } } int tipamount = val / usercount; sendMessage(channel, "Sending Ɖ" + tipamount + " to " + userlist.replaceFirst(Pattern.quote(", "), "")); for(User u : bot.getUsers(channel)) { if(!u.getNick().toLowerCase().startsWith("eduardog") && !u.getNick().equalsIgnoreCase("ejavabot")) { sendMessage("Doger", "!tip " + u.getNick() + " " + tipamount); } } } }
f7e910f8-d76c-47af-a884-a616adbdcebb
6
private ChartEntry readEntry(ScanfReader scanReader, TablePane pane) throws IOException { String entryName = scanReader.scanString("%S"); ChartEntry entry = new ChartEntry(entryName); String attributeName; while (!(attributeName = scanReader.scanString()).equals("end")) { //*** //Here we have added a special case for the entry, called "report=", this is the PDF file location of the report associated with this entry //PROBLEM: the acme scanReader reads the line in the file, but if the line has any spaces is becomes the next attribute. // so, in the valuecharts file, the user needs to specify the entire line, including the path as one single line // We suggest using "$" to replace spaces // This method also adds a double slash when the user enters a single (necessary for java opening the file) if (attributeName.startsWith("report=")) { File reportFileLocation = new File(attributeName.substring(7).replace("$", " ").replace("\\", "\\\\")); entry.setReport(reportFileLocation); //***Now create the windows necessary to hold the pdf in view //build a controller SwingController controller = new SwingController(); //Used for each window that controls a pdf document SwingViewBuilder factory = new SwingViewBuilder(controller); // Build a SwingViewFactory configured with the controller JPanel viewerComponentPanel = new JPanel(); //the panel for which the frame sits on; viewerComponentPanel = factory.buildViewerPanel(); // add copy keyboard command ComponentKeyBinding.install(controller, viewerComponentPanel); // add interactive mouse link annotation support via callback controller.getDocumentViewController().setAnnotationCallback(new org.icepdf.ri.common.MyAnnotationCallback(controller.getDocumentViewController())); //Use the factory to build a JPanel that is pre-configured //with a complete, active Viewer UI. // Open a PDF document (frame is no yet visible, but the document is opened and ready for interaction) controller.openDocument(reportFileLocation.toString()); //Make it continuous view controller.setPageFitMode(org.icepdf.core.views.DocumentViewController.PAGE_FIT_WINDOW_WIDTH, false); controller.setPageViewMode(DocumentViewControllerImpl.ONE_COLUMN_VIEW, true); // Create a JFrame to display the panel in JFrame window = new JFrame("Report for " + entryName); //the windows created for the attribute, these are used to show the report. They are class variables because we need to toggle visibility from different methods window.getContentPane().add(viewerComponentPanel); window.pack(); window.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); //we only want to hide the window, not close it. window.setSize(new Dimension(800,600)); //The Frame and controller are the only aspects of the report frame that need to be modified from elsewhere in the program (particularly AttributeCell, so they become part of the hashmap entry.setReportFrame(window); entry.setReportController(controller); //Now add the outline and bookmark items to the hash map OutlineItem entryItem = null; Outlines entryOutlines = controller.getDocument().getCatalog().getOutlines(); if (entryOutlines != null) { entryItem = entryOutlines.getRootOutlineItem(); } if (entryItem != null) { OutlineItemTreeNode outlineItemTreeNode = new OutlineItemTreeNode(entryItem); outlineItemTreeNode.getChildCount(); // Added this line Enumeration depthFirst = outlineItemTreeNode.depthFirstEnumeration(); // find the node you need } entry.setOutlineItem(entryItem); //entry.map.put("Outlines", entryOutlines); //this doesn't need to be added, it is only the items that are needed for locating } else { AttributeCell attributeCell = pane.getAttributeCell(attributeName); if (attributeCell == null) { throw new IOException("attribute " + attributeName + " not found"); } AttributeDomain domain = attributeCell.getDomain(); AttributeValue value; if (domain.getType() == AttributeDomain.DISCRETE) { String name = scanReader.scanString("%S"); value = new AttributeValue(name, domain); } else { // type == AttributeDomain.CONTINUOUS double x = scanReader.scanDouble(); value = new AttributeValue(x, domain); } entry.map.put(attributeName, value); } } return entry; }
5f05fba6-2500-447b-99bd-725421fd25bc
2
protected void updateTimeFields() { long timeAsSeconds = getTimeAsSeconds(); // Store the starting seconds minutes and hours so that we can compare // this to the new minutes seconds and hours to set the hasChanged // variable long startS = seconds, startM = minutes, startH = hours; seconds = timeAsSeconds % 60; minutes = ((getTimeAsSeconds() / 60) % 60); hours = timeAsSeconds / 3600; // Change the boolean hasChanged to true if any of the starting values // are different to the new times we calculated hasChanged = startS != seconds || startM != minutes || startH != hours; }
e2c617ae-40bf-45cc-b008-d0bfd6f3b0dd
3
public boolean validate(String str) throws Exception { str = str.toLowerCase(); if (isNameExists(str)) { return searchingFile(str).equals("true"); } else { String pattern = "^[a-z][a-z0-9\\.,\\-_]{5,31}$"; // Create a Pattern object Pattern r = Pattern.compile(pattern); // Now create matcher object. Matcher m = r.matcher(str); if (m.find()) { String s = sk.readStatus(str); if (s.contains(":200,")) { System.out.println("имени " + str + " еще нет"); addRecord(str, false); return false; } else { System.out.println("имя " + str + " уже есть"); addRecord(str, true); return true; } } else { System.out.println("имя " + str + " не подходит"); //addRecord(str,false); return false; } } }
13392422-7753-43f9-8ea3-95921d5bba84
9
private void discoverDevices() { tvDiscoveryService = TvDiscoveryService.getInstance(swingPlatform); // discovering devices can take time, so do it in a thread new Thread(new Runnable() { public void run() { showProgressDialog(resourceBundle.getString("progress.discoveringDevices")); devices = tvDiscoveryService.discoverTvs(); deviceList.removeAllItems(); deviceList.addItem(resourceBundle.getString("devices.select")); // no selection option for(TvDevice device:devices) { deviceList.addItem(device.getName()+" / "+device.getAddress().getHostName()); } Properties properties = loadProperties(); // add the manual IPs to the device list for(TvDevice device:manualDevices) { boolean alreadyFound = false; for(TvDevice foundDevice:devices) { if (foundDevice.getAddress().getHostAddress().equals(device.getAddress().getHostAddress())) { alreadyFound = true; break; } } if (!alreadyFound) { deviceList.addItem(device.getAddress().getHostName()); devices.add(device); } } deviceList.invalidate(); hideProgressDialog(); // automatically connect to the last connected device if (startup) { startup = false; String lastDevice = properties.getProperty(PROPERTY_LAST_DEVICE); if (lastDevice!=null) { int pos = 1; for(TvDevice device:devices) { if (device.getAddress().getHostAddress().equals(lastDevice)) { deviceList.setSelectedIndex(pos); break; } pos++; } } } } }).start(); }
61f2150d-f7bb-4eb4-af15-15aeb3b41b7a
0
protected void buildAttributes(Node node, StringBuffer buf) { // Iterator it = node.getAttributeKeys(); // if (it != null) { // while (it.hasNext()) { // String key = (String) it.next(); // Object value = node.getAttribute(key); // buf.append(" ").append(key).append("=\"").append(escapeXMLAttribute(value.toString())).append("\""); // } // end while // } // end if } // end method buildAttributes
de9bdea7-5964-4615-8d0b-d9db57bfd83d
4
public Recipe openFile(File f) { fileType = checkFileType(f); Debug.print("File type: " + fileType); if (fileType.equals("promash")) { PromashImport imp = new PromashImport(); myRecipe = imp.readRecipe(f); } else if (fileType.equals("sb") || fileType.equals("qbrew")) { ImportXml imp = new ImportXml(f.toString(), "recipe"); myRecipe = imp.handler.getRecipe(); } else if (fileType.equals("beerxml")) { ImportXml imp = new ImportXml(f.toString(), "beerXML"); myRecipe = imp.beerXmlHandler.getRecipe(); recipes = imp.beerXmlHandler.getRecipes(); } else { // unrecognized type, just return a new blank recipe myRecipe = new Recipe(); } return myRecipe; }
7e3f2c34-cbde-4b72-a403-6e697a6f6959
5
@Override public void initResources() { playfield = new PlayField(); // Создание спрайт групп firstBallGroup = new SpriteGroup("firstBalls"); secondBallGroup = new SpriteGroup("secondBalls"); thirdBallGroup = new SpriteGroup("thirdBalls"); playfield.addGroup(firstBallGroup); playfield.addGroup(secondBallGroup); playfield.addGroup(thirdBallGroup); // Создание спрайтов BufferedImage ballImage = getImage("img/ball.png"); Sprite ball1 = new Sprite(ballImage, firstPoint.x, firstPoint.y); Sprite ball2 = new Sprite(ballImage, secondPoint.x, secondPoint.y); Sprite ball3 = null; if (thirdPoint != null) { ball3 = new Sprite(ballImage, thirdPoint.x, thirdPoint.y); } //Заполняем буфер Ball ballElement1 = new Ball(table); ballElement1.setWeight(firstWeigt); Ball ballElement2 = new Ball(table); ballElement2.setWeight(secondWeigt); Ball ballElement3 = new Ball(table); ballElement3.setWeight(thirdWeigt); table.addPair(ballElement1, ball1); table.addPair(ballElement2, ball2); if (thirdPoint != null) { table.addPair(ballElement3, ball3); } ballElement1.addCollisionHandleEndListener(this); ball1.setSpeed(firstVector.x(), firstVector.y()); ball2.setSpeed(secondVector.x(), secondVector.y()); if (thirdPoint != null) { ball3.setSpeed(thirdVector.x(), thirdVector.y()); } // Добавление в спрайт группу и установка коллизии firstBallGroup.add(ball1); secondBallGroup.add(ball2); if (thirdPoint != null) { thirdBallGroup.add(ball3); } CollisionHandler handler = new CollisionHandler(table); handler.addHandleEndListener(this); collision = new CollisionObjectWithObject(); collision.addSpritesCollidedListener(handler); playfield.addCollisionGroup(firstBallGroup, secondBallGroup, collision); clone1 = ballElement1.clone(); clone2 = ballElement2.clone(); if (thirdPoint != null) { playfield.addCollisionGroup(firstBallGroup, thirdBallGroup, collision); playfield.addCollisionGroup(thirdBallGroup, secondBallGroup, collision); clone3 = ballElement3.clone(); } }
f389fa92-0013-44fb-b9e1-3a136b142150
7
public List<Chromosome> select(List<Chromosome> population) { List<Double> absoluteFitnesses = new LinkedList<Double>(); List<Double> proportionalFitnesses = new LinkedList<Double>(); double totalFitness = 0; for (Chromosome i : population) { double fitness = Math.abs(f.calculate(d.decode(i))); totalFitness += fitness; absoluteFitnesses.add(fitness); } List<Chromosome> parents = new LinkedList<Chromosome>(); if (totalFitness == 0) { // throw new ArithmeticException("" // + "Sum fitness is zero in RouletteParentSelection, " // + "so cannot determine proportional fitness."); parents.add(population.get(0)); parents.add(population.get(1)); return parents; } for (Double i : absoluteFitnesses) proportionalFitnesses.add(i / totalFitness); while (parents.size() < 2) { double p = Math.random(); for (int i = 0; i < population.size(); i += 1) if (p < proportionalFitnesses.get(i) && parents.size() < 2) parents.add(population.get(i)); } return parents; }
02876af8-4c56-4caa-913a-09ade7008e62
3
void resetColorsAndFonts () { super.resetColorsAndFonts (); Color oldColor = selectionForegroundColor; selectionForegroundColor = null; setSelectionForeground (); if (oldColor != null) oldColor.dispose(); oldColor = selectionBackgroundColor; selectionBackgroundColor = null; setSelectionBackground (); if (oldColor != null) oldColor.dispose(); Font oldFont = itemFont; itemFont = null; setItemFont (); if (oldFont != null) oldFont.dispose(); }
30ad7422-b51d-44e9-8589-150abe1f47dc
3
public boolean appliesToCurrentEnvironment() { if (this.rules == null) return true; Rule.Action lastAction = Rule.Action.DISALLOW; for (Rule rule : this.rules) { Rule.Action action = rule.getAppliedAction(); if (action != null) lastAction = action; } return lastAction == Rule.Action.ALLOW; }
9f3787f8-cebb-4f9a-b820-4f784d1a4cb9
5
public static void generateGradeCSV(String courseID, String actName, String path, String name) { ResultSet res = GradeAccess.accessGrades(courseID, actName); String s = ""; int x = 0; try { while(res.next()) { if(x == res.getInt(1)) { s += "," + res.getFloat(2); } else { if(x == 0) s += res.getInt(1) + "," + res.getFloat(2); else s += "\n" + res.getInt(1) + "," + res.getFloat(2); } x = res.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } try { PrintWriter out = new PrintWriter(path + "/" + name); out.write(s); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } }
6e04406c-4d20-476f-91b6-d10f947d4504
0
public HumanFirstPane(PumpingLemma l, String title) { super(l, title); l.setFirstPlayer(PumpingLemma.HUMAN); }
a19a3056-5ed1-4396-9964-6466b9448602
5
public void setTextFieldValues() { List<User> theUsers = users.getUsers(); tasks = new AccessTasks(); tasks.getTasks(); theTask = null; if(tasks != null && item != null) { theTask = tasks.getTask(Integer.parseInt(item.getText())); } if(theTask != null) { StaticWindowMethods.populateAssignedToDropDown(cboxAssignedTo, theUsers); cboxAssignedTo.select(cboxAssignedTo.indexOf(theTask.getAssignedTo().getUserName())); if (StatusCode.values().length > 0) { StaticWindowMethods.populateStatusDropDown(cboxStatus); theTask.getStatus(); cboxStatus.select(cboxStatus.indexOf(StatusCode.valueOf(theTask.getStatus().toString()).toString())); } if (PriorityCode.values().length > 0) { StaticWindowMethods.populatePriorityDropDown(cboxPriority); cboxPriority.select(cboxPriority.indexOf(PriorityCode.valueOf(theTask.getPriority().toString()).toString())); } lblCreatedByField.setText(theTask.getCreator().getUserName()); lblCreatedDateField.setText(FormatDate.formatDate(theTask.getCreatedDate())); txtTitle.setText(theTask.getTitle()); txtTimeEstimate.setText(""+theTask.getTimeEstimate()); txtTimeSpent.setText(""+theTask.getTimeSpent()); txtDescription.setText(theTask.getDescription()); txtComments.setText(theTask.getComments()); dueDate.setDay(theTask.getDueDate().get(Calendar.DAY_OF_MONTH)); dueDate.setMonth(theTask.getDueDate().get(Calendar.MONTH)); dueDate.setYear(theTask.getDueDate().get(Calendar.YEAR)); } }
da1ba30a-e39b-462b-b0bd-7e0b03816840
4
@SuppressWarnings("unchecked") public E[] toArray() { if (root == null) return null; E[] array = (E[]) Array.newInstance(root.data.getClass(), size); Stack<Node> stack = new Stack<Node>(); Node node = root; int index = 0; while (true) { if (node != null) { stack.push(node); node = node.left; } else { node = stack.pop(); array[index++] = node.data; if (index == size) break; node = node.right; } } return array; }
89ebc29b-81be-4538-982e-813f6a08f9da
3
private void stopIfDone() { if(isDone() && !(preStop || preStart)) { mm.stopMinigame(this); } }
cce5293e-08c7-4f74-a6ee-a72359348eeb
0
public UndoController() { undoStack = new SizedStack<>(25); redoStack = new SizedStack<>(25); }
1a27696b-7a35-44c2-9006-feb62d3bb9ee
4
public void upgradeTables() { // Add blocks_built into LOGIN if (_sqLite.isTable("login")) { try { _sqLite.query("ALTER TABLE login ADD COLUMN blocks_placed INT;"); _log.info("[Statistics] Table LOGIN upgraded - column blocks_placed added"); } catch (SQLException e) { } } // Add blocks_broken into LOGIN if (_sqLite.isTable("login")) { try { _sqLite.query("ALTER TABLE login ADD COLUMN blocks_broken INT;"); _log.info("[Statistics] Table LOGIN upgraded - column blocks_broken added"); } catch (SQLException e) { } } }
217a5154-996d-465d-ad8f-339ced0661c5
8
public static void main(String[] args) { int op=0; do{ System.out.println("1- Agregar Doctor"); System.out.println("2- Agregar Paciente"); System.out.println("3- Mantenimiento de Citas"); System.out.println("4- Reportes"); System.out.println("5- Salir"); System.out.println("Escoja opcion: "); try{ op = lea.nextInt(); switch(op){ case 1: addDoctor(); break; case 2: addPaciente(); break; case 3: citas(); break; case 4: reportes(); break; } } catch(IllegalArgumentException e){ System.out.println("Especialidad Incorrecta"); } catch(InputMismatchException e){ System.out.println("Ingrese un dato numerico"); lea.next(); } catch(Exception e){ System.out.println("Error: " + e.getMessage()); } }while(op!=5); }
4db6c14f-01af-4eb5-9f1e-9cb9265f8a3d
0
@Override public Employee getById(Integer id) { return map.get(id); }
531b0785-2f07-43ea-b5ea-432972c1ae62
9
public void input(){ if(Mouse.isGrabbed()){ pos.addXRot(-Mouse.getDY()*mouseSensivity); pos.addYRot(Mouse.getDX()*mouseSensivity); } if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)){ speed = 0.25f; } if (!Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)){ speed = 0.05f; } if (Keyboard.isKeyDown(Keyboard.KEY_W)){ pos.forward(speed); } if(Keyboard.isKeyDown(Keyboard.KEY_S)){ pos.backward(speed); } if(Keyboard.isKeyDown(Keyboard.KEY_A)){ pos.strafeL(speed); } if(Keyboard.isKeyDown(Keyboard.KEY_D)){ pos.strafeR(speed); } if(Keyboard.isKeyDown(Keyboard.KEY_Z)){ pos.down(speed); } if(Keyboard.isKeyDown(Keyboard.KEY_Q)){ pos.up(speed); } }
d5c34e13-5cc0-4f1e-9a08-902e5198b84d
9
boolean isCursorOnTopOf(int xCursor, int yCursor, int minRadius, Atom competitor) { // XIE: the following should be used to prevent dx2 or dy2 > Integer.MAX_VALUE if (screenX < 0 || screenX > SCREEN_SIZE.width || screenY < 0 || screenY > SCREEN_SIZE.height) return false; int r = screenDiameter / 2; if (r < minRadius) r = minRadius; int r2 = r * r; int dx = screenX - xCursor; int dx2 = dx * dx; if (dx2 > r2) return false; int dy = screenY - yCursor; int dy2 = dy * dy; int dz2 = r2 - (dx2 + dy2); if (dz2 < 0) return false; if (competitor == null) return true; int z = screenZ; int zCompetitor = competitor.screenZ; int rCompetitor = competitor.screenDiameter / 2; if (z < zCompetitor - rCompetitor) return true; int dxCompetitor = competitor.screenX - xCursor; int dx2Competitor = dxCompetitor * dxCompetitor; int dyCompetitor = competitor.screenY - yCursor; int dy2Competitor = dyCompetitor * dyCompetitor; int r2Competitor = rCompetitor * rCompetitor; int dz2Competitor = r2Competitor - (dx2Competitor + dy2Competitor); return (z - Math.sqrt(dz2) < zCompetitor - Math.sqrt(dz2Competitor)); }
3f567606-4c9d-4c34-a7ba-5657309dad5d
7
public static void main(String[] args) { String encoding = "UTF-8"; int maxlines = 100; BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream("/bigfile.txt"), encoding)); int count = 0; for (String line; (line = reader.readLine()) != null;) { if (count++ % maxlines == 0) { if(writer!=null) writer.close(); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/smallfile" + (count / maxlines) + ".txt"), encoding)); } writer.write(line); writer.newLine(); } }catch (Exception e) { } finally { try { if(writer!=null) writer.close(); if(reader!=null) reader.close(); }catch(Exception e){} } }
07cc8393-fa1a-4f5c-bcc7-8b77520c4b70
1
public boolean step() { // controller.step(); boolean worked = false; if (treePanel.next()){ stepAction.setEnabled(false); worked = true; } treePanel.repaint(); return worked; }
cde4990a-d6c1-40b4-8e3f-08be2e1cffa8
9
public void setEndPoints(int x1, int x2, int y1, int y2) { colourize(); switch (type) { case LINE: setStartingPoint(new Point(x1,y1)); setEndPoint(new Point(x2,y2)); break; case CIRCLE: case SQUARE: if (x2>=x1 && y2>=y1) { setStartingPoint(new Point(x1, y1)); int side = Math.min(x2-x1, y2-y1); setEndPoint(new Point(x1 + side, y1 + side)); } else if (x1>x2 && y2>y1) { int side = Math.min(x1-x2, y2-y1); setStartingPoint(new Point(x1-side,y1)); setEndPoint(new Point(x1, y1+side)); } else if (x2>x1 && y1>y2) { int side = Math.min(x2-x1, y1-y2); setStartingPoint(new Point(x1,y1 - side)); setEndPoint(new Point(x1 + side, y1)); } else { //x1>=x2 && y1>=y2 int side = Math.min(x1 - x2, y1 - y2); setStartingPoint(new Point(x1 - side, y1 - side)); setEndPoint(new Point(x1, y1)); } break; default: setStartingPoint(new Point(Math.min(x1, x2), Math.min(y1, y2))); setEndPoint(new Point(Math.max(x2, x1), Math.max(y2, y1))); break; } }
a105b0a8-a03c-4218-981f-da5821a9fe4a
8
protected Item getPoison(MOB mob) { if(mob==null) return null; if(mob.location()==null) return null; for(int i=0;i<mob.location().numItems();i++) { final Item I=mob.location().getItem(i); if((I!=null) &&(I instanceof Scroll) &&(((SpellHolder)I).getSpells()!=null) &&(((SpellHolder)I).getSpells().size()>0) &&(I.usesRemaining()>0)) return I; } return null; }
6bd0c9bb-7e09-482f-93a9-6223ac313819
8
void classification() { int pixels[][] = this.pixels; int width = pixels.length; int height = pixels[0].length; // convert to indexed color for (int x = width; x-- > 0;) { for (int y = height; y-- > 0;) { int pixel = pixels[x][y]; int red = (pixel >> 16) & 0xFF; int green = (pixel >> 8) & 0xFF; int blue = (pixel >> 0) & 0xFF; // a hard limit on the number of nodes in the tree if (nodes > MAX_NODES) { System.out.println("pruning"); root.pruneLevel(); --depth; } // walk the tree to depth, increasing the // number_pixels count for each node Node node = root; for (int level = 1; level <= depth; ++level) { int id = (((red > node.mid_red ? 1 : 0) << 0) | ((green > node.mid_green ? 1 : 0) << 1) | ((blue > node.mid_blue ? 1 : 0) << 2)); if (node.child[id] == null) { new Node(node, id, level); } node = node.child[id]; node.number_pixels += SHIFT[level]; } ++node.unique; node.total_red += red; node.total_green += green; node.total_blue += blue; } } }
e39986e3-d57e-428f-be01-a1fb87ce6864
3
public static Font openFont(String name) { if(fonts.containsKey(name)) return (Font) fonts.get(name); Font font = null; InputStream is = ClassLoader.getSystemResourceAsStream("org/analyse/core/gui/fonts/" + name); if (is == null) { System.err.println("Utilisation de la Fonte impossible : " + name + " ..."); System.exit(1); } try { font = Font.createFont(Font.TRUETYPE_FONT, is); } catch (Exception e) { System.err.println("Problème lors de la création de la fonte : " + name + " ..." ); System.exit(1); } return font; }
472bdaa6-3f69-4298-890c-7532b19a9419
0
public void setRoom(int room) { this.room = room; }
384bb5b6-bb5b-430f-b6a6-30c827fe8d37
4
private void currentCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_currentCheckActionPerformed serverTable.clearSelection(); if(currentCheck.isSelected()){ try { ServicioTablespace st = new ServicioTablespace(conexion.user,conexion.pass,conexion.ip,conexion.port,conexion.db); ArrayList<String> lista = st.listarTablas(conexion.db); for(int i=0;i<lista.size();i++){ ((DefaultTableModel)tablespaceTable.getModel()).addRow(new Object[]{lista.get(i)}); } } catch (GlobalException | NoDataException ex) { Logger.getLogger(ConectadoGUI.class.getName()).log(Level.SEVERE, null, ex); } } else{ serverTable.clearSelection(); for(int i=0;i<((DefaultTableModel)tablespaceTable.getModel()).getRowCount();){ ((DefaultTableModel)tablespaceTable.getModel()).removeRow(i); } } }//GEN-LAST:event_currentCheckActionPerformed
0b292ff5-3a70-40bb-9782-4ae6225e85cf
8
public static String readLine(ByteBuffer buf) { boolean completed = false; buf.mark(); while (buf.hasRemaining() && !completed) { byte b = buf.get(); if (b == '\r') { if(buf.hasRemaining() && buf.get() == '\n'){ completed = true; } } } if(!completed){ return null; } int limit = buf.position(); buf.reset(); int length = limit - buf.position(); byte[] tmp = new byte[length]; buf.get(tmp, 0, length); try { String line = new String(tmp, "US-ASCII"); if (log.isLoggable(Level.FINEST)) { log.finest(line.trim()); } return line; } catch (UnsupportedEncodingException e) { ; } return null; }
adcfe577-5a9f-4c23-a0b1-87fdf68e77f4
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ThreadTimingBean other = (ThreadTimingBean) obj; if (atomicId != other.atomicId) return false; if (end != other.end) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (start != other.start) return false; return true; }
abadc542-ce04-4269-a87f-a04b3239094b
4
private static boolean canProcess(String line){ boolean processBit = true; boolean foundAnnotationBit = false; if (line.contains("None")) processBit = true; else{ for(String lines: ARGS){ if(line.contains(lines)) foundAnnotationBit = true; } if(foundAnnotationBit){ processBit = true; foundAnnotationBit = false; }else processBit = false; } return processBit; }
b545a0a8-2c1f-4455-aedc-4107c7975935
8
public static String[] getPercents() { int a = 0; String[] s1 = new String[100]; int i = Casino.conf.getInt("settings.SevenChance"); while(i>0) { s1[a] = "➐"; i--; a++; } i = Casino.conf.getInt("settings.HeartChance"); while(i>0) { s1[a] = "❤"; i--; a++; } i = Casino.conf.getInt("settings.CheckChance"); while(i>0) { s1[a] = "✔"; i--; a++; } i = Casino.conf.getInt("settings.KnightChance"); while(i>0) { s1[a] = "♚"; i--; a++; } i = Casino.conf.getInt("settings.UpTriangleChance"); while(i>0) { s1[a] = "▲"; i--; a++; } i = Casino.conf.getInt("settings.DownTriangleChance"); while(i>0) { s1[a] = "▼"; i--; a++; } i = Casino.conf.getInt("settings.CircleChance"); while(i>0) { s1[a] = "●"; i--; a++; } i = Casino.conf.getInt("settings.SquareChance"); while(i>0) { s1[a] = "▢"; i--; a++; } return s1; }
45427024-33ae-4631-bca5-2ebd5e2ffcac
6
@Override public void validate() { if (dailybdgt == null) { addActionError("Please Enter Daily Budget"); } if (deliverytype == null) { addActionError("Please Select Delivery Type"); } if (campaignname == null) { addActionError("Please Enter Campaign Name"); } if (startdate == null) { addActionError("Please Select Start Date"); } if (enddate == null) { addActionError("Please Select End Date"); } else { if (startdate.after(enddate)) { addActionError("Please Choose End date After Start Date "); } } }
db1809fb-11a4-447d-a297-c92e41276241
5
public static <TT> TypeAdapterFactory newFactoryForMultipleTypes(final Class<TT> base, final Class<? extends TT> sub, final TypeAdapter<? super TT> typeAdapter) { return new TypeAdapterFactory() { @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { Class<? super T> rawType = typeToken.getRawType(); return (rawType == base || rawType == sub) ? (TypeAdapter<T>) typeAdapter : null; } @Override public String toString() { return "Factory[type=" + base.getName() + "+" + sub.getName() + ",adapter=" + typeAdapter + "]"; } }; }
826c95a4-bff3-4ec8-9592-529e50e5c9ee
8
private void BackspaceButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BackspaceButtonActionPerformed if (FocusOwnerIndex == 1) { if (NumberField1.getCaretPosition() != 0) { // only do something if the caret is not the at the beginning int tmpcaretpos = NumberField1.getCaretPosition(); NumberField1.setText(NumberField1.getText().substring(0, NumberField1.getCaretPosition() - 1) + NumberField1.getText().substring(NumberField1.getCaretPosition(), NumberField1.getText().length())); NumberField1.setCaretPosition(tmpcaretpos - 1); } } if (FocusOwnerIndex == 2) { if (NumberField2.getCaretPosition() != 0) { // only do something if the caret is not the at the beginning int tmpcaretpos = NumberField2.getCaretPosition(); NumberField2.setText(NumberField2.getText().substring(0, NumberField2.getCaretPosition() - 1) + NumberField2.getText().substring(NumberField2.getCaretPosition(), NumberField2.getText().length())); NumberField2.setCaretPosition(tmpcaretpos - 1); } } if (FocusOwnerIndex == 3) { if (NumberField3.getCaretPosition() != 0) { // only do something if the caret is not the at the beginning int tmpcaretpos = NumberField3.getCaretPosition(); NumberField3.setText(NumberField3.getText().substring(0, NumberField3.getCaretPosition() - 1) + NumberField3.getText().substring(NumberField3.getCaretPosition(), NumberField3.getText().length())); NumberField3.setCaretPosition(tmpcaretpos - 1); } } if (FocusOwnerIndex == 4) { if (NumberField4.getCaretPosition() != 0) { // only do something if the caret is not the at the beginning int tmpcaretpos = NumberField4.getCaretPosition(); NumberField4.setText(NumberField4.getText().substring(0, NumberField4.getCaretPosition() - 1) + NumberField4.getText().substring(NumberField4.getCaretPosition(), NumberField4.getText().length())); NumberField4.setCaretPosition(tmpcaretpos - 1); } } Validate(); }//GEN-LAST:event_BackspaceButtonActionPerformed
6c3e5fb8-95f3-451d-bb3b-a4bcdfe59621
4
private boolean checkIfOutOfRange(int x, int y) { return x < -1000000 || y < -1000000 || x > 1000000 || y > 1000000 ? true : false; }
cdb15ef5-5f9e-426b-8769-cf53b67449db
0
public static void unlockDoor(int roomId) { keyRequired[roomId-1] = 0; }
130a84c7-e985-420e-bdb2-f85c61a8387e
0
public MoveHandler(boolean pendown, boolean forward) { this.pendown = pendown; this.forward = forward; }
a080e50b-f7c1-4238-8cfd-341a452d6c38
6
@Override public boolean halt(Event lastEvent, OurSim ourSim) { boolean halt = true; List<Job> finishedJobsList = new LinkedList<Job>(); for (ActiveEntity entity : ourSim.getGrid().getAllObjects()) { if (entity instanceof Broker) { Broker broker = (Broker) entity; List<Job> jobs = broker.getJobs(); int currentlyFinished = 0; for (Job job : jobs) { if (job.getState().equals(ExecutionState.FINISHED)) { currentlyFinished++; finishedJobsList.add(job); } } halt &= currentlyFinished >= finishedJobs; } } if (halt) { for (Job job : finishedJobsList) { System.out.println(job.getEndTime()); } } return halt; }
f7c05a34-ea18-4aad-8ab6-403b8aed0326
1
public static void main(String[] args) { try { Files.createDirectories(Paths.get("/home/xander/test")); Path file = Paths.get("/home/xander/test/test.txt"); // no need to check prior to deletion Files.deleteIfExists(file); Files.createFile(file); Files.delete(file); // will fall if file does not exist Files.createFile(file); Path target = Paths.get("/home/xander/test/test.txt"); //old school copy //Files.copy(file, target); // no exception although target already exists Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING); //moving a file is easy (in jdk1.6 copy+delete or use renameTo) // Files.move(target, file, StandardCopyOption.ATOMIC_MOVE); //read-write with one line Files.write(file, Arrays.asList("Foo", "Bar"), Charset.defaultCharset()); List<String> lines = Files.readAllLines(file, Charset.defaultCharset()); System.out.println(lines); //it has absolutely verified that file does not exist System.out.println(Files.notExists(file, LinkOption.NOFOLLOW_LINKS)); //is not the same. True - exists, false - does not exist or its existence cannot be determined System.out.println(Files.exists(file, LinkOption.NOFOLLOW_LINKS)); } catch (IOException e) { e.printStackTrace(); } }
76dc481a-1aab-4738-98c2-a40152c96a9c
1
public final Image image(JPanel panel) { Image image = panel.getToolkit().createImage(ClassLoader.getSystemResource(url)); MediaTracker tracker = new MediaTracker(panel); tracker.addImage(image, 1, width, height); try { tracker.waitForAll(); } catch (InterruptedException e) { throw new RuntimeException(e); } return image; }
bcf2495f-176b-4ad2-9f53-9879076dd9ad
3
private void checkForPeakX(double x) { if (isUpPeakX) { if (x < lastX) { peakX = lastX; isUpPeakX = false; } } else { if (x > lastX) { peakX = lastX; isUpPeakX = true; } } lastX = x; }
92b56c59-a12d-48f8-bef1-963ba8fb3851
8
private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) { Map<String, BoundField> result = new LinkedHashMap<String, BoundField>(); if (raw.isInterface()) { return result; } Type declaredType = type.getType(); while (raw != Object.class) { Field[] fields = raw.getDeclaredFields(); for (Field field : fields) { boolean serialize = excludeField(field, true); boolean deserialize = excludeField(field, false); if (!serialize && !deserialize) { continue; } field.setAccessible(true); Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType()); BoundField boundField = createBoundField(context, field, getFieldName(field), TypeToken.get(fieldType), serialize, deserialize); BoundField previous = result.put(boundField.name, boundField); if (previous != null) { throw new IllegalArgumentException(declaredType + " declares multiple JSON fields named " + previous.name); } } type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass())); raw = type.getRawType(); } return result; }
d51750d2-f939-481f-b52e-ace83596a34f
8
private static Image enhance(Image image, int[]histogram) { ImageData imageData = image.getImageData(); // Calculate cumulative histogram int[] cumulativeHistogram = new int[256]; for (int i = 0; i < cumulativeHistogram.length; i++) {// height if (i == 0) cumulativeHistogram[i] = histogram[0]; else cumulativeHistogram[i] = histogram[i] + cumulativeHistogram[i - 1]; // System.out.println(i+":\t"+histogram1[i]+"\t\t"+cumulativeHistogram[i]); } // Enhance existing image int height = imageData.height; int width = imageData.width; int r = 0; // Line by Line for (int i = 0; i < height; i++) {// height for (int j = 0; j < width; j++) {// width // byte gray = imageData.data[c++]; // gray &= 0xFF;// Calculate Gray // System.out.print(gray + "="); int pixel = imageData.getPixel(j, i); switch (imageData.depth) { case 32: int A = pixel >> 32; int R = pixel >> 16 & 0xFF; int G = pixel >> 8 & 0xFF; int B = pixel & 0xFF; pixel = (int) (0.299 * R + 0.587 * G + 0.114 * B); break; case 24: R = pixel >> 16; G = pixel >> 8 & 0xFF; B = pixel & 0xFF; pixel = (int) (0.299 * R + 0.587 * G + 0.114 * B);// rgb -> gray break; } if (DEBUG) System.out.print(pixel + "\t"); int cdf = cumulativeHistogram[pixel]; int hv = Math.round((cdf - cumulativeHistogram[0]) * 255 / (height * width - cumulativeHistogram[0])); imageData.setPixel(j, i, hv); // newData[c++]=(byte)hv; // System.out.print(gray+","+hv+"\t|\t");///j+", "+i+": "+gray+" -> "+ } if (DEBUG) System.out.println(); } // Create new image Image image2 = new Image(image.getDevice(), imageData); /*boolean useTempFile = false; if (useTempFile) { ImageLoader loader = new ImageLoader(); loader.data = new ImageData[] { imageData }; String newImageName = "aaa"; loader.save(IMAGE_PATH + newImageName, SWT.IMAGE_JPEG); InputStream is = null; try { is = new FileInputStream(IMAGE_PATH + newImageName); } catch (FileNotFoundException e) { throw new RuntimeException(e); } // is = HelloWorld.class.getResourceAsStream("Fig1.jpg"); // ImageData[] data = loader.load(is); image2 = new Image(image.getDevice(), is); }*/ return image2; }
d2411091-01e3-4f8c-8e0a-04b23fe52f8a
5
private void processDeleteMaster(Sim_event ev) { if (ev == null) { return; } Object[] obj = (Object[]) ev.get_data(); if (obj == null) { System.out.println(super.get_name() + ".processDeleteMaster(): master file name is null"); return; } String name = (String) obj[0]; // get file name Integer resID = (Integer) obj[1]; // get resource id int msg = DataGridTags.CTLG_DELETE_MASTER_SUCCESSFUL; try { ArrayList list = (ArrayList) catalogueHash_.get(name); if (list.size() != 1) { msg = DataGridTags.CTLG_DELETE_MASTER_REPLICAS_EXIST; } else if (list.remove(resID) == false) { msg = DataGridTags.CTLG_DELETE_MASTER_DOESNT_EXIST; } else { catalogueHash_.remove(name); // remove from the catalogue attrHash_.remove(name); } } catch (Exception e) { msg = DataGridTags.CTLG_DELETE_MASTER_ERROR; } sendMessage(name, DataGridTags.CTLG_DELETE_MASTER_RESULT, msg, resID.intValue() ); }
406bf802-e52e-4098-a2fd-26cd676b5a3f
9
@SuppressWarnings("unchecked") public static EventWriter createEventWriter(EventEntry eventEntry){ Properties unisensProperties = UnisensProperties.getInstance().getProperties(); String readerClassName = unisensProperties.getProperty(Constants.EVENT_WRITER.replaceAll("format", eventEntry.getFileFormat().getFileFormatName().toLowerCase())); if(readerClassName != null){ try{ Class<EventWriter> readerClass = (Class<EventWriter>)Class.forName(readerClassName); Constructor<EventWriter> readerConstructor = readerClass.getConstructor(EventEntry.class); return (EventWriter)readerConstructor.newInstance(eventEntry); } catch (ClassNotFoundException e) { System.out.println("Class (" + readerClassName + ") could not be found!"); e.printStackTrace(); } catch (InstantiationException e) { System.out.println("Class (" + readerClassName + ") could not be instantiated!"); e.printStackTrace(); } catch (IllegalAccessException e) { System.out.println("Class (" + readerClassName + ") could not be accessed!"); e.printStackTrace(); } catch (ClassCastException ec) { ec.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return null; }
73545240-416f-42f5-9979-1dd82d54579e
5
@Override public void paintComponent(Graphics g) { int i = 0; Home home; super.paintComponent(g); { g.drawImage(this.image, 0, 110, getWidth(), getHeight(), null); this.sliderPiece.paintComponent(g); this.sliderValue.paintComponent(g); while (i < numberHome) { home = listHome.get(i); if ((sliderPiece.getMinimum() <= home.getPieceNumber()) && (sliderPiece.getMaximum() >= home.getPieceNumber()) && (sliderValue.getMinimum() <= home.getValue()) && (sliderValue.getMaximum() >= home.getValue())) { home.paintComponent(g); } i++; } } }
15eba24c-286f-4cf3-a168-01f5f7de0ba9
4
@Test public void test_insertions() { int m = 3; int n = 5; Matrix m1 = new MatrixArray(m,n); for(int i = 1; i <= m; i++){ for(int j = 1; j <= n; j++) m1.insert(i, j, (double)(i*j)); } for(int i = 1; i <= m; i++){ for(int j = 1; j <= n; j++) assertEquals(m1.get(i,j),(double)(i*j), 0.01); } }
c455d09b-245f-4289-bb49-e44359ff4dfa
4
public Grid(int width, int length) { frame.setLayout(new GridLayout(width, length)); grid = new JButton[width][length]; //initialise jbutton grid array for (int y = 0; y < length; y++) { for (int x = 0; x < width; x++) { grid[x][y] = new JButton("(" + x + "," + y + ")"); frame.add(grid[x][y]); //add button to grid grid[x][y].addActionListener(new ButtonListener(this,x,y,grid[x][y])); } } frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); shipsOnGrid = 0; gridArray = new Ship[width][length]; for (int i = 0; i < width; i++) { for (int j = 0; j < length; j++) { gridArray[i][j] = null; //set array values to 0 as default } } }
6ec17658-fdc8-416c-9980-f41b86ae5bea
0
@Override public String notation() { return this.from.toString() + "x" + this.to.toString(); }
08934e92-36c0-4af3-bf8d-6843e86f4752
1
public void discard() { dealer.discard(pile); player.discard(pile); info.update(deck); discardButton.setEnabled(false); hitButton.setEnabled(false); standButton.setEnabled(false); resetButton.setEnabled(true); if (player.getMoney() > 0) { betButton.setEnabled(true); } doubleButton.setEnabled(false); }
d45377ef-f845-41b6-9d6d-5eede63ebb18
1
protected DataAccessLayer(){ //ensure that the JDBC connector exists. try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Could not locate JDBC driver"); } //attempt database connection dBConnect(); }
0be366e3-94c9-4c0d-a4f1-2735a8ed0bee
7
public byte[] engineGenerateSeed(int numBytes) { if (DEBUG && debuglevel > 8) debug(">>> engineGenerateSeed()"); if (numBytes < 1) { if (DEBUG && debuglevel > 8) debug("<<< engineGenerateSeed()"); return new byte[0]; } byte[] result = new byte[numBytes]; this.engineNextBytes(result); if (DEBUG && debuglevel > 8) debug("<<< engineGenerateSeed()"); return result; }
0ec56381-aef1-4fca-b3c2-26b1fe39c5fd
4
private static int leapDays(Tm tm) { if (tm.getMonth() < 3) { return 0; } int year = tm.getYear(); return year % 4 == 0 && (year % 400 == 0 || year % 100 != 0) ? 1 : 0; }
7331fa5b-da1f-404a-ad31-4f7db8858b60
5
public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() >= 2) { zoomInAnimated(new Point(mouseCoords.x, mouseCoords.y)); } else if (e.getButton() == MouseEvent.BUTTON3 && e.getClickCount() >= 2) { zoomOutAnimated(new Point(mouseCoords.x, mouseCoords.y)); } else if (e.getButton() == MouseEvent.BUTTON2) { setCenterPosition(getCursorPosition()); repaint(); } }
79b4f983-f116-40ce-92fa-ef29fa3e18ee
0
@Test public void testTruncate_quotation() { String s = "It's ok to include \"quotation marks\" along with words."; Assert.assertEquals( "It's ok to include \"quotation marks\"…", _helper.truncate(s, 40) ); }
d9e97122-6daa-4ca2-a266-72a2ab328773
6
private void convertYCBCRtoRGB(double Y, double Cb, double Cr) { R = round(Y + (Cr - 128) * 1.402); G = round(Y - (Cb - 128) * 0.34414 - (Cr - 128) * 0.71414); B = round(Y + 1.772 * (Cb - 128)); R = R > 255 ? 255 : (R < 0 ? 0 : R); G = G > 255 ? 255 : (G < 0 ? 0 : G); B = B > 255 ? 255 : (B < 0 ? 0 : B); }
3142a554-1bbc-426a-bbdd-2650c01d2f23
9
public static Keyword computeVarianceOrStandardDeviation(ControlFrame frame, Keyword lastmove, boolean standardDeviationP) { { Proposition proposition = frame.proposition; Stella_Object listarg = (proposition.arguments.theArray)[0]; Stella_Object listskolem = Logic.argumentBoundTo(listarg); Stella_Object resultargg = (proposition.arguments.theArray)[1]; double sum = 0.0; double sum2 = 0.0; double x = 0.0; int numbercount = 0; lastmove = lastmove; if ((listskolem != null) && (!Logic.logicalCollectionP(listskolem))) { { System.out.println(); System.out.println("Non list appears in second argument to 'VARIANCE or STANDARD-DEVIATION'"); System.out.println(); } ; return (Logic.KWD_TERMINAL_FAILURE); } { List listvalue = Logic.assertedCollectionMembers(listskolem, true); if (listvalue.emptyP()) { return (Logic.KWD_TERMINAL_FAILURE); } { Stella_Object v = null; Cons iter000 = listvalue.theConsList; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { v = iter000.value; { Surrogate testValue000 = Stella_Object.safePrimaryType(v); if (Surrogate.subtypeOfIntegerP(testValue000)) { { IntegerWrapper v000 = ((IntegerWrapper)(v)); x = ((double)(v000.wrapperValue)); } } else if (Surrogate.subtypeOfFloatP(testValue000)) { { FloatWrapper v000 = ((FloatWrapper)(v)); x = v000.wrapperValue; } } else { ControlFrame.setFrameTruthValue(frame, Logic.UNKNOWN_TRUTH_VALUE); return (Logic.KWD_FAILURE); } } sum = sum + x; sum2 = sum2 + (x * x); numbercount = numbercount + 1; } } switch (numbercount) { case 0: return (Logic.KWD_TERMINAL_FAILURE); case 1: return (Logic.selectTestResult(Logic.bindArgumentToValueP(resultargg, FloatWrapper.wrapFloat(0.0), true), true, frame)); default: x = (sum2 - ((sum * sum) / numbercount)) / (numbercount - 1); if (standardDeviationP) { x = Math.sqrt(x); } return (Logic.selectTestResult(Logic.bindArgumentToValueP(resultargg, FloatWrapper.wrapFloat(x), true), true, frame)); } } } }
d9b66976-2cc6-4be6-a441-6b8941be21da
3
public void getChar() { try { if (position >= line.length()){ line = input.nextLine(); line = line + "\n"; position = 0; lineNumber++; // only a period on a line means eof if (".\n".equals(line)) eof = true; } current = line.charAt(position); position++; } catch (NoSuchElementException nsee){ eof = true; } }
fd07611c-1b7f-41d9-9ed4-acc69fb1dfc0
9
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.info("WANcostResummingServlet12h Got a GET..."); caches.reload(); link[][] linkArr = new link[caches.lSources.size()][caches.lDestinations.size()]; for (int i = 0; i < caches.lSources.size(); i++) for (int j = 0; j < caches.lDestinations.size(); j++) linkArr[i][j] = new link(); // load data younger than 12 hours Date currTime = new Date(); Date cutoffTime = new Date(currTime.getTime() - 12 * 3600l * 1000); Filter f = new Query.FilterPredicate("timestamp", FilterOperator.GREATER_THAN, cutoffTime); Query q = new Query("FAXcost6h").setFilter(f); String res=""; List<Entity> lRes = datastore.prepare(q).asList(FetchOptions.Builder.withLimit(10000).chunkSize(3000)); res+="results in last 12 h: "+ lRes.size()+"\n"; log.warning("results in last 3h : "+ lRes.size()); for (Entity result : lRes) { String s = (String) result.getProperty("source"); String d = (String) result.getProperty("destination"); int i = caches.lSources.indexOf(s); int j = caches.lDestinations.indexOf(d); if(i<0 || j<0) { log.warning(s+" "+d+" "+i+" "+j); continue; } linkArr[i][j].measurements++; if (result.getProperty("rate")==null) log.severe("rate is null"); else linkArr[i][j].sum += ((Double)result.getProperty("rate")).floatValue(); } log.info("putting new data"); List<Entity> lIns =new ArrayList<Entity>(); for (int i = 0; i < caches.lSources.size(); i++){ for (int j = 0; j < caches.lDestinations.size(); j++){ if (linkArr[i][j].getAvg()<0) continue; Entity result = new Entity("FAXcost12h"); result.setProperty("timestamp", currTime); result.setProperty("source", caches.lSources.get(i)); result.setProperty("destination", caches.lDestinations.get(j)); result.setUnindexedProperty("rate", linkArr[i][j].getAvg()); lIns.add(result); } } datastore.put(lIns); resp.getWriter().println(res); }
8e07b24a-82ac-4b9b-95e5-8770ceddbd92
2
boolean isSalesTaxApplicable(String sItem) { for(String sExmpItem : exemptedItems) if(sItem.contains(sExmpItem)) { return false; } return true; }
2c777826-d079-436e-86c6-b18c7f05a718
0
public ENCODE getEncode() { return encode; }
f79a3600-6126-498d-b6fc-89ddae7d5978
0
public int getCount() { return count; }
37a857f7-f21c-4fe9-bdee-e0b6c6187574
7
private static String getBrowserMessage() { if (UserAgentPermutation.isGecko()) { return "feels like a lizard"; } else if (UserAgentPermutation.isSafari()) { return "is out on the savannah"; } else if (UserAgentPermutation.isOpera()) { return "hits all the high notes"; } else if (UserAgentPermutation.isIe()) { String message = "is made by Microsoft "; if (UserAgentPermutation.isIe6()) { message += "and is very old"; } else if (UserAgentPermutation.isIe8()) { message += "and might be slightly dated"; } else if (UserAgentPermutation.isIe9()) { message += " and is almost decent"; } else { message += " and is newer than me"; } return message; } else { // Unknown permutation return "doesn't like me"; } }
301497f5-dce3-4a17-930e-28ba64e421ab
9
public static boolean warnAboutFunctionShadowingSlotsP(MethodSlot function) { { Symbol name = function.slotName; if (name.symbolSlotOffset != Stella.NULL_INTEGER) { { Cons slots = Stella.NIL; { Module module = null; Iterator iter000 = Stella.allModules(); while (iter000.nextP()) { module = ((Module)(iter000.value)); { Slot slot = null; Iterator iter001 = Module.allSlots(module, true); Cons collect000 = null; while (iter001.nextP()) { slot = ((Slot)(iter001.value)); if (slot.slotName == name) { if (collect000 == null) { { collect000 = Cons.cons(slot, Stella.NIL); if (slots == Stella.NIL) { slots = collect000; } else { Cons.addConsToEndOfConsList(slots, collect000); } } } else { { collect000.rest = Cons.cons(slot, Stella.NIL); collect000 = collect000.rest; } } } } } } } if (((BooleanWrapper)(KeyValueList.dynamicSlotValue(function.dynamicSlots, Stella.SYM_STELLA_METHOD_MACROp, Stella.FALSE_WRAPPER))).wrapperValue) { { Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get(); try { Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true); Stella.signalTranslationWarning(); if (!(Stella.suppressWarningsP())) { Stella.printErrorContext(">> WARNING: ", Stella.STANDARD_WARNING); { Stella.STANDARD_WARNING.nativeStream.println(); Stella.STANDARD_WARNING.nativeStream.println(" Macro `" + Stella_Object.deUglifyParseTree(name) + "' shadows the following methods/slots:"); Stella.STANDARD_WARNING.nativeStream.println(" `" + Stella_Object.deUglifyParseTree(slots) + "'."); } ; } } finally { Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000); } } } else { { Object old$PrintreadablyP$001 = Stella.$PRINTREADABLYp$.get(); try { Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true); Stella.signalTranslationWarning(); if (!(Stella.suppressWarningsP())) { Stella.printErrorContext(">> WARNING: ", Stella.STANDARD_WARNING); { Stella.STANDARD_WARNING.nativeStream.println(); Stella.STANDARD_WARNING.nativeStream.println(" Function `" + Stella_Object.deUglifyParseTree(name) + "' shadows the following methods/slots:"); Stella.STANDARD_WARNING.nativeStream.println(" `" + Stella_Object.deUglifyParseTree(slots) + "'."); } ; } } finally { Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$001); } } } return (true); } } return (false); } }
eb8a5789-e808-434a-b813-7d326be6baf1
7
public Object nextContent() throws JSONException { char c; StringBuffer sb; do { c = next(); } while (Character.isWhitespace(c)); if (c == 0) { return null; } if (c == '<') { return XML.LT; } sb = new StringBuffer(); for (;;) { if (c == '<' || c == 0) { back(); return sb.toString().trim(); } if (c == '&') { sb.append(nextEntity(c)); } else { sb.append(c); } c = next(); } }
8e88f1f4-5957-49e9-aa35-f4a84872cf5e
4
public LinkedList<Bullet> applyAllUpgrades(String[] sprites) { LinkedList<Bullet> bullets = new LinkedList<Bullet>(); LinkedList<Bullet> newBullets = new LinkedList<Bullet>(); Bullet firstBullet = new Bullet(sprites, baseAim, 10); double centerx = rect.x + rect.width / 2 - firstBullet.getRect().width / 2; firstBullet.getRect().x = centerx; firstBullet.getRect().y = this.getRect().y; bullets.add(firstBullet); for (GunUpgrade up : gunUpgrades) { Iterator<Bullet> it = bullets.iterator(); while (it.hasNext()) { Bullet b = it.next(); LinkedList<Bullet> created = applyUpgrade(b, up); for (Bullet bul : created) { newBullets.add(bul); } it.remove(); } for (Bullet b : newBullets) bullets.add(b); newBullets.clear(); } return bullets; }
cec0d1dc-af1b-4f5c-9047-28959fe61c81
2
public FileTransfer(String fileName, Long fileSizeLeft){ this.fileName = fileName; this.fileSizeLeft = fileSizeLeft; this.file = new File(this.fileName,""); try{ if(!this.file.exists()){ this.file.createNewFile(); } this.fileOutputStream = new FileOutputStream(file,true);// 追加模式写文件 this.fileChannel = fileOutputStream.getChannel(); }catch(Exception e){ e.printStackTrace(); } }
2f2f55c9-7dd5-4967-a3b3-e1795b9c8fc3
2
@Override public void update(Observable o, Object arg) { switch (arg.toString()) { case "parties": this.popupParties.setLocationRelativeTo(null); this.popupParties.setVisible(true); this.afficherPopupParties(this._jeu.getProfilCourant()); break; case "start": VuePartie plateau = new VuePartie(this, this._jeu, this._jeu.getProfilCourant(), this._jeu.getPartieCourante()); this._jeu.getPartieCourante().addObserver(plateau); // Affiche le plateau de jeu plateau.setVisible(true); this.popupParties.dispose(); this.popupParametres.dispose(); this.dispose(); break; } } // update(Observable o, Object arg)
87e174ac-6afc-4cba-aa36-9593d1d05dcf
0
public static int[] getRegion(int x,int z){ int[] chunkCoords = getChuk(x, z); return getChunkRegion(chunkCoords[0], chunkCoords[1]); }
bdd31ece-f310-47fa-a63b-74730c8e6d60
2
public void move() { PhysicsComponent ownPC = (PhysicsComponent)getOwningActor().getComponent("PhysicsComponent"); if(ownPC.getAngleRad() < ownPC.getTargetAngle() + 0.1 && ownPC.getAngleRad() > ownPC.getTargetAngle() - 0.1) { ownPC.applyAcceleration(1.0f); } }
e26e5f46-49b8-4bf8-b453-99a8e694c87d
2
public void analyze() { if (GlobalOptions.verboseLevel > 0) GlobalOptions.err.println("Reachable: " + this); ClassInfo[] ifaces = info.getInterfaces(); for (int i = 0; i < ifaces.length; i++) analyzeSuperClasses(ifaces[i]); analyzeSuperClasses(info.getSuperclass()); }
d50a05cd-36dc-4905-b6cf-75fc4fe9ee57
0
public DocumentStatistics() { super(true, true, true, INITIAL_WIDTH, INITIAL_HEIGHT, MINIMUM_WIDTH, MINIMUM_HEIGHT); Outliner.statistics = this; }
adc5abe2-a6c1-4948-887b-653ae9a9dc40
1
public String toString() { StringBuffer display = new StringBuffer(); display.append("---- " + name + " ----\n"); display.append(dough + "\n"); display.append(sauce + "\n"); for (int i = 0; i < toppings.size(); i++) { display.append((String )toppings.get(i) + "\n"); } return display.toString(); }
1a627fc8-5ef0-4014-a55d-6273f44c2a5c
6
private int handleZ(String value, DoubleMetaphoneResult result, int index, boolean slavoGermanic) { if (charAt(value, index + 1) == 'H') { //-- Chinese pinyin e.g. "zhao" or Angelina "Zhang" --// result.append('J'); index += 2; } else { if (contains(value, index + 1, 2, "ZO", "ZI", "ZA") || (slavoGermanic && (index > 0 && charAt(value, index - 1) != 'T'))) { result.append("S", "TS"); } else { result.append('S'); } index = charAt(value, index + 1) == 'Z' ? index + 2 : index + 1; } return index; }
e05ea0c4-f92b-4df0-95c1-76c0ab6eb102
0
@Override public VueVisiteur getVue() { return (VueVisiteur) vue; }
7115b8c0-fc9f-4d9c-b7e5-86d77501b206
4
public void checkPlayerCollision(Player player, boolean canKill) { if (!player.isAlive()) { return; } // check for player collision with other sprites Sprite collisionSprite = getSpriteCollision(player); if (collisionSprite instanceof PowerUp) { acquirePowerUp((PowerUp)collisionSprite); } else if (collisionSprite instanceof Creature) { Creature badguy = (Creature)collisionSprite; if (canKill) { // kill the badguy and make player bounce soundManager.play(boopSound); badguy.setState(Creature.STATE_DYING); player.setY(badguy.getY() - player.getHeight()); player.jump(true); score+=100; } else { // player dies! lives--; player.setY(badguy.getY() - player.getHeight()); player.jump(true); //player.setState(Creature.STATE_DYING); } } }
2a0c68f9-3edd-4e54-bdc0-4feda73fdef1
9
public static boolean nonNumeric( String k ){ for( int i = 0; i < k.length(); i++ ){ if( ( k.charAt(i) > '9' || k.charAt(i) < '0' ) && k.charAt(i) != ',' && k.charAt(i) != '+' && k.charAt(i) != '*' && k.charAt(i) != '/' && k.charAt(i) != '-' && k.charAt(i) != '%'){ return true; } } return false; }
0ae17142-fac5-4ac2-8c84-ade7608db9d0
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new LoginForm().setVisible(true); } }); }
ff9ac4d1-ca9d-447f-ab1e-23ed36b49d3e
2
private boolean containsElement(List<ElementInfo> elements, PlayerInfo element) { for(ElementInfo e : elements) if (e.equals(element)) return true; return false; }
bb2889db-8470-418c-b11c-a45514221818
2
public static void main(String[] args) { Scanner input = new Scanner(System.in); int cases = 1; while (true) { int n = input.nextInt(); if (n < 3) return; double A = input.nextDouble(); double angle = Math.PI * (n - 2) / (2 * n); double s = Math.sqrt(4 * A / (n * Math.tan(angle))); double ri = 2 * A / (n * s); double ro = s / (2 * Math.cos(angle)); double ai = Math.PI * ri * ri; double ao = Math.PI * ro * ro; double off = A - ai; double spec = ao - A; System.out.printf("Case %d: %.5f %.5f\n", cases, spec, off); ++cases; } }
a72a12c1-513c-45c4-9159-57cf934e1d0e
1
public Set<BankAccount> getReplacingAccounts(BiFunction<BigInteger,BigInteger,BankAccount> generator) { Set<BankAccount> result = new HashSet<>(); for (BankAccount account: accounts) result.add(generator.apply(account.getBalance().add(BigInteger.TEN),account.getCreditLimit())); return result; }
65dfdfe4-5890-47b0-a51a-a9a3ff5f6e9d
9
public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if (source == addButton) { String value = tfValue.getText(); if (value.length() == 0) return; int typeIndex = typeCombo.getSelectedIndex(); if (typeIndex == -1) return; int type = EXTHRecord.knownTypes[typeIndex]; EXTHRecord rec = null; if (EXTHRecord.isBooleanType(type)) // this is an ugly hack - we really should present a checkbox to the user { boolean boolValue = false; if (value.equals("1") || value.toLowerCase().equals("true") || value.toLowerCase().equals("on") || value.toLowerCase().equals("yes")) { boolValue = true; } rec = new EXTHRecord(type, boolValue); } else rec = new EXTHRecord(type, value, GuiModel.getCharacterEncoding()); listener.addEXTHRecord(rec); setVisible(false); dispose(); } else if (source == cancelButton) { setVisible(false); dispose(); } }
32c33c05-b276-467c-a29f-40407f4693d3
3
@Override public void onEnable() { instance = this; FileConfiguration config = this.getConfig(); config.addDefault("PromptTitle", "Player Plus Accessories"); config.addDefault("TitleX", 190); config.addDefault("Hot_Key", "KEY_U"); config.addDefault("GUITexture", "http://www.pixentral.com/pics/1duZT49LzMnodP53SIPGIqZ8xdKS.png"); config.addDefault("ForceDefaultCape", true); config.addDefault("DefaultCape", "http://www.almuramc.com/playerplus/capes/almuracape.png"); config.options().copyDefaults(true); saveConfig(); getServer().getPluginManager().registerEvents(this, this); getDataFolder().mkdir(); for (AccessoryType ttype : AccessoryType.values()) { List<WebAccessory> aval = getAvailable(ttype); for (WebAccessory wa : aval) { SpoutManager.getFileManager().addToPreLoginCache(this, wa.getUrl()); } } hotkeys = config.getString("Hot_Key"); SpoutManager.getKeyBindingManager().registerBinding("PlayerPlus", Keyboard.valueOf(PlayerPlus.hotkeys), "Opens Player Plus Accessories", new InputHandler(), PlayerPlus.getInstance()); try { MetricsLite metrics = new MetricsLite(this); metrics.start(); } catch (IOException e) { } }
730f580d-adee-407c-a59d-83278184a30b
5
private void validateParameters() throws DriverJobParametersException { if (!this.dgenInstallDir.isDirectory()) { throw new DriverJobParametersException("Data generator install dir `" + this.dgenInstallDir + "` does not exist."); } if (!this.dgenNodePropertiesPath.isFile()) { throw new DriverJobParametersException("Data genenerator properties file `" + this.dgenNodePath + "` does not exist."); } if (!this.dgenNodePath.isFile()) { throw new DriverJobParametersException("Data genenerator executable `" + this.dgenNodePath + "` does not exist."); } if (!this.outputBase.isAbsolute()) { throw new DriverJobParametersException("Base output path `" + this.outputBase + "` should be absolute."); } if (!this.outputBase.isAbsolute()) { throw new DriverJobParametersException("Base output path `" + this.outputBase + "` should be absolute."); } }
69a372de-549f-4137-8f5d-42e98917a9b3
4
public int compare(Card other){ if(this == other){ return 0; } if(this.getCardNum() < other.getCardNum()){ return -1; } if(this.getCardNum() > other.getCardNum()){ return 1; } if(this.getCardNum() == other.getCardNum()){ return 0; } return 1; }
d3b26c91-ef8e-4619-8679-ba2914a821aa
1
public LowLevelFeatureCommand(CommandParameter par) { if(par == null) throw new NullPointerException("LowLevelFeatureCommand has a null CommandParameter"); this.par= par; }
f111d221-b879-4d12-b086-c2a70a9bd477
5
public void setValue(String name, String value) { int i = indexOfName(name); if (i == -1) { if ((value != null) && (!value.equals(""))) { add(name + ": " + value); } } else { if ((value != null) && (!value.equals(""))) { set(i, name + ": " + value); } else { delete(i); } } }