text
stringlengths
14
410k
label
int32
0
9
@Override public void insertMoney(double amountInEuros) { if (amountInEuros < 0) throw new IllegalArgumentException("ERR00034512b"); totalAmountInEuros += amountInEuros; }
1
public static <T> List<T> inorderTraversal(BinaryTree<T> root) { if (root == null) { return null; } List<T> list = new ArrayList<T>(); BinaryTree<T> prev = root.getParent(); BinaryTree<T> current = root; BinaryTree<T> next = null; while (current != null) { if (prev == null || prev.getLeft() == current || prev.getRight() == current) { if (current.getLeft() != null) { next = current.getLeft(); } else { list.add(current.getData()); next = current.getRight() == null ? current.getParent() : current.getRight(); } } else if (current.getLeft() == prev) { list.add(current.getData()); next = current.getRight() == null ? current.getParent() : current.getRight(); } else { next = current.getParent(); } prev = current; current = next; } return list; }
9
@Override public void fill(Graphics2D g){ if(Display.player.me(0,1).intersects(phys))Display.player.dead=true; if(Display.player.me(0,-1).intersects(phys))Display.player.dead=true; if(Display.player.me(1,0).intersects(phys))Display.player.dead=true; if(Display.player.me(-1,0).intersects(phys))Display.player.dead=true; super.fill(g); if(Display.player.me(0,1).intersects(phys))Display.player.dead=true; if(Display.player.me(0,-1).intersects(phys))Display.player.dead=true; if(Display.player.me(1,0).intersects(phys))Display.player.dead=true; if(Display.player.me(-1,0).intersects(phys))Display.player.dead=true; }
8
public int getId() { return id; }
0
public void loadWorld(World uploadWorld) { this.world = uploadWorld; }
0
private TypedObject readDSK() throws EncodingException, NotImplementedException { // DSK is just a DSA + extra set of flags/objects TypedObject ret = readDSA(); ret.type = "DSK"; List<Integer> flags = readFlags(); for (int i = 0; i < flags.size(); i++) readRemaining(flags.get(i), 0); return ret; }
1
public String summary() { String toReturn = ""; int drinkCount, snackCount; drinkCount = snackCount = 0; for (Dispenser tempDispenser : this.dispensers) { if (tempDispenser.getType().equalsIgnoreCase("drink") && !tempDispenser.getDispenserContents().isEmpty()) { drinkCount++; } else if (tempDispenser.getType().equalsIgnoreCase("snack") && !tempDispenser.getDispenserContents().isEmpty()) { snackCount++; } } toReturn += drinkCount + " Drinks and " + snackCount + " Snacks Avalible"; return toReturn; }
5
public void mousePressed(MouseEvent e) { // where is the mouse pressed ? Point p = e.getPoint(); this.pressedIcon = null; // reset the pressed state int targetTab = findTabAt(p); if(targetTab != - 1) { Icon icon = tabbedPane.getIconAt(targetTab); if(icon instanceof JTabbedPaneSmartIcon) { JTabbedPaneSmartIcon smartIcon = (JTabbedPaneSmartIcon) icon; // convert point into smartIcon coordinates // get the tab bounds Rectangle r = tabbedPane.getBoundsAt(targetTab); if (r == null) { return; } // as the icon is the only thing visible, we consider it centered in the tab // (which is the default paint behaviour of BasicTabbedPaneUI, and should be okay // with most look and feels. int x = p.x - (r.x + r.width / 2 - icon.getIconWidth() / 2); int y = p.y - (r.y + r.height / 2 - icon.getIconHeight() / 2); if(x >= 0 && y >= 0 && x < icon.getIconWidth() && y < icon.getIconHeight()) { // forward the event to the smart icon MouseEvent eSmart = new MouseEvent((Component) e.getSource(), e.getID(), e.getWhen(), e.getModifiers(), x, y, e.getClickCount(), e.isPopupTrigger(), e.getButton()); if(smartIcon.onMousePressed(eSmart)) { tabbedPane.repaint(r.x, r.y, r.width, r.height); // no choice but trigger a repaint } pressedIcon = smartIcon; pressedTab = targetTab; } } } }
8
public int getBox(int r, int c){ if(r >= size || c >= size || r < 0 || c < 0){ System.err.println("Invalid dimentions (" + r + "," + c + ") for size " + size); System.exit(0); } return c/dimension + (r/dimension * dimension); }
4
public void undo() { if (prevSpeed == CeilingFan.HIGH) { ceilingFan.high(); } if (prevSpeed == CeilingFan.MEDIUM) { ceilingFan.medium(); } if (prevSpeed == CeilingFan.LOW) { ceilingFan.low(); } if (prevSpeed == CeilingFan.OFF) { ceilingFan.off(); } }
4
public void send(MidiMessage message, long deltaTime) { System.out.println("New MIDI message"); Event event = null; ByteArrayInputStream bais = new ByteArrayInputStream(message.getMessage()); DataInputStream dis = new DataInputStream(bais); try { dis.mark(2); int status = dis.readUnsignedByte(); int length = 0; //check running status if (status < 0x80) { status = oldStatus; dis.reset(); } if (status >= 0xFF) {//MetaEvent int type = dis.readUnsignedByte(); length = MidiUtil.readVarLength(dis); event = MidiUtil.createMetaEvent(type); } else if (status >= 0xF0) { //System Exclusive -- Not Supported System.out.println("SysEX---"); length = MidiUtil.readVarLength(dis); } else if (status >= 0x80) { //MIDI voice event short selection = (short) (status / 0x10); short midiChannel = (short) (status - (selection * 0x10)); VoiceEvt evt = (VoiceEvt) MidiUtil.createVoiceEvent(selection); evt.setMidiChannel(midiChannel); event = evt; if (event == null) { throw new IOException("Read Error"); } } if (event != null) { event.setTime((int) deltaTime); event.read(dis); } oldStatus = status; } catch (Exception e) { e.printStackTrace(); System.exit(1); } this.notifyListeners(event); }
7
public void kirjoitaOikeanmuotoinenSyote(){ try { PrintWriter kirjoitin = new PrintWriter(tiedosto); kirjoitin.println("opiskelu1 10"); kirjoitin.println("opiskelu2 20"); kirjoitin.close(); } catch (Exception e) { } }
1
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Salario)) { return false; } Salario other = (Salario) object; if ((this.codsalario == null && other.codsalario != null) || (this.codsalario != null && !this.codsalario.equals(other.codsalario))) { return false; } return true; }
5
public static String guessContentType(Extension ext){ switch(ext){ case ttl: return TranslateEnumToContentType(ContentType.TURTLE); case rdf: return TranslateEnumToContentType(ContentType.RDF); case nt: return TranslateEnumToContentType(ContentType.NT); case n3: return TranslateEnumToContentType(ContentType.N3); default: return "text/plain"; } }
4
@Override public void windowGainedFocus(WindowEvent event) { if (event.getWindow() == this) { WINDOW_LIST.remove(this); WINDOW_LIST.add(0, this); for (PaletteWindow window : getWindows(PaletteWindow.class)) { window.setAppWindow(this); } } super.windowGainedFocus(event); }
2
public DockLayout getRootLayout() { DockLayout root = this; while (root.mParent != null) { root = root.mParent; } return root; }
1
private void unfilter(byte[] curLine, byte[] prevLine) throws IOException { switch (curLine[0]) { case 0: // none break; case 1: unfilterSub(curLine); break; case 2: unfilterUp(curLine, prevLine); break; case 3: unfilterAverage(curLine, prevLine); break; case 4: unfilterPaeth(curLine, prevLine); break; default: throw new IOException("invalide filter type in scanline: " + curLine[0]); } }
5
public QueryOrdersByDateResponse queryOrderByDate(QueryOrdersByDateRequest request) throws GongmingConnectionException, GongmingApplicationException { URL path = _getPath(QUERY_ORDERS_BY_DATE); QueryOrdersByDateResponse response = _GET(path, request, QueryOrdersByDateResponse.class); if (response.code != GMResponseCode.COMMON_SUCCESS) { throw new GongmingApplicationException(response.code.toString(), response.errorMessage); } return response; }
1
public void mouseEntered(MouseEvent e) { }
0
private void chaseUpdate(Vector3f orientation, float distance){ double time = ((double)Time.getTime())/((double)Time.SECOND); double timeDecimals = time - (double)((int)time); if(timeDecimals < 0.25) material.setTexture(animations.get(0)); else if(timeDecimals < 0.5) material.setTexture(animations.get(1)); else if(timeDecimals < 0.75) material.setTexture(animations.get(2)); else material.setTexture(animations.get(3)); if(rand.nextDouble() < ATTACK_CHANCE * Time.getDelta()) state = ATTACK; if(distance > MOVE_STOP_DIST) { float movAmt = MOVE_SPEED * (float) Time.getDelta(); Vector3f oldPos = transform.getTranslation(); Vector3f newPos = transform.getTranslation().add(orientation.mul(movAmt)); Vector3f collisionVector = Game.getLevel().checkCollision(oldPos, newPos, WIDTH, LENGTH); Vector3f movementVector = collisionVector.mul(orientation); if(movementVector.length() > 0) transform.setTranslation(transform.getTranslation().add(movementVector.mul(movAmt))); if(movementVector.sub(orientation).length() != 0) Game.getLevel().openDoors(transform.getTranslation(), false); }else state = ATTACK; }
7
@Override //Quick and dirty implementation, needs some hard revision public AbstractStochasticLotSizingSolution solve( AbstractStochasticLotSizingProblem problem, boolean[] setupPattern) throws SolvingInitialisiationException, ConvolutionNotDefinedException { //Check inputs if (problem.getPeriods().length != setupPattern.length) throw new SolvingInitialisiationException("Problem and setup pattern have different planning horizons."); //Get the vector of aggregated demand (there is no ADI in this approach) RealDistribution openOrders = null; NegatableDistribution realizedOrders = null; NegatableDistribution[] realizedOrderArray = null; int setupPeriod = -1; double inventoryCost = 0.0; double setupCost = 0.0; double[] orderUpToLevelForOpenDemand = new double[setupPattern.length]; for (int t = 0; t < setupPattern.length;t++){ if (setupPattern[t]){ setupPeriod = t; setupCost += problem.getPeriods()[t].getSetupCost(); int nextSetupPeriod = t+1; while(nextSetupPeriod < setupPattern.length && !setupPattern[nextSetupPeriod]){ nextSetupPeriod++; } openOrders = problem.getPeriods()[t].openDemand(t, setupPeriod); realizedOrderArray = new NegatableDistribution[nextSetupPeriod-setupPeriod]; realizedOrderArray[0] = (NegatableDistribution) problem.getPeriods()[t].realisedDemand(t, setupPeriod); for (int tau = t+1; tau < nextSetupPeriod; tau++){ openOrders = Convoluter.convolute(openOrders, problem.getPeriods()[tau].openDemand(tau, setupPeriod)); realizedOrderArray[tau-t] = (NegatableDistribution) problem.getPeriods()[tau].realisedDemand(tau, setupPeriod); } orderUpToLevelForOpenDemand[t] = openOrders.inverseCumulativeProbability(problem.getServiceLevel()); openOrders = problem.getPeriods()[t].openDemand(t, setupPeriod); realizedOrders = (NegatableDistribution) Convoluter.convolute(realizedOrderArray, 1, realizedOrderArray.length); RealDistribution effectiveDemandDistribution = Convoluter.convolute(openOrders, realizedOrders.negate()); StockFunction stockFunction = new StockFunction(effectiveDemandDistribution); inventoryCost += problem.getPeriods()[t].getInventoryHoldingCost()*stockFunction.value(orderUpToLevelForOpenDemand[setupPeriod]); } else{ openOrders = Convoluter.convolute(openOrders,problem.getPeriods()[t].openDemand(t, setupPeriod)); realizedOrders = (NegatableDistribution) (NegatableDistribution) Convoluter.convolute(realizedOrderArray, t-setupPeriod+1, realizedOrderArray.length); RealDistribution effectiveDemandDistribution = Convoluter.convolute(openOrders, realizedOrders.negate()); StockFunction stockFunction = new StockFunction(effectiveDemandDistribution); inventoryCost += problem.getPeriods()[t].getInventoryHoldingCost()*stockFunction.value(orderUpToLevelForOpenDemand[setupPeriod]); } } return new SimpleStochasticLotSizingSolution(setupCost, inventoryCost, "Order-up-to-level for open demand", orderUpToLevelForOpenDemand, setupPattern); }
6
public static ErrorLogs DAOController(Generator generator, TransactionSet transactionSet, RuleSet ruleSet) { System.out.println("Starting DAO Controller"); ErrorLogs errorLogs = new ErrorLogs(); VendorPersistenceController vpc = new VendorPersistenceController(); TransactionPersistenceController tpc = new TransactionPersistenceController(); RulePersistenceController rpc = new RulePersistenceController(); TransactionSetPersistenceController tspc = new TransactionSetPersistenceController(); RuleSetPersistenceController rspc = new RuleSetPersistenceController(); GeneratorPersistenceController gpc = new GeneratorPersistenceController(); int errorCount = 0; String daoString = "MySQL"; gpc.setDAO(daoString); vpc.setDAO(daoString); tspc.setDAO(daoString); tpc.setDAO(daoString); rspc.setDAO(daoString); rpc.setDAO(daoString); System.out.println("Starting Database Persistence Controllers..."); System.out.println("Starting Persist Vendor..."); for (int i = 0; i < transactionSet.getVendorSet().size(); i++) { Vendor vendor = transactionSet.getVendorSet().get(i); vpc.persistVendor(vendor); //System.out //.println("vendor " + i + " is " + vendor.getVendor_name()); } int vpc_errors = vpc.getErrorLogs().getErrorMsgs().size(); System.out.println("Finished Persist Vendor"); errorCount += vpc_errors; if (errorCount != 0) { errorLogs.add("DATABASE ERROR: VENDOR TABLE"); errorLogs.add(vpc.getErrorLogs()); System.out.println("size: " + errorLogs.getErrorMsgs().size()); return errorLogs; } // iterate through tranactionset to get individual transactions //int i = 0; System.out.println("Starting Persist TransactionSet..."); tspc.persistTransactionSet(transactionSet); int tspc_errors = tspc.getErrorLogs().getErrorMsgs().size(); errorCount += tspc_errors; System.out.println("Finished Persist TransactionSet"); if (errorCount != 0) { errorLogs.add("DATABASE ERROR: TRANSACTIONSET TABLE"); errorLogs.add(tspc.getErrorLogs()); System.out.println("size: " + errorLogs.getErrorMsgs().size()); return errorLogs; } //System.out.println("errorCount: " + errorCount); System.out.println("Starting Persist Transaction..."); for (Transaction transaction : transactionSet.getTransactionSet()) { tpc.persistTransaction(transaction); } System.out.println("Finished Persist Transaction"); int tpc_errors = tpc.getErrorLogs().getErrorMsgs().size(); errorCount += tpc_errors; //System.out.println("errorCount: " + errorCount); if (errorCount != 0) { errorLogs.add("DATABASE ERROR: TRANSACTION TABLE"); errorLogs.add(tpc.getErrorLogs()); System.out.println("size: " + errorLogs.getErrorMsgs().size()); return errorLogs; } System.out.println("Starting Persist Generator..."); gpc.persistGenerator(generator.getGenerator_minSupportLevel(), generator.getGenerator_minConfidenceLevel()); //System.out.println("Finished Persist Generator"); int gpc_errors = gpc.getErrorLogs().getErrorMsgs().size(); errorCount += gpc_errors; if (errorCount != 0) { errorLogs.add("DATABASE ERROR: GENERATOR TABLE"); errorLogs.add(gpc.getErrorLogs()); return errorLogs; } System.out.println("Finished Persist Generator"); // iterate through ruleset to get individual rules System.out.println("Starting Persist RuleSet..."); rspc.persistRuleSet(ruleSet); int rspc_errors = rspc.getErrorLogs().getErrorMsgs().size(); errorCount += rspc_errors; //System.out.println("errorCount: " + errorCount); if (errorCount != 0) { errorLogs.add("DATABASE ERROR: RULESET TABLE"); errorLogs.add(rspc.getErrorLogs()); System.out.println("size: " + errorLogs.getErrorMsgs().size()); return errorLogs; } System.out.println("Finished Persist RuleSet"); System.out.println("Starting Persist Rule..."); for (Rule rule : ruleSet.getRuleSet()) { rpc.persistRule(rule); } System.out.println("Finished Persist Rule"); int rpc_errors = rpc.getErrorLogs().getErrorMsgs().size(); errorCount += rpc_errors; //System.out.println("errorCount: " + errorCount); if (errorCount != 0) { errorLogs.add("DATABASE ERROR: RULE TABLE"); errorLogs.add(rpc.getErrorLogs()); System.out.println("size: " + errorLogs.getErrorMsgs().size()); return errorLogs; } System.out.println("Final errorCount: " + errorCount); System.out.println("Finished DAO Peristence Controllers"); //System.out.println("size: " + errorLogs.getErrorMsgs().size()); return errorLogs; }
9
@Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Type)) { return false; } Type t = (Type) o; if (sort != t.sort) { return false; } if (sort >= ARRAY) { if (len != t.len) { return false; } for (int i = off, j = t.off, end = i + len; i < end; i++, j++) { if (buf[i] != t.buf[j]) { return false; } } } return true; }
7
private boolean jj_3_25() { if (jj_scan_token(DOT)) return true; if (jj_scan_token(ID)) return true; if (jj_3R_39()) return true; if (jj_scan_token(LP)) return true; Token xsp; xsp = jj_scanpos; if (jj_3R_116()) jj_scanpos = xsp; if (jj_scan_token(RP)) return true; if (jj_3R_38()) return true; return false; }
7
public static String optionsCount(String stock) { String httpdata = getHtml(yahoobase + "/op?s=" + stock); if (httpdata.contains(">There is no") || httpdata.contains("Check your spelling") || httpdata.indexOf("View By Expiration") < 0) return "0"; try { httpdata = httpdata.substring(httpdata .indexOf("View By Expiration")); httpdata = httpdata.substring(0, httpdata.indexOf("table")); } catch (Exception e) { e.printStackTrace(); } return "" + (httpdata.toLowerCase().split("a href").length - 1); }
4
public void setLimitCallDuration(int limitCallDurationSeconds) { for (Setting item : settings) { if (item instanceof SetLimitCallDurationSetting) { settings.remove(item); break; } } SetLimitCallDurationSetting limitCallSetting = new SetLimitCallDurationSetting( limitCallDurationSeconds); settings.add(limitCallSetting); }
2
protected void updateLabeling(double slack) { for (int w = 0; w < dim; w++) { if (committedWorkers[w]) { labelByWorker[w] += slack; } } for (int j = 0; j < dim; j++) { if (parentWorkerByCommittedJob[j] != -1) { labelByJob[j] -= slack; } else { minSlackValueByJob[j] -= slack; } } }
4
public void addItemToInventory(Item item) { if(item == null) throw new NullPointerException("An item can't be null."); // Checken of item niet in inventory van andere speler reeds voorkomt? inventory.add(item); }
1
public void sendMessage(String message) { try { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println(message); } catch (IOException e) { e.printStackTrace(); System.out.println("Failed at METHOD: SENDMESSAGE"); } }
1
public ResultPage<Patron> getPatronList(int offset) throws SQLException { openPatronsDatabase(); PreparedStatement statement = patronsConnection.prepareStatement( "SELECT * FROM Patrons ORDER BY Name LIMIT 11 OFFSET ?"); statement.setInt(1, offset * 10); ResultSet resultSet = statement.executeQuery(); ArrayList<Patron> results = new ArrayList<Patron>(10); for (int book = 0; book < 10 && resultSet.next(); book++) { results.add(new Patron(resultSet.getInt(1), resultSet.getString(2))); } boolean isBeginning = false; boolean isEnd = false; if (offset == 0) { isBeginning = true; } if (!resultSet.next()) { isEnd = true; } resultSet.close(); statement.close(); closePatronsDatabase(); return new ResultPage<Patron>(results, offset, isBeginning, isEnd); }
4
public void parsePicToBoard(BufferedImage pic) { board = new char[20][20]; for (int i = 0; i < 20;i++) { for (int j = 0; j < 20; j++) { if (new Color(pic.getRGB(i, j)).equals(Color.GREEN)) board[i][j] = COIN; else if (new Color(pic.getRGB(i, j)).equals(Color.WHITE)){ playerPos = new Point(i, j); board[i][j] = PLAYER; } else if (new Color(pic.getRGB(i, j)).equals( Color.RED)) board[i][j] = WALL; else board[i][j] = ' '; } } }
5
@Override public String toString(){ StringBuilder sb = new StringBuilder(); for (int i = 0; i < GRID_SIZE; i++ ) { for ( int j = 0; j < GRID_SIZE; j++) { sb.append("[ "); sb.append( StringUtils.rightPad(getLetterAt(i, j), 3) ); sb.append("]"); } sb.append(NEWLINE); } return sb.toString(); }
2
public void createRoom(int roomNumber){ list2.clear(); int[] neighbours = new int[4]; neighbours = roomNeighbour(roomNumber); //neighbours[0] ist oben, neighbours[1] ist rechts, neighbours[2] ist unten,neighbours[3] ist links for(int i=0; i<4; i++){ if(neighbours[i]!=-1){ int[] tmp = new int[6]; tmp = getValue(neighbours[i]); if((roomCounter<maxRooms)&&(tmp[0]==-1)){ list2.add(neighbours[i]);//alle gueltigen Nachbaroptionen werden gespeichert } } } if(list2.size()>0){//zufallselement aus der liste der gueltigen Nachbarn auswaehlen int a = (int)(Math.random()*(list2.size())); int[] tmp2 = new int[6]; tmp2=getValue(list2.get(a)); tmp2[0]=1; tmp2[1]=1; map.put(list2.get(a),tmp2); if(list2.size()==1){ int[] tmp3 = new int[6]; tmp3 = getValue(roomNumber); tmp3[1]=-1;//letzer freie nachbar wird belegt map.put(roomNumber, tmp3); } map.put(list2.get(a),tmp2); roomCounter++; } }
6
@EventHandler public void onInventoryClick(InventoryClickEvent event) { Player player = (Player) event.getWhoClicked(); if(player != null && bm.getSlot(player.getName()) != null && event.getInventory() instanceof Player) bm.setCurrentSlotContents(player.getName(), event.getInventory()); }
3
public void pause_ingress() { synchronized (ingress_paused) { ingress_paused = true; } }
0
public static Double distanceFromPoint(Point3D A, Point3D B) { if (A == null || B == null) return 0.0; if (B == A) return 0.0; if (!(A instanceof Point3D) || !(B instanceof Point3D)) return 0.0; if (A.isNull() || B.isNull()) return 0.0; return Math.sqrt(Math.pow((A.getOriginalX() - B.getOriginalX()), 2) + Math.pow((A.getOriginalY() - B.getOriginalY()), 2) + Math.pow((A.getOriginalZ() - B.getOriginalZ()), 2)); }
7
public void attack() { if(monsterLP <= 0 || lifepoints <= 0) { System.out.print("The winner has been chosen"); } else { if(damage > monsterD) { int gap = monsterD - damage; monsterLP = monsterLP + gap; } if(monsterD > damage) { int gap = damage - monsterD; lifepoints = lifepoints + gap; } System.out.println("Your Hero:"); System.out.println("Lifepoints: " + lifepoints); System.out.println("Damage: " + damage); System.out.println("The Monster:"); System.out.println("Lifepoints: " + monsterLP); System.out.println("Damage: " + monsterD); } }
4
public void run() { long lastTime = System.nanoTime(); long timer = System.currentTimeMillis(); final double ns = 1000000000D / 60D; double delta = 0; int frames = 0; int updates = 0; requestFocus(); while (running) { long now = System.nanoTime(); delta += (now - lastTime)/ns; lastTime = now; while (delta >= 1) { update(); updates++; delta--; } render(); frames++; if (System.currentTimeMillis() - timer > 1000) { timer += 1000; frame.setTitle(title + " | " + updates + " ups, " + frames + " fps"); updates = 0; frames = 0; } } stop(); }
3
public void cancelPiece(Piece p){ if(conState != ConnectionState.connected){ throw new RuntimeException("Can only send requests on 'connected' connections"); }else if(peer_choking){ return ; } try { Iterator<Request> itor =ourRequests.iterator(); while (itor.hasNext()) { Request r = itor.next(); if (r.index == p.pieceIndex) { itor.remove(); maintenance += 17; mp.cancel(sockOut, r.index, r.begin, r.len); } } } catch (IOException e) { conState = ConnectionState.closed; } }
5
private boolean curious_fraction(int numerator, int denominator) { Preconditions.checkArgument(numerator >= 10 && numerator < 100); Preconditions.checkArgument(denominator >= 10 && denominator < 100); int first_numerator_digit = numerator / 10; int second_numerator_digit = numerator % 10; int first_denominator_digit = denominator / 10; int second_denominator_digit = denominator % 10; double regular_result = (double)numerator / (double)denominator; if(numerator >= denominator) { return false; } if (second_numerator_digit == 0 && second_denominator_digit == 0) { return false; // trivial case covered here } if (first_numerator_digit == first_denominator_digit) { return (((double)second_numerator_digit /(double)second_denominator_digit) == regular_result); } if (first_numerator_digit == second_denominator_digit) { return (((double)second_numerator_digit /(double)first_denominator_digit) == regular_result); } if (second_numerator_digit == first_denominator_digit) { return (((double)first_numerator_digit /(double)second_denominator_digit) == regular_result); } if (second_numerator_digit == second_denominator_digit) { return (((double)first_numerator_digit /(double)first_denominator_digit) == regular_result); } return false; }
9
public static Cons idlGetConstructorDefinitions(Stella_Class renamed_Class) { { Cons constructordefs = Stella.NIL; { Slot slot = null; Iterator iter000 = renamed_Class.classSlots(); Cons collect000 = null; while (iter000.nextP()) { slot = ((Slot)(iter000.value)); if ((!slot.slotMarkedP) && ((slot.primaryType() == Stella.SGT_STELLA_METHOD_SLOT) && (Slot.localSlotP(slot, renamed_Class) && MethodSlot.idlConstructorP(((MethodSlot)(slot)))))) { if (collect000 == null) { { collect000 = Cons.cons(MethodSlot.idlYieldConstructorSignatureTree(((MethodSlot)(slot))), Stella.NIL); if (constructordefs == Stella.NIL) { constructordefs = collect000; } else { Cons.addConsToEndOfConsList(constructordefs, collect000); } } } else { { collect000.rest = Cons.cons(MethodSlot.idlYieldConstructorSignatureTree(((MethodSlot)(slot))), Stella.NIL); collect000 = collect000.rest; } } } } } return (constructordefs); } }
7
private boolean isGranadeOnMyWay(int grenade_x, int grenade_y, int grenade_dir){ int min_x = Math.abs(grenade_x-x); int min_y = Math.abs(grenade_y-y); int enX = grenade_x; int enY = grenade_y; int angle; if(x >= enX && y >= enY){ // KVADRANT 1 double pom1 = (double) min_y/min_x; angle=(int)(Math.atan(pom1)*(180.00/Math.PI)); //System.out.println("Kvadrant 1 "+angle); } else if(x >= enX && y <= enY){ // KVADRANT 4 double pom1 = (double) min_x/min_y; angle=(int)(Math.atan(pom1)*(180.00/Math.PI)); angle+= 270; //System.out.println("Kvadrant 4 "+angle); } else if(x <= enX && y <= enY){ // KVADRANT 3 double pom1 = (double) min_y/min_x; angle=(int)(Math.atan(pom1)*(180.00/Math.PI)); angle+= 180; //System.out.println("Kvadrant 3 "+angle); } else { // KVADRANT 2 double pom1 = (double) min_x/min_y; angle=(int)(Math.atan(pom1)*(180.00/Math.PI)); angle += 90; //System.out.println("Kvadrant 2 "+angle); } /*if(min_x < 20 || min_y < 20) { if(angle != 180) danger = true; return true; } if(min_x < 30 || min_y < 30) { danger = true; return true; }*/ if(grenade_dir >= angle - 10 && grenade_dir <= angle + 10) { danger = false; return true; } else { danger = false; return false; } }
8
public static boolean isPressed(int i) { return keyState[i] && !prevKeyState[i] ; }
1
@Override public void run(){ while(!super.detener){ try{ if(!this.guerreroColaAtaques.isEmpty()) recibirdaño(); if(this.objectivo.x==0&&this.objectivo.y==0){ this.objectivo=getObjectivo(); playCompleted=false; } //segundos que dura en durar al proximo cuadro en la matriz int segundos = 20 * espera; if(this.objectivo.equals(this.espacio)){ atacar(); play(IMG.getImage("dragon.wav")); } else{ mover(); } sleep(segundos); }catch (InterruptedException ex){} } ImageIcon iconLogo; iconLogo = new ImageIcon(IMG.getImage("blood.png")); this.refLabel.setDisabledIcon(iconLogo); }
6
public List<ExperienceType> getExperience() { if (experience == null) { experience = new ArrayList<ExperienceType>(); } return this.experience; }
1
public DefaultComboBoxModel<String> buildList() { DefaultComboBoxModel<String> comboBoxModel = new DefaultComboBoxModel<String>(); String line; try { BufferedReader reader = new BufferedReader(new FileReader(System.getProperty("resources") + "/database/items")); while((line = reader.readLine()) != null) { String[] temp = line.split(";"); comboBoxModel.addElement(temp[0] + ";" + temp[1]); } reader.close(); } catch (FileNotFoundException e) { System.out.println("The item database has been misplaced!"); e.printStackTrace(); } catch (IOException e) { System.out.println("Item database failed to load!"); e.printStackTrace(); } return comboBoxModel; }
3
protected String getRequestOption(String key) { if (this.options != null && this.options.containsKey(key)) { String param = this.options.get(key); if (GoCoin.hasValue(param)) { return param; } } //default to return null return null; }
3
@Override public void messageHandler(String messageName, Object messagePayload) { if (messagePayload != null) { System.out.println("RCV (model): "+messageName+" | "+messagePayload.toString()); } else { System.out.println("RCV (model): "+messageName+" | No data sent"); } MessagePayload payload = (MessagePayload)messagePayload; int field = payload.getField(); int direction = payload.getDirection(); if (direction == Constants.UP) { if (field == 1) { setVariable1(getVariable1()+Constants.UP); } else { setVariable2(getVariable2()+Constants.UP); } } else { if (field == 1) { setVariable1(getVariable1()+Constants.DOWN); } else { setVariable2(getVariable2()+Constants.DOWN); } } }
4
@Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { ArrayList<Game> games = gm.games; if (args.length >= 1) { if (args[0].equalsIgnoreCase("join")) { if (args.length > 1) { if (Integer.parseInt(args[1]) < games.size() && Integer.parseInt(args[1]) >= 0) { for (int i = 0; i < games.size(); i++) { if (games.get(i).getPlayerList().contains((Player) sender)) { sendMessage((Player) sender, ChatColor.RED + "You are allready in a game!"); return true; } } } else { sendMessage((Player) sender, ChatColor.RED + "Not an arena! Type /maze arenas To see avible arenas"); return true; } games.get(Integer.parseInt(args[1])).add((Player) sender); sendMessage(sender, ChatColor.GREEN + "Succesfully joined game"); return true; } else { sendMessage(sender, ChatColor.RED + "Not a valid agument. /maze join <Arena>"); return true; } } } sendMessage(sender, ChatColor.RED + "Not a valid command. Type /maze help"); return false; }
7
protected void initializeBoard() { tiles = new Tile[rows][columns]; int mid = columns / 2; int y = (((rows - 1) % 4 == 0)? 0 : 1); int x = 0; Tile wall = new Tile(); tiles[0][mid] = wall; tiles[tiles.length - 1][mid] = wall; for (int i = y; i < rows / 4 + y; i++) { tiles[i][mid - 2 * i + y] = wall; tiles[i][mid - 2 * i - 1 + y] = wall; tiles[i][mid + 2 * i - y] = wall; tiles[i][mid + 2 * i + 1 - y] = wall; for (int j = mid - 2 * i + y + 1; j < mid + 2 * i - y; j++) { tiles[i][j] = new Tile(openings, 6); } } for (int i = rows / 4 + y; i < rows - rows / 4 - 1; i++) { tiles[i][0] = wall; tiles[i][columns - 1] = wall; for (int j = 1; j < columns - 1; j++) { if (!isStartTile(i, j)) { tiles[i][j] = new Tile(openings, 6); } } } for (int i = rows - rows / 4 - 1; i < rows + y - 1; i++) { tiles[i][x] = wall; tiles[i][x + 1] = wall; tiles[i][columns - x - 1] = wall; tiles[i][columns - x - 2] = wall; for (int j = x + 2; j < columns - x - 2; j++) { tiles[i][j] = new Tile(openings, 6); } x += 2; } }
8
public String getCountry() { return super.getCountry(); }
0
public static boolean isOpaque(EntityType type) { boolean b = true; switch (type) { case OBJ_TREE: break; case OBJ_DOOR_WOOD: break; case ENTR_DUNGEON: b = false; break; } return b; }
3
@Override public boolean isNull() { if (getX() != 0 || getY() != 0 || getZ() != 0) return false; return true; }
3
public RotatingComponent(String imageName, int x, int y, int width, int height, final double angleSpeed) { this.setBounds(x, y, width, height); image = Utilities.resizeImage(width, height, imageName); //this.setSize(image.getWidth(null), image.getHeight(null)); timer = new Timer(20, new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { angleInDegrees = angleInDegrees + angleSpeed; if ( angleInDegrees == 360 ){ angleInDegrees = 0; } RotatingComponent.this.repaint(); } } ); timer.setRepeats(false); timer.start(); }
1
public static LinkedList<String> findSignificantWords(Path path, int nbWords, HashFunction func, int k) { if (2 * k < nbWords) throw new AssertionError("Too much significant words asked for the given sample size."); SignificantWordsSample ws = new SignificantWordsArraySample(k, func); //SignificantWordsSample ws = new SignificantWordsTreeSample(k, func); for(String str: new WordReader(path)) ws.addWord(str); // Extract only nbWords LinkedList<String> wordsList = ws.words(); //Collections.shuffle(wordsList); LinkedList<String> l = new LinkedList<String>(); for (int i = 0; i < nbWords; i++) l.add(wordsList.removeFirst()); return l; }
3
@Test public void testDeleteMiddleNode() throws Exception { head = new LinkedListNode(1).addNode(new LinkedListNode(2)).addNode(new LinkedListNode(3)).addNode(new LinkedListNode(4)).addNode(new LinkedListNode(5)); LinkedListNode middleNode = new LinkedListNode(6); head.addNode(middleNode).addNode(new LinkedListNode(7)).addNode(new LinkedListNode(8)).addNode(new LinkedListNode(9)); exerciseObj.deleteMiddleNode(middleNode); assert(head.getValue() == 1 && head.getNext().getValue() == 2 && head.getNext().getNext().getValue() == 3 && head.getNext().getNext().getNext().getValue() == 4 && head.getNext().getNext().getNext().getNext().getValue() == 5 && head.getNext().getNext().getNext().getNext().getNext().getValue() == 7 && head.getNext().getNext().getNext().getNext().getNext().getNext().getValue() == 8 && head.getNext().getNext().getNext().getNext().getNext().getNext().getNext().getValue() == 9 && head.getNext().getNext().getNext().getNext().getNext().getNext().getNext().getNext() == null); }
8
@Override public void atacar(){ for(int i = 0; i < ejercito.size(); i++){ int refPosX = ejercito.get(i).refLabel.getLocation().x; int refPosY = ejercito.get(i).refLabel.getLocation().y; Point pos = super.refPosToMatrizPos(refPosX, refPosY); //atacar a la unidad if(super.inRange(pos, alcance) && ejercito.get(i).esTerrestre()){ for(int j = 0; j < ejercito.size(); j++) if(inRange(pos, rangoAtaque)) ejercito.get(i).recibirataque(daño); this.vida = -1; this.detener = true; //cambiar sprite this.matriz[this.posicion.x][this.posicion.y].setbuilding(); this.matriz[this.posicion.x][this.posicion.y].setocupado(); ImageIcon iconLogo = new ImageIcon(IMG.getImage("destruido.png")); this.refLabel.setIcon(iconLogo); break; } //System.out.println("Pos x is " + pos.x + " and y is " + pos.y); } }
5
public FinishedJobRecord(String str) { StringTokenizer st = new StringTokenizer(str, ":"); int tokNumber = 0; while (st.hasMoreElements()) { tokNumber++; String val = st.nextToken(); // We only get what we need, fields which are not used by // pipeline will not be initialized. switch (tokNumber) { case 1: qname = val; break; case 6: job_number = val; break; case 36: task_number = Integer.parseInt(val); break; case 10: start_time = Long.parseLong(val) * 1000; break; case 11: end_time = Long.parseLong(val) * 1000; break; case 13: exit_status = Integer.parseInt(val); break; case 15: ru_utime = val; break; case 16: ru_stime = val; break; } } }
9
public SerialCtl(String aa, String bb) { a = "Not transient: " + aa; b = "Transient: " + bb; }
0
public void UpdateAtividade(Atividade atividade) throws SQLException, atividadeExistente { AtividadeDAO atividadeDAO = new AtividadeDAO(); Atividade atividadeExistente = null; atividadeExistente = atividadeDAO.SelectATividadePorNome(atividade.getNome()); if (atividadeExistente == null || atividadeExistente.getIdAtividade() == atividade.getIdAtividade()) { atividadeDAO.UpdateAtividade(atividade); } else { throw new atividadeExistente(); } }
2
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(VerInfoOrdenCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VerInfoOrdenCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VerInfoOrdenCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VerInfoOrdenCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new VerInfoOrdenCompra().setVisible(true); } }); }
6
public boolean isSenderPlayer() { if(sender != null && sender instanceof Player) return true; return false; }
2
public void searchDescricaoExames() { facesContext = FacesContext.getCurrentInstance(); renderizarDadosEncontrados = true; List<DescricaoExames> listDescricaoExames; if (!descricaoExames.getDes_codigoProcedimento().isEmpty() || !descricaoExames.getDes_nomeexame().isEmpty()) { try { listDescricaoExames = genericDAO.searchObject(DescricaoExames.class,"procedimentos", null, null, new String[]{"des_codigoProcedimento", "des_nomeexame"}, new Object[]{descricaoExames.getDes_codigoProcedimento(), descricaoExames.getDes_nomeexame()}); if (listDescricaoExames.isEmpty()) { facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Procedimento nao encontrado!", "Não há nenhum procedimento cadastrado com esses dados")); } else if (listDescricaoExames.size() == 1) { procedimentoEscolhido = listDescricaoExames.get(0); } } catch (Exception ex) { Logger.getLogger(SolicitacoesMB.class.getName()).log(Level.SEVERE, null, ex); } } }
5
public void play(String audioFilePath) { File audioFile = new File(audioFilePath); try { AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile); AudioFormat format = audioStream.getFormat(); DataLine.Info info = new DataLine.Info(Clip.class, format); Clip audioClip = (Clip) AudioSystem.getLine(info); audioClip.addLineListener(this); audioClip.open(audioStream); audioClip.start(); while (!playCompleted) { // wait for the playback completes try { Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } audioClip.close(); } catch (UnsupportedAudioFileException ex) { System.out.println("The specified audio file is not supported."); ex.printStackTrace(); } catch (LineUnavailableException ex) { System.out.println("Audio line for playing back is unavailable."); ex.printStackTrace(); } catch (IOException ex) { System.out.println("Error playing the audio file."); ex.printStackTrace(); } }
5
@Override public boolean perform(final Context context) { // Example: /<command> reset[ <Player>] OfflinePlayer target = Parser.parsePlayer(context, 1); if (target == null && context.sender instanceof OfflinePlayer) target = (OfflinePlayer) context.sender; if (target == null) { Main.messageManager.send(context.sender, "Unable to determine player", MessageLevel.SEVERE, false); return false; } String targetName = target.getName(); if (target.getPlayer() != null) targetName = target.getPlayer().getName(); if (!Timestamp.isAllowed(context.sender, this.permission, targetName)) { Main.messageManager.send(context.sender, "You are not allowed to use the " + this.getNamePath() + " action for " + target.getName(), MessageLevel.RIGHTS, false); return true; } final Recipient recipient = Timestamp.getRecipient(target); recipient.reset(); Main.messageManager.send(context.sender, "Timestamp reset for: " + targetName, MessageLevel.STATUS, false); return true; }
5
public void set_Visit(MsgParse mp) throws SQLException { if (!mp.visit.getPatient_class().isEmpty()) try { PreparedStatement prepStmt = connection.prepareStatement( "insert into visit (patient_class, admission_type, location, prior_location, " + "attending_provider_number, attending_provider_name, hospital_service, visit_number, admit_date," + "discharge_date, patient_pid) " // + "attending_provider_number, attending_provider_name, hospital_service, admit_date," // + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + patientId + ")"); // This pid comes from SET_PATIENT where we select MAX(PID) + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + patientId + ")"); prepStmt.setString(1, mp.visit.getPatient_class()); prepStmt.setString(2, mp.visit.getAdmission_type()); prepStmt.setString(3, mp.visit.getLocation()); prepStmt.setString(4, mp.visit.getPrior_location()); prepStmt.setString(5, mp.visit.getAttending_provider_number()); prepStmt.setString(6, mp.visit.getAttending_provider_name()); prepStmt.setString(7, mp.visit.getHospital_service()); prepStmt.setString(8, mp.patient.getAcctNum()); prepStmt.setString(9, mp.visit.getAdmit_date()); prepStmt.setString(10, mp.visit.getDischarge_date()); //prepStmt.setString(8, mp.visit.getAdmit_date()); //prepStmt.setString(9, mp.visit.getDischarge_date()); prepStmt.execute(); prepStmt.close(); patientId = 0; } catch (SQLException se) { System.out.println("Error in DBLoader.set_Visit: " + se); } }
2
public void start() { for (int i = 0; i < level.length; i++) { for (int j = 0; j < level[0].length; j++) { Stack<GameObject> it = level[i][j].getGameObjects(); for (int k = 0; k < it.size(); k++) { GameObject object = it.get(k); if(object != null && object instanceof Ghost) { ((Ghost) object).pauzeTimer(false); } if(object != null && object instanceof Pacman) { ((Pacman) object).pauzeTimer(false); } } } } pauzeTimer(false); }
7
public void onPreviewNativeEvent(NativePreviewEvent event) { if (!isDragging()) { // this should never happen, as the preview handler should be removed after the dragging stopped DebugLog.getInstance().printLine("Preview handler still registered, even though dragging stopped."); stopDragging(); return; } Event nativeEvent = Event.as(event.getNativeEvent()); switch (DOM.eventGetType(nativeEvent)) { case Event.ONMOUSEMOVE: // dragging onMove(nativeEvent); break; case Event.ONMOUSEUP: onUp(nativeEvent); break; case Event.ONKEYDOWN: if (nativeEvent.getKeyCode() == 27) { cancel(); } break; case Event.ONMOUSEWHEEL: onMouseWheelScroll(nativeEvent); break; default: // do nothing } event.cancel(); nativeEvent.preventDefault(); nativeEvent.stopPropagation(); }
6
@Override @SuppressWarnings("static-access") public void run() { boolean checar = true; while (checar) { if (contadorParaEfetuarATrocaDePosissoesNaFila < Integer.parseInt(Principal.tfQuantum.getText())) { JPanel panel = new JPanel(); for (int i = 0; i < Principal.processosEmExecucao.size(); i++) { Processo processo = Principal.processosEmExecucao.get(i); processo.processamento(); if (processo.checarSeOTempoZerou()) { Principal.processosEmExecucao.remove(processo); if (!Principal.processosAptos.isEmpty()) { panel.add(Principal.processosAptos.get(0).montarDesenhoDoProcesso()); Principal.processosEmExecucao.add(i, Principal.processosAptos.get(0)); Principal.processosAptos.remove(0); Principal.paAProcessar.removeAll(); JPanel panelAptos = new JPanel(); for (Processo processoAptos : Principal.processosAptos) { panelAptos.add(processoAptos.montarDesenhoDoProcesso()); } Principal.reorganizarAProcessar(panelAptos); } } else { panel.add(Principal.processosEmExecucao.get(i).montarDesenhoDoProcesso()); Principal.processosEmExecucao.set(i, processo); } } Principal.reorganizarProcessando(panel); contadorParaEfetuarATrocaDePosissoesNaFila++; } else { RR rr = new RR(); Principal.processosAptos.addAll(Principal.processosEmExecucao); Principal.processosEmExecucao = new ArrayList<Processo>(); if ( !Principal.processosAptos.isEmpty()) { rr.montarNucleos(); rr.montarProcessos(); } contadorParaEfetuarATrocaDePosissoesNaFila = 0; } try { checar = !Principal.processosEmExecucao.isEmpty(); Principal.processamento.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }
8
private void createAlphaPixels(byte pixels[], int i, int j, int drawingAreaPixels[], int l, int i1, int j1, int k1, int l1, int alpha) { l1 = ((l1 & 0xff00ff) * alpha & 0xff00ff00) + ((l1 & 0xff00) * alpha & 0xff0000) >> 8; alpha = 256 - alpha; for (int j2 = -i; j2 < 0; j2++) { for (int k2 = -i1; k2 < 0; k2++) { if (pixels[l++] != 0) { int l2 = drawingAreaPixels[j]; drawingAreaPixels[j++] = (((l2 & 0xff00ff) * alpha & 0xff00ff00) + ((l2 & 0xff00) * alpha & 0xff0000) >> 8) + l1; } else { j++; } } j += k1; l += j1; } }
3
public boolean save(Object obj) { boolean ret = false; Session session = sessionFactory.openSession(); try { session.beginTransaction(); int count = 0; if (obj instanceof Collection<?>) { List<?> list = (List<?>) obj; for (Object item : list) { session.saveOrUpdate(item); count++; if (count == 20) { //20, same as the JDBC batch size //flush a batch of inserts and release memory: session.flush(); session.clear(); count = 0; } } } else { session.saveOrUpdate(obj); } session.getTransaction().commit(); ret = true; } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } return ret; }
7
public void createDoors(){ for(int i=0; i<map.size(); i++){ int[] tmp = new int[6]; tmp = getValue(i); int[] neighbours = new int[4]; neighbours = roomNeighbour(i); int orientation = 2;//startindex in map fuer tuer oben for(int x=0; x<4; x++){ if(neighbours[x]!=-1){ int[] tmp2 = new int[6]; tmp2 = getValue(neighbours[x]); if(tmp2[0]==1){//nachbarraum vorhanden tmp[orientation]=neighbours[x];//tuer wird gesetzt in tmp falls nachbar vorhanden } } orientation++;//naechste tuerstelle abfragen/eintragen }//tueren in tmp alle gesetzt int rand = (int)(Math.random()*4); tmp[1]=rand; map.put(i,tmp); System.out.println(i+"raumgesetzt: "+tmp[0]+" raumtyp: "+tmp[1]+" oben: "+tmp[2]+" rechts: "+tmp[3]+" unten: "+tmp[4]+" links: "+tmp[5]); } }
4
@Override public void applyAllChanges() throws ApplyChangesException { try { // Check if we have a valid xml file by attempting to create a xml // document from it DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException e) throws SAXParseException { throw e; } @Override public void fatalError(SAXParseException e) throws SAXParseException { throw e; } @Override public void error(SAXParseException e) throws SAXParseException { throw e; } }); builder.parse(new InputSource(new StringReader(this.xmlDocument.getText().trim()))); } catch(SAXParseException e) { // Give some nice hints about what to do next throw new ApplyChangesException("Error (probably) on line "+e.getLineNumber() + " column "+e.getColumnNumber()+ ": " + e.getMessage()); } catch(ParserConfigurationException e) { // Will never happen, the parser is correctly configured } catch(IOException e) { // Will never happen, there is no real IO going on } catch(SAXException e) { // Shouldn't happen, but whatever throw new ApplyChangesException("Couldn't verify XML: "+ e.getMessage()); } }
4
int pack_books(Buffer opb) { opb.write(0x05, 8); opb.write(_vorbis); // books opb.write(books - 1, 8); for (int i = 0; i < books; i++) { if (book_param[i].pack(opb) != 0) { //goto err_out; return (-1); } } // times opb.write(times - 1, 6); for (int i = 0; i < times; i++) { opb.write(time_type[i], 16); FuncTime.time_P[time_type[i]].pack(this.time_param[i], opb); } // floors opb.write(floors - 1, 6); for (int i = 0; i < floors; i++) { opb.write(floor_type[i], 16); FuncFloor.floor_P[floor_type[i]].pack(floor_param[i], opb); } // residues opb.write(residues - 1, 6); for (int i = 0; i < residues; i++) { opb.write(residue_type[i], 16); FuncResidue.residue_P[residue_type[i]].pack(residue_param[i], opb); } // maps opb.write(maps - 1, 6); for (int i = 0; i < maps; i++) { opb.write(map_type[i], 16); FuncMapping.mapping_P[map_type[i]].pack(this, map_param[i], opb); } // modes opb.write(modes - 1, 6); for (int i = 0; i < modes; i++) { opb.write(mode_param[i].blockflag, 1); opb.write(mode_param[i].windowtype, 16); opb.write(mode_param[i].transformtype, 16); opb.write(mode_param[i].mapping, 8); } opb.write(1, 1); return (0); }
7
public static JSONObject getJSONObject(String url) { try { String str = ""; Scanner x = new Scanner(new URL(url).openStream()); while (x.hasNextLine()) { str += x.nextLine() + "\n"; } return new JSONObject(str); } catch (JSONException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { if(e.getMessage().contains("429")) { System.out.println("Request limit of 10 per 10s exceeded"); System.exit(1); } else { e.printStackTrace(); } } return null; }
5
@Override public int attack(double agility, double luck) { System.out.println("I tried to do a special attack but I haven't set it so I failed at this turn..."); return 0; }
0
public boolean register() { boolean registered = false; try { registered = mServerInt.newUser(mUserName, mUserPass, ServerInterface.CLIENT); } catch(Exception ex) { if(connect()) return register(); System.out.println("A Login-Error occured: " + ex.getMessage()); return false; } return registered; }
2
public static void main(String[] args) { List<String> numbers = new ArrayList<>(); for (int i = 1; i < 10; i++) { numbers.add("" + i); } Set<Integer> products = new HashSet<>(); List<String> pandigitals = permute("", numbers); for (String pandigital : pandigitals) { for (int i = pandigital.length() - 4; i > 3; i--) { int sum = Integer.valueOf(pandigital.substring(i)); for (int j = i - 1; j > 0; j--) { int x = Integer.valueOf(pandigital.substring(0, j)); int y = Integer.valueOf(pandigital.substring(j, i)); if (x * y == sum) { System.out.println("" + x + " * " + y + " = " + sum); products.add(sum); } } } } int sum = 0; for (int product : products) { sum += product; } System.out.println("Result = " + sum); }
6
private void solve(int[][] board, int cx, int cy, int ideal, int workers) { FlipPuzzle flip = new FlipPuzzle( cx, cy, board ); Solver<FlipMove> solver = workers <= 1 ? new Solver<FlipMove>() : new ConcurrentSolver<FlipMove>( workers ); solver.setInitialState(flip); // Depth-First-Search solver.setBreadthFirst(false); // States will never be revisited solver.setRevisitStates(false); // Set to false to find all paths solver.setMinimalMoves(true); // Set to true so solutions can be backtracked solver.setSaveParent(true); // Restrict the minimal number of moves, I'm assuming the given board will take less. solver.setMaxDepth(ideal); // We only want a single solution. solver.setMaxSolutions(1); solver.solve(); System.out.format("Solved in %d ms\n", solver.getSolveTime()); System.out.format("States created: %d\n", solver.getStatesCreated()); System.out.format("States visited: %d\n", solver.getStatesVisited()); System.out.format("States duplicated: %d\n", solver.getStatesDuplicates()); System.out.format("States pooled: %d\n", solver.getUniqueStates()); System.out.format("States branched: %d\n", solver.getStatesDeviated()); System.out.format("States too short: %d\n", solver.getStatesShort()); List<FlipPuzzle> solutions = solver.getSolutions(); System.out.format("Solutions: (%d) {\n", solutions.size()); for (int i = 0; i < solutions.size(); i++) { System.out.format("Solution #%d took %d move(s).\n", i + 1, solutions.get(i).getDepth()); print( solutions.get(i) ); } System.out.println("}"); System.out.println(); }
2
public void rotACW() { if (!pause) { plateau.updatePosition(0, -1); updateObservers(); } }
1
@Override public void logicUpdate(GameTime gameTime) { for (Entity entity : entityList) { processEntity(entity, gameTime.getElapsedTimeMilli()); } }
1
private Location findFood() { Field field = getField(); List<Location> adjacent = field.adjacentLocations(getLocation()); Iterator<Location> it = adjacent.iterator(); while(it.hasNext()) { Location where = it.next(); Object animal = field.getObjectAt(where); if(animal instanceof Wolf) { Wolf wolf = (Wolf) animal; if(wolf.isAlive()) { wolf.setDead(); setFoodLevel(WOLFS_FOOD_VALUE); return where; } } else if (animal instanceof Fox) { Fox fox = (Fox) animal; if(fox.isAlive()) { fox.setDead(); setFoodLevel(FOX_FOOD_VALUE); return where; } } else if (animal instanceof Rabbit) { Rabbit rabbit = (Rabbit) animal; if(rabbit.isAlive()) { rabbit.setDead(); setFoodLevel(RABBIT_FOOD_VALUE); return where; } } } return null; }
7
public static void main(String[] args) { String str = "abc"; Object obj = new Object(); obj=str; // works because String is-a Object, inheritance in java MyClass<String> myClass1 = new MyClass<String>(); MyClass<Object> myClass2 = new MyClass<Object>(); //myClass2=myClass1; // compilation error since MyClass<String> is not a MyClass<Object> obj = myClass1; // MyClass<T> parent is Object }
0
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StringKey other = (StringKey) obj; if (m_name == null) { if (other.m_name != null) return false; } else if (!m_name.equals(other.m_name)) return false; return true; }
6
public NodeDLL deletekey(int key) { NodeDLL current = first; while(current.data != key) { current = current.next; } if (first == null) { return null; } if(current == first) { first = current.next; } else { current.previous.next = current.next; } if(current == last) { last = current.previous; } else { current.next.previous = current.previous; } return current; }
4
private void runParser() { logger.debug("Start 'runParser'"); Path currentFile = null; while (true) { try { currentFile = pathStorage.get(); try { File fileForParsing = currentFile.toFile(); logger.debug("Start parsing '{}' file", currentFile); FileInputStream stream = new FileInputStream(fileForParsing); Runnable parser = new PaymentParser(stream, paymentStorage); Future<Path> fileForDelete = executor.submit(parser, currentFile); logger.debug( "File '{}' was successfully parsed and add for delete", currentFile); deletePathStorage.put(fileForDelete); } catch (FileNotFoundException e) { logger.error( "File '{}' not found or can't be read. Put it back to pathStorage", e); pathStorage.put(currentFile); } } catch (InterruptedException e) { logger.debug("'ThreadsManager' thread was interrupted", e); return; } catch (JAXBException e) { logger.error("Error during parsing xml {} {}", currentFile.toAbsolutePath(), e.getMessage()); } } }
4
private void createPreview() { page = new Page[pg.getNumberOfPages()]; PageFormat pf = pg.getPageFormat(0); Dimension size = new Dimension((int)pf.getPaper().getWidth(), (int)pf.getPaper().getHeight()); if(pf.getOrientation() != PageFormat.PORTRAIT) size = new Dimension(size.height, size.width); for(int i=0; i<page.length; i++) { jcb.addItem(i+1); page[i] = new Page(i, size); p.add(""+(i+1), new JScrollPane(page[i])); } for (int r: RES) { rcb.addItem(new Resolution (r)); } rcb.setSelectedIndex(3); setTopPanel(); this.getContentPane().add(p, "Center"); this.setSize(size.width+20,size.height+40); this.setVisible(true); page[jcb.getSelectedIndex()].refreshScale(); }
3
public Object nextValue() throws JSONException { char c = nextClean(); String s; switch (c) { case '"': case '\'': return nextString(c); case '{': back(); return new JSONObject(this); case '[': case '(': back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = next(); } back(); s = sb.toString().trim(); if (s.equals("")) { throw syntaxError("Missing value"); } return JSONObject.stringToValue(s); }
8
public static ArrayList<Integer> findSubstring(String S, String[] L) { if (L.length == 0) return new ArrayList<Integer>(); ArrayList<Integer> rs = new ArrayList<Integer>(); HashMap<String, Integer> hasFound = new HashMap<String, Integer>(); HashMap<String, Integer> needToFind = new HashMap<String, Integer>(); int len = L[0].length(); int N = L.length; for (String s : L) { if (needToFind.get(s) == null) needToFind.put(s,1); else needToFind.put(s,needToFind.get(s)+1); } for (int i = 0; i <= S.length() - N*len; i++) { int count = 0; for (int j = 0; j < N; j++) { int index = i + j*len; String s = S.substring(index, index + len); if (needToFind.get(s) != null) { if(hasFound.get(s) == null) hasFound.put(s, 1); else hasFound.put(s, hasFound.get(s)+1); if (hasFound.get(s) > needToFind.get(s)) break; count++; } else break; } hasFound.clear(); if(count == N) rs.add(i); } return rs; }
9
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof TipoRecurso)) { return false; } TipoRecurso other = (TipoRecurso) object; if ((this.idTipoRecurso == null && other.idTipoRecurso != null) || (this.idTipoRecurso != null && !this.idTipoRecurso.equals(other.idTipoRecurso))) { return false; } return true; }
5
public ExprInfo(final LocalExpr def) { this.def = def; vars = new ArrayList[cfg.size()]; for (int i = 0; i < vars.length; i++) { vars[i] = new ArrayList(); } phis = new Phi[cfg.size()]; save = false; pushes = new HashMap(); pops = new HashMap(); defs = new HashMap(); cleanup = new ArrayList(); }
1
@Override public String suggestSimilarWord(String input) throws NoSimilarWordFoundException { input = input.toLowerCase(); MyNode node_found = (MyNode) dict.find(input); String word_found = input; if (node_found == null) { word_found = ""; ArrayList<String> similar = new ArrayList<String>(); similar.add(input); do { //System.out.println(similar.toString()); int init_size = similar.size(); for (int i = 0; i < init_size; i++) { String next = similar.remove(0);// always removes the first word because it should act like a queue similar.addAll(dict.delete(next)); similar.addAll(dict.transpose(next)); similar.addAll(dict.alter(next)); similar.addAll(dict.insert(next)); } for (int i = 0; i < similar.size(); i++) { String similar_word = similar.get(i); MyNode similar_node = (MyNode) dict.find(similar_word); // If similar_word is found... if (similar_node != null) { // If this is the first word found... if (node_found == null) { word_found = similar_word; node_found = similar_node; } // If this is NOT the first word found... else { // Get the number of times the current found word occurs in the dictionary int old_num = node_found.getValue(); // Get the number of times the new found word occurs in the dictionary int new_num = similar_node.getValue(); // If the new found word occurs more frequently than the old one OR they have the same frequency and the new word is lexicographically first... if (new_num > old_num || ( new_num == old_num && similar_word.compareTo(word_found) < 0)) { word_found = similar_word; node_found = similar_node; } } } } } while (word_found.equals("")); //throw new NoSimilarWordFoundException(); } return word_found; }
9
public void testPropertySetCopyDay() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.dayOfMonth().setCopy(12); check(test, 1972, 6, 9); check(copy, 1972, 6, 12); try { test.dayOfMonth().setCopy(31); fail(); } catch (IllegalArgumentException ex) {} try { test.dayOfMonth().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} }
2
public static boolean aSubsumesB(RuleItem a, RuleItem b){ if(!a.consequence().equals(b.consequence())) return false; if(a.accuracy() < b.accuracy()) return false; for(int k = 0; k < ((a.premise()).items()).length;k++){ if((a.premise()).itemAt(k) != (b.premise()).itemAt(k)){ if(((a.premise()).itemAt(k) != -1 && (b.premise()).itemAt(k) != -1) || (b.premise()).itemAt(k) == -1) return false; } /*if(a.m_consequence.m_items[k] != b.m_consequence.m_items[k]){ if((a.m_consequence.m_items[k] != -1 && b.m_consequence.m_items[k] != -1) || a.m_consequence.m_items[k] == -1) return false; }*/ } return true; }
7
public int lengthOfLIS(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int dp[] = new int[nums.length]; Arrays.fill(dp, 1); int longest = 1; for (int i = 1; i < nums.length; i++) { for (int j = 0; j < i; j++) { if (nums[j] < nums[i] && dp[j] + 1 > dp[i]) { dp[i] = dp[j] + 1; } } if (dp[i] > longest) { longest = dp[i]; } } return longest; }
7
public EndOfGame(final String score) { //конструктор принимает счет //если честно, мне уже надоело эту шапку расписывать, поэтому не буду frame = this; this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/mainIcon.jpg"))); setTitle("Угадай картинку"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(350, 450); setResizable(false); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(dim.width / 2 - this.getSize().width / 2, dim.height / 2 - this.getSize().height / 2); setVisible(true); //вызыываю метод, который сохранит текущий результат putScore(score); //получаю все результаты с учетом сохраненного List<String> scores = getScores(); //это панель с результатами JPanel resultLabelPanel = new JPanel(new GridLayout(11, 1)); final JLabel resultLabel = new JLabel("Лучшие результаты:"); resultLabel.setFont(myFont); resultLabel.setHorizontalAlignment(SwingConstants.CENTER); resultLabelPanel.add(resultLabel); //тут я эти результаты отображаю for (int i = 0; i < scores.size(); i++) { JLabel currentLabel; if (i != 9) { currentLabel = new JLabel(Integer.toString(i + 1) + ") " + scores.get(i)); } else { currentLabel = new JLabel(Integer.toString(i + 1) + ") " + scores.get(i)); } currentLabel.setFont(myFont); resultLabelPanel.add(currentLabel); } //кнопка, при нажатии на которую происходит переход на следующий этап final JPanel resultsPanel = new JPanel(new FlowLayout()); resultLabelPanel.setPreferredSize(new Dimension(330, 350)); resultsPanel.add(resultLabelPanel); final JButton button = new JButton("OK"); button.setPreferredSize(new Dimension(100, 30)); //при нажатии заменяю панель на другую button.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { setPanel(); frame.repaint(); frame.revalidate(); } }); button.setFont(myFont); resultsPanel.add(button); //меняю панель окна на тоьлко что созданную setContentPane(resultsPanel); }
2
public List buildRequest() { List request=new ArrayList<String>(); String params=""; if(this.method==Method.GET) { String data=""; for(Iterator i=this.getParameters().keySet().iterator();i.hasNext();) { String key=(String)i.next(); data+="&"+key+"="+this.parameters.get(key); } if(!data.isEmpty()) params="?"+data.substring(1); } request.add(this.getMethod().toString()+" "+this.getResourcePath()+params+" HTTP/1.1"); request.add("Host: "+this.getHost()); for(Iterator i=this.getHeaders().keySet().iterator();i.hasNext();) { String key=(String)i.next(); request.add(key+": "+getHeaders().get(key)); } if(this.isMultipart()) { String boundary="---------------------------1298224831751237580694844359"; int brkCount=2; String data="\n"; for(Iterator i=this.getParameters().keySet().iterator();i.hasNext();) { String key=(String)i.next(); data+=boundary+"\n"; data+="Content-Disposition: form-data; name=\""+key+"\"\n"; data+="\n"; data+=(String)this.getParameters().get(key)+"\n"; brkCount+=8; } data+=boundary+"--"; request.add("Content-Type: multipart/form-data; boundary="+boundary); request.add("Content-Length: "+(data.length()+brkCount)); request.add(data); } else if(this.method==Method.POST) { String data=""; for(Iterator i=this.getParameters().keySet().iterator();i.hasNext();) { String key=(String)i.next(); data+="&"+key+"="+this.parameters.get(key); } data=data.substring(1); request.add("Content-Length: "+data.length()); request.add(""); request.add(data); } return request; }
8
public static boolean isSubstring(String searchStr, String pattern){ int[] table = new int[pattern.length()]; int pos, cnd; if (pattern.length()>0){ table[0] = -1; } if (pattern.length()>1){ table[1] = 0; } pos = 2; cnd = 0; while (pos<pattern.length()){ if (pattern.charAt(pos) == pattern.charAt(cnd)){ cnd++; table[pos] = cnd; pos++; } else if (cnd > 0){ cnd = table[cnd]; } else{ table[pos] = 0; pos++; } } int m, i; m=0; i=0; while (m+i<searchStr.length()){ if (searchStr.charAt(m+i) == pattern.charAt(i)){ if (i == pattern.length()-1){ return true; } i++; } else{ m = m+i-table[i]; if (table[i] > -1){ i = table[i]; } else{ i = 0; } } } return false; }
9
public void updateText(String newMessage, int newType) { Image newImage = null; switch (newType) { case IMessageProvider.NONE: if (newMessage == null) { restoreTitle(); } else { showTitle(newMessage, null); } return; case IMessageProvider.INFORMATION: newImage = JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_INFO); break; case IMessageProvider.WARNING: newImage = JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_WARNING); break; case IMessageProvider.ERROR: newImage = JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_ERROR); break; } messageComposite.setVisible(true); titleLabel.setVisible(false); // Any more updates required? // If the message text equals the tooltip (i.e. non-shortened text is the same) // and shortened text is the same (i.e. not a resize) // and the image is the same then nothing to do String shortText = Dialog.shortenText(newMessage,messageText); if (newMessage.equals(messageText.getToolTipText()) && newImage == messageImageLabel.getImage() && shortText.equals(messageText.getText())) { return; } messageImageLabel.setImage(newImage); messageText.setText(Dialog.shortenText(newMessage,messageText)); messageText.setToolTipText(newMessage); lastMessageText = newMessage; }
8
public void paint(DrawableItem di, Graphics2D g) { fillShape(di, g); drawShape(di, g); }
0