text
stringlengths
14
410k
label
int32
0
9
public void set_safe(final long i, final Object value) { if (value instanceof Boolean) { setBoolean_safe(i, (Boolean) value); } else if (value instanceof Byte) { setByte_safe(i, (Byte) value); } else if (value instanceof Short) { setShort_safe(i, (Short) v...
7
public int candy2(int[] ratings) { int[] candies = new int[ratings.length]; // store the candies for (int i = 0; i < ratings.length; i++) { if (i == 0) candies[i] = 1; // base case else { if (ratings[i] > ratings[i-1]) { candies[i] = candies[i-...
9
public boolean pegIsAvailableToPlayer(int c, int r, int player) { if (player == 0) { if (c == 0 || c == boardSize_ - 1) return false; else return true; } else { if (r == 0 || r == boardSize_ - 1) return false; else return true; } }
5
public void run() { // While it's not stopped by internal error or external command while (runLoop){ // Wait for 5 seconds before actually refreshing // Get all peers from the database Table peer_address=db.getTableWithColumns("peer_address", new String[]{"peer_id", "address"}); ...
6
@Override public void setValueAt (Object val, int row, int column) { if ((column < 2) || (column > 2+ MainWindow.setupData.getEventLength ())) return; MainWindow.rosterDB.getRosters().get(row).setAvailability (MainWindow.setupData.getDateAt(column-2), val); fireTableDataChanged(); }
2
AbstractNode factor() { AbstractNode node = null; if (test(IDENT)) { if (testLookAhead(DOT) || testLookAhead(LBRAC)) { node = new ContentNode(selector()); } else { node = new ContentNode(constIdent()); } } else if (test(INT)) { node = integer(); } else if (test(STR)) { node = string(); ...
7
public int numberVariables() { return (new HashSet(MAP.values())).size(); }
0
private void addLabyrinth(int height, int length) { for (int i = 1; i < height; i++) { for (int j = 1; j < length; j++) { if (border(i,j,length,height)) { super.addBricks(new Point(i, j)); } else if (centralBlo...
5
private boolean setBooleanInitParameter(String parameterValue, boolean defaultValue) { if (null != parameterValue) { try { return "true".equalsIgnoreCase(parameterValue); } catch (Exception e) { return defaultValue; } } return defaultValue; }
2
public void onEnable() { inst = this; SkyQuest.onServer = true; qm = new QuestManager(); fm = new FileManager(); qlm = new QuestLogManager(this); if(!getDataFolder().exists()) { try { fm.saveData(getDataFolder(), qm); } catch (IOException e) { e.printStackTrace(); } } getSer...
6
public List<Book> getBooksByBranch(int branch_id) { List<Book> list = new ArrayList<>(); Connection con = null; Statement stmt = null; try { DBconnection dbCon = new DBconnection(); Class.forName(dbCon.getJDBC_DRIVER()); con = DriverManager.getConnect...
5
public double[] getNumberArrayProperty(String name) { int col = Util.findColumn(model, name); double[] a = new double[model.getRowCount()]; for (int i = 0; i < a.length; i++) { a[i] = ((Number) model.getValueAt(i, col)).doubleValue(); } return ...
1
private static int countSlots(Expression[] exprs, int length) { int slots = 0; for (int i = 0; i < length; i++) slots += exprs[i].getType().stackSize(); return slots; }
1
public boolean isOptOut() { synchronized (optOutLock) { try { // Reload the metrics file configuration.load(getConfigFile()); } catch (IOException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.g...
4
public void renderSprite(int xp, int yp, Sprite sprite, boolean fixed) { if (!fixed) { xp -= xOffset; yp -= yOffset; } for (int y = 0; y < sprite.getHeight(); y++) { int ya = y + yp; for (int x = 0; x < sprite.getWidth(); x++) { ...
7
private static boolean propsEquals(Member member, Object o1, Object o2) { if (member == null) { throw new IllegalStateException("Member is null in propsEquals"); //return false; } try { if (member instanceof Field) { Field f = (Field)member; System.out.println(String.format("EqualsUtils.propsEqua...
9
public void setValue(String value) { this.value = value; }
0
private Integer[][] cross2(Integer[] t1, Integer[] t2, boolean randomCrossPosition) { int length = t1.length; int crossPosition1, crossPosition2; Integer[][] t = new Integer[6][length]; if (randomCrossPosition) { double d1, d2; d1 = Math.random() * length; ...
5
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=prof...
9
private int levelAuxPrefixFree(Node focusNode,int level, int usedLevel) { if (level==1){ if (usedLevel>0 & !focusNode.isUsed()) if (focusNode.setLUsed()) usedLevel--; //FIll 0 first if (usedLevel>0 & !focusNode.isUsed()) if (focusNode.setRUsed()) usedLevel--; } else{ if (usedLevel>0 & !foc...
7
@Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if(sender instanceof ConsoleCommandSender) { sender.sendMessage("§cThis can only be run in game!"); return true; } if(args.length== 1) return false; if(args.length>= 3) { Player p = (Player) ...
8
String reformatExpression(String exp) { int i = 0; char it; int itCount; boolean haveStar; StringBuffer buff = new StringBuffer(); int size = exp.length(); while (i < size) { it = exp.charAt(i); itCount = 1; haveStar = false; ...
9
private static void displayMovesInVector(Vector<Move> v){ for(Move m:v){ m.display(); System.out.print(", "); } System.out.println(); }
1
public synchronized void deleteWay(int pos, long wayId) { if (ways.size() > pos) ways.get(pos).remove(wayId); }
1
public void setReleaseTime(Date time) { if (time == null) throw new IllegalArgumentException("Time cannot be null"); this.releaseTime = time; }
1
@Override public void display(int depth) { StringBuffer buff = new StringBuffer(); for (int i = 0; i < depth; i++) { buff.append('-'); } System.out.println(buff + " " + getName()); }
1
public List<CompositeInstance> getFilteredInstances(){ return this.instances; }
0
public int longestConsecutive(int[] num) { HashMap<Integer, Boolean> map = new HashMap<Integer, Boolean>(); int len = num.length; if(len < 2) { return len; } int max = 1; for(int i=0;i<len;i++) { map.put(num[i], true); } for(int i=0;i<len;i++) { int current = num[i]; int count...
8
public static void count_words(String s) { boolean wordStarted = false; int wCount = 0; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); boolean letter = ch != ' ' && ch != ','; if (letter) { wordStarted = true; } else...
4
public void sendData(ObjectOutputStream[] streams, double time, int newPlayer){ for(int i=0;i<streams.length;i++){ if(streams[i] == null) continue; try { streams[i].writeDouble(time); streams[i].flush(); } catch (Exception e) { System.out.println("issue in GameMechanics.sendData"); ...
3
public void initTokenClasses() { table.println("package lexer;"); table.println(" "); table.println("/**"); table.println(" * This file is automatically generated<br>"); table.println(" * it contains the table of mappings from token"); table.println(" * constants to th...
4
public static void addSchool() { System.out.print("Connection add school ... "); //Connexion à la base BaseSetting bs = new BaseSetting(); if (bs.testerConnexion()) { System.out.println("success"); try (Scanner sc = new Scanner(System.in)) { ...
6
@Override public void setAttemptClientConnect(IAttemptClientConnect attemptClientConnect) { this.attemptClientConnect = attemptClientConnect; }
0
public int[] getTemplatePixels(int x0, int y0, int x1, int y1) { int retPixels[] = new int [735]; /* 21*35 */ int xLen, yLen, sX, sY, cX, cY, oX, oY; double xInc, yInc, nY, scale; xLen = x1 - x0; yLen = y1 - y0; /* distance between the eyes is 23 pixels from experiences */ xInc ...
7
public void put(K key, V value) { //if hashmap size is more than a certain load //its time to rehash the array if(size >= max_size*loadFactor ){ //double the max_size max_size *= 2; //temporarily copy the old array Entry []temp = new Entry[max_siz...
7
@Override public String getDescription() { // This description will be displayed in the dialog, // hard-coded = ugly, should be done via I18N return "Assembly files (*.asm)"; }
0
public Territory(GoGame game1) { game = game1; squares = new HashSet<Square>(); }
0
public static String getNick(String name) { if (name.startsWith(":")) name = name.substring(1); if (name.startsWith("#")) return name; else if (name.length() > 0 && name.indexOf('!') >= 0) { name = name.split("!")[0]; return name; } ...
4
public int recordReturnType(CtClass type, boolean useResultVar) throws CompileError { gen.recordType(type); return gen.recordReturnType(type, "$r", (useResultVar ? resultVarName : null), stable); }
1
public void generateObj() { try { Class<?> clazz = Class.forName("com.rock.reflect.User"); //默认调用无参构造器 Object u1 = clazz.newInstance(); System.out.println(u1); //获取构造方法,再调用 Constructor<?> constructor = clazz.getConstructor(int.class,String.class); Object u2 = (User) constructor.newInstance(1,"roc...
9
public void closeChat() { if (cbtn != null) cbtn.click(); }
1
public static void main(String[] args) throws InterruptedException { final Random randomizer = new Random(); final Bank bank = new Bank("Native", Math.abs(randomizer.nextLong())); final Account[] accounts = new Account[ACCOUNTS_COUNT]; double totalAmount = 0.d; for (int i = 0;...
6
public void mouseReleased(MouseEvent evt) { boolean orderChanged = false; for (int i=0; i<slotList.size(); ++i) { Slot slot = slotList.get(i); if (!slot.isDragged()) continue; if (insertBeforeSlot...
7
private static boolean validTile(ITile[][] map, int x, int y) { return (x >= 0 && x < map.length) && (y >= 0 && y < map[0].length) && map[x][y].isPassable(); }
4
public boolean salvar(Usuario usuario) { if(usuario.getNome()==null || usuario.getNome().equals("")){ return false; } if(usuario.getLogin()==null || usuario.getLogin().equals("")){ return false; } usuariosBancoDeDados.put(usuario.getId(), usuario); ...
4
public void refreshSearches () { // refresh da search panel int pageSize = pages.size(); // holds total # of pages at the time this method is called for (int i = pageSize-1; i > 0; i --) { // loop through pages remove(pages.get(i)); // remove page from panel pages.remove(pages.get(i)); // remove page from ar...
2
public static void genTagOuput(TagletManager tagletManager, Doc doc, Taglet[] taglets, TagletWriter writer, Content output) { tagletManager.checkTags(doc, doc.tags(), false); tagletManager.checkTags(doc, doc.inlineTags(), true); Content currentOutput = null; for (int i = 0; i...
7
public void SaveFile(String path, String FileContent, boolean CleanFileContent, String type) { FileWriter file; BufferedWriter writer; Calendar calendar = new GregorianCalendar(); // Fecha y hora actuales. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss"); // Formato de la fecha. String...
1
public String addNewBook() { // on récupère les données du formulaire String bookTitle = book.getBookTitle(); String bookAuthor = book.getBookAuthor(); String bookSummary = book.getBookSummary(); Integer bookType = book.getBookType(); //Integer bookState = book.getBookState(); Integer bookState = 1; // 1 ...
9
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(args.length == 1) { if(args[0].equalsIgnoreCase("help")) { // show help! showHelp(sender); return true; } } if(plugin.commands.containsKey(label)) { boolean hasPermission = true; if(sender ins...
6
public void display() { win2.pushMatrix(); // translate to coordinates of center of top of t1 int height; int h1 = myWall.getT1().getHeight(); int h2 = myWall.getT2().getHeight(); if (x < Animation.WALL_WID / 2) { height = h1; } els...
7
public boolean foundResult(Map<Variable, Term> result) { // Print the whole combination of variables that satisfies the evaluated query. Iterator<Map.Entry<Variable, Term>> bindings = result.entrySet().iterator(); while (bindings.hasNext()) { Map.Entry<Variable, Term> binding = bindi...
6
@Test public void canDetermineTheColumnFitnessOfAGrid() { for (int sudokuPower = 1; sudokuPower < 10; sudokuPower++) { // all columns are valid but the first one for (int i = 0, size = sudoku.getGridLength(); i < size; i++) { if (i == 0) continue;...
3
public static void removeRate(int rateId){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ conn.setAutoCommit(false); PreparedState...
4
private void setListeners() { /* * The action listener for remove carriage button */ btnRemove.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { theTrain.removeCarriage(); } catch (TrainException e1) { e1.printStackTrace(); } ...
8
long findRecordStart(long pos) { try { raf.seek(pos); int len = 0; for (long p = pos; (len = raf.read(buffer)) > 0; p += len) { for (int idx = 0; idx >= 0;) { // Find '\n@' in this buffer idx = findNl(buffer, idx); if (idx >= 0) { idx++; if ((idx < buffer.length) && (buffer[id...
7
@Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(getClass() != obj.getClass()) return false; Point other = (Point) obj; if(!Arrays.equals(components, other.components)) return false; if(dimension != other.dimension) return false; return true; }
5
} // ----------------------------------------------------------------------- @Override public DateTimeValueRange range(DateTimeField field) { if (field instanceof ChronoField) { ChronoField f = (ChronoField) field; if (f.isDateField()) { switch (f) { case DAY_OF_MONTH: ...
9
public static String getAttributeName(int index) { switch (index) { case 0: return "STR"; case 1: return "DEX"; case 2: return "CON"; case 3: return "INT"; case 4: return "...
6
@Override public List<Integer> loadArrayFromFile(String path) { if (path == null) { throw new IllegalArgumentException("Path is not specified!"); } List<Integer> list = new ArrayList<Integer>(); String line; BufferedReader bufferedReader = null; try {...
5
static final public void repeticao() throws ParseException { trace_call("repeticao"); try { jj_consume_token(WHILE); jj_consume_token(A_PARENTESES); expressao(); jj_consume_token(F_PARENTESES); jj_consume_token(A_CHAVES); label_2: while (true) { comando(); ...
9
public boolean checkBox (int row, int col) { int i = 0, j = 0, k = 0, count = 0; /* Uses nested for loops to check the entries */ for (k = 1; k < 10; k++) { for (i = row; i < row+4; i++) { for (j = col; j < col+4; j++) { count = 0; if (k == Integer.parseInt(entries[i][j].getText())){ ...
5
void getNewMessages(DateTime loopTime) throws Exception{ //Clean up of buffers goes here! Because we don't want to itterate over the new messages as we know //they are new! //1. First, we clean up. for (Vessel v: theVessels){ v.theTrackBuffer.cleanBuffer(theOpti...
9
@Override public int compare(Device arg0, Device arg1) { if (arg1.getPrice() > arg0.getPrice()){ return 1; } else if(arg0.getPrice() > arg1.getPrice()){ return -1; } return 0; }
2
@Override public void freeze() { if(!used && global) { global = false; } }
2
private static List <File> directoryFiles(String path, String extension) { List <File> allFiles = new ArrayList <File> (); allFiles.add(new File(path)); int index = 0; while (index != allFiles.size()) { File currentFile = allFiles.get(index); if (currentFile.isDirectory()) { allFiles.remove(index); ...
4
@Override public void setData(ByteBuffer data) { setVersion(data.getShort()); short numberSubtables = data.getShort(); for (int i = 0; i < numberSubtables; i++) { short platformID = data.getShort(); short platformSpecificID = data.getShort(); ...
3
public ArrayList<File> find(String path, String mask) throws FileNotFoundException { ArrayList<File> result = new ArrayList<>(); File file = new File(path); if (!file.isDirectory()) { throw (new FileNotFoundException("it is not directory!")); } if (!MaskValidator.isValid(mask)) { throw (new Runtim...
6
public void draw() { if (texture != null) texture.bind(); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexAttribPointer(0, 3, GL_FLOAT, false, Vertex.SIZE * 4, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUF...
1
public boolean move (int direction, Client c) { // All moves are of one square, lets make sure // that the target square is fre if (c == null) return false; if (c.current == null) return false; Coordinate newLoc = null; switch (direction) { case Coordinate.NOR...
8
public void run() { while (true) { // Create a buffer to read datagrams into byte[] buffer = new byte[1500]; // Create a packet to receive data into the buffer DatagramPacket packet = new DatagramPacket(buffer, buffer.length); if (active) { ...
6
@Override public void run() { while (Server.run) { try { stream.ping(); if (stream.isEOF()) { break; } while (stream.getAvailable() > 0) { Packet packet = Packet.readPacket(stream); if (packet != null) { packet.handle(); if (packet instanceof Packet_Login) { Packe...
8
public void clientHttp() { BufferedReader in = null; try { ListIterator<SearchHitMessage> it = Simpella.searchHitMsgList.listIterator(); String ipToConnect=""; String portToConnect=""; String fileName=""; String fileIndex=""; int flag = 0; while(it.hasNext()) { SearchHitMessage shm = i...
9
private Class<? extends Matrix> getClassFor(int rows, int cols) { if (cols==1) { switch (rows) { case 2: return Vector2.class; case 3: return Vector3.class; case 4: return Vector4.class; default: return Vector.class; } } else if (rows==2 && cols==2) return Matrix2.class; else if (rows==3 ...
9
public HashMap<String,PDFObject> getDictionary() throws IOException { if (type == INDIRECT) { return dereference().getDictionary(); } else if (type == DICTIONARY || type == STREAM) { return (HashMap<String,PDFObject>) value; } // wrong type return new Has...
3
public int modificarEnunciado(DTO.Enunciado en) { try { if (con.isClosed()) { con = bd.conexion(); } String consulta; Object ob = null; if(en.getDespuesDe().getCodigo() !=0){ ob =en.getDespuesDe().getCodigo(); ...
7
protected void stateChanged() { if(lastState == ButtonState.ACTIVE && currentState == ButtonState.HOVER) { ActionEvent e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, this.text); for(ActionListener l : actionListeners) l.actionPerformed(e); } }
3
public void loadConfig() { while (!getDataFolder().exists()) { saveConfig(); } File file = getDataFolder(); String filename = file + "/config.cfg"; config = new Properties(); try { config.load(new FileInputStream(filename)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IO...
3
public User findUserByKey(String key) { Session session =null; User user; try { session= HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Criteria criteria = session.createCriteria(User.class); user=(User)criteria.add(Re...
4
@Override public void approveSelection() { File file = getSelectedFile(); if (this.dialogType == JFileChooser.OPEN_DIALOG) { // Alert if file does not exist. if (!file.exists()) { String msg = GUITreeLoader.reg.getText("error_file_not_found"); msg = Replace.replace(msg,GUITreeComponentRegistry.PLA...
6
private boolean r_postlude() { int among_var; int v_1; // repeat, line 75 replab0: while(true) { v_1 = cursor; lab1: do { // (, line 75 // [, line 77 bra = cursor; ...
9
public HashMap<Integer, List<Integer>> constructAdjacencyList() throws IOException { HashMap<Integer, List<Integer>> adjacencyList = new HashMap<Integer, List<Integer>>(); List<String> sequence = new ArrayList<String>(); List<Integer> knotList = new ArrayList<Integer>(); BufferedReader b...
4
public static boolean isValidForename(String forename) { if (forename == null) return false; return forename.matches("[a-zA-Z]+") && forename.length() <= 32; }
2
@Override public void run() { threadRun = true; Simulator simulator = MainProgram.getSimulator(); while(threadRun && numSteps > 0 && simulator.getSimulatorView().isViable(simulator.getField())) { MainProgram.getSimulator().simulateOneStep(); numSteps--; while(infinite && numSteps == 0) { n...
6
private static void exportFrame(ExportDiagnoser d, Frame f, File baseDirectory) { Rectangle rect = f.properRectangle(); Point pivot = f.getPivot(); d.printSection(f.getName()); RelativeFile relativeImageFile = f.getImageFile(); if(relativeImageFile!=null) { File imageFile = relativeImageFile.getAbsolut...
8
public final TLParser.whileStatement_return whileStatement() throws RecognitionException { TLParser.whileStatement_return retval = new TLParser.whileStatement_return(); retval.start = input.LT(1); Object root_0 = null; Token While91=null; Token Do93=null; Token End95=nu...
2
public Integer getId() { return id; }
0
@Override public V remove(K key) { int i = findEntry(key); if (i < 0)// key not in table return null; V value = bucket[i].getValue(); bucket[i] = available; size--; return value; }
1
@Override public void itemStateChanged(ItemEvent ie) { String name = displayLabel.getFont().getName(); Font font; if(styleItems[0].isSelected() && styleItems[1].isSelected()) font = new Font(name, Font.BOLD+Font.ITALIC, 72); ...
4
public void paintComponent(Graphics g) { BufferedImage spriteSheet = null,Thruster; BufferedImageLoader loader = new BufferedImageLoader(); try { spriteSheet = loader.loadImage("images/Ship_Shop/shipshopparts.png"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrac...
7
public String getLastMessage() { return lastMessage; }
0
public boolean equals(Object o){ Production p = (Production)o; if( this.dot == p.dot && this.left.equals(p.getLeft())){ if( this.right.size() == p.right.size()){ for( int i = 0; i < this.right.size(); i++){ if( !this.right.get(i).equals(p.right.get(i))){ return false; } } ...
5
private long largest(final long number) { long result = 1; for (int p : Primes.primes) { if (number % p == 0) { result = p; } } return result; }
2
private void cycle2( int i, int k, WordInfo wf, Hand h, int cross_score, int word_score, int word_mult ) { if (WordFinder.killAllNow) { // Kill It } else if (this.Board...
5
public static CustomButton doHistoryViewButton() { final CustomButton a = new CustomButton("show my history"); a.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { JFrame searchResultFrame = new JFrame("my history"); searchResultFrame.setSize(1300, 650)...
2
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 o...
9
private void createButtons(){ java.net.URL buttonIcon = Paintimator.class.getResource("images/backPage.png"); backPage = new JButton(new ImageIcon(buttonIcon)); backPage.setToolTipText("Previous Page"); backPage.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg...
3
public void MoveModel() { if(win == GameStatus.VICTORY || lose == GameStatus.DEFEAT) pause = true; if(!pause) { CollideableObject q; int i = 0; win = GameStatus.VICTORY; lose = GameStatus.DEFEAT; while (i < data.size()) { q = data.get(i); if (q.color != Color.BLUE && q.color != Col...
8
@Override public void onDraw(Graphics G, int viewX, int viewY) { if (X>viewX&&X<viewX+300&&Y>viewY&&Y<viewY+300) { Graphics2D g = (Graphics2D)G; Composite c = g.getComposite(); // g.setComposite(new Additive()); g.setColor(new Color(255,r.nextInt(255),...
5
private void lisaaKilpienergiaa(Pelihahmo h){ if (!h.getSuojakilpi()){ h.setKilpienergia(h.getKilpienergia() + LISAAMIS_VAKIO); } }
1