text
stringlengths
14
410k
label
int32
0
9
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = in.readLine(); int n = Integer.parseInt(line); int dates[]; ArrayList<laptop> lista = new ArrayList<laptop>(); for (int i = 0; i < n; i++) { dates = atoi(in.readLine()); lista.add(new laptop(dates[0], dates[1])); } Collections.sort(lista); int minPrice = lista.get(0).price; int minQ = lista.get(0).q; int maxQ = lista.get(0).q; boolean k = false; for (int i = 1; i < lista.size() && !k; i++) { if (lista.get(i).price > lista.get(i - 1).price) { if (lista.get(i).q < maxQ) { k = true; } } else if (lista.get(i).price == lista.get(i - 1).price) { if (lista.get(i).q < minQ && lista.get(i).price > minPrice) { k = true; } } minQ = Math.min(minQ, lista.get(i).q); maxQ = Math.max(maxQ, lista.get(i).q); } if (k) { System.out.println("Happy Alex"); } else { System.out.println("Poor Alex"); } }
9
private void processLsCommand() { if (processClasses.isEmpty()) { System.out.println("No migratable program "); } else { System.out.println("All migratable programs:"); System.out.println("-------------------------------"); Iterator<Class<? extends MigratableProcess>> it = processClasses.iterator(); while (it.hasNext()) { Class<? extends MigratableProcess> processClass = it.next(); System.out.println(processClass.getSimpleName()); } } }
4
public void setDeadZone(int index, float zone) { deadZones[index] = zone; }
0
@EventHandler public void GiantStrength(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.getGiantConfig().getDouble("Giant.Strength.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getGiantConfig().getBoolean("Giant.Strength.Enabled", true) && damager instanceof Giant && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, plugin.getGiantConfig().getInt("Giant.Strength.Time"), plugin.getGiantConfig().getInt("Giant.Strength.Power"))); } }
6
public void processDamagedCells(final StyledTextConsumer consumer) { final int startRow = 0; final int endRow = myHeight; final int startCol = 0; final int endCol = myWidth; myLock.lock(); try { for (int row = startRow; row < endRow; row++) { TextStyle lastStyle = null; int beginRun = startCol; for (int col = startCol; col < endCol; col++) { final int location = row * myWidth + col; if (location < 0 || location > myStyleBuf.length) { LOG.error("Requested out of bounds runs: pumpFromDamage"); continue; } final TextStyle cellStyle = myStyleBuf[location]; final boolean isDamaged = myDamage.get(location); if (!isDamaged) { if (lastStyle != null) { //flush previous run flushStyledText(consumer, row, lastStyle, beginRun, col); } lastStyle = null; } else { if (lastStyle == null) { //begin a new run beginRun = col; lastStyle = cellStyle; } else if (!cellStyle.equals(lastStyle)) { //flush prev run and start of a new one flushStyledText(consumer, row, lastStyle, beginRun, col); beginRun = col; lastStyle = cellStyle; } } } //flush the last run if (lastStyle != null) { flushStyledText(consumer, row, lastStyle, beginRun, endCol); } } } finally { myLock.unlock(); } }
9
private boolean charIsAlpha() throws EOSReachedException { char c = this.getChar(); return (c >= 65 && c <= 90) || (c >= 97 && c <= 122); }
3
public static boolean toBoolean(int value) { boolean result; if (value == TessAPI.TRUE) { result = true; } else if (value == TessAPI.FALSE) { result = false; } else { throw new IllegalArgumentException("Invlid boolean value. Expected " + TessAPI.TRUE + " or " + TessAPI.FALSE + ". Got " + value); } return result; }
2
public void setPosition() { setLocation(x,y); setImage(bondImage); if (speed > maxSpeed) { speed = maxSpeed; } else if (movement) { speed++; } else { speed = 0; } if (x<0) { x = 0; } else if (x>1000) { x = 1000; } if (energy < energyMax) { energy+= 0.1; } if (hitpoint <= 0.0) { hitpoint = 0.0; dead = true; imageFrames = 4; } }
6
public void redoSquares() { for (int y = 0; y < squares.length; y++) { for (int x = 0; x < squares[y].length; x++) { /*for (int a = 0; a < squares[y][x].length; a++) { squares[y][x][a] = null; }*/ sqSizes[y][x] = 0; } } int start = sliceStart * squareSize; int end = (sliceStart + sliceWidth) * squareSize; for (int i = 0; i < atoms.length; i++) { Atom at = atoms[i]; if (at.x >= start && at.x < end) { int y = ((int) at.y) / squareSize; int x = ((int) at.x) / squareSize - sliceStart; squares[y][x][sqSizes[y][x]++] = at; if (sqSizes[y][x] == squares[y][x].length) { Atom[] as = squares[y][x]; Atom[] newAs = new Atom[as.length * 2]; System.arraycopy(as, 0, newAs, 0, as.length); squares[y][x] = newAs; } } } }
6
public void changeImg(String s){ if(s.equals("dead")) curImg = dead; else if(s.equals("left")) curImg = left[0]; else if(s.equals("right")) curImg = right[0]; else if(s.equals("leftHarmed")) curImg = leftHarmed; else if(s.equals("rightHarmed")) curImg = rightHarmed; }
5
@Override public void init() { super.init(); lc = getByteAt( 0 ); fc = getByteAt( 1 ); rowIndex = ByteTools.readShort( getByteAt( 2 ), getByteAt( 3 ) ); int pos = 4; for( int i = 0; i < ((lc - fc) + 1); i++ ) { try { int type = getByteAt( pos++ ); switch( type ) { case 0: // empty pos += 8; break; case 1: // numeric cachedValues.add( new Float( ByteTools.eightBytetoLEDouble( getBytesAt( pos, 8 ) ) ) ); pos += 8; break; case 2: // string short ln = ByteTools.readShort( getByteAt( pos ), getByteAt( pos + 1 ) ); byte encoding = getByteAt( pos + 2 ); pos += 3; if( encoding == 0 ) { cachedValues.add( new String( getBytesAt( pos, ln ) ) ); pos += ln; } else {// unicode cachedValues.add( new String( getBytesAt( pos, ln * 2 ), "UTF-16LE" ) ); pos += ln * 2; } break; case 4: // boolean cachedValues.add( getByteAt( pos + 1 ) == 1 ); pos += 8; break; case 16: // error cachedValues.add( new String( "Error Code: " + getByteAt( pos + 1 ) ) ); pos += 8; break; } } catch( Exception e ) { } } }
8
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + ((color == null) ? 0 : color.hashCode()); result = prime * result + radius; return result; }
1
@Column(name = "percent") @Id public double getPercent() { return percent; }
0
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EmployeeUser that = (EmployeeUser) o; return id == that.id && !(employee != null ? !employee.equals(that.employee) : that.employee != null) && !(password != null ? !password.equals(that.password) : that.password != null) && !(username != null ? !username.equals(that.username) : that.username != null); }
9
public boolean editShipInBounds(Ship ship) { if(myTurnEditing) return mySea.shipInBounds(ship); else return theirSea.shipInBounds(ship); }
1
private static int binarySearch(int[] A, int target, int l, int r) { while (l <= r) { int mid = l + (r - l) / 2; if (target > A[mid]) { l = mid + 1; } else if (target == A[mid]) { return mid; } else { r = mid - 1; } } return -1; }
3
public synchronized boolean mergeIntoMemberList(Process process) { int index = process.getGlobalList().indexOf(getAlteredNode()); MemberNode matchingNode = index == -1 ? null : process.getGlobalList().get(index); if (checkIsIntructionJoinVariant()) { if (matchingNode == null && /* && checkHasJoinArrivedLate() */ (process.getRecentLeftNode() == null || !process.getRecentLeftNode() .equals(getAlteredNode()) || getAlteredNode() .getTimeStamp() .after(process .getRecentLeftNode().getTimeStamp()))) { process.getGlobalList().add(getAlteredNode()); return true; } else if (matchingNode.getTimeStamp().before( getAlteredNode().getTimeStamp())) { matchingNode.setTimeStamp(getAlteredNode().getTimeStamp()); return true; } } else { if (matchingNode != null && matchingNode.getTimeStamp().before( getAlteredNode().getTimeStamp())) { process.getGlobalList().remove(getAlteredNode()); process.setRecentLeftNode(getAlteredNode()); return true; } else { process.setRecentLeftNode(getAlteredNode()); } } return false; }
9
@Override public Void doInBackground() throws IOException { if (taskOption == TaskOptions.EXPORT) { if (!exportStory()) { // Show popup to user that exporting failed JOptionPane.showMessageDialog( Main.this, "Exporting failed!", "Error", JOptionPane.ERROR_MESSAGE); } } else if (taskOption == TaskOptions.IMPORT) { if (!importStory()) { // Show popup to user that exporting failed JOptionPane.showMessageDialog( Main.this, "Importing failed!", "Error", JOptionPane.ERROR_MESSAGE); } } return null; }
4
public final void SetStream(InputStream stream) { Stream = stream; }
0
static Object js_createAdpter(Context cx, Scriptable scope, Object[] args) { int N = args.length; if (N == 0) { throw ScriptRuntime.typeError0("msg.adapter.zero.args"); } Class superClass = null; Class[] intfs = new Class[N - 1]; int interfaceCount = 0; for (int i = 0; i != N - 1; ++i) { Object arg = args[i]; if (!(arg instanceof NativeJavaClass)) { throw ScriptRuntime.typeError2("msg.not.java.class.arg", String.valueOf(i), ScriptRuntime.toString(arg)); } Class c = ((NativeJavaClass) arg).getClassObject(); if (!c.isInterface()) { if (superClass != null) { throw ScriptRuntime.typeError2("msg.only.one.super", superClass.getName(), c.getName()); } superClass = c; } else { intfs[interfaceCount++] = c; } } if (superClass == null) superClass = ScriptRuntime.ObjectClass; Class[] interfaces = new Class[interfaceCount]; System.arraycopy(intfs, 0, interfaces, 0, interfaceCount); Scriptable obj = ScriptRuntime.toObject(cx, scope, args[N - 1]); Class adapterClass = getAdapterClass(scope, superClass, interfaces, obj); Class[] ctorParms = { ScriptRuntime.ContextFactoryClass, ScriptRuntime.ScriptableClass }; Object[] ctorArgs = { cx.getFactory(), obj }; try { Object adapter = adapterClass.getConstructor(ctorParms). newInstance(ctorArgs); return getAdapterSelf(adapterClass, adapter); } catch (Exception ex) { throw Context.throwAsScriptRuntimeEx(ex); } }
7
public void run() { Thread thisThread = Thread.currentThread(); while (running) { try { if (reset > -1) { clearScreenAndReset(reset); } offscreenGraphics.setPaintMode(); nextpoints(alg); Thread.sleep(100); long diff = (System.currentTimeMillis() - lastRunTime); if (diff > 5000) { lastRunTime = System.currentTimeMillis(); updateHistogram(); } painter.repaint(); // ew fire event } catch (Exception e) { e.printStackTrace(); } } System.out.println("run() exited: " + thisThread.toString()); }
4
boolean isAttackPlaceHorizontallyLeftNotHarming(int position, char[] boardElements, int dimension, int leftPosition) { while (leftPosition > 0) { if (isPossibleToPlaceLeft(position, dimension, leftPosition) && isBoardElementAnotherFigure(boardElements[position - leftPosition])) { return false; } leftPosition--; } return true; }
3
@Override public void show () { shapeRenderer = new ShapeRenderer(); renderer = new Box2DDebugRenderer(); playerSprite = Util.createSquareSprite(Pixels.toMeters(Gdx.graphics.getWidth() / 8), Pixels.toMeters(Gdx.graphics.getHeight() / 8), Color.BLUE); playerSprite.setPosition(-playerSprite.getWidth() / 2 - 5 * .05f, Pixels.toMeters(-Gdx.graphics.getHeight() / 2)); shieldParts = new ShieldPart[4]; float width = 5, height = 1; Objects.world = Objects.createWorld(); Objects.world.setContactListener(new ShieldMinigameContactManager(this)); for (int i = 0; i < 4; i++) { Vector2 position = new Vector2(i * width - width * 2 + 2, Pixels.toMeters(-Gdx.graphics.getHeight() / 2) + playerSprite.getHeight() * 1.5f); BodyDef bodyDef = new BodyDef(); bodyDef.position.set(position); bodyDef.type = BodyType.KinematicBody; Body body = Objects.world.createBody(bodyDef); Box2DSprite sprite = new Box2DSprite(Util.createSquareSprite(Meters.toPixels(width), Meters.toPixels(height), Color.WHITE)); body.setUserData(sprite); PolygonShape shape = new PolygonShape(); shape.setAsBox(width / 2, height / 2); FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = shape; fixtureDef.filter.categoryBits = Values.PLAYER_CATEGORY_BITS; fixtureDef.filter.maskBits = Values.PLAYER_MASK; Fixture f = body.createFixture(fixtureDef); shieldParts[i] = new ShieldPart(body, sprite); shieldParts[i].setBoosted(false); shape.dispose(); f.setUserData(shieldParts[i]); } manager = new EnemyShootsManager(level); Vector2 badguyPosition = new Vector2(-playerSprite.getWidth() / 2 + playerSprite.getWidth() / 2, Pixels.toMeters(Gdx.graphics.getHeight() / 2) - 1); BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyType.KinematicBody; bodyDef.position.set(badguyPosition); Body body = Objects.world.createBody(bodyDef); Box2DSprite sprite = new Box2DSprite(Util.createSquareSprite(Pixels.toMeters(Gdx.graphics.getWidth() / 8), Pixels.toMeters(Gdx.graphics.getHeight() / 8), Color.RED)); body.setUserData(sprite); FixtureDef fixtureDef = new FixtureDef(); PolygonShape shape = Util.createShapeBox(sprite.getWidth() / 2, sprite.getHeight() / 2); fixtureDef.shape = shape; fixtureDef.filter.categoryBits = Values.BADGUY_CATEGORY_BITS; fixtureDef.filter.maskBits = Values.BADGUY_MASK; Fixture f = body.createFixture(fixtureDef); badguy = new ShieldMinigameBadguy(body, level); f.setUserData(badguy); shape.dispose(); }
1
@Override public boolean equals(final Object o) { if(this == o) return true; if(o == null || getClass() != o.getClass()) return false; final InnerDataSubscription that = (InnerDataSubscription)o; if(_aspect != null ? !_aspect.equals(that._aspect) : that._aspect != null) return false; if(_attributeGroup != null ? !_attributeGroup.equals(that._attributeGroup) : that._attributeGroup != null) return false; if(_object != null ? !_object.equals(that._object) : that._object != null) return false; return true; }
9
public static void writeEvent(PrintWriter pw, CalendarEvent evt) { pw.println("BEGIN:VCALENDAR"); pw.println("CALSCALE:GREGORIAN"); pw.println("VERSION:2.0"); pw.println("METHOD:PUBLISH"); pw.println("BEGIN:VEVENT"); pw.printf("UID: %s%n", evt.getUuid()); Calendar c = Calendar.getInstance(); pw.printf("LAST-MODIFIED:%s%n", dateString(c)); pw.printf("DTSTAMP:%s%n", dateString(c)); pw.printf("DTSTART:%s%n", dateString(evt.getYear(), evt.getMonth(), evt.getDay(), evt.getStartHour(), evt.getStartMinute())); pw.printf("DTEND:%s%n", dateString(evt.getYear(), evt.getMonth(), evt.getDay(), evt.getEndHour(), evt.getEndMinute())); pw.println("TRANSP:OPAQUE"); pw.printf("X-MICROSOFT-CDO-BUSYSTATUS: %s%n", evt.getShowStatus()); pw.println("SEQUENCE:0"); pw.println("DESCRIPTION: " + evt.getDescription()); pw.println("SUMMARY: " + evt.getSummary()); pw.println("LOCATION: " + evt.getLocation()); pw.println("CLASS:PUBLIC"); if (evt.getOrganizer() != null) { Person o = evt.getOrganizer(); pw.printf( "ORGANIZER;ROLE=REQ-PARTICIPANT;CUTYPE=INDIVIDUAL;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=%s:MAILTO:%s%n", o.getFullName(), o.getEmail()); } if (evt.getAttendees() != null) { for (Person attendee : evt.getAttendees()) { pw.printf( "ATTENDEE;ROLE=REQ-PARTICIPANT;CUTYPE=INDIVIDUAL;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=%s:MAILTO:%s%n", attendee.getFullName(), attendee.getEmail()); } } pw.println("END:VEVENT"); pw.println("END:VCALENDAR"); }
3
public int getSize() { return size; }
0
@Override protected Result unhandledKeyboardEvent(Key key) { if(getSelectedIndex() == -1) return Result.DO_NOTHING; if(key.getKind() == Key.Kind.Enter || key.getCharacter() == ' ') { if(itemStatus.get(getSelectedIndex()) == true) itemStatus.set(getSelectedIndex(), Boolean.FALSE); else itemStatus.set(getSelectedIndex(), Boolean.TRUE); } return Result.DO_NOTHING; }
4
static double getDaysInYearFromBasis( int basis, long date0, long date1 ) { double r = 0; switch( basis ) { case 0: // 30/360 case 2: // actual/360 case 4: // 30/360 (EURO) r = 360; break; case 1: // actual/actual GregorianCalendar fromDate = (GregorianCalendar) DateConverter.getCalendarFromNumber( new Long( date0 ) ); int y0 = fromDate.get( Calendar.YEAR ); if( isLeapYear( y0 ) ) { r = 365.4; } else { r = 365.25; } // r= (date1-date0)/yearFrac(basis, date0, date1); break; case 3: r = 365; // actual/365 break; } return r; }
6
public static void main(String... args) { ByteBuffer byteBuffer = ByteBuffer.allocate(10); byteBuffer.put((byte) 3); //此处如果不flip的话,那么取出来的就是0. byteBuffer.flip(); System.out.println(byteBuffer.get()); byteBuffer.clear(); for (int i = 0; i < 10; i++) { if (i != 5) { byteBuffer.put(i, (byte) i); } else { byteBuffer.put(i, (byte) 64); } } // 这里不要flip() 因为一旦flip,就会找不到坐标为5的位置 // byteBuffer.flip(); System.out.println(byteBuffer.get(5)); byte[] bytes = {10, 20, 30, 40, 50, 60}; byteBuffer.clear(); // 这里的第二个参数和第三个参数是offset和length 是对数据来说的,bytebuffer依然按照position来读. byteBuffer.put(bytes, 3, 2); System.out.println("_____"); for (int i = 0; i < byteBuffer.capacity(); i++) { System.out.println(byteBuffer.get(i)); } // 这里必须flip,使指针归位. byteBuffer.flip(); byte[] _bytes = new byte[5]; //这里的第二三个参数也是按照数组来说的,bytebuffer的读写都是根据position来处理. byteBuffer.get(_bytes, 3, 2); System.out.println("&&&"); for (int i = 0; i < _bytes.length; i++) { System.out.println(_bytes[i]); } }
4
private Shape mPolygonShapeParser(Shape shape){ // Obtenemos las coordenadas de cada punto del shape for (int x = 0; x < shape.getPoligons().size(); x++){ Coordinate[] coor = shape.getCoordenadas(x); // Miramos por cada punto si existe un nodo, si no lo creamos for (int y = 0 ; y < coor.length; y++){ // Insertamos en la lista de nodos del shape, los ids de sus nodos List<String> l = new ArrayList<String>(); l.add(shape.getShapeId()); shape.addNode(x,utils.generateNodeId(shape.getCodigoMasa(), coor[y], null, l)); } } // Partimos el poligono en el maximo numero de ways es decir uno por cada // dos nodos, mas adelante se juntaran los que sean posibles for (int x = 0; x < shape.getPoligons().size() ; x++){ List <Long> nodeList = shape.getNodesIds(x); for (int y = 0; y < nodeList.size()-1 ; y++){ List<Long> way = new ArrayList<Long>(); way.add(nodeList.get(y)); way.add(nodeList.get(y+1)); if (!(nodeList.get(y) == (nodeList.get(y+1)))){ List<String> shapeIds = new ArrayList<String>(); shapeIds.add(shape.getShapeId()); shape.addWay(x,utils.generateWayId(shape.getCodigoMasa(), way, shapeIds)); } } } // Creamos una relation para el shape, metiendoe en ella todos los members List <Long> ids = new ArrayList<Long>(); // Ids de los members List <String> types = new ArrayList<String>(); // Tipos de los members List <String> roles = new ArrayList<String>(); // Roles de los members for (int x = 0; x < shape.getPoligons().size() ; x++){ List <Long> wayList = shape.getWaysIds(x); for (Long way: wayList) if (!ids.contains(way)){ ids.add(way); types.add("way"); if (x == 0)roles.add("outer"); else roles.add("inner"); } } List<String> shapeIds = new ArrayList<String>(); shapeIds.add(shape.getShapeId()); shape.setRelation(utils.generateRelationId(shape.getCodigoMasa(), ids, types, roles, shape.getAttributes(), shapeIds)); return shape; }
9
public static boolean loadTreeNetworkTest(){ //!!! TEST WILL FAIL IF EQUALS COMPARES TREE IDs!!! int portTemp=TaskClientNetDriver.SERVER_PORT; InetAddress tempAddress=TaskClientNetDriver.SERVER_ADDRESS; TaskClientNetDriver.SERVER_PORT=TEST_PORT; try {TaskClientNetDriver.SERVER_ADDRESS=InetAddress.getLocalHost();} catch (UnknownHostException e) {} try { final NetworkInteraction interaction = new NetworkInteraction(); IDGenerator idGenerator= new IDGenerator(); Data data = new Data("test string"); final TaskTree tree = new TaskTree(idGenerator, data); interaction.setTree(tree); //Faking transfer: Thread fakeThread = new Thread(){ public void run() { ServerSocket server=null; Socket fakeServer=null; ObjectInputStream fakeServerInput=null; ObjectOutputStream fakeServerOutput=null; try { server = new ServerSocket(TEST_PORT); fakeServer=server.accept(); fakeServerInput=new ObjectInputStream(fakeServer.getInputStream()); fakeServerOutput=new ObjectOutputStream(fakeServer.getOutputStream()); NetworkInteraction fakeInteraction=(NetworkInteraction) fakeServerInput.readObject(); //faking transmission from server: fakeInteraction.setTree(tree); fakeInteraction.setReplyCode(NetworkInteraction.ReplyCode.SUCCESS); fakeServerOutput.writeObject(fakeInteraction); fakeServerOutput.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (server!=null) server.close(); if (fakeServer!=null) fakeServer.close(); if (fakeServerInput!=null) fakeServerInput.close(); if (fakeServerOutput!=null) fakeServerOutput.close(); } catch (IOException e) { e.printStackTrace(); } } } }; fakeThread.start(); TaskTree loadedTree=TaskClientNetDriver.loadTree(); if (!loadedTree.equals(tree)) { throw new Exception("Tree that arrived from fake server differs"); } fakeThread.join(); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { TaskClientNetDriver.SERVER_PORT=portTemp; TaskClientNetDriver.SERVER_ADDRESS=tempAddress; } }
9
private static <T> void printDFSStack(List<Node<T>> adjList) { Stack<Node<?>> stk = new Stack<>(); for (Node<T> node:adjList) { Map<Node<?>, Integer> track = new HashMap<>(); System.out.print(node + "->"); track.put(node, 2); // if (track.get(node) == null) { // track.put(node, 1); stk.push(node); while (!stk.isEmpty()) { Node<?> nodei = stk.pop(); if (track.get(nodei) < 2) { System.out.print(nodei + "->"); track.put(nodei, 2); } for (Node<?> nodej:nodei.nextNodes) { if (track.get(nodej) == null) { track.put(nodej, 1); stk.push(nodej); } } } // } System.out.println(""); } }
9
static boolean isBoardElementAnotherFigure(char boardElement) { return !isBoardElementEmpty(boardElement) && (boardElement == BISHOP.getFigure() || boardElement == ROOK.getFigure() || boardElement == KING.getFigure() || boardElement == KNIGHT.getFigure() || boardElement == QUEEN.getFigure()); }
5
private InitialCondition makeInitialCondition(Parameters p) { if (p.getIC().equals("ProducerCheater")) { // One cheater in a 5x5 block of cooperators, with the rest // of the space empty return new ProducerCheater(p); } else if (p.getIC().equals("ProducerCheaterClump")) { // A 3x3 block of cheaters inside of a 9x9 block of cooperators. // Hence, a total of 9 cheaters and 72 cooperators. The rest // of the space is empty. return new ProducerCheaterClump(p); } else if (p.getIC().equals("TwoCities")) { // A single cheater on one side and a cooperator on the other, // placed as far apart as possible on a horizontal line. return new TwoCities(p); } else if (p.getIC().equals("WellMixed")) { // A space-filling population consisting of cooperators and // cheaters in user-specified proportions. return new WellMixed(p); } else if (p.getIC().equals("SingleInvader")) { // Actually just a special case of "WellMixed," except the // invader is at the center of the simulation for convenience return new SingleProducer(p); } else if (p.getIC().equals("CheaterDisc")) { // A disc of cheaters with specified radius in a field of producers. return new CheaterDisc(p); } else if (p.getIC().equals("ProducerDisc")) { // A disc of producers with specified radius in a field of cheaters. return new ProducerDisc(p); } else if (p.getIC().equals("TwoDomains")) { // A disc of producers with specified radius in a field of cheaters. return new TwoDomains(p); } else throw new IllegalArgumentException("Unrecognized IC " + p.getIC()); }
8
public Dimension getPreferredSize(JComponent c) { String tipText = ((JToolTip)c).getTipText(); if (tipText == null) return new Dimension(0,0); textArea = new JTextArea(tipText ); rendererPane.removeAll(); rendererPane.add(textArea ); textArea.setWrapStyleWord(true); int width = ((MultiLineToolTip)c).getFixedWidth(); int columns = ((MultiLineToolTip)c).getColumns(); if( columns > 0 ) { textArea.setColumns(columns); textArea.setSize(0,0); textArea.setLineWrap(true); textArea.setSize( textArea.getPreferredSize() ); } else if( width > 0 ) { textArea.setLineWrap(true); Dimension d = textArea.getPreferredSize(); d.width = width; d.height++; textArea.setSize(d); } else { textArea.setLineWrap(false); } Dimension dim = textArea.getPreferredSize(); dim.height += 1; dim.width += 1; return dim; }
3
private void clearReferences(DatabaseUpdater updater, MergeMapping mapping) throws UpdateException { if (mapping.isManyToMany()) { String query = "DELETE FROM "+DB.ESCAPE+"" + mapping.getMappingTable() + ""+DB.ESCAPE+" WHERE "+DB.ESCAPE+"" + mapping.getColumnFrom() + ""+DB.ESCAPE+" = '" + mapping.getValueFrom() + "'"; if (!updater.execute(query)) { throw new UpdateException("unable to insert relation to mappingtable"); } } else if (mapping.isManyToOne()) { String query = "UPDATE "+DB.ESCAPE+"" + mapping.getMappingTable() + ""+DB.ESCAPE+" SET "+DB.ESCAPE+"" + mapping.getColumnFrom() + ""+DB.ESCAPE+" = 'NULL' WHERE "+DB.ESCAPE+"" + mapping.getColumnFrom() + ""+DB.ESCAPE+" = '" + mapping.getValueFrom() + "'"; if (!updater.execute(query)) { throw new UpdateException("unable to insert relation to mappingtable"); } } }
4
public void mousePressed(MouseEvent event) { if(end == false){ //x = z; z = getCardPressed(event.getX(), event.getY()); //top.setText("" + z + ""); //Integer i = new Integer(z); //if(i != -1 && z != x) count++; //if(cardSelect == true) //{ //if(count >= 12) cardSelect = false; //String s = new String(); //s = i.toString(); if(z == -1) { top.setText("NOT VALID"); } else { if(phase == 0 || phase == 1) { if(tmpDeck.getCard(z).status() == false) //this function (what ever it does) covered the whole else part of the //if else statement, it was looking through tmpDeck but that isnt even used //in phase 2............. wow austin { top.setText(tmpDeck.getCard(z).getTitle()); } else { top.setText("PICKED "); z = -1; } } if(phase == 2) { top.setText("" + z + ""); if(z < 3) { //System.out.println(p1.getDeck().getCard(z).getTitle()); top.setText(p1.getDeck().getCard(z).getTitle()); } if(z >= 3) //this is needed to show other players cards { //System.out.println(p2.getDeck().getCard(z - 3).getTitle()); top.setText(p2.getDeck().getCard(z - 3).getTitle()); } } //z = z-3; // top.setText(p2.getDeck().getCard(z).getTitle()); } repaint(); //top.setText("" + z + ""); //top.setText("x = " + event.getX() + ", y = " + event.getY() + "."); //} } }
8
void menu() { Integer option; String s; boolean exit = false; while (!exit) { UI.printHeader(); System.out.println("Selecciona una acción a continuación:"); System.out.println("1) Ver conexiones establecidas"); System.out.println("2) Establecer una conexión"); System.out.println("3) Eliminar una conexión"); System.out.println("4) Pausar una conexión"); System.out.println("5) Reanudar una conexión"); System.out.println(""); System.out.println("0) Atrás"); System.out.println(""); System.out.print("Introduce una opción: "); BufferedReader bufferRead = new BufferedReader( new InputStreamReader(System.in)); try { s = bufferRead.readLine(); option = Integer.parseInt(s); switch (option) { case 0: exit = true; break; case 1: list(); break; case 2: add(); break; case 3: remove(); break; case 4: pause(); break; case 5: start(); break; default: UI.setError("Opción no válida"); break; } } catch (NumberFormatException e) { UI.setError("Opción no válida"); } catch (IOException e) { e.printStackTrace(); } } UI.clearError(); }
9
public static Tile getTileConnectedToEntity(Entity e, int location){ if (map != null) { switch (location) { case UP: return map.getTile(e.getX(),e.getY()-e.getHeight()); case DOWN: return map.getTile(e.getX(),e.getY()); case LEFT: return map.getTile(e.getX()-e.getWidth(),e.getY()-1); case RIGHT: return map.getTile(e.getX()+e.getWidth(),e.getY()-1); default: return null; } } return null; }
5
public BodypartIconPanel(BodyPart bodypart) { super(); this.bodypart = bodypart; }
0
public Timestamp getNoteUpdateTime(int noteId) throws SQLException { NoteDatabaseManager dm = new NoteDatabaseManager(); String s_noteId = Integer.toString(noteId); String sql = "select update_time from note where note_id = " + s_noteId + ";"; ResultSet rs = dm.sqlQuery(sql); Timestamp noteUpdateTime = null; while (rs.next()) { noteUpdateTime = rs.getTimestamp("update_time"); } return noteUpdateTime; }
1
private Integer[][] getLogicalMap(CustomizedArena arena, int robotDiameterInCellNum) { int rowCount = arena.getRowCount(); int columnCount = arena.getColumnCount(); Integer[][] logicalMap = new Integer[rowCount][columnCount]; //For each obstacle cell at Row i, Col j, //Mark logicalMap[i ~ (i + robotDiameterInCellNum - 1)][(j - robotDiameterInCellNum + 1) ~ j] to 1 //Mark the top two rows and rightmost columns of logicalMap to 1 //Else Mark to 0 for(int rowID = 0;rowID < rowCount;rowID++){ for(int colID = 0;colID < columnCount;colID++){ if(rowID < robotDiameterInCellNum - 1){ logicalMap[rowID][colID] = new Integer(1); continue; } if(colID > columnCount - robotDiameterInCellNum){ logicalMap[rowID][colID] = new Integer(1); continue; } boolean obstacleInArea = false; for(int rowSpan = 0;rowSpan < robotDiameterInCellNum;rowSpan++){ for(int colSpan = 0;colSpan < robotDiameterInCellNum;colSpan++){ if(arena.getCell(rowID - rowSpan,colID + colSpan) == CellState.OBSTACLE){ obstacleInArea = true; } } } if(obstacleInArea){ logicalMap[rowID][colID] = new Integer(1); }else{ logicalMap[rowID][colID] = new Integer(0); } } } return logicalMap; }
8
public void actionPerformed(ActionEvent e) { Grammar g = environment.getGrammar(UnrestrictedGrammar.class); if (g == null) return; BruteParsePane bpp = new BruteParsePane(environment, g, null); environment.add(bpp, "Brute Parser", new CriticalTag() { }); environment.setActive(bpp); }
1
@Override public BurstMap parse(final String s) { final Map<String,Object> mp = new LinkedHashMap<String,Object>(); if((s!=null)&&(s.length()>0)&&(!s.equalsIgnoreCase(origHeader))) { final String[] flds = sepPattern.split(s,-1); // do allow trailing nulls if(null!=flds) { if((flds.length>0)||(flds[0].trim().length()>0)) { // empty string falsely looks like first field filled in with blank final int n = Math.min(headerFlds.length,flds.length); for(int i=0;i<n;++i) { mp.put(headerFlds[i],intern(flds[i],interner)); } } } } return new BurstMap(s,mp); }
7
public GregorianCalendar getHora() { return hora; }
0
public void printBoard() { System.out.println("________________"); for (int row = BOARD_SIZE; row >= 1; row--) { for (int col = 1; col <= BOARD_SIZE; col++) { ChessPiece piece = getPiece(row, col); String print = "x"; if (piece instanceof King) { print = "K"; } else if (piece instanceof Rook) { print = "R"; } else if (piece instanceof Bishop) { print = "B"; } else if (piece instanceof Knight) { print = "N"; } else if ( piece instanceof Queen) { print = "Q"; } else if (piece instanceof Pawn) { print = "P"; } System.out.print(print + " "); } System.out.print("|\n"); } System.out.println("-----------------"); }
8
public synchronized void playLoop(String file) { if (Bootstrap.MUTE) { game.log.jukebox("Game is muted, no sound played"); } else { String type = null; if (file.endsWith(".wav")) type = "wav"; else if (file.endsWith(".ogg")) type = "ogg"; if (type == "ogg") { try { OggClip ogg = new OggClip("jukebox/" + file); ogg.loop(); oggs.add(ogg); game.log.jukebox("playing '" + "/jukebox/" + file + "'"); } catch (Exception e) { game.log.jukebox("[ERROR] " + e); } } else if (type == "wav") { try { Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream(getClass().getClassLoader().getResourceAsStream("jukebox/" + file)); clip.open(inputStream); clip.loop(-1); game.log.jukebox("playing '" + "/jukebox/" + file + "'"); clips.add(clip); } catch (Exception e) { game.log.jukebox("[ERROR] " + e); } } else { game.log.jukebox("unknown file type '" + type + "'"); } } }
7
public Vertex getPath() { return path; }
0
private Direction convertToDirection(String direction) { switch (direction) { case "north": return Direction.NORTH; case "south": return Direction.SOUTH; case "west": return Direction.WEST; case "east": return Direction.EAST; case "up": return Direction.UP; default: return Direction.DOWN; } }
5
private final void method3087(BufferedStream buffer, int i, int i_3_) { if (i_3_ != 1) { if ((i_3_ ^ 0xffffffff) == -3) { buffer.readUnsignedByte(); } else if ((i_3_ ^ 0xffffffff) == -4) { anInt3157 = buffer.readInt(); anInt3166 = buffer.readInt(); anInt3150 = buffer.readInt(); } else if ((i_3_ ^ 0xffffffff) != -5) { if (i_3_ == 6) { anInt3160 = buffer.readUnsignedByte(); } else if ((i_3_ ^ 0xffffffff) != -9) { if ((i_3_ ^ 0xffffffff) != -10) { if (i_3_ == 10) { aBoolean3165 = true; } } else { anInt3162 = 1; } } else { anInt3155 = 1; } } else { anInt3163 = buffer.readUnsignedByte(); anInt3148 = buffer.readInt(); } } else { anInt3167 = buffer.readUnsignedShort(); } anInt3153++; if (i != 2) { anInt3152 = 73; } }
9
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(VtnEmpleados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VtnEmpleados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VtnEmpleados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VtnEmpleados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new VtnEmpleados().setVisible(true); } }); }
6
@Override public int hashCode() { int hash = 0; hash += (idUsuario != null ? idUsuario.hashCode() : 0); return hash; }
1
protected void buildAttributes(Node node, StringBuffer buf) { // Iterator it = node.getAttributeKeys(); // if (it != null) { // while (it.hasNext()) { // String key = (String) it.next(); // Object value = node.getAttribute(key); // buf.append(" ").append(key).append("=\"").append(escapeXMLAttribute(value.toString())).append("\""); // } // end while // } // end if } // end method buildAttributes
0
private void spinner_x1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinner_x1StateChanged if(hitbox_index_selected!=-1 || click_target_flag) { click_target_flag=true; if(hitbox_index_selected!=-1) { int i=0; for(Node hitboxes_node=current_frame.getFirstChild();hitboxes_node!=null;hitboxes_node=hitboxes_node.getNextSibling())//Hitbox loop { if(hitboxes_node.getNodeName().equals("Hitboxes")) { if(((Element)hitboxes_node).getAttribute("variable").equals(hitbox_color_selected)) { for(Node hitbox=hitboxes_node.getFirstChild();hitbox!=null;hitbox=hitbox.getNextSibling())//Red Hitboxes loop { if(hitbox.getNodeName().equals("Hitbox")) { if(i==hitbox_index_selected) ((Element)hitbox).setAttribute("x1", ""+spinner_x1.getValue()); i++; } } } } } updateHitboxes(current_frame); } }else { JOptionPane.showMessageDialog(null, "Select a hitbox first.", "Be careful", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_spinner_x1StateChanged
9
@Override public AnnotationVisitor visitParameterAnnotation(final int parameter, final String desc, final boolean visible) { if (!ClassReader.ANNOTATIONS) { return null; } ByteVector bv = new ByteVector(); if ("Ljava/lang/Synthetic;".equals(desc)) { // workaround for a bug in javac with synthetic parameters // see ClassReader.readParameterAnnotations synthetics = Math.max(synthetics, parameter + 1); return new AnnotationWriter(cw, false, bv, null, 0); } // write type, and reserve space for values count bv.putShort(cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(cw, true, bv, bv, 2); if (visible) { if (panns == null) { panns = new AnnotationWriter[Type.getArgumentTypes(descriptor).length]; } aw.next = panns[parameter]; panns[parameter] = aw; } else { if (ipanns == null) { ipanns = new AnnotationWriter[Type.getArgumentTypes(descriptor).length]; } aw.next = ipanns[parameter]; ipanns[parameter] = aw; } return aw; }
5
boolean isChromosomeMissing(Marker marker) { // Missing chromosome in marker? if (marker.getChromosome() == null) return true; // Missing chromosome in genome? String chrName = marker.getChromosomeName(); Chromosome chr = genome.getChromosome(chrName); if (chr == null) return true; // Chromosome length is 1 or less? if (chr.size() < 1) return true; // Tree not found in interval forest? if (!intervalForest.hasTree(chrName)) return true; // OK, we have the chromosome return false; }
4
public static boolean cobreTodas(Coluna col, Solucao sol){ int x = 0; ArrayList<Integer> cobertura = col.getCobertura(); for(Integer entradateste : cobertura){ if(!(sol.getLinhasCobertas().contains(entradateste))){ sol.getLinhasCobertas().add(entradateste); } } //System.out.println("Cobertura de linhas: " + sol.getLinhasCobertas().size()); if(sol.getLinhasCobertas().size()==sol.getQtdeLinhas()){ return true; } else{ return false; } }
3
static Elements filterOut(Collection<Element> elements, Collection<Element> outs) { Elements output = new Elements(); for (Element el : elements) { boolean found = false; for (Element out : outs) { if (el.equals(out)) { found = true; break; } } if (!found) output.add(el); } return output; }
4
@Override public Path shortestPath(Vertex a, Vertex b) { Hashtable<Vertex,Color> color=new Hashtable<Vertex,Color>(graph.getVertices().size()*2); Hashtable<Vertex,Vertex> tree=new Hashtable<Vertex,Vertex>(graph.getVertices().size()*2); Hashtable<Vertex,Integer> distance=new Hashtable<Vertex,Integer>(graph.getVertices().size()*2); LinkedList<Vertex> vertices = graph.getVertices(); Iterator<Vertex> j = new Iterator<Vertex>(vertices); while(j.hasNext()){ Vertex v = j.getNext(); color.put(v,Color.WHITE); tree.put(v,null); distance.put(v,Integer.MAX_VALUE); } Queue<Vertex> queue = new Queue<Vertex>(); color.put(a,Color.GREY); distance.put(a,0); queue.enqueue(a); while(!queue.isEmpty()){ Vertex u=queue.dequeue(); LinkedList<Vertex> adjacencyVertices=graph.getAdjacencyVertices(u); Iterator<Vertex> r = new Iterator<Vertex>(adjacencyVertices); while(r.hasNext()){ Vertex h = r.getNext(); if(color.get(h)==Color.WHITE){ color.put(h, Color.GREY); tree.put(h,u); distance.put(h, distance.get(u)+1); queue.enqueue(h); } } color.put(u, Color.BLACK); } if(distance.get(b)==Integer.MAX_VALUE){ return null; } return super.getPath(a,b,tree,distance); }
5
public Checker(int team){ this.team = team; if(team == 1) { setImage(new GreenfootImage("Mario.png")); } else if (team == 2) { setImage(new GreenfootImage("Wario.png")); } }
2
public void createAndListenSocket() { try { socket = new DatagramSocket(9876); byte[] incomingData = new byte[1024 * 1000 * 50]; System.out.println("Inicio del servidor"); while (true) { DatagramPacket incomingPacket = new DatagramPacket(incomingData, incomingData.length); socket.receive(incomingPacket); byte[] data = incomingPacket.getData(); ByteArrayInputStream in = new ByteArrayInputStream(data); ObjectInputStream is = new ObjectInputStream(in); fileEvent = (FileEvent) is.readObject(); if (fileEvent.getStatus().equalsIgnoreCase("Error")) { System.out.println("Algun problema ocurrio en el enpaquetamiento de los datos"); System.exit(0); } createAndWriteFile(); // writing the file to hard disk InetAddress IPAddress = incomingPacket.getAddress(); int port = incomingPacket.getPort(); String reply = "Archivo correcto"; byte[] replyBytea = reply.getBytes(); //System.out.println(replyBytea); DatagramPacket replyPacket = new DatagramPacket(replyBytea, replyBytea.length, IPAddress, port); //System.out.println(replyBytea.length); //System.out.println(IPAddress); //System.out.println(port); //System.out.println(replyPacket); socket.send(replyPacket); Thread.sleep(3000); System.out.println("Fin del servidor"); System.exit(0); } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
6
public static void infoBox(String infoMessage, String location) { JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + location, JOptionPane.INFORMATION_MESSAGE); }
0
DefaultPopupMenu(AtomisticView v) { super("Default"); this.view = v; JMenuItem mi = new JMenuItem(view.getActionMap().get(AtomisticView.PASTE)); String s = MDView.getInternationalText("Paste"); if (s != null) mi.setText(s); add(mi); addSeparator(); mi = new JMenuItem(view.getActionMap().get("Model Reader")); s = MDView.getInternationalText("OpenModel"); if (s != null) mi.setText(s); add(mi); mi = new JMenuItem(view.getActionMap().get("Model Writer")); s = MDView.getInternationalText("SaveModel"); if (s != null) mi.setText(s); add(mi); addSeparator(); mi = new JMenuItem(view.getActionMap().get("Properties")); s = MDView.getInternationalText("Properties"); if (s != null) mi.setText(s); add(mi); mi = new JMenuItem(view.getActionMap().get("Snapshot")); s = MDView.getInternationalText("Snapshot"); if (s != null) mi.setText(s); add(mi); mi = new JMenuItem(view.getActionMap().get("View Options")); s = MDView.getInternationalText("ViewOption"); if (s != null) mi.setText(s); add(mi); s = MDView.getInternationalText("TaskManager"); mi = new JMenuItem(s != null ? s : "Task Manager", IconPool.getIcon("taskmanager")); mi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { view.showTaskManager(); } }); add(mi); pack(); }
7
private JLabel getLabel(Point point) { JLabel label = null; JLabel[] searchLabel; if (whitesTurn) { searchLabel = whites; } else { searchLabel = blacks; } for (JLabel l : searchLabel) { if (l.getBounds().x == point.x && l.getBounds().y == point.y) { label = l; } } return label; }
4
private void receive_id() throws Exception { status_moves++; int field_id = readMailbox(BrickGame.bluetooth_mailboxSystem, false, -1); if (field_id < 1 || field_id > 2) { return; } if (field_id == 2) { updatePosition(); FieldGame.setField(2, pos_x, pos_y, id); System.out.println(name + ": receive field: " + field_id + " " + pos_x + " " + pos_y); downdatePosition(); direction = 0; status_foundBlock++; Gui.update(); } else { updatePosition(); FieldGame.setField(1, pos_x, pos_y, id); direction = 0; System.out.println(name + ": receive field: " + field_id + " " + pos_x + " " + pos_y); System.out.println(name + ": new position: " + pos_x + " " + pos_y); Gui.update(); } }
3
private void jMsgSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMsgSActionPerformed jTable1.getColumnModel().getColumn(0).setCellRenderer(new CustomCellRender_Message()); jTable1.setModel(modele2); jTable1.setAutoCreateRowSorter(true); Color c = new Color(63,70,73); TableRowSorter<TableModel> sorter = new TableRowSorter<>(jTable1.getModel()); jScrollPane1.setBorder(null); jTable1.setRowSorter(sorter); jTable1.setFillsViewportHeight(true); jTable1.setShowHorizontalLines(false); jTable1.setShowVerticalLines(true); JTableHeader header = jTable1.getTableHeader(); Color bgcolor = new Color(45,47,49); Color focolor = new Color(244,244,244); header.setBackground(bgcolor); header.setForeground(focolor); header.setBorder(null); getContentPane().setBackground(c); DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); renderer.setHorizontalAlignment(SwingConstants.CENTER); TableColumn AlignementCol; for(int i = 0; i < modele2.getColumnCount(); i++) { AlignementCol= jTable1.getColumnModel().getColumn(i); AlignementCol.setCellRenderer(renderer); } for(int i = 0; i < modele2.getColumnCount(); i++) { TableColumn column = jTable1.getColumnModel().getColumn(i); column.setHeaderRenderer(new CustomCellRender()); } //end set header border:disabled Color HeaderColorBackground = new Color(34,168,108); header.setBackground(HeaderColorBackground); }//GEN-LAST:event_jMsgSActionPerformed
2
public void connect() { ScheduledExecutorService spinner = Executors.newScheduledThreadPool(2); Map<String, ScheduledFuture<?>> futures = new HashMap<>(); final Socket socket; IO.Options opts = new IO.Options(); opts.forceNew = true; try { socket = IO.socket("http://localhost:3006", opts); } catch (URISyntaxException e) { throw new IllegalStateException(e); } socket.on("process", args -> { System.out.println("on process: " + player); String messageID = null; String playerID = null; try { JSONObject jsonObject = new JSONObject((String) args[0]); System.out.println("Received message: " + jsonObject.toString()); playerID = jsonObject.getString("player_id"); messageID = jsonObject.getJSONObject("message").getString("id"); } catch (JSONException e) { e.printStackTrace(); } carousel = new Carousel(socket, playerID, messageID); ScheduledFuture<?> future = spinner.scheduleAtFixedRate(carousel, 0, 3, TimeUnit.SECONDS); futures.put(messageID, future); }).on("terminate", args -> { System.out.println("on terminate: " + player); futures.values().stream().forEach(f -> f.cancel(true)); futures.clear(); System.out.println("terminating scheduled: " + player); }).on(Socket.EVENT_CONNECT, args -> { System.out.println("on connect: " + player); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("player_id", player); jsonObject.put("event_type", "initialize"); } catch (JSONException e) { e.printStackTrace(); } socket.emit("initialize", jsonObject.toString()); }).on(Socket.EVENT_DISCONNECT, args -> System.out.println("on disconnect: " + player)); socket.open(); }
5
@Override public void reservarLibroAUnSocio(String codigoLibro, String codigoSocio) throws BibliotecaError{ if (codigoLibro == null || codigoLibro.equals("")){ System.out.println("Codigo Libro invalido"); throw new BibliotecaError("Codigo Libro invalido"); } if (codigoSocio == null || codigoSocio.equals("")){ System.out.println("Codigo Socio invalido"); throw new BibliotecaError("Codigo Socio invalido"); } if(!libros.containsKey(codigoLibro) ){ System.out.println("no existe el libro"); throw new BibliotecaError("no existe el libro"); } if(!socios.containsKey(codigoSocio) ){ System.out.println("no existe el socio"); throw new BibliotecaError("no existe el socio"); } Libro libro=libros.get(codigoLibro); if(!libro.isPrestado()){ System.out.println("el libro no esta prestado"); throw new BibliotecaError("el libro no esta prestado"); } Socio socio=socios.get(codigoSocio); //verificar que el lector no tenga una reserva sobre es libro if(socio.libroYaReservado(codigoLibro)){ System.out.println("el libro fue reservado por el lector previamente"); throw new BibliotecaError("el libro fue reservado por el lector previamente"); } socio.reservarLibro(libro); libro.reservarlibro(socio); }
8
public Object invokeMethod(Reference ref, boolean isVirtual, Object cls, Object[] params) throws InterpreterException, InvocationTargetException { if (cls == null && ref.getClazz().equals(classSig)) { String clazzName = ref.getClazz(); clazzName = clazzName.substring(1, ref.getClazz().length() - 1) .replace('/', '.'); BytecodeInfo info = ClassInfo.forName(clazzName) .findMethod(ref.getName(), ref.getType()).getBytecode(); if (info != null) return interpreter.interpretMethod(info, null, params); throw new InterpreterException( "Can't interpret static native method: " + ref); } else return super.invokeMethod(ref, isVirtual, cls, params); }
3
private static boolean deleteDirectory(String dir) { if (!dir.endsWith(File.separator)) { dir = dir + File.separator; } File dirFile = new File(dir); if (!dirFile.exists() || !dirFile.isDirectory()) { return false; } boolean flag = true; File[] files = dirFile.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { flag = deleteFile(files[i].getAbsolutePath()); if (!flag) { break; } } else { flag = deleteDirectory(files[i].getAbsolutePath()); if (!flag) { break; } } } if (!flag) { return false; } if (dirFile.delete()) { return true; } else { return false; } }
9
public void close() { synchronized (soc) { if (!run) return; run = false; try { out.close(); in.close(); soc.close(); } catch(IOException e) { System.err.println("ajclient.close: failed to close the connection"); } } }
2
public void destroy() { hoistedNode = null; }
0
public static void wbml_backgroundrefresh(osd_bitmap bitmap, int trasp) { int page; int xscroll = (bg_ram[0x7c0] >> 1) + ((bg_ram[0x7c1] & 1) << 7) - 256 + 5; int yscroll = -bg_ram[0x7ba]; for (page = 0; page < 4; page++) { //const unsigned char *source = bg_ram + (bg_ram[0x0740 + page*2] & 0x07)*0x800; UBytePtr source = new UBytePtr(bg_ram, (bg_ram[0x0740 + page * 2] & 0x07) * 0x800); int startx = (page & 1) * 256 + xscroll; int starty = (page >> 1) * 256 + yscroll; int row, col; for (row = 0; row < 32 * 8; row += 8) { for (col = 0; col < 32 * 8; col += 8) { int code, priority; int x = (startx + col) & 0x1ff; int y = (starty + row) & 0x1ff; if (x > 256) { x -= 512; } if (y > 224) { y -= 512; } if (x > -8 && y > -8) { code = source.read(0) + (source.read(1) << 8); priority = code & 0x800; code = ((code >> 4) & 0x800) | (code & 0x7ff); if (trasp == 0) { drawgfx(bitmap, Machine.gfx[0], code, ((code >> 5) & 0x3f) + 64, 0, 0, x, y, Machine.drv.visible_area, TRANSPARENCY_NONE, 0); } else if (priority != 0) { drawgfx(bitmap, Machine.gfx[0], code, ((code >> 5) & 0x3f) + 64, 0, 0, x, y, Machine.drv.visible_area, TRANSPARENCY_PEN, 0); } } source.inc(2);//source+=2; } } } /* next page */ }
9
public void displayLCS() { System.out.println("Length of Longest Common Sequence is "+ length[seq1.length-1][seq2.length-1]); LinkedList<Integer> list = new LinkedList<Integer>(); int row = seq1.length-1, col = seq2.length - 1, temp = -1, index = -1; while ((row != 0) && (col != 0)) { temp = indices[row] [col]; if (temp < 0) index = -temp; else index = temp; if (temp > 0) list.addFirst(seq1[row]); col = (((1<< POW) -1) & index) & 0x7FFFFFFF; row = index >> POW; } Integer i = list.poll(); while (i != null) { System.out.print(i); i = list.poll(); } System.out.println(); }
5
public int isActivatedBy (Trigger trigger) { if (trigger == null) return -1; for (int i = 0; i < triggers.length; i++) { if (triggers[i] == trigger) return i; } return -1; }
3
@Test public void doTest() { fillIn(); for (BigInteger b : trian) { for (BigInteger p : trian) { if (trian.contains(p.subtract(b).abs()) && trian.contains(p.add(b))) { System.out.println(p + " " + b + " " + p.subtract(b).abs()); } } } }
4
public synchronized void adicionar() { try { new AreaFormacaoView(this); } catch (Exception e) { } }
1
public static Packet read(ByteBuffer buffer) { byte packetId = buffer.get(); if (packetId == ID_HELLO_PACKET) return new HelloPacket(buffer); if (packetId == ID_WORLD_UPDATE_PACKET) return new WorldUpdatesPacket(buffer); if (packetId == ID_WINDOW_PACKET) return new WindowPacket(buffer); if (packetId == ID_WORLD_REGION_PACKET) return new WorldRegionPacket(buffer); if (packetId == ID_ENTITIES_PACKET) return new EntitiesPacket(buffer); if (packetId == ID_DWARF_REQUEST_PACKET) return new DwarfRequestPacket(buffer); if (packetId == ID_PLAYER_UPDATE_PACKET) return new PlayerUpdatePacket(buffer); throw new RuntimeException("Unknown packet id: " + packetId); }
7
public static boolean fullName(String name){ String[] temp = name.split(" "); if(name(temp[0])&&name(temp[1])) return true; return false; }
2
@Test public void returnListOfStrings_whenCallPermuteAsStrings() { List<Character> chars = new ArrayList<Character>(Arrays.asList('a', 'b', 'c')); String expected = "[abc, acb, bac, bca, cba, cab]"; String actual = permutation.permuteAsStrings(chars).toString(); assertEquals(expected, actual); }
0
public String buscarGrupoEstudioPorCurso(String curso) { ArrayList<GrupoEstudio> geResult= new ArrayList<GrupoEstudio>(); ArrayList<GrupoEstudio> dbGE = tablaGrupoEstudio(); String result=""; try{ for (int i = 0; i < dbGE.size() ; i++){ if(dbGE.get(i).getCurso().equalsIgnoreCase(curso)){ geResult.add(dbGE.get(i)); //break; } } }catch (NullPointerException e) { result="no existe el Grupo de Estudio"; } if (geResult.size()>0){ for (int i = 0; i < geResult.size() ; i++) { result+="\nRegistros encontrados: "; result+="\nNombre: " + geResult.get(i).getNombre(); result+="\nAcademia: " + geResult.get(i).getAcademia(); result+="\nCurso: " + geResult.get(i).getCurso(); result+="\nFecha de Inicio: " + geResult.get(i).getFechaini(); result+="\nFecha de Fin: " + geResult.get(i).getFechafin(); result+="\nEstado: " + geResult.get(i).getEstado(); result+="\n----------------------"; } } else { result="No se ha encontrado ningun registro"; } return result; }
5
public ServerInfo(String ipAddress, int port, long maxClients) { this.ipAddress = ipAddress; this.port = port; this.maxClients = maxClients; }
0
public JButton createButton(final int index, String text) { JButton b = new JButton(); b.setText(text); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { switch (index) { case 0: String thoughtName = thoughtInputField.getText(); String notes = notesInputField.getText(); if (!listModel.contains(thoughtName)) { controller.addThought(thoughtName, notes); listModel.addElement(thoughtName); notesInputField.setText("Notes"); thoughtInputField.setText("Thought"); } else { JOptionPane.showMessageDialog(null, "This thought already exists!"); } break; case 1: controller.workThoughtOut(thoughtList.getSelectedIndex()); break; case 2: controller.removeThought(thoughtList.getSelectedIndex()); break; } } }); if (index < 3 && index >= 0) { buttons[index] = b; } return b; }
6
final synchronized void method2817(int[] is, int i, int i_67_) { try { anInt8898++; if (aClass204_8944.method1491()) { int i_68_ = (anInt8921 * ((MidiFile) aClass204_8944).anInt2683 / Class22.anInt339); do { long l = aLong8959 + (long) i_67_ * (long) i_68_; if (aLong8957 + -l >= 0L) { aLong8959 = l; break; } int i_69_ = (int) ((-1L + (long) i_68_ + aLong8957 + -aLong8959) / (long) i_68_); aLong8959 += (long) i_68_ * (long) i_69_; aClass348_Sub16_Sub1_8958.method2817(is, i, i_69_); i += i_69_; i_67_ -= i_69_; method2856((byte) 124); } while (aClass204_8944.method1491()); } aClass348_Sub16_Sub1_8958.method2817(is, i, i_67_); } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("ma.C(" + (is != null ? "{...}" : "null") + ',' + i + ',' + i_67_ + ')')); } }
5
public final void stmtList() throws RecognitionException { AST ast1 = null, ast2 = null; try { // CPP.g:300:3: ( stmt stmtList | ) int alt18 = 2; alt18 = this.dfa18.predict(this.input); switch (alt18) { case 1: // CPP.g:300:5: stmt stmtList { this.pushFollow(FOLLOW_stmt_in_stmtList1152); this.stmt(); this.state._fsp--; if (this.state.failed) { return; } if (this.state.backtracking == 0) { ast1 = this.out; this.out = null; } this.pushFollow(FOLLOW_stmtList_in_stmtList1160); this.stmtList(); this.state._fsp--; if (this.state.failed) { return; } if (this.state.backtracking == 0) { ast2 = this.out; this.out = null; } if (this.state.backtracking == 0) { this.out = new StmtListAST((OneStmtAST) ast1, (StmtListAST) ast2); } } break; case 2: // CPP.g:303:5: { if (this.state.backtracking == 0) { this.out = new EmptyStmtListAST(); } } break; } } catch (RecognitionException re) { this.reportError(re); this.recover(this.input, re); } finally { } return; }
9
private static void percDown( int[] a, int i, int n ){ int child; int tmp; for (tmp = a[i] ; leftchild( i ) < n; i = child ) { child = leftchild(i); if (child<=n-1 && a[child] < a[child+1]) { child++; if (tmp < a[child]) { int l = a[i]; a[i] = a[child]; a[child] = l; } } else if (child<=n-1 && a[child] > a[child+1]) { if (tmp < a[child]) { int l = a[i]; a[i] = a[child]; a[child] = l; } } } }
7
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection con = null; PreparedStatement ps = null; String[] unameperms = request.getParameter("uname").split(";"); String uname = unameperms[0]; String perms = unameperms[1]; String enab = unameperms[2]; System.out.println(request.getParameter("uname")); System.out.println(uname); System.out.println(perms); System.out.println(enab); System.out.println(request.getParameter("submit")); if(request.getParameter("submit").equals("Change Permissions")){ String stmt = "UPDATE author SET permissions=? WHERE uname=?"; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/faultdb","root","Cl1m8t3;"); ps = con.prepareStatement(stmt); if(perms.equals("admin")){ ps.setString(1, "dev"); } else { ps.setString(1,"admin"); } ps.setString(2, uname); ps.executeUpdate(); response.sendRedirect("viewUsers"); } catch (Exception e) { System.out.println(e); response.sendRedirect("viewUsers"); } try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } else if (request.getParameter("submit").equals("Enable/Disable Account")){ String stmt = "UPDATE author SET enabled=? WHERE uname=?"; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/faultdb","root","Cl1m8t3;"); ps = con.prepareStatement(stmt); if(enab.equals("true")){ ps.setString(1, "false"); } else { ps.setString(1,"true"); } ps.setString(2, uname); ps.executeUpdate(); response.sendRedirect("viewUsers"); } catch (Exception e) { System.out.println(e); response.sendRedirect("viewUsers"); } try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } //response.sendRedirect("viewUsers"); }
8
@Test public void testStreamSkipReadMixSmallerDelegateThrows() throws IOException { LimitedInputStream stream = streamUsingSmallStreamThrows; int limit = HALF_LIMIT; long total = 0; do { int count = (int)(Math.random() * 10); if (total + count == limit) { count++; } boolean underflow = total + count > limit; long expectedResult = underflow ? limit - total : count; long actual; boolean read = false; try { read = Math.random() > 0.5; if (read) { actual = stream.read(BUFFER, 0, count); assertEquals("Number of expected reads (read=" + total + "; count=" + count + "; expected=" + expectedResult + "; actual=" + actual, expectedResult, actual); } else { actual = stream.skip(count); assertEquals("Number of expected skips (read=" + total + "; count=" + count + "; expected=" + expectedResult + "; actual=" + actual, expectedResult, actual); } if (underflow) { fail("Expected EOF on exceeding buffer limit"); } total += actual; } catch (EOFException e) { if (!underflow) { fail("Unexpected EOF while " + (read ? "reading" : "skipping") + "(read=" + total + "; count=" + count + "; expected=" + expectedResult + ")"); } break; } } while (total < limit); }
8
public void sendQueues() { LinkedList<Bid> bidQueue = getBidQueue(); LinkedList<SeismicRequest> seismicQueue = getSeismicQueue(); LinkedList<Drill> drillQueue = getDrillQueue(); if (!bidQueue.isEmpty()) { for (Bid bid : bidQueue) { ((ServerMessages) socket).sendBidQueue(bid.toSocket()); } } if (!seismicQueue.isEmpty()) { for (SeismicRequest sm : seismicQueue) { ((ServerMessages) socket).sendSeismicQueue(sm.toSocket()); } } if (!drillQueue.isEmpty()) { for (Drill drill : drillQueue) { ((ServerMessages) socket).sendDrillQueue(drill.toSocket()); } } }
6
@Override public void setComplete(boolean complete) { this.complete = complete; }
0
private void shutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { if (FilePlayer.getSaver() != null && !FilePlayer.getSaver().isDone()) try { FilePlayer.getSaver().get(); } catch (InterruptedException | ExecutionException ex) { Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex); } } })); }
3
public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output,Reporter reporter) throws IOException { String line = value.toString(); String[] words = line.split(","); int flag = 1; for(int j=0;j<rule[rule_no].length-1 && flag==1;j++) { if(rule[rule_no].val[j].equals(words[rule[rule_no].num[j]])) flag = 1; else flag = 0; } if(flag == 1) { if(words[0].equals(rule[rule_no].class_name)) { if(rule[rule_no].val[rule[rule_no].length-1].equals(words[rule[rule_no].num[rule[rule_no].length-1]])) { reporter.incrCounter(Counter.PR0, 1); word.set("p0"); output.collect(word, one); } reporter.incrCounter(Counter.PR1, 1); word.set("p1"); output.collect(word, one); } else { if(rule[rule_no].val[rule[rule_no].length-1].equals(words[rule[rule_no].num[rule[rule_no].length-1]])) { reporter.incrCounter(Counter.NR0, 1); word.set("n0"); output.collect(word, one); } reporter.incrCounter(Counter.NR1, 1); word.set("n1"); output.collect(word, one); } } }
7
@Test public void testFindAllFromCache() throws Exception { IUserPersistence users = dbs.getDatabase1().users(); User u1 = users.create("bryand", System.currentTimeMillis(), 5, System.currentTimeMillis() + 10, System.currentTimeMillis() + 20, "this is a relatively long string", new byte[]{5, 4, 3, 2, 1}, 1.2d, 3.4d, true); User u2 = users.create("thomask", System.currentTimeMillis(), 5, System.currentTimeMillis() + 10, System.currentTimeMillis() + 20, "this is a relatively long string", new byte[]{5, 4, 3, 2, 1}, 1.2d, 3.4d, true); User u3 = users.create("emilyl", System.currentTimeMillis(), 5, System.currentTimeMillis() + 10, System.currentTimeMillis() + 20, "this is a relatively long string", new byte[]{5, 4, 3, 2, 1}, 1.2d, 3.4d, true); // fills cache User u1_1 = users.find(u1.getId()); User u2_1 = users.find(u2.getId()); User u3_1 = users.find(u3.getId()); List<User> allUsers = users.findAll(); assertTrue(allUsers.contains(u1)); assertTrue(allUsers.contains(u2)); assertTrue(allUsers.contains(u3)); // make sure findAll returned cached objects int numFound = 0; for (User user : allUsers) { if (user.getId() == u1_1.getId()) { numFound++; } else if (user.getId() == u2_1.getId()) { numFound++; } else if (user.getId() == u3_1.getId()) { numFound++; } } assertEquals("findAll did not return cached objects for all 3 users!", 3, numFound); }
4
public static String toString(JSONObject jo) throws JSONException { StringBuffer sb = new StringBuffer(); sb.append(escape(jo.getString("name"))); sb.append("="); sb.append(escape(jo.getString("value"))); if (jo.has("expires")) { sb.append(";expires="); sb.append(jo.getString("expires")); } if (jo.has("domain")) { sb.append(";domain="); sb.append(escape(jo.getString("domain"))); } if (jo.has("path")) { sb.append(";path="); sb.append(escape(jo.getString("path"))); } if (jo.optBoolean("secure")) { sb.append(";secure"); } return sb.toString(); }
4
public static void main(String[] args) { String json = "{\"name\":\"sergii\",\"age\":\"25\"}"; ObjectMapper objectMapper = new ObjectMapper(); Map<String,String> map = new HashMap<String,String>(); try{ map = objectMapper.readValue(json, new TypeReference<HashMap<String, String>>() { }); System.out.println(map); } catch (Exception e) { e.printStackTrace(); } }
1
public void rowOpenStateChanged(Row row, boolean open) { if (row.hasChildren() && mRows.contains(row)) { if (open) { addChildren(row); } else { removeRows(row.getChildren().toArray(new Row[0])); } } }
3
public static LegacyOCPMessage decodeBuffer(final ByteBuffer buffer) throws OCPException { if (buffer.limit() < OCP_MIN_LENGTH) { // Too short to possibly be a valid message throw new OCPException(); } Class<? extends LegacyOCPMessage> implementation; Constructor<? extends LegacyOCPMessage> constructor; short commandCode = buffer.getShort(OCP_CMD_CODE_OFFSET); implementation = getOCPClass(commandCode); if (implementation == null) { // Unimplemented OCP message. Try and work out what sort it was. switch (commandCode & OCP_COMMAND_TYPE_MASK) { case OCP_COMMAND_TYPE_LINK: throw new LinkMessageException( commandCode, LinkCommandUnsupported.REASON_COMMAND_CODE_UNSUPPORTED); case OCP_COMMAND_TYPE_CALL: // Extract the task IDs from the original message throw new CallMessageException( buffer.getInt(LegacyOCPMessage.OCP_DEST_TID_OFFSET), buffer.getInt(LegacyOCPMessage.OCP_ORIG_TID_OFFSET), commandCode, CallCommandUnsupported.REASON_COMMAND_CODE_UNSUPPORTED); default: throw new UnknownMessageTypeException(); } } try { constructor = implementation.getConstructor(ByteBuffer.class); return constructor.newInstance(buffer); } catch (InvocationTargetException e) { // The constructor threw an exception if (e.getTargetException() instanceof OCPException) { // Propogate OCPExceptions. throw (OCPException) e.getTargetException(); } else { // Wrap non-OCPExceptions. throw new OCPException(e.getTargetException()); } } catch (Exception e) { // Attempting to call the constructor failed. Wrap in an // OCPException. throw new OCPException(e); } }
9
private void makeLabels() { List<JPanel> labels = new ArrayList<JPanel>(); RollingStock r = theTrain.firstCarriage(); if (r == null) { this.labelList = labels; } else while (r != null) { JPanel tmpPanel = new JPanel(); tmpPanel.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null)); JLabel label = new JLabel("<html>" + r.toString() + "<br><br>" + r.getGrossWeight() + " tonnes</html>"); label.setPreferredSize(new Dimension(145, 90)); label.setOpaque(true); label.setHorizontalAlignment(JLabel.CENTER); tmpPanel.setLayout(new BorderLayout(0, 0)); if (r.getClass().getName() == "asgn2RollingStock.Locomotive") { JProgressBar progressBar = new JProgressBar(); tmpPanel.setBackground(Color.ORANGE); label.setBackground(Color.ORANGE); progressBar .setValue((int) (((double) totalWeight / (double) power) * 100)); tmpPanel.add(label); tmpPanel.add(progressBar, BorderLayout.SOUTH); } else if (r.getClass().getName() == "asgn2RollingStock.PassengerCar") { JProgressBar progressBar = new JProgressBar(); tmpPanel.setBackground(Color.GREEN); label.setBackground(Color.GREEN); progressBar .setValue((int) ((double) ((PassengerCar) r) .numberOnBoard() / (double) ((PassengerCar) r) .numberOfSeats() * 100)); tmpPanel.add(label); tmpPanel.add(progressBar, BorderLayout.SOUTH); } else if (r.getClass().getName() == "asgn2RollingStock.FreightCar") { tmpPanel.setBackground(Color.GRAY); label.setBackground(Color.GRAY); tmpPanel.add(label); } labels.add(tmpPanel); r = theTrain.nextCarriage(); } this.labelList = labels; }
5
public static int[] maximumSubArray(int[] input) { // Check for invalid input if (input == null || input.length == 0) { throw new IllegalArgumentException("invalid input array"); } // If input lenght is 1 then we simply return the same array if (input.length == 1) { return input; } // Initialise the maxSum to the first element in the array. // Like we assume first element is the maximum sub array. int maxSum = input[0]; // Set the lower bound of the maximum sub array to 0. int maxLowerBound = 0; // Set the upper bound of the maximum sub array to 0. int maxUpperBound = 0; // It holds the intermediate lower bound of the new sub array int intermediateLowerBound = 0; // It holds the intermediate sum of the sub array int intermdediateSum = input[0]; // Loop starts from index 1 in the array for (int i = 1; i < input.length; i++) { // add the current element to intermediate sum. intermdediateSum += input[i]; // if current element is creator than the intermediate sum then we // need to start with new sub array as per Kadane's algorithm. if (input[i] > intermdediateSum) { // Set the intermediate bound to new index intermediateLowerBound = i; // Set the intermediateSum to value of current element. intermdediateSum = input[i]; } // Update maxSum if intermdediateSum is greater than current maxSum if (intermdediateSum > maxSum) { // update the maxLowerBound to current intermediateLowerBound maxLowerBound = intermediateLowerBound; // update the maxUpperBound to current index maxUpperBound = i; // update the maxSum to intermediateSum maxSum = intermdediateSum; } } // create a new array. Both maxUpperBound & maxLowerBound are inclusive // so size of the array is maxUpperBound - maxLowerBound + 1 int[] output = new int[maxUpperBound - maxLowerBound + 1]; System.arraycopy(input, maxLowerBound, output, 0, output.length); return output; }
6
public void show() { for(RadioButton rb : btns) rb.show(); }
1