text
stringlengths
14
410k
label
int32
0
9
@Override public int next() { int n = -1; if (start < cs.length()) { n = cs.charAt(start++); offset++; if (n == '\r') { lines++; columns = 0; } else if (n == '\n') { if (offset < 2 || cs.charAt(offset-2) != '\r') { lines++; columns = 0; } } else { columns++; } } el...
5
private static boolean linearSearch(Long number) { for(int j = 0; j < unsorted.length; j++) { if(unsorted[j] == number) { return true; } } return false; }
2
@Test public void isEmptyReturnsTrueAfterEnqueueDequeue() { q.enqueue(0); q.dequeue(); assertTrue(q.isEmpty()); }
0
public static void setStartTime(CallInfo ci, Date start){ ci.setStart(start); }
0
public static void editMember(Member m){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Adress a = m.getAdress(); try{ conn.setAutoCommi...
4
public void teleport(LOGONode argx, LOGONode argy, boolean setX, boolean setY) { if (!setX && !setY) return; if (setX && setY) { Double retx = runAndCheckDouble(argx, "SETXY"); if (LOGOPP.errorhandler.error()) return; Double rety = runAndCheckDouble(argy, "SETXY"); if (LOGOPP.errorhandler.error()...
9
public void setServerVersion(String serverVersion) { this.serverVersion = serverVersion; }
0
public void clearArea(ImageFrame img_frame, int x, int y, int width, int height) { //clear this area from main picture Image img = img_frame.getJIPTImage().getImage(); //get main image int totalWidth = img.getWidth(main_frame); //get main picture width int totalHeight = img.g...
7
public static void binarySearch(int key, int lowerbound, int upperbound, List<Integer> list){ System.out.println("Key: "+ key); int position = (lowerbound + upperbound)/2; while(list.get(position) != key && lowerbound <= upperbound){ position = (lowerbound + upperbound)/2; if(list.get(position) < key...
4
private static void importGliderPosition() throws IOException, SQLException, ClassNotFoundException { String s; while((s = br.readLine()) != null) { String[] gliderPositionData = s.split(",",-1); GliderPosition importer = new GliderPosition(gliderPositionData[1], gliderPositionDa...
3
private void delete(RBNode z) { RBNode x = factory.create(); // work node to contain the replacement node RBNode y; // work node // find the replacement node (the successor to x) - the node one with // at *most* one child. if(z.getLeft() == sentinelNode || z.getRight() == sentinelNode)...
8
@Override public ProductA factoryA() { return new ProductA2(); }
0
* @return <tt>true</tt> if CycFort GENL is a genl of CycFort SPEC * * @throws UnknownHostException if cyc server host not found on the network * @throws IOException if a data communication error occurs * @throws CycApiException if the api request results in a cyc server error */ public boolean isGenlOf...
1
public static String getProcessOutput(String... command) { String out = null; try { ProcessBuilder pb = new ProcessBuilder(command); pb.redirectErrorStream(true); Process process = pb.start(); final BufferedReader bufferedReader = new BufferedReader(new In...
5
private String criarMetodoSalvarAtualizar(String tableName, ResultSetMetaData rsMetadata, String pkey) throws Exception { StringBuilder insertUpdateMetodo = new StringBuilder(); insertUpdateMetodo.append("\n private void salvar" + tableName + "(List<" + tableName + "> lista" + tableName + ") throws E...
9
public void testConstructorEx2_Type_int() throws Throwable { try { new Partial(DateTimeFieldType.dayOfYear(), 0); fail(); } catch (IllegalArgumentException ex) { // expected } }
1
public void onKeyTyped(char c, int i) { if(i == KeyEvent.VK_ESCAPE || (int)c == KeyEvent.VK_ESCAPE) { if(this.currentGui == null) this.setCurrentGui(new GuiMainMenu(null, 0, 0, this.getWidth(), this.getHeight())); else this.setCurrentGui(null); } if(this.currentGui != null) this.currentGui....
4
public void update(float dt) { this.timeElapsed += dt; if (timeElapsed > 1) { this.canBeCaptured = true; } if (this.getBody() != null) { Body body = this.getBody(); if (body.getPosition().x < 0 || body.getPosition().y < 0 || body.getPosition().x > Gdx.graphics.getWidth() / Constants.WORLD_SCALE ...
6
private static void handeClient() { Socket link = null; try { /* * Step 2: put the server into a waiting state */ link = serverSocket.accept(); /* * Step 3 : set up input and output streams between the server and * the client */ Scanner input = new Scanner(link.getInputStream()); ...
3
public Connection getConnection() { if (conn == null) { if (openConnection()) { System.out.println("Connection opened"); return conn; } else { return null; } } return conn; }
2
public void reorderList(ListNode head) { if (head == null || head.next == null) return; ListNode fast = head, slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; if (fast != null) { slow = slow.next; } } ...
9
protected synchronized Runnable getTask() throws InterruptedException { while (taskQueue.size() == 0) { if (!isAlive) { return null; } wait(); } return (Runnable)taskQueue.removeFirst(); }
2
private static boolean isPanlindrome(String s){ for(int i=0;i<s.length()/2;i++){ if(s.charAt(i) != s.charAt(s.length()-i-1)) return false; } return true; }
2
public void setPriority(T item, double newPriority) throws NoSuchElementException { int index; try { index = map.get(item); } catch (NullPointerException npe) { throw new NoSuchElementException(); } ...
5
private boolean doesIntersectInternal(AbstractLineSegment other) { final double d1 = direction(other.getP1(), other.getP2(), this.getP1()); final double d2 = direction(other.getP1(), other.getP2(), this.getP2()); final double d3 = direction(this.getP1(), this.getP2(), other.getP1()); final double d4 = direction...
9
public void add(K key, V value) { List<V> values = this.map.get(key); if (values == null) { values = new LinkedList<V>(); this.map.put(key, values); } values.add(value); }
1
public void testMaximumValue() { DateMidnight dt = new DateMidnight(1570, 1, 1, GJChronology.getInstance()); while (dt.getYear() < 1590) { dt = dt.plusDays(1); YearMonthDay ymd = dt.toYearMonthDay(); assertEquals(dt.year().getMaximumValue(), ymd.year().getMaximumValue...
1
@Override public void getResults(Course curr, StyledDocument doc) { // TODO Auto-generated method stub // Load the default style and add it as the "regular" text Style def = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE ); Style regular = doc.addStyle( "regular", def ); /...
8
public void setAdditionalDisplay(JComponent additionalComponent) { if (currentAdditionalDisplay == null && additionalComponent != null) { if (flowLayout) flowLayoutGatesPanel.setVisible(false); else nullLayoutGatesPanel.setVisible(false); } ...
6
@Override public void paintComponent(Graphics g) { super.paintComponent(g); // paint background // setBackground(Color.BLACK); world.setUnit(player); String report = ""; String victims = ""; for(AUnit u:player.getVictimList()){ victims = victims + " <br> " + u.getUnitName() + " was sunk !!! by " + playe...
8
public WordProcessing() { }
0
public int compare(String[] o1, String[] o2) { int result = 0; for (int i=0;i<o1.length && i<o2.length;i++) { String s1 = o1[i]; String s2 = o2[i]; if (s1 == null) { if (s2 == null) { result = 0; } else { result = 1; } } else { if (s2 == null) { result = -1; } else { ...
9
public UpgradeMenu(ProBotGame game) { super(game); bodypartPanel = new JPanel(); upgradePanel = new JPanel(); }
0
public void setTransitionsFromTuringFinalStateAllowed(boolean t) { transTuringFinal = t; transTuringFinalCheckBox.setSelected(t); }
0
public JSONObject getQuestionsTag(int USER_ID) { try { Class.forName(JDBC_DRIVER); conn=DriverManager.getConnection(DB_URL,USER,PASS); Statement stmt2=conn.createStatement(); stmt=conn.createStatement(); json=new JSONObject(); json.put(SUCCESS, 1); ResultSet rstemp=stmt2.exe...
7
public boolean logar(String login,String senha) throws UnknownHostException, IOException{ if(!login.equals("") && !senha.equals("") && login!=null && senha!=null){ Usuario usuario = new Usuario(); usuario.setSenha(senha); usuario.setUsuario(login); Conexao conexao = new Conexao(12345); conexao.conectar...
4
@Override protected List<URI> parseInternal(BufferedReader in) throws IOException { try { SAXSearchResultParser parser = new SAXSearchResultParser(); parser.parse(new InputSource(in)); List<String> resultStrings = parser.getResults(); List<URI> results = new ArrayList<>(resultStrings.size()); for ...
3
public int peek(boolean fromDiscard){ if (fromDiscard) return discard_count == 0 ? 0 : discard[discard_count-1]; return draw_count == 0 ? 0 : draw[draw_count-1]; }
3
public void outputReport() throws IOException { ListMultimap<String, String[]> commonMap = Multimaps.newListMultimap( new TreeMap<String, Collection<String[]>>() , new Supplier<ArrayList<String[]>>() { @Override public ArrayList<String[]> get() { return new ArrayL...
7
private static String getFileContents(String filename) throws IOException, FileNotFoundException { File file = new File(filename); StringBuilder contents = new StringBuilder(); BufferedReader input = new BufferedReader(new FileReader(file)); try { String line = ...
1
private double parseAngleFields(JTextField degrees, JTextField minutes, JTextField seconds) { double d, m, s; try { d = Double.parseDouble(degrees.getText()); } catch (NumberFormatException nfe) { d = 0.0; } try { m = Double.parseDouble(minutes.getText()); } catch (NumberFormatException nfe) {...
3
@EventHandler(priority = EventPriority.NORMAL) public void onPlayerDeathInArena(PlayerDeathInArenaEvent evt) { Player victim = evt.getVictim(); if (evt.getCause() == DeathCause.ENVIRONMENT) { String lastAttacker = SE.getStorage(victim.getName()).getLastHit(); @SuppressWarnings("deprecation") Player killer...
2
public synchronized void addCommandLineListener(CommandLineListener listener){ List<CommandLineListener> listeners = new ArrayList<CommandLineListener>(); if (this.listeners != null){ listeners.addAll(this.listeners); } if (!listeners.contains(listener)){ listeners.add(listener); } this.listeners =...
2
@Test public void testBigMerge() { Random r = new Random(260379); TreeMap<Integer, Integer> leftSet = new TreeMap<Integer, Integer>(); TreeMap<Integer, Integer> rightSet = new TreeMap<Integer, Integer>(); // There must be collisions and also some omissions for(int i=0; i < ...
8
public Object newArray(String type, int[] dimensions) throws InterpreterException, NegativeArraySizeException { if (type.length() == dimensions.length + 1) { Class clazz; try { clazz = TypeSignature.getClass(type .substring(dimensions.length)); } catch (ClassNotFoundException ex) { throw new...
2
private void selectWord(MouseEvent e) { if (selectedWordEvent != null && selectedWordEvent.getX() == e.getX() && selectedWordEvent.getY() == e.getY()) { // We've already the done selection for this. return; } Action a = null; RTextArea textArea = getTextArea(); ActionMap map = textArea.getAction...
6
@Override public String toString() { StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { if (i != 0) { buf.append(this.delimiter); } buf.append("" + data[i]); } return buf.toString(); }
2
public void addEdge(Vertex v, Vertex w) { if (!adjMap.containsKey(v)) { adjMap.put(v, new HashBag<Vertex>()); } if (!adjMap.containsKey(w)) { adjMap.put(w, new HashBag<Vertex>()); } adjMap.get(v).add(w); adjMap.get(w).add(v); }
2
public void draw(Graphics2D g) { if (gameStates[currentState] != null) gameStates[currentState].draw(g); else { g.setColor(Color.BLACK); g.fillRect(0, 0, GamePanel.WIDTH, GamePanel.HEIGHT); } }
1
@Override public String onAttack(L2Npc npc, L2PcInstance attacker, int damage, boolean isPet) { if (npc instanceof L2ChestInstance) { final L2ChestInstance chest = ((L2ChestInstance) npc); // If this has already been interacted, no further AI decisions are needed. if (!chest.isInteracted()) { ...
4
public String getUniversity() { return this.university; }
0
private PropertyDescriptor getWriteMethod(Field field) throws Exception { PropertyDescriptor descriptor = null; String fieldName = field.getName(); try { PropertyDescriptor[] descriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors(); for (PropertyDescriptor p...
4
public static void main(String[] args) { AccessRight accessRight = AccessRight.MANAGER; AccessRight accessRight1 = AccessRight.valueOf("DEPARTMENT"); chechAccess(accessRight); chechAccess(accessRight1); }
0
private void btnModificarEmpleadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarEmpleadoActionPerformed //creamos un empleado temporal, a partir del renglón seleccionado en la tabla: Empleado empleadoTemporal = obtenerInformacionDeRenglonSelecccionado(); /*Si el ...
6
public int getAttemptsLeft(){ return ReconnectAttempts; }
0
public void destroy() { if (!stopped) { try { worker.join(); } catch (InterruptedException e) { } try { selector.close(); } catch (IOException e) { } } }
3
public DisPane(){ super(); }
0
@SuppressWarnings("unchecked") private <T> TypedStringConverter<T> findConverterQuiet(final Class<T> cls) { if (cls == null) { throw new IllegalArgumentException("Class must not be null"); } TypedStringConverter<T> conv = (TypedStringConverter<T>) registered.get(cls); if ...
5
private void writeSymbolMap() throws IOException { BZip2BitOutputStream bitOutputStream = this.bitOutputStream; final boolean[] blockValuesPresent = this.blockValuesPresent; final boolean[] condensedInUse = new boolean[16]; for (int i = 0; i < 16; i++) { for (int j = 0, k = i << 4; j < 16; j++, k++) { ...
7
public boolean checkRoom(int... pos) { if (pos.length != 2) return true; if (openedRooms[pos[0]][pos[1]]) return false; if (openedRoomsCount >= structure.getRoomsCount()) // cant happen return true; Room room = structure.getRooms()[pos[0]][pos[1]]; if (room == null) return true; opened...
6
@Override public int compareTo(final TPair64 p) { return u == p.u ? 0 : ((u < p.u) ^ (u < 0) ^ (p.u < 0)) ? -1 : 1; // unsigned 64-bit comparison }
2
public void findBestSystem() { for (SoftwareSystem softwareSystem : systems) softwareSystem.refine(); bestSoftwareSystemEP = systems.get(0); bestSoftwareSystemW = systems.get(0); worstSoftwareSystemEP = systems.get(0); worstSoftwareSystemW = systems.get(0); for (SoftwareSystem softwareSystem : systems) {...
6
public boolean hasOverdueItems(){ boolean overdueItemFound = false; for(Copy copy : itemsBorrowed){ if(copy.isOverdue()){ overdueItemFound = true; } } for(Copy copy : booksBorrowed){ if(copy.isOverdue()){ overdueItemFound = true; } } return overdueItemFound; }
4
public void setExtraData(String extraData) { this.extraData=extraData; }
0
public static void main(String args[]) { Scanner sc = new Scanner(System.in); int H, U, D, F; while (true) { H = sc.nextInt(); if (H == 0) { break; } U = sc.nextInt(); D = sc.nextInt(); F = sc.nextInt(); ...
7
@EventHandler public void IronGolemHunger(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getIronGolemConfig().getDouble("IronGolem...
6
@Override public void paintComponent(Graphics g) { // couleur de fond pour le rectangle qui est affiche pour // ne pas avoir de trainee mais un objet qui bouge g.setColor(Color.WHITE); g.fillRect(0, 0, this.getWidth(), this.getHeight()); //on dessine flakboy g.setCol...
8
public void startWave() { if(stage != Stages.RUNNING) return; int currentWave = getCurrentWave(); player.getInterfaceManager().sendTab(player.getInterfaceManager().hasRezizableScreen() ? 11 : 0, 316); player.getPackets().sendConfig(639, currentWave); if(currentWave > WAVES.length) { if(currentWave == 37...
8
@Override public void unInvoke() { if(canBeUninvoked()) { if(affected instanceof MOB) { final MOB mob=(MOB)affected; if((buildingI!=null)&&(!aborted)) { if(messedUp) { if(activity == CraftingActivity.LEARNING) commonEmote(mob,L("<S-NAME> fail(s) to learn how to make @x1.",...
7
public void keyReleased(KeyEvent e) { //Para la entrega Alpha, una vez que se haya inicado el juego, se presiona la tecla 2 para ir al nivel 2, la tecla 3 para ir al nivel 3 // y la tecla G para terminar el juego if (nivel > 0) { if (e.getKeyCode() == KeyEvent.VK_G) { ...
4
public int getType() { if (doc != null) { return TYPE_DOC; } else if (file != null) { return TYPE_FILE; } else { return TYPE_UNKNOWN; } }
2
public CheckResultMessage checkJ02(int day) { return checkReport.checkJ02(day); }
0
public void resize(int x, int y){ Patch[][] newGrid = new Patch[y][x]; for (int i = 0; i<y; i++){ for (int j = 0; j<x; j++){ if (i<getHeight() && j<getWidth()){ newGrid[i][j] = _grid[i][j]; } else newGrid[i][j] = new Patch(this, j, i); } } _grid = newGrid; }
4
public boolean isAuthorized(String password) { if (encryptionDictionary.getRevisionNumber() < 5){ boolean value = standardEncryption.authenticateUserPassword(password); // check password against user password if (!value) { // check password against owner passw...
4
@After public void tearDown() { eventBus = null; }
0
@Override public void run() { final IdFactory _id = IdFactory.getInstance(); _idConection = _id.newId(); getLogger().log(Level.INFO, "Client Thread Started ..."); try { _connection.sendPacket(new SHello(_idConection, "09928")); boolean _while = true; ...
9
public String mapSignature(String signature, boolean typeSignature) { if (signature == null) { return null; } SignatureReader r = new SignatureReader(signature); SignatureWriter w = new SignatureWriter(); SignatureVisitor a = createRemappingSignatureAdapter(w); ...
2
public void setLastName(String lastName) { LastName = lastName; }
0
public static void add(String playerUUID, String regionName) { ArrayList<String> places = Spectacles.storedPlayerData.get(playerUUID); if (!places.contains(regionName)) { places.add(regionName); } Spectacles.storedPlayerData.put(playerUUID, places); save(Spectacles.st...
1
public static void Severe(String s){ log.info("[AprilonIRC] " + s); }
0
private void checkTypeName( String typeName ) { if( !typeName.matches( "[a-zA-Z0-9]+" ) ) { throw new IllegalArgumentException( "typeName contains not supported characters: " + typeName ); } }
1
public static void validateUser(UserTO userTO) throws ParameterValidationException{ System.out.println("Validating userTO"); //Evaluating name System.out.println("Evaluating name"); String name = userTO.getName(); if(!name.matches("[a-zA-Z ]+")){ throw new ParameterValidationException("The name cannot con...
6
public double maxValue(KrakenState state, String player, double alpha, double beta) { if (expandedNodes==maxNodesExpand || game.isTerminal(state)){ if (heuristics==null) return heuristic.h(state); else return getHeuristicFusion(state); } expandedNodes++; double value = Double.NEGATIVE_INFINITY; ...
5
public int getInt(String key) throws JSONException { Object object = this.get(key); try { return object instanceof Number ? ((Number)object).intValue() : Integer.parseInt((String)object); } catch (Exception e) { throw new JSONException("JSO...
2
public static List<Integer> divisors(int n){ List<Integer> divisors = new ArrayList<Integer>(); for(int i =1;i<Math.sqrt(n);i++){ if(n%i == 0){ divisors.add(i); if(i != 1) divisors.add(n/i); } } return divisors; }
3
@Override public String strip(String s) throws Exception { int length = s.length(); char[] oldChars = new char[length + 1]; s.getChars(0, length, oldChars, 0); oldChars[length] = '\0'; // avoiding explicit bound check in while // find first non-printable, // if there...
3
@Override public void run() { while(!manager.stopThreads){ try { //Delay for interval amount of seconds Thread.sleep(1000 * this.getInterval()); System.out.println("Sending HTTP GET to Tracker."); generateTrackerURL(); getTrackerResponse(); if (manager.stopThreads) break; decodeTr...
5
public Double evaluate(HashMap<String, Double> histogram) { if (histogram == null) { return null; } double total = 0.0; for (Double value : histogram.values()) { if (value != null) { if (value >= 0) { total += value; } else { return null; } ...
9
@Override public void setCanceled(boolean isCanceled) { this.isCanceled = isCanceled; }
0
public Map<String, Object> getSymbolsFunctionEnvironmentRecord() { return environmentStack.peek().getSymbolsSymbolTable(); }
0
public void create(Usuario usuario) { if (usuario.getVendaList() == null) { usuario.setVendaList(new ArrayList<Venda>()); } if (usuario.getReservaList() == null) { usuario.setReservaList(new ArrayList<Reserva>()); } EntityManager em = null; try { ...
9
private void setupActionListeners() { openBookListener = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { mainMenuShowing=false; frame.requestFocusInWindow(); layers.setVisible(true); String chosenBook = mainMenuPanel.getChosenBook(); if(chosenBook!=null) ...
5
public void updateOsoba(int index, Osoba newOsoba) { data.set(index, newOsoba); fireTableRowsUpdated(index, index); }
0
public void addDataType(String parameterCode){ String dataType = AirNowDataPoint.getDataTypeName(parameterCode); if (dataType != null) if (dataTypes.indexOf(dataType) == -1) dataTypes.add(dataType); }
2
public static void main(String[] args) { int n=Integer.parseInt(JOptionPane.showInputDialog("Ingrese el rango del vector")); int[] arreglo=new int[n]; int c=0; for (int i = 0; i < arreglo.length; i++) { int numero=Integer.parseInt(JOptionPane.s...
9
public static Board parse(String filename) throws IOException { Preconditions.checkNotNull(filename, "filename cannot be null"); String line; StringBuilder boardBuilder = new StringBuilder(); // Read input file BufferedReader reader = new BufferedReader(new FileReader(filename)); while...
6
@Override public void onPacketSending(PacketEvent event) { switch (event.getPacketID()) { case 0x03: PacketContainer packet = event.getPacket(); String message = packet.getSpecificModifier(String.class).read(0); message = (PerPlayerChatFilter.getI...
2
public void paint(Graphics g) { g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.WHITE); FontMetrics m = g.getFontMetrics(); int y = 0; g.drawString("An error has occurred.", 0, y + m.getAscent()); y += m.getHeight(); g.drawString(status, 0...
1
public void kopioiKuvaUlosJarResourcesTiedostosta(String lahde, String maaranpaa) { File kohdeTiedosto = new File(maaranpaa); if (kohdeTiedosto.exists()) { System.out.println("Tiedosto " + kohdeTiedosto.getPath() + " on jo tallennettuna"); } else { try { ...
4
@Override public String getColumnName(int column){ String name = "??"; switch (column){ case 0: name ="medArbId"; break; case 1: name ="Fornavn"; break; case 2: name ="EfterNavn"; break; case 3: name ="TelefonNr"; break; case 4: name ="Rolle Id"; break; ca...
7