text
stringlengths
14
410k
label
int32
0
9
public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); StringBuilder out = new StringBuilder(); while (in.hasNext()) { int n = in.nextInt(); int[] v = new int[n]; int[] r = new int[n]; for (int i = 0; i < n; i++) v[i] = r[n - i - 1] = in.nextInt(); int[] lisA = lis(v); int[] lisB = lis(r); int max = 0; for (int i = 0; i < n; i++) max = Math.max(max, Math.min(lisA[i], lisB[n - i - 1])); out.append((max * 2) - 1 + "\n"); } System.out.print(out); }
3
@Override protected int[] ParsePosition( String ToParse ) { int Position[] = { 0, 0 }; if( ToParse.length() == 2 ) { switch( ToParse.toUpperCase().charAt( 0 ) ) { case('A'): Position[0] = 0; break; case('B'): Position[0] = 1; break; case('C'): Position[0] = 2; break; case('D'): Position[0] = 3; break; case('E'): Position[0] = 4; break; case('F'): Position[0] = 5; break; case('G'): Position[0] = 6; break; case('H'): Position[0] = 7; break; } Position[1] = Integer.parseInt( ToParse.substring( 1 ) ); return Position; } Position[0] = -1; Position[1] = -1; return Position; }
9
private StringBuffer prepareFile(JoeTree tree, DocumentInfo docInfo) { String lineEnding = PlatformCompatibility.platformToLineEnding(PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_LINE_ENDING)); StringBuffer buf = new StringBuffer(); buf.append("<?xml version=\"1.0\" encoding=\"").append(PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_ENCODING_TYPE)).append("\"?>").append(lineEnding); buf.append("<").append(ELEMENT_OML).append(" ").append(ATTRIBUTE_VERSION).append("=\"1.0\">").append(lineEnding); buf.append("<").append(ELEMENT_HEAD).append(">").append(lineEnding); appendMetadataElement(buf, TITLE, PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_PATH), lineEnding); appendMetadataElement(buf, DATE_CREATED, PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_DATE_CREATED), lineEnding); appendMetadataElement(buf, DATE_MODIFIED, PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_DATE_MODIFIED), lineEnding); appendMetadataElement(buf, OWNER_NAME, PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_OWNER_NAME), lineEnding); appendMetadataElement(buf, OWNER_EMAIL, PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_OWNER_EMAIL), lineEnding); appendMetadataElement(buf, EXPANSION_STATE, docInfo.getExpandedNodesStringShifted(1), lineEnding); appendMetadataElement(buf, VERTICAL_SCROLL_STATE, PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_VERTICAL_SCROLL_STATE), lineEnding); appendMetadataElement(buf, WINDOW_TOP, PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_WINDOW_TOP), lineEnding); appendMetadataElement(buf, WINDOW_LEFT, PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_WINDOW_LEFT), lineEnding); appendMetadataElement(buf, WINDOW_BOTTOM, PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_WINDOW_BOTTOM), lineEnding); appendMetadataElement(buf, WINDOW_RIGHT, PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_WINDOW_RIGHT), lineEnding); appendMetadataElement(buf, APPLY_FONT_STYLE_FOR_COMMENTS, PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_APPLY_FONT_STYLE_FOR_COMMENTS), lineEnding); appendMetadataElement(buf, APPLY_FONT_STYLE_FOR_EDITABILITY, PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_APPLY_FONT_STYLE_FOR_EDITABILITY), lineEnding); appendMetadataElement(buf, APPLY_FONT_STYLE_FOR_MOVEABILITY, PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_APPLY_FONT_STYLE_FOR_MOVEABILITY), lineEnding); buildMetadataElements(tree, lineEnding, buf); buf.append("</").append(ELEMENT_HEAD).append(">").append(lineEnding); buf.append("<").append(ELEMENT_BODY).append(">").append(lineEnding); Node node = tree.getRootNode(); for (int i = 0, limit = node.numOfChildren(); i < limit; i++) { buildOutlineElement(node.getChild(i), lineEnding, buf); } buf.append("</").append(ELEMENT_BODY).append(">").append(lineEnding); buf.append("</").append(ELEMENT_OML).append(">").append(lineEnding); return buf; }
1
static boolean authenticate( String username , String hashString, PassthroughConnection ptc ) { try { String encodedUsername = URLEncoder.encode(username, "UTF-8"); String encodedHashString = URLEncoder.encode(hashString, "UTF-8"); String authURLString = new String( "http://www.minecraft.net/game/checkserver.jsp?user=" + encodedUsername + "&serverId=" + encodedHashString); if(!Globals.isQuiet()) { ptc.printLogMessage("Authing with " + authURLString); } URL minecraft = new URL(authURLString); URLConnection minecraftConnection = minecraft.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(minecraftConnection.getInputStream())); String reply = in.readLine(); if( Globals.isInfo() ) { ptc.printLogMessage("Server Response: " + reply ); } in.close(); if( reply != null && reply.equals("YES")) { if(!Globals.isQuiet()) { ptc.printLogMessage("Auth successful"); } return true; } } catch (MalformedURLException mue) { ptc.printLogMessage("Auth URL error"); } catch (IOException ioe) { ptc.printLogMessage("Problem connecting to auth server"); } return false; }
7
@Override public void show() { String[][] data = ScoreIO.loadScores(); names = data[0]; scoreStrings = data[1]; int[] scores = new int[5]; for (int i = 0; i < 5; i++) { scores[i] = Integer.parseInt(scoreStrings[i]); } currentScore = ScoreIO.getScore(); place = 5; while (place > 0 && currentScore >= scores[place-1]) { place--; } if (place == 5) { game.setScreen(Screens.MAIN_MENU); } else { for (int i = 4; i > place; i--) { names[i] = names[i-1]; scoreStrings[i] = scoreStrings[i-1]; } scoreStrings[place] = "" + currentScore; selectedLetter = 0; canEnter = false; canBackspace = true; initials = ""; moveTimer = 0; sound.play(); menuMusic.loop(); } }
5
public Map<Integer, Integer> getGeneSpans(String text) { Map<Integer, Integer> begin2end = new HashMap<Integer, Integer>(); Annotation document = new Annotation(text); pipeline.annotate(document); List<CoreMap> sentences = document.get(SentencesAnnotation.class); for (CoreMap sentence : sentences) { List<CoreLabel> candidate = new ArrayList<CoreLabel>(); for (CoreLabel token : sentence.get(TokensAnnotation.class)) { String pos = token.get(PartOfSpeechAnnotation.class); if (pos.startsWith("NN")) { candidate.add(token); } else if (candidate.size() > 0) { int begin = candidate.get(0).beginPosition(); int end = candidate.get(candidate.size() - 1).endPosition(); begin2end.put(begin, end); candidate.clear(); } } if (candidate.size() > 0) { int begin = candidate.get(0).beginPosition(); int end = candidate.get(candidate.size() - 1).endPosition(); begin2end.put(begin, end); candidate.clear(); } } return begin2end; }
5
public Identifier getRepresentative() { Identifier ptr = this; while (ptr.left != null) ptr = ptr.left; return ptr; }
1
public static Vector2D getClosest(ArrayList<Vector2D> list, Vector2D vec) { Vector2D closest = null; double distance = 0; for (Vector2D close : list) { double val = close.getDistance(vec); if (closest == null || val < distance && close != vec) { closest = close; distance = val; } } return closest; }
4
private void findMax() { if(calibrationDataSize > 0) { int index = 0; while(!calibrationFlag[index]) { index++; } max = data[index]; index++; for(int i=index; i<data.length; i++) { if(calibrationFlag[i] && data[i] > max) { max = data[i]; } } } }
5
void viewExistingCustomers() { boolean quit = false; while (!quit) { System.out.println("------------"); System.out .println("1.) Print All Registered Customer Information"); System.out.println("2.) Print Customer by ID"); System.out.println("3.) Print All Customers by Last Name"); System.out.println("4.) Go Back"); System.out.print("Select [1/2/3/4]: "); String userInput = inputScanner.nextLine(); if (userInput.equals("1")) { System.out.println(getCustomerRoll().toString()); quit = true; } else if (userInput.equals("2")) { System.out.println("------------"); System.out.print("User ID: "); String idInput = inputScanner.nextLine(); Integer customerID = 0; try { customerID = Integer.valueOf(idInput); } catch (Exception e) { System.out.println("[ERROR] Not a valid input"); continue; } if (isRegisteredCustomer(customerID)) { System.out.println(getCustomerRoll().getCustomer( customerID)); System.out.println(getOrderList().getOrdersByCustomerID( customerID)); quit = true; } else { System.out .println("[ERROR] No customer exists with that ID"); } } else if (userInput.equals("3")) { System.out.println("------------"); System.out.print("Last Name: "); String lastName = inputScanner.nextLine(); System.out.println(getCustomerRoll().getCustomersByLastName( lastName).toString()); } else if (userInput.equals("4")) { quit = true; } else { System.out.println("[ERROR] Invalid input."); } } }
7
@Test public void testQueryOrder() throws FileNotFoundException{; int count = 0; for (Player p : myGame.getPlayers()){ if (count == 0){ assertEquals(p.getName(), "Test name"); count++; } else if (count == 1){ assertEquals(p.getName(), "Elessar Telcontal"); count++; } else if (count == 2){ assertEquals(p.getName(), "Gandalf Grey"); count++; } else if (count == 3){ assertEquals(p.getName(), "Gollum Trahald"); count++; } else if (count == 4){ assertEquals(p.getName(), "Samwise Gamgee"); count++; } else if (count == 5){ assertEquals(p.getName(), "Frodo Baggins"); count++; } } }
7
private String generateTRGFile(String csvFilename) { // If this is the first time this step has processed data, // mark the step as started if (!this.running){ this.running=true; this.logStart(); } // Make sure filename ends in .csv if (csvFilename.toLowerCase().endsWith(".csv")) { // Replace .csv and the end of file with .trg int cnt = 0; int idx = csvFilename.toLowerCase().indexOf(".csv"); while (idx >= 0) { cnt++; idx = csvFilename.toLowerCase().indexOf(".csv", idx+1); } if (cnt > 0) { // we found .csv at least once // replace the last occurence with .trg csvFilename = csvFilename.substring(0, csvFilename.length() - 4 ).concat(".trg"); } // Generate the .trg file File newFile = new File(csvFilename); try { newFile.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // LOG: skipping file, does not end with ".csv" } return csvFilename; }
5
private void tickForwards(){ time++; if(time % 60 == 0) second++; if(second == 60){ minute++; second = 0; } if(time == maxTime) finished = true; }
3
@Override public String toString() { if (currentSize == 0) { return "[Empty Stack]"; } StringBuffer sb = new StringBuffer(); for (int i = currentSize - 1; i >= 0; --i) { sb.append("Stack[" + i + "] = " + array[i]); if (i > 0) { sb.append("\n"); } } return sb.toString(); }
3
private void removeAnimal(int index) { if (index < animals.size() && index >= 0) { //System.out.println("Removing row " + index); animals.remove(index); animalCount --; if (index == mother) { mother = -1; } else if (index < mother) { mother--; } if (index == father) { father = -1; } else if (index < father) { father--; } removeRow(index); for (; index < animalCount; index++) { int oldNumber = Integer.parseInt((String) tableModel.getValueAt(index, 0)); tableModel.setValueAt(String.valueOf(oldNumber - 1), index, 0); } table.revalidate(); repaint(); } }
7
public void renderOverlay(int mx, int my, boolean[] buttons) { super.renderOverlay(mx, my, buttons); float slotX = x; float slotY = y-amountScrolled; if(slots != null) { int slotIndex = 0; for(int i = slots.length-1;i>=0;i--) { UISlot slot = slots[i]; if(slot == null) continue; if(slotY < y+h && slotY+slot.h > y) slot.renderSlotOverlay(slotIndex, slotX, slotY, mx, my, buttons, selectedIndex == i); slotIndex++; slotY+=slot.h-2; } } }
5
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub HttpSession session = request.getSession(); synchronized(session) { response.setContentType("text/html"); // Get a output writer to write the response message into the network socket PrintWriter out = response.getWriter(); //Connection conn = null; //Statement stmt = null; try { // Print an HTML page as the output of the query out.println("<html><head>" + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">" + "<title>Ruserba</title>" + "<link rel=\"icon\" type=\"image/png\" href=\"" + request.getContextPath() + "/favicon.png\">" + "<link rel=\"stylesheet\" href=\"" + request.getContextPath() + "/css/home.css\" type=\"text/css\" /> " + "<link rel=\"stylesheet\" href=\"" + request.getContextPath() + "/css/loginpopup.css\" type=\"text/css\" />" + "<script src=\"" + request.getContextPath() + "/ajax_generic.js\"></script> " + "</head><body>"); //HEADER out.println("<header>"); out.println("<nav><div class=\"container\">"); out.println("<span id=\"login\"><a class=\"menu_cell hyperlink\" href=\"#loginbox\">Masuk</a></span>"); out.println("<form id=\"wbd_search\" class=\"menu_cell\" onSubmit=\"return testA()\">"); out.println("<input type=\"text\" name=\"search_input\" placeholder=\"Cari disini\">"); out.println("<input type=\"submit\" name=\"submit\" value=\"Cari\">"); out.println("</form>"); out.println("<a id=\"keranjang_belanja\" class=\"menu_cell hyperlink\" href=\"keranjang/\">Keranjang Belanja <span id=\"total_keranjang\"></span></a>"); out.println("<a id=\"admin\" class=\"menu_cell hyperlink\" href=\"admin\">Admin </a>"); out.println("</div>"); out.println("</nav>"); out.println("<div class=\"container\">"); out.println("<a href=\"" + request.getContextPath() + "/home\"><img id=\"logo\" src=\"" + request.getContextPath() + "/logo.png\" height=\"72\" alt=\"Ruko Serba Ada\"></a>"); out.println("</div>"); out.println("<div id=\"background_cat\">"); out.println("<img class=\"background\" id='kat1' src=\"" + request.getContextPath() + "/img_style/kat1.gif\" alt=\"Kategori 1\"/>"); out.println("<img class=\"background\" id='kat2' src=\"" + request.getContextPath() + "/img_style/kat2.gif\" alt=\"Kategori 1\"/>"); out.println("<img class=\"background\" id='kat3' src=\"" + request.getContextPath() + "/img_style/kat3.gif\" alt=\"Kategori 1\"/>"); out.println("<img class=\"background\" id='kat4' src=\"" + request.getContextPath() + "/img_style/kat4.gif\" alt=\"Kategori 1\"/>"); out.println("<img class=\"background\" id='kat5' src=\"" + request.getContextPath() + "/img_style/kat5.gif\" alt=\"Kategori 1\"/>"); out.println("</div>"); out.println("<div class=\"kategori_group\">"); out.println("<a href=\"" + request.getContextPath() + "/kategori?id=1&page=1\"><img src=\"" + request.getContextPath() + "/img_style/klik.gif\" alt=\"Klik\"/></a>"); out.println("<a href=\"" + request.getContextPath() + "/kategori?id=2&page=1\"><img src=\"" + request.getContextPath() + "/img_style/klik.gif\" alt=\"Klik\"/></a>"); out.println("<a href=\"" + request.getContextPath() + "/kategori?id=3&page=1\"><img src=\"" + request.getContextPath() + "/img_style/klik.gif\" alt=\"Klik\"/></a>"); out.println("<a href=\"" + request.getContextPath() + "/kategori?id=4&page=1\"><img src=\"" + request.getContextPath() + "/img_style/klik.gif\" alt=\"Klik\"/></a>"); out.println("<a href=\"" + request.getContextPath() + "/kategori?id=5&page=1\"><img src=\"" + request.getContextPath() + "/img_style/klik.gif\" alt=\"Klik\"/></a>"); out.println("</div>"); out.println("</header>"); //END OF HEADER //ARTICLE out.println("<article class=\"container\">"); //ResultSet kategori = Process.showKategoriNonFilter(Integer.parseInt(request.getParameter("id")), Integer.parseInt(request.getParameter("page"))).get(0); ResultSet kategori = Process.showKategoriWithFilter(Integer.parseInt(request.getParameter("id")), Integer.parseInt(request.getParameter("page")), request.getParameter("by"), request.getParameter("sort")).get(0); kategori.next(); out.println("<div class=\"kategori\">"); out.println("<h1>" + kategori.getString("kategori_nama") + "</h1>"); out.println("<p>"); out.println("<a class=\"sorting\" href=\"" + request.getContextPath() + "/kategori/?id=" + Integer.parseInt(request.getParameter("id")) + "&page=1&by=nama&sort=asc\">Sorting By Name Ascending</a>"); out.println("<a class=\"sorting\" href=\"" + request.getContextPath() + "/kategori/?id=" + Integer.parseInt(request.getParameter("id")) + "&page=1&by=nama&sort=desc\">Sorting By Name Descending</a>"); out.println("<a class=\"sorting\" href=\"" + request.getContextPath() + "/kategori/?id=" + Integer.parseInt(request.getParameter("id")) + "&page=1&by=harga&sort=asc\">Sorting By Price Ascending</a>"); out.println("<a class=\"sorting\" href=\"" + request.getContextPath() + "/kategori/?id=" + Integer.parseInt(request.getParameter("id")) + "&page=1&by=harga&sort=desc\">Sorting By Price Descending</a>"); out.println("</p>"); out.println("<p>"); out.println("<?php $size= $page_no?>"); int size; ResultSet page_size = Process.showKategoriWithFilter(Integer.parseInt(request.getParameter("id")), Integer.parseInt(request.getParameter("page")), request.getParameter("by"), request.getParameter("sort")).get(1); page_size.next(); int sisa = page_size.getInt("total")%10; size = ((page_size.getInt("total")-sisa)/10) + 1; String uri = ""; boolean filter = request.getParameter("by") != null && request.getParameter("sort") != null; for (int i = 1; i <= size; i++){ uri = request.getContextPath() + "/kategori/?id=" + Integer.parseInt(request.getParameter("id")) + "&page=" + i; if (filter) uri += "&by=" + request.getParameter("by") +"&sort=" + request.getParameter("sort"); //out.println("<h3>"+ uri +"</h3>"); out.println("<a class=\"sorting\" href=\"" + uri +"\">" + i + "</a>"); } out.println("</p>"); //ResultSet barang = Process.showKategoriNonFilter(Integer.parseInt(request.getParameter("id")), Integer.parseInt(request.getParameter("page"))).get(1); ResultSet barang = Process.showKategoriWithFilter(Integer.parseInt(request.getParameter("id")), Integer.parseInt(request.getParameter("page")), request.getParameter("by"), request.getParameter("sort")).get(2); while (barang.next()){ out.println("<div class=\"box_barang\">"); String path=""; if (barang.getString("image_url").equals("")){ path = request.getContextPath() + "/assets/image/default.png"; } else { path = request.getContextPath() + "/" + barang.getString("image_url"); } out.println("<img class=\"gambar_barang\" src=\"" + path + "\" alt=\""+ barang.getString("nama") +"\" height=\"100\" width=\"100\">"); out.println("<a href=\""+ request.getContextPath() +"/barang?id=" + barang.getInt("barang_id") + "\"> " + barang.getString("nama") + "</a>"); out.println("<span class=\"harga\">Rp." + barang.getDouble("harga") + "</span>"); out.println("<form onSubmit=\"return addToShoppingChart(this)\"><input type=\"hidden\" name=\"id_barang\" value=\"" + barang.getInt("barang_id") + "\"><input type=\"text\" name=\"qty\" onKeyUp=\"validateQty(this)\"><input type=\"submit\" value=\"+\" disabled=\"disabled\"></form>"); out.println("</div>"); } out.println("</div>"); out.println("</article>"); //END OF ARTICLE //FOOTER out.println("<footer class=\"container\"> " + " <div>Ruserba &copy; 2013</div>" + "</footer>" + "<script src=\"" + request.getContextPath() + "/use.js\"></script> " + "<script src=\"" + request.getContextPath() + "/validator.js\"></script>" ); //END OF FOOTER out.println("</body></html>"); } catch (SQLException ex) { ex.printStackTrace(); } finally { out.close(); // Close the output writer } } }
6
public static List<String> searchNineItems() { String searchUrl = SearchUrl.NINE_URL; List<String> urls = new ArrayList<>(); for (int i = 1; i <= 3; i++) { for (Map.Entry<String, List<String>> m : cidToKeyMap.entrySet()) { String cid = m.getKey(); List<String> searchContext = m.getValue(); for (String sc : searchContext) { try { int spage = (i - 1) * 40; String realUrl = searchUrl.replace("query", sc).replace("spage", String.valueOf(spage)); Document doc = Jsoup.connect(realUrl).get(); Elements elements = doc.select("ul li.list-item"); for (Element e : elements) { String money = e.select("ul li em").html().trim(); if (money.indexOf("9.") != -1) { String[] array = money.split("\\."); if (array[0].length() == 1) { String itemUrl = e.select("div a").attr("href") + "&cidurl=" + cid; urls.add(itemUrl); System.out.println("add item url------" + itemUrl); } } } } catch (IOException ex) { Logger.getLogger(SearchNine.class.getName()).log(Level.SEVERE, null, ex); } } } } return urls; }
7
public Expression simplify() { if (subExpressions[0].getType().getCanonic() .isOfType(Type.tSubType(castType))) /* * This is an unnecessary widening cast, probably that inserted by * jikes for inner classes constructors. */ return subExpressions[0].simplify(); return super.simplify(); }
1
public static void main(String[] args) throws Exception { Socket socket = new Socket("127.0.0.1",5001); OutputStream os = socket.getOutputStream(); InputStream is = socket.getInputStream(); os.write("hi ".getBytes()); byte[] buffer = new byte[200]; int length = 0; while(-1 != (length = is.read(buffer, 0, buffer.length))) { String str = new String(buffer,0,length); System.out.println(str); } is.close(); os.close(); socket.close(); }
1
public ReportResult getFilteredReport(String[] spielerNamen, String startString, String endeString) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.GERMAN); Date start = sdf.parse(startString); Date ende = null; if (endeString == null) { ende = new Date(); } else { ende = sdf.parse(endeString); } Map<String, Spieler> spielerMap = new HashMap<String, Spieler>(); Map<String, Team> teamMap = new HashMap<String, Team>(); List<Spiel> spiele = getSpieleFiltered(Arrays.asList(spielerNamen), start, ende); List<GespieltesSpiel> spielErgebnis = new ArrayList<GespieltesSpiel>(); for (Spiel spiel : spiele) { spielErgebnis.add(new GespieltesSpiel(calculateElo(spiel, spielerMap, teamMap), true)); } List<Spieler> spielerSorted = new ArrayList<Spieler>(spielerMap.values()); Collections.sort(spielerSorted, new Comparator<Spieler>() { public int compare(Spieler o1, Spieler o2) { return -1 * (o1.getPunktzahl().getPunktzahl() - o2.getPunktzahl().getPunktzahl()); } }); List<RanglistenEintrag> rangliste = new ArrayList<RanglistenEintrag>(); int rang = 1; for (Spieler spieler : spielerSorted) { rangliste.add(new RanglistenEintrag(spieler.getId(), rang, spieler.getName(), spieler.getPunktzahl().getPunktzahl(), spieler .getAnzahlSpiele(), spieler.getAnzahlSiege())); rang++; } List<Team> teamSorted = new ArrayList<Team>(teamMap.values()); Collections.sort(teamSorted, new Comparator<Team>() { public int compare(Team o1, Team o2) { return -1 * (o1.getPunktzahl().getPunktzahl() - o2.getPunktzahl().getPunktzahl()); } }); List<RanglistenEintrag> teamRangliste = new ArrayList<RanglistenEintrag>(); int teamRang = 1; for (Team team : teamSorted) { int anzahlSpiele = team.getPunktzahlHistorie().size() - 1; int anzahlSiege = 0; for (EloPunktzahl punktzahl : team.getPunktzahlHistorie()) { if (punktzahl.getZuwachs() > 0) { anzahlSiege++; } } teamRangliste.add(new RanglistenEintrag(team.getId(), teamRang, team.getSpieler1().getName() + "/" + team.getSpieler2().getName(), team.getPunktzahl().getPunktzahl(), anzahlSpiele, anzahlSiege)); teamRang++; } Collections.reverse(spielErgebnis); ReportResult result = new ReportResult(rangliste, teamRangliste, spielErgebnis); return result; }
6
public synchronized BufferedImage[] getShadeOverlays( int size ) { if( shadeOverlays == null || size != shadeOverlaySize ) { shadeOverlays = new BufferedImage[16]; for( int i=0; i<16; ++i ) shadeOverlays[i] = Blackifier.makeShadeOverlay( size, (i & TileLayerData.SHADE_TL) != 0 ? 1 : 0, (i & TileLayerData.SHADE_TR) != 0 ? 1 : 0, (i & TileLayerData.SHADE_BL) != 0 ? 1 : 0, (i & TileLayerData.SHADE_BR) != 0 ? 1 : 0 ); shadeOverlaySize = size; } return shadeOverlays; }
7
private prRegion createNewRegion(Player player) { int x1,y1,z1; try { x1 = player.getMetadata("x1").get(0).asInt(); y1 = player.getMetadata("y1").get(0).asInt(); z1 = player.getMetadata("z1").get(0).asInt(); } catch (Exception e) { player.sendMessage(ChatColor.RED + "Select point 1 first."); return null; } player.removeMetadata("x1", plugin); player.removeMetadata("y1", plugin); player.removeMetadata("z1", plugin); int x2,y2,z2; try{ x2 = player.getMetadata("x2").get(0).asInt(); y2 = player.getMetadata("y2").get(0).asInt(); z2 = player.getMetadata("z2").get(0).asInt(); } catch (Exception e) { player.sendMessage(ChatColor.RED + "Select point 2 first."); return null; } player.removeMetadata("x2", plugin); player.removeMetadata("y2", plugin); player.removeMetadata("z2", plugin); player.sendMessage(ChatColor.GREEN + "Region created!"); return new prRegion(player.getWorld(),x1,y1,z1,x2,y2,z2); }
2
public boolean action(Event e, Object o) { if (e.target == ok) { hide(); dispose(); } return true; }
4
public void adaptToHost() { //Update host size to current actual value if(inScrollPane) hostSize = scrollPanel.getSize(); else hostSize = slidePanel.getSize(); //Derive the number of onscreen pixels for one increment of the 800x600 //grid used for specifying size and positioning in the XML double gridX = (double)(hostSize.width)/800; double gridY = (double)(hostSize.height)/600; //Hence scale image coordinates and place relative to slide origin //to achieve the slide positioning defined in the XML int scaledXPos = (int)(gridX*imageParameters.getStartPoint().getX()); int scaledYPos = (int)(gridY*imageParameters.getStartPoint().getY()); setImagePosition(new Point(scaledXPos,scaledYPos)); //Also scale the dimension values so that the onscreen size matches the //grid-relative size defined in the XML int scaledWidth = (int)(gridX*imageParameters.getWidth()); int scaledHeight = (int)(gridY*imageParameters.getHeight()); setImageSize(new Dimension(scaledWidth,scaledHeight)); // Set ImagePlayer panel to match the image size and position imagePanel.setSize(imageSize); imagePanel.setLocation(imagePosition); //These debug messages are to verify correct slide adaptation if(Debug.imagePlayer) System.out.println("Slide: width:"+hostSize.width+ " height:"+hostSize.height); if(Debug.imagePlayer) System.out.println( "Image: x:"+imagePosition.x+" y:"+imagePosition.y); if(Debug.imagePlayer) System.out.println( "Image: width:"+imageSize.width+" height:"+imageSize.height); if(Debug.imagePlayer) System.out.println("ImagePlayer: x:"+imagePanel.getX()+" y:"+ imagePanel.getY()); if(Debug.imagePlayer) System.out.println( "ImagePlayer: width:"+imagePanel.getWidth()+" height:"+ imagePanel.getHeight()); //If zoom arrows are to be displayed, initialise them //at correct positions if(showArrows) { try { initArrows(arrowFolderPath); } catch (InterruptedException e) { System.out.println("ImagePlayer: Arrow initialisation interrupted"); e.printStackTrace(); } } }
8
public static Stella_Object generateCaseBasedAnswer(LogicObject probe, Surrogate slot, List cases) { { int num = cases.length(); Vector slotVector = Logic.createCaseValueVector(cases, slot); Vector matchScores = Vector.newVector(num); int farthest = 0; Vector nearestNeighbors = Vector.newVector(Logic.$NUM_NEIGHBORS$); double max = 0.0; { int i = Stella.NULL_INTEGER; int iter000 = 0; int upperBound000 = Logic.$NUM_NEIGHBORS$ - 1; for (;iter000 <= upperBound000; iter000 = iter000 + 1) { i = iter000; (nearestNeighbors.theArray)[i] = (IntegerWrapper.wrapInteger(0)); } } { int i = Stella.NULL_INTEGER; int iter001 = 0; int upperBound001 = num - 1; for (;iter001 <= upperBound001; iter001 = iter001 + 1) { i = iter001; (matchScores.theArray)[i] = (FloatWrapper.wrapFloat(1.0)); } } { int i = Stella.NULL_INTEGER; int iter002 = 0; int upperBound002 = num - 1; Stella_Object renamed_Case = null; Cons iter003 = cases.theConsList; for (;(iter002 <= upperBound002) && (!(iter003 == Stella.NIL)); iter002 = iter002 + 1, iter003 = iter003.rest) { i = iter002; renamed_Case = iter003.value; if (!(probe == renamed_Case)) { { FloatWrapper score = LogicObject.matchInstances(probe, ((LogicObject)(renamed_Case))); (matchScores.theArray)[i] = score; if (score.wrapperValue > max) { max = ((double)(i)); } if (score.wrapperValue > ((FloatWrapper)((matchScores.theArray)[(((IntegerWrapper)((nearestNeighbors.theArray)[farthest])).wrapperValue)])).wrapperValue) { (nearestNeighbors.theArray)[farthest] = (IntegerWrapper.wrapInteger(i)); farthest = 0; { int j = Stella.NULL_INTEGER; int iter004 = 1; int upperBound003 = Logic.$NUM_NEIGHBORS$ - 1; for (;iter004 <= upperBound003; iter004 = iter004 + 1) { j = iter004; if (((FloatWrapper)((matchScores.theArray)[(((IntegerWrapper)((nearestNeighbors.theArray)[j])).wrapperValue)])).wrapperValue < ((FloatWrapper)((matchScores.theArray)[(((IntegerWrapper)((nearestNeighbors.theArray)[farthest])).wrapperValue)])).wrapperValue) { farthest = j; } } } } } } } } return (Logic.combineCaseAnswers(nearestNeighbors, matchScores, slotVector)); } }
9
public static void main(String[] args) { Iterable collection = null; Iterator iterator = collection.getIterator(); while (iterator.hasNext()) { Object o = iterator.next(); } }
1
protected void onUserMode(String targetNick, String sourceNick, String sourceLogin, String sourceHostname, String mode) {}
0
@GET @Path("{path:.*}") public Response getItem(@PathParam("path") String path, @QueryParam("download") boolean download, @QueryParam("info") boolean info) throws ContentRepositoryException, IOException { try { CollectionObject item = repo.getItem(path); if (item instanceof Folder) { return Response.ok(item, getDefaultMediaType()).build(); } else if (item instanceof Content) { if (info) { return Response.ok(item, getDefaultMediaType()).build(); } else { Content content = (Content) item; InputStream in = repo.openStream(content); ResponseBuilder response = Response.ok(in, content.getMediaType()); if (download) { response.header("Content-Disposition", String.format("attachment; filename*=UTF-8''%s; filename=\"%s\"", URLEncoder.encode(item.getName(), "UTF-8"), item.getName())); } return response.build(); } } else { throw new ContentRepositoryException("Unsupported object type. " + item); } } catch (ItemNotFoundException | FileNotFoundException e) { return Response.status(Status.NOT_FOUND).entity(new ServiceResult(e)).build(); } catch (Exception e) { return Response.serverError().entity(new ServiceResult(e)).build(); } }
6
private void incomingVehicleMonitor(Vehicle v) { if (v instanceof MotorCycle) { numMotorCycles++; } else if (v instanceof Car && ((Car) v).isSmall() == true) { numSmallCars++; numCars++; } else if (v instanceof Car && ((Car) v).isSmall() == false) { numCars++; } }
5
public String toString(){ String positif = "+ = "; String negatif = ", - = "; for(Entry<String, Boolean> entry : preferences.entrySet()){ String cle = entry.getKey(); Boolean valeur = entry.getValue(); if(valeur){ positif += cle+" "; } else{ negatif += cle+" "; } } return positif+negatif; }
2
public static NymOfferDetails getNymOfferDetails(String serverID, String nymID, String transactionID) { NymOfferDetails nymOfferDetails = new NymOfferDetails(); OfferListNym offerListNym = Helpers.getNYMOffer(serverID, nymID); if (offerListNym == null) { System.out.println("getNymOfferDetails - offerListNym returns null"); return null; } for (int j = 0; j < offerListNym.GetOfferDataNymCount(); j++) { OfferDataNym offerDataNym = offerListNym.GetOfferDataNym(j); if (offerDataNym == null || !Utility.VerifyStringVal(transactionID)) { continue; } if (transactionID.equals(offerDataNym.getTransaction_id())) { nymOfferDetails.setPrice(offerDataNym.getPrice_per_scale()); nymOfferDetails.setMinIncrement(offerDataNym.getMinimum_increment()); nymOfferDetails.setTotalAssetsOnOffer(offerDataNym.getTotal_assets()); double assetCount = -1; try { assetCount = Double.parseDouble(offerDataNym.getTotal_assets()) - Double.parseDouble(offerDataNym.getFinished_so_far()); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } nymOfferDetails.setAssetsStillOnOffer(assetCount == -1 ? "" : String.valueOf(assetCount)); break; } } return nymOfferDetails; }
7
public void testObjectLargeArrayArraycopy() { Double[] data = new Double[]{1.12345, -1.54321, 100., -100., Double.MAX_VALUE, Double.MIN_VALUE, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.NaN, Double.MIN_NORMAL}; int startPos = 2; int length = 8; LargeArray.setMaxSizeOf32bitArray(1073741824); ObjectLargeArray a = new ObjectLargeArray(data); ObjectLargeArray b = new ObjectLargeArray(2 * data.length, 84); Utilities.arraycopy(a, startPos, b, 0, length); for (int i = 0; i < length; i++) { assertEquals(data[startPos + i], b.get(i)); } b = new ObjectLargeArray(2 * data.length, 84); Utilities.arraycopy(data, startPos, b, 0, length); for (int i = 0; i < length; i++) { assertEquals(data[startPos + i], b.get(i)); } LargeArray.setMaxSizeOf32bitArray(data.length - 1); a = new ObjectLargeArray(data); b = new ObjectLargeArray(2 * data.length, 84); Utilities.arraycopy(a, startPos, b, 0, length); for (int i = 0; i < length; i++) { assertEquals(data[startPos + i], b.get(i)); } b = new ObjectLargeArray(2 * data.length, 84); Utilities.arraycopy(data, startPos, b, 0, length); for (int i = 0; i < length; i++) { assertEquals(data[startPos + i], b.get(i)); } }
4
public static void clearTable(JTable table) { for (int i = 0; i < table.getRowCount(); i++) { for (int j = 0; j < table.getColumnCount(); j++) { table.setValueAt("", i, j); } } }
2
public static byte[] createChecksum(String filename) throws Exception { MessageDigest complete; try (InputStream fis = new FileInputStream(filename)) { byte[] buffer = new byte[1024]; complete = MessageDigest.getInstance("MD5"); int numRead; do { numRead = fis.read(buffer); if (numRead > 0) { complete.update(buffer, 0, numRead); } } while (numRead != -1); } return complete.digest(); }
2
private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); final JTextArea txtFilePath = new JTextArea(); txtFilePath.setEditable(false); txtFilePath.setBounds(10, 10, 290, 22); frame.getContentPane().add(txtFilePath); JButton btnOpenIrisData = new JButton("Open Iris Data"); btnOpenIrisData.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Create a file chooser final JFileChooser fc = new JFileChooser(); // In response to a button click: int returnVal = fc.showOpenDialog(frame); switch (returnVal) { case JFileChooser.APPROVE_OPTION: txtFilePath.setText(fc.getSelectedFile().getAbsoluteFile() .toString()); break; default: break; } } }); btnOpenIrisData.setBounds(310, 11, 114, 23); frame.getContentPane().add(btnOpenIrisData); JButton btnNewButton = new JButton("Start"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { final JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.showSaveDialog(frame); List<Double> validationErrors = new ArrayList<Double>(); List<IrisDistanceConfig> configs = new ArrayList<IrisDistanceConfig>(); configs.add(new IrisDistanceConfig(true, true, true, true)); configs.add(new IrisDistanceConfig(false, true, true, true)); configs.add(new IrisDistanceConfig(true, false, true, true)); configs.add(new IrisDistanceConfig(true, true, false, true)); configs.add(new IrisDistanceConfig(true, true, true, false)); configs.add(new IrisDistanceConfig(false, false, true, true)); configs.add(new IrisDistanceConfig(false, true, false, true)); configs.add(new IrisDistanceConfig(false, true, true, false)); configs.add(new IrisDistanceConfig(false, false, true, true)); configs.add(new IrisDistanceConfig(true, false, false, true)); configs.add(new IrisDistanceConfig(true, false, true, false)); configs.add(new IrisDistanceConfig(false, true, false, true)); configs.add(new IrisDistanceConfig(true, false, false, true)); configs.add(new IrisDistanceConfig(true, true, false, false)); for (IrisDistanceConfig config : configs) { try { String irisPath = txtFilePath.getText(); if (irisPath != "") { // Load the iris data Iris irisList[]; for (int k = 1; k <= 150; k++) { irisList = Iris.openCsv(irisPath); Iris classifyMe[] = Iris.openCsv(irisPath); KNearestNeighbour nearestNeighbour = new KNearestNeighbour( k, irisList); classifyMe = nearestNeighbour.classifyIris( classifyMe, config.isSepalLength(), config.isSepalWidth(), config.isPetalLength(), config.isPetalWidth()); validationErrors.add(nearestNeighbour .getValidationError(classifyMe)); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < validationErrors.size(); i++) { sb.append(validationErrors.get(i) + "\n"); } String test = fc.getSelectedFile().getPath() + "\\Results\\result-" + config.toString() + ".csv"; try { BufferedWriter out = new BufferedWriter(new FileWriter( fc.getSelectedFile().getAbsolutePath() + "\\Results\\result-" + config.toString() + ".csv")); out.write(sb.toString()); out.close(); } catch (IOException e) { String error = e.getMessage(); } } } }); btnNewButton.setBounds(310, 142, 114, 23); frame.getContentPane().add(btnNewButton); }
7
public boolean validCoordinates(int r, int c) { return !(r < 0 || r >= GameConstants.HEIGHT || c < 0 || c >= GameConstants.WIDTH); }
3
public synchronized void loadCurrentResource() { String s = getResourceAddress(); if (s == null) { setLoadingMessagePainted(false); return; } setLoadingMessagePainted(true); if (FileUtilities.isRemote(s)) { s = FileUtilities.httpEncode(s); if (ConnectionManager.sharedInstance().isCachingAllowed()) { URL u = null; try { u = new URL(s); } catch (MalformedURLException e) { e.printStackTrace(); } if (u != null) { File file = null; try { file = ConnectionManager.sharedInstance().shouldUpdate(u); if (file == null) file = ConnectionManager.sharedInstance().cache(u); setResourceAddress(file.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } } } } super.loadCurrentResource(); }
7
private void calculateEnabledState(Document doc) { if (doc == null) { setText(TEXT); setEnabled(false); } else { setText(new StringBuffer().append(TEXT).append(" ").append(doc.getUndoQueue().getRedoRangeString()).toString()); if(doc.getUndoQueue().isRedoable()) { setEnabled(true); } else { setEnabled(false); } } }
2
private boolean consideringHierarchy(Publish p) { boolean sent = false; for (Entry<Class<?>, List<SubscriberParent>> e : p.mapping.entrySet()) { if (e.getKey().isAssignableFrom(p.message.getClass())) { for (SubscriberParent parent : e.getValue()) { if (!predicateApplies(parent.getSubscriber(), p.message)) { continue; } parent.getSubscriber().receiveO(p.message); sent = true; } } } return sent; }
5
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == cancelButton) closeWindow(); else if (e.getSource() == okButton) { String name = (String) comboBoxUnitName.getSelectedItem(); double minPos = Utility.stringToDouble(textFieldMinPos.getText()); double maxPos = Utility.stringToDouble(textFieldMaxPos.getText()); double minVal = Utility.stringToDouble(textFieldMinVal.getText()); double maxVal = Utility.stringToDouble(textFieldMaxVal.getText()); double tripTm = Utility.stringToDouble(textFieldTripTime.getText()); if ( minPos == Double.MAX_VALUE || maxPos == Double.MAX_VALUE || minVal == Double.MAX_VALUE || maxVal == Double.MAX_VALUE || tripTm == Double.MAX_VALUE ) JOptionPane.showMessageDialog(this, "Every item must have a valid number"); else { if (parentWindow != null) { // In case name was changed if (toBeEdited != null) parentWindow.removeUnit(toBeEditedName); // Create new Unit and add it to parent UnitSlew unit = new UnitSlew(name, minPos, maxPos, minVal, maxVal, tripTm); parentWindow.addUnit(unit); } closeWindow(); } } }
9
public Boss(int courtWidth, int courtHeight) { super(INIT_VEL_X, INIT_VEL_Y, INIT_X, INIT_Y, SIZE, SIZE, courtWidth, courtHeight); // Set img1 to the picture of ragnaros try { if (img1 == null) { img1 = ImageIO.read(new File(img_file1)); } } catch (IOException e) { System.out.println("Internal Error:" + e.getMessage()); } // Set img2 to the picture of explosion try { img2 = ImageIO.read(new File(img_file2)); } catch (IOException e) { System.out.println("Internal Error:" + e.getMessage()); } }
3
@SuppressWarnings("SpellCheckingInspection") private void printMostActiveActor(final List<Movie> movies) { // Java 7 style. final Map<Actor, Long> actorToMovieCount = new HashMap<>(); for (final Movie movie : movies) for (final Actor actor : movie.getActors()) actorToMovieCount.put(actor, 1 + (actorToMovieCount.containsKey(actor) ? actorToMovieCount.get(actor) : 0)); long maximumMovieCount = 0; Actor mostProductiveActor = null; for (final Actor actor : actorToMovieCount.keySet()) if (actorToMovieCount.get(actor) > maximumMovieCount) { maximumMovieCount = actorToMovieCount.get(actor); mostProductiveActor = actor; } System.out.println(); if (mostProductiveActor != null) System.out.println("Java 7 - most productive actor: " + mostProductiveActor.getFullName() + ", who worked on " + actorToMovieCount.get(mostProductiveActor) + " movies."); else System.out.println("Java 7 - most productive actor not found?!?"); // Java 8 style. final Map.Entry<Actor, Long> actorAndCountEntry = movies.stream() .flatMap(movie -> movie.getActors().stream()) .collect(Collectors.toMap(Function.identity(), actor -> 1L, (count1, count2) -> count1 + count2)) .entrySet().stream() .max(Map.Entry.comparingByValue()).get(); System.out.println("Java 8 - most productive actor: " + actorAndCountEntry.getKey().getFullName() + ", who worked on " + actorAndCountEntry.getValue() + " movies."); }
6
private boolean parseAliceBob() throws FormatterError { int ln = parseToken(true); if (ln == EOF_INDICATOR) { return false; } if (ln != WORD_INDICATOR) { throw new FormatterError("parseAliceBob : Bad first word"); } is_alice_line = s.equals("Alice"); if (!is_alice_line && !s.equals("Bob")) { throw new FormatterError("parseAliceBob : Bad first word"); } logger.info("parseAliceBob: " + s); // allocate new IO object for Alice/Bob curIO = new IO(is_alice_line); return (true); }
4
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(affected instanceof Room) if((CMath.bset(msg.sourceMajor(),CMMsg.MASK_MALICIOUS)) ||(CMath.bset(msg.targetMajor(),CMMsg.MASK_MALICIOUS)) ||(CMath.bset(msg.othersMajor(),CMMsg.MASK_MALICIOUS))) { if((msg.target()!=null) &&(msg.source()!=msg.target())) { msg.source().tell(L("Nah, you feel too peaceful under that bright moon.")); final MOB victim=msg.source().getVictim(); if(victim!=null) victim.makePeace(true); msg.source().makePeace(true); } msg.modify(msg.source(),msg.target(),msg.tool(),CMMsg.NO_EFFECT,"",CMMsg.NO_EFFECT,"",CMMsg.NO_EFFECT,""); return false; } return super.okMessage(myHost,msg); }
7
@Override public void run() { isAlive = true; try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); while (isAlive) { String readLine = bufferedReader.readLine(); parseCommand(readLine); } } catch (Exception e) { } finally { isAlive = false; try { server.removeClient(client); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
3
public void visitSwitchStmt(final SwitchStmt stmt) { if (stmt.defaultTarget() == oldDst) { if (FlowGraph.DEBUG) { System.out.print(" replacing " + stmt); } stmt.setDefaultTarget(newDst); if (FlowGraph.DEBUG) { System.out.println(" with " + stmt); } } final Block[] targets = stmt.targets(); for (int i = 0; i < targets.length; i++) { if (targets[i] == oldDst) { if (FlowGraph.DEBUG) { System.out.print(" replacing " + stmt); } targets[i] = newDst; if (FlowGraph.DEBUG) { System.out.println(" with " + stmt); } } } }
7
private void setName(String name) { if (name != null) this.name = name; }
1
public void clearBoard(){ gl.clearBoard(); for(int i=0; i< game.length; i++){ game[i].setIcon(null); } }
1
@Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase("global")) { return cmdGlobal(sender, args); } else if (cmd.getName().equalsIgnoreCase("globalrules")) { return cmdGlobalRules(sender); } else if (cmd.getName().equalsIgnoreCase("globalagree")) { return cmdGlobalAgree(sender); } else if (cmd.getName().equalsIgnoreCase("globalignore")) { return cmdGlobalIgnore(sender); } else if (cmd.getName().equalsIgnoreCase("globalinfo")) { return cmdGlobalInfo(sender); } return false; }
5
public List<Location> adjacentLocations(Location location, int distance) { assert location != null : "Null location passed to adjacentLocations"; // The list of locations to be returned. List<Location> locations = new LinkedList<Location>(); if(location != null) { int row = location.getRow(); int col = location.getCol(); for(int roffset = -distance; roffset <= distance; roffset++) { int nextRow = row + roffset; if(nextRow >= 0 && nextRow < depth) { for(int coffset = -distance; coffset <= distance; coffset++) { int nextCol = col + coffset; // Exclude invalid locations and the original location. if(nextCol >= 0 && nextCol < width && (roffset != 0 || coffset != 0)) { locations.add(new Location(nextRow, nextCol)); } } } } // Shuffle the list. Several other methods rely on the list // being in a random order. Collections.shuffle(locations, rand); } return locations; }
9
public void saveToFile() { try { FileOutputStream fileOut = new FileOutputStream(FILE); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(this); out.close(); fileOut.close(); } catch (IOException e) { e.printStackTrace(); } }
1
@Override public void initialize(URL arg0, ResourceBundle arg1) { ConnectionPool.getConnection(); colItemName.setCellValueFactory( new PropertyValueFactory<ItemSaleModel, String>("itemName")); colPrice.setCellValueFactory( new PropertyValueFactory<ItemSaleModel, String>("price")); colQuantity.setCellValueFactory( new PropertyValueFactory<ItemSaleModel, String>("quantity")); colAmount.setCellValueFactory( new PropertyValueFactory<ItemSaleModel, String>("amount")); initQuantity(); txtBarCode.requestFocus(); lblTotalAmount.textProperty().bind(totalAmountProperty); table.getItems().addListener(new ListChangeListener<ItemSaleModel>() { @Override public void onChanged(javafx.collections.ListChangeListener.Change<? extends ItemSaleModel> arg0) { btnRegister.setDisable(table.getItems().isEmpty()); btnCancel.setDisable(table.getItems().isEmpty()); } }); table.getItems().clear(); hideChange(); countCustomers(); updateItemCounter(0); }
1
public void close() { try { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch(Exception e){ e.printStackTrace(); System.out.println(e); } }
4
private synchronized AffineTransform bufferTransform(){ AffineTransform r=new AffineTransform(); for(int i=0;i<a1.size();i++){ int s1=a1.get(i);Object s2=a2.get(i);Object s3[]=null; if(s2 instanceof Object[])s3=(Object[])s2; if(s1==setTransform){r=makeTransform(s2); } if(s1==shear)r.shear((Double)s3[0],(Double)s3[1]); if(s1==rotate1)r.rotate((Double)s2); if(s1==rotate2)r.rotate((Double)s3[0],(Double)s3[1],(Double)s3[2]); if(s1==scale1)r.scale((Double)s3[0],(Double)s3[1]); if(s1==translate1)r.translate((Double)s3[0],(Double)s3[1]); if(s1==translate2)r.translate((Integer)s3[0],(Integer)s3[1]); } return r; }
9
public void actionPerformed(ActionEvent e){ if(e.getSource() == btnRegister){ if (comboBox.getSelectedItem().equals("Patient")) { if (textField_1.getText().equals(textField_2.getText())) { NewPatientProfilePanel nup = new NewPatientProfilePanel(parent, textField.getText(), textField_1.getText()); parent.getContentPane().add(nup); CardLayout cl = (CardLayout) parent.getContentPane().getLayout(); cl.next(parent.getContentPane()); } else { JOptionPane.showMessageDialog(null, "Incorrect value, please try again."); } } else if (comboBox.getSelectedItem().equals("Doctor")) { if (textField_1.getText().equals(textField_2.getText())) { NewDoctorProfilePanel ndp = new NewDoctorProfilePanel(parent, textField.getText(), textField_1.getText()); parent.getContentPane().add(ndp); CardLayout cl = (CardLayout) parent.getContentPane().getLayout(); cl.next(parent.getContentPane()); } else { JOptionPane.showMessageDialog(null, "Incorrect value, please try again."); } } else { if (textField_1.getText().equals(textField_2.getText())) { if(parent.getHandler().addNewUser(textField.getText(), textField_1.getText())) { AdminHomePanel ahp = new AdminHomePanel(parent, textField.getText()); parent.getContentPane().add(ahp); CardLayout cl = (CardLayout) parent.getContentPane().getLayout(); cl.next(parent.getContentPane()); } } else { JOptionPane.showMessageDialog(null, "Incorrect value, please try again."); } } } else if (e.getSource() == btnBack) { CardLayout cl = (CardLayout) parent.getContentPane().getLayout(); cl.first(parent.getContentPane()); parent.getContentPane().remove(parent.getContentPane().getComponents().length-1); } }
8
public long getPersonId() { return this.personId; }
0
public void upY(){ if (jump > 0) { // Jump case if (jump < 15) { // Go higher y -= moveY; ++jump; } else if (jump < 30) { // Go higher more slowly y -= moveY/2; ++jump; } else if (jump == 30) { // Stand ++jump; } else if (jump <= 45) { // Start reaching the ground y += moveY/2; ++jump; } else if (jump <60) { // Start reaching the ground y += moveY; ++jump; } else { jump = -1; } } else { // Only gravity : y += moveY; } }
6
public static String baseToDec(String num, int base) { String risultato = ERRORE; long risultato_num = 0; num = num.toUpperCase(); if (numeroValido_privato(num, base)) // Numero valido { if (base==1) // Se la base è 1 { int numero = num.length(); numero--; risultato = numero+""; } else if (base==10) // Se la base è già decimale { try { // non convertire niente long numero = new Long(num); // Ma rendilo almeno leggibile risultato = numero + ""; } catch(Exception e) { // Impossibile, tanto il numero è stato verificato prima, ed È decimale. In ogni caso... risultato = ERRORE; } } else // Per tutte le altre basi { risultato = ""; double j=num.length(); // Esponente per il calcolo for (int i=0; i<num.length(); i++) { j--; byte cifra = (byte)num.charAt(i); if (cifra<=57) cifra -= 48; else cifra -= 55; double conversione = cifra*(Math.pow(base, j)); risultato_num += conversione; } risultato = "" + risultato_num; } } else risultato = ERRORE; return risultato; }
6
public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub }
0
final public String evaluate(String expression) throws InvalidInputException, RuntimeException { resetStructures(); tokenizeExpression(expression); insertImplicitMultiplication(); convertToPostfix(); int previousFunctionMode = Function.outputMode; int previousOperatorMode = Operator.outputMode; if (this.OUTPUT_MODE == Calculate.OUTPUT_APPROXIMATE_MODE && Function.outputMode == Calculate.OUTPUT_EXACT_MODE) { Function.outputMode = Calculate.OUTPUT_APPROXIMATE_MODE; Operator.outputMode = Calculate.OUTPUT_APPROXIMATE_MODE; } Expression result = evaluatePostfix(); Function.outputMode = previousFunctionMode; Operator.outputMode = previousOperatorMode; if (this.OUTPUT_MODE == Calculate.OUTPUT_EXACT_MODE) { if (result instanceof Number) { if (result instanceof Fraction) { return ((Fraction) result).getExactFractionalValue(); } else { return trimZeroes(( (Number) result ).getRepresentation()); } } else { return trimZeroes(result.getRepresentation()); } } else { if (result instanceof Number) { BigDecimal rtn = (( (Number) result ).getValue().round(new MathContext(this.FLOATING_POINT))); //if the result is less than 10^(-floating point), then round it to zero rtn = rtn.setScale(this.FLOATING_POINT, RoundingMode.HALF_UP); return trimZeroes(rtn.stripTrailingZeros().toPlainString()); } else { return result.getRepresentation(); } } }
6
private static void writeText(Client c, int skillType) { c.getPA().sendFrame126(SKILLS[skillType], TITLE_LINE); for (int j = 0; j < LEVELS[skillType].length; j++) { c.getPA().sendFrame126(LEVELS[skillType][j], LEVEL_LINE + j); } for (int j = 0; j < DESCRIPTION[skillType].length; j++) { c.getPA().sendFrame126(DESCRIPTION[skillType][j], TEXT_LINE + j); } for (int j = DESCRIPTION[skillType].length; j < 30; j++) { c.getPA().sendFrame126("", LEVEL_LINE + j); } for (int j = LEVELS[skillType].length; j < 30; j++) { c.getPA().sendFrame126("", TEXT_LINE + j); } }
4
public boolean addMessage(ChatMessage chatMessage){ boolean returnValue = false; try { Socket socket = new Socket(SERVER_ADDRESS_CHAT, CHAT_PORT); socket.setSoTimeout(TIMEOUT); OutputStream outputStream = socket.getOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream( outputStream); objectOutputStream.writeObject("ADD_MESSAGE"); chatMessage.setMessage(chatMessage.getMessage().replaceAll("[']", "''")); objectOutputStream.writeObject(chatMessage); objectOutputStream.flush(); returnValue = (boolean)(new ObjectInputStream(socket.getInputStream())).readObject(); socket.close(); }catch (SocketException e){ new ErrorFrame("Server unreachable!"); } catch (SocketTimeoutException e){ new ErrorFrame("Connection timed out"); } catch (Exception e) { new ErrorFrame("An unknown Error occoured"); } return returnValue; }
3
@Override public String toString() { StringBuilder sb = new StringBuilder("TransportResponse("); boolean first = true; sb.append("status:"); if (this.status == null) { sb.append("null"); } else { sb.append(this.status); } first = false; if (!first) sb.append(", "); sb.append("contentType:"); if (this.contentType == null) { sb.append("null"); } else { sb.append(this.contentType); } first = false; if (isSetContent()) { if (!first) sb.append(", "); sb.append("content:"); if (this.content == null) { sb.append("null"); } else { sb.append(this.content); } first = false; } if (isSetFile()) { if (!first) sb.append(", "); sb.append("file:"); if (this.file == null) { sb.append("null"); } else { org.apache.thrift.TBaseHelper.toString(this.file, sb); } first = false; } sb.append(")"); return sb.toString(); }
9
@Override public void setValueAt(Object value, int row, int col) { if (col != 0) { super.setValueAt(value,row,col); } }
1
public static void main(String[] args) { String path = "/home/jorge/quiz.txt"; try { Quiz quiz = QuizLoader.loadQuiz(path); for(Question question : quiz){ System.out.println("Id: " + question.getId()); System.out.println("Enunciado: " + question.getEnunciado()); System.out.println("Puntuación: " + question.getPuntuacion()); for(Answer answer : question){ System.out.print("----Respuesta: " + answer.getText()); if(answer.isCorrect()){ System.out.print(" - Correcta"); } System.out.print("\n"); } System.out.println(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
5
public static URL getURL(String resourceLocation) throws FileNotFoundException { Assert.notNull(resourceLocation, "Resource location must not be null"); if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) { String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length()); URL url = SpringClassUtils.getDefaultClassLoader().getResource(path); if (url == null) { String description = "class path resource [" + path + "]"; throw new FileNotFoundException( description + " cannot be resolved to URL because it does not exist"); } return url; } try { // try URL return new URL(resourceLocation); } catch (MalformedURLException ex) { // no URL -> treat as file path try { return new File(resourceLocation).toURI().toURL(); } catch (MalformedURLException ex2) { throw new FileNotFoundException("Resource location [" + resourceLocation + "] is neither a URL not a well-formed file path"); } } }
4
public final void append(final File fileToAppendTo, final File content, int bytesToDiscard) { OutputStream out = null; InputStream in = null; if (!content.exists()) { return; } try { try { out = new OutputStream(fileToAppendTo, FileSystem.UTF8, true); synchronized (this) { this.openStreams.add(new WeakReference<Closeable>(out)); } in = new InputStream(content, FileSystem.UTF8); synchronized (this) { this.openStreams.add(new WeakReference<Closeable>(in)); } } catch (final FileNotFoundException e) { handleException(ExceptionHandle.TERMINATE, e); return; } try { in.read(new byte[bytesToDiscard]); write(in, out); } catch (final IOException e) { handleException(ExceptionHandle.TERMINATE, e); } } finally { if (out != null) { close(out); } if (in != null) { close(in); } } }
5
@Override public void evaluateTheHand(Hand player){ dealerBrain = new DealerAI(player); Vector<Card> throwAway = dealerBrain.whichCardsShouldISwap(); int num = throwAway.size(); Hand newHand = new Hand(); for (int y = 0; y < hand.size();y++){ boolean seen = false; for (int x = 0; x < num;x++) { if (throwAway.get(x).equals(hand.get(y))) seen = true; } if (!seen) newHand.add(hand.get(y)); } hand = null; for (int x=0; x < num;x++) newHand.add(dealACard()); hand = newHand; }
5
public static double paretoInverseCDF(double alpha, double beta, double prob) { if (prob < 0.0 || prob > 1.0) throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive"); double icdf = 0.0D; if (prob == 0.0) { icdf = beta; } else { if (prob == 1.0) { icdf = Double.POSITIVE_INFINITY; } else { icdf = beta / Math.pow((1.0 - prob), 1.0 / alpha); } } return icdf; }
4
int allocateClusters(int tailCluster, int count) throws IOException { // - bitmap of free clusters in memory? // - chunk with free block counting for sequential allocation? // - two stage allocation with "gray" // +final static int CLUSTER_GALLOCATED = 0x80000000; // +final static int CLUSTER_GEOC = 0xC8000000; // up bit? // - resize if need? if (count < 1) throw new IOException("Cannot allocate" + count + "clusters."); synchronized (this) { checkCanWrite(); if ((tailCluster < clusterCount) && ( ((freeClusterCount >= 0) && (count <= freeClusterCount)) || ((freeClusterCount < 0) && (count <= clusterCount)))) // without guaranty on dirty FAT { try { if (tailCluster != -1 && getFatEntry(tailCluster) != FATClusterAllocator.CLUSTER_EOC) throw new IOException("Can join the chain with the tail only."); return clusterAllocator.allocateClusters(tailCluster, count); } finally { //forceFat(); } } throw new IOException("Disk full."); } }
8
public SendGUI() { initComponents(); }
0
public boolean isExpired() { if (keepAliveTimeMsecs == 0) { return false; } return ((System.currentTimeMillis() - keepAliveTimeMsecs) >= timeEntered); }
1
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Scanner scanner2 = new Scanner(System.in); String invoer, invoerOpnieuw; boolean opnieuw = false; System.out.print("Dit programma test of je invoer een palindroom is"); do { System.out.print("\nVoer een zin, woord of cijferreeks in: "); invoer = scanner.nextLine(); if(isGetallenReeks(invoer)) { System.out.println("\nEr is een cijferreeks ingevoerd\n"); invoer = filterGetallenReeks(invoer); if(palindromenTest(invoer)) System.out.println("\nDe ingevoerde cijferreeks is een palindroom"); else System.out.println("\nDe ingevoerde cijferreeks is geen palindroom"); } else if(isZin(invoer)) { System.out.println("\nEr is een zin ingevoerd\n"); invoer = filterZinOfWoord(invoer); if(palindromenTest(invoer)) System.out.println("\nDe ingevoerde zin is een palindroom"); else System.out.println("\nDe ingevoerde zin is geen palindroom"); } else { System.out.println("\nEr is een woord ingevoerd\n"); invoer = filterZinOfWoord(invoer); if(palindromenTest(invoer)) System.out.println("\nHet ingevoerde woord is een palindroom"); else System.out.println("\nHet ingevoerde woord is geen palindroom"); } System.out.print("\nWil je dit programma nog een keer uitvoeren? [y/n]: "); invoerOpnieuw = scanner2.next(); if(invoerOpnieuw.toLowerCase().equals("y")) opnieuw = true; else opnieuw = false; } while(opnieuw == true); }
7
public void reloadGMCommands() { gmcommands.clear(); try { ClassFinder classFinder = new ClassFinder(); String[] classes = classFinder.listClasses("net.sf.odinms.client.messages.commands.Jounin", true); registerGMCommand(new HelpGMCommand()); // register the helpcommand first so it appears first in the list (LinkedHashMap) for (String clazz : classes) { Class<?> clasz = Class.forName(clazz); if (GMCommand.class.isAssignableFrom(clasz)) { try { GMCommand newInstance = (GMCommand) clasz.newInstance(); registerGMCommand(newInstance); } catch (Exception e) { System.err.println("ERROR INSTANCIATING COMMAND CLASS" + e); } } } } catch (ClassNotFoundException e) { System.err.println("THROW" + e); } }
5
public JSONObject increment(String key) throws JSONException { Object value = this.opt(key); if (value == null) { this.put(key, 1); } else if (value instanceof Integer) { this.put(key, ((Integer) value).intValue() + 1); } else if (value instanceof Long) { this.put(key, ((Long) value).longValue() + 1); } else if (value instanceof Double) { this.put(key, ((Double) value).doubleValue() + 1); } else if (value instanceof Float) { this.put(key, ((Float) value).floatValue() + 1); } else { throw new JSONException("Unable to increment [" + quote(key) + "]."); } return this; }
5
public java.io.Serializable fromDOM(Document document) { automatonMap.clear(); Automaton a = createEmptyAutomaton(document); Node parent = document.getDocumentElement() .getElementsByTagName(AUTOMATON_NAME).item(0); if(parent == null) parent = document.getDocumentElement(); return readAutomaton(parent, document); }
1
public void insert(Node root, Node n){ if(root == null|| n == null) return; if(root.getData() > n.getData()){ if(root.getLeft() == null){ root.setLeft(n); System.out.println("Added node to left of "+root.getData()+" of value "+n.getData()); }else{ insert(root.getLeft(),n); } }else if(root.getData() < n.getData()){ if(root.getRight() == null){ root.setRight(n); System.out.println("Added node to Right of "+root.getData()+" of value "+n.getData()); }else{ insert(root.getRight(),n); } } }
6
public Tile(int x, int y, TileType type, Match match) { this.x = x; this.y = y; this.type = type; bombers = new LinkedList<IBomber>(); this.match = match; }
0
public boolean yatzy(){ for(int i=1; i<5; i++){ if(nopat[0].getValue()!=nopat[i].getValue()){ return false; } } return true; }
2
@Override public int hashCode() { int result = cueMovto != null ? cueMovto.hashCode() : 0; result = 31 * result + (cueNaturaleza != null ? cueNaturaleza.hashCode() : 0); result = 31 * result + (cueCuentaConcatenada != null ? cueCuentaConcatenada.hashCode() : 0); return result; }
3
@Override public void keyPressed(KeyEvent arg0) { // TODO Auto-generated method stub if (arg0.getKeyCode() == KeyEvent.VK_W) { this.canMove = false; this.move("up"); } if (arg0.getKeyCode() == KeyEvent.VK_S) { this.canMove = false; this.move("down"); } if (arg0.getKeyCode() == KeyEvent.VK_A) { this.canMove = false; this.move("left"); } if (arg0.getKeyCode() == KeyEvent.VK_D) { this.canMove = false; this.move("right"); } }
4
private void evaluateClustersWithRespectToClass(Instances inst, String fileName) throws Exception { int numClasses = inst.classAttribute().numValues(); int[][] counts = new int[m_numClusters][numClasses]; int[] clusterTotals = new int[m_numClusters]; double[] best = new double[m_numClusters + 1]; double[] current = new double[m_numClusters + 1]; DataSource source = null; Instances instances = null; Instance instance = null; int i; int numInstances; if (fileName == null) fileName = ""; if (fileName.length() != 0) { source = new DataSource(fileName); } else source = new DataSource(inst); instances = source.getStructure(inst.classIndex()); i = 0; while (source.hasMoreElements(instances)) { instance = source.nextElement(instances); if (m_clusterAssignments[i] >= 0) { counts[(int) m_clusterAssignments[i]][(int) instance.classValue()]++; clusterTotals[(int) m_clusterAssignments[i]]++; } i++; } numInstances = i; best[m_numClusters] = Double.MAX_VALUE; mapClasses(m_numClusters, 0, counts, clusterTotals, current, best, 0); m_clusteringResults.append("\n\nClass attribute: " + inst.classAttribute().name() + "\n"); m_clusteringResults.append("Classes to Clusters:\n"); String matrixString = toMatrixString(counts, clusterTotals, new Instances(inst, 0)); m_clusteringResults.append(matrixString).append("\n"); int Cwidth = 1 + (int) (Math.log(m_numClusters) / Math.log(10)); // add the minimum error assignment for (i = 0; i < m_numClusters; i++) { if (clusterTotals[i] > 0) { m_clusteringResults.append("Cluster " + Utils.doubleToString((double) i, Cwidth, 0)); m_clusteringResults.append(" <-- "); if (best[i] < 0) { m_clusteringResults.append("No class\n"); } else { m_clusteringResults. append(inst.classAttribute().value((int) best[i])).append("\n"); } } } m_clusteringResults.append("\nIncorrectly clustered instances :\t" + best[m_numClusters] + "\t" + (Utils.doubleToString((best[m_numClusters] / numInstances * 100.0), 8, 4)) + " %\n"); // copy the class assignments m_classToCluster = new int[m_numClusters]; for (i = 0; i < m_numClusters; i++) { m_classToCluster[i] = (int) best[i]; } }
8
public void switchMenu() { try { menuSwitch.get(); } catch (NullPointerException e) { while (isReadyFX == false) { } } menuSwitch.set(!menuSwitch.get()); }
2
@Override public void update(GameContainer gc, StateBasedGame sb, float delta) { if (cooldown <= 0) { cooldown = 0; onCooldown = false; } else if (onCooldown) { if(invincibleTime >=3000){ invincible=false; } cooldown -= delta; invincibleTime+=delta; } }
3
protected void alignText() { int xLoc, yLoc; int spacing = Math.max((int)Math.round(font.getSize() * spacingRatio), 1); int endIndex; switch (vAlign) { case (V_TOP) : yLoc = this.getLocationY(); break; case (V_CENTER) : yLoc = this.getLocationYC() - font.getSize()*lines.size()/2; break; case (V_BOTTOM) : yLoc = this.getLocationY() + this.getHeight() - font.getSize()*lines.size(); break; default : yLoc = this.getLocationY(); } for (int l = 0; l < lines.size(); l++) { switch (hAlign) { case (H_LEFT) : xLoc = this.getLocationX(); break; case (H_CENTER) : xLoc = this.getLocationXC() - lines.get(l).width/2; break; case (H_RIGHT) : xLoc = this.getLocationX() + this.getWidth() - lines.get(l).width; break; default : xLoc = this.getLocationX(); } endIndex = lines.get(l).startIndex + lines.get(l).numChars; //non-inclusive for (int c = lines.get(l).startIndex; c < endIndex; c++) { this.getSubComponent(c).setLocation(xLoc, yLoc); this.getSubComponent(c).setSize(font.getSize(), font.getSize()); xLoc += font.getCharWidth(((CharComponent) this.getSubComponent(c)).getCharacter()) + spacing; } yLoc += font.getSize(); } }
8
public void cleanTab(){ //Trovo il numero reale di elmenti nel vettore int num=0; //Trovo il nmero di descrittori mossa corretto for(int i=0;i<desmosse.length;i++) if(desmosse[i]!=null) ++num; //Creo il vettore ben dimensionato DescrittoreMossa[] res = new DescrittoreMossa[num]; int c=0; //Copio gli elementi nel nuovo array for(int i=0;i<desmosse.length;i++) if(desmosse[i]!=null){ res[c] = desmosse[i]; ++c; } //aggiorno il vettore della mossa desmosse=res; }
4
private void setLabelDropTarget() { fieldLabel.setDropTarget(new DropTarget(this, new DropTargetListener() { private final DataFlavor entityFieldDataFlavor = new DataFlavor(EntityField.class, EntityField.class.getName()); public void dragEnter(DropTargetDragEvent event) { if (!isDragAcceptable(event)) { event.rejectDrag(); return; } } public void dragExit(DropTargetEvent event){} public void dragOver(DropTargetDragEvent event){} public void dropActionChanged(DropTargetDragEvent event) { if (!isDragAcceptable(event)) { event.rejectDrag(); return; } } public void drop(DropTargetDropEvent event) { if (!isDropAcceptable(event)) { event.rejectDrop(); return; } event.acceptDrop(DnDConstants.ACTION_COPY); Transferable transferable = event.getTransferable(); try { EntityField entityField = (EntityField) transferable.getTransferData(entityFieldDataFlavor); DiagramAbstractEntity deF = sqlDiagramViewPanel.getEntity(entityField.getTable()); if (deF == null) { //search for derived table deF = sqlDiagramViewPanel.getDerivedEntity(entityField.getTable()); } DiagramFieldPanel dfF = deF.getField(entityField.getFieldName()); DiagramFieldPanel dfP = (DiagramFieldPanel) event.getDropTargetContext().getDropTarget() .getComponent().getParent(); sqlDiagramViewPanel.join(dfP.diagramEntity, dfP, deF, dfF); } catch (Exception ex) { ex.printStackTrace(); } event.dropComplete(true); } public boolean isDropAcceptable(DropTargetDropEvent event) { DataFlavor[] dataFlavors = event.getCurrentDataFlavors(); for (int i = 0; i < dataFlavors.length; ++i) { DataFlavor dataFlavor = dataFlavors[i]; if (dataFlavor.equals(entityFieldDataFlavor)) { return true; } } return false; } public boolean isDragAcceptable(DropTargetDragEvent event) { return event.getCurrentDataFlavorsAsList().contains(entityFieldDataFlavor); } })); }
7
@Override public Value evaluate(Value... operands) throws Exception { // we need two operands if (operands.length != input()) throw new EvalException("Error: wrong number of operands"); // get operands Value l = operands[0]; Value r = operands[1]; // if they are identical if (l.getType().isNumeric() && r.getType().isNumeric()) { // perform OR return new Value(new Boolean(l.getDouble() == r.getDouble())); } // if they are identical if (l.getType() == r.getType()) { // perform OR return new Value(new Boolean(l.getData().equals(r.getData()))); } return new Value(new Boolean(false)); }
4
public void moveTo(double toPosition) { //get the free space in front of us on this road double freeSpace = checkFreeSpaceAhead(); //calculate velocity double velocity = (_velocity / (_brakeDistance - _stopDistance)) * (freeSpace - _stopDistance); //System.out.println("V1 = " + velocity); velocity = Math.max(0, velocity); //System.out.println("V2 = " + velocity); velocity = Math.min(_velocity, velocity); double step = (velocity * MP.simulationTimeStep); double nextPos = this.getPosition() + step; //if the road is clear AND the maxMove is beyond the current road road. try to send to the next road if (nextPos > this.getCurrentRoad().getLength()) { //send to the next segment and request the appropriate space. if (sendCarToNextSeg(nextPos - this.getCurrentRoad().getLength())) { //System.out.println("Sent car to next seg " + this + " NP " + nextPos + " " + (nextPos - this.getCurrentRoad().getLength())); //_ts.enqueue(MP.simulationTimeStep + _ts.currentTime(), this); return; } else { //the car was rejected by the next road! set the max move to be the //length of the road - stopDistance, which should be the max value for the position nextPos = this.getCurrentRoad().getLength(); } } //System.out.println("C: " + this + " nextPos " + nextPos + " step " + Math.round(step) + " velocity = " + velocity + " fs: " + freeSpace + " rL = " + this.getCurrentRoad().getLength() + " VAL = " + (velocity * MP.simulationTimeStep)); if (nextPos == this.getPosition()) { //System.out.println("Car stopped: " + this + " " + nextPos + " in road " + this.getCurrentRoad()); } this.setPosition(nextPos); }
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(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Login.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() { try { new Login().setVisible(true); } catch (FileNotFoundException ex) { Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); } } }); }
8
@Override public boolean canDespawn(LivingEntity entity) { if (entity == null) return false; final boolean async = !P.p().getServer().isPrimaryThread(); for (Entry<Plugin, Protector> entry : protectors.entrySet()) { if (!entry.getKey().isEnabled()) continue; Protector protector = entry.getValue(); try { if (async && !protector.supportsAsynchronousUsage()) continue; if (!protector.canDespawn(entity)) return false; } catch (Exception e) { P.p().getLogger().severe("Caught Exception while checking if a mob could despawn"); e.printStackTrace(); } catch (Throwable e) { } } return true; }
8
String reverse(String s1){ char c[]=new char[s1.length()]; c=s1.toCharArray(); for(int i=0;i<(s1.length()/2);i++){ char temp=c[(s1.length()-1)-i]; c[(s1.length()-1)-i]=c[i]; c[i]=temp; } return new String(c); }
1
public boolean recursiveSymmetric(TreeNode left, TreeNode right) { if(left == null && right == null) return true; if((left == null && right != null) || (left != null && right == null)) return false; if(left.val != right.val) return false; boolean l = recursiveSymmetric(left.left, right.right); boolean r = recursiveSymmetric(left.right, right.left); return l && r; }
8
@Test public void heapTest(){ long start = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++){ heap.insert(i); } long end = System.currentTimeMillis(); long totaltime = end - start; System.out.println("Time spent adding 1 000 000: " + totaltime + "ms = " + (totaltime*1.0)/1000 + "s"); }
1
public void Pesquisar() throws IOException, ClassNotFoundException{ Scanner sc = new Scanner(System.in); Reader fileReader = new FileReader("registros.txt"); BufferedReader br = new BufferedReader(fileReader); String showReg = null; System.out.println("Digite um nome"); String pesquisa = sc.next(); while ((showReg = br.readLine()) != null) { if(showReg.equalsIgnoreCase(pesquisa)){ System.out.println("Contatos encontrados: " + showReg + " "); System.out.println("\nVoce deseja ver mais contatos?"); pesquisa = sc.next().toUpperCase(); if(pesquisa.equalsIgnoreCase("SIM")){ PesquisarContatos pc = new PesquisarContatos(); pc.Pesquisar(); } } } }
3
public AnnealerAdapterI run() { aa.initialState(); double t = 0.5; double acceptRate = 0.5; for (int i = 1; i < evalSMax; i++) { aa.nextState(); // the normal annealing process if (aa.costDecreasing()) { aa.accept(); acceptRate = (1.0/500.0) * (499.0 * (acceptRate + 1)); } else { double r = rand.nextDouble(); if (r < Math.pow(Math.E, (aa.costDifference() / t))) { aa.accept(); acceptRate = (1.0/500.0) * (499.0 * (acceptRate + 1)); } else { aa.reject(); acceptRate = (1.0/500.0) * (499.0 * (acceptRate)); } } // calculate the lambda rate double lamRate = 0.0; if (i/evalSMax < 0.15) { lamRate = 0.44 + 0.56 * Math.pow(560, -i/evalSMax/0.15); } else if (i/evalSMax >= 0.15 && i/evalSMax < 0.65) { lamRate = 0.44; } else if (0.65 <= i/evalSMax) { lamRate = 0.44 * Math.pow(440, -(i/evalSMax - 0.65)/0.15); } System.out.println("lam=" + lamRate + "acceptRate=" + acceptRate); // use the lambda to adjust the temperature if (acceptRate > lamRate) { t = 0.999 * t; } else { t = t / 0.999; } fireTemperatureEvent(t); } return aa; }
8
public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_W) ya = -game.getSpeedx(); if (e.getKeyCode() == KeyEvent.VK_S) ya = game.getSpeedx(); if (e.getKeyCode() == KeyEvent.VK_A) xa = -game.getSpeedx(); if (e.getKeyCode() == KeyEvent.VK_D) xa = game.getSpeedx(); }
4
public int[] getPlacementResourceCards(Coordinate coord) { coord = coord.normalizeCoordinate(); int cardsEarned[] = new int[5]; for (int i = 0; i < cardsEarned.length; i++) { cardsEarned[i] = 0; } // Get the node at the coordinate Node settlementLocation = nodeSet.get(coord); if (settlementLocation != null && settlementLocation.hasSettlement()) { // Obtain the three bordering tiles Coordinate neighboringTiles[] = new Coordinate[3]; if (coord.z == 0) { neighboringTiles[0] = new Coordinate(coord.x, coord.y, 0); neighboringTiles[1] = new Coordinate(coord.x + 1, coord.y, 0); neighboringTiles[2] = new Coordinate(coord.x + 1, coord.y - 1, 0); } else { neighboringTiles[0] = new Coordinate(coord.x, coord.y, 0); neighboringTiles[1] = new Coordinate(coord.x, coord.y + 1, 0); neighboringTiles[2] = new Coordinate(coord.x + 1, coord.y, 0); } // Add the resources, if any for (Coordinate tileCoord : neighboringTiles) { Tile tile = tileSet.get(tileCoord); if (tile != null) { cardsEarned[tile.getTileType().getIndex()]++; } } } return cardsEarned; }
6
public boolean isTintedGlass() { return tintedGlass; }
0