id
stringlengths
36
36
text
stringlengths
1
1.25M
0391cb2b-db33-412f-9475-de2cc3523145
public Image draw(APIResponse response) { if (response.getStatus() != 0) return null; ByteArrayInputStream bis = new ByteArrayInputStream(data); try { BufferedImage image = ImageIO.read(bis); Graphics2D g2d = image.createGraphics(); FontMetrics fm = g2d.getFontMetrics(); BasicStroke bs = new BasicStroke(10); Color bgColor = new Color(255, 255, 255, 128); g2d.setStroke(bs); for (APIObject obj : response.getObjects()) { ArrayList<Point> location = obj.getLocation(); g2d.setColor(Color.BLACK); for (int i = 0; i < 4; ++i) { g2d.drawLine(location.get(i).getX(), location.get(i).getY(), location.get((i + 1) % 4) .getX(), location.get((i + 1) % 4).getY()); } float x = (location.get(0).getX() + location.get(2).getX()) / 2; float y = (location.get(0).getY() + location.get(2).getY()) / 2; Rectangle2D rect = fm.getStringBounds(obj.getName(), g2d); g2d.setColor(bgColor); g2d.fillRect((int) x, (int) y - fm.getAscent(), (int) rect.getWidth(), (int) rect.getHeight()); g2d.setColor(Color.BLACK); g2d.drawString(obj.getName(), x, y); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "jpg", baos); return new Image(baos.toByteArray(), image.getWidth(), image.getHeight()); } catch (IOException e) { e.printStackTrace(); } return null; }
b50cbd85-1cbd-45bc-be0b-617386c2bcb0
public void save(String path) throws IOException { BufferedOutputStream bos = null; FileOutputStream fos = new FileOutputStream(new File(path)); bos = new BufferedOutputStream(fos); bos.write(data); }
b170d46b-3192-4322-9461-876a04e62639
public APIResponse(String jsonToParse) { objects = new ArrayList<APIObject>(); try { JSONObject resp = new JSONObject(jsonToParse); this.status= resp.getInt("status"); if (status != 0) { this.message = resp.getString("message"); return; } JSONArray obj = resp.getJSONArray("objects"); for (int i = 0; i < obj.length(); ++i) { objects.add(new APIObject(obj.getJSONObject(i))); } } catch (JSONException e) { e.printStackTrace(); } }
b46e6913-09c8-4875-abe3-31b8b8c43f94
public APIResponse(int status) { this.status = status; }
c9fc9c26-9d3b-4f14-9bef-03d130d31381
public int getStatus() { return status; }
28a62ed0-0b32-48df-b2d5-fe6bbd3cfd07
public String getMessage() { return message; }
fd42876b-61e5-4698-8f3b-532b1dd69146
public ArrayList<APIObject> getObjects() { return objects; }
16135d70-fbc0-4f53-abe8-4486be7574ef
public void setStatus(int status) { this.status = status; }
3f985dc5-2a21-4e87-88c7-6b2adc3c1d84
public void setMessage(String message) { this.message = message; }
61bab3d9-9e7a-4013-ac36-5f58d4ad3869
public void setObjects(ArrayList<APIObject> objects) { this.objects = objects; }
b299c803-29a9-4fa5-b537-7d6b9855d96e
@Override public String toString() { if (status < 0) return "Internal error: " + this.getMessage(); if (status > 0) return this.getMessage(); String text = "Found " + this.objects.size() + " objects: {"; for (APIObject obj: this.objects) { text += obj.getName() + ", "; } text = text.substring(0, text.length() - 2); return text + "}"; }
3f1fac53-1636-4d3d-bade-8b42e6442e6d
public APIObject(JSONObject object) throws JSONException { location = new ArrayList<Point>(); this.id = object.getString("id"); this.name = object.getString("name"); JSONArray loc = object.getJSONArray("location"); for (int i = 0; i < loc.length(); ++i) { location.add(new Point(loc.getJSONObject(i))); } }
b54aadd5-6244-4e73-bd73-8c5750ac3de8
public String getId() { return id; }
34905c4a-862e-4a3c-9723-abb264193316
public String getName() { return name; }
5833bca7-e910-429f-8997-c39f443b4bd5
public void setId(String id) { this.id = id; }
20fd34ca-8fad-469b-91ed-8363653b11a9
public void setName(String name) { this.name = name; }
90677130-ecf1-4e8a-b9d2-b32211497faa
public ArrayList<Point> getLocation() { return location; }
c86cde8e-19cb-422c-9033-2664433b12e3
public void setLocation(ArrayList<Point> location) { this.location = location; }
073acfb5-1a5c-43f4-a1da-653bcd9a3055
public static void main(String[] args) { Image image = readImageData("joker.jpg"); if (image == null || image.getData() == null) { System.err.println("Given image could not be read"); return; } try { // initialize proxy class (this perform authorisation) ITraffSoapProxy iTraffSoap = new ITraffSoapProxy(clientId, clapiKey, apiKey); // insert new image with 123# as ID and "Image name" as the name // (examplary response: {status=0}) Map<String, Object> result2 = iTraffSoap.imageInsert("123#", "Image name", Base64.encodeBase64String(image.getData())); // apply changes (this needs to be invoked before the newly added // (examplary response: {status=0}) // picture can be recognizable) // result2 = iTraffSoap.indexBuild(); // check progress of applying the changes (examplary response: // {status=0, data={progress=100, status=ok, uploading=0, // needUpdate=0}}) Map<String, Object> result = iTraffSoap.indexStatus(); System.out.println(result.toString()); // recognize image (this returns all the results from the // recognition) APIResponse response = recognizeReturnAll(image); // recognized // images System.out.println(response.toString()); // recognize image (this returns only the best result from the // recognition) response = recognizeReturnBest(image); System.out.println(response.toString()); image.draw(response).save("frames.jpg"); // recognize image (in multiple mode). Remember to change the mode at recognize.im first. response = recognizeMulti(image); System.out.println(response.toString()); // recognize image (in multiple mode). Remember to change the mode at recognize.im first. response = recognizeMultiAllInstances(image); System.out.println(response.toString()); } catch (RemoteException e) { System.out.println(e.toString()); // TODO handle the case when there was a proble with accessing the // remote SAOP service } catch (JSONException e) { // TODO handle the case when the response from the server was not in // the JSON format } catch (IOException e) { // TODO handle the case when there wa IO problem with sending the // request or receiving the response } }
cebff233-d7a9-420b-93c5-05113da24870
private static Image readImageData(String imageName) { byte[] imgData = null; BufferedImage img = null; try { //read image data InputStream imgIs = new FileInputStream(imageName); imgData = new byte[imgIs.available()]; imgIs.read(imgData); imgIs.close(); //read image dimensions img = ImageIO.read(new File(imageName)); } catch (IOException e) { // TODO handle IOException when there is a problem with reading return null; } return new Image(imgData, img.getWidth(), img.getHeight()); }
b00d1c9a-0f3f-4bad-b6d2-fce88e5fd00e
public static APIResponse recognizeReturnBest(Image image) throws IOException, JSONException { String recognizeMode = "single"; URL url = new URL(SERVER_ADDRESS + "v2/recognize/single/" + clientId); return recognize(image, url, recognizeMode); }
76e3656c-3a7f-4782-a757-d48f93d2fbd7
public static APIResponse recognizeReturnAll(Image image) throws IOException, JSONException { String recognizeMode = "single"; URL url = new URL(SERVER_ADDRESS + "v2/recognize/single/all/" + clientId); return recognize(image, url, recognizeMode); }
e5897baf-90d5-46bb-b8d1-318b79c9224c
public static APIResponse recognizeMulti(Image image) throws IOException, JSONException { String recognizeMode = "multi"; URL url = new URL(SERVER_ADDRESS + "v2/recognize/multi/" + clientId); return recognize(image, url, recognizeMode); }
93d19d46-d802-49e6-b955-6daca365b68c
public static APIResponse recognizeMultiAllInstances(Image image) throws IOException, JSONException { String recognizeMode = "multi"; URL url = new URL(SERVER_ADDRESS + "v2/recognize/multi/all/" + clientId); return recognize(image, url, recognizeMode); }
46813402-5313-42c8-8a8e-de913afe7ea5
private static APIResponse recognize(Image image, URL url, String recognizeMode) throws IOException, JSONException { APIResponse response = new APIResponse(-1); if (!checkImageLimits(image, recognizeMode)) { System.err.println("Image does not fulfill the requirements, terminating."); response.setMessage("Image does not fulfill the requirements, terminating."); return response; } String md5hash = getMD5FromKeyAndImage(apiKey, image.getData()); if (md5hash == null) { response.setMessage("Empty hash"); return response; } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "image/jpeg"); conn.addRequestProperty("x-itraff-hash", md5hash); OutputStream os = conn.getOutputStream(); os.write(image.getData()); os.flush(); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; output = getResponseJson(br); response = new APIResponse(output); conn.disconnect(); return response; }
a8db410b-1181-424c-b272-dd9b4742ac8a
private static boolean checkImageLimits(Image image, String recognizeMode) { final float imageSurface = (float)(image.getHeight() * image.getWidth()) / 1000000.f; //Mpix final float fileSize = (float)image.getData().length / 1000.f; //KBytes if (recognizeMode.equalsIgnoreCase("single")) { if (fileSize > SINGLEIR_MAX_FILE_SIZE || image.getHeight() < SINGLEIR_MIN_DIMENSION || image.getWidth() < SINGLEIR_MIN_DIMENSION || imageSurface < SINGLEIR_MIN_IMAGE_SURFACE || imageSurface > SINGLEIR_MAX_IMAGE_SURFACE) { return false; } } else if (recognizeMode.equalsIgnoreCase("multi")) { if (fileSize > MULTIIR_MAX_FILE_SIZE || image.getHeight() < MULTIIR_MIN_DIMENSION || image.getWidth() < MULTIIR_MIN_DIMENSION || imageSurface < MULTIIR_MIN_IMAGE_SURFACE || imageSurface > MULTIIR_MAX_IMAGE_SURFACE) { return false; } } else { System.out.println("Unknown recognize mode selected."); } return true; }
adece35b-6a59-4b58-8ba8-e82e3023449a
private static String getMD5FromKeyAndImage(String clientKey, byte[] image) { String hash = null; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.reset(); md.update(clientKey.getBytes("UTF-8")); md.update(image); byte[] array = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3)); } hash = sb.toString(); } catch (NoSuchAlgorithmException e) { hash = null; } catch (UnsupportedEncodingException e) { hash = null; } return hash; }
3c7d7537-8d1e-4540-921b-386f390b7762
private static String getResponseJson(BufferedReader in) throws IOException { StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); return sb.toString(); }
d3d56284-13b9-41ba-b9df-5898259f0a8a
public Point(JSONObject jsonObject) throws JSONException { this.x = jsonObject.getInt("x"); this.y = jsonObject.getInt("y"); }
1014f0c2-937d-427e-95f9-d47fa29d1592
public int getX() { return x; }
99f1052e-fa90-46bc-98f4-5c739f427a11
public int getY() { return y; }
5e93e631-c98f-4ef1-8a87-7f0259a18106
public void setX(int x) { this.x = x; }
9955128f-38af-4808-a947-e71c768ea3d1
public void setY(int y) { this.y = y; }
987466b8-b5c5-4934-bf35-a2336d2794ef
@Test public void testAprValidator() { assertTrue(Validators.getAprValidator().isValid(0.3)); assertTrue(Validators.getAprValidator().isValid(0.000001)); assertTrue(Validators.getAprValidator().isValid(1d)); assertTrue(Validators.getAprValidator().isValid(50d)); assertTrue(Validators.getAprValidator().isValid(5.566654)); assertTrue(Validators.getAprValidator().isValid(100d)); assertFalse(Validators.getAprValidator().isValid(0.0000001)); assertFalse(Validators.getAprValidator().isValid(0d)); assertFalse(Validators.getAprValidator().isValid(-1d)); assertFalse(Validators.getAprValidator().isValid(101d)); assertFalse(Validators.getAprValidator().isValid(103.6)); }
1fc2709d-6995-4a54-a515-0ceb53417b29
@Test public void testTermValidator() { assertTrue(Validators.getTermValidator().isValid(1d)); assertTrue(Validators.getTermValidator().isValid(5d)); assertTrue(Validators.getTermValidator().isValid(999999d)); assertTrue(Validators.getTermValidator().isValid(1000000d)); assertTrue(Validators.getTermValidator().isValid(1000000.0000)); assertFalse(Validators.getTermValidator().isValid(0d)); assertFalse(Validators.getTermValidator().isValid(-1d)); assertFalse(Validators.getTermValidator().isValid(1.2)); assertFalse(Validators.getTermValidator().isValid(133.3333)); assertFalse(Validators.getTermValidator().isValid(1000000.00001)); }
461fc12a-ea3f-4f8c-a08d-88b455b073d1
public AmortizationScheduleItem(final int paymentNumber, final BigDecimal paymentAmount, final BigDecimal paymentInterest, final BigDecimal currentBalance, final BigDecimal totalPayments, final BigDecimal totalInterestPaid) { super(); this.paymentNumber = paymentNumber; this.paymentAmount = paymentAmount; this.paymentInterest = paymentInterest; this.currentBalance = currentBalance; this.totalPayments = totalPayments; this.totalInterestPaid = totalInterestPaid; }
3f94ccc9-fc8a-4262-898c-4a46b7ad77e3
public int getPaymentNumber() { return paymentNumber; }
b13f0df2-b820-4d31-8fa3-78f68f43cc39
public void setPaymentNumber(final int paymentNumber) { this.paymentNumber = paymentNumber; }
61dac940-b7d8-4669-adc5-0f109760cd78
public BigDecimal getPaymentAmount() { return paymentAmount; }
3deefa02-6ebd-497c-9388-96419762d266
public void setPaymentAmount(final BigDecimal paymentAmount) { this.paymentAmount = paymentAmount; }
d5e25cf2-7f4c-4b09-a373-a1dd8ee7250b
public BigDecimal getPaymentInterest() { return paymentInterest; }
7b209b69-766d-4271-b93c-8d370f353adb
public void setPaymentInterest(final BigDecimal paymentInterest) { this.paymentInterest = paymentInterest; }
ca5c06e4-eb9a-4d3d-8700-c7d1ffbf0576
public BigDecimal getCurrentBalance() { return currentBalance; }
d0afd240-6651-4bde-a11c-fde6e7bc68aa
public void setCurrentBalance(final BigDecimal currentBalance) { this.currentBalance = currentBalance; }
33ccd7de-bf91-4d23-ad62-c4fb4590c147
public BigDecimal getTotalPayments() { return totalPayments; }
b504b6e1-de0a-4731-863a-cb01cf0a41fd
public void setTotalPayments(final BigDecimal totalPayments) { this.totalPayments = totalPayments; }
67cf3396-50aa-464d-8fba-2f094ea9ddc6
public BigDecimal getTotalInterestPaid() { return totalInterestPaid; }
8ac24577-8ff2-47ac-949d-b48d1f6e599a
public void setTotalInterestPaid(final BigDecimal totalInterestPaid) { this.totalInterestPaid = totalInterestPaid; }
6a6911c9-8381-4f7e-b5da-1a9e161e7a82
private long calculateMonthlyPayment() { // M = P * (J / (1 - (Math.pow(1/(1 + J), N)))); // // Where: // P = Principal // I = Interest // J = Monthly Interest in decimal form: I / (12 * 100) // N = Number of months of loan // M = Monthly Payment Amount // // calculate J monthlyInterest = apr / monthlyInterestDivisor; // this is 1 / (1 + J) double tmp = Math.pow(1d + monthlyInterest, -1); // this is Math.pow(1/(1 + J), N) tmp = Math.pow(tmp, initialTermMonths); // this is 1 / (1 - (Math.pow(1/(1 + J), N)))) tmp = Math.pow(1d - tmp, -1); // M = P * (J / (1 - (Math.pow(1/(1 + J), N)))); double rc = amountBorrowed * monthlyInterest * tmp; return Math.round(rc); }
3613911d-0653-418d-b43d-9f406f152833
public void outputAmortizationSchedule() { // // To create the amortization table, create a loop in your program and follow these steps: // 1. Calculate H = P x J, this is your current monthly interest // 2. Calculate C = M - H, this is your monthly payment minus your monthly interest, so it is the amount of principal you pay for that month // 3. Calculate Q = P - C, this is the new balance of your principal of your loan. // 4. Set P equal to Q and go back to Step 1: You thusly loop around until the value Q (and hence P) goes to zero. // String formatString = "%1$-20s%2$-20s%3$-20s%4$s,%5$s,%6$s\n"; printf(formatString, "PaymentNumber", "PaymentAmount", "PaymentInterest", "CurrentBalance", "TotalPayments", "TotalInterestPaid"); long balance = amountBorrowed; int paymentNumber = 0; long totalPayments = 0; long totalInterestPaid = 0; // output is in dollars formatString = "%1$-20d%2$-20.2f%3$-20.2f%4$.2f,%5$.2f,%6$.2f\n"; printf(formatString, paymentNumber++, 0d, 0d, ((double) amountBorrowed) / 100d, ((double) totalPayments) / 100d, ((double) totalInterestPaid) / 100d); final int maxNumberOfPayments = initialTermMonths + 1; while ((balance > 0) && (paymentNumber <= maxNumberOfPayments)) { // Calculate H = P x J, this is your current monthly interest long curMonthlyInterest = Math.round(((double) balance) * monthlyInterest); // the amount required to payoff the loan long curPayoffAmount = balance + curMonthlyInterest; // the amount to payoff the remaining balance may be less than the calculated monthlyPaymentAmount long curMonthlyPaymentAmount = Math.min(monthlyPaymentAmount, curPayoffAmount); // it's possible that the calculated monthlyPaymentAmount is 0, // or the monthly payment only covers the interest payment - i.e. no principal // so the last payment needs to payoff the loan if ((paymentNumber == maxNumberOfPayments) && ((curMonthlyPaymentAmount == 0) || (curMonthlyPaymentAmount == curMonthlyInterest))) { curMonthlyPaymentAmount = curPayoffAmount; } // Calculate C = M - H, this is your monthly payment minus your monthly interest, // so it is the amount of principal you pay for that month long curMonthlyPrincipalPaid = curMonthlyPaymentAmount - curMonthlyInterest; // Calculate Q = P - C, this is the new balance of your principal of your loan. long curBalance = balance - curMonthlyPrincipalPaid; totalPayments += curMonthlyPaymentAmount; totalInterestPaid += curMonthlyInterest; // output is in dollars printf(formatString, paymentNumber++, ((double) curMonthlyPaymentAmount) / 100d, ((double) curMonthlyInterest) / 100d, ((double) curBalance) / 100d, ((double) totalPayments) / 100d, ((double) totalInterestPaid) / 100d); // Set P equal to Q and go back to Step 1: You thusly loop around until the value Q (and hence P) goes to zero. balance = curBalance; } }
05d95835-e577-4ea0-bec5-94e790d0750f
public AmortizationScheduleOrig(double amount, double interestRate, int years) throws IllegalArgumentException { if ((isValidBorrowAmount(amount) == false) || (isValidAPRValue(interestRate) == false) || (isValidTerm(years) == false)) { throw new IllegalArgumentException(); } amountBorrowed = Math.round(amount * 100); apr = interestRate; initialTermMonths = years * 12; monthlyPaymentAmount = calculateMonthlyPayment(); // the following shouldn't happen with the available valid ranges // for borrow amount, apr, and term; however, without range validation, // monthlyPaymentAmount as calculated by calculateMonthlyPayment() // may yield incorrect values with extreme input values if (monthlyPaymentAmount > amountBorrowed) { throw new IllegalArgumentException(); } }
ab25de61-d00d-4b44-964d-8f7fdb1698b7
public static boolean isValidBorrowAmount(double amount) { double range[] = getBorrowAmountRange(); return ((range[0] <= amount) && (amount <= range[1])); }
d3e175fe-3c1e-4098-8943-c4838274c10a
public static boolean isValidAPRValue(double rate) { double range[] = getAPRRange(); return ((range[0] <= rate) && (rate <= range[1])); }
b402965e-6b76-46a3-99f0-382233b7fefb
public static boolean isValidTerm(int years) { int range[] = getTermRange(); return ((range[0] <= years) && (years <= range[1])); }
10e9078e-c5ad-4326-97a2-5f014b08f6cd
public static final double[] getBorrowAmountRange() { return borrowAmountRange; }
960e0cff-0afd-4c94-9ec5-39e0d319df76
public static final double[] getAPRRange() { return aprRange; }
7d1a8828-3f4f-4d63-95a3-08e96e30d598
public static final int[] getTermRange() { return termRange; }
834a3e8d-5d54-494b-b67d-bbb813f49926
private static void printf(String formatString, Object... args) { try { if (console != null) { console.printf(formatString, args); } else { System.out.print(String.format(formatString, args)); } } catch (IllegalFormatException e) { System.err.print("Error printing...\n"); } }
4d7252e5-ef12-46c4-8bf2-25262239b54c
private static void print(String s) { printf("%s", s); }
6274f317-edfa-462a-a70f-94d99fe0abfd
private static String readLine(String userPrompt) throws IOException { String line = ""; if (console != null) { line = console.readLine(userPrompt); } else { // print("console is null\n"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); print(userPrompt); line = bufferedReader.readLine(); } line.trim(); return line; }
c31ef0cb-4577-4054-8fe7-116a956e605f
public static void main(String [] args) { String[] userPrompts = { "Please enter the amount you would like to borrow: ", "Please enter the annual percentage rate used to repay the loan: ", "Please enter the term, in years, over which the loan is repaid: " }; String line = ""; double amount = 0; double apr = 0; int years = 0; for (int i = 0; i< userPrompts.length;) { String userPrompt = userPrompts[i]; try { line = readLine(userPrompt); } catch (IOException e) { print("An IOException was encountered. Terminating program.\n"); return; } boolean isValidValue = true; try { switch (i) { case 0: amount = Double.parseDouble(line); if (isValidBorrowAmount(amount) == false) { isValidValue = false; double range[] = getBorrowAmountRange(); print("Please enter a positive value between " + range[0] + " and " + range[1] + ". "); } break; case 1: apr = Double.parseDouble(line); if (isValidAPRValue(apr) == false) { isValidValue = false; double range[] = getAPRRange(); print("Please enter a positive value between " + range[0] + " and " + range[1] + ". "); } break; case 2: years = Integer.parseInt(line); if (isValidTerm(years) == false) { isValidValue = false; int range[] = getTermRange(); print("Please enter a positive integer value between " + range[0] + " and " + range[1] + ". "); } break; } } catch (NumberFormatException e) { isValidValue = false; } if (isValidValue) { i++; } else { print("An invalid value was entered.\n"); } } try { AmortizationScheduleOrig as = new AmortizationScheduleOrig(amount, apr, years); as.outputAmortizationSchedule(); } catch (IllegalArgumentException e) { print("Unable to process the values entered. Terminating program.\n"); } }
6e8f29c4-3c4d-4e30-8f9e-f5e87d934633
public static Validatable<Double> getBorrowAmountValidator() { return BORROW_AMOUT_VALIDATOR; }
cfc515b1-fdbd-49dc-84bd-f2f211c624b6
public static Validatable<Double> getAprValidator() { return APR_VALIDATOR; }
33353d3d-b170-492d-9a52-25583c7a2060
public static Validatable<Double> getTermValidator() { return TERM_VALIDATOR; }
e6b7051b-4415-43c0-a455-31b15e9bc2fc
private Validators() { // no-op }
133274a2-f398-4f66-a1fb-ca30fdf77eb8
@Override public boolean isValid(final Double value) { return value == value.intValue() && TERM_RANGE_VALIDATOR.isValid(value.intValue()); }
ec3700c5-c4c2-4e58-b887-604dea55a891
public RangeValidator(final Range<T> range) { this.range = range; }
c486f6d6-d2b1-466f-bed6-75e3d522e9a6
@Override public boolean isValid(final T amount) { return amount.compareTo(range.getMin()) >= 0 && amount.compareTo(range.getMax()) <= 0; }
f6f73a42-1e32-4507-8bb9-88b0eac728e0
boolean isValid(T value);
2cfe0642-26b8-43a3-9f5b-0ac65c0c969f
private long calculateMonthlyPayment() { // M = P * (J / (1 - (Math.pow(1/(1 + J), N)))); // // Where: // P = Principal // I = Interest // J = Monthly Interest in decimal form: I / (12 * 100) // N = Number of months of loan // M = Monthly Payment Amount // // calculate J monthlyInterest = apr / MONTHLY_INTEREST_DIVISOR; // this is 1 / (1 + J) double tmp = Math.pow(1d + monthlyInterest, -1); // this is Math.pow(1/(1 + J), N) tmp = Math.pow(tmp, initialTermMonths); // this is 1 / (1 - (Math.pow(1/(1 + J), N)))) tmp = Math.pow(1d - tmp, -1); // M = P * (J / (1 - (Math.pow(1/(1 + J), N)))); double rc = amountBorrowed * monthlyInterest * tmp; // GV: round the ceiling of the number. It becomes important when // dealing with the large numbers where the fraction of a cent makes the // difference between reducing and increasing the debt return Math.round(Math.ceil(rc)); }
4edd836d-1e53-4382-b816-13853a84d8c7
public List<AmortizationScheduleItem> outputAmortizationSchedule() { // // To create the amortization table, create a loop in your program and // follow these steps: // 1. Calculate H = P x J, this is your current monthly interest // 2. Calculate C = M - H, this is your monthly payment minus your // monthly interest, so it is the amount of principal you pay for that // month // 3. Calculate Q = P - C, this is the new balance of your principal of // your loan. // 4. Set P equal to Q and go back to Step 1: You thusly loop around // until the value Q (and hence P) goes to zero. // // GV: borrowing ~1/3 of US Federal Budget ($1T) for million years // under gangester's 100% rate can easily overflow long for payments and // interest paid. Using BigDecimal. BigDecimal balance = new BigDecimal(amountBorrowed); int paymentNumber = 0; BigDecimal totalPayments = BigDecimal.ZERO; BigDecimal totalInterestPaid = BigDecimal.ZERO; List<AmortizationScheduleItem> items = new ArrayList<AmortizationScheduleItem>(); items.add(new AmortizationScheduleItem(paymentNumber++, BigDecimal.ZERO, BigDecimal.ZERO, (new BigDecimal(amountBorrowed)).divide(HUNDRED), totalPayments.divide(HUNDRED), totalInterestPaid.divide(HUNDRED))); final int maxNumberOfPayments = initialTermMonths + 1; BigDecimal bdMonthlyInterest = new BigDecimal(monthlyInterest); while (balance.compareTo(BigDecimal.ZERO) > 0 && paymentNumber <= maxNumberOfPayments) { // Calculate H = P x J, this is your current monthly interest BigDecimal curMonthlyInterest = balance.multiply(bdMonthlyInterest); // the amount required to payoff the loan BigDecimal curPayoffAmount = balance.add(curMonthlyInterest); // the amount to payoff the remaining balance may be less than the // calculated monthlyPaymentAmount BigDecimal curMonthlyPaymentAmount = monthlyPaymentAmount.min(curPayoffAmount); // it's possible that the calculated monthlyPaymentAmount is 0, // or the monthly payment only covers the interest payment - i.e. no // principal // so the last payment needs to payoff the loan if (paymentNumber == maxNumberOfPayments && (curMonthlyPaymentAmount.equals(BigDecimal.ZERO) || curMonthlyPaymentAmount.equals(curMonthlyInterest))) { curMonthlyPaymentAmount = curPayoffAmount; } // Calculate C = M - H, this is your monthly payment minus your // monthly interest, // so it is the amount of principal you pay for that month BigDecimal curMonthlyPrincipalPaid = curMonthlyPaymentAmount.subtract(curMonthlyInterest); // Calculate Q = P - C, this is the new balance of your principal of // your loan. BigDecimal curBalance = balance.subtract(curMonthlyPrincipalPaid); totalPayments = totalPayments.add(curMonthlyPaymentAmount); totalInterestPaid = totalInterestPaid.add(curMonthlyInterest); items.add(new AmortizationScheduleItem(paymentNumber++, curMonthlyPaymentAmount.divide(HUNDRED), curMonthlyInterest.divide(HUNDRED), curBalance.divide(HUNDRED), totalPayments.divide(HUNDRED), totalInterestPaid.divide(HUNDRED))); // Set P equal to Q and go back to Step 1: You thusly loop around // until the value Q (and hence P) goes to zero. balance = curBalance; } return items; }
30cf5c35-53f3-41c2-8877-e4f520d789ab
public AmortizationSchedule(final double amount, final double interestRate, final int years) { if (!Validators.getBorrowAmountValidator().isValid(amount) || !Validators.getAprValidator().isValid(interestRate) || !Validators.getTermValidator().isValid((double) years)) { throw new IllegalArgumentException(); } amountBorrowed = Math.round(amount * CENTS); apr = interestRate; initialTermMonths = years * MONTHS_YEAR; monthlyPaymentAmount = new BigDecimal(calculateMonthlyPayment()); // the following shouldn't happen with the available valid ranges // for borrow amount, apr, and term; however, without range validation, // monthlyPaymentAmount as calculated by calculateMonthlyPayment() // may yield incorrect values with extreme input values if (monthlyPaymentAmount.compareTo(new BigDecimal(amountBorrowed)) > 0) { throw new IllegalArgumentException(); } }
42183144-452a-48e2-8999-ad5a40034a2b
public static void main(String[] args) { final String[] userPrompts = { "Please enter the amount you would like to borrow: ", "Please enter the annual percentage rate used to repay the loan: ", "Please enter the term, in years, over which the loan is repaid: " }; double amount = 0; double apr = 0; int years = 0; try { amount = getValue(userPrompts[0], Validators.getBorrowAmountValidator(), "Please enter a positive value between " + Validators.BORROW_AMOUNT_RANGE.getMin() + " and " + Validators.BORROW_AMOUNT_RANGE.getMax() + ". "); apr = getValue(userPrompts[1], Validators.getAprValidator(), "Please enter a positive value between " + Validators.APR_RANGE.getMin() + " and " + Validators.APR_RANGE.getMax() + ". "); years = getValue( userPrompts[2], Validators.getBorrowAmountValidator(), "Please enter a positive integer between " + Validators.TERM_RANGE.getMin() + " and " + Validators.TERM_RANGE.getMax() + ". ").intValue(); } catch (IOException e) { IOUtils.print("An IOException was encountered. Terminating program.\n"); return; } try { AmortizationSchedule as = new AmortizationSchedule(amount, apr, years); // AmortizationSchedule as = new // AmortizationSchedule(1000000000000d, 100d, 33); // AmortizationSchedule as = new AmortizationSchedule(200000d, 6.3d, 20); IOUtils.printSchedule(as.outputAmortizationSchedule()); } catch (IllegalArgumentException e) { IOUtils.print("Unable to process the values entered. Terminating program.\n"); } }
40cf1207-f3b9-4a43-ba05-cbf9b17db5d8
private static Double getValue(final String promptMessage, final Validatable<Double> validator, final String invalidMessage) throws IOException { boolean isValid = false; double amount = 0; while (!isValid) { String line = IOUtils.readLine(promptMessage); try { amount = Double.valueOf(line); if (validator.isValid(amount)) { isValid = true; } } catch (NumberFormatException e) { IOUtils.print("An invalid value was entered.\n"); } if (!isValid) { IOUtils.print(invalidMessage); } } return amount; }
b8592724-504f-4de7-9f0b-f64bb23954c7
private IOUtils() { }
11fde327-8761-4fc8-b4e1-d11a3a2fed37
public static void printf(String formatString, Object... args) { try { if (console != null) { console.printf(formatString, args); } else { System.out.print(String.format(formatString, args)); } } catch (IllegalFormatException e) { System.err.print("Error printing...\n"); } }
cce11874-6f79-4c56-b874-962994f9a2ed
public static void print(String s) { printf("%s", s); }
65e1feee-4a70-4669-9d93-f1b085e98dcc
public static String readLine(final String userPrompt) throws IOException { String line = ""; if (console != null) { line = console.readLine(userPrompt); } else { // print("console is null\n"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); print(userPrompt); line = bufferedReader.readLine(); } // GV: this will not trim the returned result //line.trim(); return line == null ? "" : line.trim(); }
4a7ba388-785a-4148-9828-52ae03d53e6c
public static void printSchedule(List<AmortizationScheduleItem> items) { String formatString = "%1$-20s%2$-20s%3$-20s%4$-20s%5$-30s%6$-30s\n"; printf(formatString, "PaymentNumber", "PaymentAmount", "PaymentInterest", "CurrentBalance", "TotalPayments", "TotalInterestPaid"); // output is in dollars formatString = "%1$-20d%2$-20.2f%3$-20.2f%4$-20.2f%5$-30.2f%6$-30.2f\n"; for (AmortizationScheduleItem item : items) { printf(formatString, item.getPaymentNumber(), item.getPaymentAmount(), item.getPaymentInterest(), item.getCurrentBalance(), item.getTotalPayments(), item.getTotalInterestPaid()); } }
187a7f0d-78ca-4eda-a966-3880f03599ec
public Range(final T min, final T max) { this.min = min; this.max = max; }
9220e9d2-7bc1-46f2-855a-f6e3695e6609
public T getMin() { return min; }
552192e5-f6f7-430b-9979-fcd4dde3ed9a
public T getMax() { return max; }
85ef7270-4d9e-4432-ba73-4e0621a2c2cc
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((max == null) ? 0 : max.hashCode()); result = prime * result + ((min == null) ? 0 : min.hashCode()); return result; }
e93b496d-5d32-4b57-b2aa-081297ab75b7
@Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Range other = (Range) obj; if (max == null) { if (other.max != null) { return false; } } else if (!max.equals(other.max)) { return false; } if (min == null) { if (other.min != null) { return false; } } else if (!min.equals(other.min)) { return false; } return true; }
0e71f337-b57e-453c-853f-4f25f5502bb0
public static String leerFichero(String nombreFichero) throws IOException { File fichero = new File (nombreFichero); // Crea un objeto File a partir del nombre del fichero a leer Scanner scan = new Scanner(fichero); //Crea un Scanner para recorrer el fichero y recuperar el contenido StringBuffer texto=new StringBuffer(); // Para guardar el texto del fichero a medida que se lee l�nea a l�nea; m�s eficiente que concatenar Strings. while (scan.hasNextLine()) { //bucle de lectura l�nea a l�nea y volcado del fichero en StringBuffer texto.append(scan.nextLine()); //a�ado la l�nea le�da con nextLine al buffer texto.append(System.getProperty("line.separator")); //a�adimos secuencia de newline adecuada seg�n el sistema operativo, para que sea portable. } scan.close(); return (texto.toString()); //convierte el StringBuffer a String y lo devuelve. }
5f428e8b-c988-427b-882b-0ad7a55e02ad
public static void escribirFichero(String texto,String nombreFichero) throws FileNotFoundException { File fichero = new File (nombreFichero); // Crea un objeto File a partir del nombre de fichero a guardar PrintWriter escritor = new PrintWriter(fichero); escritor.print(texto); // escribe el texto en fichero escritor.close(); //cierro el escritor creado. }
a5a19d4c-7307-46de-b722-654840487946
public static void main(String[] args) { Scanner consola = new Scanner(System.in); //Crea Scanner para leer por consola System.out.println("Nombre del fichero a leer> "); String nombreFichIn=consola.nextLine(); //lee la l�nea con el nombre de fichero desde consola String contenido=null; //para guardar el texto del fichero le�do try { contenido = LEfichero.leerFichero(nombreFichIn); //se intenta leer el contenido de fichero } catch (IOException e) { System.out.println("***Error de lectura*** "+e); } if (contenido!=null){ try { System.out.println("Nombre del fichero para guardar> "); String nombreFichOut=consola.nextLine(); LEfichero.escribirFichero(contenido,nombreFichOut); System.out.println("+++ El fichero de salida ha sido generado."); } catch (IOException e) { System.out.println("***Error de escritura*** "+e); } } consola.close(); }
942120fd-5ef7-45e9-bb85-0aaf42e29f13
public static void main(String[] args) throws IOException { Scanner consola = new Scanner(System.in); //Construye objeto Scanner para leer desde consola (entrada est�ndar) String linea; //para almacenar una l�nea de texto por consola System.out.println("Introduzca su nombre> "); linea=consola.nextLine(); //lee l�nea desde consola System.out.println("Ha introducido "+"\""+linea+"\""); //imprime l�nea le�da por consola entre comillas /////////// Otra forma de leer desde consola mediante un BufferReader InputStreamReader fuente = new InputStreamReader (System.in); BufferedReader lector =new BufferedReader (fuente); //Construye un buffer de texto para leer desde consola System.out.println("\nIntroduzca su tel�fono> "); linea=lector.readLine(); //lee l�nea desde consola System.out.println("Ha introducido "+"\""+linea+"\""); //imprime l�nea le�da por consola consola.close(); }
204c06fe-2bea-4b93-aef1-ecc795b6ca7a
static void ejemComparaCadenas(){ System.out.println("\nSALIDA método ejemComparaCadenas.\n"); System.out.println("*** Compara cadenas con equals"); String saludo1="hola"; String saludo2="Hola"; boolean coincide= saludo1.equals(saludo2); if (coincide) System.out.println("Las cadenas \""+ saludo1 + "\" y \"" +saludo2 +"\" son iguales"); else System.out.println("Las cadenas \""+ saludo1 + "\" y \"" +saludo2 +"\" son distintas"); System.out.println("*** Compara cadenas con equalsIgnoreCase"); coincide= saludo1.equalsIgnoreCase(saludo2); if (coincide) System.out.println("Las cadenas \""+ saludo1 + "\" y \"" +saludo2 +"\" son iguales"); else System.out.println("Las cadenas \""+ saludo1 + "\" y \"" +saludo2 +"\" son distintas"); }
54bd4282-05bc-4442-b64e-e6b6fa7068ea
public static void ejemTrimToEntero() { System.out.println("\nSALIDA método ejemTrimToEntero.\n"); String cadena=" 725 "; System.out.println("*** Elimina espacios con trim"); cadena=cadena.trim(); //elimina espacios de prefijo y sufijo en la cadena System.out.println("Tras aplicar trim la cadena es:"+"\""+cadena+"\""); int numero=Integer.parseInt(cadena); //convierte la cadena sin espacios a entero numero++; //incrementa el Número leído System.out.println("Número incrementado: "+numero); //EJERCICIO: probar a convertir cadena sin amplicar antes trim. }
8da4fd9a-f075-44fb-9040-b9f7b4899f3a
static void ejemRecorridoString(){ String[] listaCadenas={"hola","mundo",""}; //inicializa array de 3 Strings, la última es la cadena vacía String cadena; //para almacenar cadena extraída de un array de Strings int longitudCadena; // para guardar longitud de cadena extraída System.out.println("\nSALIDA método ejemREcorridoString.\n"); System.out.println("***Recorrido con bucle for, de array de String y de caracteres de String "); for (int i=0;i<listaCadenas.length;i++){ //extrae cadenas hasta no superar longitud de array cadena=listaCadenas[i]; //extrae la cadena del array longitudCadena=cadena.length(); System.out.println("\tCadena en posicion "+i+ " del array es: \""+cadena+"\""); if (cadena.equals("")){ //comprueba si cadena es vacía System.out.println("\tLa cadena extraída es vacía"); } for (int j=0;j<longitudCadena;j++){ //extrae caracteres hasta no superar longitud de cadena System.out.println("\t\tCarácter en posición "+j+ ": \'"+cadena.charAt(j)+"\'"); } } System.out.println("***Recorrido con bucle for-each de array de String"); // Bucle for each para recorrer array de otra forma for (String cadena2 : listaCadenas) { System.out.println("\tCadena extraida del array: \""+cadena2+"\""); } }// end-método
a385dc70-ba31-42cd-911a-6ee3a4e865ce
static void ejemSplitSimple(){ System.out.println("\nSALIDA método ejemSplitSimple."); String saludo="123,45,2"; String[] listaCadenas=saludo.split(","); //obtiene las cadenas leídas en la línea System.out.println("***Cadenas extraídas con split con ; como separador:"); System.out.println("Texto: \""+saludo+"\""); for (String cadena : listaCadenas) { System.out.println("\tCadena extraída: \""+cadena+"\""); } }// end-método
dc28436f-e59c-469d-be73-5d3cc06366fb
static void ejemSplitER(){ System.out.println("\nSALIDA método ejemSplitER."); String saludo="123..45,2"; String erSeparador = "[,.]+"; // ER para secuencia de coma/punto como posible separador String [] troceo1 = saludo.split(erSeparador); // las cadenas extraídas se quedan en array troceo System.out.println("***Cadenas extraídas con split con ER "+"[,.]+"); System.out.println("Texto: \""+saludo+"\""); for(String unTrozo: troceo1) System.out.println("\tCadena extraída: \""+unTrozo+"\""); // Si quitamos la clausura positiva extrae cadenas vacías erSeparador = "[ ,.]"; //modificamos la ER sin clausura positiva String [] troceo2 = saludo.split(erSeparador); System.out.println("***Cadenas extraídas con split modificado con ER [,.]"); for(String unTrozo: troceo2) System.out.println("\tCadena extraída: \""+unTrozo+"\""); }
2bc22f63-130a-4af8-b1f7-dd292acd7493
public static void main(String[] args) throws IOException { ejemComparaCadenas(); ejemTrimToEntero(); ejemRecorridoString(); ejemSplitSimple(); ejemSplitER(); }
65842108-e4b5-4725-967c-9354a7225c05
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { JLabel lbl = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if(value.toString().equals("Sent Items")) { lbl.setIcon(SENT); }else if(value.toString().equals("Inbox")) { lbl.setIcon(INBOX); }else if(value.toString().equals("Settings")) { lbl.setIcon(SETTINGS); }else if(value.toString().equals("Email")) { lbl.setIcon(EMAIL); }else if(value.toString().equals("Timeout")) { lbl.setIcon(TIMEOUT); }else { lbl.setIcon(INBOX); } return lbl; }
556a44be-aba0-4771-9694-d9896fc2016a
public static void makeTreeIcons() { getTreeIcons().add("Email"); getTreeIcons().add("Timeout"); getTreeIcons().add("Sent Items"); }
7e8d79f4-9328-44ef-a9cf-dfc9c6272c9d
public static ArrayList<Object> getTreeIcons() { return treeIcons; }
9f9d03f1-e2c3-4064-94c2-af20e55d5b3f
public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { EstimateClasses frame = new EstimateClasses(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); }
acf2b139-d1db-43f2-ac6b-08cec08634b6
public void run() { try { EstimateClasses frame = new EstimateClasses(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } }
96387638-b46a-4cda-9c7a-24688fd66475
public EstimateClasses() { setTitle("Estimated Classes"); setIconImage(Toolkit.getDefaultToolkit().getImage(EstimateClasses.class.getResource("/net/lotusdev/medusa/client/res/JavaClass.gif"))); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); Builder.getEstimateClasses(); JScrollPane scrollPane = new JScrollPane(); GroupLayout gl_contentPane = new GroupLayout(contentPane); gl_contentPane.setHorizontalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE) ); gl_contentPane.setVerticalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 243, Short.MAX_VALUE) ); JTree tree = new JTree(); tree.setShowsRootHandles(true); tree.setModel(new DefaultTreeModel( new DefaultMutableTreeNode("Classes") { { DefaultMutableTreeNode node_1; node_1 = new DefaultMutableTreeNode("colors"); node_1.add(new DefaultMutableTreeNode("blue")); node_1.add(new DefaultMutableTreeNode("violet")); node_1.add(new DefaultMutableTreeNode("red")); node_1.add(new DefaultMutableTreeNode("yellow")); add(node_1); node_1 = new DefaultMutableTreeNode("sports"); node_1.add(new DefaultMutableTreeNode("basketball")); node_1.add(new DefaultMutableTreeNode("soccer")); node_1.add(new DefaultMutableTreeNode("football")); node_1.add(new DefaultMutableTreeNode("hockey")); add(node_1); node_1 = new DefaultMutableTreeNode("food"); node_1.add(new DefaultMutableTreeNode("hot dogs")); node_1.add(new DefaultMutableTreeNode("pizza")); node_1.add(new DefaultMutableTreeNode("ravioli")); node_1.add(new DefaultMutableTreeNode("bananas")); add(node_1); } } )); scrollPane.setViewportView(tree); DefaultTreeModel model = (DefaultTreeModel) tree.getModel(); DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot(); root.removeAllChildren(); //this removes all nodes model.reload(); ImageIcon leafIcon = new ImageIcon("src/net/lotusdev/medusa/client/res/JavaClass.gif"); DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); renderer.setLeafIcon(leafIcon); tree.setCellRenderer(renderer); for(int i = 0; i < Builder.getClasses.size(); i++) { model.insertNodeInto(new DefaultMutableTreeNode(Builder.getClasses.get(i)), root, root.getChildCount()); } contentPane.setLayout(gl_contentPane); }