text
stringlengths
14
410k
label
int32
0
9
public static String escapeDoubleQuotes(String string) { if (string == null) { return null; } String result = string.replaceAll("\\\\", "\\\\\\\\"); return result.replaceAll("\\\"", "\\\\\\\""); }
1
public void languageAndWordlistCheckMain() { try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream("Options.dat"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line int count =0; while ((strLine = br.readLine()) != null) { // Print the content on the console if(count == 0){ wordbook = strLine; }else if(count == 1){ language = strLine; } count++; } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } //prepare the language selected: if(Integer.parseInt(language) == 0){ jButton1.setText("Nächstes Wort>>"); jButton2.setText("<< Zurück"); jButton3.setText("der Artikel"); jButton4.setText("der Plural"); jMenu1.setText("Hilfe"); jMenu2.setText("Geräte"); jMenuItem1.setText("Optionen"); jMenuItem2.setText("Wortliste Verwaltung"); jMenuItem3.setText("Über"); }else if(Integer.parseInt(language) == 1){ jButton1.setText("Sıradaki Kelime >>"); jButton2.setText("<< Geri"); jButton3.setText("Artikel"); jButton4.setText("Çoğul"); jMenu1.setText("Yardım"); jMenu2.setText("Ayarlar"); jMenuItem1.setText("Seçenekler"); jMenuItem2.setText("Kelime Listesini Yönet"); jMenuItem3.setText("Hakkında"); }else if(Integer.parseInt(language) == 2){ jButton1.setText("Next Word >>"); jButton2.setText("<< Back"); jButton3.setText("The Article"); jButton4.setText("The Plural"); jMenu1.setText("Help"); jMenu2.setText("Tools"); jMenuItem1.setText("Options"); jMenuItem2.setText("Edit Word List"); jMenuItem3.setText("About"); } }
7
private int knapsack(int n, int capacity, int w[], int v[]) { // dynamic programming if (vKnapsack[capacity] != Integer.MIN_VALUE) return vKnapsack[capacity]; // Find the optimal value that can carried in a knapsack of given // capacity // The optimal value that can be carried is the maximum of the optimal // subproblem solutions. // Each subproblem here represents a choice of including one of the // items in the knapsack and optimally packing into the rest of the // knapsack int max = 0; for (int i = 0; i < n; i++) { // remove this to get a solution for the unbounded problem if (inKnapsack[i]) continue; // Is there space(non-negative) in the knapsack to add item i int space = capacity - w[i]; if (space < 0) continue; // Result of optimally packing in the remaining space int t = knapsack(n, space, w, v); // optimal solution is the max of all subproblems. if (v[i] + t > max) { max = v[i] + t; contentsKnapsack[capacity] = w[i] + " " + contentsKnapsack[space]; inKnapsack[i] = true; } } vKnapsack[capacity] = max; return vKnapsack[capacity]; }
5
@EventHandler public void onTarget(EntityTargetLivingEntityEvent e) { if (e.getTarget().getType() == EntityType.PLAYER) { if (e.getTarget().isInsideVehicle()) { if (e.getEntity().getEntityId() == e.getTarget().getVehicle() .getEntityId()) { e.setCancelled(true); e.setTarget(null); if (e.getEntity() instanceof Creature) { Creature c = (Creature) e; c.setTarget(null); } } } } }
4
private void updateAsteroids() { ArrayList<Asteroid> deadAsteroid = new ArrayList<Asteroid>(); for(int i = 0; i < asteroids.size(); i++) { Asteroid a = asteroids.get(i); a.move(); if(CollisionDetector.isColliding(sc, a)) { if(!sc.isShieldActive()) sc.damaged(a.getStrength()); else score += a.getScore(); a.damaged(sc.getStrength()); } if(!a.isOnScreen()) deadAsteroid.add(a); } for(int i = 0; i < deadAsteroid.size(); i++) { Asteroid a = deadAsteroid.get(i); asteroids.remove(a); } asteroidItr = (asteroidItr + 1) % (ASTEROIDS_RATE_LIMITER - RATE_OF_ASTEROIDS); if(asteroidItr == 0 && asteroidsPresence) { asteroids.add(new Asteroid()); } }
7
public SimpleSparqlSimulator(String endpoint) throws MalformedURLException { // read the list of files of queries sparql_queries = new ArrayList<File>(); URL url = getClass().getResource("/"); LOGGER.info("Reading queries (txt files) from " + url.getPath() + SimpleSparqlSimulator.class.getName()); File dir = new File(url.getPath() + SimpleSparqlSimulator.class.getName()); if (dir.isDirectory()) { for (final File fileEntry : dir.listFiles()) { if (fileEntry.isFile()) if (fileEntry.getName().endsWith(".txt")) sparql_queries.add(fileEntry); } } else LOGGER.error("Not a directory"); this.endpoint = new URL(endpoint); }
4
public static BasicBlock find(BasicBlock[] blocks, int pos) throws BadBytecode { for (int i = 0; i < blocks.length; i++) { int iPos = blocks[i].position; if (iPos <= pos && pos < iPos + blocks[i].length) return blocks[i]; } throw new BadBytecode("no basic block at " + pos); }
3
public int atualizar(String sql) { Connection conn = this.getConn(); try { Statement stm = conn.createStatement(); return stm.executeUpdate(sql); } catch (SQLException ex) { Logger.getLogger(ConectorMySql.class.getName()).log(Level.SEVERE, null, ex); } return -1; }
1
protected void paintText(Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) { if (isSelected) { int vDifference = (int) (boldFontMetrics.getStringBounds(title, g).getWidth()) - textRect.width; textRect.x -= (vDifference / 2); super.paintText(g, tabPlacement, boldFont, boldFontMetrics, tabIndex, title, textRect, isSelected); } else { super.paintText(g, tabPlacement, font, metrics, tabIndex, title, textRect, isSelected); } }
1
public void doFilter(ServletRequest _request, ServletResponse _response, FilterChain chain) throws IOException, ServletException { if (_request instanceof HttpServletRequest && _response instanceof HttpServletResponse) { HttpServletRequest request = (HttpServletRequest) _request; HttpServletResponse response = (HttpServletResponse) _response; request = new MapHttpServletRequest(request); processPath((MapHttpServletRequest) request); request.setAttribute(AttributeNames.REQUEST_URI, request.getRequestURI()); request.setAttribute(AttributeNames.REQUEST_URL, request.getRequestURL().toString()); String path = request.getRequestURI().substring(request.getContextPath().length()); Object target = pages.resolve((MapHttpServletRequest) request, path, HttpMethods.getMethod(request.getMethod())); request.setAttribute(AttributeNames.PATH, path); if (target instanceof ServletAction) { ((ServletAction) target).invoke(request, response); return; } else if (target instanceof Page) { request.setAttribute(AttributeNames.PATH_SET, lookupPaths(target.getClass())); request.setAttribute(AttributeNames.PAGE, target); if (dispatchServlet == null) { ((Page) target).service(servletContext, request, response); } else { request.getRequestDispatcher(dispatchServlet).forward(request, response); } return; } } chain.doFilter(_request, _response); }
5
private static void printGame(JSONObject jo) { try { JSONArray champs = Champion.getAllChamps(false); long champId = jo.getLong("championId"); System.out.println("Game " + jo.getLong("gameId")); System.out.println("-----------------------------"); System.out.println("Champion: " + champId + " (" + Champion.getChampName(champs, champId) + ")"); System.out.println("Create Date: " + Util.getFriendlyDate(jo.getLong("createDate"))); System.out.println("Fellow Players:\n"); JSONArray players = jo.getJSONArray("fellowPlayers"); String ids = ""; for(int i = 0; i < players.length(); i++) { JSONObject o = players.getJSONObject(i); ids += o.getLong("summonerId") + ","; } ids = ids.substring(0, ids.lastIndexOf(",")); JSONObject names = Summoner.getSummonersById(ids); for(int i = 0; i < players.length(); i++) { JSONObject o = players.getJSONObject(i); champId = o.getLong("championId"); System.out.println(" " + names.getJSONObject(o.getLong("summonerId") + "").getString("name")); System.out.println(" -----------------------------"); System.out.println(" Champion: " + champId + "(" + Champion.getChampName(champs, champId) + ")"); System.out.println(" Team: " + (o.getInt("teamId") == 100 ? "Blue" : "Purple/Red")); System.out.println(); } int mapId = jo.getInt("mapId"); System.out.println("Map: " + mapId + " [" + GameConstants.getMapName(mapId) + "]"); System.out.println("Game Mode: " + jo.getString("gameMode")); System.out.println("Game Type: " + jo.getString("gameType")); System.out.println("Game Sub-Type: " + jo.getString("subType")); // System.out.println("Invalid " + jo.getBoolean("invalid")); System.out.println("Level: " + jo.getInt("level")); System.out.println("Spell 1: " + jo.getInt("spell1")); System.out.println("Spell 2: " + jo.getInt("spell2")); System.out.println("Team: " + (jo.getInt("teamId") == 100 ? "Blue" : "Purple/Red") + "\n"); JSONObject stats = jo.getJSONObject("stats"); System.out.println(" Stats"); System.out.println(" -----------------------------"); System.out.println(" Win: " + stats.getBoolean("win")); System.out.println(" Nexus Final Blow: " + stats.optBoolean("nexusKilled", false)); System.out.println(" K/D/A/CS: " + stats.optInt("championsKilled") + "/" + stats.optInt("numDeaths") + "/" + stats.optInt("assists") + "/" + stats.optInt("minionsKilled")); System.out.println(" Gold Earned: " + Util.getFriendlyNum(stats.getLong("goldEarned"))); System.out.println(" Spent: " + Util.getFriendlyNum(stats.getLong("goldSpent"))); System.out.println(" Time: " + Util.getTime(stats.getInt("timePlayed"))); System.out.println(); System.out.println(" Items"); System.out.println(" ============================="); System.out.println(" Items: " + stats.optInt("item0") + "/" + stats.optInt("item1") + "/" + stats.optInt("item2") + "/" + stats.optInt("item3") + "/" + stats.optInt("item4") + "/" + stats.optInt("item5") + "/" + stats.optInt("item6")); System.out.println(" Items Purchased: " + stats.optInt("itemsPurchased")); System.out.println(" Consumables Purchased: " + stats.optInt("consumablesPurchased")); System.out.println(" Legendary Items Built: " + stats.optInt("lengendaryItemsCreated")); System.out.println(" VisionWards Bought: " + stats.optInt("visionWardsBought")); System.out.println(" SightWards Bought: " + stats.optInt("sightWardsBought")); System.out.println(" Wards Placed: " + stats.optInt("wardPlaced")); System.out.println(" Wards Killed: " + stats.optInt("wardKilled")); System.out.println(); System.out.println(" Damage"); System.out.println(" ============================="); System.out.println(" Killing Sprees: " + stats.optInt("killingSprees")); System.out.println(" Double Kills: " + stats.optInt("doubleKills")); System.out.println(" Triple Kills: " + stats.optInt("tripleKills")); System.out.println(" Quadra Kills: " + stats.optInt("quadraKills")); System.out.println(" Penta Kills: " + stats.optInt("pentaKills")); System.out.println(" Unreal Kills: " + stats.optInt("unrealKills")); System.out.println(" Largest Killing Spree: " + stats.optInt("largestKillingSpree")); System.out.println(" Largest MultiKill: " + stats.optInt("largestMultiKill")); System.out.println(" Largest Critical Strike: " + Util.getFriendlyNum(stats.optInt("largestCriticalStrike"))); System.out.println(" Magic Damage Dealt: " + Util.getFriendlyNum(stats.optInt("magicDamageDealtPlayer"))); System.out.println(" To Champions: " + Util.getFriendlyNum(stats.optInt("magicDamageDealtToChampions"))); System.out.println(" Magic Damage Taken: " + Util.getFriendlyNum(stats.optInt("magicDamageTaken"))); System.out.println(" Minions Killed: " + stats.optInt("minionsKilled")); System.out.println(" Denied: " + stats.optInt("minionsDenied")); System.out.println(" Neutral Minions Killed: " + stats.optInt("neutralMinionsKilled")); System.out.println(" Your Jungle: " + stats.optInt("neutralMinionsKilledYourJungle")); System.out.println(" Enemy Jungle: " + stats.optInt("neutralMinionsKilledEnemyJungle")); System.out.println(" Physical Damage Dealt: " + Util.getFriendlyNum(stats.optInt("physicalDamageDealt"))); System.out.println(" To Champions: " + Util.getFriendlyNum(stats.optInt("physicalDamageDealtToChampions"))); System.out.println(" Physical Damage Taken: " + Util.getFriendlyNum(stats.optInt("physicalDamageTaken"))); System.out.println(" Super Monsters Killed: " + stats.optInt("superMonsterKilled")); System.out.println(" Total Damage Dealt: " + Util.getFriendlyNum(stats.optInt("totalDamageDealtPlayer"))); System.out.println(" To Champions: " + Util.getFriendlyNum(stats.optInt("totalDamageDealtToChampions"))); System.out.println(" Total Damage Taken: " + Util.getFriendlyNum(stats.optInt("totalDamageTaken"))); System.out.println(" Total Heal: " + Util.getFriendlyNum(stats.optInt("totalHeal"))); System.out.println(" Total CC Time Dealt: " + Util.getTime(stats.optInt("totalCrowdControlTimeDealt"))); System.out.println(" Total Units Killed: " + stats.optInt("totalUnitsKilled")); System.out.println(" True Damage Dealt: " + Util.getFriendlyNum(stats.optInt("trueDamageDealtPlayer"))); System.out.println(" To Champions: " + Util.getFriendlyNum(stats.optInt("trueDamageDealtToChampions"))); System.out.println(" True Damage Taken: " + Util.getFriendlyNum(stats.optInt("trueDamageTaken"))); System.out.println(" Turrets Killed: " + stats.optInt("turretsKilled")); System.out.println(); System.out.println(" Spells"); System.out.println(" ============================="); System.out.println(" Q/W/E/R Casts: " + stats.optInt("spell1Cast") + "/" + stats.optInt("spell2Cast") + "/" + stats.optInt("spell3Cast") + "/" + stats.optInt("spell4Cast")); System.out.println(" D/F Casts: " + stats.optInt("summonSpell1Cast") + "/" + stats.optInt("summonSpell2Cast")); System.out.println(); if(jo.getString("gameType").equalsIgnoreCase("ODIN")) { System.out.println(" Dominion"); System.out.println(" ============================="); System.out.println(" Barracks Killed: " + stats.getInt("barracksKilled")); System.out.println(" CombatPlayerScore: " + Util.getFriendlyNum(stats.getInt("combatPlayerScore"))); System.out.println(" Nodes Captured: " + stats.getInt("nodeCapture")); System.out.println(" Assists: " + stats.getInt("nodeCaptureAssist")); System.out.println(" Nodes Neutralized: " + stats.getInt("nodeNeutralize")); System.out.println(" Assists: " + stats.getInt("nodeNeutralizeAssist")); System.out.println(" Objective Score: " + Util.getFriendlyNum(stats.getInt("objectivePlayerScore"))); System.out.println(" Total Player Score: " + Util.getFriendlyNum(stats.getInt("totalPlayerScore"))); System.out.println(" Total Score Rank: " + Util.getFriendlyNum(stats.getInt("totalScoreRank"))); System.out.println(" Victory Point Total: " + Util.getFriendlyNum(stats.getInt("victoryPointTotal"))); } } catch (JSONException e) { e.printStackTrace(); } }
6
private void setSelected(SingleScorePanel singleScorePanel) { singleScorePanel.setSelected(true); }
0
public static void main(String args[]) { String test = args[0]; int up = 0; int down = 0; int left = 0; int right = 0; for(int i = 0; i < test.length(); i++) { switch(test.charAt(i)) { case 'U': up++; break; case 'D': down++; break; case 'L': left++; break; case 'R': right++; break; } } if( (up == down) && (left == right)) { System.out.println("ALL OKAY"); } }
7
@Override public boolean equals( Object obj ){ if (this == obj){ return true; } if (obj == null){ return false; } if (obj instanceof PassengerCar ){ PassengerCar temp = (PassengerCar) obj; return ( this.baggageWeight == temp.getBaggageWeight())&& ( this.passengersCount == temp.getPassengersCount() )&& ( this.getComfortPercent() == temp.getComfortPercent())&& ( this.getHeight() == temp.getHeight() )&& ( this.getTonsWeight() == temp.getTonsWeight() ); } else { return false; } }
7
public static int[] getRandomOrdering(int Size){ double[] randArray = new double[Size]; for(int n = 0; n < Size; n++){ randArray[n] = Math.random(); } int[] randOrder = new int[Size]; double lowestRand = 1; for(int i = 0; i < Size; i++){ for(int n = 0; n < Size; n++){ if(randArray[n] < lowestRand) { randOrder[i] = n; lowestRand = randArray[n]; } } randArray[randOrder[i]] = 1; lowestRand = 1; } return randOrder; }
4
public void timeAndComputeValue(){ }
0
public String rotate(String plainText) { char[] plainTextChars = plainText.toCharArray(); StringBuilder rotatedChars = new StringBuilder(); for (char plainTextChar : plainTextChars) { if ((plainTextChar >= 'a' && plainTextChar <= 'm') || (plainTextChar >= 'A' && plainTextChar <= 'M')) { plainTextChar += ROT13; } else if ((plainTextChar >= 'm' && plainTextChar <= 'z') || (plainTextChar >= 'M' && plainTextChar <= 'Z')) { plainTextChar -= ROT13; } rotatedChars.append(plainTextChar); } return rotatedChars.toString(); }
9
public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP && !principal.getSalta()){ principal.setSalta(); tiempoCaida = 0; } }
2
public void removeOpinion(DataRow row) { boolean result = DataVector.getInstance().dbManager.remove(row); if(!result) { ErrorDialog errorDialog = new ErrorDialog(true, "Nastąpił błąd w usuwaniu opinii: " + row.getName() + ".", "AbstractManager", "Method: removeOpinion(DataRow row)", "row"); errorDialog.setVisible(true); return; } for(AbstractOpinion a : opinions) { if(a.getName().equals(row.getName())) { opinions.remove(a); refreshData(); return; } } }
3
public String udp2String(Packet packet) { UDPPacket udpPacket = (UDPPacket) packet; //Creates a udp packet out of the packet EthernetPacket ethernetPacket = (EthernetPacket) packet.datalink; //Creates and ethernet packet for layer 2 information methodData += src_macInEnglish = ethernetPacket.getSourceAddress(); //Gets the string value of the src mac address methodData += dst_macInEnglish = ethernetPacket.getDestinationAddress(); //Gets the string value of the dst mac address methodData += src_UDPPort = udpPacket.src_port; //Gets the src udp port methodData += sourcePortUDP = String.valueOf(src_UDPPort); //creates a string using the port to place in the dataArray methodData += dst_UDPPort = udpPacket.dst_port; //Gets the dst port from the packet methodData += destinationPortUDP = String.valueOf(dst_UDPPort); //Creates a string from dst_UDPPport methodData += src_ip = udpPacket.src_ip; //Gets the inet address from the packet methodData += srcIPString = src_ip.toString(); //Converts the InetAddress to a string methodData += dst_ip = udpPacket.dst_ip; //Gets the inet dst Ip address from udppacket methodData += dstIPString = dst_ip.toString(); //Converts that to a string protocol = udpPacket.protocol; //Grabs the protocol methodData += protocolName = "UDP"; //Since this is udp we don't have to worry about other protocols for(int i = 0; i < udpPacket.data.length; i++) { //Runs through the array containing packet data data += String.valueOf((char) udpPacket.data[i]); //Creates a string from every part of that array } methodData += data; return methodData; }
1
public static void main(String [] args) throws Throwable { if (args.length < 2) { usage(); return; } Class stemClass = Class.forName("org.tartarus.snowball.ext." + args[0] + "Stemmer"); SnowballStemmer stemmer = (SnowballStemmer) stemClass.newInstance(); Reader reader; reader = new InputStreamReader(new FileInputStream(args[1])); reader = new BufferedReader(reader); StringBuffer input = new StringBuffer(); OutputStream outstream; if (args.length > 2) { if (args.length >= 4 && args[2].equals("-o")) { outstream = new FileOutputStream(args[3]); } else { usage(); return; } } else { outstream = System.out; } Writer output = new OutputStreamWriter(outstream); output = new BufferedWriter(output); int repeat = 1; if (args.length > 4) { repeat = Integer.parseInt(args[4]); } Object [] emptyArgs = new Object[0]; int character; while ((character = reader.read()) != -1) { char ch = (char) character; if (Character.isWhitespace((char) ch)) { if (input.length() > 0) { stemmer.setCurrent(input.toString()); for (int i = repeat; i != 0; i--) { stemmer.stem(); } output.write(stemmer.getCurrent()); output.write('\n'); input.delete(0, input.length()); } } else { input.append(Character.toLowerCase(ch)); } } output.flush(); }
9
public String getPassword() { return password; }
0
public void add(String line) { graph.append(line); }
0
public static boolean isOptionPresent(String cmdLineArg, char option) { boolean result = false; // avoid "--abc" if (cmdLineArg.lastIndexOf('-') == 0) { result = cmdLineArg.indexOf(option) >= 1; } return result; }
1
public long getSeatType() { return this._seatType; }
0
public static boolean isOnScreen(Entity paramEntity) { if (paramEntity.getXpos() > ScreenHelper.widthNeg(paramEntity) && paramEntity.getXpos() < ScreenHelper.widthPos(paramEntity)) { if (paramEntity.getYpos() > ScreenHelper.heightNeg(paramEntity) && paramEntity.getYpos() < ScreenHelper.heightPos(paramEntity)) { return true; } } return false; }
4
public ListNode rotateRight(ListNode head, int n) { if(null == head || null == head.next) return head; int length = getLengthOfList(head); ListNode tail = getTailOfNode(head); tail.next = head; ListNode pivot = getRotateNode(head, length - n % length); return pivot; }
2
public ArrayList<Record> getNewsfeed() { ArrayList<User> myfriends = getFriendList(); ArrayList<Record> newsFeeds = new ArrayList<Record>(); for (int i = 0; i < myfriends.size(); i++) { User friend = myfriends.get(i); newsFeeds.addAll(QuizTakenRecord.getQuizHistoryByUserID(friend.userID)); newsFeeds.addAll(QuizCreatedRecord.getCreatedQuizByUserID(friend.userID)); newsFeeds.addAll(AchievementRecord.getAchievementRecordByUserID(friend.userID)); } Collections.sort(newsFeeds, new RecordSortByTime()); return newsFeeds; }
1
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getParameter("id"); String password = req.getParameter("password"); if (id == null || id.length() == 0 || password == null || password.length() == 0) { resp.sendError(400, "incomplete parameter"); return; } AccountService service = (AccountService) context.getBean("accountService"); try { service.login(id, password); resp.getWriter().print("Login Successful!"); } catch (AccountServiceException e) { resp.sendError(400, e.getMessage()); } }
5
public void paintComponent(Graphics g){ Graphics2D g2 = (Graphics2D) g; int heightMover = 0; for (int tetIndex = 0; tetIndex<upcoming.size(); tetIndex++){ g2.setColor(controller.getBlankColor()); g2.fillRect(0, heightMover*size, size*6, size); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); heightMover++; int[][] visualMap = upcoming.get(tetIndex).getVisual(); for (int i = 0; i<visualMap.length; i++){ //draw black block to the left g2.setColor(controller.getBlankColor()); g2.fillRect(0, (i+heightMover)*size, size, size); //draw the tetromino for(int j = 0; j<visualMap[0].length; j++){ if(visualMap[i][j] == Board.VISUAL_MANA_ORB){ g2.setColor(controller.getBlankColor()); g2.fillRect((j+1)*size, (i+heightMover)*size, size, size); g2.setColor(Color.MAGENTA); g2.fillOval((j+1)*size, (i+heightMover)*size, size, size); } else { Color color; if (visualMap[i][j] == Board.VISUAL_EMPTY_AREA){ color = controller.getBlankColor(); } else { color = controller.getColor(visualMap[i][j]); } g2.setColor(color); g2.fill3DRect((j+1)*size, (i+heightMover)*size, size, size, true); } } //fill in remaining gap with black for (int l = visualMap[0].length+1; l<6; l++){ g2.setColor(controller.getBlankColor()); g2.fillRect(l*size, (i+heightMover)*size, size, size); } } heightMover += visualMap.length; } //add bottom black bar g2.setColor(controller.getBlankColor()); g2.fillRect(0, heightMover*size, size*6, size); }
6
@Override public void deserialize(Buffer buf) { elementId = buf.readInt(); if (elementId < 0) throw new RuntimeException("Forbidden value on elementId = " + elementId + ", it doesn't respect the following condition : elementId < 0"); elementCellId = buf.readShort(); if (elementCellId < 0 || elementCellId > 559) throw new RuntimeException("Forbidden value on elementCellId = " + elementCellId + ", it doesn't respect the following condition : elementCellId < 0 || elementCellId > 559"); elementState = buf.readInt(); if (elementState < 0) throw new RuntimeException("Forbidden value on elementState = " + elementState + ", it doesn't respect the following condition : elementState < 0"); }
4
@Override public void doAction(Player player) throws InvalidActionException { if (player == null) throw new IllegalArgumentException("Player can't be null!"); if (player.getRemainingActions() <= 0) throw new InvalidActionException("The player has no turns left!"); Position currentPos = player.getPosition(); Position newPos = movement.newPosition(currentPos); if (!grid.canMove(player, movement)) throw new InvalidActionException("The player can't move to the desired position!"); player.setPosition(newPos); player.setMovedDuringTurn(true); player.getLightTrail().addPosition(currentPos); player.decrementAction(); //doCollide(player); }
3
void toss(){ Random rand=new Random(); if(rand.nextInt(9)<5){ this.setHeadSide(true); }else{ this.setTailSide(true); } }
1
private long ticklessTimer() { // Calculate tickless timer, up to 1 hour long tickless = System.currentTimeMillis() + 1000 * 3600; for (STimer timer : timers) { if (timer.when == -1) timer.when = timer.delay + System.currentTimeMillis(); if (tickless > timer.when) tickless = timer.when; } long timeout = tickless - System.currentTimeMillis(); if (timeout < 0) timeout = 0; if (verbose) System.out.printf("I: zloop: polling for %d msec\n", timeout); return timeout; }
5
@SuppressWarnings({ "rawtypes", "unchecked" }) public void getAllInGroup(String group, Map target){ try{ String key; ObjectInputStream objStr; Serializable obj; PreparedStatement prep = this.conn.prepareStatement("SELECT key, value FROM keyval WHERE collection = ?"); prep.setString(1, group); ResultSet rs = prep.executeQuery(); while(rs.next()){ key = rs.getString(1); objStr = new ObjectInputStream(new ByteArrayInputStream(rs.getBytes(2))); obj = (Serializable)objStr.readObject(); target.put(key, obj); } rs.close(); }catch(Exception e){ e.printStackTrace(); } }
2
public String getConsulDefMap(String arg_dt1) throws SQLException, ClassNotFoundException { ResultSet rs; String sts = ""; Connection conPol = conMgr.getConnection("PD"); if (conPol == null) { throw new SQLException("Numero Maximo de Conexoes Atingida!"); } try { call = conPol.prepareCall("SELECT distinct tb_tp_defeito.str_defeito" + " FROM public.tb_defeito, public.tb_tp_defeito WHERE " + " tb_tp_defeito.cod_tp_defeito = tb_defeito.cod_tp_defeito AND" + " date_trunc('month', datahora) = TO_timestamp(?,'MM/YYYY')" + " order by tb_tp_defeito.str_defeito"); call.setString(1, arg_dt1); rs = call.executeQuery(); while (rs.next()) { sts = sts + "[\"" + rs.getString(1).replace(" ", "_") + "\",\"Defeitos\",0,0], \n"; } call.close(); } finally { if (conPol != null) { conMgr.freeConnection("PD", conPol); } } return sts; }
3
private void btnValiderMembreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnValiderMembreActionPerformed if(jRadioButton1.isSelected()){ jTable1.setModel(new ListMembreNomController(jTextField1.getText())); } if(jRadioButton2.isSelected()){ jTable1.setModel(new ListMembreMailController(jTextField1.getText())); } if(jRadioButton3.isSelected()){ jTable1.setModel(new supprimer_membre_controler()); } }//GEN-LAST:event_btnValiderMembreActionPerformed
3
public void fillStocks() { pnlDashboardCenter.removeAll(); stocks = new ArrayList<Stock>(Service.getAllStocks()); Collections.sort(stocks); squareGraphicList = new ArrayList<SquareGraphic>(); selectedSquare = null; for (Stock stock : stocks) { SquareGraphic sq = new SquareGraphic(); sq.addMouseListener(selectStockLisneter); sq.setPreferredSize(new Dimension(85, 85)); sq.setStock(stock); sq.setState(Service.getWorstState(stock)); pnlDashboardCenter.add(sq); squareGraphicList.add(sq); } this.repaint(); this.validate(); }
1
private boolean isStudentInOneLectureAtTheTime(Teacher teacher, List<Group> teachersGroups, Group group, int lectureNumber, LinkedHashMap<String, LinkedHashMap> dayTimeTable) { boolean mandatoryConditionsMet = true; if (group != null) { // System.out.println("Grupe idejimui: " + group.getGroupName()); List<Student> groupStudents = group.getStudents(); Collection<LinkedHashMap> teachersTimeTables = dayTimeTable.values(); // System.out.println("teachersTimeTables before if: " + teachersTimeTables); for (LinkedHashMap<String, String> teachersTimeTable : teachersTimeTables) { // System.out.println("Iskviete fore"); if (teachersTimeTable.isEmpty()) { mandatoryConditionsMet = true; continue; } // System.out.println("teachersTimeTable: " + teachersTimeTable); String groupNameToSplit = teachersTimeTable.get(String.valueOf(lectureNumber)); if (groupNameToSplit == null) { mandatoryConditionsMet = true; continue; } String[] splittedGroupNames = groupNameToSplit.split(":"); String groupName = splittedGroupNames[1].trim(); // System.out.println("Group name: " + groupName); Group groupToCheck = studentsMockDataFiller.getGroups().get(groupName); // System.out.println("groupToCheck: " + groupToCheck); boolean contains = true; if (StringUtils.equals(groupName, "-----")) { contains = false; } if (groupToCheck != null) { // System.out.println("Group to check: " + groupToCheck.getGroupName()); contains = CollectionUtils.containsAny(groupStudents, groupToCheck.getStudents()); // System.out.println("Contains: " + contains); } if (contains == false) { mandatoryConditionsMet = true; } else { mandatoryConditionsMet = false; return mandatoryConditionsMet; } } } else { mandatoryConditionsMet = false; } return mandatoryConditionsMet; }
7
public void paintComponent(Graphics g){ int x = this.getWidth(); int y = this.getHeight(); g.setColor(Color.GRAY); if(n==0) {g.setColor(Color.blue);} if(n==1) {g.setColor(Color.red);} if(n==2) {g.setColor(Color.green);} g.fillRect(0, 0, this.getWidth(), this.getHeight()); if(p>0){ g.setColor(Color.yellow); g.fillOval(x/2-x/16, y/8, x/8, x/8); g.fillRect(x/2-x/8, x/8+y/8, x/4,3*y/8 ); g.fillRect(x/2-x/8,x/8+y/8+3*y/8, x/12, y/4); g.fillRect(13*x/24,x/8+y/8+3*y/8, x/12, y/4); g.setColor(Color.blue); if(p==1){g.drawString("E", x/2-x/16, y/2+y/8);} if(p==2){g.drawString("V", x/2-x/16, y/2+y/8);} if(p==3){g.drawString("C", x/2-x/16, y/2+y/8);} if(p==4){g.drawString("L", x/2-x/16, y/2+y/8);} } }
8
public static int chooseFile() { Scanner in = new Scanner(System.in); String[] files = FileLister.getFilesArrayString(); FileLister.listFiles(files); System.out.println(">Enter a file number"); int selection = in.nextInt() - 1; return selection; }
0
public void buildClassifier(Instances instances) throws Exception { // can classifier handle the data? getCapabilities().testWithFail(instances); // remove instances with missing class instances = new Instances(instances); instances.deleteWithMissingClass(); double sumOfWeights = 0; m_Class = instances.classAttribute(); m_ClassValue = 0; switch (instances.classAttribute().type()) { case Attribute.NUMERIC: m_Counts = null; break; case Attribute.NOMINAL: m_Counts = new double [instances.numClasses()]; for (int i = 0; i < m_Counts.length; i++) { m_Counts[i] = 1; } sumOfWeights = instances.numClasses(); break; } Enumeration enu = instances.enumerateInstances(); while (enu.hasMoreElements()) { Instance instance = (Instance) enu.nextElement(); if (!instance.classIsMissing()) { if (instances.classAttribute().isNominal()) { m_Counts[(int)instance.classValue()] += instance.weight(); } else { m_ClassValue += instance.weight() * instance.classValue(); } sumOfWeights += instance.weight(); } } if (instances.classAttribute().isNumeric()) { if (Utils.gr(sumOfWeights, 0)) { m_ClassValue /= sumOfWeights; } } else { m_ClassValue = Utils.maxIndex(m_Counts); Utils.normalize(m_Counts, sumOfWeights); } }
8
public List<String> summaryRanges1(int[] nums) { List<String> result = new ArrayList<String>(); if(nums.length<1) return result; int start = nums[0]; int end = 0; int i = 0; while(i<=nums.length-1){ if(i+1 == nums.length || nums[i+1] != nums[i]+1 ){ end = nums[i]; if(end == start){ result.add(Integer.toString(start)); }else{ String s = Integer.toString(start) + "->" + Integer.toString(end); result.add(s); } if(i <nums.length-1) start = nums[i+1]; } i++; } return result; }
6
public String toString() { ToStringBuilder sb = new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE) .append("username", this.username) .append("enabled", this.enabled) .append("accountExpired", this.accountExpired) .append("credentialsExpired", this.credentialsExpired) .append("accountLocked", this.accountLocked); if (roles != null) { sb.append("Granted Authorities: "); int i = 0; for (Role role : roles) { if (i > 0) { sb.append(", "); } sb.append(role.toString()); i++; } } else { sb.append("No Granted Authorities"); } return sb.toString(); }
3
public int getAxisWidth(Graphics g) { int i; width = 0; if (minimum == maximum) return 0; if (dataset.size() == 0) return 0; calculateGridLabels(); exponent.setText(null); if (label_exponent != 0) { exponent.copyState(label); exponent.setText("x10^" + String.valueOf(label_exponent)); } if (orientation == HORIZONTAL) { width = label.getRHeight(g) + label.getLeading(g); width += Math.max(title.getRHeight(g), exponent.getRHeight(g)); } else { for (i = 0; i < label_string.length; i++) { label.setText(" " + label_string[i]); width = Math.max(label.getRWidth(g), width); } max_label_width = width; width = 0; if (!title.isNull()) { width = Math.max(width, title.getRWidth(g) + title.charWidth(g, ' ')); } if (!exponent.isNull()) { width = Math.max(width, exponent.getRWidth(g) + exponent.charWidth(g, ' ')); } width += max_label_width; } return width; }
7
Acceptor(TerminateSignaller terminateSignaller, ServerSocket serverSocket, ThreadModelType threadModelType, ExecutorService executorService, Serializer serializer, Class<T> serviceInterface, Class<V> serviceObjectClass, ThreadPoolOverflowPolicy threadPoolOverflowPolicy) throws ServerStartupException { this.terminateSignaller = terminateSignaller; this.serverSocket = serverSocket; this.executorService = executorService; this.serializer = serializer; this.serviceObjectClass = serviceObjectClass; this.reflectionCache = new ReflectionCache(serviceInterface); this.serviceObjectSingleton = null; this.threadModelType = threadModelType; this.threadPoolOverflowPolicy = threadPoolOverflowPolicy; switch (this.threadModelType) { case Singleton: try { serviceObjectSingleton = serviceObjectClass.newInstance(); } catch (InstantiationException e) { throw new ServerStartupException("Cannot create service object singleton instance!", e); } catch (IllegalAccessException e) { throw new ServerStartupException("Cannot create service object singleton instance!", e); } break; case InstancePerThread: serviceObjectSingleton = null; break; default: throw new ServerStartupException("Unknown threading model!"); } }
4
@Override public int getColumnCount() { return columnNames.length; }
0
public static boolean isGetter(Method method) { if(!method.getName().startsWith("get")) return false; if(method.getParameterTypes().length != 0) return false; if(void.class.equals(method.getReturnType())) return false; return true; }
3
private String postRequest(String URL, String request) throws IOException { HttpPost hp = new HttpPost(URL); //StringEntity ent = new StringEntity(request, "UTF-8"); StringEntity ent = new StringEntity(request, HTTP.UTF_8); hp.setEntity(ent); hp.addHeader("Authorization", "Basic " + authdata); if (sessionId != null) { hp.addHeader("X-Transmission-Session-Id", sessionId); } //HttpResponse response = httpclient.execute(targetHost, hp, localcontext); HttpResponse response = httpclient.execute(targetHost, hp); if (response.getStatusLine().getStatusCode() == 409) { EntityUtils.consume(response.getEntity()); //le kell záratni a korábbi kapcsolatot különben: //HIBA: Invalid use of BasicClientConnManager: connection still allocated. sessionId = response.getFirstHeader("X-Transmission-Session-Id").getValue(); hp.addHeader("X-Transmission-Session-Id", sessionId); //response = httpclient.execute(targetHost, hp, localcontext); response = httpclient.execute(targetHost, hp); } TGetResponse r = null; HttpEntity respEnt = response.getEntity(); StringBuilder sb = new StringBuilder(); if (respEnt != null) { String line; //Scanner sc = new Scanner(respent.getContent()).useDelimiter("\\A"); //BufferedReader reader = new BufferedReader(new InputStreamReader(respEnt.getContent())); BufferedReader reader = new BufferedReader(new InputStreamReader(respEnt.getContent(), "UTF-8")); while ((line = reader.readLine()) != null) { sb.append(line); } } return sb.toString(); }
4
private GenericConverter getRegisteredConverter(Class<?> sourceType, Class<?> targetType, Class<?> sourceCandidate, Class<?> targetCandidate) { ConvertersForPair convertersForPair = converters.get(new ConvertiblePair(sourceCandidate, targetCandidate)); return convertersForPair == null ? null : convertersForPair.getConverter(sourceType, targetType); }
5
public int process() { Stack<Character> stack=new Stack<Character>(); InputReader in=new InputReader(getClass().getResourceAsStream("/balexp.txt")); String line=in.readLine(); for(int i=0;i<line.length();i++) { char ch=line.charAt(i); switch(ch) { case '(': case '[': case '{':stack.push(ch); break; case ']': case '}': case ')':if(!stack.isEmpty()) { char top=stack.pop(); if(!doesMatch(top,ch)) return -1; break; } else { return -1; } default:break; } } return 0; }
9
public void executeLookupAction(String base, String sourceLocale, String targetLocale){ log("lookup in base \"" + base + "\" from locale \"" + sourceLocale + "\" to locale \"" + targetLocale + "\":"); log(); log("reading target word storage from disk..."); WordStorage sourceWordStorage = (WordStorage)WordStorage.loadFromFile(WordStorage.getFileName(base, sourceLocale)); if(sourceWordStorage == null) err("could not read target word storage!"); log("reading target word storage from disk..."); WordStorage targetWordStorage = (WordStorage)WordStorage.loadFromFile(WordStorage.getFileName(base, targetLocale)); if(targetWordStorage == null) err("could not read target word storage!"); log(); log("reading dictionary from disk..."); Dictionary dictionary = (Dictionary)Dictionary.loadFromFile(Dictionary.getFileName(base, sourceLocale, targetLocale)); if(dictionary == null) err("could not read dictionary data!"); log(); log("listening on stdin... (type words here)\n"); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s; try { while ((s = in.readLine()) != null && s.length() != 0){ lookup(s, sourceWordStorage, targetWordStorage, dictionary); log(); } } catch (IOException ex) { err("could not read from stdin!"); } log("lookup in base \"" + base + "\" from locale \"" + sourceLocale + "\" to locale \"" + targetLocale + "\" done."); }
6
public BadNetwork(Channel leftIn, Channel leftOut, Channel rightIn, Channel rightOut) { leftIn_ = leftIn; leftOut_ = leftOut; rightIn_ = rightIn; rightOut_ = rightOut; currentState = Status.NOMSG; /* Swing */ netLbl = new JLabel("Network"); netBtnFail = new JButton("Failure"); netBtnSuccess = new JButton("Success"); netBtnTimeout = new JButton("Timeout"); disableButtons(); add(netLbl); add(netBtnSuccess); add(netBtnFail); add(netBtnTimeout); netLbl.setAlignmentX(Component.CENTER_ALIGNMENT); netBtnFail.setAlignmentX(Component.CENTER_ALIGNMENT); netBtnSuccess.setAlignmentX(Component.CENTER_ALIGNMENT); netBtnTimeout.setAlignmentX(Component.CENTER_ALIGNMENT); setPreferredSize(Config.NET_SIZE); setLayout(new GridLayout(4,3)); //setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setBorder(BorderFactory.createMatteBorder(1, 2, 1, 1,Color.black)); /* The Java implementation has to keep track of "happens-before" events * in order to execute the correct sequence of events according to specific input events */ /* In the event that FAILURE occurs */ netBtnFail.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { disableButtons(); switch (currentState) { case MSGLEFT: leftOut_.send(new Message(Message.Type.FAILURE)); break; case MSGRIGHT: rightOut_.send(new Message(Message.Type.FAILURE)); break; } } catch (InterruptedException ie) {} } }); /* In the event that SUCCESS occurs */ netBtnSuccess.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { disableButtons(); switch (currentState) { case MSGLEFT: rightOut_.send(transitionLeftMsg); break; case MSGRIGHT: leftOut_.send(transitionRightMsg); break; } } catch (InterruptedException ie) {} } }); /* In the event that TIMEOUT occurs */ netBtnTimeout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { disableButtons(); switch (currentState) { case MSGLEFT: leftOut_.send(new Message(Message.Type.TIMEOUT)); break; case MSGRIGHT: rightOut_.send(new Message(Message.Type.TIMEOUT)); break; } } catch (InterruptedException ie) {} } }); }
9
private static void printCharacters(ArrayList<Character> characters) { Comparator<Character> chars = new Comparator<Character>() { // TODO compares Characters by level, strength and armour // note that this soln isn't quite correct, // find the bug and fix it @Override public int compare(Character char1, Character char2) { int retval = Integer.valueOf(char1.getLevel()).compareTo(char2.getLevel()); if (retval == 0) { retval = Integer.valueOf(char1.getStrength()).compareTo(char2.getStrength()); if (retval == 0) { retval = Integer.valueOf(char1.getArmour()).compareTo(char2.getArmour()); } } return retval; } }; Collections.sort(characters, chars); for (Character character : characters) { //TODO how do I print out the character's armour? System.out.println("Level: " + character.getLevel() + ", Strength " + character.getStrength() + ", Armour: " + character.getArmour() + ", Race: " + character.getRace()); } }
3
private boolean containsEnemyWool(TeamPlayer p, CTFTeam team) { Wool w = new Wool(this.GoalTeam.getColor()); //Check for wool for (ItemStack m : p.getPlayer().getInventory()) { //If item in inventory is wool if (m != null && m.getType().equals(Material.WOOL)) { System.out.println("Got some wool"); for (CTFTeam t: ((EditTeam)this.GoalTeam).session.getTeams()){ if (t.getColor().getWoolData() == m.getData().getData()){ t.resetFlag(); } } p.getPlayer().getInventory().remove(m); return true; } } return false; }
5
protected void calculateAverageContingencyMatrix() { // Initialize the matrix double[][] newMatrix = new double[super.classesNumber()][super.classesNumber()]; for(int i = 0; i < newMatrix.length; ++i) for(int j = 0; j < newMatrix[0].length; ++j) newMatrix[i][j] = 0.0; // Sum all the performances matrixes Iterator<PType> iter = this.performances.iterator(); while( iter.hasNext()) { PType perf = iter.next(); double[][] matrix = perf.getContingencyMatrix(); for(int i = 0; i < newMatrix.length; ++i) { String valI = super.indexToValue(i); for(int j = 0; j < newMatrix[0].length; ++j) newMatrix[i][j] += matrix[perf.valueToIndex(valI)][perf.valueToIndex(super.indexToValue(j))]; } } // Make the average for(int i = 0; i < newMatrix.length; ++i) for(int j = 0; j < newMatrix[0].length; ++j) newMatrix[i][j] /= this.performances.size(); super.setContingencyMatrix(newMatrix); this.contincencyMatrixSet = true; }
7
public String getShopUrl() { return shopUrl; }
0
protected static void createDescriptor() { try { InputStream descriptorStream = ResultParserParseControllerGenerated.class.getResourceAsStream(DESCRIPTOR); InputStream table = ResultParserParseControllerGenerated.class.getResourceAsStream(TABLE); boolean filesystem = false; if(descriptorStream == null && new File("./" + DESCRIPTOR).exists()) { descriptorStream = new FileInputStream("./" + DESCRIPTOR); filesystem = true; } if(table == null && new File("./" + TABLE).exists()) { table = new FileInputStream("./" + TABLE); filesystem = true; } if(descriptorStream == null) throw new BadDescriptorException("Could not load descriptor file from " + DESCRIPTOR + " (not found in plugin: " + getPluginLocation() + ")"); if(table == null) throw new BadDescriptorException("Could not load parse table from " + TABLE + " (not found in plugin: " + getPluginLocation() + ")"); descriptor = DescriptorFactory.load(descriptorStream, table, filesystem ? Path.fromPortableString("./") : null); descriptor.setAttachmentProvider(ResultParserParseControllerGenerated.class); } catch(BadDescriptorException exc) { notLoadingCause = exc; Environment.logException("Bad descriptor for " + LANGUAGE + " plugin", exc); throw new RuntimeException("Bad descriptor for " + LANGUAGE + " plugin", exc); } catch(IOException exc) { notLoadingCause = exc; Environment.logException("I/O problem loading descriptor for " + LANGUAGE + " plugin", exc); throw new RuntimeException("I/O problem loading descriptor for " + LANGUAGE + " plugin", exc); } }
9
@Override public int compare(StopRange arg0, StopRange arg1) { int stops1 = arg0.end - arg1.start; int stops2 = arg1.end - arg1.start; int rs = Integer.compare(stops1, stops2); if(rs == 0) { rs = Integer.compare(arg0.start, arg1.start); } return rs; }
1
public void update() { value = neighbours.size(); }
0
public boolean EliminarAfecta(Afecta p){ if (p!=null) { cx.Eliminar(p); return true; }else { return false; } }
1
public static int maxProfit(int[] prices) { int profit=0; if(prices.length <=0) return profit; int minPrice=prices[0]; for(int i=0;i<prices.length;i++){ profit=prices[i]-minPrice>profit?prices[i]-minPrice:profit; minPrice=prices[i]<minPrice?prices[i]:minPrice; } return profit; }
4
public void set(String seqStr) { if( seqStr == null ) { length = 0; nmer = 0; } else { nmer = 0; setLength(seqStr.length()); // Create binary sequence char seqChar[] = seqStr.toCharArray(); int i; for( i = 0; i < length; i++ ) rol(seqChar[i]); } }
2
public double value(StateObservation a_gameState) { boolean gameOver = a_gameState.isGameOver(); Types.WINNER win = a_gameState.getGameWinner(); double rawScore = a_gameState.getGameScore(); if(gameOver && win == Types.WINNER.PLAYER_LOSES) rawScore += HUGE_NEGATIVE; if(gameOver && win == Types.WINNER.PLAYER_WINS) rawScore += HUGE_POSITIVE; return rawScore; }
4
public ZElement chercheElement(int x, int y) { for (int i = zelements.size() - 1; i >= 0; i--) if (getElement(i).isSelected(x, y)) return getElement(i); return null; }
2
public void draw(int windowX, int windowY, int xStart, int yStart){ for (int x = 0; x < Standards.MAP_TILES_TO_DRAW; x++){ for (int y = 0; y < Standards.MAP_TILES_TO_DRAW; y++){ int cx = x + xStart; int cy = y + yStart; if (isOnMap(cx, cy)){ int drawX = x * Standards.TILE_SIZE; int drawY = y * Standards.TILE_SIZE; getTileAtCoords(cx, cy).draw(drawX, drawY); } } } }
3
public void notifyAdd(UpdateTag... tags) { if (updateExec == null || updateExec.done) { updateExec = new UpdateCall(); SwingUtilities.invokeLater(updateExec); } for (UpdateTag ut : tags) { if (!updateExec.mods.contains(ut)) updateExec.mods.add(ut); } }
4
@Override public String requestPro(HttpServletRequest request, HttpServletResponse response) throws Throwable { request.setCharacterEncoding("utf-8"); MultipartRequest multi = null; int sizeLimit = 10 * 1024 * 1024 ; @SuppressWarnings("deprecation") String savePath = request.getRealPath("/upload"); try{ multi=new MultipartRequest(request, savePath, sizeLimit, "utf-8", new DefaultFileRenamePolicy()); }catch (Exception e) { e.printStackTrace(); } String filename = multi.getFilesystemName("filename"); String title = multi.getParameter("title"); String writer = multi.getParameter("writer"); int count=0; String content = multi.getParameter("content"); String regip = request.getRemoteAddr(); if(title ==""||title==null) System.out.println("title is null"); if(writer==""||writer==null) System.out.println("writer is null"); if(content==""||content==null) System.out.println("content is null"); Board article = new Board(); article.setRegip(regip); article.setTitle(title); article.setWriter(writer); article.setContent(content); article.setCount(count); article.setFilename(filename); BoardDao.getInstance().insertArticle(article); return "insert.jsp"; }
7
@Override public String getName() { return NAME; }
0
public Base(HtmlMidNode parent, HtmlAttributeToken[] attrs){ super(parent, attrs); for(HtmlAttributeToken attr:attrs){ String v = attr.getAttrValue(); switch(attr.getAttrName()){ case "href": href = Href.parse(this, v); break; case "target": target = Target.parse(this, v); break; } } }
3
@Override protected void doAction(int option) { switch (option) { case 1: listAllSongs(); //lister alle sange op break; case 2: songSearch(); //søger en bestemt sang break; case 3: addSong(); //tilføjer en sang break; case 4: updateSong(); break; case 5: removeSong(); //fjerner en sang break; case 6: checkSongs(); break; case EXIT_VALUE: doActionExit(); } }
7
static public List<Class<?>> getMapTypes(String str_className, String str_fieldName) { List<Class<?>> lcla_types = new ArrayList<Class<?>>(); try { Class<?> lcl_class = Class.forName(str_className); Field lcl_f = lcl_class.getDeclaredField(str_fieldName); Type lcl_type = lcl_f.getGenericType(); if (lcl_type instanceof ParameterizedType) { ParameterizedType lcl_pType = (ParameterizedType) lcl_type; // Type lcl_rawType = lcl_pType.getRawType(); // Class lcl_argType = // (Class)lcl_pType.getActualTypeArguments()[0]; for (Type lcl_classT : lcl_pType.getActualTypeArguments()) { lcla_types.add((Class<?>) lcl_classT); } return lcla_types; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
8
private void moveToNextParam() { JTextComponent tc = ac.getTextComponent(); int dot = tc.getCaretPosition(); int tagCount = tags.size(); if (tagCount==0) { tc.setCaretPosition(maxPos.getOffset()); deactivate(); } Highlight currentNext = null; int pos = -1; List<Highlight> highlights = getParameterHighlights(); for (int i=0; i<highlights.size(); i++) { Highlight hl = highlights.get(i); // Check "< dot", not "<= dot" as OutlineHighlightPainter paints // starting at one char AFTER the highlight starts, to work around // Java issue. Thanks to Matthew Adereth! if (currentNext==null || currentNext.getStartOffset()</*=*/dot || (hl.getStartOffset()>dot && hl.getStartOffset()<=currentNext.getStartOffset())) { currentNext = hl; pos = i; } } // No params after caret - go to first one if (currentNext.getStartOffset()+1<=dot) { int nextIndex = getFirstHighlight(highlights); currentNext = highlights.get(nextIndex); pos = 0; } // "+1" is a workaround for Java Highlight issues. tc.setSelectionStart(currentNext.getStartOffset()+1); tc.setSelectionEnd(currentNext.getEndOffset()); updateToolTipText(pos); }
7
public SetDeck() { try { Gson g = new Gson(); URL url = new URL("http://128.199.235.83/icw/?q=icw/service/all_ic_of&user=624"); try { HashMap<String, ArrayList<Double>> temp = g.fromJson(new InputStreamReader(url.openStream()), HashMap.class ); ArrayList<Double> cardString = temp.get("data"); try { wallpaper2 = ImageIO.read(new File("wallpaper2.png")); } catch (IOException e1) { e1.printStackTrace(); } cardHolder = new CardHolder(CardHolder.DECK, false); deckHolder = new CardHolder(CardHolder.DECK, false); /* { public void paintComponent(Graphics g){ super.paintComponent(g); g.drawImage(wallpaper2, 0 , 0 ,this.getWidth(), this.getHeight(), this); } }; */ for(int i = 0; i < cardString.size(); i++) { cardHolder.add(new Card(cardString.get(i).intValue())); } url = new URL("http://128.199.235.83/icw/?q=icw/service/get_deck&user=624"); temp = g.fromJson(new InputStreamReader(url.openStream()), HashMap.class); ArrayList<Double> deckString = temp.get("data"); if(deckString != null) { for(int i = 0; i < deckString.size(); i++) { deckHolder.add(new Card(deckString.get(i).intValue())); } } DropHandler handler = new DropHandler(); DropTarget dropTarget = new DropTarget(cardHolder, DnDConstants.ACTION_MOVE, handler, true); cardHolder.setPreferredSize(new Dimension(328, 768)); cardHolder.setLayout(new WrapLayout(FlowLayout.LEFT, 5, 5)); deckHolder.setPreferredSize(new Dimension(328, 768)); deckHolder.setLayout(new WrapLayout(FlowLayout.LEFT, 5, 5)); this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); this.add(new JScrollPane(cardHolder)); this.add(new JScrollPane(deckHolder)); JButton submit = new JButton("Submit"); submit.setFont(new Font("Tahoma", Font.BOLD, 14)); submit.setForeground(Color.BLACK); submit.setBackground(Color.PINK); submit.setBounds(600,200,200,200 ); submit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub JButton b = (JButton) arg0.getSource(); JPanel panel = (JPanel) b.getParent(); SetDeck s = (SetDeck) panel.getParent(); Component [] c = s.deckHolder.getComponents(); int [] card = new int[c.length]; for(int i = 0; i < card.length; i++) { Card cd = (Card) c[i]; System.out.println(cd.getSize()); card[i] = cd.ic_id; } System.out.println(Arrays.toString(card)); try { String URLString = "http://128.199.235.83/icw/?q=icw/service/set_deck&user=624&pass=90408&deck="+Arrays.toString(card); URLString = URLString.replace(" ", ""); URL dest = new URL(URLString); InputStream is = dest.openStream(); // is = new URL(url).openStream(); Gson gs = new Gson(); JsonObject job = gs.fromJson(new InputStreamReader(is), JsonObject.class); System.out.println("STATUS: "+job.get("status").getAsInt()); System.out.println("MSG: "+job.get("msg").getAsString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); JPanel display = new JPanel(){ public void paintComponent(Graphics g){ super.paintComponent(g); g.drawImage(wallpaper2, 0 , 0 ,this.getWidth(), this.getHeight(), this); } }; display.setPreferredSize(new Dimension(400, 768)); display.add(submit); JButton back = new JButton("Back"); back.setFont(new Font("Tahoma", Font.BOLD, 14)); back.setForeground(Color.BLACK); back.setBackground(Color.PINK); back.setBounds(600,450,200,200 ); back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { MainMenu.setDeck.dispose(); Main.main.setVisible(true); } }); display.add(back); this.add(display); } catch (JsonSyntaxException | JsonIOException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
8
public void generateHorizontalCorridor(MapRegion room1, MapRegion room2, String[][] dungeon) { // Etäisyys lähekkäimpien seinien välillä int distance = room2.getX1() - room1.getX2(); // Valitaan alku- ja loppukoordinaatit siten, että polku ei koskaan kulje huoneen kulmasta int startY = Main.rand.nextInt(room1.getY2() - room1.getY1() - 2) + room1.getY1() + 1; int endY = Main.rand.nextInt(room2.getY2() - room2.getY1() - 2) + room2.getY1() + 1; int x = room1.getX2(), y = startY; // Kuljetaan ensin puoleen väliin vaakasuunnassa for(int i = 0; i < distance/2; i++) dungeon[x++][y] = "."; // Jos tarvii, siirrytään pystysuunnassa endY:n määrittämään y-koordinaattiin if (startY < endY) while (y != endY) dungeon[x][y++] = "."; else if (startY > endY) while (y != endY) dungeon[x][y--] = "."; // Siirrytään loppuun asti vaakasuunnassa while(x != room2.getX1()) dungeon[x++][y] = "."; }
6
private String pickMobSpawner(Random var1) { int var2 = var1.nextInt(4); return var2 == 0?"Skeleton":(var2 == 1?"Zombie":(var2 == 2?"Zombie":(var2 == 3?"Spider":""))); }
4
public Type getType() { return this.type; }
0
public boolean isStore(Chest chest){ if(chest==null) return false; return stores.containsKey(chest); }
1
public void remove(Object removedObject) { Object[] tempArray; int numberOfFindElements = 0; if (object == null||object.length==0) { throw new IllegalArgumentException( "There is no elements in Arraylist! Nothing could be deleted!"); } for (int i = 0; i < object.length; i++) { if (object[i].equals(removedObject)) { numberOfFindElements++; } } tempArray = new Object[object.length - numberOfFindElements]; for (int i = 0, j = 0; i < tempArray.length && j < object.length; j++) { if (object[j].equals(removedObject)) { continue; } tempArray[i] = object[j]; i++; } if (numberOfFindElements == 0) { System.out.println("No such elements!"); return; } object = tempArray; }
8
private String login(String username,String password,String randCode) throws IOException{ URL url = new URL("https://kyfw.12306.cn/otn/login/loginAysnSuggest?loginUserDTO.user_name="+username+"&userDTO.password="+password+"&randCode="+randCode); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setSSLSocketFactory(Utils.getSsf()); try { InputStream is = con.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8")); String res = br.readLine(); if(res==null)return null; String tmp = res.split("\"messages\":")[1]; String message = tmp.substring(0,tmp.lastIndexOf(",\"validateMessages\":")); if(message!=null && !message.equals("")){ return "0:"+message; } return getSessionId(con); } finally{ con.disconnect(); } }
3
@Override public void update(){ if(hitPoints <= 0) die(); super.update(); for(Shield shield : shields) shield.update(); }
2
public GridCell cell(int row, int col) { if (row < rows && col < cols) { if (row < 0 || col < 0) { return null; } return gridCells[row][col]; } return null; }
4
@Test public void shouldReturnAreaOfTenForTwoByFiveRectangle(){ Rectangle rectangle = new Rectangle(5, 2, 0, 0); assertEquals(10, rectangle.area()); }
0
* @param active Whether or not the active version of the color is needed. * @return The background color. */ public static Color getListBackground(boolean selected, boolean active) { if (selected) { Color color = UIManager.getColor("List.selectionBackground"); //$NON-NLS-1$ if (!active) { color = Colors.adjustSaturation(color, -0.5f); } return color; } return Color.WHITE; }
2
public static boolean ananlysisNJCM(AnalysisOutput o, List<AnalysisOutput> candidates) throws MorphException { int strlen = o.getStem().length(); boolean success = false; if(strlen>3&&(o.getStem().endsWith("에서이")||o.getStem().endsWith("부터이"))) { o.addElist(o.getStem().substring(strlen-1)); o.setJosa(o.getStem().substring(strlen-3,strlen-1)); o.setStem(o.getStem().substring(0,strlen-3)); success = true; }else if(strlen>5&&(o.getStem().endsWith("에서부터이"))) { o.addElist(o.getStem().substring(strlen-1)); o.setJosa(o.getStem().substring(strlen-5,strlen-1)); o.setStem(o.getStem().substring(0,strlen-5)); success = true; } if(!success) return false; WordEntry entry = null; if(success&&(entry=DictionaryUtil.getAllNoun(o.getStem()))!=null) { if(entry.getFeature(WordEntry.IDX_NOUN)=='2') { o.setCNoun(entry.getCompounds()); } o.setScore(AnalysisOutput.SCORE_CORRECT); } o.setPatn(PatternConstants.PTN_NJCM); o.setPos(PatternConstants.POS_NOUN); candidates.add(o); return true; }
9
public void removePreviousGlied() { SchlangenGlied oldPreviousGlied = previousGlied; previousGlied = null; if (oldPreviousGlied != null) { previousGlied.removeNextGlied(); } }
1
private void escribirTeam(Piloto pilot) { int lectura = 0; String cadenainicio = ""; String cadenamedio = ""; String cadenafinal = ""; String nuevoarchivo = ""; Scanner s; try { s = new Scanner(pilot.getFile()); while (s.hasNext()) { String texto = s.nextLine(); if (texto.contains("Number")) { lectura = 1; } else { if (lectura == 0) { cadenainicio = cadenainicio.concat(texto + '\n'); } } if (texto.contains("Engine")) { lectura = 2; } if (lectura == 2) { cadenafinal = cadenafinal.concat(texto + '\n'); } } s.close(); cadenamedio = ("Number=" + pilot.getNumber() + '\n' + "Team=" + "\"" + pilot.getTeam() + "\"" + '\n' + "PitGroup=" + "\"" + pilot.getPitgroup() + "\"" + '\n' + "Driver=" + "\"" + pilot.getName() + "\"" + '\n' + "Description=" + "\"" + pilot.getNumber() + "-" + pilot.getName() + "\"" + '\n'); nuevoarchivo = pilot.getFile().getPath(); pilot.getFile().delete(); Escribrlineas(cadenainicio, nuevoarchivo); Escribrlineas(cadenamedio, nuevoarchivo); Escribrlineas(cadenafinal, nuevoarchivo); } catch (Exception e) { ImageIcon icon = new ImageIcon(getClass().getResource("Elementos/Imagenes/PitStopErrorIcon.png")); JOptionPane.showMessageDialog(null, "Error Archivo no encontrado", "Editar Equipo - ERROR AL ESCRIBIR", JOptionPane.ERROR_MESSAGE, icon); } }
6
@Override public int observed(String sequence) { char seq[] = sequence.toUpperCase().toCharArray(); int cpg = 0; for( int pos = 0; pos < (seq.length - 1); pos++ ) if( (seq[pos] == 'C') && (seq[pos + 1] == 'G') ) cpg++; return cpg; }
3
@Override public UserDTO getUserByLogin(String login, String pass) throws SQLException { Session session = null; UserDTO user = null; try { session = HibernateUtil.getSessionFactory().openSession(); user = (UserDTO) session.createCriteria(UserDTO.class) .add(Restrictions.and( Restrictions.like("login", login), Restrictions.like("pass", pass) )) .setMaxResults(1).uniqueResult(); } catch (Exception e) { System.err.println("Error while getting user by login and password!"); } finally { if (session != null && session.isOpen()) { session.close(); } } return user; }
3
@Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String data; try { if (request.getParameter("id") == null) { data = "{\"error\":\"id is mandatory\"}"; } else { ClienteDao_Mysql oClienteDAO = new ClienteDao_Mysql(Conexion.getConection()); ClienteBean oCliente = new ClienteBean(); oCliente.setId(Integer.parseInt(request.getParameter("id"))); oClienteDAO.get(oCliente); data = new Gson().toJson(oCliente); } return data; } catch (Exception e) { throw new ServletException("ClienteGetJson: View Error: " + e.getMessage()); } }
2
@Override public void execute(CommandSender sender, String[] arg1) { if (!CommandUtil.hasPermission(sender, PERMISSION_NODES)) { sender.sendMessage(plugin.NO_PERMISSION); return; } if (arg1.length < 1) { sender.sendMessage(ChatColor.RED + "/" + plugin.setWarp + " (name) [private]"); return; } String name = arg1[0]; // sends plugin message to BungeeSuiteBukkit to get player pos ProxiedPlayer player = (ProxiedPlayer) sender; ByteArrayOutputStream b = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(b); try { out.writeUTF("SetWarp"); out.writeUTF(sender.getName()); out.writeUTF(name); } catch (IOException e) { e.printStackTrace(); } if (arg1.length > 1 && arg1[1].equalsIgnoreCase("private")) { try { out.writeBoolean(false); } catch (IOException e) { e.printStackTrace(); } } else { try { out.writeBoolean(true); } catch (IOException e) { e.printStackTrace(); } } player.getServer().sendData("BungeeSuiteMC", b.toByteArray()); }
7
public boolean load(String audiofile) { try { setFilename(audiofile); sample = AudioSystem.getAudioInputStream(getURL(filename)); clip.open(sample); return true; } catch (IOException e) { return false; } catch (UnsupportedAudioFileException e) { return false; } catch (LineUnavailableException e) { return false; } }
3
@Override public void processEvent(Event event) { if(event.getHeader().getEventType().equals(LogEventType.ROTATE)) { try{ processRotateEvent(event); } catch (SQLException ex) { } } else if(event.getData() instanceof RowsIEventData) { if(EoiContext.isEoi(((RowsIEventData) event.getData()).getTableId())) { processRowEvent(event); } } else if(event.getHeader().getEventType().equals(LogEventType.TABLE_MAP)) { processTableMapEvent(event); } }
5
public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } }
9
public JsonObject toJSON() { JsonObject obj = new JsonObject(); Gson gson = new Gson(); obj.addProperty("title", title); obj.addProperty("project", project); // Add contributors for(String key: contributors.keySet()) { if(!contributors.get(key).isEmpty()) obj.add(key, gson.toJsonTree(contributors.get(key))); } JsonArray jsonPages = new JsonArray(); obj.add("pages", jsonPages); for(Page page: pages) { jsonPages.add(page.toJSON()); } JsonArray jsonImages = new JsonArray(); obj.add("images", jsonImages); for(Image image: images) { jsonImages.add(image.toJSON()); } return obj; }
4
private void initView() { super.setLayout(new BorderLayout()); initGrammarTable(); JPanel rightPanel = initRightPanel(); JSplitPane mainSplit = SplitPaneFactory.createSplit(environment, true, 0.4, new JScrollPane(grammarTable), rightPanel); add(mainSplit, BorderLayout.CENTER); }
0
public static List<Actor> getActors(String urlString) throws TvDbException { List<Actor> results = new ArrayList<>(); Actor actor; Document doc; NodeList nlActor; Node nActor; Element eActor; try { doc = DOMHelper.getEventDocFromUrl(urlString); if (doc == null) { return results; } } catch (WebServiceException ex) { LOG.trace(ERROR_GET_XML, ex); return results; } nlActor = doc.getElementsByTagName("Actor"); for (int loop = 0; loop < nlActor.getLength(); loop++) { nActor = nlActor.item(loop); if (nActor.getNodeType() == Node.ELEMENT_NODE) { eActor = (Element) nActor; actor = new Actor(); actor.setId(DOMHelper.getValueFromElement(eActor, "id")); String image = DOMHelper.getValueFromElement(eActor, "Image"); if (!image.isEmpty()) { actor.setImage(URL_BANNER + image); } actor.setName(DOMHelper.getValueFromElement(eActor, "Name")); actor.setRole(DOMHelper.getValueFromElement(eActor, "Role")); actor.setSortOrder(DOMHelper.getValueFromElement(eActor, "SortOrder")); results.add(actor); } } Collections.sort(results); return results; }
5
public static String createPath(String folderName, String fileName) { return folderName + System.getProperties().getProperty("file.separator") + fileName; }
0
private void removeDataNode(DFSNode dataNode){ ///// System.out.println("dataNode is " + dataNode.getIp() + ":" + dataNode.getPort()); ///// for(DFSBlkDataNode dbdn : this.dataNodes){ if(dbdn.getIp().equals(dataNode.getIp()) && dbdn.getPort() == dataNode.getPort()){ this.dataNodes.remove(dbdn); break; } } for(String s : this.blkName2dataNodesMap.keySet()){ List<DFSNode> blkDataNodes = this.blkName2dataNodesMap.get(s); for(DFSNode dn : blkDataNodes){ if(dn.getIp().equals(dataNode.getIp()) && dn.getPort() == dataNode.getPort()){ blkDataNodes.remove(dn); /* Copy the block originally on dataNode to other DataNode */ DFSNode newDataNode = this.assignLocation(s); DFSNode srcDataNode = this.assignSource(s); List<DFSNode> destAndSrc = new ArrayList<DFSNode>(2); destAndSrc.add(newDataNode); destAndSrc.add(srcDataNode); DFSMessage copyBlkNameNodeReq = new DFSMessage(DFSMessageType.CopyBlkNameNodeReqMsg, s, destAndSrc); DFSMessage copyBlkDataNodeResp = DFSMessageSender.sendMessage(copyBlkNameNodeReq, newDataNode); if(copyBlkDataNodeResp == null || copyBlkDataNodeResp.getType() != DFSMessageType.CopyBlkDataNodeRespMsg){ System.out.println("Failed to send Copy-Block-Request (Block: " + s + ") to DataNode (" + newDataNode.getIp() + ":" + newDataNode.getPort() + ")"); }else{ System.out.println("Sent Copy-Block-Request (Block: " + s + ") to DataNode (" + newDataNode.getIp() + ":" + newDataNode.getPort() + ")"); } break; } } } return; }
9
public float getK() { return k; }
0