text
stringlengths
14
410k
label
int32
0
9
public synchronized void connect() throws SQLException { if (connection == null) connection = DriverManager.getConnection(jdbcUrl, username, password); }
1
private int nextBid(int currentBid) { // Loop for all of our bid values. for (int i = 0; i < LEGAL_BID_VALUES.length; i++) { // If we found the bid if (LEGAL_BID_VALUES[i] == currentBid) { // If it's the last bid, return -1. if (LEGAL_BID_VALUES[i] == LEGAL_BID_VALUES[LEGAL_BID_VALUES.length - 1]) return -1; // Otherwise return the next bid return LEGAL_BID_VALUES[i + 1]; } } return -2; // Shouldn't ever happen }
3
@Override public void write(String filename, Solution output) { //On met en parametre que le nom du fichier, l'extension est obligatoirement txt pour un fichier texte final String chemin = "./"+filename+".txt"; //On creer notre nouveau fichier objet final File fichier =new File(chemin); try { // Creation du fichier fichier .createNewFile(); // creation d'un writer final FileWriter writer = new FileWriter(fichier); try { writer.write("Bienvenue dans le fichier de sortie de l'application, voici les solutions :"+"\n"); //On ecrit nos solutions dans le fichier txt writer.write(output.getPath()+"\n"+"\n"); writer.write("Fin des solutions"); } finally { // quoiqu'il arrive, on ferme le fichier writer.close(); } } catch (Exception e) { System.out.println("Impossible de creer le fichier"); } }
1
@SuppressWarnings("deprecation") public void testFactoryFieldDifference2() throws Throwable { YearMonthDay ymd = new YearMonthDay(2005, 4, 9); try { Period.fieldDifference(ymd, (ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} try { Period.fieldDifference((ReadablePartial) null, ymd); fail(); } catch (IllegalArgumentException ex) {} }
2
@Override public void actionPerformed(ActionEvent e) { boolean selection = false; DocUtils.buttonDoClick(e); wordProcessor.area1.requestFocus(); String text = wordProcessor.area1.getSelectedText(); int start = 0, length = 0; if (text != null) { selection = true; start = wordProcessor.area1.getSelectionStart(); length = text.length(); } if (wordProcessor.underline.isSelected()) { try { if (selection) { wordProcessor.doc.remove(start, length); wordProcessor.doc.insertString(start, text, wordProcessor.doc.getStyle("underline")); } } catch (BadLocationException ble) { ble.printStackTrace(); } } else { try { if (selection) { wordProcessor.doc.remove(start, length); wordProcessor.doc.insertString(start, text, wordProcessor.doc.getStyle("regular")); } } catch (BadLocationException ble) { ble.printStackTrace(); } } }
6
@Override public void paint(Graphics graphics){ if (image==null) return; super.paint(graphics); graphics.drawImage(getBitmap(), offset, 0, null); if (offset==0){ return; } if (offset<0) { graphics.drawImage(getBufferedImage((SwingBitmap) image.getNext().getBitmap()), image.getBitmap().getWidth() + offset, 0, null); } if (offset>0) { graphics.drawImage(getBufferedImage((SwingBitmap) image.getPrev().getBitmap()), offset - image.getBitmap().getWidth(), 0, null); } }
4
public String getLNDString(int position, boolean showAllHex) { byte[] LND = null; String LNDString = ""; String contactName = ""; try { worker.getResponse(worker.select(DatabaseOfEF.DF_TELECOM.getFID())); LND = worker.readRecord(position, worker.getResponse(worker.select(DatabaseOfEF.EF_LND.getFID()))); contactName = contactName.concat(Converter.bytesToHex(LND).substring(0, 3 * (LND.length - 14))); if (!contactName.matches("[FF ]+")) { for (int i = 0; i < LND.length - 14; i++) { LNDString = LNDString.concat(Character.toString((char) (int) LND[i])); } LNDString = LNDString.concat("; "); } if (LND[LND.length - 14 + 1] == (byte) 0x91) { LNDString = LNDString.concat("00"); } for (int i = LND.length - 14 + 2; i <= LND.length - 14 + LND[LND.length - 14]; i++) { String b = Converter.byteToHex(LND[i]); String c = Converter.swapString(b); LNDString = LNDString.concat(c); } } catch (Exception ex) { Logger.getLogger(CardManager.class.getName()).log(Level.SEVERE, null, ex); } if (showAllHex) { return Converter.bytesToHex(LND); } else { return LNDString; } }
6
public static List<Element> insertionSort(List<Element> list) { int i, j, temp, size = list.size(); for (i = 1; i < size; i++) { j = i; while (j > 0 && list.get(j).getValue() < list.get(j - 1).getValue()) { Collections.swap(list, j, j - 1); // Update number of sitches /* temp = list.get(j).getNumberOfInversion(); list.get(j).setNumberOfInversion(++temp); temp = list.get(j - 1).getNumberOfInversion(); list.get(j - 1).setNumberOfInversion(++temp); */ // Update Comparison when loop condition is true temp = list.get(j).getNumberOfComparison(); list.get(j).setNumberOfComparison(++temp); temp = list.get(j - 1).getNumberOfComparison(); list.get(j - 1).setNumberOfComparison(++temp); j--; } // Update Comparison when loop condition is false temp = list.get(i).getNumberOfComparison(); list.get(i).setNumberOfComparison(++temp); temp = list.get(j).getNumberOfComparison(); list.get(j).setNumberOfComparison(++temp); } return list; }
3
private void checkOut() { String orderNum = ""; boolean isUnique = false; Statement st = null; ResultSet rs = null; ResultSet rs1 = null; Random generator = new Random(); while (isUnique == false) { int randInt = generator.nextInt(999999); orderNum = Integer.toString(randInt); String checkUnique = "select o.order_number from Orders o where o.order_number = '" + orderNum + "'"; try { st = custConn.getConnection().createStatement(); rs = st.executeQuery(checkUnique); if(rs.next() == false) isUnique = true; } catch (Exception e) { System.out.println("Error generating number"); } } try { String getStockNums = "select sc.stock_number from Shopping Cart sc where sc.customer_ID = '" + customerID + "'"; rs = st.executeQuery(getStockNums); while (rs.next()) { int month = getCurrentMonth(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); java.util.Date date = new java.util.Date(); String finalDate = dateFormat.format(date); String stockNum = rs.getString("stock_number"); int finalQty = rs.getInt("finalQty"); String priceOfItem = "select p.Price from Product p where p.stock_number= '" + stockNum + "'"; rs1 = st.executeQuery(priceOfItem); double price = rs1.getInt("Price"); double finalPrice = finalQty*price; //find out discount percentage String findDiscount = "select c.status from Customer c where c.customer_ID = '" + customerID + "'"; double discountInt = 0; rs1.next(); String discount = rs1.getString("status"); if (discount.equals("New")) discountInt = .10; else if (discount.equals("Green")) discountInt = .10; else if (discount.equals("Silver")) discountInt = .05; else if (discount.equals("Gold")) discountInt = .10; String newOrder = "insert into Orders(order_number, month, sale_date, customer_ID, stock_number, customer_Discount, final_cost, quantity) values('" + orderNum + "'," + month + ",'" + finalDate + "','" + customerID + "','" + stockNum + "'," + discountInt + "," + finalPrice + "," + finalQty + ")"; rs1 = st.executeQuery(newOrder); } //for every stock_number in shopping cart //order number is newly calculated order number //month is current month //sale date is current sale date //customer_ID is current customer ID //final cost is the total cost of all items //quantity is the total number of that product sold //Delete rows in shopping cart for that user } catch (Exception e) { System.out.println("Error checking out"); } }
9
private boolean jj_3_59() { if (jj_3R_75()) return true; return false; }
1
public static EquipmentStatusEnumeration fromValue(String v) { for (EquipmentStatusEnumeration c: EquipmentStatusEnumeration.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); }
2
public static void main(String[] args){ LinkedList<String> list = new LinkedList<>(); list.add("aaa"); list.add("bbb"); list.add("ccc"); list.add("ddd"); list.add("eee"); list.add("fff"); list.add("ggg"); list.add("hhh"); list.add("iii"); ListIterator<String> itr; for (itr = list.listIterator(); itr.hasNext();){ System.out.println(itr.next()); } System.out.print("\n"); for (; itr.hasPrevious();){ String item = itr.previous(); System.out.println(item); if(item.startsWith("a") || item.startsWith("e") || item.startsWith("i") || item.startsWith("o") || item.startsWith("u")){ itr.remove(); } } System.out.print("\n"); for (; itr.hasNext();){ String item = itr.next(); System.out.println(item); } }
8
public String getName() { return name; }
0
static void setAccessible(final AccessibleObject ao, final boolean accessible) { if (System.getSecurityManager() == null) ao.setAccessible(accessible); else { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { ao.setAccessible(accessible); return null; } }); } }
1
public void help(CommandSender sender, String[] args) { // get page name from aguments String name = convertArgsToPageName(args); // replace - with space String userFriendlyName = name.replace("-", " "); // check existance if(!config.hasPage(name)) { // send configured error message String msg = config.getMessagePageNotFound(); msg = convertColors(msg); msg = msg.replace("%page%", userFriendlyName); sender.sendMessage(msg); return; } // get permission by page name String perm = Permission.convertPageNameToPermission(name); // check permission if(!sender.hasPermission(Permission.ALLPAGES.toString()) && !sender.hasPermission(perm)) { // send configured error message String msg = config.getMessageNoPagePermission(); msg = convertColors(msg); msg = msg.replace("%page%", userFriendlyName); sender.sendMessage(msg); return; } List<String> lines = config.getPage(name); // send configured title String title = config.getMessagePageTile(); title = convertColors(title); title = title.replace("%page%", userFriendlyName); sender.sendMessage(title); // send lines of page for (String line : lines) { line = convertColors(line); line = line.replace("%page%", userFriendlyName); sender.sendMessage(line); } }
4
public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_SPACE) { fire(); } if (key == KeyEvent.VK_A) { dx = -1; } if (key == KeyEvent.VK_D) { dx = 1; } if (key == KeyEvent.VK_W) { dy = -1; } if (key == KeyEvent.VK_S) { dy = 1; } }
5
@Override public String toString() { String str = "========== " +forme.getNom() +" ==========\n" +frame.toString() +'\n' +forme.toString(); return str; }
0
@SuppressWarnings({"ToArrayCallWithZeroLengthArrayArgument"}) public void testKeySet() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap<String> map = new TObjectIntHashMap<String>(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Set<String> keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); Object[] keys_obj_array = keyset.toArray(); int count = 0; Iterator<String> iter = keyset.iterator(); while ( iter.hasNext() ) { String key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_obj_array[count], key ); count++; } String[] keys_array = keyset.toArray( new String[0] ); count = 0; iter = keyset.iterator(); while ( iter.hasNext() ) { String key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_array[count], key ); count++; } keys_array = keyset.toArray( new String[keyset.size()] ); count = 0; iter = keyset.iterator(); while ( iter.hasNext() ) { String key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_array[count], key ); count++; } keys_array = keyset.toArray( new String[keyset.size() * 2] ); count = 0; iter = keyset.iterator(); while ( iter.hasNext() ) { String key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_array[count], key ); count++; } assertNull( keys_array[keyset.size()] ); Set<String> other = new HashSet<String>( keyset ); assertFalse( keyset.retainAll( other ) ); other.remove( keys[5] ); assertTrue( keyset.retainAll( other ) ); assertFalse( keyset.contains( keys[5] ) ); assertFalse( map.containsKey( keys[5] ) ); keyset.clear(); assertTrue( keyset.isEmpty() ); }
6
default void log(String str){ System.out.println("I1 logging::"+str); }
0
void increaseLeftScore(int score) { setLeftScore(getLeftScore() + score); }
0
public static boolean useDefconsmethodP(MethodSlot method) { if ((!method.methodFunctionP) && ((List)(Stella.$CURRENT_STELLA_FEATURES$.get())).membP(Stella.KWD_USE_COMMON_LISP_CONSES)) { { Surrogate testValue000 = method.slotOwner; if (testValue000 == Stella.SGT_STELLA_CONS) { return (true); } else if (testValue000 == Stella.SGT_STELLA_STANDARD_OBJECT) { if (Stella_Class.lookupSlot(((Stella_Class)(Stella.SGT_STELLA_CONS.surrogateValue)), method.slotName).slotOwner == Stella.SGT_STELLA_CONS) { return (false); } else { return (true); } } else if (testValue000 == Stella.SGT_STELLA_OBJECT) { { Surrogate testValue001 = Stella_Class.lookupSlot(((Stella_Class)(Stella.SGT_STELLA_CONS.surrogateValue)), method.slotName).slotOwner; if ((testValue001 == Stella.SGT_STELLA_CONS) || (testValue001 == Stella.SGT_STELLA_STANDARD_OBJECT)) { return (false); } else { return (true); } } } else { } } } return (false); }
8
public void visualiserModele(){ System.out.println("Controleur::visualiserModele()") ; System.out.println("") ; System.out.println("------------------ Locations ----------------------------") ; for(Location location : this.modele.getLocations()){ System.out.println(location) ; } System.out.println("------------------- Clients -----------------------------") ; for(Client client : this.modele.getClients()){ System.out.println(client) ; } System.out.println("------------------ Véhicules ----------------------------") ; for(Vehicule vehicule : this.modele.getVehicules()){ System.out.println(vehicule) ; } System.out.println("") ; }
3
public String getLast() { return last; }
0
public YamlManager(PermWriter project) { this.project = project; }
0
public Nose(Ship parent){ this.parent = parent; xorigin = parent.getX(); yorigin = parent.getY(); engine1X = parent.engine1.engine.get(0).x; engine2X = parent.engine2.engine.get(0).x; engineTopY = parent.engine1.engine.get(0).y; double lengthPoints = parent.speed; double radiusPoints = (parent.speed/4)+parent.power; if(lengthPoints <=1 ){ noseLength = 1; //(lengthPoints - 1) / (1000 - 1) * (6-1) + 1; }else{ noseLength = parent.map(lengthPoints, 1, 1000, 2, 6); } if(radiusPoints <=2){ noseRadius = 1;//(lengthPoints - 1) / (1000 - 1) * (6-1) + 1; }else{ noseRadius = parent.map(radiusPoints, 1, 1000, 2, 12); } noseLength *= Ship.PIXEL_PER_UNIT; noseRadius *= Ship.PIXEL_PER_UNIT; noseX = xorigin; noseY = engineTopY - noseLength; noseLine1 = new Line2D.Double(engine1X, engineTopY, noseX, noseY); noseLine2 = new Line2D.Double(engine2X, engineTopY, noseX, noseY); saucer = new Ellipse2D.Double(noseX-(noseRadius/2), noseY-(noseRadius/2), noseRadius, noseRadius); }
2
private static JPanel getPanel(MainModel mainModel){ JPanel p = new JPanel(); ScoreModel h = mainModel.getScoreModel(); p.setLayout(new GridLayout(0, 1, 0, resources.MenuLookAndFeel.getGap())); if (h.existsNoScore()){ JLabel l = new JLabel(Translator.getMenuString("noScoreExplain")); l.setFont(resources.MenuLookAndFeel.getLargeFont()); p.add(l); } else { for (int a=0; a<h.getLenght(); a++){ String s = a+1 + ". "; if (h.getScore(a).length() < 1){ s+=Translator.getMenuString("noScore"); } else { s+=h.getScore(a) + "p "; } if (h.getName(a).length() < 1){ s+=Translator.getMenuString("noName"); } else { s+=h.getName(a) + ""; } JLabel l = new JLabel(s); l.setFont(resources.MenuLookAndFeel.getLargeFont()); p.add(l); } } return p; }
4
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; int times = 1; StringBuilder br = new StringBuilder(); while ((line = in.readLine()) != null) { if (line.equals("0")) break; n = Integer.parseInt(line); int arr[] = new int[ n ]; for (int i = 0; i < arr.length; i++) { arr[i] = Integer.parseInt(in.readLine()); } res = new int[ (((n - 1) * (n)) / 2) ]; int k = 0; for (int i = 0; i < arr.length; i++) { for (int j = i + 1; j < arr.length; j++) { if (i != j) { res[k] = arr[i] + arr[j]; k++; } } } Arrays.sort(res); int q = Integer.parseInt(in.readLine()); // System.out.println("case " + times + ":"); br.append("Case " + times + ":").append("\n"); for (int i = 0; i < q; i++) { int date = Integer.parseInt(in.readLine()); if (date > res[res.length - 1]) { br.append("Closest sum to " + date + " is " + res[res.length - 1] + ".").append("\n"); // System.out.println("Closest sum to " + date + " is " + // res[res.length - 1] + "."); } else if (date < res[0]) { br.append("Closest sum to " + date + " is " + res[0] + ".").append("\n"); // System.out.println("Closest sum to " + date + " is " + // res[0] + "."); } else br.append("Closest sum to " + date + " is " + binarySearch(date) + ".").append("\n"); // System.out.println("Closest sum to " + date + " is " + // binarySearch(date) + "."); } times++; } System.out.print(br); }
9
@Override public void caseADeclRepitaDefinicaoComando(ADeclRepitaDefinicaoComando node) { inADeclRepitaDefinicaoComando(node); if(node.getRepita() != null) { node.getRepita().apply(this); } if(node.getComando() != null) { node.getComando().apply(this); } if(node.getAte() != null) { node.getAte().apply(this); } if(node.getLPar() != null) { node.getLPar().apply(this); } if(node.getExpLogica() != null) { node.getExpLogica().apply(this); } if(node.getRPar() != null) { node.getRPar().apply(this); } if(node.getPontoVirgula() != null) { node.getPontoVirgula().apply(this); } outADeclRepitaDefinicaoComando(node); }
7
public void getList(int rep) { String tempQuery = ""; if(rep == 0) { tempQuery = DEFAULT_QUERY; } else if(rep == 1) { String searchText = searchBox.getText().toUpperCase(); tempQuery = "select * from member where lastname like '"+searchText+"'"; } listModel.clear(); arrayLastName.clear(); arrayFirstName.clear(); arrayMidName.clear(); arrayMemberid.clear(); Statement stmt = null; this.connect(); conn = this.getConnection(); try { stmt = conn.createStatement(); } catch (SQLException e) { e.printStackTrace(); } ResultSet rs; try { String firstname = ""; String lastname = ""; String midinit = ""; rs = stmt.executeQuery(tempQuery); while(rs.next()) { nameTemp += rs.getString("lastname"); nameTemp += ", " + rs.getString("firstname"); nameTemp += " " + rs.getString("midinit"); firstname = rs.getString("firstname"); lastname = rs.getString("lastname"); midinit = rs.getString("midinit"); arrayFirstName.add(firstname); arrayLastName.add(lastname); arrayMidName.add(midinit); arrayMemberid .add(rs.getString("memberid")); listModel.addElement(nameTemp); nameTemp = ""; //System.out.println(nameTemp); } } catch (SQLException e) { } finally{ this.disconnect(); } listMember.setSelectedIndex(0); }
5
public Class getTypeClass() throws ClassNotFoundException { if (clazz != null) return Class.forName(clazz.getName()); else if (ifaces.length > 0) return Class.forName(ifaces[0].getName()); else return Class.forName("java.lang.Object"); }
2
private void handleTouchEvent(final TouchEvent TOUCH_EVENT) { final Object SRC = TOUCH_EVENT.getSource(); final EventType TYPE = TOUCH_EVENT.getEventType(); if (SRC.equals(targetIndicator)) { if (TouchEvent.TOUCH_PRESSED == TYPE) { value.setText(String.format(Locale.US, "%." + getSkinnable().getDecimals() + "f", getSkinnable().getTarget())); resizeText(); } else if (TouchEvent.TOUCH_MOVED == TYPE) { touchRotate(TOUCH_EVENT.getTouchPoint().getSceneX() - getSkinnable().getLayoutX(), TOUCH_EVENT.getTouchPoint().getSceneY() - getSkinnable().getLayoutY(), targetIndicatorRotate); } else if (TouchEvent.TOUCH_RELEASED == TYPE) { getSkinnable().setTarget(Double.parseDouble(value.getText())); fadeBack(); } } }
4
void draw(BufferedImage toDraw, int width, int height) { if (image == null || image.getWidth() != width || image.getHeight() != height) { image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); graphics = image.createGraphics(); } graphics.drawImage(toDraw, 0, 0, null); }
3
public String Datos(String Radio) throws SQLException { String Recorrer = ""; ResultSet Rs = null; if (Radio.equals("Profesores")) { Recorrer += "<select name=\"identificacion\" id=\"ConProEsT\">"; Rs = Pres.traerProfesor(); while (Rs.next()) { Recorrer += "<option Value='" + Rs.getString("Identificacion") + "' >" + Rs.getString("nombre_completo") + "</option>"; } Recorrer += "</select>"; } else if (Radio.equals("Estudiante")) { Recorrer += "<select name=\"identificacion\" id=\"ConProEsT\">"; Rs = Pres.traerEstudiante(); while (Rs.next()) { Recorrer += "<option Value='" + Rs.getString("Identificacion") + "' >" + Rs.getString("nombre_completo") + "</option>"; } Recorrer += "</select>"; } return Recorrer; }
4
public PartB() { System.out.println("PartB builded"); }
0
public void notifyListeners(Matter matter, double processedTime) { for (final HitGroundListener listener : listeners) { listener.hitGround(matter, processedTime); } }
1
static ArrayList<String> dijkstra(AdjacencyList graph, String source, String destination) { ArrayList<String> selectedNodes = new ArrayList<>(); graph.get(source).dist = 0; graph.get(source).linked = true; selectedNodes.add(source); while (graph.size() != selectedNodes.size()) { int min_dist = Integer.MAX_VALUE; String min_dist_node = ""; for (String node : selectedNodes) { for (String adjacent : graph.get(node).adjacents.keySet()) { if (graph.get(adjacent).linked == true) //if the node is selected, skip it continue; if (graph.get(node).dist+graph.get(node).getDistTo(adjacent) < graph.get(adjacent).dist) { //if the distance from source to adjacent is reducable with a //newly-found path, update the path graph.get(adjacent).parent = node; graph.get(adjacent).dist = graph.get(node).dist+graph.get(node).getDistTo(adjacent); } if (graph.get(adjacent).dist < min_dist) { min_dist = graph.get(adjacent).dist; min_dist_node = adjacent; } } } if (min_dist_node != "") { graph.get(min_dist_node).linked = true; selectedNodes.add(min_dist_node); } } //Create the string of nodes which is a path from source to destination Stack<String> path = new Stack<>(); path.add(destination); while (graph.get(destination).parent != null) { //adds the path into the stack in the order destination -> source path.add(graph.get(destination).parent); destination = (graph.get(destination).parent); } ArrayList<String> ret = new ArrayList<>(); for (int i = 0; i < path.size(); ) { ret.add(path.pop()); //pop out of the stack and add the popped values into an arraylist to reverse the order //so the order of the returned arraylist is source -> destination } return ret; //returns the correctly ordered, shortest path from source to destination }
9
public void updateChatLog() { while (chatLog.size() > 20 && chatLog.get(0).getTime() > 8000) chatLog.remove(0); while (chatLog.size() > 10 && chatLog.get(0).getTime() > 18000) chatLog.remove(0); }
4
private boolean jj_scan_token(int kind) { if (jj_scanpos == jj_lastpos) { jj_la--; if (jj_scanpos.next == null) { jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken(); } else { jj_lastpos = jj_scanpos = jj_scanpos.next; } } else { jj_scanpos = jj_scanpos.next; } if (jj_rescan) { int i = 0; Token tok = token; while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; } if (tok != null) jj_add_error_token(kind, i); } if (jj_scanpos.kind != kind) return true; if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; return false; }
9
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(GraphicalUserInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GraphicalUserInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GraphicalUserInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GraphicalUserInterface.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 GraphicalUserInterface(project).setVisible(true); } }); }
6
@Test public void getTiles(){ Tile[][] tiles = new Tile[10][10]; for (int x = 0; x < tiles.length; x++){ for(int y = 0; y < tiles[0].length; y++){ tiles[x][y] = new Tile(new Position(x, y), 0); } } World w = new World(tiles); Tile[][] testTiles= w.getTiles(); assertTrue(testTiles.length == 10 && testTiles[9][9] != null); }
3
public int getdist(int T, int[] a) { long x = 0; long y = 0; int d = 0; for(int j = 0;j < T;j++){ for(int i = 0;i < a.length;i++){ switch(d){ case 0: y = y + a[i]; break; case 1: x = x + a[i]; break; case 2: y = y - a[i]; break; case 3: x = x - a[i]; break; } d += a[i]; d = d % 4; System.out.println(x + " " + y); } } int ans = (int)(Math.abs(x) + Math.abs(y)); return ans; }
6
public static void main(String[] args) { try { SAXBuilder saxBuilder = new SAXBuilder(); File file = new File("D:\\Java SE\\src\\xml\\jdom\\file.xml"); Document document = (Document)saxBuilder.build(file); Element node = document.getRootElement(); Element staff = node.getChild("staff"); staff.getAttribute("id").setValue("4"); Element element = new Element("age").setName("personage").setText("28"); staff.addContent(element); XMLOutputter xmlOutputter = new XMLOutputter(); xmlOutputter.setFormat(Format.getPrettyFormat()); xmlOutputter.output(document, new FileWriter("D:\\Java SE\\src\\xml\\jdom\\file.xml")); System.out.println("File updated!"); } catch (IOException io) { io.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } }
2
public void update(){ switch(mainModel.getState()){ case INITIALIZED: //initialized so switch states mainModel.setState(State.MENU); break; case MENU: mainModel.update(); mainView.update(); break; case LOAD: //TODO finish load //load the game then start it mainView.update(); mainModel.prepareLoad(saveLoad); mainModel.update(); mainModel.setState(State.PLAYING); System.out.println("LOADED"); break; case PLAYING: mainModel.update(); mainView.update(); break; case INVENTORY: // during the inventory state do this stuff mainModel.update(); mainView.update(); break; case PAUSED: // while paused do this stuff break; case GAMEOVER: //menu.section = 3; // break the loop to finish the current play break; default: System.out.println("ERROR: Controller Update Switch Hit Default."); break; } }
7
public LinkedHashMap<Integer, Compra> cargarCompraTexto(String nombreFichero) { LinkedHashMap<Integer, Compra> compras = new LinkedHashMap<>(); Compra c; FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(nombreFichero); ois = new ObjectInputStream(fis); //Si el archivo está ocupado también devuelve 0 while (fis.available() > 0) { c = (Compra) ois.readObject(); compras.put(c.getId(), c); } } catch (FileNotFoundException ex) { Logger.getLogger(FicherosDatos.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(FicherosDatos.class.getName()).log(Level.SEVERE, null, ex); } finally { if (fis != null) { try { fis.close(); ois.close(); } catch (IOException ex) { Logger.getLogger(FicherosDatos.class.getName()).log(Level.SEVERE, null, ex); } } } return compras; }
5
public static boolean jolly(int[] v){ boolean jolly = true; if(v.length==1) return jolly; else{ int contador = 0; for( int i = 0; i < v.length; ++i ){ if((i+1)< v.length){ int diferencia = Math.abs(v[i]-(v[i+1])); if( diferencia > (casos-1) ) return false; if( diferencia <= (casos-1) && !vector[diferencia]){ vector[diferencia] = true; contador++; } } } if(contador == (casos-1)) return true; return false; } }
7
private UserToken doVerifyUserToken(String token) { if (token == null) { return null; } try { UserToken userToken = dataStore.getUserToken(token); if (userToken != null && userToken.created != null && userToken.loggedOut == null) { //length of validity in millis //TODO make the timout configurable, Cookie Timeout must match Long validFor = 12L * 60L * 60L * 1000L; // 12 hours if (userToken.created > (System.currentTimeMillis()-validFor)) { return userToken; } } } catch (Exception e) { // fall through } return null; }
6
JClass parseTypeName() throws ClassNotFoundException { int start = idx; if(s.charAt(idx)=='?') { // wildcard idx++; ws(); String head = s.substring(idx); if(head.startsWith("extends")) { idx+=7; ws(); return parseTypeName().wildcard(); } else if(head.startsWith("super")) { throw new UnsupportedOperationException("? super T not implemented"); } else { // not supported throw new IllegalArgumentException("only extends/super can follow ?, but found "+s.substring(idx)); } } while(idx<s.length()) { char ch = s.charAt(idx); if(Character.isJavaIdentifierStart(ch) || Character.isJavaIdentifierPart(ch) || ch=='.') idx++; else break; } JClass clazz = ref(s.substring(start,idx)); return parseSuffix(clazz); }
7
public void CellFit(final float w, final float h, final String txt, final Borders border, final Position ln, final Alignment align, final boolean fill, final int link, final ScaleMode scale, final boolean force) throws IOException { // Get string width float str_width = this.getStringWidth(txt); // Calculate ratio to fit cell float w1 = (w == 0) ? this.w - this.rMargin - this.x : w; float ratio = (w1 - this.cMargin * 2) / str_width; boolean fit = ((ratio < 1) || ((ratio > 1) && force)); if (fit) { switch (scale) { // Character spacing case CHARSPACE: // Calculate character spacing in points float char_space = (w1 - this.cMargin * 2 - str_width) / Math.max(txt.length() - 1, 1) * this.k; // Set character spacing this._out(String.format(Locale.ENGLISH, "BT %.2f Tc ET", Float //$NON-NLS-1$ .valueOf(char_space))); break; // Horizontal scaling case HORIZONTAL: // Calculate horizontal scaling float horiz_scale = ratio * 100.0f; // Set horizontal scaling this._out(String.format(Locale.ENGLISH, "BT %.2f Tz ET", Float //$NON-NLS-1$ .valueOf(horiz_scale))); break; } // Override user alignment (since text will fill up cell) this.Cell(w1, h, txt, border, ln, null, fill, link); } else { // Pass on to Cell method this.Cell(w1, h, txt, border, ln, align, fill, link); } // Reset character spacing/horizontal scaling if (fit) { this._out("BT " + (ScaleMode.CHARSPACE.equals(scale) //$NON-NLS-1$ ? "0 Tc"//$NON-NLS-1$ : "100 Tz") //$NON-NLS-1$ + " ET");//$NON-NLS-1$ } }
8
private void createPlayer(int playerCount) { player = new Player [playerCount]; for ( int i = 0; i < playerCount; i++ ) { player[i] = new Player(); } }
1
@Override public Object registeringGUI() { long prodId; Calendar initDate = Calendar.getInstance(), finalDate = Calendar.getInstance(); while(true){ try{ prodId = Long.parseLong(guiImpl.requestData("ID do produto:")); break; }catch(NumberFormatException e){ GUIAbsTemplate.operationFailedGUI("ID inválido."); } } int day, month, year; while(true){ try{ day = Integer.parseInt(guiImpl.requestData("Data de início(dia):")); month = Integer.parseInt(guiImpl.requestData("Data de início(mês):")); year = Integer.parseInt(guiImpl.requestData("Data de início(ano):")); initDate.set(year, month, day); break; }catch(Exception e){ GUIAbsTemplate.operationFailedGUI("Data inválida."); } } while(true){ try{ day = Integer.parseInt(guiImpl.requestData("Data de término(dia):")); month = Integer.parseInt(guiImpl.requestData("Data de término(mês):")); year = Integer.parseInt(guiImpl.requestData("Data de término(ano):")); finalDate.set(year, month, day); break; }catch(Exception e){ GUIAbsTemplate.operationFailedGUI("Data inválida."); } } return new PublicSale(prodId, initDate, finalDate); }
6
public static ArrayList<Carta> parse(Scanner sc) throws IOException{ ArrayList<Carta> cartas = new ArrayList<Carta>(); String entrada = sc.next(); //Excepcion si no hay 10 caracteres en la linea if(entrada.length() != 10){ throw new IOException("Numero de caracteres por linea incorrecto"); } for(int i = 0; i < 5; i++){ cartas.add(new Carta(entrada.substring(i * 2, i * 2 + 2))); //Excepcion si los caracteres no coinciden con los numeros y palos validos respectivamente if(cartas.get(i).getNumero() == null || cartas.get(i).getPalo() == null){ throw new IOException("Caracteres invalidos"); } //Comprobacion si hay 2 cartas iguales for(int j = 0;j < i;j++){ if(cartas.get(i).equals(cartas.get(j))){ throw new IOException("Cartas iguales en una misma mano"); } } } return cartas; }
6
private void setKey(byte[] keyBytes) { workingKey = keyBytes; x = 0; y = 0; if(engineState == null) { engineState = new byte[STATE_LENGTH]; } //reset the state of the engine for(int i = 0; i < STATE_LENGTH; i++) { engineState[i] = (byte) i; } int i1 = 0; int i2 = 0; for(int i = 0; i < STATE_LENGTH; i++) { i2 = ((keyBytes[i1] & 0xff) + engineState[i] + i2) & 0xff; //do the byte swap inline byte tmp = engineState[i]; engineState[i] = engineState[i2]; engineState[i2] = tmp; i1 = (i1 + 1) % keyBytes.length; } }
3
private Expression designator(boolean acceptAddressOf) throws RequiredTokenException { enterRule(NonTerminal.DESIGNATOR); Token dereferencedToken = emitTerminal(require(Token.Kind.IDENTIFIER)); Symbol dereferencedSymbol = null; try { dereferencedSymbol = resolveSymbol(dereferencedToken); } catch (UnresolvableSymbolException e) { exitRule(); return new Error( dereferencedToken.getLineNumber(), dereferencedToken.getCharPos(), String.format("Unable to resolve symbol \"%s\".", dereferencedToken.getLexeme())); } Index prevIndex = null; while(accept(Token.Kind.OPEN_BRACKET)) { Expression indexExpression = expression0(); require(Token.Kind.CLOSE_BRACKET); if(prevIndex == null) { prevIndex = new Index( ((Command)indexExpression).lineNumber(), ((Command)indexExpression).charPosition(), new AddressOf( dereferencedToken.getLineNumber(), dereferencedToken.getCharPos(), dereferencedSymbol), indexExpression); } else { prevIndex = new Index( ((Command)indexExpression).lineNumber(), ((Command)indexExpression).charPosition(), prevIndex, indexExpression); } } exitRule(); if(acceptAddressOf && prevIndex == null) { return new AddressOf( dereferencedToken.getLineNumber(), dereferencedToken.getCharPos(), dereferencedSymbol); } return new Dereference( dereferencedToken.getLineNumber(), dereferencedToken.getCharPos(), prevIndex != null ? prevIndex : new AddressOf( dereferencedToken.getLineNumber(), dereferencedToken.getCharPos(), dereferencedSymbol)); }
6
@Basic @Column(name = "FES_ESTADO") public String getFesEstado() { return fesEstado; }
0
public int readWord() throws IOException { int read1 = in.read(); if(read1 == -1) return -1; int read2 = in.read(); if(read2 == -1) throw new IOException("EOF in middle of 16 bit word"); if(littleEndian) { return (read2 << 8) | read1; } else { return (read1 << 8) | read2; } }
3
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (available ? 1231 : 1237); result = prime * result + ((color == null) ? 0 : color.hashCode()); result = prime * result + (moveable ? 1231 : 1237); result = prime * result + xPos; result = prime * result + yPos; return result; }
3
void dispose() throws HoHumException { throw new HoHumException(); }
0
public void trieTableur() { //on boucle pour toutes les autres lignes du tableur pour décaler à chaque fois un caractère abc --> cab --> bca for(int i=1 ; i < TAILLEMOT ; i++) { tableurNonTrie.add(i, new ArrayList<Character>(tableurNonTrie.get(i-1))); carac = (char) tableurNonTrie.get(i).get(TAILLEMOT-1); tableurNonTrie.get(i).remove(TAILLEMOT-1); tableurNonTrie.get(i).add(0, carac); } /* * Permet de comparer deux mots ArrayList<Character> sur chaque lettre * Si la première est différente : comparaison, sinon on passe à la 2nde, etc... */ Comparator<ArrayList<Character>> myComparator = new Comparator<ArrayList<Character>>() { @Override public int compare(ArrayList<Character> o1, ArrayList<Character> o2) { int col = -1; boolean pasSortie = true; while(pasSortie) //TantQue le caractere est identique on boucle --> texte et tetex on boucle pour te { col++; pasSortie = o1.get(col).equals(o2.get(col)); } return o1.get(col).compareTo(o2.get(col)); } }; tableurTrie = new ArrayList<ArrayList<Character>>(tableurNonTrie); // On trie le tableur avec l'override de compare Collections.sort(tableurTrie, myComparator); position.clear(); //On compare notre tableur et le tableur trié pour connaitre la position initial des mots/lignes for(ArrayList<Character> mot : tableurTrie) position.add(tableurNonTrie.indexOf(mot)); //affichageTableur("Tableur non trié :", tableur); affichageTableur("Tableur trié : ", tableurTrie); //System.out.println("Position :\n" + position); positionChaine = tableurTrie.indexOf(chaine); //En partant de 0 et pas de 1 System.out.println("Position de la chaine de départ \" " + chaine + " \" : " + positionChaine); }
3
@Override public boolean containsAddressPara(){ for (int i = 0; i < paras.size(); i++) { if (paras.get(i).equals("$sender") || paras.get(i).equals("$recipient")) return true; } for (int i = 0; i < generateParas.size(); i++) { if (generateParas.get(i).equals("$sender") || generateParas.get(i).equals("$recipient")) return true; } return false; }
6
@XmlTransient public Collection<Sintoma> getSintomaCollection() { return sintomaCollection; }
0
@Override public String process(HttpServletRequest request) throws MissingRequiredParameter { ResultSet resultSet = null; //String result = null; JSONArray result = new JSONArray(); //String result; try { // Get Connection and Statement connection = dataSource.getConnection(); statement = connection.createStatement(); String query = "SELECT * FROM farmacias"; resultSet = statement.executeQuery(query); while (resultSet.next()) { Farmacia farm = new Farmacia(); farm.setId(resultSet.getInt("id_farmacia")); if (resultSet.getString("nombre") != null) farm.setName(resultSet.getString("nombre")); farm.setciudad(resultSet.getString("ciudad")); farm.setdireccion(resultSet.getString("direccion")); farm.sethorario(resultSet.getString("horario")); farm.setlongitud(resultSet.getString("longitud")); farm.setlatitud(resultSet.getString("latitud")); result.add(farm); } } catch (SQLException e) { return "{\"status\":\"KO\", \"result\": \"Error en el acceso a la base de datos.\"}"; } finally { try { if (null != resultSet) resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (null != statement) statement.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (null != connection) connection.close(); } catch (SQLException e) { e.printStackTrace(); } } return "{\"status\":\"OK\", \"result\":" +result.toString() + "}"; }
9
@Test public void jsonTransformEquality() throws InvalidJSONException, JSONException { Cible c1 = new Cible("c1", new Position(40.123,41.456), CibleType.WATER); Cible c2; c2 = new Cible(c1.toJSON()); assertTrue((c1.getUniqueID() == c2.getUniqueID()) && ((c1.getPosition().getLatitude() == c2.getPosition().getLatitude()) && (c1.getPosition().getLongitude() == c2.getPosition().getLongitude()))); }
2
public void putAll(Map m) { touch(m.keySet()); map.putAll(m); }//putAll
0
@Override public void init(GameContainer gc) { try { _spriteSheet = new SpriteSheet("res/sprites/player.png", 32, 32); _animation = new Animation[4]; _animation[Direction.NORTH] = new Animation(_spriteSheet, 0, 0, 2, 0, true, 200, true); _animation[Direction.EAST] = new Animation(_spriteSheet, 0, 3, 2, 3, true, 200, true); _animation[Direction.SOUTH] = new Animation(_spriteSheet, 0, 1, 2, 1, true, 200, true); _animation[Direction.WEST] = new Animation(_spriteSheet, 0, 2, 2, 2, true, 200, true); for(int i = 0; i <= _animation.length - 1; i++) { _animation[i].setPingPong(true); _animation[i].setAutoUpdate(false); } position = GridGraphicTranslator.GridToPixels(new Vector2(8, 8)); inventory = new Inventory(this); FollowingPokemon p = new FollowingPokemon(this); p.init(gc); this.follower = p; pokemon = PokemonManager.getPokemonById(0); } catch (SlickException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
2
public static NanoPost createNanoPost(String postText, byte[] parentHash, File postAttach) { //postText = escapeJson(postText); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); NanoPostAttach att = null; String postJson = "{}"; try { dos.write(parentHash); postJson = new Gson().toJson(new NanoPostInfo(postText, (int) (System.currentTimeMillis() / 1000))); dos.writeUTF(postJson); if (postAttach == null) { dos.writeUTF(""); // there is no attached file } else { att = new NanoPostAttach(ByteUtils.readBytesFromFile(postAttach), postAttach.getName(), postAttach); att.writeToStream(dos); } } catch (UnsupportedEncodingException ex) { Logger.getLogger(NanoPostFactory.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(NanoPostFactory.class.getName()).log(Level.SEVERE, null, ex); } byte[] postHash = EncryptionProvider.sha256(baos.toByteArray()); return new NanoPost(postHash, parentHash, postJson, att); }
3
*/ protected void setPosition(Point plantP) { p = (Point) plantP.clone(); if (p.getX() >= Grid.BOUND_MAX_X - 20) { p.x = Grid.BOUND_MAX_X - 20; } if (p.getY() >= Grid.BOUND_MAX_Y - 20) { p.y = Grid.BOUND_MAX_Y - 20; } }
2
private PDFObject readName(ByteBuffer buf) throws IOException { // we've already read the / that begins the name. // all we have to check for is #hh hex notations. StringBuffer sb = new StringBuffer(); int c; while (isRegularCharacter(c = buf.get())) { if (c < '!' && c > '~') { break; // out-of-range, should have been hex } // H.3.2.4 indicates version 1.1 did not do hex escapes if (c == '#' && (majorVersion != 1 && minorVersion != 1)) { int hex = readHexPair(buf); if (hex >= 0) { c = hex; } else { throw new PDFParseException("Bad #hex in /Name"); } } sb.append((char) c); } buf.position(buf.position() - 1); return new PDFObject(this, PDFObject.NAME, sb.toString()); }
7
private void fillUsedPictures() { //лист под каждую тему List<Integer> animalsList = new ArrayList<Integer>(); List<Integer> carsList = new ArrayList<Integer>(); List<Integer> musicList = new ArrayList<Integer>(); //добавление картинок в виде их номеров for (int i = 0; i < 10; i++) { animalsList.add(i); carsList.add(i); musicList.add(i); } //составление мапыц Тема -> лист картинок usedPictures.put("Животные", animalsList); usedPictures.put("Марки автомобилей", carsList); usedPictures.put("Рок-группы", musicList); }
1
public void draw(Graphics2D g2) { g2.drawImage(background, 0, 0, GamePanel.WIDTH, GamePanel.HEIGHT, null); g2.drawImage(coin, GamePanel.WIDTH - coin.getWidth() - 90, 18, coin.getWidth(), coin.getHeight(), null); g2.setFont(new Font("LCD", 2, 50)); g2.drawString(PlayerData.playerData.getName(), 80, 49); g2.drawString(String.valueOf(PlayerData.playerData.getCoins()), GamePanel.WIDTH - 90, 49); g2.setFont(new Font("Dialog", Font.PLAIN, 12)); for (int i = 0; i < 2; i++) { if (i == selectedButton) { g2.drawImage(buttons[i][0], recs[i].x, recs[i].y, recs[i].width, recs[i].height, null); } else { g2.drawImage(buttons[i][1], recs[i].x, recs[i].y, recs[i].width, recs[i].height, null); } } // Scrolling double targetPosition = selectedBackground * 50; scrollingPosition += (targetPosition - scrollingPosition) * scrollingSpeed; AffineTransform at = new AffineTransform(); at.translate(0, -scrollingPosition); BufferedImage scrollArea = new BufferedImage(300, 160, BufferedImage.TYPE_INT_RGB); Graphics2D scrollG = (Graphics2D) scrollArea.getGraphics(); scrollG.setTransform(at); for (int i = 0; i < backgrounds.size(); i++) { Background b = backgrounds.get(i); scrollG.drawImage(b.getImage(), 20, i * 50 + 5, 60, 40, null); if (b.isOwend()) { scrollG.drawString("Yours", 100, i * 50 + 30); } else { if (PlayerData.playerData.getCoins() >= 75) { scrollG.drawString("Buy 75 $", 100, i * 50 + 30); } else { scrollG.setColor(Color.RED); scrollG.drawString("Buy 75 $", 100, i * 50 + 30); scrollG.setColor(Color.WHITE); } } } g2.drawImage(scrollArea, 50, 70, 300, 160, null); if (selectedButton == 2) { g2.setColor(Color.LIGHT_GRAY); g2.drawRect(52, 72, 296, 46); g2.drawRect(53, 73, 294, 44); g2.drawRect(54, 74, 292, 42); } }
6
public void load(String fileName) { try { InputStream file = new FileInputStream(fileName); InputStream buffer = new BufferedInputStream(file); ObjectInput input = new ObjectInputStream(buffer); GameData gd = (GameData) input.readObject(); input.close(); buffer.close(); file.close(); init(); map.setData(gd); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
3
public int compare(String[] ssc1, String[] ssc2) { for (int idx:indicesOfKeys) { String str1 = ssc1[idx]; String str2 = ssc2[idx]; if (str1 == null && str2 == null) { continue; } else if (str1 != null && str2 == null) { return -1; } else if (str1 == null && str2 != null) { return 1; } else { int r = str1.compareTo(str2); if (r == 0) { continue; } else { return r; } } } return 0; }
8
public void build() { progress += 4; if(progress % 500 == 0 && progress != 0) { if(progress <= 3500) { sind ++; this.sprite = Images.stonepost.getSubimage(sind * 64, 0, 64, 64); } } }
3
@Override public void actionPerformed(ActionEvent e) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); final int thisyear = cal.get(Calendar.YEAR); cal.set((Integer) year.getSelectedItem(), (Integer) month.getSelectedItem() - 1, (Integer) day.getSelectedItem()); java.sql.Date date = new java.sql.Date(cal.getTimeInMillis()); this.student = new Student(no.getText(), name.getText(), thisyear - (Integer) year.getSelectedItem(), (String) sex.getSelectedItem(), date, address.getText(), tel.getText(), email.getText()); this.dispose(); }
0
final public void Empty_statement() throws ParseException { /*@bgen(jjtree) Empty_statement */ SimpleNode jjtn000 = new SimpleNode(JJTEMPTY_STATEMENT); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1)); try { jj_consume_token(SEMICOLON); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } }
1
public static Map<String, String> map(String... params) { Map<String, String> result = new HashMap<String, String>(); for(String param: params) { String[] kvs = param.split("->"); String key = rmvPrePostSc(StringUtils.trim(kvs[0])); String val = rmvPrePostSc(StringUtils.trim(kvs[1])); result.put(key, val); } return result; }
1
public boolean checkGoal(State state) { for (int k = 0; k < state.getData().size(); k++) { for(int m = 0; m < state.getData().get(k).size(); m++) { if (state.getData().get(k).get(m).equals("$") || state.getData().get(k).get(m).equals(".")) { return false; } } } endTime = System.nanoTime(); System.out.println("Reached goal state!"); ArrayList<Character> path = new ArrayList<Character>(); getPath(path, state); System.out.println("Nodes generated: " + totalNodesGenerated); System.out.println("nodes containing states that were generated previously: " + nodesGeneratedPreviously); nodesOnFringe = queue.size(); System.out.println("Nodes on fringe: " + nodesOnFringe); nodesOnExploredList = visited.size(); System.out.println("Nodes on explored list: " + nodesOnExploredList); totalTime = endTime - startTime; double printTime = totalTime/BILLION; //nanoseconds / 1000000000 = seconds System.out.println("Run time in seconds: " + printTime); Collections.reverse(path); System.out.print("Path: "); for(int i = 0; i < path.size(); i++) { System.out.print(path.get(i) + ", "); } System.out.println(); return true; }
5
public AbstractView getView(Class<? extends AbstractView> clazz) { for (AbstractView view : registeredViews) { if (clazz.isInstance(view)) { return view; } } return null; }
3
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(ViewProvider.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewProvider.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewProvider.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewProvider.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 ViewProvider().setVisible(true); } }); }
6
private static State mergeStates(Set<State> original, DataMerger merger) { List<String> names = new ArrayList<String>(original.size()); for (State s : original) names.add(s.name); Collections.sort(names); StringBuilder name = new StringBuilder(); for (String n : names) name.append(n + "|"); State newState = new State(name.toString()); Iterator<State> it = original.iterator(); Object o = it.next().getData(); while (it.hasNext()) { State st = it.next(); o = merger.merge(o, st.getData()); Logger.log(" " + st); } if (o instanceof Set<?>) { newState.setData(o); } else { Set<Object> set = new HashSet<Object>(); set.add(o); newState.setData(set); } return newState; }
5
@Override public String toString() { String result = "Subject: " + this.getSubject() + " Description: " + this.getDescription() + " Priority: " + this.getPriority() + " AuthorID: " + this.getAuthor() + " ExpirateDate: " + this.getExpirationDate().toString() + " Options: "; for (String option : this.getOptions()) { result += option + ", "; } result += " VoteCountIDs: "; VoteModel voteModel = new VoteModel(); for (Integer i : this.getVotes()) { Vote vote = (Vote) voteModel.get(i); result += vote.toString() + ", "; } result += " CommentIDs: "; for (Integer comment : this.getComments()) { result += comment + ", "; } result += " AttachmentIDs: "; for (String attachment : this.getAttachments()) { result += attachment + ", "; } return result; }
4
public static void Move(){ UserInteractions.PrintSeparator('-'); System.out.println("\t\tBLACK's TURN"); UserInteractions.PrintSeparator('-'); if (owner.equals(Owner.HUMAN)){ Human.makeNextBlackMoves(); } else{ assert(owner.equals(Owner.ROBOT)); Robot.makeNextBlackMoves(); } }
1
public boolean isEven(int num) { if (num % 2 == 0) return true; else return false; }
1
public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; }
6
public static void disposeImages() { // dispose loaded images { for (Image image : m_imageMap.values()) { image.dispose(); } m_imageMap.clear(); } // dispose decorated images for (int i = 0; i < m_decoratedImageMap.length; i++) { Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[i]; if (cornerDecoratedImageMap != null) { for (Map<Image, Image> decoratedMap : cornerDecoratedImageMap.values()) { for (Image image : decoratedMap.values()) { image.dispose(); } decoratedMap.clear(); } cornerDecoratedImageMap.clear(); } } }
5
public BendTrajectory(Lane lane) { fLane = lane; fStartX = lane.getStart().getPosition().getX(); fEndX = lane.getEnd().getPosition().getX(); fStartY = lane.getStart().getPosition().getY(); fEndY = lane.getEnd().getPosition().getY(); double x = fStartX; double y = fEndY; if (fStartX > fEndX && fLane.getDirection(fLane.getStart()).equals("E") || (fStartX < fEndX && fLane.getDirection(fLane.getStart()).equals("W"))) { isBackWard = true; x = fEndX; y = fStartY; } fCurve = new QuadCurve2D.Double(fStartX, fStartY, x, y, fEndX, fEndY); }
4
protected void runTests(boolean weighted, boolean multiInstance, boolean updateable) { boolean PNom = canPredict(true, false, false, false, false, multiInstance)[0]; boolean PNum = canPredict(false, true, false, false, false, multiInstance)[0]; boolean PStr = canPredict(false, false, true, false, false, multiInstance)[0]; boolean PDat = canPredict(false, false, false, true, false, multiInstance)[0]; boolean PRel; if (!multiInstance) PRel = canPredict(false, false, false, false, true, multiInstance)[0]; else PRel = false; if (PNom || PNum || PStr || PDat || PRel) { if (weighted) instanceWeights(PNom, PNum, PStr, PDat, PRel, multiInstance); canHandleZeroTraining(PNom, PNum, PStr, PDat, PRel, multiInstance); boolean handleMissingPredictors = canHandleMissing(PNom, PNum, PStr, PDat, PRel, multiInstance, true, 20)[0]; if (handleMissingPredictors) canHandleMissing(PNom, PNum, PStr, PDat, PRel, multiInstance, true, 100); correctBuildInitialisation(PNom, PNum, PStr, PDat, PRel, multiInstance); datasetIntegrity(PNom, PNum, PStr, PDat, PRel, multiInstance, handleMissingPredictors); if (updateable) updatingEquality(PNom, PNum, PStr, PDat, PRel, multiInstance); } }
9
void showdetail() { int max =0; ArrayList<Integer[]> scorelist0 = new ArrayList<Integer[]>(); ArrayList<Integer[]> scorelist1 = new ArrayList<Integer[]>(); for (int i=0; i<size*size-1; i++) { if (grid[i].value>max) { max = grid[i].value; } } for (int i=2; i<=max; i=i*2) { Integer[] tmpint = new Integer[2]; tmpint[0] = i; tmpint[1]=0; scorelist0.add(tmpint); } for (int i=2; i<=max; i=i*2) { Integer[] tmpint = new Integer[2]; tmpint[0] = i; tmpint[1]=0; scorelist1.add(tmpint); } StringBuilder a = new StringBuilder(); StringBuilder b = new StringBuilder(); for (int i=0; i<size*size-1; i++) { if (grid[i].value>=2) { if (grid[i].owner==0) { scorelist0.get((int) (Math.log(grid[i].value)/Math.log(2)-1))[1]++; } else { scorelist1.get((int) (Math.log(grid[i].value)/Math.log(2)-1))[1]++; } } } a.append(group0); a.append("--- "); for (int i=0; i<scorelist0.size(); i++) { a.append("["); a.append(scorelist0.get(i)[0]); a.append(": "); a.append(scorelist0.get(i)[1]); a.append("] "); } b.append(group1); b.append("--- "); for (int i=0; i<scorelist1.size(); i++) { b.append("["); b.append(scorelist1.get(i)[0]); b.append(": "); b.append(scorelist1.get(i)[1]); b.append("] "); } label3.setText(a.toString()); label3.setVisible(true); label4.setText(b.toString()); label4.setVisible(true); }
9
public synchronized void mouseMoved(MouseEvent e) { // this event is from re-centering the mouse - ignore it if (isRecentering && centerLocation.x == e.getX() && centerLocation.y == e.getY()) { isRecentering = false; } else { int dx = e.getX() - mouseLocation.x; int dy = e.getY() - mouseLocation.y; mouseHelper(MOUSE_MOVE_LEFT, MOUSE_MOVE_RIGHT, dx); mouseHelper(MOUSE_MOVE_UP, MOUSE_MOVE_DOWN, dy); if (isRelativeMouseMode()) { recenterMouse(); } } mouseLocation.x = e.getX(); mouseLocation.y = e.getY(); }
4
public DFS addExeLog(String fileName) throws FileNotFoundException { Scanner sc = new Scanner(new File(fileName)); while(true) { if(!sc.hasNextInt(16)) break; int b = sc.nextInt(16); int hl = sc.nextInt(16); if(hl >= 0x8000) { System.out.println("skipping non-ROM address "+Integer.toHexString(hl)); continue; } if(hl >= 0x4000) hl += (b-1)*0x4000; dfsStack.push(new DFSStackElem(hl, new CPUState(), true)); //System.out.println("added "+Integer.toHexString(hl)); } sc.close(); return this; }
4
public World() { chunks = new Chunk[ncx * ncy * ncz]; for (int x = 0; x < ncx; x++) { for(int y = 0; y < ncy; y++) { for(int z = 0; z < ncz; z++) { chunks[x + (y * ncx) + (z * ncx * ncy)] = new Chunk(this, x * Chunk.chunkW, y * Chunk.chunkH, z * Chunk.chunkD); } } } grass = new Texture("/furnace_front_lit.png"); }
3
public void setButtonReview(JButton button) { button.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent evt) { try { if (wbview.getSelectedRowCount() == 1) { wbview.getReviewDialog().setPK(wbview.getSelectedId()); wbview.invokeReviewMediaDialog(); } else { throw new Exception("multiselect"); } } catch (Exception e) { e.printStackTrace(); if (e.getMessage().equals("multiselect")) { wbview.showError("You have to select ONE media item!"); } else { wbview.showError("You have to select a media item!"); } } } }); }
3
@Override public void beginEditInterval(int start, int end) throws AlreadyEditingException { validateInterval(start, end); if (editedBy != null) throw new AlreadyEditingException(this); if (editedIntervals.isEmpty()) editionStarted(); for (Interval i : editedIntervals) if (i.start < end && start < i.end) throw new AlreadyEditingException(this); editedIntervals.add(new Interval(start, end)); }
5
private void writeLongArray(Object value, int type) { writeList.clear(); int len = Array.getLength(value); if (len > 0) { if (type == ElementType.TYPE_LONG_ARRAY) { for (int i=0;i<len;i++) { writeList.append(Array.getLong(value,i)); } } else if (type == ElementType.TYPE_LONG_WRAPPER_ARRAY) { for (int i=0;i<len;i++) { writeList.append(((Long[])value)[i]); } } } valueList.append(writeList); }
5
@Override public void setID(String iD) { super.setID(iD); }
0
private boolean concatHelper(String curWord, int startIndex, int length) { if (startIndex >= length) { return true; } TrieNode curNode = root; for (int i = startIndex; i < length; i++) { char curChar = curWord.charAt(i); HashMap<Character, TrieNode> children = curNode.getChildren(); if (children.containsKey(curChar)) { curNode = children.get(curChar); if (curNode.getIsEnd()) { // This is to avoid self construct if (startIndex == 0 && i == length - 1) return false; if (concatHelper(curWord, i + 1, length)) return true; } } else return false; } return false; }
7
private int chooseDefaultLanguage () { if (languages.length == 1) return languages [0]; Locale dflt = Locale.getDefault (); int retval = languages [0]; for (int i = 0; i < languages.length; i++) { Locale current = LangCode.getLocale (languages [i]); // return exact matches if possible if (current == dflt) return languages [i]; // insist on shared language if (current == null) continue; if (!current.getLanguage ().equals (dflt.getLanguage ())) continue; // could also check country (return now if same) // it's OK, and maybe better than our last guess retval = languages [i]; } return retval; }
5
private static <T extends JComponent> T getComponentFromList(Class<T> clazz, List<T> list, String property, Object value) throws IllegalArgumentException { T retVal = null; Method method = null; try { method = clazz.getMethod("get" + property); } catch (NoSuchMethodException ex) { try { method = clazz.getMethod("is" + property); } catch (NoSuchMethodException ex1) { throw new IllegalArgumentException("Property " + property + " not found in class " + clazz.getName()); } } try { for (T t : list) { Object testVal = method.invoke(t); if (equals(value, testVal)) { return t; } } } catch (InvocationTargetException ex) { throw new IllegalArgumentException( "Error accessing property " + property + " in class " + clazz.getName()); } catch (IllegalAccessException ex) { throw new IllegalArgumentException( "Property " + property + " cannot be accessed in class " + clazz.getName()); } catch (SecurityException ex) { throw new IllegalArgumentException( "Property " + property + " cannot be accessed in class " + clazz.getName()); } return retVal; }
7
public SessionList getSessionsViewBy(String asViewById, String asLastModified, int aiMaxSize) { String lsParam = ""; if (aiMaxSize > 0) { lsParam += "&max_size=" + Integer.toString(aiMaxSize); } if (UtilityMethods.isValidString(asLastModified)) { lsParam += "&last_modified=" + asLastModified; } if (UtilityMethods.isValidString(lsParam)) { lsParam = lsParam.replaceFirst("&", "?"); } return get(SessionList.class, REST_URL_SESSIONS_VIEW_BY + "/" + asViewById + lsParam); }
3
private String parameterValue(Object value) { if(value == null) return null; if(value.getClass() == String.class) return (String)value; else if(value.getClass() == Boolean.class) return ((Boolean)value).booleanValue()?"yes":"no"; else if(value.getClass() == List.class) { @SuppressWarnings("unchecked") List<String> values = (List<String>)value; StringBuilder sb = new StringBuilder(); int count = 0; for(String s : values) { if(count != 0) sb.append(','); sb.append(s); count ++; } return sb.toString(); } else return value.toString(); }
7
public Map<Integer, SingleRunScore> scoreSubject(Experiment goldStandard, TobiiData subjectData, Map<Integer, List<Double>> recordMap, double lookThreshold) { Map<Integer, SingleRunScore> scoreMap = new HashMap<Integer, SingleRunScore>(); for(Integer trialID : goldStandard.getTrials().keySet()) { Trial trial = goldStandard.getTrials().get(trialID); // Old version: exactly as many Tobii trials as there are Track-It trials //Trajectory<TobiiFrame> subjectTrajectory = subjectData.getTrajectories().get(trialID); // Newer version: must infer Tobii trials by Spacebar press + closest timestamp match Trajectory<TobiiFrame> subjectTrajectory = subjectData.getClosestTrajectoryTo(goldStandard.getTrials().get(trialID).getStartTime()); if(null == subjectTrajectory) { // Some error occurred while parsing the file (we've had some students with blank Tobii files); skip this continue; } int targetIdx = trial.getTargetIdx(); Trajectory<TrackItFrame> goldTrajectory = trial.getTrajectories().get(targetIdx); if(recordMap != null) { recordMap.put(trialID, new ArrayList<Double>()); } SingleRunScore record = calcScore(goldTrajectory, subjectTrajectory, recordMap == null ? null : recordMap.get(trialID)); // If the subject's eyes weren't tracked by Tobii enough, then nil the score if( ((double)record.getFrameCountOnTarget() / (double)record.getFrameCountOverall() ) < lookThreshold) { record.setScore(Double.NaN); } // Some scoring function implement secondary features, like thinking about non-target objectsp; put that stuff here calcFixationStats(record, trial, subjectTrajectory); scoreMap.put(trialID, record); } return scoreMap; }
5