method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
791788f4-b7f8-4ee3-b37f-f3da66f58860
9
@Override public boolean isBuffered() { //if(gcode==null) return false; if (Constants.GCDEF.G0.equals(gcode) || Constants.GCDEF.G1.equals(gcode) || Constants.GCDEF.G2.equals(gcode) || Constants.GCDEF.M106.equals(gcode) || Constants.GCDEF.M107.equals(gcode) ||Constants.GCDEF.G29.equals(gcode) || Constants.GCDEF.G30.equals(gcode) || Constants.GCDEF.G31.equals(gcode) || Constants.GCDEF.G32.equals(gcode)){ return true; } return false; }
17a9fc56-a65e-4850-8d11-481f5e6525b0
9
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (args.length == 0) { if (player == null) { sender.sendMessage(ChatColor.RED+"This command can only be run by a player"); return true; } player.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, 1200, 3)); sender.sendMessage(ChatColor.GOLD + "* " + ChatColor.WHITE + "You have been given Fire Resist for " + ChatColor.GREEN + "1" + ChatColor.WHITE + " minute"); return true; } else if (args.length == 1) { Player target = Bukkit.getPlayer(args[0]); if (target == null) { sender.sendMessage(ChatColor.RED + args[0] + " is not online"); return true; } target.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, 1200, 3)); sender.sendMessage(ChatColor.GREEN + "" + target.getDisplayName() + ChatColor.WHITE + " has been given Fire Resistance for " + ChatColor.GREEN + "1" + ChatColor.WHITE + " minute"); target.sendMessage(ChatColor.GOLD + "* " + ChatColor.WHITE + "You have been given Fire Resist for " + ChatColor.GREEN + "1" + ChatColor.WHITE + " minute"); return true; } else if (args.length == 2 && player == null || player.hasPermission("simpleextras.fireresist.other")) { Player target = Bukkit.getPlayer(args[0]); // CHECK IF TARGET EXISTS if (target == null) { sender.sendMessage(ChatColor.RED + args[0] + " is not online"); return true; } String min = args[1]; int mintemp = Integer.parseInt( min ); int mins = 1200 * mintemp; target.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, mins, 3)); sender.sendMessage(ChatColor.GREEN + "" + target.getDisplayName() + ChatColor.WHITE + " has been given Fire Resistance for " + ChatColor.GREEN + min + ChatColor.WHITE + " minutes"); target.sendMessage(ChatColor.GOLD + "* " + ChatColor.WHITE + "You have been given Fire Resist for " + ChatColor.GREEN + min + ChatColor.WHITE + " minutes"); return true; } return true; }
40beffd7-82ca-4ee1-9bc6-9011daf697c7
8
public void run(){ try { while(true){ Thread.sleep(1000); //TEST STUB: change to 1000 synchronized(this.doc){ //Decrement all active game times by 1 second: NodeList activeList = this.doc.getElementsByTagName("games_active"); if(((Element)activeList.item(0)).getChildNodes() == null){ continue; } NodeList gamesList = ((Element)activeList.item(0)).getElementsByTagName("game"); for(int i=0; i<gamesList.getLength(); i++){ Node gameNode = (Node)gamesList.item(i); String sTime = gameNode.getAttributes().getNamedItem("remaining_time").getNodeValue(); int nMinutes = Integer.parseInt(sTime.substring(0, sTime.indexOf(":"))); int nSeconds = Integer.parseInt(sTime.substring(sTime.indexOf(":") + 1)); //If time is zero, move the game node to the games history node: //If time is non-zero, subtract 1 second from the time: if(nMinutes > 0 || nSeconds > 0){ nSeconds -= 1; if(nSeconds < 0){ nSeconds = 59; nMinutes -= 1; } gameNode.getAttributes().getNamedItem("remaining_time").setNodeValue(nMinutes + ":" + nSeconds); } else{ //move to games_history Node gamesHistoryNode = doc.getElementsByTagName("games_history").item(0); if(gamesHistoryNode.getChildNodes().getLength() == 0){ gamesHistoryNode.appendChild(gameNode); } else{ gamesHistoryNode.insertBefore(gameNode, gamesHistoryNode.getFirstChild()); } } //Write all the changes to the XML file and update the display: Server.writeToXML(); } } } } catch (InterruptedException e) { e.printStackTrace(); } }
a87fb7dc-57b3-4b34-8564-e8ed8838d3cf
4
protected boolean decodeFrame() throws JavaLayerException { try { AudioDevice out = audio; if (out==null) return false; Header h = bitstream.readFrame(); if (h==null) return false; // sample buffer set when decoder constructed SampleBuffer output = (SampleBuffer)decoder.decodeFrame(h, bitstream); synchronized (this) { out = audio; if (out!=null) { out.write(output.getBuffer(), 0, output.getBufferLength()); } } bitstream.closeFrame(); } catch (RuntimeException ex) { throw new JavaLayerException("Exception decoding audio frame", ex); } /* catch (IOException ex) { System.out.println("exception decoding audio frame: "+ex); return false; } catch (BitstreamException bitex) { System.out.println("exception decoding audio frame: "+bitex); return false; } catch (DecoderException decex) { System.out.println("exception decoding audio frame: "+decex); return false; } */ return true; }
f7809868-6184-4f47-b56b-33987cc0dd4e
8
public void verify(String expected, Flag... flags) { List<String> lines = component.out.reset(); while (lines.isEmpty()) { lines = component.out.reset(); } if (contains(Flag.LAST, (Object[]) flags)) { lines = Collections.singletonList(lines.isEmpty() ? "" : lines.get(lines.size() - 1)); } String actual = join("\n", lines); Matcher<String> matcher; if (contains(Flag.REGEX, (Object[]) flags)) { matcher = new PatternMatcher(expected); } else { matcher = CoreMatchers.containsString(expected.toLowerCase()); actual = actual.toLowerCase(); } String msg = String.format("String must %s%s '%s' but was:%s", contains(Flag.NOT, (Object[]) flags) ? "NOT " : "", contains(Flag.REGEX, (Object[]) flags) ? "match pattern" : "contain", expected, lines.size() > 1 ? "\n" + actual : String.format(" '%s'", actual)); matcher = contains(Flag.NOT, (Object[]) flags) ? CoreMatchers.not(matcher) : matcher; assertThat(msg, actual, matcher); }
3b0a6d6b-5a35-486c-bf65-4ebaeecbe4e7
3
private boolean isPrime(int n) { boolean result = true; // assume true and try to prove otherwise int i=2; while ((i<n) && (result == true)) { if ((n%i) == 0) { result = false; } i++; } return result; }
2e2d9701-0b8b-463d-82a9-ffd2660f831d
9
void outerHtmlTail(StringBuilder accum, int depth, Document.OutputSettings out) { if (!(childNodes.isEmpty() && tag.isSelfClosing())) { if (out.prettyPrint() && (!childNodes.isEmpty() && ( tag.formatAsBlock() || (out.outline() && (childNodes.size()>1 || (childNodes.size()==1 && !(childNodes.get(0) instanceof TextNode)))) ))) indent(accum, depth, out); accum.append("</").append(tagName()).append(">"); } }
32280eb0-b3d2-4473-bf36-86156504447a
2
public T findOneByField(String campo, String condicao, String valor) { T result = null; try { Query query = manager.createQuery("select x from " + entityClass.getSimpleName() + " x " + "where x." + campo + " " + condicao + ":value"); query.setParameter(campo, valor); result = (T) query.getSingleResult(); } catch (NoResultException e) { // TODO trocar isso aqui para log System.out.println("No result found"); } catch (Exception e) { // TODO trocar isso aqui para log System.out.println("Error while running query: " + e.getMessage()); e.printStackTrace(); } return result; }
32f4164d-8eb2-49a0-b619-dc900e0aa28b
3
public static void start(){ List<String> mapsToExclude = new ArrayList<String>(); mapsToExclude.add(previousMapName); final Map mA = MapData.getRandomMapExcluding(mapsToExclude); mapsToExclude.add(mA.getName()); final Map mB = MapData.getRandomMapExcluding(mapsToExclude); mapsToExclude.add(mB.getName()); final Map mR = MapData.getRandomMapExcluding(mapsToExclude); Vote.open(mA.getName(), mA.getGameType(), mB.getName(), mB.getGameType()); Vote.broadcastVoteReadout(30); Vote.updatePlayerReadout(); RealmsMain.setServerMode(ServerMode.VOTE); SchedulerManager.registerSingle(10, new Runnable(){ public void run(){ Vote.broadcastVoteReadout(20); } }); SchedulerManager.registerSingle(20, new Runnable(){ public void run(){ Vote.broadcastVoteReadout(10); } }); SchedulerManager.registerSingle(30, new Runnable(){ public void run(){ VoteCast vote = Vote.closePolls(); if(vote == VoteCast.A) next = mA; else if(vote == VoteCast.B) next = mB; else next = mR; Broadcast.vote("The vote is in!"); Broadcast.vote("Next game is " + ChatColor.DARK_RED + next.getGameType().getFullName() + ChatColor.RED + " on " + ChatColor.DARK_RED + next.getName()); Broadcast.general("The next game will start in 20 seconds."); Broadcast.general("Don't forget to pick a class and team!"); RealmsMain.setActiveMap(next); previousMapName = next.getName(); RealmsMain.setServerMode(ServerMode.POSTVOTE); } }); SchedulerManager.registerSingle(50, new Runnable(){ public void run(){ previousMapName = next.getName(); GameMode mode = next.getGameType().getMethods(); mode.startSchedules(); RealmsMain.setServerMode(ServerMode.GAME); for(Player p : Bukkit.getOnlinePlayers()){ mode.spawn(p); } } }); }
1c5fe542-f73b-43e0-8ce1-945c1fb9df4c
6
private boolean compare(Block testBlock, int row, int column, int rowOffset, int columnOffset) { for(int i = 0; i < BLOCK_SIZE; i++) { for(int j = 0; j < BLOCK_SIZE; j++) { try { if (testBlock.getValue(i, j) == ACTIVE_BLOCK) { if(gameBoard[i + row + rowOffset][j + column + columnOffset] == INACTIVE_BLOCK || gameBoard[i + row + rowOffset][j + column + columnOffset] == BORDER) { return false; } } } // Null pointer exception catch(Exception e) { System.out.println(e); } } } return true; }
af5f5d68-3ce6-442f-b4c9-eafe6f5def95
1
public static Facade getFacade(boolean reset) { if (true) { instance = new Facade(); } return instance; }
c1bb87d9-81b2-44d3-a7ac-bbd785cf3566
4
public static void main(String args[]) { try{ ServerSocket server=null; try{ server=new ServerSocket(6888); //创建一个ServerSocket在端口6888监听客户请求 }catch(Exception e) { System.out.println("can not listen to:"+e); //出错,打印出错信息 } Socket socket=null; try{ socket=server.accept(); //使用accept()阻塞等待客户请求,有客户 //请求到来则产生一个Socket对象,并继续执行 }catch(Exception e) { System.out.println("Error."+e); //出错,打印出错信息 } String line; BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream())); //由Socket对象得到输入流,并构造相应的BufferedReader对象 PrintWriter os=new PrintWriter(socket.getOutputStream()); //由Socket对象得到输出流,并构造PrintWriter对象 BufferedReader sin=new BufferedReader(new InputStreamReader(System.in)); //由系统标准输入设备构造BufferedReader对象 System.out.println("Client:"+is.readLine()); //在标准输出上打印从客户端读入的字符串 line=sin.readLine(); //从标准输入读入一字符串 while(!line.equals("bye")){ //如果该字符串为 "bye",则停止循环 os.println(line); //向客户端输出该字符串 os.flush(); //刷新输出流,使Client马上收到该字符串 System.out.println("Server:"+line); //在系统标准输出上打印读入的字符串 System.out.println("Client:"+is.readLine()); //从Client读入一字符串,并打印到标准输出上 line=sin.readLine(); //从系统标准输入读入一字符串 } //继续循环 os.close(); //关闭Socket输出流 is.close(); //关闭Socket输入流 socket.close(); //关闭Socket server.close(); //关闭ServerSocket }catch(Exception e){ System.out.println("Error:"+e); //出错,打印出错信息 } }
59995e30-53ef-44a7-a18e-2c77b31baa40
1
public static String wrapVariableBinding(String command, CycSymbol variable, Object value) { try { // @todo consider setting *ke-purpose* return "(clet ((" + DefaultCycObject.cyclifyWithEscapeChars(variable, true) + " " + getAPIString(value) + ")) " + command + ")"; } catch (Exception e) { return command; } }
e49a8a15-c529-4b97-b1f0-aae243bc4807
8
private boolean checkBorders() { boolean check = false; int width = gameInst.container.getWidth(); int height = gameInst.container.getHeight(); if (location[0] >= width) { check = true; if (velocity[0] > 0) velocity[0] *= -.5f; } if (location[0] <= 0) { check = true; if (velocity[0] < 0) velocity[0] *= -.5f; } if (location[1] >= height) { check = true; if (velocity[1] > 0) velocity[1] *= -.5f; } if (location[1] <= 0) { check = true; if (velocity[1] < 0) velocity[1] *= -.5f; } return check; }
fb8be363-471f-42a0-b0d3-d4e094f50fdd
1
private void printCell(String s) { System.out.print(s); for (int i = s.length(); i <= 16; i++) { System.out.print(" "); } }
9a59dac7-6edb-46ba-a31f-bf7574ea57d1
5
@BeforeClass public static void setUpBeforeClass() { try { new MySQLConnection(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
5241b3a6-42ca-4c00-9615-ff30247b2bfd
7
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); int writtenKeyCount = keyCount; if (writtenKeyCount != 0) { keyCount = 0; boolean hasIntValues = in.readBoolean(); boolean hasObjectValues = in.readBoolean(); int N = 1 << power; if (hasIntValues) { keys = new int[2 * N]; ivaluesShift = N; }else { keys = new int[N]; } for (int i = 0; i != N; ++i) { keys[i] = EMPTY; } if (hasObjectValues) { values = new Object[N]; } for (int i = 0; i != writtenKeyCount; ++i) { int key = in.readInt(); int index = insertNewKey(key); if (hasIntValues) { int ivalue = in.readInt(); keys[ivaluesShift + index] = ivalue; } if (hasObjectValues) { values[index] = in.readObject(); } } } }
096b8848-47d5-425f-b296-f612d5fbc14d
7
public static boolean tryRepairingSomethingIfNeeded(Unit worker) { // If we're out of minerals, don't repair if (!xvr.canAfford(10)) { return false; } // Disallow wounded workers to repair; this way we can save many lives if (worker.getHP() < 45) { return false; } // ========================================================= Unit repairThisUnit = RepairAndSons.getUnitAssignedToRepairBy(worker); // This worker has assigned unit to repair if (repairThisUnit != null) { // If unit is damaged and it still exists, try repairing it. if (repairThisUnit.isWounded() && repairThisUnit.isExists()) { // Don't repair Vultures that are far away. They must come to // the worker. It's because they tend to be wounded all the time // and this way SCV gets killed too often. if (repairThisUnit.getType().isVulture() && repairThisUnit.distanceTo(worker) >= 7) { return false; } else { UnitActions.repair(worker, repairThisUnit); return true; } } // This repair order is obsolete, remove it. else { RepairAndSons.removeTicketFor(repairThisUnit, worker); } } // // No units assigned to repait, but check if there're some crucial // units // // to repair like e.g. tanks // else { // tryExtraRepairingTank(worker); // } return false; }
36c67d06-a109-4561-a971-c92a57b70b21
1
public static Balancer getInstance() { if (balancer == null) { balancer = new Balancer(); } return balancer; }
07bd1dc3-1961-4b0a-90fb-bff1f1057d90
0
public Piece[] getSuivantes() { return suivantes; }
95079902-ff93-4bad-a3ec-1a7aed38bc34
1
public List<ExtensionsType> getExtensions() { if (extensions == null) { extensions = new ArrayList<ExtensionsType>(); } return this.extensions; }
0465b557-7abe-4262-9d47-857d6a74e9c8
4
private void initilizeComponents (){ //Create User Options Panel userOptionsPanel = new JPanel(); userOptionsPanel.setLayout(new GridLayout(15,2)); userOptionsPanel.setBorder(BorderFactory.createEtchedBorder()); //Create Bottom Buttons bottomButtons = new JPanel(); bottomButtons.setLayout(new FlowLayout()); //Center print out of carpark log carParkLogData = new JTextArea(); carParkLogData.setAutoscrolls(true); carParkLogData.setBorder(BorderFactory.createEtchedBorder()); logScroll = new JScrollPane(carParkLogData); //Right print out of final status? carParkSummary = new JTextArea(); carParkSummary.setAutoscrolls(true); carParkSummary.setBorder(BorderFactory.createEtchedBorder()); carParkSummary.setLineWrap(true); summaryScroll = new JScrollPane(carParkSummary); //Top Panel with headings topHeadings = new JPanel(); topHeadings.setLayout(new GridLayout()); carParkLog = new JLabel("Car Park Log"); summary = new JLabel("Car Park Summary"); //Top User Options VARIABLES userOptions = new JLabel("User Data Entry Options"); variables = new JLabel ("Variables"); default_max_car_spaces = new JTextField(); default_max_car_spaces.setText(Integer.toString(maxCarSpaces)); max_car_spaces = new JLabel("Max Car Spaces"); default_max_small_car_spaces = new JTextField(); default_max_small_car_spaces.setText(Integer.toString(maxSmallSpaces)); max_small_car_spaces = new JLabel ("Max Small Car Spaces"); default_max_motorcycle_spaces = new JTextField(); default_max_motorcycle_spaces.setText(Integer.toString(maxBikeSpaces)); max_motorcycle_spaces = new JLabel("Max Motorcycle Spaces"); default_max_queue_size = new JTextField(); default_max_queue_size.setText(Integer.toString(maxQueue)); max_queue_size = new JLabel ("Max Queue Size"); //User Options PROBABILITY probabilities = new JLabel ("Probabilities"); default_seed = new JTextField(); default_seed.setText(Integer.toString(seed)); probabilitySeed = new JLabel("Seed"); default_car_prob = new JTextField(); default_car_prob.setText(Double.toString(carProb)); car_prob = new JLabel ("Car Probibility"); default_small_car_prob = new JTextField(); default_small_car_prob.setText(Double.toString(smallCarProb)); small_car_prob = new JLabel("Small Car Probibility"); default_motorcycle_prob = new JTextField(); default_motorcycle_prob.setText(Double.toString(bikeProb)); motorcycle_prob = new JLabel ("Motorcycle Probibility"); default_intended_stay_mean = new JTextField(); default_intended_stay_mean.setText(Double.toString(stayMean)); intended_stay_mean = new JLabel("Intended Stay Mean"); default_intended_stay_sd = new JTextField(); default_intended_stay_sd.setText(Double.toString(staySD)); intended_stay_sd = new JLabel ("Intended Stay SD"); //Add Everything to User Options Panel userOptionsPanel.add(variables); userOptionsPanel.add(blank3); userOptionsPanel.add(max_car_spaces); userOptionsPanel.add(default_max_car_spaces); userOptionsPanel.add(max_small_car_spaces); userOptionsPanel.add(default_max_small_car_spaces); userOptionsPanel.add(max_motorcycle_spaces); userOptionsPanel.add(default_max_motorcycle_spaces); userOptionsPanel.add(max_queue_size); userOptionsPanel.add(default_max_queue_size); userOptionsPanel.add(probabilities); userOptionsPanel.add(blank2); userOptionsPanel.add(probabilitySeed); userOptionsPanel.add(default_seed); userOptionsPanel.add(car_prob); userOptionsPanel.add(default_car_prob); userOptionsPanel.add(small_car_prob); userOptionsPanel.add(default_small_car_prob); userOptionsPanel.add(motorcycle_prob); userOptionsPanel.add(default_motorcycle_prob); userOptionsPanel.add(intended_stay_mean); userOptionsPanel.add(default_intended_stay_mean); userOptionsPanel.add(intended_stay_sd); userOptionsPanel.add(default_intended_stay_sd); //Add Headings to the top panel topHeadings.add(userOptions); topHeadings.add(carParkLog); topHeadings.add(summary); //Create Buttons with ActionListeners run = new JButton("Run"); run.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { try{ gatherUserEnteredVariables(); //Need to create brand new variables so SimulationRunner //has new data each time. carPark = new CarPark(maxCarSpaces,maxSmallSpaces,maxBikeSpaces,maxQueue); log = new Log(); sim = new Simulator(seed,stayMean,staySD,carProb,smallCarProb,bikeProb); sr = new SimulationRunner (carPark,sim,log); chartData.clear(); sr.runSimulation(); timeChart.setEnabled(true); barChart.setEnabled(true); fillGUIText(chartData); } catch (IOException ioe){ System.out.printf("There was a problem running the program.\n" + "Details are:%s\n", ioe); } catch (SimulationException se){ System.out.printf("There was a problem running the program.\n" + "Details are: %s\n", se); } catch (VehicleException ve){ System.out.printf("There was a problem running the program.\n" + "Details are: %s\n", ve); } catch (NumberFormatException nfe){ System.out.printf("There was a problem running the program.\n" + "Details are: %s\n", nfe); } } }); timeChart = new JButton("Time Series Chart"); timeChart.setEnabled(false); timeChart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { ChartPanel chartWindow = new ChartPanel("Time Series Chart", chartData, false); chartWindow.getChartDialog().pack(); RefineryUtilities.centerFrameOnScreen(chartWindow); chartWindow.getChartDialog().repaint(); chartWindow.getChartDialog().setVisible(true); } }); barChart = new JButton ("Bar Chart Summary"); barChart.setEnabled(false); barChart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { ChartPanel chartWindow = new ChartPanel("Bar Chart Summary", chartData, true); chartWindow.getChartDialog().pack(); RefineryUtilities.centerFrameOnScreen(chartWindow); chartWindow.getChartDialog().repaint(); chartWindow.getChartDialog().setVisible(true); } }); exit = new JButton ("Exit"); exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); //Add Buttons to button panel bottomButtons.add(run); bottomButtons.add(timeChart); bottomButtons.add (barChart); bottomButtons.add(exit); //Adds the three main panels to a central panel to help display allComponents.add(userOptionsPanel); allComponents.add(logScroll); allComponents.add(summaryScroll); //Add the final 2 panels plus the central panel to the GUIPANEL this.add(topHeadings,BorderLayout.PAGE_START); this.add(allComponents, BorderLayout.CENTER); this.add(bottomButtons, BorderLayout.PAGE_END); }
b3585136-7db9-4101-886d-236686df904b
4
@Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof SentenceSpan) { SentenceSpan a = (SentenceSpan) obj; return getSentence().equals(a.getSentence()) && section.equals(a.section) && Arrays.equals(getWords(), a.getWords()); } else { return false; } }
ad462e13-9939-44ce-b746-bb92c08adb92
1
public JSONArray getJSONArray(String key) throws JSONException { Object object = this.get(key); if (object instanceof JSONArray) { return (JSONArray)object; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); }
9f912028-209e-416a-9a10-c4ce49a4bb66
5
private void normal(Key key) { if (limitReached()) { return; } // If delete comes through don't print it out! if (key.getCharacter() == 127) { return; } TextGrid.DataGridCel cel = grid.getCel(currentRow + rowOffset, currentCol + colOffset); if (cel != null && cel.getBufferIndex() != -1) { grid.insertChar(cel.getBufferIndex(), key.getCharacter()); } else { grid.appendChar(key.getCharacter()); } if (currentCol == numberOfCols - 1) { colOffset++; } else { currentCol++; } }
5a55e66c-d09a-4ee9-90e0-45e1411ace85
1
public URLFileDownloader(String s) throws MalformedURLException { this.url = new URL("http://oberien.bplaced.net/Oberien/" + s); s = s.replace("%20", " "); if (s.contains("natives")) { s = "Game/" + s.substring(s.lastIndexOf("/")); } file = new File(s); }
ddedc27c-8e17-4b8e-a8cd-501a7b1b95cc
0
public GrammarTestAction(GrammarEnvironment environment) { super("Grammar Test", null); this.environment = environment; this.frame = Universe.frameForEnvironment(environment); }
30f4f5df-6c5f-4bf6-bb74-2be8ee7b6c01
9
public void retrieveEvent(String[] arguments) throws RemoteException { final String retrieveUsage = "Usage: retrieve [user] xxxx-xx-xx xx:xx:xx xxxx-xx-xx xx:xx:xx.\n"; if((arguments.length != 5) && (arguments.length != 6)) { System.out.println(retrieveUsage); return; } ArrayList<Event> reEvents = null; //Ignore user name, so retrieve events of self. if(arguments.length == 5) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d1 = null; Date d2 = null; try { d1 = format.parse(arguments[1] + " " + arguments[2]); d2 = format.parse(arguments[3] + " " + arguments[4]); } catch (ParseException e) { // TODO Auto-generated catch block //e.printStackTrace(); System.out.println("Date format incorrect.\n"); return; } Calendar begin = Calendar.getInstance(); Calendar end = Calendar.getInstance(); begin.setTime(d1); end.setTime(d2); reEvents = co.retrieveEvent(null, begin, end); } else { //Retrieve a user's calendar. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d1 = null; Date d2 = null; try { d1 = format.parse(arguments[2] + " " + arguments[3]); d2 = format.parse(arguments[4] + " " + arguments[5]); } catch (ParseException e) { // TODO Auto-generated catch block //e.printStackTrace(); System.out.println("Date format incorrect.\n"); return; } Calendar begin = Calendar.getInstance(); Calendar end = Calendar.getInstance(); begin.setTime(d1); end.setTime(d2); if(!arguments[1].equals(userName)) //Retrieve other user's calendar reEvents = co.retrieveEvent(arguments[1], begin, end); else //Retrieve self calendar. reEvents = co.retrieveEvent(null, begin, end); } if((reEvents != null) && (reEvents.size() > 0)) { for(int i = 0; i < reEvents.size(); i++) System.out.println(reEvents.get(i)); System.out.println(); } else System.out.println("No schedule during this time period.\n"); }
520513a5-0389-4210-b9d7-a7b81efa2cd1
7
public void loadGraphFromSXGFString(String graphXML) { //System.out.println(graphXML); try { Document document = builder.parse(new InputSource(new StringReader(graphXML))); // Graph NodeList graphroots = document.getElementsByTagName("Graph"); Node graphroot = graphroots.item(0); NodeList graphElements = graphroot.getChildNodes(); for (int i = 0; i < graphElements.getLength(); i++) { Node graphElement = graphElements.item(i); // Graph/Name if (graphElement.getNodeName().equals("Name")) { System.out.println("Reading Graph"); } // GraphData/Nodes else if (graphElement.getNodeName().equals("Nodes")) { System.out.println("Reading Nodes"); loadNodesFromXMLNode(graphElement); } // GraphData/Edges else if (graphElement.getNodeName().equals("Edges")) { System.out.println("Reading Edges"); loadEdgesFromXMLNode(graphElement); } } } catch (SAXException sxe) { // Error generated during parsing Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); } catch (IOException ioe) { // I/O error ioe.printStackTrace(); } }
598ad60a-3199-48d6-8de1-73ae2defdb81
3
public void replace(String statement) throws CannotCompileException { thisClass.getClassFile(); // to call checkModify(). ConstPool constPool = getConstPool(); int pos = currentPos; int index = iterator.u16bitAt(pos + 1); Javac jc = new Javac(thisClass); ClassPool cp = thisClass.getClassPool(); CodeAttribute ca = iterator.get(); try { CtClass[] params = new CtClass[] { cp.get(javaLangObject) }; CtClass retType = CtClass.booleanType; int paramVar = ca.getMaxLocals(); jc.recordParams(javaLangObject, params, true, paramVar, withinStatic()); int retVar = jc.recordReturnType(retType, true); jc.recordProceed(new ProceedForInstanceof(index)); // because $type is not the return type... jc.recordType(getType()); /* Is $_ included in the source code? */ checkResultValue(retType, statement); Bytecode bytecode = jc.getBytecode(); storeStack(params, true, paramVar, bytecode); jc.recordLocalVariables(ca, pos); bytecode.addConstZero(retType); bytecode.addStore(retVar, retType); // initialize $_ jc.compileStmnt(statement); bytecode.addLoad(retVar, retType); replace0(pos, bytecode, 3); } catch (CompileError e) { throw new CannotCompileException(e); } catch (NotFoundException e) { throw new CannotCompileException(e); } catch (BadBytecode e) { throw new CannotCompileException("broken method"); } }
f8107a94-a5a9-4ea5-8bd1-f69d1073bd57
2
public List<JsonIngredient> getParentIngredients(){ if(parent == null){ return null; } if(parent.getInternal() == null){ return null; } return parent.getInternal().getParent(); }
68cbf032-98ef-4abf-ae29-e4b34934287f
4
private String fetchFormatFromQuery( URI requestedURI, String defaultFormat ) { if( requestedURI.getQuery() == null ) return defaultFormat; String encoding = java.nio.charset.StandardCharsets.UTF_8.name(); // "UTF-8"; String key = "format"; try { ikrs.httpd.datatype.Query query = new ikrs.httpd.datatype.Query( requestedURI.getQuery(), encoding, // Query encoding false // Case sensitive? ); String format = query.getParam( key ); // Param lookup is not case sensitive if( format == null || format.length() == 0 ) return defaultFormat; else return format.toUpperCase(); } catch( java.io.UnsupportedEncodingException e ) { // Ooops. This method is just for fun. Don't raise any errors (but log the error). this.getLogger().log( Level.INFO, getClass().getName() + ".fetchFormatFromQuery(...)", "UnsupportedEncodingException when trying to fetch '" + key + "' param from query '" + requestedURI.getQuery() + "': " + e.getMessage() + ". Continue with default format setting." ); return defaultFormat; } }
5350d034-a4b9-4bd3-9a7c-6844a3bce39e
2
public void minimumParentheses(){ Pattern pattern = Pattern.compile("[(][0-9¥+¥-¥*/]+[)]"); Matcher matcher = pattern.matcher(expression); if (matcher.find()) { for(int i = 0; i < matcher.groupCount(); i++) { //add matched expression into list and replace it to %s //System.out.println(matcher.group(i)); } } else { throw new IllegalStateException("No match found."); } }
006e8587-c766-4d37-9a53-0e3bceb72863
3
public boolean isPathSelected(TreePath path, boolean dig) { if (!dig) { return super.isPathSelected(path); } while (path != null && !super.isPathSelected(path)) { path = path.getParentPath(); } return path != null; }
3b1e430a-02d8-435d-ae67-20263e36013c
3
@Override public void ejecutar(Stack<Valor> st, MemoriaDatos md, Cp cp) throws Exception { if (st.size() < 2) throw new Exception("DIV: faltan operandos"); Valor op1 = st.pop(); Valor op2 = st.pop(); if (op1 instanceof Entero && op2 instanceof Entero) { st.push(new Entero(((int) op1.getValor()) / ((int) op2.getValor()))); cp.incr(); } else throw new Exception("DIV: operandos no enteros"); }
fac678c5-0f51-4276-9e76-16146830a838
0
public Integer getId() { return this.id; }
66311d21-94c8-4478-a1c6-fc7d7648cfe6
4
protected synchronized void ensureOpened(){ if (this.dialogState == DialogState.CLOSED) { throw new IllegalStateException("对话已经关闭"); } else if (this.dialogState == DialogState.OPENNING) { throw new IllegalStateException("对话正在建立"); } else if (this.dialogState == DialogState.CREATED) { throw new IllegalSignatureException("对话刚创建"); } else if (this.dialogState == DialogState.FAILED) { throw new IllegalStateException("建立对话失败"); } }
6c5750b0-e08e-4cf9-9d21-65551d8fb3ff
3
public boolean login(){ String Username = jTextField1.getText(); String Password = String.valueOf(jPasswordField1.getPassword()); String reply = ""; try { Soutput.writeObject("login " + Username + " " + Password); Soutput.flush (); } catch (IOException e) { System.out.println ("Error writting to the socket: " + e); return false; } try { reply = (String)Sinput.readObject (); } catch (Exception e) { System.out.println("login error"); System.out.println ("Error reading from the socket: " + e); return false; } if (!reply.equals("loggedin")) { return false; } //Perform post-login actions final String accepted = Username; Thread gameThread = new Thread(){ public void run(){ basicslick.GameFrame.createNetGame(socket, Soutput, Sinput, accepted); } }; gameThread.start(); dispose(); return true; }
0f498efc-ea8e-41d0-92ba-a3e57994dcf2
3
static boolean check(int r, int c) { return r >= 0 && r < m && c >= 0 && c < n; }
c279703a-9785-4c50-baa8-5432e8309b5e
7
public void show() { if (mazeFilled) { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (maze[j][i].equals(ETile.WALL)) { System.out.print(ETile.WALL.getSymbol()); } else if (maze[j][i].equals(ETile.SPACE)) { System.out.print(ETile.SPACE.getSymbol()); } else if (maze[j][i].equals(ETile.START)) { System.out.print(ETile.START.getSymbol()); } else if (maze[j][i].equals(ETile.FINISH)) { System.out.print(ETile.FINISH.getSymbol()); } else { System.out.print("-"); } System.out.print(" "); } System.out.println(); } } else { System.out.println("MAZE: UNABLE TO PERFORM THE -show()- METHOD BECAUSE MAZE IS NOT INITIALIZED"); } }
5abfa783-40b9-45d1-9ef3-2794bb189d23
0
private void setNameGameWorld(String name) { nameGameWorld = name.substring(name.lastIndexOf(".") + 1, name.indexOf("Loc")); }
367da238-e8a6-4275-9ce1-76aeeadc19ce
5
public void putByte(byte newByte) { byte[] ar = new byte[1]; ar[0] = newByte; msg = new String(ar); if (newByte == '$') { // new Message Start detected // reset Msg String and add Start-delimiter outmsg = msg; startDetected = true; } else if (newByte == '\n' && startDetected == true) { // End of Message // Put Message in Receive-Buffer outmsg = outmsg.concat(msg); try { inQueue.put(outmsg); } catch (InterruptedException e) { // TODO handle Exception } msg = ""; outmsg = ""; startDetected = false; } else if (startDetected == true) { // Add Byte to receive Message String outmsg = outmsg.concat(msg); } else { // Dont process Data } }
7e925f6a-7ea8-4146-b2b9-9adb965e7020
2
public void displayTieOrWinMessage() { if(this.isInCheck()&&!this.canGetOutOfCheck()) { this.displayGameOverMessage(); } else { this.displayTieMessage(); } }
0cc8fbcd-b141-4a07-ae65-4495c43031be
5
@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.unban + " (PlayerName)"); return; } String name = arg1[0]; try { if (plugin.getUtilities().isBanned(name)) { try { plugin.getUtilities().unbanPlayer(name); String bmessage = plugin.PLAYER_UNBANNED; bmessage = bmessage.replace("%player", arg1[0]); sender.sendMessage(bmessage); return; } catch (SQLException e) { e.printStackTrace(); } } else { String bmessage = plugin.PLAYER_NOT_BANNED; bmessage = bmessage.replace("%player", arg1[0]); sender.sendMessage(bmessage); } } catch (SQLException e) { e.printStackTrace(); } }
5a057198-16aa-4a97-bdce-4164e9a653ba
8
public boolean fletching2(int Status, int Amount1, int Amount2) { if (playerLevel[playerFletching] >= fletching[1]) { addSkillXP((fletching[2] * fletching[3]), playerFletching); deleteItem(useitems[0], useitems[3], Amount1); deleteItem(useitems[1], useitems[2], Amount2); addItem(fletching[4], Amount2); if (Status == 1) { sendMessage("You attach feathers to "+Amount2+" arrow shafts."); } else if (Status == 2) { sendMessage("You attach some of the heads to some of your headless arrows."); sendMessage("You finish making "+Amount2+" arrows."); } else if (Status == 3) { sendMessage("You add a string to the bow."); } else if (Status == 4) { sendMessage("You finish making "+Amount2+" darts."); } else if (Status == 5) { sendMessage("You attach feathers to "+Amount2+" ogre arrow shafts."); } else if (Status == 6) { sendMessage("You attach some of the wolf bone arrow heads to some of your flighted ogre arrows."); sendMessage("You finish making "+Amount2+" ogre arrows."); } else if (Status == 7) { sendMessage("You hammer the nails and attach some to some of your flighted ogre arrows."); sendMessage("You finish making "+Amount2+" brutal arrows."); } } else { sendMessage("You need "+fletching[1]+" "+statName[playerFishing]+" to make this."); resetFL(); return false; } resetFL(); return true; }
5b249080-235e-4246-9abd-cc53d430d53c
3
public boolean adicionarPromocao(Promocao p, String nomeOUcodigo) throws ExceptionGerenteEstoque { if (getProduto(nomeOUcodigo)== null){ throw new ExceptionGerenteEstoque("Produto n��o exite"); } if (p.getId() == 0){ throw new ExceptionGerenteEstoque(" Promocao n��o exite"); } Produto prod = getProduto(nomeOUcodigo); if (prod.getPromocao() != 0) { remover(getPromocao(prod.getPromocao())); } prod.setPromocao(p.getId()); return promocoes.add(p); }
7f62b039-8406-4e3e-bd8d-c9ee6c8d878e
4
@EventHandler public void onPlayerRespawn(PlayerRespawnEvent event) { final Player player = event.getPlayer(); if (!player.hasPermission("lifemc.lives.lose")) return; int lives = plugin.getDataHandler().getLives(player); if (lives <= 1) { plugin.getDataHandler().setLives(player, 0); //player.getInventory().clear(); //player.getEquipment().clear(); //player.setExp(0); // Teleport player to bed so they spawn at their bed after they get unbanned. if (plugin.getConfigHandler().spawnAtBedAfterBan()) { final Location bedLocation = player.getBedSpawnLocation(); if (bedLocation != null) { event.setRespawnLocation(bedLocation); // Teleport player after .25 seconds plugin.getServer().getScheduler() .runTaskLater(plugin, new Runnable() { public void run() { player.teleport(bedLocation); } }, 5L); } } // Kick player after .5 seconds plugin.getServer().getScheduler() .runTaskLater(plugin, new Runnable() { public void run() { player.kickPlayer(Lang.KICK_OUT_OF_LIVES.getConfigValue()); } }, 10L); } else { plugin.getDataHandler().setLives(player, lives - 1); player.sendMessage(Lang.LOST_A_LIFE.getConfigValue()); } }
bc892e0b-0c97-458b-873c-bacb406926d6
7
private String convertXXX(int n) { if(n==0) return ""; int first = n % 10; int second = ((n - first) /10)%10; int third = ((n - 10 * second - first) / 100)%10; String result = ""; if (third != 0) { result += getWord1(third); result += " Hundred and "; } if (second != 0) { if (second > 1) { result += getWord2(second); } if (second == 1) { result += getWord3(first); return result; } } if (first != 0) { if(second!=0){ result+="-"; } result+=getWord1(first); } return result; }
5f539ca1-f9aa-45e1-90a3-d918d8cac4bf
6
public static void main(String[] argv) throws IOException, InterruptedException, LWJGLException { Renderer r = new Renderer(1); Sprite s = new Sprite("mask.dmi"); for(int x = 0; x<20; x++) for(int y=0;y<20;y++) { Atom a = new Atom(); a.direction = Directions.SOUTH; a.frame = 0; a.sprite_state = "muzzle"; a.sprite = s; a.tile_x = x; a.tile_y = y; a.layer = 0; r.addAtom(a); } for(int x = 0; x<20; x++) for(int y=0;y<20;y++) { Atom a = new Atom(); a.direction = Directions.EAST; a.frame = 0; a.sprite_state = "muzzle"; a.sprite = s; a.tile_x = x; a.tile_y = y; a.layer = 2; r.addAtom(a); } r.draw(); int i = 0; while(true) { r.draw(); Thread.sleep(1000/60); r.setEyePos(i, 0); if(Display.isCloseRequested()){ break; } i++; } }
88faeebd-b0a1-4824-81d6-367ef081826d
1
public static Duration minDuration(Duration a, Duration b) { if (a.isShorterThan(b)) { return a; } else { return b; } }
a4089b6e-c1a8-48f0-8f1b-39f435657e52
9
public static <VertexType extends BaseVertex, EdgeType extends BaseEdge<VertexType>> AbstractList<VertexType> doSort(BaseGraph<VertexType, EdgeType> graph) { ArrayList<VertexType> alv = new ArrayList<VertexType>(); ArrayList<VertexType> out = new ArrayList<VertexType>(); LibraryUtils.falsifyVertexMarks(graph); for (VertexType v : graph) if (graph.getInDegree(v) == 0) { alv.add(v); v.setMark(true); } while (alv.size() != 0) { VertexType v = alv.remove(0); out.add(v); A: for (VertexType target : graph.getNeighbors(v)) { if (target.getMark()) continue; for (VertexType src : graph.getBackNeighbours(target)) { if (!src.getMark()) { continue A; } } target.setMark(true); alv.add(target); } } for (VertexType v : graph) { if (!v.getMark()) { return null; //graph has a loop } } return out; }
2b7600fc-25f2-4fda-acb9-960154887528
3
public static void main(String[] args) { // Build model Model model = new CPModel(); // Declare every letter as a variable IntegerVariable d = Choco.makeIntVar("d", 0, 9, Options.V_ENUM); IntegerVariable o = Choco.makeIntVar("o", 0, 9, Options.V_ENUM); IntegerVariable n = Choco.makeIntVar("n", 0, 9, Options.V_ENUM); IntegerVariable a = Choco.makeIntVar("a", 0, 9, Options.V_ENUM); IntegerVariable l = Choco.makeIntVar("l", 0, 9, Options.V_ENUM); IntegerVariable g = Choco.makeIntVar("g", 0, 9, Options.V_ENUM); IntegerVariable e = Choco.makeIntVar("e", 0, 9, Options.V_ENUM); IntegerVariable r = Choco.makeIntVar("r", 0, 9, Options.V_ENUM); IntegerVariable b = Choco.makeIntVar("b", 0, 9, Options.V_ENUM); IntegerVariable t = Choco.makeIntVar("t", 0, 9, Options.V_ENUM); IntegerVariable c1 = Choco.makeIntVar("C1", 0, 1, Options.V_ENUM); //Carry 1 IntegerVariable c2 = Choco.makeIntVar("C2", 0, 1, Options.V_ENUM); //Carry 2 IntegerVariable c3 = Choco.makeIntVar("C3", 0, 1, Options.V_ENUM); //Carry 3 IntegerVariable c4 = Choco.makeIntVar("C4", 0, 1, Options.V_ENUM); //Carry 4 IntegerVariable c5 = Choco.makeIntVar("C5", 0, 1, Options.V_ENUM); //Carry 5 /** * + D O N A L D * + G E R A L D * + C5 C4 C3 C2 C1 *===================== * R O B E R T */ model.addConstraint(Choco.allDifferent(new IntegerVariable[]{d,o,n,a,l,g,e,r,b,t})); model.addConstraint(Choco.eq(Choco.plus(d, d), Choco.plus(t, Choco.mult(10, c1)))); model.addConstraint(Choco.eq(Choco.plus(Choco.plus(c1, l), l), Choco.plus(r, Choco.mult(10, c2)))); model.addConstraint(Choco.eq(Choco.plus(Choco.plus(c2, a), a), Choco.plus(e, Choco.mult(10, c3)))); model.addConstraint(Choco.eq(Choco.plus(Choco.plus(c3, n), r), Choco.plus(b, Choco.mult(10, c4)))); model.addConstraint(Choco.eq(Choco.plus(Choco.plus(c4, o), e), Choco.plus(o, Choco.mult(10, c5)))); //model.addConstraint(Choco.eq(Choco.plus(Choco.plus(c5, d), g), Choco.plus(r, Choco.mult(10, null)))); Solver solver = new CPSolver(); solver.read(model); solver.solveAll(); IntegerVariable[] donald = {d,o,n,a,l,d}; for (IntegerVariable letter : donald) { System.out.print(solver.getVar(letter) + " "); } System.out.println(); IntegerVariable[] gerald = {g,e,r,a,l,d}; for (IntegerVariable letter : gerald) { System.out.print(solver.getVar(letter) + " "); } System.out.println(); IntegerVariable[] robert = {r,o,b,e,r,t}; for (IntegerVariable letter : robert) { System.out.print(solver.getVar(letter) + " "); } }
41de44ee-5c02-4b33-ae09-f3e86fa5b2a5
2
@EventHandler public void onJoin(PlayerJoinEvent e){ Player p = e.getPlayer(); try{ API api = Plugin.getAPI(); api.setPlayersJob(p, api.getDefaultJob()); if(api.checkForProperty(p) == null){ api.setMoney(p, api.getStartMoney()); }else{ } }catch(Exception exception){ } }
e50f6603-6b18-405c-8ba5-77b4f5e68d05
5
public String toString() { StringBuffer buf = new StringBuffer(); // line 1 buf.append(" "); for (int i=1; i<=s.length(); i++) buf.append(" "+sAt(i)+" "); buf.append("\n"); // line 2 buf.append(" "); for (int i=1; i<=s.length(); i++) buf.append("---"); buf.append("\n"); // remaining lines PrintfFormat fmt = new PrintfFormat(cellFormat); for (int j=1; j<=t.length(); j++) { buf.append(" "+tAt(j)+"|"); for (int i=1; i<=s.length(); i++) { double v = printNegativeValues ? -get(i,j) : get(i,j); buf.append(fmt.sprintf(v)); } buf.append("\n"); } return buf.toString(); }
1136614f-78d5-4544-90a9-347e130b07df
0
public ArrayList<Pet> arrayList(int size) { ArrayList<Pet> result = new ArrayList<Pet>(); Collections.addAll(result, createArray(size)); return result; }
f99bb983-f62a-4278-ba83-738d381b0d1e
4
public void presentMineralMap(World world, Terrain terrain) { final int colourKey[][] = new int[mapSize][mapSize] ; final int typeColours[] = { 0xff000000, 0xffff0000, 0xff0000ff, 0xff00ff00 } ; final int degreeMasks[] = { 0xff000000, 0xff3f3f3f, 0xff7f7f7f, 0xffbfbfbf, 0xffffffff } ; for (Coord c : Visit.grid(0, 0, mapSize, mapSize, 1)) { final Tile t = world.tileAt(c.x, c.y) ; final byte type = terrain.mineralType(t) ; final float amount = terrain.mineralsAt(t, type) ; byte degree = 0 ; if (amount == Terrain.AMOUNT_TRACE) degree = 1 ; if (amount == Terrain.AMOUNT_COMMON) degree = 2 ; if (amount == Terrain.AMOUNT_HEAVY ) degree = 3 ; colourKey[c.x][c.y] = typeColours[type] & degreeMasks[degree] ; } I.present(colourKey, "minerals map", 256, 256) ; }
647fab2f-3ac2-48f6-8ced-7f06076de663
8
private final void method2590(byte[] is, int[] is_0_, int i, int i_1_, int i_2_, int i_3_, int i_4_, int i_5_, int i_6_) { int i_7_ = -(i_3_ >> 2); i_3_ = -(i_3_ & 0x3); for (int i_8_ = -i_4_; i_8_ < 0; i_8_++) { for (int i_9_ = i_7_; i_9_ < 0; i_9_++) { if (is[i_1_++] != 0) is_0_[i_2_++] = i; else i_2_++; if (is[i_1_++] != 0) is_0_[i_2_++] = i; else i_2_++; if (is[i_1_++] != 0) is_0_[i_2_++] = i; else i_2_++; if (is[i_1_++] != 0) is_0_[i_2_++] = i; else i_2_++; } for (int i_10_ = i_3_; i_10_ < 0; i_10_++) { if (is[i_1_++] != 0) is_0_[i_2_++] = i; else i_2_++; } i_2_ += i_5_; i_1_ += i_6_; } }
4391c553-02dd-4d78-9e60-abce54d59fe1
4
public boolean hasChild(Spatial spat) { if (children.contains(spat)) return true; for (Spatial child : children) { if (child instanceof Node && ((Node)child).hasChild(spat)) return true; } return false; }
d98ad612-0540-4c3f-ae39-7c7abfa8606d
3
private boolean checkWin(){ boolean win = false; int deads = 0; for (SimulatorRobot robot : Board.robots) { if (robot.getLives() <= 0) { deads++; if(deads == Board.robots.size() -1 ){ win = true; } } } return win; }
e41be2bb-1bc1-41d6-81ff-033e7e723b4e
2
public boolean replaceSubBlock(StructuredBlock oldBlock, StructuredBlock newBlock) { if (thenBlock == oldBlock) thenBlock = newBlock; else if (elseBlock == oldBlock) elseBlock = newBlock; else return false; return true; }
8f493373-39cc-494d-beba-54b32e2f4e05
2
public void update(GameContainer gc, StateBasedGame sbg, int delta)throws SlickException { if(!isGameOver) { if(!isPause) { } else { } } else { } }
3f4f4484-3d99-4c17-982d-f10cfc309d2f
8
private void playEvents() { try { while(running.get()) { // Lock the events and wait until we have unprocessed events eventsLock.lock(); try { while(eventsIsProcessed.get()){ eventsNotProcessed.await(); } // Double buffer the events so that we can play them completely playingEventsBuffer = eventsBuffer; // Mark the events as processed and signal eventsIsProcessed.set(true); eventsProcessed.signalAll(); } finally { eventsLock.unlock(); } // Process the events int previousFrame = 0; int inBufferFrameIndex = (int)(getCurrentFramePosition() - playingEventsBuffer.getPositionOffsetFrames()); while(running.get() && inBufferFrameIndex < playingEventsBuffer.getNumFramesInBuffer()) { // Set the current piece byte[] pieces = playingEventsBuffer.getPieces(); //Log.get().verbose("Idx: %d Length: %d Frames: %d\n", inBufferFrameIndex, pieces.length, playingEventsBuffer.getNumFramesInBuffer()); myModelAdapter.setNextPiece(pieces[inBufferFrameIndex]); myModelAdapter.setDelay(playingEventsBuffer.getDelays()[inBufferFrameIndex]); // Pulse with the beat boolean[] beats = playingEventsBuffer.getBeats(); boolean hasBeat = false; for(int i = previousFrame; i < inBufferFrameIndex; i++) { if(beats[i]) { hasBeat = true; break; } } if(hasBeat) { myModelAdapter.pulse(-1); } // Process an event every 10ms Thread.sleep(10); // Get the frame for the next event update previousFrame = inBufferFrameIndex; inBufferFrameIndex = (int)(getCurrentFramePosition() - playingEventsBuffer.getPositionOffsetFrames()); } } } catch(Exception e) { Log.get().warning("Exception\n", e); } }
8394a70d-dd50-4788-9b1f-7128517a5947
5
private void handleValidDate(Field field, Object container, SwingWorkerInterface swingworker) throws IllegalAccessException { ValidDate validDate=field.getAnnotation(ValidDate.class); if(validDate!=null && isCheckSupposedToExecuteBasedOnAction(validDate.value(), swingworker.getAction())){ Object jtextComponentObj = field.get(container); if(jtextComponentObj instanceof JTextComponent){ JTextComponent textComponent= (JTextComponent) jtextComponentObj; String text=textComponent.getText(); if(StringUtils.isBlank(text)){ return; } try{ DateUtils.getDateFromFormatOfString(text); }catch (InvalidDateException e){ this.isError=true; CommonUI.setErrorBorderAndTooltip(textComponent, e.getMessage()); } } } }
e3b68669-131f-44d4-bed0-807b4c28ce07
0
public ProfessorServlet() { super(); // TODO Auto-generated constructor stub }
1f992434-031e-4899-8fe8-55ceb56386f9
4
private void setTextFieldVerifiers() { //Определяем массив текстовых компонентов final JComponent[] componentArr = new JComponent[]{textFieldName, textFieldMinAmount, textFieldMaxAmount, textFieldDuration, textFieldStartPay, textFieldPercent, textAreaDescription}; //Создаем обьект проверки final TextFieldVerifier verifier = new TextFieldVerifier(); //Установка его в компоненты for (JComponent component : componentArr) { component.setInputVerifier(verifier); } //Создаем слушателя на заполнения поля KeyListener listener = new KeyAdapter() { public void keyTyped(KeyEvent e) { for (JComponent component : componentArr) { boolean enabled = verifier.verify(component); if (enabled == false) { buttonSave.setEnabled(enabled); break; } buttonSave.setEnabled(enabled); } } }; //Цепляем слушателя на все компоненты for (JComponent component : componentArr) { component.addKeyListener(listener); } }
91e4a100-86ee-4163-a2b1-304363854b0c
9
private boolean areValidObstacles() { boolean answer = true; for(Obstacle o : obstacles) { if(o.getxStart() <= 0 || o.getxStart() >= nbLigneGrille -1) { answer = false; } if(o.getyStart() <= 0 || o.getyStart() >= nbColGrille - 1) { answer = false; } if(o.getxEnd() <= 0 || o.getxEnd() >= nbLigneGrille -1) { answer = false; } if(o.getyEnd() <= 0 || o.getyEnd() >= nbColGrille - 1) { answer = false; } } return answer; }
365fe2ab-664e-4ca2-beeb-99f64b9d9d65
7
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final Item target=getTarget(mob,null,givenTarget,commands,Wearable.FILTER_ANY); if(target==null) return false; if(!(target instanceof Scroll)) { mob.tell(L("You can't clarify that.")); return false; } if(((Scroll)target).usesRemaining()>((Scroll)target).getSpells().size()) { mob.tell(L("That scroll can not be enhanced any further.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,somanticCastCode(mob,target,auto),auto?"":L("^S<S-NAME> wave(s) <S-HIS-HER> fingers at <T-NAMESELF>, uttering a magical phrase.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); mob.location().show(mob,target,CMMsg.MSG_OK_VISUAL,L("The words on <T-NAME> become more definite!")); ((Scroll)target).setUsesRemaining(((Scroll)target).usesRemaining()+1); } } else beneficialVisualFizzle(mob,target,L("<S-NAME> wave(s) <S-HIS-HER> fingers at <T-NAMESELF>, uttering a magical phrase, and looking very frustrated.")); // return whether it worked return success; }
3eb63bcc-aff9-4901-a53a-dcf626abbd5b
4
@Override public String getColumnName(int column){ switch(column){ case 0: return ("szYear"); case 1: return("szMonth"); case 2: return("IntWorkingDay"); case 3: return("szWorkplaceId"); default: return null; } }
eb596259-f4be-48b9-9b84-f36eb7d76363
3
public void newwdg(int id, Widget w, Object... args) { if(w instanceof Listbox) { chrlist = (Listbox)w; } else if(w instanceof Button) { if(((Button)w).text.text.equals("I choose you!")) selbtn = (Button)w; } check(); }
cf41051e-43cd-48a6-9462-e1bda2fe036b
8
public List<SearchResult> findPostByWord(String keyWord, Map<String, String> indexMap, File contentFile) { List<SearchResult> results = new ArrayList<SearchResult>(); try { keyWord = keyWord.toLowerCase(); String indexStr = indexMap.get(keyWord); if (indexStr == null || indexStr.trim().length() == 0) return results; RandomAccessFile raf = new RandomAccessFile(contentFile, "r"); String[] indexArray = indexStr.split(Constants.SPLIT_FLAG); for(int i=0; i<indexArray.length; i++) { SearchResult result = new SearchResult(); result.setKeyWord(keyWord); String[] postions = indexArray[i].split("\\" + Constants.RANK_SPLIT_FLAG); int position = Integer.valueOf(postions[0]); int rank = Integer.valueOf(postions[1]); result.setRank(rank); raf.seek(position); String line = raf.readLine(); if (line != null) { String[] contents = line.split("\t"); if (contents == null) { System.out.println(position + " " + line); continue; } Post post = new Post(contents[0]); if (contents.length > 1) { post.setContent(contents[1]); } result.setPost(post); results.add(result); } } raf.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return results; }
912b6d77-bb86-4417-bafe-15f5cd999584
2
@Override public void execute() { final SceneObject cutRoot = SceneEntities.getNearest(Settings.CUT_ROOT_FILTER); if(cutRoot != null) { doAction("Collect", cutRoot); } else { final SceneObject uncutRoot = SceneEntities.getNearest(Constants.STRAIGHT_ROOT_ID); if(uncutRoot != null) { doAction("Chop", uncutRoot); } } }
0b79bf54-1529-4336-9c7e-b2c10c45debd
3
public boolean testVictoire(Joueur joueur) { for (Case c : joueur.getCases()) { if (c.getBateau() != null && !c.getBateau().testBateauCoule()) { return false; } } return true; } // testVictoire(Joueur joueur)
7ad0bd46-7065-46c4-8712-ace09ac5d9e2
7
public static void makeCompactGrid(Container parent, int rows, int cols, int initialX, int initialY, int xPad, int yPad) { SpringLayout layout; try { layout = (SpringLayout)parent.getLayout(); } catch (ClassCastException exc) { System.err.println("The first argument to makeCompactGrid must use SpringLayout."); return; } //Align all cells in each column and make them the same width. Spring x = Spring.constant(initialX); for (int c = 0; c < cols; c++) { Spring width = Spring.constant(0); for (int r = 0; r < rows; r++) { width = Spring.max(width, getConstraintsForCell(r, c, parent, cols). getWidth()); } for (int r = 0; r < rows; r++) { SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols); constraints.setX(x); constraints.setWidth(width); } x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad))); } //Align all cells in each row and make them the same height. Spring y = Spring.constant(initialY); for (int r = 0; r < rows; r++) { Spring height = Spring.constant(0); for (int c = 0; c < cols; c++) { height = Spring.max(height, getConstraintsForCell(r, c, parent, cols). getHeight()); } for (int c = 0; c < cols; c++) { SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols); constraints.setY(y); constraints.setHeight(height); } y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad))); } //Set the parent's size. SpringLayout.Constraints pCons = layout.getConstraints(parent); pCons.setConstraint(SpringLayout.SOUTH, y); pCons.setConstraint(SpringLayout.EAST, x); }
d6aaeec9-6fc8-4f23-ba22-edac2cd71627
7
protected int parseTag() throws IOException { if (_peekTag >= 0) { int tag = _peekTag; _peekTag = -1; return tag; } int ch = skipWhitespace(); int endTagDelta = 0; if (ch != '<') throw expectedChar("'<'", ch); ch = read(); if (ch == '/') { endTagDelta = 100; ch = _is.read(); } if (! isTagChar(ch)) throw expectedChar("tag", ch); _sbuf.setLength(0); for (; isTagChar(ch); ch = read()) _sbuf.append((char) ch); if (ch != '>') throw expectedChar("'>'", ch); Integer value = (Integer) _tagMap.get(_sbuf.toString()); if (value == null) throw error("Unknown tag <" + _sbuf + ">"); return value.intValue() + endTagDelta; }
128a0e00-95f8-415d-81e1-92d0f9be87f4
5
public Theater getTheater(int theaterID) throws RemoteException { if(this.lastRequest == -1) this.lastRequest = System.currentTimeMillis(); if(connectionTimout()) return null; for(LinkedList<Theater> theaters : list) for(Theater t : theaters) if(t.getId() == theaterID) return t; return null; }
1a7ea015-6020-4998-b2ef-fa1246389887
1
public void commitOnly(final Set methods, final Set fields) { try { final OutputStream outStream = loader.outputStreamFor(this); final DataOutputStream out = new DataOutputStream(outStream); writeHeader(out); writeConstantPool(out); writeAccessFlags(out); writeClassInfo(out); writeFields(out, fields); writeMethods(out, methods); writeAttributes(out); out.close(); } catch (final IOException e) { e.printStackTrace(); System.exit(1); } }
47690c43-a255-4708-bc63-aeddfd8d8013
7
private boolean search(Task task) throws IOException, ParseException { searchResult = new ArrayList<TaskData>(); String content = task.getContent(); if (content != null && !content.isEmpty() && (content.startsWith("block") || content .startsWith("blocked"))) { searchResult = blockedList; } else { if (task.isDone() == null || !task.isDone()) { searchResult = searchTool.search(taskList, task); done = false; } else { searchResult = searchTool.search(completedTask, task); done = true; } } if (searchResult != null) { return true; } overdueRow = 0; return false; }
ded29651-5b8c-4146-a270-42c267db74dc
5
public int [][] darHuertosIniciales() throws Exception { int ij0=0; int ij1=0; int[][] rta= new int[Interfaz.NUM_COORD][Interfaz.NUM_HUERTOS]; for(int i=0; i <Interfaz.NUM_COORD;i++) { for(int j =0; j<Interfaz.NUM_HUERTOS;j++) { if(j%2==0){ ij0=Integer.parseInt(txtCrops[i][j].getText()); rta[i][j]=ij0; }else{ ij1=Integer.parseInt(txtCrops[i][j].getText()); if(ij1<ij0-1 || ij1>ij0+1) { throw new Exception(); }else{ rta[i][j]=ij1; } } } } return rta; }
3f6850bf-f8a8-481a-a031-c9d2223b7abf
3
@SuppressWarnings("deprecation") public static boolean isPigChest (Entity entity) { if (entity instanceof Pig) { Pig pigc = (Pig) entity; if (pigc.getPassenger() instanceof StorageMinecart) { ItemStack pigcChest = new ItemStack(Material.LEATHER_CHESTPLATE, 1, (short) - 98789); if (pigc.getEquipment().getChestplate().equals(pigcChest)) { return true; } } } return false; }
591b84a8-362a-41d8-84ee-593b4c0abfb3
1
protected static void importOutlinerDocument(FileProtocol protocol) { DocumentInfo docInfo = new DocumentInfo(); PropertyContainerUtil.setPropertyAsString(docInfo, DocumentInfo.KEY_PROTOCOL_NAME, protocol.getName()); PropertyContainerUtil.setPropertyAsBoolean(docInfo, DocumentInfo.KEY_IMPORTED, true); // Select the file we are going to open. if (!protocol.selectFileToOpen(docInfo, FileProtocol.IMPORT)) { return; } FileMenu.importFile(docInfo, protocol); }
970e1968-213e-4343-92e1-207c45d13a2a
3
public boolean addBindListener( BindListener l ) throws NullPointerException { if( l == null ) throw new NullPointerException( "Cannot add null listeners." ); for( int i = 0; i < this.bindListeners.size(); i++ ) { if( this.bindListeners.get(i) == l ) return false; } this.bindListeners.add( l ); return true; }
18d59fbd-2319-4e32-852f-07bb6f14fae2
3
public void createOffspring(Gene gene2, Gene offspring){ int crossoverBit = Math.abs(Environment.random.nextInt()%environment.bitsPerGene); int crossoverByte = crossoverBit/Byte.SIZE; byte[] firstGene, lastGene;//who provides the first bits? if(Environment.random.nextInt()%2 == 0){ firstGene = geneData; lastGene = gene2.geneData; } else { firstGene = gene2.geneData; lastGene = geneData; } // System.out.println("#### mate ###"); // // System.out.println("gene1: "); // printGene(gene1); // System.out.println("gene2: "); // printGene(gene2); // System.out.println("crossoverByte:"+crossoverByte); System.arraycopy(firstGene, 0, offspring.geneData, 0, crossoverByte); System.arraycopy(lastGene, crossoverByte, offspring.geneData, crossoverByte, lastGene.length-crossoverByte); int crossoverBitFromRight = Byte.SIZE-crossoverBit%Byte.SIZE; byte mask = (byte) (Math.pow(2,crossoverBitFromRight) -1); offspring.geneData[crossoverByte] &= mask; offspring.geneData[crossoverByte] |= (byte)(firstGene[crossoverByte] & ~mask); // System.out.println("offspring: "); // printGene(offspring); //mutate for(int i = 0;i<environment.bitsPerGene;i++){ if(Environment.random.nextFloat() < Environment.MUTATION_RATE){ // System.out.println("mutate bit "+i+", byte before: "+Integer.toBinaryString(offspring[i/Byte.SIZE] & 0xff)); offspring.geneData[i/Byte.SIZE] ^= (byte)((1<<(Byte.SIZE-i%Byte.SIZE-1))); // System.out.println("byte after: "+Integer.toBinaryString(offspring[i/Byte.SIZE] & 0xff)); } } }
fa8e312a-a46b-4e72-86a5-628e9d470687
9
public AsieLauncherGUI() { launcher = new AsieLauncher(); launcher.setUpdater((IProgressUpdater) this); isRunning = true; setResizable(false); setLocationRelativeTo(null); setDefaultCloseOperation(DISPOSE_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent ev) { isRunning = false; } }); boolean has2x = hasFile("/resources/background@2x.png") || hasFile("/resources/background@2x.jpg"); boolean useJPG = hasFile("/resources/background@2x.jpg") || hasFile("/resources/background.jpg"); boolean usePNG = hasFile("/resources/background@2x.png") || hasFile("/resources/background.png"); if (useJPG || usePNG) { if (!has2x || Utils.getScaleFactor() <= 1.0) { background = getToolkit().getImage(getClass().getResource("/resources/background." + (useJPG ? "jpg" : "png"))); } else { background = getToolkit().getImage(getClass().getResource("/resources/background@2x." + (useJPG ? "jpg" : "png"))); } panel = new BackgroundPanel(background); ((BackgroundPanel) panel).setTransparentAdd(false); } else { panel = new JPanel(); } getContentPane().setSize(320, 240); getContentPane().setPreferredSize(new Dimension(320, 240)); getContentPane().setMaximumSize(new Dimension(320, 240)); getContentPane().setMinimumSize(new Dimension(320, 240)); getContentPane().add(panel); panel.setLayout(null); pack(); }
23e86af2-c6f8-445f-87b7-dd76c77ab40f
5
public ConsoleOut(JavaConsole console) { if(mFonts == null) { mFonts = new Font[4]; for(int i = 0; i < 4; i++) { mFonts[i] = new Font("Lucida Console", i, 14); } } mForegroundColor = Color.white; mBackgroundColor = Color.black; mConsoleForegroundColor = Color.white; mConsoleBackgroundColor = Color.black; mFrame = new Frame(); mCanvas = new ConsoleCanvas(); mElementCursorPosition = new Point(0,0); mElementCount = new Dimension(80, 25); mElements = new ConsoleElement[25][80]; for(int i = 0; i < 25; i++) for(int j = 0; j < 80; j++) mElements[i][j] = new ConsoleElement(); mFrame.setBounds(50, 50, 800, 600); mFrame.add(mCanvas); mFrame.addKeyListener(new KeyAdapter() { }); mFrame.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { super.componentResized(e); } }); mFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); System.exit(0); } }); mCaretVisible = false; mCaretState = false; mCaretTimer = new Timer(); mCaretTimerT = new TimerTask() { public void run() { if(!mCaretVisible) { mCaretState = false; cancel(); mCanvas.repaint(); return; } mCaretState = !mCaretState; mCanvas.repaint(); } }; mFrame.setVisible(true); }
6e670139-04d1-4baa-85c3-0a15e75c9f41
4
@Override public String multiply(String a, String b) throws NumberFormatException { if (a.equals(BigDecimal.ZERO) || b.equals(BigDecimal.ZERO)) { return String.valueOf(BigDecimal.ZERO); } else if (a.contains(".") || b.contains(".")) { BigDecimal aa = new BigDecimal(a); BigDecimal bb = new BigDecimal(b); return aa.multiply(bb).setScale(10, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString(); } else { BigInteger aa = new BigInteger(a); BigInteger bb = new BigInteger(b); return aa.multiply(bb).toString(); } }
5defe005-25ec-4311-9f74-9f60a0f9cf3a
2
private static int findLastInstanceOfStackHanoi(Stack[] stacks) { for (int i = stacks.length - 1; i >= 0; --i) { if (stacks[i] instanceof StackHanoi) { return i; } } return -1; }
f6a88bd1-d4f7-4ea4-86cb-4693a4e73154
8
public static String printVars(String className, boolean raw, boolean newLine, MyVar... varList) { String res = className == null ? "" : className + (newLine ? "\n" : " "); for (MyVar v : varList) { res += raw ? "" : "["; if (v.name != null && !raw) { res += v.name + ": "; } res += v.value + (raw ? " " : "] ") + (newLine ? "\n" : ""); } return res; }
a4eb867a-eef7-44b4-a5a0-3f168bc16fcc
7
public void method360(int i, int j, int k) { for(int i1 = 0; i1 < anIntArray1451.length; i1++) { int j1 = anIntArray1451[i1] >> 16 & 0xff; j1 += i; if(j1 < 0) j1 = 0; else if(j1 > 255) j1 = 255; int k1 = anIntArray1451[i1] >> 8 & 0xff; k1 += j; if(k1 < 0) k1 = 0; else if(k1 > 255) k1 = 255; int l1 = anIntArray1451[i1] & 0xff; l1 += k; if(l1 < 0) l1 = 0; else if(l1 > 255) l1 = 255; anIntArray1451[i1] = (j1 << 16) + (k1 << 8) + l1; } }
3ca32194-6a89-4fbb-a130-8757bb60d8fa
3
public void simpan(javax.swing.JTextField no_beli, javax.swing.JTable kwitansiTable){ if (!no_beli.getText().equals("")){ kwitansi.setNoPembeli(no_beli.getText()); Object[][] listKwitansi = new Object[kwitansiTable.getRowCount()][3]; for (int i=0; i <kwitansiTable.getRowCount();i++){ listKwitansi[i][0] = kwitansiTable.getValueAt(i, 0); listKwitansi[i][1] = kwitansiTable.getValueAt(i, 2); listKwitansi[i][2] = kwitansiTable.getValueAt(i, 3); } kwitansi.setListKwitansi(listKwitansi); if (kwitansi.simpan()){ FormUtama.formKwitansi.setNoPembeli(""); FormUtama.formKwitansi.setNama(""); FormUtama.formKwitansi.setAlamat(""); FormUtama.formKwitansi.setTelepon(""); FormUtama.formKwitansi.clearKwitansiTable(); FormUtama.formKwitansi.setTambahKwitansi(new Object[]{}); } } else { JOptionPane.showMessageDialog(null,"no beli tidak boleh kosong\n","Kesalahan",JOptionPane.ERROR_MESSAGE); } }
38f9d833-558f-44e4-8016-d8436f8759a8
6
public static void tempBanPlayer( String sender, String player, int minute, int hour, int day, String message ) throws SQLException { BSPlayer p = PlayerManager.getPlayer( sender ); BSPlayer t = PlayerManager.getSimilarPlayer( player ); if ( t != null ) { player = t.getName(); } if ( !PlayerManager.playerExists( player ) ) { p.sendMessage( Messages.PLAYER_DOES_NOT_EXIST ); return; } if ( isPlayerBanned( player ) ) { p.sendMessage( Messages.PLAYER_ALREADY_BANNED ); return; } if ( message.equals( "" ) ) { message = Messages.DEFAULT_BAN_REASON; } Calendar cal = Calendar.getInstance(); cal.add( Calendar.MINUTE, minute ); cal.add( Calendar.HOUR_OF_DAY, hour ); cal.add( Calendar.DATE, day ); Date sqlToday = new Date( cal.getTimeInMillis() ); SimpleDateFormat sdf = new SimpleDateFormat(); sdf.applyPattern( "dd MMM yyyy HH:mm:ss" ); String time = sdf.format( sqlToday ) + "(" + day + " days, " + hour + " hours, " + minute + " minutes)"; sdf.applyPattern( "yyyy-MM-dd HH:mm:ss" ); SQLManager.standardQuery( "INSERT INTO BungeeBans (player,banned_by,reason,type,banned_on,banned_until) VALUES('" + player + "','" + sender + "','" + message + "','tempban',NOW(),'" + sdf.format( sqlToday ) + "')" ); if ( t != null ) { disconnectPlayer( t.getName(), Messages.TEMP_BAN_MESSAGE.replace( "{sender}", p.getName() ).replace( "{time}", time ).replace( "{message}", message ) ); } if ( BansConfig.broadcastBans ) { PlayerManager.sendBroadcast( Messages.TEMP_BAN_BROADCAST.replace( "{player}", player ).replace( "{sender}", p.getName() ).replace( "{message}", message ).replace( "{time}", time ) ); } else { p.sendMessage( Messages.TEMP_BAN_BROADCAST.replace( "{player}", player ).replace( "{sender}", p.getName() ).replace( "{message}", message ).replace( "{time}", time ) ); } }
fbf93435-915e-4f25-97c5-f5aa52aa2dbc
9
public Node<T> findLowestCommonAncestor(Node<T> root, T data1, T data2){ if(root ==null){ return null; } if(contains(root.left, data1) && contains(root.left, data2)){ return findLowestCommonAncestor(root.left, data1, data2); } if(contains(root.right,data1) && contains(root.right, data2)){ return findLowestCommonAncestor(root.right, data1, data2); } if((contains(root.left,data1) && contains(root.right, data2) || contains(root.left,data2) && contains(root.right, data1))) { return root; } return null; }
edb76fa1-4386-42bf-9ab2-052b3d2e6b9f
7
public int open() { final Shell dialog = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.RESIZE | getStyle()); dialog.setText(GraphicsExample.getResourceString("Gradient")); //$NON-NLS-1$ GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.marginHeight = 10; gridLayout.marginWidth = 10; dialog.setLayout(gridLayout); // create the controls in the dialog createDialogControls(dialog); dialog.addListener(SWT.Close, new Listener() { public void handleEvent(Event event) { for (int i = 0; i < resources.size(); i++) { Object obj = resources.get(i); if (obj != null && obj instanceof Resource) { ((Resource) obj).dispose(); } } dialog.dispose(); } }); dialog.setDefaultButton (okButton); dialog.pack (); Rectangle rect = getParent().getMonitor().getBounds(); Rectangle bounds = dialog.getBounds(); dialog.setLocation(rect.x + (rect.width - bounds.width) / 2, rect.y + (rect.height - bounds.height) / 2); dialog.setMinimumSize(bounds.width, bounds.height); dialog.open (); Display display = getParent().getDisplay(); while (!dialog.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } if (menu1 != null) { menu1.dispose(); menu1 = null; } if (menu2 != null) { menu2.dispose(); menu2 = null; } return returnVal; }
3ddb332d-7a6b-49cc-b765-4d8db840cd43
7
@Override public List<MOB> getCurrentReaders() { final List<MOB> readers=new LinkedList<MOB>(); if(amDestroyed()) return readers; final MOB lastReader=this.lastReader; if(lastReader!=null) { if(((lastReader==owner())||(lastReader.location()==owner())) &&(CMLib.flags().isInTheGame(lastReader, true))) readers.add(lastReader); else this.lastReader=null; } for(final Rider R : riders) { if(R instanceof MOB) readers.add((MOB)R); } return readers; }
9f092c1b-d891-41ec-9b35-057d0c2e6706
2
@Override public void run() { while (!end) { process(); try {Thread.sleep(SLEEP_LONG);} catch (InterruptedException e) {} } process(); }
e3ca6ca7-3922-44ce-9206-de45ed689f7d
2
public double getDouble(int index) throws JSONException { Object object = get(index); try { return object instanceof Number ? ((Number)object).doubleValue() : Double.parseDouble((String)object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } }
d02e126e-0d40-405e-9619-0b5b98505480
0
public Keyboard getKeyboard() { return keyboard; }
5c5de92a-288d-43b3-a3f7-312aaa5811b6
9
public BufferedImage getImage(){ boolean canMove = this.canMove; this.canMove = true; BufferedImage img = null; if(lastMove == NO_MOVE) img = isLookRight() ? skin.getStandR() : skin.getStandL(); else if(lastMove > MOVE_RIGHT) img = isLookRight() ? skin.getJumpR() : skin.getJumpL(); else img = isLookRight() ? skin.getWalkR() : skin.getWalkL(); if(!isAlive()){ dead_tick++; this.canMove = false; //1 tick == 150 ms so >=20 == >=3 s if(dead_tick>=20) respawn(); return GraphicsTools.rotate(img, isLookRight() ? -90 : 90); }else dead_tick = 0; return canMove ? img : GraphicsTools.invert(img); }
958589d6-1af0-4fc2-81e8-424ae8083160
7
public static String search4SqVenues(double[] sw, double[] ne, String clientId, String clientSecret) throws Exception { HttpsURLConnection c = null; InputStream is = null; int rc; String url=""; /** This parameter represents the date of the Foursquare API version that we use. * If you want to modify the source code, please see https://developer.foursquare.com/overview/versioning */ String vParam = "20140801"; /** Formatting the two coordinates of the bounding box. */ String swString=sw[0]+","+sw[1]; String neString=ne[0]+","+ne[1]; try { url = "https://api.foursquare.com/v2/venues/search?intent=browse&limit=100"+ "&client_id=" + clientId + "&client_secret=" + clientSecret+ "&sw="+URLEncoder.encode(swString,"UTF-8") + "&ne="+URLEncoder.encode(neString,"UTF-8")+ "&v="+vParam; } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } final StringBuilder out = new StringBuilder(); try { c = (HttpsURLConnection) (new URL(url)).openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.setReadTimeout(20000); c.connect(); // Getting the response code will open the connection, // send the request, and read the HTTP response headers. // The headers are stored until requested. rc = c.getResponseCode(); if (rc != HttpsURLConnection.HTTP_OK) throw new Exception("Connection can not be made with the Foursquare service.."); is = c.getInputStream(); final char[] buffer = new char[2048]; final Reader in = new InputStreamReader(is, "UTF-8"); for (;;) { int rsz = in.read(buffer, 0, buffer.length); if (rsz < 0) break; out.append(buffer, 0, rsz); } return out.toString(); } catch (ClassCastException e) { throw new IllegalArgumentException("Not an HTTP URL"); } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } }
be20345f-eebe-467b-ad73-541c3b9e3380
3
public void showCamera() { if (checkCameraSupport() == false) { // showAlert("Error", "Camera is not supported!", null); return; } if (checkPngEncodingSupport() == false) { // showAlert("Error", "Png encoding is not supported!", null); return; } Form cameraForm = new Form("Camera"); try { createCamera(); cameraForm.append((Item) videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null)); // addCameraToForm(); startCamera(); } catch (Exception e) { } PCommand cmdCapture = new PCommand("Capture", Command.OK, PCommand.CAPTURE_PICTURE, 0); // PCommand cmdExit = new PCommand("Exit", Command.EXIT, 0); PCommand cmdAnotherPhoto = new PCommand("Another Photo", Command.HELP, 0); cameraForm.addCommand(cmdCapture); cameraForm.addCommand(back); // cameraForm.addCommand(cmdAnotherPhoto); cameraForm.setCommandListener(this); lastDisplay = display.getCurrent(); display.setCurrent(cameraForm); }
9b04154e-3e39-457b-af25-453f4d05a621
9
private void findCutOff(double[] pos, double[] neg){ int[] pOrder = Utils.sort(pos), nOrder = Utils.sort(neg); /* System.err.println("\n\n???Positive: "); for(int t=0; t<pOrder.length; t++) System.err.print(t+":"+Utils.doubleToString(pos[pOrder[t]],0,2)+" "); System.err.println("\n\n???Negative: "); for(int t=0; t<nOrder.length; t++) System.err.print(t+":"+Utils.doubleToString(neg[nOrder[t]],0,2)+" "); */ int pNum = pos.length, nNum = neg.length, count, p=0, n=0; double fstAccu=0.0, sndAccu=(double)pNum, split; double maxAccu = 0, minDistTo0 = Double.MAX_VALUE; // Skip continuous negatives for(;(n<nNum)&&(pos[pOrder[0]]>=neg[nOrder[n]]); n++, fstAccu++); if(n>=nNum){ // totally seperate m_Cutoff = (neg[nOrder[nNum-1]]+pos[pOrder[0]])/2.0; //m_Cutoff = neg[nOrder[nNum-1]]; return; } count=n; while((p<pNum)&&(n<nNum)){ // Compare the next in the two lists if(pos[pOrder[p]]>=neg[nOrder[n]]){ // Neg has less log-odds fstAccu += 1.0; split=neg[nOrder[n]]; n++; } else{ sndAccu -= 1.0; split=pos[pOrder[p]]; p++; } count++; if((fstAccu+sndAccu > maxAccu) || ((fstAccu+sndAccu == maxAccu) && (Math.abs(split)<minDistTo0))){ maxAccu = fstAccu+sndAccu; m_Cutoff = split; minDistTo0 = Math.abs(split); } } }