method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
dad6a258-3fc8-407f-b3f9-4bf9278be2c9
1
public boolean benutzerErstellen(String benutzername, String passwort, int oeEinheit) { Benutzer neu = dbZugriff.neuerBenutzerErstellen(benutzername, passwort, oeEinheit, Optionen.isInitialbelegungbenutzergesperrt()); if (neu == null) { return false; } else { return true; } }
d0da3fbd-dfaf-455c-902a-df21d01c3cc9
0
public int getId() { return id; }
fb5a7387-b58a-4a51-b0cf-bf274481b738
8
private int setUpForEval(BitSet subset) throws Exception { int fc = 0; for (int jj = 0;jj < m_numAttributes; jj++) { if (subset.get(jj)) { fc++; } } //int [] nbFs = new int [fc]; //int count = 0; for (int j = 0; j < m_numAttributes; j++) { m_theInstances.attribute(j).setWeight(1.0); // reset weight if (j != m_theInstances.classIndex()) { if (subset.get(j)) { // nbFs[count++] = j; m_theInstances.attribute(j).setWeight(0.0); // no influence for NB } } } // process delete set for (int i = 0; i < m_numAttributes; i++) { if (m_deletedFromDTNB.get(i)) { m_theInstances.attribute(i).setWeight(0.0); // no influence for NB } } if (m_NB == null) { // construct naive bayes for the first time m_NB = new NaiveBayes(); m_NB.buildClassifier(m_theInstances); } return fc; }
472478a5-3f43-4cfe-a573-8f3cbc4fcf86
0
public void setMatches(Vector matches) {this.matches = matches;}
af5649e5-00be-430c-9316-e4fe891b5b2d
0
@BeforeClass public static void setUpClass() { }
8ac63ec6-e69e-4039-9f0b-930ac266e496
2
@Test @Ignore public void test_AttendanceResponseListGet() { AttendanceResponseList laAttRespList = laClient.getAttendanceResponseList(5, "2012-01-01-08.00.00.000000"); System.out.println(laAttRespList.getAttendanceResponseList().size()); if (laAttRespList.getAttendanceResponseList().size() > 0) { for (AttendanceResponse laAttResp : laAttRespList.getAttendanceResponseList()) { System.out.println(laAttResp.toString()); } } }
94661c87-f7ff-402c-a905-c2660573ea04
0
public int getPrice() { return price; }
9556c7d5-3d96-4ad0-8ac3-8ec22c0288c4
3
public int AddParagraph(String Text, String ID) { //Controllo se l'ID sia presente nella lista for (int i = 0; i < this._MyParagraphList.size(); i++) { if (this._MyParagraphList.get(i).GetID().equals(ID)) { //Creo il paragrafo che andrà a comporre il paragrafo Paragraph TmpParagraph = new Paragraph(new Chunk(Text, FontFactory.getFont(this._MyParagraphList.get(i).GetBaseFont(), this._MyParagraphList.get(i).GetFontSize(), this._MyParagraphList.get(i).GetStyle(), this._MyParagraphList.get(i).GetTextColor()))); TmpParagraph.setIndentationLeft(this._MyParagraphList.get(i).GetIndentationLeft()); TmpParagraph.setIndentationRight(this._MyParagraphList.get(i).GetIndentationRight()); TmpParagraph.setSpacingBefore(this._MyParagraphList.get(i).GetSpacingBefore()); TmpParagraph.setSpacingAfter(this._MyParagraphList.get(i).GetSpacingAfter()); //Se non sono presenti capitoli ritorno -2 e non imposto il paragrafo if(this._ChapterList.isEmpty()) return -2; //Aggiungo il paragrafo al capitolo this._ChapterList.get(this._ChapterList.size() - 1).addSection(TmpParagraph); return 1; } } //Se l'ID non è presente return -1; }
843a4371-1687-4983-8aea-36dd75f7ae89
2
static void drawBg1(Graphics2D ctx, Game game, World world) { if (bg == null) { bg = new BufferedImage(1200, 800, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = (Graphics2D) bg.getGraphics(); g2d.setPaint(textures.toTexture(21*12+9, 18)); g2d.fillRect(0,0,1200,800); g2d.setPaint(textures.toTexture(10*12+4));//91/*+38*/)); g2d.fillRect((int) game.getRinkLeft() , (int) game.getRinkTop() , (int) game.getRinkRight() - (int) game.getRinkLeft() , (int) game.getRinkBottom() - (int) game.getRinkTop() +1 ); //g2d.setPaint(textures.toTexture(26*12+6, 18)); g2d.fillRect(0, (int)game.getGoalNetTop(), (int)game.getRinkLeft(), (int)game.getGoalNetHeight()); g2d.fillRect((int)game.getRinkRight(), (int)game.getGoalNetTop(), (int)game.getRinkLeft(), (int) game.getGoalNetHeight()); dude.draw(g2d, new Rectangle(20, (int) game.getGoalNetTop() + (int) game.getGoalNetHeight() - dude.image.getHeight(), dude.wSize, dude.image.getHeight()), 0); dude.draw(g2d, new Rectangle(20, (int) game.getGoalNetTop(), dude.wSize, dude.image.getHeight()), 1); dude.drawMirrored(g2d, new Rectangle(1200 - 20 - dude.wSize, (int) game.getGoalNetTop() + (int) game.getGoalNetHeight() - dude.image.getHeight(), dude.wSize, dude.image.getHeight()), 1); dude.drawMirrored(g2d, new Rectangle(1200-20-dude.wSize, (int) game.getGoalNetTop(), dude.wSize, dude.image.getHeight()), 0); time.draw(g2d, new Rectangle(1150, 760, time.wSize, time.hSize), 0); g2d.dispose(); } ctx.drawImage(bg, 0, 0, null); if (bloodImg != null) ctx.drawImage(bloodImg, 0, 0, null); drawTopLine(ctx, game, world); }
91da5c52-48c8-4837-8d88-92299434cb47
1
public final JSONArray getJSONArray(String key) throws JSONException { Object o = get(key); if (o instanceof JSONArray) { return (JSONArray)o; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); }
ec5c7c86-1e37-4590-8876-3b7169a03e4f
5
public final Writer write(Writer writer) throws JSONException { try { boolean b = false; int len = length(); writer.write('['); for (int i = 0; i < len; i += 1) { if (b) { writer.write(','); } Object v = this.myArrayList.get(i); if (v instanceof JSONObject) { ((JSONObject)v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray)v).write(writer); } else { writer.write(JSONObject.valueToString(v)); } b = true; } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } }
2af84631-3a97-4f12-ab72-efee5d4e034f
4
public void updateRoom(Room newRoom) throws IllegalArgumentException { int oldRoomIndex = -1; for (int roomIndex = 0; roomIndex < rooms.size(); ++roomIndex) { if (rooms.get(roomIndex).equals(newRoom) && rooms.get(roomIndex).getRoomID() != newRoom.getRoomID()) { throw new IllegalArgumentException("Зала/стая със същото име вече съществува в тази сграда!"); } if (rooms.get(roomIndex).getRoomID() == newRoom.getRoomID()) { oldRoomIndex = roomIndex; } } rooms.set(oldRoomIndex, newRoom); save(); }
28ed573c-f5f8-4afe-ad53-1b6a0591c659
0
public PumpingLemma get(int i) { return (PumpingLemma)myList.get(i); }
1341605f-4116-4320-846c-8d16dd940f57
2
public static List<String> complement(List<String> list_1, List<String> list_2) { List<String> result_list = new ArrayList<>(); for (String element : list_1) { if (list_2.contains(element)) { result_list.add(element); } } return result_list; }
480dfd9f-2ebf-4961-b1aa-36144b873fd0
0
public void setSize(Dimension size) { generateUnit(size); }
419c63cc-4cb9-4c38-b7e5-65045d2ddfec
2
public static String currencyName2(String c1, String c2){ Connection conn = DBase.dbConnection(); PreparedStatement dbpst; String curName2 =""; try{ String query = "Select CurrencyName FROM "+c1+ " where CountryCode = ?"; dbpst=conn.prepareStatement(query); dbpst.setString(1, c2); ResultSet rs = dbpst.executeQuery(); while(rs.next()){ curName2=rs.getString(1); } dbpst.close(); conn.close(); }catch(SQLException e){System.err.println(e);} return curName2; }
cae8e769-dd87-4663-b160-d72e0b28231c
8
static final public String RelationalExpression() throws ParseException { String tmp1="",tmp3="";Token tmp2=null; tmp1 = ShiftExpression(); if (jj_2_23(2)) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 97: tmp2 = jj_consume_token(97); break; case 98: tmp2 = jj_consume_token(98); break; case 99: tmp2 = jj_consume_token(99); break; case 100: tmp2 = jj_consume_token(100); break; default: jj_la1[26] = jj_gen; jj_consume_token(-1); throw new ParseException(); } tmp3 = RelationalExpression(); } else { ; } {if (true) return "%exp1% %exp2% %exp3%".replace("%exp1%",tmp1).replace("%exp2%",tmp2!=null?tmp2.toString():"").replace("%exp3%",tmp3).trim();} throw new Error("Missing return statement in function"); }
03e40196-bc78-4410-bbfa-eae4cd098862
3
@Override public Integer get(int index) { switch(index) { case 0: return x; case 1: return y; case 2: return z; default: throw new IndexOutOfBoundsException(); } }
a22a33f8-9d09-4697-a7dd-def557a8c4cf
1
static int getLength(LinkedList list) { int size = 0; int n = list.size(); for (int i = 0; i < n; ++i) { AttributeInfo attr = (AttributeInfo)list.get(i); size += attr.length(); } return size; }
6f1bc672-bd7c-4283-b8de-883ffbf6386d
3
public void paintShape(Graphics2D g2) { if (color != null) { label.setForeground(new java.awt.Color((int) color.getRed(), (int) color.getGreen(), (int) color.getBlue())); Dimension dim = label.getPreferredSize(); if (dim.width > 0 && dim.height > 0) { label.setBounds(0, 0, dim.width, dim.height); g2.translate(getX(), getY()); g2.scale(getWidth() / dim.width, getHeight() / dim.height); label.paint(g2); } } }
c4950daa-d3f2-4048-81a5-7413566d2213
8
Circle addDigit(boolean digit) { Circle newCircle = new Circle(digits, hash); ArrayList<Boolean> newDigits = newCircle.digits; boolean[] newHash = newCircle.hash; newDigits.add(digit); byte middleHash = 0; for (byte i = N; i > 0; i--) if (newDigits.get(newDigits.size()-i)) middleHash += (byte) (Math.pow(2, i-1)); if (newHash[middleHash]) return null; else newHash[middleHash] = true; if (newDigits.size() == (int) Math.pow(2, N)) { for (byte i = 1; i < N; i++) { byte endHash = 0; for (byte n = N; n > 0; n--) if (newDigits.get((newDigits.size()+i-n)%((int)(Math.pow(2, N))))) endHash += (byte) (Math.pow(2, n-1)); if (newHash[endHash]) return null; else newHash[endHash] = true; } } return newCircle; }
969fa2a6-6514-4a65-8cf2-e633b64667fa
9
void assertConsistent() { lock.lock(); try { if (requiresEviction()) { throw new AssertionError("requires evictions: size=" + mostRecentlyUsedQueries.size() + ", maxSize=" + maxSize + ", ramBytesUsed=" + ramBytesUsed() + ", maxRamBytesUsed=" + maxRamBytesUsed); } for (LeafCache leafCache : cache.values()) { Set<Query> keys = Collections.newSetFromMap(new IdentityHashMap<>()); keys.addAll(leafCache.cache.keySet()); keys.removeAll(mostRecentlyUsedQueries); if (!keys.isEmpty()) { throw new AssertionError("One leaf cache contains more keys than the top-level cache: " + keys); } } long recomputedRamBytesUsed = HASHTABLE_RAM_BYTES_PER_ENTRY * cache.size() + LINKED_HASHTABLE_RAM_BYTES_PER_ENTRY * uniqueQueries.size(); for (Query query : mostRecentlyUsedQueries) { recomputedRamBytesUsed += ramBytesUsed(query); } for (LeafCache leafCache : cache.values()) { recomputedRamBytesUsed += HASHTABLE_RAM_BYTES_PER_ENTRY * leafCache.cache.size(); for (DocIdSet set : leafCache.cache.values()) { recomputedRamBytesUsed += set.ramBytesUsed(); } } if (recomputedRamBytesUsed != ramBytesUsed) { throw new AssertionError("ramBytesUsed mismatch : " + ramBytesUsed + " != " + recomputedRamBytesUsed); } long recomputedCacheSize = 0; for (LeafCache leafCache : cache.values()) { recomputedCacheSize += leafCache.cache.size(); } if (recomputedCacheSize != getCacheSize()) { throw new AssertionError("cacheSize mismatch : " + getCacheSize() + " != " + recomputedCacheSize); } } finally { lock.unlock(); } }
a5a5682c-9cd6-49cd-80ee-69ac7626a9a9
8
public Image getImage() { if ( text != null && image == null ) { // Create the text image image = new BufferedImage(pos.width, pos.height, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); if ( font != null ) g.setFont(font); // If the user didn't set the size, then we should resize if ( !userSpecifiedPos ) { Rectangle2D b = g.getFontMetrics().getStringBounds(text, g); if ( b.getWidth() > gui.getWidth()) { String wrapText = wordWrap(g, text, gui.getWidth()); b = g.getFontMetrics().getStringBounds(wrapText, g); } setBounds(pos.x , pos.y, (int)b.getWidth(), g.getFontMetrics().getHeight() ); g.dispose(); // We have to recreate the image, with the new bounds image = new BufferedImage(pos.width, pos.height, BufferedImage.TYPE_INT_RGB); g = image.createGraphics(); if ( font != null ) g.setFont(font); } String wrapText = wordWrap(g, text, pos.width); g.setBackground(Color.white); g.setColor( g.getBackground() ); g.fillRect(0, 0, pos.width, pos.height); g.setColor(Color.black); final String[] lines = wrapText.split("\n"); final FontMetrics f = g.getFontMetrics(); int height = f.getHeight(); int y = ( pos.height - (lines.length * height) ) / 2 + height; for (String line : lines ) { int x = 0; Rectangle2D b = f.getStringBounds(line, g); if ( hcenter ) x = (int) (( pos.width - b.getWidth() ) / 2); g.drawString(line, x, y); y += height; } g.dispose(); } return image; }
9505ed97-c9d2-4622-ad4c-cb8a6c474767
4
public TaskListTablePanel(TaskListTableModel taskListTableModel) { super(); Objects.requireNonNull(taskListTableModel); tasksBeingEdited = 0; ActionListener al = new TaskPanelActionListener(this); setLayout(new BorderLayout()); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); // Combobox for Sorting // construct the JComboBox comboMap = new LinkedHashMap<String, Comparator<Task>>(); comboMap.put("Manual", Task.manualComparator); comboMap.put("Name", Task.nameComparator); comboMap.put("Due Date", Task.dueDateComparator); comboMap.put("Priority", Task.priorityComparator); JComboBox<String> sortList = new JComboBox<String>(comboMap.keySet() .toArray(new String[comboMap.size()])); sortList.setActionCommand("dropdownsort"); sortList.addActionListener(al); JLabel sortLabel = new JLabel("Sort By: "); JPanel sortSet = new JPanel(); FlowLayout layout = new FlowLayout(); layout.setHgap(0); layout.setVgap(0); sortSet.setLayout(layout); sortSet.add(sortLabel); sortSet.add(sortList); // Up and down bump buttons upButton = createIconedButton( getClass().getResource("/resources/up.png"), "Move Up", al); downButton = createIconedButton( getClass().getResource("/resources/down.png"), "Move Down", al); // Goes with buttons sortSet.add(upButton); sortSet.add(downButton); topPanel.add(sortSet, BorderLayout.EAST); // Add the new task and the edit task buttons newTaskButton = new JButton("New Task"); editTaskButton = new JButton("Edit Task"); deleteTaskButton = new JButton("Delete Task"); newTaskButton.setActionCommand("New Task"); editTaskButton.setActionCommand("Edit Task"); deleteTaskButton.setActionCommand("Delete Task"); newTaskButton.addActionListener(al); editTaskButton.addActionListener(al); deleteTaskButton.addActionListener(al); JPanel newButtonPanel = new JPanel(); // layout.setVgap(8); newButtonPanel.setLayout(layout); newButtonPanel.add(newTaskButton); newButtonPanel.add(editTaskButton); newButtonPanel.add(deleteTaskButton); JLabel spacer2 = new JLabel(" "); newButtonPanel.add(spacer2); topPanel.add(newButtonPanel, BorderLayout.WEST); // For now, we just add a spacer // topPanel.setPreferredSize(new Dimension(600, 50)); add(topPanel, BorderLayout.NORTH); // Tag panel components JLabel tagLabel = new JLabel("Filter by Tag:"); // Multiple tag selector list tagSelectionChoices = new Vector<String>(); tagSelector = new JList<String>(tagSelectionChoices); tagSelector .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); tagSelector.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { GlobalLogger.getLogger().logp(Level.INFO, this.getClass().getName(), "valueChanged", "List selection has changed. Checking tags"); JList<String> tagSelect = (JList<String>) e.getSource(); for (int i = e.getFirstIndex(); i <= e.getLastIndex(); ++i) { String tag = tagSelectionChoices.get(i); if (tagSelect.isSelectedIndex(i)) { Timeflecks.getSharedApplication().getFilteringManager() .getTagCollection().addTag(tag); } else { Timeflecks.getSharedApplication().getFilteringManager() .getTagCollection().removeTag(tag); } } // Post notification to repopulate the task list that's // filtered by tag Timeflecks.getSharedApplication().postNotification( TimeflecksEvent.INVALIDATED_FILTERED_TASK_LIST); } }); refreshTagSelector(); JScrollPane filterScrollPane = new JScrollPane(tagSelector); filterScrollPane.setPreferredSize(new Dimension(150, 60)); // Clear tags button clearTagButton = new JButton("Clear tags"); clearTagButton.setActionCommand("Clear tag selection"); // Use anonymous action listener instead of TaskPanelActionListener // because we need access to the tagSelector. clearTagButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Clear tag selection")) { GlobalLogger.getLogger().logp(Level.INFO, this.getClass().getName(), "actionPerformed(ActionEvent)", "Clear tag button pressed. Clearing tag selection"); tagSelector.clearSelection(); } } }); // FlowLayout JPanel for tag components JPanel tagPanel = new JPanel(new FlowLayout()); tagPanel.add(tagLabel); tagPanel.add(filterScrollPane); tagPanel.add(clearTagButton); // Search text field searchField = new JTextField(); searchField.setPreferredSize(new Dimension(100, 20)); searchField.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { GlobalLogger.getLogger().logp(Level.INFO, "TaskListTablePanel", "actionPerformed(ActionEvent)", "Search button pressed."); String searchText = searchField.getText(); // Either clearing the search or searching by the string, // depending on if empty or not String logMessage = (searchText.equals("")) ? "Clearing search." : "Searching by text \"" + searchText + "\""; GlobalLogger.getLogger().logp(Level.INFO, "TaskListTablePanel", "actionPerformed(ActionEvent)", logMessage); Timeflecks.getSharedApplication().getFilteringManager() .setSearchText(searchText); Timeflecks.getSharedApplication().postNotification( TimeflecksEvent.INVALIDATED_FILTERED_TASK_LIST); } @Override public void keyPressed(KeyEvent e) { } }); // Search Label JLabel searchLabel = new JLabel("Search Tasks:"); // Search Panel JPanel filterPanel = new JPanel(new FlowLayout()); filterPanel.add(searchLabel); filterPanel.add(searchField); filterPanel.add(tagPanel); add(filterPanel, BorderLayout.SOUTH); // Actual table table = new JTable(taskListTableModel); table.setDragEnabled(true); table.setTransferHandler(new TaskListTableTransferHandler()); table.setDropMode(DropMode.USE_SELECTION); // Set column widths table.getColumnModel().getColumn(0) .setMinWidth(MIN_COMPLETED_COLUMN_WIDTH); table.getColumnModel().getColumn(0) .setPreferredWidth(PREFERRED_COMPLETED_COLUMN_WIDTH); table.getColumnModel().getColumn(1).setMinWidth(MIN_NAME_COLUMN_WIDTH); table.getColumnModel().getColumn(1) .setPreferredWidth(PREFERRED_NAME_COLUMN_WIDTH); JScrollPane scroll = new JScrollPane(table); table.setFillsViewportHeight(true); table.setAutoCreateRowSorter(false); add(scroll, BorderLayout.CENTER); // Register for Timeflecks events final TaskListTablePanel thisTaskListTablePanel = this; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Timeflecks.getSharedApplication().registerForTimeflecksEvents( thisTaskListTablePanel); } }); }
27111e94-ead8-48e0-9409-0f8fdf7a066c
6
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); Class.forName("oracle.jdbc.OracleDriver") ; out.write("\n"); out.write("\n"); out.write("<html>\n"); out.write(" <HEAD>\n"); out.write(" <TITLE>Resort Rating table </TITLE>\n"); out.write(" </HEAD>\n"); out.write("\n"); out.write(" <BODY>\n"); out.write(" <H1>Welcome to Resort Rating Database </H1>\n"); out.write("\n"); out.write(" "); Connection connection = DriverManager.getConnection( "jdbc:oracle:thin:@fourier.cs.iit.edu:1521:orcl", "mkhan12", "sourov345"); Statement statement = connection.createStatement() ; ResultSet resultset = statement.executeQuery("SELECT Resort_name, Rate_id from Resort,Resort_Rating where Resort.Resort_id=Resort_Rating.Resort_id ") ; out.write("\n"); out.write("\n"); out.write(" <TABLE BORDER=\"1\">\n"); out.write(" <TR>\n"); out.write(" <TH>Resort</TH>\n"); out.write(" <TH>Rating</TH>\n"); out.write(" \n"); out.write(" \n"); out.write(" </TR>\n"); out.write(" "); while(resultset.next()){ out.write("\n"); out.write(" <TR>\n"); out.write(" <TD> "); out.print( resultset.getString(1) ); out.write("</td>\n"); out.write(" <TD> "); out.print( resultset.getString(2) ); out.write("</TD>\n"); out.write(" \n"); out.write(" </TR>\n"); out.write(" "); } out.write("\n"); out.write(" </TABLE>\n"); out.write(" <div id=\"a15\">\n"); out.write(" \n"); out.write(" <form id=\"form6\" name=\"form1\" method=\"post\" action=\"Query....jsp\">\n"); out.write(" <label>\n"); out.write(" <input type=\"submit\" name=\"button\" id=\"button\" value=\"Insert Rating\" />\n"); out.write(" </label>\n"); out.write(" </form>\n"); out.write(" </div> \n"); out.write(" <div id=\"a15\">\n"); out.write(" \n"); out.write(" <form id=\"form6\" name=\"form1\" method=\"post\" action=\"DeleteRating.jsp\">\n"); out.write(" <label>\n"); out.write(" <input type=\"submit\" name=\"button\" id=\"button\" value=\"Delete Rating\" />\n"); out.write(" </label>\n"); out.write(" </form>\n"); out.write(" </div>\n"); out.write(" </BODY>\n"); out.write("</html>\n"); out.write("\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
dc17cfdc-cdfb-40b5-ac24-2dba261afa86
4
@Override public MoveResult makeMove(HantoPieceType pieceType, HantoCoordinate from, HantoCoordinate to) throws HantoException { HantoPlayerColor color; HantoPiece piece; MoveResult result; color = whoseTurnIsIt(); // switch case for adding different types of game pieces switch(pieceType) { case BUTTERFLY: piece = new Butterfly(color); break; case SPARROW: piece = new Sparrow(color); break; default: throw new HantoException("Unrecognized game piece type!"); } // use copy constructor on given HantoCoordinates PieceCoordinate newFrom = from == null? null : new PieceCoordinate(from); PieceCoordinate newTo = to == null? null : new PieceCoordinate(to); validateMove(pieceType, newFrom, newTo, color); decrementPieceTypeForPlayer(color, pieceType); board.addPiece(newTo, piece); result = determineGameResult(); turnCount++; return result; }
77fda23a-c7de-40f6-8392-2817ed0b0fc4
1
@Override public void mouseClicked( MouseEvent e ) { for( MouseListener listener : listeners( MouseListener.class )){ listener.mouseClicked( e ); } }
25a822f6-1b6a-4ef2-b307-146d5aec09b5
5
public static void main(String[] args) { if (args.length != 3) { System.out.println(USAGE); System.exit(0); } String name = args[0]; InetAddress addr = null; int port = 0; Socket sock = null; // check args[1] - the IP-adress try { addr = InetAddress.getByName(args[1]); } catch (UnknownHostException e) { System.out.println(USAGE); System.out.println("ERROR: host " + args[1] + " unknown"); System.exit(0); } // parse args[2] - the port try { port = Integer.parseInt(args[2]); } catch (NumberFormatException e) { System.out.println(USAGE); System.out.println("ERROR: port " + args[2] + " is not an integer"); System.exit(0); } // try to open a Socket to the server try { sock = new Socket(addr, port); } catch (IOException e) { System.out.println("ERROR: could not create a socket on " + addr + " and port " + port); } // create Peer object and start the two-way communication try { Peer client = new Peer(name, sock); Thread streamInputHandler = new Thread(client); streamInputHandler.start(); System.out.println("You can write a message! close this program by entering \".\" and pressing Enter.\n"); client.handleTerminalInput(); System.out.println("Shutting down program..."); client.shutDown(); } catch (IOException e) { e.printStackTrace(); } }
08d6cd47-640d-4ae1-ada8-372c932515c1
0
public ProtocolChatMessage(int type, String content) { mType = type; mContent = content; }
154e6ca1-1dd6-417a-8373-4069453d3d38
5
public double standardDeviation_as_double() { boolean hold = Stat.nFactorOptionS; if (nFactorReset) { if (nFactorOptionI) { Stat.nFactorOptionS = true; } else { Stat.nFactorOptionS = false; } } double variance = 0.0D; switch (type) { case 1: double[] dd = this.getArray_as_double(); variance = Stat.variance(dd); break; case 12: BigDecimal[] bd = this.getArray_as_BigDecimal(); variance = (Stat.variance(bd)).doubleValue(); bd = null; break; case 14: throw new IllegalArgumentException("Complex cannot be converted to double"); default: throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!"); } Stat.nFactorOptionS = hold; return Math.sqrt(variance); }
87d86a1f-c4b4-4d41-9f3c-c9fc5957e1e7
9
public boolean groupSum5(int start, int[] nums, int target) { if (start >= nums.length) return (target == 0); if (nums[start] % 5 == 0) { if (groupSum5(start + 1, nums, target - nums[start])) return true; } else if (start != 0 && nums[start] == 1 && nums[start - 1] % 5 == 0) { if (groupSum5(start + 1, nums, target)) return true; } else { if (groupSum5(start + 1, nums, target)) return true; if (groupSum5(start + 1, nums, target - nums[start])) return true; } return false; }
01e6134a-95fb-4e95-b1ff-a56f2d9a37be
1
public String toString() { try { return this.toJSON().toString(4); } catch (JSONException e) { return "Error"; } }
c1abf182-4e47-4fe1-9375-11ac2c2d7a87
9
public void nextQuestion() { boolean exit = false; while (!exit) { ++_currentQuestionNumber; if (_currentQuestionNumber >= _questionsList.length) { _currentQuestionNumber = 0; } final QuestionsDatabase questionDatabase = new QuestionsDatabase(); int questionNumber = _questionNumbers.get(_questionsList[_currentQuestionNumber]); assert questionNumber >= 0 : "No question number returned"; _data = questionDatabase.getQuestion(questionNumber); assert _data != null : "For the question number <" + questionNumber + "> No data returned from the database"; exit = true; if (!_data.getShowQuestion()) { exit = false; } } if (_data.getType().equals(Type.RadioButton)) { _panel = new RadioButtonPanel((RadioButton) _data, _session); } else if (_data.getType().equals(Type.CheckBox)) { _panel = new CheckBoxPanel((CheckBox) _data, _session); } else if (_data.getType().equals(Type.BlankAnswer)) { _panel = new BlankAnswerPanel((BlankAnswer) _data, _session); } else if (_data.getType().equals(Type.BlankAnswer)) { _panel = new BlankAnswerPanel((BlankAnswer) _data , _session); } else if (_data.getType().equals(Type.FillInTheBlanks)) { _panel = new FillInTheBlanksPanel((FillInTheBlanks) _data, _session); } else if (_data.getType().equals(Type.ShortCut)) { _panel = new ShortCutPanel((ShortCut) _data, _session); } else { throw new RuntimeException("Type <" + _data.getType() + "> not supported."); } }
fb22798f-9b13-444d-9d24-37da632d173f
1
public void insertCorporation(int ID, String name, String address, String email) throws SQLException { if (conn != null) { Corporation corporation = new Corporation(ID, name, address, email); corporation.insert(conn); } }
a1f63765-0e09-42ce-9f0b-6bedb3ca6a9d
5
public Object[][] make_data_file(){ String[][] data= new String[this.tank_count][3]; for(int i=0; i<this.tank_count; i++){ data[i][0]=this.tanks_available[i].get_name(); String errormessage=""; switch (this.errors[i]){ case 0: errormessage=""; break; case 1: errormessage="you can pull him into higher tier matches"; break; case 2: errormessage="he can pull you into higher tier matches"; break; case 3: errormessage="exactly same battletiers"; break; } data[i][1]=errormessage; } return data; }
393364b4-c095-4134-8987-26cd95010f1f
7
public void renderTile(int xp, int yp, Tile tile) { xp -= xOffset; yp -= yOffset; for(int y = 0; y < tile.sprite.SIZE; y++) { int ya = y + yp; for(int x = 0; x < tile.sprite.SIZE; x++) { int xa = x + xp; if(xa < -tile.sprite.SIZE || xa >= width || ya < 0 || ya >= height) break; if(xa < 0) xa = 0; pixels[xa + ya * width] = tile.sprite.pixels[x + y * tile.sprite.SIZE]; } } }
669514ab-375a-46bd-8ff1-1db254744a09
6
private void backTrackToCNF() { if (myCNFMap==null) { backTrackToUnit(); return; } // System.out.println("MAP : "+myCNFMap); int[] visited=new int[myTrace.size()]; for (int i=0; i<myTrace.size(); i++) { if (visited[i]==0) { Production target=myTrace.get(i); if (myCNFMap.keySet().contains(target)) { myAnswer.add(target); visited[i]=1; } else { for (Production p : myCNFMap.keySet()) { if (myCNFMap.get(p).contains(target)) { // System.out.println(p+" -> " + myCNFMap.get(p)+ " contains "+target); visited=searchForRest(myCNFMap.get(p), p, visited); } } } } } // System.out.println("After Backtracking CNF = "+myAnswer); }
b0f96a9e-3ec5-43e5-ac3c-0582e911abd0
9
public MiOSDeployHelper() { setMacOsFeatures(); MouseHandler mouseHandler = new MouseHandler(); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 509, 367); createMenu(); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); tabbedPane.setBounds(6, 18, 495, 278); contentPane.add(tabbedPane); JPanel panelGeneral = new JPanel(); tabbedPane.addTab("General", null, panelGeneral, null); panelGeneral.setLayout(null); JLabel lblRootFolder = new JLabel("Root Folder"); lblRootFolder.setBounds(21, 17, 88, 16); panelGeneral.add(lblRootFolder); txtRootFolder = new JTextField(); txtRootFolder.setToolTipText("Double click to open file dialog"); txtRootFolder.addMouseListener(mouseHandler); txtRootFolder.setBounds(103, 11, 347, 28); panelGeneral.add(txtRootFolder); txtRootFolder.setColumns(10); JLabel lblGroupId = new JLabel("Group ID"); lblGroupId.setBounds(21, 57, 74, 16); panelGeneral.add(lblGroupId); txtGroupId = new JTextField(); txtGroupId.setColumns(10); txtGroupId.setBounds(103, 51, 347, 28); panelGeneral.add(txtGroupId); JLabel lblArtifactId = new JLabel("Artifact ID"); lblArtifactId.setBounds(21, 137, 74, 16); panelGeneral.add(lblArtifactId); txtVersion = new JTextField(); txtVersion.setColumns(10); txtVersion.setBounds(103, 91, 347, 28); panelGeneral.add(txtVersion); JLabel lblVersion = new JLabel("Version"); lblVersion.setBounds(21, 97, 88, 16); panelGeneral.add(lblVersion); txtArtifactId = new JTextField(); txtArtifactId.setColumns(10); txtArtifactId.setBounds(103, 131, 347, 28); panelGeneral.add(txtArtifactId); JLabel lblClassifier = new JLabel("Classifier"); lblClassifier.setBounds(21, 177, 61, 16); panelGeneral.add(lblClassifier); txtClassifier = new JTextField(); txtClassifier.setBounds(103, 171, 347, 28); panelGeneral.add(txtClassifier); txtClassifier.setColumns(10); JPanel panelFiles = new JPanel(); tabbedPane.addTab("Files", null, panelFiles, null); panelFiles.setLayout(null); JLabel lblHeaderFolder = new JLabel("Header Folder"); lblHeaderFolder.setBounds(6, 16, 88, 16); panelFiles.add(lblHeaderFolder); txtHeaderFolder = new JTextField(); txtHeaderFolder.addMouseListener(mouseHandler); txtHeaderFolder.setColumns(10); txtHeaderFolder.setBounds(106, 10, 341, 28); panelFiles.add(txtHeaderFolder); JLabel label = new JLabel("Debug-Simulator"); label.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); label.setBounds(6, 44, 122, 16); panelFiles.add(label); JLabel label_1 = new JLabel("Debug-iphoneos"); label_1.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); label_1.setBounds(6, 101, 122, 16); panelFiles.add(label_1); txtDI = new JTextField(); txtDI.addMouseListener(mouseHandler); txtDI.setColumns(10); txtDI.setBounds(106, 94, 341, 28); panelFiles.add(txtDI); JLabel label_2 = new JLabel("Release-Simulator"); label_2.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); label_2.setBounds(6, 135, 122, 16); panelFiles.add(label_2); txtRS = new JTextField(); txtRS.setColumns(10); txtRS.setBounds(106, 128, 341, 28); txtRS.addMouseListener(mouseHandler); panelFiles.add(txtRS); JLabel label_3 = new JLabel("Release-iphoneos"); label_3.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); label_3.setBounds(6, 169, 122, 16); panelFiles.add(label_3); txtRI = new JTextField(); txtRI.setColumns(10); txtRI.setBounds(106, 162, 341, 28); txtRI.addMouseListener(mouseHandler); panelFiles.add(txtRI); txtDS = new JTextField(); txtDS.addMouseListener(mouseHandler); txtDS.setColumns(10); txtDS.setBounds(106, 44, 341, 28); panelFiles.add(txtDS); JLabel lblResourceFolder = new JLabel("Resource Folder"); lblResourceFolder.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); lblResourceFolder.setBounds(6, 204, 88, 16); panelFiles.add(lblResourceFolder); txtResourceFolder = new JTextField(); txtResourceFolder.setColumns(10); txtResourceFolder.setBounds(106, 198, 341, 28); txtResourceFolder.addMouseListener(mouseHandler); panelFiles.add(txtResourceFolder); final JCheckBox ckbSameFolder = new JCheckBox("Same Lib"); ckbSameFolder.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { boolean ckbState = !ckbSameFolder.isSelected(); String folderPath = txtDS.getText(); txtDI.setEnabled(ckbState); txtRS.setEnabled(ckbState); txtRI.setEnabled(ckbState); if (ckbState) { folderPath = ""; } txtDI.setText(folderPath); txtRS.setText(folderPath); txtRI.setText(folderPath); } }); ckbSameFolder.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); ckbSameFolder.setBounds(0, 72, 128, 23); panelFiles.add(ckbSameFolder); JPanel panel = new JPanel(); tabbedPane.addTab("ReadMe", null, panel, null); panel.setLayout(new BorderLayout(0, 0)); JScrollPane scrollPane = new JScrollPane(); panel.add(scrollPane, BorderLayout.CENTER); txtReadme = new JTextArea(); scrollPane.setViewportView(txtReadme); JPopupMenu popupMenu = new JPopupMenu(); addPopup(txtReadme, popupMenu); JMenuItem mntmLoadFromFile = new JMenuItem("Load from file..."); popupMenu.add(mntmLoadFromFile); JButton btnDeploy = new JButton("Deploy"); btnDeploy.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { ConfigFile cfgFile = getConfigFileFromUI(); DeployManager deployManager = new DeployManager(); //Get the current plugin. Plugin plugin = PluginManager.getInstance().getCurrentPlugin(); try { Class<?> pluginClass = Class.forName(plugin.getClazz()); DeployTask deployTask =(DeployTask) pluginClass.newInstance();; deployManager.setDeplyTask(deployTask); deployTask.setConfigFile(cfgFile); deployManager.deploy(); final OutputConsole console = new OutputConsole(); // TODO: Set the console location. console.setVisible(true); deployTask.addListener(new DeployTaskListener() { @Override public void onMessage(String message, Object context) { console.outputMessage(message); } @Override public void onError(String message, Object context) { console.outputMessage(message); } @Override public void onDeployStart(String message, Object context) { } @Override public void onDeployDone(String message, Object context) { } }); } catch (IOException e) { logger.error("Error occurs, when deploying.", e); } catch (ClassNotFoundException e) { logger.error(String.format("Class %s not found", plugin.getClazz()), e); } catch (InstantiationException e) { logger.error(String.format("Cannot instante %s", plugin.getClazz()), e); } catch (IllegalAccessException e) { logger.error("Cannot access.", e); } } }); btnDeploy.setBounds(370, 308, 117, 29); contentPane.add(btnDeploy); JButton btnLoadConfig = new JButton("Load Config"); btnLoadConfig.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { FileDialog fd = new FileDialog(MiOSDeployHelper.this); fd.setVisible(true); if (fd.getFile() == null) { return; } cfgFilePath = String.format("%s%s", fd.getDirectory(), fd.getFile()); ConfigFile cfgFile = ConfigFile.loadFromFile(cfgFilePath); if (cfgFile == null) { return; } setUIFromConfigFile(cfgFile); } }); btnLoadConfig.setBounds(241, 308, 117, 29); contentPane.add(btnLoadConfig); JButton btnSaveConfig = new JButton("Save Config"); btnSaveConfig.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { FileDialog fd = new FileDialog(MiOSDeployHelper.this); fd.setMode(FileDialog.SAVE); fd.setVisible(true); if (fd.getFile() != null) { String filePath = String.format("%s%s", fd.getDirectory(), fd.getFile()); ConfigFile cfgFile = getConfigFileFromUI(); cfgFile.saveToFile(filePath); } } }); btnSaveConfig.setBounds(112, 308, 117, 29); contentPane.add(btnSaveConfig); setCenter(); }
a4698079-3e2f-41e2-84dc-d2984e335ed5
4
@Override public CreativeMaterialType getTypeByName(final String name) throws WrongTypeNameException { if (name == null) { throw new WrongTypeNameException("Type name is empty"); } switch (name) { case SLIDES_TYPE_NAME: case VIDEO_TYPE_NAME: case PICTURE_TYPE_NAME: return new CreativeMaterialType(name); default: throw new WrongTypeNameException("Type name is wrong"); } }
82e9ba87-272c-41e9-936a-631f39e1c44a
3
public void poll() { if (runningJob != null) { // check if the job has finished if (System.currentTimeMillis() - startTime > runningJob.getDuration()) { // job done runningJob.setStatus(JobStatus.Done); // fire event handler for (INodeEventHandler handler : handlers) handler.jobDone(runningJob); // set node status runningJob = null; status = NodeStatus.Idle; } } }
55650d6e-91a0-4115-b5d8-da74da365bcf
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 ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(SendFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(SendFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(SendFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(SendFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new SendFile().setVisible(true); } }); }
cdf005a8-0bf5-45cc-a19e-0f9d6a5c3afa
4
public int score(WordChain word) { int score = 0; int size = word.getLetterChain().size; ; if(size <= 3){ score += size; }else if(size ==4){ score += 5; }else if(size ==5){ score += 7; }else if(size == 6){ score += 10; }else{ score += 15; } return score; }
e62b692c-43e0-464b-9731-2d8c759bd10f
0
public void move(int x, int y) { int newX = this.GetX() + x; int newY = this.GetY() + y; this.SetX(newX); this.SetY(newY); }
93afd67c-d3e4-4635-b243-9048caf84ac0
0
public void setDirectionY(int a){ directionY = a; }
12653dcd-4b61-447a-99df-97382a2339b3
5
public BinaryNode getSuccessor() { if(hasChildren()){ if(getLeft() == null && getRight() != null) return getRight(); else if(getLeft() != null && getRight() == null) return getLeft(); else // the two children case return getRight().getLeftmostNode(); } return null; }
d14aae7b-adb8-4b5e-a898-fb1c97f0daf9
3
private void list() { if (connections.isEmpty()) { UI.setError("No hay conexiones activas"); } else { UI.clearError(); Connection connection; int i; UI.printHeader(); System.out.println(connections.size() + " conexiones activas:"); System.out.println(""); for (i = 0; i < connections.size(); i++) { connection = connections.get(i); System.out.println((i + 1) + ") Alias: " + connection.getAlias()); } System.out.println(""); System.out.println("Pulsa intro para volver... "); BufferedReader buffer = new BufferedReader(new InputStreamReader( System.in)); try { buffer.readLine(); } catch (IOException e) { e.printStackTrace(); } } }
dd135d21-a7c7-4018-a663-2691f974ca85
6
public boolean CheckForCollisionCustom(String name, int posX, int posY, int width, int height) { /* NOTES: * * - A string value matching [""] will mean that there * will be no name checking for the collision. * * */ //Creating the variables boolean checkBoolean = false; boolean checkName = false; Rectangle checkRectangle = new Rectangle(posY, posX, width, height); //Determining whether to check by name if (name != "") { checkName = true; } //Doing the collision checks for (int num = 0; num < game.AL_GameObjects.size(); num++) { //With Name Check if (checkName == true && game.AL_GameObjects.get(num).CheckForCollisionByRectangle(checkRectangle) == true && game.AL_GameObjects.get(num).stringName == name) { //Setting the check boolean to 'true' checkBoolean = true; } //Without Name Check else if (game.AL_GameObjects.get(num).CheckForCollisionByRectangle(checkRectangle) == true) { //Setting the check boolean to 'true' checkBoolean = true; } } //Returning the collision booleans return checkBoolean; }
6f402c3c-0ed8-4948-ad9c-fa235067122f
5
public void processHost(int userLevel, String channel, String sender, String hostname, String message, boolean autoRestart, int port) { logMessage(LOGLEVEL_NORMAL, "Processing the host command for " + Functions.getUserName(hostname) + " with the message \"" + message + "\"."); if (botEnabled || isAccountTypeOf(userLevel, ADMIN, MODERATOR)) { if (isAccountTypeOf(userLevel, REGISTERED)) { int slots = MySQL.getMaxSlots(hostname); int userServers; if (getUserServers(Functions.getUserName(hostname)) == null) userServers = 0; else userServers = getUserServers(Functions.getUserName(hostname)).size(); if (slots > userServers) Server.handleHostCommand(this, servers, channel, sender, hostname, message, userLevel, autoRestart, port); else sendMessage(cfg_data.irc_channel, "You have reached your server limit (" + slots + ")"); } else sendMessage(cfg_data.irc_channel, "You must register with BestEver and be logged in to IRC to use the bot to host!"); } else sendMessage(cfg_data.irc_channel, "The bot is currently disabled from hosting for the time being. Sorry for any inconvenience!"); }
267356e8-a9eb-461b-9a9b-871986c3fc9a
7
public void serial(List<Matchable> patterns) { boolean[] flags = new boolean[patterns.size()]; for (int i=0; i<flags.length; i++) flags[i] = false; boolean terminate = false; while (!terminate) { Map<String, String> map = new HashMap<String, String>(); int index = -1; String msg = "Generate object:\n"; Iterator<Matchable> it = patterns.iterator(); while (it.hasNext()) { index++; Matchable pattern = it.next(); String field = pattern.getTitle(); if (pattern.getSize() == 0) { flags = new boolean[0]; break; } else { if (!pattern.hasNext()) { pattern.reset(); flags[index] = true; } map.put(field, pattern.next()); } msg += "\t" + field + ":" + map.get(field) + "\n"; } terminate = true; for (int j=0; j<flags.length; j++) terminate &= flags[j]; if (flags.length > 0) { System.out.println(msg); this.out.write(map); } } }
03fccc11-61cb-4bf7-a80a-4279a2a987d9
1
public boolean isPressed() { if(isDisabled()) return false; return pressed; }
78a3ec72-7f4f-482d-ba79-fd53954d53fb
9
@Override public void run() { boolean connected = false; do { connected = connect(); if( connected ) { log.info("Connected to server "+ serverConnection); } else { log.info("Can't find server "+ serverConnection +" ... trying to reconnect"); Util.pause(1); } } while( !connected ); ServerSocket socket = null; Socket connection = null; DataInputStream in = null; try { socket = new ServerSocket(Util.PORT_DATA_CLIENT); log.finer("Listening on "+ socket.getLocalPort() +" for data updates"); connection = socket.accept(); log.finest("socket accepted"); in = new DataInputStream(connection.getInputStream()); log.finest("inputStream acquired"); } catch(IOException e) { // e.printStackTrace(); // silent fail, will try to reconnect in loop anyway } while( ! viewer.isQuit() ) { try { BufferedImage img = Util.readImage(in); viewer.updateImage(img); if( !viewer.isVisible() && !viewer.isQuit() ) { viewer.setVisible(true); } } catch (IOException e) { // e.printStackTrace(); log.info("Server down, trying to reconnect ... "); try { socket.close(); connect(); socket = new ServerSocket(Util.PORT_DATA_CLIENT); connection = socket.accept(); in = new DataInputStream(connection.getInputStream()); log.info("success"); } catch(IOException ee) { // ee.printStackTrace(); log.info("fail"); } Util.pause(1); } } try { connection.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } }
3c9baa51-7505-4bda-84b1-9b0e87c2b507
5
protected void moveLabel(MouseEvent e) { mxGraph graph = graphComponent.getGraph(); mxGeometry geometry = graph.getModel().getGeometry(state.getCell()); if (geometry != null) { double scale = graph.getView().getScale(); mxPoint pt = new mxPoint(e.getPoint()); if (gridEnabledEvent) { pt = graphComponent.snapScaledPoint(pt); } double dx = (pt.getX() - first.x) / scale; double dy = (pt.getY() - first.y) / scale; if (constrainedEvent) { if (Math.abs(dx) > Math.abs(dy)) { dy = 0; } else { dx = 0; } } mxPoint offset = geometry.getOffset(); if (offset == null) { offset = new mxPoint(); } dx += offset.getX(); dy += offset.getY(); geometry = (mxGeometry) geometry.clone(); geometry.setOffset(new mxPoint(Math.round(dx), Math.round(dy))); graph.getModel().setGeometry(state.getCell(), geometry); } }
1c141b86-660e-4d33-a92f-5c6eb964e0c6
1
public int checkTileForWater(int i) { if (isWater(players.get(i).getPosition()) == true) { // check for water System.out.println("Water tile detected"); Position startPos = players.get(i).getTrail().get(0); players.get(i).ResetTrail(); players.get(i).setPosition(startPos); System.out .println("You've ran out of land! Return to starting position (Refresh)"); GenerateHTMLFile(players.get(i)); } int ret = players.get(i).getTrail().size(); return ret; }
af5246b9-12fb-443b-bfeb-cf4a00eeb3cc
8
public void postOrder() { try { if (!customerExisting) { customerFacade.create(customer); customerFacade.flush(); } Random random = new Random(); int i = random.nextInt(999999999); Date date = new Date(); customerOrder = new CustomerOrder(); customerOrder.setAmount(BigDecimal.valueOf(cartTotal)); customerOrder.setConfirmationNumber(i); customerOrder.setCustomerId(customer); customerOrder.setDateCreated(new Timestamp(date.getTime())); customerOrderFacade.create(customerOrder); customerOrderFacade.flush(); List<OrderedProduct> orderedProductCollection = new ArrayList(); for (OrderedProduct orderedProduct : customerCart) { if (orderedProduct.getQty() > 0 || orderedProduct.getCheeseQty() > 0 || orderedProduct.getEggQty() > 0 || orderedProduct.getEggCheeseQty() > 0) { int productId = orderedProduct.getProduct().getId(); OrderedProductPK orderedProductPK = new OrderedProductPK(); orderedProductPK.setCustomerOrderId(customerOrder.getId()); orderedProductPK.setProductId(productId); OrderedProduct orderedItem = new OrderedProduct(orderedProductPK); orderedItem.setQty((short) orderedProduct.getQty()); orderedItem.setCheeseQty((short) orderedProduct.getCheeseQty()); orderedItem.setEggQty((short) orderedProduct.getEggQty()); orderedItem.setEggCheeseQty((short) orderedProduct.getEggCheeseQty()); orderedItem.setProduct(orderedProduct.getProduct()); orderedItem.setCustomerOrder(customerOrder); orderedProductFacade.create(orderedItem); orderedProductCollection.add(orderedItem); } } orderedProductFacade.flush(); if (!orderedProductCollection.isEmpty()) { customerOrder.setOrderedProductCollection(orderedProductCollection); customerOrderFacade.edit(customerOrder); customerOrderFacade.flush(); } } catch (Exception e) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "FrontBean error", "postOrder() method: " + e.getMessage()); FacesContext.getCurrentInstance().addMessage(null, message); } }
d1f3dfaf-2608-4bcb-9481-f1dad5c9e047
2
public boolean requestFriendship(Person otherPerson) { if (this.friends.contains(otherPerson)){ return true; } if(this.sendMessage(otherPerson, "/friend")){ this.friends.add(otherPerson); return true; } return false; }
44f2dd40-0ad5-43bd-b9e3-29593bd88d50
1
private void mergeFinallyBlock(FlowBlock tryFlow, FlowBlock catchFlow, StructuredBlock finallyBlock) { TryBlock tryBlock = (TryBlock) tryFlow.block; if (tryBlock.getSubBlocks()[0] instanceof TryBlock) { /* * A try { try { } catch {} } finally{} is equivalent to a try {} * catch {} finally {} so remove the surrounding tryBlock. */ TryBlock innerTry = (TryBlock) tryBlock.getSubBlocks()[0]; innerTry.gen = tryBlock.gen; innerTry.replace(tryBlock); tryBlock = innerTry; tryFlow.lastModified = tryBlock; tryFlow.block = tryBlock; } /* Now merge try and catch flow blocks */ mergeTryCatch(tryFlow, catchFlow); FinallyBlock newBlock = new FinallyBlock(); newBlock.setCatchBlock(finallyBlock); tryBlock.addCatchBlock(newBlock); }
1dc0f425-bdc1-48f6-81ee-fb35fccc645d
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(MessageGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MessageGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MessageGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MessageGUI.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 MessageGUI().setVisible(true); } }); }
ad5b9760-bb7b-4547-9b8e-e0cdd6250f39
2
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed String tmpcod = JOptionPane.showInputDialog(this, "Introdusca su codigo", "Captura de codigo", JOptionPane.QUESTION_MESSAGE); Usuarios us = new Usuarios(tmpcod, null, null); UsuariosCRUD userc = new UsuariosCRUD(MyConnection.getConnection()); PrestamosCRUD p = new PrestamosCRUD(MyConnection.getConnection()); ArrayList<Usuarios> users = userc.isValid(us); if(users.isEmpty()){ JOptionPane.showMessageDialog(this, "No se encontro el usuario"); }else{ MenuPrincipalViews.user = users.get(0); MenuPrincipalViews.prestamos = p.getNumeroDePrestamos(MenuPrincipalViews.user); if(MenuPrincipalViews.prestamos>1){ jMenuItem6.setEnabled(false); } jlUser.setText("Usuario: "+this.user.getNombre()); this.jMenu2.setEnabled(true); this.jMenuItem1.setEnabled(false); } }//GEN-LAST:event_jMenuItem1ActionPerformed
d5052066-66bb-4af4-bc8d-12645557663a
8
public void update(){ if(!won && !dead){ if(hasStarted){ elapsedMS = (System.nanoTime() - startTime) / 1000000; formattedTime = formatTime(elapsedMS); } else{ startTime = System.nanoTime(); } } checkKeys(); if(score >= highScore){ highScore = score; } for(int row = 0; row < ROWS; row++){ for(int col = 0; col < COLS; col++){ Tile current = board[row][col]; if(current == null) continue; current.update(); resetPosition(current, row, col); if(current.getValue() == 2048){ won = true; } } } }
f7534b7b-6a24-48e7-9b2c-cd985641336b
0
public Ability(String name, String trigger) { this.name = name; this.trigger = trigger; }
c038c67b-b84e-48cb-a508-3cc730ca5009
1
public boolean canHaveAsCreditLimit(BigInteger creditLimit) { return (creditLimit != null) && (creditLimit.compareTo(BigInteger.ZERO) <= 0); }
b06f9284-77cc-4fac-8b59-37afcc011492
6
public static int maxProfit(int[] prices) { if(prices.length <= 1) { return 0; } int max = prices[0]; int min = prices[0]; int maxPofit = 0; for(int i = 0; i < prices.length; i++) { if(prices[i] < min) { int tmp = max-min; if(tmp > maxPofit) { maxPofit = tmp; } min = prices[i]; max = prices[i]; } if(prices[i] > max) { max = prices[i]; int tmp = max-min; if(tmp > maxPofit) { maxPofit = tmp; } } } return maxPofit; }
8f2a5221-206f-4465-af06-37ad171a2b4f
9
@Override protected void onWriteContent(XMLStreamWriter toStream, PropertySet toObject, XMLFormatType toFormatType) { if (toObject == null || toObject.isEmpty()) { return; } Object[] loKeys = toObject.getPropertyKeys().toArray(); Arrays.sort(loKeys); for (int i = 0; i < loKeys.length; i++) { String loKey = (String)loKeys[i]; java.lang.Object loValue = toObject.getProperty(loKey); if (loValue != null) { try { toStream.writeStartElement("Item"); toStream.writeStartElement("Property"); if (Goliath.DynamicCode.Java.isPrimitive(loKey) && toFormatType == XMLFormatType.TYPED()) { toStream.writeAttribute("type", loKey.getClass().getName()); } XMLFormatter.appendToXMLStream(loKey, toFormatType, toStream, null); toStream.writeEndElement(); toStream.writeStartElement("Value"); if (Goliath.DynamicCode.Java.isPrimitive(loValue) && toFormatType == XMLFormatType.TYPED()) { toStream.writeAttribute("type", loValue.getClass().getName()); } XMLFormatter.appendToXMLStream(loValue, toFormatType, toStream, null); toStream.writeEndElement(); toStream.writeEndElement(); } catch(Throwable ex) {} } } }
c5b2c212-6848-4ef1-8000-e0e3d828db00
4
@Override public boolean equals(Object o) { boolean isEqual = false; if(o != null && o instanceof User) { User temp = (User) o; if(temp.username.equals(this.username) && Arrays.equals(temp.password, this.password)) { isEqual = true; } } return isEqual; }
7784ed59-d2f5-4e29-bc34-ebc4eab2a1a6
9
private boolean duplicated(int a, int b, int max) { int maxLoop = (int) (Math.sqrt(a) + 1); for (int i = 2; i < maxLoop; i++) { if (a % i != 0) { continue; } int root = logn(i, a); if (root == -1) { continue; } int bPlus = b * root; if (bPlus <= max) { return true; } else { for (int j = (int) Math.sqrt(bPlus); j >= 2; j--) { if (bPlus % j != 0) { continue; } if (j == root) { continue; } if (bPlus / j > max) { return false; } if (Math.pow(i, j) <= a) { return true; } } return false; } } return false; }
5aab88bf-c7eb-458c-ae8f-02ec9c0818dc
1
public static void stub(String string){ if(developerMode){ System.out.println("STUB: " + getClassName() + ":" + getMethodName() + "():" + getLineNumber() + ": " + string); } }
80239c5c-836e-4ed9-8fbe-d046b8414431
7
private String startToneHunt (CircularDataBuffer circBuf,WaveData waveData) { String line; final int HighTONE=1280; final int LowTONE=520; final int toneDIFFERENCE=HighTONE-LowTONE; final int ErrorALLOWANCE=40; // Look for a low start tone followed by a high start tone int tone1=do1024FFT(circBuf,waveData,0); int tone2=do1024FFT(circBuf,waveData,(int)samplesPerSymbol*1); // Check tone1 is the same as tone2 if (tone1!=tone2) return null; int tone3=do1024FFT(circBuf,waveData,(int)samplesPerSymbol*2); // Check the first tone is lower than the second tone if (tone1>tone3) return null; int tone4=do1024FFT(circBuf,waveData,(int)samplesPerSymbol*3); // Check tone1 and 2 are the same and that tones 3 and 4 are the same also if ((tone1!=tone2)||(tone3!=tone4)) return null; // Check tones2 and 3 aren't the same if (tone2==tone3) return null; // Find the frequency difference between the tones int difference=tone3-tone1; // Check the difference is correct if ((difference<(toneDIFFERENCE-ErrorALLOWANCE)||(difference>(toneDIFFERENCE+ErrorALLOWANCE)))) return null; // Tones found // Calculate the long error correction factor correctionFactor=LowTONE-tone1; // Tell the user line=theApp.getTimeStamp()+" XPA Start Tones Found (correcting by "+Integer.toString(correctionFactor)+" Hz)"; return line; }
1daa3782-b20d-4cd0-a8ce-2b73f70c7177
9
public boolean canHaveAsWall(Wall newW) { for(Element e: elements) { if(e instanceof Player) { for(Position p : newW.getPositions()) { if(e.getPosition().equals(p)) { return false; } } } else if(e instanceof Wall) { Wall w = (Wall) e; //if(w.getDirection().equals(Direction.HORIZONTAL)){ for(Position newWp : newW.getPositions()){ for(Position wp : w.getPositions()){ if( Math.abs(newWp.getxCoordinate() - wp.getxCoordinate()) < 2 && Math.abs(newWp.getyCoordinate() - wp.getyCoordinate()) < 2){ return false; } } } //} } } return true; }
898b3399-9ffc-4056-8536-c63a67543f85
0
@After public void tearDown() throws Exception { this.service = null; }
9fc698d7-9bf8-4c65-a82f-6a27d9aae67c
2
private void paintPauseScreen(Graphics2D g){ g.setFont(pauseFont); if (fm == null){ initClickAreas(); } if (inOptions) drawOptions(g); else drawPauseScreen(g); }
f2306b1e-0222-46c9-b0c6-fb6234387896
4
private int jjMoveStringLiteralDfa3_4(long old0, long active0) { if (((active0 &= old0)) == 0L) return 3; try { curChar = input_stream.readChar(); } catch (java.io.IOException e) { return 3; } switch (curChar) { case 93: if ((active0 & 0x100000L) != 0L) return jjStopAtPos(3, 20); break; default: return 4; } return 4; }
253a9350-cc2e-4aee-aaf5-eac1ada776df
0
public Tile[] getNeighbors() { return neighbors; }
7f296e9f-f225-4a7b-837f-610b707c4dc4
1
public static int compare(String s1,String s2) { if (collator==null) collator = java.text.Collator.getInstance(); return collator.compare(s1,s2); };
e0df7814-64d1-4342-978a-6ef04a8c17d7
8
public boolean equals(Object other) { if (other instanceof Tuple) { Tuple otherTuple = (Tuple) other; return (( this.first == otherTuple.first || ( this.first != null && otherTuple.first != null && this.first.equals(otherTuple.first))) && ( this.second == otherTuple.second || ( this.second != null && otherTuple.second != null && this.second.equals(otherTuple.second))) ); } return false; }
224c7cbb-3ac5-4f4e-87ab-bd84a1a2be89
0
public int getZoomLevel() { return zoomLevel; }
ff59aa3d-6b2a-4ec8-bd3c-f2b5c88059e2
7
private void initialize() { PSOUtil.reset(); Particle bestPreviousIndividual = this.initialIndividual!=null ? new Particle(this.initialIndividual.getPersonWorkLists()) : null; Particle initialParticle = null; if (bestPreviousIndividual != null) { initialParticle = (Particle) bestPreviousIndividual.clone(); } else { initialParticle = new Particle(); } //magic number! int subProjectActivities = 15; velBounds = new double[dimension]; for (int d = 0; d < dimension; d++) { velBounds[d] = (probabilityMax-probabilityMin)*velBoundsPercentage; } rand = new Random(); particles = new Particle[swarmParticleCount]; for (int i = 0; i < swarmParticleCount; i++) { particles[i] = (Particle) initialParticle.clone(); //shuffle all particles (make initial population) PSOUtil.shuffleSubArray( particles[i].getProjectWorkUnitIndexes(), subProjectActivities, rand ); if (i == 0) { particles[i] = bestPreviousIndividual!= null ? bestPreviousIndividual : particles[i]; } //evaluate swarm particles[i].evaluate(); //set this value as best particles[i].setBestProjectDuration( particles[i].getActualDuration() ); } //neighborhood: LOCAL OR GLOBAL NEIGHBORHOOD if (globalNeighborhoodSet) { neighborhood = new GlobalNeighborhood(dimension); } else { neighborhood = new LocalNeighborhood(swarmParticleCount, dimension, neighborhoodSize); } haveBest = false; best = (Particle) initialParticle.clone(); }
d384a93a-551e-458f-adac-25238e7c2b73
8
public static final int[] adjustXYByDirections(int x, int y, final int direction) { switch(direction) { case Directions.NORTH: y--; break; case Directions.SOUTH: y++; break; case Directions.EAST: x++; break; case Directions.WEST: x--; break; case Directions.NORTHEAST: x++; y--; break; case Directions.NORTHWEST: x--; y--; break; case Directions.SOUTHEAST: x++; y++; break; case Directions.SOUTHWEST: x--; y++; break; } final int[] xy=new int[2]; xy[0]=x; xy[1]=y; return xy; }
89c326ab-b1fe-4ed5-95fd-d89f90c2d99d
9
@Override public float[] getWordEntropies(int[] iids) { // check to make sure that nodes exist for every id for(int i = 0; i < iids.length; i++) if(root.getChild(iids[i]) == null) iids[i] = this.findUnknownId(vocab.getSymbol(iids[i])); wordEnts = new float[iids.length-1]; simpleEnts = new float[iids.length-1]; classEnts = new float[iids.length-1]; // convert to classes int[] mids; if(classMap != null) { mids = new int[iids.length]; mids[0] = classMap.getWordClass(iids[0]); for(int i = 0; i < wordEnts.length; i++) { int idx = iids[i+1]; classEnts[i] = classMap.getWordProb(idx); wordEnts[i] += classEnts[i]; mids[i+1] = classMap.getWordClass(idx); } } else mids = iids; int idx; sentHits++; // start with the terminal symbol as the context NgramNode context = root.getChild(0), child; int lev = 2; for(int i = 0; i < wordEnts.length; i++) { idx = mids[i+1]; // first, fall back to a node that has children while(!context.hasChildren()) { lev--; context = context.getFallback(); } // then, fall back to a node that actually can predict the word while((child = context.getChild(idx)) == null) { // add the fallback penalty lev--; simpleEnts[i] += context.getBackoffScore(); context = context.getFallback(); if(context == null) throw new IllegalArgumentException("Could not find word in unigram vocabulary."); } // add the level that we got a hit at // System.out.println(isInVocab(idx)?lev:0); hits[isInVocab(idx)?lev:0]++; lev++; // add the score simpleEnts[i] += child.score; wordEnts[i] += simpleEnts[i]; context = child; } return wordEnts; }
8b032ed8-372e-418a-9d52-e5bc610a7fd1
8
public void continueGame(){ while(continueHit && player.getHandTotal() < 21){ playerPlay(); if(continueHit) player.printHand(); } System.out.println("--- Dealer's turn ---"); while(continueDealerHit && dealer.getHandTotal() < 21){ dealerPlay(); } dealer.printHand(); System.out.println("Dealer's total was "+ dealer.getHandTotal()); //figure out the winner, and display to user int winner = findWinner(); String winMessage; switch(winner){ case 0: winMessage = "It was a tie"; break; case 1: winMessage = "You won"; break; case 2: winMessage = "Dealer won"; break; default: winMessage = "Invalid Winner"; break; } System.out.println(winMessage); }
20ced934-b73c-40b0-bdc0-c54785756858
3
private void carregaBairrosAssesoria(String idCidade){ if(comboCidadeAssessoria.getSelectedItem().toString().equals("Selecionar....")){ System.out.println("Nenhuma cidade selecionada"); }else{ System.out.println("Carregando bairros..."); //String cod = String.valueOf(comboCidadeAssessoria.getSelectedIndex()); comboModelBairroAssesoria = (DefaultComboBoxModel) comboBairroAssessoria.getModel(); comboModelBairroAssesoria.removeAllElements(); ArrayList<Bairro> bairros = new ArrayList<>(); DaoBairro daoBairro = new DaoBairro(); bairros = daoBairro.consultar(idCidade); comboModelBairroAssesoria.addElement("Selecionar...."); if (bairros.isEmpty()) { JOptionPane.showMessageDialog(null, "ESSA CIDADE NÃO TEM BAIRROS CADASTRADOS!"); }else{ System.out.println("Carregando bairros..."); //percorrendo a lista para inserir os valores no combo for (int linha = 0; linha < bairros.size(); linha++){ //pegando a categoria da lista Bairro bairro = bairros.get(linha); //adicionando a categoria no combo System.out.println("Bairros: "+bairro.getNome()); comboModelBairroAssesoria.addElement(bairro.getNome()); } } } }
136ffea8-1f53-4721-989b-3f2ede1f9f1b
2
public void testAddDurationConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().addDurationConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); }
416d7713-89b2-412b-bb48-365967ef7ef8
9
private void readTokenFromScanner(){ int length = tokenCache.length; boolean tokenNotFound = true; while(tokenNotFound) { try { int tokenKind = scanner.getNextToken(); if(tokenKind != TokenNameEOF) { int start = scanner.getCurrentTokenStartPosition(); int end = scanner.getCurrentTokenEndPosition(); int nextInterval = currentInterval + 1; if(intervalStartToSkip.length == 0 || nextInterval >= intervalStartToSkip.length || start < intervalStartToSkip[nextInterval]) { Token token = new Token(); token.kind = tokenKind; token.name = scanner.getCurrentTokenSource(); token.start = start; token.end = end; token.line = Util.getLineNumber(end, scanner.lineEnds, 0, scanner.linePtr); if(currentInterval != previousInterval && (intervalFlagsToSkip[currentInterval] & RangeUtil.IGNORE) == 0){ token.flags = IS_AFTER_JUMP; if((intervalFlagsToSkip[currentInterval] & RangeUtil.LBRACE_MISSING) != 0){ token.flags |= LBRACE_MISSING; } } previousInterval = currentInterval; tokenCache[++tokenCacheIndex % length] = token; tokenNotFound = false; } else { scanner.resetTo(intervalEndToSkip[++currentInterval] + 1, scanner.eofPosition - 1); } } else { int start = scanner.getCurrentTokenStartPosition(); int end = scanner.getCurrentTokenEndPosition(); Token token = new Token(); token.kind = tokenKind; token.name = CharOperation.NO_CHAR; token.start = start; token.end = end; token.line = Util.getLineNumber(end, scanner.lineEnds, 0, scanner.linePtr); tokenCache[++tokenCacheIndex % length] = token; tokenCacheEOFIndex = tokenCacheIndex; tokenNotFound = false; } } catch (InvalidInputException e) { // return next token } } }
7c7dae88-c77a-435f-ac1a-c6942fe28f2a
1
private void hook() { Thread ct = Thread.currentThread(); if(!(ct instanceof HackThread)) throw(new RuntimeException("Tried to use an HackSocket on a non-hacked thread.")); final HackThread ut = (HackThread)ct; InterruptAction ia = new InterruptAction(); ut.addil(ia); this.ia.set(ia); }
a0dffa18-7c20-4a02-a310-d99ed7d4d366
4
private void menuAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuAbrirActionPerformed // TODO add your handling code here: FileFilter f = new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.getAbsolutePath().endsWith(".csv") || pathname.isDirectory()) { return true; } return false; } @Override public String getDescription() { String msg = "Archivos CSV"; return msg; } }; fileChooser.setFileFilter(f); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fileChooser.showOpenDialog(this); File archivo = fileChooser.getSelectedFile(); String path = archivo.getAbsolutePath(); try { boolean exito = controlador.cargarDesdeCSV(path); if (exito) { mostrarMensajeExito("Se ha cargado con éxito el archivo " + path); } else { mostrarMensajeError("No se ha podido cargar el archivo " + path); } } catch (IOException ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); mostrarMensajeError("No se ha podido cargar el archivo " + path); } }//GEN-LAST:event_menuAbrirActionPerformed
c0b68cb8-f552-41c5-9d6b-bec8cd02d8d5
1
public void setAnnualBonus(double annualBonus) { if (annualBonus < 0){ throw new IllegalArgumentException("Bonus must be greater than or equal to zero"); } this.annualBonus = annualBonus; }
044272ed-6d68-4d66-b6ee-8e284585bca0
8
private void handleResponsePacket(DatagramPacket packet) { try { String strPacket = new String(packet.getData(), 0, packet.getLength()); Log.d(LOG_TAG, "response=" + strPacket); String tokens[] = strPacket.trim().split("\\n"); Log.d(LOG_TAG, "tokens.length=" + tokens.length); String location = null; boolean foundSt = false; for (int i = 0; i < tokens.length; i++) { String token = tokens[i].trim(); if (token.startsWith(HEADER_LOCATION)) { // LOCATION: http://192.168.0.51:47944/dd.xml location = token.substring(10).trim(); } else if (token.startsWith(HEADER_ST)) { // ST: urn:dial-multiscreen-org:service:dial:1 String st = token.substring(4).trim(); if (st.equals(SEARCH_TARGET)) { foundSt = true; } } } if (!foundSt || location == null) { Log.w(LOG_TAG, "Malformed response: " + strPacket); return; } BroadcastAdvertisement advert; try { URL uri = new URL(location); InetAddress address = InetAddress.getByName(uri.getHost()); advert = new BroadcastAdvertisement(location, address, uri.getPort()); } catch (Exception e) { return; } mHandler.onBroadcastFound(advert); } catch (Exception e) { Log.e(LOG_TAG, "handleResponsePacket", e); } }
dbd464ae-5de3-463e-88f2-eb0a5a99a63d
1
public void testWithField3() { Partial test = createHourMinPartial(); try { test.withField(DateTimeFieldType.dayOfMonth(), 6); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20); }
cf6aab21-5294-4c5c-b5d6-612e7a1ee964
6
public void run() { try { ObjectOutputStream out = new ObjectOutputStream(server.getOutputStream()); ObjectInputStream in = new ObjectInputStream(server.getInputStream()); // --Mutil User but can't parallel String [] arr= (String[]) in.readObject(); System.out.println(arr[0]+arr[1]); switch (arr[0]) { case "write": System.out.println("Write command."); write(arr[1], arr[2]); break; case "read": System.out.println("Read command."); String data = read(arr[1]); //ӱضȡļ String[] s =new String[]{data}; out.writeObject(s); // out.flush(); break; case "delete": System.out.println("Read command."); String[] s1 = null; if(true == delete(arr[1])){ //ӱضȡļ s1 =new String[]{"Delete done."}; } else { s1 =new String[]{"Filename dose not exits."}; } out.writeObject(s1); // out.flush(); break; default: System.out.println("Wrong command."); break; } out.close(); in.close(); server.close(); } catch (IOException ex) { ex.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
7a7fd7e4-d45f-4ae5-ba45-2a7bc10fd8cb
9
private void send(OutputStream outputStream) { String mime = mimeType; SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US); gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT")); try { if (status == null) { throw new Error("sendResponse(): Status can't be null."); } PrintWriter pw = new PrintWriter(outputStream); pw.print("HTTP/1.1 " + status.getDescription() + " \r\n"); if (mime != null) { pw.print("Content-Type: " + mime + "\r\n"); } if (header == null || header.get("Date") == null) { pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n"); } if (header != null) { for (String key : header.keySet()) { String value = header.get(key); pw.print(key + ": " + value + "\r\n"); } } pw.print("Connection: keep-alive\r\n"); if (requestMethod != Method.HEAD && chunkedTransfer) { sendAsChunked(outputStream, pw); } else { sendAsFixedLength(outputStream, pw); } outputStream.flush(); safeClose(data); } catch (IOException ioe) { // Couldn't write? No can do. } }
426e8f1e-0b45-4bb2-93cc-427c01cf7260
4
void readAssignmentList(CommandSender sender, ResultSet resSet, String queriedPlayer) { String aState = ""; boolean assignmentFound = false; try { sender.sendMessage("Auftragsliste von: " + ChatColor.GREEN + queriedPlayer); sender.sendMessage("---------------------------------------------------"); while(resSet.next()) { assignmentFound = true; if(resSet.getString("state").equalsIgnoreCase("active")) { aState = ChatColor.GREEN + "offen"; } else { aState = ChatColor.YELLOW + "abholbar"; } sender.sendMessage("Nr " + ChatColor.GREEN + resSet.getRow() + ChatColor.WHITE + " am Standort: " + resSet.getString("x") + ", " + resSet.getString("y") + ", " + resSet.getString("z") + " in " + resSet.getString("world") + " ist " + aState); } if(!assignmentFound) { sender.sendMessage(ChatColor.YELLOW + "Keine Auftraege gefunden."); } sender.sendMessage("---------------------------------------------------"); } catch (Exception ex) { // nothing to do. } }
46c72251-22e3-4ed8-b49e-11abb5e66efe
2
public static void testArray() { Array<Comparable<?>> myArray = new Array<Comparable<?>>(0); // System.out.println("Set " + obj0 + " to " + 0); // myArray.setElement(0, obj0); // System.out.println(myArray); // System.out.println("Last position: " + myArray.getLastPosition()); // // System.out.println("Set " + obj1 + " to " + 1); // myArray.setElement(1, obj1); // System.out.println(myArray); // System.out.println("Last position: " + myArray.getLastPosition()); // // System.out.println("Set " + obj2 + " to " + 4); // myArray.setElement(4, obj2); // System.out.println(myArray); // System.out.println("Last position: " + myArray.getLastPosition()); // // System.out.println("Set " + obj2 + " to " + 3); // myArray.setElement(3, obj2); // System.out.println(myArray); // System.out.println("Last position: " + myArray.getLastPosition()); // // System.out.println("Set " + null + " to " + 4); // myArray.setElement(4, null); // System.out.println(myArray); // System.out.println("Last position: " + myArray.getLastPosition()); // // System.out.println("Remove at 3"); // myArray.removeAt(3); // System.out.println(myArray); // System.out.println("Last position: " + myArray.getLastPosition()); System.out.println("Append 10, 6 and " + obj7); myArray.append(10); myArray.append(6); myArray.append(obj7); System.out.println(myArray); System.out.println("Last position: " + myArray.getLastPosition()); System.out.println("Array size: " + myArray.getSize()); }
e4e17c89-1fcc-4cee-8ec5-f5b478eacf48
7
public static Keyword scanCachedGoals(ControlFrame frame) { { Proposition proposition = frame.proposition; Iterator iterator = ((Iterator)(KeyValueList.dynamicSlotValue(frame.dynamicSlots, Logic.SYM_STELLA_ITERATOR, null))); AtomicGoalCache cachedgoal = null; PatternRecord patternrecord = ((QueryIterator)(Logic.$QUERYITERATOR$.get())).currentPatternRecord; int ubstackoffset = patternrecord.topUnbindingStackOffset; if (!((BooleanWrapper)(KeyValueList.dynamicSlotValue(Logic.surrogateToDescription(((Surrogate)(proposition.operator))).dynamicSlots, Logic.SYM_LOGIC_CHECK_FOR_CACHED_GOALSp, Stella.FALSE_WRAPPER))).wrapperValue) { return (Logic.KWD_FAILURE); } if (iterator == null) { iterator = ((Iterator)(KeyValueList.setDynamicSlotValue(frame.dynamicSlots, Logic.SYM_STELLA_ITERATOR, ControlFrame.allCachedPropositions(frame), null))); } while (iterator.nextP()) { cachedgoal = ((AtomicGoalCache)(iterator.value)); { boolean alwaysP000 = true; { Stella_Object arg = null; Vector vector000 = proposition.arguments; int index000 = 0; int length000 = vector000.length(); Stella_Object cachedbinding = null; Cons iter000 = cachedgoal.bindings; loop001 : for (;(index000 < length000) && (!(iter000 == Stella.NIL)); index000 = index000 + 1, iter000 = iter000.rest) { arg = (vector000.theArray)[index000]; cachedbinding = iter000.value; if (!Logic.bindArgumentToValueP(arg, cachedbinding, true)) { alwaysP000 = false; break loop001; } } } if (alwaysP000) { return (AtomicGoalCache.finishCachedGoalProcessing(cachedgoal, frame, Logic.KWD_SUCCESS, true)); } } PatternRecord.unbindVariablesBeginningAt(patternrecord, ubstackoffset + 1); } return (Logic.KWD_FAILURE); } }
670811e2-0e84-4ba7-8c5e-282fc50b7307
7
private void initPWResetFontMenu(Color bg) { this.pwResetBtnPanel = new JPanel(); this.pwResetBtnPanel.setBackground(bg); this.pwResetBtnPanel.setLayout(new VerticalLayout(5, VerticalLayout.LEFT)); String initFontTmp = this.skin.getPWResetFont(); int initFontSizeTmp = this.skin.getPWResetFontsize(); Color initFontColorTmp = new Color(this.skin.getPWResetFontcolor()[1], this.skin.getPWResetFontcolor()[2], this.skin.getPWResetFontcolor()[3]); boolean boldTmp = this.skin.getPWResetFonttype() == Fonttype.BOLD; boolean underlineTmp = (this.skin.getPWResetFontstyle() == Fontstyle.UNDERLINE) || (this.skin.getPWResetFontstyle() == Fontstyle.SHADOWUNDERLINE); boolean shadowTmp = (this.skin.getPWResetFontstyle() == Fontstyle.SHADOW) || (this.skin.getPWResetFontstyle() == Fontstyle.SHADOWUNDERLINE); this.pwResetFontfield = new FontField(bg, strFontFieldTitle, initFontTmp, initFontSizeTmp, initFontColorTmp, boldTmp, underlineTmp, shadowTmp) { private final long serialVersionUID = 1L; @Override public void fontChosen(String input) { if (!input.equals("")) { FontChangesMenu.this.skin.setPWResetFont(input); updateFont(FontChangesMenu.this.skin.getPWResetFont()); } else { FontChangesMenu.this.skin.setPWResetFont(null); } } @Override public void sizeTyped(String input) { if (input != null) { FontChangesMenu.this.skin.setPWResetFontsize(parseInt(input)); updateSize(FontChangesMenu.this.skin.getPWResetFontsize()); } else { FontChangesMenu.this.skin.setPWResetFontsize(-1); } } @Override public void colorBtnPressed(int[] argb) { FontChangesMenu.this.skin.setPWResetFontcolor(argb); updateColor(new Color(FontChangesMenu.this.skin.getPWResetFontcolor()[1], FontChangesMenu.this.skin.getPWResetFontcolor()[2], FontChangesMenu.this.skin.getPWResetFontcolor()[3])); } @Override public void boldPressed(boolean selected) { FontChangesMenu.this.skin.setPWResetFonttype(selected ? Fonttype.BOLD : Fonttype.NORMAL); updateBold(FontChangesMenu.this.skin.getPWResetFonttype() == Fonttype.BOLD); } @Override public void underlinePressed(boolean selected) { FontChangesMenu.this.skin.setPWResetFontstyle(getUnderlineFontstyle(selected, FontChangesMenu.this.skin.getPWResetFontstyle())); updateUnderline((FontChangesMenu.this.skin.getPWResetFontstyle() == Fontstyle.UNDERLINE) || (FontChangesMenu.this.skin.getPWResetFontstyle() == Fontstyle.SHADOWUNDERLINE)); } @Override public void shadowPressed(boolean selected) { FontChangesMenu.this.skin .setPWResetFontstyle(getShadowFontstyle(selected, FontChangesMenu.this.skin.getPWResetFontstyle())); updateShadow((FontChangesMenu.this.skin.getPWResetFontstyle() == Fontstyle.SHADOW) || (FontChangesMenu.this.skin.getPWResetFontstyle() == Fontstyle.SHADOWUNDERLINE)); } }; this.pwResetBtnPanel.add(this.pwResetFontfield); }
cab27036-33d0-4027-8a6b-406dc7b349b0
0
public String getRecipient() { return recipient; }
d96e5c41-10d7-4e62-b4e7-2841e7dc83ef
5
private void flee() { if (Utils.getDistance(this, World.getMonsterArray().get(DistList.indexOf(Collections.min(DistList)))) < 50) { if (x < World.getMonsterArray().get(DistList.indexOf(Collections.min(DistList))).getX()) { isLPress = true; } else if (x > World.getMonsterArray().get(DistList.indexOf(Collections.min(DistList))).getX()) { isRPress = true; } if (y > World.getMonsterArray().get(DistList.indexOf(Collections.min(DistList))).getY()) { isDPress = true; } else if (y < World.getMonsterArray().get(DistList.indexOf(Collections.min(DistList))).getY()) { isUPress = true; } } else { stopMoving(); } ; }
89e32167-9a6f-47b7-99b9-bfc709ac1c66
4
private Rectangle getDragOverBounds() { Rectangle bounds = new Rectangle(mDragOverNode.getX(), mDragOverNode.getY(), mDragOverNode.getWidth(), mDragOverNode.getHeight()); switch (mDragOverLocation) { case NORTH: bounds.height = Math.max(bounds.height / 2, 1); break; case SOUTH: int halfHeight = Math.max(bounds.height / 2, 1); bounds.y += bounds.height - halfHeight; bounds.height = halfHeight; break; case EAST: int halfWidth = Math.max(bounds.width / 2, 1); bounds.x += bounds.width - halfWidth; bounds.width = halfWidth; break; case WEST: default: bounds.width = Math.max(bounds.width / 2, 1); break; } return bounds; }
f0c2c56a-c7d9-4503-bd6e-20d5874b1728
5
public void handleKeyPress(int value) { switch (value) { case MinuetoKeyboard.KEY_UP: this.keyUp = true; break; case MinuetoKeyboard.KEY_LEFT: this.keyLeft = true; break; case MinuetoKeyboard.KEY_RIGHT: this.keyRight = true; break; case MinuetoKeyboard.KEY_DOWN: this.keyDown = true; break; case MinuetoKeyboard.KEY_Q: System.exit(-1); break; default: System.out.println(value); } }
23a39b1d-5749-4eca-b999-e7b505f38ae7
9
public void populateEnemies(){ sprinters = new ArrayList<Sprinter>(); waiters = new ArrayList<Waiter>(); pacers = new ArrayList<Pacer>(); walkers = new ArrayList<Walker>(); spitters = new ArrayList<Spitter>(); enemies = new ArrayList<Enemy>(); Sprinter s; Waiter w; Pacer p; Walker wa; Spitter sp; Point[] leftSpitPoints = new Point[]{ new Point(1999, 239), new Point(1999, 271) }; for(int i = 0; i < leftSpitPoints.length; i++){ sp = new Spitter(tileMap, 1, "left"); sp.setPosition(leftSpitPoints[i].x, leftSpitPoints[i].y); spitters.add(sp); enemies.add(sp); } Point[] rightSpitPoints = new Point[]{ new Point(1264, 239), new Point(1264, 271) }; for(int i = 0; i < rightSpitPoints.length; i++){ sp = new Spitter(tileMap, 1, "right"); sp.setPosition(rightSpitPoints[i].x, rightSpitPoints[i].y); spitters.add(sp); enemies.add(sp); } Point[] downSprintPoints = new Point[]{ new Point(784, 432), new Point(656, 432), new Point(528, 432), new Point(400, 432), new Point(208, 560), new Point(176, 48), new Point(304, 48), new Point(432, 48), new Point(560, 48), new Point(688, 48), new Point(816, 48), }; for(int i = 0; i < downSprintPoints.length; i++){ s = new Sprinter(tileMap, 0, "down"); s.setPosition(downSprintPoints[i].x, downSprintPoints[i].y); enemies.add(s); sprinters.add(s); } Point[] UpSprintPoints = new Point[]{ new Point(848, 688), new Point(720, 688), new Point(592, 688), new Point(464, 688), new Point(368, 272), new Point(496, 272), new Point(624, 272), new Point(752, 272), }; for(int i = 0; i < UpSprintPoints.length; i++){ s = new Sprinter(tileMap, 2, "up"); s.setPosition(UpSprintPoints[i].x, UpSprintPoints[i].y); enemies.add(s); sprinters.add(s); } Point[] DownPacePoints = new Point[]{ new Point(2192, 52), new Point(2512, 52), new Point(2800, 52), }; for(int i = 0; i < DownPacePoints.length; i++){ p = new Pacer(tileMap, 2, "down", 3.7); p.setPosition(DownPacePoints[i].x, DownPacePoints[i].y); p.init(DownPacePoints[i].x, DownPacePoints[i].y); pacers.add(p); enemies.add(p); } Point[] UpPacePoints = new Point[]{ new Point(2352, 172), new Point(2672, 172), }; for(int i = 0; i < UpPacePoints.length; i++){ p = new Pacer(tileMap, 2, "up", 3.7); p.setPosition(UpPacePoints[i].x, UpPacePoints[i].y); p.init(UpPacePoints[i].x, UpPacePoints[i].y); pacers.add(p); enemies.add(p); } Point[] RightPacePoints = new Point[]{ new Point(2896, 336), new Point(2896, 592), }; for(int i = 0; i < RightPacePoints.length; i++){ p = new Pacer(tileMap, 1, "right", 3.7); p.setPosition(RightPacePoints[i].x, RightPacePoints[i].y); p.init(RightPacePoints[i].x, RightPacePoints[i].y); pacers.add(p); enemies.add(p); } Point[] LeftPacePoints = new Point[]{ new Point(3024, 464), }; for(int i = 0; i < LeftPacePoints.length; i++){ p = new Pacer(tileMap, 1, "left", 3.7); p.setPosition(LeftPacePoints[i].x, LeftPacePoints[i].y); p.init(LeftPacePoints[i].x, LeftPacePoints[i].y); pacers.add(p); enemies.add(p); } Point[] DownWaitPoints = new Point[]{ new Point(1104, 368), new Point(1200, 368), }; for(int i = 0; i < DownWaitPoints.length; i++){ w = new Waiter(tileMap, 0, "down"); w.setPosition(DownWaitPoints[i].x, DownWaitPoints[i].y); enemies.add(w); waiters.add(w); } }
c517985e-9926-47d5-9955-7b7055afc690
8
public static WordLocation parseWordLocation(String obj) { WordLocation wl = new WordLocation(); String data[] = obj.split("\n"); if( data.length != 2) return null; String tokens[] = data[0].split("[=]|[\\{]|[\\}]|[,]"); try { if(data[0].indexOf("WordLocation") != -1 || tokens.length > 0) { for( int i = 0; i<tokens.length; i++ ) { if(tokens[i].indexOf("word")!=-1) wl.setWord(tokens[i+1].trim()); else if(tokens[i].indexOf("fileName")!=-1) wl.setFileName(tokens[i+1].trim()); else if(tokens[i].indexOf("location")!=-1) wl.setLocations(parseLocation(tokens[i+1])); } wl.setBook(Book.parseBook(data[1])); wl.setCount(wl.getLocations().size()); } else { logger.warn("WordLocation:Invalid Record read " + data); } } catch(Exception ex) { logger.error("WordLocation: Error Record read " + data); ex.printStackTrace(); } return wl; }
1c142fd9-7fd5-4fb1-8774-ca33280c623c
9
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; if(target.fetchEffect(ID())!=null) { mob.tell(L("You already healed by fire.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> @x1 for flaming healing.^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("An aura surrounds <S-NAME>.")); beneficialAffect(mob,target,asLevel,0); } } else return beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 for flaming healing, but <S-HIS-HER> plea is not answered.",prayWord(mob))); // return whether it worked return success; }