text
stringlengths
14
410k
label
int32
0
9
public static double ln(double a) { double aminus1 = a - 1.0; boolean gt1 = (sqrt(aminus1 * aminus1) <= 1) ? false : true; final int iteration_count = 300; double lnsum = 0.0; if (gt1) { // use trick for fast convergence: // ln(123.456) = ln(1.23456*10^2) // ln(123.456) = ln(1.23456) + 2*ln(10) int j = 0; while (a / 10 > 1) { a /= 10; j++; } aminus1 = a - 1.0; double denominator = 1.0; for (int i = 1; i < iteration_count; i++) { denominator *= a / aminus1; lnsum += (1.0 / (denominator * ((double) i))); } if (j > 0) { lnsum += j * ln(10); } } else { int j = 0; while (a * 10 < 1) { a *= 10; j++; } aminus1 = a - 1.0; double numerator = 1.0; for (int i = 1; i < iteration_count; i++) { double sign = (i % 2 == 0) ? -1.0 : 1.0; numerator *= aminus1; lnsum += sign * (numerator / ((double) i)); } if (j > 0) { lnsum += -1.0 * j * ln(10); } } return lnsum; }
9
@Override public boolean equals(Object other) { if (other == null) return false; if (other == this) return true; if (this.row == null) return false; Place otherPlace = (Place) other; return this.number == otherPlace.getNumber() && this.row.equals(otherPlace.getRow()); }
4
private TreeElement handleClass(HashMap classes, ClassInfo clazz) { if (clazz == null) return root; TreeElement elem = (TreeElement) classes.get(clazz); if (elem != null) return elem; elem = new TreeElement(clazz.getName()); classes.put(clazz, elem); if (!clazz.isInterface()) { ClassInfo superClazz = clazz.getSuperclass(); handleClass(classes, superClazz).addChild(elem); } ClassInfo[] ifaces = clazz.getInterfaces(); for (int i = 0; i < ifaces.length; i++) handleClass(classes, ifaces[i]).addChild(elem); if (ifaces.length == 0 && clazz.isInterface()) root.addChild(elem); return elem; }
6
@Override public int registerPacketHandler(IPacketHandler iph) { log.finer("Registering a PacketHandler"); synchronized(PHList) { if(!PHList.contains(iph)) { PHList.add(iph); } return PHList.indexOf(iph); } }
1
JSONArray toJSONArray(final Message.EncodeMode encodeMode) throws JSONException { JSONArray jsonArray = null; if (values != null) { jsonArray = new JSONArray(); for (int i = 0; i < values.size(); i++) { Parameter param = values.get(i); if (encodeMode == Message.EncodeMode.VERBOSE) { String paramName = param.getName(); if (paramName == null || paramName.length() == 0) { paramName = "" + i; } if (param instanceof SingleParameter) { JSONObject jsonObject = new JSONObject(); jsonObject.put(paramName, param.getValue()); jsonArray.put(jsonObject); } else if (param instanceof ArrayParameter) { ArrayParameter arrayParam = (ArrayParameter) param; JSONObject jsonObject = new JSONObject(); jsonObject.put(paramName, arrayParam.toJSONArray(encodeMode)); jsonArray.put(jsonObject); } } else { if (param instanceof SingleParameter) { jsonArray.put(param.getValue()); } else if (param instanceof ArrayParameter) { ArrayParameter arrayParam = (ArrayParameter) param; jsonArray.put(arrayParam.toJSONArray(encodeMode)); } } } } return jsonArray; }
9
public String toString() { StringBuffer sb = new StringBuffer("<class>" + getClass().getName() + "</class>\n"); if (uid != null) sb.append("<uid>" + uid + "</uid>\n"); if (!layout.equals(BorderLayout.NORTH)) sb.append("<layout>" + layout + "</layout>\n"); sb.append("<single>" + getSingleSelection() + "</single>\n"); sb.append("<row>" + getChoiceCount() + "</row>\n"); sb.append("<width>" + getWidth() + "</width>\n"); sb.append("<height>" + getHeight() + "</height>\n"); sb.append("<title>" + XMLCharacterEncoder.encode(questionBody.getText()) + "</title>\n"); if (hasCheckAnswerButton()) sb.append("<submit>true</submit>\n"); if (hasClearAnswerButton()) sb.append("<clear>true</clear>\n"); sb.append(choicesToString()); sb.append("<answer>" + answerToString() + "</answer>\n"); if (isOpaque()) { sb.append("<bgcolor>" + Integer.toString(getBackground().getRGB(), 16) + "</bgcolor>\n"); } else { sb.append("<opaque>false</opaque>\n"); } if (!getBorderType().equals(BorderManager.BORDER_TYPE[0])) { sb.append("<border>" + getBorderType() + "</border>\n"); } String s = scriptsToString(); if (s != null && !s.trim().equals("")) { sb.append("<script>" + XMLCharacterEncoder.encode(s) + "</script>\n"); } return sb.toString(); }
8
public static double[][] readOtherData(Kattio io){ String tmp; double[][] points=null; int N=0; //read until reached the EOF line while(!(tmp=io.readLine()).equals("EOF")){ String sarr[]=tmp.split(" "); //try to read the dimension if(points==null && sarr[0].equals("DIMENSION")){ N = Integer.parseInt(sarr[2]); points = new double[2][N]; } //try to read if(points!=null){ try{ int a=Integer.parseInt(sarr[0]); int b=Integer.parseInt(sarr[1]); int c=Integer.parseInt(sarr[2]); points[0][a-1]=b; points[1][a-1]=c; } catch(Exception e){ //ignore } } } return points; }
5
public void resolvePrefixes(LinkedList<Prefix> pre){ //Scan subject, predicate and object (data indices 0 to 2) for (int i=0; i<3; i++){ String value=getByIndex(i); //Contains ':'? (a prefix) if (value.contains(":")){ //Replace prefix for (Prefix p:pre){ if (value.startsWith(p.getPrefix())){ setByIndex(i,"<"+p.getIriContent()+value.substring(p.getPrefix().length())+">"); break; } } //Is predicate? (array position 1) }else if (i==1){ //Replace 'a' predicate if (value.equals("a")){ setPredicate("<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>"); } } } }
6
public void paint(Graphics g) { g.setColor(Color.GRAY); g.fillRect(0, 0, 1000, 1000); g.setColor(new Color(clr)); g.drawImage(texture, 0, 0, 128 * scale, 128 * scale, null); if(curTool == 3) { this.overlay = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB); this.overLayGraphics = this.overlay.getGraphics(); this.overLayGraphics.setColor(new Color(clr)); if(currentMpos != null) { this.overLayGraphics.drawLine((int)mousePress.x, (int)mousePress.y, (int)currentMpos.x, (int)currentMpos.y); } } g.drawImage(overlay, 0, 0, 128 * scale, 128 * scale, null); g.setColor(Color.RED); g.drawString("Mouse X: " + mx + " Mouse Y: " + my, 10, 360); if(scale > 4) { g.setColor(Color.GRAY); for(int i = 0; i < scale*128; i+= scale) { g.drawLine(0, i, scale*128, i); g.drawLine(i, 0, i, scale*128); } } }
4
private void runExtCommand(String[] cmd, File dir, String description, boolean print) { if (description == null) setStatusBar("Calling External Program..."); else setStatusBar(description); try { Runtime r = Runtime.getRuntime(); Process p; if (dir == null) p = r.exec(cmd); else p = r.exec(cmd, new String[0], dir); if (print) { System.out.println("Command:"); for (int i = 0; i < cmd.length; i++) System.out.print(cmd[i] + " "); System.out.println(); System.out.println(); BufferedReader reader = new BufferedReader( new InputStreamReader(new DataInputStream( new BufferedInputStream(p.getInputStream())))); String lineRead = null; while ((lineRead = reader.readLine()) != null) { System.out.println(lineRead); } } resetStatusBar(); } catch (IOException e) { e.printStackTrace(); } }
6
public boolean canEncode(Serializable structure) { return false; }
0
private RenderableObject generateRectangle(Scanner inFile) { Point s = null, e = null, loc = null; int thickness = 0; Color c = null; String current = inFile.next(); while (inFile.hasNext() && !(isCloseTag(current) && parseTag(current) == LegalTag.Object)) { if (isOpenTag(current)) { switch (parseTag(current)) { case Start: s = new Point(inFile.nextInt(), inFile.nextInt()); break; case End: e = new Point(inFile.nextInt(), inFile.nextInt()); break; case Color: c = new Color(inFile.nextInt(), inFile.nextInt(), inFile.nextInt()); break; case Location: loc = new Point(inFile.nextInt(), inFile.nextInt()); break; case Thickness: thickness = inFile.nextInt(); break; default: break; } } current = inFile.next(); } Rectangle rect = new Rectangle(s, e, thickness, c); rect.setLocation(loc); return rect; }
9
public void paintComponent(Graphics g) { super.paintComponent(g); //Paint grey background g.setColor(Color.LIGHT_GRAY); g.fillRect(0, 0, this.getWidth(), this.getHeight()); g.setColor(Color.BLACK); g.fillRect(myModel.TRASHCAN.y * 40, myModel.TRASHCAN.x*40, squareW, squareH); //Paint rubble for(int i = 0; i < myModel.myCellList.size(); i++){ g.setColor(Color.RED); Cell c = myModel.myCellList.get(i); Point p = c.loc; g.fillRect(p.y * 40, p.x*40, squareW, squareH); g.setColor(Color.BLACK); g.drawString(Integer.toString(c.weight),p.y*40,p.x*40 + 20); } //Color drones for(int i = 0; i < myModel.droneList.size(); i++){ g.setColor(Color.GREEN); Drone d = myModel.droneList.get(i); Point p = d.loc; g.fillRect(p.y * 40, p.x*40, squareW, squareH); g.setColor(Color.BLACK); g.drawString("Drone",p.y*40,p.x*40 + 20); } for(int i = 0; i < myModel.currentCell.size(); i++){ g.setColor(Color.GREEN); Drone d = myModel.currentCell.get(i); Point p = d.loc; g.fillRect(p.y * 40, p.x*40, squareW, squareH); g.setColor(Color.BLACK); g.drawString("Drone",p.y*40,p.x*40 + 20); } //Paint grid lines g.setColor(Color.BLACK); for(int i = 0; i < this.getWidth(); i+=40){ g.drawLine(i, 0, i, this.getHeight()); } for(int j = 0; j < this.getHeight() + 10; j+=40){ g.drawLine(0, j, this.getWidth(), j); } }
5
public void act(ArrayList<Plant> plist, ArrayList<Bacteria> baclist){ incrementAge(); if(isDying() || isDead()){ return; } //We give a small positive movement bonus to herbivores, and negative to carnivores double boost = gen.getAggression() * (-0.15); if ((0.5*(1-getHunger())) + 0.5 + boost < rand.nextDouble()) { return; } Vector movement = new Vector(0, 0); for(Bacteria b : baclist){ // If we're next to a dying bacteria, eat it! if (this.distance(b).getLength() < 5 && this.getEnergy() < (int)(Constants.maxEnergy * 0.9)) { eatBacteria(b); } // TODO: Implementera PvP h�r! //We add the sum of all movements to the movement vector movement.add(see(this.distance(b), b)); } for(Plant pl : plist){ // If we're next to a plant and it's alive. Eat it! if (this.distance(pl).getLength() < 5 && this.getEnergy() < (int)(Constants.maxEnergy * 0.9)) { eatPlants(pl); } //We add the sum of all movements to the movement vector movement.add(see(this.distance(pl), pl)); } //Normalize the movement vector to get properly scaled end results movement.normalize(); move(movement, baclist); }
9
public T get(int id) { if (id < 0) { return null; } T definition = cache.get(id); if (definition == null) { synchronized (lock) { definition = cache.get(id); if (definition == null) { try { definition = loader.load(id); cache.put(id, definition); } catch (Exception ignored) { } } } } return definition; }
4
public static void main(String[] args) { String[] patterns; if(args.length < 2) { patterns = PATTERNS; } else { patterns = args; } String argString = patterns[0]; System.out.println("Input: " + argString); for(int i = 1; i < patterns.length; ++i) { System.out.println("RegExp: " + patterns[i]); Pattern pattern = Pattern.compile(patterns[i]); Matcher matcher = pattern.matcher(argString); while(matcher.find()) { System.out.println("Match \"" + matcher.group() + "\" at positions " + matcher.start() + (matcher.end() - matcher.start() < 2 ? "" : "-" + (matcher.end() - 1))); } } }
4
public List<BoundingBox> getEntityBoundingBoxesInRange(double x, double y, double radius) { ArrayList<BoundingBox> list = new ArrayList<BoundingBox>(); for(Entity entity : entities) { if(entity != null && !entity.isDead && entity.getDistance(x, y) <= radius) { list.add(entity.boundingBox); } } return list; }
4
public static void exit(final int iIn) { if (! Ezim.running) return; Ezim.running = false; EzimNetwork.thAckTaker.interrupt(); EzimAckTaker.getInstance().closeSocket(); EzimNetwork.thDtxTaker.interrupt(); EzimDtxTaker.getInstance().closeSocket(); EzimThreadPool etpTmp = EzimThreadPool.getInstance(); // acknowledge other peers we're going offline EzimAckSender easOff = new EzimAckSender ( EzimAckSemantics.offline() ); etpTmp.execute(easOff); etpTmp.shutdown(); try { etpTmp.awaitTermination(EzimNetwork.exitTimeout, TimeUnit.SECONDS); } catch(InterruptedException ie) { EzimLogger.getInstance().warning(ie.getMessage(), ie); } if (! Ezim.shutdown) System.exit(iIn); }
3
public void checkFields (LYNXsys system) { // check textfields before adding student to system boolean existingStudentFlag = false; // temp var to flag if student info is valid if (!(getFirstName().getTextField().getText().equals("")) && // check that ALL FIELDS are filled (4) !(getLastName().getTextField().getText().equals("")) && !(getID().getTextField().getText().equals("")) && !(getPassword().getTextField().getText().equals(""))) { // end check for (int i = 0; i < system.getUsers().size(); i ++) { // loop through all users if (getID().getTextField().getText().equalsIgnoreCase(system.getUsers().get(i).getID())){ // check if user is already in system or not existingStudentFlag = true; // if so, set true ... addStudent method will not be called } } } if (!existingStudentFlag) { // if flag is never flipped true, this code will run system.addStudent(new User (getFirstName().getTextField().getText(), getLastName().getTextField().getText(), getID().getTextField().getText(),getPassword().getTextField().getText())); } }
7
public void addYesterday(FacWarStat stat) { if (stat instanceof CharacterKills) { characterKillsYesterday.add((CharacterKills) stat); } else if (stat instanceof CharacterVictoryPoints) { characterVictoryPointsYesterday.add((CharacterVictoryPoints) stat); } else if (stat instanceof CorporationKills) { corporationKillsYesterday.add((CorporationKills) stat); } else if (stat instanceof CorporationVictoryPoints) { corporationVictoryPointsYesterday.add((CorporationVictoryPoints) stat); } else if (stat instanceof FactionKills) { factionKillsYesterday.add((FactionKills) stat); } else if (stat instanceof FactionVictoryPoints) { factionVictoryPointsYesterday.add((FactionVictoryPoints) stat); } }
6
public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { new Main(); } catch (Exception e) { e.printStackTrace(); } } }); }
1
@Override public int compareTo(MediaElement o) { final int compareTo = this.name.compareTo(o.getName()); if (this != o && compareTo == 0) return this.name.compareTo(o.getName()); else return compareTo; }
2
@Override public void run() { List<Action> actions; long startTime = System.currentTimeMillis(), estimatedTime, timeToWait = 100; while (true && !sim.isEnded()) { actions = sim.prepareUpdate(); estimatedTime = System.currentTimeMillis() - startTime; System.out.println("### time = " + estimatedTime + " ms"); try { timeToWait = 100 - estimatedTime; Thread.sleep(timeToWait < 0 ? 0 : timeToWait); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } startTime = System.currentTimeMillis(); synchronized (sim) { sim.applyUpdate(actions); simPanel.repaint(); } while (sim.isPaused()) { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
6
private void handleCommitOnly(Sim_event ev) { int src = -1; // the sender id boolean success = false; int tag = -1; try { // id[0] = resID, [1] = reservID, [2] = trans ID, [3] = sender ID int[] obj = ( int[] ) ev.get_data(); // get the data inside the array int returnTag = GridSimTags.RETURN_AR_COMMIT; tag = returnTag + obj[2]; src = obj[3]; // check whether this resource can support AR or not success = checkResourceType(src, returnTag, obj[2], GridSimTags.AR_COMMIT_ERROR_RESOURCE_CANT_SUPPORT, "can't commit a reservation"); // if this resource is not supported AR, then exit if (!success) { return; } else { ( (ARPolicy) policy_).handleCommitOnly(obj[1], src, tag); } } catch (ClassCastException c) { success = false; } catch (Exception e) { success = false; } // if there is an exception, then send back an error msg if (!success && tag != -1) { System.out.println(super.get_name() + " : Error - can't commit a "+ "reservation."); super.send(src, 0.0, GridSimTags.RETURN_AR_COMMIT, new IO_data(new Integer(GridSimTags.AR_COMMIT_ERROR),SIZE,src)); } }
5
public boolean isHorizontalCollision(Bounds r1, Bounds r2) { double tamX = r2.getRight() - r1.getLeft(); double tamY = r2.getBottom() - r1.getTop(); if(r1.getLeft() <= r2.getLeft() && r2.getLeft() < r1.getRight()) { tamX = r1.getRight() - r2.getLeft(); } if(r1.getTop() <= r2.getTop() && r2.getTop() < r1.getBottom()) { tamY = r1.getBottom() - r2.getTop(); } return tamY < tamX; }
4
protected void move() { //show/hide nodes if (visibleNodesCount != mainPanel.symbolsCount.intValue()) { visibleNodesCount = mainPanel.symbolsCount.intValue(); for (int i = 0; i < symbols.size(); i++) symbols.get(i).node.setVisible(i < visibleNodesCount); } //animate symbols for (int i = 0; i < mainPanel.symbolsCount.intValue(); i++) { NodeSymbol symbol = symbols.get(i); symbol.x += symbol.dirX * 5; symbol.y += symbol.dirY * 5; if (symbol.x < 0) symbol.dirX = Math.abs(symbol.dirX); if (symbol.y < 0) symbol.dirY = Math.abs(symbol.dirY); if (symbol.x > getWidth()) symbol.dirX = -1 * Math.abs(symbol.dirX); if (symbol.y > getHeight()) symbol.dirY = -1 * Math.abs(symbol.dirY); symbol.node.setLayoutX(symbol.x); symbol.node.setLayoutY(symbol.y); } //measure FPS frameCount++; long currentTime = System.nanoTime(); if (currentTime > lastSecondStart + 1000000000) { int fps = frameCount; frameCount = 0; lastSecondStart = currentTime; mainPanel.onFPSChange(fps); } }
8
public DecisionQuestView() { super(); this.add(new JLabel("Decision")); // quest = QuestFactory.createQuest(QuestType.DECISIONQUEST); addAnswersTable(); }
0
public int getFileCount() { try { return (int) (indexChannel.size() / IDX_BLOCK_LEN); } catch (IOException ex) { return 0; } }
1
public void setAccessPathLength(int accessPathLength) { this.accessPathLength = accessPathLength; }
0
private static String errorToString(int id) { String errorMessage=""; switch(id) { case HABITRPG_SERVER_API_CALL_NOT_FOUND: case INTERNAL_WRONG_URL: errorMessage="The server wasn't found. Please check your hosts settings."; break; case SERV_EXPERIENCING_ISSUES: errorMessage="HabitRPG's server is having some trouble. Feel free to switch to the beta server"; break; case INTERNAL_NO_CONNECTION: errorMessage="Error. Please check your connection"; break; case INTERNAL_OTHER: errorMessage="An internal unknown error happend!"; break; case HABITRPG_REGISTRATION_ERROR: errorMessage="There has been an error during the registration process! Please try again."; default: errorMessage="An unknown error happened!"; break; } return errorMessage; }
6
public static void setAlgorithm(Algorithm a) { AlgorithmInterface.algorithm = a; }
0
protected boolean parseFile(LineHandler handler, InputStream stream) throws Exception { BufferedReader bis = new BufferedReader(new InputStreamReader(stream)); int lineNum = 0; for (String line = bis.readLine(); line != null; line = bis.readLine()) { lineNum++; if (line.equals("")) { continue; } List fields = new ArrayList(); StringBuffer currentField = new StringBuffer(); boolean inQuotes = false; for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (c == '"') { inQuotes = !inQuotes; } else if (c == ',' && !inQuotes) { fields.add(currentField.toString()); currentField.setLength(0); } else { currentField.append(c); } } fields.add(currentField.toString()); String [] array = new String[fields.size()]; fields.toArray(array); if (!handler.handleLine(lineNum, array)) { return false; } } return true; }
7
public Builder socialRepository(Repository respository) { // If we didn't get a repository, do nothing. if (respository == null) { return this; } if (message.socialRepositoryList == null) { message.socialRepositoryList = new ArrayList<Repository>(); } message.socialRepositoryList.add(respository); return this; }
2
public boolean isSyncCurrentPosition(int syncmode) throws BitstreamException { int read = readBytes(syncbuf, 0, 4); int headerstring = ((syncbuf[0] << 24) & 0xFF000000) | ((syncbuf[1] << 16) & 0x00FF0000) | ((syncbuf[2] << 8) & 0x0000FF00) | ((syncbuf[3] << 0) & 0x000000FF); try { source.unread(syncbuf, 0, read); } catch (IOException ex) { } boolean sync = false; switch (read) { case 0: sync = true; break; case 4: sync = isSyncMark(headerstring, syncmode, syncword); break; } return sync; }
3
private void addDataToTable(TableDescription tableDescription, DataContainer allData) { Map<String, Row> map = allData.getRowsByDescription(tableDescription); String tableName = tableDescription.getName(); for (String key : map.keySet()) { Row row = map.get(key); try { balancer.add(tableName, row.getRow()); } catch (DBUnavailabilityException e) { log(loggers, "problem while loading data to database: database unavailable", row.getRow()); } catch (DataBaseRequestException e) { log(loggers, "problem while loading data to database: wrong request", row.getRow()); } catch (DataBaseTableException e) { log(loggers, "problem while loading data to database: table corruption", row.getRow()); } } }
4
public synchronized void removeVM(SlaveVM vm) throws UnreachableVMException { System.out.println("DEBUG: VM " + vm.getId() + " is deleted"); if (vmsInUse.contains(vm)) vmsInUse.remove(vm); if (vmsAvailable.contains(vm)) vmsAvailable.remove(vm); vm.hardExit(); }
2
@Override public String execute(String[] args){ System.exit(0); return null; }
0
public Emitter on(String event, Listener fn) { ConcurrentLinkedQueue<Listener> callbacks = this.callbacks.get(event); if (callbacks == null) { callbacks = new ConcurrentLinkedQueue <Listener>(); ConcurrentLinkedQueue<Listener> _callbacks = this.callbacks.putIfAbsent(event, callbacks); if (_callbacks != null) { callbacks = _callbacks; } } callbacks.add(fn); return this; }
2
public List<Location> adjacentLocations(Location location) { assert location != null : "Null location passed to adjacentLocations"; // The list of locations to be returned. List<Location> locations = new LinkedList<Location>(); if(location != null) { int row = location.getRow(); int col = location.getCol(); for(int roffset = -1; roffset <= 1; roffset++) { int nextRow = row + roffset; if(nextRow >= 0 && nextRow < depth) { for(int coffset = -1; coffset <= 1; coffset++) { int nextCol = col + coffset; // Exclude invalid locations and the original location. if(nextCol >= 0 && nextCol < width && (roffset != 0 || coffset != 0)) { locations.add(new Location(nextRow, nextCol)); } } } } // Shuffle the list. Several other methods rely on the list // being in a random order. Collections.shuffle(locations, rand); } return locations; }
9
private String getNextString() { while ( pos < content.length() && content.charAt(pos) == ' ') pos++; if (pos >= content.length()) return new String(""); if (content.charAt(pos) == '<') { int endPos = content.indexOf('>', pos); String retStr = content.substring(pos, endPos+1); pos = endPos + 1; return retStr; } else { int endPos = content.indexOf('<', pos); String retStr = content.substring(pos, endPos); pos = endPos; return retStr; } }
4
public static Stream allocate() { // create synchronized (Stream.queue) { Stream stream = null; if (Stream.pointer > 0) { Stream.pointer--; stream = (Stream) Stream.queue.popFront(); } if (stream != null) { stream.offset = 0; return stream; } } Stream stream = new Stream(); stream.offset = 0; stream.payload = new byte[5000]; return stream; }
2
public void print(){ for(int i =0 ; i < 9; i++){ for(int j = 0 ; j< 9; j++){ System.out.print ( etat[i][j]+" " ); } System.out.println(); } }
2
@Override public void setBoolean(long i, boolean value) { if (ptr != 0) { Utilities.UNSAFE.putShort(ptr + sizeof * i, value == true ? (short) 1 : (short) 0); } else { if (isConstant()) { throw new IllegalAccessError("Constant arrays cannot be modified."); } data[(int) i] = value == true ? (short) 1 : (short) 0; } }
4
public static void enginePulse(){ if(Game.currentGame == null) return; if(ObjectAction.difficulty == null){ Miscellaneous.log("[FATAL] Cycle rate not set, game ending."); Engine.destructGame(); } for(Entity entity : Entity.entityList){ entity.update(); } Game.getSingleton().update(); }
3
public Output() { instance = this; // Check for HTML-Output if (Config.getHtmlPath() != null) { checkValidHtmlPath(); } }
1
@Override public void execute(VGDLSprite sprite1, VGDLSprite sprite2, Game game) { if(sprite1.is_resource) { Resource r = (Resource) sprite1; applyScore=false; int numResources = sprite2.getAmountResource(r.resource_type); if(numResources + r.value <= game.getResourceLimit(r.resource_type)) { applyScore=true; sprite2.modifyResource(r.resource_type, r.value); if(killResource) //boolean variable set to false to indicate the sprite was not transformed game.killSprite(sprite1, true); } } }
3
public static List<String> tokenize(String source) { List<String> tokens = new ArrayList<String>(); String token = ""; for (char c : source.toCharArray()) if (isSpace(c)) { if (!token.isEmpty()) { tokens.add(token); token = ""; } } else token += c; if (!token.isEmpty()) tokens.add(token); return tokens; }
4
private static boolean homePageForPassenger(ObjectOutputStream toServer, ObjectInputStream fromServer, Scanner scanner) throws ParseException, IOException, ClassNotFoundException { log.debug("Start method \"homePageForPassenger\""); System.out.println("1 - find train, 2 - timetable by station, 3 - buy ticket, 0 - exit"); String scan = scanner.next().toLowerCase(); while (!"1".equals(scan) && !"2".equals(scan) && !"3".equals(scan) && !"0".equals(scan)) { System.out.println("Input 0, 1, 2 or 3"); scan = scanner.next().toLowerCase(); } switch (scan.charAt(0)) { case '1': { return PassengerHomePageHelper.findTrain(toServer, fromServer, scanner); } case '2': { return PassengerHomePageHelper.timetableByStation(toServer, fromServer, scanner); } case '3': { return PassengerHomePageHelper.buyTicket(toServer, fromServer, scanner); } case '0': { return false; } default: return false; } }
8
private synchronized Set<Message.RequestMessage> cancelPendingRequests() { Set<Message.RequestMessage> requests = new HashSet<Message.RequestMessage>(); if (this.requests != null) { for (Message.RequestMessage request : this.requests) { this.send(Message.CancelMessage.craft(request.getPiece(), request.getOffset(), request.getLength())); requests.add(request); } } return requests; }
2
private boolean writeSign(Sign sign, Set<Matcher> matchers) { int index = 0; boolean needComma = false; String[] lines = {"", "", ""}; for (Matcher matcher : new HashSet<>(matchers)) { String tmp = needComma ? "," : ""; tmp += matcher.toString(); if (lines[index].length() + tmp.length() >= 16) { index++; tmp = matcher.toString(); } else { needComma = true; } if (index > 2) { return false; } lines[index] = lines[index].concat(tmp); } sign.setLine(1, lines[0]); sign.setLine(2, lines[1]); sign.setLine(3, lines[2]); sign.update(); clearNearCache(sign.getBlock()); return true; }
4
private int secuenciaDeNodosContiguos(){ int rta=-1; if(secuencia.size()>1){ for(int i =1; i<secuencia.size();i++){ if(secuencia.get(i).getPosX()!=secuencia.get(i-1).getPosX() ||secuencia.get(i).getPosY()!=secuencia.get(i-1).getPosY() ){ rta=i; i=secuencia.size(); } } } return rta; }
4
private List<RegexNode> generateNodes(Map<Integer, List<Symbol>> table) { List<RegexNode> singles = new ArrayList<>(); List<RegexNode> parens = new ArrayList<>(); for (Entry<Integer, List<Symbol>> entry : table.entrySet()) { List<Symbol> symbols = entry.getValue(); //endeavoring to match nodes that have open and close parens int open = -1; for (int i = 0; i < symbols.size(); ++i) { Symbol current = symbols.get(i); switch (current.getSymbol()) { case '(': open = i; break; case ')': Symbol nextSymbol = peekAtNextSymbol(symbols, i); if (nextSymbol != null && nextSymbol.getSymbol() == '*') { ++i; parens.add(new StarNode(symbols.get(open), current, nextSymbol, entry.getKey())); } else parens.add(new ParenNode(symbols.get(open), current, entry.getKey())); break; case '*': //should have already been handled break; case '|': singles.add(new OrNode(current, entry.getKey())); break; default: singles.add(new SimpleNode(current, entry.getKey())); break; } } } //for ordering purposes parens.addAll(singles); return parens; }
8
public JSONObject accumulate(String key, Object value) throws JSONException { testValidity(value); Object o = opt(key); if (o == null) { put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); } else if (o instanceof JSONArray) { ((JSONArray)o).put(value); } else { put(key, new JSONArray().put(o).put(value)); } return this; }
3
public ConsoleEvaluationHandler(PrintStream output, Reader console) { if (output == null) { throw new IllegalArgumentException("The given output stream must not be null."); } if (console == null) { throw new IllegalArgumentException("The given console must not be null."); } this.output = output; this.console = console; }
2
String anonymizeString(String input,String nameToBeAnonymized) { //extract name terms String nameTerms[] = nameToBeAnonymized.split(" "); String textTerms[] = input.split(" "); String output = null; //go through input, replace name term sequences with substitute boolean lastTermWasName = false; for(int i = 0; i < textTerms.length;i++) { boolean foundName = false; for(int j = 0; j < nameTerms.length;j++) { String processedTextTerm = textTerms[i].toLowerCase().replaceAll("[,.:;]+", ""); //System.out.println(processedTextTerm); if(processedTextTerm.compareTo(nameTerms[j].toLowerCase()) == 0) { foundName = true; } } if((foundName == true) && (anonymize == true)) { if(lastTermWasName == false) { if(output == null) { output = anonymousSubstituteName; } else { output = output + " " + anonymousSubstituteName; } } lastTermWasName = true; } else { if(output == null) { output = textTerms[i]; } else { output = output + " " + textTerms[i]; } lastTermWasName = false; } } return output; }
8
public int getNumValue(boolean isABig) { switch (_value) { case "A": if (isABig) { return 14; } else { return 1; } case "J": return 11; case "Q": return 12; case "K": return 13; default: return Integer.parseInt(_value); } }
5
@Test public void testGetNeighbourhoodBest1Maximum(){ boolean result = true; double testFitness = 19; classUnderTest.setMaximum(true); classUnderTest.setWheel(19); for(int i = 0; i < 20; i++){ if(testSolutions.get(classUnderTest.neighbourhoodBest(i)) < testFitness){ result = false; } } assertTrue(result); }
2
@Override public List findRecords(String sqlString, boolean closeConnection) throws SQLException, Exception { Statement stmt = null; ResultSet rs = null; ResultSetMetaData metaData = null; final List list = new ArrayList(); Map record = null; // do this in an excpetion handler so that we can depend on the // finally clause to close the connection try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlString); metaData = rs.getMetaData(); final int fields = metaData.getColumnCount(); while (rs.next()) { record = new HashMap(); for (int i = 1; i <= fields; i++) { try { record.put(metaData.getColumnName(i), rs.getObject(i)); } catch (NullPointerException npe) { // no need to do anything... if it fails, just ignore it and continue } } // end for list.add(record); } // end while } catch (SQLException sqle) { throw sqle; } catch (Exception e) { throw e; } finally { try { stmt.close(); if (closeConnection) { conn.close(); } } catch (SQLException e) { throw e; } // end try } // end finally return list; // will be null if none found }
7
private void swim(int k){ while(k > 1 && less(k/2, k)){ exch(k/2, k); k = k/2; } }
2
public static Record getAchievementRecordByXMLElem(XMLElement root) { User user = null; Achievement achievement = null; for (int i = 0; i < root.childList.size(); i++) { XMLElement elem = root.childList.get(i); if (elem.name.equals("user")) { user = User.getUserByUsername(elem.content); } else if (elem.name.equals("achievement")) { achievement = Achievement.getAchievementByName(elem.content); } else { System.out.println("Unrecognized achievement record field " + elem.name); } } if (user == null) { System.out.println("User in achievement record not found"); return null; } if (achievement == null) { System.out.println("Quiz in achievement record not found"); return null; } return new AchievementRecord(user, achievement); }
5
public static long getElapsed(int tickID) { if (TickCount - tickID >= Ticks.length) { } long time = Ticks[(tickID % Ticks.length)]; return System.currentTimeMillis() - time; }
1
private void actionMix( ) { DefaultMutableTreeNode selNd = getSelectedNode(); if ( selNd != null ) { int[] selIdxs = getNodeIndexList(selNd); if ( selIdxs.length == 1 ) { LinkedList<double[]> audioList = audioVectors.get(selIdxs[0]); int m = audioList.size(); if ( m > 0 ) { NumberDialog numberDl = new NumberDialog(this, "Number of output signals...", 1, 1, 32); if ( numberDl.open() ) { int n = numberDl.getNumber(); MatrixDialog matrixDl = new MatrixDialog(this, "Choose the mixing matrix...", Matrix.newMatrix(m, n, 0.0)); if ( matrixDl.open() ) { // compute the new signals double[][] mixingMatrix = Matrix.transpose(matrixDl.getMatrix()); double[][] audioMatrix = AudioVector.toMatrix(audioList.toArray(new double[1][])); double[][] resAudioMatrix = Matrix.mult(mixingMatrix, audioMatrix); saveAudioVectors(resAudioMatrix, "Mixed Collection"); } } } } } }
5
public static void createGraphs(LinkedList<Game> games) { HashMap<String, XYSeriesCollection> datasets = new HashMap<>(); for (Game game : games) { for (String key : game.getVarData().keySet()) { if (datasets.containsKey(key)) { try { datasets.get(key).addSeries(createSeries(game.getVar(key), "" + game.getId())); } catch (Exception e) { } } else { datasets.put(key, new XYSeriesCollection()); datasets.get(key).addSeries(createSeries(game.getVar(key), "" + game.getId())); } } } for (String key : datasets.keySet()) { JFrame f = new JFrame(); JFreeChart chart = ChartFactory.createXYLineChart( key, // chart title "X", // x axis label "Y", // y axis label datasets.get(key), // data PlotOrientation.VERTICAL, false, // include legend true, // tooltips false // urls ); XYPlot plot = chart.getXYPlot(); XYItemRenderer rend = plot.getRenderer(); for (int i = 0; i < games.size(); i++) { Game g = games.get(i); if (g.getWinner() == 1) { rend.setSeriesPaint(i, Color.RED); } if (g.getWinner() == 2) { rend.setSeriesPaint(i, Color.BLACK); } if (g.getWinner() == 0) { rend.setSeriesPaint(i, Color.PINK); } } ChartPanel chartPanel = new ChartPanel(chart); f.setContentPane(chartPanel); f.pack(); RefineryUtilities.centerFrameOnScreen(f); f.setVisible(true); } }
9
public void heal() { List<Player> rangeList = getPlayersInRegion(); for (Player p : rangeList) { if (p.getHealth() != 20) { if (!p.isDead()) { p.setHealth(p.getHealth() + 1); } } } }
3
public Set propagateUsage() { used = new SimpleSet(); Set allUse = new SimpleSet(); Set childUse0 = subBlocks[0].propagateUsage(); Set childUse1 = subBlocks[1].propagateUsage(); /* * All variables used somewhere inside both sub blocks, are used in this * block, too. Also the variables used in first block are used in this * block, except when it can be declared locally. (Note that * subBlocks[0].used != childUse0) */ used.addAll(subBlocks[0].used); if (subBlocks[0] instanceof LoopBlock) ((LoopBlock) subBlocks[0]).removeLocallyDeclareable(used); allUse.addAll(childUse0); allUse.addAll(childUse1); childUse0.retainAll(childUse1); used.addAll(childUse0); return allUse; }
1
public MetropolisTableModel() { // construct column names colNames = new ArrayList<String>( Arrays.asList("Metropolis", "Continent", "Population")); // connection to database try { // make sure JDBC driver is loaded Class.forName("com.mysql.jdbc.Driver"); // create connection between our account and the database con = DriverManager.getConnection ("jdbc:mysql://" + server, account, password); Statement stmt = con.createStatement(); stmt.executeQuery("USE " + database); rs = stmt.executeQuery("SELECT * FROM metropolises WHERE 1=2;"); } catch (SQLException e){ e.printStackTrace(); } catch (ClassNotFoundException e){ e.printStackTrace(); } }
2
public boolean isSyncMark(int headerstring, int syncmode, int word) { boolean sync = false; if (syncmode == INITIAL_SYNC) { //sync = ((headerstring & 0xFFF00000) == 0xFFF00000); sync = ((headerstring & 0xFFE00000) == 0xFFE00000); // SZD: MPEG 2.5 } else { sync = ((headerstring & 0xFFF80C00) == word) && (((headerstring & 0x000000C0) == 0x000000C0) == single_ch_mode); } // filter out invalid sample rate if (sync) sync = (((headerstring >>> 10) & 3)!=3); // filter out invalid layer if (sync) sync = (((headerstring >>> 17) & 3)!=0); // filter out invalid version if (sync) sync = (((headerstring >>> 19) & 3)!=1); return sync; }
5
public RdpPacket_Localised receive() throws RdesktopException, IOException, CryptoException, OrderException { int sec_flags = 0; RdpPacket_Localised buffer = null; while (true) { int[] channel = new int[1]; buffer = McsLayer.receive(channel); if (buffer == null) return null; buffer.setHeader(RdpPacket.SECURE_HEADER); if (Constants.encryption || (!this.licenceIssued)) { sec_flags = buffer.getLittleEndian32(); if ((sec_flags & SEC_LICENCE_NEG) != 0) { licence.process(buffer); continue; } if ((sec_flags & SEC_ENCRYPT) != 0) { buffer.incrementPosition(8); // signature byte[] data = new byte[buffer.size() - buffer.getPosition()]; buffer.copyToByteArray(data, 0, buffer.getPosition(), data.length); byte[] packet = this.decrypt(data); buffer.copyFromByteArray(packet, 0, buffer.getPosition(), packet.length); // buffer.setStart(buffer.getPosition()); // return buffer; } } if (channel[0] != MCS.MCS_GLOBAL_CHANNEL) { channels.channel_process(buffer, channel[0]); continue; } buffer.setStart(buffer.getPosition()); return buffer; } }
7
public Point2DInt[] getCornersOfOneSide(LineSegmentInt seg, int sgn) { final Point2DInt[] corners = getCorners(); final double sgn0 = seg.side(corners[0]); final double sgn1 = seg.side(corners[1]); final double sgn2 = seg.side(corners[2]); final double sgn3 = seg.side(corners[3]); int nb = 0; if (Math.signum(sgn0) == sgn) { nb++; } if (Math.signum(sgn1) == sgn) { nb++; } if (Math.signum(sgn2) == sgn) { nb++; } if (Math.signum(sgn3) == sgn) { nb++; } final Point2DInt[] result = new Point2DInt[nb]; int i = 0; if (Math.signum(sgn0) == sgn) { result[i++] = corners[0]; } if (Math.signum(sgn1) == sgn) { result[i++] = corners[1]; } if (Math.signum(sgn2) == sgn) { result[i++] = corners[2]; } if (Math.signum(sgn3) == sgn) { result[i++] = corners[3]; } assert nb == i; return result; }
8
public boolean getScrollableTracksViewportHeight() { if (adapt) return true; return getPreferredSize().height < getParent().getSize().height; }
1
public void cellAltDraw(int x, int y){ if(!sedna.getSelected() ||sedna.getSelection(x,y)){ if(cellfillflag){ switch(cft){ case 0: populate(x,y,2); break; case 1: break; case 2: break; default: populate(x,y,2); break;} } else{ switch(cdt){ case 0: populate(x,y,2);break; case 1: break; case 2: break; default: populate(x,y,2); break;} } }}
9
@Basic @Column(name = "LOG_CANTIDAD") public int getCantidad() { return cantidad; }
0
public static String traducirMensaje(int id){ if(id == 0) return "Mensaje de login"; if(id == 1) return "Mensaje para todos"; if(id == 2) return "Mensaje privado"; if(id == 4) return "Mensaje de logout"; return "Error: Mensaje no reconocido"; }
4
public String getDesc() { return desc; }
0
@Before public void setUp() { TestHelper.signon(this); MongoHelper.setDB("fote"); MongoHelper.getCollection("users").drop(); for(User user : users) { if(!MongoHelper.save(user, "users")) TestHelper.failed("user save failed!"); } }
2
public static MapFunction getInstance(Node root) throws ParsingException { URI returnType = null; NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeName().equals("Function")) { String funcName = node.getAttributes(). getNamedItem("FunctionId").getNodeValue(); FunctionFactory factory = FunctionFactory.getGeneralInstance(); try { Function function = factory.createFunction(funcName); returnType = function.getReturnType(); break; } catch (FunctionTypeException fte) { // try to get this as an abstract function try { Function function = factory. createAbstractFunction(funcName, root); returnType = function.getReturnType(); break; } catch (Exception e) { // any exception here is an error throw new ParsingException("invalid abstract map", e); } } catch (Exception e) { // any exception that's not function type is an error throw new ParsingException("couldn't parse map body", e); } } } // see if we found the return type if (returnType == null) throw new ParsingException("couldn't find the return type"); return new MapFunction(returnType); }
6
private void costomedicamentosFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_costomedicamentosFieldKeyTyped // TODO add your handling code here: if (!Character.isDigit(evt.getKeyChar()) && evt.getKeyChar() !='.' && !Character.isISOControl(evt.getKeyChar())) { Toolkit.getDefaultToolkit().beep(); evt.consume(); } if(costomedicamentosField.getText().length() == 5) { Toolkit.getDefaultToolkit().beep(); evt.consume(); JOptionPane.showMessageDialog(this, "Costo de medicamento demadiado grande.", "ADVERTENCIA", WIDTH); } }//GEN-LAST:event_costomedicamentosFieldKeyTyped
4
public static void main(String[] args) throws InterruptedException, IOException, PropertyException, JAXBException { String path = "F:\\TargetFolder";// System.getProperty("user.dir"); boolean watchSubtree = false; //injector = GuiceInjector.getInjector(); FileOperationMask fileOperationMask = injector.getInstance(FileOperationMask.class); Watchers watchers = injector.getInstance(Watchers.class); watchers.addWatcher(path, fileOperationMask.getFileCreatedMask(),watchSubtree); System.out.println(watchers.getRegisteredWatchers().size()); while (true) { Thread.sleep(100000); } //marshal(); }
1
private MainFrame(){ frame = new JFrame(); initialize(); }
0
public Pos findGoalPos() throws Exception { ArrayList<String> sTypes = new ArrayList<>(); for(int i = 1; i < 5; i++) { for(int j = 1; j < 5; j++) { //loops over the board, trying to find a unknown square. sTypes = m_Logic.locateAllAt(j, i); if(sTypes.isEmpty()) { return new Pos(j,i); } } } for(int i = 1; i < 5; i++) { for(int j = 1; j < 5; j++) { boolean visited = false; //loops over the board again but this time to find a nonvisited //square sTypes = m_Logic.locateAllAt(j, i); for(String type : sTypes) { if(type.compareTo("visited") == 0) { visited = true; } } if(!visited) return new Pos(j,i); } } return new Pos(-1,-1); }
8
private boolean jj_3R_45() { if (jj_scan_token(RETURN)) return true; Token xsp; xsp = jj_scanpos; if (jj_3_32()) { jj_scanpos = xsp; if (jj_3_33()) return true; } if (jj_scan_token(SEMICOLON)) return true; return false; }
4
public Map placeNodes(TreeModel tree, NodeDrawer drawer) { HashMap nodeToPoint = new HashMap(); int[] width = Trees.width(tree), sofar = new int[width.length]; Arrays.fill(sofar, 0); setPoints((TreeNode) tree.getRoot(), width.length - 1, 0, width, sofar, nodeToPoint); return nodeToPoint; }
0
public void parseFile( OperationList oplist ) throws Exception{ FileReader in_file = new FileReader( data_file ); BufferedReader file_buff = new BufferedReader( in_file ); String[] split_1, split_2, operands; String op_portion, comment_portion = ""; String line, operation; int issue = 0; boolean comment_exists; while( ( line = file_buff.readLine() ) != null){ //trim line line = line.trim(); //only process non-empty lines if( line != null && !line.equals("") ){ //increment the issue_number issue++; //Check for comment if( line.indexOf( ";" ) >= 0 ){ split_1 = line.split(";"); comment_portion = split_1[1].trim(); comment_exists = true; } else{ split_1 = new String[1]; split_1[0] = line; comment_exists = false; op_portion = line; } //Split/Prse the operation & operands split_2 = (split_1[0].trim()).split("\\s+"); operation = split_2[0].trim(); operands = new String[ (split_2.length - 1) ]; for( int i = 1; i < split_2.length; i++){ //temporary index int temp_index = split_2[i].indexOf(","); //check for a comma temp_index = (temp_index ==-1 ? split_2[i].length(): temp_index); operands[ i-1 ] = split_2[i].substring( 0, temp_index ); } if( operands.length == 3 ){ oplist.addOperation( new Operation( operation, operands[0], operands[1], operands[2], comment_exists ) ); } else if( operands.length == 2 ){ oplist.addOperation( new Operation( operation, operands[0], operands[1], comment_exists ) ); } else{ throw new Exception(){ public String toString(){ return "File Parse Error: Malformed Operation"; } }; } if( comment_exists ){ oplist.getLastOperation().setComment( comment_portion ); } oplist.getLastOperation().setIssueNum( issue ); } } }
9
public RoomState state(int row, int col){ return grid[row][col]; }
0
@Override public boolean equals(Object obj) { if (obj instanceof Location) { Location other = (Location) obj; return this.x == other.x && this.y == other.y; } return false; }
2
private void getNextPosition() { // movement if (left) { dy -= moveSpeed; if (dy < -maxSpeed) { dy = -maxSpeed; } } else if (right) { dy += moveSpeed; if (dy > maxSpeed) { dy = maxSpeed; } } // falling if (falling) { dy += fallSpeed; } }
5
public ArrayList<Edge> getToDo() { if (this.runDFS) { return this.dfs.toDo; } else { return this.bfs.toDo; } }
1
public LoopingByteInputStream(byte[] buffer) { super(buffer); closed = false; }
0
public VerbConjugator(){ int confirm = 1; String verb = JOptionPane.showInputDialog(null, "Please input a verb in romaji to conjugate (dictionary form)"); Verb v = null; try { v = new Verb(verb); } catch (Exception e) { JOptionPane.showMessageDialog(null, "The input value does not conform to Japanese grammar standards for verbs."); e.printStackTrace(); } if (v.ending().equals("ru") && !v.isIrregular()){ String last3 = (verb.substring(verb.length()-3, verb.length())); String guess = last3.equals("iru") || last3.equals("eru") ? "I think it is" : "I don't think it is"; confirm = JOptionPane.showConfirmDialog(null, "Is this a ru-verb? (" + guess + ")", "Verb type", JOptionPane.YES_NO_OPTION); } if (confirm == 0){ v.setRuverb(true); }else{ v.setRuverb(false); } new ConjugatorGrid(v); }
6
private void createDir(String dir) { File f = new File(dir); if(f.exists() && !f.isDirectory()) { Main.fatalError("Cannot create folder '" + dir + "'. There is a file called the same name."); } else if(!f.exists()){ try { if(!f.mkdirs()) { Main.fatalError("Could not generate all of the directories '" + dir + "'."); } } catch(SecurityException e) { Main.fatalError("Cannot create folder '" + dir + "':\n" + e); } } }
5
public double standardizedAllResponsesMaximum(){ if(!this.dataPreprocessed)this.preprocessData(); if(!this.variancesCalculated)this.meansAndVariances(); return this.standardizedAllResponsesMaximum; }
2
@Override void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) { // Replace child for(ListIterator<PComando> i = this._comando_.listIterator(); i.hasNext();) { if(i.next() == oldChild) { if(newChild != null) { i.set((PComando) newChild); newChild.parent(this); oldChild.parent(null); return; } i.remove(); oldChild.parent(null); return; } } throw new RuntimeException("Not a child."); }
3
public static PaymentResponse fromXml(String xml) throws ArsenalPayApiException { PaymentResponse paymentResponse = read(xml); String status = paymentResponse.getMessage(); if (! "OK".equalsIgnoreCase(status)) { throw translateToException(status); } return paymentResponse; }
1
public void paint(Graphics2D g,boolean draw,boolean fill){ if (calcularVar) { calcular(); calcularVar = false; } if (draw && !fill) { g.draw(path); }else if(fill && !draw){ g.fill(path); }else if(draw && fill){ g.draw(path); g.fill(path); } }
7
public static void main(String args[]) { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); FrmAcceso acceso = new FrmAcceso(); acceso.setVisible(true); acceso.setLocationRelativeTo(null); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } } }); } catch (ClassNotFoundException ex) { Logger.getLogger(FrmAcceso.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(FrmAcceso.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(FrmAcceso.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedLookAndFeelException ex) { Logger.getLogger(FrmAcceso.class.getName()).log(Level.SEVERE, null, ex); } }
8
private boolean startGame() { //To do Decide who is starting // in case of ai openent I'm starting if (playerIsReady && (oponent.getPlayerState() == ePlayerState.Ready)) { if (oponent instanceof AI) { if (gui != null) { gui.updateState(eBattleFieldMode.Playable); gameStarted = true; return true; } } else { // to check if this is the host else send a switch turn Player p = (Player)oponent; if(p.isHost()) { if(gui != null) { gui.updateState(eBattleFieldMode.Playable); return true; } } } } return false; }
6
public static String getMediaPath(String fileName) { String path = null; String directory = getMediaDirectory(); boolean done = true; // if the directory is null if (directory == null) { // try to find the mediasources directory try { // get the URL for where we loaded this class Class<?> currClass = Class.forName("FileChooser"); URL classURL = currClass.getResource("FileChooser.class"); URL fileURL = new URL(classURL,"../mediasources/"); directory = fileURL.getPath(); File dirFile = new File(directory); if (dirFile.exists()) { setMediaPath(directory); done = true; } } catch (Exception ex) { } if (!done) { SimpleOutput.showError("The media path (directory)" + " has not been set yet! " + "Please pick the directory " + "that contains your media " + "(usually called mediasources) " + "with the following FileChooser. " + "The directory name will be stored " + "in a file and remain unchanged unless you use " + "FileChooser.pickMediaPath() or " + "FileChooser.setMediaPath(\"full path name\") " + "(ex: FileChooser.setMediaPath(\"c:/intro-prog-java/mediasources/\")) " + " to change it."); pickMediaPath(); directory = getMediaDirectory(); } } // get the full path path = directory + fileName; return path; }
5
protected void loadFields(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { super.loadFields(__in, __typeMapper); __in.peekTag(); if (__typeMapper.isElement(__in, Case__typeInfo)) { setCase((com.sforce.soap.enterprise.sobject.Case)__typeMapper.readObject(__in, Case__typeInfo, com.sforce.soap.enterprise.sobject.Case.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, CaseId__typeInfo)) { setCaseId(__typeMapper.readString(__in, CaseId__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, CreatedBy__typeInfo)) { setCreatedBy((com.sforce.soap.enterprise.sobject.Name)__typeMapper.readObject(__in, CreatedBy__typeInfo, com.sforce.soap.enterprise.sobject.Name.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, CreatedById__typeInfo)) { setCreatedById(__typeMapper.readString(__in, CreatedById__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, CreatedDate__typeInfo)) { setCreatedDate((java.util.Calendar)__typeMapper.readObject(__in, CreatedDate__typeInfo, java.util.Calendar.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, Field__typeInfo)) { setField(__typeMapper.readString(__in, Field__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, IsDeleted__typeInfo)) { setIsDeleted((java.lang.Boolean)__typeMapper.readObject(__in, IsDeleted__typeInfo, java.lang.Boolean.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, NewValue__typeInfo)) { setNewValue((java.lang.Object)__typeMapper.readObject(__in, NewValue__typeInfo, java.lang.Object.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, OldValue__typeInfo)) { setOldValue((java.lang.Object)__typeMapper.readObject(__in, OldValue__typeInfo, java.lang.Object.class)); } }
9
public static void main(final String[] args) throws Exception { int i = 0; int flags = ClassReader.SKIP_DEBUG; boolean ok = true; if (args.length < 1 || args.length > 2) { ok = false; } if (ok && "-debug".equals(args[0])) { i = 1; flags = 0; if (args.length != 2) { ok = false; } } if (!ok) { System.err .println("Prints a disassembled view of the given class."); System.err.println("Usage: Textifier [-debug] " + "<fully qualified class name or class file name>"); return; } ClassReader cr; if (args[i].endsWith(".class") || args[i].indexOf('\\') > -1 || args[i].indexOf('/') > -1) { cr = new ClassReader(new FileInputStream(args[i])); } else { cr = new ClassReader(args[i]); } cr.accept(new TraceClassVisitor(new PrintWriter(System.out)), flags); }
9
@Override public void generate() throws GeneratorException { //get the extension of the template String ext=""; String templateFile = report.getTemplate(); int i = templateFile.lastIndexOf('.'); if (i >= 0) { ext = templateFile.substring(i+1); } try { report.generate(report.getOutput()+"."+ext); } catch (XDocReportException e) { throw new GeneratorException(GeneratorError.DOCX_GENERATION_ERROR,"Error while generating the DOCX file:"+e.getMessage()); } }
2