text
stringlengths
14
410k
label
int32
0
9
public byte variance(String fileName) throws IOException { FileInputStream is = null; DataInputStream dis = null; BufferedWriter br = new BufferedWriter(new FileWriter("variance_bin.txt")); NumberFormat formatter = new DecimalFormat(); formatter = new DecimalFormat("0.000E00"); try { is = new FileInputStream(fileName); dis = new DataInputStream(new BufferedInputStream(is)); int senones = (int)dis.readFloat(); int gaussians = (int)dis.readFloat(); br.write("param " + senones + " 1 " + gaussians); br.newLine(); for(int i = 0; i < senones; i++) { br.write("mgau " + i +" "); br.newLine(); br.write("feat 0"); br.newLine(); for(int j = 0; j < gaussians; j++) { br.write("density " + j +" "); for(int k = 0 ; k < 39; k++) br.write(formatter.format(dis.readFloat()) + " "); br.newLine(); } } } catch(Exception e){ e.printStackTrace(); return 0; } finally{ if(is != null)is.close(); if(dis != null)dis.close(); if(br != null){ br.flush(); br.close(); } } return 1; }
7
public Spielfeld(Game game) { super(); this.game = game; this.setFocusable(true); }
0
private void lifeCycle() { String s = ""; StringBuilder sb = new StringBuilder(); while (isInputActive) { try { s = readInput(); if (s.length()==0) { this.isInputActive = false; break; } if (this.isValidInput(s)) { sb.append(s); } } catch (IOException e) { e.printStackTrace(); } } action(sb.toString()); }
4
public void renderProjectile(int xp, int yp, Projectile p){ xp -= xOffset; yp -= yOffset; for(int y=0;y<p.sprite.SIZE;y++){ int ya = y + yp + 0; for(int x=0;x<p.sprite.SIZE;x++){ int xa = x+xp; if(xa< -p.sprite.SIZE || xa >= width || ya<0 || ya >=height) continue; if(xa<0) xa =0; int col = p.sprite.pixels[x+y*p.sprite.SIZE]; if(col!= 0xFFFF00FF) pixels[xa+ya*width] = col; } } }
8
public synchronized void setValues(Double[] values, Double marked1, Double marked2) { this.values = values.clone(); this.marked1 = marked1; this.marked2 = marked2; repaint(); }
0
public StringBuilder readFromFileMethod(String fileName) { try { // Initialize the file input stream FileInputStream fstream = new FileInputStream(fileName); int count = 0; // Get DataInputStream object in = new DataInputStream(fstream); br = new BufferedReader(new InputStreamReader(in)); String strLine = null; WeatherMetaDataDao weatherMetaDao = new WeatherMetaDataDao(); // Read File Line By Line while ((strLine = br.readLine()) != null) { // append the content to StringBulder count++; if (count == 1) continue; HashMap<String, String> metaInfo = new HashMap<String, String>(); String[] lineArray = strLine.split(","); if (lineArray.length == 18) { metaInfo.put("primary_id", lineArray[0]); metaInfo.put("secondary_id", lineArray[1]); metaInfo.put("station_name", lineArray[2]); metaInfo.put("state", lineArray[3]); metaInfo.put("country", lineArray[4]); metaInfo.put("latitude", lineArray[5]); metaInfo.put("longitude", lineArray[6]); metaInfo.put("elevation", lineArray[7]); metaInfo.put("mesowest_network_id", lineArray[8]); metaInfo.put("network_name", lineArray[9]); metaInfo.put("status", lineArray[10]); metaInfo.put("primary_provider_id", lineArray[11]); metaInfo.put("primary_provider", lineArray[12]); metaInfo.put("secondary_provider_id", lineArray[13]); metaInfo.put("secondary_provider", lineArray[14]); metaInfo.put("tertiary_provider_id", lineArray[15]); metaInfo.put("tertiary_provider", lineArray[16]); metaInfo.put("wims_id", lineArray[17]); } weatherMetaDao.saveDataHeader(metaInfo, count); } // Close the input stream in.close(); } catch (Exception e) { logger.severe("Issue with reading file " + e.getMessage()); e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.severe("Issue with reading file " + e.getMessage()); } } if (br != null) { try { br.close(); } catch (IOException e) { logger.severe("Issue with reading file " + e.getMessage()); } } } // System.out.println("I am the one who is throwing " + data); return data; }
8
private void addStakesToStakeTempStartingFrom(int i) { while (lastStake() < endStake) { if (nextStakeFitsInGeometry(i)) { addNewStake(i); resetLeftovers(); } else if (onlyOneStakeLeft(i)) { addFinalStake(i); break; } else { addRestOfTheGeometryToLeftovers(i); i++; } } }
3
@Override public void process(Deque<String> par1Args) { for(int i = 0; i < argc; i++){ String s = par1Args.poll(); if(s.length() < 1) continue; if(s != null && conv.accept(s)){ vals.add(s); } else { throw new IllegalArgumentException(); } } }
4
void coverageByExons(Marker read, Marker m, String typeRank) { // Find corresponfing transcript Transcript tr = (Transcript) m.findParent(Transcript.class); if (tr == null) return; // Number of exons int exons = tr.numChilds(); // Do we need to add new counters? if (coverageByExons.size() <= exons) { for (int i = coverageByExons.size(); i <= exons; i++) coverageByExons.add(new CoverageByType()); } // Perform stats CoverageByType cbe = coverageByExons.get(exons); PosStats posStats = cbe.getOrCreate(typeRank); posStats.sample(read, m); }
3
private void grabBranch() { if(Main.VERBOSE) System.out.println("[INFO] Determining current Git branch..."); BufferedReader buffRead = null; String branch = null; try { Process proc = Runtime.getRuntime().exec("git branch"); buffRead = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = null; while ((line = buffRead.readLine()) != null) { if (line.contains("*")) { branch = line.replaceAll("\\* ", ""); } } } catch (IOException ioExcep) { if(Main.VERBOSE) System.out.println("[ERROR] Cannot get current Git branch!"); branch = "unknown"; } finally { if(Main.VERBOSE) System.out.println("[INFO] Branch determined as '" + branch + "'"); builder.append("Branch="); builder.append(branch); builder.append("\n"); try { if (buffRead != null) { buffRead.close(); } } catch (IOException ioExcep) { } } }
8
private static void extractFromZip( String szZipFilePath, String szExtractPath, String szName, ZipFile zf, ZipEntry ze) { if(ze.isDirectory()) return; String szDstName = slash2sep(szName); String szEntryDir; if(szDstName.lastIndexOf(File.separator) != -1) { szEntryDir = szDstName.substring( 0, szDstName.lastIndexOf(File.separator)); } else szEntryDir = ""; //System.out.print(szDstName); long nSize = ze.getSize(); long nCompressedSize = ze.getCompressedSize(); //System.out.println(" " + nSize + " (" + nCompressedSize + ")"); try { File newDir = new File(szExtractPath + File.separator + szEntryDir); newDir.mkdirs(); FileOutputStream fos = new FileOutputStream(szExtractPath + File.separator + szDstName); InputStream is = zf.getInputStream(ze); byte[] buf = new byte[1024]; int nLength; while(true) { try { nLength = is.read(buf); } catch (EOFException ex) { break; } if(nLength < 0) break; fos.write(buf, 0, nLength); } is.close(); fos.close(); } catch(Exception ex) { System.out.println(ex.toString()); //System.exit(0); } }
6
private static String byte2hex(byte[] b) { StringBuilder hs = new StringBuilder(); String stmp; for (int n = 0; b != null && n < b.length; n++) { stmp = Integer.toHexString(b[n] & 0XFF); if (stmp.length() == 1) hs.append('0'); hs.append(stmp); } return hs.toString().toUpperCase(); }
3
public static void printFactorization(int num) { int temp = num; ArrayList<Integer> array = new ArrayList<Integer>(); while (temp != 1) { for (int i = 2; i <= temp; i++) if (temp % i == 0) { array.add(i); temp /= i; break; } } Collections.sort(array); System.out.print(num + " = 1x"); for (int i = 0; i < array.size(); i++) { if (i > 0) System.out.print("x"); System.out.print(array.get(i)); } }
5
private void renderBrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_renderBrowseButtonActionPerformed JFileChooser f = new JFileChooser(renderToField.getText()); File fi = new File(renderToField.getText()); if(fi.isDirectory()) { f.setCurrentDirectory(fi); } else { f.setSelectedFile(fi); } f.setDialogTitle("Render To File"); class GIFFileFilter extends FileFilter { public boolean accept(File f) { if (f.isDirectory()) return true; return f.getName().toLowerCase().endsWith("gif"); } public String getDescription() { return "GIF files"; } } f.addChoosableFileFilter(new GIFFileFilter()); f.setFileSelectionMode(JFileChooser.FILES_ONLY); int result = f.showSaveDialog(this); if (result == JFileChooser.APPROVE_OPTION) { fi = f.getSelectedFile(); String s = fi.getPath(); if(!s.equals("")) { if (!s.endsWith(".gif")) { s = s + ".gif"; } renderToField.setText(s); } } }//GEN-LAST:event_renderBrowseButtonActionPerformed
4
public void entrenar(String[][] entradas){ boolean finalizado = false; int Pw,error, y; this.numeroEpocasFinal = 0; while(!finalizado){ finalizado = true; for(int n = 0; n < entradas.length; n++){ Pw = this.desicion(entradas[n]); y = Integer.valueOf(entradas[n][entradas[n].length-1]); //Clase esperada error = y - Pw; System.out.println("Entrada[" + n + "] Y: " + y + " Pw: " + Pw); if(error != 0){ finalizado = false; this.ajustarPesos(entradas[n], error); } } this.numeroEpocasFinal++; if(this.numeroEpocasFinal >= this.limiteEpocas) finalizado = true; } //Pesos finales System.out.println("Peso 1: " + this.getPesoLlaveEntera(0)); System.out.println("Peso 2: " + this.getPesoLlaveEntera(1)); System.out.println("Peso 3: " + this.getPesoLlaveEntera(2)); System.out.println("Peso 4: " + this.getPesoLlaveEntera(3)); }
4
public static synchronized Object evalSubL(CycAccess connection, String subl) { Object result = null; try { if (CycConnection.inAWTEventThread()) { throw new RuntimeException("Unable to communicate with Cyc from the AWT event dispatch thread."); } long resultMsecs = 0; if(useTiming) { resultMsecs = System.currentTimeMillis(); } result = connection.converseObject(subl); if(useTiming) { System.out.println("Finished call: " + subl); resultMsecs = System.currentTimeMillis() - resultMsecs; System.out.println("Call took: " + resultMsecs + " msecs."); } } catch (IOException e) { throw new CycIOException(e); } return result; }
4
public boolean start() { synchronized (optOutLock) { // Did we opt out? if (isOptOut()) { return false; } // Is metrics already running? if (task != null) { return true; } // Begin hitting the server with glorious data task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { private boolean firstPost = true; public void run() { try { // This has to be synchronized or it can collide with the disable method. synchronized (optOutLock) { // Disable Task, if it is running and the server owner decided to opt-out if (isOptOut() && task != null) { task.cancel(); task = null; // Tell all plotters to stop gathering information. for (Graph graph : graphs) { graph.onOptOut(); } } } // We use the inverse of firstPost because if it is the first time we are posting, // it is not a interval ping, so it evaluates to FALSE // Each time thereafter it will evaluate to TRUE, i.e PING! postPlugin(!firstPost); // After the first post we set firstPost to false // Each post thereafter will be a ping firstPost = false; } catch (IOException e) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); } } } }, 0, PING_INTERVAL * 1200); return true; } }
7
private boolean waitForSelect(){ try{ while (!fNext && !fCancel){ Thread.sleep(50); } if (fNext){ PrintLog.Log("button was pressed"); String path = textField.getText(); File f = new File(path); if (f.isDirectory()){ closeForm(); InstallerSettings is = new InstallerSettings(); is.setInstallDir(path); Helpers help = new Helpers(); if (help.moveFiles()){ Persistence p = new Persistence(); p.saveData("ospath", "\""+path+"\""); return true; } else { frame.setVisible(true); additionalInstructions.setText("<html>The location you selected is invalid "+ "or locked for copying. Please select a different location.</html>"); additionalInstructions.setForeground(Color.red); frame.getContentPane().repaint(); textField.setBackground(Color.yellow); fNext = false; return waitForSelect(); } } else { frame.setVisible(true); additionalInstructions.setText("<html>The location you selected is invalid "+ "or locked for copying. Please select a different location.</html>"); additionalInstructions.setForeground(Color.red); frame.getContentPane().repaint(); textField.setBackground(Color.yellow); fNext = false; return waitForSelect(); } } if (fCancel){ closeForm(); } } catch (Exception e) { e.printStackTrace(); } return false; }
7
private void verifyPlayersInBoard() throws Exception { for (int row = 0; row < _board.length; ++row) { for (int col = 0; col < _board.length; ++col) { if (isCellEmpty(row, col)) { continue; } if (_board[row][col] != _leftPlayer && _board[row][col] != _rightPlayer) { throw new JProblemsException("Invalid board - Contains invalid player symbol."); } } } }
5
public void testToStandardDays_months() { Period test = Period.months(1); try { test.toStandardDays(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(-1); try { test.toStandardDays(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(0); assertEquals(0, test.toStandardDays().getDays()); }
2
public Color getGroutingColor(Color c) { return groutingColor; }
0
@Override public String toString() { String className = this.getClass().getSimpleName(); return ((getTitle() == null || getTitle().isEmpty())? url.toString() : "[" +className+ "] " + getTitle()); }
2
private void initProjectivization(DependencyStructure pdg) throws MaltChainedException { nodeLifted.clear(); nodeTrace.clear(); headDeprel.clear(); nodePath.clear(); isCoveredRoot.clear(); nodeRelationLength.clear(); for (int index : pdg.getDependencyIndices()) { nodeLifted.add(false); nodeTrace.add(new Vector<DependencyNode>()); headDeprel.add(null); nodePath.add(false); isCoveredRoot.add(false); if (ppliftedSymbolTable != null && index != 0) { pdg.getDependencyNode(index).getHeadEdge().getLabelSet().put(ppliftedSymbolTable, ppliftedSymbolTable.getSymbolStringToCode("#false#")); } if (pppathSymbolTable != null && index != 0) { pdg.getDependencyNode(index).getHeadEdge().getLabelSet().put(pppathSymbolTable, pppathSymbolTable.getSymbolStringToCode("#false#")); } if (ppcoveredRootSymbolTable != null && index != 0) { pdg.getDependencyNode(index).getHeadEdge().getLabelSet().put(ppcoveredRootSymbolTable, ppcoveredRootSymbolTable.getSymbolStringToCode("#false#")); } } computeRelationLength(pdg); }
7
protected String readStream() throws Exception { while (!reader.ready()) { Thread.sleep(50); } String out = reader.readLine(); for (int i = 0; i < error.length; i++) { if (out.equals(error[i])) { throw new Exception(); } } return out; }
3
@Override public final synchronized void display() { this.slider.setMinimum(this.min); this.slider.setMaximum(this.max); this.slider.setValue((int) (this.value * this.factor)); this.slider.setPaintTicks(true); this.slider.setPaintLabels(true); this.slider.setMajorTickSpacing(this.step); this.slider.setMinorTickSpacing(this.ticks); this.label.setText(String.format("%s %.2f", this.value == 0 ? " " : this.value > 0 ? "+" : "-", Double.valueOf(Math .abs(this.value) / this.factor))); if (this.object != null) { this.bruteParams.setLocalValue(this.object, this.target, Double.valueOf(this.value)); } @SuppressWarnings("unchecked") final Dictionary<Integer, JLabel> dict = this.slider.getLabelTable(); final Enumeration<Integer> keys = dict.keys(); while (keys.hasMoreElements()) { final Integer key = keys.nextElement(); final JLabel labelDict = dict.get(key); labelDict.setText(String.format("%3.2f", Double.valueOf(key.intValue() / this.factor))); final Dimension d = labelDict.getSize(); d.width = 3 * labelDict.getFont().getSize(); labelDict.setSize(d); } this.slider.addChangeListener(new SliderListener()); }
4
public boolean deleteItem(int id, int slot, int amount) { if (slot > -1 && slot < playerItems.length) { if ((playerItems[slot] - 1) == id) { if (playerItemsN[slot] > amount) { playerItemsN[slot] -= amount; } else { playerItemsN[slot] = 0; playerItems[slot] = 0; } resetItems(3214); return true; } } else { return false; } return false; }
4
@Override public void render(Graphics g) { if (slomoEffect > 0) { g.setColor(new Color(0.0F, 0.0F, 0.0F, 0.051F)); } else { g.setColor(defaultBackground); } g.fillRect(0, 0, Game.WIDTH, Game.HEIGHT); g.setColor(defaultColor); g.setFont(new Font("Courier New, Courier", 12, 12)); if (firstRun) { g.drawString("Use WASD to move", 40, 60); g.drawString("Use SPACE to shoot", 40, 76); g.drawString("Shoot as many blocks as possible", 40, 92); g.drawString("Boxes with a star contain special stuff", 40, 108); g.drawString("Avoid getting hit by anything!", 40, 124); } else { if (gameOver) { g.drawString( "GAME OVER", Game.WIDTH / 2 - (int) g .getFont() .getStringBounds( "GAME OVER", new FontRenderContext(null, false, false)) .getWidth() / 2, Game.HEIGHT / 2 - 50); g.drawString( "Final score: " + score, Game.WIDTH / 2 - (int) g .getFont() .getStringBounds( "Final score " + score, new FontRenderContext(null, false, false)) .getWidth() / 2, Game.HEIGHT / 2 - 30); if (display) { g.drawString( "Press SPACE to continue", Game.WIDTH / 2 - (int) g .getFont() .getStringBounds( "Spress SPACE to continue", new FontRenderContext(null, false, false)) .getWidth() / 2, Game.HEIGHT / 2); } } else { g.drawString("Score: " + score, 20, 20); } } for (int i = 0; i < entities.size(); i++) { entities.get(i).render(g); } }
5
public int etsiOikeaX(){ int oikX = 0; for (Palikka palikka : palikat) { if (palikka.getX() > oikX){ oikX = palikka.getX(); } } return oikX; }
2
void paintOpacityFlow(CPRect srcRect, CPRect dstRect, byte[] brush, int w, int opacity, int flow) { int[] opacityData = opacityBuffer.data; int by = srcRect.top; for (int j = dstRect.top; j < dstRect.bottom; j++, by++) { int srcOffset = srcRect.left + by * w; int dstOffset = dstRect.left + j * width; for (int i = dstRect.left; i < dstRect.right; i++, srcOffset++, dstOffset++) { int brushAlpha = (brush[srcOffset] & 0xff) * flow; if (brushAlpha != 0) { int opacityAlpha = opacityData[dstOffset]; int newAlpha = Math.min(255 * 255, opacityAlpha + (opacity - opacityAlpha / 255) * brushAlpha / 255); newAlpha = Math.min(opacity * (brush[srcOffset] & 0xff), newAlpha); if (newAlpha > opacityAlpha) { opacityData[dstOffset] = newAlpha; } } } } }
4
private void sendClickBlockToController(int par1, boolean par2) { if (!par2) { this.leftClickCounter = 0; } if (par1 != 0 || this.leftClickCounter <= 0) { if (par2 && this.objectMouseOver != null && this.objectMouseOver.typeOfHit == EnumMovingObjectType.TILE && par1 == 0) { int var3 = this.objectMouseOver.blockX; int var4 = this.objectMouseOver.blockY; int var5 = this.objectMouseOver.blockZ; this.playerController.onPlayerDamageBlock(var3, var4, var5, this.objectMouseOver.sideHit); if (this.thePlayer.canPlayerEdit(var3, var4, var5)) { this.effectRenderer.addBlockHitEffects(var3, var4, var5, this.objectMouseOver.sideHit); this.thePlayer.swingItem(); } } else { this.playerController.resetBlockRemoving(); } } }
8
public void test_04_Pe() { int numTests = 1000; Random rand = new Random(20100617); for( int t = 0; t < numTests; t++ ) { // Create gap String gapStr = ""; int gap = rand.nextInt(50) + 1; for( int i = 0; i < gap; i++ ) gapStr += "N"; // Sequence 2 int len1 = rand.nextInt(100) + 1; String seq1 = randSeq(len1, rand); // Sequence 2 int len2 = rand.nextInt(100) + 1; String seq2 = randSeq(len2, rand); // Final sequence String seq = seq1 + gapStr + seq2; DnaSequencePe bseqpe = new DnaSequencePe(seq1, seq2, gap); if( verbose ) System.out.println("PE test: " + t + "\t" + bseqpe); if( !bseqpe.toString().equals(seq) ) throw new RuntimeException("Sequences do not match:\n\t" + seq + "\n\t" + bseqpe); } }
4
public static CustomButton doFileMoveButton(final File dls) { final String title = dls.getName(); final CustomButton a = new CustomButton(title); a.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String root = EarningsTest.PATH_SOURCE.getText(); if (title.contains("BIG_nas")) { String newLocation = root + File.separator + "lg" + File.separator + "q"; try { FileUtils.moveFileToDirectory(dls, new File(newLocation), true); } catch (IOException e) { e.printStackTrace(); } } else if (title.contains("nas")) { String newLocation = root + File.separator + "sm" + File.separator + "q"; try { FileUtils.moveFileToDirectory(dls, new File(newLocation), true); } catch (IOException e) { e.printStackTrace(); } } if (title.contains("BIG_ny")) { String newLocation = root + File.separator + "lg" + File.separator + "y"; try { FileUtils.moveFileToDirectory(dls, new File(newLocation), true); } catch (IOException e) { e.printStackTrace(); } } else if (title.contains("ny")) { String newLocation = root + File.separator + "sm" + File.separator + "y"; try { FileUtils.moveFileToDirectory(dls, new File(newLocation), true); } catch (IOException e) { e.printStackTrace(); } } } }); return a; }
8
public void enable() { }
0
@Override public void setVisible(boolean b) { if (b) { serverTextField.setText(Config.getInstance().getHost()); int port = Config.getInstance().getPort(); if (port == 0) { portTextField.setText(""); } else { portTextField.setText(Integer.toString(Config.getInstance().getPort())); } userTextField.setText(Config.getInstance().getRpcUser()); passwordTextField.setText(Config.getInstance().getRpcPass()); updateIntervalSpinner.setValue(Config.getInstance().getUpdateInterval()); } super.setVisible(b); }
2
public JSONObject putOnce(String key, Object value) throws JSONException { if (key != null && value != null) { if (opt(key) != null) { throw new JSONException("Duplicate key \"" + key + "\""); } put(key, value); } return this; }
3
protected static String parsePathForZip( String p, String parentDir ) { if( ((p.indexOf( "/" ) != 0) || (p.indexOf( "\\" ) == 0)) ) { while( p.indexOf( ".." ) == 0 ) { p = p.substring( 3 ); if( !parentDir.equals( "" ) && ((parentDir.charAt( parentDir.length() - 1 ) == '/') || (parentDir.charAt( parentDir.length() - 1 ) == '\\')) ) { parentDir = parentDir.substring( 0, parentDir.length() - 2 ); } int z = parentDir.lastIndexOf( "/" ); if( z == -1 ) { z = parentDir.lastIndexOf( "\\" ); } parentDir = parentDir.substring( 0, z + 1 ); } p = parentDir + p; //if(DEBUG) // Logger.logInfo("parsePathForZip:"+p); } else if( !p.equals( "" ) ) { p = p.substring( 1 ); } return p; }
8
public static double[] evaluateWinningOdds(Cards[] hands, Cards board, Cards other) { int numhands = hands.length; double[] odds = new double[numhands]; int[] wins = new int[numhands]; int[] ties = new int[numhands]; int total = 0; // Get a fresh deck Cards remaining = new Deck().getCards(); // Remove the known cards from the deck for (Cards hand : hands) { for (Card card : hand) { remaining.remove(card); } } for (Card card : board) { remaining.remove(card); } for (Card card : other) { remaining.remove(card); } // To what depth are we going to have to search if (board.size() == 0) { // Need to search 5 cards total = search5(hands, board, numhands, wins, ties, remaining); } else if (board.size() == 3) { // Need to search 2 cards total = search2(hands, board, numhands, wins, ties, remaining); } else if (board.size() == 4) { // Need to search 1 card total = search1(hands, board, numhands, wins, ties, remaining); } else if (board.size() == 5) { // Game is determined total = rankHands(hands, board, numhands, wins, ties, total); } int i = 0; for (int win : wins) { odds[i++] = ((double) win) / total; } //System.out.println(total); return odds; }
9
public void run() { long lastTime = System.nanoTime(); double ns = 16666666.666666666D; double delta = 0.0D; double delta2 = 0.0D; int ticks = 0; int frames = 0; long timer = System.currentTimeMillis(); while (run) { long now = System.nanoTime(); delta += (now - lastTime) / ns; delta2 += (now - lastTime) / ns; lastTime = now; if (delta >= 1.0D) { tick(); if (debug) { ticks++; } delta -= 1.0D; } if (delta2 >= 0.1D) { delta2 -= 0.1D; draw(); if (debug) { frames++; } } if (System.currentTimeMillis() - timer > 1000) { timer += 1000; if (debug) { this.finalFrames = frames; this.finalTicks = ticks; } frames = 0; ticks = 0; } } }
7
public boolean hasSpam(String text) { String[] words = text.toLowerCase().split(" "); for (String imp : impossibles) { if (text.contains(imp)) return true; } boolean hasSpam = true; for (String word : words) { if (word.length() > 20) return true; for (String vowel : vowels) { if (word.contains(vowel)) hasSpam = false; } if (hasSpam) return true; } while (rerepeat.matcher(text).find()) return true; while (rerepeat_.matcher(text).find()) return true; return false; }
9
public void updateStarAnm(int k, Character plat) { // manages vertical moving platforms Platform tempStar = (Platform) plat; int tempy1 = tempStar.getY(); int tempv = tempStar.getVV(); int vcount = tempStar.getVcount(); if (tempv == -1) { if (vcount >= 100) { tempStar.setVV(1); } if (vcount < 100) { tempStar.changeY(tempv); tempStar.setVcount(tempStar.getVcount() + 1); } } if (tempv == 1) { if (vcount <= -100) { tempStar.setVV(-1); } if (vcount > -100) { tempStar.changeY(tempv); tempStar.setVcount(tempStar.getVcount() - 1); } } // if(tempStar.getBrownAnimation()){ myPlatforms.set(k, tempStar); offScreenBuffer.drawImage(myImages.get(tempStar.getId()), tempStar.getX(), tempStar.getY(), this); // }else{ // myPlatforms.set(k, tempStar); // offScreenBuffer.drawImage(myImages.get(tempStar.getId()), // tempStar.getX(), tempStar.getY(), this); // } }
6
private Game createGame(String gameType) { Game game = null; Player playerA = null; Player playerB = null; if (gameType == null) { new MemoryGameError().displayError("MainCommands - create: gameType is null"); return null; } if (gameType.equals(Game.ONE_PLAYER_GAME)) { game = new Game(Game.ONE_PLAYER_GAME); playerA = new Player(Player.MAIN_USER); playerA.name = "Player 1"; } else if (gameType.equals(Game.TWO_PLAYER_GAME)) { game = new Game(Game.TWO_PLAYER_GAME); playerA = new Player(Player.MAIN_USER); playerA.name = "Player 1"; playerB = new Player(Player.SECOND_USER); playerB.name = "Player 2"; } // save the two players created as the default players of the game game.playerA = playerA; game.playerB = playerB; // set the game status to game not yet in playing mode game.status = Game.NO_ACTIVE_GAME; return game; }
3
public void setBubbleRange( String bubbleSizes ) { if( (bubbleSizes != null) && !bubbleSizes.equals( "" ) ) { myseries.getParentChart().setMetricsDirty(); Ai ai = myseries.getBubbleValueAi(); if( ai.getWorkBook() == null ) { ai.setWorkBook( wbh.getWorkBook() ); } ai.changeAiLocation( ai.toString(), bubbleSizes ); ai.setRt( 2 ); try { // also update Bubble Count for this series int[] coords = ExcelTools.getRangeCoords( bubbleSizes ); myseries.setBubbleCount( coords[4] ); myseries.getParentChart().setMetricsDirty(); } catch( Exception e ) { } } }
4
@Test public void kameraSeuraaOikein() { this.k = new Kamera(0, 0); this.p = new Pelaaja(); p.setXY(new Piste(0, 0)); for (int i = 0; i < 100; i++) { k.seuraa(p); } assertTrue("Kamera ei liikkunut oikeaan x - koordinaattiin, vaan " + k.toString(), k.getX() == -423); assertTrue("Kamera ei liikkunut oikeaan y - koordinaattiin, vaan " + k.toString(), k.getY() == -406); }
1
private void initIgnored() { if (!fIgnore.isFile()) return; String line; try { BufferedReader br = new BufferedReader(new FileReader(fIgnore)); while ((line = br.readLine()) != null) { ignoredList.add(new File(line)); } br.close(); } catch (FileNotFoundException e) { // checked with ".exists()" } catch (IOException e) { System.err.print("Warning: I/O exception when reading " + fIgnore); } }
4
private List<Tile> getShuffledTiles() { List<Tile> shuffledTiles = new ArrayList<Tile>(); for (int i = 0; i < BEARS; i++) shuffledTiles.add(new Bear()); for (int i = 0; i < FOXES; i++) shuffledTiles.add(new Fox()); for (int i = 0; i < LUMBERJACKS; i++) shuffledTiles.add(new Lumberjack()); for (int i = 0; i < HUNTERS; i++) shuffledTiles.add(new Hunter()); for (int i = 0; i < PHEASANTS; i++) shuffledTiles.add(new Pheasant()); for (int i = 0; i < DUCKS; i++) shuffledTiles.add(new Duck()); for (int i = 0; i < TREES; i++) shuffledTiles.add(new Tree()); Collections.shuffle(shuffledTiles); return shuffledTiles; }
7
void animate(int start,int end, float interpolation,ArrayList<Integer> aggNodes,boolean outlineOnly){ Integer startPosition = this.persistence.get(start); Integer endPosition = this.persistence.get(end); int interpolationAmt=0; if (startPosition ==1 && endPosition ==1){ interpolationAmt = 255; }else if (startPosition==0 && endPosition==1){ //Node is fading in interpolationAmt = easeInExpo(interpolation,0,255,1); }else if (startPosition==1 && endPosition==0){ //Node is fading out interpolationAmt = easeOutExpo((1-interpolation),0,255,1); } if (aggNodes.contains(this.id) && interpolationAmt!=255){ if (outlineOnly){ drawNode(255,outlineOnly); //Kind of redundant... }else{ drawNode(interpolationAmt,false); drawNodeLabel(255); } }else{ drawNode(interpolationAmt,false); } }
9
public boolean shapeValido() { return (numSymbol != 4 ? true : false); }
1
public void setup() { //To reduce pixelation smooth(); noStroke(); //Create an PApplet ssize of 800x700 size(800, 700); //Zooming and Panning Libaries zoomer = new ZoomPan(this); zoomer.setZoomMouseButton(PConstants.RIGHT); //Get the observer, map and sizes this.obiwan = w.getObserver(); curMap = w.getMap(); this.xSize = curMap.getXSize(); this.ySize = curMap.getYSize(); //Load all the cell images rock = loadImage("rock.png"); food = loadImage("food.png"); antHR = loadImage("redH.png"); antHB = loadImage("blackH.png"); clear = loadImage("clear.png"); antB = loadImage("blackAnt.png"); antR = loadImage("redAnt.png"); //Load the score board images scoreboard_round = loadImage("scoreboard_round.png"); scoreboard_red = loadImage("scoreboard_red.png"); scoreboard_black = loadImage("scoreboard_black.png"); //Load the fonts f = createFont("Arial", 20, true); f2 = createFont("Arial", 34, true); //Create a new board with the map sizes board = new Hexagon[xSize][ySize]; //Fill the board with Hexagons and appropriate images loaded into each hexagon Cell cCell; for (int y = 0; y < ySize; y++) { for (int x = 0; x < xSize; x++) { cCell = curMap.getCell(y, x); if (cCell.containsRock()) { board[x][y] = new Hexagon(this, rock); } else if (cCell.containsBlackAnt()) { board[x][y] = new Hexagon(this, antB); } else if (cCell.containsRedAnt()) { board[x][y] = new Hexagon(this, antR); } else if (cCell.isContainsFood()) { board[x][y] = new Hexagon(this, food); } else if (cCell.containsBlackAntHill()) { board[x][y] = new Hexagon(this, antHB); } else if (cCell.containsRedAntHill()) { board[x][y] = new Hexagon(this, antHR); } else if (cCell.isClear()) { board[x][y] = new Hexagon(this, clear); } } } //Load the library and create the buttons cp5 = new ControlP5(this); cp5.addSlider("speed").setPosition(10, 640).setSize(150, 20) .setRange(30, 500).setValue(60); cp5.addFrameRate().setInterval(10).setPosition(130, 645); cp5.addButton("endgame").setPosition(10, 670).setSize(150, 20); }
9
public void fullyMoveTondeuses() { for (int i = 0; i < tondeuses.size(); i++) { Tondeuse t = tondeuses.get(i); Integer totalNumberOfActions = t.getActions().size(); for (int j = 0; j < totalNumberOfActions; j++) { t.executeAndRemoveNextAction(); } } }
2
static byte[] changeLdcToLdcW(byte[] code, ExceptionTable etable, CodeAttribute ca, CodeAttribute.LdcEntry ldcs) throws BadBytecode { ArrayList jumps = makeJumpList(code, code.length); while (ldcs != null) { addLdcW(ldcs, jumps); ldcs = ldcs.next; } Pointers pointers = new Pointers(0, 0, 0, etable, ca); byte[] r = insertGap2w(code, 0, 0, false, jumps, pointers); return r; }
1
@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 Membergebuehr)) { return false; } Membergebuehr other = (Membergebuehr) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
5
public synchronized void addBaudRate(Link link) { double baudRate = link.getBaudRate(); if (baudRates_ == null) { return; } baudRates_.add( new Double(baudRate) ); if (bandwidth_ < 0 || baudRate < this.bandwidth_) { this.setBandwidth(baudRate); this.setBottleneckID(link.get_id()); } }
3
public boolean imageUpdate(Image img, int flags, int x, int y, int width, int height) { if((flags & HEIGHT)!=0) { this.imgHeight=height; } if((flags & WIDTH)!=0) { this.imgWidth=width; } return(this.imgHeight<0 || this.imgWidth<0 /*|| this.imgBitsPerPixel <0 || this.imgIndexedColors <0*/); }
3
private void initComponents(){ setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); backButton = new JButton("<"); trackSelection = new JLabel(); Dimension labelSize = new Dimension(200,50); trackSelection.setPreferredSize(labelSize); trackSelection.setText("Next Track"); trackSelection.setHorizontalTextPosition(JLabel.CENTER); forwardButton = new JButton(">"); quickPlayButton = new JButton("Quick Play"); quickPlayButton.setVisible(false); searchTextField = new JTextField(10); searchTextField.setText("Search.."); searchTextField.setActionCommand("search"); searchTextField.setSelectedTextColor(Color.gray); searchTextField.setForeground(Color.gray); searchTextField.setToolTipText("Search for a track, artist or album"); searchButton = new JButton("Search"); searchButton.setToolTipText("Search"); setCollapseSearchVisible(false); c.gridx = 0; c.gridy = 0; this.add(backButton,c); c.gridx = 3; c.gridy = 0; c.gridwidth = 3; c.fill = GridBagConstraints.HORIZONTAL; this.add(trackSelection); c.gridx = 4; c.gridy = 0; c.gridwidth = 1; this.add(forwardButton); c.gridx = 4; c.gridy = 0; c.gridwidth = 1; this.add(quickPlayButton); c.gridx = 5; c.gridy = 0; c.weightx = 1; c.anchor = GridBagConstraints.LINE_END; this.add(searchTextField,c); c.gridx = 6; c.gridy = 6; this.add(searchButton); searchTextField.addMouseListener(this); backButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if(!emptyPlaylist){ positionCount--; if(positionCount >=0 ){ trackSelection.setText(trackArray[positionCount]); } else{ positionCount = trackArray.length; trackSelection.setText(trackArray[positionCount]); } } } }); forwardButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if(!emptyPlaylist){ positionCount++; if(positionCount < trackArray.length) { trackSelection.setText(trackArray[positionCount]); }else{ positionCount = 0; trackSelection.setText(trackArray[positionCount]); } } } }); quickPlayButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ BottomPanel bP = BottomPanel.getInstance(); CenterConsole cC = CenterConsole.getInstance(); String[] sArray = bP.getSongFromPlaylist(trackSelection.getText()); cC.artistLabel.setText(sArray[0]); cC.titleLabel.setText(sArray[1]); cC.albumLabel.setText(sArray[2]); ButtonControlPanel control = ButtonControlPanel.getInstance(); control.play.setIcon(control.pauseIcon); control.isPaused = false; control.play.setToolTipText("Pause song"); // temp.timeNowLabel.setText(); // temp.totTimeLabel.setText(); } }); }
4
public void deleteElement(String value) { ListElement index = head; if (index.value == value) { deleteFromBegin(); } else { while (index.next != null) { if (index.next.value == value) { index.next = index.next.next; } else { index = index.next; } } if ((index.next == null) && (index.value == value)) { deleteFromEnd(); } } }
5
private static Path getCodegenDir(CommandLine line) { if (!line.hasOption(CODEGEN) && (!line.hasOption(SHOW_VALUES) && !line.hasOption(OUTPUT_MODEL))) { printHelp(configureOptions()); System.exit(1); } if (line.hasOption(CODEGEN)) { File codegenDir = new File(line.getOptionValue(CODEGEN)); if (codegenDir.exists()) { if (!codegenDir.canWrite()) { System.err.println("Codegen '" + codegenDir + "' is not writable"); System.exit(1); } else if (!codegenDir.isDirectory()) { System.err.println("Codegen '" + codegenDir + "' is not a directory"); System.exit(1); } } return codegenDir.toPath(); } else { return null; } }
7
public HTMLParser(String file) { File html = new File(file); parseHTML(html); }
0
public static NumberWrapper timesComputation(NumberWrapper x, NumberWrapper y) { { double floatresult = Stella.NULL_FLOAT; { Surrogate testValue000 = Stella_Object.safePrimaryType(x); if (Surrogate.subtypeOfIntegerP(testValue000)) { { IntegerWrapper x000 = ((IntegerWrapper)(x)); { Surrogate testValue001 = Stella_Object.safePrimaryType(y); if (Surrogate.subtypeOfIntegerP(testValue001)) { { IntegerWrapper y000 = ((IntegerWrapper)(y)); return (IntegerWrapper.wrapInteger(((int)(x000.wrapperValue * y000.wrapperValue)))); } } else if (Surrogate.subtypeOfFloatP(testValue001)) { { FloatWrapper y000 = ((FloatWrapper)(y)); floatresult = x000.wrapperValue * y000.wrapperValue; } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + testValue001 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } } } } else if (Surrogate.subtypeOfFloatP(testValue000)) { { FloatWrapper x000 = ((FloatWrapper)(x)); { Surrogate testValue002 = Stella_Object.safePrimaryType(y); if (Surrogate.subtypeOfIntegerP(testValue002)) { { IntegerWrapper y000 = ((IntegerWrapper)(y)); floatresult = x000.wrapperValue * y000.wrapperValue; } } else if (Surrogate.subtypeOfFloatP(testValue002)) { { FloatWrapper y000 = ((FloatWrapper)(y)); floatresult = x000.wrapperValue * y000.wrapperValue; } } else { { OutputStringStream stream001 = OutputStringStream.newOutputStringStream(); stream001.nativeStream.print("`" + testValue002 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream001.theStringReader()).fillInStackTrace())); } } } } } else { { OutputStringStream stream002 = OutputStringStream.newOutputStringStream(); stream002.nativeStream.print("`" + testValue000 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream002.theStringReader()).fillInStackTrace())); } } } return (FloatWrapper.wrapFloat(floatresult)); } }
6
public static String getOption() { String option = "gui"; try { BufferedReader r = new BufferedReader(new FileReader("config.txt")); String line = r.readLine(); while (line != null) { if (line.startsWith("Option=")) { String[] tokens = line.split("="); if (tokens[1].equalsIgnoreCase("gui")) option = "gui"; if (tokens[1].equalsIgnoreCase("sim")) option = "sim"; if (tokens[1].equalsIgnoreCase("simulator")) option = "sim"; if (tokens[1].equalsIgnoreCase("simdb")) option = "simdb"; if (tokens[1].equalsIgnoreCase("simulatordb")) option = "simdb"; } line = r.readLine(); } r.close(); } catch (Exception ex) { option = "gui"; } return option; }
8
@Override public String getAcademicLevel() { return super.getAcademicLevel(); }
0
public boolean matches(Operator loadop) { return (loadop instanceof InvokeOperator || loadop instanceof GetFieldOperator); }
1
private void setUpdateStatementValues(ArrayList<Integer> keyIndexes, PreparedStatement pstmt, String[] columns, String[] values, Double[] doubleValues) throws MobbedException { String[] keyColumns = addByIndex(keyIndexes, columns); String[] nonKeyColumns = removeByIndex(keyIndexes, columns); String[] keyValues = addByIndex(keyIndexes, values); String[] nonKeyValues = removeByIndex(keyIndexes, values); int i; int k = 0; int l = 0; try { for (i = 0; i < nonKeyColumns.length; i++) { int targetType = lookupTargetType(nonKeyColumns[i]); if (doubleValues != null && targetType == Types.DOUBLE) { if (doubleValues[k] != null) pstmt.setDouble(i + 1, doubleValues[k]); else pstmt.setObject(i + 1, doubleValues[k]); k++; } else { pstmt.setObject(i + 1, nonKeyValues[l], targetType); l++; } } for (int j = 0; j < keyColumns.length; j++) { int targetType = lookupTargetType(keyColumns[j]); pstmt.setObject(i + j + 1, keyValues[j], targetType); } } catch (SQLException ex) { throw new MobbedException("Could not set value\n" + ex.getMessage()); } }
6
public SelectHTMLExportStyleDialog(Frame owner, String title) { super(true, true, true, INITIAL_WIDTH, INITIAL_HEIGHT, MINIMUM_WIDTH, MINIMUM_HEIGHT); // Initialize CSS_DIR = new File(Outliner.PREFS_DIR + System.getProperty("com.organic.maynard.outliner.Outliner.cssdir", "css") + System.getProperty("file.separator")); OK = GUITreeLoader.reg.getText("ok"); CANCEL = GUITreeLoader.reg.getText("cancel"); bProceed = new JButton(OK); bCancel = new JButton(CANCEL); bProceed.addActionListener(this); bCancel.addActionListener(this); // Create the Layout Box vBox = Box.createVerticalBox(); vBox.add(styles); vBox.add(Box.createVerticalStrut(5)); Box buttonBox = Box.createHorizontalBox(); buttonBox.add(bProceed); buttonBox.add(bCancel); vBox.add(buttonBox); getContentPane().add(vBox,BorderLayout.CENTER); }
0
private int isEqualSomething(String str) { for (int i = 0; i < list_From_file.size(); i++) { if (((data) list_From_file.get(i)).getBinary_Code().equals(str)) return i; } return -1; }
2
public static void main(String[] args) { List<Integer> abundants = new ArrayList<>(); for (int i = 1; i < 28123; i++) { Collection<BigInteger> factors = Utils.factorize(BigInteger .valueOf(i)); int sum = 0; for (BigInteger factor : factors) { sum += factor.intValue(); } if (sum > i) { abundants.add(i); } } HashSet<Integer> sums = new HashSet<>(); for (int a1 : abundants) { for (int a2 : abundants) { sums.add(a1 + a2); } } BigInteger result = BigInteger.ZERO; for (int i = 1; i <= 28123; i++) { if (!sums.contains(i)) { result = result.add(BigInteger.valueOf(i)); } } System.out.println("Result = " + result); }
7
private static int applyComboScore(String passwd, int letterScore, int numberScore, int specialScore) { int comboScore = 0; // COMBOS // [verified] both upper and lower case if (letterScore == MIXED_IMPLIED) { comboScore += 2; log.debug("2 combo points for upper and lower letters."); } // [verified] both letters and numbers if (letterScore > 0 && numberScore > 0) { comboScore += 2; log.debug("2 combo points for letters and numbers."); } // [verified] letters, numbers, and special characters if (letterScore > 0 && numberScore > 0 && specialScore > 0) { comboScore += 2; log.debug("2 combo points for letters, numbers and special chars"); } // [verified] upper, lower, numbers, and special characters if (letterScore == MIXED_IMPLIED && numberScore > 0 && specialScore > 0) { comboScore += 2; log.debug("2 combo points for upper and lower case letters, numbers and special chars"); } return comboScore; }
9
public void doConversion(){ String worldName; String fileName; String number = "0"; String[] oldData; String[] newData; String[] worlds = FH.getFolders("Undo Saves"); for(int i = 0; i < worlds.length; i++){ worldName = worlds[i]; File folder = new File(FH.folder + "Undo Saves" + FH.separator + worldName); GiantTreesRevived.logInfo("Converting saves for " + worldName + "..."); File[] files = folder.listFiles(); for(int k = 0; k < files.length; k++){ fileName = files[k].getName(); if(!fileName.equals("Trees.dat")){ number = fileName.replace("Tree", ""); number = number.replace(".dat", ""); oldData = FH.read("Undo Saves" + FH.separator + worldName + FH.separator + fileName); if(isThere(oldData[0])){ append(oldData, number, "Saves" + FH.separator + worldName + FH.separator + "Trees.dat"); newData = new String[oldData.length - 4]; for(int j = 0; j < newData.length; j += 4){ //need to re-order in new format: location first, type last newData[j] = oldData[j + 5]; newData[j + 1] = oldData[j + 6]; newData[j + 2] = oldData[j + 7]; newData[j + 3] = oldData[j + 4]; } FH.write(newData, "Saves" + FH.separator + worldName + FH.separator + fileName); FH.writeToArchive("Saves" + FH.separator + worldName + FH.separator + fileName.replace(".dat", ".zip"), "Saves" + FH.separator + worldName + FH.separator + fileName); } } } String[] current = {number}; FH.write(current, "Saves" + FH.separator + worldName + FH.separator + "CurrentTree.dat"); number = "0"; } GiantTreesRevived.logInfo("Removing old stuff..."); for(int i = 0; i < worlds.length; i++){ worldName = worlds[i]; File folder = new File(FH.folder + "Undo Saves" + FH.separator + worldName); File[] files = folder.listFiles(); for(int k = 0; k < files.length; k++){ files[k].delete(); } folder.delete(); } File temp = new File(FH.folder + "Undo Saves"); temp.delete(); }
7
@Override public boolean MoveUp() { undodata.addLast(dataClone()); undoscore.addLast(scoreClone()); initFlag(); win = false; noMoreMoves = false; boolean flag = true; int count = 0; while (flag == true) { flag = false; for(int i=1; i<N; i++) { for(int j=0; j<N; j++) { if (data[i][j]==0) continue; else if (data[i-1][j] == 0) { data[i-1][j]=data[i][j]; data[i][j]=0; flag = true; count++; } else if ((data[i-1][j] == data[i][j]) && (dataflag[i-1][j] == true) && (dataflag[i][j] == true)) { score=score+data[i][j]*2; data[i-1][j]=data[i][j]*2; dataflag[i-1][j]=false; data[i][j]=0; checkWin(data[i-1][j]); flag = true; count++; } } } } if (count !=0) { addBrick(); checkLoose(); setChanged(); notifyObservers(); return true; } else{ data=undodata.removeLast(); score=undoscore.removeLast(); setChanged(); notifyObservers(); return false; } }
9
public static String desencriptar(/*String passPhrase, */String str) { Cipher ecipher = null; Cipher dcipher = null; try { // Crear la key KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), SALT_BYTES, ITERATION_COUNT); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); ecipher = Cipher.getInstance(key.getAlgorithm()); dcipher = Cipher.getInstance(key.getAlgorithm()); // Preparar los parametros para los ciphers AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT_BYTES, ITERATION_COUNT); // Crear los ciphers ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec); } catch (javax.crypto.NoSuchPaddingException e) { e.printStackTrace(); } catch (java.security.NoSuchAlgorithmException e) { e.printStackTrace(); } catch (java.security.InvalidKeyException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } try { // Decodear base64 y obtener bytes //byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str); byte[] dec = getBytes(str); // Desencriptar byte[] utf8 = dcipher.doFinal(dec); // Decodear usando utf-8 return new String(utf8, "UTF8"); } catch (javax.crypto.BadPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (java.io.IOException e) { e.printStackTrace(); } return null; }
9
public static int getIntFromUser(String prompt) { while (true) { try { return Integer.parseInt(getUserInput(prompt)); } catch (Exception e) { System.out.println("FUCK OFF THATS NOT A NUMBER"); } } }
2
public boolean matchesAndOneAbove(Card other) { return (other.getSuit() == this.suit && this.rank.ordinal() == other.getRank().ordinal() + 1); }
1
public void union(Set s) { ListNode thisNode = list.front(); ListNode anotherNode = s.list.front(); while (thisNode.isValidNode() && anotherNode.isValidNode()) { try { Comparable thisItem = (Comparable) thisNode.item(); Comparable anotherItem = (Comparable) anotherNode.item(); if (thisItem.compareTo(anotherItem) == 0) { thisNode = thisNode.next(); anotherNode = anotherNode.next(); continue; } if (thisItem.compareTo(anotherItem) < 0) { thisNode = thisNode.next(); continue; } if (thisItem.compareTo(anotherItem) > 0) { thisNode.insertBefore(anotherItem); anotherNode = anotherNode.next(); } } catch (InvalidNodeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } while (anotherNode.isValidNode()) { try { list.insertBack(anotherNode.item()); anotherNode = anotherNode.next(); } catch (InvalidNodeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
8
public void setNetwork(HaplotypeNetwork hapNet) { this.hapNet = hapNet; maxCardinality = 0; maxDist = 0; //Go through all haplotypes and create haplotypeElements for each one ArrayList<NetworkNode> haps = hapNet.getAllNodes(); for(NetworkNode node : haps) { Haplotype hap = (Haplotype)node; if (hap.getCardinality()>maxCardinality) maxCardinality = hap.getCardinality(); HaplotypeElement hapEl = new HaplotypeElement(this, hap); hapEl.setScale(1.0, 1.0, null); //We need some sort of values for xFactor and yFactor to calculate node positions, since they depend on marker size super.addElement(hapEl); hapElements.add(hapEl); hapEl.setCanConfigure(true); } //Go through all possible pairs of haplotypes and, if any two are connected, create a new //edge element that draws the connection for(int i=0; i<hapElements.size(); i++) { for(int j=i+1; j<hapElements.size(); j++) { if (areConnected(hapElements.get(i), hapElements.get(j))) { double dist = hapNet.getEdgeForPair(hapElements.get(i).getHap(), hapElements.get(j).getHap()).getWeight(); HapEdgeElement edgeEl = new HapEdgeElement(this, hapElements.get(i), hapElements.get(j), (int)dist ); if (maxDist < dist) { maxDist = dist; } edgeElements.add(edgeEl); edgeEl.setZPosition(-5); //paint these underneath super.addElement(edgeEl); } } } //We need to make an educated guess regarding the appropriate scaling for marker sizes // vs. edge lengths. The following value multiplies all edge lengths during node //layout, so it makes things leggier and nodes smaller. //If edge lengths and haplotype cardinalities are comparable, then this number should be about //one. If cardinalities are big and edge lengths short (low theta-scenario), then this number should //be about ten defaultEdgeLengthPerRadius = 2*maxCardinality / maxDist; //This should be small if edge lengths are very long adjustedEdgeLengthPerRadius = defaultEdgeLengthPerRadius * edgeLengthMultiplier; arranger.setEdgeLengthPerRadius(adjustedEdgeLengthPerRadius); for(HaplotypeElement hapEl : hapElements) { hapEl.setRadius( Math.sqrt((double)hapEl.getHap().getCardinality())); hapEl.setBaseRadius( Math.sqrt((double)hapEl.getHap().getCardinality())); } //The NodeArranger requires that nodes are in a list of type Node2D... List<Node2D> nodes = new ArrayList<Node2D>(hapElements.size()); nodes.addAll(hapElements); nodeNetwork = new NodeCollection2D(nodes); setMarkerColor(initMarkerColor); //setMarkerSizeFactor(initMarkerSize); //This calls arrange and rescale(), so we don't need to do it again recentered = false; }
7
public void onloadBrowserHandler(JavascriptContext ctx) { String inpUrl = findUrlField().getText(); this.ctx = ctx; // added download button Button dload = new Button("Download"); dload.setName("Download"); dload.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { dloadBtnAction(evt); } }); // added remove button Button remove = new Button("Remove"); remove.setName("Remove"); remove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { removeBtnAction(evt); } }); // reset the container findDLbuttonContainer().removeComponent(remove); findDLbuttonContainer().removeComponent(dload); if(inpUrl.indexOf("mangareader") != -1) { site = new MangaReader(); if((site.isMangaPage(ctx) || site.isChapterPage(ctx)) && !findDLbuttonContainer().contains(dload) && !site.isMangaAdded(ctx)) findDLbuttonContainer().addComponent(dload); else if(site.isMangaPage(ctx) && !findDLbuttonContainer().contains(remove)) findDLbuttonContainer().addComponent(remove); } findDLbuttonContainer().revalidate(); }
7
public boolean equals(Object obj) { if (!(obj instanceof Point)) return false; Point point = (Point) obj; if (this.getX() == point.getX()) if (this.getY() == point.getY()) if (this.getColor() == point.getColor()) if (this.getDotLineSize() == point.getDotLineSize()) if (this.getDotLineForme().equals(point.getDotLineForme())) return true; return false; }
6
public int update(MouseEvent event) { int mask = (event.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK); boolean buttonDown = mask == MouseEvent.BUTTON1_DOWN_MASK; if (_pressed && !buttonDown) { _pressed = false; return _id; } if (event.getX() >= _rect.x && event.getX() <= _rect.x + _rect.width && event.getY() >= _rect.y && event.getY() <= _rect.y + _rect.height) _hover = true; else _hover = false; if (_hover && buttonDown) _pressed = true; else _pressed = false; return 0; }
8
private void initOldTables() { oldTables = new ReferenceTable[reference.getFileCount()]; for (int i = 0; i < oldTables.length; i++) { ByteBuffer data = reference.get(i); if (data != null) { oldTables[i] = new ReferenceTable(i, data, null); } } }
2
public byte[] getAuthenticatorClient() { return authenticatorClient; }
0
public String properCase(String value) { if (value == null) { return ""; } if (value.isEmpty()) { return ""; } String[] delimiterlist = {" ", "-", "_", "'", "."}; boolean first = true; boolean afterdelimiter = false; String destination = ""; try { // Replace illegal characters value = value.replaceAll(" & ", " en "); value = value.replaceAll("& ", "en "); value = value.replaceAll(" &", " en"); value = value.replaceAll("&", " en "); value = value.replaceAll(" / ", " of "); value = value.replaceAll("/ ", "of "); value = value.replaceAll(" /", " of"); value = value.replaceAll("/", " of "); value = value.replaceAll("\\\\", ""); value = value.replaceAll("<", ""); value = value.replaceAll(">", ""); value = value.replaceAll("\\*", ""); char[] sourcevalue = new char[value.length()]; value = value.toLowerCase(); value.getChars(0, value.length(), sourcevalue, 0); for (char c : sourcevalue) { // Begin with a capital if (first) { destination = destination.concat(String.valueOf(c).toUpperCase()); first = false; } else { // Capital after delimiter if (afterdelimiter) { destination = destination.concat(String.valueOf(c).toUpperCase()); } else { destination = destination.concat(String.valueOf(c).toLowerCase()); } } // Check for delimiter, next character will be in uppercase afterdelimiter = false; for (String delimiter : delimiterlist) { if (String.valueOf(c).equals(delimiter)) { afterdelimiter = true; } } } return destination.trim(); } catch (Exception e) { Logger.getLogger(Address.class.getName()).log(Level.SEVERE, null, e); return ""; } }
8
@Override public Object getValueAt(int rowIndex, int columnIndex) { SimpleDateFormat format = new SimpleDateFormat("HH:mm"); switch(columnIndex) { case 0: return trains.get(rowIndex).getNumber(); case 1: return trains.get(rowIndex).getFromStation(); case 2: return trains.get(rowIndex).getToStation(); case 3: if (trains.get(rowIndex).getDepartureTime() == null) return ""; else return format.format(trains.get(rowIndex).getDepartureTime()); case 4: if (trains.get(rowIndex).getArrivalTime() == null) return ""; else return format.format(trains.get(rowIndex).getArrivalTime()); case 5: return trains.get(rowIndex).getTicketsAmount(); default: return null; } }
8
@Override public void input() { if (Input.isLocked()) { if (Input.getKeyDown(Input.KEY_ESCAPE)) Input.setLocked(false); yaw(-Input.getMouseDX() * sensitivity); pitch(Input.getMouseDY() * sensitivity); } else { if (Input.getMouseDown(Input.MOUSE_LEFT)) { Input.setLocked(true); } } if (Input.getKey(Input.KEY_W)) this.move(LocalDirection.FORWARD, 0.5f); if (Input.getKey(Input.KEY_S)) this.move(LocalDirection.BACKWARD, 0.5f); if (Input.getKey(Input.KEY_A)) this.move(LocalDirection.LEFT, 0.5f); if (Input.getKey(Input.KEY_D)) this.move(LocalDirection.RIGHT, 0.5f); if (Input.getKey(Input.KEY_SPACE)) this.move(LocalDirection.UP, 0.5f); if (Input.getKey(Input.KEY_LSHIFT)) this.move(LocalDirection.DOWN, 0.5f); }
9
public void acquirePackets(final List<Packet> buffer, final int count) { //Method to hold the received packets in an arrayList of packets //ArrayList of packets called List final PacketReceiver receiver = new PacketReceiver() { //Declaration of a new packetReciever called receiver @Override public void receivePacket(Packet packet) { //Method to process the packet System.out.println("received packet.."); //Prints a line to confirm packet was received synchronized (buffer) { buffer.add(packet); //Adds the packet to the ArrayList } packetsRecieved++; if (done || packetsRecieved == count) captor.breakLoop(); } }; //End of InnerClass //captor.loopPacket(count, receiver); Runnable runnable = new Runnable(){ @Override public void run() { //AG_Captor test = new AG_Captor(); //Temporary calling object //test.openDevice(0); //opens the device try { Thread.sleep(4000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } captor.loopPacket(count, receiver); //Loop for packets until closed } }; Thread snifferThread = new Thread(runnable); snifferThread.setName("Sniffer"); snifferThread.start(); System.out.println(snifferThread.getState()); }
3
public Profile getProfile(String id) { System.out.println("MineshafterProfileClient.getProfile(" + id + ")"); URL u; try { u = new URL(API_URL + "?uuid=" + id); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); InputStream in = conn.getInputStream(); String profileJSON = Streams.toString(in); Streams.close(in); System.out.println("MS.getProfile: " + profileJSON); if (profileJSON == null || profileJSON.length() == 0) { return null; } JsonObject pj = JsonObject.readFrom(profileJSON); // TODO: md5 the username/email // server will return a profile for the email if there is one // then it will Profile p = new Profile(id); p.setName(pj.get("username").asString()); JsonValue skinVal = pj.get("skin"); JsonValue capeVal = pj.get("cape"); String url; if (skinVal != null && !skinVal.isNull()) { url = textureHandler.addSkin(id, skinVal.asString()); p.setSkin(url); } if (capeVal != null && !capeVal.isNull()) { url = textureHandler.addCape(id, capeVal.asString()); p.setCape(url); } return p; } catch (IOException e) { e.printStackTrace(); } return null; }
7
@Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; }
1
private static void updateViewTable(final String itemContent) { /** * itemContent is the format: * PathToFile:::FunctionName:::Type+LineNo */ System.out.println("Adding from tableResult: " + itemContent); final String[] itemColums = itemContent.split(":::"); Display display = Display.getCurrent(); // may be null if outside the UI thread if (display == null) display = Display.getDefault(); display.asyncExec(new Runnable() { @Override public void run() { synchronized (this) { final String itemId = itemColums[0]; String itemType = itemColums[1]; String itemExpression = itemColums[2]; if (Integer.parseInt(itemType) == 0) { // Error Detail String itemFuncName = itemColums[3]; String itemPath = itemColums[4]; String itemLine = itemColums[5]; String itemErrorType = ""; // Check if the line has an error type if (itemColums.length == 7) { itemErrorType = itemColums[6]; } if (AutofloxView.consoleTableMap.containsKey(itemId)) { TreeItem errorDetailItem = new TreeItem( AutofloxView.consoleTableMap.get(itemId), SWT.NONE); errorDetailItem.setText(new String[] { itemExpression.trim(), itemPath, "line " + itemLine, itemErrorType }); // Add click to line func AutofloxView.PanelTree.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { TreeItem[] selection = AutofloxView.PanelTree .getSelection(); if (selection.length > 0) { String lineNoText = selection[0] .getText(2); lineNoText = lineNoText .replace("line ", ""); if (lineNoText.trim() != "") { int lineNo = Integer .parseInt(lineNoText .trim()); String filePath = selection[0] .getText(1); AutofloxView .openFileInEditor(filePath); try { AutofloxView .goToLine(lineNo); } catch (BadLocationException e1) { e1.printStackTrace(); } } }else{ System.err.println("Nothing is selected."); } } }); } } else { // Error Entry if (!AutofloxView.consoleTableMap.containsKey(itemId)) { // Create the new error entry TreeItem newErrorTreeItem = new TreeItem( AutofloxView.PanelTree, SWT.NONE); AutofloxView.consoleTableMap.put(itemId, newErrorTreeItem); // Add the error entry messages to console newErrorTreeItem.setText(new String[] { "Code-terminating DOM-related Error: " + itemExpression, "", "", "" }); } } } } }); }
8
public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, int attackDir) { if (player.health < player.maxHealth && player.payStamina(staminaCost)) { player.heal(heal); return true; } return false; }
2
public static Stella_Object accessContextSlotValue(Context self, Symbol slotname, Stella_Object value, boolean setvalueP) { if (slotname == Stella.SYM_STELLA_CHILD_CONTEXTS) { if (setvalueP) { self.childContexts = ((List)(value)); } else { value = self.childContexts; } } else if (slotname == Stella.SYM_STELLA_BASE_MODULE) { if (setvalueP) { self.baseModule = ((Module)(value)); } else { value = self.baseModule; } } else if (slotname == Stella.SYM_STELLA_ALL_SUPER_CONTEXTS) { if (setvalueP) { self.allSuperContexts = ((Cons)(value)); } else { value = self.allSuperContexts; } } else if (slotname == Stella.SYM_STELLA_CONTEXT_NUMBER) { if (setvalueP) { self.contextNumber = ((IntegerWrapper)(value)).wrapperValue; } else { value = IntegerWrapper.wrapInteger(self.contextNumber); } } else { if (setvalueP) { KeyValueList.setDynamicSlotValue(self.dynamicSlots, slotname, value, null); } else { value = self.dynamicSlots.lookup(slotname); } } return (value); }
9
public boolean isValid() { //check for valid number of states if (brainInstructions.size() > 10000) { return false; } //check that instructions use correct syntax int i = 0; int j = 0; boolean valid = true; boolean match = false; //iterate through each instruction and check for a match in //the list of valid instruction formats while (valid && i < brainInstructions.size()) { match = false; while (!match && j < syntax.size()) { match = brainInstructions.get(i).toLowerCase().matches(syntax.get(j).toLowerCase()); j++; } valid = match; j = 0; i++; } return valid; }
5
private void checkVehicletool() { List<Integer> list = new ArrayList<Integer>(); for (Route r : Solution.getRoutes()) { list.clear(); int vehicle = 0; boolean b=false; if (r.isHasType()) { vehicle = r.getType(); } List<Integer> vehicleTool = getToolVehicle(Instance.getFleet() .get(vehicle).getAttribute("tool")); List<Integer> requestTool = new ArrayList<Integer>(); for (Request n : r.getRequests()) { int id = n.getId(); List<VrpAtt> listAtt = Instance.getRequests().get(id) .getAttribute("tool"); for (VrpAtt vrpAtt : listAtt) { requestTool.add(((SkillAndTool) vrpAtt).getId()); } } for (Integer s : requestTool){ if (!vehicleTool.contains(s) && !list.contains(s)){ list.add(s); b=true; } } if(b){ String sToolMissing =""+list.get(0); for(int i=1;i<list.size();i++) sToolMissing=sToolMissing.concat("-"+list.get(i)); cEval.addMessage("VehicleTool|The following tools are missing : "+sToolMissing+" on route "+r.getId()); } } }
9
protected void processWindowEvent(WindowEvent e) { if (e.getID() == WindowEvent.WINDOW_CLOSING) { if( rosterDB.isDataChanged () || tripDB.isDataChanged() || riverDB.isDataChanged() ) { if ( JOptionPane.showConfirmDialog(null, "Sollen die Daten jetzt abgespeichert werden?", "Daten sind noch nicht abgespeichert", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION ) { saveToFile(setupData.getDataFileName()); } saveBackupFile(setupData.getDataFileName()); } try { setupData.write(SETUP_FILE_NAME); System.out.println ("Setup information written to " + SETUP_FILE_NAME + "."); } catch (Exception exception) { System.out.println ("Could not save setup information to file " + SETUP_FILE_NAME + "."); exception.printStackTrace(); } dispose(); System.exit(0); } super.processWindowEvent(e); }
6
final public void And_operator() throws ParseException { /*@bgen(jjtree) And_operator */ SimpleNode jjtn000 = new SimpleNode(JJTAND_OPERATOR); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1)); try { if (jj_2_73(3)) { jj_consume_token(AND); } else if (jj_2_74(3)) { jj_consume_token(ANDAND); } else { jj_consume_token(-1); throw new ParseException(); } } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } }
3
public static void sortStudentsPromotion() { if (FileReadService.sList.isEmpty()) { System.out.println("There is no Student !"); } else if (FileReadService.pList.isEmpty()) { System.out.println("There is no Promotion !"); } else { System.out .println("Do you want to sort in an Ascending Order (0) or Descending Order (1) ?"); int mode = -1; while (mode < 0 || mode > 1) { Scanner scMode = new Scanner(System.in); mode = scMode.nextInt(); } System.out.println("Which promotion do you want ?"); displayPromotionList(); Scanner scIndexP = new Scanner(System.in); Promotion p = null; while (p == null) { int iP = scIndexP.nextInt(); p = choosePromotionList(iP); } if (mode == 0) { p.sort(0); System.out.println(p); } else { p.sort(1); System.out.println(p); } } }
6
public Graph() { edges = new DynamicArray(); vertices = new DynamicArray(); adjacencyList = new AdjacencyList(); directed = false; hasNegativeWeights = false; }
0
@Override public Action choose() { switch (this.getCurrent()) { case 0: return Action.MOVE; case 1: return Action.ATTACK; case 2: return Action.CAST; case 3: default: return Action.CANCEL; } }
4
public boolean equals(Puzzle p) { boolean equals = true; for(int i=0; i<9; i++) { for(int j=0; j<9; j++) { equals = equals && grid[i][j].equals(p.getGrid()[i][j]); } } return equals; }
3
public static void main(String[] args) throws SlickException { new AppGameContainer(new StateFreeGame("CameraTest"){ private Camera cam; private Vector2i loc; @Override public void renderProcess(GameContainer arg0, Graphics arg1) { cam.draw(arg0,arg1); arg1.setColor(Color.gray); arg1.fillRect(10, 500, 100, 100); arg1.setColor(Color.red); arg1.fillRect(10, 10, 100, 100); arg1.setColor(Color.green); arg1.fillRect(700,40,100,100); arg1.setColor(Color.white); arg1.fillRect(700, 500, 100, 100); arg1.setColor(Color.magenta); arg1.fillRect(400, 400, 100, 100); arg1.setColor(Color.blue); arg1.fillOval(loc.getX(), loc.getY(), 10, 10); } @Override public void initProcess(GameContainer arg0) { cam = new Camera(CameraSettings.DEFAULT); cam.registerCameraInput(arg0.getInput()); loc = new Vector2i(400,300); } @Override public void updateProcess(GameContainer arg0, int arg1) { //uncomment to make the camera follow loc. //cam.track(loc); if (arg0.getInput().isKeyDown(Input.KEY_ESCAPE)) arg0.exit(); //note that y axis seems to be inverted. if (arg0.getInput().isKeyDown(Input.KEY_DOWN)) loc.add(new Vector2i(0,1)); if (arg0.getInput().isKeyDown(Input.KEY_UP)) loc.add(new Vector2i(0,-1)); if (arg0.getInput().isKeyDown(Input.KEY_LEFT)) loc.add(new Vector2i(-1,0)); if (arg0.getInput().isKeyDown(Input.KEY_RIGHT)) loc.add(new Vector2i(1,0)); //panning --comment if you're going to cam.track if (arg0.getInput().isKeyDown(Input.KEY_W)) cam.move(Camera.Direction.UP); if (arg0.getInput().isKeyDown(Input.KEY_A)) cam.move(Camera.Direction.LEFT); if (arg0.getInput().isKeyDown(Input.KEY_S)) cam.move(Camera.Direction.DOWN); if (arg0.getInput().isKeyDown(Input.KEY_D)) cam.move(Camera.Direction.RIGHT); }},800,600,false).start(); }
9
public static void newTurn() { for(int i = 0; i < unitList.size(); i++) //Loops through all units { unitList.get(i).reset(); } }
1
public int searchInsert(int[] A, int target) { int low = 0; int high = A.length - 1; while (low <= high) { if (low == high) { if (A[low] >= target) return low; return low + 1; } int mid = (low + high) >>> 1; int midVal = A[mid]; if (midVal < target) { low = mid + 1; } else if (midVal > target) { high = mid; } else { return mid; } } return -1; }
5
@Override public void setCurrentHp(int hp) { if (hp > this.maxHP) { this.curHP = this.maxHP; } else { this.curHP = hp; } }
1
public static void sendAdminChat( String message, Server server ) { if ( ChatConfig.logChat ) { LoggingManager.log( message ); } ByteArrayOutputStream b = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream( b ); try { out.writeUTF( "SendAdminChat" ); out.writeUTF( message ); } catch ( IOException e ) { e.printStackTrace(); } for ( ServerInfo s : BungeeSuite.proxy.getServers().values() ) { if ( !s.getName().equals( server.getInfo().getName() ) && s.getPlayers().size() > 0 ) { sendPluginMessageTaskChat( s, b ); } } }
5