method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
f752bafe-56d6-481a-8d58-ffe60eb21061
2
public void onEnable() { this.file = new File(getDataFolder(), "config.yml"); ruChat.cfg = YamlConfiguration.loadConfiguration(file); this.loadCfg(); ruChat.modes = new HashMap<Player, ChatMode>(); this.log = Logger.getLogger("Minecraft"); this.plugin = getServer().getPluginManager(); ruChat.usePex = false; if (plugin.getPlugin("PermissionsEx") != null) { ruChat.usePex = true; } this.plugin.registerEvents(new ChatListener(), this); List<PluginCommand> cmds = new ArrayList<PluginCommand>(); cmds.add(getCommand("g")); cmds.add(getCommand("p")); cmds.add(getCommand("s")); cmds.add(getCommand("h")); cmds.add(getCommand("chat")); CommandsExecutor ex = new CommandsExecutor(); for (PluginCommand cmd : cmds) { cmd.setExecutor(ex); } this.log("Enabled!"); }
59c0d781-faf0-4096-aa4e-c18101d5f1f0
0
private void registerService() throws Exception { ServiceManager .getServices() .initializeServices(new Object[] { new TestRailwayRepository(), new TestTicketPoolManager()}); }
b5192a81-3d26-4c25-9937-a30d09ee9971
1
public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: java Parser [input]"); System.exit(0); } Parser p = new Parser(args[0]); }
27209efa-6aca-43a3-979b-92939165d949
1
@RequestMapping(value = "/saveCustomer", method = RequestMethod.POST) public String saveCustomer(@ModelAttribute("customer") Customer customer, BindingResult result) { System.out.println("customer id:" + customer.getCustomerId()+ "name" + customer.getName()); if (customer.getCustomerId() == null) { getDAO().create(customer); } else { Customer customerObject = getDAO().getById(customer.getCustomerId()); customerObject.setName(customer.getName()); getDAO().update(customerObject); } return "redirect:customers.htm"; }
3edeffbd-493f-4191-a6e6-c2ec1da85439
3
@Override public void delete(Staff obj) { PreparedStatement pst = null; try { pst = this.connect().prepareStatement("DELETE FROM Staff where id=?;"); pst.setInt(1, obj.getId()); pst.executeUpdate(); System.out.println("suppression effectuer"); } catch (SQLException ex) { Logger.getLogger(StaffDao.class.getName()).log(Level.SEVERE, "suppression echoué", ex); }finally{ try { if(pst != null) pst.close(); } catch (SQLException ex) { Logger.getLogger(StaffDao.class.getName()).log(Level.SEVERE, "liberation preparedstatement echoué", ex); } } }
9d2ac0c1-cc31-49e2-856d-aed66f93d381
7
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NeuronPair that = (NeuronPair) o; if (n2.equals(that.n2) && n1.equals(that.n1)) return true; if (n2.equals(that.n1) && n1.equals(that.n2)) return true; return false; }
20f82f47-f120-43c6-9c22-8b76712c7f28
3
* @return True, if the contents of this statement list changed. */ public boolean removeAll(final Collection c) { boolean changed = false; if (c == this) { changed = size() > 0; clear(); } else { final Iterator iter = c.iterator(); while (iter.hasNext()) { changed = remove(iter.next()) || changed; } } return changed; }
f83383e5-681d-4a4f-a9aa-aabf8bb08bec
0
public int getSearchNumLinks() { return _searchNumLinks; }
3e9eb1cf-57d4-472a-afe4-e2f963df902a
1
@Before public void setUp(){ d = new DataArrays<int[]>(); for(int i = 0; i<5; i++){ int[] a = new int[10]; Arrays.fill(a, i); d.addToKit(a); } }
688e70e2-8c8a-4cdc-beee-b5729253cabe
5
public void filtroClientes(String dni, String apellidoPaterno, String apellidoMaterno, String nombre, String email, String telefono, String celular, String fechaContacto) { // Busqueda secuencial por strings falta comparar mas campos. for(Cliente cliente : clientes) { if(cliente.getDni().compareTo(dni) == 0 || cliente.getApellidoPaterno().compareTo(apellidoPaterno) == 0 || cliente.getApellidoPaterno().compareTo(apellidoMaterno) == 0 || cliente.getNombres().compareTo(nombre) == 0 ) listar.add(cliente); } //ordenamos la lista por fecha de vencimiento Collections.sort(listar, new Comparator() { public int compare(Object o1, Object o2) { Cliente c1 = (Cliente) o1; Cliente c2 = (Cliente) o2; return c1.getFec_contac().compareToIgnoreCase(c2.getFec_contac()); } }); }
2e2fd857-26df-4e12-8c3c-8be09231a24c
2
public void placeNumbers(BoardModel boardModel) { for (Cell[] cells : boardModel.getBoard()) { for (Cell cell : cells) { cell.setContent(checkNeighborsForMines(boardModel, cell.getPosition())); } } }
4b9bc80e-6642-4200-8161-924019ed42a7
8
public void move() { Random generator = new Random(); double a = generator.nextDouble(); if (a < 0.25) { xCoordinate -= 25; if (isOutOfBounds()) { xCoordinate += 25; } } else if (a < 0.5) { xCoordinate += 25; if (isOutOfBounds()) { xCoordinate -= 25; } } else if (a < 0.75) { yCoordinate -= 25; if (isOutOfBounds()) { yCoordinate += 25; } } else if (a <= 1) { yCoordinate += 25; if (isOutOfBounds()) { yCoordinate -= 25; } } }
7a5a7825-f80d-4cbf-ac37-a266ab1c6616
6
public static Config readDefaultArchive() throws ZipException, IOException, JSONException { loadNetworkShapes(); Config c = new Config(new JSONObject(new JSONTokener(new InputStreamReader(NetworkIO.class.getResourceAsStream("data/source.json"), "UTF-8")))); HashSet<String> taken = new HashSet<String>(); for (Config.Identifier identifier : c.identifiers) { if (identifier instanceof Config.NNIdentifier) { String name = getName(identifier, taken); Config.NNIdentifier id = (Config.NNIdentifier) identifier; for (int i = 0; i < id.numberOfNetworks; i++) { // qqDPS //FastLoadingNetwork fln = (id.classes.size() == 2 ? discriminatorTemplate : identifierTemplate).cloneWithSameShape(); FastLoadingNetwork fln = identifierTemplate.cloneWithSameShape(); fln.loadWeights(NetworkIO.class.getResourceAsStream("data/" + name + "_weights_" + i)); id.fastNetworks.add(fln); readTargets(id, NetworkIO.class.getResourceAsStream("data/" + name + "_targets_" + i)); } readRelativeSizeInfo(id, NetworkIO.class.getResourceAsStream("data/" + name + "_sizes.json")); readAspectRatioInfo(id, NetworkIO.class.getResourceAsStream("data/" + name + "_aspectRatios.json")); } if (identifier instanceof Config.NumberOfPartsIdentifier) { String name = getName(identifier, taken); Config.NumberOfPartsIdentifier id = (Config.NumberOfPartsIdentifier) identifier; readNumberOfPartsInfo(id, NetworkIO.class.getResourceAsStream("data/" + name + "_numberOfParts.json")); } if (identifier instanceof Config.TreeIdentifier) { String name = getName(identifier, taken); Config.TreeIdentifier id = (Config.TreeIdentifier) identifier; id.tree = TreePredict.readNode(new ObjectInputStream(NetworkIO.class.getResourceAsStream("data/" + name + "_tree"))); } if (identifier instanceof Config.NearestNeighbourIdentifier) { String name = getName(identifier, taken); Config.NearestNeighbourIdentifier id = (Config.NearestNeighbourIdentifier) identifier; id.comparisons = NearestNeighbour.read(new ObjectInputStream(NetworkIO.class.getResourceAsStream("data/" + name + "_comparisons"))); } } return c; }
e14744a4-2ba1-4180-a06a-432c40d5fc88
7
public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double) o).isInfinite() || ((Double) o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float) o).isInfinite() || ((Float) o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
3d1785e6-b836-4dc1-ae0b-483fe948a690
5
public Object[][] getData() { try { MCQ_DAO mcq_DAO = new MCQ_DAO(); FIB_DAO fib_DAO = new FIB_DAO(); Essay_DAO essay_DAO = new Essay_DAO(); //get question //get question ArrayList<MCQ> mcqs = mcq_DAO.getList("question_ID not in (select question_ID from QuestionsByExamID where Exam_ID='" + exam_ID + "') "); ArrayList<Object[]> objectArraylist = new ArrayList<Object[]>(); //store data into arraylist for (int i = 0; i < mcqs.size(); i++) { MCQ currentMcq = (MCQ) mcqs.get(i); Object[] col = new Object[4]; col[0] = currentMcq.getQuestion_ID(); col[1]= "MCQ"; col[2] = currentMcq.getQuestion_Text(); col[3] = false; objectArraylist.add(col); } ResultSet rs= fib_DAO.getList("questionID not in (select question_ID from QuestionsByExamID where Exam_ID='"+exam_ID+"') "); //store data into arraylist while (rs.next()) { Object[] col = new Object[4]; col[0] = rs.getInt(1); col[1] = "FIB"; col[2] = rs.getString(3); col[3] = false; objectArraylist.add(col); } rs= essay_DAO.getList("question_ID not in (select question_ID from QuestionsByExamID where Exam_ID='"+exam_ID+"') "); //store data into arraylist while (rs.next()) { Object[] col = new Object[4]; col[0] = rs.getInt(1); col[1] = "Essay"; col[2] = rs.getString(4); col[3] = false; objectArraylist.add(col); } //trun arraylist<object[]> to object[][] Object[][] datas = new Object[objectArraylist.size()][4]; for (int i = 0; i < objectArraylist.size(); i++) { datas[i] = objectArraylist.get(i); } return datas; } catch (SQLException ex) { Logger.getLogger(ChooseQuestionsPanel.class.getName()).log(Level.SEVERE, null, ex); } return null; }
e86960fa-9982-4a30-98c6-b5326c8eb507
1
private boolean isAuthenticated(HttpServletRequest paramHttpServletRequest) { Object result = paramHttpServletRequest.getSession().getAttribute(SESSION_ATTR_IS_AUTHENTICATED); if (result != null) { return (Boolean)result; } return false; }
305a3d9e-bde1-414f-8701-4e8a77457e7b
3
public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); System.out.println("Value of n is"+n); for (int count=0;count<n;count++){ for(int i=n-1;i>count;i--){ System.out.print(" "); } for(int j=0;j<=count;j++){ System.out.print("#"); } System.out.println(); } }
27e863e0-d897-4db9-9884-1b3e2f783fdc
3
public static void sortNumBubble(int[] num) { int j; boolean flag = true; // set flag to true to begin first pass int temp; //holding variable while(flag) { flag = false; //set flag to false awaiting a possible swap for(j = 0; j < num.length -1; j++ ) { if(num[j] < num[j + 1]) // change to > for ascending sort { temp = num[j]; //swap elements num[j] = num[j + 1]; num[j + 1] = temp; flag = true; //shows a swap occurred } } } }
cc03a970-0651-4fb4-93ec-31e3f862abe7
0
public static void main(String[] args) { HashMap map = new HashMap(); map.put("a","zhangsan"); map.put("b","zhangsan"); System.out.println(map); System.out.println("-------------"); String str = new String("lisi"); map.put("a",str); map.put("b",str); System.out.println(map); }
d6b7b0f7-c340-4c6e-9f99-b39f02d49040
3
public void focusGained(FocusEvent e) { JTextField textField = (JTextField)e.getComponent(); String text = textField.getText(); double value; try { NumberFormat format = NumberFormat.getInstance(Locale.getDefault()); Number number = format.parse(text.toString().trim()); value = number.doubleValue(); } catch (NumberFormatException ex) { return; } catch (ParseException m) { return; } if (value == 0) textField.selectAll(); }
6b4898a2-a9aa-40ad-bbef-0a275d122f33
7
public void startMinecraft(String player, String server, String mppass, int port, String skinServer, boolean fullscreen) { // Set up Minecraft instance MCraftApplet applet = new MCraftApplet(); MinecraftCanvas canvas = new MinecraftCanvas(); minecraft = new Minecraft(canvas, applet, fullscreen, false); if (player != null || server != null || mppass != null) { minecraft.session = new SessionData(player, "noidea"); minecraft.session.mppass = mppass; minecraft.session.haspaid = true; } minecraft.server = server; minecraft.port = port; if (skinServer != null) { minecraft.skinServer = skinServer; } // finish layout and center the frame canvas.setFocusable(true); canvas.setSize(getSize()); add(canvas, BorderLayout.CENTER); pack(); setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - getWidth()) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - getHeight()) / 2); // at least, show the game window! This starts the render loop. setVisible(true); // Idle the main thread until MC has shut down while (true) { if (!minecraft.isRunning) { minecraft.shutdown(); System.exit(0); } try { Thread.sleep(10); } catch (InterruptedException ex) { } } }
e61c4889-44f9-439d-bb41-4d9f04f756b3
2
public static void cleanUp() throws IncorrectUsageException { Throwable t = new Throwable(); StackTraceElement[] elements = t.getStackTrace(); String className = elements[1].getClassName(); String methodName = elements[1].getMethodName(); //@formatter:off if (!className.equals("com.blp.gfxlib.Game") || !methodName.equals("draw")) throw new IncorrectUsageException("method cleanUp called in " + className + " is used incorrectly"); //@formatter:on g.dispose(); }
45bdad02-b53b-4f34-a576-bbafc1e2fae2
7
@Override protected int drawUnselectedText(final Graphics g, int x, int y, int p0, int p1) throws BadLocationException { // Copied, with a few changes final Font boldFont = g.getFont().deriveFont(Font.BOLD); final Font plainFont = g.getFont().deriveFont(Font.PLAIN); final Document doc = getDocument(); Color last = null; Color fg; boolean bold = false; boolean lastBold = false; int mark = p0; while (p0 < p1) { updateScanner(p0); int p = Math.min(scanner.getEndOffset(), p1); p = (p <= p0) ? p1 : p; MutableAttributeSet style = styles.getStyle(scanner.lastToken(), scanner.lastStr()); fg = StyleConstants.getForeground(style); bold = StyleConstants.isBold(style); if ((fg != last && last != null) || (bold != lastBold)) { // color change, flush what we have g.setColor(last); g.setFont(lastBold ? boldFont : plainFont); Segment text = getLineBuffer(); doc.getText(mark, p0 - mark, text); x = Utilities.drawTabbedText(text, x, y, g, this, mark); mark = p0; } last = fg; lastBold = bold; p0 = p; } // flush remaining g.setColor(last); g.setFont(lastBold ? boldFont : plainFont); Segment text = getLineBuffer(); doc.getText(mark, p1 - mark, text); return Utilities.drawTabbedText(text, x, y, g, this, mark); }
02446fd4-2d0f-49c9-b410-f2675a1f4d88
1
public void dumpInstruction(TabbedPrintWriter writer) throws java.io.IOException { writer.print("return"); if (instr != null) { writer.print(" "); instr.dumpExpression(writer.IMPL_PAREN, writer); } writer.println(";"); }
a2bec378-830a-4897-bd6d-c5909b03a847
5
private static List<Temporal> generateTemporalSegments(Collection<Long> timestamps, Collection<Long> instances) { List<Temporal> segments = new ArrayList<Temporal>(); if (null == timestamps) return segments; if (null == instances) instances = new TreeSet<Long>(); int c = 0; long timeIntervalStart = 0; for (Long timestamp : timestamps) { if (c++ > 0) segments.add(new Temporal(timeIntervalStart, timestamp)); if (instances.contains(timestamp)) segments.add(new Temporal(timestamp, timestamp)); timeIntervalStart = timestamp; } return segments; }
3b1c6c30-b178-456c-8a29-7bd97c17e647
7
public static void registerDirectory(File directory) { // ensures that the specified File is a directory and that it isn't // currently registered if (directory.isDirectory() && !registeredDirectories.contains(directory)) { if (!running) start(); try { Path directoryPath = directory.toPath(); // the Path to the directory // the WatchKey that monitors this directory WatchKey watchKey = directoryPath.register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); // put the Path and WatchKey into a two-way mapping pathToWatchKey.put(directoryPath, watchKey); watchKeyToPath.put(watchKey, directoryPath); // add the directory to the list of registered directories, update // the user interface, and store the directory in the user's settings // so that the directory will automatically be registered the next // time the user starts the program registeredDirectories.add(directory); UserInterfaceManager.getSmartFolderFrame().getSmartFolderPanel().updateMonitoredDirectoriesTree(registeredDirectories); SettingsManager.updateSmartFolders(); // recursive step for (File child : directory.listFiles()) if (child.isFile()) ScanManager.pushFileForUpload(child, false); else if (child.isDirectory()) registerDirectory(child); } catch (IOException e) {} } }
f82f9fb0-86e1-4f4a-9991-ca7251785052
5
public boolean removeUser(String firstName, String lastName, String concordiaID){ int index = 0; for(ConcordiaMembers member: concordiaMembers){ if(member!=null){ if(member.getFirstName().equals(firstName) && member.getLastName().equals(lastName) && member.getConcordiaID().equals(concordiaID)){ concordiaMembers = ArrayUtils.remove(concordiaMembers, index); return true; } } index++; } return false; }
e5b87170-e3b6-4c67-903d-703a612d868b
0
@Override public Car driverCar() { return new BmwCar(); }
2f210b4c-6f5f-40dd-bcf5-32cdba4aa802
5
public Piece computeNextRotation() { // arraylist of TPoints to hold the rotated blocks TPoint[] rotatedPts = new TPoint[body.length]; for (int i = 0; i < body.length; i++) { int x = body[i].x; int y = body[i].y; // apply CC rotation matrix to [x, y] vector: R = [0 -1; 1 0] int x_p = x * 0 + y * (-1); int y_p = x * 1 + y * 0; TPoint rotdNotCorrctd = new TPoint(x_p, y_p); rotatedPts[i] = rotdNotCorrctd; } // we have now rotated the piece to quadrant II, so we must correct x values int xMin = 0; int yMin = 0; for (int i = 0; i < rotatedPts.length; i++) { int x = rotatedPts[i].x; int y = rotatedPts[i].y; if (x < xMin) xMin = x; if (y < yMin) yMin = y; } for (int i = 0; i < rotatedPts.length; i++) { rotatedPts[i].x += Math.abs(xMin); rotatedPts[i].y += Math.abs(yMin); } // construct new piece from the arrayList Piece rotdPiece = new Piece(rotatedPts); return rotdPiece; }
2375a973-3129-4b36-b388-84928e838b68
6
public static String getCoastlineCoding(Game game, Position center) { char[] coding = {'0','0','0','0' }; int row = center.getRow(), col = center.getColumn(); Position p; int offsetRow[] = { -1,0,+1,0 }; int offsetCol[] = { 0,+1,0,-1 }; // iterate over the four compas directions // for each find the proper tile p and // check if there is a coastline for ( int i = 0; i < 4; i++ ) { p = new Position( row+offsetRow[i], col+offsetCol[i]); if ( p.getRow() >= 0 && p.getRow() < GameConstants.WORLDSIZE && p.getColumn() >= 0 && p.getColumn() < GameConstants.WORLDSIZE && game.getTileAt(p).getTypeString() != GameConstants.OCEANS ) { coding[i] = '1'; } } String s = new String(coding); return s; }
8a720681-ffe0-4c02-8902-e26d02ff1bdd
7
public Object nextValue() throws JSONException { char c = this.nextClean(); String string; switch (c) { case '"': case '\'': return this.nextString(c); case '{': this.back(); return new JSONObject(this); case '[': this.back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = this.next(); } this.back(); string = sb.toString().trim(); if ("".equals(string)) { throw this.syntaxError("Missing value"); } return JSONObject.stringToValue(string); }
ea4bafb0-571b-40f0-a471-8e6f342eb3e4
9
public final static void evaluateStats() { logger.info( "[ " + System.currentTimeMillis() + " ] evaluating stats on " + stats.name + " ..." ) ; sentenceMap.entrySet().stream().parallel().map((entry) -> entry.getValue()).forEach((s) -> { final int _tokenCount = s.tokens.length; stats.wordCount += _tokenCount; for( int i = 0; i < _tokenCount; i++ ) { final String TAG = s.tags[ i ].toUpperCase(); if( TAG.equals( Tags.NOUN_SINGULAR ) || TAG.equals( Tags.NOUN_PLURAL ) ) { Noun _n = new Noun( s.tokens[ i ].toLowerCase() ) ; long _freq = stats.add( _n ); } else if( TAG.equals( Tags.VERB_BASE_FORM ) || TAG.equals( Tags.VERB_GERUND ) || TAG.equals( Tags.VERB_PAST_PARTICIPLE ) || TAG.equals( Tags.VERB_PAST_TENSE ) || TAG.equals( Tags.VERB_PRESENT_TENSE) || TAG.equals( Tags.VERB_PRESENT_TENSE_3RD_SINGULAR ) ) { Verb _v = new Verb( s.tokens[ i ].toLowerCase() ); long _freq = stats.add( _v ); } } }); logger.info( "[ " + System.currentTimeMillis() + " ] done evaluating stats" ); }
a79569be-bf9b-4cfe-86b2-bd558d92c791
6
@EventHandler(priority = EventPriority.HIGHEST) public void onBlockDamage(BlockDamageEvent event) { Sign sign; if (!event.isCancelled() && event.getBlock() != null && (event.getBlock().getType() == Material.WALL_SIGN || event .getBlock().getType() == Material.SIGN_POST)) { sign = (Sign) event.getBlock().getState(); if (sign.getLine(0).equals( "" + ChatColor.GRAY + ChatColor.BOLD + "[" + ChatColor.YELLOW + "ATM" + ChatColor.GRAY + "]") && !tgym.Vault.HasPermissions(event.getPlayer(), "tgym.atm.create")) event.setCancelled(true); } }
bbf22da2-9450-4d0b-a123-ae22b3c1f9ec
2
@Override public Visiteur getOne(Integer idVisiteur) throws DaoException { Visiteur result = null; ResultSet rs = null; // préparer la requête String requete = "SELECT * FROM VISITEUR WHERE ID_VISITEUR=?"; try { PreparedStatement ps = Jdbc.getInstance().getConnexion().prepareStatement(requete); ps.setInt(1, idVisiteur); rs = ps.executeQuery(); if (rs.next()) { result = chargerUnEnregistrement(rs); } } catch (SQLException ex) { throw new modele.dao.DaoException("DaoVisiteur::getOne : erreur requete SELECT : " + ex.getMessage()); } return (result); }
966ae784-e7c2-458e-b658-e539609008c2
5
public void drawMap() { for (int i = 0; i <= width; i++) { print(" _"); // boarder of map } print("\n"); for (int j = higth; j >= 0; j--) { print("|"); // boarder of map for (int i = 0; i <= width; i++) { if (nodes[i][j].isWalkable()) { print(" "); } else { print(" #"); // draw unwakable } } print("|\n"); // boarder of map } for (int i = 0; i <= width; i++) { print(" _"); // boarder of map } }
421ca73c-1ba5-4875-89c1-7cebb48f9f96
2
public User signup(String mail, String name, String username, String pass, String forumId) { for (int i = 0; i < forums.size(); i++) { if (forums.get(i).getId().equals(forumId)) return forums.get(i).signup(mail, name, username, pass); } return null; }
073e6292-9c4d-4eb1-a8bc-c8e0dbca145d
2
public static GUI getGUIById(String id){ for (GUI gui: Engine.getScreen().getGUILayer()){ if (gui.getId().equals(id)) return gui; } new RugieError(new Object(),"could not find a GUI with id: " + id + ", will return an empty gui").show(); return new GUI("ERROR_EMPTY",new Vector2f(0,0),new Vector2f(0,0)); }
1da79039-8fc4-4b03-964b-a6f58f5467bb
4
public boolean isTriangular(int[][] matrix){ for(int i = 0; i < matrix.length-1; i++){ for(int j = 0; j < matrix[0].length-1; j++){ if(i > j){ if(matrix[i][j] != 0){ return false; } } } } return true; }
11816308-ed16-40a2-8a9e-8f154acd3c7c
3
public double getTotal() { double ret = 0; if(items != null) for(Item i : items) ret += i.getCount() * i.getPrice(); return total == 0 ? ret : total; }
8d1f3432-0f89-4c15-a96f-b90b18b21a33
8
public void replaceBlocksForBiome(int par1, int par2, byte[] par3ArrayOfByte) { ChunkProviderEvent.ReplaceBiomeBlocks event = new ChunkProviderEvent.ReplaceBiomeBlocks( this, par1, par2, par3ArrayOfByte, null); MinecraftForge.EVENT_BUS.post(event); if (event.getResult() == Result.DENY) { return; } double d0 = 0.03125D; this.slowsandNoise = this.slowsandGravelNoiseGen.generateNoiseOctaves( this.slowsandNoise, par1 * 16, par2 * 16, 0, 16, 16, 1, d0, d0, 1.0D); this.gravelNoise = this.slowsandGravelNoiseGen.generateNoiseOctaves( this.gravelNoise, par1 * 16, 109, par2 * 16, 16, 1, 16, d0, 1.0D, d0); this.voidFabricExclusivityNoise = this.voidFabricExculsivityNoiseGen .generateNoiseOctaves(this.voidFabricExclusivityNoise, par1 * 16, par2 * 16, 0, 16, 16, 1, d0 * 2.0D, d0 * 2.0D, d0 * 2.0D); for (int k = 0; k < 16; ++k) { for (int l = 0; l < 16; ++l) { for (int k1 = 127; k1 >= 0; --k1) { int l1 = (l * 16 + k) * 128 + k1; if (k1 < 127 - this.hellRNG.nextInt(5) && k1 > 0 + this.hellRNG.nextInt(5)) { if (k1 < 121 - this.hellRNG.nextInt(5) && k1 > 11 + this.hellRNG.nextInt(3)) { // TODO ? add random patches of blocks } else { par3ArrayOfByte[l1] = (byte) VoidMod.hardenSpaceTimeStructure.blockID; } } else { par3ArrayOfByte[l1] = (byte) Block.bedrock.blockID; } } } } }
4ad377eb-a5f2-497a-a5c8-587d8476b961
8
public static String getPluginParams(String jarFileName) { String params = ""; try { JarFile jarFile = new JarFile(jarFileName); JarEntry je = jarFile.getJarEntry("plugin.conf"); InputStream in = jarFile.getInputStream(je); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { line = line.replaceAll("\\s+",""); if(line.contains("=")) { String[] sline = line.split("="); if((sline[0] != null) && (sline[1] != null)) { //phm.put(sline[0], sline[1]); if((sline[1].equals("required")) || sline[1].equals("optional")) { params = params + sline[0] + ":" + sline[1] + ","; } } } } reader.close(); in.close(); jarFile.close(); if(params.length() == 0) { params = null; } else { params = params.substring(0,params.length() -1); } } catch (IOException e) { params = null; e.printStackTrace(); } return params; }
13b67b92-0c33-4f3e-8447-2b0fdf576ddd
4
public void autonomousInit() { isAuton = true; //autonMode = (String) autoChooser.getSelected(); //postMode = (String) postChooser.getSelected(); // schedule the autonomous command (example) if (autonomousCommand != null && auton == "Left") autonomousCommand.start(); else if (secondAuton != null && auton == "Right") secondAuton.start(); }
a6a61748-d834-41fa-8b51-f15bcb883dca
3
public static void copyFromTopicQueueToTopicQueue(RabbitMQRequestParams rabbitMQRequestParams) throws Exception { RabbitMQTopicQueueConsumer consumer = new RabbitMQTopicQueueConsumer( rabbitMQRequestParams.getSourceHost(), rabbitMQRequestParams.getSourcePort() , rabbitMQRequestParams.getSourceUsername(), rabbitMQRequestParams.getSourcePassword() , rabbitMQRequestParams.getSourceVirtualHost(),rabbitMQRequestParams.getSourceExchange(), rabbitMQRequestParams.getSourceRoutingKey(), rabbitMQRequestParams.getSourceQueue() ); RabbitMQTopicQueueProducer producer = new RabbitMQTopicQueueProducer( rabbitMQRequestParams.getDestinationHost(), rabbitMQRequestParams.getDestinationPort() , rabbitMQRequestParams.getDestinationUsername(), rabbitMQRequestParams.getDestinationPassword() , rabbitMQRequestParams.getDestinationVirtualHost(), rabbitMQRequestParams.getDestinationExchange() , rabbitMQRequestParams.getDestinationQueue() ); List<Message> messages = consumer.consumeMulti(rabbitMQRequestParams.getNumber(), rabbitMQRequestParams.getRequeue()); if (messages != null && ! messages.isEmpty()) { for(Message message : messages) { producer.produce(message); } } }
652d67d8-6ccb-46ca-9f76-b58a18c3e122
3
private boolean isCellOutOfField (Point adjoiningCell) { return adjoiningCell.x < 0 || adjoiningCell.y < 0 || adjoiningCell.x >= width || adjoiningCell.y >= height; }
9481c2c2-4ebb-484d-9246-27818c751866
3
private CtBehavior compileMethod(Parser p, MethodDecl md) throws CompileError { int mod = MemberResolver.getModifiers(md.getModifiers()); CtClass[] plist = gen.makeParamList(md); CtClass[] tlist = gen.makeThrowsList(md); recordParams(plist, Modifier.isStatic(mod)); md = p.parseMethod2(stable, md); try { if (md.isConstructor()) { CtConstructor cons = new CtConstructor(plist, gen.getThisClass()); cons.setModifiers(mod); md.accept(gen); cons.getMethodInfo().setCodeAttribute( bytecode.toCodeAttribute()); cons.setExceptionTypes(tlist); return cons; } else { Declarator r = md.getReturn(); CtClass rtype = gen.resolver.lookupClass(r); recordReturnType(rtype, false); CtMethod method = new CtMethod(rtype, r.getVariable().get(), plist, gen.getThisClass()); method.setModifiers(mod); gen.setThisMethod(method); md.accept(gen); if (md.getBody() != null) method.getMethodInfo().setCodeAttribute( bytecode.toCodeAttribute()); else method.setModifiers(mod | Modifier.ABSTRACT); method.setExceptionTypes(tlist); return method; } } catch (NotFoundException e) { throw new CompileError(e.toString()); } }
d700ae2f-a1e0-453d-9457-c3844634f1dd
7
public Hashtable<String,Neo4jCluster> perform(DatasetLoader datasetHandler, Neo4jHandler neo4jHandler, double similairtyThreshold, int softClusteringThreshold) throws Exception { Hashtable<String,Neo4jCluster> clustersList = new Hashtable<String,Neo4jCluster>(); Hashtable<String, Document> docsHash = datasetHandler.loadDocuments(); DDSimIF similarityCalculator = new DDSimilairty(); Enumeration e = docsHash.keys(); int numberOfClusters = 0; //loop for documents in the dataset while (e.hasMoreElements()) { Hashtable<String, Double> candidateClustersHash = new Hashtable<String, Double>(); String documentID = (String) e.nextElement(); System.out.println("Processing document "+ documentID); Document document = docsHash.get(documentID); Neo4jDocument neo4jDocument = neo4jHandler.loadDocument(document); boolean clusteredYet = false; // get similar documents to the document ArrayList<Neo4jDocument> similarDocuments = getSimilarDocuments(neo4jDocument, neo4jHandler, datasetHandler); // loop over the similar documents for (Iterator iterator = similarDocuments.iterator(); iterator.hasNext();) { Neo4jDocument neo4jSimilarDocument = (Neo4jDocument) iterator.next(); // continue if the current similar document has no clusters if(neo4jSimilarDocument.getClustersHash().isEmpty()) continue; // check if the distance to the document is greater than the threshold if(similarityCalculator.calculateSimilarity(neo4jDocument, neo4jSimilarDocument, datasetHandler.numberOfDocuments()) > similairtyThreshold ){ //get the clusters of the similar document ArrayList<String> candidateDocumentClustersIDs = neo4jSimilarDocument.getClusterIDsList(); // loop over the clusters of the similar document for (Iterator iterator2 = candidateDocumentClustersIDs.iterator(); iterator2.hasNext();) { //loop for candidate clusters String candidateClusterID = (String) iterator2.next(); // get the cluster Neo4jCluster candidateNeo4jCluster = clustersList.get(candidateClusterID); // calculate the average similarity to the cluster double averageSimilairtyToCluster = calculateAvgSimilairtyToCluster(neo4jDocument, candidateNeo4jCluster, datasetHandler, neo4jHandler); // if the average similarity greater the the threshold then the cluster to the candidate clusters if(averageSimilairtyToCluster > similairtyThreshold){ clusteredYet = true; candidateClustersHash.put(candidateClusterID, averageSimilairtyToCluster); }// end if adding cluster to candidate cluster hash }//end loop for candidate clusters }//end if [checking if the distance to the candidate document is less than the threshold] }//end looping for similar documents if(!clusteredYet){ // create new cluster numberOfClusters++; Neo4jCluster newCluster = new Neo4jCluster(String.valueOf(numberOfClusters)); newCluster.addDcoument(documentID); neo4jDocument.addCluster(newCluster.getId(), 1); clustersList.put(newCluster.getId(), newCluster); }else{ // add to the cloeset cluster String nearestClusterID = getNearestCluster(candidateClustersHash); Neo4jCluster cluster = clustersList.get(nearestClusterID); cluster.addDcoument(neo4jDocument.getDocumentID()); neo4jDocument.addCluster(nearestClusterID, 1); } } // end loop for all documents in the data set return clustersList; }
a3ecb4ad-d673-47bc-8167-b6087f66deb9
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (Double.doubleToLongBits(height) != Double .doubleToLongBits(other.height)) return false; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
485bff8d-8abc-46ce-8a72-c2734d2eca4b
6
public AddFile(java.awt.Frame parent, FileEntry curr, String currVersion, List<String> versions, String currCategory) { super(parent); initComponents(); if(curr!=null) { setTitle("Edit Entry"); jButton2.setText("OK"); item = curr; jTextField1.setText(item.file.getPath()); jTextField2.setText(item.dest); for(int i=0; i<jComboBox1.getItemCount(); i++) { String cat = ((String) jComboBox1.getItemAt(i)).toLowerCase().replaceAll(" ", "_"); if(cat.equals(curr.category)) { jComboBox1.setSelectedIndex(i); break; } } } else { for(int i=0; i<jComboBox1.getItemCount(); i++) { String cat = ((String) jComboBox1.getItemAt(i)).toLowerCase().replaceAll(" ", "_"); if(cat.equals(currCategory)) { jComboBox1.setSelectedIndex(i); break; } } item = new FileEntry(); } version = currVersion; for(int i=0; i<versions.size(); i++) { jComboBox2.addItem("webOS " + versions.get(i)); } jComboBox2.setSelectedItem("webOS " + version); getContentPane().requestFocus(); }
c0764df7-ad5f-4f5a-9e76-ac12a4f2d79e
6
public static HashMap<String, HashMap<String, Integer>> getMap(String filePath) throws Exception { HashMap<String, HashMap<String, Integer>> map = new HashMap<String, HashMap<String,Integer>>(); BufferedReader reader = filePath.toLowerCase().endsWith("gz") ? new BufferedReader(new InputStreamReader( new GZIPInputStream( new FileInputStream( filePath)))) : new BufferedReader(new FileReader(new File(filePath ))); String nextLine = reader.readLine(); int numDone =0; while(nextLine != null) { StringTokenizer sToken = new StringTokenizer(nextLine, "\t"); String sample = sToken.nextToken().replace(".fastatoRDP.txt.gz", ""); String taxa= sToken.nextToken(); int count = Integer.parseInt(sToken.nextToken()); if( sToken.hasMoreTokens()) throw new Exception("No"); HashMap<String, Integer> innerMap = map.get(sample); if( innerMap == null) { innerMap = new HashMap<String, Integer>(); map.put(sample, innerMap); } if( innerMap.containsKey(taxa)) throw new Exception("parsing error " + taxa); innerMap.put(taxa, count); nextLine = reader.readLine(); numDone++; if( numDone % 1000000 == 0 ) System.out.println(numDone); } return map; }
655ab9a8-59c0-41ab-b86e-9860ef4e93a9
2
@Override public void findClasses() { try { InputStream inputStream = new FileInputStream(classFile); byte[] buffer = new byte[1024]; int count; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); while ((count = inputStream.read(buffer)) != -1) byteArrayOutputStream.write(buffer, 0 , count); inputStream.close(); ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader( byteArrayOutputStream.toByteArray()); classReader.accept(classNode, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); classes.put(classNode.name.replace(".class", ""), classNode); } catch (IOException e) { e.printStackTrace(); } }
fa05a5f7-ba40-4dad-a021-1d8ec7155a52
8
public static Object escape(Object original) { if (original instanceof Character) { char u = (char) ((Character)original); int idx = "\b\t\n\f\r\"\'\\".indexOf(u); if (idx >= 0) return "\\"+"btnfr\"\'\\".charAt(idx); if (u < 32) return "\\"+Integer.toOctalString(u); if (u > 126) return "\\u"+String.format("%04X", (int)u); return original; } else if (original instanceof String) { StringBuilder result = new StringBuilder(); for (char c : ((String)original).toCharArray()) result.append(escape(c)); return "\"" + result.toString() + "\""; } else if (original.getClass().isArray()) { StringBuilder result = new StringBuilder("["); int len = Array.getLength(original); for (int i=0; i<len; i++) result.append(" ").append(escape(Array.get(original, i))); return result.append("]").toString(); } return original; }
f058d73c-493a-4252-972c-37a8dd0e35d2
9
private boolean checkPropertyFile(File propertieFile) { boolean properFileFlag = true; Properties props = new Properties(); String reqKey = ""; boolean foundConversionPattern=false; try { FileInputStream fis = new FileInputStream(propertieFile); // read the property file props.load(fis); // getting key set from file, saving key set for later iteration NewJFrame.propKeySet = props.keySet(); // if file don't begin with log4j standard key format return false if(! ( propKeySet.toArray()[0].toString().toLowerCase().contains("log4j") ) ){ System.out.println(propKeySet.toArray()[0].toString()); return false; } System.out.println("whle key set :: "+propKeySet.toString()); String fileAppenderrKey=""; // first iteration through property file to get req. key for (Iterator iterator1 = propKeySet.iterator(); iterator1 .hasNext();) { String key = (String) iterator1.next(); if (props.getProperty(key).toLowerCase().endsWith("fileappender")) { System.out.println("in fileappedner>> " + key); fileAppenderrKey = key; // System.out.println("prop chcek>> " + props.getProperty(key + ".File")); // // if (props.getProperty(key + ".File").toLowerCase() // .endsWith(logFileName)) { // System.out.println("Got required key, breaking >>" + key); // reqKey = key; // foundReqKeyFlag = true; // break; // } } if(key.equalsIgnoreCase(fileAppenderrKey+".layout.conversionPattern")) { System.out.println("key>> "+key); conversionPattern = props.getProperty(key); System.out.println("req. conversion pattern is " + conversionPattern); foundConversionPattern=true; } } // method return if conversion pattern is found, if not probably key's not properly ordered if(foundConversionPattern){ return true; } // second iteration to get conversion pattern for (Iterator iterator2 = NewJFrame.propKeySet.iterator(); iterator2.hasNext();) { String key = (String) iterator2.next(); System.out.println(key + "<< >>" + props.getProperty(key)); if (key.startsWith(reqKey) && key.toLowerCase().contains((".layout.conversionpattern"))) { // System.out.println(object1); conversionPattern = props.getProperty(key); System.out.println("req. conversion pattern is " + conversionPattern); properFileFlag = true; break; } } // very essential close of input stream. fis.close(); } catch (IOException e) { e.printStackTrace(); } return properFileFlag; }
6d3a6e09-8fa2-46f1-8a23-5bf3fc7ab5b0
6
@Override public Object getValueAt(int row, int col) { User user = (User) globalData.get(row); switch (col) { case INDEX_ID: return user.getID(); case INDEX_FIRSTNAME: return user.getFirstName(); case INDEX_LASTNAME: return user.getLastName(); case INDEX_POINTS: return user.getPoints(); case INDEX_WEEKLY_PICK: return user.getWeeklyPick(); case INDEX_ULT_PICK: return user.getUltimatePick(); default: return null; } }
08e53460-f080-4e02-8458-1a9a711e37c2
7
public String iterativeWay(String[] strs) { if (strs == null || strs.length == 0) return ""; StringBuilder result = new StringBuilder(); int index = 0; while (true) { if (strs[0].length() <= index) break; char global = strs[0].charAt(index); for (int i = 1; i < strs.length; i++) { String current = strs[i]; if (current.length() <= index || current.charAt(index) != global) { return result.toString(); } } index++; result.append(global); } return result.toString(); }
ae402005-2de5-4233-b459-e2d6a5c74d34
3
public JSONObject putOnce(String key, Object value) throws JSONException { if (key != null && value != null) { if (opt(key) != null) { throw new JSONException("Duplicate key \"" + key + "\""); } put(key, value); } return this; }
bdb908d9-2d59-484f-ab21-265b343cae08
8
public static boolean startsWithIgnoreCase(String s,String w) { if (w==null) return true; if (s==null || s.length()<w.length()) return false; for (int i=0;i<w.length();i++) { char c1=s.charAt(i); char c2=w.charAt(i); if (c1!=c2) { if (c1<=127) c1=lowercases[c1]; if (c2<=127) c2=lowercases[c2]; if (c1!=c2) return false; } } return true; }
5379432c-0882-4299-bc8d-396eba507b68
4
@EventHandler(priority = EventPriority.HIGHEST) private void onAdministratorCommand(PlayerCommandPreprocessEvent e) { Player sender = (Player) e.getPlayer(); if (isOpen()) { String cmd = e.getMessage().toLowerCase(); if (cmd.startsWith("/stop")) { sender.sendMessage(getMessage(sender, "/stop", "Message5")); e.setCancelled(true); } if (cmd.startsWith("/reload")) { sender.sendMessage(getMessage(sender, "/reload", "Message5")); e.setCancelled(true); } if (cmd.startsWith("/kickall")) { sender.sendMessage(getMessage(sender, "/kickall", "Message5")); e.setCancelled(true); } } }
5c100f5b-ad6f-4912-a878-ca39100b1b78
0
public void resetId() { quizTriggerId=0; }
c59d0547-0686-43e2-90f9-3fdda54f513f
3
private int[] getNeighborsFor(AsciiImage img, int x, int y) { int[] neighbours = new int[9]; int current = 0; --x; --y; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (!img.isInsideBounds(x + i, y + j)) neighbours[current++] = brightest(); else neighbours[current++] = getValueOf(img.getPixel(x + i, y + j)); } } assert current == 9; Arrays.sort(neighbours); return neighbours; }
6071c63b-5623-4d23-89ff-ff3b8f7debbc
9
static double[] train(int steps) { Random rand = new Random(); double[] w = new double[28 * 28]; for (int step = 0; step < steps;) { step++; while(test(w)>0.1){ int r = rand.nextInt(5000); double[] x = I.get(r).vec; double z = 0; for(int i=0; i<x.length; i++){ z+=w[i]*x[i]; } if(z>=0 && I.get(r).characterClass==oppositeChar){ for(int n=0; n<w.length; n++){ w[n]=w[n]-x[n]; } } if(z<0 && I.get(r).characterClass==targetChar){ for(int n=0; n<w.length; n++){ w[n]=w[n]+x[n]; } } } } return w; }
d473561a-9ac0-44fc-a558-ddeea24cf7c1
3
@Test public void testRemoveAllPreferencesClient() { List<Product> productAux = null; Product book = new Product("Book", 1234, 2.30, 100); Product table = new Product("Table", 4321, 3.00, 100); facade.addProduct(book); facade.addProduct(table); Client client1 = new Client("Diego", "111", "diego.sousa@dce.ufpb.br", 18, 11, 1988); facade.addClient(client1); facade.addPreferencesClient(client1, book); facade.addPreferencesClient(client1, table); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } facade.getListProductPreferredClient(takerProductPreferredClient, client1); try { productAux = takerProductPreferredClient.take(); } catch (InterruptedException e) { e.printStackTrace(); } assertTrue(productAux.contains(book)); assertEquals(2, productAux.size()); facade.removeAllPreferencesClient(client1); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } facade.getListProductPreferredAllClients(copyAllClientsPreferences); assertFalse(copyAllClientsPreferences.contains(client1)); assertEquals(0, copyAllClientsPreferences.size()); }
aa02f941-16f7-44ba-bae1-50b37a5f5c79
6
private Token matchNumber() { SourcePosition pos = new SourcePosition(lineNo, columnNo); StringBuilder sb = new StringBuilder(); boolean decimal = false; int character = lookAhead(1); while ((character >= '0' && character <= '9') || character == '.') { if (decimal && character == '.') { throw new LexerException("Unexcepted '.' character", lineNo, columnNo); } else if (character == '.') { decimal = true; } sb.append((char) character); character = next(); } return new Token(pos, TokenType.NUMBER, sb.toString()); }
29adbca0-18e8-4d89-98d3-00f3beb9fb5c
8
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; if(target.fetchEffect(ID())!=null) { mob.tell(target,null,null,L("<S-NAME> already <S-HAS-HAVE> protection from poison.")); 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,verbalCastCode(mob,target,auto),auto?L("<T-NAME> attain(s) a anitidotal protection."):L("^S<S-NAME> @x1 for protection from poisons.^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } } else return beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 for protection from poisons, but go(es) unanswered.",prayWord(mob))); // return whether it worked return success; }
9140d798-07e1-42ed-8bb9-0d35ed65813a
7
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked if(jButton3.isEnabled()){ jButton3.setEnabled(false); if(evt.getButton() == 1){ System.out.println("im clicked"); try{ System.out.println("im running"); Socket s; //Scanner scan = new Scanner(Inet4Address.getLocalHost().getHostAddress()); DefaultListModel listModel = new DefaultListModel(); //String ip = scan.next("\\d{1,3}"); for(int x=0;x<255;x++) for(int y=0;y<255;y++) for(int z=0;z<255;z++) for(int p=0;p<65536;p++){ System.out.println("socket"); //s = new Socket(("10"+"."+x+"."+y+"."+z), p); s = new Socket("10.4.34.148", p); System.out.println("Scan: "+("10"+"."+x+"."+y+"."+z)+p); listModel.addElement(("10"+"."+x+"."+y+"."+z+":"+p)); s.close(); } jList1.setModel(listModel); } catch (IOException ex) { } } } }//GEN-LAST:event_jButton3MouseClicked
697b5a27-4549-4df1-959b-4d9e3f7e1b77
9
public static HashMap login(String userID, String password) { MessageLogger.logSecurityLoggingMessage(userID + " : LoginService -> login \r\n"); HashMap map = new HashMap(); String message = null; try{ Timestamp currdateTime = new Timestamp(Calendar.getInstance().getTime().getTime()); // for demo purpose /* AdmTO admTO = null; if (userID.equalsIgnoreCase("ADMIN")){ admTO = new AdmTO(); admTO.setRole("ADM"); }else { admTO = new AdmTO(); admTO.setRole("USR"); } */ // end demo AdmTO admTO = SecurityManager.getInstance().login(userID, password, currdateTime, currdateTime); MessageLogger.logSecurityLoggingMessage(userID + " : LoginService -> Successful Login \r\n"); map.put(Constants.ADMIN, admTO); return map; } catch (UserIDEmptyException e) { message = e.getMessage(); e.printStackTrace(); } catch (PasswordEmptyException e) { message = e.getMessage(); e.printStackTrace(); } catch (InvalidUserIDException e) { message = e.getMessage(); e.printStackTrace(); } catch (InvalidPasswordException e) { message = e.getMessage(); e.printStackTrace(); } catch (NoAccessException e) { message = e.getMessage(); e.printStackTrace(); } catch (UserIDDisabledException e) { message = e.getMessage(); e.printStackTrace(); } catch (NoActiveUserException e) { message = e.getMessage(); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); message = Messages.SYSTEM_UNABLE_PROCESS_YOUR_REQUEST; } if(message != null){ MessageLogger.logSecurityLoggingMessage(userID + " : " + message +"\r\n"); } map.put(Constants.MESSAGE_ID, message); map.put(SysConstants.URL_REDIRECT, ""); return map; }
d786cf38-00f0-41d2-94d9-887a2b25e4aa
6
private boolean checkField() { IPlayer player = game.getCurrentPlayer(); IField field = game.getMap().getField(player.getCoordinates()); if (field == null) { return false; } if (field.getZombie() != null) { game.setState(new FightState(window)); return true; } if (game.checkWin()) { window.setMenu(new WinnerMenu(window, game)); return true; } if (field.hasAmmo()) { player.setAmmo(player.getAmmo() + 1); game.update(Update.PlayerAttributeUpdate); field.setAmmo(false); } if (field.hasLife() && player.getLives() < Game.MAX_LIVES) { player.setLives(player.getLives() + 1); game.update(Update.PlayerAttributeUpdate); field.setLife(false); } return false; }
b087279b-2bb7-49d3-a974-192f22d73990
8
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed String type = txtFieldType.getText(); lblError.setText(""); boolean dbResult = false; int capacity = -1; int planeNumber = -1; String ErrorMessage = ""; type.trim(); if (type.isEmpty()) { ErrorMessage += "No type entered \n"; } if (txtFieldCapacity.getText().isEmpty()) { ErrorMessage += "no Capacity entered \n"; } else { try { capacity = Integer.parseInt(txtFieldCapacity.getText()); } catch (NumberFormatException nfe) { ErrorMessage += "Capacity issn't a number \n"; } } if (txtFieldNumber.getText().isEmpty()) { ErrorMessage += "no number entered \n"; } else { try { planeNumber = Integer.parseInt(txtFieldNumber.getText()); } catch (NumberFormatException nfe) { ErrorMessage += "plane number isn't a number \n"; } } if (ErrorMessage.isEmpty()) { if (plane == null) { plane = new Plane(); plane.setNumber(planeNumber); plane.setType(type); plane.setCapacity(capacity); dbResult = Controller.Controller.Instance().save((plane)); } else { plane.setNumber(planeNumber); plane.setType(type); plane.setCapacity(capacity); dbResult = Controller.Controller.Instance().update(plane); } if (dbResult) { JOptionPane.showMessageDialog(this, "Plane saved"); this.dispose(); } else { JOptionPane.showMessageDialog(this, "Error while saving plane!"); } } lblError.setText(ErrorMessage); }//GEN-LAST:event_btnSaveActionPerformed
fa01a3be-be94-4358-9d8f-19d858b4b0f2
7
private void initialize() { frmSearchEngine = new JFrame(); frmSearchEngine.setTitle("Search Engine"); frmSearchEngine.setBounds(100, 100, 550, 500); frmSearchEngine.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0}; gridBagLayout.columnWeights = new double[]{1.0}; frmSearchEngine.getContentPane().setLayout(gridBagLayout); // Create a new panel and add a new JLabel JPanel panel = new JPanel(); panel.add(new JLabel("ENTER SEARCH TERMS BELOW")); // Create a new GBC Panel and add it to the content pane GridBagConstraints gbc_panel = new GridBagConstraints(); gbc_panel.insets = new Insets(0, 0, 5, 0); gbc_panel.gridx = 0; gbc_panel.gridy = 0; frmSearchEngine.getContentPane().add(panel, gbc_panel); // Create a new text field for searching textField = new JTextField(); GridBagConstraints gbc_textField = new GridBagConstraints(); gbc_textField.insets = new Insets(0, 0, 5, 0); gbc_textField.fill = GridBagConstraints.HORIZONTAL; gbc_textField.gridx = 0; gbc_textField.gridy = 1; frmSearchEngine.getContentPane().add(textField, gbc_textField); textField.setColumns(10); // Combo box options String[] comboOpts = { "ALL search terms", "ANY search terms", "EXACT phrase" }; // Create and add the combo box final JComboBox comboBox = new JComboBox(comboOpts); GridBagConstraints gbc_comboBox = new GridBagConstraints(); gbc_comboBox.insets = new Insets(0, 0, 5, 0); gbc_comboBox.fill = GridBagConstraints.HORIZONTAL; gbc_comboBox.gridx = 0; gbc_comboBox.gridy = 2; frmSearchEngine.getContentPane().add(comboBox, gbc_comboBox); // Add a new button to the GBC layout JButton btnSearch = new JButton("Search"); GridBagConstraints gbc_btnSearch = new GridBagConstraints(); gbc_btnSearch.insets = new Insets(0, 0, 5, 0); gbc_btnSearch.gridx = 0; gbc_btnSearch.gridy = 3; frmSearchEngine.getContentPane().add(btnSearch, gbc_btnSearch); // New Search results label JLabel lblSearchResults = new JLabel("Search Results"); GridBagConstraints gbc_lblSearchResults = new GridBagConstraints(); gbc_lblSearchResults.insets = new Insets(0, 0, 5, 0); gbc_lblSearchResults.gridx = 0; gbc_lblSearchResults.gridy = 4; frmSearchEngine.getContentPane().add(lblSearchResults, gbc_lblSearchResults); // Column names for our JTable String[] headerNames = { "Filename", "Position" }; // Create our new table and table headers @SuppressWarnings("serial") final DefaultTableModel model = new DefaultTableModel(null, headerNames){ // Override to make the cells not editable @Override public boolean isCellEditable(int row, int column) { return false; } }; // New JTable table = new JTable(model); JTableHeader header = table.getTableHeader(); header.setBackground(Color.yellow); // New JScrollPane to hold our JTable JScrollPane scrollPane = new JScrollPane(table); GridBagConstraints gbc_scrollPane = new GridBagConstraints(); gbc_scrollPane.fill = GridBagConstraints.BOTH; gbc_scrollPane.gridx = 0; gbc_scrollPane.gridy = 5; frmSearchEngine.getContentPane().add(scrollPane, gbc_scrollPane); // Search button action performed method btnSearch.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // clear JTable before new search model.setRowCount(0); // clean input of unnecessary whitespace String input = textField.getText().replaceAll("\\s+", " ").trim(); // multiple words split by single whitespace String[] keys = input.split(" "); // check if file index is empty or no search terms entered if (FileIndex.fileIndexed.isEmpty()) { AddRemoveFileGUI.AlertWindow("No files in index."); } else if (input.length() == 0 ) { AddRemoveFileGUI.AlertWindow("No search terms entered."); } else { // type of search selected in comboBox (ALL, ANY, EXACT) int sel = comboBox.getSelectedIndex(); // ALL search if (sel == 0) { InvertedIndex.getInstance().termsInDoc(keys); } // ANY search else if (sel == 1) { for (String k : keys) { InvertedIndex.getInstance().AddToTable(k); InvertedIndex.getInstance().searchIndex(k); } } // EXACT Phrase search else { if (keys.length > 1) { InvertedIndex.getInstance().exactSearch(keys); } else { InvertedIndex.getInstance().AddToTable(keys[0]); InvertedIndex.getInstance().searchIndex(keys[0]); } } } } }); // Add a JMenuBar JMenuBar menuBar = new JMenuBar(); frmSearchEngine.setJMenuBar(menuBar); // Add a file menu option to the JMenuBar JMenu mnFile = new JMenu("File"); menuBar.add(mnFile); // Add a menu option for adding and removing files JMenuItem mntmAddremoveFile = new JMenuItem("Add/Remove File"); mnFile.add(mntmAddremoveFile); mntmAddremoveFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Call the AddRemoveFileGUI main method to show // the new application window for adding and removing files AddRemoveFileGUI.main(null); } }); // Add a menu option for the about dialog JMenuItem mntmAbout = new JMenuItem("About"); menuBar.add(mntmAbout); mntmAbout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Show the about dialog when the menu option is clicked aboutDialog(); } }); // Set the file index list FileIndex.SetFileIndexed(); // Load initial Inverted Index try { InvertedIndex.getInstance().loadIndex(FileIndex.fileIndexed); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
8c6270fc-2b46-4ede-bcf6-7b58d45e9c2f
2
@Override public void mouseMoved (MouseEvent e) { if (index != -1) { int newIndex = locationToIndex (e.getPoint()); if (newIndex != index) { setIndexHovered (index, false); index = newIndex; setIndexHovered (index, true); } } }
45475eee-e165-4d2a-b18f-ceadc155358c
7
private static String escapeChar(char input, char usedQuote) { if (input == usedQuote) return "\\" + usedQuote; switch (input) { case '\\': return "\\\\"; case '\b': return "\\b"; case '\f': return "\\f"; case '\n': return "\\n"; case '\r': return "\\r"; case '\t': return "\\t"; default: // TODO Allow the user to set a flag which generates a \\uXXXX // sequence for non standard characters return "" + input; } }
bdba7991-3f16-4704-8a9d-13c8fd484122
8
public void sendText(String text){ try { if(this.sendAllJson){ if(text.length() >= 3 && text.substring(0, 3).equals("ERR")){ text = "{\"ok\":false,\"message\":\"" + text + "\"}"; } else if(text.equals("Welcome to Bukkit, please authenticate.")){ text = "{\"ready_for_auth\":true}"; } else if(text.equals("Authenticated!")){ text = "{\"authed\":true}"; } else if(text.equals("OK")){ text = "{\"ok\":true}"; } else if(text.substring(0, 1).equals("{") == false){ text = "{\"message\":\"" + text + "\"}"; } } this.outToClient.writeBytes(text + "\r\n"); Misc.println("[Socket] Sent: \"" + text + "\" to " + ThreadID + "."); } catch (IOException e) { Misc.servere(e.toString()); } }
606c2637-6934-448a-884b-b3e9a036df29
1
private void createConfigs(){ if(!jobsfile.exists()){ this.saveResource("jobs.yml", false); } saveDefaultConfig(); }
dbc7297e-1707-437b-adfe-43321977aade
0
public void setPersonId(int personId) { this.personId = personId; }
537b38df-e863-40d3-8ae1-4c22ed3f4168
2
private void linearize_recursive(ArrayList<LUSTree> seq, boolean use_combos){ if (card != 0){ //If getting all combinations, recurse without adding if (use_combos) linearize_recursive_single(new ArrayList(seq), use_combos); seq.add(this); } linearize_recursive_single(seq, use_combos); }
74653806-f0c6-4f56-8da9-2008a4d9b55a
0
@Test public void addingEdgesWorks() { Vertex a = new Vertex(0); Vertex b = new Vertex(1); Edge e = new Edge(a, b); g.addVertex(a); g.addVertex(b); g.addEdge(a, b, 1); assertTrue(g.getEdges().get(0).equals(e)); }
fd1636de-bcd5-47ff-bea9-54dc76e826c8
8
private static <T extends Comparable<? super T>> void quicksort(T[] a, int lo, int hi) { if (hi <= lo) return; int i = lo; int j = hi; T partitionItem = a[lo + (hi-lo)/2]; while (i<=j) { while (isLess(a[i], partitionItem)) i++; while (isLess(partitionItem, a[j])) j--; if (i <= j) { exchange(a, i, j); i++;j--; } } if (lo<j)quicksort(a, lo, j); if (i<hi)quicksort(a, j + 1, hi); }
6f64e8ff-a290-4de7-a1ba-0ad3ef1226c3
4
public boolean search(File file) { try { Scanner in = new Scanner(new FileInputStream(file)); boolean found = false; while (!found && in.hasNextLine()) { String line = in.nextLine(); if (line.contains(keyword)) found = true; } in.close(); return found; } catch (IOException e) { return false; } }
e7f7dbe4-44eb-4184-b126-636d7642e273
0
public static void main (String[] arg) { // start server on port 1500 new GameServer (1500); }
451feea8-84e5-46cd-b8ed-1d182e967040
8
public void accounts(MOB mob, List<String> commands) throws IOException { mob.location().showOthers(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> wave(s) <S-HIS-HER> hands around the heavens.")); PlayerAccount theAccount = null; String oldName = null; if(commands.size()==2) { theAccount=mob.playerStats().getAccount(); oldName=theAccount.getAccountName(); CMLib.genEd().modifyAccount(mob,theAccount,-1); } else if(commands.size()<3) { mob.tell(L("You have failed to specify the proper fields.\n\rThe format is MODIFY ACCOUNT ([NAME])\n\r")); mob.location().showOthers(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> flub(s) a powerful spell.")); return; } else { final String accountName=CMStrings.capitalizeAndLower(CMParms.combine(commands, 2)); theAccount = CMLib.players().getLoadAccount(accountName); if(theAccount==null) { mob.tell(L("There is no account called '@x1'!\n\r",accountName)); mob.location().showOthers(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> flub(s) a powerful spell.")); return; } oldName=theAccount.getAccountName(); CMLib.genEd().modifyAccount(mob,theAccount,-1); mob.location().recoverRoomStats(); } Log.sysOut("Modify",mob.Name()+" modified account "+theAccount.getAccountName()+"."); if(!oldName.equals(theAccount.getAccountName())) { final Vector<MOB> V=new Vector<MOB>(); for(final Enumeration<String> es=theAccount.getPlayers();es.hasMoreElements();) { final String playerName=es.nextElement(); final MOB playerM=CMLib.players().getLoadPlayer(playerName); if((playerM!=null)&&(!CMLib.flags().isInTheGame(playerM,true))) V.add(playerM); } final PlayerAccount acc = (PlayerAccount)CMClass.getCommon("DefaultPlayerAccount"); acc.setAccountName(oldName); CMLib.database().DBDeleteAccount(acc); CMLib.database().DBCreateAccount(theAccount); for(final MOB playerM : V) CMLib.database().DBUpdatePlayerPlayerStats(playerM); } CMLib.database().DBUpdateAccount(theAccount); }
bb2e2fb8-7226-4ab2-8189-65abcf05a9b6
6
static public boolean openFile(Object obj) { File f = coerceFile(obj); if (f == null) { return false; } else if (WIN && f.isDirectory()) { try { Process proc = Runtime.getRuntime().exec("explorer /root," + f.getAbsolutePath()); try { proc.waitFor(); } catch (InterruptedException stfu) { } return true; } catch (IOException err) { return false; } } else { try { Desktop.getDesktop().open(f); return true; } catch (Exception err) { return false; } } }
c7a23161-60e3-437d-a92f-c7560e890ce2
8
public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) { this.plugin = plugin; this.type = type; this.announce = announce; this.file = file; this.id = id; this.updateFolder = plugin.getServer().getUpdateFolder(); final File pluginFile = plugin.getDataFolder().getParentFile(); final File updaterFile = new File(pluginFile, "Updater"); final File updaterConfigFile = new File(updaterFile, "config.yml"); this.config .options() .header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n' + "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n' + "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration."); this.config.addDefault("api-key", "PUT_API_KEY_HERE"); this.config.addDefault("disable", false); if (!updaterFile.exists()) { updaterFile.mkdir(); } boolean createFile = !updaterConfigFile.exists(); try { if (createFile) { updaterConfigFile.createNewFile(); this.config.options().copyDefaults(true); this.config.save(updaterConfigFile); } else { this.config.load(updaterConfigFile); } } catch (final Exception e) { if (createFile) { plugin.getLogger().severe( "The updater could not create configuration at " + updaterFile.getAbsolutePath()); } else { plugin.getLogger().severe( "The updater could not load configuration at " + updaterFile.getAbsolutePath()); } plugin.getLogger().log(Level.SEVERE, null, e); } if (this.config.getBoolean("disable")) { this.result = UpdateResult.DISABLED; return; } String key = this.config.getString("api-key"); if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) { key = null; } this.apiKey = key; try { this.url = new URL(Updater.HOST + Updater.QUERY + id); } catch (final MalformedURLException e) { plugin.getLogger().log(Level.SEVERE, "The project ID provided for updating, " + id + " is invalid.", e); this.result = UpdateResult.FAIL_BADID; } this.thread = new Thread(new UpdateRunnable()); this.thread.start(); }
6bcf8f41-fc7f-4719-8be8-2a972b7e4e5a
8
@Override public String buscarDocumentoPorFechaPago(String fechapago1, String fechapago2) { ArrayList<Compra> geResult= new ArrayList<Compra>(); ArrayList<Compra> dbCompras = tablaCompras(); String result=""; Date xfechapago1; Date xfechapago2; Date f; try{ if (fechapago1.equals("") || fechapago2.equals("")){ result="No puede dejar uno de los campos de fecha en blanco"; return result; } else { SimpleDateFormat dformat = new SimpleDateFormat("dd/MM/yyyy"); xfechapago1 = dformat.parse(fechapago1); xfechapago2 = dformat.parse(fechapago2); for (int i = 0; i < dbCompras.size() ; i++){ f=dformat.parse(dbCompras.get(i).getFechapago()); if((f.compareTo(xfechapago1))>=0 && (f.compareTo(xfechapago2))<=0){ geResult.add(dbCompras.get(i)); } } } }catch (NullPointerException e) { result="No hay Compras entre las fechas proporcionadas"; }catch (ParseException e){ result="Las fechas no tienen el formato correcto: "+e.getMessage(); } if (geResult.size()>0){ result=imprimir(geResult); } else { result="No se ha encontrado ningun registro"; } return result; }
e1062c65-3807-43c8-a334-851d5e27bbb4
9
public static String decodeTPCI(final int tpci, final KNXAddress dst) { final int ctrl = tpci & 0xff; if ((ctrl & 0xFC) == 0) { if (dst == null) return "T-broadcast/group/ind"; if (dst.getRawAddress() == 0) return "T-broadcast"; if (dst instanceof GroupAddress) return "T-group"; return "T-individual"; } if ((ctrl & 0xC0) == 0x40) return "T-connected seq " + (ctrl >> 2 & 0xF); if (ctrl == T_CONNECT) return "T-connect"; if (ctrl == T_DISCONNECT) return "T-disconnect"; if ((ctrl & 0xC3) == T_ACK) return "T-ack seq " + (ctrl >> 2 & 0xF); if ((ctrl & 0xC3) == T_NAK) return "T-nak seq " + (ctrl >> 2 & 0xF); return "unknown TPCI"; }
bbacfa52-3183-4e85-ae02-533ade9e22ea
7
public Rational root(BigInteger r) throws NumberFormatException { /* test for overflow */ if ( r.compareTo(MAX_INT) == 1 ) throw new NumberFormatException("Root "+r.toString()+" too large.") ; if ( r.compareTo(MIN_INT) == -1 ) throw new NumberFormatException("Root "+r.toString()+" too small.") ; int rthroot = r.intValue() ; /* cannot pull root of a negative value with even-valued root */ if ( compareTo(ZERO) == -1 && (rthroot % 2) ==0 ) throw new NumberFormatException("Negative basis "+ toString()+" with odd root "+r.toString()) ; /* extract a sign such that we calculate |n|^(1/r), still r carrying any sign */ final boolean flipsign = ( compareTo(ZERO) == -1 && (rthroot % 2) != 0) ? true : false ; /* delegate the main work to ifactor#root() */ Ifactor num = new Ifactor(a.abs()) ; Ifactor deno = new Ifactor(b) ; final Rational resul = num.root(rthroot).divide( deno.root(rthroot) ) ; if ( flipsign) return resul.negate() ; else return resul ; } /* Rational.root */
295c29d7-3cf3-478b-8c25-58819da690b3
9
public Location getAdjacentLocation(int direction) { // reduce mod 360 and round to closest multiple of 45 int adjustedDirection = (direction + HALF_RIGHT / 2) % FULL_CIRCLE; if (adjustedDirection < 0) adjustedDirection += FULL_CIRCLE; adjustedDirection = (adjustedDirection / HALF_RIGHT) * HALF_RIGHT; int dc = 0; int dr = 0; if (adjustedDirection == EAST) dc = 1; else if (adjustedDirection == SOUTHEAST) { dc = 1; dr = 1; } else if (adjustedDirection == SOUTH) dr = 1; else if (adjustedDirection == SOUTHWEST) { dc = -1; dr = 1; } else if (adjustedDirection == WEST) dc = -1; else if (adjustedDirection == NORTHWEST) { dc = -1; dr = -1; } else if (adjustedDirection == NORTH) dr = -1; else if (adjustedDirection == NORTHEAST) { dc = 1; dr = -1; } return new Location(getRow() + dr, getCol() + dc); }
eec0af0c-69ee-4a99-9654-c0d0746c8307
1
public void actionPerformed(ActionEvent e) { if (e.getSource().getClass() == MenuView.MenuButton.class) { ChangeState( (((MenuView.MenuButton)e.getSource())).getState() ); } }
3513bc7f-cb83-4042-adb2-0a1773f6a253
2
public static void init() { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; try { dBuilder = dbFactory.newDocumentBuilder(); doc = dBuilder.parse(Set.class.getResourceAsStream("/sets.xml")); } catch (SAXException | IOException | ParserConfigurationException e) { e.printStackTrace(); } doc.getDocumentElement().normalize(); if (doc.getDocumentElement().getNodeName() == "sets") { nodeList = doc.getDocumentElement().getChildNodes(); } else { System.err.println("Error: Sets file is not a vaild Sets XML file!"); } }
f0d2ed42-7fe0-4473-b626-9e26a12521d2
3
public String toString() { if (this == UNINITIALIZED_VALUE) { return "."; } else if (this == RETURNADDRESS_VALUE) { return "A"; } else if (this == REFERENCE_VALUE) { return "R"; } else { return type.getDescriptor(); } }
7e90ef17-4ba1-4a9b-a4e0-5932670824b7
3
private static void put(HandTypesMap map, HandTypesKeyImpl key, HandTypesImpl value, int i, boolean flag) { final int k = i; key.setBoolean(flag); key.setInt(k); value.setBoolean(flag); value.setInt(k); int size = map.size(); map.put(key, value); if (size + 1 != map.size()) { map.put(key, value); assertEquals(size + 1, map.size()); } HandTypes ht = map.get(key); if (ht == null) ht = map.get(key); assertEquals(i, ht.getInt()); if (flag != ht.getBoolean()) assertEquals(flag, ht.getBoolean()); }
3243ae8d-9817-48f0-a0e2-bd54149d8b76
1
public ASTList sublist(int nth) { ASTList list = this; while (nth-- > 0) list = list.right; return list; }
054c6291-36fd-4f58-be36-0794c2f71b97
1
public static void add(Quest q){ if(!isFull()) questLog.add(q); }
bb666579-90f2-40af-807c-a2f4840bc330
7
protected void actionPerformed(GuiButton par1GuiButton) { if (par1GuiButton.enabled) { if (par1GuiButton.id < 100 && par1GuiButton instanceof GuiSmallButton) { this.options.setOptionValue(((GuiSmallButton)par1GuiButton).returnEnumOptions(), 1); par1GuiButton.displayString = this.options.getKeyBinding(EnumOptions.getEnumOptions(par1GuiButton.id)); } if (par1GuiButton.id == 101) { this.mc.gameSettings.saveOptions(); this.mc.displayGuiScreen(new GuiVideoSettings(this, this.options)); } if (par1GuiButton.id == 100) { this.mc.gameSettings.saveOptions(); this.mc.displayGuiScreen(new GuiControls(this, this.options)); } if (par1GuiButton.id == 102) { this.mc.gameSettings.saveOptions(); this.mc.displayGuiScreen(new GuiLanguage(this, this.options)); } if (par1GuiButton.id == 200) { this.mc.gameSettings.saveOptions(); this.mc.displayGuiScreen(this.parentScreen); } } }
c79b173b-3cb7-490b-ab17-6f16e66d983b
3
public void sort(double[] input) { int n = input.length; boolean swapped = true; for (int end = n; swapped; end--) { swapped = false; for (int i = 1; i < end; i++) { if (!Helper.less(input, i - 1, i)) { Helper.exch(input, i - 1, i); swapped = true; } } } }
0472cce0-eace-4494-b9ff-d0205e6b5d31
4
public Color getDefaultRowForeground(int position, boolean selected, boolean active) { if (selected) { Color color = UIManager.getColor("List.selectionForeground"); //$NON-NLS-1$ if (!active) { Color background = getDefaultRowBackground(position, selected, active); boolean isBright = Colors.isBright(color); if (isBright == Colors.isBright(background)) { return isBright ? Color.BLACK : Color.WHITE; } } return color; } return UIManager.getColor("List.foreground"); //$NON-NLS-1$ }
7351c45a-53a8-4ed2-ab9c-16ee01c1aabb
3
public boolean validate(String str) throws Exception { if (str == "") { throw new Exception("login is not found"); } str = str.toLowerCase(); String pattern = "^[a-z][a-z0-9\\.,\\-_]{5,31}$"; // Create a Pattern object Pattern r = Pattern.compile(pattern); // Now create matcher object. Matcher m = r.matcher(str); if (m.find()) { System.out.println("Found value: " + m.group(0)); String url = "https://login.skype.com/json/validator?new_username=" + str; System.out.println("Url is - " + url); String s = readUrl(url); if (s.contains("200")) { System.out.println("такого имени еще нет"); return false; } else { System.out.println("такое имя уже есть"); return true; } } else { System.out.println("NO MATCH"); return false; } }
fa4e1dcc-8874-478d-8a37-625f1fd6486b
8
public String translateStateFormula(StateFormula formula) { String translation = ""; if (!formula.isEmpty()) { for (StateLiteralClause cl : formula.getClauses()) { if (translation != "") { translation += "& ("; } else { translation = "("; } Iterator<StateLiteral> iterator = cl.getLiterals().iterator(); while (iterator.hasNext()) { StateLiteral lit = iterator.next(); String objID = objIDs.get(lit.getDomainObject()); String inState = objID + ".state = " + lit.getState(); if (lit.isNegated()) { translation += "!(" + inState + ")"; } else { translation += inState; } if (iterator.hasNext()) { translation += " | "; } } translation += ") "; } } if (formula.isNegated() && !formula.isEmpty()) { translation = "!(" + translation + ")"; } return translation; }
166d5927-0bfa-4b55-a990-168aa9743d30
4
private void textNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textNombreKeyTyped // TODO add your handling code here: if (!Character.isLetter(evt.getKeyChar()) && !Character.isISOControl(evt.getKeyChar()) && !Character.isWhitespace(evt.getKeyChar())) { Toolkit.getDefaultToolkit().beep(); evt.consume(); } if(textNombre.getText().length() == 45) { Toolkit.getDefaultToolkit().beep(); evt.consume(); JOptionPane.showMessageDialog(this, "Nombre del proveedor demadiado largo.", "ADVERTENCIA", WIDTH); } }//GEN-LAST:event_textNombreKeyTyped
89ba1a1a-b16c-4be8-a016-0fb06c7922b0
6
public void setTroup(Troop newTroup){ //we remove the territory to the old owner if the troups is not its if(troop!=null && (newTroup==null || newTroup.getFamily()!=troop.getFamily())){ troop.getFamily().removeTerritory(this); } this.troop=newTroup; if(newTroup!=null){ owner=newTroup.getFamily(); owner.addTerritory(this); // if this is a land with a port we change the owner of the troops in the port if(this instanceof Land && this.havePort()){ this.getPort().changeOwner(newTroup.getFamily()); } }else{owner=null;} // verifier que ça ne pose pas de problemes }
ecf05045-9f97-4589-824a-656a843e5e44
8
public void messages(){ int numMessages = Integer.parseInt(outputFromServer()); System.out.println(outputFromServer()); //Show the messages that this account has received for(int i = 0; i < numMessages; i++){ System.out.println(outputFromServer()); System.out.println(outputFromServer()); System.out.println(outputFromServer()); } //Get a valid message ID from client or return to menu boolean validID = false; String serverResponse = ""; System.out.println(outputFromServer()); System.out.println(outputFromServer()); String messageID = localInput.nextLine(); if (messageID.equals("menu")){ inputToServer(messageID); return; } while(!isValidIDInteger(messageID)){ System.out.println("Please enter in a valid ID."); messageID = localInput.nextLine(); } while(!validID){ inputToServer(messageID); if (messageID.equals("menu")){ return; } serverResponse = outputFromServer(); if(serverResponse.equals("success")){ validID = true; } else if(serverResponse.equals("failure")){ System.out.println(outputFromServer()); System.out.println(outputFromServer()); System.out.println(outputFromServer()); messageID = localInput.nextLine(); } } //Print message with body content if(serverResponse.equals("success")){ System.out.println(outputFromServer()); System.out.println(outputFromServer()); System.out.println(outputFromServer()); System.out.println(outputFromServer()); } }
3d04fff5-40f7-4e8b-9483-8e9007739425
3
private void reload() throws IOException { try { Properties properties = new Properties(); File propFile = new File(PROPERTIES_NAME); if (propFile.exists()) { properties.load(new FileInputStream(propFile)); } else { InputStream propFileStream = Thread.currentThread() .getContextClassLoader() .getResourceAsStream(PROPERTIES_NAME); if (propFileStream != null) { properties.load(propFileStream); } else { throw new IOException( "no properties for databaseconnection found: " + PROPERTIES_NAME); } } this.host = properties.getProperty("host"); this.database = properties.getProperty("database"); this.username = properties.getProperty("username"); this.password = properties.getProperty("password"); this.port = properties.getProperty("port"); this.embedded = "true".equalsIgnoreCase(properties .getProperty("embedded")); this.showQuery = "true".equalsIgnoreCase(properties .getProperty("show_query")); this.connectionFactoryInfo = "true".equalsIgnoreCase(properties .getProperty("connection_factory_info")); this.tableStructureWarning = "true".equalsIgnoreCase(properties .getProperty("table_structure_warning")); this.poolsizeMin = loadPropertyInt(properties, "poolsize_min"); this.poolsizeMax = loadPropertyInt(properties, "poolsize_max"); this.poolsizeBuffer = loadPropertyInt(properties, "poolsize_buffer"); } catch (Exception e) { throw new IOException( "could not load properties for databaseconnection from: " + PROPERTIES_NAME, e); } }