text
stringlengths
14
410k
label
int32
0
9
@Override public void undo() { this.to.removePiece(this.promotionedPiece); this.to.addPiece(this.capturedPiece); this.from.addPiece(this.piece); this.piece.decreaseMoveCount(); }
0
@Override public int print(Graphics g, PageFormat pf, int page) throws PrinterException { // We have only one page, and 'page' // is zero-based if (page > 0) { return NO_SUCH_PAGE; } // User (0,0) is typically outside the // imageable area, so we must translate // by the X and Y values in the PageFormat // to avoid clipping. Graphics2D g2d = (Graphics2D)g; g2d.translate(pf.getImageableX(), pf.getImageableY()); // Now we perform our rendering g.drawString("Hello world!", 100, 100); // tell the caller that this page is part // of the printed document return PAGE_EXISTS; }
1
public static void main(String s[]) { testLoop: for (int bits = MIN_BITS ; bits <= MAX_BITS ; bits++) { final int period = (1 << bits) - 1 ; final boolean reg[] = new boolean[period] ; final LFSR lfsr = new LFSR(bits, 1) ; I.say("\nBeginning test for "+bits+" bit LFSR...") ; // // Begin an exhaustive check. for (int i = 0 ; i++ <= period ;) { final int val = lfsr.nextVal() ; if (reg[val - 1] == true) { I.say("Duplicated value after "+i+" steps- ") ; if (i < period) I.add("___TEST FAILED___") ; else I.add("Test successful!") ; continue testLoop ; } else reg[val - 1] = true ; } I.say("Test failed- seed value does not recur.") ; } }
4
public void testIsAfter_YMD() { YearMonthDay test1 = new YearMonthDay(2005, 6, 2); YearMonthDay test1a = new YearMonthDay(2005, 6, 2); assertEquals(false, test1.isAfter(test1a)); assertEquals(false, test1a.isAfter(test1)); assertEquals(false, test1.isAfter(test1)); assertEquals(false, test1a.isAfter(test1a)); YearMonthDay test2 = new YearMonthDay(2005, 7, 2); assertEquals(false, test1.isAfter(test2)); assertEquals(true, test2.isAfter(test1)); YearMonthDay test3 = new YearMonthDay(2005, 7, 2, GregorianChronology.getInstanceUTC()); assertEquals(false, test1.isAfter(test3)); assertEquals(true, test3.isAfter(test1)); assertEquals(false, test3.isAfter(test2)); try { new YearMonthDay(2005, 7, 2).isAfter(null); fail(); } catch (IllegalArgumentException ex) {} }
1
public void peliSykli() { while (jatkuu) { try { Thread.sleep(viive); } catch (Exception e) { status.setText("Jotain meni vikaan..."); } if (pause) { while (pause) { status.setText("Peli pysäytetty, paina P jatkaaksesi"); } status.setText("Paina P pysäyttääksesi pelin"); } if (this.onkoAI){ this.ai.teeSiirto(); } this.putoava.putoa(); if (!putoava.putoaa) { // kun putoava muodostelma törmää, sen palikat lisätään pelipalikoihin lisaaPalikatPeliin(putoava.getPalikat()); luoUusiPutoava(); // luodaan uusi putoava muodostelma List<Integer> tayttyneet = tarkastaTaydetRivit(); if (tayttyneet != null) { //tarkastetaan tuliko rivejä täyteen poistaTaydetRivit(tayttyneet); } } this.pelialue.repaint(); } status.setText("Peli päättynyt! Enter aloittaa uuden pelin"); }
7
public String openSEND() throws IOException{ Transporte t = new Transporte(initTransporteACKeSYN); Transporte t1 = new Transporte(initTransporteACKeSYN); seq = 0; //numero de sequencia por defeito para o cliente mtu = 1400; win = MINWIN; //criar SYN (dados = porta que recebe) t.createTransportePacket("SYN", 0, 2, win, mtu, seq, 0, Transporte.intToByte(this.receiveSocket.getLocalPort(), 2)); Console_println(t.toString()); //teste //envia SYN e espera por SYN_ACK RTT = RTT_INIT; do{ RTT--; t.enviarTransporte(this.sendSocket, this.sendIPAddress, this.sendPort); Console_println(">SYN enviado"+ " para "+this.sendIPAddress.getHostAddress()+":"+this.sendPort); this.iniciar_smallTimeOut(boundedB,timeout,SMALLTIMEOUT_OPEN*4); Console_println(">a espera de SYN_ACK"); t1 = recebeuACKde(t, this.sendIPAddress); if(timeout.value==1) Console_println("timeout"); if(RTT<0) return rtt_error; }while(timeout.value==1 || t1==null); this.sendPort = Transporte.byteToInt(t1.getDados(),2); //muda a porta de envio Transporte syn = (Transporte) t.clone(); //cria copia do SYN //criar ACK (size=1) de SYN_ACK int x = Transporte.byteToInt(t1.getSeq(), 2) + 1; //num_seq(SYN_ACK) + 1 t.createTransportePacket("ACK", 0, 1, win, mtu, seq, x, new byte[1]); Console_println(t.toString()); //teste //envia ACK (size=1) de SYN_ACK RTT = RTT_INIT; do{ RTT--; t.enviarTransporte(this.sendSocket, this.sendIPAddress, this.sendPort); Console_println(">ACK enviado"); this.iniciar_smallTimeOut(boundedB,timeout,SMALLTIMEOUT_OPEN2); //timeout superior ao do outro terminal Console_println(">a espera de SYN_ACK repetido"); t1 = recebeuACKde(syn, this.sendIPAddress); if(timeout.value==1) Console_println("timeout"); if(RTT<0) return rtt_error; }while(t1!=null && timeout.value==0); return sucesso; }
8
private static void removeFromTrees(TreeNode treeNode, List trees) { boolean found = false; // without this initialization, I get a compilation error // that says subTree may not have been initialized Tree subTree = new Tree(null, null, null); for (Iterator iter = trees.iterator(); iter.hasNext(); ) { subTree = (Tree)iter.next(); if (treeNode.equals(subTree.getRoot())) { found = true; break; } } if (found == true) { // || (subTree instanceof Tree)) { trees.remove(subTree); } }
3
@Override public Event next() { String input = null; try { input = br.readLine(); } catch (IOException e) { } if(input == null || input.equals("")){ return new DefaultState(as); } else{ return new UserHomeState(as, input); } }
3
public List<BipolarQuestion> getBipolarList(String oppositeFileName, String teamType) { List<BipolarQuestion> bipolarQuestionList = new ArrayList<BipolarQuestion>(); Element bipolarQuestionE; BipolarQuestion bipolarQuestion; BipolarQuestionDao parentBipoarQuestion = new BipolarQuestionDao(oppositeFileName); List<BipolarQuestion> bipolarQuestionParentList = parentBipoarQuestion.getBipolarParentList(teamType); BipolarQuestion parent = null; for (Iterator i = root.elementIterator("bipolarQuestion"); i.hasNext();) { bipolarQuestionE = (Element)i.next(); if (bipolarQuestionE.element("isDelete").getText().equals("false")) { String id = bipolarQuestionE.element("id").getText() , title = bipolarQuestionE.element("title").getText() , description = bipolarQuestionE.element("description").getText() , type = bipolarQuestionE.element("type").getText() , timeAdded = bipolarQuestionE.element("timeAdded").getText() , name = bipolarQuestionE.element("name").getText() , debateId = bipolarQuestionE.element("debateId").getText() , dialogState = bipolarQuestionE.elementText("dialogState") , parentId = bipolarQuestionE.elementText("parent"); for (int j = 0; j < bipolarQuestionParentList.size(); j++) { if (bipolarQuestionParentList.get(j).getId().equals(parentId)) { parent = bipolarQuestionParentList.get(j); } } bipolarQuestion = new BipolarQuestion(id, title, description, type , timeAdded, parent, name, debateId, dialogState); bipolarQuestionList.add(bipolarQuestion); } } return bipolarQuestionList; }
4
public int h() { return _map == null?0:_map.length; }
1
public List<Location> adjacentLocations(Location location) { assert location != null : "Null location passed to adjacentLocations"; // The list of locations to be returned. List<Location> locations = new LinkedList<Location>(); if(location != null) { int row = location.getRow(); int col = location.getCol(); for(int roffset = -1; roffset <= 1; roffset++) { int nextRow = row + roffset; if(nextRow >= 0 && nextRow < depth) { for(int coffset = -1; coffset <= 1; coffset++) { int nextCol = col + coffset; // Exclude invalid locations and the original location. if(nextCol >= 0 && nextCol < width && (roffset != 0 || coffset != 0)) { locations.add(new Location(nextRow, nextCol)); } } } } // Shuffle the list. Several other methods rely on the list // being in a random order. Collections.shuffle(locations, rand); } return locations; }
9
public void setColor(int i) { String strat = agents[i].getStrategy(); for(int str = 0; str < scape.strategies.length; str++) { if(strat.equals(scape.strategies[str])) { style[(i + 2)] = colors[str]; } } }
2
public static NumberWrapper plusComputation(NumberWrapper x, NumberWrapper y) { { double floatresult = Stella.NULL_FLOAT; { Surrogate testValue000 = Stella_Object.safePrimaryType(x); if (Surrogate.subtypeOfIntegerP(testValue000)) { { IntegerWrapper x000 = ((IntegerWrapper)(x)); { Surrogate testValue001 = Stella_Object.safePrimaryType(y); if (Surrogate.subtypeOfIntegerP(testValue001)) { { IntegerWrapper y000 = ((IntegerWrapper)(y)); return (IntegerWrapper.wrapInteger(((int)(x000.wrapperValue + y000.wrapperValue)))); } } else if (Surrogate.subtypeOfFloatP(testValue001)) { { FloatWrapper y000 = ((FloatWrapper)(y)); floatresult = x000.wrapperValue + y000.wrapperValue; } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + testValue001 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } } } } else if (Surrogate.subtypeOfFloatP(testValue000)) { { FloatWrapper x000 = ((FloatWrapper)(x)); { Surrogate testValue002 = Stella_Object.safePrimaryType(y); if (Surrogate.subtypeOfIntegerP(testValue002)) { { IntegerWrapper y000 = ((IntegerWrapper)(y)); floatresult = x000.wrapperValue + y000.wrapperValue; } } else if (Surrogate.subtypeOfFloatP(testValue002)) { { FloatWrapper y000 = ((FloatWrapper)(y)); floatresult = x000.wrapperValue + y000.wrapperValue; } } else { { OutputStringStream stream001 = OutputStringStream.newOutputStringStream(); stream001.nativeStream.print("`" + testValue002 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream001.theStringReader()).fillInStackTrace())); } } } } } else { { OutputStringStream stream002 = OutputStringStream.newOutputStringStream(); stream002.nativeStream.print("`" + testValue000 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream002.theStringReader()).fillInStackTrace())); } } } return (FloatWrapper.wrapFloat(floatresult)); } }
6
Announce(SharedTorrent torrent, byte[] id, InetSocketAddress address) { //> obfuscated handshake extension this.torrent = torrent; this.id = id; this.address = address; this.listeners = new HashSet<AnnounceResponseListener>(); this.thread = null; this.register(this); }
0
public static void readFile(String filePath) { lineCode lineType = lineCode.amount; try { FileInputStream fstream = new FileInputStream(filePath); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { if (noOfCases == 0) { noOfCases = Integer.parseInt(strLine); creditList = new ArrayList<Integer>(noOfCases); noOfitemList = new ArrayList<Integer>(noOfCases); } else { if (lineType == lineCode.amount) { creditList.add(Integer.parseInt(strLine)); lineType = lineCode.noOfItems; } else if (lineType == lineCode.noOfItems) { noOfitemList.add(Integer.parseInt(strLine)); lineType = lineCode.items; } else if (lineType == lineCode.items) { String string = strLine; String[] itemInt = string.split(" "); for (String itemString : itemInt) { itemslist.add(Integer.parseInt(itemString)); } lineType = lineCode.amount; } } } in.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } }
7
public static ActionCom SelectActionComById(int id) throws SQLException { String query = null; ActionCom Action = new ActionCom(); ResultSet resultat; try { query = "SELECT * from ACTION_COM where ID_ACTION=? "; PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query); pStatement.setInt(1, id); resultat = pStatement.executeQuery(); while (resultat.next()) { Action = new ActionCom(resultat.getInt("ID_ACTION"), resultat.getInt("ID_ACTION_TYPE"), resultat.getInt("ID_INTERLOCUTEUR"), resultat.getDate("ACTDATE"),resultat.getString("ACTCOMM")); } } catch (SQLException ex) { Logger.getLogger(RequetesActionCom.class.getName()).log(Level.SEVERE, null, ex); } return Action; }
2
public void undo() { if (patchIndex == 0) { return; } UndoPatch p = undoPatches.get(--patchIndex); // Reverse patch int prow; for (prow = 0; prow < p.patchText.length; prow++) { if (prow >= p.oldText.length) { for (int da = p.patchText.length - prow; da > 0; da--) { code.remove(p.startRow + prow); } break; } code.set(p.startRow + prow, new Line(p.oldText[prow])); } while (prow < p.oldText.length) { code.add(p.startRow + prow, new Line(p.oldText[prow])); prow++; } p.cbefore.replace(); fireLineChange(p.startRow, p.startRow + p.oldText.length); repaint(); }
5
private void processInput(String incoming) { String[] split = incoming.split(";"); String command = split[0].toUpperCase(); if (command.equals("NEWUSER")) { this.clientCon.getUser().addUser(split); } else if (command.equals("MESSAGE")) { } else if (command.equals("LOGIN")) { this.clientCon.getUser().verifyPassword(split[1], split[2]); } else if (command.equals("PING")) { } else if (command.equals("SEARCHUSER")) { } else if (command.equals("ADDFRIEND")) { } else if (command.equals("USERINFO")) { this.clientCon.getUser().sendUserInfo(); } /* * for (User c : Server.getUsers()) { ClientConnection out = * c.getClient(); if (c.getClient().getIn() != this) { * out.sendMessage(incoming); } } */ }
7
private static void initDisplay(boolean fullscreen) { DisplayMode chosenMode = null; try { DisplayMode[] modes = Display.getAvailableDisplayModes(); for (int i = 0; i < modes.length; i++) { if ((modes[i].getWidth() == targetWidth) && (modes[i].getHeight() == targetHeight)) { chosenMode = modes[i]; break; } } } catch (LWJGLException e) { Sys.alert("Error", "Unable to determine display modes."); System.exit(0); } // at this point if we have no mode there was no appropriate, let the user know // and give up if (chosenMode == null) { Sys.alert("Error", "Unable to find appropriate display mode."); System.exit(0); } try { Display.setDisplayMode(chosenMode); Display.setFullscreen(fullscreen); Display.setTitle("Secret Title"); Display.create(); } catch (LWJGLException e) { Sys.alert("Error", "Unable to create display."); System.exit(0); } }
6
public static double getDamageModSlash(WeaponMaterial type) { switch (type) { case COPPER: return 0.5; case BRONZE: return 0.75; case SILVER: return 0.5; case IRON: return 1; case STEEL: return 2; case ADAMANTINE: return 5; } return 1; }
6
public JLabel getjLabel3() { return jLabel3; }
0
public void buildBoard(){ Wall wall; Cheese cheese; Intersection intersection; for(int i = 0; i < levelData.length; i++){ switch(levelData[i]){ case 1: wall = new Wall(i-((i/21)*21),i/21); collisionList.add(wall); paintList.add(wall); break; case 2: cheese = new Cheese(i-((i/21)*21),i/21, false, this); collisionList.add(cheese); paintList.add(cheese); break; case 3: cheese = new Cheese(i-((i/21)*21),i/21, true, this); collisionList.add(cheese); paintList.add(cheese); break; case 4: pacman = new PacMan(i-((i/21)*21),i/21, this); paintList.add(pacman); break; case 5: intersection = new Intersection(i-((i/21)*21),i/21); intersectionList.add(intersection); paintList.add(intersection); break; case 6: intersection = new Intersection(i-((i/21)*21),i/21); intersectionList.add(intersection); paintList.add(intersection); cheese = new Cheese(i-((i/21)*21),i/21, false, this); collisionList.add(cheese); paintList.add(cheese); break; case 7: intersection = new Intersection(i-((i/21)*21),i/21); intersectionList.add(intersection); paintList.add(intersection); cheese = new Cheese(i-((i/21)*21),i/21, true, this); collisionList.add(cheese); paintList.add(cheese); break; case 8: ghost = new Ghost(i-((i/21)*21),i/21, this); collisionList.add(ghost); paintList.add(ghost); break; } } }
9
public List<Author> getAuthor() { if (author == null) { author = new ArrayList<Author>(); } return this.author; }
1
public static int bitonicSearch(Comparable[] a, int lo, int hi, Comparable t) { if (lo > hi) { return -1; } int mid = (lo + hi) / 2; final int compareToT = a[mid].compareTo(t); if (compareToT == 0) { return mid; } else if (compareToT == 1) { // mid bigger int find = bitonicSearch(a, mid + 1, hi, t); if (find == -1) { return bitonicSearch(a, lo, mid - 1, t); } else { return find; } } else { boolean leftMax = true; if (mid + 1 <= hi && a[mid].compareTo(a[mid + 1]) == -1) { leftMax = false; } if (leftMax) { return bitonicSearch(a, lo, mid - 1, t); } else { return bitonicSearch(a, mid + 1, hi, t); } } }
7
public void setAcceptByEmptyStack() { myAcceptance = EMPTY_STACK; }
0
public ColourMap(Colour[] colours, String name) { InitMap(); //First initialises array to null. if (colours.length <= m_mapSize) { /* Then if array parameter is <= max number of maps */ for (int i=0; i<colours.length; i++) { SetColour(i, colours[i]); //transfer colours to object array. } } else { /* If array parameter is > max number of maps */ for (int i=0; i<m_mapSize; i++) { /* transfer until max number is reached and ignore excess. */ SetColour(i, colours[i]); } } /* Finally, set the map name. */ SetMapName(name); }
3
protected boolean isPrimitiveWrapper(Object input) { return input instanceof Integer || input instanceof Boolean || input instanceof Character || input instanceof Byte || input instanceof Short || input instanceof Double || input instanceof Long || input instanceof Float; }
7
ArrayList<Row> getChildList() { return canHaveChildren() ? mChildren : null; }
1
static public void list() { String[] available_inputs = availableInputs(); String[] available_outputs = availableOutputs(); String[] unavailable = unavailableDevices(); if(available_inputs.length == 0 && available_outputs.length == 0 && unavailable.length == 0) return; System.out.println("\nAvailable MIDI Devices:"); if(available_inputs.length != 0) { System.out.println("----------Input----------"); for(int i = 0;i < available_inputs.length;i++) System.out.println("["+i+"] \""+available_inputs[i]+"\""); } if(available_outputs.length != 0) { System.out.println("----------Output----------"); for(int i = 0;i < available_outputs.length;i++) System.out.println("["+i+"] \""+available_outputs[i]+"\""); } if(unavailable.length != 0) { System.out.println("----------Unavailable----------"); for(int i = 0;i < unavailable.length;i++) System.out.println("["+i+"] \""+unavailable[i]+"\""); } }
9
public void stopListening() { listening = false; }
0
public void playerTurn() { int choice = 1; boolean readChoice = true; System.out.println("\n------------------------------"); System.out.println("PLAYER'S TURN"); System.out.println("------------------------------"); while (readChoice) { choice = getInt("Which column would you like to drop your piece into?"); if ( choice < 1 || choice > 7 ) { System.out.println( "Oops, that is not the number of a column. Enter 1-7."); } else if (colFull(choice)) { System.out.println( "Oops, that column is full, try again." ); } else { readChoice = false; placePiece( choice, _piece ); System.out.println( this ); _playerT = false; } } }
4
@Override public void validate() { if (platform == null) { addFieldError("platform", "Please Select Platorm"); addActionError("Please Select Platorm"); } if (location == null) { addFieldError("location", "Please Select Location"); addActionError("Please Select Location"); } if (gender == null) { addActionError("Please Select Gender"); } if (age == null) { addActionError("Please Select Age"); } }
4
static boolean nextPermutation(List<Integer> a){ int[]p = new int [a.size()]; for (int i = 0; i < p.length; i++) { p[i]=a.get(i); } int k,l,aux,i,j; for (k = p.length-1; k>0 && p[k-1]>=p[k]; k--); if (k!=0){ for (l = p.length-1; l>0 && p[k-1]>=p[l]; l--); aux=p[k-1]; p[k-1]=p[l]; p[l]=aux; for (i = k, j = p.length-1; i<j ; i++,j--){ aux=p[i]; p[i]=p[j]; p[j]=aux; } return true; } else return false; }
7
public static int partition(int[] records, int low, int high){ if(low > records.length - 1|| high > records.length - 1) { throw new IllegalArgumentException(); } int pivot = records[low]; while(low < high){ while (records[high] > pivot && low < high){ high--; } swap(records, low, high); while (records[low] < pivot && low < high){ low++; } swap(records, low, high); } return low; }
7
private boolean jj_3R_55() { Token xsp; xsp = jj_scanpos; if (jj_3_62()) { jj_scanpos = xsp; if (jj_3_63()) { jj_scanpos = xsp; if (jj_3_64()) return true; } } return false; }
3
public void setjButtonNext(JButton jButtonNext) { this.jButtonNext = jButtonNext; }
0
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Modul)) return false; Modul other = (Modul) obj; if (bezeichnung == null) { if (other.bezeichnung != null) return false; } else if (!bezeichnung.equals(other.bezeichnung)) return false; return true; }
6
private static void addList(ArrayList<Node> list, ArrayList<Node> newList) { for (int i = 0; i < list.size(); i++) { if(list.get(i).getWeight() <= Config.size){ if (!newList.contains(list.get(i))) { newList.add(list.get(i)); if (table.containsKey(list.get(i).getWeight())) { if (!table.get(list.get(i).getWeight()).contains( list.get(i))) table.get(list.get(i).getWeight()).add(list.get(i)); } else { ArrayList<Node> list2 = new ArrayList<Node>(); list2.add(list.get(i)); table.put(list.get(i).getWeight(), list2); } } } } }
5
public void SetStopBusStop(int stopBusStop) { //set the person stop bus stop this.stopBustop = stopBusStop; }
0
public String getNumBalise() { return numBalise; }
0
public Connection getConnection() { try { if(connection==null||connection.isClosed()) connection = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/workdb"); }catch(SQLException ex) { ex.printStackTrace(); } return connection; }
3
private boolean jj_2_19(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_19(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(18, xla); } }
1
public ListNode deleteDuplicates(ListNode head) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode p = dummy; if(head == null) return head; while(p.next != null){ int cur = p.next.val; ListNode pp = p.next; if(pp.next == null || pp.next.val != cur){ p = p.next; continue; } while(pp.next != null && pp.next.val == cur){ pp = pp.next; } p.next = pp.next; } return dummy.next; }
6
public int length() { int length = 2 + 2 + 4 + code.length + 2 + handlers.length * 8 + 2; for (int i = 0; i < attrs.length; i++) { length += 2 + 4 + attrs[i].length(); } return length; }
1
@Override public List<AdminCol> getColSortList(String tblNm) { log.debug("get column sort list for table = " + tblNm); Connection conn = null; PreparedStatement statement = null; ResultSet rs = null; ArrayList<AdminCol> list = new ArrayList<AdminCol>(); StringBuilder sql = new StringBuilder(); sql.append(" select col_nm, sort_ord, sort_dir"); sql.append(" from admin_col"); sql.append(" where tbl_nm = ?"); sql.append(" and sort_ind = 'Y'"); sql.append(" order by sort_ord"); try { conn = DataSource.getInstance().getConnection(); statement = conn.prepareStatement(sql.toString()); statement.setString(1, tblNm); log.debug(sql.toString()); rs = statement.executeQuery(); while (rs.next()) { AdminCol col = new AdminCol(); col.setColNm(rs.getString("col_nm")); col.setSortOrd(rs.getInt("sort_ord")); col.setSortDir(rs.getString("sort_dir")); list.add(col); } } catch (Exception e) { log.error("failed to get sort columns for table = " + tblNm, e); } finally { if (rs != null) { try { rs.close(); } catch (Exception e) {} } if (statement != null) { try { statement.close(); } catch (Exception e) {} } if (conn != null) { try { conn.close(); } catch (Exception e) {} } } return list; }
8
public void draw(Graphics2D g){ if(bulletTime&&btTimer > 0&&!btCooldown){ try { System.out.println("BULLET TIME"); Thread.sleep(btTime); } catch (InterruptedException e) { e.printStackTrace(); } }else if(btTimer == 0){ btCooldown = true; } if(gameStates[currentState] != null){ gameStates[currentState].draw(g); } }
6
public IService getService(Type type) { switch (type) { case ALBUM: return new AlbumService(this.daoFactory.getAlbumDAO()); case ARTIST: return new ArtistService(this.daoFactory.getArtistDAO()); case TRACK: return new TrackService(this.daoFactory.getTrackDAO()); case GENRE: return new GenreService(this.daoFactory.getGenreDAO()); default: throw new IllegalArgumentException(); } }
4
public static Cons collectStartupFormsFromSystemFile(SystemDefinition system) { { String systemfilename = Stella.makeSystemDefinitionFileName(system.name); Module module = null; Cons startupform = null; Cons startupforms = Stella.NIL; { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, ((Module)(Stella.$MODULE$.get()))); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); { InputFileStream inputstream = null; try { inputstream = Stella.openInputFile(systemfilename, Stella.NIL); { Stella_Object tree = null; SExpressionIterator iter000 = InputStream.sExpressions(inputstream); Cons collect000 = null; loop000 : while (iter000.nextP()) { tree = iter000.value; startupform = null; if (Stella_Object.safePrimaryType(tree) == Stella.SGT_STELLA_CONS) { { Cons tree000 = ((Cons)(tree)); if (tree000.value == Stella.SYM_STELLA_DEFMODULE) { Stella_Object.evaluate(tree000); module = Stella.getStellaModule(Stella_Object.coerceToModuleName(tree000.rest.value, true), true); if (module != null) { startupform = Cons.list$(Cons.cons(Stella.SYM_STELLA_STARTUP_TIME_PROGN, Cons.cons(Stella.KWD_MODULES, Cons.cons(Module.yieldDefineModule(module), Cons.cons(Stella.NIL, Stella.NIL))))); } } if (tree000.value == Stella.SYM_STELLA_IN_MODULE) { Stella_Object.evaluate(tree000); } } } else { } if (startupform == null) { continue loop000; } if (collect000 == null) { { collect000 = Cons.cons(startupform, Stella.NIL); if (startupforms == Stella.NIL) { startupforms = collect000; } else { Cons.addConsToEndOfConsList(startupforms, collect000); } } } else { { collect000.rest = Cons.cons(startupform, Stella.NIL); collect000 = collect000.rest; } } } } } finally { if (inputstream != null) { inputstream.free(); } } } return (startupforms); } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } } }
9
public static void main(String[] args) { int[][] array = new int[3][4]; int index=1; for(int i =0; i< 3;i++) for(int j =0; j < 4;j++){ array[i][j] = index++; } List<Integer> list = new Spiral_Matrix().spiralOrder(array); System.out.println(list); }
2
private JSONWriter append(String string) throws JSONException { if (string == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(string); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); }
7
public Action decideAction(Set<Being> beings, BehaviourType behaviourType) { Action a; double hunger = myBeing.getDynamicStats().get(StatType.D_HUNGER).getValue(); if (myBeing.childReady()) { if (Math.random() > 0.9) { a = new BearAction(myBeing); } else { a = new SplitAction(myBeing); } System.out.println(a); } else { /*if (hunger > myBeing.getConstStats().get(StatType.C_MAX_HEALTH).getValue()) { myBeing.getDynamicStats().get(StatType.D_HEALTH).addToValue(-10); }*/ Being closest = getClosestBeing(new ConditionChecker() { public boolean check(Being b) { return b.isAlive() && b.getClassID() != myBeing.getClassID(); } }); if (closest == null) { a = new IdleAction(myBeing); } else if (myBeing.getPosition().isInRadius(closest.getPosition(), 3.0)) { a = new EatAction(myBeing, closest); } else { a = new MoveAction(myBeing, myBeing.getPosition().plus(getVelocityTo(closest))); } } //System.out.println(a); return a; }
5
public void printAnalysisResultsSummaryEP() { String string = ""; for (int i = 0; i < consumptionEnergyPoints.length; i++) string += "\t\tFR" + (i + 1) + ": " + consumptionEnergyPoints[i] + "EP\n"; string += "\n\t\tTOTAL : " + systemConsumptionEP + "EP"; System.out.println(string); }
1
public void loadAllGroups() { ResultSet data = query(QueryGen.selectAllGroups()); while (iterateData(data)) { HashMap<PermissionFlag, Boolean> flags = new HashMap<PermissionFlag, Boolean>(); String groupType = getString(data, "GroupType"); String groupId = getString(data, "GroupId"); String memberType = getString(data, "MemberType"); String memberId = getString(data, "MemberId"); ChunkyObject group = ChunkyManager.getObject(groupType, groupId); if (group != null && !(group instanceof ChunkyGroup)) { Logging.warning("Attempted to load a group that is NOT a group."); continue; } ChunkyObject member = ChunkyManager.getObject(memberType, memberId); if (group != null && member != null) member.addToGroup((ChunkyGroup) group); } }
5
@Override public void paint(Graphics g) { super.paint(g); for (JComponent voie : voies) { voie.paint(g); } }
1
@Override public void run() { playing = true; orderedStopped = false; try { if ((clip != null) && (applet instanceof Applet)) { if (url == null) clip = ((Applet) applet).getAudioClip(((Applet) applet).getCodeBase(), key); else clip = ((Applet) applet).getAudioClip(new URL(url + key)); } } catch (final MalformedURLException m) { clip = null; playing = false; return; } if (clip != null) { // dunno how to set volume, but that should go here. while ((!orderedStopped) && (iterations < repeats)) { iterations++; clip.play(); } } playing = false; }
7
public static UUID toUUID(String value) { if (value == null || value.length() < 32) { return null; } try { if (!value.contains("-")) { String fixedString = value.substring(0, 8) + "-" + value.substring(8, 12) + "-" + value.substring(12, 16) + "-" + value.substring(16, 20) + "-" + value.substring(20, 32); return UUID.fromString(fixedString); } else { return UUID.fromString(value); } } catch (Exception e) { Log.e("ConvertUtils.toUUID", "Error converting string to UUID - " + value, e); } return null; }
4
@Override public void validate(Object target, Errors error) { // TODO Auto-generated method stub Contact contact=(Contact) target; String firstName=contact.getFirstName(); String lastName=contact.getLastName(); if(firstName==null || firstName.trim().equals("")){ ValidationUtils.rejectIfEmpty(error, "firstName", "NotEmpty"); } else{ if(firstName.length()<2 || firstName.length()>50) error.rejectValue("firstName", "Size.firstName"); } //validation for lastName if(lastName==null || lastName.trim().equals("")){ ValidationUtils.rejectIfEmptyOrWhitespace(error, "lastName", "NotEmpty"); } else{ if(lastName.length()<2 || lastName.length()>50) error.rejectValue("lastName", "Size.firstName"); } //validating contactNumber }
8
public void setOption(int token){ if( token == 0){ if( this.option > 0) option -- ; else option = this.optionStr.length - 1 ; }else if( token == 1){ if( this.option < this.optionStr.length - 1) option ++ ; else option = 0 ; } }
4
@Override public XValue invoke(XRuntime runtime, XExec exec, int id, XValue thiz, XValue[] params, List<XValue> list, Map<String, XValue> map){ XObjectDataMap m = (XObjectDataMap)runtime.getObject(thiz).getData(); switch(id){ case 0: return getIndex(runtime, m, params[0]); case 1: return length(m); case 2: return setIndex(runtime, m, params[0], params[1]); case 3: return delIndex(runtime, m, params[0]); case 4: return getItem(runtime, m, thiz, params[0]); case 5: return getKeys(runtime, m); } return super.invoke(runtime, exec, id, thiz, params, list, map); }
6
static void Bin2Dec(){ System.out.println(); System.out.print("Please enter a binary number containing only 0s and 1s: "); String binary = s.nextLine(); for(int i = 0; i < binary.length(); i++){ if(binary.charAt(i) != '0' && binary.charAt(i) != '1'){ System.out.println("That is not a valid binary number."); return; } } double decimal = 0; for(int i = 0; i < binary.length(); i++){ decimal = decimal + (Character.getNumericValue(binary.charAt(i)) * Math.pow(2.0, binary.length() - (i+1))); } System.out.println("The decimal of binary " + binary + " is " + decimal); }
4
public static void main(String[] args) { JFrame frame = new JFrame("Ray Tracer"); CustomPanel panel = new CustomPanel(actualWidth, actualHeight, ANTIALIASING_AMOUNT); frame.setBounds(0, 0, width, height); frame.add(panel); frame.setVisible(true); frame.setFocusable(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // renderedObjects = new Renderable[26]; // // for(int x = 0; x < 5; x++) // { // for(int z = 0; z < 5; z++) // { // int adjX = x * 400; // int adjZ = z * 400; // Sphere sphere = new Sphere(new Color(170, 0, 0), new Point3D(adjX - 800, 0, adjZ - 800), 175, .5, 0, 0); // renderedObjects[(x * 5) + z] = sphere; // } // } // renderedObjects[25] = plane; // int size = 8; // double radius = 100; // // lights = new Light[size * size * size]; // for(int x = 0; x < size; x++) // { // for(int y = 0; y < size; y++) // { // for(int z = 0; z < size; z++) // { // double adjX = (x - (size / 2.0)) * radius; // double adjY = (y - (size / 2.0)) * radius; // double adjZ = (z - (size / 2.0)) * radius; // // lights[(x * size * size) + (y * size) + z] = new Light(new Point3D(adjX - 1000, adjY + 500, adjZ + 300), 3000, .75 / ((double)size * size * size)); // } // } // } int totalFrames = 900; /* for(int frameNum = 0; frameNum < totalFrames; frameNum++) { // double angleHoriz = -((frameNum / 200.0) * Math.PI * 2); // double angleVert = -(Math.PI / 4) * Math.sin((frameNum / 240.0) * Math.PI * 2); // // camera.angleHoriz = angleHoriz; // camera.angleVert = angleVert; // // camera.center = new Point3D(0, 0, 0); // Point3D point = camera.GetAdjustedForCameraRotation(new Point3D(0, 0, 1600)); // camera.center = new Point3D(-point.x, -point.y, -point.z); // rotatingSphere.center = Utils.RotatePointAroundPoint(new Point3D(0, 0, 0), new Point3D(0, 0, -600), frameNum / 45.0, Math.sin(frameNum / 45.0)); // // //panel.clearPanel(0xFFFFFFFF); //largeCube.refractionIndex += .05; //rotatingSphere.center.z += 10; //sphere4.refractionIndex -= 1 / 40.0; //closeSphere.center.z -= 30; //encasedSphere.center.z += 40; //SetZoom(ZOOM * 1.4); for(int x = 0; x < panel.unscaledWidth; x++) { for(int y = 0; y < panel.unscaledHeight; y++) { camera.center.x += (Math.random() - .5) / 5.0; camera.center.y += (Math.random() - .5) / 5.0; camera.center.z += (Math.random() - .5) / 5.0; double adjX = x - (panel.unscaledWidth / 2); double adjY = y - (panel.unscaledHeight / 2); adjX /= panel.antialiasingAmount; adjY /= panel.antialiasingAmount; //This is so that positive y will be upwards instead of downwards adjY *= -1; Point3D origin = new Point3D(adjX * (1.0 / CAMERA_SIZE), adjY * (1.0 / CAMERA_SIZE), 0); origin = Point3D.Add(origin, camera.center); origin = camera.GetAdjustedForCameraRotation(origin); Vector3D direction = camera.GetAdjustedForCameraRotation(new Vector3D(adjX * (1 / FOCAL_LENGTH), adjY * (1 / FOCAL_LENGTH), 1)); Ray ray = new Ray(direction, origin, Ray.AIR_REFR_INDEX); Color color = GetColorAt(ray, MAX_REFLECTIONS, MAX_REFRACTIONS); // if(frameNum != 0) // { // Color oldcolor = panel.getPixel(x, y); // Color combine = new Color((color.getRed() + oldcolor.getRed()) / 2, (color.getGreen() + oldcolor.getGreen()) / 2, (color.getBlue() + oldcolor.getBlue()) / 2); // color = combine; // } panel.setPixel(x, y, color); //lights[0].center.x = -1000 + ((Math.random() * 700) - 350); //lights[0].center.y = 500 + ((Math.random() * 700) - 350); //lights[0].center.z = 300 + ((Math.random() * 700) - 350); } panel.repaint(); } panel.repaint(); if(SAVE_IMAGES) { try { panel.SaveScaledDownScreen("C:\\Users\\Roland\\Desktop\\JavaRaytracer Renders\\image" + String.format("%03d", frameNum + 1) + ".png"); } catch (IOException e) { e.printStackTrace(); } } } */ panel.repaint(); int startDiff = 1024; for(int skipAmount = startDiff; skipAmount > 0; skipAmount /= 2) { for(int x = 0; x < panel.unscaledWidth; x += skipAmount) { for(int y = 0; y < panel.unscaledHeight; y += skipAmount) { //camera.center.x += (Math.random() - .5) / 10.0; //camera.center.y += (Math.random() - .5) / 10.0; //camera.center.z += (Math.random() - .5) / 10.0; if(skipAmount != startDiff) { if((x / skipAmount % 2) == 0 && (y / skipAmount % 2) == 0) { continue; } } double adjX = x - (panel.unscaledWidth / 2); double adjY = y - (panel.unscaledHeight / 2); adjX /= panel.antialiasingAmount; adjY /= panel.antialiasingAmount; //This is so that positive y will be upwards instead of downwards adjY *= -1; Point3D origin = new Point3D(adjX * (1.0 / CAMERA_SIZE), adjY * (1.0 / CAMERA_SIZE), 0); origin = Point3D.Add(origin, camera.center); origin = camera.GetAdjustedForCameraRotation(origin); Vector3D direction = camera.GetAdjustedForCameraRotation(new Vector3D(adjX * (1 / FOCAL_LENGTH), adjY * (1 / FOCAL_LENGTH), 1)); Ray ray = new Ray(direction, origin, Ray.AIR_REFR_INDEX); Color color = GetColorAt(ray, MAX_REFLECTIONS, MAX_REFRACTIONS); //panel.setPixel(x, y, color); panel.setRectangle(x, x + skipAmount - 1, y, y + skipAmount - 1, color); panel.repaint(); } //panel.repaint(); } } }
6
private static void updateStringColumn(CyNetwork network, CyIdentifiable cyId, String columnName, List<CDDHit> hits) { List<String> dataList = new ArrayList<String>(); for (CDDHit hit: hits) { if (columnName.equals(CDD_ACCESSION)) dataList.add(hit.getAccession()); else if (columnName.equals(CDD_NAME)) dataList.add(hit.getName()); else if (columnName.equals(CDD_HIT_TYPE)) dataList.add(hit.getHitType()); else if (columnName.equals(PDB_CHAIN)) dataList.add(hit.getProteinId()); } network.getRow(cyId).set(columnName, dataList); }
5
public void transformCode(BytecodeInfo bytecode) { this.bc = bytecode; calcLocalInfo(); if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_LOCALS) != 0) { GlobalOptions.err.println("Before Local Optimization: "); dumpLocals(); } stripLocals(); distributeLocals(); if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_LOCALS) != 0) { GlobalOptions.err.println("After Local Optimization: "); dumpLocals(); } firstInfo = null; changedInfos = null; instrInfos = null; paramLocals = null; }
2
private void appendRowElements( final RowData rowData, final Set<CellKey> keys, final Map<RowElement,CellKey> rowElementKeyMap) { final List<Object> successors = rowData.getSuccessors(); if ( successors.isEmpty()) { // hat eine RowElement-Komponente final CellKey cellKey = rowData.getCellKey(); if ( keys.contains( cellKey)) { final JComponent component = rowData.getComponent(); if ( (component != null) && (component instanceof RowElement)) { final RowElement rowElement = (RowElement) component; rowElementKeyMap.put( rowElement, cellKey); } } } else { for ( Object object : successors) { if ( object instanceof RowData) { // keine Liste appendRowElements( (RowData) object, keys, rowElementKeyMap); } else { // eine Liste final RowSuccessor rowSuccessor = (RowSuccessor) object; final List<RowData> successors2 = rowSuccessor.getSuccessors(); for ( RowData rowData2 : successors2) { appendRowElements( rowData2, keys, rowElementKeyMap); } } } } }
7
void Rendre() { // Début de la location int idCarte = Integer.parseInt(JOptionPane.showInputDialog("Numéro carte abonnée ?")); Utilisateur user = null; for (Utilisateur s : ConfigGlobale.utilisateurs) { if(s.getFk_id_carte()==idCarte){ user = s; break; } } if(user != null && user.getFk_id_velo()!=-1){ LabelCarte.setForeground(Color.green); ctrlRV.RendreVelo(user); LabelRecupVelo.setForeground(Color.green); LabelRemerciement.setForeground(Color.green); } else { LabelCarte.setForeground(Color.red); } }
4
public void setSanic(){ sanic = true; if(!sanicd){ try{ BufferedImage spritesheet = ImageIO.read(getClass().getResourceAsStream("/Sprites/Sanic.png")); sprites = new ArrayList<BufferedImage[]>(); for(int i=0; i<4; i++){ BufferedImage[] bi = new BufferedImage[numFrames[i]]; for(int j = 0; j<numFrames[i]; j++){ if(i!=3){ bi[j] = spritesheet.getSubimage(j*width, i*height, width, height); }else{ bi[j] = spritesheet.getSubimage(j*2*width, i*height, width, height); } } sprites.add(bi); } }catch(Exception e){e.printStackTrace();} sanicd = true; } }
5
public void setCallback(Callback callback) { this.callback = callback; }
0
public byte[] processBlock(byte[] in, int inOff, int len) throws InvalidCipherTextException { if (param instanceof BGV11LeveledPublicKeyParameters) { // Encrypt under input level parameters BGV11LeveledPublicKeyParameters pk = ((BGV11LeveledPublicKeyParameters) param); BGV11LeveledParameters parameters = pk.getInputLevelParameters(); // Load the message Element m = parameters.getRq().newElement(); m.setFromBytes(in, inOff); // Choose the randomness Element r = parameters.getRtN().newRandomElement(); // Encrypt Element c0 = m.add(ip(pk.getInputLevelB(), r)); Element c1 = ip(pk.getInputLevelA(), r); // Move to bytes return new ElementObjectOutput().writeInt(pk.getInputLevel()).writeElements(c0, c1).toByteArray(); } else if (param instanceof BGV11LeveledSecretKeyParameters) { // Dec BGV11LeveledSecretKeyParameters sk = ((BGV11LeveledSecretKeyParameters) param); // Load level ElementObjectInput reader = new ElementObjectInput(in, inOff, len); int level = reader.readInt(); BGV11LeveledParameters parameters = sk.getParametersAt(level); Element s = sk.getSecretAt(level); // Load the ciphertext reader.setField(parameters.getRq()); Element[] c = reader.readElements(2); this.decryptionLevel = level; // Decrypt return c[0].add(c[1].mul(s)).mod(parameters.getT()).toBytes(); } else if (param instanceof BGV11LeveledAddParameters) { // Add BGV11LeveledPublicKeyParameters pk = ((BGV11LeveledAddParameters) param).getPk(); ElementObjectInput reader = new ElementObjectInput(in, inOff, len); // Load left part int leftLevel = reader.readInt(); BGV11LeveledParameters leftParams = pk.getParametersAt(leftLevel); reader.setField(leftParams.getRq()); Element[] left = reader.readElements(2); // Load right int rightLevel = reader.readInt(); BGV11LeveledParameters rightParams = pk.getParametersAt(rightLevel); reader.setField(rightParams.getRq()); Element[] right = reader.readElements(2); // Check levels int currentLevel = leftLevel; if (leftLevel != rightLevel) { if (leftLevel < rightLevel) { right = pk.refresh(rightLevel, leftLevel, right); } else { left = pk.refresh(leftLevel, rightLevel, left); currentLevel = rightLevel; } } int nextLevel = currentLevel - 1; // Sum left[0].add(right[0]); left[1].add(right[1]); // Move to bytes a refreshed ciphertext return new ElementObjectOutput().writeInt(nextLevel).writeElements( pk.refresh(currentLevel, left) // left ).toByteArray(); } else if (param instanceof BGV11LeveledMulParameters) { // Mul BGV11LeveledPublicKeyParameters pk = ((BGV11LeveledMulParameters) param).getPk(); ElementObjectInput reader = new ElementObjectInput(in, inOff, len); // Load left part int leftLevel = reader.readInt(); BGV11LeveledParameters leftParams = pk.getParametersAt(leftLevel); reader.setField(leftParams.getRq()); Element[] left = reader.readElements(2); // Load right int rightLevel = reader.readInt(); BGV11LeveledParameters rightParams = pk.getParametersAt(rightLevel); reader.setField(rightParams.getRq()); Element[] right = reader.readElements(2); // Check levels int currentLevel = leftLevel; if (leftLevel != rightLevel) { if (leftLevel < rightLevel) { right = pk.refresh(rightLevel, leftLevel, right); } else { left = pk.refresh(leftLevel, rightLevel, left); currentLevel = rightLevel; } } int nextLevel = currentLevel - 1; // Mul Element[] product = new Element[3]; product[0] = left[0].duplicate().mul(right[0]); product[1] = left[0].duplicate().mul(right[1]).add(left[1].duplicate().mul(right[0])); product[2] = left[1].duplicate().mul(right[1]); // Move to bytes a refreshed ciphertext return new ElementObjectOutput().writeInt(nextLevel).writeElements( pk.refresh(currentLevel, product) ).toByteArray(); } throw new IllegalStateException("Invalid parameters."); }
8
@Override public Object getInvokeHandler() { return invokeHandler; }
0
private void affDonneesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_affDonneesActionPerformed afficherCarte(); }//GEN-LAST:event_affDonneesActionPerformed
0
public JSONWriter key(String string) throws JSONException { if (string == null) { throw new JSONException("Null key."); } if (this.mode == 'k') { try { this.stack[this.top - 1].putOnce(string, Boolean.TRUE); if (this.comma) { this.writer.write(','); } this.writer.write(JSONObject.quote(string)); this.writer.write(':'); this.comma = false; this.mode = 'o'; return this; } catch (IOException e) { throw new JSONException(e); } } throw new JSONException("Misplaced key."); }
4
public void sendDate() { final String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; tblCalendar.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) {// must be mouseReleased int pos = 0; for (int i = 0; i < months.length; i++) { if (months[i] == months[thisMonth]) { pos = i + 1; break; } } String dateCall = ""; int row = tblCalendar.getSelectedRow(); int col = tblCalendar.getSelectedColumn(); int valueOfCell = (int) (tblCalendar.getModel().getValueAt(row, col)); String position = String.format("%02d", pos); String strValueOfCell = String.format("%02d", valueOfCell); dateCall = String.valueOf(cmbYear.getSelectedItem()) + "-" + position + "-" + strValueOfCell; if (WeekView.Weeks == null) { WeekView strDate = new WeekView(dateCall); strDate.setDate(dateCall); counts++; } else{ WeekView.date= dateCall; } } }); }
3
public UserControlParsePane(GrammarEnvironment environment, Grammar grammar) { super(environment, grammar, null); intializeGrammarTableSetting(); }
0
public void workWeek() { for (int i=0; i<5; i++) { this.shake(); } this.earnPaycheck(); this.setEffMult(1); }
1
public static Keyword continueExistsProof(ControlFrame frame, Keyword lastmove) { if (lastmove == Logic.KWD_DOWN) { return (Logic.KWD_MOVE_DOWN); } else if (lastmove == Logic.KWD_UP_TRUE) { { ControlFrame result = frame.result; if (result.partialMatchFrame != null) { result.partialMatchFrame.propagateFramePartialTruth(frame); } ControlFrame.propagateFrameTruthValue(result, frame); if (((Boolean)(Logic.$RECORD_JUSTIFICATIONSp$.get())).booleanValue()) { ControlFrame.recordExistentialIntroductionJustification(frame, lastmove); } if (frame.down == null) { return (Logic.KWD_FINAL_SUCCESS); } else { return (Logic.KWD_CONTINUING_SUCCESS); } } } else if (lastmove == Logic.KWD_UP_FAIL) { { ControlFrame result = frame.result; if (result.partialMatchFrame != null) { result.partialMatchFrame.propagateFramePartialTruth(frame); } ControlFrame.propagateFrameTruthValue(result, frame); if (frame.down == null) { return (Logic.KWD_FAILURE); } else { throw ((StellaException)(StellaException.newStellaException("Failed subgoal of 'exists' didn't remove itself from stack.").fillInStackTrace())); } } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + lastmove + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } }
8
@Override protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, TpURL tpURL, Invocation invocation) { int weight = 0; for (Invoker<T> invoker : invokers) { weight += this.getWeight(invoker, invocation); } int factor = random.nextInt(weight); for (Invoker<T> invoker : invokers) { weight = weight - this.getWeight(invoker, invocation); if (weight < factor) { return invoker; } } return invokers.get(random.nextInt(invokers.size())); }
3
public void tick() { // tykniecie arbitera manager.tick(); // wyluskiwanie widokow srodowiska RobotEnvironmentView robotEnvironmentView = environment.getRobotEnvironmentView(); StudentEnvironmentView studentEnvironmentView = environment.getStudentEnvironmentView(); // dzialanie na koordynatorach for (Coordinator coordinator : coordinators) { coordinator.coordinate(robotEnvironmentView); } // tworzenie map decyzji Map<Robot, Decision> robotDecisions = new HashMap<Robot, Decision>(); Map<Student, StudentDecision> studentDecisions = new HashMap<Student, StudentDecision>(); // wyluskiwanie decyzji for (Robot robot : environment.getRobots()) { robotDecisions.put(robot, robot.getAlgorithm().decide(robot.getElementView(), robotEnvironmentView)); } for (Student student : environment.getStudents()) { studentDecisions.put(student, student.getAlgorithm().decide(student.getElementView(), studentEnvironmentView)); } // tworzenie wykrywacza kolizji Set<Element> constantElements = new HashSet<Element>(); constantElements.addAll(environment.getBookshelfs()); constantElements.addAll(environment.getDesks()); constantElements.addAll(environment.getObstructions()); CollisionDetector collisionDetector = new CollisionDetector(environment.getWidth(), environment.getHeight(), constantElements); // wykonywanie decyzji for (Student student : studentDecisions.keySet()) { logger.level2("wykonywanie: " + studentDecisions.get(student) + " przez studenta: " + student); execute(student, studentDecisions.get(student), collisionDetector); } for (Robot robot : robotDecisions.keySet()) { logger.level2("wykonywanie: " + robotDecisions.get(robot) + " przez robota: " + robot); execute(robot, robotDecisions.get(robot), collisionDetector); } // dodawanie studentow for (Element entry : environment.getMarkers()) { if (entry.getElementType() == ElementType.STUDENT_ENTRY) { Student newStudent = manager.takeAvailablStudent(); if (newStudent != null) { newStudent.setLocation(entry.getLocation()); logger.level2("Dodawanie studenta do srodowiska: " + newStudent); environment.addStudent(newStudent); } } } }
8
public void process(Client sockector) { Response msg = sockector.getResponseMsgsNotCode().poll(); while(msg != null){ try{ if(sockector.isHandShak()){ broundMsg(sockector,msg); msg.bufferedContent();// 缓存内容 sockector.getResponseMsgs().add(msg); }else{ if(!sockector.isClient()){ sockector.setHandShak(true);//握手已经完成 msg.bufferedContent();// 缓存内容 sockector.getResponseMsgs().add(msg); } } }catch(IOException e){ e.printStackTrace(); }// 创建响应头部信息 msg = sockector.getResponseMsgsNotCode().poll(); } }
4
public synchronized void controllerUpdate(ControllerEvent event) { if (Debug.audio) System.out.println("CONTROLLER EVENT"); // If the player has just been realized, then create the control panel. if (event instanceof RealizeCompleteEvent){ // Now that the player is realized, get the gain controls to allow volume control. gainControl = player.getGainControl(); if (Debug.audio) System.out.println("AudioPlayer -> Realize complete"); // Check whether a control panel was requested, then create one if needed. if ((controls) && (controlComponent = player.getControlPanelComponent()) != null) { if (Debug.audio) System.out.println("AudioPlayer -> Creating control panel"); // Fix the size of the control panel Dimension controlDim = controlComponent.getPreferredSize(); controlDim.height = 25; controlDim.width = scaledXDim; controlComponent.setPreferredSize(controlDim); mediaPanel.add(controlComponent); controlComponent.setBounds(0, 0, scaledXDim, 25); } mediaPanel.validate(); realizeComplete = true; // Sets it to active super.setIsActive(true); } // At the end of the media, loop round if loop is set else if (event instanceof EndOfMediaEvent){ if (loop){ stopMedia(); playMedia(); } else { stopMedia(); } } }
8
public void fillDNA() { if (modelID < 0 || proteinID < 0) return; ModelCanvas mc = page.getComponentPool().get(modelID); if (mc == null) return; MoleculeCollection c = ((MolecularModel) mc.getMdContainer().getModel()).getMolecules(); if (c.isEmpty() || proteinID >= c.size()) { setDNA(null); return; } Molecule mol = c.get(proteinID); if (mol instanceof Polypeptide) { String s = ((Polypeptide) mol).getDNACode(); if (s == null) { setDNA(null); return; } setDNA(new DNA(s)); } else { setDNA(null); } }
7
public static void main(String[] args) throws IOException { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); //TODO Loop for persons, inner loop images of persons /*List matchedPersons = new ArrayList<Person>(); // person loop for (Person person : result) { // image loop for (URL url : person.images()) { } }*/ ////////////////////////////////// // BEGIN Test 1: lion on lion picture ////////////////////////////////// String searchString = "lion"; URL url = new URL("http://gowild.wwf.org.uk/wp-content/uploads/factfiles_lion_01.jpg"); try { System.out.println("[IMAGE_DECODER] Search for: " + searchString); System.out.println("[IMAGE_DECODER] Found enaugh matches: " + foundObjectInImage(downloadImage(url), searchString)); } catch(IOException e) { System.out.println("[IMAGE_DECODER] Source imgae cant be readed from the internet."); throw new IllegalArgumentException("[IMAGE_DECODER] Source imgae cant be readed from the internet."); } System.out.println(); ////////////////////////////////// // END Test 1: lion on lion picture ////////////////////////////////// ////////////////////////////////// // BEGIN Test 2: lena on car picture ////////////////////////////////// searchString = "lena"; url = new URL("http://www.sixt.com/uploads/pics/mercedes_slk-sixt_rent_a_car.png"); try { System.out.println("[IMAGE_DECODER] Search for: " + searchString); System.out.println("[IMAGE_DECODER] Found enaugh matches: " + foundObjectInImage(downloadImage(url), searchString)); } catch(IOException e) { System.out.println("[IMAGE_DECODER] Source imgae cant be readed from the internet."); throw new IllegalArgumentException("[IMAGE_DECODER] Source imgae cant be readed from the internet."); } System.out.println(); ////////////////////////////////// // END Test 2: lena on car picture ////////////////////////////////// ////////////////////////////////// // BEGIN Test 3: lena on lena picture ////////////////////////////////// searchString = "lena"; url = new URL("http://www.cs.cmu.edu/~chuck/lennapg/len_std.jpg"); try { System.out.println("[IMAGE_DECODER] Search for: " + searchString); System.out.println("[IMAGE_DECODER] Found enaugh matches: " + foundObjectInImage(downloadImage(url), searchString)); } catch(IOException e) { System.out.println("[IMAGE_DECODER] Source imgae cant be readed from the internet."); throw new IllegalArgumentException("[IMAGE_DECODER] Source imgae cant be readed from the internet."); } System.out.println(); ////////////////////////////////// // END Test 3: lena on lena picture ////////////////////////////////// ////////////////////////////////// // BEGIN Test 4: elephant on lena picture ////////////////////////////////// searchString = "elephant"; url = new URL("http://www.cs.cmu.edu/~chuck/lennapg/len_std.jpg"); try { System.out.println("[IMAGE_DECODER] Search for: " + searchString); System.out.println("[IMAGE_DECODER] Found enaugh matches: " + foundObjectInImage(downloadImage(url), searchString)); } catch(IOException e) { System.out.println("[IMAGE_DECODER] Source imgae cant be readed from the internet."); throw new IllegalArgumentException("[IMAGE_DECODER] Source imgae cant be readed from the internet."); } ////////////////////////////////// // END Test 4: elephant on lena picture ////////////////////////////////// }
4
public static void main(String[] args) { Simulation s = new Simulation(); // Clean up if control-C is pressed Runtime.getRuntime().addShutdownHook(s.new Cleanup()); if (args.length != 1) { System.err.println("Usage error: run as <program> <specfile> for a single XML world spec."); } try { // Set up SAX reader, which processes XML objects as file is read. XMLReader xr = XMLReaderFactory.createXMLReader(); FlockingReader handler = new FlockingReader(s); xr.setContentHandler(handler); xr.setErrorHandler(handler); // Parse the XML FileReader r = new FileReader(args[0]); xr.parse(new InputSource(r)); // Show the simulation on screen, if you haven't already s.w = handler.getWorld(); if (s.w == null) s.pack(); s.setVisible(true); // Get ready to record activities if (s.w != null) s.w.startLogging(); // Run any simulation indefinitely while (s.w != null && s.w.isRunnable()) { s.w.stepWorld(); try { Thread.sleep(s.w.getDelay()); } catch (InterruptedException e) { } } // Clean up if the world spec did not want a simulation s.processWindowEvent(new WindowEvent(s, WindowEvent.WINDOW_CLOSING)); } catch (SAXException e) { System.err.println(e.getMessage()); } catch (FileNotFoundException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println(e.getMessage()); } }
9
public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || this.length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; }
4
public void reorderList(ListNode head) { Stack<ListNode> stack = new Stack<ListNode>(); Queue<ListNode> queue = new LinkedList<ListNode>(); ListNode node = head; int size = 0; while(node != null){ size++; stack.add(node); queue.add(node); node = node.next; } int i =0 ; node = new ListNode(-1); while(i < size/2){ node.next = queue.poll(); node = node.next; node.next = stack.pop(); node = node.next; } if(size % 2 == 1){ node.next =queue.poll(); node = node.next; } node.next = null; }
3
public void run() { // Move all torpedoes and determine if they hit anything ArrayList<SpaceCraft> destroyed = spaceGameServer.sector.updateTorpedoes(); // Send remove messages for any ships of torpedoes // that are no longer in the game. if (destroyed != null ) { for ( SpaceCraft sc: destroyed) { spaceGameServer.sendRemoves( sc ); } } // Access the torpedoes that are still in the sector Vector<Torpedo> remainingTorpedoes = spaceGameServer.sector.getTorpedoes(); // Send update messages for torpedoes that are still // in the game for ( Torpedo t: remainingTorpedoes) { spaceGameServer.sendTorpedoUpdate( t, dgsock ); } // Check to see if the game has ended if (spaceGameServer.playing == false ){ this.cancel(); dgsock.close(); } } // end run
4
public void setId(int id) { this.id = id; }
0
private Stmt iterationStmt() throws SyntaxException { Stmt toBeReturned = null; if (isKind(currentToken, _while)) { consume(); match(LPAREN); Expr expr = expr(); match(RPAREN); match(LBRACE); ArrayList<Stmt> stmtList = new ArrayList<Stmt>(); // Stmt*. So check for // FIRST(Stmt) = { ;, IDENT, pause, _while, _if } while (isKind(currentToken, SEMI, IDENT, pause, _while, _if)) { try { Stmt stmt = stmt(); // If there are dangling semi-colons like ;;;;; then stmt() // would return null. Don't add such statements to the list. if (stmt != null) stmtList.add(stmt); } catch (SyntaxException e) { errorList.add(e); // skip tokens until next SEMI, // consume it, then continue parsing while (!isKind(currentToken, SEMI, /*IDENT,*/ pause, _while, _if, EOF)) { consume(); } if (isKind(currentToken, SEMI)) { consume(); } // if a SEMI, consume it before continuing } } match(RBRACE); toBeReturned = new IterationStmt(expr, stmtList); } return toBeReturned; }
6
private static void loadParameterFile(File file) { try { BufferedReader in = new BufferedReader(new FileReader(file)); int count; for (count = 0; in.ready(); count++) { String line = in.readLine(); if (line.compareTo("") == 0 || !loadParameter(line)) { in.close(); loadDefaults(); return; } } if (count != PARAMETER_COUNT) loadDefaults(); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
6
private static Map<? extends Attribute, ?> fillattrs(Object... attrs) { Map<Attribute, Object> a = new HashMap<Attribute, Object>(std.defattrs); for(int i = 0; i < attrs.length; i += 2) a.put((Attribute)attrs[i], attrs[i + 1]); return(a); }
3
private String privateMethod() { return "private"; }
0
private static void dropDB(String dbName, String username, String password){ Connection conn = null; Statement stmt = null; String dbURL = "jdbc:mysql://localhost"; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(dbURL, username, password); System.out.println("Connected database successfully..."); //STEP 4: Execute a query System.out.println("Deleting database " + dbName + "..."); stmt = conn.createStatement(); String sql = "DROP DATABASE " + dbName; stmt.executeUpdate(sql); System.out.println("Database deleted successfully..."); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) conn.close(); }catch(SQLException se){ }// do nothing try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Finished!"); System.out.println("========================================================================"); }
6
@Override public boolean isConverted() { // TODO Auto-generated method stub return true; }
0
public List<Object> getContent() { if (content == null) { content = new ArrayList<Object>(); } return this.content; }
1
public boolean isInsideBounds(int x, int y) { return x >= 0 && y >= 0 && x < getWidth() && y < getHeight(); }
3
public void setTotalNumberOfMatches(int totalNumberOfMatches) {this.totalNumberOfMatches = totalNumberOfMatches;}
0
@Override public Object execute(HttpServletRequest request, HttpServletResponse response) throws Exception { Contexto oContexto = (Contexto) request.getAttribute("contexto"); oContexto.setVista("jsp/mensaje.jsp"); ProfesorBean oProfesorBean = new ProfesorBean(); ProfesorParam oProfesorParam = new ProfesorParam(request); oProfesorBean = oProfesorParam.loadId(oProfesorBean); try { ProfesorDao oProfesorDao = new ProfesorDao(oContexto.getEnumTipoConexion()); oProfesorDao.remove(oProfesorBean); } catch (Exception e) { throw new ServletException("EntradaController: Remove Error: " + e.getMessage()); } String Mensaje = ("Se ha eliminado la información de la entrada con id=" + Integer.toString(oProfesorBean.getId())); return Mensaje; }
1
final public void Variable_declaration() throws ParseException { /*@bgen(jjtree) Variable_declaration */ SimpleNode jjtn000 = new SimpleNode(JJTVARIABLE_DECLARATION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1)); try { jj_consume_token(VAR); Identifier(); jj_consume_token(IS); Type(); jj_consume_token(SEMICOLON); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } }
8
private int sendPacket(Packet packet) throws NotConnectedException, NullPacketException, CouldNotEncodePacketException, PacketIOException { int sequenceNumber = -1; synchronized(CONNECTION_LOCK) { //regardless of whether the packet is valid, if the client is not connected then throw a NotConnectedException if(!isConnected && !isAttemptingToConnect) { logger.finest("Outgoing packet: could not send because client is not connected"); throw new NotConnectedException(packet); } //there's no point in sending null packets, so throw a NullPacketException if(packet == null) { logger.finest("Outgoing packet: could not send because packet is null"); throw new NullPacketException(); } synchronized(recorder) { //add the sequenceNumber, lastReceivedSequenceNumber, and receivedPacketHistory to the packet which we've been // recording with our PacketRecorder--also simultaneously record this packet as getting sent recorder.recordAndAddSequenceNumberToOutgoingPacket(packet); recorder.addReceivedPacketHistoryToOutgoingPacket(packet); sequenceNumber = packet.getSequenceNumber(); try { //attempt to send the packet byte[] bytes = packet.toByteArray(); DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, serverInetAddress, serverPort); socket.send(datagramPacket); if(logger.isLoggable(Level.FINEST)) logger.finest("Outgoing packet:\n " + packet.toString().replaceAll("\n", "\n ")); } catch (PacketEncodingException e) { //encoding issues result when the packet contains connection id or sequence numbers that are out of range. // we would not expect these to occur if everything is functioning as normal recorder.recordPreviousOutgoingPacketNotSent(); logger.finest("Outgoing packet: could not send due to PacketEncodingException \"" + e.getMessage() + "\""); throw new CouldNotEncodePacketException(e, packet); } catch (IOException e) { //wrapping any IOException the socket might throw so calling send() only throws CouldNotSendPacketExceptions recorder.recordPreviousOutgoingPacketNotSent(); logger.finest("Outgoing packet: could not send due to IOException \"" + e.getMessage() + "\""); throw new PacketIOException(e, packet); } } } //return the sequence number of the packet that we sent return sequenceNumber; }
6
@Override public boolean editEmployeeSkills(UserSkillSet userSkillSet) { String userid = userSkillSet.getUserId(); List<SkillRating> updateList = userSkillSet.getSkills(); Connection connection = new DbConnection().getConnection(); PreparedStatement preparedStatement = null; boolean flag = false; try { Iterator<SkillRating> iterator = updateList.iterator(); while (iterator.hasNext()) { SkillRating skillRating = iterator.next(); int skillId = CommonUtil.getSkillId(skillRating.getSkillName()); int ratingId = skillRating.getRatingId(); String givenBy = userid; String sql = UPDATE_EMPLOYEE_SKILL_RATING + ratingId + " where employeeId='" + userid + "' and skillId=" + skillId + " and givenBy='" + givenBy +"'"; preparedStatement = connection.prepareStatement(sql); preparedStatement.executeUpdate(); } flag = true; } catch (SQLException e) { m_logger.error(e.getMessage(), e); } finally { try { if (connection != null) connection.close(); if (preparedStatement != null) preparedStatement.close(); } catch (SQLException e) { m_logger.error(e.getMessage(), e); } } return flag; }
5
public JMenuItem mkMenuItem(ResourceBundle b, String menu, String name) { String miLabel; try { miLabel = b.getString(menu + "." + name + ".label"); } catch (MissingResourceException e) { miLabel=name; } String key = null; try { key = b.getString(menu + "." + name + ".key"); } catch (MissingResourceException e) { key=null; } if (key == null) return new JMenuItem(miLabel); else return new JMenuItem(miLabel/*, new MenuShortcut(key.charAt(0))*/); }
3