text
stringlengths
14
410k
label
int32
0
9
public void playGame() { boolean isAlive = true; printWelcome(); printHelp(); while (!game.hasWon() && isAlive) { printScreen(); System.out.println("Cheese collected: " + game.getCheeseCount() + " of 5"); Coordinate move; do { move = resolveInput(getInput()); } while (!game.validMove(move)); game.moveMouse(move); if (game.hasLost()) { isAlive = false; break; } game.moveCats(); if (game.hasLost()) { isAlive = false; } } printScreen(); if (game.hasWon()) { printWin(); } else { printDeath(); } }
6
@Override public Item swap(Item newItem) { Item temp = null; try{ temp = armorItem; armorItem = null; armorItem = (BodyArmor) newItem; return temp; }catch(Exception e){ armorItem = (BodyArmor) temp; // swap fail, return to original return newItem; } }
1
private int ParseGameState(String s) { planets.clear(); fleets.clear(); int planetID = 0; String[] lines = s.split("\n"); for (int i = 0; i < lines.length; ++i) { String line = lines[i]; int commentBegin = line.indexOf('#'); if (commentBegin >= 0) { line = line.substring(0, commentBegin); } if (line.trim().length() == 0) { continue; } String[] tokens = line.split(" "); if (tokens.length == 0) { continue; } if (tokens[0].equals("P")) { if (tokens.length != 6) { return 0; } double x = Double.parseDouble(tokens[1]); double y = Double.parseDouble(tokens[2]); int owner = Integer.parseInt(tokens[3]); int numShips = Integer.parseInt(tokens[4]); int growthRate = Integer.parseInt(tokens[5]); Planet p = new Planet(planetID++, owner, numShips, growthRate, x, y); planets.add(p); } else if (tokens[0].equals("F")) { if (tokens.length != 7) { return 0; } int owner = Integer.parseInt(tokens[1]); int numShips = Integer.parseInt(tokens[2]); int source = Integer.parseInt(tokens[3]); int destination = Integer.parseInt(tokens[4]); int totalTripLength = Integer.parseInt(tokens[5]); int turnsRemaining = Integer.parseInt(tokens[6]); Fleet f = new Fleet(owner, numShips, source, destination, totalTripLength, turnsRemaining); fleets.add(f); } else { return 0; } } return 1; }
8
@Override protected Event doExecute(RequestContext req) throws Exception { boolean rslt = true; SecurityChallenge challenge = (SecurityChallenge) req.getFlowScope().get(LookupSecurityQuestionAction.SECURITY_CHALLENGE_ATTRIBUTE); if (challenge != null) { List<SecurityQuestion> questions = challenge.getQuestions(); for (int i=0; i < questions.size(); i++) { String responseText = req.getRequestParameters().get(RESPONSE_PARAMETER_PREFIX + i); if (!questions.get(i).validateResponse(responseText)) { rslt = false; break; } } } else { rslt = false; // Should not get here... } if (!rslt) { lockoutService.registerIncorrectAttempt((String)req.getFlowScope().get("username")); } return rslt ? success() : error(/* TODO: Send error message to client */); }
5
public boolean AddUser(String PlayerName, Location loc, ArrayList<String> players, String Mod){ File file = new File(getDataFolder(),"Plates.prop"); if(PlayerName == null || loc == null || players.isEmpty() || Mod == null){ return false; } String string = PlayerName +":"+loc.getWorld().getName()+","+ loc.getBlockX()+"," + loc.getBlockY()+","+loc.getBlockZ()+"="+Mod+"="+players.toString()+""; if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { } } boolean DidWrite = logMessage(file,string); return DidWrite; }
6
public void filtrarContratos() { try { String filtro = panelInformacion.getTextoFiltro(); int tipoFiltro = panelInformacion.getTipoFiltro(); if(!filtro.trim().equals("")) { if(tipoFiltro == Contrato.FILTRO_ID_DUENIO || tipoFiltro == Contrato.FILTRO_ID_HABITANTE || tipoFiltro == Contrato.FILTRO_ID_RESPONSABLE) { long id = Long.parseLong(filtro); ArrayList<Contrato> lista = Contrato.getListaContratosFiltro(Contrato.CONTRATOS_ACTIVOS, tipoFiltro, id, ""); panelInformacion.setListaContratos(lista); } else if(tipoFiltro == Contrato.FILTRO_ID_APARTAMENTO || tipoFiltro == Contrato.FILTRO_NOMBRE_DUENIO || tipoFiltro == Contrato.FILTRO_NOMBRE_HABITANTE || tipoFiltro == Contrato.FILTRO_NOMBRE_RESPONSABLE ) { ArrayList<Contrato> lista = Contrato.getListaContratosFiltro(Contrato.CONTRATOS_ACTIVOS, tipoFiltro, -1, filtro); panelInformacion.setListaContratos(lista); } } } catch(NumberFormatException ex) { JOptionPane.showMessageDialog(panelInformacion, "Error numérico al buscar por el número de id", "Error numérico",JOptionPane.ERROR_MESSAGE); } }
9
@Override public void setPhone(String phone) { super.setPhone(phone); }
0
@Override public int compare(AndroidMethod m1, AndroidMethod m2) { if(m1.getCategory() == null && m2.getCategory() == null) return 0; else if(m1.getCategory() == null) return 1; else if(m2.getCategory() == null) return -1; else return m1.getCategory().compareTo(m2.getCategory()); }
4
public boolean isPrime(int num) { for (int i = 2; i < num; i++) { if (num % i == 0) { return false; } } return true; }
2
public void test_DateTime_withHourZero_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); try { dt.withHourOfDay(0); fail(); } catch (IllegalFieldValueException ex) { // expected } }
1
public static boolean extract(LauncherAPI api, GameFile source, File dest, int min, int max, boolean recursive) throws Exception { final String[] exts = source.getFileName() .substring(source.getFileName().indexOf('.', 0) + 1) .split("\\."); File file = source.getFile(); for (int i = exts.length - 1; i > -1; i--) { final String ext = exts[i]; boolean pass = false; if (ext.equalsIgnoreCase("lzma")) { file = extractLZMA(api, source, file, dest, min, max); } if (ext.equalsIgnoreCase("zip")) { extractZIP(api, source, file, dest, min, max); pass = true; } if (ext.equalsIgnoreCase("jar")) { extractJAR(api, source, file, dest, min, max); pass = true; } if (!recursive || pass) { i = -1; } } return false; }
6
String codons() { char seq[] = chromoSequence.toCharArray(); char seqNew[] = chromoNewSequence.toCharArray(); codonsOld = ""; codonsNew = ""; int codonIdx = 0; int i = 0; int step = transcript.isStrandPlus() ? 1 : -1; char codonOld[] = new char[3]; char codonNew[] = new char[3]; for (Exon ex : transcript.sortedStrand()) { int start = ex.isStrandPlus() ? ex.getStart() : ex.getEnd(); for (i = start; ex.intersects(i); i += step, codonIdx = (codonIdx + 1) % 3) { codonOld[codonIdx] = seq[i]; codonNew[codonIdx] = seqNew[i]; if (codonIdx == 2) addIfDiff(codonOld, codonNew); } } for (; codonIdx != 0; i += step, codonIdx = (codonIdx + 1) % 3) { codonOld[codonIdx] = 'N'; codonNew[codonIdx] = 'N'; if (codonIdx == 2) addIfDiff(codonOld, codonNew); } return codonsOld + "/" + codonsNew; }
7
private void deleteData() { if(model.getRowCount() == 0) { // 削除するものがなければ抜ける return; } // 警告ダイアログ int opt = Dialogs.showQuestionDialog("本当に削除しますか?", ""); if(opt != Dialogs.OK_OPTION) { // OK が選択されなければ何もしない return; } // 現在行を削除 model.removeRow(nowDataRow); // 削除された行の次にあたる行を表示する // 最終行を削除した場合、IndexOutOfBoundsするので、 // 右辺の(nowDataRow - 1)を実行する。 // &&演算子は、左辺がfalseだった場合、右辺は実行されない。 if(!showData(nowDataRow) && !showData(nowDataRow - 1)) { // 削除したのちテーブルが空なら、テキストフィールドを編集不可にする。 for (JTextField text : textFields) { text.setEditable(false); text.setText(""); } } textEdited = false; }
5
public boolean left() { for(boolean[] position : emplacement.getCoordoneeJeu()) if(position[0] == true) return false; for(boolean[] position : emplacement.getCoordoneeJeu()) for(int x=0; x<emplacement.getNombreColonne(); x++) if (position[x] == true){ position[x] = false; position[x-1]= true; } return true; }
5
public boolean validate() throws IllegalStateException { if(populationSize<parentSize){ throw new IllegalStateException("Liczba populacji mniejsza od liczby rodziców"); } if(populationSize==0||parentSize==0){ throw new IllegalStateException("Liczba populacji lub rodziców wynosi 0"); } if(mutationProbability<0||crossOverProbability<0){ throw new IllegalStateException("Prawdopodobieństwo mutacji lub krzyżowania mniejsze niż 0%"); } if(maxIterations<=1){ throw new IllegalStateException("Liczba iteracji za mała (co najmniej 1)"); } return true; }
6
@Override public void save() { try { saveFile.createNewFile(); fo = new FileOutputStream(saveFile); JAXB.marshal(dataholder, fo); } catch (FileNotFoundException e) { } catch (IOException e) { } }
2
public static ParseResult parseXmlAttribute( char[] chars, int offset ) throws XMLParseException { offset = skipWhitespace(chars, offset); switch( chars[offset] ) { case( '>' ): case( '/' ): return new ParseResult(null, offset); } ParseResult nameParseResult = parseXmlText(chars, offset, '='); String name = (String)nameParseResult.value; offset = nameParseResult.newOffset; if( chars[offset++] != '=' ) throw new XMLParseException("Expected '=' but found '" + chars[offset] + "' while parsing XML attribute"); if( chars[offset++] != '"' ) throw new XMLParseException("Expected '\"' but found '" + chars[offset] + "' while parsing XML attribute value opening"); ParseResult valueParseResult = parseXmlText(chars, offset, '"'); String value = (String)valueParseResult.value; offset = valueParseResult.newOffset; if( chars[offset++] != '"' ) throw new XMLParseException("Expected '\"' but found '" + chars[offset] + "' while parsing XML attribute value closing"); return new ParseResult( new XMLAttribute(name, value), offset ); }
5
public boolean hasNext() { if(empty) return false; // first check if current data block can be read for next if(bedFeatureIndex < bedFeatureList.size()) return true; // need to fetch next data block else if(leafItemIndex < leafHitList.size()) return true; else return false; }
3
public static void main(String[] args) { Scanner inputType = new Scanner(System.in); while (true) { try { TypeTable table = new TypeTable("table.csv"); System.out.println("***************************************"); System.out.println("Please enter the desired type (no caps),"); System.out.println("seperate dual types with a comma and NO"); System.out.println("space."); System.out.println("ex: type1,type2"); System.out.println("Type done to exit the program."); System.out.println("***************************************"); System.out.println(""); String type = inputType.next(); String[] types = type.split(","); if (type.equals("done") || type.equals("Done")) { System.out.println("Thank you for using this program!"); break; } if (types.length == 1) { table.find(types[0], "none"); } if (types.length == 2) { table.find(types[0], types[1]); } if (types.length > 2) { System.out.println(""); System.out.println("***************************************"); System.out.println("Sorry this program only supports up to a"); System.out.println("maximum combination of 2 types."); System.out.println("Please try again."); } } catch (IOException | NullPointerException e) { System.out.println(""); System.out.println("***************************************"); System.out.println("Sorry the program has encountered an"); System.out.println("error, please check the text file to"); System.out.println("ensure it has the proper file name"); System.out.println("(table.txt), exists/is in the same folder"); System.out.println("as the program, and that its contents are"); System.out.println("formatted correctly (top row and leftmost"); System.out.println("column are the types, all the values are"); System.out.println("seperated with commas (no spaces), and the"); System.out.println("top corner is an blank space)."); System.out.println("***************************************"); break; } } }
7
private void pop(char c) throws JSONException { if (this.top <= 0) { throw new JSONException("Nesting error."); } char m = this.stack[this.top - 1] == null ? 'a' : 'k'; if (m != c) { throw new JSONException("Nesting error."); } this.top -= 1; this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; }
5
public int numDistinct(String S, String T) { // Start typing your Java solution below // DO NOT write main() function int m = S.length(); int n = T.length(); if (n == 0 || m < n) return 0; int[][] res = new int[n + 1][m + 1]; for (int i = m; i >= 0; i--) res[n][i] = 1; // 额外初始化一层,方便统一处理 for (int i = n - 1; i >= 0; i--) { // 每次往前多匹配 T 的一个字符 char x = T.charAt(i); for (int j = m + i - n; j >= 0; j--) { res[i][j] = res[i][j + 1]; if (S.charAt(j) == x) { res[i][j] += res[i + 1][j + 1]; // 能增加这么多种可能 } } } return res[0][0]; }
6
private void firstBeepers() { if (facingEast()) { if (rightIsClear()) { turnRight(); move(); if (noBeepersPresent()) { turnAround(); move(); putBeeper(); turnRight(); } else { turnAround(); move(); turnRight(); } } } else { turnLeft(); move(); if (noBeepersPresent()) { turnAround(); move(); putBeeper(); turnLeft(); } else { turnAround(); move(); turnLeft(); } } }
4
public float getDistanceBetween(Node node1, Node node2) { // if the nodes are on top or next to each other, return 1 if (node1.getX() == node2.getX() || node1.getY() == node2.getY()) return 1 * (mapHeight + mapWith); else return (float) 1.7 * (mapHeight + mapWith); }
2
static Set<Point> getCirclePoints(int r, int cx, int cy) { Set<Point> points = new HashSet<Point>(); points.add(new Point(cx + r, cy)); points.add(new Point(cx - r, cy)); points.add(new Point(cx, cy + r)); points.add(new Point(cx, cy - r)); int y = r; for(int x = 1; x <= y; ++x) { y = (int) Math.round(Math.sqrt(Math.pow(r, 2) - Math.pow(x, 2))); points.add(new Point(cx + x, cy + y)); points.add(new Point(cx + x, cy - y)); points.add(new Point(cx - x, cy + y)); points.add(new Point(cx - x, cy - y)); points.add(new Point(cx + y, cy + x)); points.add(new Point(cx + y, cy - x)); points.add(new Point(cx - y, cy + x)); points.add(new Point(cx - y, cy - x)); } return points; }
1
private void openHttpsPostConnection(final String urlStr, final byte[] data, final int sampleRate) { new Thread () { public void run() { HttpsURLConnection httpConn = null; ByteBuffer buff = ByteBuffer.wrap(data); byte[] destdata = new byte[2048]; int resCode = -1; OutputStream out = null; try { URL url = new URL(urlStr); URLConnection urlConn = url.openConnection(); if (!(urlConn instanceof HttpsURLConnection)) { throw new IOException ("URL must be HTTPS"); } httpConn = (HttpsURLConnection)urlConn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setChunkedStreamingMode(0); //TransferType: chunked httpConn.setRequestProperty("Content-Type", "audio/x-flac; rate=" + sampleRate); // this opens a connection, then sends POST & headers. out = httpConn.getOutputStream(); //beyond 15 sec duration just simply writing the file // does not seem to work. So buffer it and delay to simulate // bufferd microphone delivering stream of speech // re: net.http.ChunkedOutputStream.java while(buff.remaining() >= destdata.length){ buff.get(destdata); out.write(destdata); }; byte[] lastr = new byte[buff.remaining()]; buff.get(lastr, 0, lastr.length); out.write(lastr); out.close(); if(resCode >= HttpURLConnection.HTTP_UNAUTHORIZED){//Stops here if Google doesn't like us/ throw new HTTPException(HttpURLConnection.HTTP_UNAUTHORIZED);//Throws } String line;//Each line that is read back from Google. BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); while ((line = br.readLine( )) != null) { GoogleResponse gr = null; if(line.length()>19 && resCode > 100 && resCode < HttpURLConnection.HTTP_UNAUTHORIZED){ gr = new GoogleResponse(); parseResponse(line, gr); } fireResponseEvent(gr); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally {httpConn.disconnect();} } }.start(); }
9
public static void main(String[] args) { setCloseTime(Calendar.getInstance()); setOpenTime(Calendar.getInstance()); //** Setup the members with gender and homeclub for(int i=0;i<max_members;i++){ mp.put(i,new Member(i, getGender(), getClub(null))); } System.out.println("Generating stats... "); //mp.get(1) + "\n" + mp.get(5)); //** setup the access starts from 2years back to now. Calendar calnow = Calendar.getInstance(); Calendar calstart = Calendar.getInstance(); calstart.add(Calendar.YEAR, -2); while(calnow.compareTo(calstart) > 0){ //** work out and offset int num_offset = getMemberEntryCountLimit(calstart); num_offset *= Math.ceil(NUM_OF_CLUBS/1); //** Generate random number of entries int num_members = new Random().nextInt(num_offset); //System.out.print("Entry Count: " + num_members + ") [" + calstart.get(Calendar.HOUR_OF_DAY) + "] "); //printDate(calstart.getTime()); for(int i=0;i<num_members;i++){ calstart.add(Calendar.MILLISECOND, ENTRY_SWIPE_PERIOD); // get the member randomly int pos = new Random().nextInt(max_members); if (pos % 7 == 0 | pos % 11 == 0 | pos % 13 == 0 | pos % 15 == 0 | pos % 17 == 0 | pos % 19 == 0) Math.min(num_members, pos++); Member m = mp.get(pos); //create entry and compute exit time entrystats.add(new StatsEntry(DateStr(calstart),getExitTime(calstart),getClub(m),m.homeclub,m.gender,m.idno)); } nextDateTime(calstart); } //print the stats try { boolean tosql = true; System.out.println("Stats count: " + entrystats.size()); if(tosql){ MySQLAccess dao = new MySQLAccess(); System.out.println("Deleting old stats from MySQL..."); dao.clearAccessStats(); System.out.println("Inserting data into MySQL..."); for(StatsEntry s:entrystats){ dao.insertAccessStat(s); } dao.close(); }else{ FileWriter file = new FileWriter("c:\\stats.csv"); file.write(StatsEntry.headers()); for(StatsEntry s:entrystats){ file.write(s.toCsvString()); } file.flush(); file.close(); } } catch (IOException e) { e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // StringBuilder stats = new StringBuilder(); // stats.append(StatsEntry.headers()); // for(StatsEntry s:entrystats){ // stats.append(s.toCsvString()); // } // writeToFile(stats.toString(), "c:\\stats.csv"); System.out.println("Stats count: " + entrystats.size()); } //end main
9
protected void onOk() { try { iteracoes = Integer.parseInt(txtIterations.getText()); } catch (NumberFormatException e) { iteracoes = 0; } if (iteracoes < 1) { JOptionPane.showMessageDialog(this, "You must define at least one interaction!"); return; } if (getRdbtnCross().isSelected()) selected = StructuringElement.CROSS; else if (getRdbtnHorizontalLine().isSelected()) selected = StructuringElement.HORIZONTAL_LINE; else if (getRdbtnVerticalLine().isSelected()) selected = StructuringElement.VERTICAL_LINE; else if (getRdbtnSquare().isSelected()) selected = StructuringElement.SQUARE; else selected = StructuringElement.RHOMBUS; ok = true; dispose(); }
6
protected void end() { Robot.tilter.stop(); }
0
public int delete() { if (size == 1) { int helpvalue = root.value; root = null; return helpvalue; } int returnedvalue = root.value; Binarynode help = root; help.value = root.value; String binary = Integer.toBinaryString(size); for (int i = 1; i < binary.length(); i++) { if (binary.charAt(i) == '0') { help = help.left; } else { help = help.right; } } root.value = help.value; if (binary.charAt(binary.length() - 1) == '0') { help.parent.left = null; } else { help.parent.right = null; } size--; heap_down(); return returnedvalue; }
4
public void actualizarTurnosBD() { conexion.conectar(); for (Turno turno : turnos) { if (turno.getDescripcion() != null && turno.getDuración() != 0) { String sql = "UPDATE turno SET estado = true, descripcion='" + turno.getDescripcion() + "'," + " duracion=" + turno.getDuración() + " where id=" + turno.getId(); conexion.consultar(sql); } } conexion.cerrarConexion(); }
3
@Test public void testGetNextCard() throws Exception { Shoe shoe = new Shoe(1, 0); Map<String, Integer> seenCards = new HashMap<String, Integer>(); for(int i = 0; i < 52; i++) { Card card = shoe.getNextCard(); if(seenCards.containsKey(card.toString())) { assertTrue(false); } seenCards.put(card.toString(), 1); } assertEquals(52, seenCards.size()); for(Card.Pip pip : Card.Pip.values()) { for(Card.Suit suit : Card.Suit.values()) { Card card = new Card(pip, suit); assertTrue(seenCards.containsKey(card.toString())); assertEquals(1, (int)seenCards.get(card.toString())); } } shoe = new Shoe(4, 0); seenCards.clear(); for(int i = 0; i < 52 * 4; i++) { if(shoe.needsReshuffle()) { shoe.reshuffleShoe(); } Card card = shoe.getNextCard(); if(!seenCards.containsKey(card.toString())) { seenCards.put(card.toString(), 1); } else { int count = seenCards.get(card.toString()) + 1; seenCards.put(card.toString(), count); } } assertEquals(52, seenCards.size()); for(Card.Pip pip : Card.Pip.values()) { for(Card.Suit suit : Card.Suit.values()) { Card card = new Card(pip, suit); assertTrue(seenCards.containsKey(card.toString())); assertEquals(4, (int)seenCards.get(card.toString())); } } }
9
public Persona actualizarLicencias(Persona p) { Persona persona = personas.get(p.getCi()); List<LicenciaConductor> eliminar = new ArrayList<>(); for (LicenciaConductor vieja : persona.getLicenciasDeConducir()) { boolean remover = true; for (LicenciaConductor nueva : p.getLicenciasDeConducir()) { if (nueva.equals(vieja)) { remover = false; // Se mantiene igual break; } else if (nueva.getNumero() == vieja.getNumero()) { // Hay que actualizar break; } } if (remover) { eliminar.add(vieja); } } try { for (LicenciaConductor licenciaConductor : eliminar) { persona.removerLicencia(licenciaConductor); db.delete(licenciaConductor); } for (LicenciaConductor nueva : p.getLicenciasDeConducir()) { if (!persona.getLicenciasDeConducir().contains(nueva)) { nueva.setPropietario(persona); agregarLicencia(persona, nueva); } } db.store(persona); db.commit(); } catch (Db4oIOException | DatabaseClosedException | DatabaseReadOnlyException e) { db.rollback(); throw new PersistenciaException(e); } return persona; }
9
public Controller() { try { bar = new OtpNode("java", "cake"); mbox = bar.createMbox(); } catch (IOException ex) { Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex); } ok = new OtpErlangAtom("ok"); // new Thread(new Runnable() { // // public void run() { // // do some stuff //// System.out.println("hey hey"); // receiveMessage(); // } // }).start(); // connect(); }
1
private void explode(int damage){ if(absoluteHitPosition.tileType == TileType.ROCK || absoluteHitPosition.tileType == TileType.VOID || absoluteHitPosition.tileType == TileType.SPAWN){ Debug.warn("Mortar hit " + absoluteHitPosition.tileType + " tile, did not explode"); return; } int baseDamage = damage; int aoeDamage = (int)Math.round(18 + 0.2*turnsLeft*18); absoluteHitPosition.damageTile(baseDamage, dealingPlayer); if(absoluteHitPosition.up != null) absoluteHitPosition.up.damageTile(aoeDamage, dealingPlayer); if(absoluteHitPosition.down != null) absoluteHitPosition.down.damageTile(aoeDamage, dealingPlayer); if(absoluteHitPosition.rightDown != null) absoluteHitPosition.rightDown.damageTile(aoeDamage, dealingPlayer); if(absoluteHitPosition.rightUp != null) absoluteHitPosition.rightUp.damageTile(aoeDamage, dealingPlayer); if(absoluteHitPosition.leftDown != null) absoluteHitPosition.leftDown.damageTile(aoeDamage, dealingPlayer); if(absoluteHitPosition.leftUp != null) absoluteHitPosition.leftUp.damageTile(aoeDamage, dealingPlayer); }
9
public CircleAccumulator(boolean[][] edgeImage, int minRadius, int maxRadius) { if(edgeImage.length < 1 || edgeImage[0].length < 1) throw new IllegalArgumentException("edgeImage must have positive dimensions"); if(minRadius >= maxRadius) throw new IllegalArgumentException("minRadius must be less than maxRadius"); minR = minRadius; maxR = maxRadius; edges = edgeImage; acc = new int[maxR-minR][edges.length][edges[0].length]; }
3
public int terminateRental(DrivingLicense drivingLicense){ String typeOfCar = ""; int fuelToFillTank = 0; int distanceTravelled = 0; Car c = AbstractCar.getInstance(typeOfCar, RegistrationNumber.getInstance(extracted(registrationNumber).getLetterIdentifier(), extracted(registrationNumber).getNumberIdentifier()), fuelCapacity, fuelInCar, carRented); carRented = false; RENTEDCARS.remove(drivingLicense); CARS.add(c); if (typeOfCar.equalsIgnoreCase("small car")){ fuelToFillTank = c.driveTheCar(distanceTravelled); } else if (typeOfCar.equalsIgnoreCase("large Car")){ fuelToFillTank = c.driveTheCar(distanceTravelled); } else{ throw new IllegalArgumentException("That is not a valid car"); } return fuelToFillTank; }
2
public int right(){ int movedNr = 0; for(int i=0;i<getX();i++){ ArrayList<Integer> merged = new ArrayList<Integer>(2); //list of all tiles which are already merged and are not allowed to be merged again for(int u=getY()-1;u>0;u--){//go from right to left int cv = u-1; if(cells[i][cv] != 0){ Boolean moved = false; for(int t=u;t<getY();t++){ //go from left to right if(cells[i][t] == 0){ cells[i][t] = cells[i][cv]; cells[i][cv] = 0; cv++; moved = true; }else{ //check if it could be merged and if we are allowed to merge if(cells[i][cv] == cells[i][t] && !merged.contains(t)){ cells[i][t] = cells[i][cv] * 2; cells[i][cv] = 0; merged.add(t); moved = true; } break; } } if(moved) movedNr++; } } } return movedNr; }
8
private byte[] compressBytes(byte[] orginal) { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); try { GZIPOutputStream gzip = new GZIPOutputStream(byteStream); gzip.write(orginal); gzip.close(); } catch (IOException e) { this.parent.server.Log("Error compressing level!"); e.printStackTrace(); return null; } return byteStream.toByteArray(); }
1
public void addTask(Task item) { try { String filepath = System.getProperty("user.home") + "/.TODO-group9/savedata.xml"; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(filepath); // Node tasklist = doc.getElementsByTagName("tasklist").item(0); int itemID = item.getId(); if (itemID == 0) { Node idCounter = doc.getElementsByTagName("idCounter").item(0); String id = ((Element) idCounter).getAttribute("id"); item.setId(Integer.parseInt(id)); String newId = "" + (Integer.parseInt(id) + 1); ((Element) idCounter).setAttribute("id",newId); Element newTask = doc.createElement("task"); newTask.setAttribute("id", id); tasklist.appendChild(newTask); Element category = doc.createElement("category"); category.appendChild(doc.createTextNode(item.getCategory().getName())); newTask.appendChild(category); Element title = doc.createElement("title"); title.appendChild(doc.createTextNode(item.getTitle())); newTask.appendChild(title); Element description = doc.createElement("description"); description.appendChild(doc.createTextNode(item.getDescription())); newTask.appendChild(description); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date date = new Date(); String dateATM = dateFormat.format(date); Element addate = doc.createElement("addate"); addate.appendChild(doc.createTextNode(dateATM)); newTask.appendChild(addate); Element duedate = doc.createElement("duedate"); duedate.appendChild(doc.createTextNode(item.getDueDate())); newTask.appendChild(duedate); Element priority = doc.createElement("priority"); priority.appendChild(doc.createTextNode(""+item.getPriority())); newTask.appendChild(priority); Element check = doc.createElement("check"); check.appendChild(doc.createTextNode(new Boolean(item.isCheck()).toString())); newTask.appendChild(check); } else { NodeList list = tasklist.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if ((""+itemID).equals(((Element) node).getAttribute("id"))) { Node categoryNodeToUpdate = ((Element) node).getElementsByTagName("category").item(0); categoryNodeToUpdate.setTextContent(item.getCategory().getName()); Node titleNodeToUpdate = ((Element) node).getElementsByTagName("title").item(0); titleNodeToUpdate.setTextContent(item.getTitle()); Node descriptionNodeToUpdate = ((Element) node).getElementsByTagName("description").item(0); descriptionNodeToUpdate.setTextContent(item.getDescription()); Node addateNodeToUpdate = ((Element) node).getElementsByTagName("addate").item(0); addateNodeToUpdate.setTextContent(item.getAdDate()); Node duedateNodeToUpdate = ((Element) node).getElementsByTagName("duedate").item(0); duedateNodeToUpdate.setTextContent(item.getDueDate()); Node priorityNodeToUpdate = ((Element) node).getElementsByTagName("priority").item(0); priorityNodeToUpdate.setTextContent("" + item.getPriority()); Node checkNodeToUpdate = ((Element) node).getElementsByTagName("check").item(0); checkNodeToUpdate.setTextContent(new Boolean(item.isCheck()).toString()); } } } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(filepath)); transformer.transform(source, result); // } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (SAXException sae) { sae.printStackTrace(); } }
7
public String iniciarProduccion() { double materiaPrima = getCantMateriaPrima(); String averia = ""; String msj = ""; if(isActivo()){ if(modoOperacion == 'C'){ while (getCantMateriaPrima() > 0) { materiaPrima = materiaPrima - getMoldeEnvases().obtenerPorcMateria(); setCantMateriaPrima(materiaPrima); // Se ha producido un envase mas. incrementarCantEnvasesProd(); // Llamar al detector cada vez que se produce un envase. averia = detectorFallas.verificarAveria(); if (averia != "") { desactivarMaquina(); reportarAveria(averia); msj = averia; } } }else{ while (numEnvases > cantEnvasesProd) { materiaPrima = materiaPrima - getMoldeEnvases().obtenerPorcMateria(); setCantMateriaPrima(materiaPrima); // Se ha producido un envase mas. incrementarCantEnvasesProd(); // Llamar al detector cada vez que se produce un envase. averia = detectorFallas.verificarAveria(); if (averia != "") { desactivarMaquina(); reportarAveria(averia); msj = averia; } } } msj += "Se produjeron "+getCantEnvasesProd()+" envases \n"; msj += "Quedan "+getCantMateriaPrima()+" de materia prima"; }else{ msj = "La maquina se encuentra desactivada"; } return msj; }
6
@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); comboCliente = new javax.swing.JComboBox(); tfProcesso = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); comboAdvogado = new javax.swing.JComboBox(); jLabel5 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); tfAcao = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); tfReboqueiro = new javax.swing.JTextField(); btCancelar = new javax.swing.JButton(); btSalvar = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); tfMarca = new javax.swing.JTextField(); tfModelo = new javax.swing.JTextField(); tfCor = new javax.swing.JTextField(); tfPlaca = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); tfAnoFabricacao = new javax.swing.JFormattedTextField(); tfAnoModelo = new javax.swing.JFormattedTextField(); jLabel15 = new javax.swing.JLabel(); tfChassi = new javax.swing.JTextField(); jLabel17 = new javax.swing.JLabel(); tfRenavam = new javax.swing.JTextField(); tfDataInicio = new javax.swing.JFormattedTextField(); tfDataFim = new javax.swing.JFormattedTextField(); jLabel16 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); taSituacaoAtual = new javax.swing.JTextArea(); jLabel14 = new javax.swing.JLabel(); tfVara = new javax.swing.JFormattedTextField(); jLabel18 = new javax.swing.JLabel(); tfComarca = new javax.swing.JTextField(); jLabel19 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); comoEstado = new javax.swing.JComboBox(); jLabel6 = new javax.swing.JLabel(); btNovaConta = new javax.swing.JButton(); tfSituacaoF = new javax.swing.JTextField(); jLabel20 = new javax.swing.JLabel(); tfTotalF = new javax.swing.JTextField(); jLabel21 = new javax.swing.JLabel(); cbAssessoria = new javax.swing.JComboBox(); btAssessoria = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jLabel1.setText("PROCESSO"); jLabel2.setText("CLIENTE"); comboCliente.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecionar . . ." })); jLabel3.setText("DATA INÍCIO"); jLabel4.setText("DATA TÉRMINO"); comboAdvogado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecionar . . ." })); jLabel5.setText("ADVOGADO"); jLabel7.setText("AÇÃO"); jLabel8.setText("REBOQUEIRO"); btCancelar.setText("CANCELAR"); btCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btCancelarActionPerformed(evt); } }); btSalvar.setText("SALVAR"); btSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btSalvarActionPerformed(evt); } }); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Informações do veículo")); jLabel9.setText("MARCA"); jLabel10.setText("MODELO"); jLabel11.setText("COR"); jLabel12.setText("PLACA"); jLabel13.setText("ANO DE FABRICAÇÃO E MODELO"); try { tfAnoFabricacao.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } try { tfAnoModelo.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } jLabel15.setText("CHASSSI"); jLabel17.setText("RENAVAM"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9) .addComponent(tfMarca, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10) .addComponent(tfModelo, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfCor, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE) .addComponent(jLabel12) .addGap(59, 59, 59)) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(tfPlaca) .addContainerGap()))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel13) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(tfAnoFabricacao) .addGap(18, 18, 18) .addComponent(tfAnoModelo, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(tfRenavam, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(37, 37, 37) .addComponent(jLabel17))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel15) .addGap(25, 25, 25)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(tfChassi) .addContainerGap()))))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(jLabel10) .addComponent(jLabel11) .addComponent(jLabel12)) .addGap(7, 7, 7) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfMarca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfModelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfCor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfPlaca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel15) .addComponent(jLabel17)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfChassi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfAnoModelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfRenavam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfAnoFabricacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); try { tfDataInicio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } try { tfDataFim.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } jLabel16.setText("SITUAÇÃO ATUAL"); taSituacaoAtual.setColumns(20); taSituacaoAtual.setRows(5); jScrollPane1.setViewportView(taSituacaoAtual); jLabel14.setText("VARA"); jLabel18.setText("Veículo foi:"); jLabel19.setText("COMARCA"); jButton1.setText("+"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("+"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); comoEstado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecionar...", "Apreendido", "Não Encontrado", "Localizado" })); jLabel6.setText("FINANCEIRO"); btNovaConta.setText("+"); btNovaConta.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btNovaContaActionPerformed(evt); } }); tfSituacaoF.setEditable(false); tfSituacaoF.setText("SEM FINANCEIRO"); tfSituacaoF.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tfSituacaoFActionPerformed(evt); } }); jLabel20.setText("TOTAL:"); tfTotalF.setEditable(false); tfTotalF.setText("0.00"); jLabel21.setText("ASSESSORIA"); btAssessoria.setText("+"); btAssessoria.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btAssessoriaActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel18) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(comoEstado, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(btCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27)) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel2) .addGroup(layout.createSequentialGroup() .addComponent(tfProcesso, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(tfDataInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(tfDataFim, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(175, 175, 175) .addComponent(jLabel3) .addGap(58, 58, 58) .addComponent(jLabel4)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel16) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane1) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel5) .addComponent(comboAdvogado, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel8) .addComponent(tfReboqueiro, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel21) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbAssessoria, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btAssessoria, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(8, 8, 8))))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel14) .addGap(161, 161, 161)) .addComponent(tfVara, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)) .addComponent(tfAcao, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel19) .addComponent(tfComarca, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addGap(0, 6, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(tfSituacaoF, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btNovaConta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel20) .addGap(5, 5, 5) .addComponent(tfTotalF))))) .addGap(2, 2, 2)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(comboCliente, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(30, 30, 30)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE) .addComponent(comboCliente)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel3) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfProcesso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfDataInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfDataFim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(jLabel16) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel14) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tfVara, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tfAcao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel19) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tfComarca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel6)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(comboAdvogado, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfReboqueiro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btNovaConta) .addComponent(tfSituacaoF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(9, 9, 9) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel20) .addComponent(tfTotalF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel21) .addComponent(cbAssessoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btAssessoria)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(jLabel18) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(comoEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(btSalvar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(18, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents
4
public void handleSaveMachineButton(){ String name = JOptionPane.showInputDialog(this,"Machine name?",null); if(name == null){ } else if(name.trim().length() > 0){ File savingDir = new File("Saved"); if (!savingDir.exists()){ savingDir.mkdirs(); } File savingMachine = new File("Saved/" + name); int result; if(savingMachine.exists()){ result = JOptionPane.showConfirmDialog(mainWindow,name.concat(" already exists.\nDo you want to replace it?"),"Confirm",JOptionPane.YES_NO_OPTION); } else{ result = -5; } if ((result == JOptionPane.YES_OPTION) || (result == -5)) { try { savingMachine.mkdirs(); ObjectOutputStream modelOut; modelOut = new ObjectOutputStream(new FileOutputStream("Saved/" + name + "/" + name + ".model")); modelOut.writeObject(aTuringMachine); modelOut.close(); ObjectOutputStream startOut; startOut = new ObjectOutputStream(new FileOutputStream("Saved/" + name + "/" + name + ".start")); startOut.writeObject(startView); startOut.close(); ObjectOutputStream transitionOut; transitionOut = new ObjectOutputStream(new FileOutputStream("Saved/" + name + "/" + name + ".transition")); transitionOut.writeObject(transitionView); transitionOut.close(); ObjectOutputStream inputOut; inputOut = new ObjectOutputStream(new FileOutputStream("Saved/" + name + "/" + name + ".input")); inputOut.writeObject(inputView); inputOut.close(); JOptionPane.showMessageDialog(this,name + " has been saved."); } catch (FileNotFoundException e) { System.out.println("Error: Cannot open file for writing"); JOptionPane.showMessageDialog(this,"File could not be saved","Error",JOptionPane.ERROR_MESSAGE); } catch (IOException e) { System.out.println("Error: Cannot write to file"); JOptionPane.showMessageDialog(this,"File could not be saved.","Error",JOptionPane.ERROR_MESSAGE); } } else{ handleSaveMachineButton(); } } else{ handleSaveMachineButton(); } }
8
public int GetOffBusTicks() { //get the tick time person got off the bus return offBusTicks; }
0
public boolean isPushTwoTransition(Transition transition) { PDATransition trans = (PDATransition) transition; String toPush = trans.getStringToPush(); if (toPush.length() != 2) return false; /* * String input = trans.getInputToRead(); if(input.length() != 1) return * false; */ String toPop = trans.getStringToPop(); if (toPop.length() != 1) return false; return true; }
2
public static Integer versionCompare(String str1, String str2) { String[] vals1 = str1.split("\\."); String[] vals2 = str2.split("\\."); int idx = 0; // set index to first non-equal ordinal or length of shortest version // string while (idx < vals1.length && idx < vals2.length && vals1[idx].equals(vals2[idx])) { idx++; } // compare first non-equal ordinal number if (idx < vals1.length && idx < vals2.length) { int diff = Integer.valueOf(vals1[idx]).compareTo(Integer.valueOf(vals2[idx])); return Integer.signum(diff); } else { // the strings are equal or one string is a substring of the other // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4" return Integer.signum(vals1.length - vals2.length); } }
5
private void pasteUrlFromClipboard() { if (Config.getInstance().getAddURLAutoPaste()) { String text = getPasteString(); URL url = getUrlFromString(text); if (url != null) { view.setUrlText(url.toString()); } } }
2
private void render(Graphics2D graphics) { for (Tile[] tileArray : tiles) { for (Tile tile : tileArray) { tile.render(graphics); } } }
2
private void removeFile() { JFrame frame = new JFrame(); // if there is at least one file parsed if( fileIndex.numOfFilesParsed() != 0 ) { // get the file name to remove String fileName = (String) JOptionPane.showInputDialog( frame, "Enter NAME of the file to remove:", "Remove File From Index", JOptionPane.OK_OPTION, new ImageIcon( PATH + REMOVE_FILE_ICON ), null, ""); // if user has clicked cancel or clicked ok without entering a filename, // show an error dialog if( fileName == null || fileName.length() == 0 ) { JOptionPane.showMessageDialog( frame, "Canceled 'Remove File' operation." ); return; } // if the file name is able to e removed, output the results to the main panel if( fileIndex.removeFile( fileName ) ) { mainContentLabel.setText( htmlParagraphPrefix + tab + "File \"" + fileName + "\" was removed from the file index." + htmlParagraphSuffix ); } else { // output the fact that were no results mainContentLabel.setText( htmlParagraphPrefix + tab + "File \"" + fileName + "\" was NOT removed from the file index." + htmlParagraphSuffix ); } } // no files are currently associated with the file index, so show an error dialog informing the user of this else { JOptionPane.showMessageDialog( frame, "ERROR: There are no files to remove." ); mainContentLabel.setText( htmlParagraphPrefix + tab + "ERROR: There are no files to remove." + htmlParagraphSuffix ); } }
4
private void extractJar(File file, String path) throws Exception { final int initialPercentage = launcher.getPercentage(); final JarFile jarFile = new JarFile(file); Enumeration<JarEntry> entries = jarFile.entries(); int totalSizeExtract = 0; while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); if (entry.isDirectory() || entry.getName().indexOf('/') != -1) { continue; } totalSizeExtract += entry.getSize(); } int currentSizeExtract = 0; entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); if (entry.isDirectory() || entry.getName().indexOf('/') != -1) { continue; } final File f = new File(path + entry.getName()); if (f.exists() && !f.delete()) { continue; } final InputStream in = jarFile.getInputStream(jarFile .getEntry(entry.getName())); final OutputStream out = new FileOutputStream(new File(path + entry.getName())); final byte[] buffer = new byte[65536]; int bufferSize; while ((bufferSize = in.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, bufferSize); currentSizeExtract += bufferSize; launcher.setPercentage(initialPercentage + currentSizeExtract * 20 / totalSizeExtract); launcher.subtaskMessage = launcherFrame.locale .getString("updater.extracting") + ": " + entry.getName() + " " + currentSizeExtract * 100 / totalSizeExtract + "%"; } in.close(); out.close(); } launcher.subtaskMessage = ""; jarFile.close(); }
9
@Override public void put(Key key, Value val) { if (N > M * 10) resize(2 * M); if (val == null) { delete(key); return; } int i = hash(key); if (!st[i].contains(key)) // Note: More efficient than contains(key) as // duplicate calculation of hash(key) not // involved N++; st[i].put(key, val); }
3
@Override public void exportDone(JComponent c, Transferable data, int action) { initialImportCount = 1; if (c instanceof mxGraphComponent && data instanceof mxGraphTransferable) { // Requires that the graph handler resets the location to null if the drag leaves the // component. This is the condition to identify a cross-component move. boolean isLocalDrop = location != null; if (action == TransferHandler.MOVE && !isLocalDrop) { removeCells((mxGraphComponent) c, originalCells); initialImportCount = 0; } } originalCells = null; location = null; offset = null; }
4
public boolean partidoCompleto() { return (listaJugadores.size()==10) && listaJugadores.stream().allMatch(j->j.getModo() instanceof Estandar); }
1
public ExponentialTerm(double base) { _base = base; }
0
@Override public void keyPressed(KeyEvent arg0) { switch(arg0.getKeyCode()){ case KeyEvent.VK_UP: upArrow = true; break; case KeyEvent.VK_DOWN: downArrow = true; break; case KeyEvent.VK_LEFT: leftArrow = true; break; case KeyEvent.VK_RIGHT: rightArrow = true; break; } }
4
private void parseResponse(String rawResponce, GoogleResponse googleResponce) { if (rawResponce == null || googleResponce == null) return; String responce1 = StringUtil.substringBetween(rawResponce, "[", "]"); boolean confident = true; if (responce1 == null || responce1.equals("")) { confident = false; } else { googleResponce.setResponse(responce1); rawResponce.replaceFirst(responce1, ""); } rawResponce = rawResponce.replaceFirst("\\{\"result\":\\[\\]\\}", ""); if (rawResponce.equals("")) return; String unsplitResponses = StringUtil.substringBetween(rawResponce, "\"alternative\":[", "]"); String[] splitResponses = unsplitResponses.split("\\},\\{"); for (int i = 0; i < splitResponses.length; i++) { splitResponses[i] = splitResponses[i].replaceAll("\\{", ""); splitResponses[i] = splitResponses[i].replaceAll("\\}", ""); String response = splitResponses[i]; if (splitResponses[i].contains(",")) response = splitResponses[i].split(",")[0]; response = response.replaceAll("\"transcript\":", ""); response = StringUtil.stripQuotes(response); if (i == 0 && !confident) googleResponce.setResponse(response); else googleResponce.getOtherPossibleResponses().add(response); } }
9
public void clickPlayGame(ArrayList<MainMenuHeroSlot> heroies) { //Initializes main menu for game play MainMenuGame.MainMenuGame.main(new String [0], heroies); //Once game is played reset the game so he can play again gumballMachine.setState(gumballMachine.hasNotChosenCharactersState()); }
0
public int getPort() { return this.port; }
0
@Override public Object getValueAt(int i, int i1) { Tenant t = tenants.get(i); //To change body of generated methods, choose Tools | Templates. switch (i1) { case 0: return t.getId(); case 1: return t.getName(); case 2: return t.getAddress(); case 3: return t.getTel(); case 4: return t.getRoom(); case 5: return t.getRentDate(); case 6: return t.getPayStatus(); default: return null; } }
7
public List<Prize> execute() throws IOException { FileInputStream fis = new FileInputStream(new File(inputFile)); XSSFWorkbook wb = new XSSFWorkbook(fis); XSSFSheet sheet = wb.getSheet(MAGIC); Iterator<Row> it = sheet.iterator(); while (it.hasNext()) { Row row = it.next(); String category = getCellString(row, 0); String classification = getCellString(row, 1); String first = getCellString(row, 2); String second = getCellString(row, 3); String third1 = getCellString(row, 4); String third2 = getCellString(row, 5); if (MAGIC.equals(category) || "種目".equals(category)) { continue; } if (!StringUtils.isNullOrEmpty(first)) { prizeList.add(new Prize(category, classification, "優勝", first)); } if (!StringUtils.isNullOrEmpty(second)) { prizeList.add(new Prize(category, classification, "準優勝", second)); } if (!StringUtils.isNullOrEmpty(third1)) { prizeList.add(new Prize(category, classification, "第三位", third1, 1)); } if (!StringUtils.isNullOrEmpty(third2)) { prizeList.add(new Prize(category, classification, "第三位", third2, 2)); } } // for (Prize prize : prizeList) { System.out.println(prize); } return prizeList; }
8
public void uploadDirectory(FTPFile srcDir, FTPFile dstDir) throws IOException, FtpWorkflowException, FtpIOException { if (!srcDir.isDirectory()) throw new FtpFileNotFoundException("Uploading: " + srcDir.getName() + " is not possible, it's not a directory!"); makeDirectory(dstDir.toString()); File[] files = srcDir.getFile().listFiles(); List<FTPFile> ftpFiles = new ArrayList<FTPFile>(); for (File file : files) ftpFiles.add(new FTPFile(file)); Collections.sort(ftpFiles); for (FTPFile file : ftpFiles) { if (!file.isDirectory()) { uploadFile(file, new FTPFile(dstDir.toString(), file.getName())); } else { uploadDirectory(file, new FTPFile(dstDir.toString(), file .getName(), true)); } } }
4
public String getSourceLine(int lineNumber) { return sourceLines.get(lineNumber).getSourceLine(); }
0
@Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); if (e.getButton() == MouseEvent.BUTTON1) addVertex(draggedToX, draggedToY); else if (e.getButton() == MouseEvent.BUTTON2) removeVertex(draggedToVertex); else if (e.getButton() == MouseEvent.BUTTON3) joinPoints(draggedToVertex); gui.repaint(); }
3
@Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof IterableComparator)) { return false; } final IterableComparator<?> other = (IterableComparator<?>) obj; if (iteratorComparator == null) { if (other.iteratorComparator != null) { return false; } } else if (!iteratorComparator.equals(other.iteratorComparator)) { return false; } return true; }
8
@Override public void out() throws Exception { Object val = fa.getFieldValue(); // Object val = access; if (ens.shouldFire()) { DataflowEvent e = new DataflowEvent(ens.getController(), this, val); //// DataflowEvent e = new DataflowEvent(ens.getController(), this, access.toObject()); ens.fireOut(e); // // the value might be altered val = e.getValue(); } // if data==null this unconsumed @Out, its OK but we do not want to set it. if (data != null) { data.setFieldValue(val); } fa.out(); }
2
public static int[][] getArray() { int [][] num={{1,2,3},{4,5},{2}}; for(int i = 0; i < num.length; i++) { for(int j = 0; j < num[i].length; j++) System.out.println(num[i][j]); } return num; }
2
public static TreeSet<Integer> primeSieve(int limit) { boolean[] numberList = new boolean[limit + 1]; TreeSet<Integer> primeList = new TreeSet<>(); for(int i = 2; i <= limit; i++) { numberList[i] = true; } for(int i = 2; i * i <= limit; i++) { if(numberList[i]) { for(int j = i; i * j <= limit; j++) { numberList[i * j] = false; } } } for(int i = 2; i <= limit; i++) { if(numberList[i]) { primeList.add(i); } } return primeList; }
6
public boolean delete(T item) { if(current != null) { if(current == current.getNext() && current.getData().equals(item)) { current = null; return true; } else { Link<T> cur = current; Link<T> prev = null; while(!cur.getData().equals(item) && cur.getNext() != current) { prev = cur; cur = cur.getNext(); } if(cur.getData().equals(item)) { if(prev != null) { prev.setNext(cur.getNext()); } else { final Link<T> next = cur.getNext(); getLast().setNext(next); current = next; } return true; } } } return false; }
7
public Builder(final Object paramValue) { this.value = null; this.paramValue = paramValue; }
0
public void run() { try { this.MReading.acquire(); if(this.counter == 0) this.MWriting.acquire(); this.counter++; this.MReading.release(); System.out.println("Lecture"); Thread.sleep(1000); this.MReading.acquire(); this.counter--; if(this.counter == 0) this.MWriting.release(); this.MReading.release(); } catch (InterruptedException e) { e.printStackTrace(); } }
3
public void pack() { boolean isrunestone = cap.text.equals("Runestone"); Coord max = new Coord(0, 0); for (Widget wdg = child; wdg != null; wdg = wdg.next) { if ((wdg == cbtn) || (wdg == fbtn)) continue; if ((isrunestone) && (wdg instanceof Label)) { Label lbl = (Label) wdg; lbl.settext(GoogleTranslator.translate(lbl.texts)); } Coord br = wdg.c.add(wdg.sz); if (br.x > max.x) max.x = br.x; if (br.y > max.y) max.y = br.y; } ssz = max; checkfold(); placecbtn(); }
7
@Override public Object get( ByteBuffer in ) { byte nil = in.get(); if (nil == Compress.NULL) { return null; } try { Object o = constructor.newInstance(); for (int i = 0; i < fields.length; i++) { reflects[i].getAndSet( in, o, fields[i] ); } return o; } catch (Exception e) { throw new RuntimeException( e ); } }
3
public Cookies(Cookie[] cookies) { // TODO Auto-generated constructor stub this.cookies = cookies; }
0
public boolean equip(final int... ids) { Item item; if (ctx.bank.opened()) { item = ctx.bank.backpack.select().id(ids).poll(); } else { item = ctx.backpack.select().id(ids).poll(); if (item.id() > -1) { if (!ctx.hud.opened(Hud.Window.BACKPACK) && ctx.hud.open(Hud.Window.BACKPACK)) { ctx.sleep(400); } if (!ctx.backpack.scroll(item)) { return false; } } } if (item.valid()) { if (item.interact(new Filter<Menu.Command>() { @Override public boolean accept(Menu.Command entry) { return entry.action.startsWith("Equip") || entry.action.startsWith("Wear") || entry.action.startsWith("Wield"); } })) { Condition.wait(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return !select().id(ids).isEmpty(); } }, 200, 10); } } return !select().id(ids).isEmpty(); }
9
public void handleInput() { if (Keys.isPressed(Keys.ESCAPE)) gsm.setPaused(true); if (player.getHealth() == 0) return; player.setUp(Keys.keyState[Keys.UP]); player.setDown(Keys.keyState[Keys.DOWN]); player.setLeft(Keys.keyState[Keys.LEFT] || Keys.keyState[Keys.A]); player.setRight(Keys.keyState[Keys.RIGHT] || Keys.keyState[Keys.D]); player.setJumping(Keys.keyState[Keys.BUTTON1]); player.setGliding(Keys.keyState[Keys.BUTTON2]); if (Keys.isPressed(Keys.BUTTON4)) player.setFiring(); if (Keys.isPressed(Keys.BUTTON3)) player.setScratching(); }
6
public void execute( JobExecutionContext context ) throws JobExecutionException { this.invocationsA++; }
0
@Override public void run() { if (Updater.this.url != null) { // Obtain the results of the project's file feed if (Updater.this.read()) { if (Updater.this.versionCheck(Updater.this.versionName)) { if ((Updater.this.versionLink != null) && (Updater.this.type != UpdateType.NO_DOWNLOAD)) { String name = Updater.this.file.getName(); // If it's a zip file, it shouldn't be downloaded as the plugin's name if (Updater.this.versionLink.endsWith(".zip")) { final String[] split = Updater.this.versionLink.split("/"); name = split[split.length - 1]; } Updater.this.saveFile(new File(Updater.this.plugin.getDataFolder().getParent(), Updater.this.updateFolder), name, Updater.this.versionLink); } else { Updater.this.result = UpdateResult.UPDATE_AVAILABLE; } } } } }
6
@Override public void move(long ticks, FrameBuffer buffer){}
0
public boolean addSpawnedMob(Mob mob, MobReference mobRef) { if (!mobRef.isValid()) return false; // Add the mob to the regions limit if (maxAliveLimiter != null && !maxAliveLimiter.add(mobRef)) return false; // Add the mob to its grouped limit if (groupedMaxAliveLimiters != null && mob.regionLimitGroup.length() > 0) { MobCounter limiter = groupedMaxAliveLimiters.get(mob.regionLimitGroup); if (limiter != null && !limiter.add(mobRef)) return false; } return true; }
7
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) {// 非空性 return false; } if (getClass() != obj.getClass()) { return false; } Point p = (Point) obj; return this.x == p.x && this.y == p.y; }
4
public int maxSubArray3(int[] A) {// O(1) space int last = 0; int max = A[0]; for (int i = 0; i < A.length; i++) { if (last >= 0) last += A[i]; else last = A[i]; max = Math.max(last, max); // keep track of the largest sum } return max; }
2
public String getWinningTeam(String matchName){ for(String teamName: TEAM_NAMES){ if(teamIsWipedOut(matchName, teamName)){ return teamName.equalsIgnoreCase(TEAM_NAMES[0]) ? TEAM_NAMES[1] : TEAM_NAMES[0]; } } return null; }
3
public Vector3f normalized() { float length = this.length(); if ( length == 0 ) return new Vector3f( 0, 0, 0 ); return ( new Vector3f( x / length, y / length, z / length ) ); }
1
private boolean decode5(ByteArrayOutputStream baos) throws PDFParseException { // stream ends in ~> int[] five = new int[5]; int i; for (i = 0; i < 5; i++) { five[i] = nextChar(); if (five[i] == '~') { if (nextChar() == '>') { break; } else { throw new PDFParseException("Bad character in ASCII85Decode: not ~>"); } } else if (five[i] >= '!' && five[i] <= 'u') { five[i] -= '!'; } else if (five[i] == 'z') { if (i == 0) { five[i] = 0; i = 4; } else { throw new PDFParseException("Inappropriate 'z' in ASCII85Decode"); } } else { throw new PDFParseException("Bad character in ASCII85Decode: " + five[i] + " (" + (char) five[i] + ")"); } } if (i > 0) { i -= 1; } int value = five[0] * 85 * 85 * 85 * 85 + five[1] * 85 * 85 * 85 + five[2] * 85 * 85 + five[3] * 85 + five[4]; for (int j = 0; j < i; j++) { int shift = 8 * (3 - j); baos.write((byte) ((value >> shift) & 0xff)); } return (i == 4); }
9
public MyClient(){ super(header); gameState = 0; Container c = getContentPane(); c.setLayout(null); Border loweredbevel, raisedbevel; loweredbevel = BorderFactory.createLoweredBevelBorder(); raisedbevel = BorderFactory.createRaisedBevelBorder(); imgHolder = new JLabel(new ImageIcon("images\\Kashiwazaki Sena.jpg")); imgHolder.setSize(250, 250); imgHolder.setLocation(15, 15); imgHolder.setBorder(raisedbevel); c.add(imgHolder); ehandle = new JButton("Start Game"); ehandle.setSize(150, 50); ehandle.setLocation(590, 15); ehandle.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e){ Message msg = new Message(""); if(gameState == 0){ msg.header = "START GAME"; gameState = 1; System.out.println("START KEY PRESS"); } else if(gameState == 1){ msg.header = "PAUSE GAME"; gameState = 2; System.out.println("PAUSE KEY PRESS"); } else if(gameState == 2){ msg.header = "RESUME GAME"; gameState = 1; System.out.println("RESUME KEY PRESS"); } try{ sendObject(msg); }catch(Exception E){ System.out.println("Error has occured!"); } } } ); c.add(ehandle); quit = new JButton("EXIT"); quit.setSize(150, 50); quit.setLocation(590, 80); quit.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e){ Message msg = new Message(9, 0); System.out.println("QUIT KEY PRESS"); try{ sendObject(msg); }catch(Exception E){ System.out.println("Error has occured!"); } System.exit(0); } } ); c.add(quit); scoreL = new JLabel("Score Board"); scoreL.setSize(300, 20); scoreL.setLocation(275, 15); c.add(scoreL); scoreTA = new JTextArea(); scoreTA.setEditable(false); scoreSP = new JScrollPane(scoreTA, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scoreSP.setSize(300, 230); scoreSP.setLocation(275, 35); scoreSP.setBorder(loweredbevel); c.add(scoreSP); ansTA = new JTextArea(); ansTA.setSize(550, 45); ansTA.setLocation(15, 275); ansTA.setBorder(loweredbevel); c.add(ansTA); sendAns = new JButton("Send Answer"); sendAns.setSize(150, 45); sendAns.setLocation(590, 275); sendAns.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e){ String ans = ansTA.getText(); ansTA.setText(""); System.out.println("SEND KEY PRESS" + " : " + ans); Message msg = new Message(8, 0, ans); try{ sendObject(msg); }catch(Exception E){ System.out.println("Error has occured!"); } } } ); c.add(sendAns); setSize(760, 365); setVisible(true); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); }
6
public static Operation createOperation(int operation) { Operation opt = null; switch (operation) { case OPERATION_ADD: opt = new OperationAdd(); break; case OPERATION_SUB: opt = new OperationSub(); break; case OPERATION_MUL: opt = new OperationMul(); break; case OPERATION_DIV: opt = new OperationDiv(); break; default: throw new IllegalArgumentException(); } return opt; }
4
public boolean opEquals(Operator o) { return (o instanceof OuterLocalOperator && ((OuterLocalOperator) o).local .getSlot() == local.getSlot()); }
1
private final Path generateMap(final Object name, final Object title) { final Path map = this.midi.getParent().resolve( this.midi.getFilename() + ".map"); final OutputStream out = this.io.openOut(map.toFile()); final String style = this.STYLE.value(); this.io.writeln(out, String.format("Name: %s", title)); this.io.writeln(out, "Speedup: " + BruteParams.SPEED.value()); this.io.writeln(out, "Pitch: " + BruteParams.PITCH.value()); this.io.writeln(out, "Style: " + style); this.io.writeln(out, "Volume: " + BruteParams.VOLUME.value()); this.io.writeln(out, "Compress: " + BruteParams.DYNAMIC.value()); this.io.writeln(out, "%no pitch guessing %uncomment to switch off guessing of default octaves"); this.io.writeln( out, "%no back folding %uncomment to switch off folding of tone-pitches inside the playable region"); this.io.writeln(out, "fadeout length " + BruteParams.FADEOUT.value()); this.io.writeln(out, String.format("Transcriber : %s", name)); final Map<DragObject<JPanel, JPanel, JPanel>, Integer> abcPartMap = new HashMap<>(); boolean empty = true; this.io.updateProgress(); for (final Iterator<DropTargetContainer<JPanel, JPanel, JPanel>> targetIter = this.targets .iterator();;) { final DropTargetContainer<JPanel, JPanel, JPanel> target = targetIter .next(); if (!targetIter.hasNext()) { break; } for (final DropTarget<JPanel, JPanel, JPanel> t : target) { empty = false; final StringBuilder params = new StringBuilder(); for (final Map.Entry<String, Integer> param : t.getParams() .entrySet()) { params.append(" "); params.append(t.printParam(param)); } this.io.writeln(out, ""); this.io.writeln(out, "abctrack begin"); this.io.writeln(out, "polyphony 6 top"); this.io.writeln(out, "duration 2"); this.io.writeln(out, String.format("instrument %s%s", target.toString(), params.toString())); writeAbcTrack(out, t, abcPartMap); this.io.writeln(out, "abctrack end"); this.io.updateProgress(); } } this.io.writeln(out, ""); this.io.writeln(out, "% Instrument names are the ones from lotro, pibgorn is supported as well"); this.io.writeln( out, "% Polyphony sets the maximal number of simultanious tones for this instrument (6 is max)"); this.io.writeln(out, "% Pitch is in semitones, to shift an octave up : pitch 12 or down pitch -12"); this.io.writeln( out, "% Volume will be added /substracted from the normal volume of that track (-127 - 127), everything above/below is truncatedtch is in semitones, to shift an octave up : pitch 12 or down pitch -12"); this.io.close(out); final InputStream in = this.io.openIn(map.toFile()); final BufferedReader r = new BufferedReader(new InputStreamReader(in)); Debug.print("==== MAP BEGIN ====\n", this.midi.toString()); while (true) { String line; try { line = r.readLine(); } catch (final IOException e) { this.io.handleException(ExceptionHandle.SUPPRESS, e); break; } if (line == null) { break; } Debug.print("%s\n", line); } this.io.close(in); Debug.print("\n==== MAP END ====\n\n", this.midi.toString()); return empty ? null : map; }
8
public PROJECTView(SingleFrameApplication app) { super(app); initComponents(); //below code remove the required components from frame filefield.setVisible(false); filelabel.setVisible(false); passfield.setVisible(false); passlabel.setVisible(false); browse.setVisible(false); messagelabel.setVisible(false); messagearea.setVisible(false); finished.setVisible(false); message.setVisible(false); restart.setVisible(false); //End of first code //code for first window insert.setSelected(true); retrieve.setSelected(false); caution.setVisible(false); // status bar initialization - message timeout, idle icon and busy animation, etc ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { statusMessageLabel.setText(""); } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate"); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]"); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; statusAnimationLabel.setIcon(busyIcons[busyIconIndex]); } }); idleIcon = resourceMap.getIcon("StatusBar.idleIcon"); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); // connecting action tasks to status bar via TaskMonitor TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { if (!busyIconTimer.isRunning()) { statusAnimationLabel.setIcon(busyIcons[0]); busyIconIndex = 0; busyIconTimer.start(); } progressBar.setVisible(true); progressBar.setIndeterminate(true); } else if ("done".equals(propertyName)) { busyIconTimer.stop(); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); progressBar.setValue(0); } else if ("message".equals(propertyName)) { String text = (String)(evt.getNewValue()); statusMessageLabel.setText((text == null) ? "" : text); messageTimer.restart(); } else if ("progress".equals(propertyName)) { int value = (Integer)(evt.getNewValue()); progressBar.setVisible(true); progressBar.setIndeterminate(false); progressBar.setValue(value); } } }); }
7
public void setDiscount(int index, float discount){ this.discount[index]=discount; }
0
private boolean isObstructed() { if (pastLeftEdge()) { return true; } if (pastRightEdge()) { return true; } int[][] rotation = currentDroppingBlock.getCurrentRotation(); for(int i = 0; i < rotation.length; i++) { for (int j = 0; j < rotation[i].length; j++) { if (rotation[i][j] == 0) { continue; } int xPos = currentBlockPos[0] + j; int yPos = currentBlockPos[1] + i; try { if (storedBoardState[yPos][xPos] > 0) { return true; } } catch (Exception e) { return true; } } } return false; }
7
public T getFoo() { return foo; }
0
public void removeOnetimeLocals() { StructuredBlock[] subBlocks = getSubBlocks(); for (int i = 0; i < subBlocks.length; i++) subBlocks[i].removeOnetimeLocals(); }
1
boolean isAttackPlaceVerticallyBelowNotHarming(int position, char[] boardElements, int dimension, int numberOfLinesBelow) { while (numberOfLinesBelow > 0) { if (isPossibleToPlaceOnNextLine(boardElements, elementVerticallyBelow(dimension, position, numberOfLinesBelow)) && isBoardElementAnotherFigure(boardElements[elementVerticallyBelow(dimension, position, numberOfLinesBelow)])) { return false; } numberOfLinesBelow--; } return true; }
3
public final void visitMethodInsn(final int opcode, final String owner, final String name, final String desc) { AttributesImpl attrs = new AttributesImpl(); if (opcode != Opcodes.INVOKEDYNAMIC) { attrs.addAttribute("", "owner", "owner", "", owner); } attrs.addAttribute("", "name", "name", "", name); attrs.addAttribute("", "desc", "desc", "", desc); addElement(AbstractVisitor.OPCODES[opcode], attrs); }
1
public Contents contents() { return new Contents(); }
0
@Test public void resolve() { int i = 1; long sum = 0; long limit = 4 * 1000 * 1000; while (true) { long value = f(i); if (value > limit) { print(sum); break; } else if (value % 2 == 0) { sum += value; } i++; } }
3
public static void main(String[] args) { /* * Порахувати опір ланки яка скл. з двох резисторів, що можуть бути з"єднані * або послідовно, або паралельно. */ System.out.print("Введіть опір 1 >> "); Scanner in = new Scanner (System.in); int r1 = in.nextInt(); System.out.print("Введіть опір 2 >> "); int r2 = in.nextInt(); System.out.print("Введіть тип з\'єднання:\n1 - послідовне\n2 - паралельне\nВаш вибір -> "); int choice = in.nextInt(); System.out.println("**********************"); System.out.println("Опір r1 = "+r1+" ом"); System.out.println("Опір r2 = "+r2+" ом"); System.out.print("Тип з\'єднання - "); if (choice == 1 ){System.out.println("послідовне");} else {System.out.println("паралельне");} System.out.print("Загальний опір "); double r; if (choice == 1) {r=r1+r2;} else {r=r1*r2/(r1+r2);} System.out.printf("%5.2f ом",r); }
2
public void act(List<Actor> newRabbits) { if (isZiek) { timeToDie--; if(timeToDie<0) { setDead(); } } incrementAge(); if(isAlive()) { giveBirth(newRabbits); // kijken of het konijntje andere konijnen kan besmetten if(isZiek) { Location location = getLocation(); Location newLocation = besmetKonijntjes(location); } // Try to move into a free location. Location newLocation = getField().freeAdjacentLocation(getLocation()); if(newLocation != null) { setLocation(newLocation); } else { // Overcrowding. setDead(); } } }
5
void workerUpdate(File dir, boolean force) { if (dir == null) return; if ((!force) && (workerNextDir != null) && (workerNextDir.equals(dir))) return; synchronized(workerLock) { workerNextDir = dir; workerStopped = false; workerCancelled = true; workerLock.notifyAll(); } if (workerThread == null) { workerThread = new Thread(workerRunnable); workerThread.start(); } }
5
public int getA() { return this.a; }
0