method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
212444a9-c7a0-4f45-9681-270e1708fabb
2
public ResultSet enviarConsulta(String consulta) { ResultSet resultado = null; try { query = factory.getConnection().createStatement(); System.out.println("DEBUG: Consulta: " + consulta); esConsulta = query.execute(consulta); if (esConsulta) { resultado = query.getResultSet(); } else { filasActualizadas = query.getUpdateCount(); } } catch (SQLException e) { e.printStackTrace(); error = true; msgError = e.getMessage(); return resultado; } return resultado; }
cfde7dd4-c0f4-4ae5-81be-ad0f0cff6bac
7
public ElementMenu(Component e) { this.element = e; JMenuItem tm = new JMenuItem("Menu for " + e.getName()); tm.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); tm.setForeground(Color.red); tm.setBackground(Color.cyan); add(tm); tm.setEnabled(false); add(new JPopupMenu.Separator()); boolean has = false; if (e instanceof Plot || e instanceof StateSpaceTrajectory) { makeShowItem(); has = true; } if (e instanceof Editable) { if (has) add(new JPopupMenu.Separator()); makeEditItem(); has = true; } if (!(e instanceof Plot || e instanceof StateSpaceTrajectory)) { if (has) add(new JPopupMenu.Separator()); makeFlipHItem(); makeFlipVItem(); } makeDeleteItem(); // makeOutputItems(); makeInputItems(); }
5b3a2847-c03a-4564-93f6-94aa2a280f02
6
@Override public void start() { super.start(); config = container.config(); logger = container.logger(); eb = vertx.eventBus(); address = config.getString("address") == null ? "shortener.persister" : config.getString("address"); host = config.getString("host") == null ? "localhost" : config.getString("host"); port = config.getNumber("port") == null ? 27017 : config.getNumber("port").intValue(); try { ServerAddress mongoAddress = new ServerAddress(host, port); mongo = new MongoClient(mongoAddress); db = mongo.getDB("url-shortener"); } catch (UnknownHostException e) { logger.error(" >> mongodb connection error : ", e); e.printStackTrace(); } logger.info(" >>> mongodbPersisterVerticle is registering event - "+address); eb.registerHandler(address, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> message) { String action = message.body().getString("action"); switch (action) { case "create": createShortUrl(message); break; case "get": getShortUrl(message); break; default: JsonObject errMsg = new JsonObject().putString("status", "error").putString("message", "[action] must be specified!"); message.reply(errMsg); } } }); logger.info(" >>> mongodbPersister server is started."); }
eb1076ce-29ca-4822-9f33-5d1599d671dc
0
public static void resignationMsg(String loserName){ System.out.println(loserName + "さんの負けです。"); }
371ebfb4-81a3-46c8-bc3a-9df9f5f62d7c
8
public static void deleteSpeculativeInstsFromReservationStations() { ArrayList<ReservationStationEntry> todelete = new ArrayList<ReservationStationEntry>(); for(ReservationStationEntry rset: ReservationStationALU1.rseSet) { if(rset.inst.specualtive) todelete.add(rset); } ReservationStationALU1.rseSet.removeAll(todelete); todelete = new ArrayList<ReservationStationEntry>(); for(ReservationStationEntry rset: ReservationStationALU2.rseSet) { if(rset.inst.specualtive) todelete.add(rset); } ReservationStationALU2.rseSet.removeAll(todelete); todelete = new ArrayList<ReservationStationEntry>(); for(ReservationStationEntry rset: ReservationStationLS.rseSet) { if(rset.inst.specualtive) todelete.add(rset); } ReservationStationLS.rseSet.removeAll(todelete); todelete = new ArrayList<ReservationStationEntry>(); for(ReservationStationEntry rset: ReservationStationBranch.rseSet) { if(rset.inst.specualtive) todelete.add(rset); } ReservationStationBranch.rseSet.removeAll(todelete); }
9b1349fa-f00c-458a-8d6f-27216700f241
9
private int doLogin () throws InterruptedException{ boolean isLogin = false; boolean first = true; int count =0; do { if (!first){ log.error("login error. retry!"); ThreadUtil.sleep( RandomUtil.getRandomInt(YueCheHelper.MAX_SLEEP_TIME)); }else{ first = false; } int loginResult = login(yueCheItem.getUserName(), yueCheItem.getPassword()); if(loginResult == YueChe.LONGIN_PROXY_ERROR || loginResult == YueChe.LONGIN_IP_FORBIDDEN ){ log.error("proxy error or ip forbidden !"); return 3; } else if( loginResult == YueChe.LONGIN_ACCOUNT_ERROR ){ String info ="accountError:"+ yueCheItem.getUserName()+","+ yueCheItem.getPassword(); log.error(info); YueCheHelper.updateYueCheBookInfo(yueCheItem.getId(), XueYuanAccount.BOOK_CAR_ACCOUNT_ERROR, info); return 3; }else if( loginResult == YueChe.LONGIN_SUCCESS ){ isLogin = true; }else{ log.error("login error!"); } count ++; if(count % 10 == 0){ int ycResult = YueCheHelper.getYueCheBookInfo(yueCheItem.getId()); if(ycResult == XueYuanAccount.BOOK_CAR_SUCCESS || ycResult == XueYuanAccount.BOOK_CAR_ALREADY_BOOKED_CAR ){ log.info(yueCheItem.getUserName()+"已经约车成功."); return 2; } } }while (!isLogin); log.info("login success!"); return 0; }
206135f2-bd1e-4dcf-89a1-e715dea50cc2
3
@Override public List<Tour> findTours(Criteria criteria) throws DaoException { if (criteria.getParam(DAO_TOUR_STATUS) == null) { criteria.addParam(DAO_TOUR_STATUS, ACTIVE); } if (criteria.getParam(DAO_TOUR_DATE_FROM) == null && criteria.getParam(DAO_TOUR_DATE_TO) == null) { criteria.addParam(DAO_TOUR_DATE_FROM, new Date()); } TypedQuery query = TypedQueryFactory.getInctance(QueryType.TOURQUERY); return query.load(criteria, loadGeneric, mysqlConn); }
770fe9ab-9d2d-48b4-9eab-f336d26aabb1
3
private LinkedList<Sprite> getValidTargets(LinkedList<Sprite>sprites){ LinkedList<Sprite>possibleTargets = new LinkedList<Sprite>(); for(int i = 0; i < sprites.size(); i++){ Sprite s = sprites.get(i); if(validTarget(s))possibleTargets.add(s); } //no targets were found make the list a null val if(possibleTargets.size() == 0) possibleTargets = null; return possibleTargets; }
0660ae56-d2e4-4daa-8a63-e238918e67f9
4
@Test public void testAgeLimits() { Metabolism m = new Metabolism(); try { m.setAge(0); fail("An IncoherentAgeException should have been thrown."); } catch(IncoherentAgeException e) {} try { m.setAge(-12); fail("An IncoherentAgeException should have been thrown."); } catch(IncoherentAgeException e) {} try { m.setAge(175); fail("An IncoherentAgeException should have been thrown."); } catch(IncoherentAgeException e) {} try { m.setAge(19); } catch(IncoherentAgeException e) { fail("An IncoherentAgeException has been thrown."); } }
28fd13b6-4fb2-4637-b1f9-682f64ec759e
6
public void removeAllNonCreativeModeEntities() { for (int x = 0; x < width; ++x) { for (int y = 0; y < depth; ++y) { for (int z = 0; z < height; ++z) { List<?> entitySlotInGrid = entityGrid[(z * depth + y) * width + x]; for (int i = 0; i < entitySlotInGrid.size(); ++i) { if (!((Entity) entitySlotInGrid.get(i)).isCreativeModeAllowed()) { entitySlotInGrid.remove(i--); } } } } } }
d5915011-795a-4143-b5cc-e6d1cbf5216c
0
public void setId(int id) { this.id = id; }
adfc51f7-14e9-42a8-9d61-7fe5d95a2e18
1
private static boolean isTri(String s, Set<Integer> set){ int v = 0; for(char c : s.toCharArray()){ v+= c - 'A' + 1; } return set.contains(v); }
5762a8c7-53e6-4f81-b877-a1c8ddf274f7
7
public void paintComponent(Graphics g){ if(save==null) init(g); super.paintComponent(g); if(back!=null) g.drawImage(back, startX, startY, this); grid.paint(g); g.translate(startX, startY); for (int x = 0; x< Map.width; x++){ for(int y = 0; y< Map.height; y++){ int type = current.getRawCell(x, y); switch(type){ case Map.CELL_BONUS: g.setColor(Color.BLUE); g.fillRect(x*size, y*size, size, size); break; case Map.CELL_OBSTACLE: if(brick_pic!=null) g.drawImage(brick_pic, x*size, y*size, this); else{ g.setColor(Color.RED); g.fillRect(x*size, y*size, size, size); } break; } } } g.translate(-startX, -startY); repaint(50); }
fc9589b9-020c-4dc0-b4b3-9550a720b750
6
public Game(String mapFilePath) { this.commandsQ = new ArrayBlockingQueue<ActionEvent>(1024); timer = new Timer(); this.mapModel = new MapModel(mapFilePath); playerPawns = new ArrayList(); com = new Connection(new IncomingActionListener()); long updateDelay = 100; //TODO revert the delay to 100 timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try{ checkInteractions(); }catch(Exception e){ System.out.println("Couldn't check interactions"); } //TODO uncomment updateAllplayers try{ updateAllPlayers(); }catch(Exception e){ System.out.println("Couldn't update players"); } try{ checkPowerup(); }catch(Exception e){ System.out.println("Couldn't check win"); } try{ checkWin(); }catch(Exception e){ System.out.println("Couldn't check win"); } } }, updateDelay, updateDelay); while (true) { /** * synchronized (commandsQ) { if (!commandsQ.isEmpty()) { * processCommand(commandsQ.remove(commandsQ.size() - 1)); } // try * { // //Thread.sleep(100); // } catch (InterruptedException ex) { * // Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, * ex); // } } * */ ActionEvent currentCommand; try { currentCommand = this.commandsQ.take(); processCommand(currentCommand); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
db73a306-05aa-41a7-b011-6d0a61f01324
1
public static void main(String[] args) { LinkList list = new LinkList(); list.insert(1, 1.01); list.insert(2, 2.02); list.insert(3, 3.03); list.insert(4, 4.04); list.insert(5, 5.05); list.printList(); while(!list.isEmpty()) { Link deletedLink = list.delete(); System.out.print("deleted: "); deletedLink.printLink(); System.out.println(""); } list.printList(); }
4d27a114-dfaa-46f2-836f-188681f1941f
5
@Override public Character dataFromSignal(List<Double> output) { int highestOutputIndex = -1; double minimum = output.get(0).doubleValue(); for (Double node : output) { if (node.doubleValue() < minimum) { minimum = node.doubleValue(); } } double highestOutput = minimum; for (int i = 0; i < output.size(); i++) { if (output.get(i).doubleValue() > highestOutput) { highestOutput = output.get(i).doubleValue(); highestOutputIndex = i; } } if (highestOutputIndex == -1) { return null; } return Character.valueOf(alphabet[highestOutputIndex]); }
92177b13-e877-4024-839c-94841072c819
0
public int GetTrips() { return trips; }
a738999a-5e75-4892-b013-f6399a6cfe58
9
int insertKeyRehash(char val, int index, int hash, byte state) { // compute the double hash final int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (state == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } state = _states[index]; // A FREE slot stops the search if (state == FREE) { if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } else { consumeFreeSlot = true; insertKeyAt(index, val); return index; } } if (state == FULL && _set[index] == val) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); }
9ee1cc3b-e1ae-4f33-b6f7-f6337ff289a9
1
private static boolean validLoginParameters(String username, String password){ boolean isValid = false; if(validateStringLength(username) & validateStringLength(password)){ isValid = true; } return isValid; }
23c3e9e4-f571-4ed6-a142-c539bdf83ac9
5
@Override public boolean equals(Object m) { if (m == this) { return true; } if (m == null || m.getClass() != this.getClass()) { return false; } Move move = (Move) m; if (move.start.equals(this.start) && move.end.equals(this.end)) { return true; } return false; }
a687399e-ac52-4ad8-b0de-06ae92620504
2
public static WallType getTypeWithReference(int ref) { WallType wallType = WallType.NONE; for (WallType wall : WallType.values()) { if (wall.getReference() == ref) { wallType = wall; } } return wallType; }
e920c89d-cb20-4e82-b953-06c002a894a8
4
public void update(int delta) { // method to anim the fly to go straight(? good english ?) if (current_state != States.FIX) { if (previous_state == current_state) { time_same_state += delta; if (time_same_state > 100 && previous_state != States.FIX) { fix(); } } } previous_state = current_state; }
7e475ca7-ae32-4dba-b255-b457d0c09fbf
6
public void update() { angle = angleCalc(); checkMove(); if (x == targetX) xa = 0; if (y == targetY) ya = 0; move(xa, ya); if (x <= targetX + 5 && x >= targetX - 5 && y <= targetY + 5 && y >= targetY - 5) { checkHit(); } }
13ee2124-6c7a-4c68-bc1b-503ac602bca5
7
public static void startupSequenceIndices() { { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/LOGIC", Stella.$STARTUP_TIME_PHASE$ > 1)); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); if (Stella.currentStartupTimePhaseP(2)) { _StartupSequenceIndices.helpStartupSequenceIndices1(); } if (Stella.currentStartupTimePhaseP(4)) { Logic.NIL_NON_PAGING_INDEX = NonPagingIndex.newNonPagingIndex(); { PagingIndex self002 = PagingIndex.newPagingIndex(); self002.selectionPattern = Stella.getQuotedTree("((:NIL-SEQUENCE) \"/LOGIC\")", "/LOGIC"); Logic.NIL_PAGING_INDEX = self002; } Logic.$LOADINGREGENERABLEOBJECTSp$.setDefaultValue(new Boolean(false)); } if (Stella.currentStartupTimePhaseP(5)) { Stella.defineStellaTypeFromStringifiedSource("(DEFTYPE SELECTION-PATTERN CONS)"); { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("SEQUENCE-INDEX", "(DEFCLASS SEQUENCE-INDEX (STANDARD-OBJECT) :DOCUMENTATION \"Abstract class for managing a sequence of objects.\" :PARAMETERS ((ANY-VALUE :TYPE OBJECT)) :ABSTRACT? TRUE :SLOTS ((THE-SEQUENCE :TYPE CONS :INITIALLY NIL) (THE-SEQUENCE-LENGTH :TYPE INTEGER :INITIALLY NULL)) :PRINT-FORM (PRINT-SEQUENCE-INDEX SELF STREAM))"); renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.SequenceIndex", "accessSequenceIndexSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.SequenceIndex"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE}); } { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("NON-PAGING-INDEX", "(DEFCLASS NON-PAGING-INDEX (SEQUENCE-INDEX) :DOCUMENTATION \"Index that manages an always-in-memory data\nstrucure containing a sequence of objects.\")"); renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.NonPagingIndex", "newNonPagingIndex", new java.lang.Class [] {}); } { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("PAGING-INDEX", "(DEFCLASS PAGING-INDEX (SEQUENCE-INDEX) :DOCUMENTATION \"Index that manages a sequence of objects retrievable from\npersistent storage. Needs to be appropriately subclassed by actual store\nimplementations and facilitated with a proper iterator class.\" :SLOTS ((SELECTION-PATTERN :TYPE SELECTION-PATTERN) (STORE :TYPE OBJECT-STORE)) :PRINT-FORM (PRINT-PAGING-INDEX SELF STREAM))"); renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.PagingIndex", "newPagingIndex", new java.lang.Class [] {}); renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.PagingIndex", "accessPagingIndexSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.PagingIndex"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE}); } { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("SEQUENCE-INDEX-ITERATOR", "(DEFCLASS SEQUENCE-INDEX-ITERATOR (ITERATOR) :DOCUMENTATION \"Iterator that generates successive members of a sequence index.\" :PARAMETERS ((ANY-VALUE :TYPE OBJECT)) :SLOTS ((LIST-ITERATOR-CURSOR :TYPE CONS)))"); renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.SequenceIndexIterator", "newSequenceIndexIterator", new java.lang.Class [] {}); renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.SequenceIndexIterator", "accessSequenceIndexIteratorSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.SequenceIndexIterator"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE}); } { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("PAGING-INDEX-ITERATOR", "(DEFCLASS PAGING-INDEX-ITERATOR (SEQUENCE-INDEX-ITERATOR) :DOCUMENTATION \"Iterator that generates successive members of a paging index.\" :PARAMETERS ((ANY-VALUE :TYPE OBJECT)))"); renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.PagingIndexIterator", "newPagingIndexIterator", new java.lang.Class [] {}); } { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("OBJECT-STORE", "(DEFCLASS OBJECT-STORE (STANDARD-OBJECT) :ABSTRACT? TRUE :SLOTS ((MODULE :TYPE MODULE)))"); renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.ObjectStore", "accessObjectStoreSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ObjectStore"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE}); } } if (Stella.currentStartupTimePhaseP(6)) { Stella.finalizeClasses(); } if (Stella.currentStartupTimePhaseP(7)) { Stella.defineMethodObject("(DEFMETHOD INSERT ((SELF SEQUENCE-INDEX) (VALUE (LIKE (ANY-VALUE SELF)))) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.SequenceIndex", "insert", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD PUSH ((SELF SEQUENCE-INDEX) (VALUE (LIKE (ANY-VALUE SELF)))) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.SequenceIndex", "push", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (FIRST OBJECT) ((SELF SEQUENCE-INDEX)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.SequenceIndex", "first", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (EMPTY? BOOLEAN) ((SELF SEQUENCE-INDEX)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.SequenceIndex", "emptyP", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (ESTIMATED-LENGTH INTEGER) ((SELF SEQUENCE-INDEX)))", Native.find_java_method("edu.isi.powerloom.logic.SequenceIndex", "estimatedLength", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineFunctionObject("SEQUENCE-INDEX.ESTIMATED-LENGTH", "(DEFUN (SEQUENCE-INDEX.ESTIMATED-LENGTH INTEGER) ((SELF SEQUENCE-INDEX)))", Native.find_java_method("edu.isi.powerloom.logic.SequenceIndex", "sequenceIndexDestimatedLength", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.SequenceIndex")}), null); Stella.defineMethodObject("(DEFMETHOD (REMOVE-DELETED-MEMBERS (LIKE SELF)) ((SELF SEQUENCE-INDEX)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.SequenceIndex", "removeDeletedMembers", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (REMOVE (LIKE SELF)) ((SELF SEQUENCE-INDEX) (VALUE OBJECT)))", Native.find_java_method("edu.isi.powerloom.logic.SequenceIndex", "remove", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (CONSIFY (CONS OF (LIKE (ANY-VALUE SELF)))) ((SELF SEQUENCE-INDEX)))", Native.find_java_method("edu.isi.powerloom.logic.SequenceIndex", "consify", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineFunctionObject("PRINT-SEQUENCE-INDEX", "(DEFUN PRINT-SEQUENCE-INDEX ((SELF SEQUENCE-INDEX) (STREAM NATIVE-OUTPUT-STREAM)))", Native.find_java_method("edu.isi.powerloom.logic.SequenceIndex", "printSequenceIndex", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.SequenceIndex"), Native.find_java_class("org.powerloom.PrintableStringWriter")}), null); Stella.defineMethodObject("(DEFMETHOD (ALLOCATE-ITERATOR (ITERATOR OF (LIKE (ANY-VALUE SELF)))) ((SELF SEQUENCE-INDEX)))", Native.find_java_method("edu.isi.powerloom.logic.SequenceIndex", "allocateIterator", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (NEXT? BOOLEAN) ((SELF SEQUENCE-INDEX-ITERATOR)))", Native.find_java_method("edu.isi.powerloom.logic.SequenceIndexIterator", "nextP", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (EMPTY? BOOLEAN) ((SELF SEQUENCE-INDEX-ITERATOR)))", Native.find_java_method("edu.isi.powerloom.logic.SequenceIndexIterator", "emptyP", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (COPY NON-PAGING-INDEX) ((SELF NON-PAGING-INDEX)))", Native.find_java_method("edu.isi.powerloom.logic.NonPagingIndex", "copy", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD CLEAR ((SELF NON-PAGING-INDEX)))", Native.find_java_method("edu.isi.powerloom.logic.NonPagingIndex", "clear", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD INSERT ((SELF PAGING-INDEX) (VALUE (LIKE (ANY-VALUE SELF)))) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.PagingIndex", "insert", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD PUSH ((SELF PAGING-INDEX) (VALUE (LIKE (ANY-VALUE SELF)))) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.PagingIndex", "push", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (ESTIMATED-LENGTH INTEGER) ((SELF PAGING-INDEX)) :DOCUMENTATION \"Return the estimated length of the sequences in 'self',\nwhich could be too large if some of the members have been deleted.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.PagingIndex", "estimatedLength", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (REMOVE-DELETED-MEMBERS (LIKE SELF)) ((SELF PAGING-INDEX)) :DOCUMENTATION \"Destructively remove all deleted members of `self'.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.PagingIndex", "removeDeletedMembers", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (REMOVE (LIKE SELF)) ((SELF PAGING-INDEX) (VALUE OBJECT)))", Native.find_java_method("edu.isi.powerloom.logic.PagingIndex", "remove", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), ((java.lang.reflect.Method)(null))); Stella.defineFunctionObject("PRINT-PAGING-INDEX", "(DEFUN PRINT-PAGING-INDEX ((SELF PAGING-INDEX) (STREAM NATIVE-OUTPUT-STREAM)))", Native.find_java_method("edu.isi.powerloom.logic.PagingIndex", "printPagingIndex", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.PagingIndex"), Native.find_java_class("org.powerloom.PrintableStringWriter")}), null); Stella.defineMethodObject("(DEFMETHOD (ALLOCATE-ITERATOR (ITERATOR OF (LIKE (ANY-VALUE SELF)))) ((SELF PAGING-INDEX)))", Native.find_java_method("edu.isi.powerloom.logic.PagingIndex", "allocateIterator", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineExternalSlotFromStringifiedSource("(DEFSLOT MODULE OBJECT-STORE :TYPE OBJECT-STORE :ALLOCATION :DYNAMIC)"); Stella.defineFunctionObject("HOME-OBJECT-STORE", "(DEFUN (HOME-OBJECT-STORE OBJECT-STORE) ((SELF OBJECT)))", Native.find_java_method("edu.isi.powerloom.logic.Logic", "homeObjectStore", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("CREATE-SEQUENCE-INDEX", "(DEFUN (CREATE-SEQUENCE-INDEX SEQUENCE-INDEX) ((SELF OBJECT) (PATTERN SELECTION-PATTERN)))", Native.find_java_method("edu.isi.powerloom.logic.Logic", "createSequenceIndex", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("edu.isi.stella.Cons")}), null); Stella.defineFunctionObject("KEYWORD.CREATE-SEQUENCE-INDEX", "(DEFUN (KEYWORD.CREATE-SEQUENCE-INDEX SEQUENCE-INDEX) ((KIND KEYWORD) (PATTERN SELECTION-PATTERN)))", Native.find_java_method("edu.isi.powerloom.logic.Logic", "keywordDcreateSequenceIndex", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Keyword"), Native.find_java_class("edu.isi.stella.Cons")}), null); Stella.defineFunctionObject("MODULE.CREATE-SEQUENCE-INDEX", "(DEFUN (MODULE.CREATE-SEQUENCE-INDEX SEQUENCE-INDEX) ((MODULE MODULE) (PATTERN SELECTION-PATTERN)))", Native.find_java_method("edu.isi.powerloom.logic.Logic", "moduleDcreateSequenceIndex", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Module"), Native.find_java_class("edu.isi.stella.Cons")}), null); Stella.defineMethodObject("(DEFMETHOD (OBJECT-STORE.CREATE-SEQUENCE-INDEX SEQUENCE-INDEX) ((STORE OBJECT-STORE) (PATTERN SELECTION-PATTERN)))", Native.find_java_method("edu.isi.powerloom.logic.ObjectStore", "objectStoreDcreateSequenceIndex", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (FETCH-RELATION NAMED-DESCRIPTION) ((STORE OBJECT-STORE) (NAME OBJECT)) :DOCUMENTATION \"Fetch the relation identified by `name' (a string or symbol) from `store'\nand return it as a named description. This needs to be appropriately \nspecialized on actual OBJECT-STORE implementations.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.ObjectStore", "fetchRelation", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (FETCH-INSTANCE OBJECT) ((STORE OBJECT-STORE) (NAME OBJECT)) :DOCUMENTATION \"Fetch the instance identified by `name' (a string or symbol) from `store'\nand return it as an appropriate logic object. This needs to be appropriately\nspecialized on actual OBJECT-STORE implementations.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.ObjectStore", "fetchInstance", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD UPDATE-PROPOSITION-IN-STORE ((STORE OBJECT-STORE) (PROPOSITION PROPOSITION) (UPDATE-MODE KEYWORD)) :DOCUMENTATION \"A module with `store' has had the truth value of `proposition'\nchange according to `update-mode'. The default method does nothing.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.ObjectStore", "updatePropositionInStore", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.Proposition"), Native.find_java_class("edu.isi.stella.Keyword")}), ((java.lang.reflect.Method)(null))); Stella.defineFunctionObject("STARTUP-SEQUENCE-INDICES", "(DEFUN STARTUP-SEQUENCE-INDICES () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic._StartupSequenceIndices", "startupSequenceIndices", new java.lang.Class [] {}), null); { MethodSlot function = Symbol.lookupFunction(Logic.SYM_LOGIC_STARTUP_SEQUENCE_INDICES); KeyValueList.setDynamicSlotValue(function.dynamicSlots, Logic.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupSequenceIndices"), Stella.NULL_STRING_WRAPPER); } } if (Stella.currentStartupTimePhaseP(8)) { Stella.finalizeSlots(); Stella.cleanupUnfinalizedClasses(); } if (Stella.currentStartupTimePhaseP(9)) { Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("LOGIC"))))); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT NIL-NON-PAGING-INDEX NON-PAGING-INDEX (NEW NON-PAGING-INDEX) :DOCUMENTATION \"Returns a non-writable empty sequence.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT NIL-PAGING-INDEX PAGING-INDEX (NEW PAGING-INDEX :SELECTION-PATTERN (QUOTE (:NIL-SEQUENCE))) :DOCUMENTATION \"Returns a non-writable empty sequence.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *LOADINGREGENERABLEOBJECTS?* BOOLEAN FALSE :DOCUMENTATION \"If TRUE, objects being created are regenerable,\nand should not be indexed using the backlinks procedures.\")"); } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } }
c8cd57b8-74a4-4826-b0b9-d7761adf9e2a
1
public void regroup(Prop foreground) { for(int x = 1; x<members.size(); x++) { int tempX = (int)((Math.random()*200)-100) + (int)members.get(0).getX(); int tempY = (int)((Math.random()*200)-100) + (int)members.get(0).getY(); members.get(x).setCourse(PathQuadStar.get().findPath(members.get(x), tempX, tempY)); } }
c4220bf7-21ac-42ec-a95a-efb5f9939d49
4
public void render(Renderer renderer) { renderer.setColor(1, 1, 1); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 1); // 1 will always be the map texture for (int z = 0; z < this.getLength() - 1; z++) { glBegin(GL_TRIANGLE_STRIP); for (int x = 0; x < this.getWidth(); x++) { glTexCoord2f(x / 128f, z / 128f); glVertex3f(x * 5, this.getHeight(x, z) * 5, z * 5); glTexCoord2f(x / 128f, (z + 1) / 128f); glVertex3f(x * 5, this.getHeight(x, z + 1) * 5, (z + 1) * 5); } glEnd(); } glDisable(GL_TEXTURE_2D); renderer.setColor(1, 0, 0); for (int z = 0; z < this.getLength() - 1; z++) { glBegin(GL_LINE_STRIP); for (int x = 0; x < this.getWidth(); x++) { glVertex3f(x * 5, this.getHeight(x, z) * 5, z * 5); glVertex3f(x * 5, this.getHeight(x, z + 1) * 5, (z + 1) * 5); glVertex3f(x * 5, this.getHeight(x, z) * 5, z * 5); } glEnd(); } }
610e1d39-b637-4549-8f53-84ef1735098c
9
public StatsPanel(final MineWindow window) { final MineBoard gameBoard = window.getMineBoard(); // Adds a timer label final JLabel timerLabel = new JLabel("Current Time: " + Integer.toString(timePassed)); this.add(timerLabel, BorderLayout.WEST); // adds a "New Game" button //uncomment for new game button //JButton newGameButton = new JButton("New Game"); //this.add(newGameButton, BorderLayout.CENTER); // adds new game button listener ActionListener newGameListener = new ActionListener() { public void actionPerformed(ActionEvent arg0) { resetTimer(); window.newGame(); } }; //newGameButton.addActionListener(newGameListener); // adds a "Mines Remaining" label final JLabel minesRemainingLabel = new JLabel("Mines Remaining: " + Integer.toString(gameBoard.getMinesRemaining())); this.add(minesRemainingLabel, BorderLayout.EAST); final JLabel face = new JLabel(); face.setIcon(new ImageIcon("good.png")); this.add(face); // Defines a timerListener Class ActionListener timerListener = new ActionListener() { public void actionPerformed(ActionEvent arg0) { StatsPanel.this.minesRemaining = gameBoard.getMinesRemaining(); StatsPanel.this.timePassed += 1; if (StatsPanel.this.timePassed % 10 == 0) { timerLabel .setText("Current Time: " + Integer .toString(StatsPanel.this.timePassed / 10)); } minesRemainingLabel.setText("Mines Remaining: " + Integer.toString(gameBoard.getMinesRemaining())); } }; // creates a timer that keeps track of game time elapsed final Timer gameTimer = new Timer(100, timerListener); // creates an action listener for the state checker timer ActionListener stateChecker = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String state = window.getMineBoard().getGameState(); if (state == "running" || state == "pressed") { gameTimer.start(); } if (state == "lostgame" || state == "wongame") { gameTimer.stop(); } if (state == "running") { face.setIcon(new ImageIcon("good.png")); } else if (state == "pressed") { face.setIcon(new ImageIcon("pressed1.png")); } else if (state == "wongame") { face.setIcon(new ImageIcon("winner.png")); } else if (state == "lostgame") { face.setIcon(new ImageIcon("gameover.png")); } } }; // creates the state checker timer which always is running checking the state final Timer stateTimer = new Timer(100, stateChecker); stateTimer.start(); }
8aaf7c9f-7b9a-4d84-822b-13dfe40ffc01
5
@Override public SceneNode build(Node node) { String id = ""; Vec3 pos = new Vec3(); NodeList nodeLst = node.getChildNodes(); for (int s = 0; s < nodeLst.getLength(); s++) { Node fstNode = nodeLst.item(s); if (fstNode != null) { if (fstNode.getNodeType() == Node.ELEMENT_NODE) { if ("id".equalsIgnoreCase(fstNode.getNodeName())) { id = fstNode.getTextContent(); } else if ( "position".equalsIgnoreCase(fstNode.getNodeName()) ) { pos.set( Vec3Builder.v3b.build( fstNode ) ); } } } } SceneNode sceneNode = new SceneNode( id ); sceneNode.localPosition.set( pos ); return sceneNode; }
0b73c579-bffb-45e3-bf56-74da9dd1fdec
4
private static void findPrimes(int aCeiling, boolean aNoPrintFlag) { PrimeFinder primeFinder = new Eratosthenes(); Instant startTime = Instant.now(); int[] primes = primeFinder.primesNotGreaterThan( aCeiling); Instant stopTime = Instant.now(); Duration computeTime = Duration.between(startTime, stopTime); if (aNoPrintFlag) { System.err.println( "\t1st prime: " + primes[0]); if (primes.length >= 1001) System.err.println( "\t1001st prime: " + primes[1000]); if (primes.length >= 10000) System.err.println( "\t10001st prime: " + primes[10000]); } else { System.out.println("Primes:"); for (Integer p : primes) { System.out.print(String.format("%-7d ", p)); } System.out.println(); } System.err.println( String.format( "Found %d primes in %d msec", primes.length, computeTime.toMillis())); }
8958997c-0ed1-4e14-87db-a3397b9ee945
7
private void startLatestJiraIssuesWorker() { SwingWorker<ArrayList<Object>, Void> worker = new SwingWorker<ArrayList<Object>, Void>() { @Override public ArrayList<Object> doInBackground() { //Disable the UI updateButton.setEnabled(false); loadLabel.setVisible(true); ArrayList<Object> latestJiraIssues = new ArrayList<Object>(); for (Integer feedIndex=0; feedIndex<RSS_FEED_NAMES.length; feedIndex++) { //System.err.println("start loop: " + feedIndex); // Integer feedIndex = 1; ArrayList<Object> feedLatestJiraIssues = getLatestJiraIssues(feedIndex); //System.err.println("feedLatestJiraIssues: " + feedLatestJiraIssues.toArray().length); //feedLatestJiraIssues.add("Worker run count = " + workerRunCount); // number of times loaded //latestJiraIssues.set(feedIndex, feedLatestJiraIssues); latestJiraIssues.add(feedLatestJiraIssues); //System.err.println("stop loop: " + feedIndex); } return latestJiraIssues; } @Override public void done() { //TODO - turn off loading gfx try { // //System.err.println("done()"); ArrayList<Object> latestJiraIssues = get(); Integer allTabsJiraIssueCount = 0; for (Integer tabIndex = 0; tabIndex < tabbedPane.getTabCount(); tabIndex++) { //System.err.println("Updating tab " + tabIndex); ArrayList<Object> myJiraIssues = (ArrayList<Object>) latestJiraIssues.get(tabIndex); Integer selectedIndex = jiraIssuesLists.get(tabIndex).getSelectedIndex(); //preserve user selection jiraIssuesLists.get(tabIndex).setListData(myJiraIssues.toArray()); //change data jiraIssuesLists.get(tabIndex).setSelectedIndex(selectedIndex); //preserve user selection jiraIssuesLists.get(tabIndex).requestFocus(); // Count the Jira issues Integer jiraIssuesCount = 0; for (Integer i = 0; i<myJiraIssues.size(); i++) { if (myJiraIssues.get(i) instanceof JiraIssueReference) { jiraIssuesCount++; } } allTabsJiraIssueCount += jiraIssuesCount; // Update the tab to reflect how many tickets there are tabbedPane.setTitleAt(tabIndex, RSS_FEED_NAMES[tabIndex] + " (" + jiraIssuesCount + ")"); } // Re-enable the UI loadLabel.setVisible(false); updateButton.setEnabled(true); // Update the tray icon toolTip to show the number of issues found String toolTip = allTabsJiraIssueCount + " " + labelsBundle.getString("jira.issues.in.total"); SystemTray tray = SystemTray.getSystemTray(); tray.getTrayIcons()[0].setToolTip(toolTip); } catch (InterruptedException ignore) { } catch (java.util.concurrent.ExecutionException e) { String why = null; Throwable cause = e.getCause(); if (cause != null) { why = cause.getMessage(); } else { why = e.getMessage(); } //System.err.println("Error getting latest Jira Issues : " + why); } // TODO - check that the timer has the correct duration (i.e. if config has changed...) timer.restart(); // wait full 5 mins after completion before looking again } }; worker.execute(); }
d7d38b2e-306b-4fd7-84ee-58aecaf7cbc9
0
private Balance() { this.balance = Constants.initialBalance; }
c615b210-43d1-4920-8f00-362918744ccd
3
@Override public void evaluateLabels(Map<String, Integer> labelValues, int position) throws TokenCompileError { if(reference != null) { Integer value = labelValues.get(reference); if(value == null) throw new SymbolLookupError(reference, getToken()); this.word = value; } // Check if this value is in range and will work as a 16-bit // value. Note that we call .getUnresolvedWord() so that we // get the value after any subclasses have done their part. int word = getUnresolvedWord(); if((word & 0xffff0000) != 0) { // Note that we don't allow a negative final value here. throw new TokenCompileError("Value doesn't fit in 16 bits", getToken()); } }
2b72753f-6719-47ba-bde5-776955126104
0
public void setHealth(int health) {this.health = health;}
bd6b316f-18c6-4a88-a3db-5c2bb477ac95
1
public String getSimpleCode(){ String str = this.printLineNumber(true) + this.operand.getSimpleCode() + this.place + " := "; if(!this.isPostFix){ str += this.operator.getValue() + this.place; } else{ str += this.place + this.operator.getValue(); } return str + "\n"; }
d0620fe7-25e2-4a37-b13e-7c1d40793017
8
public void generateSides() { //North if (getNorthNeighbor() != null && getNorthNeighbor().getSouthSide() != null) { fSides.put(COMPASS_POINT_N, getNorthNeighbor().getSouthSide()); } else { fSides.put(COMPASS_POINT_N, new HorizontalSide(fGlobals, this, new Point2D.Double(fPosition.getX() + fWidth / 2, fPosition.getY()), COMPASS_POINT_N)); } // South if (getSouthNeighbor() != null && getSouthNeighbor().getNorthSide() != null) { fSides.put(COMPASS_POINT_S, getSouthNeighbor().getNorthSide()); } else { fSides.put(COMPASS_POINT_S, new HorizontalSide(fGlobals, this, new Point2D.Double(fPosition.getX() + fWidth / 2, fPosition.getY() + fWidth), COMPASS_POINT_S)); } // West if (getWestNeighbor() != null && getWestNeighbor().getEastSide() != null) { fSides.put(COMPASS_POINT_W, getWestNeighbor().getEastSide()); } else { fSides.put(COMPASS_POINT_W, new VerticalSide(fGlobals, this, new Point2D.Double(fPosition.getX(), fPosition.getY() + fWidth / 2), COMPASS_POINT_W)); } // East if (getEastNeighbor() != null && getEastNeighbor().getWestSide() != null) { fSides.put(COMPASS_POINT_E, getEastNeighbor().getWestSide()); } else { fSides.put(COMPASS_POINT_E, new VerticalSide(fGlobals, this, new Point2D.Double(fPosition.getX() + fWidth, fPosition.getY() + fWidth / 2), COMPASS_POINT_E)); } }
89b38c8c-a016-4b41-8e90-9a127193f0be
9
public int readInt() throws IOException { switch ( type ) { case MatDataTypes.miUINT8: return (int)( buf.get() & 0xFF); case MatDataTypes.miINT8: return (int) buf.get(); case MatDataTypes.miUINT16: return (int)( buf.getShort() & 0xFFFF); case MatDataTypes.miINT16: return (int) buf.getShort(); case MatDataTypes.miUINT32: return (int)( buf.getInt() & 0xFFFFFFFF); case MatDataTypes.miINT32: return (int) buf.getInt(); case MatDataTypes.miUINT64: return (int) buf.getLong(); case MatDataTypes.miINT64: return (int) buf.getLong(); case MatDataTypes.miDOUBLE: return (int) buf.getDouble(); default: throw new IllegalArgumentException("Unknown data type: " + type); } }
83d3bbd3-1338-4faa-9d73-e5d9456f7c75
1
public String getMethod(Method method){ String result = null; method.setAccessible(true); Class[] paramTypes = method.getParameterTypes(); if (paramTypes.length == 0) { String resultOfMethod = ""; resultOfMethod = getFieldValue(ValueType.METHOD_VALUE,method); result = method.getName() + " = " + resultOfMethod; } return result; }
ff6f6d5c-f804-4479-8da6-aebcb7551e8c
1
public void testGetPartialConverterBadMultipleMatches() { PartialConverter c = new PartialConverter() { public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono) {return null;} public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono, DateTimeFormatter parser) {return null;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return Serializable.class;} }; try { ConverterManager.getInstance().addPartialConverter(c); try { ConverterManager.getInstance().getPartialConverter(new DateTime()); fail(); } catch (IllegalStateException ex) { // Serializable and ReadablePartial both match, so cannot pick } } finally { ConverterManager.getInstance().removePartialConverter(c); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); }
695f26c0-35af-48d4-b28b-20942da662b1
6
public String toString() { String rep = ""; switch (_Type) { case STRING: for (Entry<String, Integer> ent : TMS.entrySet()) { rep += ent.getKey() + " -occurs>" + ent.getValue() + "\n"; } break; case INTEGER: for (Entry<Integer, Integer> ent : TMI.entrySet()) { rep += ent.getKey() + " -occurs>" + ent.getValue() + "\n"; } for (Entry<Integer, ArrayList<Float>> ent : TMIData.entrySet()) { ArrayList<Float> alf = ent.getValue(); if (alf == null) rep += ent.getKey() + " -occurs>" + ent.getValue() + " DQ: null" + "\n"; else rep += ent.getKey() + " -dataQuality>" + new StatInfo(alf, false).dataQuality + "\n"; } break; default: break; } return rep; }
4f04f3b8-5369-4eed-a492-313981534e2e
6
private void executeUpTo(PreparedStatementKey lastToExecute, boolean moveToReuse) throws SQLException { for (Iterator<Map.Entry<PreparedStatementKey, StatementData>> iterator = statementsData.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<PreparedStatementKey, StatementData> entry = iterator.next(); StatementData statementData = entry.getValue(); Statement stmt = statementData.getStatement(); BatchResult batchResult = new BatchResult(entry.getKey().getMappedStatement(), entry.getKey().getSql()); batchResult.getParameterObjects().addAll(entry.getValue().getParameterObjects()); try { batchResult.setUpdateCounts(stmt.executeBatch()); MappedStatement ms = entry.getKey().getMappedStatement(); List<Object> parameterObjects = statementData.getParameterObjects(); KeyGenerator keyGenerator = ms.getKeyGenerator(); if (keyGenerator instanceof Jdbc3KeyGenerator) { Jdbc3KeyGenerator jdbc3KeyGenerator = (Jdbc3KeyGenerator) keyGenerator; jdbc3KeyGenerator.processBatch(ms, stmt, parameterObjects); } else { for (Object parameter : parameterObjects) { keyGenerator.processAfter(this, ms, stmt, parameter); } } } catch (BatchUpdateException e) { List<BatchResult> batchResults = results; results = new ArrayList<BatchResult>(); throw new BatchExecutorException( entry.getKey().getMappedStatement().getId() + " (batch query " + entry.getKey().getSql() + ")" + " failed. Prior " + batchResults.size() + " queries completed successfully, but will be rolled back.", e, batchResults, batchResult); } results.add(batchResult); if (moveToReuse) { iterator.remove(); unusedStatementData.put(entry.getKey(), statementData); } if (entry.getKey().equals(lastToExecute)) { break; } } }
271495cd-2669-4c42-9d88-3103aaad3495
3
void openUrl(String url) { try { if(java.awt.Desktop.isDesktopSupported()) { java.awt.Desktop desktop = java.awt.Desktop.getDesktop(); if(desktop.isSupported(java.awt.Desktop.Action.BROWSE)) { java.net.URI uri = new java.net.URI(url); desktop.browse(uri); } } } catch(Exception e) { //Something went wrong } }
9d131dab-9e70-4887-a329-0baf1df3a427
9
public static void main(String[] args) throws IOException, ParseException { int classNumber = 5; //Define the number of classes in this Naive Bayes. int Ngram = 2; //The default value is unigram. int lengthThreshold = 5; //Document length threshold int minimunNumberofSentence = 2; // each sentence should have at least 2 sentences for HTSM, LRSHTM /*****parameters for the two-topic topic model*****/ String topicmodel = "pLSA"; // pLSA, LDA_Gibbs, LDA_Variational int number_of_topics = 30; double alpha = 1.0 + 1e-2, beta = 1.0 + 1e-3, eta = 5.0;//these two parameters must be larger than 1!!! double converge = -1, lambda = 0.7; // negative converge means do need to check likelihood convergency int number_of_iteration = 100; boolean aspectSentiPrior = true; /*****The parameters used in loading files.*****/ String folder = "./data/amazon/tablet/topicmodel"; String suffix = ".json"; String stopword = "./data/Model/stopwords.dat"; String tokenModel = "./data/Model/en-token.bin"; //Token model. String stnModel = "./data/Model/en-sent.bin"; //Sentence model. Need it for pos tagging. String tagModel = "./data/Model/en-pos-maxent.bin"; String sentiWordNet = "./data/Model/SentiWordNet_3.0.0_20130122.txt"; //Added by Mustafizur---------------- String pathToPosWords = "./data/Model/SentiWordsPos.txt"; String pathToNegWords = "./data/Model/SentiWordsNeg.txt"; String pathToNegationWords = "./data/Model/negation_words.txt"; // String category = "tablets"; //"electronics" // String dataSize = "86jsons"; //"50K", "100K" // String fvFile = String.format("./data/Features/fv_%dgram_%s_%s.txt", Ngram, category, dataSize); // String fvStatFile = String.format("./data/Features/fv_%dgram_stat_%s_%s.txt", Ngram, category, dataSize); // String aspectlist = "./data/Model/aspect_output_simple.txt"; String fvFile = String.format("./data/Features/fv_%dgram_topicmodel.txt", Ngram); String fvStatFile = String.format("./data/Features/fv_%dgram_stat_topicmodel.txt", Ngram); String aspectSentiList = "./data/Model/aspect_sentiment_tablet.txt"; String aspectList = "./data/Model/aspect_tablet.txt"; /*****Parameters in learning style.*****/ //"SUP", "SEMI" String style = "SEMI"; //"RW", "RW-ML", "RW-L2R" String method = "RW-L2R"; /*****Parameters in transductive learning.*****/ String debugOutput = "data/debug/topical.sim"; // String debugOutput = null; boolean releaseContent = false; //k fold-cross validation int CVFold = 10; //choice of base learner String multipleLearner = "SVM"; //trade-off parameter double C = 1.0; /*****Parameters in feature selection.*****/ // String featureSelection = "DF"; //Feature selection method. // double startProb = 0.5; // Used in feature selection, the starting point of the features. // double endProb = 0.999; // Used in feature selection, the ending point of the features. // int DFthreshold = 30; // Filter the features with DFs smaller than this threshold. // // System.out.println("Performing feature selection, wait..."); // jsonAnalyzer analyzer = new jsonAnalyzer(tokenModel, classNumber, null, Ngram, lengthThreshold); // analyzer.LoadStopwords(stopwords); // analyzer.LoadDirectory(folder, suffix); //Load all the documents as the data set. // analyzer.featureSelection(fvFile, featureSelection, startProb, endProb, DFthreshold); //Select the features. System.out.println("Creating feature vectors, wait..."); AspectAnalyzer analyzer = new AspectAnalyzer(tokenModel, stnModel, tagModel, classNumber, fvFile, Ngram, lengthThreshold, aspectList, true); //Added by Mustafizur---------------- analyzer.setMinimumNumberOfSentences(minimunNumberofSentence); analyzer.LoadStopwords(stopword); // Load the sentiwordnet file. // analyzer.loadPriorPosNegWords(sentiWordNet, pathToPosWords, pathToNegWords, pathToNegationWords); analyzer.setReleaseContent(releaseContent); // Added by Mustafizur---------------- analyzer.LoadDirectory(folder, suffix); //Load all the documents as the data set. analyzer.setFeatureValues("TF", 0); _Corpus c = analyzer.returnCorpus(fvStatFile); // Get the collection of all the documents. pLSA tModel = null; if (topicmodel.equals("pLSA")) { tModel = new pLSA_multithread(number_of_iteration, converge, beta, c, lambda, number_of_topics, alpha); } else if (topicmodel.equals("LDA_Gibbs")) { tModel = new LDA_Gibbs(number_of_iteration, converge, beta, c, lambda, number_of_topics, alpha, 0.4, 50); } else if (topicmodel.equals("LDA_Variational")) { tModel = new LDA_Variational_multithread(number_of_iteration, converge, beta, c, lambda, number_of_topics, alpha, 10, -1); } else { System.out.println("The selected topic model has not developed yet!"); return; } tModel.setDisplayLap(0); tModel.setSentiAspectPrior(aspectSentiPrior); tModel.LoadPrior(aspectSentiPrior?aspectSentiList:aspectList, eta); tModel.EMonCorpus(); //construct effective feature values for supervised classifiers analyzer.setFeatureValues("BM25", 2); c.mapLabels(3);//how to set this reasonably if (style.equals("SEMI")) { //perform transductive learning System.out.println("Start Transductive Learning, wait..."); double learningRatio = 1.0; int k = 30, kPrime = 20; // k nearest labeled, k' nearest unlabeled double tAlpha = 1.0, tBeta = 0.1; // labeled data weight, unlabeled data weight double tDelta = 1e-5, tEta = 0.6; // convergence of random walk, weight of random walk boolean simFlag = false, weightedAvg = true; int bound = 0; // bound for generating rating constraints (must be zero in binary case) int topK = 25; // top K similar documents for constructing pairwise ranking targets double noiseRatio = 1.0; boolean metricLearning = true; boolean multithread_LR = true;//training LambdaRank with multi-threads GaussianFieldsByRandomWalk mySemi = null; if (method.equals("RW")) { mySemi = new GaussianFieldsByRandomWalk(c, multipleLearner, C, learningRatio, k, kPrime, tAlpha, tBeta, tDelta, tEta, weightedAvg); } else if (method.equals("RW-ML")) { mySemi = new LinearSVMMetricLearning(c, multipleLearner, C, learningRatio, k, kPrime, tAlpha, tBeta, tDelta, tEta, weightedAvg, bound); ((LinearSVMMetricLearning)mySemi).setMetricLearningMethod(metricLearning); } else if (method.equals("RW-L2R")) { mySemi = new L2RMetricLearning(c, multipleLearner, C, learningRatio, k, kPrime, tAlpha, tBeta, tDelta, tEta, weightedAvg, topK, noiseRatio, multithread_LR); } mySemi.setSimilarity(simFlag); mySemi.setDebugOutput(debugOutput); mySemi.crossValidation(CVFold, c); } else if (style.equals("SUP")) { //perform supervised learning System.out.println("Start SVM, wait..."); SVM mySVM = new SVM(c, C); mySVM.crossValidation(CVFold, c); } }
48e30109-deb5-490c-b57e-5828bfebdc95
6
public static String translate(String str) { if (!turnedon) return str; String res = ""; URL url = url(str); if (url == null) return str; try { final HttpURLConnection uc = (HttpURLConnection) url .openConnection(); uc.setRequestMethod("GET"); uc.setDoOutput(true); try { String result; try { result = inputStreamToString(uc.getInputStream()); } catch (Exception e) { return str; } JSONObject o = new JSONObject(result); res = o.getJSONObject("data").getJSONArray("translations").getJSONObject(0).getString("translatedText"); str = res; res = o.getJSONObject("data").getJSONArray("translations").getJSONObject(0).getString("detectedSourceLanguage"); res = "[" + res + "] " + str; } catch (JSONException e) { return str; } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html uc.getInputStream().close(); if (uc.getErrorStream() != null) { uc.getErrorStream().close(); } } } catch (IOException e) { return str; } return res; }
7c74f210-c96b-41e9-9a8f-55bdafa5d3d6
5
public boolean advance( Pos pos, char c ) { if ( pos.node == null ) { pos.node = findSon( root, c ); if ( pos.node != null ) { pos.edgePos = pos.node.edgeLabelStart; return true; } else return false; } else { int nodeLabelEnd = getNodeLabelEnd( pos.node ); // already matched that char ... if ( pos.edgePos == nodeLabelEnd ) { Node localNode = findSon( pos.node, c ); if ( localNode != null ) { pos.edgePos = localNode.edgeLabelStart; pos.node = localNode; return true; } else return false; } else { boolean success = treeString[pos.edgePos+1] == c; if ( success ) pos.edgePos++; return success; } } }
6b418e4e-35df-4ef4-bf97-8c4571377143
4
public void setWaarde(int waarde){ //controle if(waarde < minWaarde) waarde = minWaarde; if(waarde > maxWaarde) waarde = maxWaarde; this.waarde = waarde; //stel label in slider.setValue(this.waarde); textField.setText(String.valueOf(this.waarde) + eenheid); try { if(onChangeFunctie != null) onChangeFunctie.call(); } catch (Exception e){ e.printStackTrace(); } }
b454481a-1c12-4853-bd89-4ee612f1513c
4
private static void parseToolsForInitialDataRepository(Node kitchenToolsNode, Vector<AcquirableKitchenTool> RestKitchenTools) { if (kitchenToolsNode.getNodeType() == Node.ELEMENT_NODE) { Element kitchenToolsElement = (Element) kitchenToolsNode; String toolName= kitchenToolsElement.getElementsByTagName("name").item(0).getTextContent(); int toolQuantity= Integer.decode(kitchenToolsElement.getElementsByTagName("quantity").item(0).getTextContent()); if((toolName == null) || (toolName == "")) throw (new RuntimeException("toolName is null or empty string!")); if(toolQuantity < 0) throw (new RuntimeException("toolQuantity is negetive!")); AcquirableKitchenTool newKitchenTool= new AcquirableKitchenTool(toolName, toolQuantity); RestKitchenTools.add(newKitchenTool); } }
c5d5a00f-e70b-451c-9648-ba33376c6618
6
@Override public void enregistrer() { //String v_titre, String v_region, int v_exp, int v_salMin, int v_salMax, HashMap<Competence, CompType> tblComps // int compsSize = m_tblComps.size(); //System.out.println("size" + m_tblComps.size()); //System.out.println(m_tblComps); String compstr = ""; Iterator iter = m_tblComps.keySet().iterator(); while (iter.hasNext()) { Competence key = (Competence) iter.next(); compstr += key.getNomComp() + Constant.m_compTypeDelim; // System.out.println("saved compstr :" + compstr); compstr += m_tblComps.get(key).getLibType() + Constant.m_compDelim; } int tmplen = compstr.length(); if (tmplen > 0 && (compstr.substring(tmplen - 1, tmplen) == null ? Constant.m_compDelim == null : compstr.substring(tmplen - 1, tmplen).equals(Constant.m_compDelim))) { compstr = compstr.substring(0, tmplen - 1); } String content = m_titre + Constant.m_itemDelim + m_region.getRegnom() + Constant.m_itemDelim + m_experience + Constant.m_itemDelim + m_salairemin + Constant.m_itemDelim + m_salairemax + Constant.m_itemDelim + compstr; try { File file = new File(Constant.m_offreList); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.newLine(); bw.close(); System.out.println("size before ajouter" + OffreNoyauFonctionnel.getTblEmplois().size() + "Emploi.java"); OffreNoyauFonctionnel.printOutOffres(); OffreNoyauFonctionnel.ajouterEmploi(this); System.out.println("size after ajouter" + OffreNoyauFonctionnel.getTblEmplois().size() + "Emploi.java"); OffreNoyauFonctionnel.printOutOffres(); } catch (IOException e) { e.printStackTrace(); } }
4f4de027-f0d3-4e5a-8434-0eb808c6e7c0
5
static synchronized void setFilename(String filename) { if(writer != null) { try { writer.close(); writer = null; } catch (IOException e) { System.out.println("Unable to close log file"); } } if(filename == null) { writer = null; return; } FileWriter out = null; try { out = new FileWriter(filename, true); } catch (IOException e) { System.out.println("Unable to open log file: " + filename); writer = null; return; } if(out != null) { writer = new BufferedWriter(out); } }
f5058ea8-de25-4b36-b702-4d5709203892
6
public Barrier(int x1, int y1, int x2, int y2, int type) { sx = x1; sy = y1; ex = x2; ey = y2; attribute = type; switch(type) { case Terrarium.BARRIER_GAP_MINI: color = Color.YELLOW; break; case Terrarium.BARRIER_GAP_BIG: color = Color.ORANGE; break; case Terrarium.BARRIER_NET_MINI: color = Color.PINK; break; case Terrarium.BARRIER_NET_BIG: color = Color.MAGENTA; break; case Terrarium.BARRIER_WALL: color = Color.GRAY; break; case Terrarium.BARRIER_WATER: color = Color.CYAN; break; } }
a88d4dba-47da-4fcb-adb1-f7d45489ec23
4
@Override public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null || (object instanceof String && ((String) object).length() == 0)) { return null; } if (object instanceof Motivo) { Motivo o = (Motivo) object; return getStringKey(o.getIdMotivo()); } else { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), Motivo.class.getName()}); return null; } }
7b72b88b-2be6-49c1-989f-55b0ba4c1f7f
3
public ArrayList<Integer> grayCode(int n) { ArrayList<Integer> result = new ArrayList<Integer>(); result.add(0); if (n == 0) return result; int adder = 1; while (n > 0) { for (int i = result.size() - 1; i > -1; i--) result.add(adder + result.get(i)); adder <<= 1; n--; } return result; }
24b260e2-5ef8-4961-8e33-573aaaf1de6d
1
@Override public void move() { for (int i = 0; i < Initialization.getStepToPredator(); i++) { super.move(); } }
9cdcb9f0-ce97-4e20-9e77-3bcde628a21a
6
@Override public void run() { while(true) { try { //Start server and wait for connection System.out.println("Waiting on port " + serverSocket.getLocalPort()); Socket server = serverSocket.accept(); System.out.println("Connection to " + server.getRemoteSocketAddress()); //after connected, get input stream DataInputStream in = new DataInputStream(server.getInputStream()); // response stream (if needed) DataOutputStream out = new DataOutputStream(server.getOutputStream()); //handle input boolean connected = true; while(connected) { String input = in.readUTF(); System.out.println(input); //either if you want to print it out or for debugging. else comment it out // DO SOMETHING WITH INPUT like following switch(input) { case "quit" : out.writeUTF("Diconnecting from server! Goodbye! \n"); connected = false; break; case "ping" : out.writeUTF("pong \n"); break; default : out.writeUTF("Couldn't handle input! \n"); } //handle more output: //out.writeUTF("TEXT \n") } //finally close server (adapt when server closing is needed later or at another stage or time server.close(); } catch (SocketTimeoutException ste) { System.out.println("Socket Timeout!"); break; } catch (IOException ioe) { ioe.printStackTrace(); break; } } }
eb98fc32-916f-4e46-8856-0584143a4ce2
5
public static <A, B, C, D, E, F$> Equal<P6<A, B, C, D, E, F$>> p6Equal(final Equal<A> ea, final Equal<B> eb, final Equal<C> ec, final Equal<D> ed, final Equal<E> ee, final Equal<F$> ef) { return equal(p1 -> p2 -> ea.eq(p1._1(), p2._1()) && eb.eq(p1._2(), p2._2()) && ec.eq(p1._3(), p2._3()) && ed.eq(p1._4(), p2._4()) && ee.eq(p1._5(), p2._5()) && ef.eq(p1._6(), p2._6())); }
d4b25fb5-d1e4-4852-8649-ae41ec9938eb
5
boolean isValidMatch(Detection other) { return parameterIdMsb != other.parameterIdMsb && parameterIdLsb != other.parameterIdLsb && inRatioRange(w_vel, other.w_vel) && inRatioRange(peak_flux, other.peak_flux) && inRatioRange(int_flux, other.int_flux) && inRatioRange(total_flux, other.total_flux); }
c634516e-b204-4b75-b67d-cb0a0a3acaf4
0
@Override public Queue<WebPage> getUnsearchQueue() { // TODO Auto-generated method stub return null; }
ad71e4ca-2c2f-4f9d-96e7-7d29db973a37
9
public static int[] indicesOfSublist(byte[] array, byte[] sublist) { LinkedList<Integer> indexes = new LinkedList<Integer>(); if (array == null || sublist == null || array.length == 0 || sublist.length == 0 || sublist.length > array.length) { return new int[0]; } // Find instances of byte list outer: for (int i = 0; i < array.length - sublist.length + 1; i++) { for (int j = 0; j < sublist.length; j++) { if (array[i + j] != sublist[j]) { continue outer; } } indexes.add(i); } // Convert to primitive type int[] int_array = new int[indexes.size()]; for (int i = 0; i < indexes.size(); i++) { int_array[i] = indexes.get(i); } return int_array; }
91506972-9165-48b0-b597-1089d52c9d4d
1
public List<MenuElement> getChildren() { if (this.children == null) { return new ArrayList<MenuElement>(); } return this.children; }
7bd827f7-f610-4e92-bb57-403ae4ebe3b0
6
private void match(Matcher matcher) { String message = null; if (negation) { if (!matcher.matchNegation()) { message = matcher.getMatchNegationMessage(); } } else { if (!matcher.match()) { message = matcher.getMatchMessage(); } } negation = false; if (message != null) { Throwable exception = new Throwable(); StackTraceElement pos = exception.getStackTrace()[0]; for (StackTraceElement ste : exception.getStackTrace()) { if (ste.getClassName() == context.getClass().getName()) { pos = ste; break; } } results.addUnexceptedResults(message,pos); } }
312b3d21-78cd-40e5-8dd6-3d686f581168
5
private synchronized void dequeue(PacketScheduler sched) { Packet np = sched.deque(); if (np != null) { // process ping() packet if (np instanceof InfoPacket) { ((InfoPacket) np).addExitTime( GridSim.clock() ); } if (super.reportWriter_ != null) { super.write("dequeuing, " + np); } // must distinguish between normal and junk packet int tag = GridSimTags.PKT_FORWARD; if (np.getTag() == GridSimTags.JUNK_PKT) { tag = GridSimTags.JUNK_PKT; } // sends the packet via the link String linkName = getLinkName( np.getDestID() ); super.sim_schedule(GridSim.getEntityId(linkName), GridSimTags.SCHEDULE_NOW, tag, np); // process the next packet in the scheduler if ( !sched.isEmpty() ) { double nextTime = (np.getSize() * NetIO.BITS) / sched.getBaudRate(); sendInternalEvent(nextTime, sched); } } }
67a4c7cd-9fc7-4b01-bb2b-4aa41cb73e8f
8
protected static Ptg calcDProduct( Ptg[] operands ) { if( operands.length != 3 ) { return new PtgErr( PtgErr.ERROR_NA ); } DB db = getDb( operands[0] ); Criteria crit = getCriteria( operands[2] ); if( (db == null) || (crit == null) ) { return new PtgErr( PtgErr.ERROR_NUM ); } int fNum = db.findCol( operands[1].getString().trim() ); if( fNum == -1 ) { return new PtgErr( PtgErr.ERROR_NUM ); } double product = 1; // this is the colname to match String colname = operands[1].getValue().toString(); for( int i = 0; i < db.getNRows(); i++ ) { // loop thru all db rows // check if current row passes criteria requirements try { if( crit.passes( colname, db.getRow( i ), db ) ) { // passes; now do action String fnx = db.getCell( i, fNum ).getValue().toString(); if( fnx != null ) { product *= Double.parseDouble( fnx ); } } } catch( NumberFormatException e ) { } } return new PtgNumber( product ); }
814367fd-46ca-4367-876c-c2533a148ebb
1
public static void main(String[] args) { int sum = 0; for (int i = 1; i < 1000; i++) { sum += spell(i); // System.out.println(sum); // if (i==342 || i ==115) System.out.println(spell(i)); } sum+=11; System.out.println(sum); }
cb783e0e-7c09-4e2a-a9b7-f7f0258e9146
2
public void destroy() { ui.mapview.disol(17); if(walkmod) ui.mapview.release(this); if(ol != null) ol.destroy(); super.destroy(); }
30b68e12-51f1-4575-b6c9-3e3c9f62ef56
8
public void newMixer( Mixer m ) { if( myMixer != m ) { try { if( clip != null ) clip.close(); else if( sourceDataLine != null ) sourceDataLine.close(); } catch( SecurityException e ) {} myMixer = m; if( attachedSource != null ) { if( channelType == SoundSystemConfig.TYPE_NORMAL && soundBuffer != null ) attachBuffer( soundBuffer ); else if( myFormat != null ) resetStream( myFormat ); } } }
81a02ed2-0cab-469b-9e8d-bbccc2c94478
3
public State getStoppedDirectionState(Point point) { Point position = new Point(super.getIntX(), super.getIntY()); if(Point.insideAngle(Point.DOWN_LEFT, Point.DOWN_RIGHT, position, point)) { // Face up return State.STOPPED_UP; } else if(Point.insideAngle(Point.DOWN_RIGHT, Point.UP_RIGHT, position, point)) { // Face right return State.STOPPED_RIGHT; } else if(Point.insideAngle(Point.UP_RIGHT, Point.UP_LEFT, position, point)) { // Face down return State.STOPPED_DOWN; } else { // Face left return State.STOPPED_LEFT; } }
0ef6d668-b001-4a5f-85bd-bb1bae592b5c
9
@Override public void actionPerformed(ActionEvent e) { String selectedType = (String) colorOf.getSelectedItem(); if (e.getSource() == ok || e.getSource() == apply) { Color selectedColor = chooser.getColor(); if (selectedType.equals(TO_BE_TYPED)) pref.setToBeTyped(selectedColor); else if (selectedType.equals(ALREADY_TYPED)) pref.setAlreadyTyped(selectedColor); else if (selectedType.equals(MISTYPE)) pref.setMissTypeColor(selectedColor); else if (selectedType.equals(BACKGROUND)) pref.setBackgroundColor(selectedColor); pref.update(); if (e.getSource() == ok) dispose(); } else if (e.getSource() == cancel) dispose(); // When ComboBox is changed else { Color c = getColorForType(selectedType); if (c == null) return; previewPanel.setOldColor(c); chooser.setColor(c); } }
8e973414-1bda-4232-9e8e-db32d24327b7
1
public static void setSpotLights(SpotLight[] spotLights) { if (spotLights.length > MAX_SPOT_LIGHTS) { System.err .println("Error: You passed in too many spot lights. Max allowed is " + MAX_SPOT_LIGHTS + ", you passed in " + spotLights.length); new Exception().printStackTrace(); System.exit(1); } PhongShader.spotLights = spotLights; }
5f37c51b-4216-4648-89cd-6d4fd537aee4
8
public boolean isCar(char current, char[] neighbors, int[] position){ if(current == neighbors[0]){ int[] positionTwo = {(position[0]-1), position[1]}; if(!letterExistsElsewhere(current, position, positionTwo, null)){ //System.out.println("car position 1"); return true; } else { return false; } } else if (current == neighbors[2]){ int[] positionTwo = {(position[0]+1), position[1]}; if(!letterExistsElsewhere(current, position, positionTwo, null)){ //System.out.println("car position 2"); return true; } else { return false; } } else if (current == neighbors[4]){ int[] positionTwo = {position[0], (position[1]-1)}; //System.out.println(positionTwo[0] + "," + positionTwo[1]); if(!letterExistsElsewhere(current, position, positionTwo, null)){ //System.out.println("car position 3"); return true; } else { return false; } } else if (current == neighbors[6]){ int[] positionTwo = {position[0], (position[1]+1)}; if(!letterExistsElsewhere(current, position, positionTwo, null)){ //System.out.println("car position 4"); return true; } else { return false; } } else { return false; } }
14272094-c2ec-429e-87b0-9c7aa23a4e22
1
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((folderPath == null) ? 0 : folderPath.hashCode()); return result; }
91ad691e-435f-4a11-bb81-0afae9539409
8
public static ItemStack upgrade(Inventory inv, Player p){ ItemStack is = inv.getItem(0); if(is.hasItemMeta()){ if(is.getItemMeta().hasLore()){ //Check old upgrade int oldUp = 1; int newUp = 1; if(is.getItemMeta().getDisplayName().contains("+")){ String name = is.getItemMeta().getDisplayName(); int i = name.indexOf("+"); if(name.length() > i + 2){ // > 9 oldUp = Integer.parseInt(""+name.charAt(i + 1) + name.charAt(i + 2)); //p.sendMessage("true"); }else{ // < 9 oldUp = Integer.parseInt(""+is.getItemMeta().getDisplayName().charAt(i + 1)); //p.sendMessage("false"); } newUp = oldUp + newUp; } /** FAILED UPGRADE **/ if(!Upgrade.chance.getChance(newUp)){ p.playSound(p.getLocation(), Sound.ITEM_BREAK, 1f, 1f); //p.playSound(p.getLocation(), Sound.ANVIL_LAND, 0.7f, 0.7f); p.sendMessage(ChatColor.RED + "\u2718 FAILED UPGRADE. " + ChatColor.YELLOW + "BREAK"); return null; } /** SUCCESSFUL UPGRADE **/ //Get damage lore line String text = null; int time = -1; for(String lore : is.getItemMeta().getLore()){ if(lore.startsWith(ChatColor.GRAY + "Damage")){ text = ChatColor.stripColor(lore); } time++; } //Get min-max damage String damage = text.split(" ")[1]; double min = Integer.parseInt(damage.split("-")[0]); double max = Integer.parseInt(damage.split("-")[1]); //Calculate new damage after upgrade int amin = (int) (min + (min/100 * 10)); int amax = (int) (max + (max/100 * 10)); //Set lore List<String> lore = is.getItemMeta().getLore(); lore.set(time, ChatColor.GRAY + "Damage: " +ChatColor.WHITE + amin + "-" + amax); ItemMeta im = is.getItemMeta(); im.setLore(lore); //Delete and Add + if(newUp > 1){ //old //new im.setDisplayName(im.getDisplayName().replace(Color.getColor(oldUp) + " +" + (oldUp), Color.getColor(newUp) + " +" + newUp)); }else{ im.setDisplayName(im.getDisplayName() + Color.getColor(newUp) + " +" + newUp); } //Done is.setItemMeta(im); p.playSound(p.getLocation(), Sound.LEVEL_UP, 1f, 1f); p.playSound(p.getLocation(), Sound.ANVIL_LAND, 0.7f, 1f); p.sendMessage(ChatColor.GREEN + "\u2714 SUCCESSFUL UPGRADE. " + Color.getColor(newUp) + "+" +newUp); p.sendMessage(ChatColor.GRAY + "(" + (int) min + "-" + (int) max + ") " + ChatColor.DARK_GRAY + "\u27b2" + " " + ChatColor.WHITE + "(" + amin + "-" + amax + ")" ); Bukkit.broadcastMessage(ChatColor.GRAY + "[+] " + ChatColor.WHITE + "" +p.getName() + ChatColor.GRAY + " has successful upgraded " + im.getDisplayName()); //Give back to player p.getInventory().addItem(is); } } return null; }
572456c1-316e-4b4b-80e1-3ffa9e375672
5
public static Member getMemberByID(int memberID){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { Statement stmnt = conn.createStatement(); String sql = "SELECT * FROM Members WHERE member_id = " + memberID; ResultSet res = stmnt.executeQuery(sql); if(res.next()) { adress = null; member = new Member(res.getString("name"),res.getString("first_name"),res.getString("phone_num"),adress,res.getInt("member_id"), res.getInt("book_amount"),res.getDate("subscription_date"),res.getBoolean("active"), res.getBoolean("subscription_fee")); adress = AdressDAO.getAdressByID(res.getInt("address_id")); member.setAdress(adress); } } catch(SQLException e) { e.printStackTrace(); } return member; }
2dd4dc62-2de2-435a-bb28-a7a64887cf3b
3
private static void AllSubsets(String s){ int l = s.length(); StringBuilder sb = new StringBuilder(); for(int i=0;i<Math.pow(2,l);i++){ sb = new StringBuilder(); int base = 1; for(int j=0;j<l;j++){ if((i & base) > 0){ sb.append(s.charAt(j)); } base = base << 1; } System.out.println(sb.toString()); } }
f53a1231-631f-4875-8cf0-59b88b661739
5
public void run() { while (!stop) { try { if ( autoScale == true ) { if ( getYmax() < bufferYmax ) setYmax(bufferYmax); if ( getYmin() > bufferYmin ) setYmin(bufferYmin); } redrawGraph(); sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("End of paint thread."); }
65f03b0f-b730-4fdf-ae67-f9efbfc89f85
8
public byte nearHandle(double x, double y) { double dx = this.x - x; double dy = this.y - y; if (dx * dx + dy * dy < 16) return UPPER_LEFT; dx = this.x + this.width - x; dy = this.y - y; if (dx * dx + dy * dy < 16) return UPPER_RIGHT; dx = this.x + this.width - x; dy = this.y + this.height - y; if (dx * dx + dy * dy < 16) return LOWER_RIGHT; dx = this.x - x; dy = this.y + this.height - y; if (dx * dx + dy * dy < 16) return LOWER_LEFT; dx = this.x + this.width / 2 - x; dy = this.y - y; if (dx * dx + dy * dy < 16) return TOP; dx = this.x + this.width - x; dy = this.y + this.height / 2 - y; if (dx * dx + dy * dy < 16) return RIGHT; dx = this.x + this.width / 2 - x; dy = this.y + this.height - y; if (dx * dx + dy * dy < 16) return BOTTOM; dx = this.x - x; dy = this.y + this.height / 2 - y; if (dx * dx + dy * dy < 16) return LEFT; return -1; }
51f75e78-61b9-470c-8e31-838b2c67a456
4
public DiskBasedCobweb(){ try { in = new BufferedReader(new FileReader(searchedSitesFilePath)); bw = new BufferedWriter(new FileWriter(tmpSearchedSitesFilePath)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // PS. file path 不能直接直接放在某個disk底下, 起碼要有一層資料夾去包著, 否則無法讀寫 // this.searchedSitesFile = new File(searchedSitesFilePath); try { this.searchedSitesFileWriter = new FileWriter(this.searchedSitesFile); } catch (IOException e) { log.error("searchedSitesFileWriter write failed."); } this.unsearchedSitesFile = new File(unarchedSitesFilePath); try { this.unsearchedSitesFileWriter = new FileWriter(this.unsearchedSitesFile); } catch (IOException e) { log.error("unsearchedSitesFileWriter write failed."); } }
1e5da9cf-a051-4309-a735-ac903ce64e46
1
public static final String aAn(String text) { return Text.startsWithVowel(text) ? AN : A; }
817782ef-2de8-4b16-89b4-5de22a60c465
4
@Override public Player getPlayerById(Long id) { checkDataSource(); if (id == null) { throw new IllegalArgumentException("id is null"); } try (Connection conn = dataSource.getConnection(); PreparedStatement st = conn.prepareStatement("SELECT idname,surname,number,teamid,home,away,position FROM PLAYERS WHERE id = ?")) { st.setLong(1, id); ResultSet rs = st.executeQuery(); if (rs.next()) { Player player = resultSetToPlayer(rs); if (rs.next()) { throw new ServiceFailureException("Internal error: More entities with the same id found " + "(source id: " + id + ", found " + player + " and " + resultSetToPlayer(rs)); } return player; } else { return null; } } catch (SQLException ex) { String msg = "error when selecting player with id" + id; Logger.getLogger(TeamMngrImpl.class.getName()).log(Level.SEVERE, msg, ex); throw new ServiceFailureException(msg); } }
191324dd-1f71-4e09-ae9b-951194f056f8
0
private void addEncoder(Encoder encoder) { encoders.add(encoder); }
892a3862-0855-44e4-b6ba-ec01db2c8d86
0
public Long getIdConnection() { return idConnection; }
7f7e134d-c704-49f9-a184-324c293f9000
3
public static void print(RandomListNode a) { while (null != a) { int next = -1; int rand = -1; if (null != a.next) next = a.next.label; if (null != a.random) rand = a.random.label; System.out.println(a.label + "(" + next + "," + rand +")"); a = a.next; } }
2696bc60-17a4-42bd-8172-36e3076d4b3a
8
public void setRecursiveNotDirty() { super.setRecursiveNotDirty(); if(this.overlayXY!=null && this.overlayXY.isDirty()) { this.overlayXY.setRecursiveNotDirty(); } if(this.screenXY!=null && this.screenXY.isDirty()) { this.screenXY.setRecursiveNotDirty(); } if(this.rotationXY!=null && this.rotationXY.isDirty()) { this.rotationXY.setRecursiveNotDirty(); } if(this.size!=null && this.size.isDirty()) { this.size.setRecursiveNotDirty(); } this.isRotationDirty = false; }
e478c821-5cb6-41fb-8e63-07bfe9365e5e
6
private void init( File file ) { fullName = file ; String fileName = fullName.getName() ; int i1 = fileName.indexOf( '_' ) ; int i2 = fileName.indexOf( '.', -1 ) ; prefix = "" ; suffix = "" ; if ( i1 > 0 ) // has _ => filename with language extension { prefix = fileName.substring( 0, i1 ) ; if ( i2 > 0 ) { suffix = fileName.substring( i2 ) ; version = fileName.substring( i1 + 1, i2 ) ; } else // no valid suffix { version = fileName.substring( i1 + 1 ) ; } } else // no _ => no language extension { version = "" ; if ( i2 > 0 ) // only . in filename => no language extension { prefix = fileName.substring( 0, i2 ) ; suffix = fileName.substring( i2 ) ; } else // no _ and . => filename without fileextension like .properties { prefix = fileName ; } } if ( version.length() > 0 ) { // full structure "_languageID_countryID" = version i1 = version.indexOf( '_' ) ; if ( i1 > 1 ) // ignore any leading _ { country = version.substring( i1 + 1 ) ; lang = version.substring( 0, i1 ) ; i1 = country.indexOf("_") ; if ( i1 > 1) // variant available { String dummy = country ; country = dummy.substring(0, i1) ; variant = dummy.substring(i1+1) ; } } else { lang = version ; } } // System.out.println("filename #" +fileName +"# lang =" +lang +":") ; }
a3a4cf64-54c1-4413-a361-73e3ab01375f
7
public void evolve() throws GenerationEmptyException { /* @ \label{Population.java:evolve} @ */ if (generation == 0) { makeFirstGeneration(); } if (currentGeneration.size() <= 1) { throw new GenerationEmptyException("Current generation size " + currentGeneration.size() + " too small to evolve"); } // Record the new generation generation++; // Add the incoming boards to the current generation // Don't allow Population#add(GeneticBoard) to add more boards at the same time synchronized (incomingBoards) { currentGeneration.addAll(incomingBoards); incomingBoards.clear(); } // Pair up the boards by score and make children Collections.sort(currentGeneration); ArrayList<GeneticBoard> children = new ArrayList<GeneticBoard>(); GeneticBoard parent1; GeneticBoard parent2; GeneticBoard child; for (int i = 0; i < currentGeneration.size() - 1; i += 2) { // Get the next two parents parent1 = currentGeneration.get(i); parent2 = currentGeneration.get(i + 1); // Mate them childrenPerCouple times for (int j = 0; j < childrenPerCouple; j++) { child = parent1.merge(parent2); children.add(child); } } // Do elitist selection -- preserve the highest-scoring Board into the next generation GeneticBoard highest = currentGeneration.get(currentGeneration.size() - 1); children.add(highest); // Copy the unique children into childrenUnique /*@ \label{Population.java:unique} @*/ HashSet<String> uniqueGridStrings = new HashSet<String>(); ArrayList<GeneticBoard> childrenUnique = new ArrayList<GeneticBoard>(); for (GeneticBoard b : children) { if (!uniqueGridStrings.contains(b.gridToString())) { childrenUnique.add(b); uniqueGridStrings.add(b.gridToString()); // Score each unique Board b.generate(); } } // If the list is too big, truncate it, keeping only the top popCap Boards Collections.sort(childrenUnique); if (childrenUnique.size() > popCap) { childrenUnique.subList(0, childrenUnique.size() - popCap).clear(); } currentGeneration.clear(); currentGeneration.addAll(childrenUnique); }
0d468555-af85-43bb-994b-2d1824e799ba
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Cliente other = (Cliente) obj; if (idCliente == null) { if (other.idCliente != null) return false; } else if (!idCliente.equals(other.idCliente)) return false; return true; }
9b58cb72-f056-4fc7-b1ef-b1a0bfde477e
7
@Override public void removePlayer(Player player) { debug("Attempting to remove player " + player.getName()); int go = 0; for (ItemStack i : player.getInventory().getContents()) { if (i == null) continue; if (i.getType() == Material.GOLD_BLOCK) { go += i.getAmount(); } } if (go > 0) { addBlocks(go); } plugin.getSpawnDelays().remove(player.getName()); player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); player.getInventory().clear(); player.getInventory().setContents(pd.get(player.getName()).getPlayerInventory()); player.getInventory().setArmorContents(pd.get(player.getName()).getPlayerArmor()); GameMode m = pd.get(player.getName()).getPlayerGameMode(); if (player.getGameMode() != m) { player.setGameMode(m); } player.updateInventory(); pd.remove(player.getName()); player.teleport(plugin.getDump()); if (!reset) { sendGameMessage(player.getDisplayName() + ChatColor.RED + " has left the game"); } getPlayers().remove(player.getName()); if (b.getPlayers().contains(player.getName())) { b.getPlayers().remove(player.getName()); } else { r.getPlayers().remove(player.getName()); } debug(player.getName() + " has been removed successfully from the game"); }
5a2e2b0c-7fd5-4c84-8f51-bc6948ac0915
8
@Override public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) { if (cs instanceof Player) { final Player player = (Player) cs; if (args.length == 1) { final int mapid = Integer.parseInt(args[0]); if (mapid == 1 || mapid == 2 || mapid == 3) { if (mapid == 1) { Lobby.map1votes = Lobby.map1votes + 1; player.sendMessage(MessagesHandler.convert("Vote.Voted").replace("%mapid%", "1")); } else if (mapid == 2) { Lobby.map2votes = Lobby.map2votes + 1; player.sendMessage(MessagesHandler.convert("Vote.Voted").replace("%mapid%", "2")); } else if (mapid == 3) { Lobby.map3votes = Lobby.map3votes + 1; player.sendMessage(MessagesHandler.convert("Vote.Voted").replace("%mapid%", "3")); } else { //Wrong number //If this can happen anyhow :D player.sendMessage(MessagesHandler.convert("Vote.Syntax")); } } else { player.sendMessage(MessagesHandler.convert("Vote.Syntax")); } } else { player.sendMessage(MessagesHandler.convert("Vote.Syntax")); } } else { cs.sendMessage(MessagesHandler.noPlayer()); } return true; }
ab29c293-eec4-428d-9510-1411c23ba361
8
public void passagePert() { Fenetre.lePert.arcs = new ListeArcs(); for (int i = 0; i < Fenetre.lePert.sommets.size(); i++) { Sommet biparti1 = Fenetre.lePert.sommets.elementAt(i); for (int j = 0; j < Fenetre.lePert.sommets.size(); j++) { Sommet biparti2 = Fenetre.lePert.sommets.elementAt(j); for (int k = 0; k < biparti1.output.size(); k++) { Sommet leSommet3 = (Sommet) biparti1.output.elementAt(k); if (biparti2.input.contains(leSommet3)) { // System.out.println(" :::: " + biparti1.getNom() + // "->"+biparti2.getNom()); Arc leArc = new Arc(biparti1, biparti2); biparti2.ajouterPredecesseur(biparti1); biparti1.ajouterSuccesseur(biparti2); biparti1.sorties.addElement(leArc); biparti2.entrees.addElement(leArc); leArc.setNom(leSommet3.getNom()); Fenetre.lePert.arcs.addElement(leArc); // System.out.println(leArc.getNom() + " : " + // biparti1.getNom() + "->"+biparti2.getNom()); leArc.setValeur((int) biparti2.getDuree()); } } } } Iterator<Sommet> it = Fenetre.lePert.sommets.iterator(); while (it.hasNext()) { Sommet leSommet = it.next(); if ((leSommet.getSuccesseurs()).size() == 0) { Fenetre.lePert.puit = leSommet; break; } } Iterator<Sommet> it2 = Fenetre.lePert.sommets.iterator(); while (it2.hasNext()) { Sommet leSommet = it2.next(); if ((leSommet.getPredecesseurs()).size() == 0) { Fenetre.lePert.source = leSommet; break; } } leDebut.setNom("."); laFin.setNom("."); Arc alpha = new Arc(leDebut, Fenetre.lePert.source); alpha.setNom(Fenetre.leGraphe.source.getNom()); Arc omega = new Arc(Fenetre.lePert.puit, laFin); omega.setNom(Fenetre.leGraphe.puit.getNom()); Fenetre.lePert.source.entrees.addElement(alpha); Fenetre.lePert.puit.sorties.addElement(omega); Fenetre.lePert.arcs.addElement(alpha); Fenetre.lePert.arcs.addElement(omega); }
6253e635-48e2-4755-b4dd-af9a57e8c8bd
4
private double denari(ICard card) { //Una presa contiene anche la carta in esame List<List<ICard>> prese = Rules.getPrese(card, table.cardsOnTable()); if(prese.size() > 0){ double fp = 0.0; for(List<ICard> presa : prese) for(ICard c : presa) if(c.getSeed() == Seed.DENARI) fp+=0.3; return fp; } return 0.0; }
b49d6656-fcee-4fb3-862c-51b2de3a36dc
6
public double getMin() { if (total_size == 0) return Double.NaN; double min = Double.POSITIVE_INFINITY; if (type == Integer.class) { for (int i = 0; i < total_size; i++) { if (min > ((int[])vals)[i]) min = ((int[])vals)[i]; } } else { for (int i = 0; i < total_size; i++) { if (min > ((double[])vals)[i]) min = ((double[])vals)[i]; } } return min; }
10b7fd07-227b-46e8-bc11-2e4d69b96bf1
4
public static void main(String[] args) { int turn = DEFAULT_TURN; boolean vis = DEFAULT_VISUALIZE_FLG; Player p1 = null; Player p2 = null; try { String[] playerClass = new String[2]; int p = 0; for (int i = 0; i < args.length; i++) { if ("-turn".equals(args[i])) turn = Integer.valueOf(args[++i]); else if ("-vis".equals(args[i])) vis = true; else playerClass[p++] = args[i]; } p1 = Player.getInstance(PLAYERS_PACKAGE_NAME + "." + playerClass[0]); p2 = Player.getInstance(PLAYERS_PACKAGE_NAME + "." + playerClass[1]); } catch (Exception e) { System.out.println("Syntax error occurred."); System.out.println(""); System.out.println("Required Parameters:"); System.out.println(" Player1ClassName"); System.out.println(" Player2ClassName"); System.out.println("Optional Parameters:"); System.out.println(" -turn: set the number of games to be played (default to 100)"); System.out.println(" -vis: turn on the visualizer"); System.out.println(""); System.out.println("Ex1) HumanPlayer vs MinMaxPlayer"); System.out.println(" java -jar connect4.jar HumanPlayer MinMaxPlayer"); System.out.println("Ex2) AlphaBetaPlayer vs GreadyPlayer with visializer=on and turn=10"); System.out.println(" java -jar connect4.jar AlphaBetaPlayer GreadyPlayer -vis -turn 10"); System.out.println(""); return; } BatchController controller = new BatchController(turn, vis, p1, p2); controller.run(); }
729978b5-a33d-468a-ac6b-7d13881e5871
4
void parseCp() throws java.lang.Exception { char c; if (tryRead('(')) { dataBufferAppend('('); parseElements(); } else { dataBufferAppend(readNmtoken(true)); c = readCh(); switch (c) { case '?': case '*': case '+': dataBufferAppend(c); break; default: unread(c); break; } } }
a00038ee-9c9e-4bfe-a35c-90d20557535c
5
public ReturningProjectile createReturningProjectile(Actor source, String im, int sp, Point start, Point end, boolean f, boolean p, boolean dt, int d) { if (gameController.multiplayerMode != gameController.multiplayerMode.CLIENT) { ReturningProjectile projectile = new ReturningProjectile(this, registry, source, im, sp, start, end, f, p, dt, d); if (gameController.multiplayerMode == gameController.multiplayerMode.SERVER && registry.getNetworkThread() != null) { if (registry.getNetworkThread().readyForUpdates()) { UpdateProjectile up = new UpdateProjectile(); up.id = projectile.getId(); if (source != null) { up.playerId = source.getId(); } up.image = im; up.speed = sp; up.start = start; up.end = end; up.friendly = f; up.placeable = p; up.disregardTerrain = p; up.damage = d; up.action = "Create"; registry.getNetworkThread().sendData(up); } } registerProjectile(projectile); return projectile; } else { return null; } }
0f6e4632-4817-41ac-95f2-59088951eff0
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(Evasao1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Evasao1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Evasao1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Evasao1.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 Evasao1().setVisible(true); } }); }
b26c0311-fec6-45ea-bc0e-76350248a5cd
3
@Override public TestResult test(Object input, Void... args) { //如果不是基本类型 if( !InputType.isPrimitiveType(input) ){ throw new IllegalArgumentException("Parameter 'input' ONLY support primitive type."); } String inputS = String.valueOf(input); boolean passed = inputS.length() >= 0 && !inputS.trim().replaceAll("\\s", "").equals(""); String message = passed ? null : messageT; return new TestResult(passed, message); }
1478aa95-a3d7-4035-8638-9586809ca084
3
public ClientModel(ServerModel serverModel) { this.serverModel = serverModel; gameModel = new GameModel(serverModel); HashMap<String, CatanColor> playerColorMap = this.getPlayerColorMap(); log = new ArrayList<client.communication.CommsLogEntry>(); chat = new ArrayList<client.communication.CommsLogEntry>(); if(serverModel != null) { for(LogEntry entry : serverModel.getLog().getLogMessages()) { log.add(new client.communication.CommsLogEntry(playerColorMap.get(entry.getSource()), entry.getMessage())); } for(LogEntry chatMessage : serverModel.getChat().getMessages()) { chat.add(new client.communication.CommsLogEntry(playerColorMap.get(chatMessage.getSource()), chatMessage.getMessage())); } } }
ca2f685c-3541-49f2-a5b7-7c5caa3e6cce
8
protected Room alternativeLink(Room room, Room defaultRoom, int dir) { if(room.getGridParent()==this) for(int d=0;d<gridexits.size();d++) { final CrossExit EX=gridexits.elementAt(d); try { if((EX.out)&&(EX.dir==dir) &&(getGridRoomIfExists(EX.x,EX.y)==room)) { final Room R=CMLib.map().getRoom(EX.destRoomID); if(R!=null) { if(R.getGridParent()!=null) return R.getGridParent(); return R; } } } catch(final Exception e) { } } return defaultRoom; }
96428f95-0fed-44bb-bf7a-b7a1f004daee
9
public void newGame() { spaces = new Space[height][]; int col = 0; for(int y = 0; y < height; y++) { spaces[y] = new Space[width]; for(int x = 0; x < width; x++) { if(col == 0) spaces[y][x] = new BlackSpace(y, x); else spaces[y][x] = new WhiteSpace(y, x); col = 1 - col; } col = 1 - col; } col = 1; for(int y = 0; y < 3; y++) { for(int x = 0; x < width; x++) { if(col == 0) spaces[x][y].setChecker(new RedCheckerPiece(x, y)); col = 1 - col; } col = 1 - col; } col = 0; for(int y = height - 1; y > 4; y--) { for(int x = 0; x < width; x++) { if(col == 0) spaces[x][y].setChecker(new BlackCheckerPiece(x, y)); col = 1 - col; } col = 1 - col; } }
1c8b106c-5589-4760-b84e-020fca6f60b0
4
public List<Entity> getEntitiesContainingAny(Class<?>... componentClassList) { List<Entity> entityList = new LinkedList<Entity>(); for (Class<?> clazz : componentClassList) { // Get all entities that have this component HashMap<Entity, IComponent> entityMap = registeredComponents.get(clazz); // Remember we might get a null entityMap if (entityMap != null) { // Add all of the entities to the entityList entityList.addAll(new LinkedList<Entity>(entityMap.keySet())); } } return entityList; }
9c8cec7d-c545-4583-9497-ff94e58097a8
3
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof MasterDataEntity)) { return false; } MasterDataEntity other = (MasterDataEntity) object; if (this.id == null ? other.id != null : !this.id.equals(other.id)) { return false; } return true; }
1bacdaf6-035c-41ba-86f9-0f9443ff1cbd
5
private void checkPitch() { if( channel != null && channel.attachedSource == this && LibraryLWJGLOpenAL.alPitchSupported() && channelOpenAL != null && channelOpenAL.ALSource != null ) { AL10.alSourcef( channelOpenAL.ALSource.get( 0 ), AL10.AL_PITCH, pitch ); checkALError(); } }