text
stringlengths
14
410k
label
int32
0
9
public static String insert(String s, String insert, int offset) { if (s == null) { return null; } if (insert == null) { return s; } if (offset > s.length()) { offset = s.length(); } StringBuilder sb = new StringBuilder(s); sb.insert(offset, insert); return sb.toString(); }
3
@Override public void run() { try(DatagramSocket workerSocket = new DatagramSocket()) { Sender statusSender = new Sender(workerSocket, remotePort, remoteAddress); if(!isValid()) { statusSender.sendObject(new ERR(ERR.FILE_ALREADY_EXISTS, "The requested file" + request.fileName + " aleardy exists on ...
3
public static void outputResults(LinkedList largest_formable_words, int formable_word_amount){ WordNode next_node; System.out.print("\nLongest Word"); if(largest_formable_words.getSize() > 1) System.out.print("s"); System.out.print(":"); if(largest_formable_words.getSize() > 0){ next_node = larges...
5
@Override public String toString() { if (isDisposed()) { return "VCNTreeItem [Disposed; isWrap=" + isWrap + ", id=" + id + ", foregroundColor=" + foregroundColor + ", isBold=" + isBold + "]"; } return "VCNTreeItem [name = " + getText() + ", isWrap=" + isWrap + ", id=" + id + ", foregroundColo...
1
public void removeZone(String zoneName) { //Intermediate zone variable for use when iterating Zone currentZone; //The index of the zone to be removed. Initialised at 999 so that if //no zone match is found, there is no risk of inadvertently removing //an unintended zone (as would be the case if initialised ...
4
private static String formatLabel(String label) { return (label == null ) ? "" : label; }
1
private void check(int i,int j){ if(i<1|| i<1 || i>gridSize|| j>gridSize){ throw new IllegalArgumentException(); } }
4
public Iterator iterateHashCode(final int hash) { // /#ifdef JDK12 cleanUp(); // /#endif return new Iterator() { private int known = modCount; private Bucket nextBucket = buckets[Math.abs(hash % buckets.length)]; private Object nextVal; { internalNext(); } private void internalNext() { ...
5
public void Profile(){ int opt; System.out.println("Email: "+email+", Nombre: "+name+", Fecha de ingreso: "+fecha); do{ System.out.println("\t1.Cambiar mi email"); System.out.println("\t2.Cambiar mi password"); System.out.println("\t3.Cambiar mi nombre"); ...
8
public Object[] getReaders() { Object[] readers = null; try { readers = PCSCManager.getTerminalsList().toArray(); } catch (CardException e) { JOptionPane.showMessageDialog(null, "Nenhuma leitora instalada", "Erro", JOptionPane.ERROR_MESSAGE); ...
1
private static void studyDatasetBaseLyon() throws IOException, Exception { //study network // for mac neatANN.readInputDataFromExcel(AppProperties.fileName(), AppProperties.answerColNumber()); // for pc //neatANN.readInputDataFromExcel("c:/Users/Administrateur/Desktop/these_softP...
2
public void send() { try { Socket client = new Socket(SHOST, SPORT); ObjectOutputStream os = new ObjectOutputStream(client.getOutputStream()); Message m = new Message(this, "Client", "hello"); os.writeObject(m); os.flush(); ObjectInputStream is = ...
2
@Override public Class<?> getColumnClass(int i) { return Icon.class; }
1
public void removeRoster (Roster roster) { if (roster == null) return; if (rosters.contains(roster.getRosterID())) { rosters.remove ((Object)roster.getRosterID()); } }
2
public void emulate() { ran = false; // tracks if the whole program ran boolean good = true; // tracks if each step was successful // Set the next piece of code to be executed. String code = (String) view.getMemoryTable().getValueAt(programCounter, 0); // Star...
9
static private final boolean cons(int i) { switch (b[i]) { case 'a': case 'e': case 'i': case 'o': case 'u': return false; case 'y': return (i==0) ? true : !cons(i-1); default: return true; } }
7
private void acao137() throws SemanticError { if (idAtual instanceof IdentificadorMetodo) { if (((IdentificadorMetodo) idAtual).getTipo() != null) throw new SemanticError("Método sem tipo esperado"); } else { throw new SemanticError("Identificador de método esperado"); } idMetodoChamado = (Identifi...
2
private void createBoardImage() { Graphics2D g = (Graphics2D) gameBoard.getGraphics(); g.setColor(new Color(0x999999)); g.fillRoundRect(0, 0, BOARD_WIDTH, BOARD_HEIGHT, Tile.ARC_WIDTH, Tile.ARC_HEIGHT); g.setColor(new Color(0x999999)); for (int row = 0; row < ROWS; row++) { for (int col = 0; col < COLS...
2
public CycSymbol readKeyword() throws IOException { String keywordString = (String) readObject(); if (!(keywordString.startsWith(":"))) { keywordString = ":" + keywordString; } return CycObjectFactory.makeCycSymbol(keywordString); }
1
public void setPlayer(int player) { if(player == 2 || player == 1) { this.player = player; } }
2
private void doSubLWorkerTerminated(SubLWorkerEvent event) { Object[] curListeners = getInferenceListeners(); List<Exception> errors = new ArrayList<Exception>(); for (int i = curListeners.length - 1; i >= 0; i -= 1) { try { ((InferenceWorkerListener) curListeners[i]).notifyInferenceTerminated...
3
private User authenticate(Request request) { // Extract authentication credentials String authentication = ((ContainerRequest) request).getHeaderString(HttpHeaders.AUTHORIZATION); if (authentication == null) { throw new AuthenticationException("Authentication credentials are required...
7
public void deletePerson(Person person, ArrayList<Person> list) { int answer = JOptionPane.showConfirmDialog(null, "Do you really want to delete " + person.getName() + "?", " CONFIRMATION ", JOptionPane.YES_NO_OPTION);// displaying // JOptionPane.YES_NO_OPTION // Confi...
2
public void doDead() { if (!isShell) { switch (ai.getDirection()) { case LEFT: setAnimation(new String[]{"koopaDeadLeft"}); break; case RIGHT: setAnimation(new String[]{"koopaDeadRight"}); ...
4
public Set<Map.Entry<K,Double>> entrySet() { return new AbstractSet<Map.Entry<K,Double>>() { public int size() { return _map.size(); } public boolean isEmpty() { return TObjectDoubleMapDecorator.this.isEmpty(); } publi...
6
@Override public GameState use(Game game) { List <Npc> npcs; npcs = game.getCurrentRoom().getNpcs(); Kill killablenpc = null; for(Npc creature : npcs){ if(creature instanceof Killable1){ killablenpc = (Kill) creature; } ...
9
public float[] decodeFloats() { float[] res = new float[decodeInt()]; for (int i = 0; i < res.length; i++) { res[i] = decodeFloat(); } return res; }
1
public ChatServer(ServerInfo serverInfo, int verbose) { this.serverInfo = serverInfo; this.clients = new HashMap<String, Socket>(); this.clientHandlerThread = new Thread[(int) serverInfo.getMaxClients()]; this.verbose = verbose; }
0
public boolean equals( Object o ) { Tuple<T, E> tuple = ( Tuple<T, E> ) o; return tuple.getFirstElement().equals( firstElement ) && tuple.getSecondElement().equals( secondElement ); }
1
private boolean zzRefill() throws java.io.IOException { /* first: make room (if you can) */ if (zzStartRead > 0) { System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead-zzStartRead); /* translate stored positions */ zzEndRead-= zzStartRe...
3
public InputElement makeInput(WebNode node) { //TODO how to keep consistent with isInput method? Use reflection? if (SubmitButton.isSubmit(node)) return new SubmitButton(node); if (Button.isButton(node)) return new Button(node); if (Textarea.isTextarea(node)) ...
9
public void searchSolicitacoes() { facesContext = FacesContext.getCurrentInstance(); ArrayList<String> caminhos = new ArrayList<>(); ArrayList<String> colunas = new ArrayList<>(); ArrayList<String> propertyName = new ArrayList<>(); ArrayList<Object> listObjetos = new ArrayList<>(); caminhos.ad...
5
public BorderPane bottom() { BorderPane bottom = new BorderPane(); AnchorPane slider = new AnchorPane(); Rectangle rectangle = new Rectangle(); rectangle.autosize(); rectangle.setWidth(490); rectangle.setHeight(60); rectangle.setFill(Paint.valueOf(Color.WHITE.to...
9
public void generateTerrain(int par1, int par2, byte[] par3ArrayOfByte) { byte var4 = 4; byte var5 = 16; byte var6 = 63; int var7 = var4 + 1; byte var8 = 17; int var9 = var4 + 1; this.biomesForGeneration = this.worldObj.getWorldChunkManager().getBiomesForGener...
8
public String listItem(User user) { String result = ""; result += "Music: " + super.getName() + " - " + getArtist() + "\n"; if (super.getNumberOfCopies() <= 0 && !super.isElectronicallyAvailable()) { result += "Currently unavailable.\n"; } else { result += "Availa...
9
public void notifyListeners() { if (!boardListener.isEmpty()) { for (int i = 0; i < boardListener.size(); i++) { boardListener.get(i).boardChanged(); } } }
2
@Test public void testBogusStream() throws IOException { final String filename = "test.wav"; final File file = File.createTempFile("testBogusFile", filename); FileOutputStream out = new FileOutputStream(file); final Random random = new Random(); for (int i=0; i<8*1024; i++) {...
8
private int readEscapeChar() { int c = getc(); if (c == 'n') c = '\n'; else if (c == 't') c = '\t'; else if (c == 'r') c = '\r'; else if (c == 'f') c = '\f'; else if (c == '\n') ++lineNumber; return c; ...
5
public static void main(String args[]) { /* float line[] = staggeredLine(17, 2.0f) ; I.say("Line is: ") ; for (float f : line) I.add(((int) (f * 10))+", ") ; //*/ //* final int SIZE = 16 ; List <Coord[]> regions = genRegionsFor(SIZE, 3) ; I.say(regions.size()+" regions gene...
5
public static void checkOutputPath(File targetPath) { if(targetPath != null && targetPath.exists()) { // shows a window which asks you if the old content of the output directory should be deleted // int confirmation = JOptionPane.showConfirmDialog(null, "Output directory not empty. Delete all contents of ...
4
private void parseClassDeclaration() throws SyntaxError { accept(Token.CLASS); parseIdentifier(); accept(Token.LCURLY); while(isStarterDeclarators(currentToken.kind)) { parseDeclarators(); parseIdentifier(); switch(currentToken.kind) { ca...
6
public JMenuItem createSaveItem() { save = new JMenuItem("Save"); save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)); save.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (...
5
private void emitTableConstants() throws IOException { for ( Table table : mModel.getTables() ) { writer.emitSingleLineComment( "Table " + table.name + " constants " ); writer.emitField( "String", SqlUtil.IDENTIFIER( table ), EnumSet.of( Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL ), "\"" + table.name +...
6
public boolean exists(String value) { if (!isEmpty()) { ListElement current = head; while (current != tail.next()) { if (current.getValue().equals(value)) { return true; } current = current.next(); } ...
3
public boolean create(Class<?> layout) { Field[] publicFields = layout.getFields(); if (publicFields.length == 0) { Utilities.outputError("The given table layout '" + layout.getName() + "' for the table '" + m_name + "' has no public fields."); return false; } String createTable = "CREATE TABLE `...
4
private void bowlToHtml(StringBuffer buf) { buf.append("<div>"); // Text information about bowl id buf.append("<div style=\"width: 200px; height: 40px; text-align: center;font-size: 25px; font-weight: bold; font-family: 'Comic Sans MS', cursive, sans-serif\">" + "Bowl #" + round + "," + bowlId ...
6
public static void RegDespesaUI(){ RegDespesaUI nome; }
0
public static Object[] subtract(Object[] A, Object[] B) { // Short-circuit for empty sets (A-{} = A and {}-B = {} = A) if (A == null || A.length == 0 || B == null || B.length == 0) return A; // Clones A, so as to leave it unaffected Object[] Ac = A.clone(); /* Iterates through all the current names, ...
8
public Disciplina pesquisaDisciplina(String codigo) throws DisciplinaInexistenteException { Disciplina listaDisc = null; for (Disciplina e : disciplina) { if (e.getCodigo().equals(codigo)) { listaDisc = e; break; } } if (listaDisc == null) { throw new DisciplinaInexistenteException("Pesquisa...
3
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.equals(Connection.class.getMethod("commit"))) { throw new SQLException(); } else if (method.equals(Connection.class.getMethod("rollback"))) { ...
9
public double[] rawItemStandardDeviations(){ if(!this.dataPreprocessed)this.preprocessData(); if(!this.variancesCalculated)this.meansAndVariances(); return this.rawItemStandardDeviations; }
2
public boolean onTyhja() { return suoritustasot.get(0).onTyhja() && seuraavaArvollinen == null; }
1
public MonopolyResult buy (int playerID, int eventID, boolean buy) { try { if(!_gameManager.isGameExists() || !_gameManager.isGameActive()) { return new MonopolyResult("no active game"); } Event last = _gameManager.ge...
7
public void remove() { throw new UnsupportedOperationException(); }
0
public void indexDocument(Document doc, int docID) { HashSet<String> seenWords = new HashSet<String>(); for (int i=0 ; i<doc.terms.size() ; i++) { String term = doc.terms.get(i); // XXX: this is too simplistic. we must count multiple iterations // of the same term in a doc. if (!invIndex.containsKey(...
4
private void saveShieldStorage() { if (shieldStorageConfig == null || shieldStorageConfig == null) { // Don't save if there is nothing to save return; } // Make a backup of the old storage file just in case File backupFile = new File(directory, "shields.yml.old"); try { // Create backup file i...
6
private static void run() { long ct; ArrayList<MovingComponent> mcal = new ArrayList<MovingComponent>(10); mcal.add(ba); mcal.add(pd); while(true){ // for(int i = 0; i < breakout.sizeOf(); i++){ // breakout.returnComponent(i); // } for (int i = 0; i < mcal.size(); i ++){ mcal.get(i).upda...
4
public static int setMax_period(int new_max_period) { if (new_max_period > 0 && new_max_period >= min_period) { max_period = new_max_period; return max_period; } else { return -1; } }
2
public boolean isSet(String key) { if (key == null) throw new IllegalArgumentException(CLASS + ": key may not be null"); if (!keys.containsKey(key)) throw new IllegalArgumentException(CLASS + ": unknown key: " + key); return keys.get(key).getResultCount() > 0 ? true : false; }
3
protected AutomatonEnvironment getEnvironment() { return environment; }
0
public boolean isDebugging() { return debugging || (parent != null && parent.isDebugging()); }
2
@Override public boolean okMessage(Environmental oking, CMMsg msg) { if((oking==null)||(!(oking instanceof MOB))) return super.okMessage(oking,msg); final MOB mob=(MOB)oking; if(msg.amITarget(mob) &&(msg.targetMinor()==CMMsg.TYP_GIVE) &&(msg.tool() instanceof Coins)) { final String currency=CMLib....
9
public boolean isPrefixOf(ArgPosition otherArgPosition) { if (otherArgPosition == null || otherArgPosition.depth() < depth()) { return false; } else { return path.equals(otherArgPosition.getPath().subList(0, path.size())); } }
2
private void move(int i, int j) { if(i == 0 && j == 1) facingDirection = FORWARD; if(i == 1 && j == 0) facingDirection = RIGHT; if(i == 0 && j == -1) facingDirection = BACKWARD; if(i == -1 && j == 0) facingDirection = LEFT; moveAmountX += getSpeed() * i; moveAmountY += getSpeed() * j; }
8
@Override public void putAll(Map<? extends K, ? extends V> m) { for (Entry<? extends K, ? extends V> entry : m.entrySet()) { put(entry.getKey(), entry.getValue()); } }
5
@Override public void bsp( BSPPeer<NullWritable, NullWritable, NullWritable, NullWritable, NullWritable> peer) throws IOException, SyncException, InterruptedException { int nbRowsBlocks = nbRowsA / blockSize; int nbColsBlocks = nbColsB / blockSize; int nbBlocks = nbRowsBlocks * nbColsBlocks; int b...
6
private Component getHeader() { JButton jbAdd = new JButton("add"); jbAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { Vector<String> newRow = new Vector<String>(); newRow.add("AaValue" + delete_me++); ...
1
public void setLeft(PExp node) { if(this._left_ != null) { this._left_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } ...
3
public static void main(String[] args) { PorterStemmer s = new PorterStemmer(); for (int i = 0; i < args.length; i++) { try { InputStream in = new FileInputStream(args[i]); byte[] buffer = new byte[1024]; int bufferLen, offset, ch; bufferLen = in.read(buffer); off...
7
private Object number() { int length = 0; boolean isFloatingPoint = false; buf.setLength(0); if (c == '-') { add(); } length += addDigits(); if (c == '.') { add(); length += addDigits(); isFloatingPoint = tr...
9
@Override protected void run() { int cycles = 20; EDA eda = (EDA) algorithms.get("EDA"); eda.setConfiguration(this); ClonAlg clonAlg = (ClonAlg) algorithms.get("ClonAlg"); clonAlg.setConfiguration(this); // Calculate max iterations for (int cycle = 0; cycle < cycles; cycle++) { maxIterations...
4
private void doDeleteAll() { System.out.print("\n[Performing DELETE ALL] ... "); try { Statement st = conn.createStatement(); st.executeUpdate("TRUNCATE TABLE COFFEES"); } catch (SQLException ex) { System.err.println(ex.getMessage()); } }
1
private Document createDocument(String data) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setCoalescing(true); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); factory.setValidating(false); Docu...
0
public void felvisz(int i, int j, int k){ if(k==0){ sajat[i][j]=1; sajat[a][b]=9; a=i; b=j; } else{ sajat[i][j]=2; sajat[c][d]=9; c=i; d=j; } }
1
public void removeProp(Entity entity) { if(props.contains(entity)) { props.remove(entity); if(!noChildren()) { for(int x = 0; x<propChildren.length; x++) { propChildren[x].removeProp(entity); } } } }
3
public JobSchedulerBuilder withJobName( String jobName ) { this.jobName = jobName; return this; }
0
private Node findBestNode(){ Node best = open.get (0); for (int i = 0; i < open.size(); i++){ Node temp = open.get (i); if (best.getFinalCost() > temp.getFinalCost()){ best = temp; } } return best; }
2
private static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) { int original_width = imgSize.width; int original_height = imgSize.height; int bound_width = boundary.width; int bound_height = boundary.height; int new_width = original_width; int new_height = original_height; // first check if ...
2
public void calculate() throws IOException { OggStreamAudioData data; // Calculate the headers sizing OggAudioInfoHeader info = headers.getInfo(); handleHeader(info); handleHeader(headers.getTags()); handleHeader(headers.getSetup()); // Have each audio packet ha...
3
public static double getDouble() { double x = 0.0; while (true) { String str = readRealString(); if (str == null) { errorMessage("Floating point number not found.", "Real number in the range " + (-Double.MAX_VALUE) + " to " + Double.MAX_VALUE); } ...
4
@Override public T get(int index) { if (index <= size()) { MyList<T> node = first; for(int i = 1; i < index; i++) { node = node.right; } return node.value; } return null; }
2
private static void calcParam() { if(!fullScreen) { height = defHeight; width = defWidth; } }
1
public int[] importsCount(String[] requires){ n = requires.length; graph = new boolean[n][n]; visited = new boolean[n]; graph = new boolean[n][n]; for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ if(requires[i].charAt(j)=='Y') graph[i][j] = true; ...
7
public int[] getPixels() { return pixels; }
0
public Send(){ super(); }
0
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub }
0
private int read() throws IOException { if (reader != null) return reader.read(); else if (input != null) return input.read(); else throw new IllegalStateException(); }
2
public String getCode() { return code; }
0
private void RangeCheck(int index) { if (index >= size || index < 0) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } }
2
public static Matrix frustum(float left, float right, float bottom, float top, float zNear, float zFar) { if (zNear <= 0.0f || zFar < 0.0f) { throw new RuntimeException( "Frustum: zNear and zFar must be positive, and zNear>0"); } if (left == right || top == bottom) { throw new Runt...
4
public void actionPerformed(ActionEvent e) { Object o = e.getSource(); Debug.print("Action performed on: " + o); if(o == okButton) { // create a new Ferm object Hop i = new Hop(); i.setName(txtName.getText()); i.setAlpha(Double.parseDouble(txtAlpha.getText())); i.setCost(txtCost.g...
6
private void jComboBoxCommandeClientInterlocuteurItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxCommandeClientInterlocuteurItemStateChanged // si changement ou choix interlocuteur if (evt.getStateChange() == ItemEvent.SELECTED) { Interlocuteur interlocuteur ...
2
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); if (!validateFecha(fechaOferta)) { errors.add("fechaOferta", new ActionMessage("error.fecha.invalida")); } if (!validateTelefono(telefono)) { ...
9
private void setResourceURL(URL url) { resource_url = url; }
0
private ctrlDisco() { //Facs = new File("./Data/facturas"); //Clientes = new File("./Data/clientes"); //Coches = new File(":/Data/coches"); if (!Clientes.exists()) { Clientes.mkdirs(); } if (!Coches.exists()) { Coches.mkdirs(); } if...
3
public ParseException generateParseException() { jj_expentries.removeAllElements(); boolean[] la1tokens = new boolean[29]; for (int i = 0; i < 29; i++) { la1tokens[i] = false; } if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 6; i++) { ...
9
public String getName() { return Name; }
0
public void loadProperties() { try { FileInputStream fis = new FileInputStream(new File(Main.USER_PROPS)); props.load(fis); } catch (IOException e) { initProperties(); } if (!validProperties()) initProperties(); this.setBounds(new Integer(props.getProperty("X")).intValue(), new Integer(pro...
2
public void testSaveStranogGosta() { Osoba o = new Osoba(); o.setImePrezime("Alen Kopic"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { o.setDatumRodjenja(sdf.parse("1992-10-21")); } catch (java.text.ParseException p) { System.out.println(p.toString()); } o.setAdresa("Vitkova...
6
public static String[] generateInitialData(final int accountsNumber, final int transferNumber) { List<Future<String>> futures = new ArrayList<>(); ExecutorService threadPool = Executors.newFixedThreadPool(2); futures.add(threadPool.submit(new Callable<String>() { @Ov...
4