text
stringlengths
14
410k
label
int32
0
9
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
protected void TrusteeMF() { for (int iter = 1; iter <= numIters; iter++) { loss = 0; errs = 0; // gradients of B, V, W DenseMatrix BS = new DenseMatrix(numUsers, numFactors); DenseMatrix WS = new DenseMatrix(numUsers, numFactors); DenseMatrix VS = new DenseMatrix(numItems, numFactors); // rate matrix for (MatrixEntry me : trainMatrix) { int u = me.row(); int j = me.column(); double ruj = me.get(); if (ruj > 0) { double pred = predict(u, j, false); double euj = g(pred) - normalize(ruj); loss += euj * euj; errs += euj * euj; double csgd = gd(pred) * euj; for (int f = 0; f < numFactors; f++) { WS.add(u, f, csgd * Ve.get(j, f) + regU * We.get(u, f)); VS.add(j, f, csgd * We.get(u, f) + regI * Ve.get(j, f)); loss += regU * We.get(u, f) * We.get(u, f); loss += regI * Ve.get(j, f) * Ve.get(j, f); } } } // social matrix for (MatrixEntry me : socialMatrix) { int k = me.row(); int u = me.column(); double tku = me.get(); if (tku > 0) { double pred = DenseMatrix.rowMult(Be, k, We, u); double euj = g(pred) - tku; loss += regS * euj * euj; double csgd = gd(pred) * euj; for (int f = 0; f < numFactors; f++) { WS.add(u, f, regS * csgd * Be.get(k, f) + regU * We.get(u, f)); BS.add(k, f, regS * csgd * We.get(u, f) + regU * Be.get(k, f)); loss += regU * We.get(u, f) * We.get(u, f); loss += regU * Be.get(k, f) * Be.get(k, f); } } } Be = Be.add(BS.scale(-lRate)); Ve = Ve.add(VS.scale(-lRate)); We = We.add(WS.scale(-lRate)); loss *= 0.5; errs *= 0.5; if (isConverged(iter)) break; } }
8
public void union(int x, int y) { if (x == y) { return; } x = find(x); y = find(y); if (rank[x] < rank[y]) { root[x] = y; rank[y]++; } else { root[y] = x; rank[x]++; } }
2
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || this.getClass() != o.getClass()) { return false; } Dictionary n = (Dictionary) o; return dictionary.equals(n.dictionary); }
3
private void harvest(Level level, int x, int y) { int age = level.getData(x, y); int count = random.nextInt(2); for (int i = 0; i < count; i++) { level.add(new ItemEntity(new ResourceItem(Resource.seeds), x * 16 + random.nextInt(10) + 3, y * 16 + random.nextInt(10) + 3)); } count = 0; if (age == 50) { count = random.nextInt(3) + 2; } else if (age >= 40) { count = random.nextInt(2) + 1; } for (int i = 0; i < count; i++) { level.add(new ItemEntity(new ResourceItem(Resource.wheat), x * 16 + random.nextInt(10) + 3, y * 16 + random.nextInt(10) + 3)); } level.setTile(x, y, Tile.dirt, 0); }
4
public void init(String url, String saveTo, boolean logging, boolean allowReadCache, boolean forceTagging) { state = UIState.START; textFieldDirectory.setText(saveTo); chckbxLog.setSelected(logging); chckbxUseCache.setSelected(allowReadCache); chckbxForceTag.setSelected(forceTagging); try { rootPage = AbstractPage.bakeAPage(null, url, saveTo, null); textFieldURL.setText(rootPage.url.toString()); } catch (IllegalArgumentException e) { return; } lblStatus.setText("Press 'Check' button"); setRootNodeForRootPage(); enableButtons(); if (AUTO_PREFETCH) { initPrefetch(); state = UIState.READCACHEPAGES; } else { // no auto-update btnUpdate.setEnabled(false); } }
2
public static String toString(JSONObject jo) throws JSONException { boolean b = false; Iterator keys = jo.keys(); String string; StringBuffer sb = new StringBuffer(); while (keys.hasNext()) { string = keys.next().toString(); if (!jo.isNull(string)) { if (b) { sb.append(';'); } sb.append(Cookie.escape(string)); sb.append("="); sb.append(Cookie.escape(jo.getString(string))); b = true; } } return sb.toString(); }
3
private static String join(final String[] args, final String delim) { if (args == null || args.length == 0) return ""; final StringBuilder sb = new StringBuilder(); for (final String s : args) sb.append(s + delim); sb.delete(sb.length() - delim.length(), sb.length()); return sb.toString(); }
3
public Module getModuleByChain(List<String> chain) { int index = 0, size = chain.size(); Module module = getRootModule(); while(null != module && index < size) { module = module.getSubModule(chain.get(index++)); } return module; }
2
private Opcode toOpcode( byte opcode ) throws InvalidFrameException { switch ( opcode ) { case 0: return Opcode.CONTINUOUS; case 1: return Opcode.TEXT; case 2: return Opcode.BINARY; // 3-7 are not yet defined case 8: return Opcode.CLOSING; case 9: return Opcode.PING; case 10: return Opcode.PONG; // 11-15 are not yet defined default : throw new InvalidFrameException( "unknow optcode " + (short) opcode ); } }
6
private void printSeries (int fizzNumber, int buzzNumber, int limit) { for (int i = 1; i <= limit; i++) { if (i % fizzNumber == 0 && i % buzzNumber == 0) { System.out.print("FB"); } else if (i % fizzNumber == 0) { System.out.print("F"); } else if (i % buzzNumber == 0) { System.out.print("B"); } else { System.out.print(i); } if (i != limit) { System.out.print(" "); } } System.out.println(); }
6
private boolean checkDuplicate(int vx, int vy){ for(int i=0; i<_X.size(); i++){ if(_X.get(i)==vx){ if(_Y.get(i)==vy){ return false; } } } return true; }
3
private int readInteger(SeekableStream in) throws IOException { int ret = 0; boolean foundDigit = false; int b; while ((b = in.read()) != -1) { char c = (char)b; if (Character.isDigit(c)) { ret = ret * 10 + Character.digit(c, 10); foundDigit = true; } else { if (c == '#') { // skip to the end of comment line int length = lineSeparator.length; while ((b = in.read()) != -1) { boolean eol = false; for (int i = 0; i < length; i++) { if (b == lineSeparator[i]) { eol = true; break; } } if (eol) { break; } } if (b == -1) { break; } } if (foundDigit) { break; } } } return ret; }
9
RedisConstants() { String env = System.getenv(this.name()); if (env == null) { env = System.getProperty(this.name()); if (env == null) { throw new RuntimeException("Property:" + this.name() + " is not an env or property"); } } value = env; }
2
private void advance() { while (delegate.hasNext()) { T element = delegate.next(); if (filter.accept(element)) { next = element; return; } } next = null; }
2
public void removeDeadFlyUps() { List<FlyUp> toDelete = new ArrayList<FlyUp>(); for(FlyUp fly:flyups) { if(fly.timeSinceCreation() >= 3300) toDelete.add(fly); } for(FlyUp fly:toDelete) { flyups.remove(fly); } }
3
public void moveAll(String name, GameObject object) { Chest c = null; Avatar a = null; String loc = null; ArrayList<GameObject> shadowChest = new ArrayList<GameObject>(); for (Avatar v : avatarLocations.keySet()) { if (v.getName().equals(name)) { a = v; loc = v.getLocationName(); } } for (GameObject o : locations.get(loc).getAllObjects()) { if (o.getName().equals(object.getName())) { c = (Chest) o;// } } if(c.getContents().size() > 0){ for(GameObject ob: c.getContents()){ if(a.canContain((Containable) ob)){ a.getPosessions().add((Containable) ob); shadowChest.add(ob); } } } for(GameObject obj: shadowChest){ c.getContents().remove(obj); } }
8
protected ArrayList<Location> getMoveLocations() { ArrayList<Location> moveLocs = new ArrayList<Location>(); int facingDirection = getDirection(); Location loc = getLocation(); //Find and test all locations half left, in front, and half right of location of this for(int moveDirection = facingDirection + Location.HALF_LEFT; moveDirection <= facingDirection + Location.HALF_RIGHT; moveDirection += Location.HALF_RIGHT) { Location testLoc = loc.getAdjacentLocation(moveDirection); if(canInOneStepMoveFromTo(getLocation(), testLoc)) moveLocs.add(testLoc); } return moveLocs; }
2
@Override public void setEnvFlags(Environmental E, int f) { if(E instanceof Item) { final Item item=(Item)E; // deprecated, but unfortunately, its here to stay. CMLib.flags().setDroppable(item,CMath.bset(f,1)); CMLib.flags().setGettable(item,CMath.bset(f,2)); CMLib.flags().setReadable(item,CMath.bset(f,4)); CMLib.flags().setRemovable(item,CMath.bset(f,8)); } else if(E instanceof Exit) { final Exit exit=(Exit)E; exit.setReadable(CMath.bset(f,4)); } if(E instanceof CloseableLockable) { final CloseableLockable container=(CloseableLockable)E; if((CMath.bset(f, 16))||(E instanceof Exit)) // this will be a 'new method' flag { final boolean hasDoor=CMath.bset(f,32); final boolean hasLock=CMath.bset(f,64); final boolean defaultsClosed=CMath.bset(f,128); final boolean defaultsLocked=CMath.bset(f,256); container.setDoorsNLocks(hasDoor,(!hasDoor)||(!defaultsClosed),defaultsClosed,hasLock,hasLock&&defaultsLocked,defaultsLocked); } else { final boolean hasDoor=CMath.bset(f,32); final boolean hasLock=CMath.bset(f,64); container.setDoorsNLocks(hasDoor,!hasDoor,hasDoor,hasLock,hasLock,hasLock); } } }
7
public Unmark(int marker, int state) { this.state = state; this.marker = marker; }
0
public void dessineTousNoeud(Graphics g) { // Si il n'y a pas d'itineraire d�fini, alors // il n'y a pas de noeud if (itineraire == null) return;// ...donc on quitte /* * Cette liste contient toutes les adresse de livraison deja livre qui * ne doivent pas etre redessine car leur couleur doit rester celle de * leur plage horaire (y compris si elle sont de simple point de passage * pour d'autre trajet) */ HashMap<String, Color[]> adresse_deja_livre = new HashMap<String, Color[]>(); /* * Cette liste contient pour chaque noeud le nombre de couleur * differentes (donc de plage horaire) auquel il appartient */ HashMap<String, Color[]> noeud_passage_passe = new HashMap<String, Color[]>(); NoeudItineraire entrepot = itineraire.getEntrepot(); int i = 0; // On commence par dessiner tout les noeuds sur le trajet qui part de // l'entrepot if (calculated) { dessineNoeudsDeTrajetSuivantNI(entrepot, g, couleurs[i % Constantes.NB_COLORS], adresse_deja_livre, noeud_passage_passe); } // Ensuite, pour chaque livraison de chaque plage horraire List<PlageHoraire> plages = itineraire.getPlagesHoraire(); for (PlageHoraire plage : plages) { List<Livraison> livraisons = plage.getAllLivraison(); for (Livraison livraison : livraisons) { /* * ...on dessine les noeuds appartenant au trajet qui part du * point de livraison parcourus (si ce ne sont pas des point de * livraion d�j� parcourus) */ if (calculated) { dessineNoeudsDeTrajetSuivantNI(livraison, g, (color_node_comme_plage ? couleurs[i % Constantes.NB_COLORS] : c_noeud), adresse_deja_livre, noeud_passage_passe); } // ...puis on dessine le point de livraison lui m�me dessineNoeudItineraire(livraison, g, couleurs[i % Constantes.NB_COLORS], adresse_deja_livre); // adresse_deja_livre.add(livraison.getAdresse().toString()); } i++; } // On dessine l'entrepot en dernier pour eviter qu'il ne soit colorier // comme un point de passage d'un trajet dessineNoeudItineraire(entrepot, g, c_entrepot, adresse_deja_livre); }
6
public List<Graph> getErrorToProgressGraph() { Map<Integer, Double> timeProgress = new HashMap<Integer, Double>(); Map<Integer, Integer> timeCount = new HashMap<Integer, Integer>(); Map<Integer, Double> stepsProgress = new HashMap<Integer, Double>(); Map<Integer, Integer> stepsCount = new HashMap<Integer, Integer>(); Graph time = new Graph("Time Error", "Progress (steps)", "Error (s)", lineLabel); Graph steps = new Graph("Steps Error", "Progress (steps)", "Error (steps)", lineLabel); for (Error e : errors) { int progress = e.getUnit() == PredictionUnit.Milliseconds ? e.getProgressPercentage() / 10 * 10 : e.getAbsolutePathLength(); progress = e.getAbsolutePathLength(); if(e.getUnit() == PredictionUnit.Milliseconds) { if(!timeProgress.containsKey(progress)) { timeProgress.put(progress, 0.0); timeCount.put(progress, 0); } timeProgress.put(progress, timeProgress.get(progress) + e.getError()); timeCount.put(progress, timeCount.get(progress) + 1); } else { if(!stepsProgress.containsKey(progress)) { stepsProgress.put(progress, 0.0); stepsCount.put(progress, 0); } stepsProgress.put(progress, stepsProgress.get(progress) + e.getError()); stepsCount.put(progress, stepsCount.get(progress) + 1); } } for(int p : timeProgress.keySet()) { time.addDataPoint(p, timeProgress.get(p) / timeCount.get(p)); } for(int p : stepsProgress.keySet()) { steps.addDataPoint(p, stepsProgress.get(p) / stepsCount.get(p)); } List<Graph> result = new ArrayList<Graph>(); result.add(time); result.add(steps); return result; }
7
private void doHearbeats() { new Timer().schedule(new TimerTask() { @Override public void run() { // this code will be executed after 5 seconds masterLogger.logMessage("===>> Heartbeats @ sec = " + executionTime); for (Iterator<Entry<Integer, ReplicaLoc>> iterator = replicaPaths .entrySet().iterator(); iterator.hasNext();) { Entry<Integer, ReplicaLoc> entry = iterator.next(); ReplicaLoc repl = entry.getValue(); String replLoc = repl.location; int replPort = repl.replicaPort; // Reading from replica Registry registryReplica1 = null; try { registryReplica1 = LocateRegistry.getRegistry(replLoc, replPort); } catch (RemoteException e) { e.printStackTrace(); } ReplicaServerClientInterface replHandler = null; try { replHandler = (ReplicaServerClientInterface) registryReplica1 .lookup(Global.REPLICA_LOOKUP); } catch (RemoteException | NotBoundException e) { e.printStackTrace(); } try { if (!replHandler.checkIsAlive()) { masterLogger.logMessage("Replica #" + replHandler.getReplicaID() + " is NOT alive !"); } else { masterLogger.logMessage("Replica #" + replHandler.getReplicaID() + " is alive !"); } } catch (RemoteException e) { e.printStackTrace(); } } masterLogger.logMessage("===>> Heartbeats END"); executionTime += 60; doHearbeats(); } }, 60 * 1000); }
5
@Override public String toString() { StringBuffer s = new StringBuffer(); for (Student student : students) { s = s.append(student).append(System.lineSeparator()); } return s.toString(); }
1
public ImageIcon loadIcon(String image){ try { return new ImageIcon(ImageIO.read(new File(image))); } catch (Exception e) { e.printStackTrace(); } return null; }
1
public Admin lookup(String username) throws DAOPoikkeus { Admin admin; Connection connection = avaaYhteys(); String sql = "select id, username, password_hash, salt from Admin where username = ?"; try { PreparedStatement usernameLookup = connection.prepareStatement(sql); usernameLookup.setString(1, username); ResultSet rs = usernameLookup.executeQuery(); //Jos käyttäjätunnuksella löytyy käyttäjä kannasta luodaan Admin-luokan olio if(rs.next()) { admin = new Admin(rs.getInt("id"), rs.getString("username"), rs.getString("salt"), rs.getString("password_hash")); } //Tarvitaan, jotta kirjautumisen yrittäminen kestäisi väärällä käyttäjätunnuksellakin yhtä kauan(estää käyttäjätunnusten kalastelua tietokannasta) else { admin = new Admin(-1, "-", "-", "-"); } } catch(SQLException e) { throw new DAOPoikkeus("Tietokantahaku aiheutti virheen."); } finally { suljeYhteys(connection); } return admin; }
2
public void rewindNbytes(int N) { int bits = (N << 3); totbit -= bits; buf_byte_idx -= bits; if (buf_byte_idx<0) buf_byte_idx += BUFSIZE; }
1
public List<Double> decode(Chromosome chromosome) { if (chromosome.size() % 2 != 0) throw new IllegalArgumentException( "Chromosomze length must be an even number."); if (decimalPlaces < 0) throw new IllegalArgumentException("decimalPlaces must be >= 0"); List<Double> list = new LinkedList<Double>(); int splitIndex = chromosome.size() / 2; double valueA = 0; double valueB = 0; int base; /* * Note we stop before the first bit of each number's chromosome. * * This is intentional, as this bit is not part of the number itself * but instead represents whether the number is positive (false) or * negative (true). */ base = 1; for (int i = splitIndex - 1; i >= 1; base *= 2) valueA += chromosome.get(i--) ? base : 0; base = 1; for (int i = chromosome.size() - 1; i >= splitIndex + 1; base *= 2) valueB += chromosome.get(i--) ? base : 0; /* * Convert to a floating-point numbers per 'decimalPlaces' argument. */ for (int i = 0; i < decimalPlaces; i += 1) { valueA *= 0.1; valueB *= 0.1; } if (chromosome.get(0)) valueA *= (-1); if (chromosome.get(splitIndex)) valueB *= (-1); list.add(valueA); list.add(valueB); return list; }
9
public static void main(String[] args) { /*** * Dear TA's, * * There are certainly better ways of doing unit testing... * I know this isn't software practices so I won't complain. However * it may be advisable in the future to allow JUnit or frameworks of * our own creation. * * <3 <3 <3 <3 <3 */ { //region Equals //Cross object test String a = "asd"; Matrix m = new Matrix(new int[][]{{10,10},{5,12}}); if(m.equals(a)) System.out.println("EQUALS TEST: Cross object comparison failed"); else System.out.println("EQUALS TEST: Cross object comparison succeeded"); //Bounds comparison Matrix o = new Matrix(new int[][]{{10, 10}}); if(m.equals(o)) System.out.println("EQUALS TEST: Cross matrix bounds comparison failed"); else System.out.println("EQUALS TEST: Cross matrix bounds comparison succeeded"); //Element wise comparison o = new Matrix(new int[][]{{10, 10}, {5, 12}}); if(m.equals(o)) System.out.println("EQUALS TEST: Element matrix comparison succeeded"); else System.out.println("EQUALS TEST: Element matrix comparison failed"); //end } { //region Multiplication //Bounds test Matrix a = new Matrix(new int[][]{{10}}); Matrix b = new Matrix(new int[][]{{10,10},{10,10},{15,15}}); if(a.times(b) == null) System.out.println("MULTIPLICATION TEST: " + "Bounds comparison->null-pointer succesful; error successfully triggered"); else System.out.println("MULTIPLICATION TEST: " + "Bounds comparison->null-pointer failed"); //Addition test Matrix M1 = new Matrix(new int[][] {{1, 2, 3}, {2, 5, 6}}); Matrix M2 = new Matrix(new int[][] {{4, 5}, {3, 2}, {1, 1}}); // this is the known correct result of multiplying M1 by M2 Matrix M1_M2 = new Matrix(new int[][] {{13, 12}, {29, 26}}); if(M1.times(M2).equals(M1_M2)) System.out.println("MULTIPLICATION TEST: " + "Two matrices successfully added:\n" + M1 + "\n" + "****\n" + M2 + "\n" + "====\n" + M1.times(M2)); else System.out.println("MULTIPLICATION TEST: " + "Two matrices failed to add:\n" + M1 + "\n" + "****\n" + M2 + "\n" + "====\n" + M1.times(M2) +"\n" + "Should be--\n" + M1_M2); //end } { //region Addition //Bounds test Matrix a = new Matrix(new int[][]{{10}}); Matrix b = new Matrix(new int[][]{{10,10},{10,10},{15,15}}); if(a.plus(b) == null) System.out.println("ADDITIONS TEST: " + "Bounds comparison->null-pointer succesful"); else System.out.println("ADDITIONS TEST: " + "Bounds comparison->null-pointer failed"); //Addition test Matrix M1 = new Matrix(new int[][] {{1,2,3}, {4,5,6}}); Matrix M2 = new Matrix(new int[][] {{7,8,9}, {10,11,12}}); Matrix M1_M2 = new Matrix(new int[][] {{8,10,12}, {14,16,18}}); if(M1.plus(M2).equals(M1_M2)) System.out.println("ADDITIONS TEST: " + "Two matrices successfully added:\n" + M1 + "\n" + "++++\n" + M2 + "\n" + "====\n" + M1.plus(M2)); else System.out.println("ADDITIONS TEST: " + "Two matrices failed to add:\n" + M1 + "\n" + "++++\n" + M2 + "\n" + "====\n" + M1.plus(M2) +"\n" + "Should be--\n" + M1_M2); } //end int runsB = 100000; //PERFORM FINAL EXHAUSTIVE BOUNDS TEST System.out.println("\n\nRunning exhaustive bounds test at: " + runsB); if(MatrixTester.exhaustiveBoundsChecking(runsB)) System.out.println("Bounds checking successful; tests succeded"); else System.out.println("Bounds checking FAILED; one or more tests failed"); }
8
private void updatePistonState(World par1World, int par2, int par3, int par4) { int var5 = par1World.getBlockMetadata(par2, par3, par4); int var6 = getOrientation(var5); boolean var7 = this.isIndirectlyPowered(par1World, par2, par3, par4, var6); if (var5 != 7) { if (var7 && !isExtended(var5)) { if (canExtend(par1World, par2, par3, par4, var6)) { par1World.setBlockMetadata(par2, par3, par4, var6 | 8); par1World.sendClientEvent(par2, par3, par4, 0, var6); } } else if (!var7 && isExtended(var5)) { par1World.setBlockMetadata(par2, par3, par4, var6); par1World.sendClientEvent(par2, par3, par4, 1, var6); } } }
6
private List<Issue> searchIssues(User visitor, Long creator, Long assignee, String title, String priority, String status) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Issue> criteriaQuery = criteriaBuilder.createQuery(Issue.class); Root<Issue> from = criteriaQuery.from(Issue.class); List<Predicate> predicates = new ArrayList<Predicate>(); if (!Utils.isEmpty(creator)) { predicates.add(criteriaBuilder.equal(from.get("creator"), creator)); } if (!Utils.isEmpty(assignee)) { predicates.add(criteriaBuilder.equal(from.get("assignee"), assignee)); } if (!Utils.isEmpty(title)) { predicates.add(criteriaBuilder.like(from.<String>get("title"), "%" + title + "%")); } if (!Utils.isEmpty(priority)) { predicates.add(criteriaBuilder.equal(from.get("priority"), Priority.valueOf(priority))); } if (!Utils.isEmpty(status)) { predicates.add(criteriaBuilder.equal(from.get("status"), Status.valueOf(status))); } if (predicates.size() > 0) { criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])); } TypedQuery<Issue> typedQuery = entityManager.createQuery(criteriaQuery.select(from)); List<Issue> issues = typedQuery.getResultList(); issues = Utils.filter(issues, new IssuesFilter(visitor)); Collections.sort(issues, new IssuesComparator()); return issues; }
6
public final void initUI() { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.setBorder(BorderFactory.createEmptyBorder(40, 40, 40, 40)); setLayout(new BorderLayout()); panel.add(Box.createHorizontalGlue()); slider = new JSlider(0, 150, 0); slider.setPreferredSize(new Dimension(150, 30)); slider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent event) { int value = slider.getValue(); if (value == 0) { label.setIcon(mute); } else if (value > 0 && value <= 30) { label.setIcon(min); } else if (value > 30 && value < 80) { label.setIcon(med); } else { label.setIcon(max); } } }); panel.add(slider); panel.add(Box.createRigidArea(new Dimension(5, 0))); label = new JLabel(mute, JLabel.CENTER); panel.add(label); panel.add(Box.createHorizontalGlue()); add(panel, BorderLayout.CENTER); pack(); setTitle("JSlider"); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); }
5
public static void bellmanFord(int s) { dist[s] = 0; for (int k = 0; k < V - 1; k++) for (int i = 0; i < V; i++) for (int j = 0; j < adj[i].size(); j++) { Edge neigh = adj[i].get(j); int v = neigh.v, p = neigh.p; if (dist[i] != INF && dist[i] + p < dist[v]) dist[v] = dist[i] + p; } for (int u = 0; u < V; u++) for (int j = 0; j < adj[u].size(); j++) { Edge neigh = adj[u].get(j); int v = neigh.v, p = neigh.p; if (dist[u] != INF && dist[u] + p < dist[v]) { dist[v] = dist[u] + p; cycle[v] = true; } } }
9
private void idct_direct(double F[][], double f[][]) { double a[] = new double[N]; a[0] = sqrt(1. / N); for (int i = 1; i < N; i++) { a[i] = sqrt(2. / N); } double summ = 0; double koeff = 0; for (short i = 0; i < N; i++) { for (short j = 0; j < N; j++) { summ = 0.; for (short u = 0; u < N; u++) { for (short v = 0; v < N; v++) { koeff = cos((2 * j + 1) * v * PI / (2 * N)) * cos((2 * i + 1) * u * PI / (2 * N)); summ += a[u] * a[v] * F[u][v] * koeff; } f[i][j] = summ; } } } }
5
public static void editEmployee() { System.out.print("Pick employee number: "); int choice = scInt.nextInt(); Prototype temp; if ((choice > employeeList.size()) || (choice < 1)) { System.err.println("Fatal Error! Number not on list!"); System.exit(1); } temp = employeeList.get(choice - 1); employeeList.remove(choice - 1); System.out.print("Edit name? [y/n]"); String choice1 = scString.nextLine(); if (choice1.toLowerCase().equals("y")) { String name = ""; do { System.out.print("Enter name: "); name = scString.nextLine(); if (!isValidName(name)) { System.out.println("Not valid; try again!"); } } while (!isValidName(name)); temp.setName(name); } System.out.print("Edit title? [y/n]"); choice1 = scString.nextLine(); if (choice1.toLowerCase().equals("y")) { System.out.print("\nEnter title: "); String title = scString.nextLine(); temp.setTitle(title); } System.out.print("Add task? [y/n]"); choice1 = scString.nextLine(); while (choice1.toLowerCase().equals("y")) { temp.addTask(); System.out.print("Add another task? [y/n]"); choice1 = scString.nextLine(); } System.out.print("Complete task? [y/n]"); choice1 = scString.nextLine(); while (choice1.toLowerCase().equals("y")) { if (temp.getTasksToDo().size() == 0) { System.out.println("No tasks to complete!"); break; } temp.completeTask(); System.out.print("Complete another task? [y/n]"); choice1 = scString.nextLine(); } employeeList.add(temp); goToMainMenu(); }
9
private void pause() throws InterruptedException { if (ponderFactor == 0) return; TimeUnit.MILLISECONDS.sleep(rand.nextInt(ponderFactor * 250)); }
1
public static int parseTime(final String time) { int sum = 0; String buffer = ""; for (int i = 0; i < time.length(); i++) { final char c = time.charAt(i); if (Character.isDigit(c)) { buffer += c; } else { int amount = Integer.parseInt(buffer); switch (String.valueOf(c)) { case "s": sum += amount; break; case "m": sum += 60 * amount; break; case "h": sum += 60 * 60 * amount; break; case "d": sum += 60 * 60 * 24 * amount; break; case "w": sum += 60 * 60 * 24 * 7 * amount; break; case "y": sum += 60 * 60 * 24 * 365 * amount; break; } buffer = ""; } } if (sum == 0) { return 0; } return ((int) (System.currentTimeMillis() / 1000L)) + sum; }
9
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(!sender.hasPermission(pluginMain.pluginManager.getPermission("thf.trains"))){ sender.sendMessage(""); return true; } if(!(sender instanceof Player)){ sender.sendMessage(ChatColor.DARK_RED + "You cannot console train!"); return true; } final Player player = (Player) sender; player.getWorld().spawnEntity(player.getLocation(), EntityType.MINECART); for(org.bukkit.entity.Entity entity : player.getNearbyEntities(player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ())){ if(entity.getType() == EntityType.MINECART){ entity.setVelocity(player.getVelocity().multiply(2)); } } Bukkit.getScheduler().scheduleSyncDelayedTask(pluginMain, new Runnable(){ @Override public void run() { for(org.bukkit.entity.Entity entity : player.getNearbyEntities(player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ())){ if(entity.getType() == EntityType.MINECART){ entity.getLocation().getWorld().createExplosion(entity.getLocation(), 0F); entity.remove(); } } } }, 20L); return false; }
6
private void initSymbolTable() { symbolTable = new SymbolTable(); symbolTable.setParent(null); symbolTable.setDepth(0); symbolTable.insert("readInt"); symbolTable.insert("readFloat"); symbolTable.insert("printBool"); symbolTable.insert("printInt"); symbolTable.insert("printFloat"); symbolTable.insert("println"); }
0
public ArrayList<Player> getPlayersInRadius(Entity e, int radius){ ArrayList<Player> result = new ArrayList<Player>(); float ex = e.getX(); float ey = e.getY(); for(int i = 0; i < players.size(); i++){ Player entity = players.get(i); float x = entity.getX(); float y = entity.getY(); float dx = Math.abs(x - ex); float dy = Math.abs(y - ey); double distance = Math.sqrt((dx * dx) + (dy * dy)); if(distance <= radius) result.add(entity); } return result; }
2
private void jButtonChangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonChangeActionPerformed try { // TODO add your handling code here: char[] mdp = jPasswordFieldOldPass.getPassword(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < mdp.length; i++) { sb.append(mdp[i]); } String oldpass = sb.toString(); mdp = jPasswordFieldNewPass.getPassword(); sb = new StringBuilder(); for (int i = 0; i < mdp.length; i++) { sb.append(mdp[i]); } String newpass = sb.toString(); mdp = jPasswordFieldConfPass.getPassword(); sb = new StringBuilder(); for (int i = 0; i < mdp.length; i++) { sb.append(mdp[i]); } String confpass = sb.toString(); Bibliothecaire intermed = MetierServiceFactory.getAdherentService().newBibliothecaire(bibliothecaire.getNom(), bibliothecaire.getPrenom(), bibliothecaire.getLogin(), oldpass, false); if(intermed.getMotDePasse().equals(bibliothecaire.getMotDePasse())) { if(newpass.equals(confpass)) { if(!newpass.equals(oldpass)) { editBiblio.setMdpEdited(newpass); jLabelStatut.setText("<html><body><font color='green'>Votre demande a été prise en compte</font></body></html>"); editBiblio.setStatut("<html><body><font color='orange'>Modification du mot de passe en attente...</font></body></html>"); this.dispose(); }else{ jLabelStatut.setText("<html><body><font color='red'>Ancien et nouveau mot de passe doivent être différents</font></body></html>"); } }else{ jLabelStatut.setText("<html><body><font color='red'>Les deux mots de passe doivent être identiques</font></body></html>"); } }else{ jLabelStatut.setText("<html><body><font color='red'>Ancien mot de passe incorrect</font></body></html>"); } } catch (Exception ex) { Logger.getLogger(ChangePass.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButtonChangeActionPerformed
7
public void genNotes(double c) { double totalProb = 0; // randomly generate Note length for (int i = 0; i < prob.length; i++) { if (possibleCount[i] <= c) { totalProb += prob[i]; } } double randGen = Math.random() * totalProb; int counter = -1; while (randGen > 0) { counter++; if (possibleCount[counter] <= c) { randGen -= prob[counter]; } } // randomly generate Note subtype randGen = Math.random(); if (randGen >= restChance) { list.add(new PlayNote(possibleCount[counter],minNote, maxNote, key)); } else { list.add(new RestNote(possibleCount[counter])); } try { } catch (Exception e) { } if(c-possibleCount[counter]>0) { genNotes(c - possibleCount[counter]); } return; }
7
public void setProblemList(ProblemList problemList) { this.problemList = problemList; }
0
public void run(int gen, ArrayList<Section> current, int semlen) { randomize(current); //randomize the order that the sections are in establish(current, semlen); //establish the population to chromosome length of semlen //Population is now set up, time to select for breeding int i = 0; ArrayList<Chromosome> pool; //overall pool ArrayList<Chromosome> toBreed; //lucky ones to breed this generation while (i < gen) { pool = new ArrayList<Chromosome>(); toBreed = new ArrayList<Chromosome>(); int POPMAX = population.size(); for(int j = 0; j < POPMAX; j++) { pool.add(population.poll()); } int prob = pool.size(); for(int j = 0; j < pool.size(); j++) { //having troubles here. Just breed everything for now if (j < prob) { toBreed.add(pool.get(j)); } }//end for if(toBreed.size() < 2) { //if we don't have enough to breed, don't for(int j = 0; j < POPMAX; j++) { population.add(pool.get(j)); } i++; continue; } int breedingSize = toBreed.size(); for(int j = 1; j < breedingSize; j+=2) { population.add( breed(toBreed.get(j - 1),toBreed.get(j), semlen) ); } for(int j = 0; j < POPMAX; j++) { population.add(pool.get(j)); } i++; //EVERY FEW GENERATIONS NEED TO CULL SOME OF THE SAMPLE if(population.size() > 1000) cull(population); System.out.println(population.size()); }// END WHILE }
9
public void affichageTableur(String pretexte, ArrayList<ArrayList<Integer>> al) { System.out.println(pretexte); System.out.println("["); for(ArrayList<Integer> mot : al) System.out.println("\tPosition : " + al.indexOf(mot) +"(" + tableurNonTrie.indexOf(mot) + ")\t" + mot); System.out.println("]"); }
1
protected void paintTabs(Graphics g, Rectangle clip, Insets insets) { int xOffset = getXOffset(); TabSet tabs = getTabSet(); int lastX = clip.x - 10; int maxX = clip.x + clip.width + 10; int maxY = getUnitsFontHeight() + TabHeight; double zoom=1.0f; if (getTextPane() instanceof JXMLNotePane) { zoom=((JXMLNotePane) getTextPane()).getZoomFactor(); } if (insets != null) { maxY += insets.top; } int nDPI=(int) Math.round(zoom*DPI); if ((nDPI%2)==1) { nDPI+=1; } if (tabs == null) { g.setColor(getSynthesizedTabColor()); // Paragraph treats a null tabset as a tab at every 72 pixels. // Different implementations of View used to represent a // Paragraph may not due this. lastX = Math.max(xOffset, lastX / nDPI * nDPI + xOffset % nDPI); while (lastX <= maxX) { paintTab(g, clip, null, (float)lastX, maxY, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE); lastX += DPI; } } else { TabStop tab; TabStop []_tabs=new TabStop[tabs.getTabCount()]; int i,N; for(i=0,N=tabs.getTabCount();i<N;i++) { TabStop st=tabs.getTab(i); _tabs[i]=new TabStop((int) Math.round(st.getPosition()*zoom),st.getAlignment(),st.getLeader()); } TabSet ttabs=new TabSet(_tabs); g.setColor(getTabColor()); do { tab = ttabs.getTabAfter((float)lastX + .01f); if (tab != null) { lastX = (int)tab.getPosition() + xOffset; if (lastX <= maxX) { paintTab(g, clip, tab, (float)lastX, maxY, tab.getAlignment(), tab.getLeader()); } else { tab = null; } } } while (tab != null); } }
9
public boolean createWhen(){ if(grade=='c' || grade=='b') return stage.count%(50*stage.fps/frequency+1)==0 && stage.second()>=startTime; else return stage.count%(300*stage.fps/frequency+1)==0 && stage.second()<=16 && stage.second()>=startTime; }
5
public static void cssDetails(File fileName, DetailObject detailObject) { detailObject.updateNumberOfFiles(); DetailObject.updateTOTAL_NUMBER_OF_FILES(); try { BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName)); String line; while ((line = bufferedReader.readLine()) != null) { if (line.trim().startsWith("/*")) { DetailObject.updateTOTAL_COMMENT_LINES(); detailObject.updateCommentLines(); while (line != null) { if (line.trim().contains("*/")) { break; } DetailObject.updateTOTAL_COMMENT_LINES(); detailObject.updateCommentLines(); line = bufferedReader.readLine(); } } else { DetailObject.updateTOTAL_LINES_OF_CODE(); detailObject.updateLineOfCode(); } } bufferedReader.close(); } catch (FileNotFoundException fileNotFoundException) { ExceptionLogger.fileNotFoundExceptionLogger(loggerBasicDetails, fileNotFoundException); } catch (IOException ioException) { ExceptionLogger.ioExceptionLogger(loggerBasicDetails, ioException); } MainGUI.getMAINGUI().updateDetails(detailObject); }
6
public void broadcastMessage(String message, Client client, boolean fromGame) { if (!fromGame && game != null && !game.parsePublicMessage(message, client)) { return; } message = KCodeParser.parse(message, !client.isModerator(), 5, 10, 20); message = Server.get().parseSmileys(message); if (message.isEmpty()) { return; } String msg = PacketCreator.publicMessage(client.getName(), name, message); for (Client c : getClients()) { c.send(msg); } }
5
public static boolean isTypeArray(Class<?> type) { return (type != null && type.isArray()); }
2
public static final List<Integer> getEnabledSecTypes() { List<Integer> result = new ArrayList<Integer>(); result.add(secTypeVeNCrypt); result.add(secTypeTight); for (Iterator<Integer> i = enabledSecTypes.iterator(); i.hasNext();) { int refType = (Integer)i.next(); if (refType < 0x100 && refType != secTypeTight) result.add(refType); } return (result); }
3
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ) { List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>( map.entrySet() ); Collections.sort( list, new Comparator<Map.Entry<K, V>>() { public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 ) { return (o1.getValue()).compareTo( o2.getValue() ); } } ); Map<K, V> result = new LinkedHashMap<K, V>(); for (Map.Entry<K, V> entry : list) { result.put( entry.getKey(), entry.getValue() ); } return result; }
2
public static Collection<Roll> getInstance(){ if(roll_list==null){ roll_list=new ArrayList<Roll>(); } return roll_list; }
1
protected BoundMethod match(PathPattern<Method> pattern, PathInput input, Object self) { Method method = pattern.getTarget(); if (method != null) { input.bind(method); pattern.match(input); return new BoundMethod(self, method, input.getParameters()); } else { return null; } }
1
public HTTPRequestHandler() { }
0
public Object remove(Object key) { accessTimes.remove(key); return map.remove(key); }//remove
0
@PUT @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON) public Response updateCustomer(final @PathParam("id") int id, Customer cust) { if (id != cust.getId()) { throw new WebApplicationException(Response.status(Status.CONFLICT) .entity("Cannot change id of existing customer.").build()); } validateCustomer(cust); checkIfCustomerExists(id); manager.updateCustomer(id, cust); return Response.ok("Customer with Id " + id + " udpated successfully").build(); }
1
public void addBall() { try { Ball ball = new Ball(); comp.add(ball); for (int i = 1; i <= STEPS; i++) { ball.move(comp.getBounds()); comp.paint(comp.getGraphics()); Thread.sleep(DELAY); } } catch (InterruptedException e) { } }
2
public void createItem(int newItemID) { int Maxi = server.itemHandler.DropItemCount; for (int i = 0; i <= Maxi; i++) { if (server.itemHandler.DroppedItemsID[i] < 1) { server.itemHandler.DroppedItemsID[i] = newItemID; server.itemHandler.DroppedItemsX[i] = (absX); server.itemHandler.DroppedItemsY[i] = (absY); server.itemHandler.DroppedItemsN[i] = 1; server.itemHandler.DroppedItemsH[i] = heightLevel; server.itemHandler.DroppedItemsDDelay[i] = (server.itemHandler.MaxDropShowDelay + 1); //this way the item can NEVER be showed to another client server.itemHandler.DroppedItemsDropper[i] = playerId; if (i == Maxi) { server.itemHandler.DropItemCount++; if (server.itemHandler.DropItemCount >= (server.itemHandler.MaxDropItems + 1)) { server.itemHandler.DropItemCount = 0; misc.println("! Notify item resterting !"); } } break; } } }
4
static public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; }
6
public void disconnect() { ClientDisconnectMessage cdm = new ClientDisconnectMessage(username); try { output.writeObject(cdm); } catch (IOException e) { System.out.println("Exception with sending disconnect message " + e); } try { if(input != null) input.close(); } catch(Exception e) {} try { if(output != null) output.close(); } catch(Exception e) {} try{ if(socket != null) socket.close(); } catch(Exception e) {} }
7
public void concatenar(Lista<E> pLista){ if(talla == 0){ cabeza = pLista.getHead(); talla = pLista.getTalla(); cola = pLista.getTail(); return; } cola.siguiente = pLista.getHead(); pLista.getHead().previo = cola; cola = pLista.getTail(); talla = talla + pLista.getTalla(); }
1
public GameBoard() { board = new Piece[8][8]; hcolor = new Color(1.0f, 1.0f, 0, 0.5f); bBlack = new Color(80, 48, 18); bWhite = new Color(193, 144, 97); try { Image spritesheet = new Image("data/pieces.png"); pieces = new Image[6][2]; for (int n = 0; n < pieces[0].length; n++) { for (int i = 0; i < pieces.length; i++) { pieces[i][n] = spritesheet.getSubImage(i * 100, n * 100, 100, 100).getScaledCopy(40, 40); } } } catch (SlickException ex) { Logger.getLogger(GameBoard.class.getName()).log(Level.SEVERE, null, ex); } newBoard(); }
3
public static Quiz getQuizByQuizID(int quizID) { String statement = new String("SELECT * FROM " + DBTable + " WHERE qid = ?"); PreparedStatement stmt; try { stmt = DBConnection.con.prepareStatement(statement); stmt.setInt(1, quizID); ResultSet rs = stmt.executeQuery(); if (!rs.next()) { System.out.println("Quiz " + quizID + " NOT FOUND"); return null; } Quiz quiz = new Quiz(rs.getInt("qid"), rs.getString("name"), rs.getString("url"), rs.getString("description"), rs.getString("category"), rs.getInt("userid"), rs.getBoolean("israndom"), rs.getBoolean("isonepage"), rs.getBoolean("opfeedback"), rs.getBoolean("oppractice"), rs.getInt("raternumber"), rs.getDouble("rating")); rs.close(); return quiz; } catch (SQLException e) { e.printStackTrace(); } return null; }
2
public boolean validatePayment(Transaction transaction) { String paymentType = transaction.getPayment().toString(); boolean paid = false; switch (paymentType) { case "CashPayment": registerUI.setCashPayment(); break; case "CreditPayment": registerUI.setCreditPayment(); paid = transaction.getPayment().initiatePayment(); if (paid) { registerUI.setCreditCardLabel("Card Accepted"); registerUI.setAmountDue(new BigDecimal(0)); registerUI.resetUI(); this.exitKiosk.openGate(); } else { registerUI.setCreditCardLabel("Card Declined"); } break; case "AccountPayment": registerUI.setAccountPayment(); paid = transaction.getPayment().initiatePayment(); if (paid) { // marks a account as paid and opens gate registerUI.setAccountNumberLabel("Paid on Account"); registerUI.setAmountDue(new BigDecimal(0)); registerUI.resetUI(); this.exitKiosk.openGate(); } else { registerUI.setAccountNumberLabel("Account Not Found"); } // set the account paid field to license break; } return (paid); }
5
private void ensureSubItemsLoaded() { if (loadedSubItems) return; loadedSubItems = true; if (getFirst() != null) { // get first child Reference nextReference = getFirst(); Reference oldNextReference; OutlineItem outLineItem; Hashtable dictionary; // iterate through children and see if then have children. while (nextReference != null) { // result the outline dictionary dictionary = (Hashtable) library.getObject(nextReference); if (dictionary == null) { break; } // create the new outline outLineItem = new OutlineItem(library, dictionary); // add the new item to the list of children subItems.add(outLineItem); // old reference is kept to make sure we don't iterate out // of control on a circular reference. oldNextReference = nextReference; nextReference = outLineItem.getNext(); // make sure we haven't already added this node, some // Outlines terminate with next being a pointer to itself. if (oldNextReference.equals(nextReference)) { break; } } } }
5
@Override public boolean init(List<String> argumentList, DebuggerVirtualMachine dvm) { if (argumentList.size() > 0) { UserInterface.println("This command takes no arguments."); HelpCommand.displayHelp(this); return false; } breakpoints = new ArrayList<String>(); for (int i = 1; i < dvm.getSourceLinesSize(); i++) { if (dvm.isBreakpointSet(i)) { breakpoints.add(new Integer(i).toString()); } } return true; }
3
private void setObstacleVelocity(float[][] u, float[][] v) { int count = 0; float uw, vw; for (int i = 1; i < nx1; i++) { for (int j = 1; j < ny1; j++) { if (!fluidity[i][j]) { uw = uWind[i][j]; vw = vWind[i][j]; count = 0; if (fluidity[i - 1][j]) { count++; u[i][j] = uw - u[i - 1][j]; v[i][j] = vw + v[i - 1][j]; } else if (fluidity[i + 1][j]) { count++; u[i][j] = uw - u[i + 1][j]; v[i][j] = vw + v[i + 1][j]; } if (fluidity[i][j - 1]) { count++; u[i][j] = uw + u[i][j - 1]; v[i][j] = vw - v[i][j - 1]; } else if (fluidity[i][j + 1]) { count++; u[i][j] = uw + u[i][j + 1]; v[i][j] = vw - v[i][j + 1]; } if (count == 0) { u[i][j] = uw; v[i][j] = vw; } } } } }
8
@Override public void focusLost(FocusEvent arg0) { try { String Str = _view.edt_ID.getText(); if (!Str.isEmpty()) { search(Integer.parseInt (Str)); } } catch (NullPointerException E){ Error_Frame.Error("ID not found\n\n" + E.getMessage()); } catch (NumberFormatException E) { Error_Frame.Error("Please use only number for ID\n\n" + E.getMessage()); } }
3
@Override public void close() throws AudioDeviceException { boolean failed = false; for ( AudioDevice dev : this.mDevices ) { try { dev.close(); } catch (AudioDeviceException e) { failed = true; } } if ( failed ) { throw new AudioDeviceException( "couldn't close all of the underlying AudioDevices" ); } }
3
public int compareTo(Object o) { Location l = (Location)o; if (l.prio < prio) return 1; if (l.prio > prio) return -1; return 0; }
2
public void updateLongestRoad(int p) { if (_numRoads[p] > _longestRd) { if (_longestRd_Owner != -1) { _points[_longestRd_Owner] -= 2; } _points[p] += 2; _longestRd = _numRoads[p]; if (p == _playerNum && p != _longestRd_Owner) { _chatBar.addLine("9" + "You have the Largest Road Network! You now have " + _points[_playerNum] + " points."); sendMessage("9" + _name + " now has the Largest Road Network!"); } _longestRd_Owner = p; if (_points[p] >= _points_to_win && p == _playerNum) { sendWin(_name); } } }
6
@Override public void onMessage(String channel, String sender, String message) { String filter = MdBtConstants.BOTNAME + ": "; boolean toMe = false; boolean shouldLearn = !sender.equals("habbes") && !sender.equals("mlvn"); if (message.startsWith(filter)) { toMe = true; message = message.replaceFirst(filter, ""); } if (message.equals("reload plugins")) { String ret = reloadPlugins(); sendMessage(channel, "Plugins loaded: " + ret); return; } for (MdBtPlugin p : plugins.values()) { if (p.getTriggerRegex().matcher(message).matches()) { sendMessage(channel, p.onMessage(channel, sender, message)); return; } } if (message.indexOf(MdBtConstants.BOTNAME) != -1) { // Replace botname with "meg" message = message.replaceAll(MdBtConstants.BOTNAME, "meg"); toMe = true; } if (shouldLearn) { brain.add(message); } if (toMe) { sendMessage(channel, shouldITalkToYou(sender) + brain.getSentence(findWordOfInterest(message))); } }
8
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed if (!this.pretarate()) { this.msg("Campos incompletos o erróneos."); } }//GEN-LAST:event_jButton1ActionPerformed
1
public boolean isVariable(String variable) { return myVariables.contains(variable); }
0
public T[] getBFS() { Queue<Node<T>> queue = new ArrayDeque<Node<T>>(); T[] values = (T[]) new Comparable[size]; int count = 0; Node<T> node = root; while (node != null) { values[count++] = node.id; if (node.lesser != null) queue.add(node.lesser); if (node.greater != null) queue.add(node.greater); if (!queue.isEmpty()) node = queue.remove(); else node = null; } return values; }
4
private CtField getDeclaredField2(String name) { CtMember.Cache memCache = getMembers(); CtMember field = memCache.fieldHead(); CtMember tail = memCache.lastField(); while (field != tail) { field = field.next(); if (field.getName().equals(name)) return (CtField)field; } return null; }
2
static void DVP() { Scanner in = new Scanner(System.in); final Board b = Board.readBoard(in); ArrayList<Integer> nextPiece = new ArrayList<Integer>(); while(in.hasNextInt()) nextPiece.add(in.nextInt()); Searcher s; for (int i = 2; i < 7; i++){ s = new DLDFS(new LinearWeightedSum(new double[] { 0.3, 0.5, 0.2, 0.0}), i); s.playGame(b, new ArrayList<Integer>(nextPiece)); } for (int i = 2; i < 7; i++){ s = new Pruner(new LinearWeightedSum(new double[] { 0.3, 0.5, 0.2, 0.0}), i, 1); s.playGame(b, new ArrayList<Integer>(nextPiece)); } for (int i = 2; i < 7; i++){ s = new Pruner(new LinearWeightedSum(new double[] { 0.3, 0.5, 0.2, 0.0}), i, 1.0/2); s.playGame(b, new ArrayList<Integer>(nextPiece)); } for (int i = 2; i < 7; i++){ s = new Pruner(new LinearWeightedSum(new double[] { 0.3, 0.5, 0.2, 0.0}), i, 1.0/4); s.playGame(b, new ArrayList<Integer>(nextPiece)); } for (int i = 2; i < 7; i++){ s = new Pruner(new LinearWeightedSum(new double[] { 0.3, 0.5, 0.2, 0.0}), i, 1.0/16); s.playGame(b, new ArrayList<Integer>(nextPiece)); } }
6
public float[][] getM() { float[][] res = new float[4][4]; for(int i = 0; i < 4; i++) for(int j = 0; j < 4; j++) res[i][j] = m[i][j]; return res; }
2
public void consolidate(){ // add feedback boxes to forward path boxes this.closedPath = this.forwardPath.copy(); for(int i=0; i<this.nFeedbackBoxes; i++){ this.closedPath.addBoxToPath(this.feedbackPath.get(i)); } // combine forward path boxes this.forwardPath.consolidate(); if(!this.forwardPath.getCheckNoMix())this.checkNoMix = false; // combine closed path boxes this.closedPath.consolidate(); if(!this.closedPath.getCheckNoMix())this.checkNoMix = false; // Calculate transfer function ComplexPoly fpNumer = this.forwardPath.getSnumer(); ComplexPoly fpDenom = this.forwardPath.getSdenom(); ComplexPoly cpNumer = this.closedPath.getSnumer(); ComplexPoly cpDenom = this.closedPath.getSdenom(); if(fpDenom.isEqual(cpDenom)){ super.setSnumer(fpNumer.copy()); super.setSdenom((cpNumer.plus(fpDenom)).copy()); } else{ super.setSnumer(fpNumer.times(cpDenom)); super.setSdenom((cpNumer.times(fpDenom)).plus(cpDenom.times(fpDenom))); } this.checkConsolidate = true; this.deadTimeSum = this.closedPath.getDeadTime(); super.deadTime = 0.0; this.checkConsolidate = true; }
4
public void processImage() throws Exception { byte[] originalImageBytes = baseImageProvider.getImage(); byte[] watermarkImageBytes = watermarkImageProvider.getImage(); if (originalImageBytes == null) { throw new Exception("Original Image is not loaded"); } if (watermarkImageBytes == null) { throw new Exception("WatermarkImage is not loaded"); } BufferedImage original = ImageIO.read(new ByteArrayInputStream(originalImageBytes)); BufferedImage watermark = ImageIO.read(new ByteArrayInputStream(watermarkImageBytes)); if (original.getWidth() < watermark.getWidth()) { throw new Exception("Original width is smaller than watermark"); } if (original.getHeight() < watermark.getHeight()) { throw new Exception("Original height is smaller than watermark"); } BufferedImage combined = new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics graphics = combined.getGraphics(); graphics.drawImage(original, 0, 0, null); int offsetX = calculateOffset(original.getWidth(), watermark.getWidth(), horizontalAlignment); int offsetY = calculateOffset(original.getHeight(), watermark.getHeight(), verticalAlignment); graphics.drawImage(watermark, offsetX, offsetY, null); combinedImage = combined; }
4
public static void main(String [] args){ ExecutorService executor= Executors.newFixedThreadPool(numThreads); List<Future<Long>> list=new ArrayList<Future<Long>>(); for(int i=0; i<20000; i++){ Callable<Long> worker=new MyCallable(); Future<Long> submit=executor.submit(worker); list.add(submit); } long sum=0; System.out.println(list.size()); for(Future<Long> future: list){ try{ sum+=future.get(); }catch(InterruptedException ex){ ex.printStackTrace(); }catch(ExecutionException e){ e.printStackTrace(); } System.out.println(sum); executor.shutdown(); } }
4
public void removePush() { if (exprStack != null) instr = exprStack.mergeIntoExpression(instr); super.removePush(); }
1
public String createMaskFromDatePattern(String datePattern) { String symbols = "GyMdkHmsSEDFwWahKzZ"; String mask = ""; for (int i = 0; i < datePattern.length(); i++) { char ch = datePattern.charAt(i); boolean symbolFound = false; for (int n = 0; n < symbols.length(); n++) { if (symbols.charAt(n) == ch) { mask += "#"; symbolFound = true; break; } } if (!symbolFound) { mask += ch; } } return mask; }
4
public static boolean fileprocess(String downloadpath, String filepath, String []paras, String sn){ int errorcode=0;// print error code in the final output file; int errornum = 14; String result=""; File downloadfile = new File(downloadpath+"\\temp_test.txt"); File outputfile = new File(filepath); double value =0; String line=""; ArrayList <String> content = new ArrayList<String>(); try { BufferedReader br = new BufferedReader(new FileReader(downloadfile)); while ((line=br.readLine())!=null){ content.add(line); } br.close(); downloadfile.delete(); double lower_bound=Double.parseDouble(paras[0]); double upper_bound=Double.parseDouble(paras[1]); if (content.size()!=1){ result = "FAILED"; errorcode = 3; } else { value=Double.parseDouble(content.get(0)); if (value>=lower_bound){ if (value<=upper_bound){ result="PASS"; } else { result = "FAILED"; errorcode =2; } } else{ result = "FAILED"; errorcode=1; } } } catch (IOException e) { e.printStackTrace(); } catch (NumberFormatException ex){ result = "FAILED"; errorcode = 0; } try { BufferedWriter bw = new BufferedWriter(new FileWriter(outputfile,true)); bw.write("Temperature="+value+"\r\n"); System.out.println("Temperature="+value); bw.write("Temperature_Result="+result+"\r\n"); System.out.println("Temperature_Result="+result); if (result.equals("FAILED")){ NumberFormat nf = NumberFormat.getIntegerInstance(); nf.setMinimumIntegerDigits(2); bw.write("Error_Code= "+nf.format(errornum)+nf.format(errorcode)+"\r\n"); } bw.flush(); bw.close(); }catch (Exception e){ e.printStackTrace(); } return true; }
8
@Override public void applyAllChanges() throws ApplyChangesException { // Make a "backup" first Document backup = null; try { TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer tx = tfactory.newTransformer(); DOMSource source = new DOMSource(this.xmlDocument); DOMResult result = new DOMResult(); tx.transform(source, result); backup = (Document) result.getNode(); } catch(TransformerException e) { throw new ApplyChangesException(e); } try { MessageUtil.debug("Attempting to apply Changes to DomTree"); for(InputElement i : inputs) { i.apply(); } } catch(XPathExpressionException e) { if(backup != null) { this.xmlDocument = backup; } throw new ApplyChangesException(e); } }
4
@Override public synchronized Voiture circule() { Voiture v; int length = vehicules.length; for (int i = length - 1; i >= 0; i = i - 1) { v = vehicules[i]; if (v != null) { v.avancer(); } } if (waittingForInsertion == null) { return null; } v = waittingForInsertion; waittingForInsertion = null; return v; }
3
public static String getID(ProjectileType type){ switch(type){ case BOULDER: return "boulder"; case FIREBALL: return "fireball"; case ICE_SPIKE: return "icespike"; case ITEM: return "item"; case SPELL: return "greenfire"; case ELECTRO_BALL: return "electroball"; default: return ""; } }
6
public static File moveFile(File sourceFile, File destinationDir) { if (destinationDir == null || !destinationDir.isDirectory ()) return null; File movedFile = new File (destinationDir.getAbsolutePath () + File.separator + sourceFile.getName ()); if (sourceFile.renameTo (movedFile)) return movedFile; return null; }
3
public static Contributor findContributor(String domain) { loadContributors(); Contributor contributor = Contributor.contributors.get(domain); if(contributor == null) { for(Contributor cont : Contributor.contributors.values()) { if(cont.getDomain().equalsIgnoreCase(domain) || cont.getName().equalsIgnoreCase(domain)) { contributor = cont; break; } } } if(contributor == null) { logger.warn("Unable to find contributor: " + domain); logger.info("Available Domains:"); for(String dom : Contributor.contributors.keySet()) { logger.info(" " + dom); } } return contributor; }
6
public void run(){ while(this.status == Bullet.ALIVE){ try { Thread.sleep(Constant.bullet_sleep_time); } catch (InterruptedException e) { e.printStackTrace(); } if( Game.status == Game.STATUS_ON){//judge the status if(judgeIfIn()){ if( this.status == Bullet.ALIVE){ this.move(); ifHitSomething(); } }else{ this.setStatus(Bullet.DEAD); break ; } } } }
5
public void stop() { if ( !isRunning ) return; isRunning = false; }
1
public boolean codopValido(String cod){ int punto=0, tam=cod.length(); boolean flag=false; if(tam > 5){ return false; } else if(!Character.isLetter(cod.charAt(0))){ return false; } else{ for(int i=1;i<tam && !flag;i++){ if(!(Character.isLetter(cod.charAt(i)) || cod.charAt(i)=='.')) flag=true; if(cod.charAt(i)=='.') punto+=1; } if(flag || punto > 1) return false; else return true; } }
9
public void vecinos_apartir_inicio(Casilla nodopadre){ //verificar que no esten en lista cerrada if(nofin==0){ int tamCerrado=listas.tamañoL_Cerrados(); Casilla temp =new Casilla(); Casilla ini =new Casilla(); int xi=nodopadre.getcordenadaX(); int yi=nodopadre.getcordenadaY(); int continuar=0; ini=casilla[yi][xi]; for (int i=1;i<=8;i++){ if( hola_vecino(ini, i).getH()!=-1){ for(int t=0;t< listas.tamañoL_Cerrados();t++){ if(listas.mostrarL_Cerrados(t).getID()==hola_vecino(ini, i).getID()){ continuar=1; } } if (continuar==0)calcularGyF(ini, hola_vecino(ini, i)); } continuar=0; } anadir_a_Lista_cerrados(nodopadre); if(imprecorrido==1){ System.out.print("vuelta "+count+" referencia " ); impCasilla(nodopadre); } if(imprecorrido==1)listas.impAbiertos(); count+=1; selec_sigientepaso(); } }
8
@Override Color getColor(String color) { if (color == null) { return null; } if (color.equalsIgnoreCase("RED")) { return new Red(); } else if (color.equalsIgnoreCase("GREEN")) { return new Green(); } else if (color.equalsIgnoreCase("BLUE")) { return new Blue(); } return null; }
4
public static ColorRGBA getColor(int type) { switch(type) { case GRASS: return new ColorRGBA(0.2f, 0.8f, 0.2f, 1.0f); case DIRT: return new ColorRGBA(0.3f, 0.3f, 0f, 1.0f); case STONE: return new ColorRGBA(0.6f, 0.6f, 0.6f, 1.0f); case WATER: return new ColorRGBA(0f, 0.1f, 1.0f, 0.6f); case WOOD: return new ColorRGBA(0.1f, 0.1f, 0f, 1.0f); case BRICK: return new ColorRGBA(0.8f, 0.1f, 0.1f, 1.0f); case GLASS: return new ColorRGBA(0.6f, 1.0f, 0.6f, 0.2f); default: return ColorRGBA.Black; } }
7
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(VentanaColapsosDelSistema.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VentanaColapsosDelSistema.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VentanaColapsosDelSistema.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VentanaColapsosDelSistema.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 VentanaColapsosDelSistema().setVisible(true); } }); }
6
public boolean isPermutation_Hashtable(String s1, String s2){ if(s1.length() != s2.length()) return false; Hashtable<Character,Integer> ht = new Hashtable<Character,Integer>(); //put all characters in s1 to the hash table for(int i=0;i<s1.length();i++){ char k = s1.charAt(i); if(!ht.containsKey(k)) ht.put(k, 1); else{ ht.put(k, ht.get(k)+1); } System.out.println(ht.toString()); } //empty the hash table according to the string s2 for(int i=0;i<s2.length();i++){ char k = s2.charAt(i); if(ht.containsKey(k)) ht.put(k, ht.get(k)-1); else return false; if(ht.get(k) == 0) ht.remove(k); System.out.println(ht.toString()); } //empty hash table means s1 is a permutation of s2 if(ht.isEmpty()) return true; else return false; }
7
private void updateLocations(GameContainer gc, StateBasedGame sbg) throws SlickException { //Update the bullet's position. for(int i = 0;i<bulletList.size();i++){ Bullet bullet = bulletList.get(i); bullet.move(); // Removes bullets that go off screen. if ((bullet.returnX() > 639 || bullet.returnX() <= 1) || (bullet.returnY() < 1 || bullet.returnY() > 399)){ bulletList.remove(i); } } // Update the enemies' positions. for(int i = 0; i < enemiesOnScreen.size(); i++){ Enemy enemy = enemiesOnScreen.get(i); enemy.move(); // Removes enemies that go off screen. // Decrements the player's health by 10. // Sets the multiplier back down. if (enemy.returnY() > 389 ){ enemiesOnScreen.remove(i); Settings.health -= 10; score.setDefaultMultiplier(); if(Settings.health == 0){ sbg.addState(new Death(Game.DEATH_STATE)); sbg.getState(Game.DEATH_STATE).init(gc, sbg); sbg.enterState(Game.DEATH_STATE); } } } }
8
public void setIdPos(int idPosLogEnt) { this.idPosLogEnt = idPosLogEnt; }
0