method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
93fe5fa7-e5cf-4295-8f3f-b64d2b4a1f5a
0
public Map<String, Object> getProperties() { return properties; }
8fa5c850-7997-4d79-99b1-b9ba1c6d1b8c
2
public static Filter classNameMatches( String regex ) { if ( regex == null ) { throw new IllegalArgumentException( "Parameter 'regex' must not be null" ); } if ( regex.length() == 0 ) { throw new IllegalArgumentException( "Empty 'regex' not allowed" ); } return new ClassNameMatchesFilter( regex ); }
1945d0d1-b3a0-4f11-97e0-6e044f969153
6
public String setMidiIn(int id) { if(_keyboard != null) { _keyboard.close(); _keyboard = null; _midiDevices.setKeyboard(_keyboard); } if(id == -1) { return "<midi-in>-1</midi-in>"; } _keyboard = _midiDevices.getDevice(id);//hw input try { _keyboard.open(); } catch(MidiUnavailableException e) { return "<error id='setInPort'>" + e + "</error><midi-in>-1</midi-in>"; } Transmitter trans1 = null; Transmitter trans2 = null; try { trans1 = _keyboard.getTransmitter(); trans1.setReceiver(_midiReceiver); if(_synthesizer != null && _synthesizer.isOpen()) { trans2 = _keyboard.getTransmitter(); trans2.setReceiver(_synthesizer.getReceiver()); } //System.out.println("keyboard connected " + trans1.getClass()); } catch(MidiUnavailableException e) { return "<error id='setInPort'>" + e + "</error><midi-in>-1</midi-in>"; } _midiDevices.setKeyboard(_keyboard); return "<midi-in>" + id + "</midi-in>"; }
be3a2d04-752c-47ac-89a8-3c4c0d5e2390
4
public void startReceiverThread() { new Thread() { public void run() { String tmp = null; RadiogramConnection dgConnection = null; DatagramConnection dgSpamConnection = null; Datagram dgSpam = null; Datagram dg = null; try { dgConnection = (RadiogramConnection) Connector.open("radiogram://:37"); // Then, we ask for a datagram with the maximum size allowed dg = dgConnection.newDatagram(dgConnection.getMaximumLength()); } catch (IOException e) { System.out.println("Could not open radiogram receiver connection"); e.printStackTrace(); return; } while ( true ) { try { dg.reset(); dgConnection.receive(dg); tmp = dg.readUTF(); String foreignAddress = dg.getAddress(); if ( foreignAddress != null ) // Set SunSPOT sender MAC address to filter filthy ones { System.out.println("Received: [" + tmp + "] from [" + dg.getAddress() + "]"); dgSpamConnection = (DatagramConnection) Connector.open("radiogram://" + dg.getAddress() + ":37"); // Then, we ask for a datagram with the maximum size allowed dgSpam = dgSpamConnection.newDatagram(dgSpamConnection.getMaximumLength()); dgSpam.writeUTF("Heyoo! Do you want some spam? Yeah I know you want spam," + "you'll love to have so much spam. Spam spam spam, lovely" + "spaaam lovely spaaaaam!!"); dgSpamConnection.send(dgSpam); dgSpamConnection.close(); } else { System.out.println("Received: [" + tmp + "] from [UNKNOWN DEVICE]."); } } catch ( IOException e ) { System.out.println("Nothing received"); } } } }.start(); }
89e47f90-304a-442a-b12e-ea5f0567f395
8
public static void qsHelpTick( int lo, int hi, LinkedList<Stock> d ) { if ( lo >= hi ) return; int tmpLo = lo; int tmpHi = hi; String pivot = d.get(lo).getTicker(); Stock indPiv = d.get(lo); while( tmpLo < tmpHi ) { //first, slide markers in as far as possible without swaps while( d.get(tmpLo).getTicker().compareTo(pivot) < 0 ) tmpLo++; while( d.get(tmpHi).getTicker().compareTo(pivot) > 0 ) tmpHi--; if ( d.get(tmpLo).getTicker().compareTo(d.get(tmpHi).getTicker()) != 0 ) swap( tmpLo, tmpHi, d ); //dupe vals found at markers else if ( tmpLo < tmpHi ) { //extra chk for Lo<Hi bc of double marker moves below String dupe = d.get(tmpHi).getTicker(); //if dupe is pivot val, put in lower range if ( dupe == pivot ) { swap( ++tmpLo, tmpHi, d ); } else if ( dupe.compareTo(pivot) > 0 ) { //slide upper marker inward 1 pos, then swap swap( tmpLo, --tmpHi, d ); //slide upper marker inward again to get past 2nd dupe val tmpHi--; } else { //dupe < pivot swap( ++tmpLo, tmpHi, d ); tmpLo++; } } }//end big while //pivot has been floating around... plant it where it belongs d.set(tmpLo, indPiv); //recurse on lower and upper ranges qsHelpTick( lo, tmpLo-1, d ); qsHelpTick( tmpLo+1, hi, d ); }//end qsHelp
b72de233-e2ea-40df-89dc-0012776df854
4
public boolean collisionSideHelp(Obstacle[][] obs,int i, int j, int l) { boolean collide = obs[Math.max(i,0)][j].CollisionBot(); // In case of jump above the roof top limit. if ((y+height)/Obstacle.getHeight()<0) return false; // feet above the roof ^^ l += Obstacle.getHeight() / 2; // Why ? while (l<height){ if (i>=0) collide |= obs[i][j].CollisionBot(); l += Obstacle.getHeight(); ++i; } if (collide) { x -= moveX; // Put Stubi back in his N box if collision } return collide; }
93345ccc-8e8d-4594-976a-21c1aad765d6
8
public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_SPACE: // Start/Stop game if (timer.isRunning()) timer.stop(); else timer.start(); break; case KeyEvent.VK_C: // Clear grid life.clearGrid(); updateLifePanel(); break; case KeyEvent.VK_R: // Create random grid life = new GameOfLife(width, height, true); updateLifePanel(); break; case KeyEvent.VK_PLUS: // Increase speed if (timer.getDelay() > 50) timer.setDelay(timer.getDelay() - 50); break; case KeyEvent.VK_MINUS: // Decrease speed if (timer.getDelay() < 1000) timer.setDelay(timer.getDelay() + 50); break; } }
14e53f67-8e68-4df7-b08f-0140ef82078f
5
public void go() { up = down = left = right = w_key = a_key = s_key = d_key = false; if(firstGame) { gameFrame = new JFrame("Dry Ice Climber"); gameFrame.setSize(SCREEN_WIDTH, SCREEN_HEIGHT); gameFrame.setLocationRelativeTo(null); gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gameFrame.setResizable(false); surface = new GameSurface(this); gameFrame.add(surface); gameFrame.addKeyListener(new InputListener()); displayFont = new Font("Comic Sans MS", Font.BOLD, 36); } a = new Climber(this, "P1", 30, 50); if(twoPlayer) b = new Climber(this, "P2", 90, 50); else b = null; objects = new ArrayList<GameObject>(); objectsToRemove = new ArrayList<GameObject>(); //PowerUp jetpack = new PowerUp(this, SCREEN_WIDTH/2, SCREEN_HEIGHT/4, PowerUp.FLY); //PowerUp tallPowerUp = new PowerUp(this, SCREEN_WIDTH/2 - 50, SCREEN_HEIGHT/10, PowerUp.TALL); //objects.add(jetpack); //objects.add(tallPowerUp); int maxJ = SCREEN_WIDTH/Platform.DIMENSION; for(int i = 0; i < SCREEN_HEIGHT/PLAT_HEIGHT_DIST; i++) { for(int j = 0; j < maxJ; j++) { objects.add(new Platform(this, j*Platform.DIMENSION, (i)*PLAT_HEIGHT_DIST)); } } gameFrame.setVisible(true); height = 0; //instructions = true; //game = false; if(firstGame) { Timer t = new Timer(); t.scheduleAtFixedRate(new GameUpdater(), 100, 1000/FPS); } }
66a74140-f631-45bd-8bff-b6e7dfb9d1ff
5
@SuppressWarnings("unchecked") private void registerPacket(EnumProtocol protocol, Class<? extends Packet> packetClass, int packetID, boolean isClientbound) { try { if (isClientbound) { protocol.b().put(packetID, packetClass); } else { protocol.a().put(packetID, packetClass); } Field mapField = EnumProtocol.class.getDeclaredField("f"); mapField.setAccessible(true); Map<Class<? extends Packet>, EnumProtocol> map = (Map<Class<? extends Packet>, EnumProtocol>) mapField .get(null); map.put(packetClass, protocol); } catch (Exception e) { e.printStackTrace(); } }
9e78bbe2-b101-4b2b-b367-70561ac8acb6
5
private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { boolean isValueNumeric = false; try { if (value.equals("0") || !value.endsWith("0")) { Double.parseDouble(value); isValueNumeric = true; } } catch (NumberFormatException e) { isValueNumeric = false; } if (json.charAt(json.length() - 1) != '{') { json.append(','); } json.append(escapeJSON(key)); json.append(':'); if (isValueNumeric) { json.append(value); } else { json.append(escapeJSON(value)); } }
7fa34398-366c-4277-a4d8-89834d09757b
9
@Override public void unInvoke() { final Physical P=affected; super.unInvoke(); if((P instanceof MOB)&&(this.canBeUninvoked)&&(this.unInvoked)) { if((!P.amDestroyed()) &&(((MOB)P).amFollowing()==null)) { final Room R=CMLib.map().roomLocation(P); if(CMLib.law().getLandOwnerName(R).length()==0) { if(!CMLib.law().doesHavePriviledgesHere(invoker(), R)) { if((R!=null)&&(!((MOB)P).amDead())) R.showHappens(CMMsg.MSG_OK_ACTION, P,L("<S-NAME> wander(s) off.")); P.destroy(); } } } } }
511bfade-4349-4153-aac3-3caf6bec4611
9
public List<Path> generate() throws IOException { List<Path> paths = new ArrayList<>(); Map<String, List<Tick>> demomap = new LinkedHashMap<>(); Map<String, String> peeknext = new LinkedHashMap<>(); String previous = null; for (Tick tick : ticklist) { List<Tick> ticks; if (!demomap.containsKey(tick.getDemoname())) { ticks = new ArrayList<>(); demomap.put(tick.getDemoname(), ticks); } else { ticks = demomap.get(tick.getDemoname()); } ticks.add(tick); if (previous != null) { if (!peeknext.containsKey(previous) && !previous.equals(tick.getDemoname())) { peeknext.put(previous, tick.getDemoname()); } } previous = tick.getDemoname(); } for (Entry<String, List<Tick>> e : demomap.entrySet()) { String demo = e.getKey(); log.finer("Creating VDM file for demo: " + demo); List<String> lines = new ArrayList<>(); lines.add("demoactions\n{"); int count = 1; int previousEndTick = 0; for (Tick tick : e.getValue()) { if (cfg.getVdmSrcDemoFix()) { lines.add(segment(count++, "SkipAhead", "skip", "starttick \"" + (previousEndTick + 1) + "\"")); } else { lines.add(segment(count++, "SkipAhead", "skip", "starttick \"" + (previousEndTick + 1) + "\"", "skiptotick \"" + (tick.getStart() - 500) + "\"")); } lines.add(segment(count++, "PlayCommands", "startrec", "starttick \"" + tick.getStart() + "\"", "commands \"startrecording\"")); lines.add(segment(count++, "PlayCommands", "stoprec", "starttick \"" + tick.getEnd() + "\"", "commands \"stoprecording\"")); previousEndTick = tick.getEnd(); } String nextdemo = peeknext.get(demo); if (nextdemo != null) { lines.add(segment(count++, "PlayCommands", "nextdem", "starttick \"" + (previousEndTick + 1) + "\"", "commands \"playdemo " + nextdemo + "\"")); } else { lines.add(segment(count++, "PlayCommands", "stopdem", "starttick \"" + (previousEndTick + 1) + "\"", "commands \"stopdemo\"")); } lines.add("}\n"); Path added = Files.write(cfg.getTfPath().resolve(demo.substring(0, demo.indexOf(".dem")) + ".vdm"), lines, Charset.defaultCharset()); paths.add(added); log.fine("VDM file written to " + added); } return paths; }
a778b955-e545-42f2-8669-5d185d254e91
6
private static Map<Integer, Double> addActValue(Bookmark data, Map<Integer, Double> actValues, long baselineTimestamp, boolean resource, double dVal) { if (!data.getTimestamp().isEmpty()) { Double newAct = 0.0; if (resource) { newAct = 1.0; } else { Double recency = (double)(baselineTimestamp - Long.parseLong(data.getTimestamp()) + 1.0); //double recency = Math.ceil((baselineTimestamp - Long.parseLong(data.getTimestamp()) + 1.0) / 60.0 / 60.0 / 24.0 / 365.0 / 10); //System.out.println(recency); newAct = Math.pow(recency, dVal * -1.0); } for (Integer value : data.getTags()) { Double oldAct = actValues.get(value); if (!newAct.isInfinite() && !newAct.isNaN()) { actValues.put(value, (oldAct != null ? oldAct + newAct : newAct)); } else { System.out.println(data.getUserID() + "_" + baselineTimestamp + " " + data.getTimestamp()); } } } return actValues; }
9313419c-5c00-4c79-9aca-74fcc454bb5f
4
public int getPieceCount(PieceColor color) { int count = 0; for(Piece[] row : pieces) { for(Piece p : row) { if(p != null && p.getColor() == color) { count++; } } } return count; }
992bc2a6-6b67-4594-a51d-e868cf942191
9
public double[] getTrainingValues(LinkedList<Board> gameHistory, TaTeTi.CellValue player) throws Exception{ double[] trainValues = new double[gameHistory.size()]; Iterator it = gameHistory.iterator(); Board board; TaTeTi.CellValue oponent = player.equals(TaTeTi.CellValue.X) ? TaTeTi.CellValue.O : TaTeTi.CellValue.X; for(int i=0; i<gameHistory.size(); i++){ board = (Board)it.next(); if(board.isFinished()){ if(board.hasCellValueWon(player)) trainValues[i] = 100; else if(board.hasCellValueWon(oponent)) trainValues[i] = -100; else if (board.isFull()) trainValues[i] = 0; } else{ if(i+2 > gameHistory.size()-1){ if(gameHistory.get(gameHistory.size()-1).hasCellValueWon(oponent)) trainValues[i] = -100; else if (gameHistory.get(gameHistory.size()-1).hasCellValueWon(player)) trainValues[i] = 100; else trainValues[i] = 0; } else trainValues[i] = evaluateBoard(gameHistory.get(i+2), player); } } return trainValues; }
ed87e807-ff52-4142-ab0e-644fd88e39c6
6
protected static boolean addToZip(String absolutePath, String relativePath, String fileName, ZipOutputStream out) { File file = new File(absolutePath + File.separator + fileName); System.out.println("Adding \"" + absolutePath + File.separator + fileName + "\" file"); if (file.isHidden()) return true; if (file.isDirectory()) { absolutePath = absolutePath + File.separator + file.getName(); relativePath = relativePath + File.separator + file.getName(); for (String child : file.list()) { if (!addToZip(absolutePath, relativePath, child, out)) { return false; } } return true; } try { byte[] data = new byte[2048]; FileInputStream fi = new FileInputStream(file); BufferedInputStream origin = new BufferedInputStream(fi, 2048); ZipEntry entry = new ZipEntry(relativePath + File.separator + fileName); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, 2048)) != -1) { out.write(data, 0, count); } origin.close(); } catch (Exception ex) { Logger.getLogger(Zipper.class.getName()).log(Level.SEVERE, null, ex); return false; } return true; }
ceb7af9d-fb59-4f30-bd07-63da484f95ee
2
@Override public void playMonumentCard(IPresenter presenter) { MoveResponse response=presenter.getProxy().playMonumentCard(presenter.getPlayerInfo().getIndex(), presenter.getCookie()); if(response != null && response.isSuccessful()) { presenter.updateServerModel(response.getGameModel()); } else { System.err.println("Error playing monument in playing state"); } }
880694a1-6c73-4a2d-968b-284c9d916426
4
public Intersection getClosest(Ray r) throws Exception { Intersection closest = null; for (Entity o : objects) { Intersection p = o.findIntersect(r); if (p == null) { continue; } if (closest == null) { closest = p; continue; } if (p.getDistance() < closest.getDistance()) { closest = p; } } return closest; }
b36f2361-122c-4343-901f-0ba3f50c2259
8
@Override public boolean onRead(ByteBuffer sslBuffer) { logger.debug("Reading {}", sslBuffer); int bufferSize = sslEngine.getSession().getApplicationBufferSize(); ByteBuffer buffer = sslByteBuffers.acquire(bufferSize, false); try { out: while (handshaking) { SSLEngineResult.HandshakeStatus handshakeStatus = sslEngine.getHandshakeStatus(); logger.debug("Handshake status: {}", handshakeStatus); switch (handshakeStatus) { case NEED_UNWRAP: { if (handshakeUnwrap(sslBuffer, buffer)) break out; break; } case NEED_TASK: { executeTasks(); break; } case NEED_WRAP: { handshakeWrap(); break out; } case NOT_HANDSHAKING: { handshaking = false; // TLS handshake completed, now we are ready super.onOpen(); break out; } default: throw new IllegalStateException(); } } if (handshaking) return true; return wrap(sslBuffer, buffer); } catch (SSLException x) { controller.close(StreamType.INPUT_OUTPUT); throw new RuntimeIOException(x); } finally { sslByteBuffers.release(buffer); } }
252b2cad-b2e4-4048-8d8a-c40b297f15e3
0
public String getAsset_id() { return asset_id; }
36727de4-e628-4a71-90e1-230900d35f9d
5
public static void main(String[] args) { game = new Game(); Scanner scanner = new Scanner(System.in); while(!game.isGameOver()) { System.out.println(game.toString()); int chosenint; for (chosenint = -10; chosenint >= Direction.values().length || chosenint <0; chosenint=scanner.nextInt()) { int counter = 0; for(Direction d : Direction.values()) { System.out.println(counter + ": "+d.name()); counter++; } System.out.println("Please chose a direction: "); } try { System.out.println(game.moveNextPawn( Direction.values()[chosenint])); } catch (OutOfBoardException e) { System.out.println("You can't go that way!"); } } scanner.close(); }
d4f59778-a4d1-4340-bcc9-61a61097dbde
1
public void setFrontRightThrottle(int frontRightThrottle) { this.frontRightThrottle = frontRightThrottle; if ( ccDialog != null ) { ccDialog.getThrottle2().setText( Integer.toString(frontRightThrottle) ); } }
f3c6d573-219e-4ea2-8e58-096878b615a8
3
public CommandFactory() throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException { try(InputStream in = CommandFactory.class.getResourceAsStream("commands.properties")){ Properties p = new Properties(); Reader reader1 = new InputStreamReader(in); p.load(reader1); Command anyCmd = new PrintCommand(); // load "commands" package commandTable = new HashMap<>(); for (Object key:p.keySet() ) { String className= p.getProperty(key.toString()); StringBuilder packageName = new StringBuilder(""); Package[] packs = Package.getPackages(); for (Package pck :packs){ String fullClassName = pck.getName()+"."+className; try{ Class.forName(fullClassName); }catch(ClassNotFoundException e){ continue; } packageName = packageName.append(pck.getName().toCharArray()); break; } Class cls=Class.forName(packageName.toString()+"."+className); Object cmd=cls.newInstance(); Command cmd1=(Command)cmd; commandTable.put(key.toString(),cmd1); } } }
8e8d41bb-3641-4730-91fc-ace673d12188
7
public Packet decompress(Packet packet, PassthroughConnection ptc) { int stripes = packet.getInt(14) >> 1; int length = packet.getInt(18 + (stripes << 3)); Packet newPacket = packet.clone(fm); byte[] buffer = newPacket.buffer; if(length > bufferLength - 50) { return null; } for(int cnt = 0; cnt < stripes; cnt++) { packetHashes[cnt] = packet.getLong(18 + (cnt << 3)); } int start = 26 + (stripes << 3); i.reset(); i.setInput(buffer, start, length); i.finished(); int expandedLength; try { expandedLength = i.inflate(decompressed, 0, decompressed.length); } catch (DataFormatException dfe) { ptc.printLogMessage("Data format exception"); return null; } if (expandedLength >= decompressed.length) { return packet; } for(int cnt=0;cnt<stripes;cnt++) { //System.out.println("Header hash: 0x" + Long.toHexString(packetHashes[cnt])); byte[] block = hs.getHash(ptc, packetHashes[cnt]); if(block != null) { HashGenerator.copyToBuffer(decompressed, cnt, block); } else { block = new byte[2048]; HashGenerator.copyFromBuffer(decompressed, cnt, block); hs.addHash(packetHashes[cnt], block); } } d.reset(); d.setInput(decompressed, 0, expandedLength); d.finish(); int newSize = d.deflate(compressed); Packet outPacket = new Packet(); outPacket.buffer = new byte[newSize + 30]; outPacket.writeByte((byte)0x33); outPacket.writeInt(packet.getInt(1)); outPacket.writeInt(packet.getInt(5)); outPacket.writeByte(packet.getByte(9)); outPacket.writeShort(packet.getShort(10)); outPacket.writeShort(packet.getShort(12)); outPacket.writeInt(newSize); outPacket.writeInt(packet.getInt(22 + (stripes << 3))); System.arraycopy(compressed, 0, outPacket.buffer, 22, newSize); outPacket.end+=newSize; ptc.connectionInfo.saved.addAndGet(newSize - length - (stripes << 3) - 4); int percent = (int)(((100.0)*ptc.connectionInfo.saved.get())/ptc.connectionInfo.uploaded.get()); if(Main.craftGUI != null) { Main.craftGUI.safeSetStatus("<html>Saved " + (ptc.connectionInfo.saved.get()/1024) + " kB<br>Compression of " + percent + "</html>"); } else { //ptc.printLogMessage("Saved: " + percent); } //System.out.println("Saved % = " + ((100.0)*ptc.connectionInfo.saved.get())/ptc.connectionInfo.uploaded.get()); //System.out.println("New Size: " + newSize + " initial size: " + length); //System.out.println("Saved: " + ptc.connectionInfo.saved.get()); //System.out.println("Uploaded: " + ptc.connectionInfo.uploaded.get()); return outPacket; }
50e9de1f-3e08-41c7-9435-3cc1acc74b2f
3
public static Tile getTileAt(int x, int y, World world) { List<Tile> tiles = world.tiles; for (int i = 0; i < tiles.size(); i++) { if (tiles.get(i).position.x == x && tiles.get(i).position.y == y) { return tiles.get(i); } } return null; }
1429f947-4f1e-448e-8294-7e326c31b623
2
public long getLong(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } }
7e326d7f-d387-4b29-adea-63cd4394d1fd
3
public static ArrayList<Kill> findAttacker(ArrayList<Kill> killboard, String attacker) { ArrayList<Kill> resultBoard = new ArrayList<Kill>(); for (Kill K : killboard) { ArrayList<Pilot> attackingPilots = K.gettAttackingPilots(); for (Pilot P : attackingPilots) { if (P.findAttribute(attacker)) { resultBoard.add(K); } } } return resultBoard; }
19f8aaca-a94b-4373-85b0-f0cc36626ef7
0
public Long getId() { return id; }
e24d95a2-6005-47d9-9c14-0b600571764f
7
private static void group(String regex) { for (int i = listt.size() - 1; i >= 0; i--) { Tree t = listt.get(i); if (!t.isLeaf() && t.text.matches(regex)) { sortlist.add(t); fifter(t.getPid()); } } for (Tree t : sortlist) { if (t.isLeaf()) { List<Tree> tt = new ArrayList<Tree>(); sortMap.put(t.getId(), tt); } } for (Tree t : sortlist) { if (sortMap.containsKey(t.getPid())) { sortMap.get(t.getPid()).add(t); } else { List<Tree> tt = new ArrayList<Tree>(); tt.add(t); sortMap.put(0, tt); } } }
2d5eae42-e3e8-4a18-a194-0d59cf54769f
5
private static boolean isPrimitiveOrString(Object target) { if (target instanceof String) { return true; } Class<?> classOfPrimitive = target.getClass(); for (Class<?> standardPrimitive : PRIMITIVE_TYPES) { if (standardPrimitive.isAssignableFrom(classOfPrimitive)) { return true; } } return false; }
a67cb907-2581-48aa-a77c-f8107e65b570
4
public void generateAllRules() { for (Entry<Integer, List<ItemSet<V>>> entry : frequentItemSets .entrySet()) { // we only do this for itemsets larger 1, it'd be kind of a boring // rule otherwise now, wouldn't it if (entry.getKey() > 1) { System.out.println("Generating rules for level: " + entry.getKey()); // for each itemset this size for (ItemSet<V> itemSet : entry.getValue()) { System.out.println("handling itemset: " + itemSet); // for each of its items we generate a antecendent -> // consequent combination for (V is : itemSet.getItems()) { ItemSet<V> leftHandSide = itemSet.difference(is); ItemSet<V> rightHandSide = new ItemSet<V>(is); // System.out.println("Starting recursion for: " // + leftHandSide + " and " + rightHandSide); // start recursion for this combination generateRulesBase(leftHandSide, rightHandSide); } } } } }
17712b06-7e02-49e1-99e3-54a413b536c4
4
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Knooppunt other = (Knooppunt) obj; if (this.rij != other.rij) { return false; } if (this.kol != other.kol) { return false; } return true; }
1573200b-f687-4988-abda-7ccff8f12a11
1
public static void main(String[] args) { int personCount = 20; LiftView liftView = new LiftView(); Monitor monitor = new Monitor(liftView); Person[] persons = new Person[personCount]; for (int i = 0; i < personCount; i++) { persons[i] = new Person(monitor); persons[i].start(); } new Lift(monitor, liftView).start(); }
a398c5ff-24d8-44ae-95e4-884c489fea24
4
private String g_idxname( String f ) { int l = f.length(); String iext = (( l>4 && f.charAt(l-4) == '.' ) ? f.substring(l-3) : "" ); if( !iext.toLowerCase().equals("idx") ) f += "."+ (ext=="dbf" ? "idx" : "IDX"); return f; }
5961410d-2957-4aab-a95e-327e758c0aee
2
static public void main(String argv[]) { try { String name; if (argv.length == 1) { name = argv[0]; } else { name = "WebColor_Generator.txt"; } ComplexSymbolFactory csf = new ComplexSymbolFactory (); Lexer l = new Lexer(new FileReader(name)); l.setSymbolFactory(csf); Parser p = new Parser(l, csf); p.setContext(new Context()); p.parse(); } catch (Exception e) { e.printStackTrace(); } }
cd0b0482-03eb-4074-a0da-3b60e73463ad
1
public void updateRow(int index, Object[] array) { // data[rowIndex][columnIndex] = (String) aValue; EntityTransaction userTransaction = manager.getTransaction(); userTransaction.begin(); People updateRecord = peopleService.updatePeople((String) array[0], (String) array[1], (String) array[2], (String) array[3]); userTransaction.commit(); // set the current row to rowIndex int col = 0; // update the data in the model to the entries in array for (Object data : array) { setValueAt((String) data, index, col++); } }
283690a5-7ad8-40b6-9e90-1a02829e8cac
5
public void insert(int index, String stringItem, Image imageItem) { if (index > size() || index < 0) throw new IndexOutOfBoundsException(); ScmDeviceLabel label = new ScmDeviceLabel("item", null, true); label.selectButtonRequired = true; label.setText(stringItem); if (imageItem != null) { label.object = imageItem; label.image = imageItem._image; } label.highlight = true; label.checkbox = type != IMPLICIT; // label.addKeyListener(eventHandler); if (type == IMPLICIT){ label.selectOnFocus = true; label.addActionListener(listener); } if (group != null) { group.addElement(label); label.group = group; } list.add(label, index); }
ecfb35ef-8587-4700-85a2-158d919d5880
9
public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { //Presiono flecha izquierda direccion = 3; mueveJohn = true; } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { //Presiono flecha derecha direccion = 4; mueveJohn = true; } else if ((e.getKeyCode() == KeyEvent.VK_UP) && (!gravedadB)) { //Presiono flecha derecha brinco = 20; if (sonidosFlag) { sonidoSalta.play(); } } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { //Presiono flecha derecha mueveJohn = false; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { if ((jhon.getBalas() > 0) && !bala.getEnMovimiento()) { //Solo se puede disparar si se tienen balas y no se esta disparando jhon.setDispara(true); jhon.setNum(5); // Contador de tiempo para quedarse en la imagen de disparo y quedarse sin moverse jhon.setBalas(jhon.getBalas() - 1); sonidoDisparo.play(); bala.setPosX(jhon.getPosX()); bala.setPosY(jhon.getPosY() + jhon.getAlto() / 2); bala.cambiaDispara(); } } }
3ce99f6d-15ae-4de4-86af-aa0c8e01abcf
6
public static MethodSlot stellaFunctionFromProcedure(ComputedProcedure procedure) { if (procedure.procedureFunction != null) { return (procedure.procedureFunction); } { Symbol procedurename = procedure.procedureName; MethodSlot stellafunction = null; if (procedurename == null) { procedurename = Symbol.internSymbolInModule(procedure.surrogateValueInverse.symbolName, ((Module)(procedure.surrogateValueInverse.homeContext)), true); procedure.procedureName = procedurename; } stellafunction = Symbol.lookupFunction(procedurename); if (stellafunction == null) { { Symbol kernelname = Symbol.lookupSymbolInModule(procedurename.symbolName, Logic.$PL_KERNEL_MODULE$, false); if (kernelname != null) { stellafunction = Symbol.lookupFunction(kernelname); } } } if (stellafunction == null) { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); { Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get(); try { Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true); stream000.nativeStream.println("ERROR: Missing specialist, no STELLA function is named `" + procedurename + "'."); Logic.helpSignalPropositionError(stream000, Logic.KWD_ERROR); } finally { Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000); } } throw ((PropositionError)(PropositionError.newPropositionError(stream000.theStringReader()).fillInStackTrace())); } } if (Logic.$POWERLOOM_EXECUTION_MODE$ == Logic.KWD_RELEASE) { procedure.procedureFunction = stellafunction; } return (stellafunction); } }
f2898fc4-c21a-4b29-93ee-191d3728084b
4
@Override public double[][] updateVelocities(){ assert(neighbourhood != null && velocities != null && position != null); double constrictionCoefficient = calculateConstrictionCoefficient(); calculateVelocities(); for(int i = 0; i < velocities.length; i++){ for(int k = 0; k < velocities[i].length; k++){ velocities[i][k] = velocities[i][k] * constrictionCoefficient; } } return getVelocities(); }
9af98727-2ca6-4ecc-8ad8-b43dfba886d7
8
public String monthAdd(String field) { String newField = " ADD "; String number = ""; for(int i = 1; i <= field.length(); i++) { if(isNumber(field.substring(i - 1, i))) { number = number + field.substring(i - 1, i); } else { number = "~invalid~"; break; } boolean over = false; try { if(Integer.parseInt(number) > 12) { over = true; } }catch(Exception e) { System.out.println("not a integer"); } if(over) { number = "~invalid over~"; break; } } boolean under = false; try { if(Integer.parseInt(number) < 1) { under = true; } }catch(Exception e) { System.out.println("not a integer"); } if(under) { number = "~invalid under~"; } newField = newField + number; return newField; }
635e50f5-0082-40cb-9550-19f403cef565
3
private ByteBuffer readStream(ByteBuffer buf, PDFObject dict) throws IOException { // pointer is at the start of a stream. read the stream and // decode, based on the entries in the dictionary PDFObject lengthObj = dict.getDictRef("Length"); int length = -1; if (lengthObj != null) { length = lengthObj.getIntValue(); } if (length < 0) { throw new PDFParseException("Unknown length for stream"); } // slice the data int start = buf.position(); ByteBuffer streamBuf = buf.slice(); streamBuf.limit(length); // move the current position to the end of the data buf.position(buf.position() + length); int ending = buf.position(); if (!nextItemIs(buf, "endstream")) { System.out.println("read " + length + " chars from " + start + " to " + ending); throw new PDFParseException("Stream ended inappropriately"); } return streamBuf; // now decode stream // return PDFDecoder.decodeStream(dict, streamBuf); }
a42b2916-9086-41b2-b62d-6792f81ac75e
3
@Override public Card playTurn(Pile hand, Pile playedCards, int playerIndexOfWhoStarted) { // TODO (right now, for the purpose of testing, return any card in hand) // [Strategy] // Examine what Cards have been played, and by which Player // (playedCards is designed such that the first Card in the Pile is the card that was played first) // Examine the Cards in your hand, and return the Card you decide to play. // Keep GameType variables in mind in order to pick valid Cards. // (This can be used to test the error for a user not having a card they played). //if(true) // return new Card(Card.CARD_SUIT.CLUBS, Card.FACE_VALUE.ACE); // If we're not leading suit.. if(playedCards.getNumCards() > 0) { // Get the leading suit Card.CARD_SUIT leadingSuit = playedCards.getCard(0).getSuit(); // If we can find a leading suit card, let's play it, this way it will be a valid play. for(int i = 0; i < hand.getNumCards(); i++) if(hand.getCard(i).getSuit() == leadingSuit) { return hand.getCard(i); } } // Play a random card Random r = new Random(); int cardIndex = r.nextInt(hand.getNumCards()); return hand.getCard(cardIndex); }
0855ca78-9b94-4624-9e4e-a5074cf8397d
1
public static byte[][] generateSubKeys(byte[] key) { byte[] sourceCD = key; // Splitst de source array in twee tabellen (C, D) byte[] permutatedBlock = ByteHelper.permutFunc(sourceCD, permutatieTabel1); byte[] C = getFirstHalf(permutatedBlock); byte[] D = getSecondHalf(permutatedBlock); //Array om de keys in op te slaan byte[][] keys = new byte[16][6]; // bereken alle subkeys for (int i = 0; i < iteraties.length; i++) { //Voer de benodigde left shifts uit C = ByteHelper.rotateLeft(C, 28, iteraties[i]); D = ByteHelper.rotateLeft(D, 28, iteraties[i]); //Voeg C en D terug samen byte[] CD = combineCD(C, D); keys[i] = ByteHelper.permutFunc(CD, permutatieTabel2); } // TODO check key niet 00000000 of 111111111, of subkeys vaak gelijk, ... return keys; }
5a36d01b-90b8-41fc-9024-ac3a6f571761
2
@EventHandler public void onReload(ServerCommandEvent e){ if(e.getCommand().equalsIgnoreCase("reload")){ for(Player p : Bukkit.getOnlinePlayers()){ p.kickPlayer("[RP] Plugin is reloading!"); } } }
8b599d9e-21fe-4241-8cf5-ebe53f9e378a
7
void radb2(final int ido, final int l1, final double in[], final int in_off, final double out[], final int out_off, final int offset) { int i, ic; double t1i, t1r, w1r, w1i; int iw1 = offset; int idx0 = l1 * ido; for (int k = 0; k < l1; k++) { int idx1 = k * ido; int idx2 = 2 * idx1; int idx3 = idx2 + ido; int oidx1 = out_off + idx1; int iidx1 = in_off + idx2; int iidx2 = in_off + ido - 1 + idx3; double i1r = in[iidx1]; double i2r = in[iidx2]; out[oidx1] = i1r + i2r; out[oidx1 + idx0] = i1r - i2r; } if (ido < 2) return; if (ido != 2) { for (int k = 0; k < l1; ++k) { int idx1 = k * ido; int idx2 = 2 * idx1; int idx3 = idx2 + ido; int idx4 = idx1 + idx0; for (i = 2; i < ido; i += 2) { ic = ido - i; int idx5 = i - 1 + iw1; int idx6 = out_off + i; int idx7 = in_off + i; int idx8 = in_off + ic; w1r = wtable_r[idx5 - 1]; w1i = wtable_r[idx5]; int iidx1 = idx7 + idx2; int iidx2 = idx8 + idx3; int oidx1 = idx6 + idx1; int oidx2 = idx6 + idx4; t1r = in[iidx1 - 1] - in[iidx2 - 1]; t1i = in[iidx1] + in[iidx2]; double i1i = in[iidx1]; double i1r = in[iidx1 - 1]; double i2i = in[iidx2]; double i2r = in[iidx2 - 1]; out[oidx1 - 1] = i1r + i2r; out[oidx1] = i1i - i2i; out[oidx2 - 1] = w1r * t1r - w1i * t1i; out[oidx2] = w1r * t1i + w1i * t1r; } } if (ido % 2 == 1) return; } for (int k = 0; k < l1; k++) { int idx1 = k * ido; int idx2 = 2 * idx1; int oidx1 = out_off + ido - 1 + idx1; int iidx1 = in_off + idx2 + ido; out[oidx1] = 2 * in[iidx1 - 1]; out[oidx1 + idx0] = -2 * in[iidx1]; } }
2f5ec943-c53f-4856-adda-2293ab1e7f42
4
private LuaValue push_onecapture(int i, int soff, int end) { if (i >= this.level) { if (i == 0) { return s.substring(soff, end); } else { return error("invalid capture index"); } } else { int l = clen[i]; if (l == CAP_UNFINISHED) { return error("unfinished capture"); } if (l == CAP_POSITION) { return valueOf(cinit[i] + 1); } else { int begin = cinit[i]; return s.substring(begin, begin + l); } } }
cd23a2fb-757b-44d9-ba43-e44d22c5d482
9
private static List<PolygonP> transformPointsToPolygon(List<Point[]> polygonPointList){ List<PolygonP> polygons = new ArrayList<PolygonP>(); for(Point[] polygonPoints : polygonPointList){ int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE, height = 0; for(Point point : polygonPoints){ if(point.y > height) max = point.y; if(point.y < min) min = point.y; } height = Math.abs(max - min); System.out.println("==========================="); System.out.println("Object "+polygons.size()+" height "+height); Point[] polygonBounds = new Point[height * 2]; int index = 0, y = 0; boolean left = false; for(int i = 0; i < polygonPoints.length; i++){ if(!left){ polygonBounds[polygonBounds.length - index - 1] = polygonPoints[i]; left = true; y = polygonPoints[i].y; } if(left && (i == polygonPoints.length - 1 || polygonPoints[i+1].y == y + 1)){ polygonBounds[index] = polygonPoints[i]; left = false; index++; y++; } } polygons.add(PolygonP.create(polygonBounds)); } return polygons; }
ea94955b-eae1-4fea-883d-a9a2aefb4a59
0
public void doSomething() { System.out.println("共通処理 " + LoggerUtils.getSig()); strategy.logic1(); strategy.logic2(); }
0090c3d6-5cdf-4bbd-974d-ae1021618fcb
9
private static Source toSource(Object xml) throws IOException { if(xml==null) throw new IllegalArgumentException("no XML is given"); if (xml instanceof String) { try { xml=new URI((String)xml); } catch (URISyntaxException e) { xml=new File((String)xml); } } if (xml instanceof File) { File file = (File) xml; return new StreamSource(file); } if (xml instanceof URI) { URI uri = (URI) xml; xml=uri.toURL(); } if (xml instanceof URL) { URL url = (URL) xml; return new StreamSource(url.toExternalForm()); } if (xml instanceof InputStream) { InputStream in = (InputStream) xml; return new StreamSource(in); } if (xml instanceof Reader) { Reader r = (Reader) xml; return new StreamSource(r); } if (xml instanceof Source) { return (Source) xml; } throw new IllegalArgumentException("I don't understand how to handle "+xml.getClass()); }
81b8040f-33b9-46ba-9a5d-0ff518d78ec8
5
public Object showInfoTableContent(String listName, String conditions) { if (!(listName.equals("student_list") || listName.equals("login_list") || listName .equals("log_list"))) { listName = "teacher_list;" + listName.split("_")[0]; } String command2 = "show;" + listName + ";" + conditions; ArrayList<String> list = null; String[][] content = null; try { NetService client = initNetService(); client.sendCommand(command2); list = client.receiveList(); content = new String[list.size()][]; for (int i = 0; i < list.size(); i++) { content[i] = list.get(i).split(";"); } client.shutDownConnection(); } catch (Exception e) { e.printStackTrace(); return Feedback.INTERNET_ERROR; } return content; }
955d5cca-6bea-44cd-b172-8d09db958491
2
public void add(Production production) { String lhs = production.getLHS(), rhs = production.getRHS(); // Does the RHS already have a unique mapping? if (rhsToLhs.containsKey(rhs)) throw new IllegalArgumentException(rhs + " already represented by " + rhsToLhs.get(rhs)); // Add the production. Set rhses = (Set) lhsToRhs.get(lhs); if (rhses == null) { rhses = new HashSet(); lhsToRhs.put(lhs, rhses); } rhses.add(rhs); rhsToLhs.put(rhs, lhs); }
7cac4151-2a2f-4cee-97bf-9bfaebfd228a
6
public static final char next (final int row, final int col, final char[][] map) { initMovesRecord(map); final GameSimulation initGame = new GameSimulation(map); final NodeForExhaust initNode = new NodeForExhaust(initGame, SEARCH_DEPTH); final ArrayList<NodeForExhaust> resultSet = new ArrayList<NodeForExhaust>(); // Use stack because depth first search will be space efficient. final ArrayDeque<NodeForExhaust> frontierStack = new ArrayDeque<NodeForExhaust>(); for (char action : ACTION_SET) { final NodeForExhaust firstStepNode = getSuccessor(initNode, action); if (firstStepNode != null) { firstStepNode.setAncestorAction(action); frontierStack.push(firstStepNode); } } while (!frontierStack.isEmpty()) { final NodeForExhaust curNode = frontierStack.pop(); if (curNode.isEnd()) { resultSet.add(curNode); } else { // Get the successor of current node. for (char action : ACTION_SET) { final NodeForExhaust nextStepNode = getSuccessor(curNode, action); if (nextStepNode != null) { frontierStack.push(nextStepNode); } } } // if (curState.isEnd()) { } // while (!frontierStack.isEmpty()) { final NodeForExhaust bestNode = Collections.max(resultSet, null); updateRecordMap(bestNode, row, col); return bestNode.getAncestorAction(); }
2641ecb5-8560-4d47-ad92-6441cc2ce446
8
public int compare(String o1, String o2) { String s1 = (String)o1; String s2 = (String)o2; int thisMarker = 0; int thatMarker = 0; int s1Length = s1.length(); int s2Length = s2.length(); while (thisMarker < s1Length && thatMarker < s2Length) { String thisChunk = getChunk(s1, s1Length, thisMarker); thisMarker += thisChunk.length(); String thatChunk = getChunk(s2, s2Length, thatMarker); thatMarker += thatChunk.length(); // If both chunks contain numeric characters, sort them numerically int result = 0; if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // Simple chunk comparison by length. int thisChunkLength = thisChunk.length(); result = thisChunkLength - thatChunk.length(); // If equal, the first different number counts if (result == 0) { for (int i = 0; i < thisChunkLength; i++) { result = thisChunk.charAt(i) - thatChunk.charAt(i); if (result != 0) { return result; } } } } else { result = thisChunk.compareTo(thatChunk); } if (result != 0) return result; } return s1Length - s2Length; }
f1e01c30-cbcc-4402-aee2-09336b414c93
9
public static void main(String[] params) { String cp = System.getProperty("java.class.path", ""); cp = cp.replace(File.pathSeparatorChar, Decompiler.altPathSeparatorChar); String bootClassPath = System.getProperty("sun.boot.class.path"); if (bootClassPath != null) cp += Decompiler.altPathSeparatorChar + bootClassPath.replace(File.pathSeparatorChar, Decompiler.altPathSeparatorChar); int i = 0; if (i < params.length) { if (params[i].equals("--classpath") || params[i].equals("--cp") || params[i].equals("-c")) cp = params[++i]; else if (params[i].startsWith("-")) { if (!params[i].equals("--help") && !params[i].equals("-h")) System.err.println("Unknown option: " + params[i]); usage(); return; } else cp = params[i]; i++; } if (i < params.length) { System.err.println("Too many arguments."); usage(); return; } Main win = new Main(cp); win.show(); }
04f4e420-268b-45fc-b8d9-968e1def54e3
1
@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLayeredPane2 = new javax.swing.JLayeredPane(); jLabel1 = new javax.swing.JLabel(); val_token = new javax.swing.JTextField(); btn_generate_token = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); jLayeredPane3 = new javax.swing.JLayeredPane(); jScrollPane1 = new javax.swing.JScrollPane(); table_token = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setName("frameToken"); // NOI18N setResizable(false); jLabel1.setText("CAD:"); val_token.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { val_tokenActionPerformed(evt); } }); btn_generate_token.setText("OK"); btn_generate_token.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_generate_tokenActionPerformed(evt); } }); javax.swing.GroupLayout jLayeredPane2Layout = new javax.swing.GroupLayout(jLayeredPane2); jLayeredPane2.setLayout(jLayeredPane2Layout); jLayeredPane2Layout.setHorizontalGroup( jLayeredPane2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jLayeredPane2Layout.createSequentialGroup() .addGap(9, 9, 9) .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(val_token) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btn_generate_token)) ); jLayeredPane2Layout.setVerticalGroup( jLayeredPane2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jLayeredPane2Layout.createSequentialGroup() .addContainerGap() .addGroup(jLayeredPane2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jLayeredPane2Layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(val_token)) .addGroup(jLayeredPane2Layout.createSequentialGroup() .addGroup(jLayeredPane2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(btn_generate_token)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jLayeredPane2.setLayer(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER); jLayeredPane2.setLayer(val_token, javax.swing.JLayeredPane.DEFAULT_LAYER); jLayeredPane2.setLayer(btn_generate_token, javax.swing.JLayeredPane.DEFAULT_LAYER); table_token.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "", "Token", "Lexema" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(table_token); if (table_token.getColumnModel().getColumnCount() > 0) { table_token.getColumnModel().getColumn(0).setMinWidth(20); table_token.getColumnModel().getColumn(0).setMaxWidth(30); table_token.getColumnModel().getColumn(1).setResizable(false); table_token.getColumnModel().getColumn(2).setResizable(false); } javax.swing.GroupLayout jLayeredPane3Layout = new javax.swing.GroupLayout(jLayeredPane3); jLayeredPane3.setLayout(jLayeredPane3Layout); jLayeredPane3Layout.setHorizontalGroup( jLayeredPane3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jLayeredPane3Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1) .addContainerGap()) ); jLayeredPane3Layout.setVerticalGroup( jLayeredPane3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jLayeredPane3Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 383, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLayeredPane3.setLayer(jScrollPane1, javax.swing.JLayeredPane.DEFAULT_LAYER); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLayeredPane3) .addComponent(jLayeredPane2, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLayeredPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLayeredPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(63, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents
5d0c7b2c-26a0-4eff-98a5-963e71a014d4
6
public Codebook getMostInformativeSubset() { // Get distance matrix for all basis vectors. int numVects = basisVectors.getColumnDimension(); double[][] proximity = new double[numVects][]; for(int i = 0; i < numVects; i++){ proximity[i] = new double[i+1]; for(int j = 0; j < i; j++){ proximity[i][j] = MaximalCrossCorrelation.distance( basisVectors.getColumnVector(i), basisVectors.getColumnVector(j)); } } // Generate complete linkage cluster. HierarchicalClustering hc = new HierarchicalClustering(new CompleteLinkage(proximity)); // Cutoff at (ceil) number of vectors / 10. int numClusters = (int) Math.ceil((double) numVects/10); int[] label = hc.partition(numClusters); // Separate clusters // Allocate. ArrayList<ArrayList<RealVector>> res = new ArrayList<ArrayList<RealVector>>(numClusters); for(int i = 0; i < numClusters; i++){ res.add(new ArrayList<RealVector>()); } // Populate. for(int i = 0; i < label.length; i++){ res.get(label[i]).add(basisVectors.getColumnVector(i)); } // Extract most relevant basis vectors. LinkedList<RealVector> newBasisVectors = new LinkedList<RealVector>(); for(int i = 0; i < numClusters; i++){ ArrayList<RealVector> currList = res.get(i); // Sort. Collections.sort(currList, new java.util.Comparator<RealVector>() { public int compare(RealVector a, RealVector b) { double shanA = empiricalEntropy(a, 10); double shanB = empiricalEntropy(b, 10); return Double.compare(shanB, shanA); } }); // Select most relevant 90%. int itemsToSelect = (int) Math.min(Math.ceil( (double) currList.size()*0.9), currList.size()); for(int j = 0; j < itemsToSelect; j++){ newBasisVectors.add(currList.get(j)); } } // Return better codebook. return new Codebook(newBasisVectors, this.alpha); }
fdaacef9-cdf5-42fc-8c21-fc1198c30f1b
6
protected com.akamon.slots.model.SymbolSet ParseSymbolSet(SymbolSet xmlSymbolSet) throws SlotModelException { com.akamon.slots.model.SymbolSet modelSymbolSet = new com.akamon.slots.model.SymbolSet(xmlSymbolSet.name); for(NaturalSymbol xmlNaturalSymbol : xmlSymbolSet.getNaturalSymbol()) { modelSymbolSet.addNaturalSymbol(xmlNaturalSymbol.name); } for(SymbolClassPlaceHolder xmlSymbolClassPlaceholder : xmlSymbolSet.symbolClassName) { modelSymbolSet.addSymbolClassName(xmlSymbolClassPlaceholder.name, xmlSymbolClassPlaceholder.type.equals("Exclude")); } for(SubstitutionScheme xmlSubScheme : xmlSymbolSet.substitutionScheme) { modelSymbolSet.createSubstitutionScheme(xmlSubScheme.name, xmlSubScheme._default != null && xmlSubScheme.isDefault()); for (SymbolClass symbolClass : xmlSubScheme.getSymbol()) { for(SymbolClass.ComponentSymbol component : symbolClass.componentSymbol) { modelSymbolSet.addSubstitution(xmlSubScheme.name, symbolClass.name, component.symbolname); } } } return modelSymbolSet; }
a61d4950-8058-423c-ad37-a811a6012025
8
public static void idlOutputAllUnitsToFile(String sourcefile) { { String codeoutputfile = Stella.idlMakeCodeOutputFileName(sourcefile); OutputFileStream codeoutputstream = OutputFileStream.newOutputFileStream(codeoutputfile); Cons globals = Stella.NIL; Cons methods = Stella.NIL; Cons verbatimstatements = Stella.NIL; Cons forms = Stella.NIL; { Object old$CurrentStream$000 = Stella.$CURRENT_STREAM$.get(); try { Native.setSpecial(Stella.$CURRENT_STREAM$, codeoutputstream); Native.setSpecial(Stella.$TRANSLATIONUNITS$, ((List)(Stella.$TRANSLATIONUNITS$.get())).reverse()); { TranslationUnit unit = null; Cons iter000 = ((List)(Stella.$TRANSLATIONUNITS$.get())).theConsList; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { unit = ((TranslationUnit)(iter000.value)); { Symbol testValue000 = unit.category; if ((testValue000 == Stella.SYM_STELLA_METHOD) || ((testValue000 == Stella.SYM_STELLA_PRINT_METHOD) || (testValue000 == Stella.SYM_STELLA_MACRO))) { methods = Cons.cons(unit.translation, methods); } else if (testValue000 == Stella.SYM_STELLA_VERBATIM) { verbatimstatements = Cons.cons(unit.translation, verbatimstatements); } else if (testValue000 == Stella.SYM_STELLA_GLOBAL_VARIABLE) { globals = Cons.cons(unit.translation, globals); } else { forms = Cons.cons(unit.translation, forms); } } } } System.out.println("Writing `" + codeoutputfile + "'..."); { ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.println("// " + codeoutputfile); ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.println(); } ; if (Stella.translateWithCopyrightHeaderP()) { OutputStream.outputCopyrightHeader(((OutputStream)(Stella.$CURRENT_STREAM$.get()))); } { Stella_Object form = null; Cons iter001 = forms; for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) { form = iter001.value; Stella_Object.idlOutputStatement(((Cons)(form))); } } codeoutputstream.free(); } finally { Stella.$CURRENT_STREAM$.set(old$CurrentStream$000); } } } }
042e6eb7-1c20-4f0f-9058-fc1bb78f86d7
0
public void setUserObject(Object userObject) { this.userObject = userObject; }
f9961daf-cb9f-4bac-846d-ebe51cda14cc
4
public static void main(String[] args) throws IOException { BufferedReader buf = new BufferedReader( new InputStreamReader(System.in)); String line = ""; StringBuilder sb = new StringBuilder(); int f = 0; d: do { line = buf.readLine(); if(line==null || line.length()==0) break d; int c = Integer.parseInt(line); String n =factorial(new BigInteger(String.valueOf(c)), c).toString(); sb.append(suma(n)).append("\n"); //System.out.println(suma(n)); } while (line != null && line.length()!=0); System.out.print(sb); }
be245a99-8d3b-4089-a302-a5c24ce72187
6
private void resetCanBeAvail(final ExprInfo exprInfo, final Phi phi) { phi.setCanBeAvail(false); final Iterator blocks = cfg.nodes().iterator(); // For each phi whose operand is at while (blocks.hasNext()) { final Block block = (Block) blocks.next(); final Phi other = exprInfo.exprPhiAtBlock(block); if (other == null) { continue; } final Iterator e = cfg.preds(other.block()).iterator(); while (e.hasNext()) { final Block pred = (Block) e.next(); final Def def = other.operandAt(pred); if (def == phi) { other.setOperandAt(pred, null); if (!other.downSafe() && other.canBeAvail()) { resetCanBeAvail(exprInfo, other); } } } } }
8db7018e-5a20-4b18-a8d6-95cb1a43718a
9
public boolean isFlowerOut(Graph a_graph) { //First, see this node. for(int i = 0; i < m_enemies.size(); ++i) { if(m_enemies.get(i).m_type == Sprite.KIND_ENEMY_FLOWER) { return true; } } //If not, I have neighbors IN THE SAME POT that could have the flower. int numN = m_edges.size(); for(int i = 0; i < numN; ++i) { Edge edg = a_graph.getEdge(m_edges.get(i)); if(edg != null && (edg.getMode() == Graph.MODE_WALK_BIG || edg.getMode() == Graph.MODE_WALK_SMALL)) { int nodeId = edg.getA() != m_id ? edg.getA() : edg.getB(); Node n = a_graph.getNode(nodeId); Vector<Enemy> destEnemies = n.getEnemies(); for(int j = 0; j < destEnemies.size(); ++j) { if(destEnemies.get(j).m_type == Sprite.KIND_ENEMY_FLOWER) { return true; } } } } return false; }
6d1b5be3-26f3-4fe8-bc53-42dd7eba773a
3
@Override public boolean onBlockActivated( World world, int x, int y, int z, EntityPlayer player, int i, float j, float k, float l ) { if (!world.isRemote) { TileEntity te = world.getTileEntity(x, y, z); if (te == null || player.isSneaking()) return false; player.openGui(GraphiteMod.instance, GUIHandler.GUI_DISTILLERY, world, x, y, z); } return true; }
242e37fa-0956-4db1-b4b9-eba0b0b2d0eb
1
private boolean isValidIdentityDiscCoverage(Grid grid) { final int identityDiscCount = getIdentityDiscsOfGrid(grid).size(); if (identityDiscCount * 100 / grid.gridSize() <= 2) return true; return false; }
ec2caa22-7aeb-49fe-9029-b0fa03a1c13e
4
public static Map<AnagramWord, String> findAnagrams(File wordFile) { Map<AnagramWord, String> anagramList = new HashMap<AnagramWord, String>(); List<AnagramWord> wordList = extractWords(wordFile); for (AnagramWord word : wordList) { if (anagramList.containsKey(word)) { String anagram = anagramList.get(word); anagram = anagram + " " + word.display(); anagramList.put(word, anagram); } else { anagramList.put(word, word.display()); } } for (Iterator<String> it = anagramList.values().iterator(); it.hasNext();) { String word = it.next(); if(!wordHasAnagrams(word)) { it.remove(); } } return anagramList; }
e56fb77c-1276-4c86-aa77-a3f2cba523a1
3
private List<Keyword> keywordsFromType(KeywordType type, List<Keyword> keywords) { List<Keyword> res = new ArrayList<Keyword>(); if (keywords == null) { return res; } for (Keyword keyword : keywords) { if (keyword.getKeywordData().getType().equals(type)) { res.add(keyword); } } return res; }
ebdf967a-96e2-45f1-a9bf-e516b1810eb7
7
SpellGroup getSpellGroup(String strName) { SpellGroup grpStore; for (int i=0;i<vctSpellGroups.size();i++) { grpStore = (SpellGroup)vctSpellGroups.elementAt(i); if (strName.equalsIgnoreCase(grpStore.strName)) { return grpStore; } } try { grpStore = new SpellGroup(strName); RandomAccessFile rafSpellGroup = new RandomAccessFile("defSpellGroups/"+strName,"r"); try { String strStore = rafSpellGroup.readLine(); while (strStore != null && !strStore.equals("") && !strStore.equals(".")) { grpStore.vctSpells.addElement(strStore); strStore = rafSpellGroup.readLine(); } }catch (Exception e) { log.printError("getSpellGroup():While trying to read spell group file for \""+strName+"\"", e); } rafSpellGroup.close(); vctSpellGroups.addElement(grpStore); return grpStore; }catch(Exception e) { log.printError("getSpellGroup():While trying to get spell group info for \""+strName+"\"", e); } return null; }
c87a6149-3953-43b8-89ba-e593cafd57b5
7
public int edmons_karp(int s, int t) { int u, e; mf = 0; this.s = s; Arrays.fill(p, -1); while (true) { f = 0; Queue<Integer> q = new LinkedList<Integer>(); int[] dist = new int[V]; Arrays.fill(dist, INF); dist[s] = 0; q.offer(s); Arrays.fill(p, -1); while (!q.isEmpty()) { u = q.poll(); if (u == t) break; for (int i = 0; i < ady[u].size(); i++) { e = ady[u].get(i); if (g[u][e] > 0 && dist[e] == INF) { dist[e] = dist[u] + 1; q.offer(e); p[e] = u;// parent of vertex e is vertex u } } } augment(t, INF); if (f == 0) break; mf += f; } return mf; }
b7adc6fb-8038-4698-8a92-b425da304e4c
3
public void setDisplayOptions (int ordering, int nameForm, int direction) { // Only update if something has changed. if ( (currentDisplayOrdering != ordering) || (currentDisplayNameForm != nameForm) || (currentDisplayDirection != direction) ) { // store the new values. currentDisplayOrdering = ordering; currentDisplayNameForm = nameForm; currentDisplayDirection = direction; // sync view to model. syncTreeSet(); syncMenuItems(); } }
e49237a9-787c-4872-8ea4-00ec0abeb4ce
0
public HBox initHeader(String titleText) { HBox header = new HBox(); header.setAlignment(Pos.CENTER_LEFT); header.getStyleClass().add("popUpHeader"); header.setPrefHeight(28); Button closeBtn = new Button(); closeBtn.getStyleClass().add("close-button"); closeBtn.setPrefSize(16, 16); closeBtn.setMinSize(16, 16); closeBtn.setMaxSize(16, 16); closeBtn.setCursor(Cursor.HAND); closeBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { closePopUp(); } }); StackPane sp = new StackPane(); sp.getChildren().add(closeBtn); sp.setAlignment(Pos.CENTER_RIGHT); Label titleLbl = new Label(titleText); titleLbl.getStyleClass().add("popUpHeaderLbl"); header.getChildren().addAll(titleLbl, sp); HBox.setHgrow(sp, Priority.ALWAYS); addDragListeners(header); return header; }
7ea2591c-9332-423f-92f9-bae8f97212f0
3
public String insertionSort2(String a) { char[] arr = a.toCharArray(); char tmp; for (int i = 1; i < arr.length; i++) { for (int j = i; j > 0; j--) { if (arr[j] < arr[j - 1]) { tmp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = tmp; } else break; } } return new String(arr); }
48656651-bd72-4410-8fcc-d6192218e7c6
3
public static String platformToLineEnding(String platform) { if (platform.equals(PLATFORM_MAC)) { return LINE_END_MAC; } else if (platform.equals(PLATFORM_WIN)) { return LINE_END_WIN; } else if (platform.equals(PLATFORM_UNIX)) { return LINE_END_UNIX; } else { return LINE_END_DEFAULT; } }
02be234f-6166-428e-a2b6-77f93fe6c522
3
@Override public void moveItem(String fromPath, String toPath) throws ContentRepositoryException, IOException { File from = new File(rootDir, fromPath); File to = new File(rootDir, toPath); if (from.isDirectory()) { if (to.isDirectory()) { FileUtils.moveDirectoryToDirectory(from, to, false); } else { FileUtils.moveDirectory(from, to); } } else { if (to.isDirectory()) { FileUtils.moveFileToDirectory(from, to, true); } else { FileUtils.moveFile(from, to); } } }
d9304c50-6059-4da9-8f23-2a375d4011df
0
public static void StartingHall() { currentRoomName = "Starting Hall"; currentRoom = 1; RoomDescription = "The room is small, square and made of solid stone. It is cold and there is a ladder " + "going up through a hatch."; }
d5e1129a-ff6d-4065-af61-3a0ca4f37f0e
2
public static void unregisterFrame(EnvironmentFrame frame) { try { fileToFrame.remove(getPath(frame.getEnvironment().getFile())); } catch (NullPointerException e) { // The environment doesn't have a file. } environmentToFrame.remove(frame.getEnvironment()); // If there are no other frames open, prompt for newness. if (numberOfFrames() == 0) gui.action.NewAction.showNew(); }
6f2a5cd0-8aef-454e-919a-f76530f5b87f
4
@Override public Border getBorderStyle(Side side) { switch (side) { case TOP: return topBorder; case LEFT: return leftBorder; case BOTTOM: return bottomBorder; case RIGHT: return rightBorder; } return null; }
016d73d4-933f-42de-adc9-25e6e611f612
6
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(AboutDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AboutDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AboutDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AboutDialog.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 AboutDialog().setVisible(true); } }); }
44b72057-d1d8-45b6-9c98-50e4fd604cf1
3
public synchronized void actualiza(long tiempoTranscurrido){ if (cuadros.size() > 1){ tiempoDeAnimacion += tiempoTranscurrido; if (tiempoDeAnimacion >= duracionTotal){ tiempoDeAnimacion = tiempoDeAnimacion % duracionTotal; indiceCuadroActual = 0; } while (tiempoDeAnimacion > getCuadro(indiceCuadroActual).tiempoFinal){ indiceCuadroActual++; } } }
45f3c4b5-d6ec-41df-a101-325e6862d41a
5
public static final void main(String... args) { String bigNumber = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"; List<Integer> numbers = new ArrayList<>(); for (int i = 0; i < bigNumber.length(); i++) { numbers.add(Character.digit(bigNumber.charAt(i), 10)); } int result = 0; int startIndex = 0; List<Integer> numbersSequance = numbers.subList(startIndex, startIndex + 5); if (isIncludeZero(numbersSequance) > 0) { startIndex = numbers.indexOf(0); } else { result = multipling(numbersSequance); startIndex = 5; } for (int i = startIndex; i < numbers.size() - 1 - 5; i++) { numbersSequance = numbers.subList(i, i + 5); if (isIncludeZero(numbersSequance) > 0) { i += isIncludeZero(numbersSequance); } int productive = 1; multipling(numbersSequance); if (productive > result) { result = productive; } iterations++; } System.out.println("Result: " + result); System.out.println("Iterations: " + iterations); }
2467d89c-4e16-452d-b99f-47f657f8c20a
3
private void createTSPFile(int dimension) throws IOException { FileWriter writer = new FileWriter(path, false); PrintWriter printer = new PrintWriter(writer); printer.printf("%s" + "%n", "NAME: " + path); printer.printf("%s" + "%n", "TYPE: TSP"); printer.printf("%s" + "%n", "DIMENSION: " + dimension); printer.printf("%s" + "%n", "EDGE_WEIGHT_TYPE: EXPLICIT"); printer.printf("%s" + "%n", "EDGE_WEIGHT_FORMAT: LOWER_DIAG_ROW"); printer.printf("%s" + "%n", "EDGE_WEIGHT_SECTION"); for(int i = 0; i < dimension; i++) { for(int j = 0; j <= i; j ++) { try { printer.printf("%s" + "%n", graph[i][j]); } catch (NullPointerException e) { printer.printf("%s" + "%n", "2"); } } } printer.printf("%s" + "%n", "EOF"); printer.flush(); printer.close(); }
9997ed60-3b2b-4914-8045-d29589a2f48e
6
public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (num.length == 0) return result; if (num.length == 1) { ArrayList<Integer> onePermute = new ArrayList<Integer>(); onePermute.add(new Integer(num[0])); result.add(onePermute); return result; } ArrayList<Integer> visited = new ArrayList<Integer>(); for (int i = 0; i < num.length; i++) { Integer curInt = new Integer(num[i]); if (visited.contains(curInt)) { break; } else { visited.add(curInt); ArrayList<Integer> restInts = new ArrayList<Integer>(); for (int j = 0; j < num.length; j++) { if (j != i) restInts.add(new Integer(num[j])); } // ArrayList<ArrayList<Integer>> restPermute = // getPermute(restInts); } } return result; }
b8d3165e-d150-4f26-9b57-dd4bd9365dae
7
public void crearGrups(FitxerJugadorsOut espases, FitxerJugadorsOut oros, FitxerJugadorsOut copes, FitxerJugadorsOut bastos) { try { Jugador j = (Jugador)ois.readObject(); while(!j.esCentinela()) { switch(j.getEquip()) { case ESPASES: espases.escriu(j); break; case OROS: oros.escriu(j); break; case COPES: copes.escriu(j); break; case BASTOS: bastos.escriu(j); break; } j = (Jugador)ois.readObject(); } } catch (ClassNotFoundException e) { System.out.println("Error: " + e.getMessage()); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } }
c7369880-a052-4b32-9da5-1f6a2adec46c
4
public int[] getRoomCoords(MansionArea room) { int[] coords = {-2, -2}; if(room.equals(start)) { coords[0] = -1; coords[1] = -1; }else { for(int i=0; i<grid.length; i++) { for(int j=0; j<grid[0].length; j++) { if(room.equals(grid[i][j])) { coords[0] = i; coords[1] = j; } } } } return coords; }
67f7816f-9819-4f26-aa2c-c03b184dbebb
1
public void incluirNoFim(ContaCorrente conta) { if(this.quantasContas >= this.capacidade) this.aContas[this.capacidade-1] = conta; else this.aContas[this.quantasContas] = conta; this.quantasContas ++; }
da7b49ff-0684-4656-aeeb-ff18c5277079
7
public TriTileCoord pointToCoord(Point2D point, TriTileDimension dim) { final int section_x = (int) (point.getX() / (dim.getSide() / 2.0)); final int sectionPxl_x = (int) (point.getX() % (dim.getSide() / 2.0)); final int coord_y = (int) (point.getY() / dim.getHeight()); final int sectionPxl_y = (int) (point.getY() % dim.getHeight()); final double m = dim.getHeight() / (dim.getSide() / 2.0); final int coord_x; int yforx = (int) (sectionPxl_x * m); if((0 != (section_x % 2) ^ (0 != (coord_y % 2)))) { // points down if(sectionPxl_y > yforx) { coord_x = section_x -1; } else { coord_x = section_x; } } else { // points up if(sectionPxl_y < (dim.getHeight() - yforx)) { coord_x = section_x - 1; } else { coord_x = section_x; } } if ((coord_x < 0) || (coord_x >= getXSize()) || (coord_y < 0) || (coord_y >= getYSize())) { return null; } else { return new TriTileCoord(coord_x, coord_y); } }
bfa9749d-9044-431c-98ef-9dbb681dd1fa
9
private JSON urlfetch(URI uri, int protocol, Map<String, String> headers, CharSequence content, boolean sign) { JSON result = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpRequestBase method = null; if (protocol == GET) { method = new HttpGet(uri); } else { HttpPost httppost = new HttpPost(uri); httppost.setEntity(new StringEntity(content.toString())); method = httppost; } for (Map.Entry<String, String> e : headers.entrySet()) { method.setHeader(e.getKey(), e.getValue()); } if (sign) { sign(method); } HttpResponse response = httpclient.execute(method); HttpEntity entity = response.getEntity(); if (entity != null) { result = JSON.parse(new InputStreamReader(entity.getContent(), "UTF-8")); } else { result = JSON.o(); } } catch (ClientProtocolException e) { throw new FreebaseException(e); } catch (IOException e) { throw new FreebaseException(e); } catch (IllegalStateException e) { throw new FreebaseException(e); } catch (ParseException e) { throw new FreebaseException(e); } catch (ClassCastException e) { throw new FreebaseException(e); } return check_result(result); }
8a5dba63-75c8-47d2-9dc0-eabbfb18af73
3
public static void main(String args[]) throws NumberFormatException, IOException { int i = 0; int N = 0; BufferedReader ob = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter value for N"); N = Integer.parseInt(ob.readLine()); int arr[] = new int[N]; Scanner sc=new Scanner(System.in); System.out.println("Please enter elements..."); for (i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); } System.out.println("Input Array is :"); for (i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } Merge_Sort obj = new Merge_Sort(); obj.sort(arr); System.out.println("\n"); System.out.println("Sorted Array is :"); for (i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } }
3da84537-f0b4-4881-99f4-aabe040b48b0
6
@Override public boolean equals(Object innyObiekt) { if (innyObiekt == null) { return false; } if (innyObiekt == this) { return true; } if (!(innyObiekt instanceof Towar)) { return false; } Towar innyTowar = (Towar) innyObiekt; return (nazwa == null ? innyTowar.getNazwa() == null : nazwa.equals(innyTowar.getNazwa())) && (cena == innyTowar.getCena()) && (waga == innyTowar.getWaga()); }
9a5f6fab-499f-4578-af51-64faef9f2847
2
public void setInterfaces(String[] nameList) { cachedInterfaces = null; if (nameList != null) { int n = nameList.length; interfaces = new int[n]; for (int i = 0; i < n; ++i) interfaces[i] = constPool.addClassInfo(nameList[i]); } }
53828415-76a6-4749-9bbf-0b0114d26188
6
public static void quick(List<Element> list, int start, int end) { int i = start; int j = end; int temp; // select pivot int pivot = list.get((start + end) / 2).getValue(); do { while (list.get(i).getValue() < pivot) { temp = list.get(i).getNumberOfComparison(); list.get(i).setNumberOfComparison(++temp); temp = list.get((start + end) / 2).getNumberOfComparison(); list.get((start + end) / 2).setNumberOfComparison(++temp); i++; } while (pivot < list.get(j).getValue()) { temp = list.get(i).getNumberOfComparison(); list.get(i).setNumberOfComparison(++temp); temp = list.get((start + end) / 2).getNumberOfComparison(); list.get((start + end) / 2).setNumberOfComparison(++temp); j--; } if (i <= j) { Collections.swap(list, i, j); /* temp = list.get(i).getNumberOfInversion(); list.get(i).setNumberOfInversion(++temp); temp = list.get(j).getNumberOfInversion(); list.get(j).setNumberOfInversion(++temp); */ i++; j--; } } while (i <= j); if (start < j) { quick(list, start, j); } if (i < end) { quick(list, i, end); } }
98cc12f0-0ad6-4a54-aafd-c5ca28a1a53f
1
public ShellLink setCMDArgs(String s) { if (s == null) header.getLinkFlags().clearHasArguments(); else header.getLinkFlags().setHasArguments(); cmdArgs = s; return this; }
7be845eb-7a4b-4d2d-b4b0-07edeabdfa8d
1
private void jMenuAtividadesAtrasadasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuAtividadesAtrasadasActionPerformed if (usuarioLogado.getTipo().equals("Gerente")) { this.atividadesAtrasadas(); } else { JOptionPane.showMessageDialog(null, "Você não possui previlégios para acessar \n " + "a Tela de Atividades Trabalhadas!", " Atividades Trabalhadas", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jMenuAtividadesAtrasadasActionPerformed
975c4e91-651d-4034-bd1b-06ab9480babd
0
@Override public Node getNode() {return node;}
162b2965-0bec-4c20-abaf-56d5cd387d1f
1
private static void initRotate(Composite inComposite, int heightHint) { final Composite toolbar = new Composite(inComposite, SWT.BORDER); final Composite imageContainer = new Composite(inComposite, SWT.BORDER); GridData toolbarGridData = new GridData(GridData.FILL_HORIZONTAL); toolbarGridData.grabExcessHorizontalSpace = true; toolbar.setLayoutData(toolbarGridData); final Combo combo = new Combo(toolbar, SWT.READ_ONLY); combo.setItems(new String[] { "0", "30", "60", "90", "120", "150", "180", "210", "240", "270", "300", "330", "360" }); combo.setText("30"); toolbar.setLayout(new GridLayout(2, false)); Button button = new Button(toolbar, SWT.PUSH); button.setText("Rotate NearNeighbour"); button.setBounds(0, 0, 100, 30); button.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1)); button.addListener(SWT.MouseDown, new Listener() { public void handleEvent(Event event) { int dd = 30; try { dd = Integer.parseInt(combo.getText()); } catch (Exception e) { e.printStackTrace(); } rotate(dd); ImageUtils.paintImage(new GC(imageContainer), rotate, rotateHisto); } }); GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.grabExcessHorizontalSpace = true; gridData.heightHint = heightHint; imageContainer.setLayoutData(gridData); imageContainer.addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { ImageUtils.paintImage(event.gc, rotate, rotateHisto); } }); }
f24cc107-9e3a-48a8-8d0b-53d50d2253ea
2
public String[] getParameterValues(String parameter) { String[] values = super.getParameterValues(parameter); if (values==null) { return null; } int count = values.length; String[] encodedValues = new String[count]; for (int i = 0; i < count; i++) { encodedValues[i] = cleanXSS(values[i]); } return encodedValues; }
9cc762af-a99f-4107-84eb-b8f164e48503
8
protected String toJSONFragment() { StringBuffer json = new StringBuffer(); boolean first = true; if (isSetSubscriptionId()) { if (!first) json.append(", "); json.append(quoteJSON("SubscriptionId")); json.append(" : "); json.append(quoteJSON(getSubscriptionId())); first = false; } if (isSetRefundAmount()) { if (!first) json.append(", "); json.append("\"RefundAmount\" : {"); Amount refundAmount = getRefundAmount(); json.append(refundAmount.toJSONFragment()); json.append("}"); first = false; } if (isSetCallerReference()) { if (!first) json.append(", "); json.append(quoteJSON("CallerReference")); json.append(" : "); json.append(quoteJSON(getCallerReference())); first = false; } if (isSetCancelReason()) { if (!first) json.append(", "); json.append(quoteJSON("CancelReason")); json.append(" : "); json.append(quoteJSON(getCancelReason())); first = false; } return json.toString(); }
1c94e811-7e22-43c9-b583-eec7fc8ca7b2
0
public GraphPanel getGraphPanel() { return graphPanel; }
67d3dc92-7d5d-4735-a53b-18bfe9cd7e66
9
private Point getOrigin(Dimension size, Container target) { Point origin = new Point(); if (anchor == NORTH_WEST) { origin.x = 0; origin.y = 0; } else if (anchor == NORTH) { origin.x = ((target.getWidth() - size.width) / 2); origin.y = 0; } else if (anchor == NORTH_EAST) { origin.x = target.getWidth() - size.width; origin.y = 0; } else if (anchor == EAST) { origin.x = target.getWidth() - size.width; origin.y = ((target.getHeight() - size.height) / 2); } else if (anchor == SOUTH_EAST) { origin.x = target.getWidth() - size.width; origin.y = target.getHeight() - size.height; } else if (anchor == SOUTH) { origin.x = ((target.getWidth() - size.width) / 2); origin.y = target.getHeight() - size.height; } else if (anchor == SOUTH_WEST) { origin.x = 0; origin.y = target.getHeight() - size.height; } else if (anchor == WEST) { origin.x = 0; origin.y = (target.getHeight() - size.height) / 2; } else if (anchor == CENTER) { origin.x = ((target.getWidth() - size.width) / 2); origin.y = (target.getHeight() - size.height) / 2; } return origin; }
317d4d34-edf6-4eee-94ff-8d73fa5f06dd
1
public static CharacterStorageInventory create(){ if(storageInventory == null){ storageInventory = new CharacterStorageInventory(); } return storageInventory; }