method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
6bf2ca0a-5f1f-4fc4-baa0-82f04f17d6e9
9
public Path optimizePath(Path path, int[][] distances) { // int[][] distances = distanceHolder.distances; Node[] nodes = path.nodes; Path newPath = null; int skipped = 0; double bestDistance = 10000000; //path.distance; double newDistance = Integer.MAX_VALUE; double diff = 10000; // outerloop: do { // printPathToSystemErr(path); boolean search = true; outerloop: while(search){ System.err.println("New loop"); //diff = 100000; search = false; nodes = path.nodes; for (int i = 0; i+1 < nodes.length; i++) { for (int j = i+1; (j+1 < nodes.length)&&(j!=i); j++) { for (int k = 0; (k < 1); k++) { for (int m = 0; (m+1 < nodes.length)&&(m!=j)&&(m!=i); m++) { //i = starting node one //j = starting node two //k = 1 if the first new connection should be used, 2 if the second new connection //m = starting node three int distance = 0; distance += distances[nodes[i+1-k].number][nodes[j+1-k].number]; distance += distances[nodes[j+k].number][nodes[m+1].number]; distance += distances[nodes[i+k].number][nodes[m].number]; int distance2 = 0; distance2 += distances[nodes[i].number][nodes[i+1].number]; distance2 += distances[nodes[j].number][nodes[j+1].number]; distance2 += distances[nodes[m].number][nodes[m+1].number]; if(distance<distance2){ search = true; twoOpt.forceSwap(path, i, j, distances); twoOpt.forceSwap(path, i+k, m, distances); // path = newPath; continue outerloop; // make(i, j) // make(i+1, j+1) // reverse(i+1, j) // // make(i+k, m) // make(j+k, m+1) // reverse(m, j+1) // if(b){ //// try { //// Thread.sleep(1); // //v.updatePath(path); //// } catch (InterruptedException e) { //// // TODO Auto-generated catch block //// e.printStackTrace(); //// } // } }else{ skipped++; continue; } } } } } } System.err.println("Skipped: " + skipped); return path; }
3259f8fb-5123-43e9-be2d-20bf836abf87
7
protected int getVersionIndex(String romId) { switch (romId) { case "B4WJ0": return 0; case "B4BJ0": return 1; case "B4WE0": return 2; case "B4WP0": return 3; case "B4BE0": return 4; case "B4BP0": return 5; case "B4WJ1": return 6; //case "B4BJ1": // return 7; default: throw new IllegalArgumentException("Unknown ROM ID \"" + romId + "\"."); } }
19461ee6-7db2-4c5a-97bb-06ba038d2646
2
private synchronized void pulse(){ for(int i = 0; i < peerList.size();i++){ Peer p = peerList.get(i); if(!checkPulse(p)){//if it has no pulse, it's dead disconnect(p); } } }
9462b359-6f6d-4f6c-aa1c-3021dc2014e5
5
public boolean checkcheck(Board b){ aiarr=b.getBoardArray(); for(int x=0;x<8;x++){ for(int y=0;y<8;y++){ if(aiarr[x][y].toString().charAt(0)==color && aiarr[x][y].toString().charAt(1)=='K' && isThreatened(new Point(x,y))){ System.out.println("CHECK"); //checkCheckmate(b,x,y); return true; } } } return false; }
fa66dde9-14b4-4c2e-a309-84f68e17e180
5
private final String getChunk(String s, int slength, int marker) { StringBuilder chunk = new StringBuilder(); char c = s.charAt(marker); chunk.append(c); marker++; if (isDigit(c)) { while (marker < slength) { c = s.charAt(marker); if (!isDigit(c)) break; chunk.append(c); marker++; } } else { while (marker < slength) { c = s.charAt(marker); if (isDigit(c)) break; chunk.append(c); marker++; } } return chunk.toString(); }
6684d5bb-2613-478a-b48b-be98dd293e0e
2
private void playSound(){ if (cSound.getModel().isSelected()) { if(status.getChangedServerList().size() > 0) alarm.play(); } }
fcd745eb-63f7-4649-9606-95aa9fc2906a
7
public static void main(String[] args) { if (args.length < 3) { System.out.println("Simple Web Crawler"); System.out.println("Usage:"); System.out.println("First argument: page URL e.g. http://example.com"); System.out.println("Second argument: number of pages to obtain e.g. 1000"); System.out.println("Third argument: output file name, e.g links.csv"); System.exit(-1); } URL url; try { url = new URL(args[0]); } catch (MalformedURLException e) { System.out.println("Page URL " + args[0] + " is malformed"); System.exit(1); return; } int max; try { max = Integer.parseInt(args[1]); } catch (NumberFormatException e) { System.out.println("Number of pages argument is not a number: " + args[1]); System.exit(2); return; } // Create file BufferedWriter writer; try { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(args[2]), "utf-8")); } catch (IOException ex) { System.out.println("Cannot create file: " + args[2]); System.exit(3); return; } // Crawl! Crawler crawler = new Crawler(url, max, new PageFetcher(), new PageParser()); crawler.crawl(); // Write results to the file try { for (String link: crawler.getLinks()) { writer.write(link); writer.newLine(); } } catch (IOException e) { System.out.println("Error occurred when writing to the file: " + args[2]); System.exit(4); return; } finally { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } System.exit(0); }
43745c06-b4c3-402c-91d8-adc8aebf6c46
8
private boolean validateInput(Move theMove, Board board) { if (theMove == null || board == null) { throw new IllegalArgumentException("Move or Board were null"); } if (!(theMove instanceof ConnectFourMove)) { throw new IllegalArgumentException("Wrong move type"); } if (boardColumns != board.getColumns() || boardRows != board.getRows() ) { throw new IllegalArgumentException("wrong board size"); } int column = ((ConnectFourMove)theMove).column; if ((column > board.getColumns()-1) || (column < 0)) { return false; } if (board.getPieces(board.getRows()-1, column) != null) { return false; } return true; }
f606c5eb-e984-40d1-af49-36b682a9fd57
1
synchronized public void quitterVoie(Train train){ train.setVenteOuverte(false); if(train.listeVoyageurIsEmpty()){ listeTrainQuai.remove(train); System.out.println( train.getNomTrain() +" quitte gare"); } voiesDispo++; // Pour les trains en attente d'un quai libre. notifyAll(); }
497bf258-9552-4d1a-8eca-43278192b116
6
public static void main(String[] args) { WrapCheckedException wce = new WrapCheckedException(); for(int i = 0; i < 3; i++) { try { if(i < 3) { wce.throwRuntimeException(i); } else { throw new RuntimeException(); } } catch(RuntimeException re) { try { throw re.getCause(); } catch(Sneeze e) { System.out.println("Sneeze: " + e); } catch(Annoyance e) { System.out.println("Annoyance: " + e); } catch(Throwable e) { System.out.println("Throwable: " + e); } } } }
a5bd990d-35b0-40d3-afea-48ea2a4950b5
5
public static String checkSum(String f) { try { MessageDigest md = MessageDigest.getInstance("MD5"); DigestInputStream ds = new DigestInputStream( new FileInputStream(f), md); byte[] b = new byte[512]; while (ds.read(b) != -1) ; String computed = ""; for(byte v : md.digest()) computed += byteToHex(v); return computed; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "<error computing checksum>"; }
13e1d38d-7c5e-42bb-b1a3-e294344703f7
5
@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 AttributeStorageLevel)) { return false; } AttributeStorageLevel other = (AttributeStorageLevel) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
a70b0a59-f14b-44ba-8425-98460d6b8a05
5
public void paint(Graphics g) { super.paint(g); if (ingame) { Graphics2D g2d = (Graphics2D)g; if (craft.isVisible()) g2d.drawImage(craft.getImage(), craft.getX(), craft.getY(), this); ArrayList ms = craft.getMissiles(); for (int i = 0; i < ms.size(); i++) { Missile m = (Missile)ms.get(i); g2d.drawImage(m.getImage(), m.getX(), m.getY(), this); } for (int i = 0; i < aliens.size(); i++) { Alien a = (Alien)aliens.get(i); if (a.isVisible()) g2d.drawImage(a.getImage(), a.getX(), a.getY(), this); } g2d.setColor(Color.WHITE); g2d.drawString("Aliens left: " + aliens.size(), 5, 15); } else { String msg = "Game Over"; Font small = new Font("Helvetica", Font.BOLD, 14); FontMetrics metr = this.getFontMetrics(small); g.setColor(Color.white); g.setFont(small); g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2); } Toolkit.getDefaultToolkit().sync(); g.dispose(); }
3bf2cc7c-b704-470f-ac3e-3b8f244ef5da
1
public Double compute(User u) { Integer correct = u.get("correct"); Integer questions = u.get("questions"); if(questions == 0) return 1.0; else return correct / (double) questions; }
9bf5858e-eb24-4b73-b961-04bac1710ede
3
public boolean addNewSportsBooking(ArrayList<SportsBooking> sb1, Connection conn) throws SQLException { int rowsInserted = 0; try { String SQLString = "insert into sportsBooking values (?,?,?,to_timestamp(?),?)"; PreparedStatement statement = null; statement = conn.prepareStatement(SQLString); for (int i = 0; i < sb1.size(); i++) { sb = sb1.get(i); statement.setString(1, sb.getReservationsNumber()); statement.setString(2, sb.getSportsID()); statement.setString(3, sb.getSportsType()); statement.setString(4, sb.getSportsDate()); statement.setInt(5, sb.getTrainer()); rowsInserted += statement.executeUpdate(); } if (sb.getTrainer() == 1) { addTrainerToBooking(conn); } } catch (Exception e) { System.out.println("Fail in BookingMapper - addNewSportsBooking"); System.out.println(e.getMessage()); } return (rowsInserted == sb1.size()); }
c6258dfb-3ff3-45ba-bec4-d8d4ff4152ef
4
public void eseguiSimulazioneDoppiaCPU() { /* Inizializzazione vettore. */ ArrayList<Double> tempiUscitaMedi = new ArrayList<Double>(); /* Cicla sui job. */ for (int i = passo ; i <= jobTotali ; i += passo) { /* Cicla sui run. */ for (int j = 1 ; j <= run ; j++) { /* Genera un sistema a singola CPU e registra la media dei tempi dei job. */ DoubleCPU doubleCPU = new DoubleCPU(seed_arrivi, seed_cpu_1, seed_cpu_2, seed_cpu_3, seed_io_1, seed_io_2, seed_io_3, seed_routing, seed_routing_cpu, i); tempiUscitaMedi.add(doubleCPU.simula()); /* Aggiornamento dei seeds. */ seed_arrivi = doubleCPU.getGeneratoreArrivi().getX0(); seed_cpu_1 = doubleCPU.getGeneratoreCPU().getG1().getX0(); seed_cpu_2 = doubleCPU.getGeneratoreCPU().getG2().getX0(); seed_cpu_3 = doubleCPU.getGeneratoreCPU().getG3().getX0(); seed_io_1 = doubleCPU.getIo().getGeneratore().getG1().getX0(); seed_io_2 = doubleCPU.getIo().getGeneratore().getG2().getX0(); seed_io_3 = doubleCPU.getIo().getGeneratore().getG3().getX0(); seed_routing = doubleCPU.getGeneratoreRouting().getX0(); } /* Calcolo della media sperimentale. */ double somma = 0.0; for (Double d : tempiUscitaMedi) somma += d; somma = somma / run; /* Calcolo della deviazione standard sperimentale. */ double sd = 0.0; for (Double d : tempiUscitaMedi) sd += Math.pow(d - somma, 2); sd /= (run - 1); /* Registraione dei valori. */ avgs.add(somma); sds.add(sd); /* Reset del vettore. */ tempiUscitaMedi = new ArrayList<Double>(); } /* Stampa i vettori per i grafici. */ print(jobTotali); }
ca57b441-f7eb-4719-b908-61fdc0241a46
9
@Override public void putAll( MultiMap< ? extends K, ? extends V > map ) { // Get iterator to map's entry set Iterator< ? extends Map.Entry< ? extends K, ? extends V > > it = null; try { it = map.entrySet().iterator(); } catch( Throwable t ) { return; } Map.Entry< ? extends K, ? extends V > entry = null; // Iterate over map's entry set while( it.hasNext() ) { // Get next entry entry = it.next(); // Add entry to this map this.put( entry.getKey(), entry.getValue() ); } }
1b732335-e4d0-4427-80f7-4dd6685db445
8
private ArrayList<NonDuplicateArrayList<String>> getKSubset(NonDuplicateArrayList<String> set, int k){ /* // recursive approach // ref: http://stackoverflow.com/questions/4504974/how-to-iteratively-generate-k-elements-subsets-from-a-set-of-size-n-in-java ArrayList<NonDuplicateArrayList<Integer>> subsets = new ArrayList<NonDuplicateArrayList<Integer>>(); Integer[] subset = new Integer[k]; processLargerSubsets(set, subset, 0, 0, subsets); return subsets; */ // iterative approach // ref: http://stackoverflow.com/questions/4504974/how-to-iteratively-generate-k-elements-subsets-from-a-set-of-size-n-in-java int c = (int) Math.binomial(set.size(), k); // ArrayList<NonDuplicateArrayList<Integer>> subsets = new ArrayList<NonDuplicateArrayList<Integer>>(); ArrayList<NonDuplicateArrayList<String>> subsets = new ArrayList<NonDuplicateArrayList<String>>(); for (int i = 0; i < c; i++) subsets.add(new NonDuplicateArrayList<String>()); // subsets.add(new NonDuplicateArrayList<Integer>()); int[] ind = k < 0?null:new int[k]; for (int i = 0; i < k; i++) ind[i] = i; for (int i = 0; i < c; i++){ for (int j = 0; j < k; j++) subsets.get(i).add(set.get(ind[j])); int x = ind.length - 1; boolean loop; do{ loop = false; ind[x] = ind[x] + 1; if (ind[x] > set.size() - (k - x)){ x--; loop = x >= 0; } else{ for (int x1 = x + 1; x1 < ind.length; x1++) ind[x1] = ind[x1 - 1] + 1; } } while (loop); } return subsets; }
1c44def6-c772-485d-b595-018500899394
8
@Override public void mutate(){ TspPopulation offspring = new TspPopulation(); for (int i = 0; i < population.getSize(); ++i){ double r; synchronized (rng){ r = rng.nextDouble(); } if (r < PROBABILITY){ TspIndividual mutant = new TspIndividual(population.getIndividual(i)); int possition1; int length = 0; synchronized (rng){ length = rng.nextInt(3); } length += 3; synchronized (rng){ possition1 = Math.abs(rng.nextInt(mutant.size() - length + 1)); } int possition2 = possition1 + length - 1; int[] path = mutant.getPath(); List<Integer> shuffled = new ArrayList<Integer>(); for (int k = possition1; k <= possition2; ++k){ shuffled.add(path[k]); } Collections.shuffle(shuffled); for (int k = possition1; k <= possition2; ++k){ path[k] = shuffled.get(k - possition1); } mutant.setPath(path); offspring.addIndividual(mutant); if (!mutant.check()){ System.out.println("ALARM!!!"); } } else { offspring.addIndividual(new TspIndividual(population.getIndividual(i))); } } offspring.setGraph(population.getGraph()); double bestOld = population.getFittest(); double bestNew = offspring.getFittest(); if (bestNew < bestOld){ reward = 1; // reward = (bestOld - bestNew) / bestOld; for (int i = 0; i < population.getSize(); ++i){ population.setIndividual(i, offspring.getIndividual(i)); } } else if (bestNew == bestOld){ // reward = 0.5; reward = 0; } else { reward = 0; } }
c6427ee2-aaf1-4603-99f8-db38c40b700e
8
private void writeTag(ByteQueue queue, int tagNumber, boolean classTag, long length) { int classValue = classTag ? 8 : 0; if (length < 0 || length > 0x100000000l) throw new IllegalArgumentException("Invalid length: " + length); boolean extendedTag = tagNumber > 14; if (length < 5) { if (extendedTag) { queue.push(0xf0 | classValue | length); queue.push(tagNumber); } else queue.push((tagNumber << 4) | classValue | length); } else { if (extendedTag) { queue.push(0xf5 | classValue); queue.push(tagNumber); } else queue.push((tagNumber << 4) | classValue | 0x5); if (length < 254) queue.push(length); else if (length < 65536) { queue.push(254); BACnetUtils.pushShort(queue, length); } else { queue.push(255); BACnetUtils.pushInt(queue, length); } } }
3f2bbadc-2f57-49f9-aa70-a08b9f4615b1
5
private void actionInterested (String key, OutputStream out) throws IOException { Object o = _hash.get(key); if (o != null){ Fichier f = (Fichier)o; if (_estMisAssertion) System.out.println("On me demande mon fichier " + key); String reponse = "have " + key + " "; int i; boolean[] masque = f.getMasque(); for ( i=0 ; i<masque.length ; i++){ if (masque[i]) reponse += "1"; else reponse += "0"; } reponse += " "; if (_estMisAssertion) System.out.println(">> " + reponse); out.write(reponse.getBytes()); out.flush(); } else System.out.println("Clé inexistante ..."); }
f51f2134-d664-4a7f-b5e4-3a6caee29342
7
public void setValueAt(int numSample, int numChannel, Object value) { boolean channelAdded = false; boolean valueAdded = false; if (numSample < 0 || numChannel < 0) return; //Locate the channel while (numChannel >= channelsValues.size()){ //Add empty vectors until the desired channel channelsValues.addElement(new Vector()); channelAdded = true; } Vector channel = (Vector)channelsValues.elementAt(numChannel); //Locate the sample within the channel while (numSample >= channel.size()){ //Add empty elements until the desired sample channel.addElement(null); } if (numSample >= getTotalNumSamples()){ valueAdded = true; } //Set the value channel.setElementAt(value, numSample); if (channelAdded){ notifyChannelDescChanged(); } if (valueAdded){ notifyDataAdded(); } else{ notifyDataChanged(); } }
a1dc6cb7-e462-4865-bd3f-41feddad6d69
0
public ProxyDynamicSubject(Object obj) { this.obj = obj; }
ee3d5e9c-0ab4-43bb-b8ce-b35e687e5f0c
9
void showdetail() { int max =0; ArrayList<Integer[]> scorelist0 = new ArrayList<Integer[]>(); ArrayList<Integer[]> scorelist1 = new ArrayList<Integer[]>(); for (int i=0; i<size*size-1; i++) { if (grid[i].value>max) { max = grid[i].value; } } for (int i=2; i<=max; i=i*2) { Integer[] tmpint = new Integer[2]; tmpint[0] = i; tmpint[1]=0; scorelist0.add(tmpint); } for (int i=2; i<=max; i=i*2) { Integer[] tmpint = new Integer[2]; tmpint[0] = i; tmpint[1]=0; scorelist1.add(tmpint); } StringBuilder a = new StringBuilder(); StringBuilder b = new StringBuilder(); for (int i=0; i<size*size-1; i++) { if (grid[i].value>=2) { if (grid[i].owner==0) { scorelist0.get((int) (Math.log(grid[i].value)/Math.log(2)-1))[1]++; } else { scorelist1.get((int) (Math.log(grid[i].value)/Math.log(2)-1))[1]++; } } } a.append(group0); a.append("--- "); for (int i=0; i<scorelist0.size(); i++) { a.append("["); a.append(scorelist0.get(i)[0]); a.append(": "); a.append(scorelist0.get(i)[1]); a.append("] "); } b.append(group1); b.append("--- "); for (int i=0; i<scorelist1.size(); i++) { b.append("["); b.append(scorelist1.get(i)[0]); b.append(": "); b.append(scorelist1.get(i)[1]); b.append("] "); } label3.setText(a.toString()); label3.setVisible(true); label4.setText(b.toString()); label4.setVisible(true); }
47b5614e-8769-4a59-a40f-477ef7f3493a
2
public static int columnIndex(CSTable table, String name) { for (int i = 1; i <= table.getColumnCount(); i++) { if (table.getColumnName(i).equals(name)) { return i; } } return -1; }
025ce6d3-4ffa-4cdc-9484-b9eae9d95d3c
9
void run(){ Scanner sc = new Scanner(System.in); for(boolean h = true;;h=false){ n = sc.nextInt(); m = sc.nextInt(); if((n|m)==0)break; if(!h)System.out.println(); Map<String, Integer> ref = new HashMap<String, Integer>(); String[] s = new String[n]; for(int i=0;i<n;i++){ s[i] = sc.next(); ref.put(s[i], i); } e = new boolean[m][n]; for(int i=0;i<m;i++){ int k = sc.nextInt(); while(k--!=0)e[i][ref.get(sc.next())] = true; } u = new boolean[n]; min = INF; f(0, 0); if(min==INF)System.out.println("Impossible"); else { System.out.println(min); for(int i=0;i<n;i++)if(res[i])System.out.println(s[i]); } } }
0830c515-4dcc-4b0f-af88-d944c71298fa
5
private void init(int numRowsOfPieces) { for (int i = 0; i < SIZE; i++) { //Adds red checkers. for (int j = 0; j < numRowsOfPieces; j++) if ((i + j) % 2 == 1) pieces.add(new RedChecker(i, j)); //Adds blue checkers for (int j = SIZE - numRowsOfPieces; j < SIZE; j++) if ((i + j) % 2 == 1) pieces.add(new BlueChecker(i, j)); } }
80bf399e-eb2f-4de3-bedd-3a2bbf78e4cc
2
public boolean taskExists(Task task){ for (Task t : tasks){ if (t.equals(task)){ return true; } } return false; }
8b5f5a7d-dd8f-4f72-8bcb-2cdd2a629573
3
public void checkDeclaration(Set declareSet) { if (instr instanceof StoreInstruction && (((StoreInstruction) instr).getLValue() instanceof LocalStoreOperator)) { StoreInstruction storeOp = (StoreInstruction) instr; LocalInfo local = ((LocalStoreOperator) storeOp.getLValue()) .getLocalInfo(); if (declareSet.contains(local)) { /* * Special case: This is a variable assignment, and the variable * has not been declared before. We can change this to a * initializing variable declaration. */ isDeclaration = true; declareSet.remove(local); } } }
ecc46575-ab36-48ad-b8ea-16dc6d1dfa29
3
public void sendMessage(Message m, String url) { try { IMessageReceivedHandler stub = (IMessageReceivedHandler) java.rmi.Naming.lookup("rmi://"+registry+":1099/"+url); stub.onMessageReceived(m); } catch (MalformedURLException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } catch (NotBoundException e) { e.printStackTrace(); } /*catch (MalformedURLException | RemoteException | NotBoundException e) { e.printStackTrace(); }*/ }
c8f7a3a9-f035-48a7-9e44-f5ef554c5d4a
9
public static void setLongLE(final byte[] array, final int index, final long value, final int size) { switch (size) { case 0: return; case 1: Bytes.setInt1(array, index, (int)value); break; case 2: Bytes.setInt2LE(array, index, (int)value); break; case 3: Bytes.setInt3LE(array, index, (int)value); break; case 4: Bytes.setInt4LE(array, index, (int)value); break; case 5: Bytes.setLong5LE(array, index, value); break; case 6: Bytes.setLong6LE(array, index, value); break; case 7: Bytes.setLong7LE(array, index, value); break; case 8: Bytes.setLong8LE(array, index, value); break; default: throw new IllegalArgumentException(); } }
6a05fb9d-5a0d-4bd5-8f54-2a5ea28348c2
7
float getMeasurement(int[] countPlusIndices) { float value = Float.NaN; if (countPlusIndices == null) return value; int count = countPlusIndices[0]; if (count < 2) return value; for (int i = count; --i >= 0;) if (countPlusIndices[i + 1] < 0) { return value; } switch (count) { case 2: value = getDistance(countPlusIndices[1], countPlusIndices[2]); break; case 3: value = getAngle(countPlusIndices[1], countPlusIndices[2], countPlusIndices[3]); break; case 4: value = getTorsion(countPlusIndices[1], countPlusIndices[2], countPlusIndices[3], countPlusIndices[4]); break; default: Logger.error("Invalid count in measurement calculation:" + count); throw new IndexOutOfBoundsException(); } return value; }
9d5d4e39-b1b4-4f7e-ace6-704ceba5165d
4
private static double slowCos(final double x, final double result[]) { final double xs[] = new double[2]; final double ys[] = new double[2]; final double facts[] = new double[2]; final double as[] = new double[2]; split(x, xs); ys[0] = ys[1] = 0.0; for (int i = 19; i >= 0; i--) { splitMult(xs, ys, as); ys[0] = as[0]; ys[1] = as[1]; if ( (i & 1) != 0) { continue; } split(FACT[i], as); splitReciprocal(as, facts); if ( (i & 2) != 0 ) { facts[0] = -facts[0]; facts[1] = -facts[1]; } splitAdd(ys, facts, as); ys[0] = as[0]; ys[1] = as[1]; } if (result != null) { result[0] = ys[0]; result[1] = ys[1]; } return ys[0] + ys[1]; }
c1e79ecc-8356-482a-9bd3-e875a598ac93
1
public static void main(String[] args) { EntityManagerFactory entityManagerFactory= Persistence.createEntityManagerFactory("introducaojpa_pu"); EntityManager entityManager = entityManagerFactory.createEntityManager(); Scanner scanner = new Scanner(System.in); Banda banda; for(int i = 0;i<2;i++ ){ banda = new Banda(); System.out.println("Nome da banda"); banda.setNome(scanner.nextLine()); entityManager.getTransaction().begin(); entityManager.persist(banda); entityManager.getTransaction().commit(); } entityManager.close(); entityManagerFactory.close(); // TODO Auto-generated method stub }
9ef67dfe-3d6b-4cf3-84fc-e1881224cba0
0
public void destroy() { removeAll(); removeNotify(); setIcon(null); renderer = null; }
a6894248-ffa8-4820-9309-7052dffe005d
6
public StringTemplate getAbandonEducationMessage(boolean checkStudent) { if (!(getLocation() instanceof WorkLocation)) return null; boolean teacher = getStudent() != null; boolean student = checkStudent && getTeacher() != null; if (!teacher && !student) return null; Building school = (Building)((teacher) ? getLocation() : getTeacher().getLocation()); String action = (teacher) ? Messages.message("abandonEducation.action.teaching") : Messages.message("abandonEducation.action.studying"); return StringTemplate.template("abandonEducation.text") .addStringTemplate("%unit%", Messages.getLabel(this)) .addName("%colony%", getColony().getName()) .add("%building%", school.getNameKey()) .addName("%action%", action); }
36049c90-fdef-40a8-a700-8aae6e7dc826
1
public final String encode(final K[] plain) { String crypt = ""; for (K symbol : plain) { crypt += this.symbols.get(symbol); } return crypt; }
9fbec80f-79f9-4b57-a0df-48a17e42b9d9
1
public void set(int symbol, int freq) { checkSymbolInRange(symbol); if (freq < 0) throw new IllegalArgumentException("Negative symbol frequency"); freqTable.set(symbol, freq); }
7fa70212-8c9d-4492-a35c-6738c9858cc0
2
public Object success(NullParamFn<? extends Object> fn) { return this.suc ? fn.fn() : null; }
c2ccee8f-3eee-4bd7-a712-294805e431d1
2
public void run() { while (true) { try { sleep(delay); } catch (InterruptedException e) { } objectPool.reapObjects(); } }
1b5a2e3f-bfe1-4bc8-a548-242884142006
9
private static void parseTraces(final JsonNode rootNode, final TraceRelationshipBuilder<Integer> builder) throws IOException { for (JsonNode traceNode : getField(rootNode, JsonTraceCodec.TRACES)) { final int traceId = getIntField(traceNode, JsonTraceCodec.TRACE_ID); final String name = getTextField(traceNode, JsonTraceCodec.TRACE_NAME); final ResultType resultType = ResultType.valueOf(getTextField(traceNode, JsonTraceCodec.TRACE_RESULT_TYPE)); final ShallowTraceBuilder shallowBuilder = new ShallowTraceBuilder(name, resultType); if (traceNode.get(JsonTraceCodec.TRACE_HIDDEN) != null) shallowBuilder.setHidden(getBooleanField(traceNode, JsonTraceCodec.TRACE_HIDDEN)); if (traceNode.get(JsonTraceCodec.TRACE_SYSTEM_HIDDEN) != null) shallowBuilder.setSystemHidden(getBooleanField(traceNode, JsonTraceCodec.TRACE_SYSTEM_HIDDEN)); if (traceNode.get(JsonTraceCodec.TRACE_VALUE) != null) shallowBuilder.setValue(getTextField(traceNode, JsonTraceCodec.TRACE_VALUE)); if (traceNode.get(JsonTraceCodec.TRACE_START_NANOS) != null) shallowBuilder.setStartNanos(getLongField(traceNode, JsonTraceCodec.TRACE_START_NANOS)); if (traceNode.get(JsonTraceCodec.TRACE_PENDING_NANOS) != null) shallowBuilder.setPendingNanos(getLongField(traceNode, JsonTraceCodec.TRACE_PENDING_NANOS)); if (traceNode.get(JsonTraceCodec.TRACE_END_NANOS) != null) shallowBuilder.setEndNanos(getLongField(traceNode, JsonTraceCodec.TRACE_END_NANOS)); if(traceNode.get(JsonTraceCodec.TRACE_ATTRIBUTES) != null) { for(JsonNode node : getField(traceNode, JsonTraceCodec.TRACE_ATTRIBUTES)) { String key = getTextField(node, JsonTraceCodec.TRACE_ATTRIBUTE_KEY); String value = getTextField(node, JsonTraceCodec.TRACE_ATTRIBUTE_VALUE); shallowBuilder.addAttribute(key, value); } } builder.addTrace(traceId, shallowBuilder.build()); } }
1080e8ed-7097-456a-a7c1-bc2054750839
8
public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof PieDataset)) { return false; } PieDataset that = (PieDataset) obj; int count = getItemCount(); if (that.getItemCount() != count) { return false; } for (int i = 0; i < count; i++) { Comparable k1 = getKey(i); Comparable k2 = that.getKey(i); if (!k1.equals(k2)) { return false; } Number v1 = getValue(i); Number v2 = that.getValue(i); if (v1 == null) { if (v2 != null) { return false; } } else { if (!v1.equals(v2)) { return false; } } } return true; }
f5f35f72-5633-4843-b666-5b444f676406
0
public static boolean getAutoConnect(){ return AutoConnect; }
03a1ba95-34fa-4efb-87e3-a781322690cf
7
private static boolean isOnlyDoubleByteKanji(String content) { byte[] bytes; try { bytes = content.getBytes("Shift_JIS"); } catch (UnsupportedEncodingException uee) { return false; } int length = bytes.length; if (length % 2 != 0) { return false; } for (int i = 0; i < length; i += 2) { int byte1 = bytes[i] & 0xFF; if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) { return false; } } return true; }
48a1fe2c-1b3a-4c5c-bd31-5e233049c838
2
@RequestMapping(value = {"/CuentaBancaria/{idCuentaBancaria}/MovimientosBancarios"}, method = RequestMethod.GET) public void readMovimientosPorCuenta(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse, @PathVariable("idCuentaBancaria") String idCuentaBancaria) { try { ObjectMapper jackson = new ObjectMapper(); String json = jackson.writeValueAsString(movimientoBancarioDAO.findByCuenta(idCuentaBancaria)); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setContentType("application/json; charset=UTF-8"); noCache(httpServletResponse); httpServletResponse.getWriter().println(json); } catch (Exception ex) { noCache(httpServletResponse); httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); httpServletResponse.setContentType("text/plain; charset=UTF-8"); try { noCache(httpServletResponse); ex.printStackTrace(httpServletResponse.getWriter()); } catch (Exception ex1) { noCache(httpServletResponse); } } }
86156403-f75d-46d1-8491-a1c7603c7aef
0
public KeyboardListener() { keyMapper = new KeyMapper(); keyStates = new boolean[MAX_KEY]; }
7165326b-7bde-416b-842e-b845cfb76154
6
public static void main(String[] args) { // TODO Auto-generated method stub String sr_ip; int sr_port; if (args.length < 3) { System.out.println("Wrong arguments, Format: java examples/TestServer <ip of S_Registry> <port of S_Registry> <port of this Server>"); return; } sr_ip = args[0]; try { sr_port = Integer.parseInt(args[1]); server_port = Integer.parseInt(args[2]); } catch(NumberFormatException e) { System.out.println("Please input valid port"); return; } String ip_server = args[0]; System.out.println("test ipserver:"+ip_server); M_Registry register = new M_Registry(sr_ip, sr_port); Test test = new Test(); /*Class<?> interfaces[] = test.getClass().getInterfaces(); String remote_name = test.getClass().toString(); String[] interface_names=new String[interfaces.length];*/ RMIServer rms = rmi.RMIServer.getInstance(server_port); RemoteObjectRef ror = rms.create_ror(url, test); System.out.println("in TestServer, created ror, serverip:"+ror.getIP_adr()); try { //bind register.bind(url, ror); //list Vector<String> s = register.list(); if (s == null) { System.out.println("TestServer can not connect to Registry"); rms.stop(); return; } Iterator<String> itr = s.iterator(); System.out.println(" > Listing ..."); while (itr.hasNext()) { String insts = itr.next(); System.out.println(" > "+insts); } //unbind register.unbind(url); //list s = register.list(); itr = s.iterator(); System.out.println(" > Listing ..."); while (itr.hasNext()) { String insts = itr.next(); System.out.println(" > "+insts); } //rebind register.rebind(url, ror); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Can not connect to S_Registry, please start S_Registry first and use the proper ip and port of S_Registry"); } }
52f6d065-f014-4a95-8304-532653dc0b16
4
public void run() { // Adjust sleeping time to avoid too small times double sampleInterval = DESIRED_INTERVAL; double execInterval = sampleInterval / mySpeed; if (execInterval < MINIMUM_INTERVAL) { execInterval = MINIMUM_INTERVAL; sampleInterval = MINIMUM_INTERVAL * mySpeed; } try { long t = 0; long start = System.currentTimeMillis(); while(true) { // Update simulation state updateState(sampleInterval/1000.0); // Delay thread execution t += execInterval; long time = System.currentTimeMillis(); long sleep = t - (time - start); RTThread.sleep(sleep>0?sleep:0); } } catch(Exception e) { /* Shouldn't happen */ } }
50c06bcd-88d1-4e46-bfda-6c27f020e205
6
public boolean chocaElPardalet(float px, float py, float pw, float ph) { //System.out.println(py+" "+yEspacio); if(px>x+getW()){ System.out.println("estem a lesquerra"); } if(px+pw<x) System.out.println("estem a la dreta"); if(px+pw>x) System.out.println("Dreta: "+px+" "+pw+", "+x); if(py>yEspacio+yEspacio+hEspacio)System.out.println("entem a sota"); if(py>yEspacio+yEspacio+hEspacio)System.out.println(" baix: "+ py+", "+yEspacio+" " +hEspacio); if(py+ph<yEspacio)System.out.println("estem a sobre"); return RectWithRect(x, yEspacio, getW(), hEspacio,px, py, pw, ph); }
9d50387e-e112-4074-b065-5e8068cdf622
4
public static void reset() { step = 0; actors.clear(); populate(); if(CUSTOM_DEPTH>0 && CUSTOM_WIDTH>0 && CUSTOM_DEPTH <=100 && CUSTOM_WIDTH <=100) { field.setField(CUSTOM_DEPTH, CUSTOM_WIDTH); view.getSim().getView().changeView(CUSTOM_DEPTH,CUSTOM_WIDTH); view.repack(); } // Show the starting state in the view. view.getSim().showStatus(step, field); }
312ca556-215c-4678-b5fd-28f847d38629
5
public void convert(String input, String output, Formats inputFileformat, int lineCount) throws IOException { // we save the parameter in the class fields this.input = input; this.output = output; this.lineCount = lineCount; // we create an object fro writing the output file writer = new BufferedWriter(new FileWriter(output)); // we call the appropriate method for converting a database // according to the format of the input file if(inputFileformat.equals(Formats.IBMGenerator)){ convertIBMGenerator(); } else if(inputFileformat.equals(Formats.Kosarak)){ convertKosarak(); }else if(inputFileformat.equals(Formats.CSV_INTEGER)){ convertCSV(); }else if(inputFileformat.equals(Formats.BMS)){ convertBMS(); }else if(inputFileformat.equals(Formats.Snake)){ convertSnake(); } // we close the output file writer.close(); }
dc016bde-a4a3-4bc1-b02d-1560cdd97148
5
public void loadLibrary() { try { BufferedReader br = new BufferedReader(new FileReader("./ivJava.ini")); String line = ""; while ((line = br.readLine()) != null) { if (line.length() > 0) { int index = line.indexOf("LoadLibrary="); if (index >= 0) { String Library = line.substring(index + 12); Library = Library.replace(';', ','); System.out.println("Loading rad extensions : "); System.out.println(Library); if (!mivCanvas.loadLibraries(Library)) System.out.println("Not all rad extensions could be loaded"); break; } } } } catch (Exception ex) { System.out.println(ex); } }
de452f38-a713-46e1-b054-312baa006dd1
6
public static int[] lcp(int[] sa) { int n = sa.length; int[] rank = new int[n]; for (int i = 0; i < n; i++) rank[sa[i]] = i; int[] lcp = new int[n - 1]; for (int i = 0, h = 0; i < n; i++) { if (rank[i] < n - 1) { for (int j = sa[rank[i] + 1]; Math.max(i, j) + h < cad.length && cad[i + h] == cad[j + h]; ++h) ; lcp[rank[i]] = h; if (h > 0) --h; } } return lcp; }
16a7ade3-7355-4cc3-b079-b435b991eb08
0
private void initializeWithABC() { l.insert(c); l.insert(b); l.insert(a); }
59920104-a450-4b37-a29d-a18eb3d8d91d
9
public static void main(String[] args) { if (args.length != 1 || args[0].charAt(0) != '-') { usage(); return; } try { // Create the modeler/solver object IloCplex cplex = new IloCplex(); IloNumVar[][] var = new IloNumVar[1][]; IloRange[][] rng = new IloRange[1][]; // Evaluate command line option and call appropriate populate method. // The created ranges and variables are returned as element 0 of arrays // var and rng. switch (args[0].charAt(1)) { case 'r': populateByRow(cplex, var, rng); break; case 'c': populateByColumn(cplex, var, rng); break; case 'n': populateByNonzero(cplex, var, rng); break; default: usage(); return; } // write model to file cplex.exportModel("lpex1.lp"); // solve the model and display the solution if one was found if (cplex.solve()) { double[] x = cplex.getValues(var[0]); double[] dj = cplex.getReducedCosts(var[0]); double[] pi = cplex.getDuals(rng[0]); double[] slack = cplex.getSlacks(rng[0]); cplex.output().println("Solution status = " + cplex.getStatus()); cplex.output().println("Solution value = " + cplex.getObjValue()); int nvars = x.length; for (int j = 0; j < nvars; ++j) { cplex.output().println("Variable " + j + ": Value = " + x[j] + " Reduced cost = " + dj[j]); } int ncons = slack.length; for (int i = 0; i < ncons; ++i) { cplex.output().println("Constraint " + i + ": Slack = " + slack[i] + " Pi = " + pi[i]); } } cplex.end(); } catch (IloException e) { System.err.println("Concert exception '" + e + "' caught"); } }
202ee728-5548-4ce5-a489-c8162f79b2b3
3
public void update() { time++; if (time >= 7400) time = 0; if (time > life) remove(); za -= 0.1; if (zz < 0) { zz = 0; za *= -0.55; xa *= 0.4; ya *= 0.4; } move(xx + xa, (yy + ya) + (zz + za)); }
db57b191-d94d-4888-b0e5-9957bcdc3121
9
private void postPlugin(final boolean isPing) throws IOException { // The plugin's description file containg all of the plugin data such as // name, version, author, etc final PluginDescriptionFile description = plugin.getDescription(); // Construct the post data final StringBuilder data = new StringBuilder(); data.append(encode("guid")).append('=').append(encode(guid)); encodeDataPair(data, "version", description.getVersion()); encodeDataPair(data, "server", Bukkit.getVersion()); encodeDataPair(data, "players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length)); encodeDataPair(data, "revision", String.valueOf(REVISION)); // If we're pinging, append it if (isPing) { encodeDataPair(data, "ping", "true"); } // Acquire a lock on the graphs, which lets us make the assumption we // also lock everything // inside of the graph (e.g plotters) synchronized (graphs) { final Iterator<Graph> iter = graphs.iterator(); while (iter.hasNext()) { final Graph graph = iter.next(); for (Plotter plotter : graph.getPlotters()) { // The key name to send to the metrics server // The format is C-GRAPHNAME-PLOTTERNAME where separator - // is defined at the top // Legacy (R4) submitters use the format Custom%s, or // CustomPLOTTERNAME final String key = String.format("C%s%s%s%s", CUSTOM_DATA_SEPARATOR, graph.getName(), CUSTOM_DATA_SEPARATOR, plotter.getColumnName()); // The value to send, which for the foreseeable future is // just the string // value of plotter.getValue() final String value = Integer.toString(plotter.getValue()); // Add it to the http post data :) encodeDataPair(data, key, value); } } } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, encode(plugin.getDescription().getName()))); // Connect to the website URLConnection connection; // Mineshafter creates a socks proxy, so we can safely bypass it // It does not reroute POST requests so we need to go around it if (isMineshafterPresent()) { connection = url.openConnection(Proxy.NO_PROXY); } else { connection = url.openConnection(); } connection.setDoOutput(true); // Write the data final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data.toString()); writer.flush(); // Now read the response final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); final String response = reader.readLine(); // close resources writer.close(); reader.close(); if (response == null || response.startsWith("ERR")) { throw new IOException(response); // Throw the exception } else { // Is this the first update this hour? if (response.contains("OK This is your first update this hour")) { synchronized (graphs) { final Iterator<Graph> iter = graphs.iterator(); while (iter.hasNext()) { final Graph graph = iter.next(); for (Plotter plotter : graph.getPlotters()) { plotter.reset(); } } } } } }
622ab433-0507-422a-a02d-12472b47a03a
3
private String buildBar() { // Collecting information about the bar length int every = 100 / BAR_DEPTH; int bars = approx_progress / every; int subDepth = BAR_DEPTH / 2; // Creating the array of character corresponding to the percentage of // completion char a[] = new char[BAR_DEPTH]; if (bars > BAR_DEPTH) { bars = BAR_DEPTH; } for (int i = 0; i < bars; i++) { a[i] = '='; } for (int i = bars; i < a.length; i++) { a[i] = ' '; } // Dividing the bar into two parts String all = new String(a); String before = all.substring(0, subDepth); String after = all.substring(subDepth, BAR_DEPTH); // Formatting the bar with the percentage value in the middle String res = String.format(PROGRESS_BAR, note, before, approx_progress, after); return res.trim(); }
2de72012-fc19-454c-a93a-3e985413f6d9
3
private void jTextField9KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField9KeyPressed if (evt.getKeyCode() == 38) { jTextField7.grabFocus(); } else if (evt.getKeyCode() == 40) { jTextField8.grabFocus(); } else if (evt.getKeyCode() == 39) { jRadioButton1.grabFocus(); } }//GEN-LAST:event_jTextField9KeyPressed
41e3a7e8-78a8-4c1f-b5d7-6f1bb23c0607
9
public final void interfaces() throws RecognitionException { try { // fontes/g/CanecaSemantico.g:216:2: ( ^( INTERFACE_ modificadorDeAcessoFeminino IDENTIFICADOR listaDeTiposGenericos listaDeInterfaces corpoDaInterface ) ) // fontes/g/CanecaSemantico.g:216:4: ^( INTERFACE_ modificadorDeAcessoFeminino IDENTIFICADOR listaDeTiposGenericos listaDeInterfaces corpoDaInterface ) { match(input,INTERFACE_,FOLLOW_INTERFACE__in_interfaces629); if (state.failed) return ; match(input, Token.DOWN, null); if (state.failed) return ; pushFollow(FOLLOW_modificadorDeAcessoFeminino_in_interfaces631); modificadorDeAcessoFeminino(); state._fsp--; if (state.failed) return ; match(input,IDENTIFICADOR,FOLLOW_IDENTIFICADOR_in_interfaces633); if (state.failed) return ; pushFollow(FOLLOW_listaDeTiposGenericos_in_interfaces635); listaDeTiposGenericos(); state._fsp--; if (state.failed) return ; pushFollow(FOLLOW_listaDeInterfaces_in_interfaces637); listaDeInterfaces(); state._fsp--; if (state.failed) return ; pushFollow(FOLLOW_corpoDaInterface_in_interfaces639); corpoDaInterface(); state._fsp--; if (state.failed) return ; match(input, Token.UP, null); if (state.failed) return ; } } catch (RecognitionException erro) { throw erro; } finally { // do for sure before leaving } return ; }
3a3786df-d5c5-4ef6-aa3c-33ee5a71cb51
4
private int checkRegEx(String result) { if(result == null || result.isEmpty()) return 0; result = result.toLowerCase(); String regEx1 = "[2-9][p-z][a-h][2-9][a-z]*[p-z][2-9][p-z][2-9][p-z]"; String regEx2 = "[2-9][p-z][p-z][a-h][2-9][a-z]*[p-z][2-9][2-9][2-9][p-z]"; if(result.matches(regEx1) || result.matches(regEx2)) return 1; return 2; }
59950f67-d14f-424e-9424-2250cc5f36d3
0
public String getName(){ return name; }
a2748b0e-976e-4fae-bccf-d38002128691
9
public void keyPressed(KeyEvent arg0) { int keyCode = arg0.getKeyCode(); if(keyCode == KeyEvent.VK_ENTER) { name = inputName.getText(); for(int i = 0; i < name.length(); i++) { if(name.charAt(i) == ' ' && i < name.length() - 1) { name = name.substring(0, i) + name.substring(i + 1); } } if(inputName.getText().length() > 9 || inputName.getText().length() < 1) { } else if(name.equals("\r\n")) { name = "rn"; } else { try { out1.write("\r\n" + name + " " + score + " " + level); } catch (IOException e) {} try { out1.close(); } catch (IOException e) {} layout.swapView("Start Menu"); } } }
e204439c-1bbc-4565-b6ef-b31808104006
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(ModifierPrestataire.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ModifierPrestataire.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ModifierPrestataire.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ModifierPrestataire.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 ModifierPrestataire().setVisible(true); } }); }
1a01199f-3f7f-44a4-9880-0efe73dd8559
0
private void connectLocal(DcServer server, DCStation station) { DummyChannel chA = new DummyChannel(), chB = new DummyChannel(); Connection c1 = new DummyConnection(chA.getInputStream(), chB.getOutputStream(), station); Connection c2 = new DummyConnection(chB.getInputStream(), chA.getOutputStream(), server); station.setConnection(c1); server.getCB().addConnection(c2); }
64b2968a-0195-432b-8119-d4964cb08200
7
public static void conversationthread() throws Exception { while (worker1) { java.sql.Connection conn = DbController.dbconnect(); conv = DbController.getconversation(conn, m_loggedas); try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } int length = conv.size(); for (int i = 0; i < length; i++) { if ((conv.get(i) != null)) { try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (convstarted == 0) { startconversation(); } } } try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
73d110c9-d3c7-4352-ba1b-1974fef98c7c
9
public int Execute(PolishProgram program) throws Exception { // execute the command. // returns -10 - standard running // returns label in goto - in case the command was goto // returns -1 - in case there is a runtime error int expressionVal = -1; switch (m_Type) { case Assignment: { expressionVal = m_Expression.Execute(program); if (expressionVal != -1) { program.AssignVar(m_VarName1, expressionVal); return -10; } return -1; } case Goto: return m_Lable; case Print: { expressionVal = m_Expression.Execute(program); if (expressionVal != -1) { program.Print(expressionVal); return -10; } return -1; } case BoolOpertion: { int val1 = program.GetVarValue(m_VarName1); if (val1 == -1) { program.AddError(PolishProgram.ErrorCodeInitalization, "Not initalized var " + m_VarName1); return -1; } int val2 = program.GetVarValue(m_VarName2); if (val2 == -1) { program.AddError(PolishProgram.ErrorCodeInitalization, "Not initalized var " + m_VarName2); return -1; } if (EveluateBoolOpearion(val1, val2, m_BoolOp)) { return m_Command.Execute(program); } else { return -10; } } default: throw new Exception("Why there is some execution?"); } }
c2039078-5e74-4b7f-a800-f981fe7d1fef
5
public static World initWorld( ResourceContext rc ) throws IOException { final DemoBlocks blocks = DemoBlocks.load(rc); final GenericPhysicalNonTileInternals crateInternals = getCrateInternals(rc); final SubstanceContainerInternals fuelCanInternals = getFuelCanInternals(rc); int worldSizePower = 24; int worldDataOrigin = -(1<<(worldSizePower-1)); RSTNode n = QuadRSTNode.createHomogeneous(blocks.bricks.stack, worldSizePower); n = RSTUtil.fillShape( n, worldDataOrigin, worldDataOrigin, worldSizePower, new TCircle( -2, -2, 4 ), new SolidNodeFiller( BlockStackRSTNode.EMPTY )); n = RSTUtil.fillShape( n, worldDataOrigin, worldDataOrigin, worldSizePower, new TCircle( +2, +2, 4 ), new SolidNodeFiller( BlockStackRSTNode.EMPTY )); n = RSTUtil.fillShape( n, worldDataOrigin, worldDataOrigin, worldSizePower, new TRectangle( 3, 0, 32, 32 ), new SolidNodeFiller( BlockStackRSTNode.EMPTY )); n = RSTUtil.fillShape( n, worldDataOrigin, worldDataOrigin, worldSizePower, new TRectangle( 3, 31, 32, 1 ), new SolidNodeFiller( blocks.spikes.stack )); n = RSTUtil.fillShape( n, worldDataOrigin, worldDataOrigin, worldSizePower, new TRectangle( -24, 0, 20, 4 ), new SolidNodeFiller( BlockStackRSTNode.EMPTY )); n = RSTUtil.fillShape( n, worldDataOrigin, worldDataOrigin, worldSizePower, new TRectangle( -24, 4, 20, 1 ), new SolidNodeFiller( blocks.dirt.stack )); n = RSTUtil.fillShape( n, worldDataOrigin, worldDataOrigin, worldSizePower, new TRectangle( -24, 3, 20, 1 ), new RSTNodeUpdater() { final RSTNode treeAndGrass = BlockStackRSTNode.create(new Block[] { blocks.tree, blocks.grass } ); final Random r = new Random(); @Override public RSTNode update(RSTNode oldNode, int x, int y, int sizePower) { double v = r.nextDouble(); return v < 0.1 ? blocks.bricks.stack : v < 0.25 ? treeAndGrass : blocks.grass.stack; } }); EntitySpatialTreeIndex<NonTile> nonTiles = new EntitySpatialTreeIndex<NonTile>(); Random r = new Random(); for( int i=0; i<10; ++i ) { double sx = 0, sy = 0, dir = 0, rad = 8; while( rad > 1 ) { n = RSTUtil.fillShape( n, worldDataOrigin, worldDataOrigin, worldSizePower, new TCircle( sx, sy, rad ), new SolidNodeFiller( BlockStackRSTNode.EMPTY )); sx += Math.cos(dir); sy += Math.sin(dir); dir += r.nextGaussian() * 0.1; rad *= (0.996 + r.nextGaussian()*0.02); } //nonTiles = nonTiles.with( new BlargNonTile(0, 0, sx, sy, 0, 0, fuelCanInternals) ); } for( int i=0; i<20; ++i ) { double sx = r.nextGaussian() * 10; double sy = r.nextGaussian() * 10; //nonTiles = nonTiles.with( new BlargNonTile(0, 0, sx, sy, 0, 0, crateInternals) ); } nonTiles = nonTiles.with( new BlargNonTile(0, 0, -5, 0, 0, 0, fuelCanInternals) ); return new World(0, n, worldSizePower, nonTiles, new LayerLink(true, new SoftResourceHandle<Layer>("urn:sha1:blah"), 0, 0, 0, 0xFF001122) ); }
5a8771fe-657e-4378-a547-9915bb087b30
1
@Override public Clock deepCopy() { VectorClock newClock = new VectorClock(); newClock.hostName = this.hostName; for (String key : this.clock.keySet()) { newClock.clock.put(key, this.clock.get(key)); } return newClock; }
b52f342c-bc56-4cb9-88e2-307fa20a9bc8
7
public static Stella_Object accessTruthValueSlotValue(TruthValue self, Symbol slotname, Stella_Object value, boolean setvalueP) { if (slotname == Logic.SYM_LOGIC_POLARITY) { if (setvalueP) { self.polarity = ((Keyword)(value)); } else { value = self.polarity; } } else if (slotname == Logic.SYM_LOGIC_STRENGTH) { if (setvalueP) { self.strength = ((Keyword)(value)); } else { value = self.strength; } } else if (slotname == Logic.SYM_LOGIC_POSITIVE_SCORE) { if (setvalueP) { self.positiveScore = ((FloatWrapper)(value)).wrapperValue; } else { value = FloatWrapper.wrapFloat(self.positiveScore); } } else { if (setvalueP) { KeyValueList.setDynamicSlotValue(self.dynamicSlots, slotname, value, null); } else { value = self.dynamicSlots.lookup(slotname); } } return (value); }
c9fb834e-2eca-491b-9e26-dad5edbd544c
3
public HomeScreen(Market m, User u) { setPreferredSize(new Dimension(1000, 650)); // set it to the same size as the container setLayout(null); // it will be a card in the main deck setBackground(Color.black); // From MainFrame market = m; user = u; // Set up the home label homeLabel = new JLabel("<html> <h1> <i>Home</i> </h1> </html>"); homeLabel.setBackground(Color.black); homeLabel.setForeground(Color.white); add(homeLabel); // add to panel homeLabel.setBounds(10, 15, 100, 20); homeLabel.setOpaque(true); // Set up Expensive Stocks Label String expensiveText = "<html> <h1 align='center'>Expensive Stocks</h1><h3 align='center'> "; LinkedList<Stock> hotties = market.getExpensiveStocks(5); Stock st; for (int i = 0; i < 5; i++){ st = hotties.get(i); // System.out.println(st.getTicker()); FOR TESTING expensiveText += st.getTicker() + " : " + st.getPrice() + "$ <br>"; } expensiveText += "</h3></html>"; expensiveStocks = new JLabel(expensiveText, SwingConstants.CENTER); expensiveStocks.setBorder(BorderFactory.createLoweredBevelBorder()); add(expensiveStocks); expensiveStocks.setBounds(10, 50, 320, 290); expensiveStocks.setOpaque(true); // Set up Cheap Stocks Label String cheapText = "<html> <h1 align='center'>Cheap Stocks</h1> <h3 align='center'>"; LinkedList<Stock> weakies = market.getCheapestStocks(5); for (int i = 0; i < 5; i++){ st = weakies.get(i); cheapText += st.getTicker() + " : " + st.getPrice() + "$ <br>"; } cheapText += "</h3></html>"; cheapStocks = new JLabel(cheapText, SwingConstants.CENTER); cheapStocks.setBorder(BorderFactory.createLoweredBevelBorder()); add(cheapStocks); cheapStocks.setBounds(340, 50, 320, 290); cheapStocks.setOpaque(true); // Set up button to view stocks page viewStocksButton = new JButton("View Stocks"); add(viewStocksButton); viewStocksButton.setBounds(890, 10, 100, 30); // Set up news label String newsText = "<html><h1 align='center'> NEWS </h1></html>"; // add the text to the news panel news = new JLabel(newsText, SwingConstants.CENTER); // instantiate news panel and give it a border news.setBorder(BorderFactory.createLoweredBevelBorder()); add(news); // add and position news panel news.setBounds(10, 350, 650, 290); news.setOpaque(true); // Set up Portfolio label String portText = "<html> <h1 align='center'>Portfolio</h1> </html><h3 align='center'>"; LinkedList<StockPosition> portfolio = user.getPortfolio(); StockPosition s; for (int i = 0; i < portfolio.size(); i++){ s = portfolio.get(i); portText += s.getTicker() + " : " + s.getNumShares() + "<br>"; } portText += "$" + user.getMoney() + "</h3></html>"; myPort = new JLabel(portText, SwingConstants.CENTER); myPort.setBorder(BorderFactory.createLoweredBevelBorder()); add(myPort); myPort.setBounds(670, 50, 320, 410); myPort.setOpaque(true); // Set up button to sell all held stocks sellAll = new JButton("Sell All Stocks"); add(sellAll); sellAll.setBounds(665, 470, 330, 30); // Set up Goldberg Saacs Index label String gsText = "<html> <h1 align='center'>Goldberg Saacs Index</h1> <h3 align='center'>$" + market.getIndexVal() + "</h3></html>"; gsIndex = new JLabel(gsText, SwingConstants.CENTER); gsIndex.setBorder(BorderFactory.createLoweredBevelBorder()); add(gsIndex); gsIndex.setBounds(670, 510, 320, 130); gsIndex.setOpaque(true); }
fd436f30-3045-4dff-a082-7763f72b458e
1
private static void hasRole() throws Exception { UserDAO ud = new UserDAO(); RoleDAO rd = new RoleDAO(); Role role = (Role) rd.findById(2); User user = (User) ud.findById(2); boolean itHasRole = ud.hasRole(role, user); if (itHasRole == true) { System.out.println("Yep! :)"); } else { System.out.println("Nop! :("); } }
4400d2cb-5812-46cf-a302-87700dfe1c98
6
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { try { commands.execute(cmd.getName(), args, sender, sender); } catch (CommandPermissionsException e) { sender.sendMessage(ChatColor.RED + "You don't have permission."); } catch (MissingNestedCommandException e) { sender.sendMessage(ChatColor.RED + e.getUsage()); } catch (CommandUsageException e) { sender.sendMessage(ChatColor.RED + e.getMessage()); sender.sendMessage(ChatColor.RED + e.getUsage()); } catch (WrappedCommandException e) { if (e.getCause() instanceof NumberFormatException) { sender.sendMessage(ChatColor.RED + "Number expected, string received instead."); } else { sender.sendMessage(ChatColor.RED + "An error has occurred. See console."); e.printStackTrace(); } } catch (CommandException e) { sender.sendMessage(ChatColor.RED + e.getMessage()); } return true; }
add5a6f1-a916-4f34-873c-a73bad1de73d
0
@Override public Object filter(PropertyContainer container, Object value) { return value; }
3053a9bb-af40-43fc-8b11-15bb510d35c0
5
@Override public void handle(HttpExchange exchange) throws IOException { System.out.println("In rob player handler"); String responseMessage = ""; if(exchange.getRequestMethod().toLowerCase().equals("post")) { try { //TODO verify cookie method String unvalidatedCookie = exchange.getRequestHeaders().get("Cookie").get(0); CookieParams cookie = Cookie.verifyCookie(unvalidatedCookie, translator); BufferedReader in = new BufferedReader(new InputStreamReader(exchange.getRequestBody())); String inputLine; StringBuffer requestJson = new StringBuffer(); while ((inputLine = in.readLine()) != null) { requestJson.append(inputLine); } in.close(); System.out.println(requestJson); RobPlayerRequest request = (RobPlayerRequest) translator.translateFrom(requestJson.toString(), RobPlayerRequest.class); exchange.getRequestBody().close(); ServerModel serverModel = this.movesFacade.robPlayer(request, cookie); System.out.println("Request Accepted!"); // create cookie for user List<String> cookies = new ArrayList<String>(); // send success response headers exchange.getResponseHeaders().put("Set-cookie", cookies); exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0); movesLog.store(new RobPlayerCommand(movesFacade, request, cookie)); String name = serverModel.getPlayerByID(cookie.getPlayerID()).getName(); String robbee = request.getVictimIndex() == -1 ? "No One" : serverModel.getPlayerByID(request.getVictimIndex()).getName(); serverModel.getLog().addMessage(new LogEntry(name+ " robbed " + robbee , serverModel.getPlayerByID(cookie.getPlayerID()).getName())); responseMessage = translator.translateTo(serverModel); // TODO join game in gameModels list } catch (InvalidCookieException | InvalidMovesRequest e) { // else send error message System.out.println("unrecognized / invalid build city request"); responseMessage = e.getMessage(); exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0); } } else { // unsupported request method responseMessage = "Error: \"" + exchange.getRequestMethod() + "\" is no supported!"; exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0); } //set "Content-Type: text/plain" header List<String> contentTypes = new ArrayList<String>(); String type = "text/plain"; contentTypes.add(type); exchange.getResponseHeaders().put("Content-type", contentTypes); if (!responseMessage.isEmpty()) { //send failure response message OutputStreamWriter writer = new OutputStreamWriter( exchange.getResponseBody()); writer.write(responseMessage); writer.flush(); writer.close(); } exchange.getResponseBody().close(); }
a7a3115e-e8be-4fd9-ac7f-29eea493f71c
3
public UIForm toUIForm(String heading) { if (null == heading) throw new IllegalArgumentException(); if (_menu.size() < 1) throw new IllegalStateException(); UIForm.Pair[] array = new UIForm.Pair[_menu.size()]; for (int i = 0; i < _menu.size(); i++) array[i] = _menu.get(i); return new UIForm(heading, array); }
1656fd78-26a7-415e-9736-e2d6a9a0f9b5
4
@Override public Map<UUID, String> call() throws Exception { Map<UUID, String> uuidStringMap = new HashMap<UUID, String>(); for (UUID uuid : uuids) { HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")) .openConnection(); JSONObject response = (JSONObject) jsonParser.parse(new InputStreamReader(connection.getInputStream())); String name = (String) response.get("name"); if (name == null) { continue; } String cause = (String) response.get("cause"); String errorMessage = (String) response.get("errorMessage"); if (cause != null && cause.length() > 0) { throw new IllegalStateException(errorMessage); } uuidStringMap.put(uuid, name); } return uuidStringMap; }
4b355869-498b-4cc2-98f7-28a28bf13450
5
public static void main(String[] args) throws InvalidFormatException, IOException, ClassNotFoundException, InterruptedException { InputStream is = new FileInputStream( "en-pos-maxent.bin" ); setModel( new POSModel( is ) ); //use sockets? System.out.print("USE SOCKETS? "); boolean useSockets = scan.nextLine().toLowerCase().equals("true"); boolean actServer = false; if (useSockets) { System.out.print("ACT AS SERVER? "); actServer = scan.nextLine().toLowerCase().equals("true"); } if (useSockets && actServer) { //use sockets as server socketServerExchange(); } else if (useSockets && !actServer) { //use sockets as client socketClientExchange(); } else { //for not sockets exchange(); } }
8bf36192-64c6-4fa8-93b3-74daad6dde4f
3
@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { fcSkin = new javax.swing.JFileChooser(); grbLogin = new javax.swing.JPanel(); lblUsername = new javax.swing.JLabel(); txtUsername = new javax.swing.JTextField(); lblPassword = new javax.swing.JLabel(); btnLogin = new javax.swing.JButton(); btnRegister = new javax.swing.JButton(); txtPassword = new javax.swing.JPasswordField(); tabs = new javax.swing.JTabbedPane(); tabMain = new javax.swing.JPanel(); panBg = new javax.swing.JPanel(); tabSync = new javax.swing.JPanel(); panSync = new javax.swing.JPanel(); pbSync = new javax.swing.JProgressBar(); btnRestartSync = new javax.swing.JButton(); spTblSync = new javax.swing.JScrollPane(); tblSync = new javax.swing.JTable(); tabLog = new javax.swing.JPanel(); logTabs = new javax.swing.JTabbedPane(); tabOutLog = new javax.swing.JPanel(); spLog = new javax.swing.JScrollPane(); txtLog = new javax.swing.JTextArea(); tabChatLog = new javax.swing.JPanel(); scChatDates = new javax.swing.JScrollPane(); lbChatDates = new javax.swing.JList(); scChatLog = new javax.swing.JScrollPane(); txtChatLog = new javax.swing.JTextArea(); btnRefresh = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); grbSkin = new javax.swing.JPanel(); panSkin = new javax.swing.JPanel(); btnRemoveSkin = new javax.swing.JButton(); btnUploadSkin = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); btnChangePassword = new javax.swing.JButton(); txtNewPassword = new javax.swing.JPasswordField(); jPanel3 = new javax.swing.JPanel(); lblMemory = new javax.swing.JLabel(); cbMemory = new javax.swing.JComboBox(); btnLaunch = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); txtWidth = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); txtHeight = new javax.swing.JTextField(); jPanel4 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); fcSkin.setAcceptAllFileFilterUsed(false); fcSkin.setDialogTitle("Select skin png"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } public void windowClosed(java.awt.event.WindowEvent evt) { formWindowClosed(evt); } }); grbLogin.setBorder(javax.swing.BorderFactory.createTitledBorder("Login")); lblUsername.setText("Username:"); txtUsername.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtUsernameKeyTyped(evt); } }); lblPassword.setText("Password:"); btnLogin.setText("Login"); btnLogin.setEnabled(false); btnLogin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLoginActionPerformed(evt); } }); btnRegister.setText("Register"); btnRegister.setEnabled(false); btnRegister.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRegisterActionPerformed(evt); } }); txtPassword.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtPasswordKeyTyped(evt); } }); javax.swing.GroupLayout grbLoginLayout = new javax.swing.GroupLayout(grbLogin); grbLogin.setLayout(grbLoginLayout); grbLoginLayout.setHorizontalGroup( grbLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(grbLoginLayout.createSequentialGroup() .addContainerGap() .addGroup(grbLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE) .addComponent(txtUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE) .addGroup(grbLoginLayout.createSequentialGroup() .addComponent(btnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE) .addComponent(btnRegister, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(grbLoginLayout.createSequentialGroup() .addGroup(grbLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblUsername) .addComponent(lblPassword)) .addGap(0, 174, Short.MAX_VALUE))) .addContainerGap()) ); grbLoginLayout.setVerticalGroup( grbLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(grbLoginLayout.createSequentialGroup() .addComponent(lblUsername) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblPassword) .addGap(1, 1, 1) .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(grbLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnLogin) .addComponent(btnRegister))) ); javax.swing.GroupLayout panBgLayout = new javax.swing.GroupLayout(panBg); panBg.setLayout(panBgLayout); panBgLayout.setHorizontalGroup( panBgLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 508, Short.MAX_VALUE) ); panBgLayout.setVerticalGroup( panBgLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 486, Short.MAX_VALUE) ); javax.swing.GroupLayout tabMainLayout = new javax.swing.GroupLayout(tabMain); tabMain.setLayout(tabMainLayout); tabMainLayout.setHorizontalGroup( tabMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(tabMainLayout.createSequentialGroup() .addComponent(panBg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); tabMainLayout.setVerticalGroup( tabMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panBg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); tabs.addTab("Main", tabMain); panSync.setBorder(javax.swing.BorderFactory.createEtchedBorder()); pbSync.setStringPainted(true); btnRestartSync.setText("Restart"); btnRestartSync.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRestartSyncActionPerformed(evt); } }); javax.swing.GroupLayout panSyncLayout = new javax.swing.GroupLayout(panSync); panSync.setLayout(panSyncLayout); panSyncLayout.setHorizontalGroup( panSyncLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panSyncLayout.createSequentialGroup() .addContainerGap() .addComponent(pbSync, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnRestartSync) .addContainerGap()) ); panSyncLayout.setVerticalGroup( panSyncLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panSyncLayout.createSequentialGroup() .addContainerGap() .addGroup(panSyncLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(pbSync, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnRestartSync)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); tblSync.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "File", "Status", "Progress" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.Object.class }; boolean[] canEdit = new boolean [] { false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); spTblSync.setViewportView(tblSync); if (tblSync.getColumnModel().getColumnCount() > 0) { tblSync.getColumnModel().getColumn(2).setResizable(false); tblSync.getColumnModel().getColumn(2).setCellRenderer(new TableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (table.getValueAt(row, 2) == null) { table.setValueAt(new JProgressBar(), row, 2); } if (table.getValueAt(row, 2) instanceof Component) { return (Component)table.getValueAt(row, 2); } else { return null; } } }); } javax.swing.GroupLayout tabSyncLayout = new javax.swing.GroupLayout(tabSync); tabSync.setLayout(tabSyncLayout); tabSyncLayout.setHorizontalGroup( tabSyncLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panSync, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(spTblSync, javax.swing.GroupLayout.DEFAULT_SIZE, 508, Short.MAX_VALUE) ); tabSyncLayout.setVerticalGroup( tabSyncLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(tabSyncLayout.createSequentialGroup() .addComponent(panSync, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(spTblSync, javax.swing.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE)) ); tabs.addTab("File sync", tabSync); spLog.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); spLog.setAutoscrolls(true); txtLog.setEditable(false); txtLog.setColumns(20); txtLog.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N txtLog.setRows(5); spLog.setViewportView(txtLog); javax.swing.GroupLayout tabOutLogLayout = new javax.swing.GroupLayout(tabOutLog); tabOutLog.setLayout(tabOutLogLayout); tabOutLogLayout.setHorizontalGroup( tabOutLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(spLog, javax.swing.GroupLayout.DEFAULT_SIZE, 496, Short.MAX_VALUE) ); tabOutLogLayout.setVerticalGroup( tabOutLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(spLog, javax.swing.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE) ); logTabs.addTab("Output", tabOutLog); lbChatDates.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lbChatDatesMouseClicked(evt); } }); scChatDates.setViewportView(lbChatDates); scChatLog.setAutoscrolls(true); txtChatLog.setEditable(false); txtChatLog.setColumns(20); txtChatLog.setFont(new java.awt.Font("Courier New", 0, 12)); // NOI18N txtChatLog.setRows(5); scChatLog.setViewportView(txtChatLog); btnRefresh.setText("Refresh"); btnRefresh.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRefreshActionPerformed(evt); } }); javax.swing.GroupLayout tabChatLogLayout = new javax.swing.GroupLayout(tabChatLog); tabChatLog.setLayout(tabChatLogLayout); tabChatLogLayout.setHorizontalGroup( tabChatLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(tabChatLogLayout.createSequentialGroup() .addGroup(tabChatLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(scChatDates, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE) .addComponent(btnRefresh, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(scChatLog, javax.swing.GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE)) ); tabChatLogLayout.setVerticalGroup( tabChatLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(tabChatLogLayout.createSequentialGroup() .addGroup(tabChatLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(scChatLog) .addComponent(scChatDates, javax.swing.GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnRefresh) .addContainerGap()) ); logTabs.addTab("Chat log", tabChatLog); javax.swing.GroupLayout tabLogLayout = new javax.swing.GroupLayout(tabLog); tabLog.setLayout(tabLogLayout); tabLogLayout.setHorizontalGroup( tabLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(logTabs) ); tabLogLayout.setVerticalGroup( tabLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(logTabs, javax.swing.GroupLayout.PREFERRED_SIZE, 486, Short.MAX_VALUE) ); tabs.addTab("Log", tabLog); grbSkin.setBorder(javax.swing.BorderFactory.createTitledBorder("Skin setup")); panSkin.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout panSkinLayout = new javax.swing.GroupLayout(panSkin); panSkin.setLayout(panSkinLayout); panSkinLayout.setHorizontalGroup( panSkinLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 153, Short.MAX_VALUE) ); panSkinLayout.setVerticalGroup( panSkinLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 157, Short.MAX_VALUE) ); btnRemoveSkin.setText("Remove"); btnRemoveSkin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveSkinActionPerformed(evt); } }); btnUploadSkin.setText("Setup new"); btnUploadSkin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnUploadSkinActionPerformed(evt); } }); javax.swing.GroupLayout grbSkinLayout = new javax.swing.GroupLayout(grbSkin); grbSkin.setLayout(grbSkinLayout); grbSkinLayout.setHorizontalGroup( grbSkinLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(grbSkinLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(panSkin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(grbSkinLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnUploadSkin, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE) .addComponent(btnRemoveSkin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) ); grbSkinLayout.setVerticalGroup( grbSkinLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panSkin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(grbSkinLayout.createSequentialGroup() .addComponent(btnUploadSkin) .addGap(4, 4, 4) .addComponent(btnRemoveSkin)) ); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Change password")); jLabel1.setText("New password:"); btnChangePassword.setText("Change"); btnChangePassword.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnChangePasswordActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(btnChangePassword)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(txtNewPassword)) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtNewPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnChangePassword) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(grbSkin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(grbSkin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(289, Short.MAX_VALUE)) ); tabs.addTab("My Account", jPanel1); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Launch", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); lblMemory.setText("Memory:"); cbMemory.setEditable(true); cbMemory.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "512", "1024", "2048", "3032", "4096" })); btnLaunch.setText("Launch"); btnLaunch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLaunchActionPerformed(evt); } }); jButton2.setText("Get launch command"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel4.setText("Resolution:"); jLabel5.setText("X"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnLaunch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jButton2)) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblMemory) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(txtWidth, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtHeight, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(cbMemory, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblMemory) .addComponent(cbMemory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(txtWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5) .addComponent(txtHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnLaunch) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2) .addContainerGap()) ); jPanel4.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jLabel2.setText("(c) 2014-2015 Cr0s"); jLabel3.setForeground(new java.awt.Color(22, 88, 54)); jLabel3.setText("!!rkyi9XPa76"); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap(74, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel3) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel3))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(tabs) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(grbLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(grbLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(tabs)) ); pack(); }// </editor-fold>//GEN-END:initComponents
5c029e19-1d5b-4d55-804c-d0df0bf9a680
1
public void addClassAnalyzer(ClassAnalyzer clazzAna) { if (innerAnalyzers == null) innerAnalyzers = new Vector(); innerAnalyzers.addElement(clazzAna); getParent().addClassAnalyzer(clazzAna); }
ea457ede-4621-4c49-abd4-31db087ed13e
2
@Override public void run() { while (true) { repaint(); try { Thread.sleep(10); } catch (InterruptedException e) { } frame++; } }
721920dc-eaaa-4004-b29e-9a494890dc43
1
@Override protected boolean doDelete(final String key) { boolean ok = client.delete(key); if (!ok) { CacheErrorHandler.handleError(new Exception("Memcached:删除缓存Key[" + key + "]对应的对象失败")); } return ok; }
7c00109e-c5a9-4a04-9d8b-e5f81eb243db
5
public void askActionType(List<String> actions) { System.out.println(this.texts.get("actionType")); String result = ""; for (int i = 0; i < actions.size(); i++) { result += "\t[" + (i + 1) + "]\t" + actions.get(i) + "\n"; } System.out.println(result); String rep = ""; int indexRep = -1; boolean error = true; while (error) { try { rep = this.getAnswer(); indexRep = Integer.parseInt(rep); error = !(indexRep > 0 && indexRep < actions.size() + 1); if (!error) break; System.err.println("Wrong index : out of bounds"); } catch (NumberFormatException e) { System.err.println("Invalid input - Please try again"); } } this.controler.notifyActionTypeSelected(actions.get(indexRep - 1)); }
f11c5afc-3136-4de6-8a27-4a2b8a3f20cd
6
@Override public int processMessage(String msg) { System.out.println(msg); String[] action = msg.trim().split(":"); if(!action[0].equals(tabPlayer[currentPlayer].getId())) return -2; if (action[1].equals("MOVEB")) { if(moveB(tabPlayer[currentPlayer].getColor(), action[2], action[3])) return 0; else return -1; } else if (action[1].equals("MOVES")) { if(moveS(tabPlayer[currentPlayer].getColor(), action[2], action[3])) return 1; else return -1; } else if (action[1].equals("ENDTURN")) { return 2; } return -1; }
37b34f8c-0937-4e01-939d-4ced44f69340
6
public static boolean chooseSave() { JFileChooser cho = new JFileChooser(file); cho.setFileSelectionMode(JFileChooser.FILES_ONLY); FileFilter emu = new FileFilter(){{} @Override public boolean accept(File f) { if (f.isDirectory()) return true; String ext = getExtension(f); if (ext != null) { if (ext.equals("db")) return true; else return false; } return false; } @Override public String getDescription() { // TODO Auto-generated method stub return "*.db Database Files"; }}; cho.addChoosableFileFilter((javax.swing.filechooser.FileFilter) emu); cho.setFileFilter(emu); cho.setSelectedFile(file); int choice = cho.showSaveDialog(Main.mainInstance.frame); System.out.println(choice); if (choice == JFileChooser.APPROVE_OPTION) { File f = cho.getSelectedFile(); String ext = getExtension(f); if (ext==null||!ext.equals("db")) f = new File(f.getAbsolutePath()+".db"); return saveFile(f); } return false; }
03e4952e-63af-471f-956e-70621c7bfe05
4
public boolean isOptOut() { synchronized (optOutLock) { try { // Reload the metrics file configuration.load(getConfigFile()); } catch (IOException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } catch (InvalidConfigurationException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } return configuration.getBoolean("opt-out", false); } }
50ebc905-2ce7-4cbb-b8bb-2c8f8c8652ac
0
public String getTrainNumber() { return this._trainNumber; }
d937ac99-4252-4914-a87e-c34989ea7dd0
5
@Override public Object solve() { int max = 0; for (int i = 0; i < 20; i++) { for (int j = 0; j < 20; j++) { for (Direction d : Direction.values()) { if (isAValidDirection(d, i, j)) { int val = calculateProduct(d, i, j); if (val > max) { max = val; } } } } } return max; }
aa03cddc-b98c-4183-85bf-715a84d7b824
3
public boolean isPrime(long num) { if (num%2 == 0) { return false; } for (int i = 3; i*i <= num; i+=2) { if (num % i == 0) { return false; } } return true; }
d68daf1d-9243-44d4-a296-a723720f3afc
1
public void pause() { for (ConnectionProcessor pipe : pipes) { pipe.pause(); } }
783301ba-a11f-4bf1-bd92-760b7b32fe6e
1
public static ArrayList<Excel> rotateX(int angle, ArrayList<Excel> toScale) { ArrayList<Excel> result = new ArrayList<Excel>(); double matrix[][] = { {1, 0,0,0}, {0, Math.cos(angle * Math.PI/180), Math.sin(angle* Math.PI/180), 0}, {0,(-Math.sin(angle* Math.PI/180)), Math.cos(angle* Math.PI/180),0}, {0, 0,0,1} }; Matrix scaleMatrix = new Matrix(4,4); scaleMatrix.setMatrix(matrix); for (Excel ex: toScale) { double l[][] = {{ex.getX()}, {ex.getY()}, {ex.getZ()}, {ex.getT()} }; Matrix line = new Matrix(4,1); line.setMatrix(l); Matrix multiplied = Matrix.matrixMultiplication(scaleMatrix, line); int x =(int) Math.round(multiplied.getEl(0, 0)); int y =(int) Math.round(multiplied.getEl(1, 0)); int z =(int) Math.round(multiplied.getEl(2, 0)); int t =(int) Math.round(multiplied.getEl(3, 0)); result.add(new Excel(x,y,z,t, ex.getColor())); } return result; }
b44c0b0c-af1c-45b6-930d-96b059fd5cd8
2
public void broadcast(String broadcastMessage){ Iterator<DCBroadcastReceiver> it = dCBroadcasterSubscribers.iterator(); while(it.hasNext()) { DCBroadcastReceiver subscriber = it.next(); if (subscriber==null) { it.remove(); } else { subscriber.onReceive(broadcastMessage); } } }
d656914e-a52d-418d-8e1d-e740327d33b2
6
static void checkMethodSignature(final String signature) { // MethodTypeSignature: // FormalTypeParameters? ( TypeSignature* ) ( TypeSignature | V ) ( // ^ClassTypeSignature | ^TypeVariableSignature )* int pos = 0; if (getChar(signature, 0) == '<') { pos = checkFormalTypeParameters(signature, pos); } pos = checkChar('(', signature, pos); while ("ZCBSIFJDL[T".indexOf(getChar(signature, pos)) != -1) { pos = checkTypeSignature(signature, pos); } pos = checkChar(')', signature, pos); if (getChar(signature, pos) == 'V') { ++pos; } else { pos = checkTypeSignature(signature, pos); } while (getChar(signature, pos) == '^') { ++pos; if (getChar(signature, pos) == 'L') { pos = checkClassTypeSignature(signature, pos); } else { pos = checkTypeVariableSignature(signature, pos); } } if (pos != signature.length()) { throw new IllegalArgumentException(signature + ": error at index " + pos); } }
545c7e66-d1f7-4dee-aee5-253962455046
1
public void addHability(Ability ability) { if(!this.abilitiesListed.contains(ability.getName())) { buttons[cur].setAbility(ability); buttons[cur].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectedAbility = ((AbilityButton)e.getSource()).getAbility(); owner.getMain().getGamePanel().setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); } }); this.abilitiesListed.add(ability.getName()); repaint(); buttons[cur].setVisible(true); cur++; } }
39b35edf-0a4d-48d8-b381-c7e79c7e7b8d
9
private void setOutputFormatNumeric() { if (m_Indices == null) { setOutputFormat(null); return; } FastVector newAtts; int newClassIndex; StringBuffer attributeName; Instances outputFormat; FastVector vals; // Compute new attributes newClassIndex = getInputFormat().classIndex(); newAtts = new FastVector(); for (int j = 0; j < getInputFormat().numAttributes(); j++) { Attribute att = getInputFormat().attribute(j); if ((!att.isNominal()) || (j == getInputFormat().classIndex())) { newAtts.addElement(att.copy()); } else { if (j < getInputFormat().classIndex()) newClassIndex += att.numValues() - 2; // Compute values for new attributes for (int k = 1; k < att.numValues(); k++) { attributeName = new StringBuffer(att.name() + "="); for (int l = k; l < att.numValues(); l++) { if (l > k) { attributeName.append(','); } attributeName.append(att.value(m_Indices[j][l])); } if (m_Numeric) { newAtts. addElement(new Attribute(attributeName.toString())); } else { vals = new FastVector(2); vals.addElement("f"); vals.addElement("t"); newAtts. addElement(new Attribute(attributeName.toString(), vals)); } } } } outputFormat = new Instances(getInputFormat().relationName(), newAtts, 0); outputFormat.setClassIndex(newClassIndex); setOutputFormat(outputFormat); }
751823a5-7e90-4c50-b005-d0a0d7b5a8f3
8
private Object genRandom(Class<?> clazz) { Object rand = null; if (clazz == Boolean.class) { rand = random.nextBoolean(); } else if (clazz == Integer.class) { rand = random.nextInt(); } else if (clazz == Long.class) { rand = random.nextLong(); } else if (clazz == Double.class) { rand = random.nextDouble(); } else if (clazz == String.class) { rand = UUID.randomUUID().toString(); } else { try { rand = clazz.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return rand; }
08bf5bff-c39f-4930-b1d0-697824ae03e3
7
static boolean isThereAStraight(Hand hand){ //first check for ace low straight if (hand.get(0).getValue() == 2 && hand.get(1).getValue() == 3 && hand.get(2).getValue() == 4 && hand.get(3).getValue() == 5 && hand.get(4).getValue() == 14) return true; for(int x = 0; x < hand.size()-1 ; x++) // look for a difference of one between sequential cards { if (hand.get(x).getValue()+1 != hand.get(x+1).getValue()) // if difference is greater than 1, false return false; } return true; }
4f110985-791b-4485-b3eb-6a9ff69061d7
3
MainWindow() { this.setLayout(new BorderLayout()); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(WINDOW_DEFAULT_WIDTH, WINDOW_DEFAULT_HEIGTH); this.setTitle(WINDOW_TITLE); this.setMinimumSize(new Dimension(WINDOW_MIN_WIDTH, WINDOW_MIN_HEIGTH)); frame = this; settings.get(frame); clipboard = new ClipboardUtils(); //Test area Dimension d1234 = new Dimension(12, 20); settings.put("A", d1234); settings.save(); Dimension d1111 = new Dimension(0, 0); d1111 = settings.getDimension("A"); System.out.println("CMP::" + d1234); System.out.println("CMP::" + d1111); mainWindowHeaderPanel = getHeader(); //settings.get(MAIN_PANEL_TITLE, mainWindowHeaderPanelSize); //System.err.println("BOOTmainWindowHeaderPanelSize" + mainWindowHeaderPanelSize); add(mainWindowHeaderPanel, BorderLayout.NORTH); add(getMainContentPanel(), BorderLayout.CENTER); add(getFooter(), BorderLayout.SOUTH); this.setVisible(true); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent event){ settings.put(frame); settings.put(MAIN_PANEL_TITLE, mainWindowHeaderPanelSize); settings.save(); } }); addComponentListener(new ComponentListener() { public void componentResized(ComponentEvent evt) { Dimension size = mainWindowHeaderPanel.getSize(); if (size != null && size.height > 0 && size.width > 0) { mainWindowHeaderPanelSize = size; } remove(mainWindowHeaderPanel); mainWindowHeaderPanel = getHeader(); add(mainWindowHeaderPanel, BorderLayout.NORTH); System.out.println("componentResized::" + mainWindowHeaderPanelSize); } @Override public void componentMoved(ComponentEvent e) {} @Override public void componentShown(ComponentEvent e) {} @Override public void componentHidden(ComponentEvent e) {} }); }
4eefcf3c-da77-470d-ab86-3687b6cf6530
0
public String getCountry() { return super.getCountry(); }
42723639-56f0-4a0c-b663-2860e3eb18e9
7
public int check() { if (columns < 3 || rows < 3) { return 1; } else if (timesteps < 1) { return 2; } else if (constantK <= 0 || constantK > 1) { return 3; } else if (timesteps > 100) { return 4; } else if (rows * columns > 3600) { return 5; } else { return 0; } }