method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
e086a5d6-b381-429b-bbab-7be68e53829e
3
private boolean isToken(HttpServletRequest request) { HttpSession session = request.getSession(); String token_cline = request.getParameter("token"); if(token_cline == null){ return false; } String token_server = (String) session.getAttribute("token"); if(token_server==null){ return false; } if(!token_cline.equals(token_server)){ return false; } return true; }
bff43ef2-1fcc-47ae-a8d0-8d313a9fd3e4
5
public ParamsParse (String filePath) throws Exception { // Инициализация объекта db = new DBParams(); try { // Откроем файл File fXmlFile = new File(filePath); // Подготовим парсер DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Распарсим файл Document doc = dBuilder.parse(fXmlFile); // Без этого узел может расползтись на несколько строк и будет неправильно разобран doc.getDocumentElement().normalize(); // Получим режим работы this.mode = doc.getDocumentElement().getElementsByTagName("mode").item(0).getTextContent(); // В зависимости от режима работы будем выбирать определенные структуры // Если режим неизвестный то выходим с ошибкой if ( !(this.mode.equalsIgnoreCase("compare") || this.mode.equalsIgnoreCase("generate")) ) { throw new Exception("Неизвестный режим в файле параметров"); } // Получим остальные параметры // Имена конечных тегов одинаковые так что искать можно без условностей. this.fileName = doc.getDocumentElement().getElementsByTagName("file_name").item(0).getTextContent(); db.setSchemaName(doc.getDocumentElement().getElementsByTagName("schema_name").item(0).getTextContent()); db.setSchemaPassword(doc.getDocumentElement().getElementsByTagName("schema_password").item(0).getTextContent()); db.setBaseName(doc.getDocumentElement().getElementsByTagName("base_name").item(0).getTextContent()); db.setBaseHost(doc.getDocumentElement().getElementsByTagName("base_host").item(0).getTextContent()); db.setBasePort(Integer.parseInt(doc.getDocumentElement().getElementsByTagName("base_port").item(0).getTextContent())); } catch (Exception e) { System.out.println("ParamsParse: Ошибка при разборе параметров из файла"); System.out.println(e.toString()); throw e; } // После того как файл с параметрами разобрали надо проверить что все поля заполнены if ( ! db.checkNotEmpty()) throw new Exception("ParamsParse: Ошибка в параметрах. Параметры схемы заполнены не верно."); if (this.fileName.isEmpty()) throw new Exception("ParamsParse: Ошибка в параметрах. Параметр file_name задан неверно."); }
63597169-17a2-40a4-9b9a-1399f6bbc66a
3
public static List<UserTrend> constructTrendList(Response res) throws WeiboException { try { JSONArray list = res.asJSONArray(); int size = list.length(); List<UserTrend> trends = new ArrayList<UserTrend>(size); for (int i = 0; i < size; i++) { trends.add(new UserTrend(list.getJSONObject(i))); } return trends; } catch (JSONException jsone) { throw new WeiboException(jsone); } catch (WeiboException te) { throw te; } }
1a99d2c2-7c6e-441a-ace5-6d1c20756c86
0
public void setKey(String key) { this.key = key; }
df92ce21-8d3c-41f3-9e21-b09f27dac05d
7
public void actionPerformed(ActionEvent e) { if(e.getSource()==btnDmarrerSimulation){ new Thread(new Runnable() { public void run() { controleur.configurerSimulation(genererDonnees(),spinner.getValue().toString()); } }).start(); } else if(e.getSource()==btnEditerPosteur){ FconfPosteur.setVisible(true); System.out.println("ok"); } else if(e.getSource()==btnEditerFan){ FconfFan.setVisible(true); } else if(e.getSource()==btnEditerObjecteur){ FconfObjecteur.setVisible(true); } else if(e.getSource()==btnEditerSuiveur){ FconfSuiveur.setVisible(true); } else if(e.getSource()==btnEditerRapid){ FconfRapide.setVisible(true); } else if(e.getSource()==btnEditerLambda){ FconfLambda.setVisible(true); } }
596e8b27-e665-434f-b50a-f515df06937a
6
public void seCacher() { int nombreAtrouver, nombreDuJoueur = 100, nombreEssais = 0; String nombreString; nombreAtrouver = (int) (Math.random() * 50); System.out.println("Pour vous cacher à temps, il faut que vous trouviez le nombre recherche en moins de 5 essais" + "\nEntrez un nombre compris entre 0 et 50"); while(nombreDuJoueur != nombreAtrouver) { boolean recommencer = true; while (recommencer) { nombreString = keyboard.nextLine(); try { nombreDuJoueur = Integer.parseInt(nombreString); recommencer = false; } catch (NumberFormatException e) { recommencer = true; System.out.println("Entrez un chiffre !"); } } if (nombreDuJoueur < nombreAtrouver) { System.out.println("Le nombre à trouver est plus grand"); } else if (nombreDuJoueur > nombreAtrouver) { System.out.println("Le nombre à trouver est plus petit"); } nombreEssais ++; } if (nombreEssais <= 5) { System.out.println("Felicitation, vous avez pu vous cacher à temps, vous êtes sain et sauf !" + "\nLe braqueur vient d'être arrete par la police, vous pouvez continuer à jouer"); } else { System.out.println("Vous avez ete trop lent à vous cacher..." + "\nLe braqueur vous a trouve sur sa route et vous a tue" + "\n GAME OVER"); System.exit(0); } }
d91bea9b-1606-40a1-9876-abfce8154437
0
public Context(List tokens, int center, List[] results) { this.tokens = tokens; this.center = center; this.results = results; }
d145efe4-7119-4106-b7f4-b282390d7a7c
6
public void edit(int index, String subject, String text, int priority) { if(index<0 || index==this.size()) { // Reveals if the number exists return; } boolean a; for(int i = 0; i<this.size(); ++i) { a = true; for(int j = 0; j<this.size(); ++j) { // Makes the subject unique if(subject.equals(get(j).getSubject())) { subject += " "; a = false; } } if(a) { // If the subject is unique, continue with program get(index).setSubject(subject); get(index).setText(text); get(index).setPriority(priority); get(index).changeDate(); return; } } }
50644050-36b2-496d-90b8-a801a104ec0e
5
private void removeBrokenMTWCs(MTWData data) { Set<Set<Tuple<Integer, Integer>>> set; if (data.player == playerID) { set = data.mTWCFP2; } else { set = data.mTWCFP1; } Iterator<Set<Tuple<Integer, Integer>>> combinations = set.iterator(); while (combinations.hasNext()) { Set<Tuple<Integer, Integer>> combination = combinations.next(); for (Tuple<Integer, Integer> coordinate : combination) { // Remove the combination if it contains the current coordinate // (safely by using the iterator remove) if (coordinate._1.equals(data.column) && coordinate._2.equals(data.row)) { combinations.remove(); break; } } } }
5994b7c1-2234-46dc-ae77-5d7bc6c62347
1
public void tableChanged(TableModelEvent e) { try { // get the index of the inserted row // tableModel.getRowSet().moveToCurrentRow(); int firstIndex = e.getFirstRow(); // create a new table model with the new data tableModel = new ProjectTableModel(tableModel.getList(), tableModel.getEntityManager()); tableModel.addTableModelListener(this); // update the JTable with the data admingui.updateTable(); // read the data in each column using getValueAt and display it on // corresponding textfield admingui.setProjNameTextField((String) tableModel.getValueAt(firstIndex, 1)); admingui.setCategoryTextField((String) tableModel.getValueAt(firstIndex, 6)); admingui.setStatusComboBox((String) tableModel.getValueAt(firstIndex, 5)); admingui.setOutcomeTextField((String) tableModel.getValueAt(firstIndex, 7)); admingui.setScopeTextField((String) tableModel.getValueAt(firstIndex, 4)); admingui.setFromDateTextField((String) tableModel.getValueAt(firstIndex, 2)); admingui.setToDateTextField((String) tableModel .getValueAt(firstIndex, 3)); admingui.updateFileComboBox(); admingui.updatePeopleComboBox(); } catch (Exception exp) { exp.getMessage(); exp.printStackTrace(); } }
685d8a50-badd-4f8b-910f-e50acd477679
2
@Override public Iterator<Integer> iterator() { ArrayList<Integer> nonNullProperties = new ArrayList<Integer>(); for (int x = 0; x < this.values.size(); x++) { if (values.get(x) != null) { nonNullProperties.add(x); } } return nonNullProperties.iterator(); }
2c3ccd98-de6a-4ff2-9c4b-d01b68da8bed
2
public static void main(String[] args) { Collection<Integer> c = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) c.add(i); // Autoboxing for (Integer i : c) System.out.print(i + ", "); }
87723ae7-077e-473b-abe1-9430d68dd8ff
9
public boolean addItem(String description, String pwd){ String newItem; String [] existDesc; if(description.isEmpty() || description == null || description.length() < 1) return false; // Create the XML tags and enclose the description and password separated // by a comma. newItem = "<pwd>" + description + ", " + pwd + "</pwd>"; // Check to see if this is the first item. if(RAW_PW_STRING == null || RAW_PW_STRING.isEmpty() ){ RAW_PW_STRING = newItem; }else{ existDesc = this.getDescriptionValues(); if(existDesc != null){ // Loop through all the description values stored and check to see if you // used them already. for(int i = 0; i < existDesc.length; i++ )if(description.equals(existDesc[i]))return false; } RAW_PW_STRING = RAW_PW_STRING + newItem; } // Save the encrypted passwords into the file. if(!this.encode())return false; return true; }
3aff0bc1-c6fb-4db4-b265-3db4cd293131
4
public static boolean accept(AbstractSyntaxNode node, TokenReader reader) { boolean result = false; final Term term = new Term(); if (Factor.accept(term, reader)) { while (reader.accept(Token.TIMES) || reader.accept(Token.DIVIDE) || reader.accept(Token.MOD)) { final Token op = reader.lookahead(-1); final Operation operation = new Operation(op.code()); term.addChild(operation); Factor.accept(term, reader); } node.addChild(term); result = true; } return result; }
fca4ea36-0bf1-404d-a1e9-aa08348c370e
6
@Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_LEFT: doAction(Action.MOVE_LEFT); break; case KeyEvent.VK_RIGHT: doAction(Action.MOVE_RIGHT); break; case KeyEvent.VK_DOWN: doAction(Action.MOVE_DOWN); break; case KeyEvent.VK_UP: doAction(Action.ROTATE_RIGHT); break; case KeyEvent.VK_SPACE: doAction(Action.HARD_DROP); break; case KeyEvent.VK_S: doAction(Action.DROP); break; } }
20e613fe-a626-4c9d-9520-0859d1d14999
4
* @return The double[] that the buffer has been converted into. */ private double[] bytesToDoubleArray(byte[] bufferData){ final int bytesRecorded = bufferData.length; final int bytesPerSample = getAudioFormat().getSampleSizeInBits()/8; final double amplification = 100.0; // choose a number as you like double[] micBufferData = new double[bytesRecorded - bytesPerSample +1]; for (int index = 0, floatIndex = 0; index < bytesRecorded - bytesPerSample + 1; index += bytesPerSample, floatIndex++) { double sample = 0; for (int b = 0; b < bytesPerSample; b++) { int v = bufferData[index + b]; if (b < bytesPerSample - 1 || bytesPerSample == 1) { v &= 0xFF; } sample += v << (b * 8); } double sample32 = amplification * (sample / 32768.0); micBufferData[floatIndex] = sample32; } return micBufferData; }
8cf33d61-3afc-4ca0-829f-0d76886c0d9e
1
public void transfer(int from, int to, double amount) { if (accounts[from] < amount) return; System.out.print(Thread.currentThread()); accounts[from] -= amount; System.out.printf(" %10.2f from %d to %d", amount, from, to); accounts[to] += amount; System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); }
280bb8ae-2e30-4656-bfd7-a52d5debb1d6
6
@Override public synchronized void execute(final Runnable r) { queue.offer(new Runnable() { public void run() { runs = true; try { r.run(); // to fire up the exception if there was one. if( r instanceof SwingWorker ) ((SwingWorker<?,?>)r).get(); } catch( Exception e ) { ApplicationLogger.logError(e); if( !continueOnException ) { // clear remaining queue and shutdown queue.clear(); exitWithErrorRunnable(); } } scheduleNext(); } }); if( currentRunnable == null ) scheduleNext(); }
7b7d0362-39dc-4467-a747-98f0793764af
7
private void create(String[] args) { boolean clientOnlyMode = false; boolean useAWT = false; System.setErr(System.out); SplashScreen splashScreen = new SplashScreen("/images/welcome.gif"); splashScreen.setVisible(true); for (String arg : args) { if (arg.equals("-client")) { clientOnlyMode = true; } if (arg.equals("-awt")) { useAWT = true; } } MeetingProtocol meetingProtocol = MeetingProtocol.getInstance(); MBProtocol mbProtocol = MBProtocol.getInstance(); addDispatchers(meetingProtocol, mbProtocol); Frame mainFrame = useAWT ? new msgtool.awt.MainFrame() : new msgtool.swing.MainFrame(); SwingWrapper.setSwingMode(!useAWT); if (!clientOnlyMode) { if (!MessageProtocol.getInstance().initializeServerSocket() || !MiscProtocol.getInstance().initializeServerSocket()) { splashScreen.setVisible(false); showInUseWarningDialog(useAWT, mainFrame); System.exit(1); } MBProtocol.getInstance().startServer(); } MainFrameFeatures frameFeature = (MainFrameFeatures) mainFrame; frameFeature.showMyAddress(); frameFeature.checkIfIPAddressChanged(); startThreads(); frameFeature.joinMeetingRooms(); splashScreen.setVisible(false); mainFrame.setVisible(true); }
1727ac87-c0ef-4e04-bbf7-8e6bd663d5f5
3
public void paintComponent( Graphics g ) { super.paintComponent( g ); Graphics2D g2d = (Graphics2D) g; for(int i =0; i < NUM; i++) { g2d.setColor( pelotas[i].col ); pelotas[i].draw(g2d); } g2d.setColor(Color.GRAY); raqueta.dibuja(g2d); g2d.setColor(Color.ORANGE); raqueta2.dibuja(g2d); g2d.setColor(Color.GRAY); g2d.setFont(new Font("Verdana", Font.BOLD, 30)); g2d.drawString(""+ score, 10, 30); if( perdi ) { Sonido.FINDEJUEGO.play(); g2d.setColor(Color.BLACK); g2d.setFont(new Font("Verdana", Font.BOLD, 24)); g2d.drawString("Finalizo el juego", 30,160); for(int i =0; i < NUM; i++) pelotas[i].interrupt(); } }
8e2a643a-2903-400a-b399-252a935ae250
4
private static boolean isaffected( int[] cellrc, int[] arearc ) { if( cellrc[0] < arearc[0] ) { return false; // row above the first ref row? } if( cellrc[0] > arearc[2] ) { return false; // row after the last ref row? } if( cellrc[1] < arearc[1] ) { return false; // col before the first ref col? } if( cellrc[1] > arearc[3] ) { return false; // col after the last ref col? } return true; }
fbf0b648-5bc3-4e5c-adda-5816d8b83732
1
public BufferedImage loadImage(String fnm) { try { BufferedImage im = ImageIO.read(ImageLoader.class.getResource(fnm)); //ImageIO.read(Art.class.getResource(fileName)); int transparency = im.getColorModel().getTransparency(); BufferedImage copy = gc.createCompatibleImage( im.getWidth(), im.getHeight(), transparency); Graphics2D g2d = copy.createGraphics(); g2d.drawImage(im, 0, 0, null); g2d.dispose(); return copy; } catch (IOException e) { EIError.debugMsg("Load Image error for " + fnm + ":\n" + e, EIError.ErrorLevel.Error); return null; } }
d2b204d3-689a-46fa-8167-212f63617ec7
6
public boolean AfegirRestriccioGrupSessio(String nomA, int grup, String dia, int hora) { int d; if ( dia.equals("dilluns") ) d = 0; else if ( dia.equals("dimarts") ) d = 1; else if ( dia.equals("dimecres") ) d = 2; else if ( dia.equals("dijous") ) d = 3; else if ( dia.equals("divendres") ) d = 4; else if ( dia.equals("dissabte") ) d = 5; else d = 6; RestGrupSessio rgs = new RestGrupSessio(nomA, grup, d, hora); return cjtRestGS.afegeixRestriccio( rgs ); }
d3bcaad5-e4a0-4525-92aa-4a23cba85763
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Group other = (Group) obj; if (idGroup != other.idGroup) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
4c2ca1ae-75c7-4909-b3e8-1d9e9598c5cb
0
public String getCalle() { return addressCompany.getCalle(); }
ab5ec025-1e62-4694-80a3-532a362fe8ea
3
final public Link get() { Link retVal = null; String url = null; try { Memcached cache = Memcached.getInstance(); @SuppressWarnings("unchecked") ArrayList<String> cacheValue = (ArrayList<String>) cache .get("jPapayaUrlList"); while (cacheValue == null || cacheValue.size() < 3) { cacheValue = this.datamodel.getUrlList(); } url = cacheValue.remove(0).toString(); cache.set("jPapayaUrlList", cacheValue); retVal = new Link(url); } catch (Exception e) { ErrorLog.getInstance().write("UrlGetter.get: " + e.getMessage()); } return retVal; }
4204a0d2-5d1e-43b3-8892-da6593b10965
9
public String match(String query, String fullLine){ int qTextLen = query.length(); int fLineLen = fullLine.length(); int[][] opt = new int [qTextLen + 1][fLineLen+1]; if(qTextLen == 0 || fLineLen == 0){ return null; } // Build the table for (int i = qTextLen - 1; i >= 0; i--) { for (int j = fLineLen - 1; j >=0; j--) { if (query.charAt(i) == fullLine.charAt(j)) opt[i][j] = opt[i+1][j+1] + 1; else opt[i][j] = Math.max(opt[i+1][j], opt[i][j+1]); } } // Return the string int i = 0, j = 0; while( i < qTextLen && j < fLineLen) { if (query.charAt(i) == fullLine.charAt(j)) { matchStr = matchStr + query.charAt(i); i++; j++; } else if (opt[i+1][j] >= opt[i][j+1]) i++; else j++; } return matchStr; }
6ef1dc7f-40ab-4bd7-a5c9-4b88d0f87c6c
8
public void onReceive(Object msg) { if (msg.equals("start")) { // start by depositing enough money in the account to cover the // txfrs accountA.tell(new BankAccount.Deposit(taskCount * 100), getSelf()); probe.tell("started", getSelf()); } else if (msg.equals(BankAccount.TransactionStatus.DONE)) { // once the initial deposit is done, fire off a transfer in each // direction for all the tasks for this teller log.info("deposit done"); probe.tell("deposited", getSelf()); for (int i = 0; i < tellerTxfrs; i++) { ActorRef txfr = getContext().actorOf( Props.create(BankTransfer.class), "aToBtxfr" + i); ActorRef txfr2 = getContext().actorOf( Props.create(BankTransfer.class), "bToAtxfr" + i); txfrs.add(txfr); txfrs.add(txfr2); txfr.tell(new BankTransfer.Transfer(accountA, accountB, 2), getSelf()); txfr2.tell( new BankTransfer.Transfer(accountB, accountA, 2), getSelf()); } } else if (msg.equals(BankTransfer.TransferStatus.DONE)) { // every time a txfr finishes, remove it from the list and increment the count log.debug("txfr done"); txfrs.remove(sender()); txfrCount++; if (txfrCount % 1000 == 0) log.info("Processed " + txfrCount + " txfrs"); // when all txfrs are done, end the test if (txfrCount == tellerTxfrs * 2) { log.info("Processed all txfrs"); probe.tell("done", getSelf()); } } else if (msg.equals(BankTransfer.TransferStatus.FAILED)) { log.error("txfr failed"); } else if (msg instanceof ActorRef) { probe = (ActorRef) msg; } else { log.error("unknown msg"); throw new RuntimeException("unknown msg"); } }
948ad419-a2db-4eca-8ba9-5cb84353ebf8
5
final public java.util.Map.Entry < FtanString, FtanValue > KeyValuePair() throws ParseException { FtanString key; FtanValue value; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case SQ_STRING_START: case DQ_STRING_START: key = String(); break; case NAME: key = Name(); break; default: jj_la1[7] = jj_gen; jj_consume_token(-1); throw new ParseException(); } jj_consume_token(ELEMENT_KEYVALUESEPARATOR); value = Value(); {if (true) return new java.util.AbstractMap.SimpleImmutableEntry < FtanString, FtanValue > (key, value);} throw new Error("Missing return statement in function"); }
0bb7a98d-36f8-43fb-91f7-614465379a2c
8
public void insertIntoPosition(HTreeNode node, int position){ /* Checks if node is null. */ if (node == null) return; /* Creates a new node from node; designates a null next() link. */ HTreeNode newNode = new HTreeNode(node); /* The iterator node for the insertion. */ HTreeNode iterator = getHeadNode(); /* Checks if position is at front of list. */ if (position == 0 || iterator == null){ /* Set new node as head. */ newNode.setNext(iterator); setHead(newNode); /* Increment length of linked list. */ this.length++; } /* Checks if position is greater than list length. */ if (position >= length()) { /* Inserts new node at end of list. */ insertAtEnd(newNode); return; } /* Inserts new node if position is greater than 0 and iterator is not null. */ if (position > 0 && iterator != null) { /* Finds the node after position in the linked list. */ for (int i = 0; i < position + 2; i++) { /* Handles case if iterator is null after position. */ if (iterator.next() == null) { insertAtEnd(newNode); return; } /* Continues traversing if iterator is not null. */ iterator = iterator.next(); } /* Call to method to insert node at position. */ insertBefore(iterator, node); } }
9dc6776b-4cd8-4a14-a32c-354d8b2a4c4d
2
private Vector getResultant() { Vector resultant = new Vector(myUniverse.getDimension()); //TODO Bit of a hack here, consider cleaning for(Vector element: forceList) { try { resultant = Vector.add(resultant,element); } catch (DimensionMismatchException e) { e.printStackTrace(); } } return resultant; }
cbb53eaa-faca-40b3-b456-0b778d9617c3
3
@Override protected void updateAnimation() { if (left || right) { if (currentAction != 0) { currentAction = 0; getAnimation().setFrames(entityTexture); getAnimation().setDelay(75); } } getAnimation().update(); }
979129b1-6697-48b1-8b93-c90095085604
0
public NamePrinter(SharedObject counter) { this.counter=counter; }
bb510f9b-3721-4c94-8240-14c1e34344e8
7
public void mousePressed(MouseEvent e) { Point click = e.getPoint(); int xIndex = click.x/TILE; int yIndex = click.y/TILE; Tile clicked = campus.getTile(xIndex+screenX, yIndex+screenY); System.out.println("Clicked: " + xIndex + "," + yIndex + ", Tile: " + clicked); if (e.getButton() == MouseEvent.BUTTON3) { Tile choice = (Tile)JOptionPane.showInputDialog(null, "Please choose a tile:", "Tile Swap", JOptionPane.QUESTION_MESSAGE, null, new Tile[] { // corners new Tile(Tile.Type.CORNER, Tile.Direction.UP), new Tile(Tile.Type.CORNER, Tile.Direction.RIGHT), new Tile(Tile.Type.CORNER, Tile.Direction.DOWN), new Tile(Tile.Type.CORNER, Tile.Direction.LEFT), // forks new Tile(Tile.Type.FORK, Tile.Direction.UP), new Tile(Tile.Type.FORK, Tile.Direction.RIGHT), new Tile(Tile.Type.FORK, Tile.Direction.DOWN), new Tile(Tile.Type.FORK, Tile.Direction.LEFT), // straights new Tile(Tile.Type.ROAD), new Tile(Tile.Type.ROAD, Tile.Direction.LEFT), // nature new Tile(Tile.Type.TREE), new Tile(Tile.Type.TREE, Tile.Direction.DOWN), new Tile(Tile.Type.FLOWER, Tile.Direction.DOWN), new Tile(Tile.Type.GRASS, Tile.Direction.DOWN), new Tile(Tile.Type.LAND, Tile.Direction.DOWN), // buildings new Tile(Tile.Type.DOOR), new Tile(Tile.Type.ROOF), new Tile(Tile.Type.WALL), new Tile(Tile.Type.WINDOW, Tile.Direction.LEFT), new Tile(Tile.Type.WINDOW, Tile.Direction.RIGHT), new Tile(Tile.Type.WINDOW), new Tile(Tile.Type.LAND, Tile.Direction.UP) } , null); // choice is the tile chosen from list if (choice != null) { campus.changeTile(choice, new Point(xIndex+screenX,yIndex+screenY)); if (choice.getType() == Tile.Type.LAND) campus.addLand(new Point(xIndex+screenX, yIndex+screenY)); tiles[xIndex][yIndex] = tileFactory.get(choice); //renderScreen(); } System.out.println("New choice: " + choice); if (xIndex+yIndex+screenX+screenY == 0) // right clicked on upper left most tile { int result = JOptionPane.showConfirmDialog(null, "Export code to text?", "Export", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { // Export code to campus.txt try { BufferedWriter writer = new BufferedWriter(new FileWriter(new File("campus.txt"))); String[] words = campus.getConstructor().split("\n"); for (String line : words) { writer.write(line); writer.newLine(); } writer.close(); } catch (Exception ex) {} } } } }
5b7921f3-e473-4231-a11a-46e0ab1d0a92
5
public void selectNone() { expandMenu(); for(int i = 0; i < methodTree.getRowCount(); i++) { TreePath path = methodTree.getPathForRow(i); if(path == null) return; DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) path.getLastPathComponent(); if(treeNode.getUserObject() instanceof TreeNodeObject) { TreeNodeObject co = (TreeNodeObject) treeNode.getUserObject(); if(co.isSelected() && co.isNoCategory()) { co.setSelected(false); handler.toggleDecodingMethod(co.getMethodID()); } } } methodTree.repaint(); }
bc263b92-5206-4859-a291-c55cb1d1f03b
3
public int getOil(int size){ if (resource1==2){ if (size==1){ return sgenrate1; } else if (size==2){ return mgenrate1; } else { return lgenrate1; } } else{ return 0; } }
c15c23e6-9948-474e-83b0-b2c9e60485e7
2
public int getLevel() { // Level not calculated yet? if( level < 0 ) { level = 0; // Level = max(parent's level) + 1; for( GoTerm parent : parents ) level = Math.max(level, parent.getLevel() + 1); } return level; }
495791f4-83e4-4e73-95c0-508e80e54dc7
7
public static void sortMaps() { mapPanels.clear(); maps.removeAll(); currentMaps.clear(); int counter = 0; selectedMap = 0; maps.repaint(); LaunchFrame.updateMapInstallLocs(new String[]{""}); mapInfo.setText(""); HashMap<Integer, List<Map>> sorted = new HashMap<Integer, List<Map>>(); sorted.put(0, new ArrayList<Map>()); sorted.put(1, new ArrayList<Map>()); for(Map map : Map.getMapArray()) { if(originCheck(map) && compatibilityCheck(map) && textSearch(map)) { sorted.get((map.isCompatible(ModPack.getSelectedPack().getName())) ? 1 : 0).add(map); } } for(Map map : sorted.get(1)) { addMap(map); currentMaps.put(counter, map); counter++; } for(Map map : sorted.get(0)) { addMap(map); currentMaps.put(counter, map); counter++; } updateMaps(); }
82f62370-980a-46d8-b6ab-282b913bf75d
0
public String getSampleOutput() { return this.sampleOutput; }
6a92f6a9-694f-4610-a105-e8afc736fa98
2
private double normalisoi(double kulma){ if (kulma < 0){ return kulma + Math.PI*2; } else if (kulma > Math.PI*2) { return kulma - Math.PI*2; } else { return kulma; } }
a0e5081c-244f-41ff-abc6-629055a2bc56
9
public static void main(String[] args) throws Throwable{ StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int caso = 1; for(String str1; (str1=in.readLine())!=null; caso++){ sb.append((caso<10?" ":"") + caso + ". "); String str2 = in.readLine(); if(str1.length()==0||str2.length()==0) sb.append("Blank!\n"); else{ String[] arr1 = str1.trim().replaceAll("[^a-zA-z0-9]", " ").split(" +"); String[] arr2 = str2.trim().replaceAll("[^a-zA-z0-9]", " ").split(" +"); int[][] dp = new int[arr1.length+1][arr2.length+1]; for(int i = arr1.length-1; i>=0; i--) for(int j = arr2.length-1; j>=0; j--){ dp[i][j] = max(dp[i+1][j], dp[i][j+1]); if(!arr1[i].equals("")&&!arr2[j].equals("")&&arr1[i].equals(arr2[j]))dp[i][j]=max(dp[i][j],dp[i+1][j+1]+1); } sb.append("Length of longest match: " + dp[0][0] + "\n"); } } System.out.print(new String(sb)); }
796f130c-c1e8-4da0-94db-b52ed86dfa22
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(MainView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> }
869797f0-08fd-4897-b4e7-fe4849fc3f2f
4
public void setConfigSize(Integer w, Integer h) { if (w == null && h == null) return; if (w == null) w = getSize().width; if (h == null) w = getSize().height; setSize(w, h); }
713c6638-1700-4b04-9c72-d84bede5003a
0
public Target(String ip, int dv) { this.ip = ip; this.dv = dv; }
eaf2a707-8473-42c0-bdc1-a1af64a498f4
2
public Iterator<Compound> col_wise() { return new Iterator<Compound>() { int y = 0; int x = 0; int idx = 0; public boolean hasNext() { if ((x == cols-1) && (y < rows-1)) { x = 0; } return true; } public Compound next() { idx++; return get(x,y); } public void remove() { throw new UnsupportedOperationException(); } }; }
a4b320dc-4a7b-4643-ac11-974ed2278a30
1
private static void putInput(Comparable[] a, String type) { try { SortHelper.class.getMethod("put" + type + "Input", Comparable[].class).invoke(null, (Object) a); } catch (Exception e) { System.out.println(e + "\n" + e.getCause()); System.exit(1); } }
9b2e1b5b-5650-475d-887a-97018214c98d
8
private void applyMovement() { if (isGoLeft() && isCanLeft()) { getGame().setxOffset(getGame().getxOffset() + getMovementSpeed()); } if (isGoRight() && isCanRight()) { getGame().setxOffset(getGame().getxOffset() - getMovementSpeed()); } if (isGoUp() && isCanUp()) { getGame().setyOffset(getGame().getyOffset() + getMovementSpeed()); } if (isGoDown() && isCanDown()) { getGame().setyOffset(getGame().getyOffset() - getMovementSpeed()); } }
e5cd9567-9475-4633-be0a-3a8b516a4d3b
0
public String getType() { return "pda"; }
173ab78f-1dd3-44ab-824e-3a785d34225f
2
@Override public Boolean needScrolling(ViewEventArgs args){ Boolean needScrolling = false; int totalHeight = 0; for (Row row : this.document.getRows()){ totalHeight += row.getHeight(); } if (totalHeight > args.getFrameHeight()){ needScrolling = true; } return needScrolling; }
2e8d33ad-e520-48c1-8e2a-56330d3c24c0
7
public void generate_signals(Instruction current_instruction){ clear_signals(); switch(current_instruction.get_format()){ case 0: set_reg_write(true); break; case 1: set_reg_write(true); set_mem_read(true); set_mem_to_reg(true); break; case 2: set_mem_write(true); break; case 3: set_branch(true); break; case 4: set_jump(true); if (current_instruction.get_type() == InstructionType.jal){ set_reg_write(true); } break; case 5: set_reg_write(true); set_jump(true); break; } }
31a3d3c5-aa07-4323-8a8b-e8d77c1651a4
1
private void peopleProjectComboBoxActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: int index = peopleProjectComboBox.getSelectedIndex(); if (index != -1) { String projID = projectTableController.getTableModel().getValueAt(index,0).toString(); peopleTableController.filterPeopleList(projID); //System.out.println(projID); updatePeopleTable(); } }
b5b302a7-2680-409d-92be-94637b8c9adf
8
private void processGridlet(Sim_event ev, int type) { int gridletId = 0; int userId = 0; try { // if a sender using gridletXXX() methods int data[] = (int[]) ev.get_data(); gridletId = data[0]; userId = data[1]; } // if a sender using normal send() methods catch (ClassCastException c) { try { Gridlet gl = (Gridlet) ev.get_data(); gridletId = gl.getGridletID(); userId = gl.getUserID(); } catch (Exception e) { System.out.println(super.get_name() + ": Error in processing Gridlet"); System.out.println( e.getMessage() ); return; } } catch (Exception e) { System.out.println(super.get_name() + ": Error in processing a Gridlet."); System.out.println( e.getMessage() ); return; } // begins executing .... switch (type) { case GridSimTags.GRIDLET_CANCEL: policy_.gridletCancel(gridletId, userId); break; case GridSimTags.GRIDLET_PAUSE: policy_.gridletPause(gridletId, userId, false); break; case GridSimTags.GRIDLET_PAUSE_ACK: policy_.gridletPause(gridletId, userId, true); break; case GridSimTags.GRIDLET_RESUME: policy_.gridletResume(gridletId, userId, false); break; case GridSimTags.GRIDLET_RESUME_ACK: policy_.gridletResume(gridletId, userId, true); break; default: break; } }
c57012a8-7f49-4408-9b9d-a9849e85b630
7
@Override public void alreadyExists(User user) throws EntityAlreadyExistsException, UnablePerformDBOperation, CantGetDBConnection { log.info("Searching user " + user.toString() + " in DB"); checkConnection(); String queryLogin = "select * from users where login = ? "; String queryEmail = "select * from users where email = ? "; boolean updatingUser = (user.getId() != 0); if (updatingUser) { queryLogin += "and id != ?"; queryEmail += "and id != ?"; } String baseErrorMessage = "Exception while checking user in DB: " + user.toString() + ". "; try { try (PreparedStatement statement = connection.prepareStatement(queryLogin)) { statement.setString(1, user.getLogin()); if (updatingUser) { statement.setInt(2, user.getId()); } try (ResultSet resultSet = statement.executeQuery()) { if (resultSet.next()) { String errorMessage = "User with login " + user.getLogin() + " already alreadyExists in DB"; log.error(errorMessage); throw new EntityAlreadyExistsException(errorMessage); } } } try (PreparedStatement statement = connection.prepareStatement(queryEmail)) { statement.setString(1, user.getEmail()); if (updatingUser) { statement.setInt(2, user.getId()); } try (ResultSet resultSet = statement.executeQuery()) { if (resultSet.next()) { String errorMessage = "User with email " + user.getEmail() + " already alreadyExists in DB"; log.error(errorMessage); throw new EntityAlreadyExistsException(errorMessage); } } } } catch (EntityAlreadyExistsException e) { throw e; } catch (Exception e) { log.error(baseErrorMessage); throw new UnablePerformDBOperation(baseErrorMessage, e); } }
d3dfb552-5d8e-4ee0-8c41-8ab7c2721c25
7
private void mode() { Stopwatch.start(); Boolean moreThen0 = false; Map<Integer, Integer> freqs = new HashMap<Integer, Integer>(); for (Integer val : _myBigArray) { Integer freq = freqs.get(val); if (freq == null) { freq = 1; } else { freq++; moreThen0 = true; } freqs.put(val, freq); } int mode = 0, maxFreq = 1; if (moreThen0) { for (Map.Entry<Integer, Integer> entry : freqs.entrySet()) { int freq = entry.getValue(); int v = entry.getKey(); if (freq > maxFreq) { maxFreq = freq; mode = v; } else if (freq == maxFreq && mode > v) { // get the minimum of all the maximum frequencies mode = v; } } } Stopwatch.stop(); System.out.format("\tMode: %.2f\t%s\n", (double) mode, Stopwatch.getTimeStr()); }
22f70377-e76b-4ec6-9faa-1ff62f917281
6
public List<Map<Double,Double>> getNormalDataSet(int saptak) { List<Map<Double,Double>> dataList = new ArrayList<Map<Double,Double>>(); //DataSet Map double maxTimeValue = 0; Map<Double,Double> map = new LinkedHashMap<Double,Double>(); if (pointFramesMap != null) { for(String _pointFrame : pointFramesMap.keySet()) { double pointFrame = Double.parseDouble(_pointFrame); double timeValue = pointFrame / sampleRate; double freq = pointFramesMap.get(_pointFrame); if (freq>300 || freq<100) { continue; } map.put(timeValue,freq); maxTimeValue = timeValue; } } int listIdx = 0; dataList.add(listIdx++,map); //Octaves Double[] freqs = conv.getSaptakFrequencies(0); for(int i=0; i<12; i++) { map = new LinkedHashMap<Double,Double>(); map.put(0.0, freqs[i]); map.put(maxTimeValue, freqs[i]); dataList.add(listIdx++,map); } try { FileOutputStream fileOut = new FileOutputStream("graphData.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(dataList); out.close(); fileOut.close(); }catch(IOException i) { i.printStackTrace(); } return dataList; }
cc4d2331-6eee-4961-90df-822a9b18e1bb
6
public final void statement() throws RecognitionException { ParserRuleReturnScope labelfield1 =null; try { // C:\\Users\\Shreeprabha\\Documents\\GitHub\\CecilRPi\\src\\org\\raspberrypi\\cecil\\model\\grammar\\Cecil.g:140:3: ( ( '.' labelfield )? mnemonicdata ) // C:\\Users\\Shreeprabha\\Documents\\GitHub\\CecilRPi\\src\\org\\raspberrypi\\cecil\\model\\grammar\\Cecil.g:140:5: ( '.' labelfield )? mnemonicdata { // C:\\Users\\Shreeprabha\\Documents\\GitHub\\CecilRPi\\src\\org\\raspberrypi\\cecil\\model\\grammar\\Cecil.g:140:5: ( '.' labelfield )? int alt4=2; int LA4_0 = input.LA(1); if ( (LA4_0==8) ) { alt4=1; } switch (alt4) { case 1 : // C:\\Users\\Shreeprabha\\Documents\\GitHub\\CecilRPi\\src\\org\\raspberrypi\\cecil\\model\\grammar\\Cecil.g:140:6: '.' labelfield { match(input,8,FOLLOW_8_in_statement99); pushFollow(FOLLOW_labelfield_in_statement101); labelfield1=labelfield(); state._fsp--; /* filling labelfield hashmap */ if(labelfield.containsKey((labelfield1!=null?input.toString(labelfield1.start,labelfield1.stop):null))) throw new RecognitionException(); else labelfield.put(((labelfield1!=null?input.toString(labelfield1.start,labelfield1.stop):null)),pointer); } break; } pushFollow(FOLLOW_mnemonicdata_in_statement114); mnemonicdata(); state._fsp--; } } /** * Rulecatch implicitly invoked by the parser. The error is appended to the StreamOutputError list. */ catch (RecognitionException e) { String msg = getErrorMessage(e, tokenNames); this.stream.getErrors().add(new OutputError(e.line, msg)); System.out.println(e.line + " : " + msg); } finally { // do for sure before leaving } }
b9fdbf7d-5e4c-47c7-b5f2-816e7d40fd95
1
public Complex getElem(int ri, int ci) { try { return matrix[ri][ci]; } catch (Exception e) { System.out.println("Invalid indices in getElem(int ri, int ci)"); e.printStackTrace(); } return null; }
b803ee9f-8b7c-460d-a34c-a3c794ca0f72
3
public static Graph<Vertex, Edge<Vertex>> FileToGraph(String dat, boolean directed) { int[][] GArray = FileToGraphArray(dat); int n = GArray[0][0]; int m = GArray[0][1]; Graph<Vertex, Edge<Vertex>> G = new Graph(n); // Knoten hinzufuegen for (int i = 0; i < n; i++) { G.addVertex(new Vertex(i)); } /* Kanten hinzufuegen */ for (int i = 1; i <= m; i++) { int idxa = GArray[i][0]; int idxb = GArray[i][1]; Vertex a = G.getVertex(idxa); Vertex b = G.getVertex(idxb); G.addEdge(new Edge<Vertex>(a, b)); if (!directed) { G.addEdge(new Edge<Vertex>(b, a)); } } return G; }
b63b0bcc-548c-44cf-bc0e-ca1c886f472b
2
public static void main(String args[]) { In in = new In(args[0]); int N = in.readInt(); UnionFindWQU qf = new UnionFindWQU(N); while (!in.isEmpty()) { int p = in.readInt(); int q = in.readInt(); if (qf.connected(p, q)) continue; qf.union(p, q); System.out.println(p + " " + q); } System.out.println(qf.componentCount() + " components"); }
0475535a-f5fb-48af-992b-010c2f31b38f
3
private void butterflyStage(double[] from, double[] to, int numFftPoints, int currentDistance) { int ndx1From; int ndx2From; int ndx1To; int ndx2To; int ndxWeightFft; if (currentDistance > 0) { int twiceCurrentDistance = 2 * currentDistance; for (int s = 0; s < currentDistance; s++) { ndx1From = s; ndx2From = s + currentDistance; ndx1To = s; ndx2To = s + (numFftPoints >> 1); ndxWeightFft = 0; while (ndxWeightFft < (numFftPoints >> 1)) { /** * <b>weightFftTimesFrom2 = weightFft[k] </b> <b>*from[ndx2From] </b> */ this.weightFftTimesFrom2 = multiplyCmplx(this.weightFft[2 * ndxWeightFft], this.weightFft[2 * ndxWeightFft + 1], from[2 * ndx2From], from[2 * ndx2From + 1]); /** * <b>to[ndx1To] = from[ndx1From] </b> <b>+ weightFftTimesFrom2 </b> */ to[2 * ndx1To] = from[2 * ndx1From] + this.weightFftTimesFrom2[0]; to[2 * ndx1To + 1] = from[2 * ndx1From + 1] + this.weightFftTimesFrom2[1]; /** * <b>to[ndx2To] = from[ndx1From] </b> <b>- weightFftTimesFrom2 </b> */ to[2 * ndx2To] = from[2 * ndx1From] - this.weightFftTimesFrom2[0]; to[2 * ndx2To + 1] = from[2 * ndx1From + 1] - this.weightFftTimesFrom2[1]; ndx1From += twiceCurrentDistance; ndx2From += twiceCurrentDistance; ndx1To += currentDistance; ndx2To += currentDistance; ndxWeightFft += currentDistance; } } /** * This call'd better be the last call in this block, so when it returns we go straight * into the return line below. We switch the <i>to </i> and <i>from </i> variables, the * total number of points remains the same, and the <i>currentDistance </i> is divided * by 2. */ butterflyStage(to, from, numFftPoints, (currentDistance >> 1)); } return; }
c16bf415-8200-4c01-ad78-6aff67aaa526
9
public void readCarvia(String tipo) throws IOException{ InputStream inputStream = null; if (tipo.equals("UR")) inputStream = new FileInputStream(Config.get("UrbanoSHPPath") + "/CARVIA/Carvia.DBF"); else if (tipo.equals("RU")) inputStream = new FileInputStream(Config.get("RusticoSHPPath") + "/CARVIA/Carvia.DBF"); DBFReader reader = new DBFReader(inputStream); int indiceVia = 0; int indiceDenomina = 0; for (int i = 0; i < reader.getFieldCount(); i++) { if (reader.getField(i).getName().equals("VIA")) indiceVia = i; if (reader.getField(i).getName().equals("DENOMINA")) indiceDenomina = i; } Object[] rowObjects; while((rowObjects = reader.nextRecord()) != null) { // La posicion indiceVia es el codigo de via // La posicion indiceDenomina es la denominacion de via if (rowObjects[indiceVia] instanceof Double){ double v = (Double) rowObjects[indiceVia]; ejesNames.put((long) v, (String) rowObjects[indiceDenomina]); } else if (rowObjects[indiceVia] instanceof Long){ ejesNames.put((Long) rowObjects[indiceVia], (String) rowObjects[indiceDenomina]); } else if (rowObjects[indiceVia] instanceof Integer){ int v = (Integer) rowObjects[indiceVia]; ejesNames.put((long) v, (String) rowObjects[indiceDenomina]); } } }
cc5bdf5b-7249-4801-af99-c6c3503f2dd4
6
public static void main(String[] args) { Scanner scan = new Scanner(System.in); Random rand = new Random(); // The default ranges int[][] ranges = {{0,10}, {0,100}, {0,500}, {0,1000}}; try { do { int[] range = getRange(scan, ranges); int min = range[0], max = range[1]; int secret = randomRange(rand, min, max); boolean success = false; int guesses = minimumGuesses(min, max); System.out.println("You have " + guesses + " guess(es) to guess the secret number."); do { if (guesses == 0) { System.out.print("You ran out of guesses. The secret number was " + secret + ". "); break; } int guess = getGuess(scan, min, max); guesses--; if (guess == secret) { System.out.print("CORRECT! You guessed the secret number. "); success = true; } else if (guess < secret) { System.out.println("Your guess is too low, please try again. " + "You have " + guesses + " guess(es) left."); } else if (guess > secret) { System.out.println("Your guess is too high, please try again. " + "You have " + guesses + " guess(es) left."); } else { System.out.println("You broke my program, impressive..."); } } while (!success); } while (keepPlaying(scan)); System.out.println("Good-bye!"); } finally { scan.close(); } }
9f831649-6a9e-42bd-837e-4978fc25e888
0
public List<Park> getParkList() { List<Park> list = new ArrayList<Park>(); list.addAll(this.parkList); return list; }
ff995590-3967-4cc3-8fd2-dd63bf8e94ac
1
public void process() { for (int i = 0; i < 1000; i++) { stageOne(); stageTwo(); } }
a3209cd7-620f-46a7-8de9-e45c58d18289
8
public static Double calcLogSumOfLogs(Double logX, Double logY) { if (logX == null && logY == null) { return null; } else if (logX == null) { return logY; } else if (logY == null) { return logX; } if (logX >= 0 || logY >= 0) { double x = Math.pow(2, logX); double y = Math.pow(2, logY); double logSum = Math.log(x + y) / Math.log(2); return logSum; } double logZ = Math.max(logX, logY) * -1.0; double scaledLogX = logX + logZ; double scaledLogY = logY + logZ; double scaledX = Math.pow(2, scaledLogX); double scaledY = Math.pow(2, scaledLogY); double logScaledSum = Math.log(scaledX + scaledY) / Math.log(2); double logSum = logScaledSum - logZ; if (!(Double.isNaN(logX) || Double.isNaN(logY))) { System.out.println("logX = " + logX + ", logY = " + logY + ", logSum = " + logSum); } return logSum; }
0a0c1189-829e-460d-b315-2f2aa0018886
2
public void setFocused(Configuration configuration) { ConfigurationButton button = (ConfigurationButton) configurationToButtonMap .get(configuration); if (button == null) return; if (button.state == ConfigurationButton.NORMAL) { //System.out.println("Setting color"); button.setState(ConfigurationButton.FOCUSED); button.doClick(); } }
164a1a53-c12d-4084-8877-49b2bed03dc6
5
private void drainOutput() { try { LOGGER.debug("Draining Output"); if ((readyOps & SelectionKey.OP_WRITE) != 0) { Message msg; while ((msg = outQueue.poll()) != null) { LOGGER.debug("Sending message " + msg.toString()); ByteBuffer buffer = msg.toByteBuffer(); channel.write(buffer); } if (outQueue.isEmpty()) { disableWriteSelection(); if (shutingdown) { channel.close(); } } } } catch (IOException e) { LOGGER.warn("remote client ended connection"); this.kill(); } }
ad144528-8fc5-46f7-bb0a-1f7e9c2fde44
2
public FriendsList() { loaded = false; //it's currently not loaded lastMessage = new Date(Calendar.getInstance().getTimeInMillis()); //create friends list friendsList = new JFrame(); //menubar for exit and information menubar = new JMenuBar(); icon = new ImageIcon(getClass().getResource("exit.png")); file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); exitItem = new JMenuItem("Exit", icon); exitItem.setMnemonic(KeyEvent.VK_C); exitItem.setToolTipText("Exit application"); exitItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); file.add(exitItem); help = new JMenu("Help"); helpItem = new JMenuItem("About"); helpItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { aboutBox(); } }); help.add(helpItem); menubar.add(file); menubar.add(help); //temporary text until friends are loaded String loadText = "<br /><br /><br /><br /><h1>Loading Friends List</h1>"; fList = new JEditorPane(new HTMLEditorKit().getContentType(), loadText); ((HTMLDocument) fList.getDocument()).getStyleSheet().addRule(BODY_CSS); //use default system font fList.setEditable(false); fList.setContentType("text/html"); fList.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); fList.setText(loadText); fList.addHyperlinkListener( new HyperlinkListener() { // if user clicked hyperlink, go to specified page public void hyperlinkUpdate(HyperlinkEvent event) { if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { if (Controller.checkClient(event.getDescription()) == false) { //start a new chat session and register with controller Thread ct = new Thread(new ChatSession(event.getDescription())); ct.start(); Controller.addClient(event.getDescription()); } } } // end method hyperlinkUpdate } // end inner class ); fScroller = new JScrollPane(fList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); friendsList.add(fScroller); friendsList.setJMenuBar(menubar); friendsList.setTitle(TwitterChat.getTitle() + " Friends List"); friendsList.setSize(300, 800); friendsList.setLocation(10, 10); //disable shutdown unless user specifically requests exit from menu or system tray friendsList.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } public void windowIconified(java.awt.event.WindowEvent evt) { formWindowIconified(evt); } public void windowDeiconified(java.awt.event.WindowEvent evt) { formWindowDeiconified(evt); } }); }
92b2315e-f9eb-4488-b05e-b81e320cda57
6
public RoundLcdClock() { hColor = new SimpleObjectProperty<>(this, "hourColor", Color.BLACK); mColor = new SimpleObjectProperty<>(this, "minuteColor", Color.rgb(0, 0, 0, 0.5)); m5Color = new SimpleObjectProperty<>(this, "5MinuteColor", Color.BLACK); sColor = new SimpleObjectProperty<>(this, "secondColor", Color.BLACK); timeColor = new SimpleObjectProperty<>(this, "timeColor", Color.BLACK); dateColor = new SimpleObjectProperty<>(this, "dateColor", Color.BLACK); alarmOn = new SimpleBooleanProperty(this, "alarmOn", false); alarm = new SimpleObjectProperty<>(LocalTime.now().minusMinutes(1)); dateVisible = new SimpleBooleanProperty(this, "dateVisible", false); alarmVisible = new SimpleBooleanProperty(this, "alarmVisible", false); time = new StringBuilder(); lastTimerCall = System.nanoTime(); timer = new AnimationTimer() { @Override public void handle(long now) { if (now > lastTimerCall + 100_000_000l) { time.setLength(0); pm = LocalTime.now().get(ChronoField.AMPM_OF_DAY) == 1; hours = LocalTime.now().getHour(); String hourString = Integer.toString(hours); if (hours < 10) { time.append("0"); time.append(hourString.substring(0, 1)); } else { time.append(hourString.substring(0, 1)); time.append(hourString.substring(1)); } time.append(":"); minutes = LocalTime.now().getMinute(); String minutesString = Integer.toString(minutes); if (minutes < 10) { time.append("0"); time.append(minutesString.substring(0, 1)); } else { time.append(minutesString.substring(0, 1)); time.append(minutesString.substring(1)); } seconds = LocalTime.now().getSecond(); if (isAlarmOn() && LocalTime.now().isAfter(getAlarm()) && LocalTime.now().isBefore(getAlarm().plusNanos(105_000_000))) { fireAlarmEvent(); } drawForeground(); lastTimerCall = now; } } }; init(); initGraphics(); registerListeners(); timer.start(); }
e0f02023-9b9a-43d9-a122-e25b01d55cdc
3
public static List fromArray(Object[] array) { if ((array == null) || (array.length == 0)) { return new ArrayList(); } List list = new ArrayList(array.length); for (int i = 0; i < array.length; i++) { list.add(array[i]); } return list; }
61044e49-468c-4a65-9782-e94fc6382099
8
final public void WhileExp() throws ParseException {/*@bgen(jjtree) WhileExp */ SimpleNode jjtn000 = (SimpleNode)SimpleNode.jjtCreate(this, JJTWHILEEXP); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(WHILE); Expression(); jj_consume_token(DO); Expression(); jj_consume_token(END); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
cad0e9f3-3694-42ce-963c-b47b7cd72456
5
public void ThreateningScore(Board b) { char c; if (color == 'W') c = 'B'; else c = 'W'; int score = 0; int best = -10; System.out.println(c); checkThreats(b, c); printThreats(); for (int i = 0; i < numThreatened; i++) { score = toInt(threatened[i]); if (isThreatened(locThreatening[i])) { score += toInt(threatening[i]); } System.out.println(score); makeMove(locThreatened[i], locThreatening[i]); if (isThreatened(locThreatened[i])) { score -= toInt(threatening[i]); } makeMove(locThreatened[i], locThreatening[i]); if (score > best) { best = score; loc1 = locThreatened[i]; loc2 = locThreatening[i]; } } }
5c950c8d-83af-49b9-8c2f-490e54fb6516
4
@Override public void compileClicked(ArrayList<ArrayList<String>> code) { if(checkCorrectInput(code)) { model.compile(new Program(code)); this.setViewOutput(); if(model.isCompileSuccess()){ view.setButtonsEnabled(model.isCompileSuccess()); if(sendToIO) for(int i = 0; i < 10; i++) opin.get(i).low(); } } else { model.setViewToDefault(); this.setViewOutput(); view.setConsoleError(model.getErrorStream().getErrors()); } }
7030920f-5220-4397-ba52-23887c3895c3
3
public int getMaxPacketSize () { int field = getU16 (4); int size = field & 0x3ff; String type = getType (); boolean highspeed = iface.getDevice ().getSpeed () == "high"; // "high bandwidth" mode may use multiple packets per microframe if (highspeed && (type == "iso" || type == "interrupt")) size *= 1 + (field >> 11) & 0x03; return size; }
b2fd84e3-3173-4772-82b2-588927d99e8e
1
public void visitNewArrayExpr(final NewArrayExpr expr) { print("new " + expr.elementType() + "["); if (expr.size() != null) { expr.size().visit(this); } print("]"); }
7c7253e2-9301-4a17-be98-e5dad85bd443
3
public SearchedTrainListFrame(Title myTitle, TrainSchedule TS, String searchTerm) throws IOException { setBackground(new Color(173, 216, 230)); setLayout(null); //===================================== THIS SHOULD TAKE THE OUTPUT FROM THE SEARCH METHOD INSTEAD OF AN IMAGE ========================== JTable label = TS.search(searchTerm); JScrollPane scrollPane = new JScrollPane(label); label.addMouseListener(new MouseAdapter() { @Override //===================================== TAKE WHICH TRAIN IS SELECTED, "SEND" THIS TO THE SELECT METHOD ============================= public void mouseClicked(MouseEvent e) { int[] selected = label.getSelectedRows(); for(int i = 0; i < selected.length; i++){ selectedTrain = (String) label.getValueAt(selected[i], i); } try { ClickedTrainListFrame lblTrainClicked = new ClickedTrainListFrame(myTitle, TS, selectedTrain); previousTrainListContent = (JPanel) myTitle.getContentPane(); myTitle.setContentPane(lblTrainClicked); myTitle.invalidate(); myTitle.validate(); } catch (IOException e1) { e1.printStackTrace(); } } }); scrollPane.setBounds(81, 73, 1120, 513); add(scrollPane, BorderLayout.CENTER); JButton btnUpload = new JButton("Upload another schedule"); btnUpload.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { myTitle.setContentPane(BrowseFrame.previousBrowseContent); myTitle.invalidate(); myTitle.validate(); BrowseFrame.txtBrowse.setText("Browse..."); } }); btnUpload.setBounds(987, 597, 214, 64); add(btnUpload); JButton btnQuit = new JButton("Quit"); btnQuit.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { System.exit(0); } }); btnQuit.setBounds(81, 597, 141, 64); add(btnQuit); JButton btnBack = new JButton("Back"); btnBack.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { myTitle.setContentPane(TrainListFrame.previousTrainListContent); } }); btnBack.setBounds(987, 672, 89, 23); add(btnBack); //===================================== THIS SHOULD RUN THE SAVE METHOD ================================================================= JButton btnSave = new JButton("Save"); btnSave.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { JFileChooser fc = new JFileChooser(); fc.setVisible(true); fc.showSaveDialog(fc); } }); btnSave.setBounds(1112, 672, 89, 23); add(btnSave); txtSearch = new JTextField(); txtSearch.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //searchTerm = txtSearch.getText(); try { SearchedTrainListFrame txtSearched = new SearchedTrainListFrame(myTitle, TS, txtSearch.getText()); previousTrainListContent = (JPanel) myTitle.getContentPane(); myTitle.setContentPane(txtSearched); myTitle.invalidate(); myTitle.validate(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); txtSearch.setText("Search..."); txtSearch.setBounds(1115, 42, 86, 20); add(txtSearch); txtSearch.setColumns(10); //This takes the search term entered by the user. JLabel lblSearchedTerm = new JLabel("Searched for: " + searchTerm); lblSearchedTerm.setBounds(81, 16, 300, 64); add(lblSearchedTerm); //fit text to label Font labelFont = lblSearchedTerm.getFont(); String labelText = lblSearchedTerm.getText(); int stringWidth = lblSearchedTerm.getFontMetrics(labelFont).stringWidth(labelText); int componentWidth = lblSearchedTerm.getWidth(); // Find out how much the font can grow in width. double widthRatio = (double)componentWidth / (double)stringWidth; int newFontSize = (int)(labelFont.getSize() * widthRatio); int componentHeight = lblSearchedTerm.getHeight(); // Pick a new font size so it will not be larger than the height of label. int fontSizeToUse = Math.min(newFontSize, componentHeight); // Set the label's font size to the newly determined size. lblSearchedTerm.setFont(new Font("Lucida Grande", lblSearchedTerm.getFont().getStyle(), lblSearchedTerm.getFont().getSize() + 10)); }
92d28cf6-942a-45f6-9c4e-c48ead8293d3
5
public static void moveSubArray(int[] arr, int from, int to, int offset){ int iters=0; if(from>to){ iters=((arr.length-from)+to)+1; } else { iters=(to-from)+1; } if(offset==1){ int previous=circleIncrement(to, arr.length); for(int i=0;i<iters;i++){ swap(arr,to,previous); previous=to; to=circleDecrement(to,arr.length); } } if(offset==-1){ int previous=circleDecrement(from, arr.length); for(int i=0;i<iters;i++){ swap(arr,from,previous); previous=from; from=circleIncrement(from,arr.length); } } }
5b199b24-df2c-4a67-b339-6a5127e6f753
8
protected void paintBackground(Graphics g, JComponent c, int x, int y, int w, int h) { // if (!AbstractLookAndFeel.getTheme().isDarkTexture()) { // super.paintBackground(g, c, x, y, w, h); // return; // } JMenuItem b = (JMenuItem) c; ButtonModel model = b.getModel(); if (c.getParent() instanceof JMenuBar) { if (model.isRollover() || model.isArmed() || (c instanceof JMenu && model.isSelected())) { TextureUtils.fillComponent(g, c, TextureUtils.ROLLOVER_TEXTURE_TYPE); } } else { if (model.isArmed() || (c instanceof JMenu && model.isSelected())) { TextureUtils.fillComponent(g, c, TextureUtils.ROLLOVER_TEXTURE_TYPE); } else { TextureUtils.fillComponent(g, c, TextureUtils.MENUBAR_TEXTURE_TYPE); } } }
8a405809-533d-4ebe-9ae9-3457eb274f9c
8
final public void Insert() throws ParseException { /*@bgen(jjtree) Insert */ ASTInsert jjtn000 = new ASTInsert(JJTINSERT); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1)); try { jj_consume_token(INSERT); jj_consume_token(INTO); Identifier(); jj_consume_token(38); Columns(); jj_consume_token(40); jj_consume_token(VALUES); jj_consume_token(38); Values(); jj_consume_token(40); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } }
f88acd12-b3bb-4f6d-94c3-0cb86f7e0214
6
public Boolean find(int[] arrA, int x, int y) { int range = y - x; for (int i = 0; i < arrA.length; i++) { if (arrA[i] >= x && arrA[i] <= y) { int z = arrA[i] - x; if (arrA[z] > 0) { arrA[z] = arrA[z] * -1; } } } // for(int i=0;i<arrA.length;i++){ // System.out.print(" " + arrA[i]); // } for (int i = 0; i < range; i++) { if (arrA[i] > 0) return false; } return true; }
0c25e702-d348-48ec-a084-a02a31ca5f76
4
public void saveSongs(List<String> songLinkList, SongParserForOneGenre songParser) { if (songParser != null) { for (String songLink : songLinkList) { if (!DataUtils.isEmpty(songLink)) { try { songParser.pasrePage(songLink); Thread.sleep(delayTime); } catch (IOException | InterruptedException e) { logger.error("", e); } } } } }
4ffe504c-ab85-46f2-a2c7-3a4b24c2d9be
3
public static void initWindowGL(int width, int height, String title) { try { Display.setTitle(title); Display.setDisplayMode(new DisplayMode(width, height)); Display.create(); } catch (LWJGLException e) { e.printStackTrace(); } RenderingEngine.instance.init(); lastFPS = Time.getTime(); while (!Display.isCloseRequested() && !Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) { renderingEngine.render(); int delta = getDelta(); update(delta); Display.update(); Display.sync(60); } // RenderUtil.cleanUP(); Display.destroy(); }
4f1a9603-5ede-4691-b71f-bd4955463b16
1
public JSONObject optJSONObject(String key) { Object object = this.opt(key); return object instanceof JSONObject ? (JSONObject)object : null; }
f3ade82c-0847-4349-9810-f79ebe75ed98
2
private void updateGame() { // If no current block, generate new one if (gameBoard.getCurrentBlock() == null) { gameBoard.completeRows(); gameBoard.newBlock(); gameBoard.setRow(0); gameBoard.setCol(4); if(gameBoard.isValidMove(Direction.DOWN) == false) { isRunning = false; } return; } gameBoard.moveDown(); }
8c64cfeb-e5ac-4fcc-928c-24d8a7d528b7
6
private void handleCheck( CommandSender sender, String label, String[] args) { Collection<GroupSettings> allGroups = mPlugin.getGroups(true); LinkedList<GroupSettings> matching = new LinkedList<GroupSettings>(); for(int i = 0; i < args.length; ++i) { boolean found = false; for(GroupSettings group : allGroups) { if(group.getName().equalsIgnoreCase(args[i])) { found = true; matching.add(group); break; } } if(!found) { sender.sendMessage(ChatColor.RED + "Unknown rule " + args[i]); return; } } sender.sendMessage(ChatColor.GOLD + "Starting check"); if(matching.isEmpty()) mPlugin.checkGroups(true, sender); else { CheckReport report = new CheckReport(sender); for(GroupSettings group : matching) mPlugin.checkGroup(group, report); } }
c0b71b74-214c-435e-9832-bb3af211f1eb
3
private void formatClassFeatures(StringBuilder formatted, List<String> features) { if (!features.isEmpty()) { formatted.append("\\n|"); boolean first = true; for (String feature : features) { if (first) { first = false; } else { formatted.append("\\n"); } formatted.append(ensureTextIsValid(feature)); } } }
eeb5cbc9-6a45-4987-9476-fff1ffa50722
5
direction NNIEdgeTest(edge e, double[][] A, double[] weight, int wIndex ) { int a,b,c,d; edge f; double[] lambda; double D_LR, D_LU, D_LD, D_RD, D_RU, D_DU; double w1,w2,w0; if ( e.tail.leaf() || e.head.leaf() ) return direction.NONE; lambda = new double[3];; a = e.tail.parentEdge.topsize; f = e.siblingEdge(); b = f.bottomsize; c = e.head.leftEdge.bottomsize; d = e.head.rightEdge.bottomsize; lambda[0] = ((double) b*c + a*d)/((a + b)*(c+d)); lambda[1] = ((double) b*c + a*d)/((a + c)*(b+d)); lambda[2] = ((double) c*d + a*b)/((a + d)*(b+c)); D_LR = A[e.head.leftEdge.head.index][e.head.rightEdge.head.index]; D_LU = A[e.head.leftEdge.head.index][e.tail.index]; D_LD = A[e.head.leftEdge.head.index][f.head.index]; D_RU = A[e.head.rightEdge.head.index][e.tail.index]; D_RD = A[e.head.rightEdge.head.index][f.head.index]; D_DU = A[e.tail.index][f.head.index]; w0 = wf2(lambda[0],D_RU,D_LD,D_LU,D_RD,D_DU,D_LR); w1 = wf2(lambda[1],D_RU,D_LD,D_DU,D_LR,D_LU,D_RD); w2 = wf2(lambda[2],D_DU,D_LR,D_LU,D_RD,D_RU,D_LD); if (w0 <= w1) { if (w0 <= w2) //w0 <= w1,w2 { weight[wIndex] = 0.0; return direction.NONE; } else //w2 < w0 <= w1 { weight[wIndex] = w2 - w0; return direction.RIGHT; } } else if (w2 <= w1) //w2 <= w1 < w0 { weight[wIndex] = w2 - w0; return direction.RIGHT; } else //w1 < w2, w0 { weight[wIndex] = w1 - w0; return direction.LEFT; } }
ef450e60-4413-4756-82af-b73137ca8ba0
7
public static void main(String []args) throws ParseException, IOException, WrongArgumentException { CommandLineParser parser = new PosixParser(); Options options = new Options(); HelpFormatter f = new HelpFormatter(); options.addOption("h",false,"Print The help infomation"); options.addOption("s", true, "Chunk Strategy of the partition"); options.addOption("p",true,"Partition strategy"); options.addOption("v",true,"Varible size"); options.addOption("start",true,"start"); options.addOption("off",true,"off"); CommandLine cmd = parser.parse(options, args); if( cmd.hasOption("h")) { f.printHelp("NetCDF Loader", options); System.exit(-1); } String p = cmd.getOptionValue("p"); String v = cmd.getOptionValue("v"); String start = cmd.getOptionValue("start"); String off = cmd.getOptionValue("off"); if(p == null) { f.printHelp("NetCDF Loader", options); System.exit(-1); } String [] ps = p.split(","); String [] vs = v.split(","); String [] starts = start.split(","); String [] offs = off.split(","); int d = ps.length; int [] pshape = new int [d]; int [] vshape = new int [d]; int [] sss = new int[d]; int [] ooo = new int[d]; int i = 0; for( i = 0; i < d; i++) { pshape[i] = Integer.parseInt(ps[i]); vshape[i] = Integer.parseInt(vs[i]); sss[i] = Integer.parseInt(starts[i]); ooo[i] = Integer.parseInt(offs[i]); } String [] ss = cmd.getOptionValues("s"); if( ss == null ) { f.printHelp("NetCDF Loader", options); System.exit(-1); } Vector<int []> shapes = new Vector<int []>(); for(String s:ss) { String [] a = s.split(","); if(a.length != d) { System.out.println("Wrong chunk strategy"); System.exit(-1); } int [] tmp = new int [d]; i = 0; for(String ts: a) { tmp[i++] = Integer.parseInt(ts); } shapes.add(tmp); } shapes.add(pshape); PartitionReader reader = new PartitionReader(); reader.CostEstimate(vshape, pshape, shapes, sss, ooo); }
3fb62a61-a0d0-44cf-8cef-884ec8882b33
4
public BlockFace faceFromYaw(int yaw){ int cYaw = cardinalYaw(yaw); switch (cYaw){ case 0: return BlockFace.SOUTH; case 90: return BlockFace.WEST; case 180: return BlockFace.NORTH; case 270: return BlockFace.EAST; default : return BlockFace.SOUTH; } }
3bab1883-df7d-4d68-9778-13463dada6c8
2
public void selectMode() { String[] modes = {"Play New Game", "Load Saved Game/Level", "Open Level Creator"}; String mode = (String)JOptionPane.showInputDialog( null, "Select mode:\n", "Kraft Dinner Table Game", JOptionPane.QUESTION_MESSAGE, null, modes, modes[0]); if(mode.equals("Play New Game")) { play(); } else if(mode.equals("Load Saved Game/Level")) { playSaved(); } else { new LevelEditorView(); } }
d6607df9-cc65-4350-9bfc-59ab1592bd8e
3
protected void populateButtons() { int month = lMonths.getSelectedIndex(); int year = lYears.getSelectedIndex() + mStartYear; GregorianCalendar gc = new GregorianCalendar(year, month, 1); // Get which day of week is the first day of the month int firstDay = gc.get(Calendar.DAY_OF_WEEK) - 1; // System.out.println("isLeapYear = " + gc.isLeapYear(year) ); int pos = 0; // Disable all the buttons up to the first day while (pos < firstDay) { mButtons[pos++].setDate(null); } int numberOfDaysInMonth = gc.getActualMaximum(Calendar.DAY_OF_MONTH); while (gc.get(Calendar.DAY_OF_MONTH) <= numberOfDaysInMonth) { mButtons[pos++].setDate(gc.getTime()); gc.add(Calendar.DAY_OF_MONTH, 1); } while (pos < mButtons.length) { mButtons[pos].setDate(null); } }
9d53fa1c-3088-48be-b643-c93a97f18027
4
@Override public void handleSimpleTag(HTML.Tag tag, MutableAttributeSet attrs, int pos) { logger.info("SimpleTag: " + tag); HTMLComponent comp = null; for (HTML.Tag t : wantedSimpleTags) { if (t == tag) { comp = HTMLComponentFactory.create(tag, attrs); break; } } if (comp == null && !totallyIgnoreThisTag(tag)) { comp = new GenericHTMLComponent(null, tag.toString()); } logger.info("DOING SIMPLE: " + comp); handleCommon(comp); return; }
4a920b36-8caa-4c3f-be65-2d2ade3fe6e3
1
public void load() { if (!new File(plugin.getDataFolder(), "config.yml").exists()) { plugin.saveDefaultConfig(); } configLoader = (YamlConfiguration) plugin.getConfig(); }
846474c0-1825-4e29-b117-59b87fb7a9c7
7
public boolean validate () { // check primes. BigInteger mm = p.multiply(q); if (!mm.equals (m)) return false; BigInteger pm1 = p.subtract (BigInteger.ONE); BigInteger qm1 = q.subtract (BigInteger.ONE); BigInteger r = pm1.multiply(qm1).divide(pm1.gcd(qm1)); // check public exponent. if (!r.gcd (e).equals (BigInteger.ONE)) return false; // check private exponent BigInteger dd = e.modInverse (r); if (!dd.equals (d)) { // probably just a different representation BigInteger x = d.mod(r); if (!x.equals(dd)) return false; } // check prime exponents and coefficient BigInteger pEE = e.modInverse (pm1); if (!pEE.equals (pE)) return false; BigInteger qEE = e.modInverse (qm1); if (!qEE.equals (qE)) return false; BigInteger coeff = (q.compareTo(p) < 0 ? q.modInverse(p) : p.modInverse(q)); return coeff.equals (crt); }
403bdbd7-32a5-42dc-ab4c-18c8b1a47cd0
6
@Override public void render(RenderContext renderContext) { // System.out.println(getCurrentMatrix().toString()); glMatrixMode(GL_PROJECTION); glLoadMatrix(toFloatBuffer(renderContext.getCamera().getProjection(getViewport().getSize()).m)); glMatrixMode(GL_MODELVIEW); glLoadMatrix(toFloatBuffer(renderContext.getCamera().getTransform().m)); polys = 0; if (Display.wasResized()) { // wasResized = true } else { // wasResized = false } setColor(Color.WHITE); for (InstancedModel iModel : renderContext.getModelGroup().getIModels()) { ModelLoader model = iModel.model; List<InstanceAttributes> instanceAttributes = iModel.attributes; OpenGLModelData openGLModelData = OpenGLModelData.getOpenGLModelData(model); glBindVertexArray(openGLModelData.VAOID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, openGLModelData.VBOIID); if (openGLModelData.normals) glEnableClientState(GL_NORMAL_ARRAY); if (openGLModelData.colors) glEnableClientState(GL_COLOR_ARRAY); if (openGLModelData.textures) { glEnableClientState(GL_TEXTURE_COORD_ARRAY); glBindTexture(GL_TEXTURE_2D, OpenGLTextureData.getOpenGLTextureData(model.texture).id); } for (InstanceAttributes instanceAttribute : instanceAttributes) { glPushMatrix(); //load the model translation matrix float[] m = instanceAttribute.getTransform().m; glMultMatrix(toFloatBuffer(m)); // Draw the vertices glDrawElements(GL_TRIANGLES, model.indices.getSize() * model.indices.getStride(), GL_UNSIGNED_INT, 0); polys += model.indices.getSize(); glPopMatrix(); } // Put everything back to default (deselect) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindVertexArray(0); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glBindTexture(GL_TEXTURE_2D, 0); } // System.out.println(polys + " polygons"); GLErrorHelper.checkError(); }
6442f2a0-753f-466f-88a2-998c3b418ee7
2
private void saveAs_buildPropButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveAs_buildPropButtonActionPerformed JFileChooser buildChooser = new JFileChooser(); buildChooser.setDialogTitle(parser.parse("buildProp:saveAs_title")); buildChooser.setApproveButtonText(parser.parse("buildProp:saveAs_approveButton")); int result = buildChooser.showSaveDialog(null); if (result == JOptionPane.OK_OPTION) try { BufferedWriter writer = new BufferedWriter(new FileWriter(buildChooser.getSelectedFile())); writer.write(jTextArea1.getText()); writer.close(); } catch (IOException ex) { logger.log(Level.ERROR, "An error occurred while attempting to save the build.prop file to the hard drive: " + ex.toString() + "\n" + "The error stack trace will be printed to the console..."); ex.printStackTrace(System.err); } }//GEN-LAST:event_saveAs_buildPropButtonActionPerformed
cc34457c-7235-43b3-ad4d-39775200876a
7
@Override protected TreeNode<K,V> delete(TreeNode<K,V> deleteNode) { TreeNode<K,V> spliceNode = null; // either replacement or deleted ! //case 1, 2 if (deleteNode.left == null || deleteNode.right == null){ spliceNode = deleteNode; } else //case 3 spliceNode = successorWithParent(deleteNode); // at most one node ? // now do the splice botch TreeNode<K,V> spliceChild = null; if (spliceNode.left != null){ spliceChild = spliceNode.left; } else { spliceChild = spliceNode.right; } // point orphaned child to grandparent (new parent) if (spliceChild != null) spliceChild.parent = spliceNode.parent; // point new parent at new child if (spliceNode.parent == null) { //root root = spliceChild; } else if (spliceNode == spliceNode.parent.left) { spliceNode.parent.left = spliceChild; } else { spliceNode.parent.right = spliceChild; } // case 3 if (deleteNode != spliceNode) { deleteNode.key = spliceNode.key; deleteNode.value = spliceNode.value; } return spliceNode; }
8251d8bf-27cc-48a5-b652-cc62ba1a34f3
9
public int insertarTipoMovimiento(String codigo, String descripcion, String accion, String estado) { if(codigo.trim().length()==3 && descripcion.trim().length()>0 && descripcion.trim().length()<=40 && accion.trim().length()>0 && accion.trim().length()<=10 && estado.trim().length()>0 && estado.trim().length()<=15) { if(buscarTipoMovimiento(codigo) == null) { TipoMovimiento tipoM = new TipoMovimiento(codigo, descripcion,accion,estado); String mensaje = new TipoMovimientoDAL().insertarTipoMovimiento(tipoM); if(mensaje == null) { showMessageDialog(null,"Registro insertado","Aviso",1); return 0; } else { showMessageDialog(null,mensaje,"Problema",0); return 1; } }else { showMessageDialog(null,"Código ya existe","Aviso",2); return 2; } }else { showMessageDialog(null,"Datos no válidos","Aviso",0); return 3; } }
a554ce9c-3eaa-4053-b611-758d9f3e93bb
4
@SuppressWarnings({ "rawtypes", "unchecked" }) public PersonRegister() { setBounds(7, 55, 1290, 600); setResizable(false); setModal(true); setLocationRelativeTo(null); // dim = super.,getToolkit().getScreenSize(); // super.setSize(dim); // setLocationRelativeTo(null); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); panel = new JPanel(); panel.setBorder(new TitledBorder(null, "Universitary studies:", TitledBorder.LEFT, TitledBorder.TOP, null, null)); panel.setBounds(10, 252, 349, 231); contentPanel.add(panel); panel.setVisible(false); panel.setLayout(null); panel_4 = new JPanel(); panel.add(panel_4); panel_4.setBorder(new TitledBorder(null, "Technical studies:", TitledBorder.LEFT, TitledBorder.TOP, null, null)); panel_4.setBounds(10, 252, 349, 231); contentPanel.add(panel_4); panel_4.setVisible(false); panel_4.setLayout(null); JLabel label_4 = new JLabel("Certified:"); label_4.setHorizontalAlignment(SwingConstants.TRAILING); label_4.setBounds(10, 27, 107, 14); panel_4.add(label_4); JComboBox comboBox = new JComboBox(); comboBox.setModel(new DefaultComboBoxModel( new String[] { "<Select>", "Human resource management", "Surveying and Geomatics for real estate development", "Atmosphere of premises: Creating and composing styles environments", "Basic Statistical Analysis", "Culinary arts", "Financial audit", "Library and information science", "Chocolate and confectionery", "Configuring and Deploying Windows Server 2008", "Financial accounting", "Address and business management", "Design and development of business models", "Strategic Finance:", "Optimization of resources and investment projection", "Administrative management for executive assistants", "Risk management of information security", "Strategic management of family businesses", "Integrated project management (DIGIP) in real estate and construction in DR", "Management and strategic direction of human capital", "Corporate Taxes: New Trends and tax regulations", "Corporate Intelligence", "Intermediate English", "Measurement, redesign and process improvements", "Supply chain management", "Techniques of computer assisted audit (TAAC'S)" })); comboBox.setBounds(127, 24, 219, 20); panel_4.add(comboBox); JLabel label_1 = new JLabel("Specialized \r\ncourses:"); label_1.setHorizontalAlignment(SwingConstants.TRAILING); label_1.setBounds(10, 48, 107, 22); panel_4.add(label_1); JComboBox comboBox_5 = new JComboBox(); comboBox_5 .setModel(new DefaultComboBoxModel( new String[] { "<Select>", "Knowing the stock market DR", "Cost control for food and beverage operations", "IT network essential", "Effective management of social networks", "Sales Forecast", "Specialized techniques in preparation of meat: Cortes, cooking, completion and presentation" })); comboBox_5.setBounds(127, 49, 219, 20); panel_4.add(comboBox_5); JLabel label_2 = new JLabel("Technical college:"); label_2.setHorizontalAlignment(SwingConstants.TRAILING); label_2.setBounds(10, 73, 107, 22); panel_4.add(label_2); JComboBox comboBox_6 = new JComboBox(); comboBox_6.setModel(new DefaultComboBoxModel(new String[] { "<Select>", "Small and medium enterprises", "Advertising", "Market aspects", "Graphic design", "Programming information systems", "Computerized accounting", "Financial and tax accounting" })); comboBox_6.setBounds(127, 74, 219, 20); panel_4.add(comboBox_6); JLabel label_3 = new JLabel("Job:"); label_3.setHorizontalAlignment(SwingConstants.TRAILING); label_3.setBounds(10, 98, 107, 22); panel_4.add(label_3); JComboBox comboBox_7 = new JComboBox(); comboBox_7.setModel(new DefaultComboBoxModel(new String[] { "<Select>", "Accountant", "Actor / Actress", "Air hostess", "Archaeologist", "Astronaut", "Baker", "Biologist", "Bricklayer", "Bus driver", "Businessman", "Businesswoman", "Butcher", "Caretaker", "Carpenter", "Cashier", "Cleaner", "Clown", "Cobbler", "Consultant", "Cook", "Counselor", "Chef", "Chemist", "Dancer", "Decorator", "Dentist", "Designer", "Dressmaker", "Dustman", "Economist", "Electrician", "Farmer", "Fireman", "FIsherman", "Florist", "Fruiterer", "Garbage collector", "Gardener", "Hairdresser", "Housewife", "Hunter", "Jeweller", "Judge", "Lawyer", "Librarian", "Life guard", "Lorry driver", "Mailman", "Mechanic", "Meteorologist", "Miner", "Model", "Monk", "Nanny", "Nun", "Nurse", "Nursemaid", "Office worker", "Painter", "Pastry cook", "Pharmacist", "Photographer", "Physicist", "Plumber", "Policeman / Policewoman", "Politician", "Porter", "Postman", "Priest", "Professor", "Programmer", "Psychiatrist", "Psychologist", "Receptionist", "Researcher", "Sailor", "Salesman", "Scientist", "Secretary", "Secretary", "Shoemaker", "Shop assistant", " Singer", "Social worker", "Surgeon", "Taxi driver", "Teacher", "Telephone operator", "Travel agent", "Truck driver", "Vet", "Veterinarian", "Waiter", "Waitress", "Window cleaner", "Writer" })); comboBox_7.setBounds(127, 99, 219, 20); panel_4.add(comboBox_7); panel_5 = new JPanel(); panel_5.setBorder(new TitledBorder(null, "Other studies:", TitledBorder.LEFT, TitledBorder.TOP, null, null)); panel_4.setBounds(10, 252, 349, 231); contentPanel.add(panel_5); panel_5.setVisible(false); panel_5.setLayout(null); { JLabel label = new JLabel("Certified:"); label.setHorizontalAlignment(SwingConstants.TRAILING); label.setBounds(10, 25, 107, 14); panel_5.add(label); } { JComboBox comboBox_8 = new JComboBox(); comboBox_8 .setModel(new DefaultComboBoxModel( new String[] { "<Select>", "Human resource management", "Surveying and Geomatics for real estate development", "Atmosphere of premises: Creating and composing styles environments", "Basic Statistical Analysis", "Culinary arts", "Financial audit", "Library and information science", "Chocolate and confectionery", "Configuring and Deploying Windows Server 2008", "Financial accounting", "Address and business management", "Design and development of business models", "Strategic Finance:", "Optimization of resources and investment projection", "Administrative management for executive assistants", "Risk management of information security", "Strategic management of family businesses", "Integrated project management (DIGIP) in real estate and construction in DR", "Management and strategic direction of human capital", "Corporate Taxes: New Trends and tax regulations", "Corporate Intelligence", "Intermediate English", "Measurement, redesign and process improvements", "Supply chain management", "Techniques of computer assisted audit (TAAC'S)" })); comboBox_8.setBounds(127, 22, 219, 20); panel_5.add(comboBox_8); } { JLabel label = new JLabel("Specialized \r\ncourses:"); label.setHorizontalAlignment(SwingConstants.TRAILING); label.setBounds(10, 46, 107, 22); panel_5.add(label); } { JComboBox comboBox_8 = new JComboBox(); comboBox_8 .setModel(new DefaultComboBoxModel( new String[] { "<Select>", "Knowing the stock market DR", "Cost control for food and beverage operations", "IT network essential", "Effective management of social networks", "Sales Forecast", "Specialized techniques in preparation of meat: Cortes, cooking, completion and presentation" })); comboBox_8.setBounds(127, 47, 219, 20); panel_5.add(comboBox_8); } { JLabel label = new JLabel("Job:"); label.setHorizontalAlignment(SwingConstants.TRAILING); label.setBounds(10, 72, 107, 22); panel_5.add(label); } { JComboBox comboBox_8 = new JComboBox(); comboBox_8.setModel(new DefaultComboBoxModel(new String[] { "<Select>", "Accountant", "Actor / Actress", "Air hostess", "Archaeologist", "Astronaut", "Baker", "Biologist", "Bricklayer", "Bus driver", "Businessman", "Businesswoman", "Butcher", "Caretaker", "Carpenter", "Cashier", "Cleaner", "Clown", "Cobbler", "Consultant", "Cook", "Counselor", "Chef", "Chemist", "Dancer", "Decorator", "Dentist", "Designer", "Dressmaker", "Dustman", "Economist", "Electrician", "Farmer", "Fireman", "FIsherman", "Florist", "Fruiterer", "Garbage collector", "Gardener", "Hairdresser", "Housewife", "Hunter", "Jeweller", "Judge", "Lawyer", "Librarian", "Life guard", "Lorry driver", "Mailman", "Mechanic", "Meteorologist", "Miner", "Model", "Monk", "Nanny", "Nun", "Nurse", "Nursemaid", "Office worker", "Painter", "Pastry cook", "Pharmacist", "Photographer", "Physicist", "Plumber", "Policeman / Policewoman", "Politician", "Porter", "Postman", "Priest", "Professor", "Programmer", "Psychiatrist", "Psychologist", "Receptionist", "Researcher", "Sailor", "Salesman", "Scientist", "Secretary", "Secretary", "Shoemaker", "Shop assistant", " Singer", "Social worker", "Surgeon", "Taxi driver", "Teacher", "Telephone operator", "Travel agent", "Truck driver", "Vet", "Veterinarian", "Waiter", "Waitress", "Window cleaner", "Writer" })); comboBox_8.setBounds(127, 73, 219, 20); panel_5.add(comboBox_8); } { JLabel lblPu = new JLabel("Grade:"); lblPu.setHorizontalAlignment(SwingConstants.TRAILING); lblPu.setBounds(10, 26, 107, 14); panel.add(lblPu); } JComboBox comboBox_2 = new JComboBox(); comboBox_2 .setModel(new DefaultComboBoxModel( new String[] { "<Select>", "Business adm. mention operations", "Business adm. mention finance", "Business adm. mention strategy", "Business adm. mention creation and development of new business", "Business adm. mention human gestion", "Business adm. mention international business", "Hotel management mention food and drink", "Hotel management mention hotel marketing", "Architecture", "Social communication mention audiovisual production", "Social communication mention corporate communication", "Law", "Design and interior", "Ecology and environmental management", "Economy", "Education", "Nursing", "Stomatology", "Phylosophy", "Financial management and auditing", "Civil Engineering", "Electromechanical Engineering mention mechanical", "Electronechanical Engineerin mention electric", "Industrial Engineering", "System and computer Engineering", "Electronic Engineering", "Telematic Engineering", "Medicine", "Marketing", "Nutrition and dietetics", "Psychology", "Physical therapy" })); comboBox_2.setBounds(127, 23, 219, 20); panel.add(comboBox_2); JLabel lblPostgrade = new JLabel("Post-grade:"); lblPostgrade.setHorizontalAlignment(SwingConstants.TRAILING); lblPostgrade.setBounds(10, 51, 107, 14); panel.add(lblPostgrade); JComboBox comboBox_3 = new JComboBox(); comboBox_3 .setModel(new DefaultComboBoxModel( new String[] { "<Select>", "Executive Master in Strategic Human Resources", "Master of Strategic Management", "MBA in Insurance Programs", "LLM in Economic Regulation", "Master of Labour Law and Social Security", "MSc in Real Estate", "Master of Intellectual Property and New Technologies", "Master of Law in Corporate Business", "Master of International Relations", "Master of Public Policy", "Master of Business Economics", "Executive Master in Supply Chain Management", "Architectural Design Master of Interior Architecture Concentration", "Architectural Design Master of Architecture mention Tourist Accommodation", "Specialization in Applied Mathematics in Education", "Specialization in Mathematics Education Basic Level" })); comboBox_3.setBounds(127, 48, 219, 20); panel.add(comboBox_3); { JLabel lblCertified = new JLabel("Certified:"); lblCertified.setHorizontalAlignment(SwingConstants.TRAILING); lblCertified.setBounds(10, 79, 107, 14); panel.add(lblCertified); } { JComboBox comboBox_4 = new JComboBox(); comboBox_4 .setModel(new DefaultComboBoxModel( new String[] { "<Select>", "Human resource management", "Surveying and Geomatics for real estate development", "Atmosphere of premises: Creating and composing styles environments", "Basic Statistical Analysis", "Culinary arts", "Financial audit", "Library and information science", "Chocolate and confectionery", "Configuring and Deploying Windows Server 2008", "Financial accounting", "Address and business management", "Design and development of business models", "Strategic Finance:", "Optimization of resources and investment projection", "Administrative management for executive assistants", "Risk management of information security", "Strategic management of family businesses", "Integrated project management (DIGIP) in real estate and construction in DR", "Management and strategic direction of human capital", "Corporate Taxes: New Trends and tax regulations", "Corporate Intelligence", "Intermediate English", "Measurement, redesign and process improvements", "Supply chain management", "Techniques of computer assisted audit (TAAC'S)" })); comboBox_4.setBounds(127, 76, 219, 20); panel.add(comboBox_4); } { JLabel lblSpecializedCourses = new JLabel( "Specialized \r\ncourses:"); lblSpecializedCourses .setHorizontalAlignment(SwingConstants.TRAILING); lblSpecializedCourses.setBounds(10, 102, 107, 22); panel.add(lblSpecializedCourses); } { JComboBox comboBox_4 = new JComboBox(); comboBox_4 .setModel(new DefaultComboBoxModel( new String[] { "<Select>", "Knowing the stock market DR", "Cost control for food and beverage operations", "IT network essential", "Effective management of social networks", "Sales Forecast", "Specialized techniques in preparation of meat: Cortes, cooking, completion and presentation" })); comboBox_4.setBounds(127, 103, 219, 20); panel.add(comboBox_4); } { JLabel lblTechnicalCollege = new JLabel("Technical college:"); lblTechnicalCollege.setHorizontalAlignment(SwingConstants.TRAILING); lblTechnicalCollege.setBounds(10, 127, 107, 22); panel.add(lblTechnicalCollege); } { JComboBox comboBox_4 = new JComboBox(); comboBox_4 .setModel(new DefaultComboBoxModel(new String[] { "<Select>", "Small and medium enterprises", "Advertising", "Market aspects", "Graphic design", "Programming information systems", "Computerized accounting", "Financial and tax accounting" })); comboBox_4.setBounds(127, 128, 219, 20); panel.add(comboBox_4); } { JLabel lblDoctorate = new JLabel("Doctorate:"); lblDoctorate.setHorizontalAlignment(SwingConstants.TRAILING); lblDoctorate.setBounds(10, 155, 107, 22); panel.add(lblDoctorate); } { JComboBox comboBox_4 = new JComboBox(); comboBox_4 .setModel(new DefaultComboBoxModel( new String[] { "<Select>", "Constitutional Law and Fundamental Rights", "Democratic Society, State and Law", "Education (and/or in leadership or in pedagogical sciencies)", "Business studies", "Cooperation and Social Intervention", "Educational Psychology and Human Development", "Economy", "Sociology", "Philosophy for a Global World" })); comboBox_4.setBounds(127, 156, 219, 20); panel.add(comboBox_4); } JLabel lblJob = new JLabel("Job:"); lblJob.setHorizontalAlignment(SwingConstants.TRAILING); lblJob.setBounds(10, 181, 107, 22); panel.add(lblJob); JComboBox comboBox_4_1 = new JComboBox(); comboBox_4_1.setModel(new DefaultComboBoxModel(new String[] { "<Select>", "Accountant", "Actor / Actress", "Air hostess", "Archaeologist", "Astronaut", "Baker", "Biologist", "Bricklayer", "Bus driver", "Businessman", "Businesswoman", "Butcher", "Caretaker", "Carpenter", "Cashier", "Cleaner", "Clown", "Cobbler", "Consultant", "Cook", "Counselor", "Chef", "Chemist", "Dancer", "Decorator", "Dentist", "Designer", "Dressmaker", "Dustman", "Economist", "Electrician", "Farmer", "Fireman", "FIsherman", "Florist", "Fruiterer", "Garbage collector", "Gardener", "Hairdresser", "Housewife", "Hunter", "Jeweller", "Judge", "Lawyer", "Librarian", "Life guard", "Lorry driver", "Mailman", "Mechanic", "Meteorologist", "Miner", "Model", "Monk", "Nanny", "Nun", "Nurse", "Nursemaid", "Office worker", "Painter", "Pastry cook", "Pharmacist", "Photographer", "Physicist", "Plumber", "Policeman / Policewoman", "Politician", "Porter", "Postman", "Priest", "Professor", "Programmer", "Psychiatrist", "Psychologist", "Receptionist", "Researcher", "Sailor", "Salesman", "Scientist", "Secretary", "Secretary", "Shoemaker", "Shop assistant", " Singer", "Social worker", "Surgeon", "Taxi driver", "Teacher", "Telephone operator", "Travel agent", "Truck driver", "Vet", "Veterinarian", "Waiter", "Waitress", "Window cleaner", "Writer" })); comboBox_4_1.setBounds(127, 182, 219, 20); panel.add(comboBox_4_1); JLabel lblId = new JLabel("ID:"); lblId.setHorizontalAlignment(SwingConstants.TRAILING); lblId.setVerticalAlignment(SwingConstants.BOTTOM); lblId.setBounds(10, 11, 68, 14); contentPanel.add(lblId); textField = new JTextField(); textField.setBounds(106, 8, 124, 20); contentPanel.add(textField); textField.setColumns(10); table = new JTable(); table.setBorder(new LineBorder(new Color(0, 0, 0))); table.setBounds(35, 400, 400, 200); tableModel = new DefaultTableModel(); String[] columnNames = { "#", "ID", "Name", "Last name", "Born date", "Nacionality", "Sex", "Civil state" }; tableModel.setColumnIdentifiers(columnNames); loadCandidate(); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(1343, 267, -1331, 428); contentPanel.add(scrollPane); { JPanel panel_1 = new JPanel(); panel_1.setBorder(new TitledBorder(null, "Personal data:", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel_1.setBounds(10, 48, 272, 201); contentPanel.add(panel_1); panel_1.setLayout(null); { JLabel lblName = new JLabel("Name:"); lblName.setBounds(21, 27, 68, 14); panel_1.add(lblName); lblName.setHorizontalAlignment(SwingConstants.TRAILING); lblName.setVerticalAlignment(SwingConstants.BOTTOM); } { textField_1 = new JTextField(); textField_1.setBounds(117, 24, 130, 20); panel_1.add(textField_1); textField_1.setColumns(10); } { JLabel lblLastName = new JLabel("Last name:"); lblLastName.setBounds(21, 51, 68, 14); panel_1.add(lblLastName); lblLastName.setHorizontalAlignment(SwingConstants.TRAILING); lblLastName.setVerticalAlignment(SwingConstants.BOTTOM); } { textField_2 = new JTextField(); textField_2.setBounds(117, 48, 130, 20); panel_1.add(textField_2); textField_2.setColumns(10); } { JLabel lblBornDate = new JLabel("Born date:"); lblBornDate.setBounds(21, 71, 68, 20); panel_1.add(lblBornDate); lblBornDate.setHorizontalAlignment(SwingConstants.TRAILING); } JSpinner spinner = new JSpinner(); spinner.setBounds(117, 71, 130, 20); panel_1.add(spinner); spinner.setModel(new SpinnerDateModel(new Date(-946756800000L), new Date(-946756800000L), new Date(915163200000L), Calendar.DAY_OF_YEAR)); { JComboBox comboBox_1_1 = new JComboBox(); comboBox_1_1.setBounds(117, 95, 130, 20); panel_1.add(comboBox_1_1); comboBox_1_1.setModel(new DefaultComboBoxModel(new String[] { "<Select>", "Afghan", "American", "Argentinian", "Australian", "Austrian", "Belgian", "Bolivian", "Brazilian", "British", "Bulgarian", "Canadian", "Chilean", "Chinese", "Colombian", "Costa Rican", "Cuban", "Czech", "Danish", "Dominican", "Dutch", "Ecuadorean", "Egyptian", "English", "Filipino ", "Finnish ", "French ", "German ", "Greek ", "Greenlander ", "Guatemalan ", "Haitian ", "Hawaiian ", "Honduran ", "Hungarian ", "Icelandic ", "Indian ", "Indonesian ", "Iranian ", "Iraqui ", "Irish ", "Israeli ", "Italian ", "Jamaican ", "Japanese ", "korean ", "Lebanese ", "Malaysian ", "Maltese ", "Mexican ", "Moroccan ", "Nepalese ", "New Zealander ", "Nicaraguan ", "Nigerian ", "Norwegian ", "Pakistani ", "Palestinian ", "Panamanian", "Paraguayan ", "Peruvian ", "Polish ", "Portuguese ", "Puerto Rican ", "Rumanian ", "Russian ", "Saudi Arabian ", "Scottish ", "Singaporean ", "Spanish ", "Swedish ", "Swiss ", "Syrian ", "Tahitian ", "Thai ", "Tunisian ", "Turkish ", "Ukrainian ", "Uruguayan ", "Venezuelan ", "Vietnamese ", "Welsh ", "Yugoslavian " })); } { JLabel lblNacionality = new JLabel("Nacionality:"); lblNacionality.setBounds(21, 95, 68, 20); panel_1.add(lblNacionality); lblNacionality.setHorizontalAlignment(SwingConstants.TRAILING); } { JComboBox comboBox_1_1 = new JComboBox(); comboBox_1_1.setBounds(117, 119, 130, 20); panel_1.add(comboBox_1_1); comboBox_1_1.setModel(new DefaultComboBoxModel(new String[] { "<Select>", "Female", "Male" })); } { JLabel lblSex = new JLabel("Sex:"); lblSex.setBounds(21, 119, 68, 20); panel_1.add(lblSex); lblSex.setHorizontalAlignment(SwingConstants.TRAILING); } { JLabel lblCivilState = new JLabel("Civil state:"); lblCivilState.setBounds(21, 143, 68, 20); panel_1.add(lblCivilState); lblCivilState.setHorizontalAlignment(SwingConstants.TRAILING); } { JComboBox comboBox_1_1 = new JComboBox(); comboBox_1_1.setBounds(117, 143, 130, 20); panel_1.add(comboBox_1_1); comboBox_1_1.setModel(new DefaultComboBoxModel(new String[] { "<Select>", "Single", "Married", "Dirvorced", "Widowed", "Engaged", "Other" })); } comboBox_1 = new JComboBox(); comboBox_1.setBounds(117, 167, 130, 20); panel_1.add(comboBox_1); comboBox_1.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent arg0) { if (comboBox_1.getSelectedItem() == "Tecnical") { panel.setVisible(false); panel_4.setVisible(true); panel_5.setVisible(false); } if (comboBox_1.getSelectedItem() == "Universitary") { panel_4.setVisible(false); panel.setVisible(true); panel_5.setVisible(false); } if (comboBox_1.getSelectedItem() == "Other") { panel_5.setVisible(true); panel.setVisible(false); panel_4.setVisible(false); } if ((comboBox_1.getSelectedItem() == "<Select>")) { panel_5.setVisible(false); panel.setVisible(false); panel_4.setVisible(false); } } }); comboBox_1.setModel(new DefaultComboBoxModel(new String[] { "<Select>", "Universitary", "Technical", "Other" })); JLabel lblSyudyLevel = new JLabel("Study level:"); lblSyudyLevel.setBounds(10, 170, 82, 14); panel_1.add(lblSyudyLevel); lblSyudyLevel.setHorizontalAlignment(SwingConstants.TRAILING); { JPanel panel_2 = new JPanel(); panel_2.setBorder(new TitledBorder(null, "Contact:", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel_2.setBounds(292, 52, 510, 195); contentPanel.add(panel_2); panel_2.setLayout(null); { JPanel panel_3 = new JPanel(); panel_3.setBorder(new TitledBorder(null, "Adress:", TitledBorder.LEFT, TitledBorder.TOP, null, null)); panel_3.setBounds(10, 77, 490, 116); panel_2.add(panel_3); panel_3.setLayout(null); { JLabel label = new JLabel("Street:"); label.setBounds(10, 25, 68, 14); panel_3.add(label); label.setVerticalAlignment(SwingConstants.BOTTOM); label.setHorizontalAlignment(SwingConstants.TRAILING); } { textField_8 = new JTextField(); textField_8.setBounds(108, 22, 130, 20); panel_3.add(textField_8); textField_8.setColumns(10); } { JLabel label = new JLabel("Number:"); label.setBounds(10, 53, 68, 14); panel_3.add(label); label.setVerticalAlignment(SwingConstants.BOTTOM); label.setHorizontalAlignment(SwingConstants.TRAILING); } { textField_7 = new JTextField(); textField_7.setBounds(108, 50, 130, 20); panel_3.add(textField_7); textField_7.setColumns(10); } { JLabel lblCountry = new JLabel("Country:"); lblCountry.setBounds(10, 80, 68, 14); panel_3.add(lblCountry); lblCountry.setVerticalAlignment(SwingConstants.BOTTOM); lblCountry .setHorizontalAlignment(SwingConstants.TRAILING); } { JLabel lblSector = new JLabel("Sector:"); lblSector.setBounds(262, 22, 88, 14); panel_3.add(lblSector); lblSector.setVerticalAlignment(SwingConstants.BOTTOM); lblSector .setHorizontalAlignment(SwingConstants.TRAILING); } { textField_10 = new JTextField(); textField_10.setBounds(360, 21, 120, 20); panel_3.add(textField_10); textField_10.setColumns(10); } { JLabel lblCity = new JLabel("City:"); lblCity.setBounds(262, 58, 88, 14); panel_3.add(lblCity); lblCity.setVerticalAlignment(SwingConstants.BOTTOM); lblCity.setHorizontalAlignment(SwingConstants.TRAILING); } { textField_9 = new JTextField(); textField_9.setBounds(360, 52, 120, 20); panel_3.add(textField_9); textField_9.setColumns(10); } { JLabel lblRegion = new JLabel("Region:"); lblRegion.setBounds(264, 89, 86, 14); panel_3.add(lblRegion); lblRegion.setVerticalAlignment(SwingConstants.BOTTOM); lblRegion .setHorizontalAlignment(SwingConstants.TRAILING); } { textField_11 = new JTextField(); textField_11.setBounds(360, 86, 120, 20); panel_3.add(textField_11); textField_11.setColumns(10); } { JComboBox comboBox_1_1 = new JComboBox(); comboBox_1_1.setBounds(108, 77, 130, 20); panel_3.add(comboBox_1_1); comboBox_1_1 .setModel(new DefaultComboBoxModel( new String[] { "<Select>", "Afghanistan ", "Albania ", "Algeria ", "American Samoa ", "Andorra ", "Angola", "Anguilla ", "Antarctica ", "Antigua and Barbuda ", "Argentina ", "Armenia ", "Aruba ", "Australia ", "Austria ", "Azerbaijan ", "Bahamas ", "Bahrain ", "Bangladesh ", "Barbados ", "Belarus ", "Belgium ", "Belize ", "Benin ", "Bermuda ", "Bhutan", "Bolivia ", "Bosnia and Herzegovina ", "Botswana ", "Brazil ", "Brunei Darussalam", "Bulgaria ", "Burkina Faso ", "Burundi ", "Cambodia ", "Cameroon ", "Canada ", "Cape Verde ", "Cayman Islands ", "Central African Republic ", "Chad ", "Chile ", "China ", "Christmas Island ", "Cocos (Keeling) Islands ", "Colombia ", "Comoros ", "Democratic Republic of the Congo (Kinshasa) ", "Congo, Republic of (Brazzaville) ", "Cook Islands ", "Costa Rica ", "Ivory Coast (Cote d'Ivoire) ", "Croatia ", "Cuba ", "Cyprus ", "Czech Republic ", "Denmark ", "Djibouti ", "Dominica ", "Dominican Republic ", "East Timor Timor-Leste ", "Ecuador ", "Egypt ", "El Salvador ", "Equatorial Guinea ", "Eritrea ", "Estonia ", "Ethiopia ", "Falkland Islands ", "Faroe Islands ", "Fiji ", "Finland ", "France ", "French Guiana ", "French Polynesia ", "French Southern Territories ", "Gabon ", "Gambia ", "Georgia ", "Germany ", "Ghana ", "Gibraltar ", "Great Britain ", "Greece ", "Greenland ", "Grenada ", "Guadeloupe ", "Guam ", "Guatemala ", "Guinea ", "Guinea-Bissau ", "Guyana ", "Haiti ", "Holy See ", "Honduras ", "Hong Kong ", "Hungary ", "Iceland ", "India ", "Indonesia ", "Iran (Islamic Republic of) ", "Iraq", "Ireland ", "Israel ", "Italy ", "Jamaica ", "Japan ", "Jordan ", "Kazakhstan ", "Kenya ", "Kiribati", "Korea, Democratic People's Rep. (North Korea)", "Korea, Republic of (South Korea)", "Kosovo", "Kuwait ", "Kyrgyzstan", "Lao, People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macao", "Macedonia, Rep. of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federal States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Myanmar, Burma", "Namibia", "Nauru ", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Palestinian territories", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn Island", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion Island", "Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saint Tome and Principe ", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Sudan", "Spain", "Sri Lanka", "Sudan", "Suriname", "Swaziland", "Sweden", "Switzerland", "Syria", "Taiwan (Republic of China)", "Tajikistan", "Tanzania", "Thailand", "Tibet", "Timor-Leste (East Timor)", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey ", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay", "Uzbekistan", "Vanuatu", "Vatican City State (Holy See)", "Venezuela", "Vietnam", "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna Islands", "Western Sahara", "Yemen", "Zambia", "Zimbabwe" })); } } { JLabel lblEmail = new JLabel("E-mail:"); lblEmail.setBounds(15, 26, 68, 14); panel_2.add(lblEmail); lblEmail.setVerticalAlignment(SwingConstants.BOTTOM); lblEmail.setHorizontalAlignment(SwingConstants.TRAILING); } { textField_3 = new JTextField(); textField_3.setBounds(111, 23, 136, 20); panel_2.add(textField_3); textField_3.setColumns(10); } { JLabel lblCellphone = new JLabel("Cell-phone:"); lblCellphone.setBounds(15, 57, 68, 14); panel_2.add(lblCellphone); lblCellphone.setVerticalAlignment(SwingConstants.BOTTOM); lblCellphone .setHorizontalAlignment(SwingConstants.TRAILING); } { textField_4 = new JTextField(); textField_4.setBounds(111, 54, 136, 20); panel_2.add(textField_4); textField_4.setColumns(10); } { JLabel lblTelephone = new JLabel("Telephone:"); lblTelephone.setBounds(272, 26, 88, 14); panel_2.add(lblTelephone); lblTelephone.setVerticalAlignment(SwingConstants.BOTTOM); lblTelephone .setHorizontalAlignment(SwingConstants.TRAILING); } { textField_5 = new JTextField(); textField_5.setBounds(370, 23, 119, 20); panel_2.add(textField_5); textField_5.setColumns(10); } { JLabel lblPostalCode = new JLabel("Postal code:"); lblPostalCode.setBounds(274, 57, 86, 14); panel_2.add(lblPostalCode); lblPostalCode.setVerticalAlignment(SwingConstants.BOTTOM); lblPostalCode .setHorizontalAlignment(SwingConstants.TRAILING); } { textField_6 = new JTextField(); textField_6.setBounds(370, 54, 119, 20); panel_2.add(textField_6); textField_6.setColumns(10); } } JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { setVisible(false); } }); { JButton btnDelete = new JButton("Delete"); buttonPane.add(btnDelete); } { JButton btnUpdate = new JButton("Update"); buttonPane.add(btnUpdate); } JButton btnRegister = new JButton("Register"); buttonPane.add(btnRegister); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { dispose(); } }); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } }
992fed05-e4e9-433f-b69a-117749da7e41
2
private static String makeUrl(String filename) throws MalformedURLException { final String url; if (filename.indexOf("://") > 0 || filename.startsWith("file:")) { url = filename; } else { url = new File(filename).toURI().toString(); } return url; }