text
stringlengths
14
410k
label
int32
0
9
public long getMaxClients() { return maxClients; }
0
public static void insertInitInfectedContacts() { int numInserts = 0; double minContactDuration = 0.0; try { HashSet<Integer> sick = new HashSet<Integer>(565685); Connection con = dbConnect(); ResultSet getSickQ = con.createStatement().executeQuery( "SELECT victimID FROM "+dendroTbl); while (getSickQ.next()) { Integer p = new Integer(getSickQ.getInt("victimID")); sick.add(p); } getSickQ.close(); HashSet<Integer> initInfected = new HashSet<Integer>(100); getSickQ = con.createStatement().executeQuery( "SELECT id FROM "+initTbl); while (getSickQ.next()) { Integer p = new Integer(getSickQ.getInt("id")); initInfected.add(p); } getSickQ.close(); PreparedStatement insert = con.prepareStatement( "INSERT INTO "+sickConTbl+" (person1ID,person2ID,duration) VALUES (?,?,?)"); PreparedStatement getContacts = con.prepareStatement( "SELECT person2ID,duration FROM "+conTbl+" WHERE person1ID = ?"); Iterator<Integer> initInfectedItr = initInfected.iterator(); while (initInfectedItr.hasNext()) { Integer person = initInfectedItr.next(); getContacts.setInt(1, person.intValue()); ResultSet getContactsQ = getContacts.executeQuery(); while (getContactsQ.next()) { insert.setInt(1, person); Integer contact = getContactsQ.getInt("person2ID"); double duration = getContactsQ.getDouble("duration"); if (sick.contains(contact) && duration >= minContactDuration) { insert.setInt(2, contact); insert.setDouble(3, duration); numInserts += insert.executeUpdate(); } } } con.close(); System.out.println("Number of inserts: "+numInserts); } catch (Exception e) { System.out.println(e); } }
7
public static final Color checkColour(int red, int green, int blue) { if (red < 0) red = 0; else if (red > 255) red = 255; if (green < 0) green = 0; else if (green > 255) green = 255; if (blue < 0) blue = 0; else if (blue > 255) blue = 255; return new Color(red, green, blue); }
6
@Override public boolean equals(Object obj) { if (this == obj) { return true; } return false; }
1
private void draw() { if (this.turnNumber > 1) { this.activePlayer.draw(1); } }
1
public static Map<String, Object> getHasOne(Object obj) throws Exception { Map<String, Object> attrs = new HashMap<String, Object>(); for (Field field : obj.getClass().getDeclaredFields()) { Class<?> fieldType = field.getType(); String fieldName = field.getName(); Annotation[] annotations = field.getDeclaredAnnotations(); if (annotations.length > 0 && HasOne.class.equals(annotations[0].annotationType())) { String foreignKey = ((HasOne) annotations[0]).FK(); attrs.put("column", foreignKey); attrs.put("fieldType", fieldType); String getterName = BeanUtils.getter(fieldName); Method getter = obj.getClass().getMethod(getterName); Object target = getter.invoke(obj); attrs.put("value", target); attrs.put("fieldName", fieldName); break; } } return attrs; }
4
protected void rodaMidiaVirtual(){ /* * verificacao de seguranca. * se nao houver nenhuma midia na memoria secundaria. */ if(jogos.isEmpty()) if(JOptionPane.showConfirmDialog(null, "\nSem midias virtuais no disco local.\n\nAdicionar?","Midias Virtuais",JOptionPane.YES_NO_OPTION) == 0 ) if(!addMidiaVirtual()) return; String texto = ""; for(int i = 0; i<jogos.size(); i++) texto += (i+1)+". "+jogos.get(i) +'\n';//concatena os jogos armazenados localmente int jogo = Integer.parseInt( JOptionPane.showInputDialog(null, "\nSelecione um jogo:\n\n"+texto+"\n","Midias Virtuais",JOptionPane.INFORMATION_MESSAGE) ); if(jogo <= jogos.size() && jogo > 0){ jogoRodando = jogos.get(jogo-1); rodaMidiaFisica();//roda como se fosse uma midia fisica } else JOptionPane.showMessageDialog(null, "\nOpção inválida\n","Erro",JOptionPane.ERROR_MESSAGE); }
6
public void updateState(int state) { if( isValidStateToGo(state) ) { setState(state); switch (state) { case CREATED: setCreateTime(new Date()); case RUNNING: setStartTime(new Date()); case ENDED: case ENDED_CANCELLED: case ENDED_TIMEOUT: setEndTime(new Date()); default: } } else { InvalidStateException.throwWith(this, getState(), state); } }
6
public void sendGlobalMessage(ChatPlayer player, String message) { String formattedMessage = formatMessage(player, message); for (ChatPlayer data : plugin.onlinePlayers.values()) { if (!data.ignoringPlayer(player.getName()) || data.isChatSpying()) { data.sendMessage(formattedMessage); } } if (plugin.logChat) { plugin.cl.log(formattedMessage); } dispatchMessage(formattedMessage, SUBCHANNEL_NAME); }
4
public void render() { for(int i = 0; i < Sidebar.MAX_ELEMS; i ++) { if(elements[i] != null) { elements[i].render(Sidebar.xPos_ + Sidebar.HORIZONTAL_SPACING, elementPos[i]); } } }
2
public void run() { try { // this will handle our XML voyageurhandler voyHandler = new voyageurhandler(); // get a parser object SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); // get an InputStream from somewhere (could be HttpConnection, for example) HttpConnection hc = (HttpConnection) Connector.open("http://localhost:8080/smartPhp/getXmlUser.php"); DataInputStream dis = new DataInputStream(hc.openDataInputStream()); parser.parse(dis, voyHandler); // display the result voy = voyHandler.getvoyageur(); try { loadPlayer(); GUIControl guiControl = (GUIControl) player.getControl("javax.microedition.media.control.GUIControl"); if (guiControl == null) { throw new Exception("No GUIControl!!"); } Item videoItem = (Item) guiControl.initDisplayMode(GUIControl.USE_GUI_PRIMITIVE,null); videoItem.setPreferredSize(f2.getWidth()-2,f2.getHeight()/2); f2.insert(0, videoItem); f1.append(new Spacer(50, 50)); player.start(); } catch (Exception e) { error(e); } for (int i = 0; i < voy.length; i++) { if (voy[i].getEmail().equals(login.getString()) && voy[i].getPassword() == Integer.parseInt(password.getString())) { nom_voyageur.setText(voy[i].getNom()); f2.append(nom_voyageur); disp.setCurrent(f2); } } } catch (Exception e) { System.out.println("Exception:" + e.toString()); } }
6
private SimpleNode findNodeABR(SimpleNode node, final int value) { SimpleNode ret = null; if (this.root == null) { throw new RuntimeException("Le noeud [" + this.min + "; " + this.max + "] est vide et ne contient donc pas " + value + " !"); } if (node == null) { throw new RuntimeException("Le noeud à rechercher ne peut pas être nul !"); } else if (value > node.getValue()) { // Si la valeur est inférieure à la valeur du noeud courant, on recherche dans le fils droit if (node.getRightSon() != null) { ret = findNodeABR((SimpleNode) node.getRightSon(), value); } } else if (value < node.getValue()) { // Si la valeur est supérieure à la valeur du noeud courant, on recherche dans le fils gauche if (node.getLeftSon() != null) { ret = findNodeABR((SimpleNode) node.getLeftSon(), value); } } else if (value == node.getValue()) { ret = node; } return ret; }
7
protected void initializeCommandTypeInfo() { super.initializeCommandTypeInfo(); Map mm6ArgumentTypeArrayByCommandTypeMap = super.getArgumentTypeArrayByCommandTypeMap(); Map mm6ArgumentTypeDisplayInfoArrayByCommandTypeMap = super.getArgumentTypeDisplayInfoArrayByCommandTypeMap(); Object replacementArgumentsByCommandType[] = new Object[] { new Integer(EVENT_COMMAND__CreateMonster), new Object[] { _I_(ARGUMENT_TYPE__SPECIES_TYPE), "of species #", ",", _I_(1), _I_(ARGUMENT_TYPE__SUBSPECIES_TYPE), "subspecies", null, _I_(2), _I_(ARGUMENT_TYPE__MONSTER_CREATION_COUNT), null, "monster(s)", _I_(0), _I_(ARGUMENT_TYPE__COORDINATE_SET), "at", null, _I_(3), _I_(ARGUMENT_TYPE__UNKNOWN_INTEGER), "with spawn group number", null, _I_(4), // TODO: ARGUMENT_TYPE__SPAWN_GROUP_NUMBER _I_(ARGUMENT_TYPE__UNKNOWN_INTEGER), "and monster name id", null, _I_(5) // TODO: ARGUMENT_TYPE__MONSTER_NAME_ID }, new Integer(EVENT_COMMAND__ModifyMonster), new Object[] { _I_(ARGUMENT_TYPE__UNKNOWN_INTEGER), "monsterId?", null, _I_(1), _I_(ARGUMENT_TYPE__UNKNOWN_INTEGER), "bit?", null, _I_(2), _I_(ARGUMENT_TYPE__BOOLEAN), "Set?", null, _I_(0), // set or unset }, new Integer(EVENT_COMMAND__EV_PlaySmacker), new Object[] { _I_(ARGUMENT_TYPE__UNKNOWN_BYTE), "stretch?", null, _I_(0), _I_(ARGUMENT_TYPE__UNKNOWN_BYTE), "exit now?", null, _I_(1), _I_(ARGUMENT_TYPE__FILENAME_12), null, null, _I_(2) // movie name, seems like it might only be 9 characters } }; int argumentTypesForCommandTypeArrayColumns = 2; if (replacementArgumentsByCommandType.length % argumentTypesForCommandTypeArrayColumns != 0) { throw new RuntimeException("argsAndSizeArray.length = " + replacementArgumentsByCommandType.length + " which is not a power of " + argumentTypesForCommandTypeArrayColumns + "."); } for (int index = 0; index < replacementArgumentsByCommandType.length; index = index+argumentTypesForCommandTypeArrayColumns) { Integer commandTypeNumber = (Integer)replacementArgumentsByCommandType[index]; Object argumentTypeDataArray[] = (Object [])replacementArgumentsByCommandType[index+1]; Integer key = null; for (int commandTypesIndex = 0; commandTypesIndex < commandTypes.length; commandTypesIndex++) { if (commandTypes[commandTypesIndex].equals(commandTypeNumber)) { key = new Integer(commandTypesIndex); } } if (null == key) { throw new RuntimeException("Unable to find command type value" + commandTypeNumber + " in commandTypes"); } int[] argumentTypeArray = getArgumentTypeArrayFromArgumentTypeDataArray(argumentTypeDataArray); Object newArgumentTypeArrayValue = argumentTypeArray; if (false == mm6ArgumentTypeArrayByCommandTypeMap.containsKey(key)) { throw new RuntimeException("mm6ArgumentTypeArrayByCommandTypeMap does not contain key " + key + " for replacement value of " + newArgumentTypeArrayValue); } mm6ArgumentTypeArrayByCommandTypeMap.put(key, newArgumentTypeArrayValue); ArgumentTypeDisplayInfo[] argumentTypeDisplayInfoArray = getArgumentTypeDisplayInfoArrayFromArgumentTypeDataArray(argumentTypeDataArray); Object newArgumentTypeDisplayInfoArrayValue = argumentTypeDisplayInfoArray; if (false == mm6ArgumentTypeDisplayInfoArrayByCommandTypeMap.containsKey(key)) { throw new RuntimeException("mm6ArgumentTypeDisplayInfoArrayByCommandTypeMap does not contain key " + key + " for replacement value of " + newArgumentTypeArrayValue); } mm6ArgumentTypeDisplayInfoArrayByCommandTypeMap.put(key, newArgumentTypeDisplayInfoArrayValue); } }
7
public static int[][] place(State[][] map, int width, int height) { int _i = width / 2; int _j = height / 2; int _1strandi; int _1strandj; int _2ndrandi; int _2ndrandj; int _3rdrandi; int _3rdrandj; int d12; int d13; int d23; do { Random rand = new Random(); do { _1strandi = rand.nextInt((_i-1) - 0 + 1) + 0; _1strandj = rand.nextInt((_j-1) - 0 + 1) +0; } while(map[_1strandi][_1strandj].getLoyalty().ordinal() != 1); do { _2ndrandi = rand.nextInt((_i-1) - 0 + 1) + 0; _2ndrandj = rand.nextInt((height-1) - (_j) + 1) + (_j); } while(map[_2ndrandi][_2ndrandj].getLoyalty().ordinal() != 1); do { _3rdrandi = rand.nextInt((width-1) - (_i) + 1) + (_i); _3rdrandj = rand.nextInt((height-1) - (_j) + 1) + (_j); } while(map[_3rdrandi][_3rdrandj].getLoyalty().ordinal() != 1); //test de distance d12 = Math.abs(_2ndrandi-_1strandi) + Math.abs(_2ndrandj-_1strandj); d13 = Math.abs(_3rdrandi-_1strandi) + Math.abs(_3rdrandj-_1strandj); d23 = Math.abs(_3rdrandi-_2ndrandi) + Math.abs(_3rdrandj-_2ndrandj); } while(d12 < 5 || d13 < 5 || d23 < 5); int[] _1strand = new int[2]; _1strand[0] = _1strandi; _1strand[1] = _1strandj; int[] _2ndrand = new int[2]; _2ndrand[0] = _2ndrandi; _2ndrand[1] = _2ndrandj; int[] _3rdrand = new int[2]; _3rdrand[0] = _3rdrandi; _3rdrand[1] = _3rdrandj; int[][] pos = new int[3][]; pos[0] = _1strand; pos[1] = _2ndrand; pos[2] = _3rdrand; return pos; }
6
public List<String> start(String nzbPath) { List<String> out = new LinkedList<String>(); NZB nzb = getNzb(nzbPath); List<File> files = nzb.getFiles(); int fileCount = 1; for (Iterator<File> i = files.iterator(); i.hasNext();) { File file = i.next(); System.out.println("File " + fileCount + "/" + files.size() + " " + file.getSubject()); List<String> segmentNames = new ArrayList<String>(); List<DownloadThread> downloadThreads = new ArrayList<DownloadThread>(); for (Iterator<Segment> j = file.getSegments(). iterator(); j.hasNext();) { Segment seg = j.next(); String downloadName = file.getSubject(). hashCode() + "_" + seg.getNumber() + ".yenc"; //Thread thread = createDownloadSegThread(segCount, file.getGroups().get(0).getName(), "<" + seg.getString() + ">", downloadName); DownloadThread thread = createDownloadSegThread(pool, file.getGroups(). get(0). getName(), "<" + seg.getString() + ">", downloadName); thread.start(); try { //Give some time for the thread to get started so that the joins complete in a good order. Thread.sleep(100); } catch (InterruptedException e) { } downloadThreads.add(thread); segmentNames.add(downloadName); } //Wait for all the threads to finish int segCount = 1; boolean failure = false; for (Iterator<DownloadThread> t = downloadThreads.iterator(); t.hasNext();) { try { DownloadThread thread = t.next(); thread.join(); if (thread.getResult()) { System.out.println("\t" + segCount + "/" + file.getSegments(). size() + " of " + file.getSubject()); } else { System.err.println("\t" + segCount + "/" + file.getSegments(). size() + " of " + file.getSubject() + " failed."); failure = true; } segCount++; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (!failure) { String filename = launchDecode(segmentNames); if (filename != null) out.add(filename); } else { System.err.println("Couldn't download all segments. Skipping decode."); for (Iterator<String> j = segmentNames.iterator(); j.hasNext();) { //clean up segments new java.io.File(config.getCacheDir() + java.io.File.separator + j.next()).delete(); } } fileCount++; } return out; }
9
public <G, H> BinaryCompositeBinaryFunction(BinaryFunction<? super G, ? super H, ? extends T> f, BinaryFunction<? super L, ? super R, ? extends G> g, BinaryFunction<? super L, ? super R, ? extends H> h) { this.helper = new Helper<G, H, L, R, T>( Validate.notNull(f, "final BinaryFunction argument must not be null"), Validate.notNull(g, "left preceding BinaryFunction argument must not be null"), Validate.notNull(h, "right preceding BinaryFunction argument must not be null") ); }
9
private void setFilterJob(String targetColumn, String... args) { // Mapper Class job.setMapperClass(FilterMapper.class); // Output Key/Value job.setMapOutputKeyClass(NullWritable.class); job.setMapOutputValueClass(Text.class); // Reducer Task job.setNumReduceTasks(0); //Set Parameters //value : EMPTY, NEMPTY, EQ, NEQ, GT, LT, GTE, LTE, START, END job.getConfiguration().set("targetColumn", targetColumn); if (args.length == 1) { if (args[0].equals("EMPTY") || args[0].equals("NEMPTY")) { job.getConfiguration().set("commandName", args[0].toLowerCase()); job.getConfiguration().set("value", "null"); } } else if (args.length == 2) { if (!(args[0].equals("EMPTY") || args[0].equals("NEMPTY"))) { job.getConfiguration().set("commandName", args[0].toLowerCase()); job.getConfiguration().set("value", args[1]); } } }
6
@Override public void paint(Graphics g, RsTransform gt){ Color fc, lc; fc = getFillColor(); lc = getLineColor(); if(fc==null && lc==null) return; if(refSegment==null){ // the shape is not depicted and not interactive because // no polygon was ever supplied } int nSegment = refSegment.length; double x, y; for(int i=0; i<nSegment; i++){ x=refSegment[i].x; y=refSegment[i].y; ix[i] = (int)Math.floor(gt.m11*x + gt.m12*y + gt.m13 + 0.5); iy[i] = (int)Math.floor(gt.m21*x + gt.m22*y + gt.m23 + 0.5); } ix[nSegment]=ix[0]; iy[nSegment]=iy[0]; if(fc!=null){ g.setColor(fc); g.fillPolygon(ix, iy, nSegment+1); } if(lc!=null){ g.setColor(lc); g.drawPolygon(ix, iy, nSegment+1); } }
6
public void addSetMethod(Field field, Method method) { if(field == null) { throw new IllegalArgumentException("Field cannot be null"); } FieldStoreItem item = store.get(FieldStoreItem.createKey(field)); if(item != null) { item.setSetMethod(method); } else { item = new FieldStoreItem(field); item.setSetMethod(method); store.put(item.getKey(),item); } }
2
public boolean readFile(String filename) { try { BufferedReader reader = new BufferedReader(new FileReader(filename)); String currentLine = reader.readLine(); while(currentLine!=null) { switch(currentLine.charAt(0)) { case 99: //99 = c comment line. currentLine = reader.readLine(); break; case 112: //112 = p "p cnf" line getCounts(currentLine.substring(6)); currentLine = reader.readLine(); formula = new Formula(clauseCount); //we will have clause count by this time. break; default: //remaining lines makeClause(currentLine); currentLine = reader.readLine(); break; } } return true; //file successfully read } catch(IOException ioe) { System.out.println("Invalid filename '"+filename+"'"); return false; } }
4
@Override public boolean hasNext() { if (position >= addIngredientCommands.size() || addIngredientCommands == null) { return false; } else { return true; } }
2
public List<Integer> grayCode(int n) { List<Integer> list = new ArrayList<Integer>(); list.add(0); for(int i =0; i < n;i++){ int base = 1 << i; for(int j = list.size()-1;j >=0;j--){ list.add(base + list.get(j)); } } return list; }
2
private static void performWork(String dataStructure, int nrThreads, int nrItems, int workTime, long seed) throws InterruptedException { Sorted<Integer> sorted = null; if (dataStructure.equals(CGL)) { sorted = new CoarseGrainedList<Integer>(); } else if (dataStructure.equals(CGT)) { sorted = new CoarseGrainedTree<Integer>(); } else if (dataStructure.equals(FGL)) { sorted = new FineGrainedList<Integer>(); } else if (dataStructure.equals(FGT)) { sorted = new FineGrainedTree<Integer>(); } else if (dataStructure.equals(LFL)) { sorted = new LockFreeList<Integer>(); } else if (dataStructure.equals(LFT)) { sorted = new LockFreeTree<Integer>(); } else { exitWithError(); } startThreads(sorted, nrThreads, nrItems, workTime, seed); }
6
public void fall() { for (Block b : currentTetromino.getBlocks()) { if ((b.getMapIndexY() == boardSizeY) || (tetrisMap[b.getMapIndexX()][b.getMapIndexY() + 1] == 1)) { currentTetromino.setActiveStatus(false); for (Block blk : currentTetromino.getBlocks()) { tetrisMap[blk.getMapIndexX()][blk.getMapIndexY()] = 1; } } } if (currentTetromino.getActiveStatus() == true) { for (Block b : currentTetromino.getBlocks()) { tetrisMap[b.getMapIndexX()][b.getMapIndexY()] = 0; } for (Block b : currentTetromino.getBlocks()) { b.translateDown(); tetrisMap[b.getMapIndexX()][b.getMapIndexY()] = currentTetromino .getKey(); } } notifyObservers(); }
7
private static int getuid(String s) { try { File file = new File(s + "uid.dat"); if (!file.exists() || file.length() < 4L) { DataOutputStream dataoutputstream = new DataOutputStream( new FileOutputStream(s + "uid.dat")); dataoutputstream.writeInt((int) (Math.random() * 99999999D)); dataoutputstream.close(); } } catch (Exception _ex) { } try { DataInputStream datainputstream = new DataInputStream( new FileInputStream(s + "uid.dat")); int i = datainputstream.readInt(); datainputstream.close(); return i + 1; } catch (Exception _ex) { return 0; } }
4
private void testHelper_method_nullAnchor_shouldFail(MethodToTest method) { final IMutableMolecule NULL_ANCHOR = null; switch (method) { case changeMoleculeEnergyLevel: moleculeMediator.changeMoleculeEnergyLevel(NULL_ANCHOR, VALID_POSITION, VALID_ENERGY_CHANGE_AMOUNT); break; case createMoleculeAtPositionRelativeToAnchor: moleculeMediator.createMoleculeAtPositionRelativeToAnchor( NULL_ANCHOR, VALID_POSITION, new MoleculeDescriptor( VALID_REMAINING_ENERGY, VALID_MAX_ENERGY, VALID_BEHAVIOUR, neuteredMovementAction)); break; case getMoleculeAtPositionRelativeToAnchor: moleculeMediator.getMoleculeAtPositionRelativeToAnchor(NULL_ANCHOR, VALID_POSITION); break; case getResourcesAtPositionRelativeToAnchor: moleculeMediator.getResourcesAtPositionRelativeToAnchor(NULL_ANCHOR, VALID_POSITION); break; case exchangeMoleculePositions: moleculeMediator.exchangeMoleculePositions(NULL_ANCHOR, VALID_POSITION); break; case changeResourceAmount: moleculeMediator.changeResourceAmount(NULL_ANCHOR, VALID_POSITION, VALID_TYPE, VALID_AMOUNT); break; case modifyMolecule: moleculeMediator.modifyMolecule(NULL_ANCHOR, VALID_POSITION, VALID_MODIFIER); break; default: throw new RuntimeException("Unknown method: " + method.name()); } }
7
public static void main(String[] args) { List<Integer> powInts = new ArrayList<>(); int limit = 10000000; int pow = 5; int start = 2; //ignore 1 for sum for (Integer i = start; i < limit; i++) { String s = String.valueOf(i); char[] c = new char[s.length()]; c = s.toCharArray(); int sum = 0 ; for (int j = 0; j < c.length ;j++) { sum += new BigInteger(""+c[j]).pow(pow).intValue(); } if (sum == i){ powInts.add(i); } } int sum = 0; for (Integer i: powInts) { System.out.println(i); sum += i; } System.out.println("Result = " + sum); }
4
protected float convert(char tipo, float grados){ float aux=0; switch(tipo){ case 'c': aux=(float)(this.gradosK-273.15); break; case 'k': aux=(float)(this.gradosC+273.15); break; default: System.out.println("Error el tipo es c o k"); break; } return aux; }
2
private String createImports() { ImportGenerator imports = new ImportGenerator( filePath ); imports.addImport( "import static org.junit.Assert.*;" ); imports.addImport( "import org.junit.*;" ); if ( hasSearch ) { imports.addImport( "import java.util.List;" ); } imports.addImport( "import " + pkg + ".domain.*;" ); imports.addImport( "import " + pkg + ".dao.*;" ); imports.addImport( "import " + pkg + ".util.*;" ); return imports.toString(); }
1
public void majResumePersos(Joueur j){ LinkedList<Personnage> persos = j.getPersonnages(); Iterator<Personnage> persosIt = persos.iterator(); Personnage p; JPanel unPerso; panelResumePerso.removeAll(); while(persosIt.hasNext()){ p = persosIt.next(); unPerso = new JPanel(); unPerso.setLayout(new BoxLayout(unPerso, BoxLayout.PAGE_AXIS)); if (p.getClass() == Mage.class) { unPerso.add(new JLabel("Mage")); } else if (p.getClass() == Voleur.class) { unPerso.add(new JLabel("Voleur")); } else if (p.getClass() == Guerrier.class) { unPerso.add(new JLabel("Guerrier")); } else if (p.getClass() == CavalierCeleste.class) { unPerso.add(new JLabel("Cavalier Céleste")); } unPerso.add(new JLabel(p.getNom())); unPerso.add(new JLabel(p.getAge() + " ans")); unPerso.setBorder(BorderFactory.createEtchedBorder()); panelResumePerso.add(unPerso); } }
5
public static void saveDimension(File file, PlaneDimension pd) { Cell[][] dim = pd.getAllSeats(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < dim[0].length; i++) { for (int j = 0; j < dim.length; j++) { int outputVal = 0; Cell.CellType ct = dim[j][i].getCellType(); if (ct == Cell.CellType.SEAT) { outputVal = 1; } else if (ct == Cell.CellType.PRIORITY_SEAT) { outputVal = 2; } else if (ct == Cell.CellType.AISLE) { outputVal = 3; } sb.append(outputVal).append(" "); } sb.append("\n"); } String toOut = sb.toString(); try { FileOutputStream fos; fos = new FileOutputStream(file); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); bw.write(toOut); bw.close(); fos.close(); } catch (Exception ex) { } }
6
public boolean replaceSubBlock(StructuredBlock oldBlock, StructuredBlock newBlock) { if (innerBlock == oldBlock) innerBlock = newBlock; else return false; return true; }
1
private void start (Player p) { if ( p != white_player && p != black_player ) { // runtime error! return; } curPlayer = p; }
2
public void mouseDragged(MouseEvent e) { if (documentViewModel.getViewToolMode() == DocumentViewModel.DISPLAY_TOOL_TEXT_SELECTION) { textSelectionHandler.mouseDragged(e); } else if (documentViewModel.getViewToolMode() == DocumentViewModel.DISPLAY_TOOL_SELECTION || documentViewModel.getViewToolMode() == DocumentViewModel.DISPLAY_TOOL_LINK_ANNOTATION) { annotationHandler.mouseDragged(e); } }
3
public void intersect( PhysicObject object1, PhysicObject object2 ) { // TODO: do intersect with all colliders IntersectData intersectData = Intersect.colliders( object1.getColliders().get( 0 ), object2.getColliders().get( 0 ) ); if ( intersectData != null && intersectData.isIntersect() ) { Vector3f direction = intersectData.getDirection().normalized(); Vector3f otherDirection = direction.reflect( object1.getVelocity().normalized() ); float restitutionCoefficient = ( object1.getPhysicalProperties().getFloat( "restitutionCoefficient" ) + object2.getPhysicalProperties().getFloat( "restitutionCoefficient" ) ) / 2; object1.setVelocity( object1.getVelocity().reflect( otherDirection ).mul( restitutionCoefficient ) ); object2.setVelocity( object2.getVelocity().reflect( direction ).mul( restitutionCoefficient ) ); } }
2
public static void main(String args[]) { Scanner sc = new Scanner(System.in); int k, m; while ((k = sc.nextInt())!=0 && k!=0) { m = sc.nextInt(); HashMap course = new HashMap(); boolean satisfied = true; for (int i = 0; i < k; i++) { course.put(sc.next(), 1); } for (int i = 0; i < m; i++) { int c = sc.nextInt(); int r = sc.nextInt(); int cnt = 0; for (int j = 0; j < c; j++) { if (course.containsKey(sc.next())) { cnt++; } } if (cnt < r) { satisfied = false; } } if (satisfied) { System.out.println("yes"); } else { System.out.println("no"); } } }
8
@Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Pair<?, ?>) { Pair<?, ?> other = (Pair<?, ?>) obj; return ObjectUtils.equals(first, other.first) && ObjectUtils.equals(second, other.second); } return false; }
9
@Override public void nativeKeyPressed(NativeKeyEvent ev) { // Copy if (ev.getKeyCode() == NativeKeyEvent.VK_C && NativeInputEvent.getModifiersText(ev.getModifiers()).equals( "Ctrl")) { System.out.println("Ctrl+C : call"); // Clip the pop try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } clipStack.push(sysClip.getContents(null)); lastWasCtrlC = true; System.out.println("Ctrl+C : finished status Stack(" + clipStack.size() + ")"); } // Paste if (ev.getKeyCode() == NativeKeyEvent.VK_V && NativeInputEvent.getModifiersText(ev.getModifiers()).equals( "Ctrl")) { System.out.println("Ctrl+V : call"); if(lastWasCtrlC){ lastWasCtrlC = false; if(clipStack.size() > 1) clipStack.pop(); } // Pop the clip try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } if (clipStack.size() > 1) { System.out.println("Ctrl+V : pop"); sysClip.setContents(clipStack.pop(), null); } else{ System.out.println("Ctrl+V : peek"); sysClip.setContents(clipStack.peek(), null); } System.out.println("Ctrl+V : finished status Stack(" + clipStack.size() + ")"); } }
9
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((orderProductId == null) ? 0 : orderProductId.hashCode()); result = prime * result + ((productId == null) ? 0 : productId.hashCode()); result = prime * result + ((productName == null) ? 0 : productName.hashCode()); result = prime * result + ((proformId == null) ? 0 : proformId.hashCode()); result = prime * result + ((quantity == null) ? 0 : quantity.hashCode()); result = prime * result + ((salePrice == null) ? 0 : salePrice.hashCode()); result = prime * result + ((vatRate == null) ? 0 : vatRate.hashCode()); return result; }
8
public boolean hasError() { return isErrorProteinLength() || isErrorStartCodon() || isErrorStopCodonsInCds(); }
2
public final String relativize(final Path base) { Path p = this; synchronized (Path.relativizer) { Path.relativizer.clear(); while (p.getNameCount() > base.getNameCount()) { p = p.getParent(); } int same = p.getNameCount(); if (p != base) { Path q = base; if (q.getNameCount() > p.getNameCount()) { while (q.getNameCount() > p.getNameCount()) { q = q.getParent(); Path.relativizer.appendLast("../"); } } while (p != q) { if (--same == 0) { return this.str; } p = p.getParent(); q = q.getParent(); Path.relativizer.appendLast("../"); } } while (same < getNameCount()) { Path.relativizer.appendLast(getComponentAt(same++)); Path.relativizer.appendLast("/"); } Path.relativizer.removeLast(); return Path.relativizer.toString(); } }
7
public void setEdge ( int edge ) { if ( edge < 8 ) throw new IllegalArgumentException ( "Parameter edge must be not less than 8 it was set to " + edge ); if ( edge > MAX_EDGE ) throw new IllegalArgumentException ( "Parameter edge must be less than " + MAX_EDGE + " it was set to " + edge ); if ( edge % 8 != 0 ) edge = ( int ) ( ( Math.round ( ( double ) edge ) / 8 ) * 8 ); this.edge = edge; double preciseHeight = edge * Math.sqrt ( 3 ); height = ( int ) Math.round ( preciseHeight ); if ( height % 2 == 1 ) { if ( height > preciseHeight ) height--; else height++; } HexEventRegister.getInstance ().triggerEvent ( new ConfigurationChanged ( "edge" ) ); }
5
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(ModuloUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ModuloUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ModuloUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ModuloUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ModuloUsuarios().setVisible(true); } }); }
6
private void deactivate() { if (!isActive()) throw new IllegalArgumentException("Forcefield was already deactivated, something went wrong"); this.active = false; }
1
@Override public void actionPerformed(ActionEvent e) { @SuppressWarnings("rawtypes") JComboBox cb = (JComboBox) e.getSource(); String component = (String) cb.getSelectedItem(); // Afiseaza sau ascunde imaginea de background if (component.compareTo(ElementsVisibility.S_IMAGE.toString()) == 0) { gui.getDraw().changeImageDrawingStatus(true); } else { gui.getDraw().changeImageDrawingStatus(false); } // Afiseaza elementele conform selectiei: randuri, blocuri Component[] gList = gui.getDraw().getComponents(); for (Component element : gList) { GElement gElem = (GElement) element; if (gui.visCombo.getSelectedItem().toString() .compareTo(ElementsVisibility.S_IMAGE.toString()) == 0) { gElem.setTextAreaVisible(false); } else { if (gElem.element.getData().elementType == gui.visibleElements .toType()) { gElem.setTextAreaVisible(true); } else { gElem.setTextAreaVisible(false); } } } }
4
@Override public boolean renomearArquivo(String caminhoOrigem, String novoNome, String nomeUsuario) throws RemoteException, XPathExpressionException { Document xml = pedirXML(nomeUsuario); //Alterar XML String expressao; if (caminhoOrigem.endsWith(".txt")) { //Renomeando arquivo if (!manipuladorXML.existeArquivo(caminhoOrigem, xml)) { return false; } expressao = manipuladorXML.montarExpressaoArquivo(caminhoOrigem); } else { //Renomeando pasta if (!manipuladorXML.existePasta(caminhoOrigem, xml)) { return false; } expressao = manipuladorXML.montarExpressaoPasta(caminhoOrigem); } Node node = manipuladorXML.pegaUltimoNode(expressao, xml); node.getAttributes().getNamedItem("nomeFantasia").setTextContent(novoNome); //atualiza data de modificacao SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-YYYY HH:MM"); String dataAgora = sdf.format(new Date()); node.getAttributes().getNamedItem("dataUltimaModificacao").setTextContent(dataAgora); try { manipuladorXML.salvarXML(xml, nomeUsuario); } catch (TransformerException ex) { Logger.getLogger(SistemaArquivo.class .getName()).log(Level.SEVERE, null, ex); return false; } return true; }
4
public void setListener(MqttListener listener) { this.listener = listener; if (handler != null) { handler.setListener(listener); } }
1
private void merge(int[] array, int start, int mid, int end){ int leftIndex = start; int rightIndex = mid+1; int helperIndex = start; //Compare and add elements in sorted manner to helper array while(leftIndex <= mid && rightIndex <= end){ if(array[leftIndex] < array[rightIndex]){ mHelperArray[helperIndex++] = array[leftIndex++]; }else if(array[rightIndex] < array[leftIndex]){ mHelperArray[helperIndex++] = array[rightIndex++]; }else if(array[leftIndex] == array[rightIndex]){ mHelperArray[helperIndex++] = array[leftIndex++]; mHelperArray[helperIndex++] = array[rightIndex++]; } } //Copy leftover items from left array to helperArray while(leftIndex <= mid){ mHelperArray[helperIndex++] = array[leftIndex++]; } //Copy leftover items from right array to helperArray while(rightIndex <= end){ mHelperArray[helperIndex++] = array[rightIndex++]; } //Copy helper to input array int i=start; while(i<=end){ array[i] = mHelperArray[i]; i++; } }
8
public JPanel getOptionBarMenu() { if (!isInitialized()) { IllegalStateException e = new IllegalStateException("Call init first!"); throw e; } return this.optionsBarMenu; }
1
@Override public void propertyChange(PropertyChangeEvent evt) { CompoundPainter<?> painter = ref.get(); if (painter == null) { AbstractPainter<?> src = (AbstractPainter<?>) evt.getSource(); src.removePropertyChangeListener(this); } else { String property = evt.getPropertyName(); if ("dirty".equals(property) && evt.getNewValue() == Boolean.FALSE) { return; } painter.setDirty(true); } }
6
protected void parseStormData(StormSet stormSet, String gpx) throws Exception { if(gpx == null) throw new Exception("GPX XML is null"); this.stormSet = stormSet; SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); SAXParser parser = factory.newSAXParser(); if(parser == null) throw new Exception("Failed to create SAX parser to parse GPX data."); if(parser.getXMLReader() == null) throw new Exception("Failed to get XML reader from SAX parser."); parser.getXMLReader().setContentHandler(this); parser.getXMLReader().parse(new InputSource(new StringReader(gpx))); parser = null; factory = null; }
3
public void refresh() { Transform3D t3d = new Transform3D(); presentation.getTransform(t3d); t3d.setRotation(abstraction.getOrientation()); t3d.setTranslation(abstraction.getPosition()); t3d.normalize(); if (getUsedBy().isEmpty() && presentation.isBillBoardExisting()) presentation.hideBillBoard(); else if (!presentation.isBillBoardExisting() && !getUsedBy().isEmpty()) { presentation.showBillBoard(); } presentation.setTransform(t3d); }
4
@Override public void execute(CommandSender sender, String[] arg1) { if (!CommandUtil.hasPermission(sender, PERMISSION_NODES)) { sender.sendMessage(plugin.NO_PERMISSION); return; } if (arg1.length < 1) { sender.sendMessage(ChatColor.RED + "/" + plugin.mute + " (player)"); return; } ProxiedPlayer player = plugin.getUtilities().getClosestPlayer(arg1[0]); if (player != null) { ChatPlayer cp = plugin.getChatPlayer(player.getName()); cp.toggleMute(); if (cp.isMuted()) { player.sendMessage(plugin.PLAYER_MUTE); sender.sendMessage(plugin.PLAYER_MUTED); } else { player.sendMessage(plugin.PLAYER_UNMUTE); sender.sendMessage(plugin.PLAYER_UNMUTED); } return; } else { sender.sendMessage(plugin.PLAYER_NOT_EXIST); return; } }
4
public void layoutContainer(Container parent){ Insets insets=parent.getInsets(); synchronized(parent.getTreeLock()){ int n=parent.getComponentCount(); Dimension pd=parent.getSize(); int y=0; //work out the total size for(int i=0;i<n;i++){ Component c=parent.getComponent(i); Dimension d=c.getPreferredSize(); y+=d.height+vgap; } y-=vgap; //otherwise there's a vgap too many //Work out the anchor paint if(anchor==TOP)y=insets.top; else if(anchor==CENTER)y=(pd.height-y)/2; else y=pd.height-y-insets.bottom; //do layout for(int i=0;i<n;i++){ Component c=parent.getComponent(i); Dimension d=c.getPreferredSize(); int x=insets.left; int wid=d.width; if(alignment==CENTER)x=(pd.width-d.width)/2; else if(alignment==RIGHT)x=pd.width-d.width-insets.right; else if(alignment==BOTH)wid=pd.width-insets.left-insets.right; c.setBounds(x,y,wid,d.height); y+=d.height+vgap; } } }
7
public ArrayList<String> placeDotCom(int comSize) { // line 19 ArrayList<String> alphaCells = new ArrayList<String>(); String [] alphacoords = new String [comSize]; // holds 'f6' type coords String temp = null; // temporary String for concat int [] coords = new int[comSize]; // current candidate coords int attempts = 0; // current attempts counter boolean success = false; // flag = found a good location ? int location = 0; // current starting location comCount++; // nth dot com to place int incr = 1; // set horizontal increment if ((comCount % 2) == 1) { // if odd dot com (place vertically) incr = gridLength; // set vertical increment } while ( !success & attempts++ < 200 ) { // main search loop (32) location = (int) (Math.random() * gridSize); // get random starting point //System.out.print(" try " + location); int x = 0; // nth position in dotcom to place success = true; // assume success while (success && x < comSize) { // look for adjacent unused spots if (grid[location] == 0) { // if not already used coords[x++] = location; // save location location += incr; // try 'next' adjacent if (location >= gridSize){ // out of bounds - 'bottom' success = false; // failure } if (x>0 & (location % gridLength == 0)) { // out of bounds - right edge success = false; // failure } } else { // found already used location // System.out.print(" used " + location); success = false; // failure } } } // end while int x = 0; // turn good location into alpha coords int row = 0; int column = 0; // System.out.println("\n"); while (x < comSize) { grid[coords[x]] = 1; // mark master grid pts. as 'used' row = (int) (coords[x] / gridLength); // get row value column = coords[x] % gridLength; // get numeric column value temp = String.valueOf(alphabet.charAt(column)); // convert to alpha alphaCells.add(temp.concat(Integer.toString(row))); x++; // System.out.print(" coord "+x+" = " + alphaCells.get(x-1)); } // System.out.println("\n"); return alphaCells; }
8
@SuppressWarnings("unchecked") @Override public void drop(DropTargetDropEvent dtde) { Transferable trans = dtde.getTransferable(); if (isDnD(trans)) { dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); Vector<File> fileLst = new Vector<File>(); try { if (trans.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { List<File> tempLst = (List<File>) trans .getTransferData(DataFlavor.javaFileListFlavor); for (File file : tempLst) { fileLst.add(file); } } else if (trans.isDataFlavorSupported(DataFlavor.stringFlavor)) { String str = ((String) trans.getTransferData(DataFlavor.stringFlavor)) .trim(); logger.info("Drop: " + str); String sep = System.getProperty("line.seperator"); if (str.contains(sep)) { String[] strs = str.split(sep); for (String filename : strs) { fileLst.add(new File(new URI(filename.trim()))); } } else { fileLst.add(new File(new URI(str))); } } } catch (UnsupportedFlavorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } _mainCtl.updateFileLst(fileLst); } }
9
public static Date getStartOfTheDay(Date date) { String value = date2String(date, "yyyy-MM-dd 00:00:00"); return string2Date(value); }
0
public Boolean load() { FileInputStream fis = null; ObjectInputStream ois = null; try { File f = new File("abalone.save"); fis = new FileInputStream(f); ois = new ObjectInputStream(fis); Game loadedGame = (Game) ois.readObject(); this.game = new Game(loadedGame.getTurn(), loadedGame.getTimeLeft(), loadedGame.getTurnsLeft()); this.game.setHistory(loadedGame.getHistory()); this.game.setBoard(Board.getInstance()); this.game.getBoard().fill(loadedGame); AI.init(this.game, ((Boolean) Config.get("AI")) ? Color.BLACK : Color.NONE); this.currentBestMove = AI.getInstance().getBestMove(this.game.getTurn()); this.window.updateBoard(this.game.getTurn()); } catch (Exception ex) { Logger.getLogger(GameController.class.getName()).log(Level.SEVERE, null, ex); return Boolean.FALSE; } finally { try { if ( fis != null ) fis.close(); if ( ois != null ) ois.close(); } catch (IOException ex) { Logger.getLogger(GameController.class.getName()).log(Level.SEVERE, null, ex); } } this.window.updateBoard(this.game.getTurn()); return Boolean.TRUE; }
5
@Override public void insertUpdate(DocumentEvent de) { //Skip to the next TextField if input is valid and complete try { String text = de.getDocument().getText(0, de.getDocument().getLength()); int inputNumber = Integer.parseInt(text); if ((inputNumber >= 2 && inputNumber <= 15) || text.equals("01") || text.equals("00")) { KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); manager.focusNextComponent(); } } catch (NumberFormatException e) { //Do nothing } catch (BadLocationException ex) { Logger.getLogger(SubjectUI.class.getName()).log(Level.SEVERE, "Why is this happening?", ex); } }
6
private static void addFiles(File file, List<String> result, File reference) { if (!file.exists() || !file.isDirectory()) { return; } for (File child : file.listFiles()) { if (child.isDirectory()) { addFiles(child, result, reference); } else { String path = null; while (child != null && !child.equals(reference)) { if (path != null) { path = child.getName() + "/" + path; } else { path = child.getName(); } child = child.getParentFile(); } result.add(path); } } }
7
public SimpleComputer() { clearAll = new JButton("Clear All"); save = new JButton("Save"); load = new JButton("Load"); step = new JButton("Step"); run = new JButton("Run"); quickRef = new JButton("Quick Reference"); memory = new RegisterBox("Memory", 100, 20, 5); cpu = new CPU(); inputCards = new InputCards(); outputCards = new RegisterBox("Output Cards", 15, 15, 0); north = new JPanel(); west = new JPanel(); southwest = new JPanel(); //This block rearranges the registers in memory so that they are in // descending order. memory.center.removeAll(); for(int rowCount = 0; rowCount < MEM_NUM_ROWS; rowCount++) { for(int colCount = 0; colCount < MEM_NUM_COLS; colCount++) { memory.center.add (memory.registers[colCount * MEM_NUM_ROWS + rowCount]); } } memory.registers[0].setValue(1); memory.registers[0].text.setEditable(false); //Renaming the output cards to start at 1 instead of 0. for(int count = 0; count < outputCards.registers.length; count++) { outputCards.registers[count].setLabel(count + 1); } clearAll.addActionListener(new ButtonListener()); save.addActionListener(new ButtonListener()); load.addActionListener(new ButtonListener()); step.addActionListener(new ButtonListener()); run.addActionListener(new ButtonListener()); quickRef.addActionListener(new ButtonListener()); southwest.setLayout(new GridLayout(1, 2)); southwest.add(inputCards); southwest.add(outputCards); west.setLayout(new BorderLayout()); west.add(cpu, BorderLayout.NORTH); west.add(southwest, BorderLayout.SOUTH); north.setLayout(new GridLayout(2, 0)); north.add(clearAll); north.add(save); north.add(load); north.add(step); north.add(run); north.add(quickRef, BorderLayout.SOUTH); setLayout(new BorderLayout()); add(north, BorderLayout.NORTH); add(west, BorderLayout.WEST); add(memory, BorderLayout.EAST); setTitle("Simple Computer"); setSize(700, 900); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); }
3
@Override protected String toString(int indent) { String result = toString(indent, "Procedure"); // // decl // return toString(indent, "ProcedureDeclaration\n") // + procHeading.toString(indent + 1) + "\n" // + procBody.toString(indent + 1); // // head // String str = toString(indent, "ProcedureHeadingNode(" + subject + ")"); result += "( " + subject + ")\n"; // if (fparams != null) { // str += "\n" + fparams.toString(indent + 1); // } if (fparams != null) { result += "\n" + fparams.toString(indent + 1); } // return str; // // body // String str = toString(indent, "ProcedureBodyNode\n"); // if(declarations != null) // str += declarations.toString(indent+1) + "\n"; if(declarations != null) result += declarations.toString(indent+1) + "\n"; // if(statseq != null) // str += statseq.toString(indent+1) + "\n"; if(statseq != null) result += statseq.toString(indent+1) + "\n"; // return str; return result; }
3
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed try { int index = interfaceList.getSelectedIndex(); if((!model.isEmpty() || model.getElementAt(0) != "<html><i>Your order is empty</i></html>") && index >= 0) { if(model.isEmpty()) { model.addElement("<html><i>Your order is empty</i></html>");} main.result -= results.get(index); results.remove(index); model.removeElementAt(index); returnArrayListSize(); if(model.isEmpty()) { model.addElement("<html><i>Your order is empty</i></html>");} interfaceOrderPrice.setText("£" + String.format("%.2f", main.result)); if(interfaceOrderPrice.getText().contains("-")) { interfaceOrderPrice.setText("£0"); } } else { if(model.isEmpty()) { model.addElement("<html><i>Your order is empty</i></html>");} JOptionPane.showMessageDialog(null, "There are no items to remove or you have not selected an item ", "Item Remove Error", JOptionPane.ERROR_MESSAGE); } } catch(Exception e) { if(model.isEmpty()) { model.addElement("<html><i>Your order is empty</i></html>");} JOptionPane.showMessageDialog(null, "There are no items to remove or you have not selected an item ", "Item Remove Error", JOptionPane.ERROR_MESSAGE);} }//GEN-LAST:event_jButton2ActionPerformed
9
static final public void valConst() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case entier: jj_consume_token(entier); declaration.ajoutConstanteParEntier(YakaTokenManager.entierLu); break; case SUBNEG: jj_consume_token(SUBNEG); jj_consume_token(entier); declaration.ajoutConstanteParEntier(YakaTokenManager.entierLu*-1); break; case ident: jj_consume_token(ident); declaration.ajoutConstanteParConstante(YakaTokenManager.identLu); break; case VRAI: jj_consume_token(VRAI); declaration.ajoutConstanteParBooleen(-1); break; case FAUX: jj_consume_token(FAUX); declaration.ajoutConstanteParBooleen(0); break; default: jj_la1[8] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
6
public Barrillo generarGrano() { Random rand = new Random(); int x = (int) (0.28 * getWidth()) + rand.nextInt((int) (0.42 * getWidth())); int y = (int) (0.34 * getHeight()) + rand.nextInt((int) (0.55 * getHeight())); int maxAncho = rand.nextInt(20); int maxAlto = maxAncho; while (comprobarRectangulos(x, y) == true) { x = (int) (0.28 * getWidth()) + rand.nextInt((int) (0.42 * getWidth())); y = (int) (0.34 * getHeight()) + rand.nextInt((int) (0.55 * getHeight())); } Barrillo barrillo; if (rand.nextInt(100) <= 10) { barrillo = new Barrillo(x, y, "grano2", maxAncho, maxAlto, this); } else { barrillo = new Barrillo(x, y, "grano", maxAncho, maxAlto, this); } barrillos.add(barrillo); repaint(); //vuelve a pintar todos los componentes barrillo.start(); return barrillo; }
2
private int getMachineIndexBySelectedRow(JTable table){ InputTableModel model = (InputTableModel) table.getModel(); int row = table.getSelectedRow(); if(row < 0) return -1; String machineFileName = (String)model.getValueAt(row, 0); return getMachineIndexByName(machineFileName); }
1
public void valueChanged( final ListSelectionEvent e ) { if ( e.getSource() == _font_list ) { if ( _font_list.getSelectedValue() != null ) { _fonts_tf.setText( ( ( String ) ( _font_list.getSelectedValue() ) ) ); } _type = _fonts_tf.getText(); _test_tf.setFont( new Font( _type, _style, _size ) ); } else if ( e.getSource() == _style_list ) { _style_tf.setText( ( ( String ) ( _style_list.getSelectedValue() ) ) ); if ( _style_tf.getText().equals( REGULAR ) ) { _style = 0; } else if ( _style_tf.getText().equals( BOLD ) ) { _style = 1; } else if ( _style_tf.getText().equals( ITALIC ) ) { _style = 2; } else if ( _style_tf.getText().equals( BOLD_ITALIC ) ) { _style = 3; } _test_tf.setFont( new Font( _type, _style, _size ) ); } else if ( e.getSource() == _size_list ) { if ( _size_list.getSelectedValue() != null ) { _size_tf.setText( ( ( String ) ( _size_list.getSelectedValue() ) ) ); } _size = ( Integer.parseInt( _size_tf.getText().trim() ) ); _test_tf.setFont( new Font( _type, _style, _size ) ); } }
9
public Tile getTileFromVec(Vector2f v) { int x = (int) (v.getX() / Tile.size); int y = (int) (v.getY() / Tile.size); if(x < 0 || x > world.loadedMap.tileWidth - 1 || y < 0 || y > world.loadedMap.tileHeight - 1) return null; return world.tileGrid[y][x]; }
4
public static boolean isTypePage(Class<?> type) { return (type != null && isAssignable(type, Page.class)); }
2
@Override public boolean equals( Object obj ) { if( obj == this ){ return true; } if( obj == null || obj.getClass() != getClass() ){ return false; } ConnectionFlavor that = (ConnectionFlavor)obj; return that.id.equals( id ); }
3
private Direction getTurnDirection(double start, double stop) { boolean turnOverZero = false; if (Math.abs(start - stop) > 180) turnOverZero = true; if (turnOverZero && start > stop) return Direction.LEFT; else if (turnOverZero && start < stop) return Direction.RIGHT; else if (!turnOverZero && start > stop) return Direction.RIGHT; else return Direction.LEFT;// if(!turnOverZero && start < stop) }
7
public static void crearMusica(HashMap<Integer, Musica> tablaMusica) { String titulo; String formato; Scanner entrada = null; do // Validacion nombre { entrada = new Scanner(System.in); System.out.print("Titulo del disco: "); titulo = entrada.nextLine(); } while(titulo.equals("")); do // Validacion del formato { System.out.print("Formato del disco (CD/vinilo/casete): "); formato = entrada.nextLine().toLowerCase(); if (!verificaFormato(formato)) System.out.println("No se ha introducido un formato valido."); } while (!verificaFormato(formato)); Musica musica = new Musica (titulo, formato); numMusica = numMusica + 1; tablaMusica.put(numMusica, musica); // Damos de alta el disco System.out.println("Musica creada con exito con codigo " + numMusica); }
3
@Override public String lookup(String barcode) { String productDesc = ""; if(!(barcode == null || barcode.equals(""))) { try { //Max lookups per day // There are max lookup of 2500 requests per day //if(numberOfRequests < 2500) String result = ""; String finalVal = ""; result = getResultString(barcode, result); JSONParser parser = new JSONParser(); JSONObject obj = (JSONObject)parser.parse(result); if((Long)obj.get("totalItems") > 0) { JSONArray obj2 = (JSONArray)obj.get("items"); if ((Long)obj.get("totalItems") > 0) { JSONObject obj3 = (JSONObject) obj2.get(0); JSONObject finalObj = (JSONObject) obj3.get("product"); productDesc = (String) finalObj.get("title"); System.out.println("found in GoogleHandler" + productDesc); } } } catch (IOException ex) { System.err.println("Error with the Buffered Reader"+ex.getMessage()); } catch (ParseException ex) { System.out.println("No product in GoogleHandler"); } } if(productDesc.equals("") && next != null) { productDesc = next.lookup(barcode); } System.out.println("description:"+ productDesc); return productDesc; }
8
public /*@non_null@*/ int [] getSelection() { if (m_Upper == -1) { throw new RuntimeException("No upper limit has been specified for range"); } int [] selectIndices = new int [m_Upper + 1]; int numSelected = 0; if (m_Invert) { for (int i = 0; i <= m_Upper; i++) { if (!m_SelectFlags[i]) { selectIndices[numSelected++] = i; } } } else { Enumeration enu = m_RangeStrings.elements(); while (enu.hasMoreElements()) { String currentRange = (String)enu.nextElement(); int start = rangeLower(currentRange); int end = rangeUpper(currentRange); for (int i = start; (i <= m_Upper) && (i <= end); i++) { if (m_SelectFlags[i]) { selectIndices[numSelected++] = i; } } } } int [] result = new int [numSelected]; System.arraycopy(selectIndices, 0, result, 0, numSelected); return result; }
8
public synchronized Image getImage() { if (frames.size() == 0) { return null; } else { return getFrame(currentFrame).image; } }
1
@Override public String getDesc() { return "BrandishSpear"; }
0
public String createTable(DataSetDescriptor dsd) { String tableName = dsd.getTablename(); String nameGeomColumn = dsd.getGeoColumnName(); String pk = dsd.getNamePK(); List<Column> columns = dsd.getFields(); int srid = 4326; String columnsToTable = ""; String sqlCreateTable = "CREATE TABLE "; Column geoColumn = null; for(Column c: columns){ if(c.getName().equals(nameGeomColumn)){ geoColumn = new Column(); geoColumn.setName(c.getName()); geoColumn.setType(c.getType()); columns.remove(c); } } if(geoColumn == null){ geoColumn = new Column(); geoColumn.setName(nameGeomColumn); geoColumn.setType(DataBaseType.GEOMETRY); } Iterator<Column> it = columns.iterator(); Column c = (Column)it.next(); columnsToTable += c.getName() + " " + c.getType(); while(it.hasNext()){ c = (Column)it.next(); columnsToTable += ", " + c.getName() + " " + c.getType(); } sqlCreateTable = sqlCreateTable + tableName + " (" + pk + " SERIAL PRIMARY KEY, " + columnsToTable + ")"; this.simpleJdbcTemplate.execute(sqlCreateTable); // Add the geometry field into DB String sqlGeometry = "Select AddGeometryColumn ('" + tableName + "', '" + geoColumn.getName() + "', " + String.valueOf(srid) + ", '" + geoColumn.getType() + "', " + String.valueOf(2) + ")"; this.simpleJdbcTemplate.execute(sqlGeometry); return tableName; }
4
public void apply() throws XPathExpressionException { if(!input.isEnabled()) { return; } int value = Integer.parseInt(input.getText()); // sanity checks if(value < min) { throw new IllegalArgumentException("Value is " + value + ". Has to be > " + min); } if(value > max) { throw new IllegalArgumentException("Value is " + value + ". Has to be < " + max); } Element e = editor.getXMLElementByString(this.xmlPath); MessageUtil.debug("Setting element " + e.getNodeName() + " attribute "+attributeName+ " to "+value); e.setAttribute(attributeName, Integer.toString(value)); }
3
private static Node dot(Node recieverNode, Node call) { Argument reciever = recieverNode.getArgument(); if (!(call instanceof Reference)) throw new EvaluationException(call, "Can not invoke " + call); Reference ref = (Reference) call; String name = ref.getName(); Argument[] args = ref.resolveArguments(); try { Config config = recieverNode.getExpression().getConfig(); Object result = config.invoke(reciever, name, args); return (Node) Config.wrap(recieverNode, result, false); } catch (NoSuchFieldException e) { throw new EvaluationException(call, "Field '" + name + "' not found for " + reciever.getType().getName(), e); } catch (NoSuchMethodException e) { StringBuilder builder = new StringBuilder(); builder.append("Method ").append(name); builder.append('('); for (int i = 0; i < args.length; i++) { if (i > 0) builder.append(", "); builder.append(args[i].getType()); } builder.append(')'); builder.append(" not found for ").append(reciever.getType().getName()); throw new EvaluationException(call, builder.toString(), e); } catch (Exception e) { throw new EvaluationException(call, "Can not invoke " + name, e); } }
6
public static String getFilePath(File file) { if(file == null) { return null; } String path; try { path = file.getCanonicalPath(); } catch(IOException e) { path = file.getAbsolutePath(); } if(file.isFile()) { int index = -1; for(int i=path.length() - 1;i>=0;i--) { if(path.charAt(i) == '/' || path.charAt(i) == '\\') { index = i; break; } } if(index >= 0) { path = path.substring(0, index + 1); } } if(path.charAt(path.length() - 1) != '/' && path.charAt(path.length() - 1) != '\\') { path += System.getProperty("file.separator"); } return path; }
9
public static int partition2(int[] records, int low, int high){ if(low > records.length - 1|| high > records.length - 1) { throw new IllegalArgumentException(); } int pivot = records[low]; while(low < high){ while (records[high] > pivot && low < high){ high--; } records[low] = records[high]; while (records[low] < pivot && low < high){ low++; } records[high] = records[low]; } records[low] = pivot; return low; }
7
private static void test7() throws FileNotFoundException { //Test winning by waiting for the guard to pass String input = "new\n" + "pick up key\n" + "wait\n" + "unlock door with key\n" + "go through cell door\n" + "quit\n" + "y\n"; HashMap<Integer, String> output = new HashMap<Integer, String>(); boolean passed = true; try { in = new ByteArrayInputStream(input.getBytes()); System.setIn(in); out = new PrintStream("testing.txt"); System.setOut(out); Game.main(null); } catch (ExitException se) { } catch (Exception e) { System.setOut(stdout); System.out.println("Error: "); e.printStackTrace(); passed = false; } finally { System.setOut(stdout); @SuppressWarnings("resource") Scanner sc = new Scanner(new File("testing.txt")); ArrayList<String> testOutput = new ArrayList<String>(); while (sc.hasNextLine()) { testOutput.add(sc.nextLine()); } //The expected output for specific lines output.put(13,"The guard walks toward your cell."); output.put(14,">> Some time goes by."); output.put(15,"The guard peers into the cell, checking that the door is secured, then continues on."); output.put(18,">> You walk through the cell door."); output.put(21,"The guard walks away from your cell."); output.put(22,"You escape silently into the shadows."); output.put(23,"YOU WON!"); output.put(testOutput.size() - 1, ">>"); if (passed) { for (Map.Entry<Integer, String> entry : output.entrySet()) { if (!testOutput.get(entry.getKey()) .equals(entry.getValue())) { passed = false; System.out.println("test7 failed: Line " + entry.getKey()); System.out.println("\tExpected: " + entry.getValue()); System.out.println("\tReceived: " + testOutput.get(entry.getKey())); } } if (passed) { System.out.println("test7 passed"); } } else { System.out.println("test7 failed: error"); } } }
7
public void desconectarBaseDeDatos(){ //metodo de desconexion try{ if(conexion !=null){ if (sentencia !=null){ //si la conexion devuelve valores nulos sentencia.close(); } conexion.close(); } } catch (SQLException ex){ } }
3
public static String longestCommonPrefix(String[] strs){ int i = 0; int minLength = Integer.MAX_VALUE; if(strs == null || strs.length == 0) return ""; for(String str : strs){ if(str.length() < minLength) minLength = str.length(); } char[] chs = new char[minLength]; while(true) { char c = ' '; for(String str : strs) { if(i < str.length()){ if(c == ' '){ c = str.charAt(i); }else if(str.charAt(i) != c){ return new String(chs, 0, i); } }else return new String(chs,0,i); } chs[i++] = c; } }
9
static String[] sort(String[] input){ String temp; int left=0; int right=0; for(int i=1; i<input.length;i++){ left=0; right=i-1; while(left<right){ int mid=(left+right)/2; if(input[mid].compareTo(input[i])>0){ right=mid-1; }else{ left=mid +1; } } temp =input[i]; if(input[left].compareTo(temp)>0){ for(int j=i;j>left;j--){ input[j]=input[j-1]; } input[left]=temp; }else{ for(int j=i;j>left+1;j--){ input[j]=input[j-1]; } input[left+1]=temp; } for(int k=0; k<input.length;k++) System.out.print(input[k]+","); System.out.println(); } return input; }
7
public static void swap(List<Character> list, int i, int j) { Character temp = list.get(i); list.set(i, list.get(j)); list.set(j, temp); }
0
public static RunData loadFromFile(File file) throws XMLParsingExeption, ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); // Get all circles NodeList circles = doc.getElementsByTagName(CustomNode.Circle.getTagName()); List<Circle> loadedCircles = new ArrayList<Circle>(); for(int i = 0; i < circles.getLength(); i++) { Element circleElement = (Element) circles.item(i); NodeList idNL = circleElement.getElementsByTagName(CustomNode.Id.getTagName()); NodeList heightNL = circleElement.getElementsByTagName(CustomNode.Height.getTagName()); if(idNL.getLength() != 1 || heightNL.getLength() != 1) throw new CustomExceptions.XMLParsingExeption("Invalid id or height value for for circle " + (i+1)); int id = Integer.valueOf(idNL.item(0).getFirstChild().getNodeValue()); double height = Double.valueOf(heightNL.item(0).getFirstChild().getNodeValue()); int y = (int) Utils.convert(height * MainWindow._scaleFactor, Utils.UNIT.MM, Utils.UNIT.CM); loadedCircles.add(new Circle(y, id)); } System.out.println("Loaded data from file " + file.getAbsolutePath() + " (" + loadedCircles.size() + " circles)"); return new RunData(loadedCircles.toArray(new Circle[0])); }
3
@Override public void mouseClicked(final MouseEvent e) { this.e = e; player.setActivityTimer(1000); //if(player.getActivityTimer()==0){ new Thread(new Runnable(){ @Override public void run() { BarOverlay overlay = (BarOverlay)((JLabel) e.getSource()).getParent(); overlay.progress.setVisible(true); overlay.progressText.setVisible(true); overlay.close.setVisible(false); while(player.getActivityTimer()>0) { // System.out.println("Event"+player.getActivityTimer()); switch(player.getActivityTimer()*5/1000) { case 3: overlay.progress.setIcon(new ImageIcon(overlay.graphicManager.progress1.getImage())); break; case 2: overlay.progress.setIcon(new ImageIcon(overlay.graphicManager.progress2.getImage())); break; case 1: overlay.progress.setIcon(new ImageIcon(overlay.graphicManager.progress3.getImage())); break; case 0: overlay.progress.setIcon(new ImageIcon(overlay.graphicManager.progress4.getImage())); } try { Thread.sleep(40); } catch (InterruptedException e1) {} } DiscoObject.setStatusES(player, action); ((JLabel) e.getSource()).getParent().setVisible(false); ((JLabel) e.getSource()).getParent().setEnabled(false); disableActions(); player.setActivity(0); // Reset overlay.progress.setIcon(new ImageIcon(overlay.graphicManager.progress0.getImage())); overlay.progress.setVisible(false); overlay.progressText.setVisible(false); overlay.close.setVisible(true); ((JLabel) e.getSource()).setIcon(i); } }).start();; //} }
6
public static void loadScripts() throws IOException { System.out.println("Loading scripts..."); ScriptManager.python.cleanup(); File scriptDir = new File("./Data/scripts/"); if (scriptDir.isDirectory() && !scriptDir.getName().startsWith(".")) { File[] children = scriptDir.listFiles(); for (File child : children) if (child.isFile()) { if (child.getName().endsWith(".py")) { System.out.println("\tLoading script: " + child.getPath()); ScriptManager.python .execfile(new FileInputStream(child)); ScriptManager.scriptsLoaded++; } } else ScriptManager.recurse(child.getPath()); } System.out.println("Loaded " + ScriptManager.scriptsLoaded + " scripts!"); ScriptManager.scriptsLoaded = 0; }
5
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * Servlet näyttää käyttäjälle hänen tekemänsä tilauksen, jonka tiedot * haetaan tietokannasta. Aluksi varmistetaan, ettei käyttäjä saa * virheilmoitusta jos hän päivittää sivun sen jälkeen kun tilaussessio * on jo mitätöity. */ if (request.getSession().getAttribute("tilausID") == null) { // Ohjataan käyttäjä palvelun etusivulle. response.sendRedirect("index"); } else { // Alustetaan Tilaus-luokan olio. Tilaus tilaus = new Tilaus(); // Otetaan vastaan tilauksen ID-numero. int tilausID = (Integer) request.getSession().getAttribute( "tilausID"); // Haetaan tietokannasta tilauksen kaikki tiedot sen ID-numerolla. try { TilausDAO tilDao = new TilausDAO(); tilaus = tilDao.haeTilauksenTiedot(tilausID); } catch (DAOPoikkeus e) { // Virheen sattuessa heitetään poikkeus ruudulle. throw new ServletException(e); } catch (SQLException e) { e.printStackTrace(); } // Muokataan tilausaika fiksumpaan muotoon. SimpleDateFormat pvm = new SimpleDateFormat("d.M.yyyy"); SimpleDateFormat aika = new SimpleDateFormat("HH:mm"); String tilauspvm = pvm.format(tilaus.getTilausAika()); String tilausaika = aika.format(tilaus.getTilausAika()); System.out.println(tilaus.getMaksutapaId()); System.out.println(tilaus.getToimitustapaId()); // Asetetaan tilaustiedot ja -aika attribuutiksi: request.setAttribute("tilaus", tilaus); request.setAttribute("tilauspvm", tilauspvm); request.setAttribute("tilausaika", tilausaika); // JSP-sivu muotoilee. request.getRequestDispatcher("tilausvahvistus.jsp").forward( request, response); // Mitätöidään lopuksi sessio, koska sitä ei enää tarvita. request.getSession().invalidate(); } }
3
public String toString(String input) { return name; }
0
public int addRun(int start, int length, T font) { int end = start + length - 1; RunArrayEntry newEntry = new RunArrayEntry(start, end, font); if (runArray.size() == 0) { // Empty runArray runArray.add(newEntry); return 0; } // Find position of new entry int previousEntryIdx = -1; int nextEntryIdx = -1; List<Integer> toDeleteList = new LinkedList<Integer>(); for (int i = 0; i < runArray.size(); i++) { if (runArray.get(i).startIdx < start) { // New entry start index falls into the existing entry. Record // this entry previousEntryIdx = i; } else if (runArray.get(i).endIdx <= end) { // Entry within start and end range will be overwritten toDeleteList.add(i); } if (runArray.get(i).endIdx > end) { // New entry end index falls into the existing entry. Record // this entry nextEntryIdx = i; break; } } if (previousEntryIdx != -1) { // Previous entry's end index needs update runArray.get(previousEntryIdx).setEndIdx(start - 1); } if (nextEntryIdx != -1) { // Next entry's start index needs update runArray.get(nextEntryIdx).setStartIdx(end + 1); } for (int i = toDeleteList.size() - 1; i >= 0; i--) { runArray.remove(toDeleteList.get(i)); } // Insert new entry behind previous entry runArray.add(previousEntryIdx + 1, newEntry); return previousEntryIdx + 1; }
8
public static Question getQuestionData(int QDbId) { try { Question q = new Question(); String qstatement = String.format("Select * from question where questionid = %d", QDbId); ResultSet qrs = getQueryResults(qstatement); if (qrs.next()) { q.questionText = qrs.getString("QuestionText"); q.dbId = qrs.getInt("QuestionID"); q.AuthorId = qrs.getInt("AuthorID"); q.isValidated = qrs.getBoolean("ISVALIDATED"); q.isRejected = qrs.getBoolean("ISREJECTED"); } String astatement = String.format("Select * from questionanswer where questionid = %d", QDbId); ResultSet ars = getQueryResults(astatement); while(ars.next()) { String atext = ars.getString("ANSWERTEXT"); boolean IsCorrect = ars.getBoolean("ISCORRECT"); int AnswerId = ars.getInt("ANSWERID"); q.answers.add(new Answer(atext, IsCorrect, AnswerId)); } return q; } catch (SQLException ex) { return null; } catch (Exception e) { return null; } }
4
private int maximalSquareLengthFromPoint(char matrix[][], int row, int column) { String areaLookupKey = String.valueOf(row)+","+String.valueOf(column); if (areaLookup.containsKey(areaLookupKey)) { return areaLookup.get(areaLookupKey); } if (matrix[row][column] == '0') { return 0; } if (row == matrix.length-1 || column == matrix[0].length-1) { return Character.getNumericValue(matrix[row][column]); } if (matrix[row][column+1] == 0 || matrix[row+1][column+1] == 0 || matrix[row+1][column] == 0) { return 0; } // compute areas of adjoining maximalSquares int area1 = maximalSquareLengthFromPoint(matrix, row, column + 1); int area2 = maximalSquareLengthFromPoint(matrix, row + 1, column + 1); int area3 = maximalSquareLengthFromPoint(matrix, row + 1, column); // maximalSquareLengthFromPoint starting with matrix[i][j]? int areas[] = new int[]{area1, area2, area3}; Arrays.sort(areas); areaLookup.put(areaLookupKey, areas[0]+1); return areas[0]+1; }
7
public void logisticProbabilityPlot(){ this.lastMethod = 8; // Check for suffient data points this.logisticNumberOfParameters = 2; if(this.numberOfDataPoints<3)throw new IllegalArgumentException("There must be at least three data points - preferably considerably more"); // Create instance of Regression Regression min = new Regression(this.sortedData, this.sortedData); double muest = mean; if(muest==0.0)muest = this.standardDeviation/3.0; double betaest = this.standardDeviation; double[] start = {muest, betaest}; this.initialEstimates = start; double[] step = {0.3*muest, 0.3*betaest}; double tolerance = 1e-10; // Add constraint; beta>0 min.addConstraint(1, -1, 0); // Create an instance of LogisticProbPlotFunc LogisticProbPlotFunc lppf = new LogisticProbPlotFunc(); lppf.setDataArray(this.numberOfDataPoints); // Obtain best probability plot varying mu and sigma // by minimizing the sum of squares of the differences between the ordered data and the ordered statistic medians min.simplex(lppf, start, step, tolerance); // Get mu and beta for best correlation coefficient this.logisticParam = min.getBestEstimates(); // Get mu and beta errors for best correlation coefficient this.logisticParamErrors = min.getBestEstimatesErrors(); // Get sum of squares this.logisticSumOfSquares = min.getSumOfSquares(); // Calculate Logistic order statistic medians this.logisticOrderMedians = Stat.logisticOrderStatisticMedians(this.logisticParam[0], this.logisticParam[1], this.numberOfDataPoints); // Regression of the ordered data on the Logistic order statistic medians Regression reg = new Regression(this.logisticOrderMedians, this.sortedData); reg.linear(); // Intercept and gradient of best fit straight line this.logisticLine = reg.getBestEstimates(); // Estimated erors of the intercept and gradient of best fit straight line this.logisticLineErrors = reg.getBestEstimatesErrors(); // Correlation coefficient this.logisticCorrCoeff = reg.getSampleR(); // Initialize data arrays for plotting double[][] data = PlotGraph.data(2,this.numberOfDataPoints); // Assign data to plotting arrays data[0] = this.logisticOrderMedians; data[1] = this.sortedData; data[2] = logisticOrderMedians; for(int i=0; i<this.numberOfDataPoints; i++){ data[3][i] = this.logisticLine[0] + this.logisticLine[1]*logisticOrderMedians[i]; } // Create instance of PlotGraph PlotGraph pg = new PlotGraph(data); int[] points = {4, 0}; pg.setPoint(points); int[] lines = {0, 3}; pg.setLine(lines); pg.setXaxisLegend("Logistic Order Statistic Medians"); pg.setYaxisLegend("Ordered Data Values"); pg.setGraphTitle("Logistic probability plot: gradient = " + Fmath.truncate(this.logisticLine[1], 4) + ", intercept = " + Fmath.truncate(this.logisticLine[0], 4) + ", R = " + Fmath.truncate(this.logisticCorrCoeff, 4)); pg.setGraphTitle2(" mu = " + Fmath.truncate(this.logisticParam[0], 4) + ", beta = " + Fmath.truncate(this.logisticParam[1], 4)); // Plot pg.plot(); this.logisticDone = true; this.probPlotDone = true; }
3
final void method737(AbstractToolkit var_ha, int i, int i_32_, int i_33_, int i_34_, int i_35_, int i_36_) { if (aClass105_1221 != null) { int i_37_ = anInt1231 - i_35_ & 0x3fff; int i_38_ = anInt1219 - i_36_ & 0x3fff; if (i_38_ > 8192) i_38_ -= 16384; if (i_37_ > 8192) i_37_ -= 16384; int i_39_ = i_37_ * i_34_ / 4096 + (i_34_ - anInt1217) / 2; int i_40_ = i_38_ * i_34_ / -4096 + (i_33_ - anInt1217) / 2; if (i_39_ < i_34_ && i_39_ + anInt1217 > 0 && i_40_ < i_33_ && i_40_ + anInt1217 > 0) aClass105_1221.method973(i_40_ + i, i_39_ + i_32_, anInt1217, anInt1217); } }
7
public void setScreenX(int screenX) { this.screenX = screenX; }
0
private void removeFoundNode(TreeNode removingNode) { TreeNode parentNode; if (removingNode.left == null || removingNode.right == null) { parentNode = removingNode; } else { parentNode = successor(removingNode); removingNode.key = parentNode.key; } TreeNode childNode; if (parentNode.left != null) { childNode = parentNode.left; } else { childNode = parentNode.right; } if (childNode != null) { childNode.parent = parentNode.parent; } if (parentNode.parent == null) { this.root = childNode; } else { if (parentNode == parentNode.parent.left) { parentNode.parent.left = childNode; } else { parentNode.parent.right = childNode; } recursiveBalance(parentNode.parent); } parentNode = null; }
6
public int readBits(int numBits) { if (numBits < 1 || numBits > 32) { throw new IllegalArgumentException(); } int result = 0; // First, read remainder from current byte if (bitOffset > 0) { int bitsLeft = 8 - bitOffset; int toRead = numBits < bitsLeft ? numBits : bitsLeft; int bitsToNotRead = bitsLeft - toRead; int mask = (0xFF >> (8 - toRead)) << bitsToNotRead; result = (bytes[byteOffset] & mask) >> bitsToNotRead; numBits -= toRead; bitOffset += toRead; if (bitOffset == 8) { bitOffset = 0; byteOffset++; } } // Next read whole bytes if (numBits > 0) { while (numBits >= 8) { result = (result << 8) | (bytes[byteOffset] & 0xFF); byteOffset++; numBits -= 8; } // Finally read a partial byte if (numBits > 0) { int bitsToNotRead = 8 - numBits; int mask = (0xFF >> bitsToNotRead) << bitsToNotRead; result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead); bitOffset += numBits; } } return result; }
8
public void execute(String statement) { try{ Statement stat; stat=this.conn.createStatement(); stat.execute(statement); }catch(SQLException e) { e.printStackTrace(); } }
1