text
stringlengths
14
410k
label
int32
0
9
public boolean removeOpenFormat(String formatName) { int index = indexOfName(formatName, openerNames); if (index >= 0) { openerNames.remove(index); openers.remove(index); // Also remove it from the list of formats stored in the preferences Preferences.FILE_FORMATS_OPEN.remove(index); return true; } return false; }
1
private List<PseudoSequence> buildProjectedDatabase(Integer item, List<PseudoSequence> database, Set<Integer> sidset, boolean inPostFix) { // We create a new projected database List<PseudoSequence> sequenceDatabase = new ArrayList<PseudoSequence>(); // for each sequence in the database received as parameter for(PseudoSequence sequence : database){ if(sidset.contains(sequence.getId()) == false){ continue; } // for each itemset of the sequence for(int i = 0; i< sequence.size(); i++){ if (sequence.isPostfix(i) != inPostFix){ // if the item is not in a postfix, but this itemset // is a postfix, then we can continue scanning from the next itemset continue; } // check if the itemset contains the item that we use for the projection int index = sequence.indexOfBis(i, item); // if it does not, move to next itemset if(index == -1 ){ continue; } // if the item is the last item of this itemset if(index == sequence.getSizeOfItemsetAt(i)-1){ // if it is not the last itemset if ((i != sequence.size()-1)){ // create new pseudo sequence // add it to the projected database. sequenceDatabase.add(new PseudoSequence( sequence, i+1, 0)); //System.out.println(sequence.getId() + "--> "+ newSequence.toString()); // break itemsetLoop; } }else{ // create a new pseudo sequence and // add it to the projected database. sequenceDatabase.add(new PseudoSequence(sequence, i, index+1)); //System.out.println(sequence.getId() + "--> "+ newSequence.toString()); // break itemsetLoop; } } } return sequenceDatabase; // return the projected database }
7
public static int getTreeHeight(ParserNode node, int symbolSize) { if (node.isVar()) return 0; int height = 0; List<ParserNode> children = node.getChildren(); int childrenSize = children.size(); if (childrenSize == 1) { // Ako čvor ima samo jedno dijete, stablo je visoko koliko je // visoko i podstablo tog djeteta height = getTreeHeight(node.getChildren().get(0), symbolSize); } else { // visina stabla jednaka je zbroju visina podstabala // gornja podstabla for (int i = 0; i < childrenSize / 2; i++) { height += getTreeHeight(children.get(i), symbolSize); // ako je i-to dijete operacija, onda ona ima svoje podstablo // pa je potrebno dodati još i razmak do sljedeceg podstabla if (children.get(i).isOp()) height += symbolSize; } // gornja podstabla mogu biti barem symbolSize široka, zato jer je // sam sklop širok toliko if (height == 0) height = symbolSize; // flag koji pokazuje je li dodan jedan symbolSize previse boolean exceeds = false; // donja podstabla for (int i = childrenSize / 2; i < childrenSize; i++) { height += getTreeHeight(children.get(i), symbolSize); if (children.get(i).isOp()) { // ako je i-to dijete operacija, onda ona ima svoje // podstablo // pa je potrebno dodati još i razmak do sljedeceg podstabla // Prvo dodavanje symbolSizea je višak, pa se postavlja flag height += symbolSize; exceeds = true; } } if (exceeds) height -= symbolSize; } // podstablo operacije može biti visoko najmanje symbolSizes return symbolSize > height ? symbolSize : height; }
9
private List<Integer> findSharedUsers(int movie1, int movie2) { List<Integer> sharedUsers = new ArrayList<Integer>(); HashSet<Integer> movie1Raters = usersByMovie.get(movie1); HashSet<Integer> movie2Raters = usersByMovie.get(movie2); // Return empty list if one user didn't rate any movies if (movie1Raters == null || movie2Raters == null) { return sharedUsers; } Iterator<Integer> it = movie1Raters.iterator(); while (it.hasNext()) { Integer value = (Integer) it.next(); if (movie2Raters.contains(value)) { sharedUsers.add(value); } } return sharedUsers; }
4
public static void removeAllBorders() { if (!borderEnabled()) return; for(CircleMarker marker : roundBorders.values()) { marker.deleteMarker(); } roundBorders.clear(); for(AreaMarker marker : squareBorders.values()) { marker.deleteMarker(); } squareBorders.clear(); }
3
public void addCourse(String name, String course) { /* search entire tree, if found, add course */ StudentNode currentStudent = root; StudentNode preNode = null; /* empty tree */ if (root == null) { StudentNode newNode = new StudentNode(name); newNode.courses.add(course); root = newNode; numStudents++; return; } while (currentStudent != null) { /* store pre-node */ preNode = currentStudent; /* found */ if (currentStudent.name.equals(name)) { currentStudent.courses.add(course); return; } /* traverse to next node */ currentStudent = name.compareTo(currentStudent.name) < 0 ? currentStudent.left : currentStudent.right; } /* if not found, create a new node, insert it */ StudentNode newNode = new StudentNode(name); newNode.courses.add(course); numStudents++; if (name.compareTo(preNode.name) < 0) { preNode.left = newNode; } else { preNode.right = newNode; } }
5
public User login(String userName, String password) { ArrayList<User> lista = (ArrayList<User>) userList.getUserList(); for (User us : lista) { if (userName.equals(us.getName()) && password.equals(us.getPassword())) { return us; } } return null; }
3
final Class258_Sub3 method3467(int i, int i_4_) { anInt4357++; Object object = aClass60_4361.method583((long) i, -127); if (object != null) return (Class258_Sub3) object; if (!aD4359.method4(-7953, i)) return null; TextureDefinition class12 = aD4359.getTexture(i, -6662); int i_5_ = (!((TextureDefinition) class12).aBoolean199 ? ((OpenGlToolkit) aHa_Sub2_4355).anInt7712 : 64); Class258_Sub3 class258_sub3; if (((TextureDefinition) class12).aBoolean218 && aHa_Sub2_4355.isBloomSupported()) { float[] fs = aD4359.method1(i_5_, 0.7F, false, -30824, i_5_, i); class258_sub3 = new Class258_Sub3(aHa_Sub2_4355, 3553, 34842, i_5_, i_5_, (((TextureDefinition) class12).aByte205 ^ 0xffffffff) != -1, fs, 6408); } else { int[] is; if ((((TextureDefinition) class12).anInt200 ^ 0xffffffff) == -3 || !Class251.method1915((byte) 4, ((TextureDefinition) class12).aByte213)) is = aD4359.method6(-21540, i_5_, 0.7F, i, false, i_5_); else is = aD4359.method5(true, i, 0.7F, i_5_, i_5_, i_4_ + -196); class258_sub3 = new Class258_Sub3(aHa_Sub2_4355, 3553, 6408, i_5_, i_5_, ((TextureDefinition) class12).aByte205 != 0, is, 0, 0, false); } class258_sub3.method1965(((TextureDefinition) class12).aBoolean215, ((TextureDefinition) class12).aBoolean217, 10243); if (i_4_ != 256) method3466(22); aClass60_4361.method582(class258_sub3, (long) i, (byte) -114); return class258_sub3; }
8
public static Phasor parsePhasor(String ss){ Phasor ph = new Phasor(); ss = ss.trim(); int anglePos = ss.indexOf('<'); if(anglePos==-1){ anglePos = ss.indexOf('L'); if(anglePos==-1)throw new IllegalArgumentException("no angle symbol, <, in the string, ss"); } int degPos = ss.indexOf('d'); if(degPos==-1)degPos = ss.indexOf('D'); int radPos = ss.indexOf('r'); if(radPos==-1)degPos = ss.indexOf('R'); String mag = ss.substring(0,anglePos); ph.magnitude = Double.parseDouble(mag); String phas = null; if(degPos!=-1){ phas = ss.substring(anglePos+1, degPos); ph.phaseInDeg = Double.parseDouble(mag); ph.phaseInRad = Math.toRadians(ph.phaseInDeg); } if(degPos==-1 && radPos==-1){ phas = ss.substring(anglePos+1); ph.phaseInDeg = Double.parseDouble(phas); ph.phaseInRad = Math.toRadians(ph.phaseInDeg); } if(radPos!=-1){ phas = ss.substring(anglePos+1, radPos); ph.phaseInRad = Double.parseDouble(phas); ph.phaseInDeg = Math.toDegrees(ph.phaseInRad); } ph.rectangular.polar(ph.magnitude, ph.phaseInRad); return ph; }
8
public void moveOwl() { if (move != null){ if (move.getWhere() == 0){ x += 10; } else if(move.getWhere() == 1){ //vasen x -= 10; }else if (move.getWhere() == 2){ //alas y += 10; } else if (move.getWhere() == 3) { //ylös y -= 10; } } }
5
private AbstractResource findResource (String resName, String resID, String packageName) { // Find the correct package for (ARSCFileParser.ResPackage pkg : this.resourcePackages) { // If we don't have any package specification, we pick the app's default package boolean matches = (packageName == null || packageName.isEmpty()) && pkg.getPackageName().equals(this.appPackageName); matches |= pkg.getPackageName().equals(packageName); if (!matches) continue; // We have found a suitable package, now look for the resource for (ARSCFileParser.ResType type : pkg.getDeclaredTypes()) if (type.getTypeName().equals(resID)) { AbstractResource res = type.getFirstResource(resName); return res; } } return null; }
6
public String getDescription() { if ( fullDescription == null ) { if ( description == null || isExtensionListInDescription() ) { fullDescription = description == null ? "(" : description + " (" ; // build the description from the extension list Enumeration extensions = filters.keys() ; if ( extensions != null ) { fullDescription += "." + ( String ) extensions.nextElement() ; while ( extensions.hasMoreElements() ) { fullDescription += ", ." + ( String ) extensions.nextElement() ; } } fullDescription += ")" ; } else { fullDescription = description ; } } return fullDescription ; }
6
public double newPurchase(){ Random r = new Random(); if (marketStrength == 0) marketStrength += .01; double marketEffect = marketStrength * beta + stockStrength; // strength less than one causes decrease in price, beta exaggerates/ mitigate's market's effect double d = r.nextDouble() * volatility * marketEffect; // higher volatility makes new purchase deviate further from current price int marketSentiment = Math.abs((int)(marketEffect * 10)) + 1; // +1 meant to avoid errors on nextInt when strength is zero marketSentiment = Math.abs(marketSentiment); // for use in next int if (r.nextInt(marketSentiment) == 1) d = 0-d; // adds degree of fluctuation. A market sentiment closer to zero is more likely to yield a reverse in direction of price return (price + price*d); }
2
private void message(String user_name, CommandArgsIterator args_it) throws IOException { if (args_it.hasNext()) { String dest = args_it.next(); String message = args_it.remainder(); if (dest.length() >= 1 && !message.isEmpty()) { if (dest.charAt(0) == '#') { // Message sur un salon String chan_name = dest.substring(1); if (!chan_name.isEmpty()) { Chan chan; synchronized (this._chans) { chan = this._chans.get(chan_name); } if (chan != null) { this.traceEvent("Message sur #" + chan_name); chan.sendMessage(user_name, message); this.ack(); } else this.writeCommand(Errors.ChanNotJoined); } else this.syntaxError(); } else { // Message privé Map<String, Client> users = this._server.getUsers(); Boolean success; // Pour envoyer le feedback hors du lock synchronized (users) { Client dest_user = users.get(dest); if (users.containsKey(dest)) { dest_user.sendMessage(user_name, message); success = true; } else success = false; } if (success) { this.traceEvent("Message à " + dest); this.ack(); } else this.writeCommand(Errors.UnknownUsername); } } else this.syntaxError(); } else { this.syntaxError(); } }
8
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Circuit circuit = (Circuit) o; if (eRank != null ? !eRank.equals(circuit.eRank) : circuit.eRank != null) return false; if (hRank != null ? !hRank.equals(circuit.hRank) : circuit.hRank != null) return false; if (pRank != null ? !pRank.equals(circuit.pRank) : circuit.pRank != null) return false; return true; }
9
protected void setOutput(String output) { ((MooreMachine) to.getAutomaton()).setOutput(to, output); }
0
public static double informationGainRatio(String attribute, ArrayList<HashMap<String, String>> examples, HashMap<String, String[]> attributeValues, String goalAttribute) { double iv = intrinsicValue(attribute, examples, attributeValues); if (iv == 0) { return 1; } return informationGain(attribute, examples, attributeValues, goalAttribute) / intrinsicValue(attribute, examples, attributeValues); }
1
public DonneeArgos ( String numBalise, String precision, String date, String heure, String latitude, String longitude ) { this.numBalise = numBalise; this.precision = precision; int annee = 0; int mois = 0; int jour = 0; int heures = 0; int minutes = 0; // On extrait la date et l'heure try { annee = Integer.parseInt(date.substring(0, 4)); mois = Integer.parseInt(date.substring(5, 7)) - 1; jour = Integer.parseInt(date.substring(8, 10)); heures = Integer.parseInt(heure.substring(0, 2)); minutes = Integer.parseInt(heure.substring(3, 5)); } catch ( NumberFormatException | IndexOutOfBoundsException e ) { System.out.println("Impossible de charger les nombres : " + e.toString()); } this.date = new GregorianCalendar(annee, mois, jour, heures, minutes); // On extrait les latitude et longitude try { this.latitude = Double.parseDouble(latitude); this.longitude = Double.parseDouble(longitude); } catch ( NumberFormatException e ) { System.out.println("Impossible de charger les nombres : " + e.toString()); } }
2
private void sendMessage(String text) { // Due to chunk generation eating up memory and Java being too slow about GC, we need to track memory availability int availMem = Config.AvailableMemory(); Config.Log("[Fill] " + text + " (free mem: " + availMem + " MB)"); if (notifyPlayer != null) notifyPlayer.sendMessage("[Fill] " + text); if (availMem < 200) { // running low on memory, auto-pause pausedForMemory = true; Config.StoreFillTask(); text = "Available memory is very low, task is pausing. A cleanup will be attempted now, and the task will automatically continue if/when sufficient memory is freed up.\n Alternatively, if you restart the server, this task will automatically continue once the server is back up."; Config.Log("[Fill] " + text); if (notifyPlayer != null) notifyPlayer.sendMessage("[Fill] " + text); // prod Java with a request to go ahead and do GC to clean unloaded chunks from memory; this seems to work wonders almost immediately // yes, explicit calls to System.gc() are normally bad, but in this case it otherwise can take a long long long time for Java to recover memory System.gc(); } }
3
@Override public boolean equals(Object obj) { if (super.equals(obj)) { StringTag o = (StringTag) obj; return ((data == null && o.data == null) || (data != null && data.equals(o.data))); } return false; }
4
private void TfCodProdutoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TfCodProdutoKeyReleased if (!TfCodProduto.getText().equals("")) { prodcompravenda.getForneproduto().getProduto().setCodigo(Integer.parseInt(TfCodProduto.getText())); if (!TfCodFornecedor.getText().equals("")){ if (prodcompravenda.getForneproduto().getProduto().eprodutoativo() && prodcompravenda.getForneproduto().produtodestefornecedor() && !prodcompravenda.getForneproduto().getProduto().eservico()) { TfProduto.setText(prodcompravenda.getForneproduto().getProduto().retornadescricaoproduto()); TfValorUnitario.setValue(BigDecimal.valueOf(prodcompravenda.getForneproduto().getProduto().mediavalordecompraproduto())); TfQuantidade.setValue(BigDecimal.valueOf(0)); TfValorProduto.setValue(BigDecimal.valueOf(0)); } else{ TfProduto.setText(""); TfValorUnitario.setValue(BigDecimal.valueOf(0)); TfQuantidade.setValue(BigDecimal.valueOf(0)); TfValorProduto.setValue(BigDecimal.valueOf(0)); if(!prodcompravenda.getForneproduto().produtodestefornecedor() && prodcompravenda.getForneproduto().getProduto().eprodutoativo() && !prodcompravenda.getForneproduto().getProduto().eservico()){ msg.CampoNaoPreenchido(LbNotificacao, "Este produto não pode ser comprado com este fornecedor"); } } } else { msg.CampoNaoPreenchido(LbNotificacao, "Insira o Fornecedor da Compra para que o sistema faça a busca dos Produtos!"); TfCodFornecedor.grabFocus(); } } else { TfProduto.setText(""); TfValorUnitario.setValue(BigDecimal.valueOf(0)); TfQuantidade.setValue(BigDecimal.valueOf(0)); TfValorProduto.setValue(BigDecimal.valueOf(0)); } }//GEN-LAST:event_TfCodProdutoKeyReleased
8
public static int firstPrimeAfter(int n) { for(int i = n + 1; i > n; ++i) { int factors = 0; for(int j = 1; j < (i + 2) / 2; ++j) { if((i % j) == 0) factors++; } if(factors < 2) { return i; } } return 0; }
4
public String getOneChapterContent(String ver, String bookChapter) throws ParseException, IOException { Path file = Paths.get("/home/mark/bible/content/" + ver + "/" + bookChapter + ".htm"); StringBuilder sb = new StringBuilder(); Charset charset = Charset.forName("US-ASCII"); if (ver.equals("tw")) { charset = Charset.forName("BIG5"); } String line = null; try (BufferedReader reader = Files.newBufferedReader(file, charset)) { while ((line = reader.readLine()) != null) { sb.append(line); System.out.println(line); } } catch (IOException x) { System.err.format("getOneChapterContent ...IOException:", x); System.err.format("%nver=%s", ver); System.err.format("%nbook chap=%s%n", bookChapter); System.err.format("%n%s%n", sb.toString()); // System.exit(-1); } return sb.toString(); }
3
public static boolean isTrue(String s) { if (s == null || s.length() == 0) { return false; } char c = s.charAt(0); return c == 't' || c == 'T' || c == 'y' || c == 'Y' || c == '1'; }
6
public void paintGameObjects(Graphics2D g) { if(instructions) { g.setColor(Color.WHITE); g.setFont( displayFont ); g.drawString("Player One Uses Arrow Keys.", 20, SCREEN_HEIGHT/4); g.drawString("Player Two Uses WASD.", 20, SCREEN_HEIGHT/2); g.drawString("Press 1 for one player, 2 for two.", 20, 3*SCREEN_HEIGHT/4); return; } a.paint(g); if(twoPlayer) { b.paint(g); } synchronized(objects) { for(GameObject object : objects) { object.paint(g); } } if(!game) { g.setColor(Color.WHITE); g.setFont( displayFont ); g.drawString("GAME OVER", SCREEN_WIDTH/4, SCREEN_HEIGHT/4); if(twoPlayer) { String winner = a.y < b.y ? "Player One wins." : "Player Two wins."; if(a.y == b.y) winner = "Tie."; g.drawString(winner, SCREEN_WIDTH/4, SCREEN_HEIGHT/2); } else { g.drawString("Score: " + (height*10), SCREEN_WIDTH/4, SCREEN_HEIGHT/2); } g.drawString("Press r to restart.", SCREEN_WIDTH/4, 3*SCREEN_HEIGHT/4); } }
7
public void setQuery(String q) { tmp = new Vector<String[]>(); try { ResultSet rs = statement.executeQuery(q); ResultSetMetaData meta = rs.getMetaData(); columns = meta.getColumnCount(); headers = new String[columns]; for (int i = 1; i <= columns; i++) headers[i - 1] = meta.getColumnName(i); while (rs.next()) { String[] record = new String[columns]; for (int i = 0; i < columns; i++) record[i] = rs.getString(i + 1); tmp.addElement(record); } fireTableChanged(null); } catch (Exception e) { tmp = new Vector<String[]>(); logField.setText(logField.getText() + "\nError! time: " + System.currentTimeMillis() + ",\n" + e.getMessage()); } }
4
public static List<Weapon> parseWeapons(File f){ List<Weapon> weapons = new ArrayList<>(); try { Scanner sc = new Scanner(f); while(sc.hasNextLine()){ String line = sc.nextLine(); String[] content = line.split(","); String name = content[0]; String dmgDice = content[1]; String profBonus = content[2]; String range = content[3]; String[] groups = content[4].split("-"); String properties = content[5]; // parse damagedice String[] dmg = dmgDice.split("d"); final int dicetype = Integer.parseInt(dmg[1]); final int diceamount = Integer.parseInt(dmg[0]); Diceroll d = new StandardDice(dicetype, diceamount); int proficiencyBonus = Integer.parseInt(profBonus); int shortRange = 1; int longRange = 1; if(!range.equals("-")){ String[] ranges = range.split("/"); shortRange= Integer.parseInt(ranges[0]); longRange = Integer.parseInt(ranges[1]); } String[] attributes = {""}; if(!properties.equals("-")){ attributes = properties.split("-"); } Weapon w = new StandardWeapon(name, d, proficiencyBonus, shortRange, longRange, attributes, groups); weapons.add(w); weaponMap.put(w.getName(), w); } } catch (FileNotFoundException e) { e.printStackTrace(); } return weapons; }
4
private int getIntBigEndian(byte[] a, int offs) { return (a[offs] & 0xff) << 24 | (a[offs + 1] & 0xff) << 16 | (a[offs + 2] & 0xff) << 8 | a[offs + 3] & 0xff; }
0
@POST @Path("/createEvent") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createEvent(String jsonObject) { Gson gson = new GsonBuilder().setDateFormat(WS_DATE_PATTERN).create(); Event event = null; try { event = gson.fromJson(jsonObject, Event.class); } catch (JsonSyntaxException e1) { try{ gson = new GsonBuilder().setDateFormat(JS_DATE_FORMAT).create(); event = gson.fromJson(jsonObject, Event.class); }catch (JsonSyntaxException e){ e.printStackTrace(); return makeCORS(Response.status(400)); } } EventMongoDAO mc = null; try { mc = EventMongoDAO.getInstance(); } catch (UnknownHostException e) { e.printStackTrace(); return makeCORS(Response.status(503)); } if (event.getId() != null && mc.exists(event.getId())) { return makeCORS(Response.status(400)); } else { Event ev = mc.create(event); String toReturn = gson.toJson(ev); return makeCORS(Response.ok().entity(toReturn)); } }
5
@Override public Vector substract(Vector vector) throws IllegalArgumentException { if (this.getFieldsNumber() != vector.getFieldsNumber()) { throw new IllegalArgumentException(); } for (int i = 0; i < getFieldsNumber(); i++) { try { setElementAt(i + 1, this.getElementAt(i + 1) - vector.getElementAt(i + 1)); } catch (OutOfBoundsException e) { // Jak zwykle nie wystapi e.printStackTrace(); } } return this; }
3
private static DetailObject getDetailObject(String language) { boolean objectFound = false; DetailObject detailObject = null; for (DetailObject detailObject1 : SourceScanner.detailObjects) { if (detailObject1.getLanguage().equalsIgnoreCase(language)) { objectFound = true; detailObject = detailObject1; } } if (!objectFound) { detailObject = new DetailObject(language); SourceScanner.detailObjects.add(detailObject); MainGUI.getMAINGUI().addDetails(detailObject); } return detailObject; }
3
public void drawColored(Bitmap bitmap, int color, int xo, int yo) { for (int y = 0; y < bitmap.height; y++) { int yy = y + yo; if (yy < 0 || yy >= this.height) continue; for (int x = 0; x < bitmap.width; x++) { int xx = x + xo; if (xx < 0 || xx >= this.width) continue; if (bitmap.pixels[x + y * bitmap.width] < 0) pixels[xx + yy * this.width] = color; } } }
7
public Causa eliminacionTestigoPorTeclado(){ @SuppressWarnings("resource") Scanner scanner = new Scanner (System.in); String texto; int expediente; Long dni; Causa causa = new Causa(); try { System.out.println("Eliminar Testigo de la Causa"); System.out.println("----------------------------"); while (true) { try { System.out.print("Ingrese Numero de Expediente: "); expediente = scanner.nextInt(); causa = this.getCausaByNumero(expediente); if (causa == null) { System.out.println("No existe ninguna Causa con Expediente " + expediente + ".Intente nuevamente"); } else { break; } } catch (RangeException e) { System.out.println(e.getMessage()); } } System.out.println("Datos de la Causa"); System.out.println("-----------------"); System.out.println(causa); scanner = new Scanner (System.in); while (true) { try { System.out.print("Ingrese el DNI del Testigo a eliminar de la Causa o presione [ENTER] para continuar: "); texto = scanner.nextLine(); if (texto.length()>0) { dni=Long.parseLong(texto); if (dni>0) causa.removeTestigo(dni); } break; } catch (NumberFormatException e) { System.out.println("El DNI del Testigo debe ser numerico"); } catch (ExcepcionValidacion e) { System.out.println(e.getMessage()); } } return causa; } catch (Exception e) { System.out.printf("ERROR EN EL SISTEMA: %s",e); return null; } }
9
public boolean listenSocket() { try { server = new ServerSocket(4444); System.out.println("server running on port 4444"); } catch (IOException e) { System.out.println("Could not listen on port 4444"); System.exit(-1); } //listen for new connections while (true) { try { System.out.println("in while serverlogic"); //server.accept returns a client connection connection = new ServerThread(server.accept()); System.out.println("new server object created"); connection.getCredentials(); //check username and password if (isGoodLogin(connection.recievedUsername, connection.recievedPassword, connectedClients) == true) { //create and start new Thread Thread t = new Thread(connection); t.start(); //put the username + threadobject in hashmap connectedClients.put(connection.recievedUsername, connection); connection.setRecentHashMap(connectedClients); System.out.println(connectedClients.get(connection.recievedUsername).toString()); System.out.println(connectedClients.size()); //method to set the recent hashmap of online users for the clients connection.setRecentHashMapForUsers(connectedClients); } //new users handling else if (connection.recievedUsername.startsWith("new") == true) { String message; if (creationAccount(connection.recievedUsername, connection.recievedPassword) == true) message = "[Success]Account has been created!"; else message = "[Error]Account could not be created!"; System.out.println(message); connection.out.writeUTF(message); connection.out.flush(); } else { System.err.println("Bad username or Password...or user already logged in"); } } catch (IOException e) { System.out.println("Accept failed: 4444"); System.exit(-1); } } }
6
private void cpuLoadNextProcess() { System.out.println("cpuLoadNextProcess()"); Process p = cpu.startNextProcess(); if (p != null) { p.updateProcess(CPU_ACTIVE); long processRemainingTime = p.getRemainingCPUTime(); long maxCpuTime = this.maxCpuTime; long processNextIO = p.getTimeToNextIoOperation(); long pid = p.getProcessId(); System.out.println("["+pid+"] Got process from CPU queue..."); System.out.println("["+pid+"] processRemainingTime: "+processRemainingTime); System.out.println("["+pid+"] maxCpuTime: "+maxCpuTime); System.out.println("["+pid+"] processNextIO: "+processNextIO); if (processRemainingTime < maxCpuTime && processRemainingTime < processNextIO) { // Process is finished this.newEvent(END_PROCESS, processRemainingTime); } else if (maxCpuTime < processRemainingTime && maxCpuTime < processNextIO) { // Process max time in CPU exceeded this.newEvent(SWITCH_PROCESS, maxCpuTime); } else { // Process needs to perform IO operation this.newEvent(IO_REQUEST, processNextIO); } } else { System.out.println("No process to load in CPU queue"); } }
5
int open_seekable() throws SoundException { Info initial_i = new Info(); Comment initial_c = new Comment(); int serialno; long end; int ret; int dataoffset; Page og = new Page(); // is this even vorbis...? int[] foo = new int[1]; ret = fetch_headers(initial_i, initial_c, foo, null); serialno = foo[0]; dataoffset = (int) offset; //!! os.clear(); if (ret == -1) { return (-1); } if (ret < 0) { return (ret); } // we can seek, so set out learning all about this file seekable = true; fseek(datasource, 0, SEEK_END); offset = ftell(datasource); end = offset; // We get the offset for the last page of the physical bitstream. // Most OggVorbis files will contain a single logical bitstream end = get_prev_page(og); // moer than one logical bitstream? if (og.serialno() != serialno) { // Chained bitstream. Bisect-search each logical bitstream // section. Do so based on serial number only if (bisect_forward_serialno(0, 0, end + 1, serialno, 0) < 0) { clear(); return OV_EREAD; } } else { // Only one logical bitstream if (bisect_forward_serialno(0, end, end + 1, serialno, 0) < 0) { clear(); return OV_EREAD; } } prefetch_all_headers(initial_i, initial_c, dataoffset); return 0; }
5
public HashMap<String, Character> getState() { HashMap<String, Character> points = new HashMap<String, Character>(); for (int i = 0; i < plateau.length; i++) { for (int j = 0; j < plateau[0].length; j++) { if (updates[i][j]) { System.out.println("Updated"); char sym; if(plateau[i][j]==null) sym = ' '; else { sym = (plateau[i][j].getColor().charAt(0)); sym = (plateau[i][j].getHaveBall())?Character.toLowerCase(sym):sym; } updates[i][j] = false; points.put(i + "," + j, sym); } } } return points; }
5
public void commandLine() { while (true) { System.out.print(">"); command = userInput.nextLine().split(" "); //String junk = userInput.next(); if (command[0].equals("addplayer")) { comAddplayer(); } else if (command[0].equals("removeplayer")) { comRemoveplayer(); } else if (command[0].equals("editplayer")) { comEditplayer(); } else if (command[0].equals("resetstats")) { comResetstats(); } else if (command[0].equals("displayplayer")) { comDisplayplayer(); } else if (command[0].equals("rankings")) { comRankings(); } else if (command[0].equals("startgame")) { comStartgame(); } else if (command[0].equals("exit")) { comExit(); } else { System.out.println(); } }// end loop }// end method
9
private void whereDoIGo(String urlParameter, HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{ // URL string for the file the user should be taken to next. String whereToGo; // Check if parameter is null, ie, was not supplied if(urlParameter == null){ urlParameter = DirectorEnums.NO_VALUE.name(); // Assign name of enum to String. } // Convert parameter to uppercase (give Enum.ValueOf() an uppercase argument) urlParameter = urlParameter.toUpperCase(); // Define outside of try-catch DirectorEnums enumDirector; // Get enum associated with string try{ enumDirector = DirectorEnums.valueOf(urlParameter); // return enum associated with this string }catch (IllegalArgumentException e){ enumDirector = DirectorEnums.INCORRECT_VALUE; // no enum associated with given string, assign enum. } // Switch statement using enums switch(enumDirector){ case LOGIN: whereToGo = "/Video_35_login.jsp"; break; case DOLOGIN: whereToGo = doLogin(request); break; case NEW_ACCOUNT: whereToGo = "/Video_36_NewAccount.jsp"; break; case NEW_ACCOUNT_FORM: whereToGo = newAccount(request); break; case INCORRECT_VALUE: whereToGo = "/Video_35_errorPage.jsp"; break; case NO_VALUE: whereToGo = "/index.jsp"; break; default: whereToGo = "Error in Switch Statement"; // yep, that'll throw an error but I want to see it should that happen. break; } // Forward to page request.getRequestDispatcher(whereToGo).forward(request, response); }
8
public static MyList board() { // generate positions for a square board, and let the // onBoard() function filter out the wrong positions MyList boardlist = new MyList(); for (int r = 1; r <= 17; r++) { // for every row int c = ((r % 2 == 0) ? 2 : 1); // what col to start? for (; c <= 9; c += 2) { Hexpos h = new Hexpos(r, c); if (h.onBoard()) boardlist.add(h); } } return boardlist; }
4
public void recuperar() { FileInputStream fis = null; ObjectInputStream stream = null; try { File arquivo = new File("arquivo.bin"); if (arquivo.exists()) { fis = new FileInputStream(arquivo); stream = new ObjectInputStream(fis); persistencia = (Persistencia) stream.readObject(); } } catch (Exception e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
6
public void writeHistory(DataOutput output) { try { output.writeInt(VERSION); sourcePanel.writeHistory(output); destinationPanel.writeHistory(output); int comboCount = commandCombo.getItemCount(); Vector commands = new Vector(); for (int i = 0; i < comboCount; ++i) { String nextCommand = (String) commandCombo.getItemAt(i); if (!nextCommand.trim().equals("")) { commands.add(nextCommand); } } output.writeInt(commands.size()); Iterator iter = commands.iterator(); while (iter.hasNext()) { output.writeUTF((String) iter.next()); } } catch (IOException e) { // NYI } }
4
private static void invokeServiceListenerCallback(Bundle bundle, final EventListener l, Filter filter, Object acc, final EventObject event, final Dictionary<String, Object> oldProps) { // Service events should be delivered to STARTING, // STOPPING, and ACTIVE bundles. if ((bundle.getState() != Bundle.STARTING) && (bundle.getState() != Bundle.STOPPING) && (bundle.getState() != Bundle.ACTIVE)) { return; } // Check that the bundle has permission to get at least // one of the service interfaces; the objectClass property // of the service stores its service interfaces. ServiceReference<?> ref = ((ServiceEvent) event).getServiceReference(); boolean hasPermission = true; if (hasPermission) { // Dispatch according to the filter. boolean matched = (filter == null) || filter.match(((ServiceEvent) event).getServiceReference()); if (matched) { ((ServiceListener) l) .serviceChanged((ServiceEvent) event); } // We need to send an MODIFIED_ENDMATCH event if the listener // matched previously. else if (((ServiceEvent) event).getType() == ServiceEvent.MODIFIED) { if (filter.match(oldProps)) { final ServiceEvent se = new ServiceEvent( ServiceEvent.MODIFIED_ENDMATCH, ((ServiceEvent) event).getServiceReference()); ((ServiceListener) l).serviceChanged(se); } } } }
9
@Override public void createFrom(int elementIndex, int numberOfPoints) { int size = 0; for(int i = 0; i<numberOfPoints; i++){ size = size + inData.getLength()/numberOfPoints; Float[] array = new Float[size]; for(int j = 0; j < size; j++ ){ array[j] = ((Float[])inData.getFromKit(elementIndex))[j]; } outData.addToKit(array); } }
2
public final void visitTryCatchBlock( final Label start, final Label end, final Label handler, final String type) { AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute("", "start", "start", "", getLabel(start)); attrs.addAttribute("", "end", "end", "", getLabel(end)); attrs.addAttribute("", "handler", "handler", "", getLabel(handler)); if (type != null) { attrs.addAttribute("", "type", "type", "", type); } addElement("TryCatch", attrs); }
1
public void tick() { anim.tick(x, y); if (Main.getKey("W")) y -= speed; if (Main.getKey("S")) y += speed; if (Main.getKey("A")) x -= speed; if (Main.getKey("D")) x += speed; }
4
public RegistrationPage getRegistrationPage() { if (registrationPage == null) { registrationPage = new RegistrationPage(this); } return registrationPage; }
1
public static void setMaxLitterSize(int max_litter_size) { if (max_litter_size >= 1) Grass.max_litter_size = max_litter_size; }
1
public void changeOrAdd(MindmapLastStateStorage pStore) { boolean found = false; for (Iterator it = mLastStatesMap.getListMindmapLastStateStorageList() .iterator(); it.hasNext(); ) { MindmapLastStateStorage store = (MindmapLastStateStorage) it.next(); if (Tools.safeEquals(pStore.getRestorableName(), store.getRestorableName())) { // deep copy store.setLastZoom(pStore.getLastZoom()); store.setLastSelected(pStore.getLastSelected()); store.setX(pStore.getX()); store.setY(pStore.getY()); Vector listCopy = new Vector(pStore.getListNodeListMemberList()); store.clearNodeListMemberList(); for (Iterator it2 = listCopy.iterator(); it2.hasNext(); ) { NodeListMember member = (NodeListMember) it2.next(); store.addNodeListMember(member); } found = true; setLastChanged(store); break; } } if (!found) { setLastChanged(pStore); mLastStatesMap.addMindmapLastStateStorage(pStore); } // size limit if (mLastStatesMap.sizeMindmapLastStateStorageList() > LIST_AMOUNT_LIMIT) { // make map from date to object: TreeMap dateToStoreMap = new TreeMap(); for (Iterator it = mLastStatesMap .getListMindmapLastStateStorageList().iterator(); it .hasNext(); ) { MindmapLastStateStorage store = (MindmapLastStateStorage) it .next(); dateToStoreMap .put(Long.valueOf(-store.getLastChanged()), store); } // clear list mLastStatesMap.clearMindmapLastStateStorageList(); // rebuild int counter = 0; for (Iterator it = dateToStoreMap.entrySet().iterator(); it .hasNext(); ) { Entry entry = (Entry) it.next(); mLastStatesMap .addMindmapLastStateStorage((MindmapLastStateStorage) entry .getValue()); counter++; if (counter >= LIST_AMOUNT_LIMIT) { // drop the rest of the elements. break; } } } }
8
boolean shootAt(int row, int column){ if(this.isSunk()){ return false; } if(this.isHorizontal()){ for(int j = 0; j < this.getLength(); j++){ // System.out.println(this.bowRow + "," + this.bowColumn + j); // System.out.println(row + "," + column); if(this.bowRow == row && column == j + this.bowColumn){ hit[j] = true; return true; } } } else{ for(int i = 0; i < this.getLength(); i++){ // System.out.println(i + this.bowRow + "," + this.bowColumn); // System.out.println(row + "," + column); if(this.bowColumn == column && row == i + this.bowRow){ hit[i] = true; return true; } } } System.out.println("none of the conditions work"); return false; }
8
static public DalcPlaylist getInstance() { if (m_instance == null) { m_instance = new DalcPlaylist(); } return m_instance; }
1
public void train(int maxIter, int windowSize, double initStep, double shrinkage){ int iteration = m_iteration; // Step 0: output the settings System.out.println("[Info]LambdaRank configuration:"); System.out.format("\tOptimization Type %s, Lambda %.3f, Shrinkage %.3f, WindowSize %d\n", m_oType, m_lambda, shrinkage, windowSize); System.out.format("\tInitial step size %.1f, Steps %d, Iteration %d\n", initStep, maxIter, iteration); System.out.println("Iter\tMisorder\tLogLilikelihood\tPerf"); // Step 1: setup the workers int workerSize = initWorkers(windowSize, maxIter, initStep, shrinkage); // Step 2: start multi-thread training double weight = 1.0 / workerSize, performance = 0; int querySize = m_queries.size(); long starttimer = System.currentTimeMillis(); double obj = 0, perf = 0; int misorder = 0; // //evaluate initial performance // WaitTillFinish(OperationType.OT_evaluate); // for(LambdaRankWorker worker:m_workers){ // obj += worker.m_obj; // perf += worker.m_perf; // misorder += worker.m_misorder; // } // perf /= querySize; // obj -= 0.5 * m_lambda * Utils.L2Norm(m_weight);//to be maximized // System.out.format("0\t%d\t%.2f\t%.4f\n", misorder, obj, perf); for(int i=0; i<iteration; i++){ // training operation WaitTillFinish(OperationType.OT_train); // aggregate the learned weights from workers Arrays.fill(m_weight, 0); for(LambdaRankWorker worker:m_workers) Utils.add2Array(m_weight, worker.getWeight(), weight); //evaluate training performance WaitTillFinish(OperationType.OT_evaluate); obj = 0; perf = 0; misorder = 0; for(LambdaRankWorker worker:m_workers){ obj += worker.m_obj; perf += worker.m_perf; misorder += worker.m_misorder; } perf /= querySize; obj -= 0.5 * m_lambda * Utils.L2Norm(m_weight);//to be maximized if (performance>0){ if (performance<=perf)//become better iteration--; else//become worse iteration = Math.min(MAX_TRAIN_ITER, iteration+2); } performance = perf; System.out.format("%d\t%d\t%.2f\t%.4f\n", 1+i, misorder, obj, perf); } System.out.format("[Info]Training procedure takes %.2f seconds to finish...\n", (System.currentTimeMillis()-starttimer)/1000.0); }
5
public int compare(final Delta<?> a, final Delta<?> b) { final int posA = a.getOriginal().getPosition(); final int posB = b.getOriginal().getPosition(); if (posA > posB) { return 1; } else if (posA < posB) { return -1; } return 0; }
4
public void saveDefaults() { if (file == null) { file = new File(InstaScatter.ins.getDataFolder(), name); } if (!file.exists()) { InstaScatter.ins.saveResource(name, false); } }
2
@Override public void map(IntWritable key, IntArrayWritable value, OutputCollector<IntWritable, IntArrayWritable> output, Reporter reporter) throws IOException { IntWritable[] xMovie = (IntWritable[]) value.toArray(); Set<Integer> imdbMovie = new HashSet<Integer>(); for(int i =0 ;i<xMovie.length; i++) { imdbMovie.add(xMovie[i].get()); } Map<Integer, Float> score = new HashMap<Integer, Float>(); float minScore = Float.MAX_VALUE; for(Entry<Integer, Set<Integer>> e: nflixCluster.entrySet()){ Set<Integer> intersection = new HashSet<Integer>(imdbMovie); Set<Integer> union = new HashSet<Integer> (imdbMovie); intersection.retainAll(e.getValue()); float interSize = intersection.size(); union.addAll(e.getValue()); float unionSize = union.size(); float dist= Float.MAX_VALUE; if(unionSize>0) dist = 1-(interSize/unionSize); if(dist<minScore) { minScore = dist; } score.put(e.getKey(), dist); } List<Integer> out = new ArrayList<Integer>(); float threshold = Constant.CLUSTER_MAP_THRESHOLD*minScore; for(Entry<Integer, Float> e: score.entrySet()) { if(e.getValue()<=threshold) out.add(new Integer(e.getKey())); } opValue.setIntegerCollection(out); output.collect(key, opValue); }
6
public static void commandHandler(String cmd) throws IOException { // switch(String) doesn't exist on JDK 6 (only 7)... Resorting to a series of ifelse statments if(cmd.contains("/query-for-peers")) { System.out.println("Querying directory server..."); sendToDirectory("QUERY", null, null); } else if(cmd.contains("/go-online")) { System.out.println("Informing directory server..."); String data[] = {"", ""}; sendToDirectory("ONLINE", data, username); runChatServer(); } else if(cmd.contains("/go-offline")) { System.out.println("Informing directory server..."); sendToDirectory("OFFLINE", null, null); endChatServer(); } else if(cmd.contains("/join-room")) { if(cmd.length() < 11) { System.out.println("Please specify a chat room to join"); } else { for (String[] roomListing : rooms) { if(roomListing[0].equals(cmd.substring(11))) { System.out.println("Joining chat room \""+roomListing[0]+"\"..."); System.out.println("Informing directory server..."); String data[] = {"", cmd.substring(11)}; sendToDirectory("JOINED", data, cmd.substring(11)); consoleState = cmd.substring(11); joinChatServer(roomListing[1], Integer.parseInt(roomListing[2])); } } System.out.println("No room by that name!"); } } else if(cmd.contains("/quit")) { System.out.println("Quitting!"); } else if(cmd.contains("/test-rdt")) { System.out.println("Sending a payload > 58 bytes to directory server..."); sendToDirectory("RDTCHECK", null, "AAAAAAAAAAAAAAAAAAABBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCC"); } else { System.out.println("You need to join a room before chatting!"); } }
9
static final public void MessageSend() throws ParseException { PrimaryExpression(); jj_consume_token(DOT); Identifier(); jj_consume_token(LPAREN); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LPAREN: case NOT: case FALSE: case NEW: case THIS: case TRUE: case INTEGER_LITERAL: case IDENTIFIER: ExpressionList(); break; default: jj_la1[14] = jj_gen; ; } jj_consume_token(RPAREN); }
9
public Cookie getUsuarioLogado() { Cookie[] cookies = this.cookies; if(cookies == null) return null; for (Cookie cookie : cookies) { if(cookie.getName().equals("usuarioLogado")){ return cookie; } } return null; }
3
public double calculoCoeficiente(double unPrecio){ if(unPrecio>500){ return(1.35);} else{ return(1.1);} }
1
double[] randomSample() { double[] sample = new double[n]; for (int i = 0; i < n; i++) { sample[i] = (lowBound[i] + generator.nextDouble() * (upBound[i] - lowBound[i])); } return sample; }
1
public synchronized byte[] encode(String str, int size) { byte abyte0[] = null; if (size > 0) { abyte0 = f; f = new byte[size]; } g = 0; h = 0; int l = str.length(); e += l; for (int j1 = 0; j1 < l;) { Integer integer = null; int i1 = j1 + 1; Hashtable hashtable = c; do { if (j1 >= l) { break; } char c1 = str.charAt(j1); Integer integer1 = (Integer) hashtable.get(b(c1)); if (integer1 != null) { i1 = j1 + 1; integer = integer1; } hashtable = (Hashtable) hashtable.get(c(c1)); if (hashtable == null) { break; } j1++; } while (true); j1 = i1; if (integer == null) { a(a); a(0x10000000 + str.charAt(j1 - 1)); } else { a(integer.intValue()); } } b(); byte abyte1[] = new byte[h]; System.arraycopy(f, 0, abyte1, 0, h); d += h; if (size > 0) { f = abyte0; } return abyte1; }
8
public String toString() { String equipmentString = ""; int i = 1; for (Field f : EquipmentSet.class.getFields()) { if (!f.getType().isPrimitive()) { try { equipmentString += i + ") " + f.getName() + ": " + f.get(this) + "\n"; } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } i++; } } return equipmentString; }
4
@Override public Iterator<String> iterator() { return cookies.keySet().iterator(); }
0
public String toString() { String output = ""; for (int i = 0; i < lists.length; i++) { if (i <= lists.length && lists[i] != null) { if (lists[i].toString() != null) { output += lists[i].toString(); output += "; "; } } } return output; }
4
public int getMinJaar() { int jaar = 99999; // Itereer de datasets for (DataSet set: this.datasets) { for (Category cat: set.categories) { for (SubCategory scat: cat.subcategories) { SubCategory subcat = new SubCategory(scat.id, scat.naam, scat.datatype, scat.weight, scat.red, scat.green, scat.blue, false); for (Period per: scat.periods) { if (per.year < jaar) { jaar = per.year; } } } } } return jaar; }
5
public static void main(String[] args) { try(AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open()) { if (socketChannel.isOpen()) { Set<SocketOption<?>> socketOptions = socketChannel.supportedOptions(); System.out.println(socketOptions); socketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024); socketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); socketChannel.setOption(StandardSocketOptions.SO_SNDBUF, 4 * 1024); socketChannel.connect(new InetSocketAddress("127.0.0.1", 5555)); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); ByteBuffer buffer = ByteBuffer.wrap("welcome to here".getBytes()); ByteBuffer randomBuffer; CharsetDecoder charsetDecoder = Charset.defaultCharset().newDecoder(); Future<Integer> future = socketChannel.write(buffer); while (!future.isDone()) { System.out.println("echo to wait write completeed........."); } System.out.println("write count is:"+future.get()); while (socketChannel.read(byteBuffer).get() != -1) { byteBuffer.flip(); System.out.println("read data is :"+charsetDecoder.decode(byteBuffer)); if (byteBuffer.hasRemaining()) { byteBuffer.compact(); }else{ byteBuffer.clear(); } int i = new Random().nextInt(100); if (i == 50) { System.out.println("find the number ......"); break; } randomBuffer = ByteBuffer.wrap(("echo number is :" + i).getBytes()); socketChannel.write(randomBuffer); } } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }
9
public boolean contains(Attributes attributeList) { return indexOf(attributeList) >= 0; }
0
@Override public boolean deleteICNum(String id, double num) { // TODO Auto-generated method stub double icnum = getICNum(id); double totalNum = 0; int status = memberDaoImpl.getICStatus(id); if (icnum < num) { if (status >= 6) { memberDaoImpl.setICStatus(id, 6); memberDaoImpl.alterStatus(id, MemberStatus.STOP.toString()); } else { memberDaoImpl .setICStatus(id, memberDaoImpl.getICStatus(id) + 1); memberDaoImpl.alterStatus(id, MemberStatus.SUSPEND.toString()); } return false; } else { if (memberDaoImpl.getSingleMemberBaseInfo(id).getStatus() .equals(MemberStatus.CANCEL.toString())) { return false; } else { totalNum = icnum - num; memberDaoImpl.deleteICNum(id, totalNum); memberDaoImpl.setICStatus(id, 0); memberDaoImpl.alterStatus(id, MemberStatus.NORMAL.toString()); return true; } } }
3
public static Integer getBoyToGirlRashiDistance(Rashi boyRashi, Rashi girlRashi) { int boyNumber = boyRashi.ordinal() + 1; int girlNumber = girlRashi.ordinal() + 1; int distance = 0; if (boyNumber < girlNumber) { distance = girlNumber - (boyNumber - 1); } if (boyNumber > girlNumber) { distance = (girlNumber + 13) - boyNumber; } if (boyNumber == girlNumber) { distance = 1; } return distance; }
3
@SuppressWarnings("unchecked") public <T> T getVariable(String name, T type) throws InvalidParameterException, TesseractException { requireState(State.INITIALIZED); int rv = 0; if (type instanceof Integer) { IntBuffer value = IntBuffer.allocate(1); rv = api.TessBaseAPIGetIntVariable(handle, name, value); checkGetVariableReturnValue(rv, name); return (T)new Integer(value.get()); } else if (type instanceof Boolean) { IntBuffer value = IntBuffer.allocate(1); rv = api.TessBaseAPIGetBoolVariable(handle, name, value); checkGetVariableReturnValue(rv, name); return (T)Boolean.valueOf(toBoolean(value.get())); } else if (type instanceof Double) { DoubleBuffer value = DoubleBuffer.allocate(1); rv = api.TessBaseAPIGetDoubleVariable(handle, name, value); checkGetVariableReturnValue(rv, name); return (T)new Double(value.get()); } else if (type instanceof String) { String result = api.TessBaseAPIGetStringVariable(handle, name); if (result == null) { Map<String, String> map = Collections.singletonMap(name, ""); throw new InvalidParameterException("Could not retrieve the requested parameter", map); } return (T)result; } else { Map<String, String> map = Collections.singletonMap(name, ""); throw new InvalidParameterException( "Could not get variable. Unsupported type: " + type.getClass().getName() + ". Excepted Integer, Double, Boolean, or String", map); } }
5
public void takeTurn(AtomicReference<Player> whoseTurn) throws InterruptedException { this.gameStillRunning = true; while (this.gameStillRunning) { for (int i = 0; i < this.playerList.size(); i++) { Player player = this.playerList.get(i); whoseTurn.set(player); System.out.println(whoseTurn.get().getName()); Move move = player.makeAMove(); if (move == null) { // Client disconnected this.gameStillRunning = false; break; } if (this.board.makeMove(move) == false) { System.out.println("Wrong move!"); // Give them another chance i--; continue; } else { // Signal the "move-made" event this.onMoveMade(move); int result = this.checkMoveIsWin(move); if (result == 1 || result == -1) { // Tell everybody that the game ended // But a game-end also starts a new game this.onGameEnd(result, player); break; } } } } }
6
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Location other = (Location) obj; if (Double.doubleToLongBits(this.row) != Double.doubleToLongBits(other.row)) { return false; } if (Double.doubleToLongBits(this.column) != Double.doubleToLongBits(other.column)) { return false; } if (this.displayed != other.displayed) { return false; } if (this.visited != other.visited) { return false; } return true; }
6
public static File[] saveAs(Saveable saveable) { if (saveable == null) { return new File[0]; } String path = saveable.getPreferredSavePath(); File result = StdFileDialog.choose(UIUtilities.getComponentForDialog(saveable), false, SAVE_AS, PathUtils.getParent(path), PathUtils.getLeafName(path), saveable.getAllowedExtensions()); File[] files = result != null ? saveable.saveTo(result) : new File[0]; for (File file : files) { RecentFilesMenu.addRecent(file); } return files; }
3
public Ruutu seuraavaRuutu(Ruutu ruutu, int suunta) { int vipu=(suunta)%4; switch (vipu) { case 0: if (ruutu.getY()==koko) { return null; } ruutu=pelilauta[ruutu.getX()][ruutu.getY()+1]; break; case 1: if (ruutu.getX()==koko) { return null; } ruutu=pelilauta[ruutu.getX()+1][ruutu.getY()]; break; case 2: if (ruutu.getY()<=0) { return null; } ruutu=pelilauta[ruutu.getX()][ruutu.getY()-1]; break; case 3: if (ruutu.getX()<=0) { return null; } ruutu=pelilauta[ruutu.getX()-1][ruutu.getY()]; break; } return ruutu; }
8
public String toString(){ String clause = ""; for (int i = 0; i < literals.size() - 1; i++) { clause += getLiteral(i) + " OR "; } if(literals.size() > 0){ clause += getLiteral(literals.size() -1); } return clause; }
2
public void mouseClicked(MouseEvent e) { if (image !=null && tileset) { if (e.getX()>=0 && e.getX() <image.getWidth() && e.getY() >= 0 && e.getY() < image.getHeight()) { tileSelected = new Vector<Integer>(); x0 = (e.getX()/(8*zoom)); y0 = (e.getY()/(8*zoom)); tileSelected.add(x0 + (y0*(image.getWidth()/(8*zoom)))); repaint(); } } }
6
@Test public void calcMeanValues_test() { try{ double [][]mat1= {{1.0,2.0}, {3.0,1.0}}; PCA pca = new PCA(mat1); PCA.calcMeanValues(mat1); pca.getEigenValues(); pca.getEigenVectors(); pca.getVectorsZeroMean(); pca.getResultingVectors(); pca.getMeanValues(); double[] result=PCA.calcMeanValues(mat1); double [] exp={1.5,2.0}; Assert.assertArrayEquals(exp, result, 0.001); } catch (Exception e) { // TODO Auto-generated catch block fail("Not yet implemented"); } }
1
private UnitPlayer randomPositionAvatar() { int id = -1; //Get the current Highest ID to set the new Avatars ID to one higher than that ID for (int x = 0; x < gameBoard.length; x++) { for (int y = 0; y < gameBoard[0].length; y++) { if (gameBoard[x][y] instanceof UnitPlayer) { id = Math.max(id, ((UnitPlayer) gameBoard[x][y]).getID()); } } } //Generate random map positions on the map until one is free then put the player there. while(true){ //Limited until map scrolling is implemented. int x = 6;//(int) (Math.random() * gameBoard.length); int y = 5;///(int) (Math.random() * gameBoard[0].length); if(gameBoard[x][y] == null){ gameBoard[x][y] = new UnitPlayer(new Point(x,y), id+1); return (UnitPlayer) gameBoard[x][y]; } } }
5
@Override public ArrayList<Task> findAllActive(Boolean active) { ArrayList taskList = new ArrayList(); try { connection = getConnection(); ptmt = connection.prepareStatement(QUERY_SELECT + "WHERE active=?;"); ptmt.setBoolean(1, active); resultSet = ptmt.executeQuery(); while (resultSet.next()) { Task task = new Task(); task.setDescription(resultSet.getString(DESCRIPTION)); task.setTitle(resultSet.getString(TITLE)); task.setIdtask(resultSet.getInt(ID_TASK)); task.setIdOwner(resultSet.getInt(ID_OWNER)); task.setIdExecutor(resultSet.getInt(ID_EXECUTOR)); task.setActive(resultSet.getBoolean(ACTIVE)); task.setDone(resultSet.getBoolean(DONE)); taskList.add(task); } } catch (SQLException ex) { Logger.getLogger(TaskDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (ptmt != null) { ptmt.close(); } if (connection != null) { connection.close(); } if (resultSet != null) { resultSet.close(); } } catch (SQLException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } } return taskList; }
6
private void getData(){ try { cbSubject.removeAllItems(); cbObject.removeAllItems(); cbVerb.removeAllItems(); cbLocation.removeAllItems(); cbLocationObject.removeAllItems(); ConnectDatabase cdb = new ConnectDatabase(); ResultSet result = cdb.st.executeQuery("SELECT idsubjects, SubjectName FROM subjects"); cbSubject.addItem(new comboItem("", -1)); cbObject.addItem(new comboItem("", -1)); while(result.next()) { cbSubject.addItem(new comboItem(result.getString("SubjectName"), result.getInt("idsubjects"))); cbObject.addItem(new comboItem(result.getString("SubjectName"), result.getInt("idsubjects"))); } result = cdb.st.executeQuery("SELECT idevents, EventName FROM events"); cbVerb.addItem(new comboItem("", -1)); while(result.next()) { cbVerb.addItem(new comboItem(result.getString("EventName"), result.getInt("idevents"))); } result = cdb.st.executeQuery("SELECT idplaces, PlaceName FROM places"); cbLocation.addItem(new comboItem("", -1)); cbLocationObject.addItem(new comboItem("", -1)); while(result.next()) { cbLocation.addItem(new comboItem(result.getString("PlaceName"), result.getInt("idplaces"))); cbLocationObject.addItem(new comboItem(result.getString("PlaceName"), result.getInt("idplaces"))); } cdb.st.close(); } catch( Exception e ) { e.printStackTrace(); } ConnectDatabase cdb = new ConnectDatabase(); String Query = "SELECT IFNULL(subjects.SubjectTypesID,'-1') as SubjectTypesID, subjects.SubjectName, places.PlaceName, events.EventName, IFNULL(o.SubjectTypesID,'') as objTypesID, IFNULL(o.SubjectName, '') as ObjectName, IFNULL(po.PlaceName, '') as ObjPlaceName from sentences " + " left join subjects on sentences.SubjectID = subjects.idsubjects" + " left join subjects o on sentences.ObjectID = o.idsubjects" + " left join events on sentences.VerbID = events.idevents" + " left join places on sentences.LocationID = places.idplaces" + " left join places po on sentences.LocationObjectID = po.idplaces "; try { ResultSet result = cdb.st.executeQuery(Query); String SubType = "-1", SubName, SubPlaceName, Verb, ObjName, ObjPlaceName, ObjType= "-1"; textPane.setText(""); while(result.next()) { SubType = result.getString("SubjectTypesID"); ObjType = result.getString("objTypesID"); SubName = result.getString("subjects.SubjectName"); SubPlaceName = result.getString("places.PlaceName"); Verb = result.getString("events.EventName"); ObjName = result.getString("ObjectName"); ObjPlaceName = result.getString("ObjPlaceName"); StyledDocument doc = textPane.getStyledDocument(); System.out.println(SubName); System.out.println(SubType); try { Style style = textPane.addStyle("Style", null); if (SubType.equals("0")){ StyleConstants.setForeground(style, Color.blue);} else{StyleConstants.setForeground(style, Color.red);} doc.insertString(doc.getLength(), SubName + " ", style); StyleConstants.setForeground(style, Color.orange); doc.insertString(doc.getLength(), " (" + SubPlaceName + ") ", style); StyleConstants.setForeground(style, Color.gray); doc.insertString(doc.getLength(), Verb +" ", style); if (ObjType.equals("0")){ StyleConstants.setForeground(style, Color.blue);} else{StyleConstants.setForeground(style, Color.red);} doc.insertString(doc.getLength(), ObjName, style); StyleConstants.setForeground(style, Color.orange); doc.insertString(doc.getLength(), " (" + ObjPlaceName + ") \n", style); } catch (BadLocationException ex){} } cdb.st.close(); } catch(SQLException ex){System.out.print(ex);} }
9
public void start() { CountdownTimer.setDELTA_TARGET(Constants.DELTA_TARGET); game = Game.getInstance(); final int DELTA_TARGET_NANOS = Constants.DELTA_TARGET * 1000 * 1000 * TICK_RENDER_RATIO; while (true) { long timeStart = System.nanoTime(); BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(3); continue; } // ##### tick and render ##### for (int i = 0; i < TICK_RENDER_RATIO; i++) tick(); render(bs.getDrawGraphics()); if (bs != null) bs.show(); regulateFPS(timeStart, DELTA_TARGET_NANOS); } }
4
int NNI( double[][] avgDistArray, int count ) { edge e, centerEdge; edge[] edgeArray; direction[] location; heap p,q; int i; int possibleSwaps; double[] weights; p = new heap(size+1); q = new heap(size+1); edgeArray = new edge[size+1]; weights = new double[size+1]; location = new direction[size+1]; for (i=0;i<size+1;i++) { weights[i] = 0.0; location[i] = direction.NONE; } e = root.leftEdge.findBottomLeft(); /* *count = 0; */ while ( null != e ) { edgeArray[e.head.index+1] = e; location[e.head.index+1] = NNIEdgeTest( e,avgDistArray,weights,e.head.index+1 ); e = depthFirstTraverse( e ); } possibleSwaps = p.makeThreshHeap(q,weights,size+1,0.0); p.permInverse( q,size+1 ); /*we put the negative values of weights into a heap, indexed by p with the minimum value pointed to by p[1]*/ /*p[i] is index (in edgeArray) of edge with i-th position in the heap, q[j] is the position of edge j in the heap */ while ( weights[p.p[1]] < 0) { centerEdge = edgeArray[p.p[1]]; count++; weight += weights[p.p[1]]; NNItopSwitch( edgeArray[p.p[1]], location[p.p[1]], avgDistArray ); location[p.p[1]] = direction.NONE; weights[p.p[1]] = 0.0; /*after the NNI, this edge is in optimal configuration*/ p.popHeap(q,weights,possibleSwaps--,1); /*but we must retest the other four edges*/ e = centerEdge.head.leftEdge; possibleSwaps = NNIRetestEdge( p,q,e,avgDistArray,weights, location,possibleSwaps ); e = centerEdge.head.rightEdge; possibleSwaps = NNIRetestEdge( p,q,e,avgDistArray,weights, location,possibleSwaps ); e = centerEdge.siblingEdge(); possibleSwaps = NNIRetestEdge( p,q,e,avgDistArray,weights, location,possibleSwaps ); e = centerEdge.tail.parentEdge; possibleSwaps = NNIRetestEdge( p,q,e,avgDistArray,weights, location,possibleSwaps ); } return count; }
3
@Override public Ingredient addIngredient(String s) { Ingredient c = getIngredient(s); if(c != null){ return c; } c = new Ingredient(getNextId(), s.toUpperCase(Locale.ENGLISH)); ingredientRepository.add(c); return c; }
1
private void drawSouth(Terrain[][] currentBoard, Entities[][] currentObjects, Graphics g) { //Same logic as above but reversed x, y in respect to board array to draw "upside down" Location playerDir = boardState.getPlayerCoords(); for (int i = 0; i < currentBoard.length; i++) { for (int j = 0; j < currentBoard[0].length; j++) { double x = ((i - currentBoard.length + 6 + (playerDir.x)) * 0.5 * width / 10) - ((j - currentBoard[0].length + 6 + (playerDir.y)) * 0.5 * width / 10) + (10 / 1.75) * (int) width / 13; double y = ((i - currentBoard.length + 6 + (playerDir.x)) * 0.5 * height / (15)) + ((j - currentBoard[0].length + 6 + (playerDir.y)) * 0.5 * height / (15)) + (10 / 3) * (int) height / 21; if (currentBoard[currentBoard.length - 1 - i][currentBoard[0].length - 1 - j] != null) g.drawImage( currentBoard[currentBoard.length - 1 - i][currentBoard[0].length - 1 - j].img, (int) x, (int) y, (int) width / 10, (int) height / 15, null); else { System.out.println("Error!"); } } } for (int i = 0; i < currentBoard.length; i++) { for (int j = 0; j < currentBoard[0].length; j++) { if (currentObjects[currentObjects.length - 1 - i][currentObjects[0].length - 1 - j] != null) { double x = ((i - currentBoard.length + 6 + (playerDir.x)) * 0.5 * width / 10) - ((j - currentBoard[0].length + 6 + (playerDir.y)) * 0.5 * width / 10) + (10 / 1.75) * (int) width / 13 - (currentObjects[currentObjects.length - 1 - i][currentObjects[0].length - 1 - j].imgs[1].getWidth(null) * (width / startingWidth) - width/10)/2; double y = ((i - currentBoard.length + 6 + (playerDir.x)) * 0.5 * height / 15) + ((j - currentBoard[0].length + 6 + (playerDir.y)) * 0.5 * height / 15) + (10 / 3) * (int) height / 21 + (0.75 * height / 15) - (currentObjects[currentObjects.length - 1 - i][currentObjects[0].length - 1 - j].imgs[1].getHeight(null) * (height / startingHeight)); g.drawImage( currentObjects[currentObjects.length - 1 - i][currentObjects[0].length - 1 - j].imgs[1], (int) x, (int) y, (int) (currentObjects[currentObjects.length - 1 - i][currentObjects[0].length - 1 - j].imgs[1] .getWidth(null) * (width / startingWidth)), (int) (currentObjects[currentObjects.length - 1 - i][currentObjects[0].length - 1 - j].imgs[1] .getHeight(null) * (height / startingHeight)), null); } } } }
6
public void kulkusuunnanKustannus(int i, int j) { if ((i == 0 && j == 0) || (i == 0 && j == 2) || (i == 2 && j == 0) || (i == 2 && j == 2)) { naapuri.setPaino(kulmittain); // Kulmittain } else { naapuri.setPaino(sivuttain); // Suoraan sivussa } }
8
public static Controller getController(ControllerType type) { switch (type) { case TREE_CONTROLLER: break; case DOOR_CONTROLLER: return new DoorController(); case ENTRANCE_CONTROLLER: return new EntranceController(); } return null; }
3
@Override public void keyPressed(KeyEvent key) { switch (key.getKeyCode()) { case KeyEvent.VK_UP: System.out.println("pressed: Key Up"); break; case KeyEvent.VK_DOWN: System.out.println("pressed: Key Down"); break; case KeyEvent.VK_LEFT: if(!moveLeft){ moveLeft = true; ball.move(moveRight, moveLeft); System.out.println("pressed: Key Left"); } break; case KeyEvent.VK_RIGHT: if(!moveRight){ moveRight = true; ball.move(moveRight, moveLeft); System.out.println("pressed: Key Right"); } break; case KeyEvent.VK_SPACE: ball.furtherjump = true; ball.jump(); System.out.println("pressed: Jump"); break; default: break; } }
7
protected static void importFile(DocumentInfo docInfo, FileProtocol protocol) { openFile(docInfo, protocol, MODE_IMPORT) ; }
0
* @param settlement The <code>Settlement</code> that is trading. */ private void attemptBuyFromSettlement(Unit unit, Settlement settlement) { Player player = freeColClient.getMyPlayer(); Goods goods = null; // Get list of goods for sale List<Goods> forSale = askServer().getGoodsForSaleInSettlement(freeColClient.getGame(), unit, settlement); for (;;) { if (forSale.isEmpty()) { // There is nothing to sell to the player gui.showInformationMessage(settlement, "trade.nothingToSell"); return; } // Choose goods to buy goods = gui.showSimpleChoiceDialog(unit.getTile(), "buyProposition.text", "buyProposition.nothing", forSale); if (goods == null) break; // Trade aborted by the player int gold = -1; // Initially ask for a price for (;;) { gold = askServer().buyProposition(unit, settlement, goods, gold); if (gold <= 0) { showTradeFail(gold, settlement, goods); return; } // Show dialog for buy proposal boolean canBuy = player.checkGold(gold); switch (gui.showBuyDialog(unit, settlement, goods, gold, canBuy)) { case CANCEL: // User cancelled return; case BUY: // Accept price, make purchase if (askServer().buyFromSettlement(unit, settlement, goods, gold)) { gui.updateMenuBar(); // Assume success } return; case HAGGLE: // Try to negotiate a lower price gold = gold * 9 / 10; break; default: throw new IllegalStateException("showBuyDialog fail"); } } } }
9
public int driveTheCar(int distanceTravelled) { if (isCarRented() == true || fuelInCar > 0){ int consumptionRate; if (distanceTravelled <= 50){ consumptionRate = distanceTravelled/10; return consumptionRate; } else { consumptionRate = ((distanceTravelled - 50)/15) + 5; return consumptionRate; } } else { return 0; } }
3
void updateContentInfo() { Map<String, Integer> groups=new HashMap(); int dayLenght=0; for(String name:Day.getAllDays().keySet()) { Day d=Day.getAllDays().get(name); for(DayEvent e:d.getEventList()){ if(!e.isUnused()){ if(groups.keySet().contains(e.getSubjectName())){ int cur=(int)groups.get(e.getSubjectName())+e.getEventLength(); groups.put(e.getSubjectName(),cur); }else{ groups.put(e.getSubjectName(),e.getEventLength()); } dayLenght+=e.getEventLength(); } } contentInfoPanel.removeAll(); for(String s:groups.keySet()){ contentInfoPanel.add(new JLabel(s+" "+(int)groups.get(s)/60+"ч."+(int)groups.get(s)%60+"м.")); } this.infoBar.setText("Длинна недели "+dayLenght/60+"ч. "+dayLenght%60+"м."); } this.validate(); this.repaint(); }
5
private Observer createObserver() { return new Observer() { @Override public void update(final String event) { switch (event) { case "Opened": int count = cell.countNeighborsWithMines(); refresh((count == 0) ? "" : Integer.toString(count)); break; case "Marked": marked = true; notifyObservers("marked"); break; case "errorMarked": notifyObservers("errorMarked"); break; case "Locked": notifyObservers("*"); break; case "Exploded": notifyObservers("**"); Action act = factory.createAction("GameOver"); if (act != null) act.execute(); break; default: restart(); } } }; }
7
public static void printStepCounts(DualGbState state) { System.out.println("size: "+state.stateBufferL.size() + " + " + state.stateBufferR.size()); int minStepCountL = Integer.MAX_VALUE; int maxStepCountL = Integer.MIN_VALUE; int minDelayStepCountL = Integer.MAX_VALUE; int maxDelayStepCountL = Integer.MIN_VALUE; for(State s : state.stateBufferL.getStates()) { if (minStepCountL > s.stepCount) { minStepCountL = s.stepCount; minDelayStepCountL = s.delayStepCount; } if (maxStepCountL < s.stepCount) { maxStepCountL = s.stepCount; maxDelayStepCountL = s.delayStepCount; } if(s.stepCount < state.gbL.stepCount) state.gbL.restore(s); } int minStepCountR = Integer.MAX_VALUE; int maxStepCountR = Integer.MIN_VALUE; int minDelayStepCountR = Integer.MAX_VALUE; int maxDelayStepCountR = Integer.MIN_VALUE; for(State s : state.stateBufferR.getStates()) { if (minStepCountR > s.stepCount) { minStepCountR = s.stepCount; minDelayStepCountR = s.delayStepCount; } if (maxStepCountR < s.stepCount) { maxStepCountR = s.stepCount; maxDelayStepCountR = s.delayStepCount; } if(s.stepCount < state.gbR.stepCount) state.gbR.restore(s); } System.out.println("min: " + minStepCountL + "(-" + minDelayStepCountL + ") + " + minStepCountR + "(-" + minDelayStepCountR + "), max: " + maxStepCountL + "(-" + maxDelayStepCountL + ") + " + maxStepCountR + "(-" + maxDelayStepCountR + ")"); }
8
public LinkedList<Node> findPath() { DijkstraNode current, start = map_[start_.x][start_.y] , goal = map_[goal_.x][goal_.y]; start.setGScore(0); // setting the g score of the start to zero while(!open_list_.isEmpty()) { current = lookingForBestNode(); // get node with lowest f Costs from open list if (current.equals(goal)) // found goal return constructPath(current); open_list_.remove(current); // delete current node from open list LinkedList<DijkstraNode> adjacent_nodes = new LinkedList<DijkstraNode>(); ArrayList<Node> edges = current.getNode().getEdges(); if(edges != null) { for (int idx = 0, size = edges.size(); idx<size; ++idx) { DijkstraNode current_edje = map_[edges.get(idx).getPosition().x][edges.get(idx).getPosition().y]; if(!current_edje.isObstacle()) { adjacent_nodes.add(current_edje); } } } for (int idx = 0, size = adjacent_nodes.size(); idx<size; ++idx) { DijkstraNode current_adj = adjacent_nodes.get(idx); // costs from current node are cheaper than previous costs if(current_adj.getGScore()>(current.getGScore() + COST)) { current_adj.setParentNode(current); // set current node as previous for this node current_adj.setGScore(current.getGScore() + COST); // set g costs of this node (costs from start to this node) } } } return null; }
7
public void print() { for(int i = 0; i < nodes.size(); i++) { ((Node)nodes.get(i)).print(); } }
1
public static void loadConfig() { try { BufferedReader reader = new BufferedReader(new FileReader(System.getProperty("user.dir") + "/config")); String line; while((line = reader.readLine()) != null) { if(line.matches("<AUDIO>")) { String[] temp = reader.readLine().split("="); Ensemble.get().setMasterVolume(Float.parseFloat(temp[1])); } else if(line.matches("<VIDEO>")) { // TODO Custom video settings } else if(line.matches("<KEYS>")) { while((line = reader.readLine()) != null) { Keybinds.changeBind(line); } } } reader.close(); } catch (FileNotFoundException e) { createConfig(); } catch (IOException e) { System.out.println("Config file failed to load!"); e.printStackTrace(); } }
7
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Funcao other = (Funcao) obj; if (this.IdFuncao != other.IdFuncao && (this.IdFuncao == null || !this.IdFuncao.equals(other.IdFuncao))) { return false; } return true; }
5
public void setReorderLevel(int reorderLevel) { this.reorderLevel = reorderLevel; }
0
public int getCapacity() { return CAPACITY; }
0
private void updateNeighbors(long[] l) { if((this.sectionID == 1) || (this.sectionID == 2)) { for(int i=0; i<height; i++) submesh[0][i].setTemp(l[i]); for(int i=0; i<height; i++) submesh[width-1][i].setTemp(l[i+height]); } else if(this.sectionID == 3) { for(int i=0; i<height; i++) submesh[0][i].setTemp(l[i]); } else { for(int i=0; i<height; i++) submesh[width-1][i].setTemp(l[i]); } }
7