method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
b06f1929-0eee-4963-9291-58a93dfc17f8
5
public Writer write(Writer writer) throws JSONException { try { boolean commanate = false; Iterator keys = this.keys(); writer.write('{'); while (keys.hasNext()) { if (commanate) { writer.write(','); } Object key = keys.next(); writer.write(quote(key.toString())); writer.write(':'); Object value = this.map.get(key); if (value instanceof JSONObject) { ((JSONObject)value).write(writer); } else if (value instanceof JSONArray) { ((JSONArray)value).write(writer); } else { writer.write(valueToString(value)); } commanate = true; } writer.write('}'); return writer; } catch (IOException exception) { throw new JSONException(exception); } }
fb11fc2d-4d1f-4cad-999f-f84803b193d4
0
public void synchonizeDefaultMenuItem() { OutlinerSubMenuItem openMenu = (OutlinerSubMenuItem) GUITreeLoader.reg.get(GUITreeComponentRegistry.OPEN_MENU_ITEM); OpenFileMenuItem openMenuItem = (OpenFileMenuItem) openMenu.getItem(0); openMenuItem.setProtocol(getDefault()); OutlinerSubMenuItem importMenu = (OutlinerSubMenuItem) GUITreeLoader.reg.get(GUITreeComponentRegistry.IMPORT_MENU_ITEM); ImportFileMenuItem importMenuItem = (ImportFileMenuItem) importMenu.getItem(0); importMenuItem.setProtocol(getDefault()); OutlinerSubMenuItem saveAsMenu = (OutlinerSubMenuItem) GUITreeLoader.reg.get(GUITreeComponentRegistry.SAVE_AS_MENU_ITEM); SaveAsFileMenuItem saveAsMenuItem = (SaveAsFileMenuItem) saveAsMenu.getItem(0); saveAsMenuItem.setProtocol(getDefault()); OutlinerSubMenuItem exportMenu = (OutlinerSubMenuItem) GUITreeLoader.reg.get(GUITreeComponentRegistry.EXPORT_MENU_ITEM); ExportFileMenuItem exportMenuItem = (ExportFileMenuItem) exportMenu.getItem(0); exportMenuItem.setProtocol(getDefault()); OutlinerSubMenuItem exportSelectionMenu = (OutlinerSubMenuItem) GUITreeLoader.reg.get(GUITreeComponentRegistry.EXPORT_SELECTION_MENU_ITEM); ExportSelectionFileMenuItem exportSelectionMenuItem = (ExportSelectionFileMenuItem) exportSelectionMenu.getItem(0); exportSelectionMenuItem.setProtocol(getDefault()); }
4983f48b-1b50-4bee-a070-c43ec71dc764
4
private static String generateKey() { Random r = new Random(); long maxNumber = 4294967295L; long spaces = r.nextInt( 12 ) + 1; int max = new Long( maxNumber / spaces ).intValue(); max = Math.abs( max ); int number = r.nextInt( max ) + 1; long product = number * spaces; String key = Long.toString( product ); // always insert atleast one random character int numChars = r.nextInt( 12 ) + 1; for( int i = 0 ; i < numChars ; i++ ) { int position = r.nextInt( key.length() ); position = Math.abs( position ); char randChar = (char) ( r.nextInt( 95 ) + 33 ); // exclude numbers here if( randChar >= 48 && randChar <= 57 ) { randChar -= 15; } key = new StringBuilder( key ).insert( position, randChar ).toString(); } for( int i = 0 ; i < spaces ; i++ ) { int position = r.nextInt( key.length() - 1 ) + 1; position = Math.abs( position ); key = new StringBuilder( key ).insert( position, "\u0020" ).toString(); } return key; }
7fdb8592-0364-42ba-acf9-694e81d29f51
1
private ItemSelectionListener global() { return new ItemSelectionListener() { @Override public void itemSelectionChanged( ItemSelectionEvent event ) { for( ItemSelectionListener listener : getListeners() ) { listener.itemSelectionChanged( event ); } } }; }
40ced1bb-02f3-4a18-839d-338aaf515f2c
0
public StringPickerGenerator(String tableName, String columnName, List<String> alternatives) { super(tableName, columnName); this.alternatives = alternatives; }
3e8d69d7-7ee2-4dfc-a977-b7bdf38c0acd
5
final void method3954(int i, Class310_Sub2 class310_sub2) { method3956((byte) -56, class310_sub2); if (aBooleanArray9786[((DirectxToolkit) this).anInt8175] == !((Class310_Sub2) class310_sub2).aBoolean6334) { ((DirectxToolkit) this).anIDirect3DDevice9810.SetSamplerState (((DirectxToolkit) this).anInt8175, 1, !((Class310_Sub2) class310_sub2).aBoolean6334 ? 3 : 1); aBooleanArray9786[((DirectxToolkit) this).anInt8175] = ((Class310_Sub2) class310_sub2).aBoolean6334; } if (i == 13700) { if (!aBooleanArray9806[((DirectxToolkit) this).anInt8175] == ((Class310_Sub2) class310_sub2).aBoolean6335) { ((DirectxToolkit) this).anIDirect3DDevice9810.SetSamplerState (((DirectxToolkit) this).anInt8175, 2, !((Class310_Sub2) class310_sub2).aBoolean6335 ? 3 : 1); aBooleanArray9806[((DirectxToolkit) this).anInt8175] = ((Class310_Sub2) class310_sub2).aBoolean6335; } } }
6654c1fb-105c-44c1-9592-b6ae7b0a3b6d
0
public ConfigFile() { //initialize hashtable configSections = new Hashtable(); //read the config file ReadConfigFile(); }
6ae656f8-4efa-4bf9-90ef-2c2fbffee189
0
public void sendtoserver(String s) { String title = "[pvpϵͳ]"; this.log.info(title + s); }
28294959-5864-45d1-9207-c4eaf81bdc60
0
public static Secteur selectOne(EntityManager em, String code_sec) throws PersistenceException { Secteur unSecteur = null; unSecteur = em.find(Secteur.class, code_sec); return unSecteur; }
22db99ee-544c-46e9-ad0c-512f90f112bf
3
@Test public void emptyResultsIfGettersOutOfBounds() { setupHighScoreTest(); assertTrue(high.getNameByRank(-1).equals("") && high.getScoreByRank(-1) == 0 && high.getNameByRank(3).equals("") && high.getScoreByRank(3) == 0); }
282e4568-7e42-4853-830f-9beaa3af5067
3
public <ObjectType, SpriteType extends Sprite<ObjectType>> SpriteType getSpriteOfTypeFor( Class<SpriteType> type, ObjectType object) { if (object == null) { return null; } for (SpriteType sprite : getSpritesOfType(type)) { if (object.equals(sprite.getObject())) { return sprite; } } return null; }
bd35e4ab-5e31-4861-a31a-3bde2d14a2e7
7
public static boolean NTfuncDef() throws IOException { boolean success = true; success = ErrorRecovery(NonTerminal.funcDef); switch (lookahead) { case ID: case INTEGER: case REAL: if (!NTfuncHead()) success = false; if (!NTfuncBody()) success = false; if (!match(TokenType.SEMICOLON)) success = false; if (success) { writetoFile(derivationFileName, "funcDef -> funcHead funcBody ';'"); break; } default: success = false; } return success; }
fa9ecce8-9bbe-449c-8ddd-0f40d66e4c4b
2
public void reachableReference(Reference ref, boolean isVirtual) { String clName = ref.getClazz(); if (clName.charAt(0) == '[') /* Can't represent arrays */ return; ClassIdentifier ident = getClassIdentifier(clName.substring(1, clName.length() - 1).replace('/', '.')); if (ident != null) ident.reachableReference(ref, isVirtual); }
889fb10c-b65f-4328-9bcc-699ffc855084
7
@Override protected double valueMove(Move m, GameBoard board, int lookahead) { if (m instanceof NoMove) return 0; else if (m instanceof BuyDevCard) return 1; else if (m instanceof ProposeTrade || m instanceof FulfillTrade) return 2; else if (m instanceof BuildRoad) return 3; else if (m instanceof BuildSettlement) return 4; else if (m instanceof BuildCity) return 5; else return 0; }
1cf0f4af-3270-4cae-b2a0-f69c9fe8586a
8
@Test public void warandPeaceTest() throws Exception{ DLB dict = new DLB(); File warPeace = new File("warandpeace.txt"); StringTokenizer tk; String str; String nxt; boolean allContained = true; if(warPeace.isFile()){ BufferedReader wpReader = new BufferedReader(new FileReader(warPeace)); while((str = wpReader.readLine())!=null){ tk = new StringTokenizer(str , ",.!?*-' "); while(tk.hasMoreTokens()){ nxt = tk.nextToken(); if (nxt != null){ dict.add(nxt); } } } wpReader.close(); wpReader = new BufferedReader(new FileReader(warPeace)); while((str = wpReader.readLine())!=null){ tk = new StringTokenizer(str , ",.!?*-' "); while(tk.hasMoreTokens()){ nxt = tk.nextToken(); if (nxt != null){ if(dict.searchPrefix(new StringBuilder(nxt)) == 0){ allContained = false; } } } } } assertTrue(allContained); }
adeac073-97f6-4d95-8956-89ed2f5a445d
9
public static Class getWrapper(Class primitive) { if ( ! primitive.isPrimitive()) { return primitive; } Class result = null; if ( primitive.equals(int.class)) { result = Integer.class; } else if ( primitive.equals(long.class)) { result = Long.class; } else if ( primitive.equals(byte.class)) { result = Byte.class; } else if ( primitive.equals(char.class)) { result = Character.class; } else if ( primitive.equals(boolean.class)) { result = Boolean.class; } else if ( primitive.equals(short.class)) { result = Short.class; } else if ( primitive.equals(float.class)) { result = Float.class; } else if ( primitive.equals(double.class)) { result = Double.class; } return result; }
fdb5a17b-a887-4c51-bc06-360960f85291
2
public static String vectorCaddieDeletionToHTML(Vector<Caddie> rs){ if (rs.isEmpty()) return ""; String toReturn = "<TABLE BORDER='1' width=\"1000\">"; toReturn+="<CAPTION>Ces places ne sont pas réservables car la représentation a déjà eu lieu :</CAPTION>"; toReturn+="<TR>"; toReturn+="<TH> <i>Reservation n°</i></TH>"; toReturn+="<TH> <i>Spectacle</i> </TH><TH> <i>Date représentation</i></TH>"; toReturn+="<TH> <i> Zone </i></TH>"; toReturn+="</TR>"; for (int i = 0; i < rs.size(); i++) { toReturn+="<TR>"; toReturn+="<TH> "+(i+1)+"</TH>"; toReturn+="<TH>"+rs.elementAt(i).getNom()+" </TH><TH> "+rs.elementAt(i).getDate()+"</TH>"; toReturn+="<TH> "+rs.elementAt(i).getZone()+" ("+rs.elementAt(i).getNomZ()+")</TH>"; toReturn+="</TR>"; } return toReturn+"</TABLE>"; }
8c3b7f4e-dd85-446c-9670-e1231609f9a0
9
public void moveTo(FATFolder newParent) throws IOException { if (newParent == null) throw new IllegalArgumentException("Bad new parent"); if (isRoot()) throw new IOException("Cannot move the root"); //only one move or delete at once freeze(); try { final FATFile oldParentFile = fatParent; //cannot run away from deleting folder oldParentFile.freeze(); try { int nestUp = 0; final FATFile newParentFile = newParent.asFile(); try { //lock chain from move for [newParent] FATFile newUpParentFile = newParentFile; while (newUpParentFile != null) { if (!newUpParentFile.tryToFreeze()) { if (newParentFile.fileId == oldParentFile.fileId) return;//nothing to do if (newUpParentFile.fileId == fileId) throw new IOException("Cannot move to child or self."); throw new FATFileLockedException(newUpParentFile,true); } ++nestUp; newUpParentFile = newUpParentFile.fatParent; } //up lock order //newParentFile <?- oldParentFile <- this FATLock lockNewParentFile = newParentFile.getLockInternal(true); try { FATLock lockOldParentFile = oldParentFile.getLockInternal(true); try { //don't need [this] lock - it's protected from [move] or [delete] //PERFORMANCE HIT // Reserve storage first. // Yes, I do not support move on partition without space. // Else I need to take a storage lock. That is dramatically // reduce parallel operations. newParent.ts_wl_reserveRecord(); // storage have a space for new record. // since now - no way back - maintenance mode only boolean success = false; try { getParent().ts_deRef(this); //oldParentFile locked newParent.ts_wl_ref(this); // newParentFile locked //here is the only place where parent is been changing fatParent = newParentFile; success = true; } finally { if (!success) fs.ts_setDirtyState("Cannot rollback movement of the file. ", false); } } finally { lockOldParentFile.unlock(); } } finally { lockNewParentFile.unlock(); } } finally { //unlock chain from move for [newParent] FATFile newUpParentFile = newParentFile; while (newUpParentFile != null && nestUp > 0) { newUpParentFile.unfreeze(); --nestUp; newUpParentFile = newUpParentFile.fatParent; } } } finally { oldParentFile.unfreeze(); } } finally { unfreeze(); } }
cbf7c0bb-716e-4728-bcf1-ec79a543c4b2
0
public static int putMap(HashMap<String,String> map,String key, String value){ map = new HashMap<String,String>(); map.put(key, value); counter_put++; return counter_put; }
2eaede38-73b2-49dd-ae32-99fb80bd16e3
5
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i++) { nums[i] = scanner.nextInt(); } Arrays.sort(nums); int minDiff = Integer.MAX_VALUE; int[] diffs = new int[n - 1]; for (int i = 0; i < nums.length - 1; i++) { diffs[i] = nums[i + 1] - nums[i]; if (diffs[i] < minDiff) { minDiff = diffs[i]; } } for (int i = 0; i < diffs.length; i++) { if (diffs[i] == minDiff) { System.out.print(String.format("%d %d ", nums[i], nums[i + 1])); } } scanner.close(); }
5d518100-cda6-4537-bf3d-927e23eba853
2
public Track getTrack(String name) { for(int x = 0; x<tracks.size(); x++) { if(tracks.get(x).getName().matches(name)) return tracks.get(x); } return null; }
84446db0-08f8-4ce0-97d5-dbf9c67bb464
9
private void setNextObject() { if (!iter.hasNext()) { nextObject = null; iter = null; return; } Object o = iter.next(); try { if (o instanceof File) { File file = (File) o; if (file.isDirectory()) { ArrayList<Object> l = new ArrayList<Object>(); l.addAll(Arrays.asList(file.listFiles())); while (iter.hasNext()) { l.add(iter.next()); } iter = l.iterator(); file = (File) iter.next(); } if (file.getName().endsWith(".gz")) { nextObject = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(file)), enc)); } else { nextObject = new BufferedReader(new EncodingFileReader(file, enc)); } //nextObject = new BufferedReader(new FileReader(file)); } else if (o instanceof String) { // File file = new File((String)o); // if (file.exists()) { // if (file.isDirectory()) { // ArrayList l = new ArrayList(); // l.addAll(Arrays.asList(file.listFiles())); // while (iter.hasNext()) { // l.add(iter.next()); // } // iter = l.iterator(); // file = (File) iter.next(); // } // if (((String)o).endsWith(".gz")) { // BufferedReader tmp = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(file)), enc)); // nextObject = tmp; // } else { // nextObject = new BufferedReader(new EncodingFileReader(file, enc)); // } // } else { nextObject = new BufferedReader(new StringReader((String) o)); // } } else if (o instanceof URL) { // todo: add encoding specification to this as well? -akleeman nextObject = new BufferedReader(new InputStreamReader(((URL) o).openStream())); } else if (o instanceof Reader) { nextObject = new BufferedReader((Reader) o); } else { throw new RuntimeException("don't know how to get Reader from " + o); } } catch (IOException e) { throw new RuntimeException(e); } }
fc8d47da-5b6a-4deb-9968-74effff840f2
7
public InfoPanel() { super(new BorderLayout()); Box verticalBox = Box.createVerticalBox(); Box center = Box.createHorizontalBox(); center.add(Box.createHorizontalGlue()); center.add(new JLabel(new ImageIcon(DataStorage.mainLogo.getImage().getScaledInstance( DataStorage.mainLogo.getIconWidth() / 2, DataStorage.mainLogo.getIconHeight() / 2, Image.SCALE_SMOOTH)))); center.add(Box.createHorizontalGlue()); verticalBox.add(center); latestButton = new JButton(checkButtonString); latestButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!checked) { busyLabel.setBusy(true); DataStorage.executors.submit(checker); // latestButton.setMinimumSize(latestButton.getSize()); // latestButton.setText("Checking..."); } else if (!latestButton.isEnabled()) { // we have newest } else { if (Desktop.isDesktopSupported()) { Desktop d = Desktop.getDesktop(); if (d != null) { try { d.browse(new URI("http://www.mylifesucks.de/oss/NCSimulator/NCSimulator-latest.zip")); } catch (Exception ex) { } } } } } }); checkText = new JLabel(" "); checkText.setSize(300, checkText.getSize().height); busyLabel = new JXBusyLabel(); center = Box.createHorizontalBox(); center.add(Box.createHorizontalGlue()); center.add(latestButton); center.add(busyLabel); center.add(Box.createHorizontalGlue()); verticalBox.add(center); center = Box.createHorizontalBox(); center.add(Box.createHorizontalGlue()); center.add(checkText); center.add(Box.createHorizontalGlue()); verticalBox.add(center); checker = new Runnable() { public void run() { try { URL url = new URL("http://www.mylifesucks.de/oss/NCSimulator/NCSimulator-latest.txt"); URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); String newest = new Scanner(is, "UTF-8").useDelimiter("\\Z").next(); //System.out.println(newest); if (newest.equals("NCSimulator-" + Main.version)) { //System.out.println("Current"); //latestButton.setText(youhavenewest); // latestButton.setEnabled(false); checkText.setText(youhavenewest); } else { checkText.setText(newest); } is.close(); // checked = true; } catch (Exception ex) { //Logger.getLogger(InfoPanel.class.getName()).log(Level.SEVERE, null, ex); } busyLabel.setBusy(false); } }; // checkThread.start(); JTextArea jta = new JTextArea("Some hacked Java GUI to simulate the OSD (and some other) output from the NC\n" + "A lot of bugs might be here since it is heavily untested stuff but somehow helpfull for debugging own Applications that require data from an MK.\n" + "\n" + "Open Source:\n" + "\tLicensed under: Creative Commons / Non Commercial / Share Alike\n" + "\thttp://creativecommons.org/licenses/by-nc-sa/2.0/de/\n" + "\tSources available at: https://github.com/crathje/NCSimulator\n" +"\n" + "This Software uses:\n" + "\tRXTX which is licensed under the LGPL v2.1 and available from http://rxtx.qbang.org/\n" + "\tSwingX which is licensed under the LGPL and available from http://www.swinglabs.org/\n" + "\n" + "Credits to:\n" + "\tMarcus -LiGi- Bueschleb for the Encode/Decode java parts I borrowed from DUBWise\n" + "\tHolger Buss & Ingo Busker for the MikroKopter-project\n" + "\tFrank Blumenberg for adapting the simulator to current FC/NC releases\n" + ""); // jta.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 14)); jta.setBackground(this.getBackground()); //jta.setWrapStyleWord(true); //jta.setAutoscrolls(true); jta.setBackground(this.getBackground()); jta.setEditable(false); jta.setLineWrap(true); //jta.setColumns(20); /*jta.setSize(new Dimension(DataStorage.mainLogo.getIconWidth(), DataStorage.mainLogo.getIconHeight())); jta.setPreferredSize(jta.getSize()); jta.setMinimumSize(jta.getSize()); jta.setMaximumSize(jta.getSize());*/ center = Box.createHorizontalBox(); center.add(Box.createHorizontalGlue()); Box vertical = Box.createVerticalBox(); JTabbedPane tabbed = new JTabbedPane(); tabbed.add("General", new JScrollPane(jta)); //vertical.add(new JScrollPane(jta)); JTextArea changeLog = new JTextAreaFromFile("/CHANGE.LOG"); changeLog.setEditable(false); changeLog.setBackground(getBackground()); changeLog.setLineWrap(true); tabbed.add("Change Log", new JScrollPane(changeLog)); vertical.add(tabbed); Box links = Box.createHorizontalBox(); links.add(new LinkLabel("NCSimulator", "http://www.mylifesucks.de/oss/NCSimulator/")); links.add(Box.createHorizontalGlue()); links.add(new LinkLabel("NCSimulator latest", "http://www.mylifesucks.de/oss/NCSimulator/NCSimulator-latest.zip")); links.add(Box.createHorizontalGlue()); links.add(new LinkLabel("Thread in MK-Forum", "http://forum.mikrokopter.de/topic-20435.html")); links.add(Box.createHorizontalGlue()); links.add(new LinkLabel("MikroKopter", "http://www.mikrokopter.de/")); links.add(Box.createHorizontalGlue()); links.add(new LinkLabel("DUBwise", "http://www.mikrokopter.de/ucwiki/DUBwise")); vertical.add(links); center.add(vertical); center.add(Box.createHorizontalGlue()); // center.add(jb); center.add(Box.createHorizontalGlue()); verticalBox.add(center); //Desktop.getDesktop().browse(null); add(verticalBox, BorderLayout.CENTER); }
0d782e4a-6af9-4060-b436-73bab4c59f71
5
private void btnEnterRecordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnterRecordActionPerformed foundIndex = NOT_FOUND; partNo = this.txtNewProdNo.getText(); partDesc = this.txtNewProdDesc.getText(); try { partPrice = Double.parseDouble(this.txtNewProdPrice.getText()); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Sorry, the price entry must be a whole or floating point number only.\n", "Number Format Error", JOptionPane.WARNING_MESSAGE); return; } if (emptyRow > 10) { JOptionPane.showMessageDialog(this, "Sorry, you have reach the maximum of 10 items.\n" + "No more items can be saved.", "Maximum Reached", JOptionPane.WARNING_MESSAGE); } else if (partNo.length() == 0 || partDesc.length() == 0 || this.txtNewProdPrice.getText().length() == 0) { JOptionPane.showMessageDialog(this, "Sorry, you must complete all fields. Please try again.", "Incomplete Part Entry", JOptionPane.WARNING_MESSAGE); this.txtNewProdNo.requestFocus(); } else { partNums[emptyRow] = partNo; partDescs[emptyRow] = partDesc; partPrices[emptyRow] = partPrice; this.emptyRow += 1; } clearEntryFields(); this.txtNewProdNo.requestFocus(); }//GEN-LAST:event_btnEnterRecordActionPerformed
1cb26acb-a977-4aab-aedd-6157f70003c7
7
public int findElement(int array[], int element) { int n = array.length; if(n == 1) return array[0]; int middle = (n-1)/2; //best cases! if(element == array[middle]) return array[middle]; if(n==2) return array[n-1]; //search on RIGHT block : for(int i = middle+1; i <= n; i++) int start = middle+1; int end = n; // search on LEFT block : for(int i = 0; i < middle; i++) if(element>=array[0] && array[middle]<element) { start = 0; end = middle; } while(start<end) { if(array[start]==element) return start; start++; moves++; } return -1; //not found }
25d7b831-5e9c-4f71-94c8-fd82bac89819
5
@Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(cmd.getName().equalsIgnoreCase("god")) { if(sender instanceof Player) { Player p = (Player) sender; PlayerUtil pu = new PlayerUtil(p); if(pu.hasPermission("Nostalgia.Command.god", PermissionType.NORMAL)) { if(mainClass.GodPlayers.contains(p)) { mainClass.GodPlayers.remove(p); p.sendMessage(LangUtil.ToggleGodOff()); } else if(!mainClass.GodPlayers.contains(p)) { mainClass.GodPlayers.add(p); p.sendMessage(LangUtil.ToggleGodOn()); } else { p.sendMessage(LangUtil.fourthWall()); } } else { MessageUtil.noPermission(p, "Nostalgia.Command.god"); } } } return false; }
a04d1b82-8981-4239-9132-1b8bf212de5a
5
protected synchronized boolean broadcastMessage(Message msg){ if(msg == null) return false; msg.setSourceID(this.auctioneerID); msg.setDestinationID(Message.TO_ALL_BIDDERS); msg.setAuctionID(this.auctionID); int tag = -1; int nBidders = bidders.size(); if( msg instanceof MessageCallForBids){ tag = AuctionTags.AUCTION_CFP; } else if( msg instanceof MessageInformStart){ tag = AuctionTags.AUCTION_INFORM_START; } else if( msg instanceof MessageInformOutcome){ tag = AuctionTags.AUCTION_INFORM_OUTCOME; } /* TODO: * For now, we are assuming that every message has a size of about 100 bytes. * It would be better to consider some FIPA's encoding schema, for example. * Please see: www.fipa.org */ for(int i=0; i<nBidders; i++){ int destId = ((Integer)bidders.get(i)).intValue(); super.sim_schedule(this.outputPort, GridSimTags.SCHEDULE_NOW, tag, new IO_data(msg, 100, destId)); } return true; }
cd75a829-ba39-49fd-8d2c-0a7f9cc40965
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(Consultapedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Consultapedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Consultapedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Consultapedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Consultapedido().setVisible(true); } }); }
1eca2040-3266-4a84-86f6-d858bf2be9e9
1
public ObjektNode[] getChilds(ObjektNode paramObjektNode) throws XmlRpcException, IOException { Vector localVector = (Vector)Client.getXmlRpcClient().execute("TreeHandler.getChilds",paramObjektNode.getParentId(), paramObjektNode.getArt().toString(), Boolean.valueOf(false), null, null); ObjektNode[] arrayOfObjektNode = new ObjektNode[localVector.size()]; int i = 0; Enumeration localEnumeration = localVector.elements(); while (localEnumeration.hasMoreElements()) { ObjektNode localObjektNode = new ObjektNode((Vector)localEnumeration.nextElement()); arrayOfObjektNode[(i++)] = localObjektNode; } return arrayOfObjektNode; }
223c3b74-8109-4bb1-8268-a85c22c6b531
3
@Override public void sendUsageImpl(CommandSender sender) { if (!(sender instanceof Player)) return; sender.sendMessage(EdgeCore.usageColor + "/cash info"); sender.sendMessage(EdgeCore.usageColor + "/cash give <user> <amount>"); sender.sendMessage(EdgeCore.usageColor + "/cash donate <amount>"); User u = EdgeCoreAPI.userAPI().getUser(sender.getName()); if (u == null || !Level.canUse(u, Level.MODERATOR)) return; sender.sendMessage(EdgeCore.usageColor + "/cash update <user> <amount>"); sender.sendMessage(EdgeCore.usageColor + "/cash transfer <from> <to> <amount>"); }
0ac1c346-8011-426f-87a7-1cccf1ca5931
6
@Override public long put(long priority, int delaySeconds, int timeToRun, byte[] data) { if (data == null) { throw new BeanstalkException("null data"); } if (priority > MAX_PRIORITY) { throw new BeanstalkException("invalid priority"); } long jobId = -1; Request request = new Request("put " + priority + " " + delaySeconds + " " + timeToRun + " " + data.length, new String[] { "INSERTED", "BURIED" }, new String[] { "JOB_TOO_BIG" }, data, ExpectedResponse.None); Response response = getProtocolHandler().processRequest(request); if (response != null && response.getStatus().equals("JOB_TOO_BIG")) { BeanstalkException be = new BeanstalkException(response.getStatus()); throw be; } if (response != null && response.isMatchOk()) { jobId = Long.parseLong(response.getReponse()); } return jobId; }
9b104136-5ef4-431f-9ea9-504cf989ef32
0
public String getSearchURLArgs() { _read.lock(); try { return _searchURLArgs; } finally { _read.unlock(); } }
27e00f9f-9c1e-4acc-8558-6c330f49ca97
8
public static void handleMouse(){ MouseEvent event; int mx = Mouse.getEventX(); int my = Mouse.getEventY(); while(Mouse.next()){ if(Mouse.getEventButton() == 0){ if(Mouse.isButtonDown(0)){ if(game.duringPass){ for(Player p : game.getAllPlayers()){ if(p.getDisplay().getRect().contains(Clamp.clampX(mx), Clamp.clampY(my))){ game.ball.targetPlayer(p); game.interceptPlayer = p; game.duringPass = false; break; } } } event = MouseEvent.DOWN; } else event = MouseEvent.UP; } else{ event = MouseEvent.MOVE; } for(Button button : buttons){ if(button.handleMouse(event, mx, my)) break; } } }
dad43db9-7936-40a7-bdb9-b8bd59a37bd2
8
public List<MorrisIntersection> getNeighbor() { List<MorrisIntersection> ret = new ArrayList<MorrisIntersection>(); if (hasLeft()) { ret.add(left()); } if (hasRight()) { ret.add(right()); } if (hasUp()) { ret.add(up()); } if (hasDown()) { ret.add(down()); } if (this.hasSkewLeftUp()) { ret.add(skewLeftUp()); } if (this.hasSkewLeftDown()) { ret.add(skewLeftDown()); } if (this.hasSkewRightUp()) { ret.add(skewRightUp()); } if (this.hasSkewRightDown()) { ret.add(skewRightDown()); } return ret; }
539f0d48-7891-4123-8f44-a1d31b2fdc6d
6
String getMenuItemText(String item) { boolean cascade = item.equals("Cascade"); boolean mnemonic = mnemonicsButton.getSelection(); boolean accelerator = acceleratorsButton.getSelection(); char acceleratorKey = item.charAt(0); if (mnemonic && accelerator && !cascade) { return ControlExample.getResourceString(item + "WithMnemonic") + "\tCtrl+Shift+" + acceleratorKey; } if (accelerator && !cascade) { return ControlExample.getResourceString(item) + "\tCtrl+Shift+" + acceleratorKey; } if (mnemonic) { return ControlExample.getResourceString(item + "WithMnemonic"); } return ControlExample.getResourceString(item); }
a7714ecf-8dd9-4f5a-b70a-56d094853ce3
0
public Address(String City, String Sector, String Calle, String HouseNumber, String PostalCode, String country, String region) { this.City = City; this.Sector = Sector; this.Calle = Calle; this.HouseNumber = HouseNumber; this.PostalCode = PostalCode; this.country=country; this.region=""; }
5dd5a828-6f13-402a-a267-aae80a317dca
5
public WeaponEditor(String name) { setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setTitle("Weapon Editor"); setBounds(100, 100, 600, 475); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); contentPanel.setOrientation(JSplitPane.VERTICAL_SPLIT); contentPanel.setBounds(0, 0, 584, 402); JPanel panel = new JPanel(); contentPanel.setLeftComponent(panel); panel.setLayout(null); { JLabel nameLabel = new JLabel("Weapon Name"); nameLabel.setBounds(12, 9, 79, 16); panel.add(nameLabel); } JLabel lblWeaponType = new JLabel("Weapon Type"); lblWeaponType.setBounds(145, 9, 73, 16); panel.add(lblWeaponType); meleeButton = new JRadioButton("Melee"); meleeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(meleeButton.isSelected()) { tabbedPane.setEnabledAt(0, true); tabbedPane.setEnabledAt(1, true); tabbedPane.setEnabledAt(2, true); tabbedPane.setEnabledAt(3, false); tabbedPane.setSelectedIndex(0); } } }); meleeButton.setBounds(145, 34, 57, 25); panel.add(meleeButton); meleeButton.setSelected(true); buttonGroup.add(meleeButton); magicButton = new JRadioButton("Magic"); magicButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(magicButton.isSelected()) { tabbedPane.setEnabledAt(0, false); tabbedPane.setEnabledAt(1, false); tabbedPane.setEnabledAt(2, false); tabbedPane.setEnabledAt(3, true); tabbedPane.setSelectedIndex(3); } } }); magicButton.setBounds(206, 34, 59, 25); panel.add(magicButton); buttonGroup.add(magicButton); rangedButton = new JRadioButton("Ranged"); rangedButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(rangedButton.isSelected()) { tabbedPane.setEnabledAt(0, false); tabbedPane.setEnabledAt(1, false); tabbedPane.setEnabledAt(2, false); tabbedPane.setEnabledAt(3, true); tabbedPane.setSelectedIndex(3); } } }); rangedButton.setBounds(269, 34, 65, 25); panel.add(rangedButton); buttonGroup.add(rangedButton); fistButton = new JRadioButton("Fist"); fistButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(fistButton.isSelected()) { tabbedPane.setEnabledAt(0, false); tabbedPane.setEnabledAt(1, false); tabbedPane.setEnabledAt(2, false); tabbedPane.setEnabledAt(3, true); tabbedPane.setSelectedIndex(3); } } }); fistButton.setBounds(338, 34, 43, 25); panel.add(fistButton); buttonGroup.add(fistButton); nameText = new JTextField(name); nameText.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { thrustPanel.updateSprite(nameText.getText() + "_thrust"); crushPanel.updateSprite(nameText.getText() + "_crush"); slashPanel.updateSprite(nameText.getText() + "_slash"); attackPanel.updateSprite(nameText.getText() + "_attack"); tabbedPane.getSelectedComponent().repaint(); } }); nameText.setBounds(12, 38, 116, 22); panel.add(nameText); nameText.setColumns(10); tabbedPane = new JTabbedPane(JTabbedPane.TOP); contentPanel.setRightComponent(tabbedPane); thrustPanel = new WeaponPanel(nameText.getText() + "_thrust"); tabbedPane.addTab("Thrust", null, thrustPanel, null); thrustPanel.setLayout(null); crushPanel = new WeaponPanel(nameText.getText() + "_crush"); tabbedPane.addTab("Crush", null, crushPanel, null); crushPanel.setLayout(null); slashPanel = new WeaponPanel(nameText.getText() + "_slash"); tabbedPane.addTab("Slash", null, slashPanel, null); slashPanel.setLayout(null); attackPanel = new WeaponPanel(nameText.getText() + "_attack"); tabbedPane.addTab("Attack", null, attackPanel, null); tabbedPane.setEnabledAt(3, false); attackPanel.setLayout(null); contentPanel.setDividerLocation(75); { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { save(); dispose(); } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } if(name != null) load(); setModalityType(ModalityType.APPLICATION_MODAL); setVisible(true); }
a3ffd7d0-70a3-406b-8e9a-cc53acf6381b
1
public void testWithField2() { DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0); try { test.withField(null, 6); fail(); } catch (IllegalArgumentException ex) {} }
b80c6f76-1bc8-4e6b-a11c-32aa8f4bbd25
8
public static Calendar parseTimestamp(String timestamp) { // Timestamp pattern Pattern p1 = Pattern .compile("\\w{3}, \\d{1,2} \\w{3} \\d{4} \\d{2}:\\d{2}:\\d{2} [+-]{1}\\w{4}"); Pattern p2 = Pattern .compile("\\w{3}, \\d{1,2} \\w{3} \\d{4} \\d{2}:\\d{2}:\\d{2} \\w{3}[+-]{0,1}\\d{0,2}[:]{0,1}\\d{0,2}"); Pattern p3 = Pattern .compile("\\d{1,2}/\\d{1,2}/\\d{4} \\d{1,2}:\\d{1,2}:\\d{1,2} \\w{2}"); Pattern p4 = Pattern .compile("\\d{4}-\\d{2}-\\d{2}\\w{1}\\d{2}:\\d{2}:\\d{2}.\\d{0,3}[+-]{1}\\d{2}:\\d{2}"); String dateFormat; Calendar calendar = Calendar.getInstance(); if (p1.matcher(timestamp).matches()) { dateFormat = "EEE, d MMM yyyy HH:mm:ss Z"; } else if (p2.matcher(timestamp).matches()) { dateFormat = "EEE, d MMM yyyy HH:mm:ss z"; } else if (p3.matcher(timestamp).matches()) { StringTokenizer t1 = new StringTokenizer(timestamp, " "); String date = t1.nextToken(); String time = t1.nextToken(); String mk = t1.nextToken(); StringTokenizer t2 = new StringTokenizer(date, "/"); String month = t2.nextToken(); String day = t2.nextToken(); String year = t2.nextToken(); if (month.length() == 1) month = "0" + month; if (day.length() == 1) day = "0" + month; StringTokenizer t3 = new StringTokenizer(time, ":"); String hour = t3.nextToken(); String min = t3.nextToken(); String sec = t3.nextToken(); if (hour.length() == 1) hour = "0" + hour; timestamp = month + "/" + day + "/" + year + " " + hour + ":" + min + ":" + sec + " " + mk; dateFormat = "MM/dd/yyyy hh:mm:ss a"; } else if (p4.matcher(timestamp).matches()) { dateFormat = "yyyy-MM-dd'T'HH:mm:ss.s"; } else { dateFormat = "yyyy-MM-ddThh:mm:ss'Z'"; } DateFormat df = new SimpleDateFormat(dateFormat, Locale.US); try { calendar.setTime(df.parse(timestamp)); } catch (ParseException ex) { // TODO Auto-generated catch block ex.printStackTrace(); } return calendar; }
9ec8a96a-27f1-4a35-b343-1179daaecbe7
5
public void initialize(String filePath){ _rawData = new LinkedList<String>(); patternEncoderUtil = new PatternEncoderUtil(); try { fileReader = new FileReader(filePath); _bufferedReader = new BufferedReader(fileReader); while ((sCurrentLine = _bufferedReader.readLine()) != null ) { _rawData.add(sCurrentLine); index++; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (_bufferedReader != null)_bufferedReader.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
2e8d38a7-a738-4315-bb68-0ad3a9643554
0
public CmdResetExecutor(SimpleQueues plugin) { this.plugin = plugin; }
1633e8f8-121c-4474-9c19-ed855f53cf25
5
@Test public void TestaaYlhaaltaAlasEste() { rakentaja = new Kartanrakentaja(10, 6); rakentaja.asetaEste(5, 3); rakentaja.asetaEste(5, 4); rakentaja.asetaEste(5, 2); char[][] kartta = rakentaja.getKartta(); Solmu aloitus = new Solmu(0, 3); Solmu maali = new Solmu(9, 3); Reitinhaku haku = new Reitinhaku(kartta); char[][] tulos = haku.etsiReitti(aloitus, maali); int pituus = 0; for(int i = 0; i < tulos.length; i++) { for (int j = 0; j < tulos[0].length; j++) { if(tulos[i][j] == 'X') { pituus++; } } } System.out.println(""); for(int i = 0; i < tulos.length; i++) { System.out.println(""); for (int j = 0; j < tulos[0].length; j++) { System.out.print(tulos[i][j]); } } assertEquals(13, pituus); }
53c3292b-a670-4465-a64a-0d6ea5f80a31
7
public void paint1(Graphics g) { //g.setColor(Color.RED); //g.fillRect(0, 0, getWidth(), getHeight()); // Muestra en pantalla el cuadro actual de la animación g.drawImage(background, 0, 0, this); // Imagen de background if (pelota != null && pelota.getImagenI() != null) { g.drawImage(pelota.getImagenI(), pelota.getPosX(), pelota.getPosY(), this); } if (canasta != null && canasta.getImagenI() != null) { g.drawImage(canasta.getImagenI(), canasta.getPosX(), canasta.getPosY(), this); } g.setFont(new Font("default", Font.BOLD, 16)); if (pausa) { // mensaje de pausa g.setColor(Color.white); g.drawImage(pause, canasta.getPosX() - 10, canasta.getPosY() - 37, this); } g.setColor(Color.green); g.drawString("Score: " + score, 20, 55); g.setColor(Color.blue); g.drawString("Caídas: " + caidas, 20, 80); g.setColor(Color.red); g.drawString("Vidas: " + vidas, 20, 105); if (instrucciones) { setBackground(Color.black); g.drawImage(instructionBack, 0, 0, this); // Imagen de instrucciones } if (vidas <= 0) { pausa = true; g.drawImage(gameover, 0, 0, this); // Imagen de instrucciones } }
440956cf-e727-4893-8ddf-56f84ec5348f
9
@Override public int[] getInts(int par1, int par2, int par3, int par4) { deepOcean = BiomeGenBase.deepOcean.biomeID; mushroomIsland = BiomeGenBase.mushroomIsland.biomeID; int i1 = par1 - 1; int j1 = par2 - 1; int k1 = par3 + 2; int l1 = par4 + 2; int[] aint = this.parent.getInts(i1, j1, k1, l1); int[] aint1 = IntCache.getIntCache(par3 * par4); for (int i2 = 0; i2 < par4; ++i2) { for (int j2 = 0; j2 < par3; ++j2) { int k2 = aint[j2 + 0 + (i2 + 1) * k1]; int l2 = aint[j2 + 2 + (i2 + 1) * k1]; int i3 = aint[j2 + 1 + (i2 + 0) * k1]; int j3 = aint[j2 + 1 + (i2 + 2) * k1]; int k3 = aint[j2 + 1 + (i2 + 1) * k1]; if (k3 == mushroomIsland) { aint1[j2 + i2 * par3] = k3; continue; } if (k2 == l2 && i3 == j3) { this.initChunkSeed(j2 + par1, i2 + par2); if (this.nextInt(2) == 0) { k3 = k2; } else { k3 = i3; } } else { if (k2 == l2) { k3 = k2; } else if (i3 == j3) { k3 = i3; } else { // special tricks needs for stray lakes if (k3 == 0) { k3 = climateSmoothed(i1, j1, k1, l1, k2, l2, i3, j3, k3, par1, par2, i2, j2); } } } aint1[j2 + i2 * par3] = k3; } } return aint1; }
75fab6d6-a2b9-4243-9720-9ef70599f3df
5
protected boolean verificarConvergencia() { boolean converge = false; for (int i = 0; i < this.matriz.linhas && !converge; i++) { for (int j = i + 1; j < this.matriz.linhas && !converge; j++) { converge = criterioLinhas(); if(!converge) { trocarLinhas(i,j); } } } return converge; }
62a64f4f-f9e7-4686-8c25-e55ba8d7ebb4
8
public void omitLessFreq() { if (name == null) return; // Illegal int threshold = n_words[0] / LESS_FREQ_RATIO; if (threshold < MINIMUM_FREQ) threshold = MINIMUM_FREQ; Set<String> keys = freq.keySet(); int roman = 0; for(Iterator<String> i = keys.iterator(); i.hasNext(); ){ String key = i.next(); int count = freq.get(key); if (count <= threshold) { n_words[key.length()-1] -= count; i.remove(); } else { if (key.matches("^[A-Za-z]$")) { roman += count; } } } // roman check if (roman < n_words[0] / 3) { Set<String> keys2 = freq.keySet(); for(Iterator<String> i = keys2.iterator(); i.hasNext(); ){ String key = i.next(); if (key.matches(".*[A-Za-z].*")) { n_words[key.length()-1] -= freq.get(key); i.remove(); } } } }
59c155bc-6855-4e7a-9dbd-8f43c5045edf
1
public static void spawnPossessedItem (Location loc, int amount, ItemStack stack) { int i = 0; while (i < amount) { Skeleton possessedItem = (Skeleton) loc.getWorld().spawnEntity(loc, EntityType.SKELETON); possessedItem.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, 2147483647, 10)); possessedItem.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 2147483647, 10)); possessedItem.setHealth(6); possessedItem.getEquipment().setHelmet(new ItemStack(Material.GLOWSTONE_DUST, 1)); possessedItem.getEquipment().setChestplate(new ItemStack(Material.GLOWSTONE, 1, (short) - 98789)); possessedItem.getEquipment().setItemInHand(stack); possessedItem.getEquipment().setHelmetDropChance(0.0F); possessedItem.getEquipment().setChestplateDropChance(0.0F); possessedItem.getEquipment().setItemInHandDropChance(100.0F); possessedItem.setCanPickupItems(false); i++; } }
5a4965f6-e26d-408f-a1ee-73f879413dbe
6
private void insertFixup(Node z) { while(z.parent.color == RED){ if(z.parent.equals(z.parent.parent.left)){ Node y = z.parent.parent.right; if(y.color == RED){ z.parent.color = BLACK; y.color = BLACK; z.parent.parent.color = RED; z = z.parent.parent; }else{ if(z.equals(z.parent.right)){ z = z.parent; leftRotate(z); } z.parent.color = BLACK; z.parent.parent.color = RED; rightRotate(z.parent.parent); } }else{ Node y = z.parent.parent.left; if(y.color == RED){ z.parent.color = BLACK; y.color = BLACK; z.parent.parent.color = RED; z = z.parent.parent; }else{ if(z.equals(z.parent.left)){ z = z.parent; rightRotate(z); // ok? } z.parent.color = BLACK; z.parent.parent.color = RED; leftRotate(z.parent.parent); // ok? } } } root.color = BLACK; }
de6d1595-02db-4aff-be88-2aa85968e488
9
private void BtGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtGravarActionPerformed if (camposobrigatoriospreenchidos()) { if (JOptionPane.showConfirmDialog(null, "Tem certeza que deseja realmente Gravar os dados deste fornecedor?", "Confirmar", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { if (TfCodigo.getText().equals("")) { enviardados(); if(fornecedor.incluir()) msg.Sucesso(LbNotificacao, "Dados do Fornecedor gravados com sucesso!"); fornecedor.getPessoajur().getPessoa().getTelefone().setCodigopessoa(fornecedor.getPessoajur().getPessoa().getCodigo()); fornecedor.getPessoajur().getPessoa().getEmail().setCodigopessoa(fornecedor.getPessoajur().getPessoa().getCodigo()); JOptionPane.showMessageDialog(null, "Código: " + fornecedor.getCodigo() + "\n" + "Fornecedor: " + fornecedor.getPessoajur().getNomefantasia().toUpperCase(), "Informe o Código", JOptionPane.INFORMATION_MESSAGE); for (int i = 0; i < TbTelefone.getRowCount(); i++) { fornecedor.getPessoajur().getPessoa().getTelefone().setCodigo(i + 1); fornecedor.getPessoajur().getPessoa().getTelefone().setNrtelefone(TbTelefone.getValueAt(i, 1).toString()); fornecedor.getPessoajur().getPessoa().getTelefone().setTipotelefone(TbTelefone.getValueAt(i, 2).toString()); fornecedor.getPessoajur().getPessoa().getTelefone().incluir(); } for (int i = 0; i < TbEmail.getRowCount(); i++) { fornecedor.getPessoajur().getPessoa().getEmail().setCodigo(i + 1); fornecedor.getPessoajur().getPessoa().getEmail().setEmail(TbEmail.getValueAt(i, 1).toString()); fornecedor.getPessoajur().getPessoa().getEmail().setTipoemail(TbEmail.getValueAt(i, 2).toString()); fornecedor.getPessoajur().getPessoa().getEmail().incluir(); } limpar.Limpar(PnCadastro); limpar.Limpar(TbTelefone); limpar.Limpar(TbEmail); TfNrCNPJKeyReleased(null); valida.validacamposCancelar(PnCadastro, PnBotoes); } else { fornecedor.setCodigo(Integer.parseInt(TfCodigo.getText())); fornecedor.getPessoajur().getPessoa().setCodigo(fornecedor.retornacodigopessoafornecedor()); enviardados(); if(fornecedor.alterar()) msg.Sucesso(LbNotificacao, "Dados do Fornecedor alterados com sucesso!"); fornecedor.getPessoajur().getPessoa().getTelefone().setCodigopessoa(fornecedor.getPessoajur().getPessoa().getCodigo()); fornecedor.getPessoajur().getPessoa().getEmail().setCodigopessoa(fornecedor.getPessoajur().getPessoa().getCodigo()); fornecedor.getPessoajur().getPessoa().getTelefone().deletartelefones(); fornecedor.getPessoajur().getPessoa().getEmail().deletaremails(); for (int i = 0; i < TbTelefone.getRowCount(); i++) { fornecedor.getPessoajur().getPessoa().getTelefone().setCodigo(i + 1); fornecedor.getPessoajur().getPessoa().getTelefone().setNrtelefone(TbTelefone.getValueAt(i, 1).toString()); fornecedor.getPessoajur().getPessoa().getTelefone().setTipotelefone(TbTelefone.getValueAt(i, 2).toString()); fornecedor.getPessoajur().getPessoa().getTelefone().incluir(); } for (int i = 0; i < TbEmail.getRowCount(); i++) { fornecedor.getPessoajur().getPessoa().getEmail().setCodigo(i + 1); fornecedor.getPessoajur().getPessoa().getEmail().setEmail(TbEmail.getValueAt(i, 1).toString()); fornecedor.getPessoajur().getPessoa().getEmail().setTipoemail(TbEmail.getValueAt(i, 2).toString()); fornecedor.getPessoajur().getPessoa().getEmail().incluir(); } limpar.Limpar(PnCadastro); limpar.Limpar(TbTelefone); limpar.Limpar(TbEmail); TfNrCNPJKeyReleased(null); valida.validacamposCancelar(PnCadastro, PnBotoes); } } } }//GEN-LAST:event_BtGravarActionPerformed
323fe4d4-e218-4310-ba58-20714f348cfb
6
public int appendTo(StringBuilder sb, boolean tiny, boolean noneIfEmpty) { int num = 0; for (int i = 0; i < total.length; i++) { int t = total[i]; if (t != 0) { if (num++ > 0) { sb.append(", "); } StatT stat = STATS[i]; stat.appendValue(sb, t); sb.append(" "); sb.append(tiny ? stat.tinyName : stat.shortName); } } if (num == 0 && noneIfEmpty) { sb.append("None"); } return num; }
bac05f2e-4c40-4f64-9a17-780691e87bb6
8
@SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case statePackage.STATE__PLAYERS: getPlayers().clear(); getPlayers().addAll((Collection<? extends Player>)newValue); return; case statePackage.STATE__COUNTRY_STATE: ((EStructuralFeature.Setting)getCountryState()).set(newValue); return; case statePackage.STATE__TURN: setTurn((Player)newValue); return; case statePackage.STATE__PHASE: setPhase((TurnPhase)newValue); return; case statePackage.STATE__STATE: setState((GameState)newValue); return; case statePackage.STATE__TROOPS_TO_SET: setTroopsToSet((Integer)newValue); return; case statePackage.STATE__CONQUERED_COUNTRY: setConqueredCountry((Boolean)newValue); return; } super.eSet(featureID, newValue); }
cd2510f0-7703-4d72-9e6a-0f7c136f90e6
7
static void dradb2(int ido, int l1, float[] cc, float[] ch, float[] wa1, int index){ int i, k, t0, t1, t2, t3, t4, t5, t6; float ti2, tr2; t0=l1*ido; t1=0; t2=0; t3=(ido<<1)-1; for(k=0; k<l1; k++){ ch[t1]=cc[t2]+cc[t3+t2]; ch[t1+t0]=cc[t2]-cc[t3+t2]; t2=(t1+=ido)<<1; } if(ido<2) return; if(ido!=2){ t1=0; t2=0; for(k=0; k<l1; k++){ t3=t1; t5=(t4=t2)+(ido<<1); t6=t0+t1; for(i=2; i<ido; i+=2){ t3+=2; t4+=2; t5-=2; t6+=2; ch[t3-1]=cc[t4-1]+cc[t5-1]; tr2=cc[t4-1]-cc[t5-1]; ch[t3]=cc[t4]-cc[t5]; ti2=cc[t4]+cc[t5]; ch[t6-1]=wa1[index+i-2]*tr2-wa1[index+i-1]*ti2; ch[t6]=wa1[index+i-2]*ti2+wa1[index+i-1]*tr2; } t2=(t1+=ido)<<1; } if((ido%2)==1) return; } t1=ido-1; t2=ido-1; for(k=0; k<l1; k++){ ch[t1]=cc[t2]+cc[t2]; ch[t1+t0]=-(cc[t2+1]+cc[t2+1]); t1+=ido; t2+=ido<<1; } }
97b8f954-4539-42af-bd92-2a9d1d0f5f1c
7
public void sendBundledMessages(final Message[] buf, final int read_index, final int available_msgs) { int max_bundle_size=transport.getMaxBundleSize(); byte[] cluster_name=transport.cluster_name.chars(); int start=read_index; final int end=index(start + available_msgs-1); // index of the last message to be read for(;;) { Message msg=buf[start]; if(msg == null) { if(start == end) break; start=advance(start); continue; } Address dest=msg.dest(); try { output.position(0); Util.writeMessageListHeader(dest, msg.src(), cluster_name, 1, output, dest == null); // remember the position at which the number of messages (an int) was written, so we can later set the // correct value (when we know the correct number of messages) int size_pos=output.position() - Global.INT_SIZE; int num_msgs=marshalMessagesToSameDestination(dest, buf, start, end, max_bundle_size); if(num_msgs > 1) { int current_pos=output.position(); output.position(size_pos); output.writeInt(num_msgs); output.position(current_pos); } transport.doSend(output.buffer(), 0, output.position(), dest); if(transport.statsEnabled()) transport.incrBatchesSent(num_msgs); } catch(Exception ex) { log.error("failed to send message(s)", ex); } if(start == end) break; start=advance(start); } }
d9197790-eed2-46dc-aa98-7f63dde75559
2
public void method(String str) throws MyException,MyException1 { if(null == str) { throw new MyException("传入的字符串参数不能为null"); } else if("hello".equals(str)) { throw new MyException1("输入的内容是:hello !"); }else { System.out.println(str); } }
11616372-cf43-4b70-af93-c0e2b069917c
1
public void printMessages() { for (String s : list ) { System.out.println(s); } }
18341ac4-1750-48e9-8d43-2a4bdc70e8bc
7
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { Physical target=mob; if((auto)&&(givenTarget!=null)) target=givenTarget; if(target.fetchEffect(this.ID())!=null) { mob.tell(mob,target,null,L("<T-NAME> <T-IS-ARE> already affected by @x1.",name())); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> become(s) protected from outsiders."):L("^S<S-NAME> @x1 for protection from outsiders.^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } } else return beneficialWordsFizzle(mob,null,L("<S-NAME> @x1 for protection, but there is no answer.",prayWord(mob))); // return whether it worked return success; }
858a2cb8-36cb-4012-a8a6-2976c9a9242e
3
public static void newProcessingFormat(Object[] Fieldsin) { //Filed(0) = Nombre de campo //Field(s%4=0) = VariableComp1 = [X:|S:|C:|E:][N:|H:]NAME_op1 //Field(s%4=1) = operation = '==' '!=' '<' '>' '>=' '<=' //Field(s%4=2) = VariableComp2 = [X:|S:|C:|E:][N:|H:]NAME_op2 //Field(s%4=3) = VariableAsig = [A|B|C|...] //Field(s-1) = VariableForm = Ej: !(A|B)^C String Fields = (String) Fieldsin[0]; String phrase; int where; try { where = Deliver.SYNTAX_AREA; String[] splitfields = Fields.split(" ; "); String[] splitfields1 = splitfields[0].split(" "); String inicial = splitfields1[0].substring(0, 1); if (inicial.equalsIgnoreCase("Q")) {inicial = "X";} phrase = "%^" + inicial.toUpperCase() + "_TRATAR_" + splitfields1[0].toUpperCase() + ".\""; for (int i = 1; i < splitfields1.length - 4; i += 4) { phrase += splitfields1[i] + " " + splitfields1[i+1] + " " + splitfields1[i+2] + " = " + splitfields1[i+3].toUpperCase() + " ; "; } phrase += splitfields1[splitfields1.length-4] + " " + splitfields1[splitfields1.length-3] + " " + splitfields1[splitfields1.length-2] + " = " + splitfields1[splitfields1.length-1].toUpperCase(); phrase += " # " + splitfields[1]; phrase += "\""; } catch (Exception e) { where = Deliver.ERROR; phrase = "insert EH:ORIGEN == ‘MI_CENTRAL’ A XN:NUMERO >= EN:SECUENCIA " + "B XN:NUM > 100 C ; !(C | B) & A@" + "%^I_TRATAR_INSERT.”EH:ORIGEN == ‘MI_CENTRAL’ = A ;" + " XN:NUMERO >= EN:SECUENCIA = B ; XN:NUM > 100 = C #" + " !(C | B) & A”"; } Deliver.deliver(where, phrase); }
deadfc9e-54c8-4638-b1e4-3bf0ab0fa1e0
7
public ComputStdMethodDouble(double []v){ if (null == v || 0 == v.length){ mean = median = stddev = 0; min = max = 0; }else if (1 == v.length){ mean = median = stddev = v[0]; min = max = v[0]; }else{ double sum = v[0],sqSum=0; min =v[0]; max = v[0]; for (int i=1;i<v.length;i++) { //Minimum if (v[i] < min) min = v[i]; //Maximum if (v[i] > max) max = v[i]; sum += v[i]; sqSum += (v[i]-v[i-1]) * (v[i]-v[i-1]); } mean = sum / (double) v.length; stddev = Math.sqrt(sqSum/(double)(v.length)); Arrays.sort(v); if (0 == (v.length % 2)) median = v[v.length/2]; else{ int mid = v.length/2; median = (v[mid] + v[mid+1])/2; } } }
5712f09d-55e9-4034-b9f2-a77e39154fd5
1
public void incluirNoInicio(ContaCorrente conta) { for (int i=this.capacidade - 2; i > 0; i ++) this.aContas[i+1] = this.aContas[i]; this.aContas[0] = conta; this.quantasContas ++; }
c32fa131-6611-4b2a-8093-28cbdce48683
7
private TreeNode getSearchedNodes(String searchTxt) { final DefaultMutableTreeNode master = new DefaultMutableTreeNode(); final Widget[] widgets = Widgets.getLoaded(); outer: for (final Widget widget : widgets) { if (widget.getChildrenCount() > 0) { final WidgetChild[] children = widget.getChildren(); for (final WidgetChild child : children) { if (child.getText().toLowerCase().contains(searchTxt.toLowerCase())) { addWidgetNode(master, widget); continue outer; } final WidgetChild[] subChildren = child.getChildren(); if (subChildren.length > 0) { for (WidgetChild subChild : subChildren) { if (subChild.getText().toLowerCase().contains(searchTxt.toLowerCase())) { addWidgetNode(master, widget); continue outer; } } } } } } return master; }
6b9b1092-a1b6-4148-9fc8-adf4c58f1a99
5
public static boolean isPrime(int x) { if (x == 2) { return true; } if (x % 2 == 0 || x == 1) { return false; } for (int i = 3; i * i <= Math.abs(x); i += 2) { if (x % i == 0) { return false; } } return true; }
6366ba7e-4dcb-43bc-afc2-fade3eb79277
8
public static List<Integer> findTetrahedralChiralCenters(Molecule molecule) { List<Integer> chiralCenterIndices = new ArrayList<Integer>(); MoleculeSignature molSig = new MoleculeSignature(molecule); List<String> signatureStrings = molSig.getVertexSignatureStrings(); for (int i = 0; i < molecule.getAtomCount(); i++) { int[] connected = molecule.getConnected(i); if (connected.length < 4) { continue; } else { String s0 = signatureStrings.get(connected[0]); String s1 = signatureStrings.get(connected[1]); String s2 = signatureStrings.get(connected[2]); String s3 = signatureStrings.get(connected[3]); if (s0.equals(s1) || s0.equals(s2) || s0.equals(s3) || s1.equals(s2) || s1.equals(s3) || s2.equals(s3)) { continue; } else { chiralCenterIndices.add(i); } } } return chiralCenterIndices; }
3510f758-c2ae-4d05-bd9a-a5690d125d9b
5
public java.awt.Component getTableCellEditorComponent( javax.swing.JTable jtable, Object value, boolean isSelected, int row, int column) { if (isReadOnly(row, column)) return null; colm = column; SimpleColumn columnDefinition = getColumn(column); Object rowObject = getValueAt(row); component = columnDefinition.getEditor(rowObject, row, isSelected); if (component == null) { Object actualValue = columnDefinition.getCellData(rowObject, row); if (actualValue == null) { actualClass = columnDefinition.getColumnClass(); if (actualClass == null) actualClass = String.class; } else { actualClass = actualValue.getClass(); if (actualClass==this.getClass()) throw new Error("SimpleColumns: A column's editor is incorrectly configured and has become self-referrential."); } editor = jtable.getDefaultEditor(actualClass); // // This is a hack. Internally, getTableCellEditorComponent calls jtable.getModel().getColumnClass(column), // which normally returns the SimpleColumn derivative class. It would then try to create an instance // of the SimpleColumn derivative class given a string parameter. This breaks. To get around this, // we temporarily return actualClass in the model's getColumnClass(int). // // Alternatively, we could simply create our own default editors, but this might cause unpleasant // (further) divergence from standard JTable behavior. // ((ColumnTableModel)jtable.getModel()).setTemporaryColumnClass(actualClass); // component = editor.getTableCellEditorComponent(jtable, actualValue, isSelected, row, column); // ((ColumnTableModel)jtable.getModel()).setTemporaryColumnClass(null); // } else { editor = null; } return component; }
725161a2-ee4f-4e09-8f6b-98ac823cb70c
2
private void adjustBounds() { if (mStorageCount > 0) { Rectangle bounds = mStorage[0].getBounds(); mBounds.x = bounds.x; mBounds.y = bounds.y; mBounds.width = bounds.width; mBounds.height = bounds.height; for (int i = 1; i < mStorageCount; i++) { mBounds.add(mStorage[i].getBounds()); } } else { mBounds.x = 0; mBounds.y = 0; mBounds.width = 0; mBounds.height = 0; } }
42e98589-ef0b-4d68-8585-3dbdf6a0d472
8
protected void compareDatasets(Instances data1, Instances data2) throws Exception { if (!data2.equalHeaders(data1)) { throw new Exception("header has been modified\n" + data2.equalHeadersMsg(data1)); } if (!(data2.numInstances() == data1.numInstances())) { throw new Exception("number of instances has changed"); } for (int i = 0; i < data2.numInstances(); i++) { Instance orig = data1.instance(i); Instance copy = data2.instance(i); for (int j = 0; j < orig.numAttributes(); j++) { if (orig.isMissing(j)) { if (!copy.isMissing(j)) { throw new Exception("instances have changed"); } } else if (orig.value(j) != copy.value(j)) { throw new Exception("instances have changed"); } if (orig.weight() != copy.weight()) { throw new Exception("instance weights have changed"); } } } }
93c092ca-5595-450c-9dd9-c6adcb93b143
9
public static Stack<Point> getPath(Point home, Point size, ArrayList<Point> dirts, ArrayList<Point> bumps) { State cur = new State(home, null,new HashSet<Point>(dirts),new HashSet<Point>(bumps)); //Shearch for the path. Stack<State> frontier = new Stack<State>(); HashSet<State> visited = new HashSet<State>(); while (cur.dirt.size() > 0) { if (!visited.contains(cur)) { visited.add(cur); for (State p : cur.legalMoves(size.x,size.y)) frontier.add(p); } if (frontier.size() > 0) cur = frontier.pop(); else break; // No solution found. } //Get home ! :) frontier = new Stack<State>(); visited = new HashSet<State>(); while (!cur.curPos.equals(home)) { if (!visited.contains(cur)) { visited.add(cur); for (State p : cur.legalMoves(size.x,size.y)) frontier.add(p); } if (frontier.size() > 0) cur = frontier.pop(); else break; // No solution found. } //Building the path. Stack<Point> path = new Stack<Point>(); System.out.println("Path:"); for (;cur != null; cur = cur.prevPos){ System.out.println("x: " + cur.curPos.x + " y:" + cur.curPos.y); path.push(cur.curPos); } path.pop(); return path; }
1a71adcc-8473-489f-a7ba-97c8ff7dc9a0
8
static Gain parseGain(final int algorithmNumber, final byte[] gainParameters) throws ParseException { Gain gain; switch (algorithmNumber) { case 0: gain = null; break; case 1: gain = ToneParser.parse(gainParameters); break; case 2: gain = CrunchParser.parse(gainParameters); break; case 3: gain = ScreamerParser.parse(gainParameters); break; case 4: gain = OverdriveParser.parse(gainParameters); break; case 5: gain = DistortionParser.parse(gainParameters); break; case 6: gain = PreampParser.parse(gainParameters); break; case 7: gain = SplitPreampParser.parse(gainParameters); break; default: throw new ParseException("Invalid Gain algorithm number: " + algorithmNumber); } return gain; }
9fabbb99-cbfe-40d0-9510-852aac530028
1
public void abortCommunication(final SubLWorker worker) throws IOException { final Integer id = worker.getId(); if (id.intValue() < 0) { //@note serial communications cannot be canceled right now return; } try { final String command = "(fif (" + "terminate-active-task-process" + " " + worker.getId() + " \"" + uuid + "\" " + ":abort" + ") '(ignore) '(ignore))"; converse(cycAccess.makeCycList(command)); } finally { // the SubL implementation of ABORT will not send anything back, // so we do need to perform event signaling and cleanup worker.fireSubLWorkerTerminatedEvent(new SubLWorkerEvent(worker, SubLWorkerStatus.ABORTED_STATUS, null)); // waitingReplyThreads.remove(id); } }
a66e6c9f-d65a-4d7f-962d-8b32c586e6d2
3
public static boolean isTruncatable(String num) { for (int i = 1; i < num.length(); i++) { if (!isPrime(Integer.parseInt(num.substring(0, i))) || !isPrime(Integer.parseInt(num.substring(i)))) { return false; } } return true; }
2151bddb-1514-4967-8636-1b02bdf7a72e
6
@Override public void actionPerformed(ActionEvent e) { if(e.getSource().equals(btnNextPanel1)){ cardLayout.show(frame.getContentPane(), "Panel2"); } else if(e.getSource().equals(btnNextPanel2)){ cardLayout.show(frame.getContentPane(), "Panel3"); }else if(e.getSource().equals(btnNextPanel3)){ cardLayout.show(frame.getContentPane(), "Panel4"); }else if(e.getSource().equals(btnPrevPanel2)){ cardLayout.show(frame.getContentPane(), "Panel1"); }else if(e.getSource().equals(btnPrevPanel3)){ cardLayout.show(frame.getContentPane(), "Panel2"); }else if(e.getSource().equals(btnPrevPanel4)){ cardLayout.show(frame.getContentPane(), "Panel3"); } }
1ec7e83c-db0d-4db9-884e-de49efdfd12e
5
public AbbreviationAlignmentContainer<AbbvGapsHMM.Emissions, AbbvGapsHMM.States> findMostProbablePathBackwards(Acronym acronym){ int sPos = _sParam.getRangeEnd(); int lPos = _lParam.getRangeEnd(); int state = States.S.ordinal(); int stringPosS = -1; int stringPosL = -1; if(_evalMat.at(0, 0, States.S.ordinal()) == 0){ return null; } List<Emissions> emmisionsPath = new ArrayList<AbbvGapsHMM.Emissions>(); List<States> statesPath = new ArrayList<AbbvGapsHMM.States>(); List<String> lAlign = new ArrayList<String>(); List<String> sAlign = new ArrayList<String>(); Emissions[] emissionValues = Emissions.values(); States[] stateValues = States.values(); Emissions currEmission; Integer currSF; Integer currLF; Integer currState; Integer currSF_stringPos; Integer currLF_stringPos; while(sPos < _sParam.getEvalMatrixSize()-1 || lPos < _lParam.getEvalMatrixSize()-1){ currEmission = emissionValues[ (int) Math.round(_emissions.at(sPos, lPos, state)) ]; currSF = (int) Math.round(_prevSF.at(sPos, lPos, state)); currLF = (int) Math.round(_prevLF.at(sPos, lPos, state)); currState = (int) Math.round(_states.at(sPos, lPos, state)); currSF_stringPos = (int) Math.round(_prevSF_stringPos.at(sPos, lPos, state)); currLF_stringPos = (int) Math.round(_prevLF_stringPos.at(sPos, lPos, state)); if(stringPosS != -1 && stringPosL != -1){ stringPosS = getLegalStringPos(stringPosS, acronym._shortForm); stringPosL = getLegalStringPos(stringPosL, acronym._longForm); lAlign.add(acronym._longForm.substring(stringPosL, currLF_stringPos)); sAlign.add(acronym._shortForm.substring(stringPosS, currSF_stringPos)); } emmisionsPath.add(currEmission); statesPath.add(stateValues[currState]); sPos = currSF; lPos = currLF; state = currState; stringPosS = currSF_stringPos; stringPosL = currLF_stringPos; } return new AbbreviationAlignmentContainer<AbbvGapsHMM.Emissions, AbbvGapsHMM.States>(sAlign, lAlign, emmisionsPath, statesPath, _evalMat.at(0, 0, States.S.ordinal())); }
f4c906f0-51d2-4398-ac1c-91faf36c15d8
4
public void setInstruments(int percusInstr) { switch(percusInstr) { case 0: // Rock this.bass = "[acoustic_bass_drum]"; this.snare = "[acoustic_snare]"; this.openHiHat = "[open_hi_hat]"; this.closedHiHat = "[closed_hi_hat]"; this.hiTom = "[hi_tom]"; this.hiMidTom = "[hi_mid_tom]"; this.loMidTom = "[lo_mid_tom]"; this.loTom = "[lo_tom]"; this.cymbal = "[crash_cymbal_2]"; break; case 1: // Hip-Hop this.bass = "[bass_drum]"; this.snare = "[electric_snare]"; this.openHiHat = "[open_hi_hat]"; this.closedHiHat = "[closed_hi_hat]"; this.hiTom = "[lo_mid_tom]"; this.hiMidTom = "[lo_tom]"; this.loMidTom = "[hi_floor_tom]"; this.loTom = "[lo_floor_tom]"; this.cymbal = "[ride_cymbal_1]"; break; case 2: // Electric this.bass = "[open_cuica]"; this.snare = "[vibraslap]"; this.openHiHat = "[hi_wood_block]"; this.closedHiHat = "[lo_wood_block]"; this.hiTom = "[electric_snare]"; this.hiMidTom = "[electric_snare]"; this.loMidTom = "[electric_snare]"; this.loTom = "electric_snare[]"; this.cymbal = "[long_whistle]"; break; case 3: // Ethnics this.bass = "[open_cuica]"; this.snare = "[claves]"; this.openHiHat = "[maracas]"; this.closedHiHat = "[cabasa]"; this.hiTom = "[hi_timbale]"; this.hiMidTom = "[lo_timbale]"; this.loMidTom = "[hi_bongo]"; this.loTom = "[lo_bongo]"; this.cymbal = "[ride_bell]"; break; } }
ec0ea037-fe98-4cb4-9ccd-efe47cb728f8
7
public Element handle(FreeColServer server, Player player, Connection connection) { ServerPlayer serverPlayer = server.getPlayer(connection); Unit carrier; try { carrier = player.getFreeColGameObject(carrierId, Unit.class); } catch (Exception e) { return DOMMessage.clientError(e.getMessage()); } if (!carrier.canCarryGoods()) { return DOMMessage.clientError("Not a goods carrier: " + carrierId); } else if (!carrier.isInEurope()) { return DOMMessage.clientError("Not in Europe: " + carrierId); } GoodsType type = server.getSpecification().getGoodsType(goodsTypeId); if (type == null) { return DOMMessage.clientError("Not a goods type: " + goodsTypeId); } else if (!player.canTrade(type)) { return DOMMessage.clientError("Goods are boycotted: " + goodsTypeId); } int amount; try { amount = Integer.parseInt(amountString); } catch (NumberFormatException e) { return DOMMessage.clientError("Bad amount: " + amountString); } if (amount <= 0) { return DOMMessage.clientError("Amount must be positive: " + amountString); } // Try to buy. return server.getInGameController() .buyGoods(serverPlayer, carrier, type, amount); }
cbec2022-c7a2-4386-937a-7a442429f064
0
public void setResultFilePath(String resultFilePath) { this.resultFilePath = resultFilePath; }
c613dcad-d803-4b9d-b839-2ee4300e2a68
5
private boolean roomIconClicked(Point mousePos){ for(int i = 0;i<rooms.size();i++){ if( mousePos.x > getRoomIconPos(i).x && mousePos.x < getRoomIconPos(i).x+rooms.get(i).getIconSize().x && mousePos.y > getRoomIconPos(i).y && mousePos.y < getRoomIconPos(i).y+rooms.get(i).getIconSize().y ){ flushPanel(conversationWindow,"Click on a person to ask questions!"); currentRoom = rooms.get(i); return true; } } return false; }
18065a21-210b-45a3-9b9d-5ce9d65b5b1a
6
protected int[] besterZug(int[] aktuellePosition, ArrayList<int[]> moeglicheZuege, String[][] spielfeld) { int[] zielPosition = getAktuelleZielPosition(spielfeld); double aktuellerAbstand = berechneAbstand(aktuellePosition, zielPosition); int[] bestePosition = { aktuellePosition[0], aktuellePosition[1] }; double besterZugWert = 0; for (int i = 0; i < moeglicheZuege.size(); i++) { double aktuellerZugWert = 0; int anzahlSpruengeZeile = 0; int anzahlSpruengeSpalte = 0; int[] mglZuege = moeglicheZuege.get(i); anzahlSpruengeZeile = Math.abs(aktuellePosition[0] - mglZuege[0]); anzahlSpruengeSpalte = Math.abs(aktuellePosition[1] - mglZuege[1]); if (anzahlSpruengeSpalte != anzahlSpruengeZeile) { aktuellerZugWert = Math.max(anzahlSpruengeSpalte, anzahlSpruengeZeile) + bewerteVertikal(); } else { aktuellerZugWert = anzahlSpruengeSpalte; if (aktuellerAbstand > berechneAbstand(mglZuege, zielPosition)) { aktuellerZugWert += bewerteDiagonal(); } } for (int[] beliebigeZielPosition : getZielPsotionen()) { if (Arrays.equals(mglZuege, beliebigeZielPosition)) { aktuellerZugWert += bewerteZiel(); } } if (besterZugWert < aktuellerZugWert) { besterZugWert = aktuellerZugWert; bestePosition[0] = mglZuege[0]; bestePosition[1] = mglZuege[1]; } } return bestePosition; }
99f2ba6a-45d4-4238-af9d-a00d662ecd99
4
public void gameLoop() { long lastTick = System.nanoTime(); while (true) { try { Thread.sleep(4); } catch (Exception e) {}; // pause a bit so that we don't choke the system double deltaTime = (double)(System.nanoTime() - lastTick) / 1_000_000_000.0; lastTick = System.nanoTime(); // Update multiple times rather than with a dangerously large delta-time while (deltaTime > MAX_DT) { System.out.println("[Game] dt > " + MAX_DT + " (" + deltaTime + ")."); update(MAX_DT); deltaTime -= MAX_DT; } if (deltaTime > 0) update(deltaTime); Graphics.clear(); draw(); } }
3ed277f3-c0d6-4384-b6ec-4ae07523e407
2
public List<String> listServerIds() throws Exception { CloudStackApiClient client = new CloudStackApiClient(LIST_VIRTUALMACHINE, apiKey, secretKey, apiUrl); String response = client.execute(); if (containsErrorMessage(response)) { throw new Exception("Error retrieving Servers. Response:" + getErrorMessage(response)); } Document doc = stringToXmlDocument(response); NodeList vms = doc.getElementsByTagName("virtualmachine"); List<String> vmIds = new ArrayList<String>(); for (int i = 0; i < vms.getLength(); i++) { vmIds.add(((Element) vms.item(i)).getElementsByTagName("id").item(0).getTextContent().trim()); } return vmIds; }
c55e2165-94d4-45a0-bfa7-5769677ee1c0
5
@Override public String onAdvEvent(String event, L2Npc npc, L2PcInstance player) { String htmltext = ""; QuestState st = player.getQuestState(qn); if (st != null && Util.isDigit(event)) { int score = Integer.parseInt(event); if (SCORES.containsKey(score)) { int crystal = SCORES.get(score).getCrystalId(); String ok = SCORES.get(score).getOkMsg(); String noadena = SCORES.get(score).getNoAdenaMsg(); String noscore = SCORES.get(score).getNoScoreMsg(); if (st.getQuestItemsCount(score) == 0) htmltext = npc.getNpcId() + "-" + noscore + ".htm"; else if (st.getQuestItemsCount(ADENA) < COST) htmltext = npc.getNpcId() + "-" + noadena + ".htm"; else { st.takeItems(ADENA, COST); st.giveItems(crystal, 1); htmltext = npc.getNpcId() + "-" + ok + ".htm"; } } } return htmltext; }
96702002-dcf1-4ae0-989e-c078281bb678
7
*/ public void centerVertical(FastVector nodes) { // update undo stack if (m_bNeedsUndoAction) { addUndoAction(new centerVerticalAction(nodes)); } int nMinX = -1; int nMaxX = -1; for (int iNode = 0; iNode < nodes.size(); iNode++) { int nX = getPositionX((Integer) nodes.elementAt(iNode)); if (nX < nMinX || iNode == 0) { nMinX = nX; } if (nX > nMaxX || iNode == 0) { nMaxX = nX; } } for (int iNode = 0; iNode < nodes.size(); iNode++) { int nNode = (Integer) nodes.elementAt(iNode); m_nPositionX.setElementAt((nMinX + nMaxX) / 2, nNode); } }
63acfc1e-0dc1-4ca5-82cf-4462e49d6292
6
public float arg() { final float PI = (float)Math.PI; if (x == 0) { if(y < 0) { return -PI/2; } else if (y > 0) { return PI/2; } throw new IllegalArgumentException("The argument of the zero vector is undefined."); } float atan = (float)Math.atan(y/x); if(x > 0) { return atan; } else if(x < 0) { if (y > 0) { return atan + PI; } return atan - PI; } throw new IllegalArgumentException("SNAFU"); }
4c2523f6-52e5-48a0-9a35-3dbf4c25ffcd
2
public boolean hasStatus(UnitStatus.Type statusType) { for (UnitStatus status : statuses) { if (status.getType() == statusType) { return true; } } return false; }
2773ffe8-2280-4b97-b1c5-763bb2f7a3e3
3
@Override public void run() { long beforeTime, timeDiff, sleep; beforeTime = System.currentTimeMillis(); while (gameLogic.getBase().getHealth() > 0) { gameLogic.moveEnemies(); gameLogic.checkCollisions(); repaint(); timeDiff = System.currentTimeMillis() - beforeTime; sleep = Definitions.simulationSepInMillis - timeDiff; if (sleep < 0) sleep = 2; try { Thread.sleep(sleep); } catch (InterruptedException e) { System.out.println("interrupted"); } beforeTime = System.currentTimeMillis(); } gameLogic.doDefeat(); }
baa181b2-cd16-428e-bfb5-9301eb1ed1da
4
public String getHumanPropValue(String name, String prop) throws IOException { if (name.isEmpty()) return null; if (humanProp == null) setHumanProp(); if (humanProp == null) throw new NullPointerException(); LinkedHashMap<String, String> human = humanProp.getHuman(name); if (human == null) return null; return human.get(prop); }
b9cbd10b-5ed5-411d-8fcd-cf2b9fef42e0
7
public static void main(String[] args){ // Socket which will connect to the engine. Socket socket = null; // Reader to read packets from engine BufferedReader inStream = null; // Convenience wrapper to write back to engine PrintWriter outStream = null; // port number specified by engine to connect to. int port = Integer.parseInt(args[0]); try { socket = new Socket("localhost", port); outStream = new PrintWriter(socket.getOutputStream(), true); inStream = new BufferedReader(new InputStreamReader( socket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host - can't connect."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection."); System.exit(1); } String input; String output; GenericBot bot = new SimpleBot(); while (true) { try { // block until engine sends us a packet, then read it into input input = inStream.readLine(); } catch (IOException e) { System.out.println("Connection reset while waiting to read."); e.printStackTrace(); break; } if (input == null) { System.out.println("Gameover, engine disconnected"); break; } // Here is where you should implement code to parse the packets from // the engine and act on it. // System.out.println(input); output = bot.parse(input); if (input.split(" ")[0].compareToIgnoreCase("GETACTION") == 0) { // When appropriate, reply to the engine with a legal action. // The engine will ignore all spurious packets you send. // The engine will also check/fold for you if you return an // illegal action. outStream.println(output); // outStream.println("CHECK"); } } // Once the server disconnects from us, close our streams and sockets. try { outStream.close(); inStream.close(); socket.close(); } catch (IOException e) { System.out.println("Encounterd problem shutting down connections"); e.printStackTrace(); } }
5f2d78c9-16b5-4390-ac4b-7fc625ec1358
4
private Image findGameElementImage(Element element) { if (element instanceof IdentityDisc) { return identitydisc; } else if (element instanceof LightGrenade) { if (!((LightGrenade) element).isActive() && !((LightGrenade) element).isExploded()) return lightgrenade; } return null; }
00fe1e4a-bb0d-4b74-a176-06ba0a8a8c65
8
void output(int code, OutputStream outs) throws IOException { cur_accum &= masks[cur_bits]; if (cur_bits > 0) cur_accum |= (code << cur_bits); else cur_accum = code; cur_bits += n_bits; while (cur_bits >= 8) { char_out((byte) (cur_accum & 0xff), outs); cur_accum >>= 8; cur_bits -= 8; } // If the next entry is going to be too big for the code size, // then increase it, if possible. if (free_ent > maxcode || clear_flg) { if (clear_flg) { maxcode = MAXCODE(n_bits = g_init_bits); clear_flg = false; } else { ++n_bits; if (n_bits == maxbits) maxcode = maxmaxcode; else maxcode = MAXCODE(n_bits); } } if (code == EOFCode) { // At EOF, write the rest of the buffer. while (cur_bits > 0) { char_out((byte) (cur_accum & 0xff), outs); cur_accum >>= 8; cur_bits -= 8; } flush_char(outs); } }
7d6165a1-2868-4da9-b309-4c5bcb025ecf
2
@Override public void setForeground(Color foregroundColor) { assert foregroundColor != null; if (this.foregroundColor != null && this.foregroundColor.getRGB().equals(foregroundColor.getRGB())) { return; } super.setForeground(foregroundColor); this.foregroundColor = foregroundColor; }
64818cf8-c674-4235-b2aa-405ae851bdca
6
protected void paintFocus(Graphics g, AbstractButton b, Rectangle viewRect, Rectangle textRect, Rectangle iconRect) { boolean divider = b.getName() == null ? false : b.getName().equals("dividerButton"); if(b.getModel().isPressed() || mouseOver || divider) { return; } g.setColor(Color.white); g.setColor(new Color(55, 55, 255)); g.drawString(b.getText() == null ? "" : b.getText(), textRect.x, textRect.y + g.getFontMetrics().getAscent()); if(b.getBorder() == null) { drawBorder(g, b); } }
19e88862-5a30-465d-82d7-c16dbc074f09
4
public Attacks removeMin() { if ( _heap.size() == 0 ) return null; //store root value for return at end of fxn Attacks retVal = peekMin(); //store val about to be swapped into root Attacks foo = _heap.get( _heap.size() - 1); //swap last (rightmost, deepest) leaf with root swap( 0, _heap.size() - 1 ); //lop off last leaf _heap.remove( _heap.size() - 1); // walk the now-out-of-place root node down the tree... int pos = 0; int minChildPos; while( pos < _heap.size() ) { //choose child w/ min value, or check for child minChildPos = minChildPos(pos); //if no children, then i've walked far enough if ( minChildPos == -1 ) break; //if i am less than my least child, then i've walked far enough else if ( foo.getPri() < _heap.get(minChildPos).getPri() ) break; //if i am > least child, swap with that child else { swap( pos, minChildPos ); pos = minChildPos; } } //return removed value return retVal; }//O(logn)
41b1c40c-cc2f-4fb9-a376-1d610dde4761
1
public Deliver OnDeliver() { if (this.LoginResult.ErrorCode == 0) { return this.pconnect.OnDeliver(); } else { return null; } }
9454ef79-dd61-4843-8e81-8d4c1081c044
1
public void testInvalidObj() { aDateTime = getADate("2000-01-01T00:00:00"); try { cYear.compare("FreeBird", aDateTime); fail("Invalid object failed"); } catch (IllegalArgumentException cce) {} }
b05e218f-6388-47cb-aef3-e23ba4ea3f99
6
void betting() throws Exception { System.out.println("Betting begins. "); System.out.println("-----------------------------------------------"); System.out.println("Specify entry payment amount:"); int payment = sc.nextInt(); if (payment <= 0) { System.out.println("Payment ought to be higher than 0! Try again . . ."); sc = new Scanner(System.in); payment = sc.nextInt(); } betsSmallBig(); for (Iterator<Player> i = players.iterator(); i.hasNext(); ) { Player currentPlayer = i.next(); if (currentPlayer.chips >= payment) // check if player can afford the payment { if (currentPlayer.smallBlind == true) { currentPlayer.chips -= paymentSmallBlind; bank += paymentSmallBlind; System.out.println(currentPlayer+" has "+currentPlayer.chips+" chips left."); } else if (currentPlayer.bigBlind == true) { currentPlayer.chips -= paymentBigBlind; bank += paymentBigBlind; System.out.println(currentPlayer+" has "+currentPlayer.chips+" chips left."); } else { currentPlayer.chips -= payment; bank += payment; System.out.println(currentPlayer+" has "+currentPlayer.chips+" chips left."); } } else { System.out.println(currentPlayer+ " does not have enough chips to proceed!"); if (players.size() == 1) { System.out.println("The last player dropped out of the game!"); System.exit(0); } else { i.remove(); } } } System.out.println("Bank raised "+bank+" chips."); }
21945c66-e40a-41f6-810d-5549942c05fd
9
@Override public void run(){ StaticVar.countProcess++; //需要增加while循环检测connectionTimeOut并作相应处理,使其重新连接 while(this.connectTime<=maxConnectTime){ try { this.httpUrl=(HttpURLConnection)new URL(downloadWorker.getHttpDownload().getSrcUrl()).openConnection(); break; } catch (IOException e) { // TODO Auto-generated catch block //需要重写,在catch到IOException(connectionTimeOut)后将连接次数+1 this.connectTime++; e.printStackTrace(); } } try{ if(this.connectTime<maxConnectTime){ if(piece.getCurPos()<piece.getEndPos()){ rfwrite =new RandomAccessFile(downloadWorker.getHttpDownload().getSavePath()+downloadWorker.getHttpDownload().getFileName(),"rw"); httpUrl.setRequestProperty("User-Agent", "jmultidownload");//设置user-agent String contentRange="bytes="+piece.getCurPos()+"-";//设置文件流开始位置 httpUrl.setRequestProperty("RANGE", contentRange);//设置文件流开始位置 //out.println("线程"+name+"ContentRange="+httpurl.getHeaderField("Content-Range")); if(206==httpUrl.getResponseCode()){ //服务器响应206:partial content,该响应对应Range字段 input = httpUrl.getInputStream(); rfwrite.seek(piece.getCurPos()); int c=0; while((c=input.read(b,0,1024))>0){ synchronized (this){ if(StaticVar.PAUSE_DOWNLOAD==downloadWorker.getDownloaddStatus()){ this.wait(); } } System.out.println("begPos="+piece.getBegPos()+"/curPos"+piece.getCurPos()+"/endPos"+piece.getEndPos()); piece.setCurPos(piece.getCurPos()+c); if(piece.getCurPos()>=piece.getEndPos()){//该块已传输结束 int realWrite=c-(int)(piece.getCurPos()-piece.getEndPos());//读写修正 rfwrite.write(b, 0, realWrite); piece.setCurPos(piece.getEndPos()); downloadWorker.growBytes(realWrite); break; }else{ rfwrite.write(b,0,c); downloadWorker.growBytes(c); } } //out.println("线程"+name+"结束字节是"+currentPos); input.close(); rfwrite.close(); } } }else{ //TODO超出最大连接次数,应进行出错处理 } }catch(IOException | InterruptedException e){ e.printStackTrace(); } }
beb03536-40c5-4484-a5bf-404cca3a71a1
4
private void jButton21ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton21ActionPerformed try { if (jTable4.getSelectedRow() < 0) { JOptionPane.showMessageDialog(this, "Please select server to delete", "Error", JOptionPane.ERROR_MESSAGE); return; } int userSelection = JOptionPane.showConfirmDialog(this, "Deleting server will remove all accounts associated with server.\nAre you sure you want to delete server", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); System.out.println("userSelection:" + userSelection); if (userSelection == 0) { boolean status = StorageHelper.removeOtherTabServer((String) jTable4.getModel().getValueAt(jTable4.getSelectedRow(), 2), (String) jTable4.getModel().getValueAt(jTable4.getSelectedRow(), 1)); if (status) { JOptionPane.showMessageDialog(null, "Server deleted successfully", "Server Delete Success", JOptionPane.INFORMATION_MESSAGE); loadOtherTabServers(); ((OtherTabAccountModel) jTable3.getModel()).clearValue(); CardLayout topLayout = (CardLayout) (jPanel27.getLayout()); CardLayout bottomlayout = (CardLayout) (jPanel28.getLayout()); topLayout.show(jPanel27, "BlankTop"); bottomlayout.show(jPanel28, "BlankBottom"); } else { JOptionPane.showMessageDialog(null, "Server could not be deleted because of storage failure", "Error", JOptionPane.ERROR_MESSAGE); } } } catch (Exception e) { e.printStackTrace(); } }
1015c0ba-88de-46c2-abbe-7d4ba64e772f
7
private static void checkPanDigital(int[] indexes, HashMap<Integer, Integer> products) { for (int split1 = 1; split1 < indexes.length - 1; split1++) { for (int split2 = split1 + 1; split2 < indexes.length; split2++) { StringBuilder sb1 = new StringBuilder(); for (int i = 0; i < split1; i++) { sb1.append(indexes[i]); } StringBuilder sb2 = new StringBuilder(); for (int j = split1; j < split2; j++) { sb2.append(indexes[j]); } StringBuilder sb3 = new StringBuilder(); for (int k = split2; k < indexes.length; k++) { sb3.append(indexes[k]); } final int i = Integer.parseInt(sb1.toString()); final int j = Integer.parseInt(sb2.toString()); final int k = Integer.parseInt(sb3.toString()); if ((i * j) == k) { if (!products.containsKey(k)) { System.out.println(Arrays.toString(new int[]{i, j, k})); products.put(k, products.size()); } } } } }
af1da002-1318-4458-b9b8-b17f1cd26d6e
0
public int getRed(){ return _red; }
3ade00d2-82da-4e84-83c9-2e05503c8029
0
public Grammar getGrammar() { return grammar; }
e2d14004-b2e1-4ef2-a779-a7aff11a0b04
2
public void addComponentToPane(Container pane) { // Set up the title image for reuse. titleImage = null; try { titleImage = ImageIO.read(new File("src" + File.separator + "mentalpoker" + File.separator + "images" + File.separator + "title.png")); } catch (IOException e) { e.printStackTrace(); } JLabel titleImageLabel = new JLabel(new ImageIcon(titleImage)); /* Username input card */ JPanel usernameInputPaneLine1 = new JPanel(); usernameLabel = new JLabel("Enter your username:"); usernameField = new JTextField(20); startButton = new JButton(); startButton.setText("Set Username"); startButton.addActionListener(this); usernameInputPaneLine1.add(usernameLabel); usernameInputPaneLine1.add(usernameField); JRootPane rootPane = frame.getRootPane(); rootPane.setDefaultButton(startButton); JPanel usernameInputPaneGridLayout = new JPanel(new GridLayout(0, 1)); usernameInputPaneGridLayout.add(titleImageLabel); usernameInputPaneGridLayout.add(usernameInputPaneLine1); JPanel usernameInputButtons = new JPanel(); JButton continueButton = new JButton("Continue"); continueButton.setActionCommand("setUsername"); continueButton.addActionListener(this); usernameInputButtons.add(continueButton); warning = new JLabel("You must provide a username"); warning.setForeground(Color.red); warning.setVisible(false); usernameInputPaneGridLayout.add(usernameInputButtons); usernameInputPaneGridLayout.add(warning); usernameInputPaneGridLayout.setBorder(new EmptyBorder(10, 10, 10, 10)); /* Game choice card */ JPanel joinOrHostPageOuterLayout = new JPanel(new GridLayout(0, 1)); joinOrHostPagePanel = new JPanel(); JButton joinGame = new JButton("Join Game"); JButton hostGame = new JButton("Host Game"); joinGame.setActionCommand("joinGame"); hostGame.setActionCommand("hostGame"); joinGame.addActionListener(this); hostGame.addActionListener(this); joinOrHostPagePanel.add(hostGame); joinOrHostPagePanel.add(joinGame); // Create a textbox and input button to display the game host choices slotChoiceLayout = new JPanel(new GridLayout(0, 1)); slotChoiceLayout.setBorder(new EmptyBorder(10, 10, 10, 10)); JLabel hostingGameTitle = new JLabel("Set up your game..."); JLabel numberOfSlotsInstruction = new JLabel( "Select a number of slots to use:"); String[] slots = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" }; numberOfSlots = new JComboBox(slots); JButton startGameButton = new JButton("Start Game"); startGameButton.setActionCommand("startGameWithSlots"); startGameButton.addActionListener(this); JLabel titleImageLabel2 = new JLabel(new ImageIcon(titleImage)); slotChoiceLayout.add(titleImageLabel2); slotChoiceLayout.add(hostingGameTitle); slotChoiceLayout.add(numberOfSlotsInstruction); slotChoiceLayout.add(numberOfSlots); slotChoiceLayout.add(startGameButton); slotChoiceLayout.setVisible(false); // This is hidden, will be shown later. slotChoiceLayout.setLayout(new BoxLayout(slotChoiceLayout, BoxLayout.Y_AXIS)); JLabel titleImageLabel3 = new JLabel(new ImageIcon(titleImage)); joinOrHostPageOuterLayout.add(titleImageLabel3); joinOrHostPageOuterLayout.add(joinOrHostPagePanel); /* Hosting game screen (only seen if user is hosting game). */ hostingScreenGridLayout = new JPanel(new GridBagLayout()); JLabel nowHosting = new JLabel( "Now hosting, users will appear in the boxes as they connect"); hostGameGBConstraints = new GridBagConstraints(); hostGameGBConstraints.fill = GridBagConstraints.HORIZONTAL; JLabel titleImageLabel4 = new JLabel(new ImageIcon(titleImage)); hostGameGBConstraints.gridx = 0; hostGameGBConstraints.gridy = 0; hostGameGBConstraints.gridwidth = 3; hostingScreenGridLayout.add(titleImageLabel4, hostGameGBConstraints); hostGameGBConstraints.ipady = 40; hostGameGBConstraints.gridx = 0; hostGameGBConstraints.gridy = 1; hostingScreenGridLayout.add(nowHosting, hostGameGBConstraints); hostGameGBConstraints.gridwidth = 1; userButtons = new ArrayList<JButton>(); // Create user boxes for people, initially black. for (int i = 0; i < 10; i++) { JButton temp = new JButton(); userButtons.add(temp); } /* Join game panel, showing available games. */ joinGamePanel = new JPanel(new GridBagLayout()); joinGameGBConstraints = new GridBagConstraints(); JButton mainMenuButton = new JButton("Back to main menu"); mainMenuButton.setActionCommand("backToMainMenu"); mainMenuButton.addActionListener(this); joinGameGBConstraints.gridx = 0; joinGameGBConstraints.gridy = 0; joinGamePanel.add(mainMenuButton, joinGameGBConstraints); JLabel joinGameTitle = new JLabel("Available games will appear below"); joinGameGBConstraints.gridx = 1; joinGameGBConstraints.gridy = 0; joinGameGBConstraints.weighty = 1; // Move this to the bottom right element when it is added joinGameGBConstraints.weightx = 1; // Move this to the bottom right element when it is added joinGamePanel.add(joinGameTitle, joinGameGBConstraints); // Set up the "join game" list joinGameGBConstraints.gridwidth = 4; joinGameGBConstraints.ipadx = 400; joinGameGBConstraints.anchor = GridBagConstraints.NORTHWEST; joinGameGBConstraints.gridx = 0; joinGameGBConstraints.gridy = 1; joinGameGBConstraints.gridheight = 1; listModel = new DefaultListModel(); gamesList = new JList(listModel); gamesList.addListSelectionListener(this); JScrollPane scrollPane = new JScrollPane(gamesList); joinGamePanel.add(scrollPane, joinGameGBConstraints); nameofHosterField = new JTextField(); JButton joinGameButton = new JButton("Join game"); joinGameGBConstraints.gridx = 0; joinGameGBConstraints.ipadx = 300; joinGameGBConstraints.gridy = 2; joinGameGBConstraints.gridwidth = 2; joinGameGBConstraints.gridheight = 1; joinGamePanel.add(nameofHosterField, joinGameGBConstraints); joinGameGBConstraints.gridx = 2; joinGameGBConstraints.ipadx = 0; joinGameGBConstraints.gridy = 2; joinGameGBConstraints.gridwidth = 1; joinGameGBConstraints.gridheight = 1; joinGamePanel.add(joinGameButton, joinGameGBConstraints); joinGameButton.setActionCommand("joinGameFromSearch"); joinGameButton.addActionListener(this); /* Card screen */ cardScreenLayout = new JPanel(new GridBagLayout()); cardScreenGBC = new GridBagConstraints(); cardScreenGBC.gridx = 0; cardScreenGBC.gridy = 0; cardScreenGBC.gridwidth = 2; JLabel yourCardsTitle = new JLabel("Your hand:"); cardScreenLayout.add(yourCardsTitle, cardScreenGBC); cardScreenGBC.gridwidth = 1; cards = new JPanel(new CardLayout()); cards.add(usernameInputPaneGridLayout, usernameInputTitle); cards.add(joinOrHostPageOuterLayout, joinOrHostTitle); cards.add(slotChoiceLayout, slotChoiceTitle); cards.add(hostingScreenGridLayout, hostingScreenGridLayoutTitle); cards.add(joinGamePanel, joinGameScreenTitle); cards.add(cardScreenLayout, cardScreenTitle); pane.add(cards, BorderLayout.WEST); }
f0b6b3ab-6ad8-4cad-93b8-9ec179812a10
3
public int getValV(String nodeID, String attr){ increaseAccess(); Node n = nodeMap.get(nodeID); if (n != null){ Object val = n.getAttr(attr); if(val != null && val instanceof Integer){ return (Integer)val; } } return Integer.MAX_VALUE; }