text
stringlengths
14
410k
label
int32
0
9
public Coord xlate(Coord c, boolean in) { if (in) { return c.div(getScale()); } else { return c.mul(getScale()); } }
1
public void setInt(int wert) { setBits(false); if (wert < 0) return; for (int i = 0; i < size; i++) { if (wert == 0) break; if ((wert & 1) == 1) bits[i] = true; wert = wert >>> 1; } }
4
public static void clOutputOneUnit(TranslationUnit unit, PrintableStringWriter stream) { { Stella_Object translation = unit.translation; if (translation == null) { System.out.println("`" + unit + "' has a NULL translation."); return; } if (unit.category != null) { if (!(TranslationUnit.auxiliaryVariableUnitP(unit))) { stream.println(); } if (unit.annotation != null) { { stream.println(";;; " + unit.annotation); stream.println(); } ; } if (Stella_Object.isaP(translation, Stella.SGT_STELLA_CONS) && (((Cons)(translation)).value == Stella.internCommonLispSymbol("PROGN"))) { { Stella_Object form = null; Cons iter000 = ((Cons)(translation)).rest; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { form = iter000.value; Stella_Object.printStellaDefinition(form, stream); } } } else { Stella_Object.printStellaDefinition(translation, stream); } unit.category = null; } } }
7
public void setX(int x) { this.x = x; }
0
public void mouseClicked(MouseEvent e) { if (!onClickDown && e.getClickCount() == 2 && actionCommandDoubleClick != null) { callActionListenersDouble(); } }
3
@Override public boolean equals(Object obj) { if (obj instanceof Coordinate) { Coordinate otherCoord = (Coordinate)obj; return this.row == otherCoord.row && this.col == otherCoord.col; } return false; }
2
private void initPanel() { JPanel p = new JPanel(); p.setLayout(null); for (int i=0;i<7;i++){ createLabel(p,i); createTextField(p,i); } // Add confirm button JButton confirmButton = new JButton("Confirm"); confirmButton.setBounds(WIDTH/4, 9*HEIGHT/11, WIDTH/2, HEIGHT/13); confirmButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String year = textFields.get(6).getText().trim(); if (!isNumeric(year)) { popMsg("Year needs to be a number!"); return; } for (int i = 1; i <= 5; i++) { String text = textFields.get(i).getText().trim(); if (text.equals("")) { popMsg("A field is missing!"); return; } } //Execute when button is pressed Book b = new Book( textFields.get(1).getText().trim(), textFields.get(2).getText().trim(), textFields.get(3).getText().trim(), textFields.get(4).getText().trim(), textFields.get(5).getText().trim(), Integer.parseInt(year)); BookCopy bcUpdate = new BookCopy( textFields.get(1).getText().trim(), 1, "in"); System.out.println("Book has been created"); String callNumber = b.getCallNumber(); Integer countBook = 0; try { countBook = LibraryDB.getManager().countBook(callNumber); } catch (SQLException e2) { // TODO Auto-generated catch block determineError(e2); } if (countBook > 0) { // returns true if book exists try { Integer countBookCopy = LibraryDB.getManager().countBookCopy(callNumber); System.out.println(countBookCopy); BookCopy bc = new BookCopy(b.getCallNumber(), countBookCopy + 1, "in"); // insert book copy instead LibraryDB.getManager().insertBookCopy(bc); System.out.println("This is happening 1"); exitWindow(); System.out.println("Submit book copy"); } catch (SQLException e1) { determineError(e1); } } else { try { System.out.println("We are trying!"); LibraryDB.getManager().insertBook(b); // just insert the book if callnumber doesnt exist // Jimmy: Not quite, we do need to insert a bookcopy. // A Book isn't exactly a physical object, it's just a call number // A bookcopy is, when we add a new book(which really means bookcopy), check if it currently exists // If not, then add a record for the new callnumber (in book) and then add the new physical book (bookcopy) // Jimmy responding to your comment, I commented it out, but you might not have noticed the change when // you were pushing // So yeah, I was saying this line SHOULD BE HERE because we do want to make a new tuple for bookcopy. LibraryDB.getManager().insertBookCopy(bcUpdate); exitWindow(); System.out.println("Submit book"); } catch (SQLException e1) { determineError(e1); } } } }); JButton backButton = new JButton("Back"); backButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new UserFrame(); //lf.dispose(); } }); p.add(backButton); p.add(confirmButton); this.add(p); }
8
public void inserisci(T x) { AlberoBin<T> padre = cercaNodo(x); if (padre == null) { // inserisco la radice coll = new AlberoBinLF<T>(); coll.setVal(x); } else if (!padre.val().equals(x)) { AlberoBinLF<T> figlio = new AlberoBinLF<T>(); figlio.setVal(x); if (x.compareTo(padre.val()) < 0) padre.setSin(figlio); else padre.setDes(figlio); } }
3
private String getTextAsEps(String text) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < text.length(); i++) { final char c = text.charAt(i); if (c == '\\') { sb.append("\\\\"); } else if (c == '(') { sb.append("\\("); } else if (c == ')') { sb.append("\\)"); } else if (c < ' ') { sb.append("?"); } else if (c >= ' ' && c <= 127) { sb.append(c); } else { final String s = "" + c; try { final byte b[] = s.getBytes("ISO-8859-1"); if (b.length == 1) { final int code = b[0] & 0xFF; sb.append("\\" + Integer.toOctalString(code)); } else { sb.append('?'); } } catch (UnsupportedEncodingException e) { sb.append('?'); } } } return sb.toString(); }
9
private int getol(Coord tc) throws Loading { int ol = map.getol(tc); if (ol == -1) throw (new Loading()); return (ol); }
1
public synchronized void threadStart(SimThread t) { if (Constants.muCheck) { if ((Constants.muIncS += Constants.muIncUp) <= .95) { t.Constants._epsilon = this.epsilon; t.Constants._SIM_epsilon_start = this.epsilon; t.Constants._SIM_epsilon_final = this.epsilon; t.setRunNum(runNum); runNum++; DataHolder holder = new DataHolder(); holder.init(t); t.start(); } } else if (Constants.ConstantEp) { if (Main.threads.size() < 2) { t.Constants._epsilon = this.epsilon; t.Constants._SIM_epsilon_start = t.Constants._epsilon; t.Constants._SIM_epsilon_final = t.Constants._epsilon; t.setRunNum(runNum); runNum++; DataHolder holder = new DataHolder(); holder.init(t); t.start(); } else { threadCheck(t); t.start(); } } else if (t.Constants._epsilon != constants._SIM_epsilon_final) { t.Constants._epsilon = this.epsilon; t.Constants._SIM_epsilon_start = t.Constants._epsilon; t.Constants._SIM_epsilon_final = t.Constants._epsilon; this.epsilon += this.constants._SIM_epsilon_step; t.setRunNum(runNum); runNum++; DataHolder holder = new DataHolder(); holder.init(t); t.start(); } }
5
public void openDoor() { System.out.println("模板共性,打开车门"); }
0
public static boolean skipClass(ClassInfo clazz) { InnerClassInfo[] outers = clazz.getOuterClasses(); if (outers != null) { if (outers[0].outer == null) { return doAnonymous(); } else { return doInner(); } } return false; }
2
public SubscribeEventModel buildFromXml(String xml) throws DocumentException { if (null == xml || xml.trim().isEmpty()) return null; List<Element> list = WechatUtils.getXmlRootElements(xml); SubscribeEventModel subscribeModel = new SubscribeEventModel(); for (Element element : list) { if (Constant.EVENT.equals(element.getName())) { subscribeModel.setEvent(element.getTextTrim()); } if (Constant.TO_USER_NAME.equals(element.getName())) { subscribeModel.setToUserName(element.getTextTrim()); } if (Constant.FROM_USER_NAME.equals(element.getName())) { subscribeModel.setFromUserName(element.getTextTrim()); } if (Constant.CREATE_TIME.equals(element.getName())) { subscribeModel.setCreateTime(WechatUtils.formatTime(element.getTextTrim())); } } return subscribeModel; }
7
private static boolean checkHwReqs(float wfHwCpu, float wfHwMem,float wfHwStorage, String archValue, QuerySolution qs) { //iapp HW specs (in MB) float iappHwCpu = 0; float iappHwMem = 0; float iappHwStorage = 0; String iappArch = ""; String hwcpu = qs.get("?hwcpu").toString(); String hwmem = qs.get("?hwmem").toString(); String hwstorage = qs.get("?hwstorage").toString(); //CPU calculation ResultSet getHwCPUFeatQR = QueryExecute.execute(svaModel, QueryStrings.getHwFeatValueQS, "hw_uri", hwcpu); if(getHwCPUFeatQR.hasNext()) { while(getHwCPUFeatQR.hasNext()) { QuerySolution cpuqs = getHwCPUFeatQR.next(); String v = cpuqs.get("?value").toString(); String u = cpuqs.get("?unit").toString(); if(u.equals("bits")) //arch { iappArch = v; } else //freq { iappHwCpu = Float.valueOf(v) * getUnitFactor(u); } } } else { System.err.println("Not found iapp CPU for:"+hwcpu); } //MEM calculation ResultSet getHwMemFeatQR = QueryExecute.execute(svaModel, QueryStrings.getHwFeatValueQS, "hw_uri", hwmem); if(getHwMemFeatQR.hasNext()) { QuerySolution memqs = getHwMemFeatQR.next(); String mv = memqs.get("?value").toString(); String mu = memqs.get("?unit").toString(); iappHwMem = Float.valueOf(mv) * getUnitFactor(mu); } else { System.err.println("Not found iapp mem for:"+hwmem); } //Storage calculation ResultSet getHwStorageFeatQR = QueryExecute.execute(svaModel, QueryStrings.getHwFeatValueQS, "hw_uri", hwstorage); if(getHwStorageFeatQR.hasNext()) { QuerySolution stqs = getHwStorageFeatQR.next(); String sv = stqs.get("?value").toString(); String su = stqs.get("?unit").toString(); iappHwStorage = Float.valueOf(sv) * getUnitFactor(su); } else { System.err.println("Not found iapp storage for:"+hwstorage); } System.out.println("<><><><><><><><><><><> checkHwReqs <><><><><><><><><><>"); System.out.println("<> wfHwCpu="+wfHwCpu); System.out.println("<> wfHwMem="+wfHwMem); System.out.println("<> wfHwStorage="+wfHwStorage); System.out.println("<> archValue="+archValue); System.out.println("<><> " +qs.get("?iapp")); System.out.println("<> iappHwCpu="+iappHwCpu); System.out.println("<> iappHwMem="+iappHwMem); System.out.println("<> iappHwStorage="+iappHwStorage); System.out.println("<> iappArch="+iappArch); System.out.println("<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>"); if ((iappHwCpu>=wfHwCpu) && (iappHwMem>=wfHwMem) && (iappHwStorage>=wfHwStorage) && (archValue.equals(iappArch))) { System.out.println("<><><><><><><><><><><><><> IT'S A MATCH <><><><><><><><><><><><><><><>\n"); return true; } //TODO return false; }
9
public final boolean equals(Object o) { if (!(o instanceof Entry)) return false; Entry e = (Entry)o; Object k1 = Integer.valueOf(getKey()); Object k2 = Integer.valueOf(e.getKey()); if ((k1 == k2) || ((k1 != null) && (k1.equals(k2)))) { Object v1 = getValue(); Object v2 = e.getValue(); if ((v1 == v2) || ((v1 != null) && (v1.equals(v2)))) return true; } return false; }
7
@Test public void test_saveArrayToFile() { String filePath = "testFile.txt"; // creating list with specified amount of random numbers List<Integer> list = appUtil.getRandomNumbers(10, 10); appUtil.saveArrayToFile(filePath, list); // testing existence of file File file = new File(filePath); assertTrue("Fail - file test.text must be created", file.exists()); // testing content of file List<Integer> list2 = appUtil.loadArrayFromFile(filePath); assertEquals("Fail - file must contain same digits", list, list2); // deleting testing file File myFile = new File(filePath); if (myFile.exists()) { myFile.delete(); } }
1
public static int getMaxTimerFromScore(GameMode mode, int score) { if (mode == GameMode.CASUAL) { return 10000; } else { if (score < 100) { return 10000; } else if (score < 150) { return 7000; } else if (score < 200) { return 5000; } else if (score < 250) { return 4000; } else if (score < 300) { return 3000; } else { return 2000; } } }
6
public void visitReturnExprStmt(final ReturnExprStmt stmt) { if (stmt.expr == from) { stmt.expr = (Expr) to; ((Expr) to).setParent(stmt); } else { stmt.visitChildren(this); } }
1
public Piece makePiece(String s) { boolean color = 'W' == s.charAt(0); switch (s.charAt(1)) { case 'X': return new Blank(color); case 'B': return new Bishop(color); case 'R': return new Rook(color); case 'P': return new Pawn(color); case 'Q': return new Queen(color); case 'K': return new King(color); case 'N': return new Knight(color); default: return null; } }
7
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ud = request.getParameter("u"); String rd = request.getParameter("r"); response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet AddUserRoleServlet</title>"); out.println("<link rel=\"stylesheet\" href=\"css/style.css\"/>"); out.println("</head>"); out.println("<body>"); out.println("<div class=\"main\">"); if (ud == null || rd == null) { out.println("<h1>Invalid operation:"); } else { UserRole ur = new UserRole(); ur.setUserId(Long.parseLong(ud)); ur.setRoleId(Long.parseLong(rd)); urfl.create(ur); response.sendRedirect("listuser"); } out.println("<a class=\"go-back\" href=\"index.html\">Home</a>"); out.println("</div>"); out.println("</body>"); out.println("</html>"); } }
2
@Override public boolean onCommand(final CommandSender sender, final ItemStackRef itemStackRef, Command command, String label, String[] args) { // Check the player is holding the item ItemStack held = itemStackRef.get(); if (held == null || held.getTypeId() == 0) { sender.sendMessage(plugin.translate(sender, "error-no-item-in-hand", "You must be holding a menu item")); return true; } if (args.length < 1) { return false; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < args.length; i++) { sb.append(args[i]); if (i + 1 < args.length) { sb.append(' '); } } sb.append(".txt"); String filename = sb.toString(); File scriptsFolder = new File(plugin.getDataFolder(), "scripts"); final File scriptFile = new File(scriptsFolder, filename); new TextFileLoader(plugin, scriptFile, new TextCallback() { @Override public void onLoad(List<String> lines) { ItemStack held = itemStackRef.get(); if (held == null || held.getTypeId() == 0) { sender.sendMessage(plugin.translate(sender, "error-no-item-in-hand", "You must be holding a menu item")); return; } ItemMeta meta = held.getItemMeta(); meta.setDisplayName(lines.get(0)); meta.setLore(lines.subList(1, lines.size())); held.setItemMeta(meta); sender.sendMessage(plugin.translate(sender, "script-imported", "Import successful")); itemStackRef.update(); } @Override public void fail(Exception ex) { if (ex instanceof FileNotFoundException) { sender.sendMessage(plugin.translate(sender, "import-file-not-found", "Could not find {0}", scriptFile.getPath())); } else { sender.sendMessage(plugin.translate(sender, "import-load-error", "An error occurred while attempting to read {0}. Please see console for details.", scriptFile.getPath())); plugin.getLogger().log(Level.WARNING, "Error occured while attempting to read " + scriptFile.getPath(), ex); } } }).load(); return true; }
8
public static int singleNumber(int[] A) { HashMap<Integer, Integer> hashMap=new HashMap<>(); for(int i=0;i<A.length;i++){ if(!hashMap.containsKey(A[i])) hashMap.put(A[i], 1); else { if(hashMap.get(A[i]) == 2) hashMap.remove(A[i]); else { hashMap.put(A[i], hashMap.get(A[i])+1); } } } Iterator iter = hashMap.entrySet().iterator(); Map.Entry entry = (Map.Entry) iter.next(); return (int) entry.getKey(); }
3
private static String join(final String[] args, final String delim) { if (args == null || args.length == 0) return ""; final StringBuilder sb = new StringBuilder(); for (final String s : args) sb.append(s + delim); sb.delete(sb.length() - delim.length(), sb.length()); return sb.toString(); }
3
private String[] getClassPath() { java.util.Vector x = new java.util.Vector(); String classPath = System.getProperty("java.class.path"); String s = ""; for (int i = 0; i < classPath.length(); i++) { if (classPath.charAt(i) == ';') { x.add(s); s = ""; } else { s += classPath.charAt(i); } } if (!s.equals("")) x.add(s); String javaHome = System.getProperty("java.home"); if (javaHome != null) x.add(javaHome + File.separatorChar + "lib" + File.separatorChar + "rt.jar"); String[] retVal = new String[x.size()]; x.copyInto(retVal); return retVal; }
4
public void pickUpAction(int index) throws InvalidActionException { if (grid.getItemsOnPosition(grid.getElementPosition(getActivePlayer())).isEmpty()) throw new IllegalArgumentException("There is no item to be picked up on the current position!"); if (grid.getItemsOnPosition(grid.getElementPosition(getActivePlayer())).size() < index) throw new IllegalArgumentException("The given index is invalid!"); final Item item = grid.getItemsOnPosition(grid.getElementPosition(getActivePlayer())).get(index); ((Pickupable) item).pickUp(getActivePlayer()); getGrid().getEventManager().sendEvent(new Event(EventType.END_ACTION, getActivePlayer())); if (getActivePlayer().getRemainingActions() <= 0) activePlayerEndTurn(); }
3
public void get_file() throws IOException { // Source //File f = new File("D://Alibaba//test.csv"); File f = new File("D://Alibaba//t_alibaba_data.csv"); InputStream is = new FileInputStream(f); try { BufferedReader reader = new BufferedReader( new InputStreamReader(is)); String lineString = reader.readLine(); // filter title UserNRecords userNRecords = null; ArrayList<Record> brandRecords = null; String tempUserID = "00000"; for (;;) { lineString = reader.readLine(); if (lineString == null) { break; } Record r = new Record(); String tokens[] = lineString.split(","); String userID = tokens[0]; r.setBrand(tokens[1]); r.setType(tokens[2]); r.setDate(tokens[3]); if (!userID.equals(tempUserID)) { userNRecords = new UserNRecords(); brandRecords = new ArrayList<Record>(); userNRecords.setUserID(userID); userNRecords.setRecordList(brandRecords); list.add(userNRecords); } brandRecords.add(r); tempUserID = userID; } is.close(); } catch (Exception e) { } }
4
@Override public void addJob(State s, Job j) { VM vm = null; VMType type = null; JobType jobType = j.getType(); double utilization = Double.MAX_VALUE; // Find for (Entry<VMType, UtilizationVector> e : jobType.utilizationVector.entrySet()) { UtilizationVector v = e.getValue(); double u = v.CPU.average + Math.exp(v.RAM.average) + v.disk.average / 1.5 + v.network.average / 1.1; VMType vmtype = e.getKey(); double price = s.getVmTypes().get(vmtype.getName()).getPrice(); double time = jobType.times.get(vmtype).average; u = u * time; if ( u < utilization){ type = e.getKey(); utilization = u; } } boolean foundOne = false; for (VM vm2 : vms) { if (type == vm2.type) { double jobs = 0; for (Job j1 : vm2.getJobs()) { if (!j1.isFinished()) { jobs++; } } if (jobs < factor) { foundOne = true; vm = vm2; break; } } } if (!foundOne) { vm = s.addVM(type, s.getTime()); vms.add(vm); } if (vm == null) { System.err.println("VM cannot be null here."); System.exit(1); } s.log("Job #" + j.getId() + " assigned to VM #" + vm.id); j.assignVM(vm); }
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(RegistrationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(RegistrationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(RegistrationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(RegistrationUI.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 RegistrationUI().setVisible(true); } }); }
6
public void visitFieldInsn( final int opcode, final String owner, final String name, final String desc){ mv.visitFieldInsn(opcode, owner, name, desc); if(constructor) { char c = desc.charAt(0); boolean longOrDouble = c == 'J' || c == 'D'; switch(opcode) { case GETSTATIC: pushValue(OTHER); if(longOrDouble) { pushValue(OTHER); } break; case PUTSTATIC: popValue(); if(longOrDouble) { popValue(); } break; case PUTFIELD: popValue(); if(longOrDouble) { popValue(); popValue(); } break; // case GETFIELD: default: if(longOrDouble) { pushValue(OTHER); } } } }
9
@Override public ILDAPRetrievalService buildService() throws LDAPServiceCreationException { ILDAPRetrievalService service = null; if (this.getLDAPResource().getServerVendor().equals(LDAPServiceProviderType.APACHEDS_SERVICE_PROVIDER.name())) { try { service = new org.sharpsw.ldap.services.apacheds.RetrievalServiceImpl(this.getConnectionFactory().getConnection(this.getLDAPResource()), this.getLDAPResource()); } catch (LDAPException exception) { throw new LDAPServiceCreationException("Error when creating the admin service", exception); } } else if (this.getLDAPResource().getServerVendor().equals(LDAPServiceProviderType.MS_ACTIVE_DIRECTORY_2003_SERVICE_PROVIDER.name())) { try { service = new org.sharpsw.ldap.services.msad.RetrievalServiceImpl(this.getConnectionFactory().getConnection(this.getLDAPResource()), this.getLDAPResource()); } catch (LDAPException exception) { throw new LDAPServiceCreationException("Error when creating the service", exception); } } else if (this.getLDAPResource().getServerVendor().equals(LDAPServiceProviderType.OPEN_LDAP_SERVICE_PROVIDER.name())) { try { service = new org.sharpsw.ldap.services.openldap.RetrievalServiceImpl(this.getConnectionFactory().getConnection(this.getLDAPResource()), this.getLDAPResource(), new DistinguishedNameBuilder()); } catch (LDAPException exception) { throw new LDAPServiceCreationException("Error when creating the service", exception); } } else { StringBuffer buffer = new StringBuffer(); buffer.append("Invalid service provider supplied: ").append(this.getLDAPResource().getServerVendor()); throw new LDAPServiceCreationException(buffer.toString()); } return service; }
6
public static void traversal(TreeNode root, int sum) { if (null == root) return; if (null == root.left && null == root.right && sum == root.val) { stack.add(root.val); List<Integer> items = new ArrayList<Integer>(); for (Integer i : stack) { items.add(i); } res.add(items); } else { stack.add(root.val); traversal(root.left, sum - root.val); traversal(root.right, sum - root.val); } stack.remove(stack.size() - 1); return; }
5
public String stOpenBrowserInstance (int dataid,int expVal, String flow){ int actVal=1000; String returnVal=null; hm.clear(); hm=STFunctionLibrary.stMakeData(dataid, "Post"); String url = hm.get("URL"); String newwindowtitle = hm.get("NewWindowTitle"); try { Block : { /*Open New window*/ browser.open(url); // browser.openWindow(url, newwindowtitle); try { Thread.sleep(15000); } catch (InterruptedException e) { e.printStackTrace(); } /*Select newly open window*/ browser.selectWindow(newwindowtitle); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } String browsertitle = browser.getTitle(); if (browsertitle.contains(newwindowtitle)) { actVal = 0; /*Browser instance opens successfully*/ break Block; } else { actVal= 1;/*Failed to open Browser instance*/ break Block; } } } catch (SeleniumException sexp) { Reporter.log(sexp.getMessage()); } returnVal=STFunctionLibrary.stRetValDes(expVal, actVal, "stOpenBrowserInstance",flow, hm); if(flow.contains("STOP")){ assertEquals("PASS",returnVal); } return returnVal; }
5
private void selectAnimalChange( Animal nouvelAnimal ) { animalSelect = nouvelAnimal; positions = animalSelect.getPositions(); positionsAff = animalSelect.getPositions(); nomAnimal = animalSelect.getNom(); afficherDonnees(); }
0
public IntTreeBag() { this.root = null; }
0
private static String escape(String str) { int len = str.length(); StringWriter writer = new StringWriter((int) (len * 0.1)); for (int i = 0; i < len; i++) { char c = str.charAt(i); switch (c) { case '"': writer.write("&quot;"); break; case '&': writer.write("&amp;"); break; case '<': writer.write("&lt;"); break; case '>': writer.write("&gt;"); break; case '\'': writer.write("&apos;"); break; default: if (c > 0x7F) { writer.write("&#"); writer.write(Integer.toString(c, 10)); writer.write(';'); } else { writer.write(c); } } } return writer.toString(); }
7
public double Opera(char operando, String verificaPosicao, String [] guardaVariavel, double [] guardaValores, int linhasGuardaVariavel){ double result=0; String aux2=verificaPosicao.substring(verificaPosicao.indexOf("=")+1, verificaPosicao.indexOf(operando));//variavel antes do token + - / * % String aux3=verificaPosicao.substring(verificaPosicao.indexOf(operando)+1, verificaPosicao.indexOf(";"));//variavel depois do token double auxiliar=verGuardaVar2(aux2, guardaVariavel, guardaValores, linhasGuardaVariavel);//auxiliar recebe o valor após o = double auxiliar3=verGuardaVar3(aux3, guardaVariavel, guardaValores, linhasGuardaVariavel);//auxiliar recebe o valor depois do token da operação if(operando == '+'){ result=auxiliar+auxiliar3;//Adiçao } else if(operando == '-'){ result=auxiliar-auxiliar3;//Subtraçao } else if(operando == '*'){ result=auxiliar*auxiliar3;//Multiplicaçao } else if(operando == '%'){ result=auxiliar%auxiliar3;//Modulo } else if(operando == '/'){ result=auxiliar/auxiliar3;//Divisao } else if(operando == '='){ result=auxiliar;//novo valor a ser atribuido } return result; //retorna o resultado da operação }
6
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed Helpers.setMinTransfer(jTextField1.getText()); String assetID = "ALL"; if (assetList != null && assetList.size() > 0 && jComboBox6.getSelectedIndex() > -1) { System.out.println("----ind:" + (Integer) jComboBox6.getSelectedIndex()); System.out.println("----Value:" + assetList.get((Integer) jComboBox6.getSelectedIndex())); assetID = ((String[]) assetList.get((Integer) jComboBox6.getSelectedIndex()))[1]; } Helpers.addBasketExistingAssets(assetID); Helpers.setSubCurrency(assetID); this.dispose(); }//GEN-LAST:event_jButton2ActionPerformed
3
public static void main(String args[]) { try { //RXgN^IȂƂ͐ɂōsB if (args.length >= 1) { infroot = args[0]; if (args.length >= 2) { clusterMax = Integer.parseInt(args[1]); if (args.length >= 3) { maxIter = Integer.parseInt(args[2]); } } } } catch (Exception e) { System.out.println("Usage: matz.EM[ <ROOT_DIR>[ <#_OF_CLUSTER>[ <#_OF_ITERATION>]]]"); System.out.println("Note: Arguments must follow the order above."); e.printStackTrace(); return; } try { //if (args.length >= 1) clusterMax = Integer.parseInt(args[0]); //̏ݒ͏try߂Ɉړ //if (args.length >= 2) maxIter = Integer.parseInt(args[1]); //Ƀf[^T File rootPath = new File(infroot); File[] dataDirs = rootPath.listFiles(regex("retweetLog[\\d]+")); for (File dir : dataDirs) { String[] dataFileNames = dir.list(regex("[\\d]+\\.csv")); for (String fileName : dataFileNames) { File resFile = new File(dir, fileName.replaceAll("([\\d]+\\.)(csv)", "$1res.$2")); //ʏo͐ if (!resFile.exists()) { //o̓t@C݂(ɏς݂)f[^͖ File dataFile = new File(dir, fileName); //͌ new EM(dataFile, resFile); } } } } catch(FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
9
public void connect() throws Exception { URLConnection yc = website.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); }
1
public void setShortMessageFontstyle(Fontstyle fontstyle) { if (fontstyle == null) { this.shortMessageFontStyle = UIFontInits.SHORTMESSAGE.getStyle(); } else { this.shortMessageFontStyle = fontstyle; } somethingChanged(); }
1
public String stFacebookSharingVerification(int dataId,int ExpVal,String flow ) { int actVal=1000; String returnVal=null; hm.clear(); hm=STFunctionLibrary.stMakeData(dataId, "Post"); String url = hm.get("URL"); String newwindowtitle = hm.get("NewWindowTitle"); String sharingtitle = hm.get("SharingTitle"); STCommonLibrary comLib=new STCommonLibrary(); Vector<String> xPath=new Vector<String>(); Vector<String> errorMsg=new Vector<String>(); try { Block: { /*Open new window for facebook*/ browser.openWindow(url, newwindowtitle); try { Thread.sleep(15000); } catch (InterruptedException e) { e.printStackTrace(); } /*Select newly open window*/ browser.selectWindow(newwindowtitle); /* Clicking on Home link to refresh the FB wall */ comLib.stClick(FACEBOOK_HOME_LINK, "Facebook Home link not found on FB wall", ""); try { Thread.sleep(25000); } catch (InterruptedException e) { e.printStackTrace(); } /*Verification of shared post on Facebook */ xPath.add(FACEBOOK_POST_TITLE); errorMsg.add("Shared Title is not present"); comLib.stVerifyObjects(xPath, errorMsg, flow); xPath.clear(); errorMsg.clear(); String getposttitle = browser.getText(FACEBOOK_POST_TITLE); //String getposttitle = browser.getText(FACEBOOK_POST_SHARED_TITLE); System.out.println("getposttitle " +getposttitle); System.out.println("sharingtitle :" +sharingtitle); /* Comparing Sharing Title */ if(sharingtitle.contains(getposttitle)) { actVal= 0; /*Sharing Post is matching on Facebook */ break Block; } else { actVal= 1; /*Sharing post is not matching*/ break Block; } } } catch (SeleniumException sexp) { Reporter.log(sexp.getMessage()); } returnVal=STFunctionLibrary.stRetValDes(ExpVal, actVal, "stFacebookSharingVerification",flow, hm); if(flow.contains("STOP")){ assertEquals("PASS",returnVal); } return returnVal; }
5
private ApiProfileImpl() throws ProfileExceptions { String defaultPath = new File("").getAbsolutePath().toString() + BitMusicStructure; if(!Files.exists(FileSystems.getDefault().getPath(defaultPath))) { try { Files.createDirectory(FileSystems.getDefault().getPath(defaultPath)); } catch(IOException io) { throw new ProfileExceptions(io.toString()); } } if(!Files.exists(FileSystems.getDefault().getPath(defaultPath + profilesStructure))) { try { Files.createDirectory(FileSystems.getDefault().getPath(defaultPath + profilesStructure)); } catch (IOException ex) { throw new ProfileExceptions(ex.toString()); } } }
4
public void getPermissoesRelatorios() { item_relAtendimentoAnalitico.setVisible(permissoes.getRelAtendimentoAnalitico()); item_relAtendimentoSintetico.setVisible(permissoes.getRelAtendimentoSintetico()); item_relClienteByLink.setVisible(permissoes.getRelClientesByLink()); item_relClienteBySegmento.setVisible(permissoes.getRelClientesBySegmento()); item_relInformacoes.setVisible(permissoes.getRelInformacoes()); item_relUsuario.setVisible(permissoes.getRelUsuarios()); if ((permissoes.getRelAtendimentoAnalitico() == false) && (permissoes.getRelAtendimentoSintetico() == false) && (permissoes.getRelClientesByLink() == false) && (permissoes.getRelClientesBySegmento() == false) && (permissoes.getRelInformacoes() == false) && (permissoes.getRelUsuarios() == false)) { Menu_Relatorios.setVisible(false); } }
6
public Complex log() { double rpart = Math.sqrt(re * re + im * im); double ipart = Math.atan2(im, re); if(ipart > Math.PI) { ipart = ipart - 2.0 * Math.PI; } return new Complex(Math.log(rpart), ipart); }
1
public void getMultiPart(Multipart content) { try { int multiPartCount = content.getCount(); for (int i = 0; i < multiPartCount; i++) { BodyPart bodyPart = content.getBodyPart(i); Object o; o = bodyPart.getContent(); if (o instanceof String) { maildata.append(o+"\n"); } else if (o instanceof Multipart) { getMultiPart((Multipart) o); } } } catch (IOException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } }
5
private synchronized void sendTo(ClientThread client, ChatMessage message) { //envoyer un message à un destinataire en particulier (pour MPs et connexions) message.setDest(client.username); if (message.getSender().equals("null")) message.setSender("Serveur"); message.setTimeStamp(simpleDate.format(new Date()).toString()); String whatToWrite = message.getTimeStamp() + " " + message.getSender() + " --> " + message.getDest() + " : "; if (message.getType() == ChatMessage.KEYCommon || message.getType() == ChatMessage.KEYPrivate || message.getType() == ChatMessage.KEYPublic) whatToWrite += " échange de clés."; else whatToWrite += "Message"; serverUI.appendRoom(whatToWrite + "\n"); //affiche le message (crypté bien sûr) dans la fenêtre chat du serveur et son destinataire ChatMessage messageToSend = new ChatMessage(message); for(int i = clientList.size(); --i >= 0;) { //idem que pour brodcast sauf qu'on n'enverra qu'au client qui correspond ClientThread clientToMessage = clientList.get(i); messageToSend.setMessage(clientToMessage.clientKeys.encrypt(message.getMessage()).toString()); //on chiffre avec la clé du destinataire if(clientToMessage.id == client.id && !client.writeMsg(messageToSend)) { //on garde la boucle afin de pouvoir supprimer le client en cas de perte de connexion clientList.remove(i); display(clientToMessage.username + " ne répond plus. Déconnecté du serveur."); break; } } }//sendTo
7
int backward(int cur) { _optimumEndIndex = cur; int posMem = _optimum[cur].PosPrev; int backMem = _optimum[cur].BackPrev; do { if (_optimum[cur].Prev1IsChar) { _optimum[posMem].makeAsChar(); _optimum[posMem].PosPrev = posMem - 1; if (_optimum[cur].Prev2) { _optimum[posMem - 1].Prev1IsChar = false; _optimum[posMem - 1].PosPrev = _optimum[cur].PosPrev2; _optimum[posMem - 1].BackPrev = _optimum[cur].BackPrev2; } } int posPrev = posMem; int backCur = backMem; backMem = _optimum[posPrev].BackPrev; posMem = _optimum[posPrev].PosPrev; _optimum[posPrev].BackPrev = backCur; _optimum[posPrev].PosPrev = cur; cur = posPrev; } while (cur > 0); backRes = _optimum[0].BackPrev; _optimumCurrentIndex = _optimum[0].PosPrev; return _optimumCurrentIndex; }
3
public void moveVisibleAreaToCoord(double xCoord, double yCoord) { visibleArea.setCoord(xCoord - (visibleArea.getxLength() / 2), yCoord - (visibleArea.getyLength() / 2), visibleArea.getxLength(), visibleArea.getyLength()); searchXCoord = getWidth() / 2; searchYCoord = getHeight() / 2; timer.purge(); timer.cancel(); timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { if (xlength <= quadTreeToDraw.getQuadTreeLength() / 180) { timer.cancel(); timer.purge(); searchYCoord = 0; searchXCoord = 0; zoomInConstant = 0.98; } else { zoomInConstant = 0.99 - Math.log(xlength)*0.0014; zoomIn(searchXCoord, searchYCoord); repaint(); } } }; timer.scheduleAtFixedRate(task, 10, 10); }
1
public VentanaPrincipal(ListaTexto textoOriginal, ListaTexto textoNuevo) { //iniciar Objetos this.miTextoOriginal = textoOriginal; this.miTextoNuevo = textoNuevo; miMaestroControlador = new MaestroControlador(miTextoOriginal, miTextoNuevo); //iniciar propiedades del frame setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(0, 0, 450, 300); setResizable(false); setTitle("Formato texto"); contentPane = new JPanel(); contentPane.setBackground(Color.GRAY); //contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(null); setContentPane(contentPane); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); setSize((int) d.getWidth(), (int) d.getHeight()-39); scrollPane = new JScrollPane(); scrollPane.setBounds(10, 100, 658, 568); contentPane.add(scrollPane); //iniciar atributos del frame jEPIzq = new JEditorPane(); jEPIzq.setText(""); jEPIzq.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { actualizarTextoOriginal(e); } }); scrollPane.setViewportView(jEPIzq); scrollPane_1 = new JScrollPane(); scrollPane_1.setBounds(688, 100, 658, 568); contentPane.add(scrollPane_1); jEPDer = new JEditorPane(); jEPDer.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { e.consume(); } }); scrollPane_1.setViewportView(jEPDer); grupoRBotones = new ButtonGroup(); btnAbrir = new JButton("Abrir"); btnAbrir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { abrirArchivo(); try { archivo = new File (fc.getSelectedFile().toString()); fr = new FileReader (archivo); br = new BufferedReader(fr); int i = 0; String linea; while((linea=br.readLine())!=null){ if(i ==0){ jEPIzq.setText(linea); i++; } else jEPIzq.setText(jEPIzq.getText()+"\n"+linea); } } catch(Exception ex){ ex.printStackTrace(); }finally{ try{ if( null != fr ){ fr.close(); } }catch (Exception e2){ e2.printStackTrace(); } } miMaestroControlador.actualizarTextoOriginal(new StringBuilder(jEPIzq.getText().toString())); jEPDer.setText(miMaestroControlador.getTextoNuevo().toString());; } }); btnAbrir.setBounds(10, 31, 89, 23); contentPane.add(btnAbrir); rdbtnPreposiciones = new JRadioButton("Mostrar preposiciones"); rdbtnPreposiciones.setBounds(120, 31, 165, 23); contentPane.add(rdbtnPreposiciones); grupoRBotones.add(rdbtnPreposiciones); rdbtnTildadas = new JRadioButton("Palabras t\u00EDldadas"); rdbtnTildadas.setBounds(308, 31, 138, 23); contentPane.add(rdbtnTildadas); grupoRBotones.add(rdbtnTildadas); rdbtnInverso = new JRadioButton("Orden inverso"); rdbtnInverso.setBounds(653, 31, 109, 23); contentPane.add(rdbtnInverso); grupoRBotones.add(rdbtnInverso); rdbtnAlfabeticamente = new JRadioButton("Ordenar alfabeticamente"); rdbtnAlfabeticamente.setBounds(993, 31, 183, 23); contentPane.add(rdbtnAlfabeticamente); grupoRBotones.add(rdbtnAlfabeticamente); btnCambiarSentido = new JButton("<="); btnCambiarSentido.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { jEPIzq.setText(jEPDer.getText()); } }); btnCambiarSentido.setBounds(653, 72, 49, 23); contentPane.add(btnCambiarSentido); btnEliminarPalabra = new JButton("Eliminar palabra"); btnEliminarPalabra.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String aEliminar = JOptionPane.showInputDialog(null, "Cual eliminar?","Opcion Eliminar",JOptionPane.QUESTION_MESSAGE); if(!aEliminar.toString().equals("")){ jEPDer.setText(miMaestroControlador.textoEliminar(aEliminar).toString()); } } }); btnEliminarPalabra.setBounds(476, 31, 145, 23); contentPane.add(btnEliminarPalabra); btnReemplazarPalabra = new JButton("Reemplazar palabra"); btnReemplazarPalabra.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String aReemplazarVieja = JOptionPane.showInputDialog(null, "Cual reemplazar?","Opcion Reemplazar",JOptionPane.QUESTION_MESSAGE); String aReemplazarNueva = JOptionPane.showInputDialog(null, "Reemplazar con","Opcion Reemplazar",JOptionPane.QUESTION_MESSAGE); if(!aReemplazarVieja.toString().equals("")){ jEPDer.setText(miMaestroControlador.textoReemplazar(aReemplazarVieja, aReemplazarNueva).toString()); } } }); btnReemplazarPalabra.setBounds(793, 31, 165, 23); contentPane.add(btnReemplazarPalabra); rdbtnNinguno = new JRadioButton("Ninguno"); rdbtnNinguno.setBounds(1210, 31, 109, 23); rdbtnNinguno.setSelected(true); contentPane.add(rdbtnNinguno); grupoRBotones.add(rdbtnNinguno); }
7
@Override public List<StrasseDTO> findStreetsByStartPoint(Long startPunktId, boolean b) { List<StrasseDTO> ret = new ArrayList<StrasseDTO>(); if(startPunktId ==1){ StrasseDTO s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(1)); s.setEndPunktId(Long.valueOf(2)); s.setDistanz(Long.valueOf(11)); s.setSpeed(120); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(1)); s.setEndPunktId(Long.valueOf(5)); s.setDistanz(Long.valueOf(9)); s.setSpeed(50); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(1)); s.setEndPunktId(Long.valueOf(6)); s.setDistanz(Long.valueOf(9)); s.setSpeed(80); ret.add(s); } else if(startPunktId==2) { StrasseDTO s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(2)); s.setEndPunktId(Long.valueOf(1)); s.setDistanz(Long.valueOf(11)); s.setSpeed(120); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(2)); s.setEndPunktId(Long.valueOf(3)); s.setDistanz(Long.valueOf(2)); s.setSpeed(50); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(2)); s.setEndPunktId(Long.valueOf(6)); s.setDistanz(Long.valueOf(5)); s.setSpeed(80); ret.add(s); } else if(startPunktId==3) { StrasseDTO s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(3)); s.setEndPunktId(Long.valueOf(2)); s.setDistanz(Long.valueOf(2)); s.setSpeed(50); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(3)); s.setEndPunktId(Long.valueOf(4)); s.setDistanz(Long.valueOf(4)); s.setSpeed(50); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(3)); s.setEndPunktId(Long.valueOf(6)); s.setDistanz(Long.valueOf(1)); s.setSpeed(30); ret.add(s); } else if(startPunktId==4) { StrasseDTO s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(4)); s.setEndPunktId(Long.valueOf(3)); s.setDistanz(Long.valueOf(4)); s.setSpeed(50); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(4)); s.setEndPunktId(Long.valueOf(5)); s.setDistanz(Long.valueOf(9)); s.setSpeed(60); ret.add(s); } else if(startPunktId==5) { StrasseDTO s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(5)); s.setEndPunktId(Long.valueOf(1)); s.setDistanz(Long.valueOf(9)); s.setSpeed(50); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(5)); s.setEndPunktId(Long.valueOf(4)); s.setDistanz(Long.valueOf(9)); s.setSpeed(60); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(5)); s.setEndPunktId(Long.valueOf(6)); s.setDistanz(Long.valueOf(2)); s.setSpeed(50); ret.add(s); } else { StrasseDTO s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(6)); s.setEndPunktId(Long.valueOf(1)); s.setDistanz(Long.valueOf(9)); s.setSpeed(80); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(6)); s.setEndPunktId(Long.valueOf(2)); s.setDistanz(Long.valueOf(5)); s.setSpeed(80); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(6)); s.setEndPunktId(Long.valueOf(3)); s.setDistanz(Long.valueOf(1)); s.setSpeed(30); ret.add(s); s= new StrasseDTO(); s.setStartPunktId(Long.valueOf(6)); s.setEndPunktId(Long.valueOf(5)); s.setDistanz(Long.valueOf(2)); s.setSpeed(50); ret.add(s); } return ret; }
5
void generateAddrModeClasses() throws IOException { setPrinter(newInterfacePrinter("addr", hashMapImport, null, tr("The <code>$addr</code> class represents an addressing mode for this architecture. An " + "addressing mode fixes the number and type of operands, the syntax, and the encoding format " + "of the instruction."))); println("public void accept($instr i, $addrvisitor v);"); for ( AddrModeSetDecl as : arch.addrSets ) { startblock("public interface $1 extends $addr", as.name); for ( AddrModeDecl.Operand o : as.unionOperands ) println("public $operand get_$1();", o.name); endblock(); } List<AddrModeDecl> list = new LinkedList<AddrModeDecl>(); for ( AddrModeDecl am : arch.addrModes ) list.add(am); for ( InstrDecl id : arch.instructions ) { // for each addressing mode declared locally if ( id.addrMode.localDecl != null && DGUtil.addrModeClassExists(id) ) list.add(id.addrMode.localDecl); } for ( AddrModeDecl am : list ) emitAddrMode(am); endblock(); close(); emitAddrModeVisitor(list); }
7
@Override public double getTipValue() { double tip = 0.00; // always initialize local variables switch(serviceQuality) { case GOOD: tip = baseTipPerBag * bagCount * (1 + GOOD_RATE); break; case FAIR: tip = baseTipPerBag * bagCount * (1 + FAIR_RATE); break; case POOR: tip = baseTipPerBag * bagCount * (1 + POOR_RATE); break; } return tip; }
3
public void windowActivated(WindowEvent e) { // TODO Auto-generated method stub }
0
public int getWidth() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getWidth(); } else { return 0; } }
1
public int remove(Long objId){ for(Town i: towns){ if(i.getId().equals(objId)){ towns.remove(i); return 0; } } for(Airport i: aports){ if(i.getAirportId().equals(objId)){ aports.remove(i); return 0; } } return 0; }
4
public final void setContext(String context, CLC contextController) { if(contextMap.containsKey(context)) { System.out.println("[CLC] Warning: There is already a context controller associated with the context "+ context); } contextMap.put(context, contextController); }
1
@Test public void testCancelButtonAfterCalculated() throws Exception { propertyChangeSupport.firePropertyChange(DialogWindowController.CALCULATED, 0, 1); assertEquals(view.getButton().isEnabled(), false); view.close(); assertEquals(view.getButton().isEnabled(), true); }
0
public void test_getDefault_checkRedundantSeparator() { try { PeriodFormat.getDefault().parsePeriod("2 days and 5 hours "); fail("No exception was caught"); } catch (Exception e) { assertEquals(IllegalArgumentException.class, e.getClass()); } }
1
private void writeJSON(Object value) throws JSONException { if (JSONObject.NULL.equals(value)) { write(zipNull, 3); } else if (Boolean.FALSE.equals(value)) { write(zipFalse, 3); } else if (Boolean.TRUE.equals(value)) { write(zipTrue, 3); } else { if (value instanceof Map) { value = new JSONObject((Map) value); } else if (value instanceof Collection) { value = new JSONArray((Collection) value); } else if (value.getClass().isArray()) { value = new JSONArray(value); } if (value instanceof JSONObject) { write((JSONObject) value); } else if (value instanceof JSONArray) { write((JSONArray) value); } else { throw new JSONException("Unrecognized object"); } } }
8
private int getPlayerIndexInGame(String username, List<PlayerDescription> players) { int playerGameIndex = -1; for (int i = 0; i < players.size(); i++) { PlayerDescription pd = players.get(i); if(pd.getName().equals(username)) { playerGameIndex = i; break; } } return playerGameIndex; }
2
public Rule.Action getMatchedAction(Message message) { for (Rule rule : this.rules) { if (rule.isMatched(message)) { return rule.getAction(); } } return null; }
2
@Override public ArrayList<String> getGoToList() { // TODO Auto-generated method stub return null; }
0
private void inputBestValue(){ double ansd = 0; String ans = null; ans = (String)JOptionPane.showInputDialog(this, "Best Value", "Other", JOptionPane.PLAIN_MESSAGE, null, null, String.valueOf(obj_sel.minC + (obj_sel.maxC - obj_sel.minC)/2)); //suggest the median value try{ if ((ans != null) && (ans.length() > 0)) { ansd = (Double.valueOf(ans)).doubleValue(); if (ansd <= obj_sel.maxC && ansd >= obj_sel.minC) obj_sel.setContinuous(ansd); else{ JOptionPane.showMessageDialog(this, "Out of range", "Error", JOptionPane.WARNING_MESSAGE); inputBestValue(); } } }catch(NumberFormatException e){ JOptionPane.showMessageDialog(this, "Invalid Entry", "Error", JOptionPane.WARNING_MESSAGE); inputBestValue(); } }
5
public AbstractMatrix(int m, int n) { if (n <= 0 || m <= 0) { try { throw new Exception( "The matrix has to have a size of at least 1 x 1."); } catch (Exception e) { e.printStackTrace(); } } this.m = m; this.n = n; }
3
public DataModel<PacienteBean> listaPacientes() { PacienteDAO paciente = new PacienteDAO(); if (paciente.getPacientes() != null) { pacientesBean.removeAll(pacientesBean); for (PacienteDAO p : paciente.getPacientes()) { pacientesBean.add(new PacienteBean(p.getId(), p.getNome(), p.getDataNasc(), p.getLogradouro(), p.getNumero(), p.getBairro(), p.getCidade(), p.getUf())); } return new ListDataModel(pacientesBean); } return null; }
2
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProcedureCallNode other = (ProcedureCallNode) obj; if (actualParameters == null) { if (other.actualParameters != null) return false; } else if (!actualParameters.equals(other.actualParameters)) return false; if (ident == null) { if (other.ident != null) return false; } else if (!ident.equals(other.ident)) return false; return true; }
9
private String getText() throws ParsingException { Characters c = lastEvent.asCharacters(); // Ignore empty content if (!c.isWhiteSpace()) { return c.toString(); } else { return ""; } }
1
public AlarmCreater(MainFrame parent){ this.parent = parent; try { aal = new Alarm_AccessLink(); } catch (IOException ex) { JOptionPane.showMessageDialog(parent, "An sql error has occured: " + ex.getMessage()); } initComponents(); txtTime.setValue(System.currentTimeMillis()-3600000); Date currentDate = new Date(System.currentTimeMillis()-3600000); txtDate.setValue(System.currentTimeMillis()-3600000); setSize(300, 100); setBackground(MyConstants.COLOR_BLUE); setForeground(Color.WHITE); setButtonColors(); btnCancel.addActionListener(new MyActionListener()); btnAccept.addActionListener(new MyActionListener()); btnAccept.setEnabled(false); txtDestination.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if(!txtDestination.getText().equals("") && !txtType.getText().equals("")) btnAccept.setEnabled(true); else btnAccept.setEnabled(false); } }); txtType.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if(!txtDestination.getText().equals("") && !txtType.getText().equals("")) btnAccept.setEnabled(true); else btnAccept.setEnabled(false); } }); }
5
@Override public void handle(HttpExchange he) throws IOException { String method = he.getRequestMethod().toUpperCase(); response = ""; status = 0; switch (method) { case "GET": getRequest(he); break; case "POST": postRequest(he); break; case "DELETE": deleteRequest(he); break; case "PUT": putRequest(he); break; } he.getResponseHeaders().add("Content-Type", "application/json"); sr.sendMessage(he, status, response); }
4
public void mousePressed(MouseEvent e) { if((e.isControlDown())&&(e.getButton()==BUTTON1)) { markerRect=new MarkerRect(MapGetter.getLatitude(e.getY()),MapGetter.getLongtitude(e.getX())); //MainView.createPoint(MapGetter.getLongtitude(e.getX()), MapGetter.getLatitude(e.getY())); } markerRect.selectSize(e.getX(), e.getY()); mouseStartX=e.getX(); mouseStartY=e.getY(); //mouse_x=e.getX(); //mouse_y=e.getY(); System.out.println("X:"+Integer.toString(e.getX())); System.out.println("Y:"+Integer.toString(e.getY())); repaint(); // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. }
2
@Test public void testAwaitAsyncExecutionSuccess() { SyncProcess proc = TestUtil.executionSuccessSyncProcess(); IProcessComponent<Void> busyComp = new BusyComponent(TestUtil.executionSuccessComponent(true)); IProcessComponent<?> asyncComp = new AsyncComponent<Void>(busyComp); proc.add(asyncComp); try { proc.execute(); } catch (InvalidProcessStateException ex) { fail(); } catch (ProcessExecutionException ex) { fail("Should execute successfully."); } assertTrue(proc.getState() == ProcessState.EXECUTION_SUCCEEDED); assertTrue(asyncComp.getState() == ProcessState.EXECUTION_SUCCEEDED); }
3
private void registerButtonActionPerformed() { ArrayList<ScheduleDTO> schedule = saleTrainsTableModel.getTrains(); request.setService(Constants.ClientService.buyTicket); int row = saleTrainsTable.getSelectedRow(); if (row == -1) { JOptionPane.showMessageDialog(null, "Не выбран поезд"); return; } order.setTrainNumber(schedule.get(row).getNumber()); order.setFromStation(schedule.get(row).getFromStation()); if (order.getFirstName() == null || order.getFirstName() == "") { JOptionPane.showMessageDialog(null, "Некорректно введено имя. Повторите ввод."); return; } else if (order.getSecondName() == null || order.getSecondName() == "") { JOptionPane.showMessageDialog(null, "Некорректно введена фамилия. Повторите ввод."); return; } request.setObject(order); ResponseDTO responce; try { responce = ClientConnectionManager.connect(request); } catch (ConnectToServerException ex) { JOptionPane.showMessageDialog(null, ex.getMessage()); return ; } if (responce.getStatus() == Constants.StatusOfExecutedService.success) { JOptionPane.showMessageDialog(null, "Пассажир успешно зарегистрирован"); } else if (responce.getStatus() == Constants.StatusOfExecutedService.error) { JOptionPane.showMessageDialog(null, ((Exception)responce.getObject()).getMessage()); } clearSaleWidgetsContent(); }
8
public static JSONArray freeGPIOs() { JSONArray freeList = new JSONArray(); DTO dtoCreator = new DTO(); String pinmuxFile = "/sys/kernel/debug/pinctrl/"+baseOffset+".pinmux/pinmux-pins"; try { BufferedReader pinmux = new BufferedReader(new FileReader(pinmuxFile)); // get rid of the first two lines String pin = null; while ((pin = pinmux.readLine()) != null) { if (pin.contains("(MUX UNCLAIMED) (GPIO UNCLAIMED)")) { // add this to our list // pin is of form "pin 8 (44e10820): (MUX UNCLAIMED) (GPIO UNCLAIMED)" try { String[] pinExplode = pin.split(" "); String address = pinExplode[2].replace("(", ""); address = address.replace("):", ""); String offset = String.format("0x%03x", (Integer.decode("0x"+address) - Integer.decode("0x"+baseOffset))); // we now have the offset JSONObject pinJSON = dtoCreator.findDetailsByOffset(offset); if(pinJSON != null) { freeList.add(pinJSON); } } catch (NumberFormatException e) { // ignore these, these are the leading lines System.out.println(e.getMessage()); } } } return freeList; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
6
public static Image load(File imageFile) { Image input = new Image(Display.getCurrent(), imageFile.getAbsolutePath()); // go check if we have to rotate it Image result = null; try { Metadata metaData = ImageMetadataReader.readMetadata(imageFile); if (metaData.containsDirectory(ExifIFD0Directory.class)) { int angle = 0; switch (metaData.getDirectory(ExifIFD0Directory.class).getInt( ExifIFD0Directory.TAG_ORIENTATION)) { case 6: angle = 90; break; case 8: angle = -90; break; } if (0 != angle) { result = new Image(Display.getCurrent(), input.getBounds().height, input.getBounds().width); GC gc = new GC(result); gc.setAdvanced(true); Rectangle b = input.getBounds(); Transform transform = new Transform(Display.getCurrent()); // The rotation point is the center of the image transform.translate(b.height / 2, b.width / 2); // Rotate transform.rotate(angle); // Back to the orginal coordinate system transform.translate(-b.width / 2, -b.height / 2); gc.setTransform(transform); gc.drawImage(input, 0, 0); gc.dispose(); } } } catch (ImageProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MetadataException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (null == result) result = input; } return result; }
8
public void decode( ByteBuffer socketBuffer ) { if( !socketBuffer.hasRemaining() || flushandclosestate ) return; if( DEBUG ) System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" ); if( readystate == READYSTATE.OPEN ) { decodeFrames( socketBuffer ); } else { if( decodeHandshake( socketBuffer ) ) { decodeFrames( socketBuffer ); } } assert ( isClosing() || isFlushAndClose() || !socketBuffer.hasRemaining() ); }
8
public void actionPerformed(ActionEvent e){ if(e.getSource() == connectbutton){ try { connect(); indicator.setText("Connecting..."); indicator.setForeground(Color.blue); } catch (IOException e1) { } }else if(e.getSource() == sendbutton){ //Show Status indicator.setText("Encrypting"); indicator.setForeground(Color.GREEN); send(); }else if(e.getSource() == disconnect){ try { disconnect(); } catch (IOException e1) { //e1.printStackTrace(); } }else if(e.getSource() == sendbox){ sendbutton.doClick(); } }
6
public void testGoodAnswerGameToBeLost() { System.out.println("Test 2 : gameToBeLost"); Game gameToBeLost = new Game(new GameMaster( DefaultValues.DEFAULTATTEMPTCOMBINATION1), new Board()); Answer answer; // 1. Wrong combinations input. number : Board.SIZE. for (int i = 0; i < Board.SIZE - 1; i++) { answer = gameToBeLost .giveAnswer(DefaultValues.DEFAULTATTEMPTCOMBINATION2); assertEquals(true, answer.more_attempts); assertEquals(false, answer.target_found); assertEquals(i + 1, answer.remaining_attempts); } answer = gameToBeLost.giveAnswer(DefaultValues.DEFAULTATTEMPTCOMBINATION2); assertEquals(false, answer.more_attempts); assertEquals(false, answer.target_found); assertEquals(-1, answer.remaining_attempts); // 2. Another combination attempt (a wrong one). answer = gameToBeLost.giveAnswer(DefaultValues.DEFAULTATTEMPTCOMBINATION2); assertEquals(false, answer.more_attempts); assertEquals(false, answer.target_found); assertEquals(-1, answer.remaining_attempts); // 3. Another combination attempt (the right one). answer = gameToBeLost.giveAnswer(DefaultValues.DEFAULTATTEMPTCOMBINATION1); assertEquals(false, answer.more_attempts); assertEquals(false, answer.target_found); assertEquals(-1, answer.remaining_attempts); }
1
public String get_username(int id) { if(users == null) return ""; List listusers = users.getChildren(); if (listusers != null){ Iterator i = listusers.iterator(); while(i.hasNext()){ Element current = (Element)i.next(); int currid = Integer.parseInt(current.getAttributeValue("id")); if(currid == id) { return current.getAttributeValue("name"); } } } return ""; }
4
ArrayList<Schedule> fitnessCalc(ArrayList<Schedule> schedule){ ArrayList<Schedule> scheduleFit = new ArrayList<>(); Schedule chromoSchedule; //for(int i=0; i) for(int a=0; a<schedule.size(); a++){ chromoSchedule = schedule.get(a); RoomScheme roomA = chromoSchedule.schedule[0][0]; RoomScheme roomB = chromoSchedule.schedule[1][0]; RoomScheme roomC = chromoSchedule.schedule[0][1]; RoomScheme roomD = chromoSchedule.schedule[1][1]; RoomScheme roomE = chromoSchedule.schedule[0][2]; RoomScheme roomF = chromoSchedule.schedule[1][2]; roomA.setFitness(checkFitness(roomA)); roomB.setFitness(checkFitness(roomB)); roomC.setFitness(checkFitness(roomC)); roomD.setFitness(checkFitness(roomD)); roomE.setFitness(checkFitness(roomE)); roomF.setFitness(checkFitness(roomF)); chromoSchedule.schedule[0][0] = roomA; chromoSchedule.schedule[1][0] = roomB; chromoSchedule.schedule[0][1] = roomC; chromoSchedule.schedule[1][1] = roomD; chromoSchedule.schedule[0][2] = roomE; chromoSchedule.schedule[1][2] = roomF; //chromoSchedule.setFitness(roomA.getFitness()); chromoSchedule.setFitness(roomA.getFitness() + roomB.getFitness() + roomC.getFitness() + roomD.getFitness()+ roomE.getFitness() + roomF.getFitness()); scheduleFit.add(chromoSchedule); } return scheduleFit; }
1
public static void removeFromTable(int index) throws NullPointerException { if (tableData!=null){ int datalength = tableData.length -1; Object[][] temp = new Object[datalength][5]; total -= (Integer) (tableData[index][2]) * (Integer) (tableData[index][3]); Item tempitem=new Item(); tempitem.setId((Integer)(tableData[index][0])); Item item = itemList.get(itemList.indexOf(tempitem)); item.changeQuantity((Integer)(tableData[index][2])); modifyItem(item); if (tableData != null) for (int i = 0; i < datalength; i++) for (int j = 0; j < 5; j++){ if (i < index){ temp[i][j] = tableData[i][j]; } else { temp[i][j] = tableData[i+1][j]; } } tableData = temp; } }
5
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed try { String username = usernameTextField.getText(); String password = passwordTextField.getText(); if (password.equals("") || username.equals("")) { JOptionPane.showMessageDialog(this, "Udfyld venligt begge felter","Login fejl",JOptionPane.ERROR_MESSAGE); }else if (dbhandler.isUserCorrectPassword(username, password)) { Employee login = dbhandler.retrieveEmployee(username); MainFrame mf = new MainFrame(login, dbhandler); mf.setVisible(true); }else{ JOptionPane.showMessageDialog(this, "YOU FAILED!","Login fejl",JOptionPane.ERROR_MESSAGE); } } catch (SQLException ex) { Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_loginButtonActionPerformed
4
private int binaryToDecimal(String binaryNumber){ int len = binaryNumber.length(),sum =0,c=0; int e = 0; int multiplier = 0; for(int start=0; start<binaryNumber.length(); start++) { len--; e= (int) Math.pow(2,len); if(binaryNumber.charAt(start) == '0'){ multiplier = 0; } else{ multiplier = 1; } c = multiplier * e; sum=sum+c; } return sum; }
2
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(RDate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(RDate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(RDate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(RDate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new RDate().setVisible(true); } }); }
6
public void notifyPropertyChangeListeners(int oldMoney, int newMoney) { PropertyChangeEvent event = new PropertyChangeEvent(this, "money", oldMoney, newMoney); for(PropertyChangeListener listener:listeners) { listener.propertyChange(event); } }
1
@Override public void run() { try { sendBlockMangerData(); } catch (Exception e) { EIError.debugMsg("Error Sending Block Manager Data..." + e.getMessage()); } }
1
@Override public String toString() { String typ = "Illegal"; switch (type) { case TYPE_HELLO: typ = "Hello"; break; case TYPE_KNOCK: typ = "Knock"; break; case TYPE_BUSY: typ = "Busy"; break; case TYPE_BYE: typ = "Bye"; break; } return "Hello(" + typ + ", " + version + ")"; }
4
public DeviceInfoType createDeviceInfoType() { return new DeviceInfoType(); }
0
private static void doAddTest() { System.out.print("Testing add command "); try { File testFolder = new File( TEST_FOLDER ); // remove mvds File[] mvds = testFolder.listFiles(); for ( int i=0;i<mvds.length;i++ ) { if ( mvds[i].isFile() && mvds[i].getName().endsWith(".mvd") ) mvds[i].delete(); } if ( !testFolder.exists() ) testFolder.mkdir(); File testData = new File( TEST_DATA ); if ( !testData.exists() ) throw new MVDTestException("Missing test data folder"); String[] testFolders = testData.list(); if ( testFolders.length == 0 ) throw new MVDTestException("Nothing in test data folder"); for ( int i=0;i<testFolders.length;i++ ) { File subFolder = new File( testData, testFolders[i] ); if ( subFolder.isDirectory() ) createTestMVD( subFolder ); } testsPassed++; System.out.println(" test passed."); } catch ( Exception e ) { doTestFailed( e ); } }
9
public String[] generateTextFromPicture( BufferedImage im, int aCols ) { Raster data = im.getData(); StringBuffer ret = new StringBuffer(""); double xresolution = im.getWidth() / (double)aCols; double yresolution = xresolution * sHeightToWidthRatio; int lRows = (int) (im.getHeight() / yresolution ); int lCols = aCols; double [][] scores = new double[lRows][lCols]; double min = 1; double max = 0; for ( int row = 0; row < lRows; row++ ) { for ( int col = 0; col < lCols; col++ ) { // determine character for this one int x0 = (int)(col * xresolution); int y0 = (int)(row * yresolution); int dx = (int) xresolution; int dy = (int) yresolution; double score = mPixelAnalyzer.getScoreOfSection(im, x0, y0, dx, dy); scores[row][col] = score; min = Math.min(score, min); max = Math.max(score, max); } } for ( int row = 0; row < lRows; row++ ) { for ( int col = 0; col < lCols; col++ ) { double score = scores[row][col]; score -= min; score = score / ( max - min ); mPixelAnalyzer.addScore(score); char c = mPixelAnalyzer.getBestCharacterForScore(score); ret.append(""+c); } ret.append( System.lineSeparator() ); } return ret.toString().split("\n"); }
4
@SuppressWarnings("unchecked") static boolean setThreadedLocal(String classname, String field, Object value) { if (Functions.isEmpty(classname)) return false; if (Functions.isEmpty(field)) return false; try { Class<?> c = Class.forName(cn(classname)); if (c == null) return false; if (c.isEnum()) return false; Field f = getField(c,field); ThreadLocal<Object> o = (ThreadLocal<Object>) f.get(null); o.set(value); } catch (Exception e) { return false; } return true; }
6
public List<OrderSubstatus> possibleCancellationReasons(OrderStatus for_status) { List<OrderSubstatus> ret = new ArrayList<>(); switch(for_status) { case PROCESSING: ret = Arrays.asList(USER_UNREACHABLE, USER_CHANGED_MIND, USER_REFUSED_DELIVERY, USER_REFUSED_PRODUCT, SHOP_FAILED, REPLACING_ORDER); break; case DELIVERY: case PICKUP: ret = Arrays.asList(USER_UNREACHABLE, USER_CHANGED_MIND, USER_REFUSED_DELIVERY, USER_REFUSED_PRODUCT, USER_REFUSED_QUALITY, SHOP_FAILED); break; default: break; } return ret; }
3
public static void updateUpdater() { File root=new File(Main.path); root.mkdir(); double version=0.0; //Get current updater jar version from web try { URL url=new URL("http://"+Main.ip+"/d0941e68da8f38151ff86a61fc59f7c5cf9fcaa2/computer/updaterVersion.html"); BufferedReader in=new BufferedReader(new InputStreamReader(url.openStream())); String ln; String out=""; while ((ln=in.readLine())!=null) out+=ln; in.close(); version=Double.parseDouble(out); } catch (Exception e) {} File vers=new File(Main.path+"version.txt"); vers.delete(); try { PrintWriter out=new PrintWriter(Main.path+"version.txt"); out.print(version); out.close(); } catch (Exception e) {} File updater=new File(Main.path+"Updater.jar"); updater.delete(); try { URL website = new URL("http://"+Main.ip+"/d0941e68da8f38151ff86a61fc59f7c5cf9fcaa2/computer/Updater.jar"); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(Main.path+"Updater2.jar"); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (Exception e) {e.printStackTrace();} }
4
private void do_cross_validation() { int i; int total_correct = 0; double total_error = 0; double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0; double[] target = new double[prob.l]; svm.svm_cross_validation(prob,param,nr_fold,target); if(param.svm_type == svm_parameter.EPSILON_SVR || param.svm_type == svm_parameter.NU_SVR) { for(i=0;i<prob.l;i++) { double y = prob.y[i]; double v = target[i]; total_error += (v-y)*(v-y); sumv += v; sumy += y; sumvv += v*v; sumyy += y*y; sumvy += v*y; } System.out.print("Cross Validation Mean squared error = "+total_error/prob.l+"\n"); System.out.print("Cross Validation Squared correlation coefficient = "+ ((prob.l*sumvy-sumv*sumy)*(prob.l*sumvy-sumv*sumy))/ ((prob.l*sumvv-sumv*sumv)*(prob.l*sumyy-sumy*sumy))+"\n" ); } else { for(i=0;i<prob.l;i++) if(target[i] == prob.y[i]) ++total_correct; System.out.print("Cross Validation Accuracy = "+100.0*total_correct/prob.l+"%\n"); } }
5
@Override public void run() { while (enabled) { if (logQueue.size() != 0) { StringBuilder stringBuilder = new StringBuilder(); while (logQueue.size() != 0) { stringBuilder.append(logQueue.poll()); } if (file.exists() && file.isFile()) { FileWriter writer = null; try { writer = new FileWriter(file, true); writer.append(stringBuilder.toString()); } catch (IOException e) { Log.w("Unable to write to log file."); e.printStackTrace(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { Log.w("Unable to close writer for log file."); e.printStackTrace(); } } } } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }
9
public DataFinder Where(String field, Object value) throws NoSuchFieldException, SecurityException { Field searchField = searchClass.getField(field); Index annotation = searchField.getAnnotation(Index.class); if (annotation == null) throw new IllegalArgumentException(field); conditions.put(annotation.IndexName(), DataWorker.ConvertValueForIndexing(value)); return this; }
1
public void update() { if (!arrived) { if (Point2D.distance(currentTileX, currentTileY, endTile.getX(), endTile.getY()) < velocity) { currentTileX = endTile.getX(); currentTileY = endTile.getY(); arrived = true; dealDamage(); boom = new Explosion(currentTileX, currentTileY); } else { currentTileX += Math.cos(angle) * velocity; currentTileY += Math.sin(angle) * velocity; } } else if (!finished) { boom.update(); if (boom.isFinished()) { finished = true; } } }
4
private void shiftPaletteBackward() { if(color_cycling_location > 0) { color_cycling_location--; if(color_choice == palette.length - 1) { temp_color_cycling_location = color_cycling_location; } } else { return; } updateColorPalettesMenu(); setOptions(false); progress.setValue(0); resetImage(); backup_orbit = null; whole_image_done = false; if(d3) { Arrays.fill(((DataBufferInt)image.getRaster().getDataBuffer()).getData(), 0, image_size * image_size, Color.BLACK.getRGB()); } if(filters[ANTIALIASING] || (domain_coloring && use_palette_domain_coloring)) { if(julia_map) { createThreadsJuliaMap(); } else { createThreads(); } calculation_time = System.currentTimeMillis(); if(julia_map) { startThreads(julia_grid_first_dimension); } else { startThreads(n); } } else { if(d3) { createThreads(); } else { createThreadsPaletteAndFilter(); } calculation_time = System.currentTimeMillis(); startThreads(n); } }
9
private Object resume(Context cx, Scriptable scope, int operation, Object value) { if (savedState == null) { if (operation == GENERATOR_CLOSE) return Undefined.instance; Object thrown; if (operation == GENERATOR_THROW) { thrown = value; } else { thrown = NativeIterator.getStopIterationObject(scope); } throw new JavaScriptException(thrown, lineSource, lineNumber); } try { synchronized (this) { // generator execution is necessarily single-threaded and // non-reentrant. // See https://bugzilla.mozilla.org/show_bug.cgi?id=349263 if (locked) throw ScriptRuntime.typeError0("msg.already.exec.gen"); locked = true; } return function.resumeGenerator(cx, scope, operation, savedState, value); } catch (GeneratorClosedException e) { // On closing a generator in the compile path, the generator // throws a special exception. This ensures execution of all pending // finalizers and will not get caught by user code. return Undefined.instance; } catch (RhinoException e) { lineNumber = e.lineNumber(); lineSource = e.lineSource(); savedState = null; throw e; } finally { synchronized (this) { locked = false; } if (operation == GENERATOR_CLOSE) savedState = null; } }
7
private void programmerSaveButton(java.awt.event.ActionEvent evt) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Please Enter File Name and Choose Location"); List<String> userInput = Arrays.asList(programmerText.getText().split("\n")); PrintWriter out = null; int userSelection = fileChooser.showSaveDialog(fileChooser); if (userSelection == JFileChooser.APPROVE_OPTION) { try { File fileToSave = fileChooser.getSelectedFile(); out = new PrintWriter(fileToSave.getAbsolutePath()+".txt"); for(int loop = 0; loop < userInput.size(); loop++) { out.println(userInput.get(loop)); } out.close(); } catch (FileNotFoundException ex) { Logger.getLogger(World.class.getName()).log(Level.SEVERE, null, ex); } } }
3