method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
6a2a49bf-3fe4-4895-8655-9ab3ed1b8abe
3
public ArrayList<String> readFinnKinoXML() { DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd"); Date date = new Date(); String url = "http://www.finnkino.fi/xml/Schedule/?area="+kaupunki+"&dt="+dateFormat.format(date); finnKinoElokuvat.clear(); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(url); doc.getDocumentElement().normalize(); //System.out.println ("Root element: " + // doc.getDocumentElement().getNodeName()); NodeList items = doc.getElementsByTagName("Show"); for(int i = 0; i< items.getLength(); i++){ //Hakee elokuvien tiedot kyseiseltä paikkakunnalta ja lisää ne arraylistiin finnKinoElokuvat Node n = items.item(i); if(n.getNodeType() != Node.ELEMENT_NODE) continue; Element e = (Element) n; NodeList titlelist = e.getElementsByTagName("Title"); Element titleElem = (Element) titlelist.item(0); Node titleNode = titleElem.getChildNodes().item(0); //System.out.println(titleNode.getNodeValue()); NodeList titlelist1 = e.getElementsByTagName("dttmShowStart"); Element titleElem1 = (Element) titlelist1.item(0); Node titleNode1 = titleElem1.getChildNodes().item(0); NodeList titlelist2 = e.getElementsByTagName("LengthInMinutes"); Element titleElem2 = (Element) titlelist2.item(0); Node titleNode2 = titleElem2.getChildNodes().item(0); NodeList titlelist3 = e.getElementsByTagName("Genres"); Element titleElem3 = (Element) titlelist3.item(0); Node titleNode3 = titleElem3.getChildNodes().item(0); String nayttoAika = titleNode1.getNodeValue().substring(11); finnKinoElokuvat.add(i,titleNode.getNodeValue() +" - "+nayttoAika+" - "+titleNode2.getNodeValue()+" min"+" - "+titleNode3.getNodeValue()); //System.out.println(finnKinoElokuvat.get(i)); //System.out.println(nayttoAika); } } catch (Exception e) {System.out.println(e);} return finnKinoElokuvat; }
4687d814-60ba-4788-a038-e07d6d886a0c
9
public static void main(String[] args) { try { Args arg = new Args("a, c*", args); boolean displayFullFeed = arg.getBoolean('a'); String currencyRule = arg.getString('c'); String rssUrl = "http://rss.nbp.pl/kursy/TabelaA.xml"; ExchangeRateCreator exRateCreator = new ExchangeRateCreator( new HTMLTableParser(), currencyRule ); XMLReader xmlr = new XMLReader(); if(currencyRule.length() > 0) { exRateCreator.setCurrencyRule(currencyRule); } xmlr.readRemoteXML(rssUrl); if(displayFullFeed) { for (FeedMessage aMessage : xmlr.getFeed().getMessages()) { for (ExchangeRate aRate : exRateCreator.getExchangeRatesFrom(aMessage)) { System.out.println(aRate); } } } else { for (ExchangeRate aRate : exRateCreator.getExchangeRatesFrom( xmlr.getFeed().getMessages().get(0) )) { System.out.println(aRate); } } } catch (JCurrencyException ex) { System.out.println("Blad: " + ex.errorMessage()); } catch (ArgsException ex) { System.out.println("Blad: " + ex.errorMessage()); } catch (MalformedURLException ex) { System.out.println("Blad: " + ex.getLocalizedMessage()); } catch (ParseException ex) { System.out.println("Blad: " + ex.getLocalizedMessage()); } }
d638dc86-d87b-467d-a230-86f36ede6b62
2
@Override public void mousePressed(MouseEvent e) { if (!tabPane.isEnabled()) { return; } tabPressed = tabForCoordinate(tabPane, e.getX(), e.getY()); if (tabPressed != -1) { tabPane.repaint(getTabBounds(tabPane, tabPressed)); } }
0a95924d-d9db-406e-bc96-c2c1319c67fa
5
@Override public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof CacheTuple)) return false; if (!root.equals(((CacheTuple) obj).root)) return false; if (!slug.equals(((CacheTuple) obj).slug)) return false; if (!url.equals(((CacheTuple) obj).url)) return false; return true; }
ceb45b78-a6a1-48c1-afc1-172a8663320b
0
@Override public void documentRemoved(DocumentRepositoryEvent e) {}
cfe07cb2-9be9-452d-940e-5f342aaa5ada
7
@Override public boolean adapt(ClassNode node) { if (!node.superName.equals("java/awt/Canvas")) return false; System.out.println("Found Canvas Class: " + node.name); node.superName = "com/omrlnr/bot/hooks/Canvas"; ListIterator<?> mli = node.methods.listIterator(); while (mli.hasNext()) { MethodNode mn = (MethodNode) mli.next(); if (mn.name.equals("<init>")) { ListIterator<?> ili = mn.instructions.iterator(); while (ili.hasNext()) { AbstractInsnNode ain = (AbstractInsnNode) ili.next(); if (ain.getOpcode() == Opcodes.INVOKESPECIAL) { MethodInsnNode min = (MethodInsnNode) ain; min.owner = "com/omrlnr/bot/hooks/Canvas"; break; } } } } return true; }
778cf5cc-7480-4a54-a39f-af7e104c007a
9
public ParseException generateParseException() { jj_expentries.clear(); boolean[] la1tokens = new boolean[48]; if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 17; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } if ((jj_la1_1[i] & (1<<j)) != 0) { la1tokens[32+j] = true; } } } } for (int i = 0; i < 48; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.add(jj_expentry); } } jj_endpos = 0; jj_rescan_token(); jj_add_error_token(0, 0); int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = jj_expentries.get(i); } return new ParseException(token, exptokseq, tokenImage); }
fc84c657-0574-4bf9-be9b-3848d8bfdefa
3
public boolean validateUniqueNickname(String nickname){ boolean isUniqueNickname = false; try { Socket loginSocket = new Socket(SERVER_ADDRESS_LOGIN, LOGIN_PORT); loginSocket.setSoTimeout(TIMEOUT); OutputStream outputStream = loginSocket.getOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject("CHECK_UNIQUE_NICKNAME"); objectOutputStream.writeObject(nickname); objectOutputStream.flush(); InputStream inputStream = loginSocket.getInputStream(); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); isUniqueNickname = objectInputStream.readBoolean(); loginSocket.close(); }catch (SocketException e){ new ErrorFrame("Login Server unreachable!"); } catch (SocketTimeoutException e){ new ErrorFrame("Connection timed out"); } catch (Exception e) { new ErrorFrame("An unknown Error occoured"); } return isUniqueNickname; }
9576f96c-d888-4216-ad59-268c923ddc14
9
public void listen(){ _log("listening to new client..."); Socket client = null; try{ _serverSocket = new ServerSocket(_server.listenPort()); _serverSocket.setSoTimeout(1000*100); while(true) { client = _serverSocket.accept(); _log("Get connection from " + client.getInetAddress().getHostAddress()); //TODO: here, it should control how many threads we could accept at most //TEST //TODO: add the thread pool Thread t; // TODO: if the client is firstly connected, should make a new directory for him t = new Thread(new DropboxFileServerClientHandler(client, _server)); t.start(); } }catch(InterruptedIOException e){ _elog(e.toString()); if(_server.debugMode()){ e.printStackTrace(); } }catch(IOException e){ _elog(e.toString()); if(_server.debugMode()){ e.printStackTrace(); } }finally{ try{ _log("Close connection from " + client.getInetAddress().getHostAddress()); if(_serverSocket != null ) _serverSocket.close(); if( client != null ) client.close(); }catch(IOException e){ _elog(e.toString()); if(_server.debugMode()){ e.printStackTrace(); } } } }
a5a2562a-d6a0-4381-afca-c1cb35a8ca58
8
private void CheckButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CheckButtonActionPerformed String flightno = FlightNoTextField.getText(); if (flightno.equals("")) { return; } StatusPanel.setVisible(true); try { Connection con; con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "system", "oracle"); Statement st1 = con.createStatement(); Statement st2 = con.createStatement(); String from = "", to = "", via = "", status = ""; ResultSet rs1 = st1.executeQuery("select a.aid, a.city " + "from flight, airport a " + "where flightno='" + flightno + "'" + " and a.aid in (depID,arrID) " + "group by a.aid,a.city " + "having count(aid)=1"); ResultSet rs3 = st2.executeQuery("select status from flight where flightno='" + flightno + "'"); if (rs3.next()) { status = rs3.getString(1); } else { StatusTextArea.setText("No such flight exists!"); con.close(); return; } while (rs1.next()) { ResultSet rs2 = st2.executeQuery("Select a.aid,a.apname,a.iatacode,a.city from airport a, flight f" + " where flightno='" + flightno + "'" + " and a.aid=depID " + " and a.aid=" + rs1.getInt(1)); if (rs2.next()) { from = rs2.getString(2) + " Airport (" + rs2.getString(3) + "), " + rs2.getString(4); } rs2 = st2.executeQuery("select a.aid,a.apname,a.iatacode,a.city from airport a, flight f" + " where flightno='" + flightno + "'" + " and a.aid=arrID " + " and a.aid=" + rs1.getInt(1)); if (rs2.next()) { to = rs2.getString(2) + " Airport (" + rs2.getString(3) + "), " + rs2.getString(4); } } rs1 = st1.executeQuery("select a.city " + "from flight, airport a " + "where flightno='" + flightno + "'" + " and a.aid in (depID,arrID) " + "group by a.aid,a.city " + "having count(aid)=2"); while (rs1.next()) { via += rs1.getString(1) + ", "; } if (via.equals("")) { via = "No Stops"; } else { via = via.substring(0, via.length() - 2); } StatusTextArea.setText("FROM\t" + from); StatusTextArea.append("\nTO\t" + to); StatusTextArea.append("\nVIA\t" + via); StatusTextArea.append("\nSTATUS:\t" + status); con.close(); } catch (SQLException se) { System.out.println(se); } }//GEN-LAST:event_CheckButtonActionPerformed
1b1a2999-4680-4817-a7f1-f93a5a980171
1
public static final String clean(String path) { if(StringUtils.isBlank(path)){ return EMPTY_STRING; } path = stripDots(path); return path; }
b3706324-fe07-4e15-923b-45fe47e5832c
7
public boolean isBlocked() { if (emptyTiles().size() > 0) return false; for (int x = 0; x < 3; x++) for (int y = 0; y < 4; y++) if (getTile(x, y).getValue() == getTile(x + 1, y).getValue()) return false; for (int x = 0; x < 4; x++) for (int y = 0; y < 3; y++) if (getTile(x, y).getValue() == getTile(x, y + 1).getValue()) return false; return true; }
6c4bd4a9-ecb7-4ccb-83fa-93df04f86a44
1
public void charge(long deltaMs) { charged += deltaMs; if(charged >= chargeTime) { timeSinceLastShot = 0; charged = 0; charging = false; weapon.fire(); } }
ec5760cc-8f5f-490b-9f56-482a7f5f6a0c
0
public int getCurrentFrame() { return currentFrame; }
b11596d9-0695-4e8d-90bb-1c9e5a4da448
1
public static synchronized EmployeeRepositorySingleton getRepository() { //TODO implement method that returns repository instance if(instance == null){ instance = new EmployeeRepositorySingleton(); } return instance; }
b50a36e0-e0d0-47e6-9158-0bbf9e80115c
7
protected void _dealCmd() { String cmd = null; boolean needStartTask = false; //添加到命令行队列中,并判断是否需要开启任务 _lockCmd(); if(!_m_lCmdList.isEmpty()) { //取第一个命令行 cmd = _m_lCmdList.getFirst(); } _unlockCmd(); //获取处理队列 ArrayList<_IALBasicServerCmdDealer> dealerList = getDealerList(); if(null != cmd) { //非空才进行处理 for(int i = 0; i < dealerList.size(); i++) { _IALBasicServerCmdDealer dealer = dealerList.get(i); if(null == dealer) continue; try { dealer.dealCmd(cmd); } catch (Exception e) { e.printStackTrace(); } } } _lockCmd(); //取出第一个命令行 _m_lCmdList.pop(); //判断命令行是否为空 if(!_m_lCmdList.isEmpty()) needStartTask = true; _unlockCmd(); //原队列为空则注册任务开启对应操作的执行 if(needStartTask) ALSynTaskManager.getInstance().regTask(new ALSynCmdDealTask()); }
185a46ff-ff67-46ab-8c27-7e46f18243c9
3
void loadCheckpoint() throws FileNotFoundException{ /* * load index info back into the index from the checkpoint file */ Scanner indexSave = new Scanner(new File("testData/indexCheckpoint/index")); while(indexSave.hasNextLine()){ String indexEntry[] = indexSave.nextLine().split(","); String key = indexEntry[0]; long[] indexMeta = new long[M+2]; indexMeta[0] = Long.parseLong(indexEntry[1]); for(int i = 1; i <=M+1; i++){ indexMeta[i] = Long.parseLong(indexEntry[i+1]); } index.put(key, indexMeta); } /* * load estimateBase info back into the estimateBase from the checkpoint file */ Scanner estimateSave = new Scanner(new File("testData/indexCheckpoint/estimateBase")); while(estimateSave.hasNextLine()){ String estimateEntry[] = indexSave.nextLine().split(","); String key = estimateEntry[0]; long[] estimateMeta = new long[2]; estimateMeta[0] = Long.parseLong(estimateEntry[1]); estimateMeta[1] = Long.parseLong(estimateEntry[2]); index.put(key, estimateMeta); } }
176c42ed-2421-4efb-bee6-7b3690ff7965
1
@Override public void changedMostRecentDocumentTouched(DocumentRepositoryEvent e) { if (e.getDocument() == null) { setEnabled(false); } else { setEnabled(true); } }
47ffb4d8-a440-453b-9405-b5b702da0d78
4
public void movePiece(Piece chosenPiece) { Piece gonnaMovePiece; System.out.println("움직일 위치의 좌표값을 입력하세요."); Position gonnaMovePos = inputPos(); while (!chosenPiece.moveAblePosList.contains(gonnaMovePos)) { if(isKing(chosenPiece) && isCastling(gonnaMovePos)) break; //캐슬링 처리 System.out.println("접근할 수 없는 위치입니다. 다시 입력해주세요."); gonnaMovePos = inputPos(); } gonnaMovePiece = Board.chessBoard.get(chosenPos); if(isEnpassant(gonnaMovePiece, gonnaMovePos)){ //앙파상 처리 Position baseBeside = new Position(gonnaMovePos.getxPos(),gonnaMovePos.getyPos()-1); Board.chessBoard.remove(baseBeside); } Board.chessBoard.put(gonnaMovePos, gonnaMovePiece); gonnaMovePiece.resetMoveablePosList(gonnaMovePos); gonnaMovePiece.moveCount++; Board.chessBoard.remove(chosenPos); isPromotion();//HACK: 프로모션의 처리, 명확하지 못하다. 해결방법을 잘 모르겠다. }
3ef10a44-ec74-448b-997a-9dfb4fd4f775
9
public Object getValue(Object target, Class<?> type, long fieldOffset) { if (type == int.class) return unsafe.getInt(target, fieldOffset); else if (type == long.class) return unsafe.getLong(target, fieldOffset); else if (type == short.class) return unsafe.getShort(target, fieldOffset); else if (type == boolean.class) return unsafe.getBoolean(target, fieldOffset); else if (type == char.class) return unsafe.getChar(target, fieldOffset); else if (type == double.class) return unsafe.getDouble(target, fieldOffset); else if (type == byte.class) return unsafe.getByte(target, fieldOffset); else if (type == float.class) return unsafe.getFloat(target, fieldOffset); else return unsafe.getObject(target, fieldOffset); }
6acfa338-ce10-410d-8604-b36c55e4b425
1
@Override public void windowClosing(WindowEvent arg0) { Object[] object = {"Yes", "9 9 9"}; int answer = JOptionPane.showOptionDialog(null, "Are you sure you want to exit the JGame Collection?", "Exit", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, object, object[1]); if(answer == 0) { JGSystem.getInstance().exit(user); } }
fe5bf2f1-4040-4156-8f3a-2006c59a8da6
6
private void searchFlights() { if (checkBoxRoundTrip.getChecked() && dateFieldReturn.getDate() < dateFieldDeparture.getDate()) { Dialog.alert("Return date should be greater or equals to departure date"); return; } if (searchParameters.getFromAirportId() == null || searchParameters.getToAirportId() == null) { Dialog.alert("Select From and To"); return; } searchParameters.setDepartureDate(dateFieldDeparture.getDate()); if (checkBoxRoundTrip.getChecked()) { searchParameters.setReturnDate(dateFieldReturn.getDate()); } // create process object to handle response ProcessSearchFlights processSearchFlights = new ProcessSearchFlights(searchParameters) { public void onComplete() { UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { if(getErrorCode() != null) { Dialog.alert("Error: " + errorCode); return; } UiApplication.getUiApplication().pushScreen(new FlightSearchResultsScreen(getResult())); } }); } public String getLoadingMessage() { return "Searching ... Please wait."; } }; // call search flight ws TravelSDK.INSTANCE.searchFlights(processSearchFlights); }
7741a4d9-9948-4339-b14d-e5c8cd4c258c
5
private static String getImageThunb(Element work) throws Exception{ try{ Elements tmp = work.getElementsByClass("work_thumb"); if(tmp==null || tmp.size()==0) return "http://www.dlsite.com/images/web/home/no_img_sam.gif"; Element thumb = tmp.get(0).child(0); Elements tmp1 = thumb.getElementsByTag("img"); if(tmp1==null) return "http://www.dlsite.com/images/web/home/no_img_sam.gif"; //thumbnail url String img = tmp1.get(0).attr("src") ; if("/images/web/home/no_img_sam.gif".equals(img)){ return "http://www.dlsite.com/images/web/home/no_img_sam.gif"; } return "http:"+img; }catch(Exception e){ throw new Exception(e); } }
7a6d25e6-ca11-4795-9629-4373641993d4
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(SignupBox.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(SignupBox.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(SignupBox.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(SignupBox.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 SignupBox().setVisible(true); } }); }
ddee4c69-d953-4266-b8fb-57e8ca2c8249
5
public synchronized List<ChunkInFilePosition> getChunks() { final List<ChunkInFilePosition> res = new ArrayList<ChunkInFilePosition>(); try { for(int x = 0; x < 32; x++) { for(int z = 0; z < 32; z++) { if(regionSource.hasChunk(x, z)) { final DataInputStream regionChunkInputStream = regionSource.getChunkDataInputStream(x, z); if(regionChunkInputStream == null) { System.err.println("Failed to fetch input stream"); continue; } res.add(new ChunkInFilePosition(x, z)); regionChunkInputStream.close(); } } } } catch(final IOException e) { e.printStackTrace(); } return res; }
4c59a4f8-8c10-41d6-9d00-ec78f87fb733
6
@Override public void handleClick(int x, int y) { if((x >= (2 * Sidebar.HORIZONTAL_SPACING)) && (x <= (getWidth()))) { double topY = getHeight() - Sidebar.VERTICAL_SPACING; double height = (getHeight() - (3 * Sidebar.VERTICAL_SPACING)) / 2; if((y < (topY)) && (y > (topY - height))) { double pos = 1 - ((x - (2 * Sidebar.HORIZONTAL_SPACING)) / (getWidth() - (2 * Sidebar.HORIZONTAL_SPACING))); amplitude = MIN_AMPLITUDE + (AMP_RANGE * pos); } if((y < (topY - (height + Sidebar.VERTICAL_SPACING))) && (y > (topY - ((2 * height) + Sidebar.VERTICAL_SPACING)))) { double pos = 1 - ((x - (2 * Sidebar.HORIZONTAL_SPACING)) / (getWidth() - (2 * Sidebar.HORIZONTAL_SPACING))); period = MIN_PERIOD + (PER_RANGE * pos); } } }
c22270a1-c9c9-4f84-b277-e01aa75c2c14
7
public void setLocale(final String localeKey) { if (localeKey != null || !localeKey.isEmpty()) { String[] parts = localeKey.split("[_\\.]"); if (parts.length == 1) { currentLocale = new Locale(parts[0]); } else if (parts.length == 2) { currentLocale = new Locale(parts[0], parts[1]); } else if (parts.length == 3) { currentLocale = new Locale(parts[0], parts[1], parts[2]); } } ResourceBundle.clearCache(); formatCache.clear(); BackpacksPlugin.getInstance().getLogger().info("Using Locale: " + this.currentLocale.toString()); try { localeBundle = ResourceBundle.getBundle(MESSAGES, currentLocale); } catch (MissingResourceException e) { localeBundle = new ResourceBundle() { @Override protected Object handleGetObject(String key) { return null; } @Override public Enumeration<String> getKeys() { return null; } }; } try { customBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new FileClassLoader(this.backpacksPlugin, this.backpacksPlugin.getClass().getClassLoader())); } catch (MissingResourceException e) { customBundle = new ResourceBundle() { @Override protected Object handleGetObject(String key) { return null; } @Override public Enumeration<String> getKeys() { return null; } }; } }
b89a47f0-13ba-433d-b6f8-51c7931b66b8
9
public static Rectangle2D createRectangle(Size2D dimensions, double anchorX, double anchorY, RectangleAnchor anchor) { Rectangle2D result = null; final double w = dimensions.getWidth(); final double h = dimensions.getHeight(); if (anchor == RectangleAnchor.CENTER) { result = new Rectangle2D.Double(anchorX - w / 2.0, anchorY - h / 2.0, w, h); } else if (anchor == RectangleAnchor.TOP) { result = new Rectangle2D.Double(anchorX - w / 2.0, anchorY, w, h); } else if (anchor == RectangleAnchor.BOTTOM) { result = new Rectangle2D.Double(anchorX - w / 2.0, anchorY - h, w, h); } else if (anchor == RectangleAnchor.LEFT) { result = new Rectangle2D.Double(anchorX, anchorY - h / 2.0, w, h); } else if (anchor == RectangleAnchor.RIGHT) { result = new Rectangle2D.Double(anchorX - w, anchorY - h / 2.0, w, h); } else if (anchor == RectangleAnchor.TOP_LEFT) { result = new Rectangle2D.Double(anchorX, anchorY, w, h); } else if (anchor == RectangleAnchor.TOP_RIGHT) { result = new Rectangle2D.Double(anchorX - w, anchorY, w, h); } else if (anchor == RectangleAnchor.BOTTOM_LEFT) { result = new Rectangle2D.Double(anchorX, anchorY - h, w, h); } else if (anchor == RectangleAnchor.BOTTOM_RIGHT) { result = new Rectangle2D.Double(anchorX - w, anchorY - h, w, h); } return result; }
df53505d-497e-4fd7-a240-8860a60aeca4
2
private void saveDictionnaire(PrintStream out) throws IOException { out.println("<dictionnaire>"); for (int i = 0; i < dico.getRowCount() - 1; i++) { out.println("<information code=\"" + dico.getID(i) + "\" nom=\"" + dico.getValue(dico.getID(i), DictionnaireTable.NAME) + "\" type=\"" + dico.getValue(dico.getID(i), DictionnaireTable.TYPE) + "\" taille=\"" + dico.getValue(dico.getID(i), DictionnaireTable.SIZE) + "\" utilise=\"" + (((Boolean) dico.getValue(dico.getID(i), DictionnaireTable.USE)).booleanValue() ? "true" : "false") + "\" />"); } out.println("</dictionnaire>"); }
4fc06924-c2ee-463c-9e09-a65380072f27
1
public void setTitle(String title, String format) { if (format != null) { titleMap.put(title.toLowerCase(), format); } else { titleMap.remove(title.toLowerCase()); } }
ed13af50-cb1b-44de-beb8-653396e135b8
2
public void render() { player.render(); shader.bind(); shader.updateUniforms(transform.getTransformation(), transform.getProjectedTransformation(), material); mesh.draw(); for(Door door : doors) door.render(); for(MedKit medkit : medkits) medkit.render(); rounds.render(); }
78679a24-79b9-495e-951c-41a8b67f114b
0
@Override public String getDesc() { return "Default"; }
58145d00-1e97-4e20-b8dd-5c15c95b00cd
5
@Override public void controllerUpdate(ControllerEvent evt) { if (evt instanceof ConfigureCompleteEvent || evt instanceof RealizeCompleteEvent || evt instanceof PrefetchCompleteEvent) { synchronized (this) { stateTransitionOK = true; this.notifyAll(); } } else { if (evt instanceof ResourceUnavailableEvent) { synchronized (this) { stateTransitionOK = false; this.notifyAll(); } } else { if (evt instanceof EndOfMediaEvent) { processor.close(); System.exit(0); } } } }
4ecdacb4-7fe7-4f94-b3df-352b26772e5b
3
public void setExp(PExp node) { if(this._exp_ != null) { this._exp_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._exp_ = node; }
6f94aade-df54-44ea-bb6b-8e46da48444e
0
public void setShopAddress(String shopAddress) { this.shopAddress = shopAddress; }
5caf5649-905f-4a84-81e1-de9742f1f776
5
public void stClickKey(int sleepTime, String... args) { try { Interpreter In = new Interpreter(); try { In.set("rb2", new Robot()); In.eval("rb2.mouseMove(70,515" + ");"); for (String s : args) In.eval("rb2.keyPress(java.awt.event.KeyEvent." + s + ");"); for (String s : args) In.eval("rb2.keyRelease(java.awt.event.KeyEvent." + s + ");"); } catch (EvalError e1) { e1.printStackTrace(); } } catch (AWTException e) { e.printStackTrace(); } try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } }
3544be8f-fda3-4e6b-b688-368f6dfc7f86
1
public void unload(int y){ if(section[y] != null)section[y].removeFromParent(); section[y] = null; System.gc(); }
a9ad4a43-141f-4e88-a111-75143b16ba1e
4
private void paintImage(GodImage chosenImage, Rectangle rect) { int width = rect.width; int height = rect.height; if(rect.x > frame.getWidth() || rect.y > frame.getHeight() || rect.x+width < 0 || rect.y+height < 0 ) return; graphic.drawImage(chosenImage.getImage().getBufferedImage(), rect.x, rect.y, width, height, null); }
875bdfbb-253d-4711-bb6c-c5800848e507
8
public final void removalTask() { try { if (!player.getAllBuffs().isEmpty()) { player.cancelAllBuffs_(); } if (!player.getAllDiseases().isEmpty()) { player.dispelAllDebuffs(); } if (player.getTrade() != null) { MapleTrade.cancelTrade(player.getTrade()); } NPCScriptManager.getInstance().dispose(this); if (player.getEventInstance() != null) { player.getEventInstance().playerDisconnected(player); } player.getCheatTracker().dispose(); if (player.getMap() != null) { player.getMap().removePlayer(player); } final IMaplePlayerShop shop = player.getPlayerShop(); if (shop != null) { shop.removeVisitor(player); if (shop.isOwner(player)) { shop.setOpen(true); } } } catch (final Throwable e) { FileoutputUtil.outputFileError(FileoutputUtil.Acc_Stuck, e); } }
97c971ca-f113-4b91-84f4-b06d3861c888
8
private static <T> T enhance(Type typeToWrap, MethodEntry methodEntry) { try { net.sf.cglib.proxy.Enhancer e = new net.sf.cglib.proxy.Enhancer(); Map<String, Class<?>> parameterizedTypeMap = null; if (typeToWrap instanceof ParameterizedType) { parameterizedTypeMap = prepareTypeMap(((ParameterizedType) typeToWrap)); Class<?> type = (Class) ((ParameterizedType) typeToWrap).getRawType(); if (type.isInterface()) { e.setInterfaces(new Class[]{type, Parametrized.class}); } else { e.setSuperclass(type); e.setInterfaces(new Class[]{Parametrized.class}); } } else if (typeToWrap instanceof TypeVariable) { e.setSuperclass((methodEntry.getReturnType())); } else { e.setSuperclass((Class<?>) typeToWrap); } e.setCallback(new Interceptor(methodEntry, parameterizedTypeMap)); return (T) e.create(); } catch (NoSuchFieldException e) { throw new EnhanceException(e); } catch (IllegalAccessException e) { throw new EnhanceException(e); } }
230d67c9-e7e8-4455-8d47-2a9086035674
4
private boolean isFull() { return full?true:(full=o0!=null&&o0.isFull()&&o1!=null&&o1.isFull()); }
ab6fb662-6a39-4ffb-b20a-1a648ccafbb7
1
@SuppressWarnings("unchecked") public FollowingGraph(String dir) { this.dir = dir; try { FileInputStream fin = new FileInputStream(dir); ObjectInputStream oos = new ObjectInputStream(fin); map = (TreeMap<Integer, UserFollowers>) oos.readObject(); oos.close(); } catch (Exception e) { e.printStackTrace(); } }
4e03d1dc-eae1-4900-b8ca-a7f70ebe776a
4
public int checkPresence(){ int loop; for (loop = 0; loop < enemiesPresent.size(); loop++){ if (!enemiesPresent.get(loop).stillPresent() && !enemiesPresent.get(loop).gotChecked() && enemiesPresent.get(loop).portalPassing()){ enemiesPassed++; enemiesPresent.get(loop).nowChecked(); } } return enemiesPassed; }
01f7f0a2-cd12-4aa4-b416-b1ad752aa77f
8
public static LinkedListNode findloop(LinkedListNode n) { if(n==null || n.next == null) return null; LinkedListNode quick=n, slow=n; while(true) { if(quick == null || quick.next == null) return null; quick = quick.next.next; slow = slow.next; if(quick == slow) break; } quick = n; while(true) { if(quick == slow) return slow; quick = quick.next; slow = slow.next; } }
10645fdd-9a15-4f54-aa4e-84f84118307c
1
public static boolean getKeyDown(int keyCode) { return getKey(keyCode) && !lastKeys[keyCode]; }
c14ae666-c382-4bfc-aefe-7a6979bcf254
4
@Override public TLValue evaluate() { TLValue a = lhs.evaluate(); TLValue b = rhs.evaluate(); if(a.isNumber() && b.isNumber()) { return new TLValue(a.asDouble() < b.asDouble()); } if(a.isString() && b.isString()) { return new TLValue(a.asString().compareTo(b.asString()) < -1); } throw new RuntimeException("illegal expression: " + this); }
fec370b2-f253-4d54-a897-0eb0d776a013
5
private Class<?> getConstraintValidatorClass( TypeElement memberAnnotationTypeElement, Class<? extends Annotation> constraintAnnotationClass) { AnnotationMirror constraintAnnotation = AnnotationProcessingUtils .findAnnotationMirror(processingEnv, memberAnnotationTypeElement, constraintAnnotationClass); Class<?> constraintValidatorClass = null; if (constraintAnnotation != null) { String constraintValidatorClassName = AnnotationProcessingUtils .getAnnotationElementValue(processingEnv, constraintAnnotation, "value").getValue() .toString(); try { constraintValidatorClass = Class .forName(constraintValidatorClassName); } catch (Exception ex) { processingEnv.getMessager().printMessage( Diagnostic.Kind.ERROR, "Cannot get class object for ConstraintValidator class: " + constraintValidatorClassName); } } return constraintValidatorClass; }
daec5809-ea28-4fbb-bc14-491d6253c650
5
public boolean equals(Object other){ if(other instanceof LogEvent){ LogEvent otherEvent = (LogEvent)other; return otherEvent.getLevel().equals(getLevel()) && otherEvent.getMessage().equals(getMessage()) && otherEvent.getOriginalLogger().equals(getOriginalLogger()) && (otherEvent.getThrowable() != null ? otherEvent.getThrowable().equals(getThrowable()) : getThrowable() == null); } return false; }
318c2f71-e5bc-4b8a-8cff-372b3565d73f
1
public String describeNode() { return "["+(getNodeProperty()==null?"null":StringUtils.stripControlCharacters(getNodeProperty().toString())) +"]";//+"="+ toString() /*+ (isValueValid()?"":" (invalid)")*/; }
9d0a7247-9dc1-4d73-949c-4335c09dafa9
0
public Player (boolean color, Board field ){ myColor=color; this.field=field; }
1690caf6-b902-430b-8922-a68cf4358f72
3
public boolean isBalancedRec(TreeNode root, TreeNode tmp){ if(root == null) { return true; } TreeNode tmpL = new TreeNode(0); boolean isLeft = isBalancedRec(root.left, tmpL); TreeNode tmpR = new TreeNode(0); boolean isRight = isBalancedRec(root.right, tmpR); int hLeft = tmpL.val; int hRight = tmpR.val; tmp.val = Math.max(hLeft, hRight) + 1; return isLeft && isRight && Math.abs(hLeft - hRight) <= 1; }
8bad0d5f-9d91-47cb-a303-ee1297af9f92
0
public void setVistingHourId(int vistingHourId) { this.vistingHourId = vistingHourId; }
cf7247db-0143-4c94-bdaf-7f4470963fe8
4
private void test() { System.out.println("Input IP-address of active node"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String ipAddress = null; String message = "Fuck"; try { ipAddress = br.readLine(); } catch (IOException e) { System.out.println("IO error!"); System.exit(1); } XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); try { config.setServerURL(new URL(stringToURL(ipAddress))); } catch (MalformedURLException e) { e.printStackTrace(); } XmlRpcClient client = new XmlRpcClient(); client.setConfig(config); Object[] params = new Object[]{message}; try { Object[] result = (Object[]) client.execute("Calendar.test", params); for (int i = 0; i < result.length; i++) { System.out.println(result[i].toString()); } System.out.println("-------------------"); } catch (XmlRpcException e) { e.printStackTrace(); } }
8f5e2ec5-afd1-4c3a-8dc9-7da9d5518ba2
8
private boolean r_verb() { int among_var; int v_1; // (, line 136 // [, line 137 ket = cursor; // substring, line 137 among_var = find_among_b(a_4, 46); if (among_var == 0) { return false; } // ], line 137 bra = cursor; switch (among_var) { case 0: return false; case 1: // (, line 143 // or, line 143 lab0: do { v_1 = limit - cursor; lab1: do { // literal, line 143 if (!(eq_s_b(1, "\u0430"))) { break lab1; } break lab0; } while (false); cursor = limit - v_1; // literal, line 143 if (!(eq_s_b(1, "\u044F"))) { return false; } } while (false); // delete, line 143 slice_del(); break; case 2: // (, line 151 // delete, line 151 slice_del(); break; } return true; }
9cb37254-6837-4136-a10a-218d9e288d5a
8
public static void Classic_Cannit(){ System.out.print("INFO: Welcome to " + Name); System.out.println("INFO: The version you are running is " + Version); try{ prop.load(new FileReader("server.properties")); }catch (Exception localException2){ System.out.println("WARNING: Failed to load server.properties!"); }try{ serverName = prop.getProperty("server-name", "Classic Minecraft Server"); motd = prop.getProperty("motd", "Welcome to my Classic Minecraft Server"); port = Integer.parseInt(prop.getProperty("port", "25565")); maxPlayers = Integer.parseInt(prop.getProperty("max-players", "20")); maxConnections = Integer.parseInt(prop.getProperty("max-connections", "3")); Public = Boolean.parseBoolean(prop.getProperty("public", "true")); verifyNames = Boolean.parseBoolean(prop.getProperty("verify-names", "true")); growTrees = Boolean.parseBoolean(prop.getProperty("grow-trees", "false")); adminSlots = Boolean.parseBoolean(prop.getProperty("admin-slot", "false")); if(maxPlayers < 1) maxPlayers = 1; if(maxPlayers > 32) maxPlayers = 32; prop.setProperty("server-name", serverName); prop.setProperty("motd", motd); prop.setProperty("port", new StringBuilder().append("").append(port).toString()); prop.setProperty("max-players", new StringBuilder().append("").append(maxPlayers).toString()); prop.setProperty("public", new StringBuilder().append("").append(Public).toString()); prop.setProperty("verify-names", new StringBuilder().append("").append(verifyNames).toString()); prop.setProperty("max-connections", "3"); prop.setProperty("grow-trees", new StringBuilder().append("").append(growTrees).toString()); prop.setProperty("admin-slot", new StringBuilder().append("").append(adminSlots).toString()); }catch (Exception localException3){ Exception localException1; (localException1 = localException3).printStackTrace(); System.out.println("WARNING: Error in server.properties!"); System.exit(0); } if(!verifyNames){ System.out.println("WARNING: ######################### WARNING #########################"); System.out.println("WARNING: The verify-names setting has been turn to false!"); System.out.println("WARNING: Anyone can connect to this server and have any username the player"); System.out.println("WARNING: wants! This includes being an OP!"); if(Public){ System.out.println("WARNING: Being a public server it could or will happen to you!"); } System.out.println("WARNING: If you wish to fix this, edit server.properties, and change"); System.out.println("WARNING: verify-names to true."); System.out.println("WARNING: ###########################################################"); if(!Public){ System.out.println("INFO: Hey! Your server is private"); } }try{ prop.store(new FileWriter("server.properties"), "Classic Minecraft Server Properties"); }catch (Exception localException4){ System.out.println("WARNING: Failed to save server.properties!"); } }
40acab86-443f-4905-a3e9-77facf37d7f3
7
public static void main(String [ ] args) { player player1 = new player("x"); player player2 = new player("o"); boolean cont = true; int input = -1; String continput = ""; String winner = null; boolean player = true; while(cont){ Board playBoard = new Board(); StdOut.print("input placement for your symbol (0-8)"); StdOut.println(); while(true){ while(!playBoard.isValid(input)){ input = StdIn.readInt(); } if(player){ playBoard.inputSymbol("x", input); player = !player; } else{ playBoard.inputSymbol("o", input); player = !player; } printBoard(playBoard); winner = playBoard.Win(); if(winner != null){ if(winner == player1.symbol()){ StdOut.println("player 1 wins"); player1.win(); player2.lose(); } else{ StdOut.println("player 2 wins"); player1.lose(); player2.win(); } break; } } StdOut.println("score is player1: "+ player1.score() + " player2: " + player2.score()); StdOut.println("continue?(y/n)"); continput = StdIn.readString(); if(continput.toLowerCase() == "y") { cont = true; } else { cont = false; } } }
be2a7188-c49b-4543-92df-8d616f25c6c8
5
public boolean init_sentinel(aos.jack.jak.agent.NameSpace __a) { ev = (peer.Init) __a.findEvent("peer.Init"); if (ev == null) { warning("Init ev: is not found in the capability/agent this plan comes from"); return false; } authentication = (peer.AuthenticationRequest) __a.findEvent("peer.AuthenticationRequest"); if (authentication == null) { warning("AuthenticationRequest authentication: is not found in the capability/agent this plan comes from"); return false; } heartBeat = (peer.HeartBeatTimer) __a.findEvent("peer.HeartBeatTimer"); if (heartBeat == null) { warning("HeartBeatTimer heartBeat: is not found in the capability/agent this plan comes from"); return false; } churn = (peer.Churn) __a.findEvent("peer.Churn"); if (churn == null) { warning("Churn churn: is not found in the capability/agent this plan comes from"); return false; } PeerBS = (peer.PeerInfo) lookupNamedObject("PeerBS","peer.PeerInfo",0); if (PeerBS == null) { warning("PeerInfo PeerBS: is not found in the capability/agent this plan comes from"); return false; } return true; }
cfe65f49-138a-4e04-8d0c-ee238273bb2b
3
int gjYearFromFixed(long date) { long d0 = date - 1; long n400 = div(d0, 146097); long d1 = mod(d0, 146097); long n100 = div(d1, 36524); long d2 = mod(d1, 36524); long n4 = div(d2, 1461); long d3 = mod(d2, 1461); long n1 = div(d3, 365); long year = 400 * n400 + 100 * n100 + 4 * n4 + n1; if (!(n100 == 4 || n1 == 4)) { year += 1; } int year_i = (int)year; if (year_i == year) { return year_i; } else { throw new RuntimeException("year cannot be cast to an int: " + year); } }
be32c729-0c5d-48f9-8a3f-22cfa83c1d99
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(EightPuzzleInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EightPuzzleInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EightPuzzleInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EightPuzzleInterface.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 EightPuzzleInterface().setVisible(true); } }); }
c45cef13-1621-4197-810a-0797a5d03874
6
public ResultSet Funcionarios() throws SQLException { Connection conexao = null; PreparedStatement comando = null; ResultSet resultado = null; try { conexao = BancoDadosUtil.getConnection(); comando = conexao.prepareStatement(SQL_SELECT_TODOS_funcionarios); resultado = comando.executeQuery(); conexao.commit(); } catch (Exception e) { if (conexao != null) { conexao.rollback(); } throw new RuntimeException(e); } finally { if (comando != null && !comando.isClosed()) { comando.close(); } if (conexao != null && !conexao.isClosed()) { conexao.close(); } } return resultado; }
93310e56-638a-45fa-9f94-c6f7befcde29
3
@Override public void ParseIn(Connection Main, Server Environment) { Room Room = Environment.RoomManager.GetRoom(Main.Data.CurrentRoom); if (Room == null) { return; } if (!Room.CheckRights(Main.Data, false)) { return; } RoomItem Item = Room.GetFloorItem(Main.DecodeInt()); if (Item == null) { return; } int x = Main.DecodeInt(); int y = Main.DecodeInt(); int Rotation = Main.DecodeInt(); Room.SetFloorItem(Main, Item, x, y, Rotation, false); }
2f211269-da3f-42e4-8d36-44816a50454b
1
public void simplify() { block.simplify(); if (nextByAddr != null) nextByAddr.simplify(); }
3c91b54d-d557-4c05-8969-c01ac74ddb12
7
public void pickUp(String object, ArrayList<String> inv) { if (object.equalsIgnoreCase("floor")) { System.out.println("You can't pick up the floor...\n"); } else if (object.equalsIgnoreCase("wall") || object.equalsIgnoreCase("walls")) { System.out.println("You can't pick up the walls...\n"); } else if (object.equalsIgnoreCase("computer") || object.equalsIgnoreCase("screen") || object.equalsIgnoreCase("computer screen")) { System.out.println("You can't pick up the computer screen...\n"); } else if (object.equalsIgnoreCase("keyboard")) { System.out.println("You can't pick up the keyboard...\n"); } else { System.out.println("You want to pick up what?\n"); } }
78f13fd7-76df-4929-93cf-c44aef1edda6
1
private void readMethods(final DataInputStream in) throws IOException { final int numMethods = in.readUnsignedShort(); methods = new Method[numMethods]; for (int i = 0; i < numMethods; i++) { methods[i] = new Method(in, this); } }
899e92f8-5517-45d7-b541-666ecc891f19
5
@Override public void actionPerformed(ActionEvent ae) { // EACH BUTTON STORES A COMMAND, WHICH REPRESENTS // WHICH BUTTON WAS CLICKED String command = ae.getActionCommand(); // WHICH BUTTON WAS CLICKED? switch (command) { // THE NEW BUTTON? case NEW_COMMAND: fileManager.processNewLevelRequest(); break; // THE OPEN BUTTON? case OPEN_COMMAND: fileManager.processOpenLevelRequest(); break; // THE SAVE BUTTON? case SAVE_COMMAND: fileManager.processSaveLevelRequest(); break; // THE SAVE AS BUTTON? case SAVE_AS_COMMAND: fileManager.processSaveAsLevelRequest(); break; // THE EXIT BUTTON? case EXIT_COMMAND: fileManager.processExitRequest(); break; } }
8919aca0-251a-432c-b1e6-b919caf98836
9
public int setPage(int page) { if (select == null) { return -1; } int nbpage = getPageCount(); if (nbpage > 0) { if (page > 0 && page < getPageCount()) { currentPage = page - 1; currentRows = getNbRow(); select.limit = currentRows; select.offset = currentPage * rowperpage; try { this.curRows = this.database.getRows(select); currentRows = this.curRows.size(); } catch (WaarpDatabaseSqlException e) { this.curRows = null; } fireTableStructureChanged(); } } else { if (page > 0) { select.limit = currentRows; select.offset = (page-1) * rowperpage; List<String[]> temp = null; try { temp = this.database.getRows(select); } catch (WaarpDatabaseSqlException e) { } if (temp == null || temp.size() == 0) { select.limit = currentRows; select.offset = currentPage * rowperpage; } else { currentPage = page - 1; currentRows = temp.size(); this.curRows = temp; } fireTableStructureChanged(); } } return currentPage + 1; }
708ca36c-cd47-401a-8e38-ce1c63599ddc
1
public int[] StringToIntArray(String range) { List<Integer> lst = StringToList(range); int[] arr = new int[lst.size()]; for (int i=0; i< arr.length; i++) { arr[i] = lst.get(i); } return arr; }
7fb17a38-0fd0-4c05-b7a2-4d0be68d7882
7
private void ok_buttonActionPerformed(ActionEvent evt) {// GEN-FIRST:event_ok_buttonActionPerformed String first = first_name_field.getText(); String last = last_name_field.getText(); int id = Integer.parseInt(id_field.getText()); String username = username_field.getText(); String pass = password_field.getText(); boolean block_value = block_account_checkbox.isSelected(); Account creation; String account_select = account_type_dropdown.getSelectedItem() .toString(); if (account_select.equalsIgnoreCase("System Admin")) creation = new SystemAdmin(first, last, id, username, pass); else if (account_select.equalsIgnoreCase("Administrator")) creation = new AcademicAdmin(first, last, id, username, pass); else if (account_select.equalsIgnoreCase("Assistant Admin")) creation = new AssistantAdmin(first, last, id, username, pass); else if (account_select.equalsIgnoreCase("Instructor")) creation = new Instructor(first, last, id, username, pass); else if (account_select.equalsIgnoreCase("TA")) creation = new TATM(first, last, id, username, pass); else { // Incorrect account type, this should never happen creation = null; System.out.println("Is it Christmas right now? Because you have an" + " error message to unwrap."); } if (modify_existing_checkbox.isSelected()) { creation.setBlocked(block_value); AccountAccess.modifyAccount(existing_account_dropdown .getSelectedItem().toString(), creation); if (!block_value) AccountAccess.successfulLogin(username); System.out.println("Account " + username_field.getText() + " modified."); } else { System.out.println("Creating " + account_select + " type account."); AccountAccess.createAccount(creation); JOptionPane.showMessageDialog(this, "Account Created: " + username_field.getText()); } setOkToNav(); GUIUtils.getMasterFrame(this).goBack(); }//GEN-LAST:event_ok_buttonActionPerformed
18aa6287-93ad-419b-81c0-6bf64215f5bd
0
public byte getTypeId() { return (byte)typeId; }
f40b0b9f-83cf-47ee-ae60-49284f72fe7b
6
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (flipHorizontally ? 1231 : 1237); result = prime * result + (flipVertically ? 1231 : 1237); result = prime * result + (objToBgPriority ? 1231 : 1237); result = prime * result + ((palette == null) ? 0 : palette.hashCode()); result = prime * result + ((upperTile == null) ? 0 : upperTile.hashCode()); result = prime * result + ((lowerTile == null) ? 0 : lowerTile.hashCode()); result = prime * result + x; result = prime * result + y; return result; }
c6030660-4bfc-43d1-9f57-40e8c175b7a1
9
public GOEPanel() { m_Backup = copyObject(m_Object); m_ClassNameLabel = new JLabel("None"); m_ClassNameLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); m_ChildPropertySheet = new PropertySheetPanel(); m_ChildPropertySheet.addPropertyChangeListener (new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { m_Support.firePropertyChange("", null, null); } }); m_OpenBut = new JButton("Open..."); m_OpenBut.setToolTipText("Load a configured object"); m_OpenBut.setEnabled(true); m_OpenBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object object = openObject(); if (object != null) { // setValue takes care of: Making sure obj is of right type, // and firing property change. setValue(object); // Need a second setValue to get property values filled in OK. // Not sure why. setValue(object); } } }); m_SaveBut = new JButton("Save..."); m_SaveBut.setToolTipText("Save the current configured object"); m_SaveBut.setEnabled(true); m_SaveBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveObject(m_Object); } }); m_okBut = new JButton("OK"); m_okBut.setEnabled(true); m_okBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { m_Backup = copyObject(m_Object); if ((getTopLevelAncestor() != null) && (getTopLevelAncestor() instanceof Window)) { Window w = (Window) getTopLevelAncestor(); w.dispose(); } } }); m_cancelBut = new JButton("Cancel"); m_cancelBut.setEnabled(true); m_cancelBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (m_Backup != null) { m_Object = copyObject(m_Backup); // To fire property change m_Support.firePropertyChange("", null, null); m_ObjectNames = getClassesFromProperties(); updateObjectNames(); updateChildPropertySheet(); } if ((getTopLevelAncestor() != null) && (getTopLevelAncestor() instanceof Window)) { Window w = (Window) getTopLevelAncestor(); w.dispose(); } } }); setLayout(new BorderLayout()); if (m_canChangeClassInDialog) { JButton chooseButton = createChooseClassButton(); JPanel top = new JPanel(); top.setLayout(new BorderLayout()); top.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); top.add(chooseButton, BorderLayout.WEST); top.add(m_ClassNameLabel, BorderLayout.CENTER); add(top, BorderLayout.NORTH); } else { add(m_ClassNameLabel, BorderLayout.NORTH); } add(m_ChildPropertySheet, BorderLayout.CENTER); // Since we resize to the size of the property sheet, a scrollpane isn't // typically needed // add(new JScrollPane(m_ChildPropertySheet), BorderLayout.CENTER); JPanel okcButs = new JPanel(); okcButs.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); okcButs.setLayout(new GridLayout(1, 4, 5, 5)); okcButs.add(m_OpenBut); okcButs.add(m_SaveBut); okcButs.add(m_okBut); okcButs.add(m_cancelBut); add(okcButs, BorderLayout.SOUTH); if (m_ClassType != null) { m_ObjectNames = getClassesFromProperties(); if (m_Object != null) { updateObjectNames(); updateChildPropertySheet(); } } }
e06cf642-5c93-4d0b-b2c5-7ce9fa6ea689
2
public static void main(String[] args) { MatrixCornerProblem matrixCornerProblem = new MatrixCornerProblem(); System.out.println(" Matrix is ******************* "); matrixCornerProblem.display(); if (matrixCornerProblem.rows <= 0 || matrixCornerProblem.columns <= 0) { System.out.println("Cant perform "); return; } System.out.println("Min sum is " + matrixCornerProblem.findMinimumValueAndReachCorner(0, 0)); }
a7c7707a-ddd4-4ed2-b73c-b08fde80e02a
7
@Override public void startCharacter(MOB mob, boolean isBorrowedClass, boolean verifyOnly) { if(!verifyOnly) { mob.setPractices(mob.getPractices()+getPracsFirstLevel()); mob.setTrains(mob.getTrains()+getTrainsFirstLevel()); grantAbilities(mob,isBorrowedClass); CMLib.achievements().grantAbilitiesAndExpertises(mob); } if((mob!=null) && (CMSecurity.isASysOp(mob) || CMSecurity.isAllowedEverywhere(mob, CMSecurity.SecFlag.ALLSKILLS))) { final PlayerStats pStats = mob.playerStats(); if((pStats != null)&&(!pStats.isOnAutoInvokeList("ANYTHING"))) { for(String s : CMProps.getListFileVarSet(CMProps.ListFile.WIZ_NOAUTOINVOKE)) pStats.addAutoInvokeList(s); } } }
02a6cb8d-8193-4416-8831-d99a4fa075b8
7
public void write(String fileName) throws IOException { RandomAccessFile out = null; try { out = new RandomAccessFile(fileName, "rw"); out.setLength(0); FileChannel file = out.getChannel(); long offset = 0L; int headerSize = 4 * 3; ByteBuffer header = file.map(FileChannel.MapMode.READ_WRITE, offset, headerSize); header.putInt(FSA_MAGIC); header.putInt(transSymbols.length); header.putInt(startState); offset += headerSize; for (int pos = 0; pos < transSymbols.length; ) { int chunk = pos + CHUNK_SIZE < transSymbols.length ? CHUNK_SIZE : transSymbols.length - pos; ByteBuffer buf = file.map(FileChannel.MapMode.READ_WRITE, offset, chunk); buf.put(transSymbols, pos, chunk); pos += chunk; offset += chunk; } for (int pos = 0; pos < transStates.length; ) { int chunk = pos + CHUNK_SIZE < transStates.length ? CHUNK_SIZE : transSymbols.length - pos; ByteBuffer buf = file.map(FileChannel.MapMode.READ_WRITE, offset, chunk * 4); for (int i = pos; i < pos + chunk; ++i) { buf.putInt(transStates[i]); } pos += chunk; offset += chunk * 4; } file.close(); } catch (IOException e) { throw e; } finally { if (out != null) out.close(); } }
9cd6c954-7f36-49e2-bd3f-5818f4f12952
1
public void acceptRequest(AsynchronousSocketChannel socket) { Worker worker = workers.poll(); if (worker == null) { requests.add(socket); } else { synchronized (worker) { worker.setSocket(socket); worker.notify(); } } }
e6b47ca4-a20d-48dd-8fef-68f6ffb16f7d
3
private void bFs(Grafo g, int s){ ArrayList<Integer> cola= new ArrayList<Integer>(); marked[s]= true; cola.add(s); while(cola.size()!=0){ int saliente= cola.remove(0); for(int i : g.adj(saliente)){ if(!marked[i]){ edgeTo[i]=saliente; marked[i]=true; cola.add(i); } } } }
96f5b08f-8969-41e1-aacf-e6044d430f09
7
public void generationTrajetsMultiples(Information<Float> information){ float signauxRetarde[][] = new float[nbTrajetIndirect][]; float signalFinal[]; int decaTempoMax = 0; informationEmise = new Information<Float>(); // Recherche du plus grand decalage afin de determiner la taille du signal d'arrivé for(int i = 0; i < nbTrajetIndirect; i++){ if (decaTempo[i] > decaTempoMax)decaTempoMax = decaTempo[i]; } signalFinal = new float[information.nbElements() + decaTempoMax]; // Generation de nbTrajetIndirect signaux for(int i = 0; i< nbTrajetIndirect; i++){ // Instanciation du ieme trajet avec une taille de nbElement + decalage signauxRetarde[i] = new float[information.nbElements() + decaTempo[i]]; // Remplissage trajet retardé en fonction de l'amplitude relavite au signal initial for(int j = 0; j < signauxRetarde[i].length; j ++){ if(j < decaTempo[i]) signauxRetarde[i][j] = 0f; else signauxRetarde[i][j] = amplRel[i] * information.iemeElement(j - decaTempo[i]).floatValue(); signalFinal[j] += signauxRetarde[i][j]; // Somme des trajets retardés } } // Generation information émise en faisant la somme des trajets retardés au signal initial for(int i = 0; i < information.nbElements() + decaTempoMax; i++){ if(i < information.nbElements()) informationEmise.add(signalFinal[i] + information.iemeElement(i)); else informationEmise.add(signalFinal[i]); } }
2c0a9db1-303c-4f78-b3fe-eef649d1135a
1
public ArrayList<String> getCourseNames() { ArrayList<String> courseNames = new ArrayList<String>(); for (String name : courses.keySet()) { courseNames.add(name); } return courseNames; }
6584b415-0625-43b3-8048-d745d0a949c2
2
private void closeSocket(){ if (socket != null) { try { socket.close(); } catch (IOException e1) { e1.printStackTrace(); } } }
f915d5df-f8cd-4206-bb1d-0c28b1c5c4b4
2
@Override public void handleRequest(int request) { if (request == 2) { System.out.println("ConcreteHandlerB handleRequest " + request); } else if (mSuccessor != null) { mSuccessor.handleRequest(request); } }
60c2370a-9c52-49c0-b029-3b32ba3dd574
9
public static void main(String[] args) { try { BaseL8Manager l8Manager = new BaseL8Manager(); L8 l8 = l8Manager.createEmulatedL8(); //L8 l8 = l8Manager.reconnectDevice("4c9b26176af0768e562837eeebdc227d"); l8.clearMatrix(); l8.setLED(0, 3, Color.CYAN); l8.readLED(0, 3); l8.clearLED(0, 3); Color[][] matrix = new Color[8][8]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { matrix[i][j] = Color.RED; } } l8.setMatrix(matrix); l8.readMatrix(); l8.setSuperLED(Color.BLUE); l8.readSuperLED(); l8.clearSuperLED(); l8.enableSensor(Sensor.AMBIENTLIGHT); l8.disableSensor(Sensor.PROXIMITY); List<Sensor.Status> sensors = l8.readSensors(); System.out.println(sensors); Sensor.TemperatureStatus temperature = (Sensor.TemperatureStatus)l8.readSensor(Sensor.TEMPERATURE); System.out.println("read temperature sensor: " + temperature); Sensor.ProximityStatus proximity = (Sensor.ProximityStatus)l8.readSensor(Sensor.PROXIMITY); System.out.println("read proximity sensor: " + proximity); Sensor.AccelerationStatus acceleration = (Sensor.AccelerationStatus)l8.readSensor(Sensor.ACCELERATION); System.out.println("read acceleration sensor: " + acceleration); System.out.println("bluetooth enabled? " + l8.isBluetoothEnabled()); System.out.println("battery status: " + l8.getBatteryStatus()); l8.setLED(4, 5, Color.LIGHT_GRAY); l8.setLED(7, 6, Color.BLUE); l8.setLED(1, 3, Color.GREEN); l8.getButton(); l8.getMemorySize(); l8.getFreeMemory(); l8.getVersion(); System.out.println("id: " + l8.getId()); Color[][] matrix0 = new Color[8][8]; for (int i = 0; i < matrix0.length; i++) { for (int j = 0; j < matrix0[i].length; j++) { matrix0[i][j] = Color.RED; } } L8.Frame frame0 = new L8.Frame(matrix0, 100); Color[][] matrix1 = new Color[8][8]; for (int i = 0; i < matrix1.length; i++) { for (int j = 0; j < matrix1[i].length; j++) { matrix1[i][j] = Color.YELLOW; } } L8.Frame frame1 = new L8.Frame(matrix1, 200); Color[][] matrix2 = new Color[8][8]; for (int i = 0; i < matrix2.length; i++) { for (int j = 0; j < matrix2[i].length; j++) { matrix2[i][j] = Color.GREEN; } } L8.Frame frame2 = new L8.Frame(matrix2, 400); List<L8.Frame> frames = new ArrayList<L8.Frame>(); frames.add(frame0); frames.add(frame1); frames.add(frame2); L8.Animation animation = new L8.Animation(frames); l8.setAnimation(animation); } catch (L8Exception e) { e.printStackTrace(); } }
cf664c8b-1f7a-45c1-a1cc-c0c03fa87ad6
9
private static boolean afterSpace(Node node) { Node prev; int c; if (node == null || node.tag == null || !((node.tag.model & Dict.CM_INLINE) != 0)) return true; prev = node.prev; if (prev != null) { if (prev.type == Node.TextNode && prev.end > prev.start) { c = ((int)prev.textarray[prev.end - 1]) & 0xFF; // Convert to unsigned. if (c == 160 || c == ' ' || c == '\n') return true; } return false; } return afterSpace(node.parent); }
8b23b703-3e3d-4ceb-80e4-70a6fe5237e9
2
@Override protected boolean next() { switch(state()) { case size_ready: return size_ready (); case message_ready: return message_ready (); default: return false; } }
9cfe71a4-8585-4f08-8532-04ff797c5c59
3
public static void main(String[] args) { LOG.info("Args: "); int i = 0; for (String arg : args) { LOG.info("{}:{}", i++, arg); } // create Options object Options options = new Options(); options.addOption("outdir", true, "the output dir"); options.addOption("?", false, "print this message"); options.addOption("nolog", false, "do not produce a log file"); options.addOption("nofiltering", false, "do not filter the data"); options.addOption("array_id", true, "the file to process"); try { CommandLineParser parser = new GnuParser(); // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption("?")) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ProduceCSV", options); return; } setup(line); } catch (Throwable e) { // oops, something went wrong LOG.error("Exception Caught", e); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ProduceCSV Error", options); return; } ProduceCSV produceCSV = new ProduceCSV(); produceCSV.run(); }
751cc709-bbe3-4683-b4e2-2cbe4efde344
6
public Dimension minimumLayoutSize(Container parent) { //System.err.println("minimumLayoutSize"); synchronized (parent.getTreeLock()) { Insets insets = parent.getInsets(); int ncomponents = parent.getComponentCount(); int nrows = getRows(); int ncols = getColumns(); if (nrows > 0) { ncols = (ncomponents + nrows - 1) / nrows; } else { nrows = (ncomponents + ncols - 1) / ncols; } int[] w = new int[ncols]; int[] h = new int[nrows]; for (int i = 0; i < ncomponents; i ++) { int r = i / ncols; int c = i % ncols; Component comp = parent.getComponent(i); Dimension d = comp.getMinimumSize(); if (w[c] < d.width) { w[c] = d.width; } if (h[r] < d.height) { h[r] = d.height; } } int nw = 0; for (int j = 0; j < ncols; j ++) { nw += w[j]; } int nh = 0; for (int i = 0; i < nrows; i ++) { nh += h[i]; } return new Dimension(insets.left + insets.right + nw + (ncols-1)*getHgap(), insets.top + insets.bottom + nh + (nrows-1)*getVgap()); } }
2a0e1b9d-7423-460b-8786-09db45d69650
2
private double getExchangeRateFromDB(Currency toCurrency, Currency fromCurrency, Connection connection, Date date) { try { String query = "select cambio from historico_cambios " + "where divisa_desde='" + fromCurrency.getCode() + "' and divisa_a='" + toCurrency.getCode() + "'"; ResultSet resulSet; resulSet = connection.createStatement().executeQuery(query); while (resulSet.next()) return resulSet.getDouble(1); } catch (SQLException ex) { ex.getMessage(); } return 0; }
64816a58-5752-4a74-a2de-96fe554d0439
6
private void calculateResult() { int[] tmp = new int[options.length]; for (int i = 0; i < votes.length; i++) { if (votes[i].decision != -1) { tmp[votes[i].decision]++; } } int max = -1; boolean onlyMax = true; int maxID = 0; for (int i = 0; i < tmp.length; i++) { if (max == tmp[i]) { onlyMax = false; } else if (tmp[i] > max) { max = tmp[i]; maxID = i; onlyMax = true; } } if (onlyMax) { result = options[maxID]; } else { result = null; } }
2eac2212-5976-406b-971a-517b34318f46
7
public boolean canPlaceBlockAt(World par1World, int par2, int par3, int par4) { int i = par1World.getBlockId(par2, par3 - 1, par4); if (i == blockID) { return true; } if (i != Block.grass.blockID && i != Block.dirt.blockID && i != Block.sand.blockID) { return false; } if (par1World.getBlockMaterial(par2 - 1, par3 - 1, par4) == Material.water) { return true; } if (par1World.getBlockMaterial(par2 + 1, par3 - 1, par4) == Material.water) { return true; } if (par1World.getBlockMaterial(par2, par3 - 1, par4 - 1) == Material.water) { return true; } return par1World.getBlockMaterial(par2, par3 - 1, par4 + 1) == Material.water; }
c9a592e0-37b4-45c3-ad9e-7d4c57820a20
4
public void welcome() { while (true) { Socket s = null; try { s = ss.accept(); System.out.println("Port:" + s.getPort()); System.out.println("Address:" + s.getInetAddress()); System.out.println("LocalPort:" + s.getLocalPort()); System.out.println("LocalAddress:" + s.getLocalAddress()); Scanner stdIn = new Scanner(System.in); ChatSession session = new ChatSession(s, this); synchronized (this) { sessions.add(session); } session.start(); } catch (IOException e) { System.out.print(e); try { if (s != null) { s.close(); } } catch (IOException ee) { } } } }
f4fead61-390d-4cf0-bd15-6fed20db8e53
1
public boolean isDone() { if(null == threadVar.get()) { return true; } return false; }
428bb4fd-b1c1-451d-9478-6f7c21f94371
4
public static void saveCopy(MediaCopy mc){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { conn.setAutoCommit(false); PreparedStatement stmnt = conn.prepareStatement("INSERT INTO MediaCopies(media_id) VALUES(?)"); stmnt.setInt(1, mc.getMediaID()); stmnt.execute(); conn.commit(); conn.setAutoCommit(true); }catch(SQLException e){ System.out.println("insert fail!! - " + e); } }
9fb00efd-39be-4612-afb8-1597f4103a0d
1
public boolean Equals(Vector2 v) { return (v.X == X && v.Y == Y); }
e06082a1-040b-412e-b1e7-33a5fcd43352
8
@Override public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_1: handleResponse(1); break; case KeyEvent.VK_2: handleResponse(2); break; case KeyEvent.VK_3: handleResponse(3); break; case KeyEvent.VK_4: handleResponse(4); break; case KeyEvent.VK_CAPS_LOCK: break; case KeyEvent.VK_SCROLL_LOCK: break; case KeyEvent.VK_NUM_LOCK: break; case KeyEvent.VK_Q: state = State.HOME; correct = 0; incorrect = 0; currentQuestion = null; setHome(); break; default: handleResponse(0); break; } }
d83a178e-e58c-4cb3-a43c-ac45e91c9a91
1
private void setActivePlayer(Player activePlayer) { if (activePlayer == null) throw new IllegalArgumentException("Player can't be null!"); this.activePlayer = activePlayer; }
4c186b3f-2499-46fc-b1ad-0e455dcc77ef
8
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; if(target.fetchEffect(ID())!=null) { mob.tell(target,null,null,L("<S-NAME> <S-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> <T-IS-ARE> protected from prayers."):L("^S<S-NAME> chant(s) for a ward against prayers around <T-NAMESELF>.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } } else beneficialWordsFizzle(mob,target,L("<S-NAME> chant(s) for a ward, but nothing happens.")); return success; }
3df9d016-4fac-4785-925d-6f18619654fd
5
@Override public void doUniformBlur() { if (imageManager.getBufferedImage() == null) return; WritableRaster raster = imageManager.getBufferedImage().getRaster(); double[][] newPixels = new double[raster.getWidth()][raster.getHeight()]; for (int x = 1; x < raster.getWidth() - 1; x++) { for (int y = 1; y < raster.getHeight() - 1; y++) { double total = 0; total += raster.getPixel(x+1, y+1, new double[3])[0]; total += raster.getPixel(x+1, y-1, new double[3])[0]; total += raster.getPixel(x, y+1, new double[3])[0]; total += raster.getPixel(x, y-1, new double[3])[0]; total += raster.getPixel(x-1, y+1, new double[3])[0]; total += raster.getPixel(x-1, y-1, new double[3])[0]; total += raster.getPixel(x, y, new double[3])[0]; total += raster.getPixel(x+1, y, new double[3])[0]; total += raster.getPixel(x-1, y, new double[3])[0]; double average = total/9; newPixels[x][y] = average; } } for (int x = 1; x < raster.getWidth() - 1; x++) { for (int y = 1; y < raster.getHeight() - 1; y++) { double[] pixel = new double[3]; pixel[0] = pixel[1] = pixel[2] = newPixels[x][y]; raster.setPixel(x, y, pixel); } } GUIFunctions.refresh(); }
6a7cb4ed-6a6a-4978-a1e5-add68f667cbd
6
public void overwriteTRNS(byte r, byte g, byte b) { if(hasAlphaChannel()) { throw new UnsupportedOperationException("image has an alpha channel"); } byte[] pal = this.palette; if(pal == null) { transPixel = new byte[] { 0, r, 0, g, 0, b }; } else { paletteA = new byte[pal.length/3]; for(int i=0,j=0 ; i<pal.length ; i+=3,j++) { if(pal[i] != r || pal[i+1] != g || pal[i+2] != b) { paletteA[j] = (byte)0xFF; } } } }
3c387a9d-c932-4dc8-bec6-be4ed34a6911
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RemoteAddress other = (RemoteAddress) obj; if (address == null) { if (other.address != null) return false; } else if (!address.equals(other.address)) return false; if (portNumber != other.portNumber) return false; return true; }
c5d4e0bf-e2be-4550-b485-51f24c1a196b
7
public T run() { int currentIteration = 0; long waitTimeIfTimeout = 5; while (true) { Transaction txn = datastore.beginTransaction(); try { return txnBlock(txn); } catch (ConcurrentModificationException cme) { if (currentIteration == retryCount) { logger.warning("Failed with ConcurrentModificationException after " + retryCount + " retries: " + cme.getMessage()); throw cme; } logger.warning("ConcurrentModificationException caught on iteration " + currentIteration + ", retrying."); } catch (DatastoreTimeoutException dte) { if (currentIteration == retryCount) { logger.warning("Failed with DatastoreTimeoutException after " + retryCount + " retries: " + dte.getMessage()); throw dte; } logger.warning("DatastoreTimeoutException caught on iteration " + currentIteration + ", retrying."); //sleep at most 10 secs, but we wait longer on successive failures try { Thread.sleep(Math.min(waitTimeIfTimeout, 10000)); } catch (InterruptedException ie) { /* ok */ } waitTimeIfTimeout *= waitTimeIfTimeout; } finally { if (txn.isActive()) { txn.rollback(); } } //if here, we failed but we're retrying currentIteration++; } }
e86be784-18a0-49fa-bd61-02d29adbe7db
6
@Override public boolean shadow_hit(Ray ray, FloatRef tmin) { if (bounds != null && !bounds.hit(ray)) return false; float tMin = Float.MAX_VALUE; boolean hit = false; for (GeometricObject obj : objects) { FloatRef fr = new FloatRef(); if (obj.shadow_hit(ray, fr) && fr.value < tMin) { hit = true; tMin = fr.value; } } if (hit) { tmin.value = tMin; } return hit; }