text
stringlengths
14
410k
label
int32
0
9
public int getM(String word){ int m = 0; String vc = ""; if(word != null){ for (int i = 0; i < word.length(); i++) { char charAtIndex = word.charAt(i); char vcChar =vcTrans(charAtIndex); if(vcChar == 'y'){ if(i>0 && vcTrans(word.charAt(i-1)) == 'c'){ vc.concat("v"); }else{ vc.concat("c"); } }else{ // String s = String.valueOf(word.charAt(i)); // String ns =(String) vcTable.get(s); String ns = String.valueOf(vcTrans(word.charAt(i))); vc.concat(ns); } } for (int i = 0; i < vc.length()-1; ++i) { if ((vc.charAt(i) == 'v') && (vc.charAt(i+1) == 'c')) { m++; } } } return m; }
8
public boolean isMatch(String s, String p) { boolean[] a = new boolean[s.length()+1]; boolean[] b = new boolean[s.length()+1]; a[0] = true; for (int j=1; j<=s.length(); j++) a[j] = false; for (int i=1; i<=p.length(); i++) { char cp = p.charAt(i-1); b[0] = cp=='*' && a[0]; for (int j=1; j<=s.length(); j++) { if (cp=='*') { b[j] = a[j] || b[j-1]; } else if (cp=='?') { b[j] = a[j-1]; } else { b[j] = cp==s.charAt(j-1) && a[j-1]; } } a = b; } return a[s.length()]; }
8
public Car driverCar() { return new Audo(); }
0
public void sort (int[] a){ if (a==null || a.length<=1){ return; } int max = a[0]; for (int i=1; i<a.length; i++){ max = Math.max(max, a[i]); } int ten=1; int[] aux = new int[a.length]; int [] count = new int[10]; while (ten<=max){ for (int i=0; i<a.length; i++){ count[(a[i]/ten)%10]++; } for (int i=1; i<count.length; i++){ count[i]+=count[i-1]; } for (int i=a.length-1; i>=0; i--){ aux[--count[(a[i]/ten)%10]] = a[i]; } for (int i=0; i<a.length; i++){ a[i] = aux[i]; } for (int i=0; i<count.length; i++){ count[i]=0; } ten*=10; } }
9
public void test_getValue_long_long() { assertEquals(0, iField.getValue(0L, 567L)); assertEquals(12345678 / 90, iField.getValue(12345678L, 567L)); assertEquals(-1234 / 90, iField.getValue(-1234L, 567L)); assertEquals(INTEGER_MAX / 90, iField.getValue(LONG_INTEGER_MAX, 567L)); try { iField.getValue(LONG_INTEGER_MAX + 1L, 567L); fail(); } catch (ArithmeticException ex) {} }
1
public void fitBoundsToLayers() { int width = 0; int height = 0; Rectangle layerBounds = new Rectangle(); for (int i = 0; i < layers.size(); i++) { getLayer(i).getBounds(layerBounds); if (width < layerBounds.width) width = layerBounds.width; if (height < layerBounds.height) height = layerBounds.height; } bounds.width = width; bounds.height = height; }
3
public void polynomialFit(int n){ if(this.nAnalyteConcns<(n+2))throw new IllegalArgumentException("Method polynomialFit(" + n +") requres at least " + (n+2) + " data points; only " + this.nAnalyteConcns + " were supplied"); this.methodUsed = 2; this.sampleErrorFlag = true; this.degSet = true; this.polyDegree = n; this.titleOne = "Polynomial fitting: r = c[0] + c[1].a + c[1].a^2 + ... + c[n].a^n; degree (n) = " + n; if(!this.setDataOneDone)this.setDataOne(); super.polynomial(n); for(int i=0; i<this.nInterp; i++){ this.calculatedResponses[i] = 0.0; for(int j=0; j<=n; j++){ this.calculatedResponses[i] += super.best[j]*Math.pow(this.interpolationConcns[i], j); } } if(!this.supressPlot)this.plott(); this.curveCheck(this.methodIndices[this.methodUsed]); }
5
public final FEMFormatter putParams(final Iterable<? extends FEMFunction> params) throws NullPointerException, IllegalArgumentException { final Iterator<? extends FEMFunction> iter = params.iterator(); if (iter.hasNext()) { FEMFunction item = iter.next(); if (iter.hasNext()) { this.putIndent().put("(").putBreakInc().putFunction(item); do { item = iter.next(); this.put(";").putBreakSpace().putFunction(item); } while (iter.hasNext()); this.putBreakDec().put(")"); } else { this.put("(").putBreakInc().putFunction(item).putBreakDec().put(")"); } } else { this.put("()"); } return this; }
5
String get_rep2() { switch( action_type ) { case SS_ACTION_CUT: return "CUT(" + arg + ")"; case SS_ACTION_ZERO: return "ZERO(" + arg + ")"; case SS_ACTION_RANGE_ERROR: return "RANGE_ERROR"; case SS_ACTION_RESTART: return "RESTART"; case SS_ACTION_DONE: return "DONE"; case SS_ACTION_NEGATE: return "NEGATE"; default: return "HUH???"; } }
6
@Override public float contains( int x, int y ) { if( boundaries.contains( x, y ) ){ return 1.f; } else{ return 0.f; } }
1
@EventHandler public void onPlayerInteract (PlayerInteractEvent event) { Player player = event.getPlayer(); Block block = event.getClickedBlock(); if (event.getAction() == Action.LEFT_CLICK_BLOCK && player.getItemInHand().getType() == Material.BLAZE_ROD) { player.setMetadata("x1", new FixedMetadataValue(plugin, block.getX())); player.setMetadata("y1", new FixedMetadataValue(plugin, block.getY())); player.setMetadata("z1", new FixedMetadataValue(plugin, block.getZ())); player.sendMessage(ChatColor.GOLD + "Selected first point."); event.setCancelled(true); return; } if (event.getAction() == Action.RIGHT_CLICK_BLOCK && player.getItemInHand().getType() == Material.BLAZE_ROD) { player.setMetadata("x2", new FixedMetadataValue(plugin, block.getX())); player.setMetadata("y2", new FixedMetadataValue(plugin, block.getY())); player.setMetadata("z2", new FixedMetadataValue(plugin, block.getZ())); player.sendMessage(ChatColor.GOLD + "Selected second point."); event.setCancelled(true); return; } if (event.getAction() == Action.RIGHT_CLICK_BLOCK && (block.getTypeId() == 63 || block.getTypeId() == 68)) { Sign sign = (Sign) block.getState(); String[] lines = sign.getLines(); if (lines.length > 2) { if (!sign.getLine(0).equalsIgnoreCase("[replace]")) return; String name = sign.getLine(1); prRegion pr = new prRegion(); pr.place(name, block.getWorld()); event.setCancelled(true); player.sendMessage(ChatColor.GREEN + "Done!"); return; } } }
9
public void handle(CollisionEvent event) { ArrayList<OperateShape> shapes = event.getTarget(); for (MoveShape shape : shapes) { if (shape instanceof Circle) { switch (event.getEdgeType()) { case RIGHT: shape.setAngle(180 - (shape.getAngle())); break; case LEFT: shape.setAngle(180 - (shape.getAngle())); break; case TOP: shape.setAngle( - (shape.getAngle())); break; case BOTTOM: shape.setAngle( - (shape.getAngle())); break; case LEFTSIDEOFTHEBAR: shape.setY(670); shape.setAngle(30 - (shape.getAngle())); shape.setSpeed(8); case MIDDLEOFTHEBAR: shape.setY(670); shape.setAngle(-(shape.getAngle())); shape.setSpeed(7); case RIGHTSIDEOFTHEBAR: shape.setY(670); shape.setAngle( - 30 - (shape.getAngle())); shape.setSpeed(8); } } } }
9
public static JDialog createDialog(Component c, String title, boolean modal, final JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) throws HeadlessException { final Color initialColor = chooserPane.getColor(); Window window = getWindowForComponent(c); final JDialog ret; if (window instanceof Frame) { ret = new JDialog((Frame) window, title, modal); } else { ret = new JDialog((Dialog) window, title, modal); } ret.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); Locale locale = window.getLocale(); String okString = UIManager.getString("ColorChooser.okText", locale); String cancelString = UIManager.getString("ColorChooser.cancelText", locale); String resetString = UIManager.getString("ColorChooser.resetText", locale); ret.setLayout(new BorderLayout()); ret.add(chooserPane, BorderLayout.CENTER); JPanel buttons = new JPanel(); buttons.setLayout(new FlowLayout(FlowLayout.RIGHT)); ret.add(buttons, BorderLayout.SOUTH); JButton okB = new JButton(okString); okB.getAccessibleContext().setAccessibleDescription(okString); okB.setActionCommand("OK"); okB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ret.setVisible(false); } }); if (okListener != null) { okB.addActionListener(okListener); } buttons.add(okB); final JButton cancelB = new JButton(cancelString); cancelB.getAccessibleContext().setAccessibleDescription(cancelString); // The following few lines are used to register esc to close the dialog Action cancelKeyAction = new AbstractAction() { private static final long serialVersionUID = 6313146026842426365L; public void actionPerformed(ActionEvent e) { cancelB.doClick(); } }; KeyStroke cancelKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); InputMap inputMap = cancelB .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); ActionMap actionMap = cancelB.getActionMap(); if (inputMap != null && actionMap != null) { inputMap.put(cancelKeyStroke, "cancel"); actionMap.put("cancel", cancelKeyAction); } // end esc handling cancelB.setActionCommand("cancel"); cancelB.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ret.setVisible(false); } }); if (cancelListener != null) { cancelB.addActionListener(cancelListener); } buttons.add(cancelB); JButton resetB = new JButton(resetString); resetB.getAccessibleContext().setAccessibleDescription(resetString); resetB.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { chooserPane.setColor(initialColor); } }); buttons.add(resetB); if (JDialog.isDefaultLookAndFeelDecorated()) { boolean supportsWindowDecorations = UIManager.getLookAndFeel() .getSupportsWindowDecorations(); if (supportsWindowDecorations) { ret.getRootPane().setWindowDecorationStyle( JRootPane.COLOR_CHOOSER_DIALOG); } } ret.applyComponentOrientation(((c == null) ? ret.getRootPane() : c) .getComponentOrientation()); ret.pack(); ret.setLocationRelativeTo(c); ret.getRootPane().setDefaultButton(okB); ret.getAccessibleContext().setAccessibleDescription(title); return ret; }
8
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(qMainUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(qMainUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(qMainUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(qMainUI.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 qMainUI().setVisible(true); } }); }
6
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((code == null) ? 0 : code.hashCode()); return result; }
1
public void func_73707_e() { if (!field_73713_b.isFile()) { return; } BufferedReader bufferedreader; try { bufferedreader = new BufferedReader(new FileReader(field_73713_b)); } catch (FileNotFoundException filenotfoundexception) { throw new Error(); } try { do { String s; if ((s = bufferedreader.readLine()) == null) { break; } if (!s.startsWith("#")) { BanEntry banentry = BanEntry.func_73688_c(s); if (banentry != null) { field_73715_a.func_76116_a(banentry.func_73684_a(), banentry); } } } while (true); } catch (IOException ioexception) { Logger.getLogger("Minecraft").log(Level.SEVERE, "Could not load ban list", ioexception); } }
7
public static void main(String [] args) { try { //System.err.println("DBThread Runs"); Class.forName("com.mysql.jdbc.Driver"); connect = DriverManager.getConnection("jdbc:mysql://localhost/cdr_data?user=root&password=root"); preparedStatement = connect.prepareStatement("select Directory_Number from annuaire_tel WHERE SDA =? "); preparedStatement.setString(1, "055"); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { System.err.println(rs.getString("Directory_Number")); } } catch (SQLException e) { Logger.getLogger(ConcurrentDataInsertTest.class.getName()).log(Level.SEVERE, null, e); } catch (ClassNotFoundException ex) { Logger.getLogger(DBInsert.class.getName()).log(Level.SEVERE, null, ex); } }
3
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed PrintWriter settings = null; try { settings = new PrintWriter(System.getProperty("user.home")+"/Documents/AcerX/settingsYM.txt", "UTF-8"); settings.println(jTextField1.getText()); settings.println(jTextField2.getText()); if(jCheckBox1.isSelected()) { settings.println("true"); ChatBox.muted = true; } else { settings.println("false"); ChatBox.muted = false; } dispose(); } catch (FileNotFoundException ex) { Logger.getLogger(Preferences.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(Preferences.class.getName()).log(Level.SEVERE, null, ex); } finally { settings.close(); } }//GEN-LAST:event_jButton1ActionPerformed
3
private static boolean isDigit(int c) { return '0' <= c && c <= '9'; }
1
public boolean displayModesMatch(DisplayMode m1, DisplayMode m2){ if(m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight()){ return false; } if(m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth()){ return false; } if(m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate()){ return false; } return true; }
8
private JSONWriter append(String string) throws JSONException { if (string == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(string); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); }
7
public boolean isOnBorder(int x, int y) { if (selectedX + x >= tileWidth) { return true; } else if (vectorToId(selectedX + x, selectedY) >= inv.getItems() .size()) { return true; } return false; }
2
private void initLog4J() { logger.setLevel(Level.INFO); Logger.getRootLogger().addAppender(new ConsoleAppender(new PatternLayout("%d %-5p [%c] - %m%n"))); try { if(logfile != null) Logger.getRootLogger().addAppender(new FileAppender(new PatternLayout("%d %-5p [%c] - %m%n"), logfile)); } catch (IOException e) { logger.error("Could not write log file", e); } catch (SecurityException e) { logger.debug("Could not create log file. Running in an applet."); } }
3
public void setOptions(String[] options) throws Exception { setDebug(Utils.getFlag('D', options)); String classIndex = Utils.getOption('c', options); if (classIndex.length() != 0) { if (classIndex.toLowerCase().equals("last")) { setClassIndex(0); } else if (classIndex.toLowerCase().equals("first")) { setClassIndex(1); } else { setClassIndex(Integer.parseInt(classIndex)); } } else { setClassIndex(0); } String classifyIterations = Utils.getOption('l', options); if (classifyIterations.length() != 0) { setClassifyIterations(Integer.parseInt(classifyIterations)); } else { setClassifyIterations(10); } String prob = Utils.getOption('p', options); if (prob.length() != 0) { setP( Double.parseDouble(prob)); } else { setP(-1); } //throw new Exception("A proportion must be specified" + " with a -p option."); String seedString = Utils.getOption('s', options); if (seedString.length() != 0) { setSeed(Integer.parseInt(seedString)); } else { setSeed(1); } String dataFile = Utils.getOption('t', options); if (dataFile.length() != 0) { setDataFileName(dataFile); } else { throw new Exception("An arff file must be specified" + " with the -t option."); } String trainSize = Utils.getOption('T', options); if (trainSize.length() != 0) { setTrainSize(Integer.parseInt(trainSize)); } else { setTrainSize(-1); } //throw new Exception("A training set size must be specified" + " with a -T option."); String classifierName = Utils.getOption('W', options); if (classifierName.length() != 0) { setClassifier(AbstractClassifier.forName(classifierName, Utils.partitionOptions(options))); } else { throw new Exception("A learner must be specified with the -W option."); } }
9
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (active(request)) //if there is an active user { if (request.getRequestURI().equals(request.getContextPath() + "/followers")) //if there is no string after followers/ { List<User> followerList = followMain.getFollowers(user.getEmail()); if (followerList.size() == 0) //if the user doesn't have any followers request.setAttribute("noFollowers", "You do not have any followers"); request.setAttribute("followerList", followerList); request.setAttribute("followers", followerList.size()); request.getRequestDispatcher("/followers.jsp").forward(request, response); return; } else //there is a string after followers/ { request.getRequestDispatcher("/404.jsp").forward(request, response); return; } } else //there is not an active user { response.sendRedirect(request.getContextPath() + "/login"); return; } }
3
public static String getString(String expression) { String result = ""; for (int i = 0; i < expression.length(); i++) { if (expression.charAt(i) == '#') { result += getRandomString(true, false, false, 1); } else if (expression.charAt(i) == '*') { result += getRandomString(true, true, true, 1); } else if (expression.charAt(i) == '>') { result += getRandomString(false, false, true, 1); } else if (expression.charAt(i) == '<') { result += getRandomString(false, true, false, 1); } else if (expression.charAt(i) == '$') { result += getRandomString(false, true, true, 1); } else if (expression.charAt(i) == ']') { result += getRandomString(true, true, false, 1); } else if (expression.charAt(i) == '[') { result += getRandomString(true, false, true, 1); } } return result; }
8
private static final int method3961(Class70 class70, int i) { if (i != 2) aFloatArray9797 = null; if (Class342.aClass70_4247 == class70) return 2; if (class70 == Class285_Sub2.aClass70_8503) return 0; if (Class318_Sub1_Sub2.aClass70_8737 != class70) { if (Class348_Sub40_Sub39.aClass70_9485 == class70) return 3; } else return 1; throw new IllegalArgumentException(); }
5
private boolean isChar(char c) { return 'a' <= c && 'z' >= c || 'A'<=c && 'Z' >=c || '0' <= c && '9' >= c ; }
5
private static int digitSum(String bigInt){ int sum = 0; for(char c:bigInt.toCharArray()){ sum+=Integer.parseInt(""+c); } return sum; }
1
String convert(String s, int nRows){ if(nRows<=1) return s; StringBuffer result = new StringBuffer(); if(s.length()==0) return ""; for(int i=0;i<nRows;i++){ for(int j=0,index =i; index<s.length();j++,index=(2*nRows-2)*j+i){ result.append(s.charAt(index)); if(i==0||i==nRows-1) continue; if(index+(nRows- i-1)*2 < s.length()) result.append(s.charAt(index+(nRows- i-1)*2)); } } return result.toString(); }
7
@Test public void testGetAllTiles() { System.out.println("getAllTiles"); Tile newtile=new Tile(); Tile[][] store=new Tile[3][3]; for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ store[i][j]=newtile; } } map.MapArray=store; Tile[][] expResult = store; Tile[][] result = map.getAllTiles(); assertArrayEquals(expResult, result); }
2
public static AbstractCarriage generateFreightCarriage() { AbstractCarriage carriage = null; try { carriage = FreightCarriageFactory.newCarriage( new RandomEnum<FreightCarType>(FreightCarType.class).random(), generateId(), generateNumber(), generateMaxCapacity()); ((AbstractFreightCarriage) carriage).setCurCapacity(random .nextInt(((AbstractFreightCarriage) carriage).getMaxCapacity())); } catch (CarriageException e) { LOG.fatal("Cant't generete new FreightCarriage", e); System.exit(1); } LOG.debug("New FreightCarriage was generaed: " + carriage); return carriage; }
1
public int getLowestX() { int x = a[0]; if(b[0] < x) { x = b[0]; } if(c[0] < x) { x = c[0]; } if(d[0] < x) { x = d[0]; } return(x); }
3
private void checkVersion(int[] requiredVersion) throws IOException { if (m_registryVersion == null) { m_registryVersion = requiredVersion; } else if (requiredVersion != null) { for (int i = 0; i < requiredVersion.length; i++) { if (m_registryVersion[i] != requiredVersion[i]) { throw new RegistryFormatException("incorrect registry version no"); } } } }
4
private static int max(int[] histogram) { int max = 0; for (int i = 0; i < histogram.length; i++) { if (histogram[i] > max) max = histogram[i]; } return max; }
2
protected void addNewChat() { String chatContent = chatInputJTxa.getText(); DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm a"); Date date = new Date(); if (!(chatContent == null || chatContent.isEmpty())) { //chatHistoryDLM.addElement(userLogin.getName() + " (" + dateFormat.format(date) + "):"+ chatContent); // public Chat(String content, String timeAdded, int userId, int debateId) { Chat c = new Chat(chatContent, dateFormat.format(date), userLogin.getName(), debateSelected.getId()); if (chat.addChat(fileName, c) ) { chatInputJTxa.setText(""); getChatHistory(); } } }
3
private void validate() { if (majorVersion()<0 || year()<0 || month()<0 || minorVersion()<0) throw new IllegalArgumentException("No components of a version" + " number may be negative."); if (year() > 99) throw new IllegalArgumentException("The second number in a" + " version number must be a year value from 0 to 99."); if (month() < 1 || month() > 12) throw new IllegalArgumentException("The third number in a" + " version number must be a month value from 1 to 12."); if (letterSuffix == null) throw new IllegalArgumentException("The letter suffix of a" + " version number may not be null. If it is meant to be" + " blank, use an empty string for this value."); if (!letterSuffix.matches("[a-zA-Z_\\-]*")) throw new IllegalArgumentException("The letter suffix of a" + " version number must be either blank or composed only" + " of letters, numbers, hyphens, and underscores."); }
9
public static void main(String[] args) { HelloWorld hw = new HelloWorld(); hw.printHelloWorld(); System.out.println(args[0]); System.out.println(args[1]); System.out.println(args[2]); HelloWorldWithMethod hw2 = new HelloWorldWithMethod(); hw2.hello(); HelloWorldWithAttrib hw3 = new HelloWorldWithAttrib("Salut!"); hw3.hello(); int sum = 0; for (int i=0; i<100; i++) { sum += i; } System.out.println(sum); ArrayStack as = new ArrayStack(10); as.push(10); try { as.pop(); } catch (EmptyException ex) { Logger.getLogger(Tp1.class.getName()).log(Level.SEVERE, null, ex); } LinkedStack ls = new LinkedStack(); System.out.println(ls.isEmpty()); ls.push(new Integer(100)); ls.push(new Integer(50)); try { System.out.println(ls.pop()); System.out.println(ls.pop()); } catch (EmptyException ex) { Logger.getLogger(Tp1.class.getName()).log(Level.SEVERE, null, ex); } }
3
public boolean displayModesMatch(DisplayMode mode1, DisplayMode mode2) { if (mode1.getWidth() != mode2.getWidth() || mode1.getHeight() != mode2.getHeight()) { return false; } if (mode1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode1.getBitDepth() != mode2.getBitDepth()) { return false; } if (mode1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode1.getRefreshRate() != mode2.getRefreshRate()) { return false; } return true; }
8
private void closeIfNotKeepAlive() { if ("close".equals(getFirstHeader("connection"))) { requestClose(false); } }
1
private int[] getSq() { int startRow = row/SQ_SIZE * SQ_SIZE; int startCol = col/SQ_SIZE * SQ_SIZE; int[] sqNumbers = new int[SIZE]; int count = 0; for (int i = 0; i < SQ_SIZE; i++) { for (int j = 0; j < SQ_SIZE; j++) { sqNumbers[count] = grid[startRow + i][startCol + j]; count++; } } return sqNumbers; }
2
public static void beginButtonAction() { running = true; factories = new ArrayList<Factory>(); customers = new ArrayList<Customer>(); factoryCount = maxFactoryCount; customerCount = maxCustomerCount; factoryClock = new Signal(); factoryStore = new FactoryStoreSignal(); // construct store customerStore = new StoreCustomerSignal(); store = new Store(factoryStore, customerStore); customerStore.registerStore(store); // construct factories for (int i=0; i<factoryCount; i++) { factories.add(new Factory(i+1, factoryClock, factoryStore, 10000)); } // construct customers for (int i=0; i<customerCount; i++) { customers.add(new Customer(i+1, customerStore)); } // start threads for (int i=0; i<factories.size(); i++) { (new Thread(factories.get(i))).start(); } (new Thread(store)).start(); for (int i=0; i<customers.size(); i++) { (new Thread(customers.get(i))).start(); } EventQueue.invokeLater(new Runnable() { public void run() { try { displayFrame = new DisplayFrame(); displayFrame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); }
5
private void cargarSetPrueba(){ DefaultTableModel temp = (DefaultTableModel) this.tablaSetPruebas.getModel(); String csvFile = "dataset/diabetes_prueba.csv"; BufferedReader br = null; String line = ""; String cvsSplitBy = ","; try { double maximo0 = normalizacion.obtenerMaximo(0, csvFile); double maximo1 = normalizacion.obtenerMaximo(1, csvFile); double maximo2 = normalizacion.obtenerMaximo(2, csvFile); double maximo3 = normalizacion.obtenerMaximo(3, csvFile); double maximo4 = normalizacion.obtenerMaximo(4, csvFile); double maximo5 = normalizacion.obtenerMaximo(5, csvFile); double maximo6 = normalizacion.obtenerMaximo(6, csvFile); double maximo7 = normalizacion.obtenerMaximo(7, csvFile); double minimo0 = normalizacion.obtenerMinimo(0, csvFile); double minimo1 = normalizacion.obtenerMinimo(1, csvFile); double minimo2 = normalizacion.obtenerMinimo(2, csvFile); double minimo3 = normalizacion.obtenerMinimo(3, csvFile); double minimo4 = normalizacion.obtenerMinimo(4, csvFile); double minimo5 = normalizacion.obtenerMinimo(5, csvFile); double minimo6 = normalizacion.obtenerMinimo(6, csvFile); double minimo7 = normalizacion.obtenerMinimo(7, csvFile); br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { String[] patron = line.split(cvsSplitBy); if(normalizar.equals("NO")){ Object nuevo[]= {patron[0], patron[1], patron[2], patron[3], patron[4], patron[5], patron[6], patron[7], "-"}; temp.addRow(nuevo); }else if(normalizar.equals("MAX")){ Object nuevo[]= {String.valueOf(Double.valueOf(patron[0])/maximo0), String.valueOf(Double.valueOf(patron[1])/maximo1), String.valueOf(Double.valueOf(patron[2])/maximo2), String.valueOf(Double.valueOf(patron[3])/maximo3), String.valueOf(Double.valueOf(patron[4])/maximo4), String.valueOf(Double.valueOf(patron[5])/maximo5), String.valueOf(Double.valueOf(patron[6])/maximo6), String.valueOf(Double.valueOf(patron[7])/maximo7), "-" }; temp.addRow(nuevo); }else if(normalizar.equals("MAX/MIN")){ Object nuevo[]= {String.valueOf((double)(Double.valueOf(patron[0])-minimo0)/(double)(maximo0-minimo0)), String.valueOf((double)(Double.valueOf(patron[1])-minimo1)/(double)(maximo1-minimo1)), String.valueOf((double)(Double.valueOf(patron[2])-minimo2)/(double)(maximo2-minimo2)), String.valueOf((double)(Double.valueOf(patron[3])-minimo3)/(double)(maximo3-minimo3)), String.valueOf((double)(Double.valueOf(patron[4])-minimo4)/(double)(maximo4-minimo4)), String.valueOf((double)(Double.valueOf(patron[5])-minimo5)/(double)(maximo5-minimo5)), String.valueOf((double)(Double.valueOf(patron[6])-minimo6)/(double)(maximo6-minimo6)), String.valueOf((double)(Double.valueOf(patron[7])-minimo7)/(double)(maximo7-minimo7)), "-" }; temp.addRow(nuevo); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IndexOutOfBoundsException e) { System.out.println("Error accediendo al csv prueba"); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }
9
public File askForTargetArchive(File def) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new FileFilter() { public boolean accept(File f) { if(f.isDirectory()) return true; else{ Algorithm algs[] = model.getAlgorithms(); for(int i = 0; i < algs.length; i++){ if(f.getName().endsWith(algs[i].getSuffix())){ return true; } } return false; } } public String getDescription() { return "jFileCrypt-Archive"; } }); chooser.setSelectedFile(def); int returnVal = chooser.showSaveDialog(view); if(returnVal == JFileChooser.APPROVE_OPTION) { return chooser.getSelectedFile(); } else { return null; } }
4
public void removePreferences(String module) { String prefix = module + '.'; ArrayList<String> list = new ArrayList<>(); int length = prefix.length(); for (Enumeration<Object> keys = mPrefs.keys(); keys.hasMoreElements();) { String key = (String) keys.nextElement(); if (key.startsWith(prefix)) { list.add(key.substring(length)); } } if (!list.isEmpty()) { startBatch(); mDirty = true; for (String keyToRemove : list) { removePreference(module, keyToRemove); } endBatch(); } }
4
public void addPropertyTablesToJoin(ObjectStack propertyStack) { boolean propertiesFound = false; List<ObjectRepresentation> allReps = propertyStack .getAllRepresentations(); for (ObjectRepresentation rep : allReps) { if (!propertiesFound) { if (rep.getNonNullPropertyCount() > 0 || rep.isArray()) { propertiesFound = true; } } if (propertiesFound) { if (rep.isArray()) { addPropertyTableToJoin(NameGenerator.getArrayTablename(adapter), rep.getAsName()); } else { addPropertyTableToJoin(rep.getTableName(), rep.getAsName()); } } } }
6
private void produceHumidity() { Perlin noise = new Perlin(); try { noise.setOctaveCount(octaves); } catch (Exception e) {e.printStackTrace();} noise.setFrequency(frequency); noise.setSeed(seed); if (details) System.out.println("Noise produced."); int dimx = MyzoGEN.DIMENSION_X * chunksX; int dimy = MyzoGEN.DIMENSION_Y * chunksY; NoiseMap tempMap = null; try { tempMap = new NoiseMap(dimx, dimy); NoiseMapBuilderPlane builder = new NoiseMapBuilderPlane(); builder.setSourceModule(noise); builder.setDestNoiseMap(tempMap); builder.setDestSize(dimx, dimy); builder.setBounds(0, chunksX * 4, 0, chunksY*4); builder.build(); } catch (Exception e) {e.printStackTrace();} for (int ii = 0; ii < dimx; ii++) { for (int jj = 0; jj < dimy; jj++) { MyzoGEN.getOutput().setHumidity(new Point(ii, jj), Utils.roundToDecimals(tempMap.getValue(ii, jj), 4)); } } if (ioflags.SAVE) { ImageCafe image = null; try { RendererImage render = new RendererImage(); image = new ImageCafe(dimx, dimy); render.setSourceNoiseMap(tempMap); render.setDestImage(image); render.clearGradient(); Gradient gradient = new Gradient("humidity"); for (int i = 0; i < gradient.gradientPoints.length; i++) { render.addGradientPoint(gradient.gradientPoints[i], gradient.gradientColors[i]); } render.render(); } catch (ExceptionInvalidParam ex) { ex.printStackTrace(); } BufferedImage im = Utils.imageCafeToBufferedImage(dimx, dimy, image); Utils.saveImage(im, "output/"+name+"/overviews/humidity_overview.png"); if (details) System.out.println("Humidity overview produced. It can be found in: output/"+name+"/overviews/"); } }
9
private PreparedStatement createQuery(String prefix, Connection con, Set<Key> keys, int count) { List<Object> parms = new ArrayList<>(); List<Column> pk = getPk(); StringBuilder sb = new StringBuilder(); int rowIndex = 0; for (Key key : new HashSet<>(keys)) { keys.remove(key); // Remove as we go if (sb.length() > 0) { sb.append("\tOR "); } sb.append("("); for (int pkIdx = 0; pkIdx < pk.size(); pkIdx++) { if (pkIdx > 0) { sb.append(" AND "); } Column col = pk.get(pkIdx); sb.append("["); sb.append(col.getColumnName()); sb.append("]=?"); // Grab the value of the parameter Object val = key.get(pkIdx); parms.add(val); } sb.append(")\n"); if (++rowIndex >= count) { break; } } String sql = String.format("%s\nFROM [%s]\nWHERE %s", prefix, getName(), sb.toString()); try { PreparedStatement stmt = con.prepareStatement(sql); for (int i = 0; i < parms.size(); i++) { Object javaVal = parms.get(i); Object sqlVal = javaToSql(javaVal); stmt.setObject(i + 1, sqlVal); } return stmt; } catch (Exception ex) { throw new RuntimeException("Error creating select query!", ex); } }
7
public static void saveMeetingRoom(MeetingRoom mr){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { conn.setAutoCommit(false); PreparedStatement stmnt = conn.prepareStatement("INSERT INTO MeetingRooms(floor, seats_amount, name) VALUES(?,?,?)"); stmnt.setInt(1, mr.getFloor()); stmnt.setInt(2, mr.getSeatsAmount()); stmnt.setString(3, mr.getName()); stmnt.execute(); conn.commit(); conn.setAutoCommit(true); }catch(SQLException e){ System.out.println("Insert fail: " + e); } }
4
static void browseDump(ClassFile cls) { String[] ix = cls.browseInterfaces(); String[] fx = cls.browseFields(); String[] mx = cls.browseMethods(); String[][] mf = cls.browseFieldrefs(); String[][] mm = cls.browseMethodrefs(); String[][] mi = cls.browseInterfaceMethodrefs(); String[][] ic = cls.browseInnerClasses(); System.out.println("+++++++++++++++++++++++"); System.out.println(" SourceFile = " + cls.browseSourceFile()); System.out.println(" class = " + cls.browseClass()); System.out.println(" extends = " + cls.browseSuper()); for (int i = 0; i < ix.length; i++) System.out.println(" implements = " + ix[i]); for (int i = 0; i < fx.length; i++) System.out.println(" field = " + fx[i]); for (int i = 0; i < mx.length; i++) { System.out.println(" method = " + mx[i]); for (int j = 0; j < mf[i].length; j++) System.out.println(" fields = " + mf[i][j]); for (int j = 0; j < mm[i].length; j++) System.out.println(" methods = " + mm[i][j]); for (int j = 0; j < mi[i].length; j++) System.out.println(" interfaces = " + mi[i][j]); } for (int i = 0; i < ic.length; i++) { System.out.println("innerClass[" + i + "] = " + ic[i][0]); System.out.println("outerClass[" + i + "] = " + ic[i][1]); System.out.println("innerName[" + i + "] = " + ic[i][2]); } }
7
@Override public void handleRequest(int request) { if (request == 1) { System.out.println("ConcreteHandlerA handleRequest " + request); } else if (mSuccessor != null) { mSuccessor.handleRequest(request); } }
2
private List<DBObject> ConstructYahooObj(List<String> finvizReturn, String Ticker) { LinkedList<DBObject> MongoObjList = new LinkedList<DBObject>(); int headerFlag = 0; String[] headers = new String[]{""}; for (String finvizValues : finvizReturn){ if (headerFlag == 0){ //extract headers headers = finvizValues.split(","); headerFlag++; }else { BasicDBObject YahooEntry = new BasicDBObject(); String[] YahooRec = finvizValues.split(","); int counter = 0; for (String header : headers){ if(NumericalUtil.isDouble(YahooRec[counter])){ YahooEntry.put(header,Double.parseDouble(YahooRec[counter])); }else{ YahooEntry.put(header,YahooRec[counter]); } counter ++; } YahooEntry.put("Ticker",Ticker); //MongoObjList.add(new BasicDBObject("$set",YahooEntry)); MongoObjList.add(YahooEntry); } } return MongoObjList; }
4
public Transaction transactionWLockOnVar(int index) { for (Transaction t: locks.keySet()) { ArrayList<Lock> lockListT = locks.get(t); for (Lock lock: lockListT) { if(lock.getIndex()==index && lock.isWrite()) { return t; } } } return null; }
4
public List<Position> getPath3(int x, int y){ try{ Pattern pattern= Pattern.compile("(\\d+)"); List<Position> posList= new ArrayList<>(); int X,Y = 0; if(posicao(pacmanX(),pacmanY())){ String str=intelFant(x, y, pacmanX(), pacmanY(),"path"); Matcher matcher=pattern.matcher(str); while(matcher.find()){ X=Integer.parseInt(matcher.group()); if(matcher.find()){ Y=Integer.parseInt(matcher.group()); } posList.add(new Position(X,Y)); } } return posList; } catch(NumberFormatException ex){ return new ArrayList<>(); } }
4
private static void copyToZip(ZipOutputStream output, File from, boolean keepManifest) throws IOException { ZipFile input = new ZipFile(from); Enumeration<? extends ZipEntry> entries = input.entries(); while (entries.hasMoreElements()) { try { ZipEntry entry = entries.nextElement(); if (!keepManifest && entry.getName().equals("META-INF/MANIFEST.MF")) { // Continue with the next entry in case it is the manifest. continue; } output.putNextEntry(entry); InputStream inputStream = input.getInputStream(entry); byte[] buffer = new byte[4096]; while (inputStream.available() > 0) { output.write(buffer, 0, inputStream.read(buffer, 0, buffer.length)); } inputStream.close(); output.closeEntry(); } catch (ZipException e) { // Assume that the error is the warning about a duplicate and // ignore it. // I know that this is evil... } } input.close(); }
6
private String ExtractIdFromLink(String partialLink) { int beginIdx = partialLink.indexOf(ID_PREFIX)+ID_PREFIX.length(); int endIdx = partialLink.indexOf("-", beginIdx); String id = endIdx != -1 ? partialLink.substring(beginIdx, endIdx) : partialLink.substring(beginIdx); return id; }
1
public boolean onItemUse(ItemStack var1, EntityPlayer var2, World var3, int var4, int var5, int var6, int var7) { if(var7 != 1) { return false; } else { ++var5; BlockBed var8 = (BlockBed)Block.bed; int var9 = MathHelper.floor_double((double)(var2.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3; byte var10 = 0; byte var11 = 0; if(var9 == 0) { var11 = 1; } if(var9 == 1) { var10 = -1; } if(var9 == 2) { var11 = -1; } if(var9 == 3) { var10 = 1; } if(var3.isAirBlock(var4, var5, var6) && var3.isAirBlock(var4 + var10, var5, var6 + var11) && var3.isBlockNormalCube(var4, var5 - 1, var6) && var3.isBlockNormalCube(var4 + var10, var5 - 1, var6 + var11)) { var3.setBlockAndMetadataWithNotify(var4, var5, var6, var8.blockID, var9); var3.setBlockAndMetadataWithNotify(var4 + var10, var5, var6 + var11, var8.blockID, var9 + 8); --var1.stackSize; return true; } else { return false; } } }
9
private static float commonOverPrintAlpha(float alpha) { // if alpha is already present we reduce it and we minimize // it if it is already lower then our over paint. This an approximation // only for improved screen representation. if (alpha != 1.0f && alpha > OVERPAINT_ALPHA) { alpha -= OVERPAINT_ALPHA; } else if (alpha < OVERPAINT_ALPHA) { // alpha = 0.1f; } else { alpha = OVERPAINT_ALPHA; } return alpha; }
3
@Override public String toString() { StringBuffer sb = new StringBuffer(28); if (hardwareType != HTYPE_ETHER) { // append hType only if it is not standard ethernet sb.append(this.hardwareType).append("/"); } for (int i=0; i<hardwareAddress.length; i++) { if ((hardwareAddress[i] & 0xff) < 0x10) sb.append("0"); sb.append(Integer.toString(hardwareAddress[i] & 0xff, 16)); if (i<hardwareAddress.length-1) { sb.append(":"); } } return sb.toString(); }
4
@Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); String keyEvent = ""; if (key == KeyEvent.VK_LEFT) { keyEvent = "VK_LEFT"; } if (key == KeyEvent.VK_RIGHT) { keyEvent = "VK_RIGHT"; } if(keyEvent != "" && started){ SnakeUserMessage SUM = new SnakeUserMessage(Player, keyEvent); try { sendMessage(enc.encode(SUM)); } catch (JSONException e1) { e1.printStackTrace(); } } }
5
final private void createAndAddVariable(String variableRepresentation) throws InvalidInputException { //ignore empty variable names if (variableRepresentation.trim().equals("")) { return; } //find the variable and then add it to the tokenized expression for (int variableIndex = 0; variableIndex < this.m_variables.size(); variableIndex++) { Variable aVariable = this.m_variables.get(variableIndex); if (variableRepresentation.equals(aVariable.getRepresentation())) { this.m_tokenizedExpression.addElement(new Variable(variableRepresentation, aVariable.getValue())); return; } } throw new InvalidInputException(Text.CALCULATIONS.getInvalidNumberMessage(variableRepresentation)); }
3
public void setHelloWorld(String helloWorld) { this.helloWorld = helloWorld; }
0
static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
7
public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; }
6
public void loadMap(String s) { try { InputStream in = getClass().getResourceAsStream(s); BufferedReader br = new BufferedReader(new InputStreamReader(in)); numCols = Integer.parseInt(br.readLine()); numRows = Integer.parseInt(br.readLine()); map = new int[numRows][numCols]; width = numCols * tileSize; height = numRows * tileSize; xmin = GamePanel.WIDTH - width; xmax = 0; ymin = GamePanel.HEIGHT - height; ymax = 0; String delims = "\\s+"; for (int row = 0; row < numRows; row++) { String line = br.readLine(); String[] tokens = line.split(delims); for (int col = 0; col < numCols; col++) { map[row][col] = Integer.parseInt(tokens[col]); } } } catch (Exception e) { e.printStackTrace(); } }
3
public String ex_string(String buff, int item, String sep) { String result = null; int ptr1 = 0; int ptr2 = 0; int cpt = 0; int next = 0; if ( item > 1) while ( cpt < item -1) { ptr1 = buff.indexOf(sep, next); //search the tag preceeding area cpt++; next = ptr1+1; } else ptr1 = 0; //1st item requested : point on buffer begin if(ptr1 == 0) ptr2 = buff.indexOf(sep); //search the 1st tag following array else ptr2 = buff.indexOf(sep, ptr1 + sep.length()); //search the 2nd tag following array if((ptr1 < (buff.length() - sep.length())) && (ptr1 >= 0)) { //previous tag found if(ptr1 > 0) ptr1 += sep.length(); //skip the separator itself //1st sep found if( (ptr2 < (buff.length() - sep.length())) && (ptr2 > ptr1) ) { //2nd found, too ! if( (ptr2 - 1) == ptr1 ) { /* //empty result result = ""; */ // single digit result = buff.substring(ptr1, ptr2); } else { result=buff.substring(ptr1, ptr2); } } else { //2nd not found : take the rest of line result = buff.substring(ptr1, buff.length()); } } else { //no separator found : return empty string ! result = ""; } return result; }
9
synchronized public static void setEarthRadius(double radius, LengthUnit unit) { EARTH_RADIUS = new double[LengthUnit.values().length]; for (LengthUnit toUnit : LengthUnit.values()) { EARTH_RADIUS[toUnit.ordinal()] = unit.convertTo(toUnit, radius); } }
1
private void idCmbxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_idCmbxActionPerformed String id = ""; tableModel.setRowCount(0); if (idCmbx.getSelectedItem() != null && idCmbx.getSelectedIndex() != 0) { id = idCmbx.getSelectedItem().toString(); if (!id.equals("No such employee..")) { try { ResultSet rst = controller.searchWorkingDetByID(id); Employee employee = empController.searchEmployeeByID(id); if (employee != null) { nameCmbx.setSelectedItem(employee.getFirstName() + " " + employee.getLastName()); desiTxt.setText(employee.getDesignation()); } imageLbl.setIcon(employee.getImage()); if (rst.first()) { do { String date = rst.getDate(1).toString(); String time = rst.getTime(2).toString(); String classID = rst.getString(3); tableModel.addRow(new String[]{date, time, classID}); } while (rst.next()); } } catch (SQLException | ClassNotFoundException ex) { } } } }//GEN-LAST:event_idCmbxActionPerformed
7
public void updateTheory(final List<Rule> rulesToAdd, // final Set<String> rulesToDelete, // Map<String, List<Rule>> oldNewRuleMapping) throws TheoryException { if (null != rulesToDelete) { for (String ruleLabel : rulesToDelete) { removeRule(ruleLabel); } } if (null != rulesToAdd) { for (Rule rule : rulesToAdd) { addRule(rule); } } if (null != oldNewRuleMapping && oldNewRuleMapping.size() > 0) { // System.out.println(oldNewRuleMapping.toString()); try { updateSuperiorityMapping(oldNewRuleMapping); } catch (TheoryException e) { throw new TheoryException("Old-New rule mapping exception appeared while updating the theory!", e); } } }
7
@SuppressWarnings("deprecation") public void testConstructor_RP_RP6() throws Throwable { YearMonthDay dt1 = new YearMonthDay(2005, 7, 17); TimeOfDay dt2 = new TimeOfDay(10, 20, 30, 40); try { new Period(dt1, dt2); fail(); } catch (IllegalArgumentException ex) {} }
1
public Report cleanupDirs(Report report) throws IOException { List<Path> newDirectories = new ArrayList<Path>(); for (Path path : report.getNewDirectories()) { newDirectories.add(path); } Collections.sort(newDirectories, new Comparator<Path>() { @Override public int compare(Path o1, Path o2) { return o1.toString().length() > o2.toString().length() ? -1 : 1; } }); for (Path targetDir : newDirectories) { if (isDirectoryEmpty(targetDir)) { if (!isDirectoryEmpty(source.resolve(target.relativize(targetDir)))) { if (!this.isSimulationMode) { Files.delete(targetDir); } report.removeDirectory(targetDir); } } } return report; }
6
@Override public void run() { int i = 0; for (String line : linesToCheck) { try { boolean recursive = false; if (DNSChecker.CheckedReflectors.containsKey(line)) { continue; } int size = Integer.parseInt(line.split(" ")[2]); try { recursive = DNSChecker.isRecursive(line); if (recursive) { i++; if (i > 100) { System.out.println("+100 Reflectors!"); i=0; } } } catch (Exception e) { } DNSChecker.CheckedReflectors.put(line, new Couple(size, recursive)); } catch (Exception e) { } } workFinish = true; }
6
private boolean correctSyntax(String format, String assemblyLine, ArrayList<String> relevantOperands) { String[] formatSplit = format.split("\\s+"); int noOfTokens = formatSplit.length; String regex = ".*"; int i = 1; int i2 = 0; for (String str : formatSplit) { if(i > 1 && i <= noOfTokens) regex += "\\s+"; String[] strSplit = str.split("((?=^[,]*)|(?<=^[,]*))|((?=[,]*$)|(?<=[,]*$))"); for(String str2: strSplit){ if(!str2.isEmpty()){ if(str2.equals(",")) regex += ","; else{ regex += "("+ Pattern.quote(relevantOperands.get(i2))+")"; i2++; } } } i++; } boolean legitSyntax = Pattern.matches(regex, assemblyLine); return legitSyntax; }
6
public UpdateModule(){ setAuthor("Sinrel Group"); setName("GameUpdater"); setVersion("1.0.0"); }
0
public int getY() { return y; }
0
private void checkPoint() { // Ball went past left side if (ball.getX() + ball.getWidth() / 2 < 0) { ballSleep = Calendar.getInstance().getTimeInMillis() + POINT_DELAY; ball.setPos(paddles[0].getX() + paddles[0].getWidth() / 2 + ball.getWidth() / 2, paddles[0].getY()); ball.setXSpeed(- ball.getXSpeed()); scores[1]++; } // Ball went past right side if (ball.getX() - ball.getWidth() > WINDOW_DIMENSIONS[0]) { ballSleep = Calendar.getInstance().getTimeInMillis() + POINT_DELAY; ball.setPos(paddles[1].getX() - paddles[1].getWidth() / 2 - ball.getWidth() / 2, paddles[1].getY()); ball.setXSpeed(- ball.getXSpeed()); scores[0]++; } // A player has generated enough points to win, thus closing the application if (scores[1] >= POINTS_TO_WIN) { active = false; JOptionPane.showMessageDialog(null, "Player 2 has won with " + POINTS_TO_WIN + " points!"); System.exit(0); } else if (scores[0] >= POINTS_TO_WIN) { active = false; JOptionPane.showMessageDialog(null, "Player 1 has won with " + POINTS_TO_WIN + " points!"); System.exit(0); } }
4
public int getColumnCount() { // TODO Auto-generated method stub return 0; }
0
public static String[] searchHistory(Integer ID,String changed, String name) { Database db = dbconnect(); String [] Array = null; try { String query = ("SELECT * FROM ticket_history WHERE ticket_TID = ? " + "AND changed_on = ? AND column_name = ?"); db.prepare(query); db.bind_param(1, ID.toString()); db.bind_param(2, changed); db.bind_param(3, name); ResultSet rs = db.executeQuery(); while(rs.next()) { Array = new String[]{rs.getString(rs.getMetaData().getColumnName(2)), rs.getString(rs.getMetaData().getColumnName(3)), rs.getString(rs.getMetaData().getColumnName(4))}; } db.close(); } catch (SQLException e) { Error_Frame.Error(e.toString()); } return Array; }
2
public void update() { if (listBadgeNames.getSelectedValue() == null) { return; } clearErrors(); if (txtBadgeName.isMessageDefault() || txtBadgeName.getText().isEmpty()) { Util.setError(lblNameError, "Advancement name cannot be left blank"); return; } for (int i = 0; i < listBadgeNames.getModel().getSize(); ++i) { String advancementName = (String) listBadgeNames.getModel().getElementAt(i); if (advancementName.equalsIgnoreCase(txtBadgeName.getText()) && !txtBadgeName.getText().equals(listBadgeNames.getSelectedValue().toString())) { Util.setError(lblNameError, "Advancement name already exists"); return; } } Advancement advancement = LogicAdvancement.findByName(listBadgeNames.getSelectedValue().toString()); if (advancement == null) { return; } if (txtImagePath.isMessageDefault()) { advancement.setImgPath(""); } else { advancement.setImgPath(txtImagePath.getText()); } advancement.setName(txtBadgeName.getText()); List<Requirement> requirementList = validateRequirements(advancement.getId()); if (requirementList == null) return; Util.processBusy(pnlBadgeConf.getBtnUpdate(), true); // when editing requirements may need to check who is using them LogicRequirement.updateList(requirementList, advancement.getId(), RequirementTypeConst.ADVANCEMENT.getId()); LogicAdvancement.update(advancement); Util.processBusy(pnlBadgeConf.getBtnUpdate(), false); reloadData(); }
9
public Terrain getTerrainAt(int x, int y) { System.out.println("TERRAIN AT "+x+" "+y+" "+tmap[x][y]); if (tmap[x][y].ground) { return tmap[x][y]; } for (int i=x-1; i<=x+1; ++i) { for (int j=y-1; j<=y+1; ++j) { //System.out.println("TERRAIN AT "+i+" "+j+" "+tmap[i][j]); try { if (tmap[i][j].ground) { return tmap[i][j]; } } catch (Exception e) {} } } return Terrain.GRASS; }
5
public void lueFunktio() throws IllegalStateException { if (!merkkiOsaTunnusta()) { throw new IllegalStateException(); } int aloituspaikka = paikka; siirryTunnuksenLoppuun(); Funktio lisattava = kirjasto.haeFunktio( syote.substring(aloituspaikka, paikka)); if (lisattava == null || !funktiotaSeuraaSulku()) { throw new IllegalStateException(); } lauseke.lisaaFunktioJaAvaaLohko(lisattava); }
3
public String createEnvironment() { // returns a string containing a fully written out environment for this // datasource StringBuilder sb = new StringBuilder(); sb.append( TAB + TAB + "<environment id=\"" + this.environmentName + "\">\n" ); sb.append( TAB + TAB + TAB + "<transactionManager type=\"" + this.transactionManager + "\" />\n" ); sb.append( TAB + TAB + TAB + "<dataSource type=\"" + this.typeOfDataSource + "\">\n" ); if ( this.dataSource.equals( "" ) == false ) { sb.append( TAB + TAB + TAB + TAB + "<property name=\"data_source\" value=\"" + this.dataSource + "\" />\n" ); } if ( this.driver.equals( "" ) == false ) { sb.append( TAB + TAB + TAB + TAB + "<property name=\"driver\" value=\"" + this.driver + "\" />\n" ); } if ( this.url.equals( "" ) == false ) { sb.append( TAB + TAB + TAB + TAB + "<property name=\"url\" value=\"" + this.url + "\" />\n" ); } sb.append( createLoginInfo() ); sb.append( TAB + TAB + TAB + "</dataSource>\n" ); sb.append( TAB + TAB + "</environment>\n" ); return sb.toString(); }
3
public String getToken() { if (token == null) { token = out.toString(); } return token; }
1
private GraphModel groupHelpVertexes(GraphModel newGraph, int K) { ArrayList<GraphPoint> p = new ArrayList<GraphPoint>(); for (Vertex v : newGraph.getVertexArray()) { // Alle Punkte, die 'noch zu Relokalisieren' sind (Hilfspunkte) // werden gesammelt... if (v.getLabel().equals("noch zu Relokalisieren")) p.add(v.getLocation()); } GraphPoint[] pArray = p.toArray(new GraphPoint[p.size()]); // ... und an den KMeans uebergeben.... Cluster[] c = LloydKMeans.cluster(pArray, K); // ... um die Clustermenge zu erhalten. for (Cluster cluster : c) { // Fuer jeden Cluster wird ein Mittelpunktvertex angelegt... Vertex centerVertex = new Vertex(); centerVertex.setLabel(""); centerVertex.setLocation(cluster.getCenter()); newGraph.addVertex(centerVertex); for (GraphPoint pointC : cluster.getMembers()) { // ... und alle Hilfspunkte des Clusters auf diesen umgelegt... for (int i = 0; i < newGraph.getVerticesCount(); i++) { if (newGraph.getVertex(i).getLocation().equals(pointC)) { // ... indem sie im Graph gefunden werden,... Vertex actualVertex = newGraph.getVertex(i); Iterator<Vertex> list = newGraph.getNeighbors(actualVertex).iterator(); Vertex a = list.next(); Vertex b = list.next(); // ...ihre Verbindungen mit ihren Nachbarn fuer den // Mittelpunktvertex uebernommen werden... Edge edge = new Edge(centerVertex, b); edge.setWeight(newGraph.getEdge(a, actualVertex).getWeight()); if (newGraph.isEdge(edge.source, edge.target)) { // Sollte eine Kante bereits im Graph vorkommen, // werden nur die gewichte erhoeht. newGraph.getEdge(edge.source, edge.target).setWeight( newGraph.getEdge(edge.source, edge.target).getWeight() + edge.getWeight()); } else { newGraph.addEdge(edge); } Edge baseEdge = new Edge(a, centerVertex); baseEdge.setWeight(newGraph.getEdge(actualVertex, b).getWeight()); if (newGraph.isEdge(baseEdge.source, baseEdge.target)) { // Sollte eine Kante bereits im Graph vorkommen, // werden nur die gewichte erhoeht. newGraph.getEdge(baseEdge.source, baseEdge.target) .setWeight(newGraph.getEdge(baseEdge.source, baseEdge.target).getWeight() + baseEdge.getWeight()); } else { newGraph.addEdge(baseEdge); } // ... und der alte Vertex mit seinen Kanten entfernt // wird. newGraph.removeEdge(newGraph.getEdge(a, actualVertex)); newGraph.removeEdge(newGraph.getEdge(actualVertex, b)); newGraph.removeVertex(actualVertex); i--;// Die Vertexmenge in der for-Schleife wird // reduziert. // Somit wuerde nicht Vertex_(i+1) sondern // Vertex_(i+2) // als naechster Vertex betrachtet werden. Um // gegenzusteuern i--. break; } } } } return newGraph; }
8
public static void saveHouseInt() { String output ="savedata/"+idString+".houseaninteger"; try { PrintWriter fout=new PrintWriter(new FileWriter(output)); if(VERSION.equals("Peaches")) fout.println("PDAE"+idString); else fout.println("CDAE"+idString); fout.println(houseInt); fout.close(); System.out.println("House Integer saved."); } catch(Exception ignored){} }
2
public String[][] productdata(JXTreeTable treeTable, Boolean[] bflag) { String[][] datas = new String[treeTable.getRowCount()][treeTable .getColumnCount() + 1]; for (int i = 0; i < treeTable.getRowCount(); i++) { for (int j = 0; j <= treeTable.getColumnCount(); j++) { if (j < treeTable.getColumnCount()) { datas[i][j] = treeTable.getValueAt(i, j).toString(); } else { if (bflag[i]) { datas[i][j] = "1"; } else { datas[i][j] = "0"; } } } } return datas; }
4
public boolean isFPSStatus() { if(frame == null) buildGUI(); return fpsStatus.isSelected(); }
1
private boolean zzRefill() throws java.io.IOException { /* first: make room (if you can) */ if (zzStartRead > 0) { System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead-zzStartRead); /* translate stored positions */ zzEndRead-= zzStartRead; zzCurrentPos-= zzStartRead; zzMarkedPos-= zzStartRead; zzStartRead = 0; } /* is the buffer big enough? */ if (zzCurrentPos >= zzBuffer.length) { /* if not: blow it up */ char newBuffer[] = new char[zzCurrentPos*2]; System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); zzBuffer = newBuffer; } /* finally: fill the buffer with new input */ int numRead = zzReader.read(zzBuffer, zzEndRead, zzBuffer.length-zzEndRead); if (numRead > 0) { zzEndRead+= numRead; return false; } // unlikely but not impossible: read 0 characters, but not at end of stream if (numRead == 0) { int c = zzReader.read(); if (c == -1) { return true; } else { zzBuffer[zzEndRead++] = (char) c; return false; } } // numRead < 0 return true; }
5
private static void indent(StringBuffer buf, int depth) { for (int i = 0; i < depth; i++) { buf.append("\t"); } }
1
@Basic @Column(name = "FES_ID_FUNCIONARIO") public Integer getFesIdFuncionario() { return fesIdFuncionario; }
0
@Override public Object getValueAt(int row, int col) { switch (col) { case 0: return entidades.get(row).getUsuario().getNome(); case 1: return entidades.get(row).getDataInicio().toLocalDate().toString(); case 2: return entidades.get(row).getDataTermino().toLocalDate().toString(); case 3: return entidades.get(row).getDetalhes(); default: throw new RuntimeException("coluna inválida"); } }
4
public void setStage() { //Initial set up before any level starts //System.out.println("size=" + brickList.size()); brickList = null; brickList = new ArrayList<Brick>(); powerList.clear(); for (int i = 0; i < stage.length; i++) { //System.out.println(stage[i][0]); if (stage[i][0] == currentLevel) { Brick b = new Brick(stage[i][1], stage[i][2], stage[i][3]); //create brick //System.out.println("yes"); brickList.add(b); //add brick to list } else { if (stage[i][0] > currentLevel) { break; } } } //System.out.println("size=" + brickList.size()); //below code assignes each power twice to random bricks, total 10 powers. Random randnum = new Random(); for (int i = 0; i < 2; i++) { brickList.get(randnum.nextInt(brickList.size())).setPower(1); //super ball } for (int i = 0; i < 2; i++) { brickList.get(randnum.nextInt(brickList.size())).setPower(2); //big puddle } for (int i = 0; i < 2; i++) { brickList.get(randnum.nextInt(brickList.size())).setPower(3); //small puddle } for (int i = 0; i < 2; i++) { brickList.get(randnum.nextInt(brickList.size())).setPower(4); //bomb } for (int i = 0; i < 2; i++) { brickList.get(randnum.nextInt(brickList.size())).setPower(5); //weapon } }
8
public void doit(JvstCodeGen gen, Bytecode bytecode, ASTList args) throws CompileError { int num = gen.getMethodArgsLength(args); if (num != dimension) throw new CompileError(Javac.proceedName + "() with a wrong number of parameters"); gen.atMethodArgs(args, new int[num], new int[num], new String[num]); bytecode.addOpcode(opcode); if (opcode == Opcode.ANEWARRAY) bytecode.addIndex(index); else if (opcode == Opcode.NEWARRAY) bytecode.add(index); else /* if (opcode == Opcode.MULTIANEWARRAY) */ { bytecode.addIndex(index); bytecode.add(dimension); bytecode.growStack(1 - dimension); } gen.setType(arrayType); }
3
private int getConstructorType(StructuredBlock body) { /* * A non static constructor must begin with a call to another * constructor. Either to a constructor of the same class or to the * super class */ InstructionBlock ib; if (body instanceof InstructionBlock) ib = (InstructionBlock) body; else if (body instanceof SequentialBlock && (body.getSubBlocks()[0] instanceof InstructionBlock)) ib = (InstructionBlock) body.getSubBlocks()[0]; else return 0; Expression superExpr = ib.getInstruction().simplify(); if (!(superExpr instanceof InvokeOperator) || superExpr.getFreeOperandCount() != 0) return 0; InvokeOperator superInvoke = (InvokeOperator) superExpr; if (!superInvoke.isConstructor() || !superInvoke.isSuperOrThis()) return 0; Expression thisExpr = superInvoke.getSubExpressions()[0]; if (!isThis(thisExpr, clazzAnalyzer.getClazz())) return 0; if (superInvoke.isThis()) return 2; else return 1; }
9
public String getPopupWarning() { if (this.description == null) return null; if (this == SNAPSHOT) return "Are you sure you want to enable development builds?\nThey are not guaranteed to be stable and may corrupt your world.\nYou are advised to run this in a separate directory or run regular backups."; if (this == OLD_BETA) return "These versions are very out of date and may be unstable. Any bugs, crashes, missing features or\nother nasties you may find will never be fixed in these versions.\nIt is strongly recommended you play these in separate directories to avoid corruption.\nWe are not responsible for the damage to your nostalgia or your save files!"; if (this == OLD_ALPHA) return "These versions are very out of date and may be unstable. Any bugs, crashes, missing features or\nother nasties you may find will never be fixed in these versions.\nIt is strongly recommended you play these in separate directories to avoid corruption.\nWe are not responsible for the damage to your nostalgia or your save files!"; return null; }
4
private Representation execute() { Representation repr = null; // Get context Context context = getContext(); // generate the DatabaseRequest DataSetApplication datasetApp = (DataSetApplication) getApplication(); DataSetExplorerUtil dsExplorerUtil = new DataSetExplorerUtil(datasetApp, getRequest(), getContext()); this.corotIDParam = this.getModel().getParameterByName("corotIdCol"); this.raParam = this.getModel().getParameterByName("raCol"); this.decParam = this.getModel().getParameterByName("decCol"); // Get request parameters if (datasetApp.getConverterChained() != null) { datasetApp.getConverterChained().getContext().getAttributes().put("REQUEST", getRequest()); } // Get DatabaseRequestParameters DatabaseRequestParameters params = dsExplorerUtil.getDatabaseParams(); DataSet ds = datasetApp.getDataSet(); createQueryCorotID(params,ds); DatabaseRequest databaseRequest = DatabaseRequestFactory.getDatabaseRequest(params); try { if (params.getDistinct()) { databaseRequest.createDistinctRequest(); }else { databaseRequest.createRequest(); } // Recuperation dans la base du fichiers fits context.getLogger().log(Level.INFO, "nbr de resultat : "+databaseRequest.getCount()); while (databaseRequest.nextResult()) { Record rec = databaseRequest.getRecord(); this.raValue = Double.parseDouble(OrderResourceUtils.getInParam(raParam, rec).getValue().toString()); this.decValue = Double.parseDouble(OrderResourceUtils.getInParam(decParam, rec).getValue().toString()); Map a = getDataModel(); repr = new GeoJsonRepresentation(a); } } catch (Exception e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL,e.getMessage()); } return repr; }
4
public SaveRunnable(MainClass mainClass) { FileUtil.checkAutoSaveConfigYAML(); SavedMSG = LangUtil.getSavedMSG(); SavingMSG = LangUtil.getSavingMSG(); if(!SavingMSG.equals("%NONE%")){ saving = true; } if(!SavedMSG.equals("%NONE%")){ saved = true; } }
2
public void decoder(int[] octets_data){ /* if (taille == 3){ capt_distri = (octets_data[0] & 0xC0) >>> 6; sonar_droit = (octets_data[0] & 0x20) >>> 5; sonar_gauche = (octets_data[0] & 0x10) >>> 4; etat_match = (octets_data[0] & 0x8) >>> 3; couleur_table = (octets_data[0] & 0x4) >>> 2; type_balle = (octets_data[0] & 0x3); angle_high = octets_data[1]; angle_low = octets_data[2]; } */ }
0
public void setVisible(boolean visible) { if(frame == null) buildGUI(); frame.setVisible(visible); }
1
public void close() { if (bdl != null) { bdl.close(); } if (server != null) { server.close(); } isConnected = false; boolean retry = true; while (retry) { try { join(); retry = false; break; } catch (InterruptedException ex) { } } System.out.println("Server stopped."); }
4