text
stringlengths
14
410k
label
int32
0
9
public static int discrete(double[] a) { double EPSILON = 1E-14; double sum = 0.0; for (int i = 0; i < a.length; i++) { if (a[i] < 0.0) throw new IllegalArgumentException("array entry " + i + " is negative: " + a[i]); sum = sum + a[i]; } if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON) throw new I...
7
public static int countNeighbours(boolean [][] world, int col, int row){ int total = 0; total = getCell(world, col-1, row-1) ? total + 1 : total; total = getCell(world, col , row-1) ? total + 1 : total; total = getCell(world, col+1, row-1) ? total + 1 : total; total = getCell(world, col-1, row ) ? total + 1...
8
protected void validateBySelector(DataSetReport report, List<Tuple> actual) { for (int i = 0; i < actual.size(); i++) { Tuple tuple = actual.get(i); // -- create a list of the validators which can be applied to the current tuple List<TupleValidator> applicableValidators = n...
6
public void setCbSecteur(JComboBox cbSecteur) { this.jComboBoxSecteur = cbSecteur; }
0
public void edit(Fornecedor fornecedor) throws NonexistentEntityException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); fornecedor = em.merge(fornecedor); em.getTransaction().commit(); } catch (Ex...
5
private boolean shouldBlock(HttpRequest req) { String uri = req.getUri(); for (Pattern blockPattern : blackList) { if (blockPattern != null && blockPattern.matcher(uri).matches()) { return true; } } return false; }
3
private void paintEscudos(Graphics2D g2d){ for(Escudo e: escudos) if(e.isVivo()) e.paint(g2d); }
2
public Liste() { listeMetadonnees = new ArrayList<Metadonnee>(); }
0
private ArrayList buildPredicates() throws Exception { ArrayList predicates = new ArrayList(); /* The result. */ Predicate predicate; Attribute attr; Enumeration attributes = m_instances.enumerateAttributes(); boolean individual = (m_parts != null); /* Individual-based learning ? */ /* Attribu...
8
public Brick14(int gameAreaStartX, int gameAreaStartY, int brickSize, int brickIndex, BufferedImage brickImage) { super(brickSize, brickIndex, brickImage); switch(brickIndex) { case 1: this.row = 0; this.column = 8; this.relativeRow ...
5
public synchronized void register(Cancelable current, Cancelable parent) { if (parent == null) { TreeNode currentNode = findNodeInTaskTrees(current); if (currentNode instanceof TreeNode) { TreeNode currentParent = currentNode.getParent(); if (currentParent instanceof TreeNode) { ...
6
public void incrementCount(Class animalClass) { Counter count = counters.get(animalClass); if(count == null) { // We do not have a counter for this species yet. // Create one. count = new Counter(animalClass.getName()); counters.put(animalClass, count)...
1
public boolean equals( Object obj ){ if (this == obj){ return true; } if (obj == null){ return false; } if (obj instanceof Locomotive ){ Locomotive temp = (Locomotive) obj; return ( this.engine.equals(temp.getEngine()))&& ( this.model.equals(temp.getModel() ))&& ( this.getComfortPercent...
8
public EU2Country getController() { int id = getId(); String sid = go.getString("id"); if (!scenario.provCanHaveOwner(id)) return null; for (GenericObject c : scenario.countries) if (c.getChild("controlledprovinces").contains(sid)) ...
3
@Override public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(bg, 0, 0, this.getWidth(), this.getHeight(), this); for(int y = 0; y < 12; y++) { for(int x = 0; x < 16; x++) { g.drawImage(creationWindow.getImages()[creatio...
2
private boolean changeField(Object component, String text, String insert, int movestart, int moveend, int start, int end) { movestart = Math.max(0, Math.min(movestart, text.length())); moveend = Math.max(0, Math.min(moveend, text.length())); if ((insert == null) && (start == movestart) && (end == moveend)) { ...
8
public void setResult(String src, String tgt, String compare) { if (compare == null) { // simple move board.movePiece(src, tgt); board.updatePiece(tgt); } else if (compare.equals(">")) { // the piece on the source position // killed the piece on the target ...
5
public static boolean isPacketDropped(int x1, int y1, int x2, int y2) { double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); int probability = new Random().nextInt(100); if (distance <= 80) { return false; } else if (distance <= 90) { if (probability < 20) { return true;...
9
public Grid(boolean isPlaceholder) { // Make default background transparent this.setOpaque(false); if (isPlaceholder) { visibleRows = 4; rows = 4; cols = 4; insertion = new Point(-1, -1); } else { visibleRows = 20; rows = 24; cols = 10; insertion = new Point(5, 20); } this.setLayout(new ...
5
public void run(String givenWord,String[] book){ for(String word:book){ word=word.toLowerCase(); if(word.trim()!=""){ if(!map.containsKey(word)){ map.put(word, 1); }else{ map.put(word, map.get(word)+1); } } } }
3
public List<Quiz> getFilteredQuizzes() { List<Quiz> returnList = new ArrayList<Quiz>(); for(int i = 0; i < quizList.size(); i++) { if(filter == 1) { if(quizList.get(i).getUserId() == correspondingId) returnList.add(quizList.get(i));...
9
public boolean setClassConstant(String clazzName) { if (constant != null) return false; if (clazzName.charAt(0) == '[') { if (clazzName.charAt(clazzName.length() - 1) == ';') clazzName = clazzName.substring(0, clazzName.length() - 1); if (fieldName.equals("array" + (clazzName.replace('[', '$').re...
6
static private int decodeDoubleSign(long longBits) { final int signBit = (int) ((longBits >> 63) & 1L); if (signBit == 0) { return 1; } else { return -1; } }
1
@Override public void paintComponent(final Graphics the_graphics) { super.paintComponent(the_graphics); final Color clear = new Color(0, 0, 0, 0); final Graphics2D g2d = (Graphics2D) the_graphics; if (my_board.gameIsOver()) { setBackground(Color.BLACK); g2d.setPaint(NERV_RED); ...
8
public boolean camposobrigatoriospreenchidos() { if (TfDescricao.getText().equals("")) { msg.CampoObrigatorioNaoPreenchido(LbNotificacao, "Digite a descrição do produto!"); TfDescricao.grabFocus(); return false; } if (!especproduto.getTipoproduto().isServico(...
9
public void draw(Graphics2D g) { g.drawImage(image, (int)x, (int)y, null); if(x < 0) { g.drawImage(image, (int)x + StatePanel.PWIDTH, (int)y, null); } if(x > 0) { g.drawImage(image, (int)x - StatePanel.PWIDTH, (int)y, null); ...
4
private char[] hashPassword(char[] password) throws CharacterCodingException { byte[] bytes = null; char[] result = null; String charSet = getProperty(PARAM_CHARSET); bytes = Utility.convertCharArrayToByteArray(password, charSet); if (md != null) { synchr...
3
private int incrementItem(String item, String storage) { String[] split = storage.split(" "); int count = 0; for (String s : split) { if (s.contains(item)) { count++; } } return count; }
2
private void loadTextures() { String name = ""; for (GameButton button : buttons) { name = button.getName(); this.name2texture.put(name, new Texture(Gdx.files.internal("model/flag/" + name + ".png"))); } this.name2texture.put("background",new Texture(Gdx.files.internal("model/titleScreen.jpg"))); }
1
public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } try { Connection conn = DriverManager.ge...
4
@Test public void testBinomialSequence() { final int numRuns = (int) 1e5; final double[] testCases = { // 100, 0.5, // // 250, 0.1, // 500, 0.05, // // 100, 0.05, // }; for (int test = 0; test < testCases.length / 2; ++test) { int size = (int) testCases[2 * test]; double prob = testCase...
5
public byte[] getData() { return data; }
0
public void setData(byte[] data) throws IllegalArgumentException { /* if (data == null) data = new byte[0]; */ if (data == null || data.length == 0) throw new IllegalArgumentException("The data field in the " + frameType.getId() + " frame may not be empty."); if (data.length > MAX_DA...
3
private void program(SmartBasicSubroutine subroutine) throws Exception { while (scanner.currentLexeme != SourceLexemeType.FILE_END) { if (scanner.currentLexeme == SourceLexemeType.ENDSUB) { scanner.getNextLexeme(); if (subroutine.name.equals(SmartBasicProgram.MAIN_SUBROUT...
9
public void download() throws IOException { HttpURLConnection httpConnect = null; float totalDataRead; BufferedInputStream bufferedIStream; FileOutputStream fileOStream; BufferedOutputStream bufferedOStream; byte[] data = new byte[1024]; int i = 0; ...
2
public int getNumberOfWins() { return _wins; }
0
public Queue<String> panzerXMLUnit (){ try { path = new File(".").getCanonicalPath(); FileInputStream file = new FileInputStream(new File(path + "/xml/papabicho.xml")); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); Do...
9
static final Class142_Sub27_Sub13 method1614(Class73 class73, boolean flag, int i, int j, Class73 class73_1) { int ai[] = class73_1.method772((byte) -69, j); boolean flag1 = true; for (int k = 0; ai.length > k; k++) { byte abyte0[] = class73_1.method799(ai[k], true, j); i...
7
private Object readObjectFieldValue() throws IOException, JSONException { Object value = this.readValue(); int c = this.skipWSRead(); if (c == JSON.VALUE_SEPARATOR || c == JSON.END_OBJECT) { if (c == JSON.END_OBJECT) this.unread(c); return value; } else { String message = S...
3
private static void createWindow(Serializable object) { DIALOG.setVisible(false); FrameFactory.createFrame(object); }
0
public static IFiniteAutomata getFiniteAutomataFromStringList( List<String> list) throws FailedToGetFiniteAutomataFromStringListException { if (list == null) { throw new IllegalArgumentException("Argument can't be null: list."); } int listSize = list.size(); if (listSize < 5) { throw new Fa...
7
public void removeVictim(int index) { victims.remove(index); }
0
public List<LoginEntry> readLogins() { List<LoginEntry> retList = new ArrayList<LoginEntry>(); try { ResultSet rs = _sqLite.query("SELECT login.*, player.playername as playername FROM player, login " + "WHERE player.id = login.id_player " + "ORDER BY time_login DESC;"); while (rs.next(...
3
private void addToList(MainContainer main, int count) { switch(count){ case 0 : containersnul.add(main); break; case 1 : containerseen.add(main);break; case 2 : containerstwee.add(main); break; case 3 : containersdrie.add(main); break; } }
4
public Object[][] listSeries() { Logger.getLogger(BooksFolderAnalyser.class.getName()).entering(BooksFolderAnalyser.class.getName(), "listSeries"); try { File[] allfiles = null; if (booksDirectory == null || !booksDirectory.exists()) { Logger.getLogger(BooksFolder...
8
public boolean equal(Hexpos hp) { return hp.col() == j+1 && hp.row() == i+1; }
1
@Override public void doLoopAction() { sound.playBackGround("/sound/background/Yoster Island.wav"); for(GameObject gameObject : StageSelectorObjects) { gameObject.doLoopAction(); } if (!stageSelectorMario.isFindPath()) { if (confirm == true...
7
Decoder2 GetDecoder(int pos, byte prevByte) { return m_Coders[(((pos & m_PosMask) << m_NumPrevBits) + ((prevByte & 0xFF) >>> 8 - m_NumPrevBits))]; }
0
final synchronized boolean registerMerge(MergePolicy.OneMerge merge) throws MergePolicy.MergeAbortedException { if (merge.registerDone) return true; if (stopMerges) { merge.abort(); throw new MergePolicy.MergeAbortedException("merge is aborted: " + merge.segString(directory)); } fin...
8
private StringBuffer appendCharToBuffer(StringBuffer chunk, char c) { if (chunk == null) { chunk = new StringBuffer(); } chunk.append(c); return chunk; }
1
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onDropFromLockedSlot(PlayerDropItemEvent event) { Player player = event.getPlayer(); if (player.getItemOnCursor() == null || player.getItemOnCursor().getType() == Material.AIR) { PlayerInvent...
6
public boolean write_data(String filename) throws IOException { if(!ok) { return false; } else { FileWriter fout = new FileWriter(filename); Enumeration e, k; String sec, key, value; Properties p; e=sections.keys(); while(e.hasMoreElements()) { sec =(String) e.nextEleme...
3
private void info(final String msg) { logger.info(msg); }
0
protected void startGame() { Card lowestCard = null; for (int i = 0; i < players.length; i++) { Card playerLowest = getLowestCard(players[i]); if (playerLowest != null && (lowestCard == null || playerLowest.getRank().compareTo(lowestCard.getRank()) < 0)) { lowestCard = playerLowest; currentPlayer = i...
4
public void initTransient() { if(this.blocks == null) { throw new RuntimeException("The level is corrupt!"); } else { this.listeners = new ArrayList(); this.blockers = new int[this.width * this.height]; Arrays.fill(this.blockers, this.depth); this.calcLightDepths...
9
public synchronized void update(Collection<Snake> snakes) { Location nextLocation = head.getAdjacentLocation(direction); if (nextLocation.x >= SnakeWebSocketServlet.PLAYFIELD_WIDTH) { nextLocation.x = 0; } if (nextLocation.y >= SnakeWebSocketServlet.PLAYFIELD_HEIGHT) { ...
6
public KeyHandler getKeyHandler() { return kh; }
0
private boolean doAction(final String action, SceneObject obj) { if(Players.getLocal().getAnimation() == -1 && !Players.getLocal().isMoving()) { if(obj.getLocation().distanceTo() > 5) { Walking.walk(obj.getLocation()); } else { if(!obj.isOnScreen()) { ...
9
private int getGCD(int a, int b){ if(b==0) return a; else return getGCD(b, a % b); }
1
public StepButtonListener(GraphDrawer d) { this.d = d; }
0
public static ArrayList<Quiz> getQuizListByTag(String tagString) { ArrayList<Quiz> quizList = new ArrayList<Quiz>(); if (tagString.trim().isEmpty()) return quizList; String statement = new String("SELECT * FROM " + TagDBTable + " WHERE tag = ?"); PreparedStatement stmt; try { stmt = DBConnection.con.pre...
3
Point p(int i, float t) { float px = 0; float py = 0; for (int j = -2; j <= 1; j++) { px += b(j, t) * ptsIn.xpoints[i + j]; py += b(j, t) * ptsIn.ypoints[i + j]; } return new Point((int) Math.round(px), (int) Math.round(py)); }
1
private String generateCSVRow(List row) { //this.totalRowsGenerated++; String retval = ""; for (int i=0; i < row.size(); i++) { String fieldVal = (String) row.get(i); if (this.quoteAllOutputFields) retval += "\""; if (row.get(i) != null) { retval += row.get(i); } if (this.quoteAllOutputFiel...
5
private int[][] scheduleInstructions() { int[][] schedule = new int[executed.size()][4]; int dependancy; boolean reset = false; boolean cdbEmpty; Instruction instruction; for (int i = 0; i < schedule.length; i++) { instruction = executed.get(i); if (i == 0) schedule[i][0] = 1; else if (rese...
9
@Override public void deserialize(Buffer buf) { super.deserialize(buf); partyType = buf.readByte(); if (partyType < 0) throw new RuntimeException("Forbidden value on partyType = " + partyType + ", it doesn't respect the following condition : partyType < 0"); partyLeaderId...
5
public static void main(String[] args) { // ConfigManager configManager = ConfigManager.getInstance(); MainService is = new MainService(); is.getLogger().info("start-------------------"); is.fetch(); is.extract(); is.initOnGoing(); }
0
private int divide(int start, int end) { int separatorPos = getSeparatorPos(start, end); swap(end, separatorPos); int firstGreatPos = -1; int separator = get(end); for (int i = start; i < end; i++) { if(get(i) <= separator) { if(firstGreatPos != -1) ...
6
public Unit findStudent(final Unit teacher) { if (getSpecification().getBoolean(GameOptions.ALLOW_STUDENT_SELECTION)) return null; // No automatic assignment Unit student = null; GoodsType expertProduction = teacher.getType().getExpertProduction(); int skillLevel = INFINITY; ...
8
@Test public void testPermutate2() { int[] testExpansionTabel = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; byte[] block = new byte[]{10, 12, 11, 13}; ...
1
public static PVector resolveAny(ENeighbour neighbour, PVector v) { switch( neighbour) { case TOPLEFT: return resolveTopLeft(v); case TOP: return resolveTopMiddle(v); case TOPRIGHT: return resolveTopRight(v); case RIGHT: return resolveRight(v); case BOTRIGHT: return resolveBottomRight(v); case BOTTOM: ret...
9
public Cat(String name, float weight, FlyingAbility flyingAbility) { super(name, weight, "meow", flyingAbility); }
0
public static double trapecio(double extremoIzq, double extremoDer, Funcion fun, double k) { double n = 1; double h = extremoDer - extremoIzq; double t0 = (h / 2) * (fun.f(extremoIzq) + fun.f(extremoDer)); if (k == 0) { return t0; } n = n * 2; h = h / ...
3
public boolean typeBoolean(String op1, boolean bool1, String op2, boolean bool2){ if (bool1 == bool2){ if (op1.equals("=") && op2.equals("!=")){ return false; }else if(op1.equals("!=") && op2.equals("=")){ return false; }else{ return true; } }else{ //if (bool1 != bool2) { if (op1.equals(o...
6
public String processInput(int time, String inputString, boolean verbose) { String outputString = null; // Read input into a HashMap HashMap<String, String> messageMap = new HashMap<String, String>(); String[] split = inputString.split(" "); for (String s : split) { String[] tempS = s.split("="); ...
6
private boolean camposCompletos (){ if((!field_fec_alta.getText().equals(""))&& (!field_limite_cred.getText().equals(""))&& (!field_dni.getText().equals(""))&& (!field_nombre.getText().equals(""))&& (!field_apellido.getText().equals(""))&& (!field_telefono....
9
private String formatMass(double mass, boolean isForce) { final int ZERO_DIGIT = 4; String massStr = String.valueOf(mass); if (isForce) { // 強制的に全ての桁を統一する(0埋めと切捨てを行う) if (massStr.indexOf(".") == -1) { massStr += ".0000"; } else { if (massStr.indexOf(".") != -1) { String [] tmpMzStr = mass...
8
public void setVisited(String direction) { switch(direction){ case "north": // Maak van .getNorth een String String convertString = "" + myRooms[myPlayer.getCurrentroom()].getNorth(); // Als de visited string het nummer van de kamer al in zich heeft, doe dan niks if (this.visited.contains(convertString)){ ...
8
public void paint(Graphics g){ TheColor TC = new TheColor(Color.black); // Set initial color of TheColor class to a default black for(InputSaver s : opener.newPhrase){ // If statements to draw proper shapes on to canvas if(s.phrase.equals("line")){ int x = Integer.parseInt(s.xCoord); int y = Integer.pa...
9
@SuppressWarnings("unused") private void testImage(CoordXZ region, List<Boolean> data) { int width = 32; int height = 32; BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = bi.createGraphics(); int current = 0; g2.setColor(Color.BLACK); for (int x = 0; ...
4
public Set<T> append(T a)// append the element a at the end of a set. { Set<T> res=this; if(res.hasElement(a)) { return res; } else { if(res.next==null) { return new Set(res.a, new Set(a,null));} else { return new Set(res.a, res.next.append(a)); } } }
2
protected void actualizarDisparos(){ if(!disparos.isEmpty()){ Iterator<Disparo> itDisparo = disparos.iterator(); try{ while(itDisparo.hasNext()){ Disparo d = itDisparo.next(); //Movemos el disparo y nos retorna su salud //elimin...
4
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Employee)) { return false; } Employee other = (Employee) object; if ((this.id == null && other.id != null) || (...
5
private int minimax(int m, int dt, Board b, boolean max) { int bestValue; int val; if (dt == 0 || findPossibleMoves(max, b).length == 0) { return getRating(max, b, m); } else if (max == true) { bestValue = Integer.MIN_VALUE; for (int i : findPoss...
5
@Override public void actionPerformed(ActionEvent event) { String url = event.getActionCommand(); if (SITE_URL.equals(url) || PROJECT_URL.equals(url)) { String os = System.getProperty("os.name"); String[] cmd = null; if (os == null) { // error, the...
7
public static void getHrefOfContent(String content) { System.out.println("ʼ"); String[] contents = content.split("<a href=\""); for (int i = 1; i < contents.length; i++) { int endHref = contents[i].indexOf("\""); // String aHref = FunctionUtils....
5
private boolean requiresDownload(Repository repository, Release latestRelease) { boolean requiresDownload = false; HashMap<String, DataFile> fileData = repoFileCache.getIfPresent(repository.getName()); if (fileData == null) { // We have no cached data for this repo. ...
6
public ClientThread(Socket connectionSocket) { this.connectionSocket = connectionSocket; this.connectionID = nextClientThreadID++; }
0
private void button1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button1ActionPerformed try { if (!isLookingForGame() && (sessionImpl == null || !hasGameStarted())) { //unwise System.setSecurityManager(null); //String serverAddres...
6
public boolean equals( Object o ) { // Si l'objecte es null retornem false directament. if ( o == null ) { return false; } // Si és ell mateix retornem true (reciprocitat). if ( o == this ) { return true; } // Si no és una casella, retornem false. if ( !( o instanceof Casella ) ) { retur...
5
private static void handleDir(File dir, ZipOutputStream zipOut) throws IOException { // System.out.println("-----------dir: " + dir.getAbsolutePath()); // System.out.println("-----------dir.isDirectory: " + dir.isDirectory()); FileInputStream fileIn=null; int readedBytes = 0; byte[] buf = new byte[512]; Fi...
9
private boolean checkExistingTab(String className) { boolean exist = false; int count = tabbedPane.getTabCount(); for (int i = 0; i < count; i++) { Component comp = tabbedPane.getComponentAt(i); if(className == comp.getClass().getName()) { tabbedPane.setSelectedIndex(i); ...
2
protected void computeRect(Raster[] sources, WritableRaster dest, Rectangle destRect) { Raster source = sources[0]; Rectangle srcRect = mapDestRect(destRect, 0); int formatTag = MediaLibAccessor.findCompatibleTag(sources,dest); ...
9
@Override public void run() { for (i=0; i <= aantal; i++){ System.out.print(i); } }
1
public static void parseParameter(String arg1, String arg2) { if(arg1.equalsIgnoreCase("-g")) game = arg2; else if(arg1.equalsIgnoreCase("-l")) level = arg2; else if(arg1.equalsIgnoreCase("-a")) actionFile = arg2; else if(arg1.equalsIgnoreCase("-d"...
4
public void setExplored(Tile tile) { tile.setExploredBy(this, true); }
6
public float getCurrentBoxFrame(int x) { float total = 0; for(int a = 0; a<=x; a++) { total += boxFrame.get(a); } return total; }
1
public InputStreamSource(InputStream in) { if (in==null) throw new NullPointerException("in"); this.in = in; }
1
public Type getSpecializedType(Type type) { if (type.typecode == TC_RANGE) type = ((RangeType) type).getBottom(); return type; }
1
public int evalMove(Move m, State s, int depth) { if (depth == 0) { // cutting off search -> evaluate resulting state return evalState(s.tryMove(m)); } else { // minimax-search // update the state State newstate = s.tryMove(m); // get a list of possible moves from newstate MyList moves = ne...
4
public int cdlAbandonedBabyLookback( double optInPenetration ) { if( optInPenetration == (-4e+37) ) optInPenetration = 3.000000e-1; else if( (optInPenetration < 0.000000e+0) || (optInPenetration > 3.000000e+37) ) return -1; return ((( ((( (this.candleSettings[CandleSettingType.Bod...
6