text
stringlengths
14
410k
label
int32
0
9
public Transporte recebeuACKde(Transporte t, InetAddress adress){ Transporte t1=new Transporte(initTransportePSH); this.Recebidos.lock(); ArrayList<DatagramPacket> lista = (ArrayList<DatagramPacket>) this.Recebidos.lista.clone(); this.Recebidos.unlock(); for(DatagramPacket p : lista){ if(p.getAddress().equals(adress)){ try { t1 = t1.receberDeDatagramPacket(p); } catch (IOException ex) {} int x = 1; //se enviarmos pacote com seq=0, o ACK recebido vai ter seqAck=1 if( Transporte.byteToInt(t1.getSeqAck(), 2) == Transporte.byteToInt(t.getSeq(), 2) + x ){ this.Recebidos.lock(); this.Recebidos.lista.remove(p); this.Recebidos.unlock(); return t1; } } } return null; }
4
public final void gen_attack_bknight(Board board, int square) { int mobility_all = 0; int mobility_safe = 0; int mobility_total = 0; int attackedSquare; for(int i = 0; i < 8; i++) { attackedSquare = square + knight_delta[i]; if((attackedSquare & 0x88) ==0) { BB[attackedSquare] |= MINOR_BIT; BB[attackedSquare]++; if(board.boardArray[attackedSquare] == EMPTY_SQUARE) { mobility_all++; if((WB[attackedSquare] & PAWN_BIT) == 0) { mobility_safe++; } } } } // The total mobility is 2 times the safe mobility plus the unsafe mobility mobility_total = (2*mobility_safe + mobility_all); // If the piece only can move to one safe square it's mobility is so restricted // that it is likely to be trapped so penalize this if(mobility_safe == 1) { // A 'trapped' piece further up on the board is worse than closer to home // since it risks being captured further up mobility_total -= ((7-Board.rank(square)+1) *5)/2; } // If the piece have no safe squares it is just as good as trapped so penalize // this even harder else if(mobility_safe == 0) { mobility_total -= ((7-Board.rank(square)+1)*5); } evalDetail.mobility.bm += mobility_total; evalDetail.mobility.be += mobility_total; }
6
protected UIComponent createVerbatimComponentFromBodyContent() { UIOutput verbatim = null; String bodyContentString; String trimString; if (null != bodyContent && null != (bodyContentString = bodyContent.getString()) && 0 < (trimString = bodyContent.getString().trim()).length()) { if (!(trimString.startsWith("<!--") && trimString.endsWith("-->"))) { verbatim = createVerbatimComponent(); verbatim.setValue(bodyContentString); bodyContent.clearBody(); } else { StringBuilder content = new StringBuilder(trimString.length()); int sIdx = trimString.indexOf("<!--"); int eIdx = trimString.indexOf("-->", sIdx); while (sIdx >= 0 && eIdx >= 0) { if (sIdx == 0) { trimString = trimString.substring(eIdx + 3); } else { content.append(trimString.substring(0, sIdx)); trimString = trimString.substring(eIdx + 3); } sIdx = trimString.indexOf("<!--"); eIdx = trimString.indexOf("-->", sIdx); } content.append(trimString); String result = content.toString(); if (result.trim().length() > 0) { verbatim = createVerbatimComponent(); verbatim.setValue(content.toString()); } bodyContent.clearBody(); } } return verbatim; }
9
protected boolean needsFill(Point p) { if (p.x < 0 || p.y < 0 || p.x >= source.getWidth() || p.y >= source.getHeight()) return false; return needsFillInBound(p); }
4
private void makeWormTurn(int i, int j) { Worm thisWorm = (Worm) Level[i][j]; if (thisWorm.isChecked()) { return; } HexDirection dir = thisWorm.getWormsNewDirection(); int newX = TranslateDirection(i, j, dir, 'x'); int newY = TranslateDirection(i, j, dir, 'y'); if (newX >= 0 && newX < levelSize && newY >= 0 && newY < levelSize && (Level[newX][newY] == null || Level[newX][newY].is(Bacteria.class))) { moveWormAndEatBacteriaIfAble(thisWorm, newX, newY); //worm moved elsewhere Level[i][j] = null; } else if (!thisWorm.looseWeight()) { //dead worm Level[i][j] = null; } else { evolveIfStuck(thisWorm); } checkOverweightAndMultiplyIfNeeded(i, j, thisWorm, newX, newY); thisWorm.setChecked(true); }
8
void BalWFext( double[][] A) { edge f, g; if ( head.leaf() && tail.leaf() ) distance = A[head.index][head.index]; else if ( head.leaf() ) { f = tail.parentEdge; g = siblingEdge(); distance = 0.5*(A[head.index][g.head.index] + A[head.index][f.head.index] - A[g.head.index][f.head.index]); } else { f = head.leftEdge; g = head.rightEdge; distance = 0.5*(A[g.head.index][head.index] + A[f.head.index][head.index] - A[f.head.index][g.head.index]); } }
3
@Override public void doAction() { if (isRunning) return; isRunning = true; RoundManager roundManager = RoundManager.getInstance(); ScoreManager scoreManager = ScoreManager.getInstance(); MessageDialog messageDialog = MessageDialog.getInstance(); NamesManager namesManager = NamesManager.getInstance(); int nextRound = roundManager.getRound() + 1; int maxRound = roundManager.getMaxRound(); if (maxRound > 0 && nextRound > maxRound) { if (scoreManager.getLeftScore() > scoreManager.getRightScore()) messageDialog.show(namesManager.getLeftName() + " выиграл!"); else if (scoreManager.getLeftScore() < scoreManager.getRightScore()) messageDialog.show(namesManager.getRightName() + " выиграл!"); else messageDialog.show("Ничья!"); ScoreManagerSingleton.getInstance().newGame(); } else { roundManager.setRound(nextRound); } SoundManager.getInstance().resetSounds(); Timer.getInstance().restart(); super.doAction(); }
5
public void decrementAttempts(){ ReconnectAttempts--; }
0
void menuSave() { if (image == null) return; animate = false; // stop any animation in progress // If the image file type is unknown, we can't 'Save', // so we have to use 'Save As...'. if (imageData.type == SWT.IMAGE_UNDEFINED || fileName == null) { menuSaveAs(); return; } Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT); shell.setCursor(waitCursor); imageCanvas.setCursor(waitCursor); try { // Save the current image to the current file. loader.data = new ImageData[] {imageData}; loader.save(fileName, imageData.type); } catch (SWTException e) { showErrorDialog(bundle.getString("Saving_lc"), fileName, e); } catch (SWTError e) { showErrorDialog(bundle.getString("Saving_lc"), fileName, e); } finally { shell.setCursor(null); imageCanvas.setCursor(crossCursor); waitCursor.dispose(); } }
5
public static void start() { GraphDrawer drawer = new GraphDrawer(); drawer.setGraph(GraphInterface.getGraph()); GraphCanvas canvas = new GraphCanvas(drawer); Window w = new Window(canvas); SwingUtilities.invokeLater(w); }
0
public static int getMaxCardsSuite(ArrayList<Card> cards) { int[] suiteCounts = new int[Card.NUM_SUITES]; for (Card card : cards) { suiteCounts[card.suite]++; } int maxSuiteIndex = 0; for (int i = 1; i < suiteCounts.length; i++) { if (suiteCounts[i] > suiteCounts[maxSuiteIndex]) { maxSuiteIndex = i; } } return maxSuiteIndex; }
3
public int buscarIndex(clsEnArticulo[] arreglo, String nombre) { int res=-1; for(int i=0;i<arreglo.length;i++) { if(arreglo[i].getNomprod().equals(nombre)) { res=i; break; } } return res; }
2
public static void init(String _language) { if (replace == null) { replace = new SetOfReplacements(SegmentationConstant.FILE_REPLACE); } if (_language.equals("???")) { System.out.println("default=EN"); _language = "ENGLISH"; } language = _language; String dictionnary = SenseOS.getMYCAT_HOME() + "/config/dict"; readAbreviation(dictionnary + "/" + language + ".txt"); if (_language.equals("FRENCH")) { boundary = BreakIterator.getSentenceInstance(ULocale.FRENCH); } if (_language.equals("ENGLISH")) { boundary = BreakIterator.getSentenceInstance(ULocale.ENGLISH); } if (_language.equals("RUSSIAN")) { boundary = BreakIterator.getSentenceInstance(new ULocale("ru")); } if (_language.equals("ARABIC")) { boundary = BreakIterator.getSentenceInstance(new ULocale("ar")); } if (_language.equals("CHINESE")) { boundary = BreakIterator.getSentenceInstance(ULocale.CHINESE); } if (_language.equals("SPANISH")) { boundary = BreakIterator.getSentenceInstance(new ULocale("es")); } if (_language.equals("PORTUGUESE")) { boundary = BreakIterator.getSentenceInstance(new ULocale("pt")); } }
9
private Class getWrapperClassFromPrimitive(Class t) { if(t == int.class) { return Integer.class; } if(t == short.class) { return Short.class; } if(t == float.class) { return Float.class; } if(t == boolean.class) { return Boolean.class; } if(t == double.class) { return Double.class; } if(t == long.class) { return Long.class; } if(t == char.class) { return Character.class; } return t; }
7
public KAModel() { super(); data = new Vector<Osoba>(); }
0
public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("How many times do you want to repeat the figure (>1)?: "); int repeatTimes = keyboard.nextInt(); System.out.print("Indicate the number of stars (>1): "); int numberOfStars = keyboard.nextInt(); for (int outsideCount = 0; outsideCount < repeatTimes; outsideCount++) { for (int count = numberOfStars; count > 0; count--) { for (int insideCount = 0; insideCount < count; insideCount++) { System.out.print("*"); } System.out.print("\n"); } for (int count = 1; count <= numberOfStars; count++) { for (int insideCount = 0; insideCount < count; insideCount++) { System.out.print("*"); } System.out.print("\n"); } } }
5
protected void _putcatalog() { this._out("/Type /Catalog"); this._out("/Pages 1 0 R"); if ((this.zoomMode == null) && (this.zoomFactor > 0)) { this._out("/OpenAction [3 0 R /XYZ null null " + this.zoomFactor / 100 + "]"); } else if (Zoom.FULLPAGE.equals(this.zoomMode)) { this._out("/OpenAction [3 0 R /Fit]"); } else if (Zoom.FULLWIDTH.equals(this.zoomMode)) { this._out("/OpenAction [3 0 R /FitH null]"); } else if (Zoom.REAL.equals(this.zoomMode)) { this._out("/OpenAction [3 0 R /XYZ null null 1]"); } if (Layout.SINGLE.equals(this.layoutMode)) { this._out("/PageLayout /SinglePage"); } else if (Layout.CONTINUOUS.equals(this.layoutMode)) { this._out("/PageLayout /OneColumn"); } else if (Layout.TWO.equals(this.layoutMode)) { this._out("/PageLayout /TwoColumnLeft"); } }
8
private static boolean isPangram(String in) { int []arr = new int[26]; int BASE_A = 'a'; in.trim(); in=in.toLowerCase(); in=in.replace(" ",""); char []chars = in.toCharArray(); for(char ch : chars){ int c = ch; arr[c-BASE_A] = 1; } boolean flg = true; int i = 0; while(flg && i<26){ if(arr[i]==0){ flg=false; return false; } i++; } return true; }
4
@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=proficiencyCheck(mob,0,auto); if(success) { invoker=mob; final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> whisper(s) to <T-NAMESELF>.^?")); final CMMsg msg2=CMClass.getMsg(mob,target,this,CMMsg.MSK_CAST_MALICIOUS_VERBAL|CMMsg.TYP_MIND|(auto?CMMsg.MASK_ALWAYS:0),null); if((mob.location().okMessage(mob,msg))||(mob.location().okMessage(mob,msg2))) { mob.location().send(mob,msg); mob.location().send(mob,msg2); if(msg.value()<=0) { amountRemaining=300; maliciousAffect(mob,target,asLevel,0,-1); target.location().show(target,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> go(es) under the grip of delirium!!")); } } } else return maliciousFizzle(mob,target,L("<S-NAME> whisper(s) to <T-NAMESELF>, but the spell fades.")); // return whether it worked return success; }
8
public void update(Graphics g) { paint(g); }
0
public boolean hit(final int portal){ if(portal == 1){ this.health1--; for(final Player p : Bukkit.getOnlinePlayers()){ p.playEffect(one, Effect.SMOKE, 0); p.playEffect(one, Effect.SMOKE, 0); p.playEffect(one, Effect.SMOKE, 0); p.playEffect(one, Effect.SMOKE, 0); p.playEffect(one, Effect.SMOKE, 0); p.playEffect(one, Effect.SMOKE, 0); p.playEffect(one, Effect.SMOKE, 0); if(this.health1 > 0) p.playEffect(one, Effect.ZOMBIE_CHEW_WOODEN_DOOR, 0); else p.playEffect(one, Effect.ZOMBIE_DESTROY_DOOR, 0); }if(this.health1 <= 0){ destroyPortal(1); return true; } }else if(portal == 2){ this.health2--; for(final Player p : Bukkit.getOnlinePlayers()){ p.playEffect(two, Effect.SMOKE, 0); p.playEffect(two, Effect.SMOKE, 0); if(this.health2 > 0) p.playEffect(two, Effect.ZOMBIE_CHEW_WOODEN_DOOR, 0); else p.playEffect(two, Effect.ZOMBIE_DESTROY_DOOR, 0); }if(this.health2 <= 0){ destroyPortal(2); return true; } }else throw new IllegalArgumentException("Portal number must be 1 or 2"); return false; }
8
@Test public void test_simple_table() throws ParserConfigurationException, SAXException, IOException{ /* * Arrange */ HtmlView<?> view = new HtmlView(); view.head().title("Dummy Table"); HtmlTable<?> t = view.body() .heading(1, "Dummy Table") .hr() .div() .table(); HtmlTr<?> headerRow = t.tr(); headerRow.th().text("Id1"); headerRow.th().text("Id2"); headerRow.th().text("Id3"); /* * Act */ int[][] output = {{1,2,3},{4,5,6}, {7,8,9}}; for (int i = 0; i < output.length; i++) { HtmlTr<?> tr = t.tr(); for (int j = 0; j < output[i].length; j++) { tr.td().text(output[i][j] + ""); } } ByteArrayOutputStream mem = new ByteArrayOutputStream(); view.setPrintStream(new PrintStream(mem)); view.write(); /* * Assert */ Element elem = DomUtils.getRootElement(mem.toByteArray()); Assert.assertEquals(ElementType.HTML.toString(), elem.getNodeName()); NodeList childNodes = elem.getChildNodes(); Assert.assertEquals(ElementType.HEAD.toString(), childNodes.item(1).getNodeName()); Assert.assertEquals(ElementType.BODY.toString(), childNodes.item(3).getNodeName()); Node div = childNodes.item(3).getChildNodes().item(5); Assert.assertEquals(ElementType.DIV.toString(), div.getNodeName()); Node table = div.getChildNodes().item(1); Assert.assertEquals(ElementType.TABLE.toString(), table.getNodeName()); for (int i = 0; i < output.length; i++) { Node tr = table.getChildNodes().item(3 + i*2); Assert.assertEquals(ElementType.TR.toString(), tr.getNodeName()); for (int j = 0; j < output[i].length; j++) { Node td = tr.getChildNodes().item(j*2 + 1); Assert.assertEquals("td", td.getNodeName()); String val = td.getFirstChild().getNodeValue(); Assert.assertEquals(output[i][j], Integer.parseInt(val)); } } System.out.println(mem.toString()); }
8
private void streamFile(FTPFile fromFile, PipedInputStream pis) throws IOException, FtpWorkflowException, FtpIOException { setConnectionStatusLock(CSL_INDIRECT_CALL); setConnectionStatus(RECEIVING_FILE_STARTED, fromFile, null); setConnectionStatus(RECEIVING_FILE); RetrieveCommand command = new RetrieveCommand(Command.RETR, fromFile, pis); SocketProvider provider = null; if (getConnectionType() == FTPConnection.AUTH_SSL_FTP_CONNECTION || getConnectionType() == FTPConnection.AUTH_TLS_FTP_CONNECTION) { Command pbsz = new Command(Command.PBSZ, "0"); (sendCommand(pbsz)).dumpReply(); Command prot = new Command(Command.PROT, "P"); (sendCommand(prot)).dumpReply(); } // Send TYPE I Command commandType = new Command(connectionTransferType); (sendCommand(commandType)).dumpReply(); Reply commandReply = new Reply(); if (isPassiveMode()) { provider = initDataSocket(command, commandReply); } else { provider = sendPortCommand(command, commandReply); } this.setConnectionStatusLock(FTPConnection.CSL_INDIRECT_CALL); this.setConnectionStatus(FTPConnection.RECEIVING_FILE); command.setDataSocket(provider); // INFO response from ControllConnection is ignored try { command.fetchDataConnectionReply(RetrieveCommand.STREAM_BASED); }catch(IOException ioe) { setConnectionStatus(ERROR); disconnect(); throw ioe; } if (commandReply.getLines().size() == 1) { try { Reply streamReply = ReplyWorker.readReply(socketProvider); streamReply.dumpReply(); streamReply.validate(); }catch(IOException ioe) { setConnectionStatus(ERROR); disconnect(); throw ioe; } } setConnectionStatus(RECEIVING_FILE_ENDED, fromFile, null); setConnectionStatus(IDLE); setConnectionStatusLock(CSL_DIRECT_CALL); }
6
public void addAload(int n) { if (n < 4) addOpcode(42 + n); // aload_<n> else if (n < 0x100) { addOpcode(ALOAD); // aload add(n); } else { addOpcode(WIDE); addOpcode(ALOAD); addIndex(n); } }
2
public static void main(String[] args) { // 对象名,要在反射的时候输入名称,名称需要在SRC文件下的全路径 AbstractDriver driver = AbstractDriver.getInstance("designPattern.factory.abstraction.BmwDriver"); Car car = driver.driverCar(); Bus bus = driver.driverBus(); car.driver(); bus.driver(); }
0
@SuppressWarnings("unused") private static void updateOldJobs() { JobsDatabase oldJob = new JobsDatabase(); int[] refuseSet = {31}; int[] rejectedSet = {12,29,32}; int[] inProcessSet = {49,50,51}; if(refuseSet.length>0){ for(int i=0;i<refuseSet.length;i++){ JobsDatabase.updateJobStatus(jobDBM, "Refuse", Integer.toString(refuseSet[i])); } } if(rejectedSet.length>0){ for(int i=0;i<rejectedSet.length;i++){ JobsDatabase.updateJobStatus(jobDBM, "Rejected", Integer.toString(rejectedSet[i])); } } if(inProcessSet.length>0){ for(int i=0;i<inProcessSet.length;i++){ JobsDatabase.updateJobStatus(jobDBM, "In Process", Integer.toString(inProcessSet[i])); } } }
6
@Override Integer redactEntity(Criteria criteria, AbstractDao dao) throws DaoException { Integer idOrder = (Integer) criteria.getParam(DAO_ID_TOURIST); if (idOrder != null) { return updateTourist(criteria, dao); } else { return createTourist(criteria, dao); } }
1
public void update(String tabName, String value, String column, ArrayList<String> values, ArrayList<String> names){ String statement = "UPDATE " + tabName + " SET " + column + "=? WHERE "; connect(); if(msg.equals("OK")) { for(int i = 0; i < names.size(); i++) { if(i + 1 == values.size()) { statement = statement.concat(names.get(i)+"=?"); } else { statement = statement.concat(names.get(i)+"=? && "); } } try{ PreparedStatement ps = con.prepareCall(statement); try { ps.setInt(1, Integer.parseInt(value)); } catch (Exception e) { ps.setString(1, value); } for(int i = 0; i < values.size(); i++) { try { ps.setInt(i + 2, Integer.parseInt(values.get(i))); } catch (Exception e) { ps.setString(i + 2, values.get(i)); } } ps.executeUpdate(); fireResult("Záznam byl změněn"); } catch (SQLException e) { fireResult(e.getMessage()); } } else { fireResult("No connection"); } close(); }
7
private CarFeature carFeatureParse(String a) { if (a.equals(CarFeature.ABS.toString())) { return CarFeature.ABS; }else if (a.equals(CarFeature.ALARM.toString())) { return CarFeature.ALARM; }else if (a.equals(CarFeature.CAR_AUDIO.toString())) { return CarFeature.CAR_AUDIO; }else if (a.equals(CarFeature.CLIMA.toString())) { return CarFeature.CLIMA; }else if (a.equals(CarFeature.ELECTRICAL_MIRRORS.toString())) { return CarFeature.ELECTRICAL_MIRRORS; }else if (a.equals(CarFeature.ELECTRICAL_WINDOWS.toString())) { return CarFeature.ELECTRICAL_WINDOWS; }else if (a.equals(CarFeature.GPS.toString())) { return CarFeature.GPS; }else if (a.equals(CarFeature.HYDRAULIC_SUSPENSION.toString())) { return CarFeature.HYDRAULIC_SUSPENSION; }else if (a.equals(CarFeature.COMPUTER.toString())) { return CarFeature.COMPUTER; }else { return null; } }
9
public void put(byte[] data, int offset, int len) { if (len == 0) return; synchronized (signal) { // see if we have enough room while (putAvailable() < len) { try { signal.wait(1000); } catch (Exception e) { System.out.println("Put.Signal.wait:" + e); } } // copy data if (putHere >= getHere) { int l = Math.min(len, bufferSize - putHere); System.arraycopy(data, offset, buffer, putHere, l); putHere += l; if (putHere >= bufferSize) putHere = 0; if (len > l) put(data, offset + l, len - l); } else { int l = Math.min(len, getHere - putHere - 1); System.arraycopy(data, offset, buffer, putHere, l); putHere += l; if (putHere >= bufferSize) putHere = 0; } signal.notify(); } }
7
private static String findUsingDP(String str){ int maxLen = 0; int strLen = str.length(); String result = ""; int[][] dpTable = new int[str.length()][str.length()]; for(int i=0;i<strLen;i++){ dpTable[i][i]=1; } for(int i=0;i<=strLen-2;i++){ if(str.charAt(i)==str.charAt(i+1)){ dpTable[i][i+1] = 1; result = str.substring(i,i+2); maxLen = 2; } } for(int l=3;l<=strLen;l++){ for(int i=0;i<=strLen-1;i++){ int j=i+l-1; if(j<str.length()){ if(str.charAt(i)==str.charAt(j)){ dpTable[i][j] = dpTable[i+1][j-1]; if(dpTable[i][j]==1 && l > maxLen){ result = str.substring(i,j+1); maxLen = result.length(); } } else{ dpTable[i][j] = 0; } } } } return result; }
9
public void AssignPlayersInTeams() { for (int i = 0; i < players.size(); i++) { Player p = players.get(i); int team_num = (int) (Math.random() * (NumOfTeams)); teams.get(team_num).AttachPlayer(p); } }
1
public int hasLoop(MySinglyLinkedList first) { if(first == null) // list does not exist..so no loop either. return 0; MySinglyLinkedList slow, fast; // create two references. slow = fast = first; // make both refer to the start of the list. while(true) { slow = slow.nextNode; // 1 hop. if(fast.nextNode != null) fast = fast.nextNode.nextNode; // 2 hops. else return 0; // next node null => no loop. if(slow == null || fast == null) // if either hits null..no loop. return 0; if(slow == fast) { // if the two ever meet...we must have a loop. int cnt = 1; slow = slow.nextNode; StringBuffer buffer = new StringBuffer(); while (slow != fast) { buffer.append(slow.value); cnt++; slow = slow.nextNode; } buffer.append(fast.value); String t = cnt + buffer.toString(); return Integer.parseInt(t); } } }
7
protected final void advance(char c) { cursorState = true; cursorTimer.restart(); switch (c) { case '\n': cursorX = 0; if (++cursorY >= rows) scrollByOneRow(); break; case '\r': break; default: if (++cursorX >= logicalColumns) { cursorX = 0; if (++cursorY >= rows) scrollByOneRow(); } } repaintChar(cursorX, cursorY); }
5
public static AbstractConfigurator getConfigurator(ConfigurationSection globalConfig, AbstractCommand command) { AbstractConfigurator result = new NullConfigurator(); switch (command.getCommandType()) { case BAN: result = new BanConfigurator(globalConfig); break; case UNBAN: result = new UnbanConfigurator(); break; case LIST: result = new ListConfigurator(); break; case RM: result = new RmConfigurator(); break; case HELP: result = new HelpConfigurator(); break; } return result; }
5
public static byte[] encrypt(byte[] data, byte[] key) { byte[] bloc = new byte[16]; key = paddingKey(key); S = generateSubkeys(key); int lenght = 16 - data.length % 16; byte[] padding = new byte[lenght]; padding[0] = (byte) 0x80; for (int i = 1; i < lenght; i++) padding[i] = 0; int count = 0; byte[] tmp = new byte[data.length+lenght]; //afiseazaMatrice(S); int i; for(i=0;i<data.length+lenght;i++){ if(i>0 && i%16 == 0){ bloc = encryptBloc(bloc); System.arraycopy(bloc, 0, tmp, i-16, bloc.length); } if (i < data.length) bloc[i % 16] = data[i]; else{ bloc[i % 16] = padding[count]; count++; if(count>lenght-1) count = 1; } } bloc = encryptBloc(bloc); System.arraycopy(bloc, 0, tmp, i - 16, bloc.length); return tmp; }
6
public static Image createWhiteImage(int height, int width) { Image whiteImage = new RgbImage(width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { whiteImage.setPixel(x, y, Color.WHITE.getRGB()); } } return whiteImage; }
2
public static void setBalance(String uid, double bal) { balance = bal; }
0
public void setTask(Task task) { this.task = task; }
0
public Client(String address, int port) throws ConnectException, IOException { try { clientSocket = new SocketManager(address, port); clientSocket.setSoTimeout(5000); } catch (ConnectException e) { throw new ConnectException(); }catch (IOException e) { throw new IOException(); } }
2
void stepinto() { debugMode = 0; new Memory(); checkpoint.reset(); backend.StepRun.transfer = 0; backend.step_over.otransfer = 0; backend.step_out.common = 0; backend.step_out.call = false; ScanFile.call_count = 0; backend.step_out.next = 0; backend.step_over.ocall = false; backend.step_over.ocommon = 0; backend.step_out.i = 0; backend.step_out.j = 0; backend.step_over.k = 0; backend.step_over.onext = 0; ini_line = 0; fin_line = 0; backend.StepRun.ini_line = 0; backend.StepRun.fin_line = 0; backend.StepRun.initial_pos = 0; BufferedWriter out = null; backend.Register.resetRegisters(); clean_branchtable(); clean_memtable(); FrontEnd.run_stepOut.setEnabled(true); FrontEnd.run_stepOver.setEnabled(true); FrontEnd.r_stepOut.setEnabled(true); FrontEnd.r_stepover.setEnabled(true); FrontEnd.steprun.setEnabled(true); FrontEnd.run_Next.setEnabled(true); FrontEnd.reset.setEnabled(true); try { FrontEnd.exceptionraised = 0; File fin = null; int id = FrontEnd.EditorPane.getSelectedIndex(); backend.Register.r[16].b = 0; backend.ScanFile.current_line = new Integer(0); if (FrontEnd.EditorPane.getToolTipTextAt(id) != null) { // FrontEnd.statuswindow.append("Saving File...\n"); FrontEnd.appendToPane(FrontEnd.statuswindow,"Saving File..\n",Color.BLACK); //frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length()); try { FrontEnd.filepath = FrontEnd.EditorPane.getToolTipTextAt(id); fin = new File(FrontEnd.filepath); out = new BufferedWriter(new FileWriter(fin)); out.write(FrontEnd.activepane.getText()); // FrontEnd.statuswindow.append("PROGRAM STARTED " + FrontEnd.filepath + "\n"); FrontEnd.appendToPane(FrontEnd.statuswindow,"PROGRAM STARTED\n",Color.GREEN); //frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length()); //StepRunWindow obj = new StepRunWindow(new javax.swing.JFrame(), true); backend.ScanFile.path = fin; backend.ScanFile.br = new RandomAccessFile(fin, "r"); int ct_line = 0; backend.ScanFile.br.seek(0); String file_text = frontend.FrontEnd.activepane.getText(); String[] lines = file_text.split("\r\n|\r|\n"); ct_line = lines.length; //System.out.println("number of lines " + ct_line); backend.ScanFile.pos = backend.ScanFile.br.getFilePointer(); //obj.call(fin); FrontEnd.steprun.setVisible(true); FrontEnd.stop_debug_mode.setVisible(true); f = 0; b = new checkpoint(ct_line); FrontEnd.addTab(b); } catch (IOException ex) { FrontEnd.appendToPane(FrontEnd.statuswindow,"Error Occured While Saving File\n",Color.BLACK); // FrontEnd.statuswindow.append("Error occured while saving file...\n"); // FrontEnd.statuswindow.append(ex.getStackTrace().toString()); FrontEnd.appendToPane(FrontEnd.statuswindow,ex.getStackTrace().toString(),Color.BLACK); //frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length()); } finally { try { out.close(); } catch (IOException ex) { //FrontEnd.statuswindow.append("Error occured while saving file...\n"); //FrontEnd.statuswindow.append(ex.getStackTrace().toString()); FrontEnd.appendToPane(FrontEnd.statuswindow,"Error Occured While Saving File\n",Color.BLACK); FrontEnd.appendToPane(FrontEnd.statuswindow,ex.getStackTrace().toString(),Color.BLACK); //frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length()); frontend.FrontEnd.exceptionraised++; } } } else { try { // Create temp file. File temp = File.createTempFile("temp", ".s"); FrontEnd.filepath = null; out = null; try { out = new BufferedWriter(new FileWriter(temp)); out.write(FrontEnd.activepane.getText()); //statuswindow.append("Compiling source file " + filepath + "\n"); // StepRunWindow obj = new StepRunWindow(new javax.swing.JFrame(), true); backend.ScanFile.path = temp; // obj.call(temp); backend.ScanFile.br = new RandomAccessFile(temp, "rw"); backend.ScanFile.pos = backend.ScanFile.br.getFilePointer(); FrontEnd.steprun.setVisible(true); FrontEnd.stop_debug_mode.setVisible(true); int ct_line = 0; backend.ScanFile.br.seek(0); String file_text = frontend.FrontEnd.activepane.getText(); String[] lines = file_text.split("\r\n|\r|\n"); ct_line = lines.length; //System.out.println("number of lines " + ct_line); backend.ScanFile.pos = backend.ScanFile.br.getFilePointer(); //obj.call(fin); FrontEnd.steprun.setVisible(true); FrontEnd.stop_debug_mode.setVisible(true); f = 0; b = new checkpoint(ct_line); FrontEnd.addTab(b); } catch (IOException ex) { FrontEnd.appendToPane(FrontEnd.statuswindow,"Error Occured..\n",Color.BLACK); FrontEnd.appendToPane(FrontEnd.statuswindow,ex.getStackTrace().toString(),Color.BLACK); // FrontEnd.statuswindow.append("Error occured ...\n"); // FrontEnd.statuswindow.append(ex.getStackTrace().toString()); //frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length()); } finally { try { out.close(); } catch (IOException ex) { FrontEnd.appendToPane(FrontEnd.statuswindow,"Error Occured...\n",Color.BLACK); FrontEnd.appendToPane(FrontEnd.statuswindow,ex.getStackTrace().toString(),Color.BLACK); // FrontEnd.statuswindow.append("Error occured ...\n"); // FrontEnd.statuswindow.append(ex.getStackTrace().toString()); //frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length()); //frontend.FrontEnd.exceptionraised++; } } temp.deleteOnExit(); } catch (IOException e) { } } } catch (Exception ex) { Logger.getLogger(FrontEnd.class.getName()).log(Level.SEVERE, null, ex); } }
7
@Override public Item peekFirstItem() { if (packageText().length() == 0) return null; final List<XMLLibrary.XMLTag> buf = CMLib.xml().parseAllXML(packageText()); if (buf == null) { Log.errOut("Packaged", "Error parsing 'PAKITEM'."); return null; } final XMLTag iblk = CMLib.xml().getPieceFromPieces(buf, "PAKITEM"); if ((iblk == null) || (iblk.contents() == null)) { Log.errOut("Packaged", "Error parsing 'PAKITEM'."); return null; } final String itemi = iblk.getValFromPieces( "PICLASS"); final Environmental newOne = CMClass.getItem(itemi); final List<XMLLibrary.XMLTag> idat = iblk.getContentsFromPieces( "PIDATA"); if ((idat == null) || (newOne == null) || (!(newOne instanceof Item))) { Log.errOut("Packaged", "Error parsing 'PAKITEM' data."); return null; } CMLib.coffeeMaker().setPropertiesStr(newOne, idat, true); return (Item) newOne; }
7
@Override public void mouseClicked(MouseEvent me) { for(Entity e : Area.entities) { if(e instanceof Slave) { if(e.distance(me.getX() + View.x, me.getY() + View.y) < 10) { select = e; } } } }
3
public final AbstractPage getChildByURL (URL urlRequested) { for (AbstractPage child: childPages) if (child.url.equals(urlRequested)) return child; return null; }
2
@Override public List<Funcionario> Buscar(Funcionario obj) { // Corpo da consulta String consulta = "select f from Funcionario f WHERE f.ativo = 1 AND f.id != 0 "; // A parte where da consulta String filtro = " "; // Verifica campo por campo os valores que serão filtrados if (obj != null) { //Nome if (obj.getNome() != null && obj.getNome().length() > 0) { filtro += " AND f.nome like '%" + obj.getNome() + "%' "; } //Id if (obj.getId() != null && obj.getId() > 0) { filtro += " AND f.id like '%" + obj.getId() + "%'"; } //Cpf if (obj.getCpf() != null && obj.getCpf().length() > 0) { filtro += " AND f.cpf like '%" + obj.getCpf() + "%'"; } // Se houver filtros, coloca o "where" na consulta if (filtro.length() > 0) { consulta += filtro; } } // Cria a consulta no JPA Query query = manager.createQuery(consulta); // Executa a consulta return query.getResultList(); }
8
@Override public long solve() { byte[] numbers = new byte[2000001]; long sum = 2; int breakpoint = (int) Math.sqrt(20000000); for (int x = 3; x < numbers.length; x += 2) { if (numbers[x] == IS_PRIME) { sum += x; if (x < breakpoint) { strikeOutMultiplesOf(numbers, x); } } } return sum; }
3
public void mouseClicked(java.awt.event.MouseEvent me) { // System.out.println("\n mouseClicked"); TWPoint p = drawBoard_.mapClickToRowAndCol(new TWPoint(me.getPoint())); // System.out.println("mouse click @ " + p.x + "/" + p.y); if (currentState_ == STATE_PLACE_PEG) { tryPlacePeg(p); } else if (currentState_ == STATE_PLACE_LINK_START) { tryPlaceLinkStart(p); } else if (currentState_ == STATE_PLACE_LINK_END) { tryPlaceLinkEnd(p); } else if (commControl_.isConnected() && currentState_ == STATE_NET_START) { if (tryPlacePeg(p)) { // We got the drop on 'em. We go first. // System.out.println("We got the drop on 'em!"); currentPlayerIndex_ = thisPlayerIndex_; setPlayerTurn(currentPlayerIndex_); showMessage("You are Red player."); setYouLabel("Red"); sendState(); } } } // mouseClicked
6
private void buyHoldSell(Stock[] stocks){ int buyTemp=0; int sellTemp=0; int holdTemp=0; buyArray = new Object [buy][10]; sellArray = new Object [sell][10]; holdArray = new Object [hold][10]; Object [][] smallBuy = new Object [buy][6]; Object [][] smallSell = new Object [sell][6]; Object [][] smallHold = new Object [hold][6]; for (Stock currStock: stocks) { if(currStock.getBsh()==BSH.BUY){ columnsInArray(buyArray,currStock,buyTemp); smallArray(smallBuy,currStock,buyTemp); buyTemp++; }else if(currStock.getBsh()==BSH.SELL){ columnsInArray(sellArray,currStock,sellTemp); smallArray(smallSell,currStock,sellTemp); sellTemp++; }else{ columnsInArray(holdArray,currStock,holdTemp); smallArray(smallHold,currStock,holdTemp); holdTemp++; } } buyTable.setModel(new DefaultTableModel( smallBuy, new String [] {"Symbol", "Name", "Last", "Open" , "Close" , "Volume"}){ private static final long serialVersionUID = 1L; @Override public boolean isCellEditable(int row,int column){ return false; } }); sellTable.setModel(new DefaultTableModel( smallSell, new String [] {"Symbol", "Name", "Last", "Open" , "Close" , "Volume"}){ private static final long serialVersionUID = 1L; @Override public boolean isCellEditable(int row,int column){ return false; } }); holdTable.setModel(new DefaultTableModel( smallHold, new String [] {"Symbol", "Name", "Last", "Open" , "Close" , "Volume"}){ private static final long serialVersionUID = 1L; @Override public boolean isCellEditable(int row,int column){ return false; } }); if(buyTemp >= 1){ buyTable.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ if(e.getClickCount()==2){ JTable target = (JTable)e.getSource(); int row = target.getSelectedRow(); printMessage(buyArray,row,"buy"); } } }); } if(sellTemp >= 1){ sellTable.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ if(e.getClickCount()==2){ JTable target = (JTable)e.getSource(); int row = target.getSelectedRow(); printMessage(sellArray,row,"sell"); } } }); } if(holdTemp >= 1){ holdTable.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ if(e.getClickCount()==2){ JTable target = (JTable)e.getSource(); int row = target.getSelectedRow(); printMessage(holdArray,row,"hold"); } } }); } }
9
public static void playGame() { System.out.print("PLAY"); processing(); do { deck.add(playerOneHand.get(playerOneHand.size() - 1)); playerOneHand.remove(playerOneHand.size() - 1); if (compareCards()) { randomPlayer(); } deck.add(playerTwoHand.get(playerTwoHand.size() - 1)); playerTwoHand.remove(playerTwoHand.size() - 1); if (compareCards()) { randomPlayer(); } } while (winCondition()); if (playerOneHand.size() < 1) { System.out.println("Player 2 Wins!"); // break; } else if (playerTwoHand.size() < 1) { System.out.println("Player 1 Wins!"); // break; } System.out.println("Game Over"); }
5
public boolean add(IAliasedItem<T> item) { String key = item.getKey(); if(backingMap.containsKey(key)) { return false; } //IAliasedItem ai = new AliasedItem(item, aliases); backingMap.put(key, item); for(String alias : item.getAllAliases()) { StringList list = aliasesMap.get(alias); if(list == null) { list = new StringList(key); aliasesMap.put(alias, list); } else { list.add(key); if(!list.valid()) { for(String s : list) { backingMap.get(s).removeAlias(alias); } } } } return true; }
5
protected static final synchronized WritableRaster getCachedRaster (ColorModel cm, int w, int h) { if (cm == cachedModel) { if (cached != null) { WritableRaster ras = (WritableRaster) cached.get(); if (ras != null && ras.getWidth() >= w && ras.getHeight() >= h) { cached = null; return ras; } } } // Don't create rediculously small rasters... if (w < 32) w = 32; if (h < 32) h = 32; return cm.createCompatibleWritableRaster(w, h); }
7
private long collatzSteps(long num) { long result=0; cache2.clear(); while(num!=1){ if(cache.get(num)!=null){ result = result+cache.get(num); break; } if(num<0){ print(num, "< 0"); } if(num%2==0){ num=num/2; }else{ num=num*3+1; } result++; cache2.put(num, result); } for(Long i:cache2.keySet()){ if(!cache.containsKey(i)){ cache.put(i, result-cache2.get(i)); } } return result; }
6
public static void play(){ GUI g = new GUI(); }
0
public Collection<V> values() { if (values == null) { values = new AbstractCollection<V>() { public Iterator<V> iterator() { return new ValueIterator(); } public int size() { return LinkedTreeMap.this.size(); } public boolean contains(Object o) { for (Entry<K,V> e = firstEntry(); e != null; e = successor(e)) if (valEquals(e.getValue(), o)) return true; return false; } public boolean remove(Object o) { for (Entry<K,V> e = firstEntry(); e != null; e = successor(e)) { if (valEquals(e.getValue(), o)) { deleteEntry(e); return true; } } return false; } public void clear() { LinkedTreeMap.this.clear(); } }; } return values; }
5
public boolean checkNijikokunPermissions(Player p, String perm) { if (nijikokunPermissions == null) { Plugin plug = parent.getServer().getPluginManager().getPlugin("Permissions"); if (plug != null) { nijikokunPermissions = (com.nijikokun.bukkit.Permissions.Permissions) plug; parent.log.debug("Nijikokun Permissions detected and enabled"); } } if (nijikokunPermissions != null) { parent.log.debug("Running Nijikokun Permissions check on " + p.getName() + " for " + perm); return nijikokunPermissions.getHandler().has(p, perm); } else { return false; } }
3
public static double[][] ordenarPorCercania(double[][] dis){//arreglar double[][] ordenado=new double[11][2]; ordenado[0][0]=dis[0][0]; ordenado[0][1]=dis[0][1]; for(int i=0;i<11;i++){ int min=i; for(int j=i+1;j<11;j++) { if(ordenado[j][0]<ordenado[min][0]) { min=j; } } if(i!=min){ double aux[]=new double[2]; aux[0]=ordenado[i][0]; aux[1]=ordenado[i][1]; ordenado[i][0]=ordenado[min][0]; ordenado[i][1]=ordenado[min][1]; ordenado[min][0] = aux[0]; ordenado[min][1]=aux[1]; } } return ordenado; }
4
public void render(){ x = Game.PLAYER.getCameraX(); y = Game.PLAYER.getCameraY(); if(update > 0){ Font.renderColored("LVL UP", Game.PLAYER.getX() - 6*4, Game.PLAYER.getY() + 32, 2, 1f, 0.8f, 0); update--; } if(renderInventory) Inventory.render(x, y); if(renderQuestLog) QuestLog.render(x, y); if(renderPlayerStats) PlayerStats.render(); if(renderSKillWindow) SkillWindow.render(); renderStandardUI(); renderInfos(); if(renderLootDialog)LootWindow.renderLootDialog(); if(renderPaused)renderPaused(); if(dragItem != null) dragItem.render(x + Mouse.getX(), y + Mouse.getY() - 32); }
8
@Override public void writeBytesToChannel(final DataBuffers buffers) throws IOException { while(buffers.hasNext()) { final ByteBuffer buffer=buffers.next(); while(buffer.hasRemaining()) { appSizedBuf.clear(); if(buffer.remaining() <= appSizedBuf.remaining()) appSizedBuf.put(buffer); else while((buffer.hasRemaining()) && (appSizedBuf.hasRemaining())) appSizedBuf.put(buffer.get()); appSizedBuf.flip(); while(appSizedBuf.hasRemaining()) { final ByteBuffer outBuf=ByteBuffer.allocate(sslOutgoingBuffer.capacity()); sslEngine.wrap(appSizedBuf, outBuf); if(outBuf.position() > 0) { outBuf.flip(); super.writeBytesToChannel(new CWDataBuffers(outBuf, 0, false)); } } } } buffers.close(); }
7
public static <T> boolean ifHasLoop(MyListNode<T> head) { //One pointer advances once at each step, // and the other advances twice at each step. // If the faster pointer meets the slower one again, // there is a loop in the list. // Otherwise, there is no loop if the faster one reaches the end of list. if(head == null) { return false; } MyListNode<T> first = head; MyListNode<T> next = head; while(next!=null && (first==head || first!=next)) { first = first.next; if(next.next != null) { next = next.next.next; } else { return false; } } if(next == null) { return false; } else { return true; } }
6
public static String[] getPageNames(Class<? extends BasePage> pageClass) { int numPages = 0; for (Class<?> clz : pageTypes) { if (pageClass.isAssignableFrom(clz)) { numPages++; } } String[] res = new String[numPages]; int i = 0; for (Class<?> clz : pageTypes) { if (pageClass.isAssignableFrom(clz)) { res[i++] = clz.getName(); } } return res; }
7
public StringList() { this.strings=null; this.numEntries=0; }
0
private int appendSymbolHistory(StringBuilder b, SymbolTable current) { if(current == null) return 0; int indent = appendSymbolHistory(b, current.getParent()); for(Symbol s : current.getDeclarationOrder()) { // Two spaces per indent. for(int i = 0; i < indent; i++) b.append(" "); b.append(String.format("Symbol(%s)\n", s.getName())); } return indent + 1; }
3
private double smooth(int x, int y, BufferedImage image) { double newValue = 0; for(int i = x - 1; i <= x + 1; ++i) { for(int j = y - 1; j <= y + 1; ++j) { newValue += grayscale(image.getRGB(i, j)); } } return newValue/9; }
2
public static int getEnvironmentalTempUnit() throws ClassNotFoundException { int weightUnit = 0; try{ //Class derbyClass = RMIClassLoader.loadClass("lib/", "derby.jar"); Class.forName(driverName); Class.forName(clientDriverName); }catch(java.lang.ClassNotFoundException e) { throw e; } try (Connection connect = DriverManager.getConnection(databaseConnectionName)) { Statement stmt = connect.createStatement(); ResultSet thePilots = stmt.executeQuery("SELECT temp_unit " + "FROM EnvironmentalUnits " + "WHERE unit_set = 0"); while(thePilots.next()) { try { weightUnit = Integer.parseInt(thePilots.getString(1)); }catch(NumberFormatException e) { //TODO What happens when the Database sends back invalid data JOptionPane.showMessageDialog(null, "Number Format Exception in reading from DB"); } } thePilots.close(); stmt.close(); }catch(SQLException e) { JOptionPane.showMessageDialog(null, e.getMessage()); return -1; } return weightUnit; }
4
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); String msj_exito = "Se registro el usuario exitosamente"; String msj_error = "Error al registrar usuario"; HttpSession sesion = request.getSession(true); String tipo_sesion = (String) sesion.getAttribute("identidad"); if (registraUsuario(request, response)) { response.sendRedirect(tipo_sesion + ".jsp?mensaje=" + URLEncoder.encode(msj_exito, "UTF-8") + "&exito=true"); } else { response.sendRedirect(tipo_sesion + ".jsp?mensaje=" + URLEncoder.encode(msj_error, "UTF-8") + "&exito=false"); } }
1
public Image scale(Image img) { // Offset the image by one pixel so there's a border around it. // This lets us avoid having to check that A-I are in range of the image before samping them sourceGraphics.drawImage(img, 1, 1, null); int line = width + 2; for (int y = 0; y < height; y++) { // Two lines of target pixel pointers int tp0 = y * width * 4 - 1; int tp1 = tp0 + width * 2; // Three lines of source pixel pointers int sp0 = (y) * line; int sp1 = (y + 1) * line; int sp2 = (y + 2) * line; // Fill the initial A-I values int A = sourcePixels[sp0]; int B = sourcePixels[++sp0]; int C = sourcePixels[++sp0]; int D = sourcePixels[sp1]; int E = sourcePixels[++sp1]; int F = sourcePixels[++sp1]; int G = sourcePixels[sp2]; int H = sourcePixels[++sp2]; int I = sourcePixels[++sp2]; for (int x = 0; x < width; x++) { if (B != H && D != F) { targetPixels[++tp0] = D == B ? D : E; targetPixels[++tp0] = B == F ? F : E; targetPixels[++tp1] = D == H ? D : E; targetPixels[++tp1] = H == F ? F : E; } else { targetPixels[++tp0] = E; targetPixels[++tp0] = E; targetPixels[++tp1] = E; targetPixels[++tp1] = E; } // Scroll A-I left A = B; B = C; D = E; E = F; G = H; H = I; // Resample rightmost edge C = sourcePixels[++sp0]; F = sourcePixels[++sp1]; I = sourcePixels[++sp2]; } } return targetImage; }
8
@Override public void delete() { Wire start = this.getStartPiece(); Wire end = this.getEndPiece(); if (end.potential != null) { end.potential.delete(); this.circuit.getSimulation().addEvent(end.potential.getNode1(), 0); this.circuit.getSimulation().addEvent(end.potential.getNode2(), 0); } Board board1 = this.circuit.getBoardAt(start.getStartX(), start.getStartY()); Board board2 = this.circuit.getBoardAt(end.getEndX(), end.getEndY()); if (board1 != board2) { if (board1 != null) { board1.interwires.remove(end); } if (board2 != null) { board2.interwires.remove(end); } } if (board2 != null) { board2.wires.remove(end); } while (start != null) { this.circuit.remove(start); start = start.next; } this.circuit.repaint(); }
6
static String[] mergePropertyNames(String[] localNames, String[] sourceNames) { // Set the output names to the other array if one array is null // or zero-length. String[] names = null; if(localNames == null || localNames.length == 0) { names = sourceNames; } else if(sourceNames == null || sourceNames.length == 0) { names = localNames; } else { // Merge the name arrays. // Allocate a Set. Set nameSet = new HashSet((localNames.length+sourceNames.length)/2); // Add source names first as they have lower priority. int numSourceNames = sourceNames.length; for(int i = 0; i < numSourceNames; i++) { nameSet.add(new CaselessStringKey(sourceNames[i])); } // Add local names which will "bump" duplicate source names. int numLocalNames = localNames.length; for(int i = 0; i < numLocalNames; i++) { nameSet.add(new CaselessStringKey(localNames[i])); } // Convert result to an array of Strings. int numNames = nameSet.size(); CaselessStringKey[] caselessNames = new CaselessStringKey[numNames]; nameSet.toArray(caselessNames); names = new String[numNames]; for(int i = 0; i < numNames; i++) { names[i] = caselessNames[i].getName(); } } // Set return value to null if zero-length. if(names != null && names.length == 0) { names = null; } return names; }
9
public static int byteToInt(byte b){ if (b >= 0) return (int) b; else return b + 256; }
1
public static SequenceMove slow(int num, int withMove) { EflUtil.assertNoEfl(); List<Move> moves = new ArrayList<Move>(); int move = num > 0 ? Move.DOWN: Move.UP; if (num < 0) num = -num; if(num > 0) moves.add(new PressButton(move | (num == 1 ? withMove : 0))); for (int i=1; i<num; i++) { moves.add(new SkipInput(1)); moves.add(new PressButton(move | (num == i+1 ? withMove : 0))); } return new SequenceMove(moves.toArray(new Move[0])); }
6
@Override public void run() { System.out.println("Subprocess Ouput RUN"); try { String text ; int n; byte[] buffer; text=""; n=0; buffer= new byte[9096]; System.out.println("Ok"); out.setEditable(true); while ((n = in.read(buffer)) != -1) { // System.out.println("Loop"); text = new String(buffer, 0, n); out.setForeground(c); out.append(text); this.out.setCaretPosition(this.out.getDocument().getLength()); //System.out.println("Returning loop"); } in.close(); System.out.print("Subprocess output:\n" + text); /*OutputStream out = System.out; int n; byte[] buffer = new byte[4096]; while ((n = in.read(buffer)) != -1) { //for(int i=0; i<buffer.length; i++) out.write(buffer, 0, n); out.flush(); }*/ } catch (IOException e) { System.out.println(e+" output"); } }
2
public int compare(String a, String b) { int[][] score = new int[a.length() + 1][b.length() + 1]; for (int i = 0; i <= a.length(); i++) { score[0][i] = i; } for (int j = 0; j <= b.length(); j++) { score[j][0] = j; } for (int i = 1; i <= a.length(); i++) { for (int j = 1; j <= b.length(); j++) { int p = min(score[i - 1][j], score[i - 1][j - 1], score[i][j - 1]); score[i][j] = (a.charAt(i - 1) != b.charAt(j - 1) ? p + 1 : p); } } for (int i = 0; i <= a.length(); i++) { for (int j = 0; j <= b.length(); j++) { System.out.print(score[i][j] + " "); } System.out.println(); } return score[a.length()][b.length()]; }
7
static int hex2num(char hex) { if ((hex >= '0') && (hex <= '9')) return (hex - '0'); else if ((hex >= 'a') && (hex <= 'f')) return (hex - 'a' + 10); else if ((hex >= 'A') && (hex <= 'F')) return (hex - 'A' + 10); else throw (new IllegalArgumentException()); }
6
private Command findCommand(String name) { for (Command command : commands) if (command.getName().equals(name)) return command; return null; }
2
public boolean checkIfMiddleInitial(String checkString) { if(checkString.matches(".*\\d.*")) return false; if(checkString.length() == 2 || checkString.length() == 1) { if(checkString.charAt(0) == '.') return false; if(this.checkPeriod(checkString)) return true; } return false; }
5
public static TestPanel getTestPanel() { if (testPanel == null) { testPanel = new TestPanel(); } return testPanel; }
1
public void onUpdate() { if (this.isEntityAlive()) { this.lastActiveTime = this.timeSinceIgnited; int var1 = this.getCreeperState(); if (var1 > 0 && this.timeSinceIgnited == 0) { this.worldObj.playSoundAtEntity(this, "random.fuse", 1.0F, 0.5F); } this.timeSinceIgnited += var1; if (this.timeSinceIgnited < 0) { this.timeSinceIgnited = 0; } if (this.timeSinceIgnited >= 30) { this.timeSinceIgnited = 30; if (!this.worldObj.isRemote) { if (this.getPowered()) { this.worldObj.createExplosion(this, this.posX, this.posY, this.posZ, 6.0F); } else { this.worldObj.createExplosion(this, this.posX, this.posY, this.posZ, 3.0F); } this.setDead(); } } } super.onUpdate(); }
7
private float func_1224_a(int i, int j, int k, Material material) { int l = 0; float f = 0.0F; for (int i1 = 0; i1 < 4; ++i1) { int j1 = i - (i1 & 1); int l1 = k - (i1 >> 1 & 1); if (this.blockAccess.getBlockMaterial(j1, j + 1, l1) == material) { return 1.0F; } Material material1 = this.blockAccess.getBlockMaterial(j1, j, l1); if (material1 == material) { int i2 = this.blockAccess.getBlockMetadata(j1, j, l1); if (i2 >= 8 || i2 == 0) { f += BlockFluid.getFluidHeightPercent(i2) * 10.0F; l += 10; } f += BlockFluid.getFluidHeightPercent(i2); ++l; } else if (!material1.isSolid()) { ++f; ++l; } } return 1.0F - f / (float) l; }
6
public static void main(String[] args) { Random randGen = new Random(); Scanner input = new Scanner(System.in); int n = input.nextInt(); String[] cards = {"2", "3", "4", "5", "6", "7" ,"8", "9", "10", "J","Q", "K", "A"}; char[] suits = { '♣', '♦', '♥', '♠' }; ArrayList<String> Deck = new ArrayList<String>(); for (int i = 0; i < cards.length; i++) { for (int j = 0; j < suits.length; j++) { Deck.add(cards[i] + suits[j]); } } for (int i = 0; i < n; i++) { String result = ""; for (int j = 0; j < 5; j++) { result+= Deck.get(randGen.nextInt(52)); } System.out.println(result); } }
4
private void processGetReplica(Sim_event ev) { if (ev == null) { return; } Object[] data = (Object[]) ev.get_data(); if (data == null) { return; } String filename = (String) data[0]; // get name Integer sender = (Integer) data[1]; // get destination // if our catalogue contains the file, we immediately send it back Object[] dataTemp = new Object[2]; dataTemp[0] = filename; /**** // DEBUG System.out.println(super.get_name() + ".processGetReplica(): for " + filename + " from " + GridSim.getEntityName(sender.intValue())); ****/ ArrayList list = (ArrayList) catalogueHash_.get(filename); if (list != null) { dataTemp[1] = (Integer) list.get(0); super.send(super.output, 0, DataGridTags.CTLG_REPLICA_DELIVERY, new IO_data(dataTemp,Link.DEFAULT_MTU,sender.intValue()) ); } else { dataTemp[1] = senderID_; waitingReplicaRequest_.add(data); super.send(super.output, 0, DataGridTags.CTLG_GET_REPLICA, new IO_data(dataTemp, Link.DEFAULT_MTU, getHigherLevelRCid()) ); } }
3
public int Area(int[] height,int sta,int end){ if(sta > end){ return 0; }else{ int minIndex = minHeight(height,sta,end); int areaT = (end-sta+1)* height[minIndex]; int areaL = Area(height,sta,minIndex-1); int areaR = Area(height,minIndex+1,end); return Math.max(Math.max(areaL, areaR),areaT); } }
1
public static synchronized void addConnectionBackToPool(Connection c) { if(c != null) { usedConnections.removeElement(c); availableConnections.addElement(c); } }
1
@Override public void storeArray(Float a[],int column) { //store array as column in AL for(int i=0;i<a.length;i++) { switch(column) { case 0: attribute1.remove(i); attribute1.add(i, a[i]); break; case 1: attribute2.remove(i); attribute2.add(i, a[i]); break; case 2: attribute3.remove(i); attribute3.add(i, a[i]); break; case 3: attribute4.remove(i); attribute4.add(i, a[i]); break; case 4: attribute5.remove(i); attribute5.add(i, a[i]); break; case 5: attribute6.remove(i); attribute6.add(i, a[i]); break; case 6: attribute7.remove(i); attribute7.add(i, a[i]); break; } } }
8
public int next() { int value = -1; try { value = m.getElement(next_point[0], next_point[1]); calculateNext(); } catch(Matrix.MatrixError e) {} return value; }
1
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AddFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AddFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AddFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AddFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { AddFuncionario dialog = new AddFuncionario(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
6
private static int sum(int... nums) { int sum = 0; for(int element: nums) { sum = sum + element; } return sum; }
1
private static void addMetadata( OtuWrapper originalWrapper, File inFile, File outFile, boolean fromR) throws Exception { HashMap<String, MetadataParser> metaMap = MetadataParser.getMap(); BufferedReader reader = new BufferedReader(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); writer.write("key\tprimers\tsample\treadNumber\tcaseControl\tnumSequences\tshannonDiversity"); String[] splits = reader.readLine().split("\t"); for( int x= (fromR ? 0 : 1); x < splits.length; x++ ) writer.write("\t" + splits[x].replaceAll("\"", "")); writer.write("\n"); for(String s = reader.readLine(); s != null; s = reader.readLine()) { splits = s.split("\t"); StringTokenizer pToken = new StringTokenizer(splits[0].replaceAll("\"", ""),"_"); String key = splits[0].replaceAll("\"", ""); String sample = pToken.nextToken().replaceAll("\"", ""); writer.write(key + "\t" + pToken.nextToken( ) + "\t" + sample + "\t" + key.substring(key.lastIndexOf("_")+1, key.lastIndexOf("_")+2) + "\t"); System.out.println( key + " " + sample); MetadataParser mdp = metaMap.get(sample); Integer val = mdp == null ? null : mdp.getCaseControl() ; writer.write( ( val == null ? "NA" : val ) + "\t" + originalWrapper.getNumberSequences(key) + "\t" + originalWrapper.getShannonEntropy(key)); for( int x=1; x < splits.length; x++) writer.write("\t" + splits[x]); writer.write("\n"); } writer.flush(); writer.close(); reader.close(); }
6
public boolean rd_play( int i, int j, int val ){ int nval = -val; int i1 = i+1; int j1=j+1; while( i1<values.length && j1<values[0].length && values[i1][j1] == nval ){ i1++; j1++; } if( i1<values.length && j1<values[0].length && i+1 < i1 && values[i1][j1] == val ){ // Valid play for( int k=i+1; k<i1; k++ ){ j++; values[k][j] = val; } return true; } return false; }
8
public void Puntajes() throws IOException { try { String nomArchivo = "Datos.txt"; // Nombre del archivo de texto BufferedReader fileIn = new BufferedReader(new FileReader(nomArchivo)); int apunta = -1; // Apuntador auxiliar para cambiar el nombre int[] arreglo; // Arreglo auxiliar donde guardar los puntajes del .txt arreglo = new int[5]; // De tamanio 5 String[] nombres; // Arreglo auxiliar donde guardar los nombres nombres = new String[5]; //Leer los nombres y puntajes //nom1 = fileIn.readLine(); nombres[0] = fileIn.readLine(); arreglo[0] = Integer.parseInt(fileIn.readLine()); //nom2 = fileIn.readLine(); nombres[1] = fileIn.readLine(); arreglo[1] = Integer.parseInt(fileIn.readLine()); // nom3 = fileIn.readLine(); nombres[2] = fileIn.readLine(); arreglo[2] = Integer.parseInt(fileIn.readLine()); //nom4 = fileIn.readLine(); nombres[3] = fileIn.readLine(); arreglo[3] = Integer.parseInt(fileIn.readLine()); //nom5 = fileIn.readLine(); nombres[4] = fileIn.readLine(); arreglo[4] = Integer.parseInt(fileIn.readLine()); fileIn.close(); //Auxiliares de reacomodo int aux; int aux2; String ayuda; String ayuda2; for (int i = 0; i < 5; i++) { // Recorre el arreglo completamente if (puntos > arreglo[i]) { // Si el puntaje actual es mayor al de la posicion actual del arreglo //Reemplaza el valor y reacomoda todo el arreglo aux = arreglo[i]; ayuda = nombres[i]; arreglo[i] = puntos; nombres[i] = playerName; apunta = i; for (int j = i + 1; j < 5; j++) { aux2 = arreglo[j]; ayuda2 = nombres[j]; arreglo[j] = aux; nombres[j] = ayuda; aux = aux2; ayuda = ayuda2; } i = 6; // Sale del ciclo } } //Reasignar los valores de mejores puntajes con sus respectivos nombres punt1 = arreglo[0]; nom1 = nombres[0]; punt2 = arreglo[1]; nom2 = nombres[1]; punt3 = arreglo[2]; nom3 = nombres[2]; punt4 = arreglo[3]; nom4 = nombres[3]; punt5 = arreglo[4]; nom5 = nombres[4]; switch (apunta) { // Sirve para sustituir el nombre correspondiente y su puntaje case 0: nom1 = playerName; break; case 1: nom2 = playerName; break; case 2: nom3 = playerName; break; case 3: nom4 = playerName; break; case 4: nom5 = playerName; break; } //Reescribir en el archivo de texto los mejores puntajes PrintWriter fileOut = new PrintWriter(new FileWriter(nomArchivo)); fileOut.println(nom1); fileOut.println(punt1); fileOut.println(nom2); fileOut.println(punt2); fileOut.println(nom3); fileOut.println(punt3); fileOut.println(nom4); fileOut.println(punt4); fileOut.println(nom5); fileOut.println(punt5); fileOut.close(); } catch (IOException e) { // Si no existe el archivo, crea uno y escribe los valores default String nomArchivo = "Datos.txt"; PrintWriter fileOut = new PrintWriter(new FileWriter(nomArchivo)); fileOut.println(nom1); fileOut.println(punt1); fileOut.println(nom2); fileOut.println(punt2); fileOut.println(nom3); fileOut.println(punt3); fileOut.println(nom4); fileOut.println(punt4); fileOut.println(nom5); fileOut.println(punt5); fileOut.close(); } }
9
public void originalVerticesLocal(double paramDistancia,double paramRadio) { Iterator elemFuente; Elemento entrada,salida; Iterator elemDestino = destino.listaElementos(); double sumaDistancias,sumaValores,distancia,ponderacion; while(elemDestino.hasNext()) //Recorre elementos destino { sumaDistancias = sumaValores = 0; // inicializa sumas salida = (Elemento)((Entry)elemDestino.next()).getValue(); elemFuente = fuente.listaElementos(); //carga fuentes while(elemFuente.hasNext()) //recorre elementos fuente { entrada = (Elemento)((Entry)elemFuente.next()).getValue(); distancia = distancia(entrada,salida); if(distancia < paramRadio) { ponderacion = Math.pow(distancia, paramDistancia); sumaDistancias += 1/ponderacion; sumaValores += entrada.valor() / ponderacion; } } salida.valor(sumaValores / sumaDistancias); } }
3
public void setMessage(String message) { this.message = message; }
0
private void enterRule(NonTerminal productionRule) { if(root == null) { root = current = new ParseNode(productionRule, null); return; } ParseNode newNode = new ParseNode(productionRule, null); newNode.Parent = current; if(current.FirstChild == null) current.FirstChild = newNode; else { ParseNode lastChild = current.FirstChild; while(lastChild.Sibling != null) lastChild = lastChild.Sibling; lastChild.Sibling = newNode; } current = newNode; }
3
private Class getElementTypeFromGenerics (Type type) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; Type rawType = parameterizedType.getRawType(); if (isCollection(rawType) || isMap(rawType)) { Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (actualTypeArguments.length > 0) { return (Class)actualTypeArguments[actualTypeArguments.length - 1]; } } } return null; }
4
@FXML public void handleAddToCenter(MouseEvent e) throws Exception{ String resourceURL = null ; ImageView ev = (ImageView)e.getSource() ; if(ev.getId().equals("departmentImageView")){ resourceURL = "/application/department/addDepartmentDocument.fxml" ; }else if(ev.getId().equals("teacherImageView")){ resourceURL = "/application/etacher/addTeacherDocument.fxml" ; }else if(ev.getId().equals("roomImageView")){ resourceURL = "/application/room/addRoomDocument.fxml" ; }else if(ev.getId().equals("courseImageView")){ resourceURL = "/application/course/addCourseDocument.fxml" ; }else if(ev.getId().equals("yearImageView")){ resourceURL = "/application/year/addYearDocument.fxml" ; }else if(ev.getId().equals("sectionImageView")){ resourceURL = "/application/year/addSectionDocument.fxml" ; }else if(ev.getId().equals("subjectImageView")){ resourceURL = "/application/subject/addSubjectDocument.fxml" ; } Pane child = FXMLLoader.load(getClass().getResource(resourceURL)) ; Adder.addToCenter(workplacePane , child); animation = new ScaleAnimation(scaleProperty); animation.animate(child); }
7
private boolean stringIsNullOrEmpty(String str) { return (str == null || str.length() == 0); }
1
public boolean containsConflictingLoad(MatchableOperator op) { if (op.matches(this)) return true; for (int i = 0; i < subExpressions.length; i++) { if (subExpressions[i].containsConflictingLoad(op)) return true; } return false; }
3
public void setFactory( ConnectionFactory factory ) { this.factory = factory; if( site != null ){ if( factory == null ){ site.listening(); } else{ trigger(); } } }
2
public void spread(World wld){ float newX, newY, newZ; newX = x; newY = y; newZ = z; Random rndGen = new Random(); int direction = rndGen.nextInt(9) + 1; switch (direction) { case 1: newX = x - 1; newZ = z - 1; wld.EntityArray.add(new Plant(newX,newY,newZ)); break; case 2: newX = x - 1; wld.EntityArray.add(new Plant(newX,newY,newZ)); break; case 3: newX = x - 1; newZ = z + 1; wld.EntityArray.add(new Plant(newX,newY,newZ)); break; case 4: newZ = z - 1; wld.EntityArray.add(new Plant(newX,newY,newZ)); break; case 5: break; case 6: newZ = z + 1; wld.EntityArray.add(new Plant(newX,newY,newZ)); break; case 7: newX = x = 1; newZ = z - 1; wld.EntityArray.add(new Plant(newX,newY,newZ)); break; case 8: newX = x + 1; wld.EntityArray.add(new Plant(newX,newY,newZ)); break; case 9: newX = x + 1; newZ = z + 1; wld.EntityArray.add(new Plant(newX,newY,newZ)); break; } }
9
private static byte[] buildOid(String hex) { byte[] oid = new byte[SIZE]; for (int i = 0; i < HEX_SIZE; ++i) { char c = hex.charAt(i); if (c >= '0' && c <= '9') { c -= '0'; } else if (c >= 'a' && c <= 'f') { c -= 'a' - 10; } else if (c >= 'A' && c <= 'F') { c -= 'A' - 10; } else { throw new IllegalArgumentException(String.format("Invalid character in sha1: {0}", c)); } oid[i / 2] |= (i % 2) == 0 ? (byte) (c << 4) : (byte) c; } return oid; }
8
@Basic @Column(name = "address_1") public String getAddress1() { return address1; }
0