method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
c79a3983-c032-46d5-85c7-c8cede790244
0
public void put(Object o) { queueList.addLast(o); }
35e1910a-3ee5-4ef1-9ffa-1f58d46984a6
6
public final Section build() { final Section SECTION = new Section(); for (String key : properties.keySet()) { if ("start".equals(key)) { SECTION.setStart(((DoubleProperty) properties.get(key)).get()); } else if("stop".equals(key)) { SECTION.setStop(((DoubleProperty) properties.get(key)).get()); } else if("text".equals(key)) { SECTION.setText(((StringProperty) properties.get(key)).get()); } else if("icon".equals(key)) { SECTION.setIcon(((ObjectProperty<Image>) properties.get(key)).get()); } else if ("styleClass".equals(key)) { SECTION.setStyleClass(((StringProperty) properties.get(key)).get()); } } return SECTION; }
2e7d76fe-992c-4b2b-8cea-eb7490603d27
7
public void run() { while (active) { int mod = timeElapsed % 7; switch(mod) { case 0: log.info("info level log."); break; case 1: log.debug("debug level log."); break; case 2: log.error("error level log"); break; case 3: log.warn("warn level log"); break; case 5: log.trace("trace level log"); break; } try { Random r = new Random(); int i = r.nextInt(8) + 7; timeElapsed += i; Thread.sleep(i*1000); } catch (Exception e) { log.error("Thread interrupted " + e.getMessage(), e); } } }
5801689a-e5ba-411a-91ed-64b0489f8166
6
public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); int m=scanner.nextInt();//灯的数目 int array[]=new int[m+1]; for(int i=0;i<m+1;i++){ array[i]=0; } for(int i=1;i<m+1;i++){ int flag=i; int flag1=flag; while(flag1 < m+1){ if(array[flag1] == 1) array[flag1] = 0; else { array[flag1]=1; } flag1+=flag; } } int num=0; for(int i=1;i<m+1;i++){ if(array[i] == 1) num++; } System.out.println(num); }
eaf45596-abb6-4ef8-9c09-87997fa59f96
3
public int tsfLookback( int optInTimePeriod ) { if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) ) optInTimePeriod = 14; else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) ) return -1; return optInTimePeriod-1; }
ac0c7986-dbe2-4dc7-9163-b23b2405cfb0
3
public void checkCbolOriginalDirV2() { Path dir = Paths.get(CBOL_HOME); // //http://docs.oracle.com/javase/tutorial/essential/io/dirs.html String str; String str2; String str3; try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path file : stream) { str = file.getFileName().toString(); if (str.startsWith("unv_")) { str2 = str.substring(4); str3 = str2.replace(".html", ""); System.out.println(str3); } } } catch (IOException | DirectoryIteratorException x) { // IOException can never be thrown by the iteration. // In this snippet, it can only be thrown by newDirectoryStream. System.err.println(x); } }
1f5cb140-a08b-4639-916e-1d92f8576cc6
4
public boolean removeHotkeyBinding(String key) { if (!this.fileLoaded) { return false; } try { XMLNode hotkeysNode = this.rootNode.getChildNodesByType("hotkeys")[0]; XMLNode[] hotkeys = hotkeysNode.getChildNodesByType("hotkey"); for (XMLNode node : hotkeys) { if (node.getChildNodesByType("name")[0].getValue().equalsIgnoreCase(key)) { hotkeysNode.removeChild(node); this._getHotkeys(); return true; } } return false; } catch (Exception ex) { return false; } }
72051a71-2a25-4037-9242-0df24fb2a6c1
6
public Report getReportById(int report_id) { Report r = new Report(); ResultSet rs = null; try { statement = connection.createStatement(); String sql = "select * from reports where id = " + report_id; rs = statement.executeQuery(sql); if(rs.next()) { r.setCabin_id(rs.getInt("cabin_id")); r.setWood(rs.getInt("wood")); r.setDamage(rs.getString("damage")); r.setMissing(rs.getString("missing")); r.setReport_date(rs.getDate("report_date")); r.setEmail(rs.getString("email")); r.setOther(rs.getString("other")); } } catch(SQLException se) { se.printStackTrace(); } finally { try{ if(rs != null) rs.close(); } catch(Exception e) {}; try{ if(statement != null) statement.close(); } catch(Exception e) {}; } return r; }
27ff07a5-b7cf-4bca-841e-4d1ac82b63f7
7
private GsSong[] readFile(File f) { if(!f.exists()) return null; try { int size=0; GsSong[] res=new GsSong[1]; res[0]=null; BufferedReader in=new BufferedReader(new FileReader(f)); String line; while((line=in.readLine())!=null) { if(line.length()==0) // skip empty lines continue; if(line.charAt(0)=='#') // skip comment lines continue; String[] data=line.split(","); if(data.length<4) continue; GsSong song=new GsSong(data,playlist.getParent()); if(size!=0) { GsSong[] newArr=new GsSong[size+1]; System.arraycopy(res, 0, newArr, 0, size); res=newArr; } res[size]=song; size++; } return res; } catch (Exception e) { PMS.debug("error reading playlist "+e); return null; } }
74619510-e0aa-4088-bb50-6ed1c8866dcb
7
private void downloadSW(String url) { String fileSizeString = ""; long fileSize = 1; _percent = 0; try { _builder = new ProcessBuilder(_downloadcmd, "-c", "--progress=bar", url); _builder = _builder.redirectErrorStream(true); _process = _builder.start(); InputStream stdout = _process.getInputStream(); BufferedReader stdoutBuffered = new BufferedReader( new InputStreamReader(stdout)); // This block is in charge of getting progress through the download String line = null; Boolean calculatePercentage = false; while ((line = stdoutBuffered.readLine()) != null) { if (line.startsWith("Length:")) { int k = 8; while (line.charAt(k) != ' ') { k++; } fileSizeString = line.substring(8, k); fileSize = Integer.parseInt(fileSizeString); calculatePercentage = true; } if (calculatePercentage == true) { File urlFile = new File(url); File file = new File(urlFile.getName()); _percent = (int) ((file.length() * 100) / fileSize); } } if (calculatePercentage == false) { // Fail- safe, if download continues, but is already complete _percent = 100; } _result = _process.waitFor(); _process.destroy(); } catch (IOException | InterruptedException e) { if (e.getMessage() == "Stream closed") { // This is expected behavior from cancel(). } else { e.printStackTrace(); } } }
2f4cd5e7-b1a8-4ef6-90c1-334dc7c1784f
7
public static ReservedWords parseCommand(String command) { if (command.equalsIgnoreCase("add")) return ReservedWords.ADD; if (command.equalsIgnoreCase("create")) return ReservedWords.CREATE; if (command.equalsIgnoreCase("remove")) return ReservedWords.REMOVE; if (command.equalsIgnoreCase("update")) return ReservedWords.UPDATE; if (command.equalsIgnoreCase("delete")) return ReservedWords.DELETE; if (command.equalsIgnoreCase("persist")) return ReservedWords.PERSIST; if (command.equalsIgnoreCase("load")) return ReservedWords.LOAD; return ReservedWords.WRONG; }
9c09c3a8-79b9-47c6-b7d6-bbb880aafe87
1
public float getRZAxisDeadZone() { if (rzaxis == -1) { return 0; } return getDeadZone(rzaxis); }
2a9c5109-1db5-44ab-8404-6f4fa3cb8182
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(ProductosOC.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ProductosOC.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ProductosOC.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ProductosOC.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 ProductosOC().setVisible(true); } }); }
b94ab218-7273-40ca-ace5-ba0ee07d1e82
0
public SaveGraphJPGAction(Environment environment, JMenu menu) { super("Save Graph as JPG", null); this.environment = environment; this.myMenu = menu; }
5cbd0674-6548-4da7-9277-331f7039fb1b
9
@Override public void paintBorder(final Component c, Graphics g, int x, int y, int width, int height) { Color saveColor = g.getColor(); try { final Rectangle r = c.getBounds(); if (options.top > 0) { int colorIndex = startIndex; for (int i = r.x; i < (r.x + r.width); i += options.top) { g.setColor(options.colors[colorIndex]); colorIndex = (colorIndex + 1) % options.colors.length; g.fillRect(i, r.y, options.top, options.top); } } if (options.left > 0) { int colorIndex = startIndex; for (int i = r.y; i < (r.y + r.height); i += options.left) { g.setColor(options.colors[colorIndex]); colorIndex = (colorIndex + 1) % options.colors.length; g.fillRect(r.x, i, options.left, options.left); } } if (options.bottom > 0) { int yPos = r.y + r.height - options.bottom; int colorIndex = startIndex; for (int i = r.x; i < (r.x + r.width); i += options.bottom) { g.setColor(options.colors[colorIndex]); colorIndex = (colorIndex + 1) % options.colors.length; g.fillRect(i, yPos, options.bottom, options.bottom); } } if (options.right > 0) { int xPos = r.x + r.width - options.right; int colorIndex = startIndex; for (int i = r.y; i < (r.y + r.height); i += options.right) { g.setColor(options.colors[colorIndex]); colorIndex = (colorIndex + 1) % options.colors.length; g.fillRect(xPos, i, options.right, options.right); } } if (options.blinkDelay > 0) { startIndex = (startIndex + 1) % options.colors.length; Timer t = new BorderTimer(c, options.top, options.left, options.bottom, options.right, options.blinkDelay); t.setRepeats(false); t.start(); } } finally { g.setColor(saveColor); } }
8f172b17-c0bd-4039-934d-76b33bc26840
9
public void updatePositions(){ dyingParticles.clear(); for(Particle p: aliveParticles){ if( checkCollision( p.getxPosition(), p.getyPosition() ) == true ){ for( int newx = (p.getxPosition() - 2) ; newx <= (p.getxPosition() + 2) ; newx++){ for( int newy = (p.getyPosition() - 2) ; newy <= (p.getyPosition() + 2) ; newy++){ if(newx >= 0 && newx < 640 && newy >= 0 && newy < 480){ matrix[newx][newy] = true; } } } deadParticles.add(p); dyingParticles.add(p); } else { double randomangle = Math.random() * ( 2 * Math.PI ); p.updatePosition(randomangle); } } for(Particle n: dyingParticles){ aliveParticles.remove(n); } }
69de5110-e438-474a-9bbd-f399ccdb0cc6
4
private void runClient() { try { System.out.println("Client: Ready for commands (hit 'enter' for command list)"); BufferedReader bufferedPromptReader = new BufferedReader(new InputStreamReader(System.in)); // Loop taking input until exit while(!exit) { System.out.print(">>> "); parseInput(bufferedPromptReader.readLine()); } // Close session if(socket != null) { socket.close(); System.out.println("Client: Closing client connection and exiting..."); } else { System.out.println("Client: Exiting client..."); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
cc98cce7-b35a-49aa-b67f-3aac10b8b2fb
3
@Override public Cliente getByCpf(Cliente cliente) { Cliente clienteLido = null; try{ conn = ConnectionFactory.getConnection(); String sql = "SELECT nome FROM cliente WHERE cpf LIKE ?"; ps = conn.prepareStatement(sql); ps.setString(1, cliente.getCpf()); rs = ps.executeQuery(); if(rs.next()){ clienteLido = new Cliente(); clienteLido.setNome(rs.getString("nome")); clienteLido.setCpf(rs.getString("cpf")); }else{ close(); throw new RuntimeException("Cliente não encontrado!"); } } catch (SQLException e){ throw new RuntimeException("Erro " + e.getSQLState() + " ao atualizar o objeto: " + e.getLocalizedMessage()); } catch (ClassNotFoundException e){ throw new RuntimeException("Erro ao conectar ao banco: " + e.getMessage()); } finally { close(); return clienteLido; } }
39b782da-f81b-4091-b640-26edcf7768bb
9
private void showIfInfo (StringBuffer buf, Configuration config) { int numIf = config.getNumInterfaces (); byte epStatus [] = new byte [2]; for (int i = 0; i < numIf; i++) { try { Interface intf = config.getInterface (i, 0); // some devices don't expose these when configured if (intf == null) { buf.append ("<em>Can't get interface "); buf.append (i); buf.append ("</em>.<br>\n"); continue; } String temp; int value; buf.append ("<b>Interface "); buf.append (intf.getNumber ()); value = intf.getInterfaceClass (); if (value != 0) { buf.append (" ("); buf.append (intf.getInterfaceClassName ()); buf.append (")"); } value = intf.getAlternateSetting (); if (value != 0) { buf.append (", alt "); buf.append (value); } buf.append ("</b><br>\n"); temp = intf.getInterface (0); if (temp != null) { buf.append ("Description: <em>"); buf.append (temp); buf.append ("</em><br>\n"); } /* buf.append ("class "); buf.append (intf.getInterfaceClass ()); buf.append (", subclass "); buf.append (intf.getInterfaceSubclass ()); buf.append (", protocol "); buf.append (intf.getInterfaceProtocol ()); buf.append ("<br>\n"); */ value = intf.getNumEndpoints (); for (int j = 0; j < value; j++) { Endpoint ep = intf.getEndpoint (j); buf.append ("<em>Endpoint "); buf.append (ep.getEndpointAddress ()); buf.append (":</em> "); temp = ep.getType (); buf.append (temp); if (ep.isInput ()) buf.append (" IN "); else buf.append (" OUT "); if ("interrupt".equals (temp)) { buf.append (" (poll "); buf.append (ep.getInterval ()); buf.append ("ms.) "); } buf.append ("maxpacket "); buf.append (ep.getMaxPacketSize ()); // NOTE: can't try for interface status (zeroes) // or endpoint status (HALT) unless we claimed the // interface, which we don't want at this time. buf.append ("<br>\n"); } buf.append ("<br>\n"); } catch (IOException e) { buf.append ("<br>Interface data unavailable. "); buf.append ("Index = "); buf.append (i); buf.append ("<br>\nDiagnostic: <em>"); buf.append (e.getMessage ()); buf.append ("</em>\n"); } } }
b8802741-7f82-4b31-9514-fb15833906f3
8
public static void main(String[] args) throws InterruptedException { int loadedLevel = 0; startMenu(); while (true) { if (loadedLevel != level && level > 0) { loadedLevel = level; if (level > 0 && !LevelSet.levelExists(level)) { System.out.println("Level does not exist: " + Integer.toString(level)); JOptionPane.showMessageDialog(game,"YOU WIN!!!"); if (JOptionPane.showConfirmDialog(game, "Save High Score?") == JOptionPane.YES_OPTION) { HighScores.addRecord(game.player.getName(),game.player.getScore()); } System.exit(0); } if (level > 1) { blank = new JFrame(); blank.setUndecorated(true); blank.setSize(frame.getSize()); JPanel blankPanel = new JPanel(); blankPanel.setBackground(Color.BLACK); blank.add(blankPanel); blank.setLocationRelativeTo(null); blank.setVisible(true); Thread.sleep(400); frame.setVisible(false); } LoadingBar loadBar = setUpLoadingScreen(); createUI(loadBar); loadBar.increment("Getting player name"); game.getUserDetails(loadBar); loadBar.increment("Beginning game init"); game.initialiseGame(loadBar, level); loadFrame.setVisible(false); frame.setVisible(true); if (level > 1) { Thread.sleep(400); blank.setVisible(false); } Game.runAllGameLoops(game); } } }
38bdcb67-f441-4bb5-8a72-131152ba271b
7
private void okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okActionPerformed ClienteController control = new ClienteController(mode); try { if (!textCodigo.getText().isEmpty()) { int codigo = Integer.parseInt(textCodigo.getText()); if (control.existClienteById(codigo)) { switch (mode) { case 'U': fsoporte.textUsuario.setText(textCodigo.getText()); break; case 'A': fsoporte.textAnalista.setText(textCodigo.getText()); break; } this.dispose(); } } else { switch (mode) { case 'U': JOptionPane.showMessageDialog(this, "NO EXISTE EL USUARIO", "A T E N C I O N", JOptionPane.INFORMATION_MESSAGE); break; case 'A': JOptionPane.showMessageDialog(this, "NO EXISTE EL ANALISTA", "A T E N C I O N", JOptionPane.INFORMATION_MESSAGE); break; } } } catch (Exception e) { e.printStackTrace(); } }//GEN-LAST:event_okActionPerformed
c737ea59-0b8e-420e-b167-aa94ff270f34
6
void updateColumnWidth (CTableColumn column, GC gc) { int columnIndex = column.getIndex (); gc.setFont (getFont (columnIndex, false)); String oldDisplayText = displayTexts [columnIndex]; computeDisplayText (columnIndex, gc); /* the cell must be damaged if there is custom drawing being done or if the alignment is not LEFT */ if (isInViewport ()) { boolean columnIsLeft = (column.getStyle () & SWT.LEFT) != 0; if (!columnIsLeft || parent.isListening (SWT.EraseItem) || parent.isListening (SWT.PaintItem)) { Rectangle cellBounds = getCellBounds (columnIndex); parent.redraw (cellBounds.x, cellBounds.y, cellBounds.width, cellBounds.height, false); return; } /* if the display text has changed then the cell text must be damaged in order to repaint */ if (oldDisplayText == null || !oldDisplayText.equals (displayTexts [columnIndex])) { Rectangle cellBounds = getCellBounds (columnIndex); int textX = getTextX (columnIndex); parent.redraw (textX, cellBounds.y, cellBounds.x + cellBounds.width - textX, cellBounds.height, false); } } }
02ce25fb-8d93-4a9e-ada5-3c8af873e221
3
private int[] totals(int[][] values) { int[] totals = {0,0,0,0,0,0,0}; for (int i=0; i<7; i++) { for (int in=0; i<4; i++) { if (in%2 == 0) { totals[i] = totals[i]+values[i][in]; } else { totals[i] = totals[i]-values[i][in]; } } } return totals; }
5e1d0829-2081-46a2-a447-8e68252e8ade
2
public void fillRandomly() { for (int i = 0; i < rows; i++) for (int j = 0; j < columns; j++) { int r = (int)(256*Math.random()); int g = (int)(256*Math.random()); int b = (int)(256*Math.random()); grid[i][j] = new Color(r,g,b); } forceRedraw(); }
8b343fce-141b-43d3-9d05-161fb8d8b18f
9
public void histogram(Graphics g) { g.drawLine(rightOffset, 0, rightOffset, getHeight() - bottomOffset); g.drawLine(rightOffset, getHeight() - bottomOffset, getWidth()-rightOffset, getHeight() - bottomOffset); ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); ((Graphics2D) g).setFont(new Font("Sans serif", 0, 9)); if (this.rectangles == null) { // There's no data if(DEBUG){ System.out.println("No data to plot histogram"); } return; } double valuesGap = scaleTop/(double)NUM_LABELS; double pixelGap = (scaleTop/(double)NUM_LABELS)*((getHeight()-bottomOffset)/scaleTop); for (int i = 0; i<NUM_LABELS+1; i++){ g.drawLine(leftOffset, (int)Math.round(getHeight()-bottomOffset-(i*pixelGap)), leftOffset-leftOffset/3, (int)Math.round(getHeight()-bottomOffset-(i*pixelGap))); g.drawString(""+Math.round(valuesGap*i), leftOffset-20, (int)Math.round(getHeight()-bottomOffset-(i*pixelGap)+5)); } // Plots a GREEN bar for all timeslots within preferred range // Plots a YELLOW bar for all timeslots outside preferred range // Plots a RED bar for all timeslots below min/above max for (Rectangle r : rectangles.keySet()) { Timeslot s = rectangles.get(r); // Set color according to things if (s.getAssigned().size() < s.getMinStudents() || s.getAssigned().size() > s.getMaxStudents()) g.setColor(Color.RED); else if (s.getAssigned().size() < s.getPreferredMin() || s.getAssigned().size() > s.getPreferredMax()) g.setColor(Color.YELLOW); else g.setColor(Color.GREEN); // If neither previous, should be within preferred range g.fillRect(r.x, r.y, r.width, r.height); g.setColor(Color.black); g.drawRect(r.x, r.y, r.width, r.height); ((Graphics2D) g).rotate(Math.PI / 6); Point textPoint = new Point(r.x + r.width / 2, r.y + r.height + 10); Point newPos = new Point(); try { ((Graphics2D) g).getTransform().createInverse() .deltaTransform(textPoint, newPos); ((Graphics2D) g).drawString(s.toString(), newPos.x, newPos.y); ((Graphics2D) g).rotate(-Math.PI / 6); } catch (NoninvertibleTransformException e) { e.printStackTrace(); } } }
cd23cef4-42fa-4b16-a545-4ebd6850568e
4
public Matrix plus(Matrix B) { Matrix A = this; if (B.M != A.M || B.N != A.N) throw new RuntimeException("Illegal matrix dimensions."); Matrix C = new Matrix(M, N); for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) C.data[i][j] = A.data[i][j] + B.data[i][j]; return C; }
0f596f1d-a18e-4929-adbe-e5a235899a04
2
@Override public void generate() throws GeneratorException { Options options = Options.getTo(ConverterTypeTo.PDF).via(ConverterTypeVia.XWPF); try { report.generate(options, report.getOutput()+".pdf"); } catch (XDocConverterException e) { throw new GeneratorException(GeneratorError.PDF_CONVERTION_ERROR,"Error while converting the PDF:"+e.getMessage()); } catch (XDocReportException e) { throw new GeneratorException(GeneratorError.PDF_GENERATION_ERROR,"Error while generating the PDF:"+e.getMessage()); } }
abef3c4a-9f2e-45d6-8fad-d8b23c71e860
5
public static void simpleKMeans(Instances data, Instances originalData) throws Exception { // create a KMeans clusterer SimpleKMeans skm = new SimpleKMeans(); skm.setNumClusters(3); skm.buildClusterer(data); // evaluate the KMeans clusterer ClusterEvaluation skmEvaluation = new ClusterEvaluation(); skmEvaluation.setClusterer(skm); skmEvaluation.evaluateClusterer(data); System.out.println(skmEvaluation.clusterResultsToString()); // to calculate the RAND index, need to know // a: number of pairs with same class label and in same cluster // b: the number of pairs with the same class label, but in different clusters // c: the number of pairs in the same cluster, but with different class labels // d: the number of pairs with a different class label, in different clusters int a = 0; int b = 0; int c = 0; int d = 0; // get class data as an array of doubles double[] classes = originalData.attributeToDoubleArray(0); // get cluster data as an array of doubles double[] clusters = skmEvaluation.getClusterAssignments(); // Compare classes and clusters for(int i = 0; i < classes.length; i++) { for(int j = i + 1; j < classes.length; j++) { if(classes[i] == classes[j]) { if(clusters[i] == clusters[j]) a++; else b++; } else { if(clusters[i] == clusters[j]) c++; else d++; } } } System.out.println("a: " + a + " b: " + b + " c: " + c + " d: " + d); double rand = (double) (a + d) / (double) (a + b + c + d); System.out.println("Rand: " + rand); }
50721052-8c65-4aa7-bdc1-64e39af97e95
9
private void resizeScreenIfNeeded() { TerminalSize newSize; synchronized(resizeQueue) { if(resizeQueue.isEmpty()) return; newSize = resizeQueue.getLast(); resizeQueue.clear(); } int height = newSize.getRows(); int width = newSize.getColumns(); ScreenCharacter [][]newBackBuffer = new ScreenCharacter[height][width]; ScreenCharacter [][]newVisibleScreen = new ScreenCharacter[height][width]; for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { if(backbuffer.length > 0 && x < backbuffer[0].length && y < backbuffer.length) newBackBuffer[y][x] = backbuffer[y][x]; else newBackBuffer[y][x] = new ScreenCharacter(paddingCharacter); if(visibleScreen.length > 0 && x < visibleScreen[0].length && y < visibleScreen.length) newVisibleScreen[y][x] = visibleScreen[y][x]; else newVisibleScreen[y][x] = new ScreenCharacter(paddingCharacter); } } backbuffer = newBackBuffer; visibleScreen = newVisibleScreen; wholeScreenInvalid = true; terminalSize = new TerminalSize(newSize); }
79808faa-5b23-4fce-8889-dcb6759833ad
7
private byte[] crypt_raw(byte password[], byte salt[], int log_rounds) { int rounds, i, j; int cdata[] = (int[])bf_crypt_ciphertext.clone(); int clen = cdata.length; byte ret[]; if (log_rounds < 4 || log_rounds > 31) throw new IllegalArgumentException ("Bad number of rounds"); rounds = 1 << log_rounds; if (salt.length != BCRYPT_SALT_LEN) throw new IllegalArgumentException ("Bad salt length"); init_key(); ekskey(salt, password); for (i = 0; i < rounds; i++) { key(password); key(salt); } for (i = 0; i < 64; i++) { for (j = 0; j < (clen >> 1); j++) encipher(cdata, j << 1); } ret = new byte[clen * 4]; for (i = 0, j = 0; i < clen; i++) { ret[j++] = (byte)((cdata[i] >> 24) & 0xff); ret[j++] = (byte)((cdata[i] >> 16) & 0xff); ret[j++] = (byte)((cdata[i] >> 8) & 0xff); ret[j++] = (byte)(cdata[i] & 0xff); } return ret; }
b217027f-ddf0-4091-8bd4-c745ed669662
0
public RandomDateGenerator(String tableName, String columnName, Date start, Date end) { super(tableName, columnName); this.start = start; this.end = end; sdf = new SimpleDateFormat("yyyy-MM-dd"); }
6fe2cd01-0dd0-49b8-bbbe-f42ea9fb54cb
7
private void xmlBuildRootNode(org.w3c.dom.Node node) throws SAXNotRecognizedException, SAXException { if(node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { Element elt = (Element) node; String name = elt.getNodeName(); if(name.equals("DockingPanel")) { // only one child at most NodeList children = elt.getChildNodes(); for(int i = 0, len = children.getLength(); i < len; i++) { xmlBuildDockingPanelNode(elt.getChildNodes().item(i)); } } else if(name.equals("Border")) { int zone = Integer.parseInt(elt.getAttribute("zone")); NodeList children = elt.getElementsByTagName("Dockable"); for(int i = 0, len = children.getLength(); i < len; i++) { xmlBuildAutoHideNode(zone, (Element) children.item(i)); } } else if(name.equals("Floating")) { int x = Integer.parseInt(elt.getAttribute("x")); int y = Integer.parseInt(elt.getAttribute("y")); int width = Integer.parseInt(elt.getAttribute("width")); int height = Integer.parseInt(elt.getAttribute("height")); NodeList children = elt.getElementsByTagName("Dockable"); xmlBuildFloatingNode(children, new Rectangle(x, y, width, height)); //2005/10/10 /* for (int i = 0, len = children.getLength(); i < len; i++) { xmlBuildFloatingNode((Element)children.item(i), new Rectangle(x, y, width, height)); }*/ } else if(name.equals("TabGroups")) { NodeList children = elt.getElementsByTagName("TabGroup"); xmlBuildTabGroup(children); //2005/10/10 } else { throw new SAXNotRecognizedException(name); } } }
43899d69-3223-4397-8d19-095ea50c06b2
3
@Override void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) { // Replace child if(this._const_ == oldChild) { setConst((TConst) newChild); return; } if(this._var_ == oldChild) { setVar((PVar) newChild); return; } if(this._valor_ == oldChild) { setValor((PValor) newChild); return; } throw new RuntimeException("Not a child."); }
fd73e1e9-3e09-48f0-93a4-4fe1eb6ab900
9
byte[] readCodewords() throws FormatException { FormatInformation formatInfo = readFormatInformation(); Version version = readVersion(); // Get the data mask for the format used in this QR Code. This will exclude // some bits from reading as we wind through the bit matrix. DataMask dataMask = DataMask.forReference((int) formatInfo.getDataMask()); int dimension = bitMatrix.getHeight(); dataMask.unmaskBitMatrix(bitMatrix, dimension); BitMatrix functionPattern = version.buildFunctionPattern(); boolean readingUp = true; byte[] result = new byte[version.getTotalCodewords()]; int resultOffset = 0; int currentByte = 0; int bitsRead = 0; // Read columns in pairs, from right to left for (int j = dimension - 1; j > 0; j -= 2) { if (j == 6) { // Skip whole column with vertical alignment pattern; // saves time and makes the other code proceed more cleanly j--; } // Read alternatingly from bottom to top then top to bottom for (int count = 0; count < dimension; count++) { int i = readingUp ? dimension - 1 - count : count; for (int col = 0; col < 2; col++) { // Ignore bits covered by the function pattern if (!functionPattern.get(j - col, i)) { // Read a bit bitsRead++; currentByte <<= 1; if (bitMatrix.get(j - col, i)) { currentByte |= 1; } // If we've made a whole byte, save it off if (bitsRead == 8) { result[resultOffset++] = (byte) currentByte; bitsRead = 0; currentByte = 0; } } } } readingUp ^= true; // readingUp = !readingUp; // switch directions } if (resultOffset != version.getTotalCodewords()) { throw FormatException.getFormatInstance(); } return result; }
a9e0be4f-8912-4298-af6d-d2fd62441995
4
private ArrayList<Piece> getBlackTeamPieces() { ArrayList<Piece> blackTeam = new ArrayList<>(); // adds all pieces, except kings, to their appropriate teams in an ArrayList for(int y = 0; y < maxHeight; y++) { for(int x = 0; x < maxWidth; x++) { Piece currentPiece = board.getChessBoardSquare(x, y).getPiece(); Position currentPosition = new Position(x, y); possibleMovesForPiece(currentPiece, currentPosition); if(currentPiece.getPieceColor().equals(black)) { if(currentPiece.getPossibleMoves().size() > 0) { blackTeam.add(currentPiece); } } } } return blackTeam; }
6faacd75-f2c6-4809-aef4-d110852cf479
7
public static void main(String[] args) throws IOException { try { BufferedReader br = new BufferedReader(new FileReader("Data/Prediction_Similarities/sim.dat")); String line; while ((line = br.readLine()) != null) { // while loop begins here String[] splitLine = line.split("\t"); int userId = Integer.parseInt(splitLine[0]); double sim = Double.parseDouble(splitLine[2]); if (userSimilarities.containsKey(userId)) { userSimilarities.get(userId).add(sim); } else { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(sim); userSimilarities.put(userId, temp); } } br.close(); } catch (IOException e) { System.err.println("Error: " + e); } File file = new File("Data/Prediction_Similarities/similarityOfUsers.dat"); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); for (Entry<Integer, ArrayList<Double>> entry : userSimilarities.entrySet()) { double tempSim = 0; for (int i = 0; i < entry.getValue().size(); i++) { tempSim += entry.getValue().get(i); } try { double sim = tempSim / entry.getValue().size(); bw.write(entry.getKey() + "\t" + sim + "\n"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } bw.close(); }
215ca878-f22d-4497-88d5-f9f1161bfcde
4
public void checkObject () { Object object = (Object)getOneIntersectingObject(Object.class); if( object != null ) { if ( object instanceof CharPlayer ) { //CharBot.setSlowSpeed(4); //destroy(); } else if ( object instanceof CharBot ) { CharBot.setSlowSpeed(-4); destroy(); } else if ( object instanceof Ground ) { destroy(); } } }
419dc7e0-6dd1-43de-92d5-57734ca8da6d
0
public void setMonths(ArrayList <Month> m) { months = m; }
0d935885-aaff-4cb8-a0f1-ee64fe5c353e
3
public int Expect(String Data, int NumBytes ) { byte target = 0; int cnt = 0; try { while ((NumBytes--) != 0) { target = file.readByte(); if (target != Data.charAt(cnt++)) return DDC_FILE_ERROR; } } catch (IOException ioe) { return DDC_FILE_ERROR; } return DDC_SUCCESS; }
099735d7-d2ca-4265-b75a-155d37591d0a
0
public void setMimeType(String mimeType) { this.mimeType = mimeType; }
924ed508-0d4d-44aa-a6d9-55143d48699c
7
final public void Relation_operator() throws ParseException { /*@bgen(jjtree) Relation_operator */ SimpleNode jjtn000 = new SimpleNode(JJTRELATION_OPERATOR); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1)); try { if (jj_2_65(3)) { jj_consume_token(EQUALEQUAL); } else if (jj_2_66(3)) { jj_consume_token(EXCLAMEQUAL); } else if (jj_2_67(3)) { jj_consume_token(GREATER); } else if (jj_2_68(3)) { jj_consume_token(GREATEREQUAL); } else if (jj_2_69(3)) { jj_consume_token(SMALLER); } else if (jj_2_70(3)) { jj_consume_token(SMALLEREQUAL); } else { jj_consume_token(-1); throw new ParseException(); } } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } }
b0b1421c-8a7e-48db-a843-63cbc29c66a5
8
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Message message = (Message) o; if (idmessage != message.idmessage) return false; if (content != null ? !content.equals(message.content) : message.content != null) return false; if (date != null ? !date.equals(message.date) : message.date != null) return false; return true; }
df9fcd41-387c-41d2-8255-65e1efc966d4
8
private Tuple<Float, HeuristicData> min(LongBoard state, HeuristicData data, float alpha, float beta, int action, int depth) { statesChecked++; Tuple<Float, HeuristicData> y = new Tuple<>((float) Integer.MAX_VALUE, data); Winner win = gameFinished(state); if(cache.get(state.toString()) != null) { cacheHits++; return new Tuple<>(cache.get(state.toString()),null); } // If the state is a finished state if (win != Winner.NOT_FINISHED) { float value = utility(win, depth); cache.put(state.toString(), value); return new Tuple<>(value, null); } if(cache.get(state.toString()) != null) { cacheHits++; return new Tuple<>(cache.get(state.toString()),null); } if (depth == 0) { hasReachedMaxDepth = true; HeuristicData newData = H.moveHeuristic(data, action, playerID); Tuple<Float, HeuristicData> value = h(state, newData); cache.put(state.toString(), value._1); return value; } for (int newaction : generateActions(state)) { // Stop if time's up if (isTimeUp()) break; HeuristicData newData = H.moveHeuristic(data, action, playerID); Tuple<Float, HeuristicData> max = max( result(state, newaction), newData, alpha, beta, newaction, depth - 1 ); if (max._1 < y._1) { y = max; } // tests for possible alpha cut if (y._1 <= alpha) { cutoffs++; cache.put(state.toString(), y._1); return y; } beta = Math.min(beta, y._1); } cache.put(state.toString(), y._1); return y; }
f9983e3e-8e8c-440c-a97c-230b60e6b385
0
public Occurrence(String name){ this.docName = name; this.termFrequency = 1; }
7f45bab6-2bcd-4525-8cec-b221588e3002
9
@Override protected void processTask() { String visitingUrl = _url.toString(); Document page = null; try { // Wikipedia's robots.txt advises a crawl-delay of atleast 1 sec Thread.sleep(1000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { page = Jsoup.connect(visitingUrl).get(); getContributorsForPage(page, _url); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.err.print("Couldn't make request to URL " + visitingUrl); } if (null != page) { _stateListener.executingTask("Parsing for links, page at URL:" + visitingUrl, _myId); Elements paragraphs = page.select("p"); Elements linkedArticles = paragraphs.select("a[href]"); int noOfLinksAdded = 0; if (false == _urlQueue.hasMaxDepthReached()) { for (Element link : linkedArticles) { if (noOfLinksAdded < _noOfUrlsPerPage) { String pageUrl = link.attr("href"); try { // urls might be relative to current page URL completeUrl = new URL(_url, pageUrl); if (true == _urlQueue.push(completeUrl)) { // Increment count only if link was added, // don't increment if it was duplicate/invalid URL noOfLinksAdded++; } } catch (MalformedURLException e) { System.err.print("MalformedUrl: foundurl:" + pageUrl); // e.printStackTrace(); } } else { System.out.println(_noOfUrlsPerPage + " visited!"); break; } } } } _stateListener.finished(_myId); }
53a2a587-45c1-4557-ab6f-8cbc40308f2d
2
public static String pedirDni(){ boolean correcto=false; String dni=""; try{ do{ System.out.print("DNI => "); BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in)); dni=stdin.readLine(); correcto=Operaciones.isdni(dni); }while(correcto==false); }catch(Exception e){ System.out.println("Error "+e); } return dni; }
ee7cbb86-980d-4c5a-a919-b236104d7b5e
1
public static Object getJsonContent(URL url, String method, Type classToConvert){ HttpURLConnection conn=null; Object obj=null; try { conn = HTTPConnector.HTTPConnect(url,method, null); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); //set the json file content obj=JsonUtility.fromJsonToObject(br, classToConvert); br.close(); HTTPConnector.HTTPDisconnect(conn); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return obj; }
ee235427-d460-4f93-8964-7ec2d2049705
9
private boolean post2Qc() { boolean uploaded = true; List<String> logFilePaths = testRunInfo.getClientLogFilePaths(); TestRunInfo newTestRun = null; try { newTestRun = qcConnector.postResult2Qc(testRunInfo); if (newTestRun != null) { log.info("Successfully posted test run result into QC :" + newTestRun.getId()); } else { log.error("Failed to post test result into QC"); } } catch(Exception ex) { log.error("Got an exception when posting test run result into QC", ex); } try { if (newTestRun != null && logFilePaths != null && !logFilePaths.isEmpty()) { for(String logFilePath : logFilePaths) { if (qcConnector.uploadLogFile2Qc(newTestRun.getId(), logFilePath) != null) { log.info("Test logs are successfully uploaded into QC :" + logFilePaths); } else { log.error("Failed to upload test logs into QC :" + logFilePaths); uploaded = false; } } } } catch(Exception ex) { log.error("Got an exception when uploading testlog files into QC", ex); uploaded = false; } return newTestRun != null && uploaded; }
4c2be268-919d-40b9-8871-cb4a77b41fb9
7
public static UncertainPlayer fromConfiguration(String configuration) { String name = "uncertain"; int sample_size = -1; int decision_time = 5000; long seed = System.currentTimeMillis(); double alpha = 1; boolean verbose = true; for (Map.Entry<String,String> entry: Util.parseConfiguration(configuration).entrySet()) { String k = entry.getKey(), v = entry.getValue(); if (k.equals("name")) name = v; if (k.equals("sample_size")) sample_size = Integer.parseInt(v); if (k.equals("decision_time")) decision_time = Integer.parseInt(v); if (k.equals("belief_seed")) seed = Long.parseLong(v); if (k.equals("belief_alpha")) alpha = Double.parseDouble(v); if (k.equals("verbose")) verbose = Boolean.parseBoolean(v); } return new UncertainPlayer(name, Player.fromConfiguration(configuration), sample_size, decision_time, seed, alpha, verbose); }
33f7988b-99bc-45dc-bb8f-f9b2c99c1823
6
public boolean validarConexion (String n_url, String n_port, boolean seg_int, String n_usu, String n_cla){ boolean valida = false; if (! n_port.equals("")){ port = n_port; } else{ port = "1433"; } String urlConexion = jdbc+n_url+":"+port+";"; if (seg_int){ urlConexion +="integratedSecurity=true;"; } else{ urlConexion +="user="+n_usu+";password="+n_cla+";"; } try { conn = DriverManager.getConnection(urlConexion); valida = true; conn.close(); } catch (SQLException ex) { //corto la longitud del mensaje y muestro el error //para informar por que no puede conectarce a la BD String error = ""; String[] palabras = ex.getMessage().split(" "); int i = 0; int j = 0; while (i < palabras.length){ while ((i < palabras.length) && (j <= 11)){ error+=" "+palabras[i]; i=i+1; j=j+1; } j=0; error+="\n "; } JOptionPane.showMessageDialog(null,"Código del ERROR: "+ex.getErrorCode()+"\nMensaje del ERROR: "+ error, "Error al intentar establecer la Conexión", JOptionPane.ERROR_MESSAGE); } return valida; }
73558002-50bc-4cc6-a46b-4e39d2c466af
6
private static int isFullHouse(ArrayList<Card> list) { assert(list.size() == EFFECTIVE_CARD_NUM); int setPos = containSet(list); if (setPos < 0 || setPos == 1 ){ return -1; } if (setPos == 0 && list.get(3).getPoint() == list.get(4).getPoint()){ return list.get(0).getPoint(); } if (setPos == 2 && list.get(0).getPoint() == list.get(1).getPoint()){ return list.get(2).getPoint(); } return -1; }
5fe3c74d-06bd-4247-9bf6-82fd2e071ded
3
public Connection getConnection() { try { if ((MySQLCore.connection == null) || (MySQLCore.connection.isClosed())) { initialize(); } } catch (SQLException e) { initialize(); } return MySQLCore.connection; }
e417e170-5044-44da-9e86-322de28b6164
0
public void remove() { q.clear(); }
3b6d15a0-a1ac-47a7-a76f-1a837b11a2fc
7
public void soften() { RadialBondCollection rbc = model.getBonds(); RadialBond rb; synchronized (rbc.getSynchronizationLock()) { for (Iterator it = rbc.iterator(); it.hasNext();) { rb = (RadialBond) it.next(); if (contains(rb.getAtom1()) && contains(rb.getAtom2())) { rb.setBondStrength(SOFT_BOND); } } } AngularBondCollection abc = model.getBends(); AngularBond ab; synchronized (abc.getSynchronizationLock()) { for (Iterator it = abc.iterator(); it.hasNext();) { ab = (AngularBond) it.next(); if (contains(ab.getAtom1()) && contains(ab.getAtom2()) && contains(ab.getAtom3())) { ab.setBondStrength(SOFT_BEND); } } } }
07d52d8f-c507-4b08-a8d8-b3a28bb8f5d0
7
public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new BufferedInputStream(System.in)); PrintWriter cout = new PrintWriter(System.out); int number, len; HashMap<String, Integer> hashcount = new HashMap<String, Integer>(); while (true) { number = sc.nextInt(); len = sc.nextInt(); sc.nextLine(); hashcount.clear(); if (number == 0 && len == 0) { break; } for (int line = 1; line <= number; line++) { String s = sc.nextLine(); if (hashcount.containsKey(s)) { hashcount.put(s, hashcount.get(s) + 1); } else { hashcount.put(s, 1); } } int[] output = new int[number]; for (Entry<String, Integer> keyset : hashcount.entrySet()) { output[keyset.getValue() - 1]++; } for (int i = 0; i < output.length; i++) { cout.println(output[i]); } } cout.flush(); }
a1a44303-d03d-4fad-9189-f2a4863ec1e4
5
@Override public T next() { try { resultSet.next(); // Instantiate T to fill be able to fill it with result data T instance = c.newInstance(); // Column names are stored in the metaData ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); for (int columnIndex = 1; true; columnIndex++) { try { String columnName = resultSetMetaData.getColumnName(columnIndex); // Capitalize first character columnName = columnName.substring(0, 1).toUpperCase() + columnName.substring(1); Method instanceSetMethod; // Try getting a set method from T that matches the current column name try { instanceSetMethod = instance.getClass().getMethod("set" + columnName, Object.class); } catch (NoSuchMethodException | SecurityException e) { continue; } // Invoke retrieved method with the data from the result set try { instanceSetMethod.invoke(instance, resultSet.getObject(columnIndex)); } catch (IllegalArgumentException | InvocationTargetException e) { continue; } } // When the last column ID is reached, an SQLException is thrown. Break on this point. catch (SQLException e) { break; } } return instance; } catch (SQLException | InstantiationException | IllegalAccessException e) { e.printStackTrace(); } return null; }
b88de9dc-28f7-4896-b985-d1d43664110d
4
@Override public BlocService getBloc(int i, int j){ BlocService b; if(!(0<=i && i<super.getNombreColonnes() && 0<=j && j<super.getNombreLignes())) throw new PreConditionError("unboud i or j"); checkInvariants(); b = super.getBloc(i, j); checkInvariants(); return b; }
b65a2507-5947-4b61-b0be-c50d5b536ea7
6
public String GetLaunchUrlWithTags(String registrationId, String redirectOnExitUrl, String cssUrl, String debugLogPointerUrl, String learnerTags, String courseTags, String registrationTags) throws Exception { ServiceRequest request = new ServiceRequest(configuration); request.getParameters().add("regid", registrationId); if (!Utils.isNullOrEmpty(redirectOnExitUrl)) request.getParameters().add("redirecturl", redirectOnExitUrl); if(!Utils.isNullOrEmpty(cssUrl)) request.getParameters().add("cssurl", cssUrl); if (!Utils.isNullOrEmpty(debugLogPointerUrl)) request.getParameters().add("saveDebugLogPointerUrl", debugLogPointerUrl); if(!Utils.isNullOrEmpty(learnerTags)){ request.getParameters().add("learnerTags", learnerTags); } if(!Utils.isNullOrEmpty(courseTags)){ request.getParameters().add("courseTags", courseTags); } if(!Utils.isNullOrEmpty(registrationTags)){ request.getParameters().add("registrationTags", registrationTags); } return request.constructUrl("rustici.registration.launch"); }
a03fd72d-5658-48c4-b43e-127eb0352981
3
public static boolean saveNewWord(ArrayList<WordsPair> stringArray, String filename) { if (stringArray == null) { return false; } //Checking parameter for null. FileWriter output; //Creating reference for filewriter. try { output = new FileWriter(new File(filename)); //Opening connection to file. for (WordsPair pair : stringArray) { //running through the ArrayList. output.write(pair.toString() + "\n"); //Each String object is written as a line in file. } output.close(); //Closing the file } catch (Exception ex) { //If something goes wrong everything is send to system out. System.out.println("Could not save to file!"); System.out.println(ex.toString()); ex.printStackTrace(); return false; //If something goes wrong false is returned! } return true; }
64b6f0c2-24a7-40e0-ad4a-1fe2c3098ba3
8
public static void main(String[] args) { Terrain mount1 = Terrain.getMountain(); Terrain mount2 = Terrain.getMountain(); if (mount1.equals(mount2)) { System.out.println("Son la misma montaña"); } GridCell map[][] = new GridCell[33][38]; System.out.println("La longitud X del mapa es " + map.length); System.out.println("La longitud Y del mapa es " + map[0].length); //Run along the array without considering it's dimensions for (GridCell gridRow[] : map) { for (GridCell gridCell : gridRow) { //System.out.println("Getting to it"); } } try { ClassLoader.getSystemClassLoader().loadClass("aw2m.common.core.Unit"); } catch (ClassNotFoundException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } //DEBUG: Creación de mapa de Prueba: Terreno con planicies //DEBUG: Index were bytes. for (byte i = 0; i < 33; i++) { for (byte j = 0; j < 38; j++) { map[i][j] = new GridCell(); map[i][j].terrain = Terrain.getPlain(); map[i][j].x = i; map[i][j].y = j; } } //DEBUG: Creación de la unidad de prueba /* Unit infantry = Unit.newInfantry(); infantry.setX(Byte.parseByte("5")); infantry.setY(Byte.parseByte("5")); map[infantry.getX()][infantry.getY()].setUnit(infantry); //DEBUG: Calcular el radio de movimiento de la infanteria Set<GridCell> radio = new HashSet<GridCell>(); radio = Logic.calculateMovementRadius(infantry, map); System.out.println("Movimiento: \n" + radio); */ /*Testing the cross algorythm**/ /* Set<GridCell> cross = new HashSet<GridCell>(); cross = Logic.getCrossArea(map[5][5], (byte) 3, map); System.out.println("Cross \n" + cross); */ /*Testing the movement crawl algorithm*/ //Requires previously set map on Logic Unit u = new Unit(); u.location = map[9][9]; u.unitType = Unit.FIGHTER; u.player = new Player((byte)1); u.player.currentCO = new CO(CO.ANDY); if (u.location == null) { System.out.println("location is null!"); } else { System.out.println("location is NOT null!"); } //TEST FOR TERRAIN affecting movement map[6][9].terrain = Terrain.getWood(); map[8][9].terrain = Terrain.getWood(); map[10][9].terrain = Terrain.getWood(); map[12][9].terrain = Terrain.getWood(); Set<GridCell> movementSet; movementSet = new HashSet<GridCell>(Logic.calculateMovementRadius(u, map)); System.out.println("movementSet \n" + movementSet); System.out.println("Iterations: " + Logic.iterations); System.out.println("Set Size: " + movementSet.size()); //movementSet = new HashSet<GridCell>(Logic.calculateMovementRadiusUsingAStar(u, map)); int allIterations = 0; LinkedList<DijkstraElement> movementList = Logic.calculateMovementRadiusUsingAStar(u, map); System.out.println("movementList\n" + movementList); System.out.println("Iterations: " + Logic.iterations); System.out.println("List Size: " + movementList.size()); allIterations += Logic.iterations; int counter = 0; //Generate all possible movement ranges from selecting each of the gridCells on the actual movementList for (DijkstraElement d : movementList) { u.location = d.gridCell; LinkedList<DijkstraElement> calculateMovementRadiusUsingDijkstra = Logic.calculateMovementRadiusUsingAStar(u, map); System.out.println("movementList\n" + calculateMovementRadiusUsingDijkstra); System.out.println("Iterations: " + Logic.iterations); System.out.println("List Size: " + calculateMovementRadiusUsingDijkstra.size()); allIterations += Logic.iterations; counter++; } System.out.println("ALL Iterations: " + allIterations); System.out.println("Counter: " + counter); /* //Spann Island MapLoader.sizeX = 15; MapLoader.sizeY = 10; map = new GridCell[MapLoader.sizeX][MapLoader.sizeY]; for (byte i = 0; i < MapLoader.sizeX; i++) { for (byte j = 0; j < MapLoader.sizeY; j++) { map[i][j] = new GridCell(); map[i][j].x = i; map[i][j].y = j; } } MapLoader.map = map; MapLoader.readMap("SpannIsland.csv"); //MENU //noOfPlayers, map, System.out.println("Multiplayer"); System.out.println("Choose Map"); System.out.println(""); System.out.println(""); System.out.println(""); System.out.println(""); System.out.println(""); System.out.println(""); System.out.println(""); */ }
3ff4bccf-a2db-4ccf-b822-4f4386c86b6b
9
protected static Ptg calcDAverage( Ptg[] operands ) { if( operands.length != 3 ) { return new PtgErr( PtgErr.ERROR_NA ); } DB db = getDb( operands[0] ); Criteria crit = getCriteria( operands[2] ); if( (db == null) || (crit == null) ) { return new PtgErr( PtgErr.ERROR_NUM ); } int fNum = db.findCol( operands[1].getString().trim() ); if( fNum == -1 ) { return new PtgErr( PtgErr.ERROR_NUM ); } double average = 0; int count = 0; // this is the colname to match String colname = operands[1].getValue().toString(); for( int i = 0; i < db.rows.length; i++ ) { // loop thru all db rows // check if current row passes criteria requirements Ptg[] rwz = db.getRow( i ); // slight optimization one less call to getRow -jm if( crit.passes( colname, rwz, db ) ) { // passes; now do action Ptg vx = rwz[fNum]; if( vx != null ) { try { average += Double.parseDouble( vx.getValue().toString() ); count++; // if it can be parsed into a number, increment count } catch( NumberFormatException exp ) { } } } } if( count > 0 ) { average = average / count; } return new PtgNumber( average ); }
2e851853-975a-4e17-963f-092f5bac2fa2
4
public void setJSONDataInArray(int id_cod, String cod_rastreio){ JSONParser parser = new JSONParser(); JSONArray a; all = ""; try { String url_link = "http://developers.agenciaideias.com.br/correios/rastreamento/json/" + cod_rastreio; this.url = new URL(url_link); in = new BufferedReader(new InputStreamReader(this.url.openStream())); while ((line = in.readLine()) != null) { all += line; } in.close(); a = (JSONArray) parser.parse(all); for (Object o : a) { JSONObject person = (JSONObject) o; al.add((String) person.get("data")); al.add((String) person.get("local")); al.add((String) person.get("acao")); al.add((String) person.get("detalhes")); } } catch (org.json.simple.parser.ParseException ex) { JOptionPane.showMessageDialog(null, "Problemas no 'parsing' do JSON.", ":'(", JOptionPane.ERROR_MESSAGE); Logger.getLogger(JSON.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Problemas ao submeter o código à API dos correios. (PARSING JSON)", ":'(", JOptionPane.ERROR_MESSAGE); Logger.getLogger(JSON.class.getName()).log(Level.SEVERE, null, ex); } }
951d88c0-1e6e-4188-8284-842fe012ab27
9
protected void keyTyped(char par1, int par2) { if (par2 == 15) { this.completePlayerName(); } else { this.field_50060_d = false; } if (par2 == 1) { this.mc.displayGuiScreen((GuiScreen)null); } else if (par2 == 28) { String var3 = this.inputField.getText().trim(); if (var3.length() > 0 && !this.mc.lineIsCommand(var3)) { this.mc.thePlayer.sendChatMessage(var3); } this.mc.displayGuiScreen((GuiScreen)null); } else if (par2 == 200) { this.getSentHistory(-1); } else if (par2 == 208) { this.getSentHistory(1); } else if (par2 == 201) { this.mc.ingameGUI.adjustHistoryOffset(19); } else if (par2 == 209) { this.mc.ingameGUI.adjustHistoryOffset(-19); } else { this.inputField.textboxKeyTyped(par1, par2); } }
90f84934-ee8f-428c-85eb-891aa5cb13c2
3
public ShadingPattern(Library library, Hashtable entries) { super(library, entries); type = library.getName(entries, "Type"); patternType = library.getInt(entries, "PatternType"); Object attribute = library.getObject(entries, "ExtGState"); if (attribute instanceof Hashtable) { extGState = new ExtGState(library, (Hashtable) attribute); } else if (attribute instanceof Reference) { extGState = new ExtGState(library, (Hashtable) library.getObject( (Reference) attribute)); } Vector v = (Vector) library.getObject(entries, "Matrix"); if (v != null) { matrix = getAffineTransform(v); } else { // default is identity matrix matrix = new AffineTransform(); } }
f31813bc-9a7b-4f93-b92c-c24d4befb9eb
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(JDElegirProyecto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JDElegirProyecto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JDElegirProyecto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JDElegirProyecto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { JDElegirProyecto dialog = new JDElegirProyecto(new javax.swing.JFrame(), true, proyectos); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
de829778-e5cd-4531-ad8d-21560e87da94
3
@Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, selected,expanded, leaf, row, hasFocus); if(value instanceof SPFile) { SPFile f = (SPFile) value; String type = f.getType(); if(!type.isEmpty()) { File file; try { file = File.createTempFile("icon", type); FileSystemView view = FileSystemView.getFileSystemView(); Icon icon = view.getSystemIcon(file); file.delete(); setIcon(icon); } catch (IOException e) { e.printStackTrace(); } } } return this; }
efff8f4d-550a-485b-bc1e-3a6c73b30d6b
6
public void produceEmails(){ emails.removeAll(emails); try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Where is your MySQL JDBC Driver?"); e.printStackTrace(); } PreparedStatement ps = null; Connection con = null; ResultSet rs; try { con = DriverManager.getConnection("jdbc:mysql://mysql2.cs.stonybrook.edu:3306/mlavina", "mlavina", "108262940"); if (con != null) { con.setAutoCommit(false); try { String sql = "SELECT Email from Customer"; ps = con.prepareStatement(sql); ps.execute(); rs = ps.getResultSet(); while (rs.next()) { emails.add(rs.getString("email")); } con.commit(); } catch (Exception e) { con.rollback(); } } } catch (Exception e) { System.out.println(e); } finally { try { con.setAutoCommit(true); con.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } }
1ca9a76c-bbbe-479a-b32a-403dbba495f1
5
public void visitCallMethodExpr(final CallMethodExpr expr) { if (expr.receiver() != null) { expr.receiver().visit(this); } print("."); if (expr.method() != null) { print(expr.method().nameAndType().name()); } print("("); if (expr.params() != null) { for (int i = 0; i < expr.params().length; i++) { expr.params()[i].visit(this); if (i != expr.params().length - 1) { print(", "); } } } print(")"); }
e022d9b6-33db-4916-9c2c-8db9e4a7a57a
3
public static boolean intersect(Rectangle a,Rectangle b) { // boolean x = (a.left() <= b.right() && a.right() >= b.left()) || (a.left() >= b.left() && a.right() <= b.right()) || (a.left() <= b.right() && a.right() >= b.right()); // boolean y = (a.top() <= b.bottom() && a.bottom() >= b.top()) || (a.top() >= b.top() && a.bottom() <= b.bottom()) || (a.top() <= b.bottom() && a.bottom() >= b.bottom()); boolean x = (a.left() < b.right()) && (a.right() > b.left()); boolean y = (a.top() < b.bottom()) && (a.bottom() > b.top()); return x && y; }
e2f42dfe-706e-4c17-a0ae-be6954db4aae
3
public void nextHit() { if (current == "Registration") { if (helpy.isSelected()) { NewUser newbie = new NewUser(); Helpy helpMe = new Helpy(newbie.txuser.toString(), newbie.pass1.getText()); } else if (needy.isSelected()) { NewUser newbie = new NewUser(); Needy meNeed = new Needy(newbie.txuser.toString(), newbie.pass1.getText()); } } }
0b806578-ef14-4361-92eb-839e414c0cf1
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(frmPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(frmPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(frmPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(frmPrincipal.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 frmPrincipal().setVisible(true); } }); }
c05bc7f3-4ae3-4885-bebe-f74b8ca83cbb
5
private void MergeSortParts(int low, int mid, int high) { for (int i = low; i <= high; i++) { tempArray[i] = array[i]; } int i = low; int j = mid + 1; int k = low; while (i <= mid && j <= high) { if (tempArray[i] <= tempArray[j]) { array[k] = tempArray[i]; i++; } else { array[k] = tempArray[j]; j++; } k++; } while (i <= mid) { array[k] = tempArray[i]; k++; i++; } }
7352e4cd-7c0a-43db-8957-246feb8193f8
1
public ChatServer() { try { ssocket = new ServerSocket(port); } catch (IOException e) { e.printStackTrace(); } }
0e2e987a-978d-43ec-b99a-39b362b352ba
2
public void test() throws ModelException { Account a = new Account(); FIXMLBuilder builder = new FIXMLBuilder(a); builder.timeInForce(TimeInForceField.DAY_ORDER); builder.symbol("OCQLF"); builder.priceType(PriceType.LIMIT); builder.securityType(SecurityType.STOCK); builder.quantity(1); builder.executionPrice(.01); builder.side(MarketSideField.BUY); MarketPreviewOrder order = new MarketPreviewOrder(new Account(), builder); for(OrderPreviewField f: OrderPreviewField.values()) { if(order.hasField(f)) { String value = order.getField(f); System.out.println(f+" "+value); } } }
ca87dbb1-b602-4f88-96ab-df8a7a83bf39
3
public boolean containsTag(Tag tag) { if (hasTag(tag)) return true; else { for (GenericTreeNode child : getChildren()) if (((Area) child).hasTag(tag)) return true; return false; } }
c13f4977-97bc-4980-8f5a-d371dbf867d4
9
void readAtoms(int modelAtomCount) throws Exception { for (int i = 0; i < modelAtomCount; ++i) { readLine(); Atom atom = atomSetCollection.addNewAtom(); int isotope = parseInt(line); String str = parseToken(line); // xyzI if (isotope == Integer.MIN_VALUE) { atom.elementSymbol = str; } else { str = str.substring((""+isotope).length()); atom.elementNumber = (short)((isotope << 7) + JmolConstants.elementNumberFromSymbol(str)); atomSetCollection.setFileTypeName("xyzi"); } atom.x = parseFloat(line, ichNextParse); atom.y = parseFloat(line, ichNextParse); atom.z = parseFloat(line, ichNextParse); if (Float.isNaN(atom.x) || Float.isNaN(atom.y) || Float.isNaN(atom.z)) { logger.log("line cannot be read for XYZ atom data: " + line); atom.x = 0; atom.y = 0; atom.z = 0; } setAtomCoord(atom); for (int j = 0; j < 4; ++j) isNaN[j] = Float.isNaN(chargeAndOrVector[j] = parseFloat(line, ichNextParse)); if (isNaN[0]) continue; if (isNaN[1]) { atom.formalCharge = (int)chargeAndOrVector[0]; continue; } if (isNaN[3]) { atom.vectorX = chargeAndOrVector[0]; atom.vectorY = chargeAndOrVector[1]; atom.vectorZ = chargeAndOrVector[2]; continue; } atom.formalCharge = (int)chargeAndOrVector[0]; atom.vectorX = chargeAndOrVector[1]; atom.vectorY = chargeAndOrVector[2]; atom.vectorZ = chargeAndOrVector[3]; } }
d13c1de0-fec8-4668-b09b-b905a8ab9381
1
public float getDelay(Component cmp) { return delays.containsKey(cmp) ? delays.get(cmp) : 0; }
df6b08e8-2d22-4f88-8b14-d9cd7c19ae46
1
public void lazilyExit() { Thread thread = new Thread() { public void run() { // first, wait for the VM exit on its own. try { Thread.sleep(2000); } catch (InterruptedException ex) { } // system is still running, so force an exit System.exit(0); } }; thread.setDaemon(true); thread.start(); }
7cbf517e-70ab-4654-a094-b78ce4a407fd
2
public void checkConsistent() { super.checkConsistent(); if (trueBlock.jump == null || !(trueBlock instanceof EmptyBlock)) throw new jode.AssertError("Inconsistency"); }
78d0cb1d-b51d-4016-a57b-55e55d3f6949
2
public static ArrayList<UserStocks> getUserStocks() { ArrayList<UserStocks> usersStocks = new ArrayList<UserStocks>(); File f = new File("userstocks.txt"); try { FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); String s = ""; while ((s = br.readLine()) != null) { String[] comp = splitLine(s, 3); UserStocks u = new UserStocks(); u.setUsername(comp[0]); u.setTickername(comp[1]); u.setNo(Integer.valueOf(comp[2])); usersStocks.add(u); } br.close(); } catch (IOException e) { e.printStackTrace(); } return usersStocks; }
00d0bc54-316b-4dfa-872a-491d59d90998
4
@Override public List<Image> getImages() { if(images != null) return images; File[] imageFiles = directory.listFiles(); Arrays.sort(imageFiles); images = new ArrayList<Image>(); for(File f : imageFiles) if(f.isFile() && !f.getName().equals(".displaystate")) images.add(new LocalImage(f)); return images; }
93feda8e-807b-4612-adb6-159b7f112c69
8
private Component cycle(Component currentComponent, int delta) { int index = -1; loop : for (int i = 0; i < m_Components.length; i++) { Component component = m_Components[i]; for (Component c = currentComponent; c != null; c = c.getParent()) { if (component == c) { index = i; break loop; } } } // try to find enabled component in "delta" direction int initialIndex = index; while (true) { int newIndex = indexCycle(index, delta); if (newIndex == initialIndex) { break; } index = newIndex; // Component component = m_Components[newIndex]; if (component.isEnabled() && component.isVisible() && component.isFocusable()) { return component; } } // not found return currentComponent; }
70d8f89b-a11a-4d4e-a478-d0cfbc1a74c0
3
@Override public TrackerResponse sendRequest (TrackerRequest request, long time, TimeUnit unit) { long remaining = unit.toNanos(time); int left = trackers.size(); for (Iterator<Tracker> it = trackers.iterator(); it.hasNext() && remaining > 0;) { long stTime = System.nanoTime(); Tracker tracker = it.next(); TrackerResponse resp = tracker.sendRequest(request, remaining / left, TimeUnit.NANOSECONDS); long ndTime = System.nanoTime(); remaining -= (ndTime - stTime); left--; if (resp != null) { // WARNING :: ConcurrentModificationException ! // This will NEVER throw such an exception, as the loop ENDS here. I wanted to clarify this, so no one // ever, not even myself, removes this for that reason. it.remove(); trackers.addFirst(tracker); return resp; } } return null; }
84d6efa6-43a6-4b7c-8196-2a3dd57f7913
2
public void setLoc(Atom new_loc) { if(location != null) { location.contents.remove(this); } location = new_loc; this.outdated |= Atom.positionOutdated; if(new_loc != null) { new_loc.contents.add(this); } }
67a63ec3-f530-4fc1-97d4-2827d59fc390
1
@Override public List<Integer> update(Criteria beans, Criteria criteria, GenericUpdateQuery updateGeneric, Connection conn) throws DaoQueryException { List paramList1 = new ArrayList<>(); List paramList2 = new ArrayList<>(); StringBuilder sb = new StringBuilder(UPDATE_QUERY); String queryStr = new QueryMapper() { @Override public String mapQuery() { Appender.append(DAO_ID_DIRECTION, DB_TOUR_ID_DIRECTION, criteria, paramList1, sb, COMMA); Appender.append(DAO_TOUR_DATE, DB_TOUR_DATE, criteria, paramList1, sb, COMMA); Appender.append(DAO_TOUR_DAYS, DB_TOUR_DAYS_COUNT, criteria, paramList1, sb, COMMA); Appender.append(DAO_TOUR_PRICE, DB_TOUR_PRICE, criteria, paramList1, sb, COMMA); Appender.append(DAO_TOUR_DISCOUNT, DB_TOUR_DISCOUNT, criteria, paramList1, sb, COMMA); Appender.append(DAO_TOUR_TOTAL_SEATS, DB_TOUR_TOTAL_SEATS, criteria, paramList1, sb, COMMA); Appender.append(DAO_TOUR_FREE_SEATS, DB_TOUR_FREE_SEATS, criteria, paramList1, sb, COMMA); Appender.append(DAO_TOUR_STATUS, DB_TOUR_STATUS, criteria, paramList1, sb, COMMA); sb.append(WHERE); Appender.append(DAO_ID_TOUR, DB_TOUR_ID_TOUR, beans, paramList2, sb, AND); Appender.append(DAO_ID_DIRECTION, DB_TOUR_ID_DIRECTION, beans, paramList2, sb, AND); Appender.append(DAO_TOUR_DATE, DB_TOUR_DATE, beans, paramList2, sb, AND); Appender.append(DAO_TOUR_DAYS, DB_TOUR_DAYS_COUNT, beans, paramList2, sb, AND); Appender.append(DAO_TOUR_PRICE, DB_TOUR_PRICE, beans, paramList2, sb, AND); Appender.append(DAO_TOUR_DISCOUNT, DB_TOUR_DISCOUNT, beans, paramList2, sb, AND); Appender.append(DAO_TOUR_TOTAL_SEATS, DB_TOUR_TOTAL_SEATS, beans, paramList2, sb, AND); Appender.append(DAO_TOUR_FREE_SEATS, DB_TOUR_FREE_SEATS, beans, paramList2, sb, AND); Appender.append(DAO_TOUR_STATUS, DB_TOUR_STATUS, beans, paramList2, sb, AND); return sb.toString(); } }.mapQuery(); paramList1.addAll(paramList2); try { return updateGeneric.sendQuery(queryStr, paramList1.toArray(), conn); } catch (DaoException ex) { throw new DaoQueryException(ERR_TOUR_UPDATE, ex); } }
212cfdc0-ce9f-49ac-ba5e-fe1d4eb62250
1
@Override public void update(GameContainer container, int delta) throws SlickException { if(wturn){ wturn = !players[0].go(container, board); } else{ wturn = players[1].go(container, board); } }
79d03f13-dc3c-4733-bb14-53bc56a355c1
2
public ArrayList<String> getTags() { ArrayList<String> tagList = new ArrayList<String>(); String statement = new String("SELECT * FROM " + TagDBTable + " WHERE qid = ?"); PreparedStatement stmt; try { stmt = DBConnection.con.prepareStatement(statement); stmt.setInt(1, quizID); ResultSet rs = stmt.executeQuery(); while (rs.next()) { String tag = rs.getString("tag"); tagList.add(tag); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } return tagList; }
34349913-4e87-4d1e-a18e-55bf48ba1a77
3
private static Person getPerson(String[] personInfo) { Integer classValue = 0; if ("50000+".equals(personInfo[41])) { classValue = 1; } Person person = new Person(classValue); person.addAttribute(0, Double.parseDouble(personInfo[0])); person.addAttribute(1, Double.parseDouble(personInfo[18])); Double marrigeStatus = 0.0; if (personInfo[7].startsWith("Married")) { marrigeStatus = 1.0; } person.addAttribute(2, marrigeStatus); Double employer = 1.0; if ("0".equals(personInfo[30])) { employer = 0.0; } person.addAttribute(3, employer); return person; }
aa5d4dc7-c55d-4b61-8076-7fb52c660511
2
public void disable() throws IOException { // This has to be synchronized or it can collide with the check in the task. synchronized (optOutLock) { // Check if the server owner has already set opt-out, if not, set it. if (!isOptOut()) { configuration.set("opt-out", true); configuration.save(configurationFile); } // Disable Task, if it is running if (task != null) { task.cancel(); task = null; } } }
b7eb52f2-dff0-492a-b227-e562e7e73898
4
public synchronized void shutdown(){ if(!shutdown) shutdown = true; //Poll the queue and release all objects left in the queue. while(true){ Reference<?> ref = queue.poll(); if(ref != null){ Resource res = refs.get(ref);//Get the resource by the reference. refs.remove(ref);//Remove the object referred to by "ref" because it is retrieved from the queue. res.release(); ref.clear(); } else//No objects in the queue.//2012/12 Wrong. The condition to end this roop is that refs is empty. Queue need not to be checked. break; } }
505ae194-0a60-427a-b271-4ec3bfb4d895
6
public ArrayList<String> personToTopicPopulate(String name) { // arraylist that will populate the topic list based on person selected ArrayList<String> personToTopic = new ArrayList(); try { // open the file File xmlPerson = new File(fileName); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // uses DOM to parse the xml Document doc = dBuilder.parse(xmlPerson); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("Person"); //loop through person nodes for (int i = 0; i < nList.getLength(); i++) { Node nNode = nList.item(i); // get persons children NodeList sublist = nNode.getChildNodes(); if (nNode.getNodeType() == Node.ELEMENT_NODE) { // the person element Element eElement = (Element) nNode; // if the name attribute matches the parameter if (name.equals(eElement.getAttribute("name"))) { for (int j = 0; j < sublist.getLength(); j++) { Node cNode = (Node) sublist.item(j); if (cNode.getNodeType() == Node.ELEMENT_NODE) { //add the topic element Element cElement = (Element) cNode; personToTopic.add(cElement.getAttribute("subject")); } } } } } } catch (Exception e) { e.printStackTrace(); } return personToTopic; }
c5b168c3-a982-49f9-bd1c-0e8e88fb85cd
5
private DelegateGroupVotes createDelegateGroupVotes( EntityUserAndVote delegate, Map<Key, DelegateGroupVotes> allVotesMap, Map<Key, List<EntityUserAndVote>> delegateVotes) { Key delegateKey = Key.EMPTY; if (delegate != null) { delegateKey = delegate.getUser().getId().getKey(); } DelegateGroupVotes delegateGroupVotes = allVotesMap.get(delegateKey); if (delegateGroupVotes == null) { UserAndDecision delegateUserDecision = null; VoteDocumentDecision voteDocumentDecision = null; if (delegate != null) { voteDocumentDecision = delegate.getVote().getVoteDocumentDecision(); delegateUserDecision = new UserAndDecision(delegate.getUser(), voteDocumentDecision); } delegateGroupVotes = new DelegateGroupVotes(delegateUserDecision); if (delegate != null) { List<EntityUserAndVote> votesForDelegate = delegateVotes.get(delegateKey); if (votesForDelegate != null) { delegateGroupVotes.getGroupVotes().add(new DecisionsMap(voteDocumentDecision, votesForDelegate.size() + 1)); } } allVotesMap.put(delegateKey, delegateGroupVotes); } return delegateGroupVotes; }
f82e61be-e59d-46ad-9aa1-28179652ab73
7
public Expr Shift_Expr() throws ParseException { Expr e, et; Token tok; e = Add_Expr(); label_23: while (true) { switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case SHIFTLEFT: case SHIFTRIGHT: break; default: jj_la1[53] = jj_gen; break label_23; } switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case SHIFTLEFT: tok = jj_consume_token(SHIFTLEFT); break; case SHIFTRIGHT: tok = jj_consume_token(SHIFTRIGHT); break; default: jj_la1[54] = jj_gen; jj_consume_token(-1); throw new ParseException(); } et = Add_Expr(); e = new BinOpExpr(e, tok, et); } return e; }
99604980-9383-4014-9120-8653c8f709e7
1
@Override public float isContextMenuEnabledAt( int x, int y ) { SelectableCapability selection = getCapability( CapabilityName.SELECTABLE ); if( selection != null ) { return selection.contains( x, y ); } else { return 0.f; } }
f619b5ae-a68b-4afe-ab32-72e23a6cbac4
6
private String receiveThinking(long time, LineEval finalEval) { // Built the pv line String pvString = ""; for(int i = 0; i < 128; i++) { if(i == 0) { pvString += (Move.inputNotation(finalEval.line[0]) + " "); } else if(finalEval.line[i] == 0) break; else pvString += (Move.inputNotation(finalEval.line[i]) + " "); } // Calculate the nodes per second, we need decimal values // to get the most accurate result. // If we have searched less than 1 second return the nodesSearched // since the numbers tend to get crazy at lower times long splitTime = (System.currentTimeMillis() - time); int nps; if((splitTime / 1000) < 1) nps = totalNodesSearched; else { Double decimalTime = new Double(totalNodesSearched/(splitTime/1000D)); nps = decimalTime.intValue(); } // Send the info to the uci interface if(finalEval.eval >= MATE_BOUND) { int rest = ((-MATE_VALUE) - finalEval.eval)%2; int mateInN = (((-MATE_VALUE)-finalEval.eval)-rest)/2+rest; return "info score mate " + mateInN + " depth " + current_depth + " nodes " + totalNodesSearched + " nps " + nps + " time " + splitTime + " pv " + pvString; } else if(finalEval.eval <= -MATE_BOUND) { int rest = ((-MATE_VALUE) + finalEval.eval)%2; int mateInN = (((-MATE_VALUE)+finalEval.eval)-rest)/2+rest; return "info score mate " + -mateInN + " depth " + current_depth + " nodes " + totalNodesSearched + " nps " + nps + " time " + splitTime + " pv " + pvString; } return "info score cp " + finalEval.eval + " depth " + current_depth + " nodes " + totalNodesSearched + " nps " + nps + " time " + splitTime + " pv " + pvString; } // END receiveThinking
5542475d-09df-4c52-ab9c-da7fcf81ed9e
9
public int compareTo( Object obj ) { if( obj == null ) { return( 1 ); } else if( obj instanceof GenKbAddressByUDescrIdxKey ) { GenKbAddressByUDescrIdxKey rhs = (GenKbAddressByUDescrIdxKey)obj; if( getRequiredContactId() < rhs.getRequiredContactId() ) { return( -1 ); } else if( getRequiredContactId() > rhs.getRequiredContactId() ) { return( 1 ); } { int cmp = getRequiredDescription().compareTo( rhs.getRequiredDescription() ); if( cmp != 0 ) { return( cmp ); } } return( 0 ); } else if( obj instanceof GenKbAddressBuff ) { GenKbAddressBuff rhs = (GenKbAddressBuff)obj; if( getRequiredContactId() < rhs.getRequiredContactId() ) { return( -1 ); } else if( getRequiredContactId() > rhs.getRequiredContactId() ) { return( 1 ); } { int cmp = getRequiredDescription().compareTo( rhs.getRequiredDescription() ); if( cmp != 0 ) { return( cmp ); } } return( 0 ); } else { throw CFLib.getDefaultExceptionFactory().newUnsupportedClassException( getClass(), "compareTo", "obj", obj, null ); } }
af36de5c-5e98-4595-a079-15337e67d252
8
public void keyPressed (KeyEvent e) { int key = e.getKeyCode(); // Implemented boolean switches for the collider. Player can't move unless these are true. if ((key == KeyEvent.VK_W) && (directy == true)) dy = -1; if ((key == KeyEvent.VK_S) && (directy == true)) dy = 1; if ((key == KeyEvent.VK_A) && (directx == true)) dx = -1; if ((key == KeyEvent.VK_D) && (directx == true)) dx = 1; }
7361be8a-62e7-461f-87e4-b013d6171eb1
3
private void activity_submitModify_buttonActionPerformed(ActionEvent evt, String courseID, String actName) { boolean prog; boolean group; if(activity_type_combo.getSelectedItem().toString().equalsIgnoreCase("Programming")) prog = true; else prog = false; if(activity_group_checkbox.isSelected()) group = true; else group = false; Activity new_activity = new Activity(activity_name_field.getText(), activity_desc_field.getText(), activity_student_submissionpath_field.getText(), activity_solution_field.getText(), activity_lang_field.getText(), activity_due_date_1_field.getText(), prog, group, Integer.parseInt(activity_test_number_field.getText())); CourseAccess.modifyActivity(courseID, actName, new_activity); if (prog) CourseAccess.addTest(courseid, new_activity, activity_test_in_field.getText(), activity_test_out_field.getText()); else CourseAccess.deleteTests(courseid,new_activity); JOptionPane.showMessageDialog(this, "Activity modified."); setOkToNav(); GUIUtils.getMasterFrame(this).goBack(); }
7cc91ae3-0ac6-49cc-8b56-a1e672172beb
4
public static boolean lostOnlyPart(Robot paramRobot, Class paramClass) { Enumeration localEnumeration = GameApplet.thisApplet.getGameState().getRobotPartPatterns().elements(); while (localEnumeration.hasMoreElements()) if (paramClass.isInstance(localEnumeration.nextElement())) return false; RobotPart[] arrayOfRobotPart = paramRobot.getRobotParts(); for (int i = 0; i < arrayOfRobotPart.length; i++) if (paramClass.isInstance(arrayOfRobotPart[i])) return true; return false; }
6b1c5260-d874-4463-9b1b-402e966f8312
5
public static SignalAspect mostRestrictive(SignalAspect first, SignalAspect second) { if (first == null && second == null) return RED; if (first == null) return second; if (second == null) return first; if (first.ordinal() > second.ordinal()) return first; return second; }