+
diff --git a/assets/css/style.css.map b/assets/css/style.css.map
index ed8a529..d7f1215 100755
--- a/assets/css/style.css.map
+++ b/assets/css/style.css.map
@@ -3,12 +3,12 @@
"file": "style.css",
"sources": [
"style.scss",
- "../../tmp/jekyll-remote-theme-20230427-1-1b27ii1/_sass/minima/skins/classic.scss",
- "../../tmp/jekyll-remote-theme-20230427-1-1b27ii1/_sass/minima/skins/auto.scss",
- "../../tmp/jekyll-remote-theme-20230427-1-1b27ii1/_sass/minima/initialize.scss",
+ "../../tmp/jekyll-remote-theme-20230428-1-3ykbmp/_sass/minima/skins/classic.scss",
+ "../../tmp/jekyll-remote-theme-20230428-1-3ykbmp/_sass/minima/skins/auto.scss",
+ "../../tmp/jekyll-remote-theme-20230428-1-3ykbmp/_sass/minima/initialize.scss",
"_sass/minima/custom-variables.scss",
- "../../tmp/jekyll-remote-theme-20230427-1-1b27ii1/_sass/minima/_base.scss",
- "../../tmp/jekyll-remote-theme-20230427-1-1b27ii1/_sass/minima/_layout.scss",
+ "../../tmp/jekyll-remote-theme-20230428-1-3ykbmp/_sass/minima/_base.scss",
+ "../../tmp/jekyll-remote-theme-20230428-1-3ykbmp/_sass/minima/_layout.scss",
"_sass/minima/custom-styles.scss",
"_sass/minima/fastpages-styles.scss",
"_sass/minima/dark-mode.scss"
diff --git a/assets/js/search-data.json b/assets/js/search-data.json
index 18cd4c7..ba8aa48 100755
--- a/assets/js/search-data.json
+++ b/assets/js/search-data.json
@@ -2,39 +2,50 @@
"post0": {
+ "title": "Classes FRQ",
+ "content": "public class AdditionPattern { private int current; private int increment; public AdditionPattern(int start, int inc) { current = start; increment = inc; } // Variable sets integer currentNumber and returns the current value public int currentNumber() { return current; } // Increments the values public void next() { current += increment; } // Subtracts Values public void prev() { if (current > increment) { current -= increment; } } public static void main(String[] args) { AdditionPattern plus3 = new AdditionPattern(2, 3); System.out.println(plus3.currentNumber()); // expected output: 2 plus3.next(); System.out.println(plus3.currentNumber()); // expected output: 5 plus3.next(); System.out.println(plus3.currentNumber()); // expected output: 8 plus3.next(); System.out.println(plus3.currentNumber()); // expected output: 11 plus3.prev(); System.out.println(plus3.currentNumber()); // expected output: 8 plus3.prev(); System.out.println(plus3.currentNumber()); // expected output: 5 plus3.prev(); System.out.println(plus3.currentNumber()); // expected output: 2 plus3.prev(); System.out.println(plus3.currentNumber()); // expected output: 2 } } AdditionPattern.main(null); . 2 5 8 11 8 5 2 2 .",
+ "url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/28/FRQ's.html",
+ "relUrl": "/2023/04/28/FRQ's.html",
+ "date": " • Apr 28, 2023"
+ }
+
+
+
+
+ ,"post1": {
"title": "Pranav IJave Kernel Examples",
"content": "public class PrimitiveExamples { public static void main(String[] args) { int exampleInt = 94; double exampleDouble = 100.4; boolean exampleBoolean = false; String exampleString = "Argentina winning the world cup!"; String exampleStringFormal = new String("Lionel Messi along with the Argentinian National Team are the favorites for this World Cup"); System.out.println("Integer Example: " + exampleInt); System.out.println("Double Example: " + exampleDouble); System.out.println("Boolean Example: " + exampleBoolean); System.out.println("String Example: " + exampleString); System.out.println("Formal String Example: " + exampleStringFormal); } } PrimitiveExamples.main(null) . Integer Example: 94 Double Example: 100.4 Boolean Example: false String Example: Argentina winning the world cup! Formal String Example: Lionel Messi along with the Argentinian National Team are the favorites for this World Cup . import java.util.Scanner; public class PranavPrimitivesExamples { public static void main(String[] args) { Scanner input; input = new Scanner(System.in); System.out.print("Type An Integer: "); try { int PersonInt = input.nextInt(); System.out.println(PersonInt); } catch (Exception e) { System.out.println("This Isn't An Integer (form like 159), " + e); } input.close(); input = new Scanner(System.in); System.out.print("Type A Double: "); try { double PersonDouble = input.nextDouble(); System.out.println(PersonDouble); } catch (Exception e) { System.out.println("This Isn't A Double (form like 9.99), " + e); } input.close(); input = new Scanner(System.in); System.out.print("Type A Boolean: "); try { boolean PersonBoolean = input.nextBoolean(); System.out.println(PersonBoolean); } catch (Exception e) { System.out.println("This Isn't A Boolean (true or false), " + e); } input.close(); input = new Scanner(System.in); System.out.print("Type A String: "); try { String PersonString = input.nextLine(); System.out.println(PersonString); } catch (Exception e) { System.out.println("This Isn't A String, " + e); } input.close(); } } PranavPrimitivesExamples.main(null); . Type An Integer: 5 5 Type A Double: 10.7 10.7 Type A Boolean: true true Type A String: yooooo yooooo . . public class PranavPrimitiveDivision { public static void main(String[] args) { int b1 = 9, b2 = 3; System.out.println("Division For Integers"); System.out.println("int output with concatenation: " + b1 + "/" + b2 + " = " + b1/b2); System.out.println(String.format("int output with format: %d/%d = %d",b1, b2, b1/b2)); System.out.printf(" tint output with printf: %d/%d = %d n",b1, b2, b1/b2); double c1 = 9, c2 = 3; System.out.println("Division For Doubles"); System.out.println(" tdouble output with concatenation: " + c1 + "/" + c2 + " = " + c1/c2); System.out.println(String.format(" tdouble output with format: %.2f/%.2f = %.2f",c1, c2, c1/c2)); System.out.printf(" tdouble output with printf: %.2f/%.2f = %.2f n",c1, c2, c1/c2); System.out.println("Casting and Remainders"); System.out.printf(" tint cast to double on division: %d/%d = %.2f n",b1, b2, b1/(double)b2); System.out.println(" tint using modulo for remainder: " + b1 + "/" + b2 + " = " + b1/b2 + " remainder " + b1%b2); } } PranavPrimitiveDivision.main(null); . Division For Integers int output with concatenation: 9/3 = 3 int output with format: 9/3 = 3 int output with printf: 9/3 = 3 Division For Doubles double output with concatenation: 9.0/3.0 = 3.0 double output with format: 9.00/3.00 = 3.00 double output with printf: 9.00/3.00 = 3.00 Casting and Remainders int cast to double on division: 9/3 = 3.00 int using modulo for remainder: 9/3 = 3 remainder 0 . public class PranavSchoolGradeCalculator { ArrayList<Double> grades; public PranavSchoolGradeCalculator() { this.grades = new ArrayList<>(); this.enterGrades(); } private boolean isZero(double value){ double threshold = 0.001; return value >= -threshold && value <= threshold; } private void enterGrades() { Scanner input; while (true) { input = new Scanner(System.in); System.out.print("Enter a double, 0 to exit: "); try { double sampleInputDouble = input.nextDouble(); System.out.println(sampleInputDouble); if (isZero(sampleInputDouble)) break; else this.grades.add(sampleInputDouble); } catch (Exception e) { System.out.println("Not an double (form like 9.99), " + e); } input.close(); } } public double average() { double total = 0; for (double num : this.grades) { total += num; } return (total / this.grades.size()); } public static void main(String[] args) { PranavSchoolGradeCalculator grades = new PranavSchoolGradeCalculator(); System.out.println("Average: " + String.format("%.2f", grades.average())); } } PranavSchoolGradeCalculator.main(null); . Enter a double, 0 to exit: 10.5 10.5 Enter a double, 0 to exit: 11 11.0 Enter a double, 0 to exit: 12.3 12.3 Enter a double, 0 to exit: 14.5 14.5 Enter a double, 0 to exit: 55.5 55.5 Enter a double, 0 to exit: 65.6 65.6 Enter a double, 0 to exit: 0 0.0 Average: 28.23 . public class PranavSchoolGradeCalculator { ArrayList<Double> grades; public PranavSchoolGradeCalculator() { this.grades = new ArrayList<>(); this.enterGrades(); } private boolean isZero(double value){ double threshold = 0.001; return value >= -threshold && value <= threshold; } private void enterGrades() { Scanner input; while (true) { input = new Scanner(System.in); System.out.print("Enter a double, 0 to exit: "); try { double sampleInputDouble = input.nextDouble(); System.out.println(sampleInputDouble); if (isZero(sampleInputDouble)) break; else this.grades.add(sampleInputDouble); } catch (Exception e) { System.out.println("Not an double (form like 9.99), " + e); } input.close(); } } public double average() { double total = 0; for (double num : this.grades) { total += num; } return (total / this.grades.size()); } public static void main(String[] args) { PranavSchoolGradeCalculator grades = new PranavSchoolGradeCalculator(); System.out.println("Average: " + String.format("%.2f", grades.average())); } } .",
- "url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/26/PranavPrimitiveJupyterPage.html",
- "relUrl": "/2023/04/26/PranavPrimitiveJupyterPage.html",
- "date": " • Apr 26, 2023"
+ "url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/27/PranavPrimitiveJupyterPage.html",
+ "relUrl": "/2023/04/27/PranavPrimitiveJupyterPage.html",
+ "date": " • Apr 27, 2023"
}
- ,"post1": {
+ ,"post2": {
"title": "Java Notebook",
"content": "public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } HelloWorld.main(null); . Hello World! .",
- "url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/26/Java-Jupyter-Notebook.html",
- "relUrl": "/2023/04/26/Java-Jupyter-Notebook.html",
- "date": " • Apr 26, 2023"
+ "url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/27/Java-Jupyter-Notebook.html",
+ "relUrl": "/2023/04/27/Java-Jupyter-Notebook.html",
+ "date": " • Apr 27, 2023"
}
- ,"post2": {
+ ,"post3": {
"title": "Java ArrayList",
"content": "Definition . An ArrayList is like an array that has more flexibility, so it can be resized and things can be added and removed after the array is created. No size limit, and it can have duplicate elements. . import java.util.ArrayList; ArrayList<String> matches = new ArrayList<String>(); matches.add("barcelona"); matches.add("beat"); matches.add("real madrid"); matches.add("4-0"); matches.add("last"); matches.add("year"); System.out.println(matches); . [barcelona, beat, real madrid, 4-0, last, year] . Add and addAll . Adding elements using add(). Can also be added at a certain index if specified. addAll() is used to add all the elements from one array to another. . matches.add("."); //adds the ! to the end of the arraylist matches.add(1, "easily"); //adds the word very to the list at index 4 System.out.println(matches); . [barcelona, easily, beat, real madrid, 4-0, last, year, .] . Size . This returns the size of the list by using size(). . ArrayList<String> more_matches = new ArrayList<String>(); more_matches.add("barcelona"); more_matches.add("lost"); more_matches.add("to"); more_matches.add("liverpool"); more_matches.add("4-3"); //this is very true matches.addAll(more_matches); //adds the second list to the first one System.out.println(matches); matches.size(); . [barcelona, easily, beat, real madrid, 4-0, last, year, ., barcelona, lost, to, liverpool, 4-3] . 13 . Remove (int index) and (element) . This method remove(), removes an element from the index, it shifts the other elements and decreases index by the amount of elements removed. Can be used by removing the index number or the name of the element. . matches.remove(1); //you can see that the word "are" has been removed System.out.println(matches); . [barcelona, beat, real madrid, 4-0, last, year, ., barcelona, lost, to, liverpool, 4-3] . matches.remove("4-3"); matches.remove("lost"); System.out.println(matches); . [barcelona, beat, real madrid, 4-0, last, year, ., barcelona, to, liverpool] . Get . The get() method returns elements at the specific index. . matches.get(0); . barcelona . Set . The set() method replaces an element at an index with another element . matches.set(3, new String("CF")); System.out.println(matches); . [barcelona, beat, real madrid, CF, last, year, ., barcelona, to, liverpool] . IndexOf . The indexOf() method returns when the element occurs first or -1 if its not there. . matches.indexOf("barcelona"); . 0 . lastIndexOf(element) . This method returns the index of when the element comes up last, or -1 if its not in the list. . matches.indexOf("chelsea"); . -1 . hashCode() . Returns the hashcode value of a list, a hashcode is an integer value that corresponds with an object. . matches.hashCode(); . -1011032613 . isEmpty . This method checks if the list is empty or not, and returns true or false if it is empty or not respectively. . matches.isEmpty(); . false . more_matches.isEmpty(); . false . contains(element) . This checks if the list has a certain element, true if it does and false if it doesn't. . matches.contains("real madrid"); . true . matches.contains("inter"); . false . Sort . This method sorts the elements of a list based on a comparator. . import java.util.Collections; System.out.println("List : "+matches); //will sort the string according to alphabetical order Collections.sort(matches); System.out.println("Sorted List : "+matches); . List : [barcelona, beat, real madrid, CF, last, year, ., barcelona, to, liverpool] Sorted List : [., CF, barcelona, barcelona, beat, last, liverpool, real madrid, to, year] . matches.clear(); //clears all the elements in list System.out.println(matches); //they're all gone, how sad . [] .",
- "url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/26/Java-ArrayList.html",
- "relUrl": "/2023/04/26/Java-ArrayList.html",
- "date": " • Apr 26, 2023"
+ "url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/27/Java-ArrayList.html",
+ "relUrl": "/2023/04/27/Java-ArrayList.html",
+ "date": " • Apr 27, 2023"
}
- ,"post3": {
+ ,"post4": {
"title": "Hack 1",
"content": "import java.util.Arrays; import java.util.Random; public class SeatingChart { private String[][] seats; // Constructor that initializes the seating chart with empty seats public SeatingChart(int numRows, int numCols) { seats = new String[numRows][numCols]; for (int i = 0; i < numRows; i++) { Arrays.fill(seats[i], ""); } } // Method to print the current seating chart public void printChart() { System.out.println("Current Seating Chart:"); for (int i = 0; i < seats.length; i++) { for (int j = 0; j < seats[i].length; j++) { System.out.print(seats[i][j] + " t"); } System.out.println(); } } // Method to add a person to a specific seat public void addPerson(String name, int row, int col) { seats[row][col] = name; } // Method to shuffle the seats randomly public void shuffleSeats() { Random rand = new Random(); for (int i = 0; i < seats.length; i++) { for (int j = 0; j < seats[i].length; j++) { int randRow = rand.nextInt(seats.length); int randCol = rand.nextInt(seats[i].length); String temp = seats[i][j]; seats[i][j] = seats[randRow][randCol]; seats[randRow][randCol] = temp; } } } // Method to replace a person in a specific seat public void replacePerson(String newName, int row, int col) { seats[row][col] = newName; } public static void main(String[] args) { SeatingChart chart = new SeatingChart(4, 5); // Create a 4x5 seating chart chart.addPerson("Alice", 0, 0); chart.addPerson("Bob", 1, 2); chart.addPerson("Charlie", 2, 3); chart.addPerson("David", 3, 1); chart.printChart(); chart.shuffleSeats(); chart.printChart(); chart.replacePerson("Eve", 1, 2); chart.printChart(); } } SeatingChart.main(null); . Current Seating Chart: Alice Bob Charlie David Current Seating Chart: Bob Charlie Alice David Current Seating Chart: Bob Charlie Eve Alice David . //create ArrayLists that satisfy the following // a) that stores Boolean values ArrayList<Boolean> boolList = new ArrayList<Boolean>(); // b) that stores Turtle Objects ArrayList<Turtle> turtleList = new ArrayList<Turtle>(); // c) that initializes with 10 Strings ArrayList<String> stringList = new ArrayList<String>(Arrays.asList("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten")); . Hack 2 . import java.util.ArrayList; public class Hack2 { public static void main(Integer[] args) { ArrayList<Integer> randomNumbers = new ArrayList<Integer>(); randomNumbers.add(1); randomNumbers.add(4); randomNumbers.add(7); randomNumbers.add(12); randomNumbers.add(23); System.out.println("ArrayList: " + randomNumbers); ; ; ; } } Hack2.main(null); . ArrayList: [1, 4, 7, 12, 23] . Hack 3 . public class Hack3 { public static void main(String[] args) { ArrayList<Integer> values = new ArrayList<Integer>(); values.add(1); values.add(4); values.add(7); values.add(12); values.add(23); System.out.println("ArrayList: " + values); int total = 0; for (int i=0; i < values.size(); i++) { total += values.get(i); } System.out.println("Total: " + total); } } Hack3.main(null); . ArrayList: [1, 4, 7, 12, 23] Total: 47 . Hack 4 . public class SelectionSort { public static void main(String[] args) { int[] arr = {64, 25, 12, 22, 11}; for (int i = 0; i < arr.length; i++) { for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[i]) { // Swap the elements int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } System.out.print(arr[i] + " "); } } } SelectionSort.main(null); . 11 12 22 25 64 . Hack 5 . public class ArrayIndexingExample { public static void main(String[] args) { int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; System.out.println("Elements with even indexes:"); for (int i = 0; i < arr.length; i += 2) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("Elements with odd indexes:"); for (int i = 1; i < arr.length; i += 2) { System.out.print(arr[i] + " "); } System.out.println(); } } ArrayIndexingExample.main(null); . Elements with even indexes: 1 3 5 7 9 Elements with odd indexes: 2 4 6 8 10 . Hack 7 . public class Test1 { public static void main(String[] args) { int[][] array = { {1,2,3},{-1,-2,-3},{4,5,6} }; int sum = 0; // Iterate over the diagonal of the array for (int i = 0; i < array.length; i++) { sum += array[i][i]; } System.out.println("Sum of diagonal elements: " + sum); } } Test1.main(null); . Sum of diagonal elements: 5 . Extra Credit . // FRQ Array Lists //Part a class MemberInfo { private String name; private int gradYear; private boolean goodStanding; public MemberInfo(String name, int gradYear, boolean goodStanding) { this.name = name; this.gradYear = gradYear; this.goodStanding = goodStanding; } public int getGradYear() { return gradYear; } public boolean inGoodStanding() { return goodStanding; } public String getMemberName() { return name; } } . //Part B import java.util.ArrayList; public class ClubMembers { private ArrayList<MemberInfo> memberList; public ClubMembers() { memberList = new ArrayList<>(); } /** * Adds new club members to memberList. * Precondition: names is a non-empty array. */ public void addMembers(String[] names, int gradYear) { for (String name : names) { MemberInfo member = new MemberInfo(name, gradYear, true); memberList.add(member); } } /** * Removes members who have graduated and returns a list of members who have * graduated and are in good standing. */ public ArrayList<MemberInfo> removeMembers(int year) { ArrayList<MemberInfo> graduatedMembers = new ArrayList<>(); for (int i = 0; i < memberList.size(); i++) { MemberInfo member = memberList.get(i); if (member.getGradYear() == year && member.inGoodStanding()) { graduatedMembers.add(member); memberList.remove(i); i--; // Decrement the index as the list size has changed } } return graduatedMembers; } // Tester method public static void main(String[] args) { ClubMembers club = new ClubMembers(); // Adding members String[] names = {"John", "Emily", "David"}; int gradYear = 2024; club.addMembers(names, gradYear); // Removing members who graduated in a specific year int yearToRemove = 2024; ArrayList<MemberInfo> removedMembers = club.removeMembers(yearToRemove); // Displaying removed members System.out.println("Removed members who graduated in " + yearToRemove + ":"); for (MemberInfo member : removedMembers) { System.out.println(member.getGradYear() + ": " + member.getMemberName()); } } } ClubMembers.main(null); . Removed members who graduated in 2024: 2024: John 2024: Emily 2024: David .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/26/HW-Rohangroup.html",
@@ -45,7 +56,7 @@
- ,"post4": {
+ ,"post5": {
"title": "Title",
"content": "// Defines a class called "Book" that represents a book with a title and an ID public class Book { private String title; private int id; private static int bookCount = 0; // One-argument constructor for title // The ID is automatically assigned when a new book object is created, and it is incremented for each new book created public Book(String title) { this.title = title; this.id = ++Book.bookCount; } // Getter for BookCount //static variable called "bookCount", which keeps track of the total number of books created public static int getBookCount() { return Book.bookCount; } // Override toString() method to return title @Override public String toString() { return this.title; } // Tester Method // tester method called "main()" which creates two book objects, prints out their IDs and titles, also prints out the total book in library as well public static void main(String[] args) { Book book1 = new Book("Boy With The Striped Pajamas"); Book book2 = new Book("Refugee"); System.out.println("Book 1 ID: " + book1.id); System.out.println("Book 1 Title: " + book1.toString()); System.out.println("Book 2 ID: " + book2.id); System.out.println("Book 2 Title: " + book2.toString()); System.out.println("Total books in library: " + Book.getBookCount()); } } //Executes all code within book class to work Book.main(null); . Book 1 ID: 7 Book 1 Title: Boy With The Striped Pajamas Book 2 ID: 8 Book 2 Title: Refugee Total books in library: 8 . // Part 2 import java.time.LocalDate; import java.time.temporal.ChronoUnit; public class Book { //These are where the instance variables are created, fulfilling part 2 private String title; private LocalDate publicationDate; private int shelfLife; public Book(String title, LocalDate publicationDate) { this.title = title; this.publicationDate = publicationDate; this.shelfLife = calculateShelfLife(); } //This is where we calculate the shelf Life of a book private int calculateShelfLife() { LocalDate today = LocalDate.now(); long daysSincePublication = ChronoUnit.DAYS.between(publicationDate, today); return (int)daysSincePublication; } public int getShelfLife() { return shelfLife; } //This is where a boolean method (true/false) is created to determine whether or not the book should come off the shelf and in this situation it comes off the shelf if the shelfLife is greater than or equal to 365 public boolean shouldRemoveFromShelf() { return shelfLife >= 365; } } //This is where part 1 is fulfilled, as the novel and textbook class extend from Book and are created here public class Novel extends Book { private String author; public Novel(String title, LocalDate publicationDate, String author) { super(title, publicationDate); this.author = author; } public String getAuthor() { return author; } } //This is where part 1 is fulfilled, as the novel and textbook class extend from Book and are created here public class Textbook extends Book { private String publishingCompany; public Textbook(String title, LocalDate publicationDate, String publishingCompany) { super(title, publicationDate); this.publishingCompany = publishingCompany; } public String getPublishingCompany() { return publishingCompany; } } //This is where the Book Tester is (part 5, tests everything in parts 1-3) public class BookTester { public static void main(String[] args) { LocalDate publicationDate = LocalDate.of(2010, 1, 1); Novel novel = new Novel("Refugee", publicationDate, "Alan Gratz"); System.out.println(novel.getAuthor()); System.out.println(novel.getShelfLife()); System.out.println(novel.shouldRemoveFromShelf()); Textbook textbook = new Textbook("Integrated 3A", publicationDate, "Pearson"); System.out.println(textbook.getPublishingCompany()); System.out.println(textbook.getShelfLife()); System.out.println(textbook.shouldRemoveFromShelf()); } } BookTester.main(null); . Alan Gratz 4861 true Pearson 4861 true . import java.util.ArrayList; // Tester Method public class BookShelf { public static void main(String[] args) throws InterruptedException { // Construct some books and add them to a library ArrayList<Book> library = new ArrayList<>(); library.add(new TextBook("Diary Of A Wimpy Kid")); library.add(new Novel("Refugee")); library.add(new Novel("Boy With The Striped Pajamas")); // Sleep in java stops Thread.sleep(5000); // Check which books need to be removed from the shelf for (Book book : library) { if (book.isExpired()) { System.out.println(book.getTitle() + " - Expired"); } else { System.out.println(book.getTitle() + " - Available"); } } } } public abstract class Book { private String title; private long constructionTime; public Book(String title) { this.title = title; this.constructionTime = System.nanoTime(); } public String getTitle() { return title; } public long getConstructionTime() { return constructionTime; } // Returns Current Shelf Life public long getShelfLife() { long currentTime = System.nanoTime(); long shelfLife = currentTime - constructionTime; return shelfLife; } public abstract boolean isExpired(); } // Expireation date for shelf life is 3000 nanoseconds or 3 yrs public class TextBook extends Book { private static final long SHELF_LIFE = 3000; public TextBook(String title) { super(title); } public boolean isExpired() { long shelfLife = getShelfLife(); return shelfLife > SHELF_LIFE; } } // Computed Shelf Life extends main public class Novel extends Book { public Novel(String title) { super(title); } public void addReturnStamp() { returnStamps++; } // This method detrmiens when the book needs to come off the shelf or not public boolean isExpired() { long shelfLife = getShelfLife(); long shelfLifeLeft = SHELF_LIFE - shelfLife; if (shelfLifeLeft <= 0) { return true; } else { long renewalThreshold = 3 * 365 * 24 * 60 * 60 * 1000000000L; // 3 years in nanoseconds } } } BookShelf.main(null); . | returnStamps++; cannot find symbol symbol: variable returnStamps | long shelfLifeLeft = SHELF_LIFE - shelfLife; cannot find symbol symbol: variable SHELF_LIFE | public boolean isExpired() { | long shelfLife = getShelfLife(); | long shelfLifeLeft = SHELF_LIFE - shelfLife; | | if (shelfLifeLeft <= 0) { | return true; | } else { | long renewalThreshold = 3 * 365 * 24 * 60 * 60 * 1000000000L; // 3 years in nanoseconds | } | } missing return statement .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/23/Test.html",
@@ -56,7 +67,7 @@
- ,"post5": {
+ ,"post6": {
"title": "Title",
"content": "// Hack 1 import java.util.ArrayList; public class Example { public static void main(String[] args) { // a) ArrayList that stores Boolean values ArrayList<Boolean> booleanList = new ArrayList<>(); // b) ArrayList that stores Turtle Objects ArrayList<String> dogsList = new ArrayList<>(); // c) ArrayList that initializes with 10 Strings ArrayList<String> stringList = new ArrayList<>(10); stringList.add("one"); stringList.add("two"); stringList.add("three"); stringList.add("four"); stringList.add("five"); stringList.add("six"); stringList.add("seven"); stringList.add("eight"); stringList.add("nine"); stringList.add("ten"); booleanList.add(true); // Print the contents of each ArrayList System.out.println("Boolean List:"); for (Boolean b : booleanList) { System.out.println(b); } System.out.println("Dogs List:"); for (String b : stringList) { System.out.println(b); } System.out.println("String List:"); for (String s : stringList) { System.out.println(s); } } } Example.main(null); . Boolean List: true Dogs List: one two three four five six seven eight nine ten String List: one two three four five six seven eight nine ten . // Hack 2 import java.util.ArrayList; public class Hack2 { public static void main(Integer[] args) { ArrayList<Integer> randomNumbers = new ArrayList<Integer>(); randomNumbers.add(1); randomNumbers.add(4); randomNumbers.add(7); randomNumbers.add(12); randomNumbers.add(23); System.out.println("ArrayList: " + randomNumbers); randomNumbers.remove(3); // Removes the element at index 3 (which is 12) System.out.println("ArrayList: " + randomNumbers); randomNumbers.set(2, 9); // Replaces the element at index 2 (which is 7) with 9 System.out.println("ArrayList: " + randomNumbers); randomNumbers.add(6); System.out.println("ArrayList: " + randomNumbers); ; ; ; } } Hack2.main(null); . ArrayList: [1, 4, 7, 12, 23] ArrayList: [1, 4, 7, 23] ArrayList: [1, 4, 9, 23] ArrayList: [1, 4, 9, 23, 6] .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/23/Hacks.html",
@@ -67,7 +78,7 @@
- ,"post6": {
+ ,"post7": {
"title": "POJO Blog",
"content": "What is a POJO . POJO stands for Plain Old Java Object, which is a term used to describe a Java object that does not depend on any framework, container or library outside of the core Java libraries. Characteristics of a POJO . | Simple: A POJO should be simple, with minimal dependencies and clear and concise code. | Accessible: POJOs are easy to access and manipulate since they do not depend on any third-party framework or library. | Serializable: A POJO should be serializable, meaning it can be converted to a byte stream and back to an object, which is useful for things like data transfer and storage. | Testable: POJOs are easy to test since they do not depend on any external libraries or frameworks. | Standard: POJOs should follow standard Java conventions and be written in accordance with the JavaBeans specification. Example of a POJO . . | In this example, we can see a simple POJo that represents a person It has two private fields, name and age, along with getters and setters for each field. | The constructor takes in values for the name and age fields and initializes them. What is JPA . | . | JPA stands for Java Persistence API. It is a specification in the Java programming language for managing relational data in applications. | JPA defines a set of interfaces and classes that provide a standard way to map Java objects to relational database tables and to perform common database operations such as creating, reading, updating, and deleting records. | JPA supports object-relational mapping (ORM), which means that developers can work with Java objects in their code and JPA will handle the details of translating those objects to and from database records. This can simplify development by abstracting away many of the complexities of working with a relational database. Characteristics of JPA . | . | Firstly you have to create an entity class that prepresents the table you want to work with | Next, you’ll need to create a repository interface that extends the JpaRepository interface. | Finally, you have to you can use this repository to perform CRUD operations on the “users” table. Here are some examples: | Overall, this service class uses the UserRepository to perform CRUD operations on the “users” table. | The createUser method creates a new user and saves it to the database. | The getUserById method retrieves a user by their ID. The updateUserPassword method updates a user’s password | .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/markdown/2023/03/02/POJO-Blog.html",
@@ -78,7 +89,7 @@
- ,"post7": {
+ ,"post8": {
"title": "AP CSA Test Corrections",
"content": "Score: 45/52 . Question 7 . . Answer B Incorrect. This would be the result if the division used was floating point division, instead of integer division. This would be the case if either x or y were of type double instead of type int or if either value was typecast as a double in the expression. | Answer C Correct. When we evaluate the express(x < 10) && (y < 0) for x having the value 7 and y having the value 3, x < 10 evaluates to true, since 7 is less than 10, and y < 0 evaluates to false, since 3 is not less than 0. The logic operator && evaluates to true when both conditions are true and evaluates to false otherwise. Since the second condition is false, the boolean expression is false. As a result, the compiler will skip the first output statement and execute the statement in the else. The expression x / y is integer division for 7 / 3, which is 2. | This was more of a conceptual error as I didn’t read the code segment thoroughly resulting in the wrong output being displayed when I looked at it. | . Question 9 . . Answer A Incorrect. This will prevent an ArrayIndexOutOfBoundsException from being thrown if target does not appear in data, however if target is at element 0, -1 will be returned instead of 0 as intended. | Answer B Correct. The seqSearchRecHelper recursive method does not work as intended when target does not appear in data. In this case, when last becomes -1, the method will throw an ArrayIndexOutOfBoundsException in the first if statement after line 1. To prevent this, we should add a check to see if last is less than 0 and if it is, return -1 as expected. | I did this wrong because if you look at the function, the main target wasn’t displaying the correct output. | . Question 19 . . Answer D Incorrect. The indices for myList are 0 through myList.size() – 1, for a total of myList.size() elements. Adding 1 to myList.size() and then multiplying Math.random() by this value results in a range that is from 0 to myList.size(), which is one element too many. | Answer B Correct. The indices for myList are 0 through myList.size() – 1, for a total of myList.size() elements. Using Math.random()generates a random floating point number between 0 and 1, not including 1. When this value is multiplied by the number of elements we want in our range, myList.size(), a random floating point number between 0 and myList.size(), not including myList.size(), is generated. When this value is typecast as an int, the result is an integer value between 0 and myList.size() – 1 inclusive. | In order to get this correct in the future, I plan on studying both topic 2.9 and 7.2 as they cover Arraylists. | . Question 30 . . Answer C Incorrect. List is an interface, which an ArrayList implements. Please note that List is no longer tested as part of the AP CSA exam and ArrayList will be used instead. This would be the correct answer if the remove occurred before the size was calculated in the statement animals.add(animals.size()-k, animals.remove(k)); and only one iteration of the loop occurred. | Answer B Correct. List is an interface, which an ArrayList implements. Please note that List is no longer tested as part of the AP CSA exam and ArrayList will be used instead. The manipulate method contains a for loop with a loop control variable k that starts at the right most index of animals, decrements by 1 each time, until k is equal to 0. In the first iteration, when k is 5, if the element of animals at 5 (“baboon”) starts with a “b”, which it does, then this value is removed from the list and inserted at index 1. The list would then be {“bear”, “baboon”, “zebra”, “bass”, “cat”, “koala”}. | To fix this I will focus on topics 2.7 and 7.4 as they cover instatizing and initializing lists. | . Question 36 . . Answer C Incorrect. The value 5 is at newArray[1][1]. | Answer D Correct. The enhanced for loop iterates over the array oldArray. In the first iteration, newArray[0][0] is assigned the value 1. The value of row is incremented to 1. Since 1 % 3 does not equal 0, the statements in the if are not executed. In the next iteration, newArray[1][0] is assigned the value 2. The value of row is incremented to 2. The algorithm continues to fill column 0 with the subsequent values of oldArray. Once row is 3, the if condition is true and row is assigned 0 and col is incremented to 1. The algorithm proceeds to fill column 1. | Resources: 8.1: Daily Video 1 (Skill 3.E), 8.1: Daily Video 2 (Skill 3.E), 8.1: Daily Video 3 (Skill 1.B) | . Question 44 . . Answer D Incorrect. Choice III uses the default Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error. | Answer B Correct. Choice I uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0, instead of x assigned the value a and y assigned the value b. Choice II correctly uses the two parameter Point constructor to create a new Point with x assigned the value a and y assigned the value b. Choice III uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error. | There is a compiling error that comes out of the answer in option D due to the way in which the constructor assigns a new point. | . Question 48 . . Answer B Incorrect. This would be the result if the division used was floating point division, instead of integer division. This would be the case if either x or y were of type double instead of type int or if either value was typecast as a double in the expression. | Answer C Correct. When we evaluate the express(x < 10) && (y < 0) for x having the value 7 and y having the value 3, x < 10 evaluates to true, since 7 is less than 10, and y < 0 evaluates to false, since 3 is not less than 0. The logic operator && evaluates to true when both conditions are true and evaluates to false otherwise. Since the second condition is false, the boolean expression is false. As a result, the compiler will skip the first output statement and execute the statement in the else. The expression x / y is integer division for 7 / 3, which is 2. | This was more of a conceptual error as I didn’t read the code segment thoroughly resulting in the wrong output being displayed when I looked at it. | .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/markdown/2023/01/31/52Q-Corrections.html",
@@ -89,7 +100,7 @@
- ,"post8": {
+ ,"post9": {
"title": "AP CSA Test Corrections",
"content": "Score: 53/66 . Question 8 . . Answer B Incorrect. This would be the result if the division used was floating point division, instead of integer division. This would be the case if either x or y were of type double instead of type int or if either value was typecast as a double in the expression. | Answer C Correct. When we evaluate the express(x < 10) && (y < 0) for x having the value 7 and y having the value 3, x < 10 evaluates to true, since 7 is less than 10, and y < 0 evaluates to false, since 3 is not less than 0. The logic operator && evaluates to true when both conditions are true and evaluates to false otherwise. Since the second condition is false, the boolean expression is false. As a result, the compiler will skip the first output statement and execute the statement in the else. The expression x / y is integer division for 7 / 3, which is 2. | This was more of a conceptual error as I didn’t read the code segment thoroughly resulting in the wrong output being displayed when I looked at it. | . Question 19 . . Answer E Incorrect. This will prevent an ArrayIndexOutOfBoundsException from being thrown if target does not appear in data, however if target is at element 0, -1 will be returned instead of 0 as intended. | Answer A Correct. The seqSearchRecHelper recursive method does not work as intended when target does not appear in data. In this case, when last becomes -1, the method will throw an ArrayIndexOutOfBoundsException in the first if statement after line 1. To prevent this, we should add a check to see if last is less than 0 and if it is, return -1 as expected. | I did this wrong because if you look at the function, the main target wasn’t displaying the correct output. | . Question 21 . . Answer C Incorrect. The indices for myList are 0 through myList.size() – 1, for a total of myList.size() elements. Adding 1 to myList.size() and then multiplying Math.random() by this value results in a range that is from 0 to myList.size(), which is one element too many. | Answer D Correct. The indices for myList are 0 through myList.size() – 1, for a total of myList.size() elements. Using Math.random()generates a random floating point number between 0 and 1, not including 1. When this value is multiplied by the number of elements we want in our range, myList.size(), a random floating point number between 0 and myList.size(), not including myList.size(), is generated. When this value is typecast as an int, the result is an integer value between 0 and myList.size() – 1 inclusive. | In order to get this correct in the future, I plan on studying both topic 2.9 and 7.2 as they cover Arraylists. | . Question 35 . . Answer C Incorrect. List is an interface, which an ArrayList implements. Please note that List is no longer tested as part of the AP CSA exam and ArrayList will be used instead. This would be the correct answer if the remove occurred before the size was calculated in the statement animals.add(animals.size()-k, animals.remove(k)); and only one iteration of the loop occurred. | Answer B Correct. List is an interface, which an ArrayList implements. Please note that List is no longer tested as part of the AP CSA exam and ArrayList will be used instead. The manipulate method contains a for loop with a loop control variable k that starts at the right most index of animals, decrements by 1 each time, until k is equal to 0. In the first iteration, when k is 5, if the element of animals at 5 (“baboon”) starts with a “b”, which it does, then this value is removed from the list and inserted at index 1. The list would then be {“bear”, “baboon”, “zebra”, “bass”, “cat”, “koala”}. | To fix this I will focus on topics 2.7 and 7.4 as they cover instatizing and initializing lists. | . Question 42 . . Answer C Incorrect. The value 5 is at newArray[1][1]. | Answer D Correct. The enhanced for loop iterates over the array oldArray. In the first iteration, newArray[0][0] is assigned the value 1. The value of row is incremented to 1. Since 1 % 3 does not equal 0, the statements in the if are not executed. In the next iteration, newArray[1][0] is assigned the value 2. The value of row is incremented to 2. The algorithm continues to fill column 0 with the subsequent values of oldArray. Once row is 3, the if condition is true and row is assigned 0 and col is incremented to 1. The algorithm proceeds to fill column 1. | Resources: 8.1: Daily Video 1 (Skill 3.E), 8.1: Daily Video 2 (Skill 3.E), 8.1: Daily Video 3 (Skill 1.B) | . Question 49 . . Answer D Incorrect. Choice III uses the default Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error. | Answer B Correct. Choice I uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0, instead of x assigned the value a and y assigned the value b. Choice II correctly uses the two parameter Point constructor to create a new Point with x assigned the value a and y assigned the value b. Choice III uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error. | There is a compiling error that comes out of the answer in option D due to the way in which the constructor assigns a new point. | . Question 56 . . Answer D Incorrect. Choice III uses the default Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error. | Answer B Correct. Choice I uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0, instead of x assigned the value a and y assigned the value b. Choice II correctly uses the two parameter Point constructor to create a new Point with x assigned the value a and y assigned the value b. Choice III uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error. | There is a compiling error that comes out of the answer in option D due to the way in which the constructor assigns a new point. | . Question 58 . . Answer B Incorrect. Choice III uses the default Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error. | Answer E Correct. Choice I uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0, instead of x assigned the value a and y assigned the value b. Choice II correctly uses the two parameter Point constructor to create a new Point with x assigned the value a and y assigned the value b. Choice III uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error. | There is a compiling error that comes out of the answer in option D due to the way in which the constructor assigns a new point. | . Question 59 . . Answer C Incorrect. Choice III uses the default Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error. | Answer B Correct. Choice I uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0, instead of x assigned the value a and y assigned the value b. Choice II correctly uses the two parameter Point constructor to create a new Point with x assigned the value a and y assigned the value b. Choice III uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error. | There is a compiling error that comes out of the answer in option D due to the way in which the constructor assigns a new point. | . Question 63 . . Answer B Incorrect. Choice III uses the default Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error. | Answer C Correct. Choice I uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0, instead of x assigned the value a and y assigned the value b. Choice II correctly uses the two parameter Point constructor to create a new Point with x assigned the value a and y assigned the value b. Choice III uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error. | There is a compiling error that comes out of the answer in option D due to the way in which the constructor assigns a new point. | .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/markdown/2023/01/23/66mctestcorrections.html",
@@ -100,7 +111,7 @@
- ,"post9": {
+ ,"post10": {
"title": "Vocab List 4",
"content": "Subclass constructor, super Keyword . Extending a class and then constructing the new extends class will call the constructor of the superclass. This is useful when you want to have a constructor that will call the constructor of the superclass. | . public class Superclass { public void printMethod() { System.out.println("Printed in Superclass."); } } public class Subclass extends Superclass { // overrides printMethod in Superclass public void printMethod() { super.printMethod(); System.out.println("Printed in Subclass"); } public static void main(String[] args) { Subclass s = new Subclass(); s.printMethod(); } } Subclass.main(null); . Printed in Superclass. Printed in Subclass . Overloading a method, same name different parameters . In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading. | . // Overloading by changing the number of parameters class MethodOverloading { private static void display(int a){ System.out.println("Arguments: " + a); } private static void display(int a, int b){ System.out.println("Arguments: " + a + " and " + b); } public static void main(String[] args) { display(1); display(1, 4); } } MethodOverloading.main(null); . Arguments: 1 Arguments: 1 and 4 . Overriding a method, same signature of a method . Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. | . // method overriding in java // Base Class class Parent { void show() { System.out.println("Parent's show()"); } } // Inherited class class Child extends Parent { // This method overrides show() of Parent @Override void show() { System.out.println("Child's show()"); } } // Driver class class Main { public static void main(String[] args) { // If a Parent type reference refers // to a Parent object, then Parent's // show is called Parent obj1 = new Parent(); obj1.show(); // If a Parent type reference refers // to a Child object Child's show() // is called. This is called RUN TIME // POLYMORPHISM. Parent obj2 = new Child(); obj2.show(); } } Main.main(null); . Parent's show() Child's show() . Abstract Class, Abstract Method . Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). | Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from). | . //An abstract class can have both abstract and regular methods: abstract class Animal { public abstract void animalSound(); public void sleep() { System.out.println("Zzz"); } } . Standard methods: . toString(): Used to convert an object into a string. | equals(): Useful for comparing two objects to see if they are equal | hashCode(): Useful for getting a unique hash code for an object. | . class toString { public static void main( String args[] ) { //Creating an integer of value 10 Integer number=10; // Calling the toString() method as a function of the Integer variable System.out.println( number.toString() ); } } toString.main(null) . 10 . String myStr1 = "Karthik"; String myStr2 = "Evan"; String myStr3 = "Pranav"; String myStr4 = "Sanjay"; String myStr5 = "Jay"; String myStr6 = "Karthik"; System.out.println(myStr1.equals(myStr6)); // Returns true because they are equal System.out.println(myStr1.equals(myStr4)); // false . true false . /* * Program Demonstrate hashcode() method of Method Class. */ import java.lang.reflect.Method; public class hashCode { // create a Method name getSampleMethod public void getSampleMethod() {} // create main method public static void main(String args[]) { try { // create class object for class name hashCode Class c = hashCode.class; // get Method object of method name getSampleMethod Method method = c.getDeclaredMethod("getSampleMethod", null); // get hashcode of method object using hashCode() method int hashCode = method.hashCode(); // Print hashCode with method name System.out.println("hashCode of method " + method.getName() + " is " + hashCode); } catch (Exception e) { // print if any exception occurs e.printStackTrace(); } } } hashCode.main(null) . hashCode of method getSampleMethod is 49965842 . Late binding of object, referencing superclass object . Late binding is when you have allow the compiler to determine which method to use at runtime instead of compile time. | . public class lateBinding { public static class superclass { void print() { System.out.println("print in superclass."); } } public static class subclass extends superclass { @Override void print() { System.out.println("print in subclass."); } } public static void main(String[] args) { superclass A = new superclass(); superclass B = new subclass(); A.print(); B.print(); } } lateBinding.main(null) . print in superclass. print in subclass. . Polymorphism: any of overloading, overriding, late binding . Polymorphism is the ability to have multiple methods with the same name but different parameters. This is useful when you want to have multiple methods that do the same thing but with different parameters. This is also useful when you want to have a method that can take multiple types of parameters. | . abstract class Animal { public void distanceDriven() { System.out.println("Anima has walked 120 feet"); } } class Dog extends Animal { public void distanceDriven() { System.out.println("The SUV has driven 70 feet"); } } class Cat extends Animal { public void distanceDriven() { System.out.println("The truck has driven 60 feet"); } } // Instantiating the Car class would throw an error as it is abstract Dog dog = new Dog(); Cat cat = new Cat(); dog.distanceDriven(); cat.distanceDriven(); . The SUV has driven 70 feet The truck has driven 60 feet . Big O notation for Hash map, Binary Search, Single loop, Nested Loop . Implementing Big O notation is useful for determining the efficiency of an algorithm. Making algorithms more efficient is useful for making programs compile and run faster and likely reduce the load of it, which could be especially good for websites where users may be runnning the same function through an api many times. | . class Main { public static void main(String[] args) { int a = 0, b = 0; int N = 4, M = 4; // This loop runs for N time for (int i = 0; i < N; i++) { a = a + 10; } // This loop runs for M time for (int i = 0; i < M; i++) { b = b + 40; } System.out.print(a + " " + b); } } Main.main(null) . 40 160 .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/12/01/vocab-(4).html",
@@ -111,7 +122,7 @@
- ,"post10": {
+ ,"post11": {
"title": "Vocab List 3",
"content": "- Accessor Methods . A method called an accessor retrieves confidential information that is kept inside an object. An accessor offers a way for other program elements to access an object's state. . class Student { //Instance variable name private String name; /** getName() example * @return name */ public String getName() { return name; } public static void main(String[] args) { // To call a get method, use objectName.getVarName() Student s = new Student(); System.out.println("Name: MasterCoder " + s.getName() ); } } Student.main(null) . Name: MasterCoder null . - Mutator Methods . A technique used to regulate changes to a variable is known as a mutator method. They're also frequently referred to as setter methods. A getter, often referred to as an accessor, frequently follows a setter and returns the value of the private member variable. . import java.math.BigDecimal; public class Product { private BigDecimal price; private String name; public BigDecimal getPrice() { return price; } public String getName() { return name; } // mutator or setter methods public void setPrice(BigDecimal price) { if(price.compareTo(BigDecimal.ZERO)<0 )throw new IllegalArgumentException("Empty product name"); this.price = price; } public void setName(String name) { if(name.isEmpty()) throw new IllegalArgumentException("Empty product name"); this.name = name; } } . - Static, Class Variables . All instances of a class share static variables, which are variables. This implies that no matter how many instances of the same class of objects you create, changing a static variable or method will update it for all of them. This is helpful if you want to increment a counter for each instance of a class, for example. . class VariableDemo { static int count=0; public void increment() { count++; } public static void main(String args[]) { VariableDemo obj1=new VariableDemo(); VariableDemo obj2=new VariableDemo(); obj1.increment(); obj2.increment(); System.out.println("Obj1: count is="+obj1.count); System.out.println("Obj2: count is="+obj2.count); } } VariableDemo.main(null) . Obj1: count is=2 Obj2: count is=2 . public class VariableExample{ int myVariable; static int data = 30; public static void main(String args[]){ int a = 100; VariableExample obj = new VariableExample(); System.out.println("Value of instance variable myVariable: "+obj.myVariable); System.out.println("Value of static variable data: "+VariableExample.data); System.out.println("Value of local variable a: "+a); } } VariableExample.main(null) . Value of instance variable myVariable: 0 Value of static variable data: 30 Value of local variable a: 100 . - Public, Private, Protected . public: available to everyone. protected: open to subclasses in any package as well as classes belonging to the same package. default, indicating that no modifiers are specified: accessible by classes belonging to the same package. private: only available to members of the same class. . public class Addition { public int addTwoNumbers(int a, int b){ return a+b; } } class Test{ public static void main(String args[]){ Addition obj = new Addition(); System.out.println(obj.addTwoNumbers(100, 1)); } } Test.main(null) . 101 . class Data { private String name; // getter method public String getName() { return this.name; } // setter method public void setName(String name) { this.name= name; } } public class Main { public static void main(String[] main){ Data d = new Data(); // access the private variable using the getter and setter d.setName("Mortensen"); System.out.println(d.getName()); } } Main.main(null) . Mortensen . public class Addition { protected int addTwoNumbers(int a, int b){ return a+b; } } class Test extends Addition{ public static void main(String args[]){ Test obj = new Test(); System.out.println(obj.addTwoNumbers(11, 22)); } } . - Static, Class Methods . A static method is a method that is declared as a member of an object but can only be accessed from the constructor of an API object rather than from an instance of the object generated by the constructor. Class methods, on the other hand, are methods that are invoked on the class as a whole rather than on a single object instance. As a result, it falls under the class level, and the class method is shared by all class instances. A class method is linked to the class itself, not to any class objects. Only class variables are accessible to it. . public class StaticExample { public static int x; public static void main(String[] args) { x += 7; System.out.println("Add 7. Result: " + x); } } StaticExample se = new StaticExample(); se.main(null); . Add 7. Result: 7 . - "this Keyword" . In a method or constructor, the "this keyword" refers to the current object. As a class attribute is shadowed by a method or constructor argument, the this keyword is most frequently used to clarify the differences between class attributes and parameters with the same name. . class A{ A(){ this(5); System.out.println("hello world"); } A(int x){ System.out.println(x); } } class TestThis6{ public static void main(String args[]){ A a=new A(); }} . - "main method" . As the starting point for running a Java program, the main method in Java is typically the first method you encounter when learning how to program in Java. The main method can be located in any class that is a part of a program and can contain code to run or call other methods. . // Extends static example and modifies x value public class ExtendsExample extends StaticExample { public static void main(String[] args) { x += 10232; System.out.println("Add 10232. Result: " + x); } } ExtendsExample ee = new ExtendsExample(); ee.main(null); . Add 10232. Result: 10239 . - Inherticance, Extends . It can inherit properties and methods from the class it is extending by using an extends method. When you want to alter or add to an existing class without having to completely rewrite the code for the class you are extending, this is helpful. . public class Cat extends Animal{ private String color; public Cat(boolean veg, String food, int legs) { super(veg, food, legs); this.color="White"; } public Cat(boolean veg, String food, int legs, String color){ super(veg, food, legs); this.color=color; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } } public class AnimalInheritanceTest { public static void main(String[] args) { Cat cat = new Cat(false, "milk", 4, "black"); System.out.println("Cat is Vegetarian?" + cat.isVegetarian()); System.out.println("Cat color is " + cat.getColor()); } } AnimalInheritanceTest.main(null) . Cat is Vegetarian?false Cat color is black .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/homework/2022/12/01/vocab-(3).html",
@@ -122,7 +133,7 @@
- ,"post11": {
+ ,"post12": {
"title": "Vocab List 2",
"content": "Comparing Numbers . To check two numbers for equality in Java, we can use the Equals() method as well as the == operator. | Firstly, let us set Integers. Integer val1 = new Integer(5); Integer val2 = new Integer(5); Now, to check whether they are equal or not, let us use the == operator. | . public class Example { public static void main(String[] args) { int x = 20; int y = 23; if(x==y) { System.out.println("Both are equal"); } else { System.out.println("x and y are not equal"); } } } . Comparing Strings . The == operator, known as the equality operator, is used to compare two strings in Java. | Using user-defined function : Define a function to compare values with following conditions : if (string1 > string2) it returns a positive value. | if both the strings are equal lexicographically | i.e.(string1 == string2) it returns 0. | if (string1 < string2) it returns a negative value. | . | . public class StringComp { public static void main(String[] args) { String s1 = "hello"; String s2 = "hello"; String s3 = new String("hello"); System.out.println(s1 ==s2); System.out.println(s1 ==s3); } } . Comparing Objects . Comparing objects is an essential feature of object-oriented programming languages. | By comparing two objects, the value of those objects isn't 1. Rather, it's their memory addresses in the stack that are different, since both objects are created using the new operator. If we assigned a to b, then we would have a different result | In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. | . public class Netflix { public static void main(String[] args) { String s1 = "name"; String s2 = "name"; if(s1 == (s2)) { System.out.println(s1); } } } . For Loop . A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times. | A for loop is useful when you know how many times a task is to be repeated. | . public class Vehicles { public static void main(String[] args) { String[] cars = {"Audi", "BMW", "Nissan"}; for(String car : cars); } } . While Loop . The Java while loop is used to iterate a part of the program repeatedly until the specified Boolean condition is true. | As soon as the Boolean condition becomes false, the loop automatically stops. | The while loop is considered as a repeating if statement. | . class WhileLoop { public static void main(String[] args) { int i = 1; while(i <= 6) { System.out.println(i); i++; } } } . Nested Loops . A nested loop is a (inner) loop that appears in the loop body of another (outer) loop. | The inner or outer loop can be any type: while, do while, or for. | For example, the inner loop can be a while loop while an outer loop can be a for loop. | . for (int i = 0; i < 3; i++) { for(int j = 0; j < 2; j++) System.out.println(i + " " + j); System.out.println(); } . 0 0 0 1 1 0 1 1 2 0 2 1 . How to Create a Class . Everything in Java is associated with classes and objects, along with its attributes and methods. | For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake. | A Class is like an object constructor, or a "blueprint" for creating objects. | Classes are required in OOPs because: It provides template for creating objects, which can bind code into data. | It has definitions of methods and data. It supports inheritance property of Object Oriented Programming and hence can maintain class hierarchy. | . Constructor . A constructor in Java is a special method that is used to initialize objects. | The constructor is called when an object of a class is created. | In Java, constructors can be divided into 3 types: No-Arg Constructor. Parameterized Constructor. Default Constructor. | . public String getName() { return name; } public static void main(String[] args) { Data d = new Data("Java"); System.out.println(d.getName()); } .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/12/01/vocab-(2).html",
@@ -133,7 +144,7 @@
- ,"post12": {
+ ,"post13": {
"title": "Vocab List 1",
"content": "Casting . Below, there are two examples of casting. Both examples convert a double data type to integer via truncation. 1.511 is outputted as 1 in the first line. 28.2 is printed as 28 in the second line. This can simplify the output and make it easier to operate on in future code as well. . double d1 = 6.53; double d2 = 4.32; // Casting for division int dd = (int) (d1/d2); // Casting for multiplication int md = (int) (d1*d2); System.out.println(dd); // output of division, is integer System.out.println(md); // output of multiplication, is integer . 1 28 . Wrapper Classes . Wrapper class allow the use of primitive data types like integers as classes, and therefore use methods and code that otherwise would not be allowed. Below, the toString method can not be used with the primitive, but works with the wrapper. . int i = 1; Integer ii = 1; // String unwrapped = i.toString(); String wrapped = ii.toString(); System.out.println(i); System.out.println(ii); . | String unwrapped = i.toString(); int cannot be dereferenced . Concatenation . Concatenation is combinining two or more strings. . String s1 = "hello"; String s2 = "world"; String conc = s1.concat(s2); System.out.println(s1+ " " + s2); System.out.println(conc); System.out.println(s1 + " " + s2 + " " + 12); . hello world helloworld hello world 12 . Math Class . Allows math operations. Absolute value and random. . int ex = -1; System.out.println(Math.abs(-1)); // random between 1 and 10 System.out.println((int)(Math.random() * (100-10) + 10)); System.out.println((Math.random() * (10-1) + 1)); . 1 27 2.393138714397412 . Compound Boolean Expression . Compound boolean expressions are when multiple boolean expressions are nested within each other. . boolean a = true; boolean b = false; System.out.println(!a && !b); . false . Truth Tables . Help visualize compound boolean expressions and make it easier to evaluate. . DeMorgans Law . Make boolean expressions easier. . boolean a = true; boolean b = false; System.out.println(!(a&&b)); System.out.println(!a || !b); System.out.println(!(a||b)); System.out.println(!a && !b); . true true false false .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/12/01/vocab-(1).html",
@@ -144,7 +155,7 @@
- ,"post13": {
+ ,"post14": {
"title": "AP CSA Test Corrections",
"content": "Question 4 . . Answer B Incorrect. This would be the result if the division used was floating point division, instead of integer division. This would be the case if either x or y were of type double instead of type int or if either value was typecast as a double in the expression. | Answer C Correct. When we evaluate the express(x < 10) && (y < 0) for x having the value 7 and y having the value 3, x < 10 evaluates to true, since 7 is less than 10, and y < 0 evaluates to false, since 3 is not less than 0. The logic operator && evaluates to true when both conditions are true and evaluates to false otherwise. Since the second condition is false, the boolean expression is false. As a result, the compiler will skip the first output statement and execute the statement in the else. The expression x / y is integer division for 7 / 3, which is 2. | This was more of a conceptual error as I didn’t read the code segment thoroughly resulting in the wrong output being displayed when I looked at it. | . Question 11 . . Answer A Incorrect. This will prevent an ArrayIndexOutOfBoundsException from being thrown if target does not appear in data, however if target is at element 0, -1 will be returned instead of 0 as intended. | Answer B Correct. The seqSearchRecHelper recursive method does not work as intended when target does not appear in data. In this case, when last becomes -1, the method will throw an ArrayIndexOutOfBoundsException in the first if statement after line 1. To prevent this, we should add a check to see if last is less than 0 and if it is, return -1 as expected. | I did this wrong because if you look at the function, the main target wasn’t displaying the correct output. | . Question 18 . . Answer D Incorrect. The indices for myList are 0 through myList.size() – 1, for a total of myList.size() elements. Adding 1 to myList.size() and then multiplying Math.random() by this value results in a range that is from 0 to myList.size(), which is one element too many. | Answer B Correct. The indices for myList are 0 through myList.size() – 1, for a total of myList.size() elements. Using Math.random()generates a random floating point number between 0 and 1, not including 1. When this value is multiplied by the number of elements we want in our range, myList.size(), a random floating point number between 0 and myList.size(), not including myList.size(), is generated. When this value is typecast as an int, the result is an integer value between 0 and myList.size() – 1 inclusive. | In order to get this correct in the future, I plan on studying both topic 2.9 and 7.2 as they cover Arraylists. | . Question 23 . . Answer C Incorrect. List is an interface, which an ArrayList implements. Please note that List is no longer tested as part of the AP CSA exam and ArrayList will be used instead. This would be the correct answer if the remove occurred before the size was calculated in the statement animals.add(animals.size()-k, animals.remove(k)); and only one iteration of the loop occurred. | Answer B Correct. List is an interface, which an ArrayList implements. Please note that List is no longer tested as part of the AP CSA exam and ArrayList will be used instead. The manipulate method contains a for loop with a loop control variable k that starts at the right most index of animals, decrements by 1 each time, until k is equal to 0. In the first iteration, when k is 5, if the element of animals at 5 (“baboon”) starts with a “b”, which it does, then this value is removed from the list and inserted at index 1. The list would then be {“bear”, “baboon”, “zebra”, “bass”, “cat”, “koala”}. | To fix this I will focus on topics 2.7 and 7.4 as they cover instatizing and initializing lists. | . Question 24 . . Answer C Incorrect. The value 5 is at newArray[1][1]. | Answer D Correct. The enhanced for loop iterates over the array oldArray. In the first iteration, newArray[0][0] is assigned the value 1. The value of row is incremented to 1. Since 1 % 3 does not equal 0, the statements in the if are not executed. In the next iteration, newArray[1][0] is assigned the value 2. The value of row is incremented to 2. The algorithm continues to fill column 0 with the subsequent values of oldArray. Once row is 3, the if condition is true and row is assigned 0 and col is incremented to 1. The algorithm proceeds to fill column 1. | Resources: 8.1: Daily Video 1 (Skill 3.E), 8.1: Daily Video 2 (Skill 3.E), 8.1: Daily Video 3 (Skill 1.B) | . Question 34 . . Answer D Incorrect. Choice III uses the default Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error. | Answer B Correct. Choice I uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0, instead of x assigned the value a and y assigned the value b. Choice II correctly uses the two parameter Point constructor to create a new Point with x assigned the value a and y assigned the value b. Choice III uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error. | There is a compiling error that comes out of the answer in option D due to the way in which the constructor assigns a new point. | .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/markdown/2022/11/08/Test-Corrections.html",
@@ -155,7 +166,7 @@
- ,"post14": {
+ ,"post15": {
"title": "N@TM Blog",
"content": "| | | | After going to the N@TM event, there were many takeaways I had Firstly, many of the viewers(both parents and students) loved our interactive quiz due to the elaborate bank of questions we implemented and the styling on the page | We also received some feedback from peers to help us make our votes page look nicer, and also were given suggestions on what future pages we can implenet in our project from now on | Overall, I had a great time at the event and I hope to have a successful second trimester and become an overall better coder and student in AP CSA. | . | .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/markdown/2022/11/08/N@TM-Blog.html",
@@ -166,7 +177,7 @@
- ,"post15": {
+ ,"post16": {
"title": "Unit 7 2018 HW",
"content": "2. This question involves reasoning about pairs of words that are represented by the following . public class WordPair . { . /* Constructs a WordPair object. / . public WordPair(String first, String second) . { / implementation not shown / } . /* Returns the first string of this WordPair object. / . public String getFirst() . { / implementation not shown / } . /* Returns the second string of this WordPair object. / . public String getSecond() . { / implementation not shown / } . } . WordPair class. . 2. You will implement the constructor and another method for the following WordPairList class. . public class WordPairList . { . /* The list of word pairs, initialized by the constructor. / . private ArrayList allPairs;</p> /** Constructs a WordPairList object as described in part (a). . Precondition: words.length >= 2 . */ . public WordPairList(String[] words) . { / to be implemented in part (a) / } . /** Returns the number of matches as described in part (b). . */ . public int numMatches() . { / to be implemented in part (b) / } . } . </div> </div> </div> (a) Write the constructor for the WordPairList class. The constructor takes an array of strings words as . a parameter and initializes the instance variable allPairs to an ArrayList of WordPair objects. A WordPair object consists of a word from the array paired with a word that appears later in the array. The allPairs list contains WordPair objects (words[i], words[j]) for every i and j, where 0 £ i < j < words.length . Each WordPair object is added exactly once to the list. The following examples illustrate two different WordPairList objects. . . Complete the WordPairList constructor below. . /** Constructs a WordPairList object as described in part (a). . Precondition: words.length >= 2 */ public WordPairList(String[] words) | . public class WordPairList { public WordPairList(String[] words) { allPairs = new ArrayList<WordPair>(); for(int i = 0; i < words.length; i++) for(int j = i + 1; j < words.length; j++) allPairs.add(new WordPair(words[i], words[j])); } } . (2b) . Write the WordPairList method numMatches. This method returns the number of WordPair objects in allPairs for which the two strings match. For example, the following code segment creates a WordPairList object. . String[] moreWords = {"the", "red", "fox", "the", "red"}; . WordPairList exampleThree = new WordPairList(moreWords); . After the code segment has executed, the allPairs instance variable of exampleThree will contain the following WordPair objects in some order. The pairs in which the first string matches the second string are shaded for illustration. . ("the", "red"), ("the", "fox"), ("the", "the"), . ("the", "red"), ("red", "fox"), ("red", "the"), . ("red", "red"), ("fox", "the"), ("fox", "red"), . ("the", "red") . The call exampleThree.numMatches() should return 2. . . Complete method numMatches below. . /** Returns the number of matches as described in part (b). . */ . public int numMatches() . public int numMatches() { int matches = 0; for(WordPair wp : allPairs) if(wp.getFirst().equals(wp.getSecond())) matches++; return matches; } . </div> .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/homework/2022/10/27/Unit-7-HW.html",
@@ -177,7 +188,7 @@
- ,"post16": {
+ ,"post17": {
"title": "Unit 6 Homework",
"content": "Hack 1 . How do we access the even numbers in arrayOne from above? . import java.util.Arrays; int[] arrayOne = {1, 3, 5, 7, 9}; for (int i = 0; i<arrayOne.length;i++) { if (arrayOne[i] % 2 == 0) { System.out.println(arrayOne[i] + " "); } } . Hack 2 . Which of the following is FALSE about arrays . A. A java array is an object | B. Length of array can be changed after creation of array | C. Numerical data types of arrays are initialized to 0 to start | . B . APCSA 2021 Question 3 . A high school club maintains information about its members in a MemberInfo object. A MemberInfo object stores a club member’s name, year of graduation, and whether or not the club member is in good standing. A member who is in good standing has fulfilled all the responsibilities of club membership. . A partial declaration of the MemberInfo class is shown below. . public class MemberInfo { / Constructs a MemberInfo object for the club member with name name, graduation year gradYear, and standing hasGoodStanding. / public MemberInfo(String name, int gradYear, boolean hasGoodStanding) { / implementation not shown */ } / Returns the graduation year of the club member. / public int getGradYear() { / implementation not shown / } /** Returns true if the member is in good standing and false otherwise. / public boolean inGoodStanding() { / implementation not shown / } // There may be instance variables, constructors, and methods that are not shown. } | . | The ClubMembers class maintains a list of current club members. The declaration of the ClubMembers class is shown below. . public class ClubMembers { private ArrayList memberList; / Adds new club members to memberList, as described in part (a). Precondition: names is a non-empty array. / public void addMembers(String[] names, int gradYear) { / to be implemented in part (a) */ } / Removes members who have graduated and returns a list of members who have graduated and are in good standing, as described in part (b). / public ArrayList removeMembers(int year) { /</em> to be implemented in part (b) */ } // There may be instance variables, constructors, and methods that are not shown. } </li> </ul> </li> </ul> </div> </div> </div> (A) . Write the ClubMembers method addMembers, which takes two parameters. The first parameter is a String array containing the names of new club members to be added. The second parameter is the graduation year of all the new club members. The method adds the new members to the memberList instance variable. The names can be added in any order. All members added are initially in good standing and share the same graduation year, gradYear. . Complete the addMembers method. . /* Adds new club members to memberList, as described in part (a). Precondition: names is a non-empty array./ . public void addMembers(String[] names, int gradYear) . public void addMembers(String[] names, int gradYear) { for (String n : names) { MemberInfo newM = new MemberInfo (n, gradYear, true); memberList.add(newM); } } . </div> | . | .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/homework/2022/10/25/Unit-6-HW.html",
@@ -188,7 +199,7 @@
- ,"post17": {
+ ,"post18": {
"title": "Unit 5 2019 FRQ Q2",
"content": "2. . This question involves the implementation of a fitness tracking system that is represented by the StepTracker class. A StepTracker object is created with a parameter that defines the minimum number of steps that must be taken for a day to be considered active. The StepTracker class provides a constructor and the following methods. . addDailySteps, which accumulates information about steps, in readings taken once per day | activeDays, which returns the number of active days | averageSteps, which returns the average number of steps per day, calculated by dividing the total number of steps taken by the number of days tracked | . The following table contains a sample code execution sequence and the corresponding results. . . Write the complete StepTracker class, including the constructor and any required instance variables and methods. Your implementation must meet all specifications and conform to the example. . public class StepTracker { private final int minStepsActive; private int activeDays; private int days; private int totalSteps; public StepTracker(int minStepsActive) { this.minStepsActive = minStepsActive; activeDays = 0; days = 0; totalSteps = 0; } public void addDailySteps(int steps) { if(steps >= minStepsActive) activeDays++; days++; totalSteps += steps; } public int activeDays() { return activeDays; } public double averageSteps() { if(days == 0) return 0; return totalSteps / (double) days; } } .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/homework/2022/10/25/Unit-5-FRQ.html",
@@ -199,7 +210,7 @@
- ,"post18": {
+ ,"post19": {
"title": "Unit 4 Homework",
"content": "Reference Vocab list 3, for better understanding of strings | . // import required classes and package, if any import java.util.Scanner; // create class CaesarCipherExample for encryption and decryption public class CaesarCipherExample { // ALPHABET string denotes alphabet from a-z public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz"; // create encryptData() method for encrypting user input string with given shift key public static String encryptData(String inputStr, int shiftKey) { // convert inputStr into lower case inputStr = inputStr.toLowerCase(); // encryptStr to store encrypted data String encryptStr = ""; // use for loop for traversing each character of the input string for (int i = 0; i < inputStr.length(); i++) { // get position of each character of inputStr in ALPHABET int pos = ALPHABET.indexOf(inputStr.charAt(i)); // get encrypted char for each char of inputStr int encryptPos = (shiftKey + pos) % 26; char encryptChar = ALPHABET.charAt(encryptPos); // add encrypted char to encrypted string encryptStr += encryptChar; } // return encrypted string return encryptStr; } // create decryptData() method for decrypting user input string with given shift key public static String decryptData(String inputStr, int shiftKey) { // convert inputStr into lower case inputStr = inputStr.toLowerCase(); // decryptStr to store decrypted data String decryptStr = ""; // use for loop for traversing each character of the input string for (int i = 0; i < inputStr.length(); i++) { // get position of each character of inputStr in ALPHABET int pos = ALPHABET.indexOf(inputStr.charAt(i)); // get decrypted char for each char of inputStr int decryptPos = (pos - shiftKey) % 26; // if decryptPos is negative if (decryptPos < 0){ decryptPos = ALPHABET.length() + decryptPos; } char decryptChar = ALPHABET.charAt(decryptPos); // add decrypted char to decrypted string decryptStr += decryptChar; } // return decrypted string return decryptStr; } // main() method start public static void main(String[] args) { // create an instance of Scanner class Scanner sc = new Scanner(System.in); // take input from the user System.out.println("Enter a string for encryption using Caesar Cipher: "); String inputStr = sc.nextLine(); System.out.println("Enter the value by which each character in the plaintext message gets shifted: "); int shiftKey = Integer.valueOf(sc.nextLine()); System.out.println("Encrypted Data ===> "+encryptData(inputStr, shiftKey)); System.out.println("Decrypted Data ===> "+decryptData(encryptData(inputStr, shiftKey), shiftKey)); // close Scanner class object sc.close(); } } CaesarCipherExample.main(null) . Enter a string for encryption using Caesar Cipher: Enter the value by which each character in the plaintext message gets shifted: Encrypted Data ===> lipps Decrypted Data ===> hello .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/homework/2022/10/25/Unit-4-JavaExercises_copy.html",
@@ -210,7 +221,7 @@
- ,"post19": {
+ ,"post20": {
"title": "Unit 3 - Java Practice Programs",
"content": "1. Write a Java program to get a number from the user and print whether it is positive or negative. . import java.util.Scanner; public class Exercise1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input number: "); int input = in.nextInt(); if (input > 0) { System.out.println("Number is positive"); } else if (input < 0) { System.out.println("Number is negative"); } else { System.out.println("Number is zero"); } } } Exercise1.main(null); . Input number: . java.util.InputMismatchException: null at java.base/java.util.Scanner.throwFor(Scanner.java:943) at java.base/java.util.Scanner.next(Scanner.java:1598) at java.base/java.util.Scanner.nextInt(Scanner.java:2263) at java.base/java.util.Scanner.nextInt(Scanner.java:2217) at Exercise1.main(#13:1) at .(#40:1) . 2. Write a Java program to solve quadratic equations (use if, else if and else). . import java.util.Scanner; public class Exercise2 { public static void main(String[] Strings) { Scanner input = new Scanner(System.in); System.out.print("Input a: "); double a = input.nextDouble(); System.out.print("Input b: "); double b = input.nextDouble(); System.out.print("Input c: "); double c = input.nextDouble(); double result = b * b - 4.0 * a * c; if (result > 0.0) { double r1 = (-b + Math.pow(result, 0.5)) / (2.0 * a); double r2 = (-b - Math.pow(result, 0.5)) / (2.0 * a); System.out.println("The roots are " + r1 + " and " + r2); } else if (result == 0.0) { double r1 = -b / (2.0 * a); System.out.println("The root is " + r1); } else { System.out.println("The equation has no real roots."); } } } Exercise2.main(null); . Input a: Input b: Input c: The equation has no real roots. . 3. Take three numbers from the user and print the greatest number. . Reference Vocab List 2, to get a better understanding of comparing objects, numbers, and strings | . import java.util.Scanner; public class Exercise3 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input the 1st number: "); int num1 = in.nextInt(); System.out.print("Input the 2nd number: "); int num2 = in.nextInt(); System.out.print("Input the 3rd number: "); int num3 = in.nextInt(); if (num1 > num2) if (num1 > num3) System.out.println("The greatest: " + num1); if (num2 > num1) if (num2 > num3) System.out.println("The greatest: " + num2); if (num3 > num1) if (num3 > num2) System.out.println("The greatest: " + num3); } } Exercise3.main(null); . Input the 1st number: Input the 2nd number: Input the 3rd number: The greatest: 3 . 4.Write a Java program that reads a floating-point number and prints "zero" if the number is zero. Otherwise, print "positive" or "negative". Add "small" if the absolute value of the number is less than 1, or "large" if it exceeds 1,000,000. . import java.util.Scanner; public class Exercise4 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input value: "); double input = in.nextDouble(); if (input > 0) { if (input < 1) { System.out.println("Positive small number"); } else if (input > 1000000) { System.out.println("Positive large number"); } else { System.out.println("Positive number"); } } else if (input < 0) { if (Math.abs(input) < 1) { System.out.println("Negative small number"); } else if (Math.abs(input) > 1000000) { System.out.println("Negative large number"); } else { System.out.println("Negative number"); } } else { System.out.println("Zero"); } } } Exercise4.main(null); . Input value: Positive number . 5. Write a Java program that keeps a number from the user and generates an integer between 1 and 7 and displays the name of the weekday. . import java.util.Scanner; public class Exercise5 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input number: "); int day = in.nextInt(); System.out.println(getDayName(day)); } // Get the name for the Week public static String getDayName(int day) { String dayName = ""; switch (day) { case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; case 4: dayName = "Thursday"; break; case 5: dayName = "Friday"; break; case 6: dayName = "Saturday"; break; case 7: dayName = "Sunday"; break; default:dayName = "Invalid day range"; } return dayName; } } Exercise5.main(null); . Input number: Saturday . 6. Write a Java program that reads in two floating-point numbers and tests whether they are the same up to three decimal places. . import java.util.Scanner; public class Exercise6 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input floating-point number: "); double x = in.nextDouble(); System.out.print("Input floating-point another number: "); double y = in.nextDouble(); x = Math.round(x * 1000); x = x / 1000; y = Math.round(y * 1000); y = y / 1000; if (x == y) { System.out.println("They are the same up to three decimal places"); } else { System.out.println("They are different"); } } } Exercise6.main(null); . Input floating-point number: Input floating-point another number: They are different . 7. Write a Java program to find the number of days in a month. . import java.util.Scanner; public class Exercise7 { public static void main(String[] strings) { Scanner input = new Scanner(System.in); int number_Of_DaysInMonth = 0; String MonthOfName = "Unknown"; System.out.print("Input a month number: "); int month = input.nextInt(); System.out.print("Input a year: "); int year = input.nextInt(); switch (month) { case 1: MonthOfName = "January"; number_Of_DaysInMonth = 31; break; case 2: MonthOfName = "February"; if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) { number_Of_DaysInMonth = 29; } else { number_Of_DaysInMonth = 28; } break; case 3: MonthOfName = "March"; number_Of_DaysInMonth = 31; break; case 4: MonthOfName = "April"; number_Of_DaysInMonth = 30; break; case 5: MonthOfName = "May"; number_Of_DaysInMonth = 31; break; case 6: MonthOfName = "June"; number_Of_DaysInMonth = 30; break; case 7: MonthOfName = "July"; number_Of_DaysInMonth = 31; break; case 8: MonthOfName = "August"; number_Of_DaysInMonth = 31; break; case 9: MonthOfName = "September"; number_Of_DaysInMonth = 30; break; case 10: MonthOfName = "October"; number_Of_DaysInMonth = 31; break; case 11: MonthOfName = "November"; number_Of_DaysInMonth = 30; break; case 12: MonthOfName = "December"; number_Of_DaysInMonth = 31; } System.out.print(MonthOfName + " " + year + " has " + number_Of_DaysInMonth + " days n"); } } Exercise7.main(null); . Input a month number: Input a year: August 2005 has 31 days . 8. Write a Java program that takes the user to provide a single character from the alphabet. Print Vowel or Consonant, depending on the user input. If the user input is not a letter (between a and z or A and Z), or is a string of length > 1, print an error message. . import java.util.Scanner; public class Exercise8 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input an alphabet: "); String input = in.next().toLowerCase(); boolean uppercase = input.charAt(0) >= 65 && input.charAt(0) <= 90; boolean lowercase = input.charAt(0) >= 97 && input.charAt(0) <= 122; boolean vowels = input.equals("a") || input.equals("e") || input.equals("i") || input.equals("o") || input.equals("u"); if (input.length() > 1) { System.out.println("Error. Not a single character."); } else if (!(uppercase || lowercase)) { System.out.println("Error. Not a letter. Enter uppercase or lowercase letter."); } else if (vowels) { System.out.println("Input letter is Vowel"); } else { System.out.println("Input letter is Consonant"); } } } Exercise8.main(null); . Input an alphabet: Input letter is Vowel . 9. Write a Java program that takes a year from user and print whether that year is a leap year or not. . import java.util.Scanner; public class Exercise9 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input the year: "); int year = in.nextInt(); boolean x = (year % 4) == 0; boolean y = (year % 100) != 0; boolean z = ((year % 100 == 0) && (year % 400 == 0)); if (x && (y || z)) { System.out.println(year + " is a leap year"); } else { System.out.println(year + " is not a leap year"); } } } Exercise9.main(null); . Input the year: 2022 is not a leap year . 10. Write a program in Java to display the first 10 natural numbers. . public class Exercise10 { public static void main(String[] args) { int i; System.out.println ("The first 10 natural numbers are: n"); for (i=1;i<=10;i++) { System.out.println (i); } System.out.println (" n"); } } Exercise10.main(null); . The first 10 natural numbers are: 1 2 3 4 5 6 7 8 9 10 . 11. Write a program in Java to display n terms of natural numbers and their sum. . import java.util.Scanner; public class Exercise11 { public static void main(String[] args) { int i, n, sum=0; { Scanner in = new Scanner(System.in); System.out.print("Input number: "); n = in.nextInt(); } System.out.println("The first n natural numbers are : "+n); for(i=1;i<=n;i++) { System.out.println(i); sum+=i; } System.out.println("The Sum of Natural Number upto "+n+ " terms : " +sum); } } Exercise11.main(null); . Input number: The first n natural numbers are : 4 1 2 3 4 The Sum of Natural Number upto 4 terms : 10 . 12. Write a program in Java to input 5 numbers from keyboard and find their sum and average . import java.util.Scanner; public class Exercise12 { public static void main(String[] args) { int i,n=0,s=0; double avg; { System.out.println("Input the 5 numbers : "); } for (i=0;i<5;i++) { Scanner in = new Scanner(System.in); n = in.nextInt(); s +=n; } avg=s/5; System.out.println("The sum of 5 no is : " +s+" nThe Average is : " +avg); } } Exercise12.main(null); . Input the 5 numbers : The sum of 5 no is : 15 The Average is : 3.0 . 13. Write a program in Java to display the cube of the number upto given an integer. . import java.util.Scanner; public class Exercise13 { public static void main(String[] args) { int i,n; System.out.print("Input number of terms : "); Scanner in = new Scanner(System.in); n = in.nextInt(); for(i=1;i<=n;i++) { System.out.println("Number is : " +i+" and cube of " +i+" is : "+(i*i*i)); } } } Exercise13.main(null); . Input number of terms : Number is : 1 and cube of 1 is : 1 Number is : 2 and cube of 2 is : 8 Number is : 3 and cube of 3 is : 27 Number is : 4 and cube of 4 is : 64 Number is : 5 and cube of 5 is : 125 . 14. Write a program in Java to display the multiplication table of a given integer. . import java.util.Scanner; public class Exercise14 { public static void main(String[] args) { int j,n; System.out.print("Input the number(Table to be calculated): "); { System.out.print("Input number of terms : "); Scanner in = new Scanner(System.in); n = in.nextInt(); System.out.println (" n"); for(j=0;j<=n;j++) System.out.println(n+" X "+j+" = " +n*j); } } } Exercise14.main(null); . 15. Write a program in Java to display the n terms of odd natural number and their sum. . import java.util.Scanner; public class Exercise15 { public static void main(String[] args) { int i,n,sum=0; System.out.print("Input number of terms is: "); { Scanner in = new Scanner(System.in); n = in.nextInt(); System.out.println (" nThe odd numbers are :"); for(i=1;i<=n;i++) { System.out.println (2*i-1); sum+=2*i-1; } System.out.println ("The Sum of odd Natural Number upto " +n+" terms is: " +sum); } } } Exercise15.main(null); . 16. Write a program in Java to display the pattern like right angle triangle with a number. . import java.util.Scanner; public class Exercise16 { public static void main(String[] args) { int i,j,n; System.out.print("Input number of rows : "); Scanner in = new Scanner(System.in); n = in.nextInt(); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) System.out.print(j); System.out.println(""); } } } Exercise16.main(null); . 17. Write a program in Java to make such a pattern like right angle triangle with a number which will repeat a number in a row.The pattern is as follows : . import java.util.Scanner; public class Exercise17 { public static void main(String[] args) { int i,j,n; System.out.print("Input number of n : "); Scanner in = new Scanner(System.in); n = in.nextInt(); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) System.out.print(i); System.out.println(""); } } } Exercise17.main(null); . 18. Write a program in Java to make such a pattern like right angle triangle with number increased by 1.The pattern like : . import java.util.Scanner; public class Exercise18 { public static void main(String[] args) { int i,j,n,k=1; System.out.print("Input number of rows : "); Scanner in = new Scanner(System.in); n = in.nextInt(); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) System.out.print(k++); System.out.println(""); } } } Exercise18.main(null); . 19. Write a program in Java to make such a pattern like a pyramid with a number which will repeat the number in the same row. . import java.util.Scanner; public class Exercise19 { public static void main(String[] args) { int i,j,n,s,x; System.out.print ("Input number of rows : "); Scanner in = new Scanner(System.in); n = in.nextInt(); s=n+4-1; for(i=1;i<=n;i++) { for(x=s;x!=0;x--) { System.out.print(" "); } for(j=1;j<=i;j++) { System.out.print(i+" "); } System.out.println(); s--; } } } Exercise19.main(null); . 20. Write a program in Java to print the Floyd's Triangle. . import java.util.Scanner; public class Main { public static void main(String[] args) { int numberOfRows; System.out.print("Input number of rows : "); Scanner in = new Scanner(System.in); numberOfRows = in.nextInt(); int number = 1; for (int row = 1; row <= numberOfRows; row++) { for (int column = 1; column <= row; column++) { System.out.print(number + " "); number++; } System.out.println(); } } } Main.main(null); .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/10/25/Unit-3-JavaExercises-(1).html",
@@ -221,7 +232,7 @@
- ,"post20": {
+ ,"post21": {
"title": "Unit 3 - FRQ Practice Question 1",
"content": "1. The APCalendar class contains methods used to calculate information about a calendar. You will write two methods of the class. . public class APCalendar { / Returns true if year is a leap year and false otherwise. / private static boolean isLeapYear(int year) { / implementation not shown */ } / Returns the number of leap years between year1 and year2, inclusive. . Precondition: 0 <= year1 <= year2 / public static int numberOfLeapYears(int year1, int year2) { / to be implemented in part (a) */ } /** Returns the value representing the day of the week for the first day of year, | where 0 denotes Sunday, 1 denotes Monday, ..., and 6 denotes Saturday. / private static int firstDayOfYear(int year) { / implementation not shown */ } /** Returns n, where month, day, and year specify the nth day of the year. | Returns 1 for January 1 (month = 1, day = 1) of any year. | Precondition: The date represented by month, day, year is a valid date. / private static int dayOfYear(int month, int day, int year) { / implementation not shown */ } /** Returns the value representing the day of the week for the given date | (month, day, year), where 0 denotes Sunday, 1 denotes Monday, ..., | and 6 denotes Saturday. | Precondition: The date represented by month, day, year is a valid date. / public static int dayOfWeek(int month, int day, int year) { / to be implemented in part (b) */ } // There may be instance variables, constructors, and other methods not shown. } | . 1(a) . Write the static method numberOfLeapYears, which returns the number of leap years between year1 and year2 inclusive. In order to calculate this value, a helper method is provided for you. . isLeapYear(year) returns true if year is a leap year and false otherwise. | . Complete method numberOfLeapYears below. You must use isLeapYear appropriately to receive full credit. /** Returns the number of leap years between year1 and year2, inclusive. . Precondition: 0 <= year1 <= year2 */ public static int numberOfLeapYears(int year1, int year2) | . public static int numberOfLeapYears(int year1, int year2) { int leapYears = 0; for(int y = year1; y <= year2; y++) if(isLeapYear(y)) leapYears++; return leapYears; } . 1. . Write the static method dayOfWeek, which returns the integer value representing the day of the week for the given date (month, day, year), where 0 denotes Sunday, 1 denotes Monday, ..., and 6 denotes Saturday. For example, 2019 began on a Tuesday, and January 5 is the fifth day of 2019. As a result, January 5, 2019, fell on a Saturday, and the method call dayOfWeek(1, 5, 2019) returns 6. . As another example, January 10 is the tenth day of 2019. As a result, January 10, 2019, fell on a Thursday, and the method call dayOfWeek(1, 10, 2019) returns 4. . In order to calculate this value, two helper methods are provided for you. . firstDayOfYear(year) returns the integer value representing the day of the week for the first day of year, where 0 denotes Sunday, 1 denotes Monday, ..., and 6 denotes Saturday. For example, since 2019 began on a Tuesday, firstDayOfYear(2019) returns 2. | dayOfYear(month, day, year) returns n, where month, day, and year specify the nth day of the year. For the first day of the year, January 1 (month = 1, day = 1), the value 1 is returned. This method accounts for whether year is a leap year. For example, dayOfYear(3, 1, 2017) returns 60, since 2017 is not a leap year, while dayOfYear(3, 1, 2016) returns 61, since 2016 is a leap year. | . Class information for this question . public class APCalendar | private static boolean isLeapYear(int year) | public static int numberOfLeapYears(int year1, int year2) | private static int firstDayOfYear(int year) | private static int dayOfYear(int month, int day, int year) | public static int dayOfWeek(int month, int day, int year) | . 1(b) . Complete method dayOfWeek below. You must use firstDayOfYear and dayOfYear appropriately to receive full credit. . /** Returns the value representing the day of the week for the given date . (month, day, year), where 0 denotes Sunday, 1 denotes Monday, ..., | and 6 denotes Saturday. | Precondition: The date represented by month, day, year is a valid date. | . public static int dayOfWeek(int month, int day, int year) . public static int dayOfWeek(int month, int day, int year) { int weekday = firstDayOfYear(year); int additionalDays = dayOfYear(month, day, year) - 1; for(int d = 1; d <= additionalDays; d++) { weekday++; if(weekday == 7) weekday = 0; } return weekday; } . A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times. | A for loop is useful when you know how many times a task is to be repeated. | .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/10/25/Unit-3-2019FRQ.html",
@@ -232,7 +243,7 @@
- ,"post21": {
+ ,"post22": {
"title": "Pranav Java API",
"content": "%%loadFromPOM <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20190722</version> </dependency> . import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.Scanner; public class NBA { public static void main(String[] args) throws IOException, InterruptedException { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://free-nba.p.rapidapi.com/players?page=0&per_page=25")) .header("X-RapidAPI-Key", "a52c00a742mshc6c13b49056f1c7p11b54cjsnc5e7c51a6001") .header("X-RapidAPI-Host", "free-nba.p.rapidapi.com") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } } NBA.main(null); . {"data":[{"id":14,"first_name":"Ike","height_feet":null,"height_inches":null,"last_name":"Anigbogu","position":"C","team":{"id":12,"abbreviation":"IND","city":"Indiana","conference":"East","division":"Central","full_name":"Indiana Pacers","name":"Pacers"},"weight_pounds":null},{"id":25,"first_name":"Ron","height_feet":null,"height_inches":null,"last_name":"Baker","position":"G","team":{"id":20,"abbreviation":"NYK","city":"New York","conference":"East","division":"Atlantic","full_name":"New York Knicks","name":"Knicks"},"weight_pounds":null},{"id":47,"first_name":"Jabari","height_feet":null,"height_inches":null,"last_name":"Bird","position":"G","team":{"id":2,"abbreviation":"BOS","city":"Boston","conference":"East","division":"Atlantic","full_name":"Boston Celtics","name":"Celtics"},"weight_pounds":null},{"id":67,"first_name":"MarShon","height_feet":null,"height_inches":null,"last_name":"Brooks","position":"G","team":{"id":15,"abbreviation":"MEM","city":"Memphis","conference":"West","division":"Southwest","full_name":"Memphis Grizzlies","name":"Grizzlies"},"weight_pounds":null},{"id":71,"first_name":"Lorenzo","height_feet":null,"height_inches":null,"last_name":"Brown","position":"G","team":{"id":28,"abbreviation":"TOR","city":"Toronto","conference":"East","division":"Atlantic","full_name":"Toronto Raptors","name":"Raptors"},"weight_pounds":null},{"id":90,"first_name":"Omri","height_feet":null,"height_inches":null,"last_name":"Casspi","position":"F","team":{"id":15,"abbreviation":"MEM","city":"Memphis","conference":"West","division":"Southwest","full_name":"Memphis Grizzlies","name":"Grizzlies"},"weight_pounds":null},{"id":1,"first_name":"Alex","height_feet":6,"height_inches":6,"last_name":"Abrines","position":"G","team":{"id":21,"abbreviation":"OKC","city":"Oklahoma City","conference":"West","division":"Northwest","full_name":"Oklahoma City Thunder","name":"Thunder"},"weight_pounds":200},{"id":119,"first_name":"Tyler","height_feet":null,"height_inches":null,"last_name":"Davis","position":"C","team":{"id":21,"abbreviation":"OKC","city":"Oklahoma City","conference":"West","division":"Northwest","full_name":"Oklahoma City Thunder","name":"Thunder"},"weight_pounds":null},{"id":149,"first_name":"Keenan","height_feet":null,"height_inches":null,"last_name":"Evans","position":"G","team":{"id":9,"abbreviation":"DET","city":"Detroit","conference":"East","division":"Central","full_name":"Detroit Pistons","name":"Pistons"},"weight_pounds":null},{"id":179,"first_name":"Marcin","height_feet":null,"height_inches":null,"last_name":"Gortat","position":"C","team":{"id":13,"abbreviation":"LAC","city":"LA","conference":"West","division":"Pacific","full_name":"LA Clippers","name":"Clippers"},"weight_pounds":null},{"id":1593,"first_name":"Andrew","height_feet":null,"height_inches":null,"last_name":"Bogut","position":"F","team":{"id":10,"abbreviation":"GSW","city":"Golden State","conference":"West","division":"Pacific","full_name":"Golden State Warriors","name":"Warriors"},"weight_pounds":null},{"id":241,"first_name":"Amir","height_feet":6,"height_inches":9,"last_name":"Johnson","position":"C-F","team":{"id":23,"abbreviation":"PHI","city":"Philadelphia","conference":"East","division":"Atlantic","full_name":"Philadelphia 76ers","name":"76ers"},"weight_pounds":240},{"id":392,"first_name":"Malachi","height_feet":null,"height_inches":null,"last_name":"Richardson","position":"G","team":{"id":29,"abbreviation":"UTA","city":"Utah","conference":"West","division":"Northwest","full_name":"Utah Jazz","name":"Jazz"},"weight_pounds":null},{"id":281,"first_name":"Zach","height_feet":null,"height_inches":null,"last_name":"Lofton","position":"G","team":{"id":9,"abbreviation":"DET","city":"Detroit","conference":"East","division":"Central","full_name":"Detroit Pistons","name":"Pistons"},"weight_pounds":null},{"id":263,"first_name":"Kosta","height_feet":7,"height_inches":0,"last_name":"Koufos","position":"C","team":{"id":26,"abbreviation":"SAC","city":"Sacramento","conference":"West","division":"Pacific","full_name":"Sacramento Kings","name":"Kings"},"weight_pounds":245},{"id":382,"first_name":"Billy","height_feet":null,"height_inches":null,"last_name":"Preston","position":"F","team":{"id":6,"abbreviation":"CLE","city":"Cleveland","conference":"East","division":"Central","full_name":"Cleveland Cavaliers","name":"Cavaliers"},"weight_pounds":null},{"id":384,"first_name":"Zhou","height_feet":null,"height_inches":null,"last_name":"Qi","position":"F-C","team":{"id":11,"abbreviation":"HOU","city":"Houston","conference":"West","division":"Southwest","full_name":"Houston Rockets","name":"Rockets"},"weight_pounds":null},{"id":388,"first_name":"Zach","height_feet":null,"height_inches":null,"last_name":"Randolph","position":"F","team":{"id":26,"abbreviation":"SAC","city":"Sacramento","conference":"West","division":"Pacific","full_name":"Sacramento Kings","name":"Kings"},"weight_pounds":null},{"id":430,"first_name":"DJ","height_feet":null,"height_inches":null,"last_name":"Stephens","position":"G-F","team":{"id":15,"abbreviation":"MEM","city":"Memphis","conference":"West","division":"Southwest","full_name":"Memphis Grizzlies","name":"Grizzlies"},"weight_pounds":null},{"id":437,"first_name":"Milos","height_feet":null,"height_inches":null,"last_name":"Teodosic","position":"G","team":{"id":13,"abbreviation":"LAC","city":"LA","conference":"West","division":"Pacific","full_name":"LA Clippers","name":"Clippers"},"weight_pounds":null},{"id":448,"first_name":"Gary","height_feet":null,"height_inches":null,"last_name":"Trent Jr.","position":"G","team":{"id":25,"abbreviation":"POR","city":"Portland","conference":"West","division":"Northwest","full_name":"Portland Trail Blazers","name":"Trail Blazers"},"weight_pounds":null},{"id":494,"first_name":"Michael","height_feet":null,"height_inches":null,"last_name":"Smith","position":"","team":{"id":2,"abbreviation":"BOS","city":"Boston","conference":"East","division":"Atlantic","full_name":"Boston Celtics","name":"Celtics"},"weight_pounds":null},{"id":495,"first_name":"John","height_feet":null,"height_inches":null,"last_name":"Morton","position":"","team":{"id":6,"abbreviation":"CLE","city":"Cleveland","conference":"East","division":"Central","full_name":"Cleveland Cavaliers","name":"Cavaliers"},"weight_pounds":null},{"id":496,"first_name":"Howard","height_feet":null,"height_inches":null,"last_name":"Wright","position":"","team":{"id":1,"abbreviation":"ATL","city":"Atlanta","conference":"East","division":"Southeast","full_name":"Atlanta Hawks","name":"Hawks"},"weight_pounds":null},{"id":497,"first_name":"Michael","height_feet":null,"height_inches":null,"last_name":"Ansley","position":"","team":{"id":22,"abbreviation":"ORL","city":"Orlando","conference":"East","division":"Southeast","full_name":"Orlando Magic","name":"Magic"},"weight_pounds":null}],"meta":{"total_pages":151,"current_page":1,"next_page":2,"per_page":25,"total_count":3757}} .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/10/02/javaapi.html",
@@ -243,7 +254,7 @@
- ,"post22": {
+ ,"post23": {
"title": "Arrays and Images",
"content": "import javax.imageio.ImageIO; import java.io.File; import java.io.IOException; import java.awt.image.BufferedImage; public class ImageIOTest { public static void main( String[] args ){ BufferedImage img = null; // buffer type try { // Name of file and directories String name = "MonaLisa"; String in = "images/"; String out = "images/tmp/"; // Either use URL or File for reading image using ImageIO File imageFile = new File(in + name + ".png"); img = ImageIO.read(imageFile); // set buffer of image data // ImageIO Image write to gif in Java // Documentation https://docs.oracle.com/javase/tutorial/2d/images/index.html ImageIO.write(img, "gif", new File(out + name + ".gif") ); // write buffer to gif } catch (IOException e) { e.printStackTrace(); } System.out.println("Success"); } } ImageIOTest.main(null); . import java.awt.Color; import java.awt.image.BufferedImage; import java.awt.Image; import java.awt.Graphics2D; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.imageio.stream.ImageOutputStream; import javax.imageio.stream.ImageInputStream; import javax.imageio.metadata.IIOMetadata; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.ImageReader; import javax.imageio.ImageTypeSpecifier; public class Pics { private final String inDir = "images/"; // location of images private final String outDir = "images/tmp/"; // location of created files private final String greyDir = "images/tmp/greyscale/"; private final String redDir = "images/tmp/red/"; private final String blueDir = "images/tmp/blue/"; private final String greenDir = "images/tmp/green/"; private String inFile; private String resizedFile; private String redFile; private String greenFile; private String blueFile; private String greyscaleFile; private String asciiFile; private String ext; // extension of file private long bytes; private int width; private int height; // Constructor obtains attributes of picture public Pics(String name, String ext) { this.ext = ext; this.inFile = this.inDir + name + "." + ext; this.resizedFile = this.outDir + name + "." + ext; this.greyscaleFile = this.greyDir + name + "_grey" + "." + ext; this.redFile = this.redDir + name + "_red" + "." + ext; this.blueFile = this.blueDir + name + "_blue" + "." + ext; this.greenFile = this.greenDir + name + "_green" + "." + ext; this.asciiFile = this.outDir + name + ".txt"; this.setStats(); } // An image contains metadata, namely size, width, and height public void setStats() { BufferedImage img; try { Path path = Paths.get(this.inFile); this.bytes = Files.size(path); img = ImageIO.read(new File(this.inFile)); this.width = img.getWidth(); this.height = img.getHeight(); } catch (IOException e) { } } // Console print of data public void printStats(String msg) { System.out.println(msg + ": " + this.bytes + " " + this.width + "x" + this.height + " " + this.inFile); } // Convert scaled image into buffered image public static BufferedImage convertToBufferedImage(Image img) { // Create a buffered image with transparency BufferedImage bi = new BufferedImage( img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); // magic? Graphics2D graphics2D = bi.createGraphics(); graphics2D.drawImage(img, 0, 0, null); graphics2D.dispose(); return bi; } // Scale or reduce to "scale" percentage provided public void resize(int scale) { BufferedImage img = null; Image resizedImg = null; int width = (int) (this.width * (scale/100.0) + 0.5); int height = (int) (this.height * (scale/100.0) + 0.5); try { // read an image to BufferedImage for processing img = ImageIO.read(new File(this.inFile)); // set buffer of image data // create a new BufferedImage for drawing resizedImg = img.getScaledInstance(width, height, Image.SCALE_SMOOTH); } catch (IOException e) { return; } try { ImageIO.write(convertToBufferedImage(resizedImg), this.ext, new File(resizedFile)); } catch (IOException e) { return; } this.inFile = this.resizedFile; // use scaled file vs original file in Class this.setStats(); } public void greyscale() { BufferedImage img = null; BufferedImage greyImg = null; try { // read an image to BufferedImage for processing img = ImageIO.read(new File(this.inFile)); // set buffer of image data greyImg = img; // create a new BufferedImage for drawing for (int i = 0; i < img.getHeight(); i++) { for (int j = 0; j < img.getWidth(); j++) { Color co = new Color(img.getRGB(j, i)); int red = (int) (co.getRed() * 0.299); int green = (int) (co.getGreen() * 0.587); int blue = (int) (co.getBlue() * 0.114); int total = red + green + blue; Color newColor = new Color( total, total, total ); greyImg.setRGB(j, i, newColor.getRGB()); } } } catch (IOException e) { return; } try { ImageIO.write(convertToBufferedImage(greyImg), this.ext, new File(greyscaleFile)); } catch (IOException e) { return; } this.inFile = this.greyscaleFile; // use scaled file vs original file in Class this.setStats(); } public void redscale() { BufferedImage img = null; BufferedImage redImg = null; try { // read an image to BufferedImage for processing img = ImageIO.read(new File(this.inFile)); // set buffer of image data redImg = img; // create a new BufferedImage for drawing for (int i = 0; i < img.getHeight(); i++) { for (int j = 0; j < img.getWidth(); j++) { Color co = new Color(img.getRGB(j, i)); int red = (int) co.getRed(); int green = 0; int blue = 0; Color newColor = new Color( red, green, blue); redImg.setRGB(j, i, newColor.getRGB()); } } } catch (IOException e) { return; } try { ImageIO.write(convertToBufferedImage(redImg), this.ext, new File(redFile)); } catch (IOException e) { return; } this.inFile = this.redFile; // use scaled file vs original file in Class this.setStats(); } public void greenscale() { BufferedImage img = null; BufferedImage greenImg = null; try { // read an image to BufferedImage for processing img = ImageIO.read(new File(this.inFile)); // set buffer of image data greenImg = img; // create a new BufferedImage for drawing for (int i = 0; i < img.getHeight(); i++) { for (int j = 0; j < img.getWidth(); j++) { Color co = new Color(img.getRGB(j, i)); int red = 0; int green = (int) co.getGreen(); int blue = 0; Color newColor = new Color( red, green, blue); greenImg.setRGB(j, i, newColor.getRGB()); } } } catch (IOException e) { return; } try { ImageIO.write(convertToBufferedImage(greenImg), this.ext, new File(greenFile)); } catch (IOException e) { return; } this.inFile = this.greenFile; // use scaled file vs original file in Class this.setStats(); } public void bluescale() { BufferedImage img = null; BufferedImage blueImg = null; try { // read an image to BufferedImage for processing img = ImageIO.read(new File(this.inFile)); // set buffer of image data blueImg = img; // create a new BufferedImage for drawing for (int i = 0; i < img.getHeight(); i++) { for (int j = 0; j < img.getWidth(); j++) { Color co = new Color(img.getRGB(j, i)); int red = (int) (co.getRed() * 0.299); int green = (int) (co.getGreen() * 0.587); int blue = (int) (co.getBlue() * 0.114); int total = red + green + blue; Color newColor = new Color(0, 0, total); blueImg.setRGB(j, i, newColor.getRGB()); } } } catch (IOException e) { return; } try { ImageIO.write(convertToBufferedImage(blueImg), this.ext, new File(blueFile)); } catch (IOException e) { return; } this.inFile = this.blueFile; // use scaled file vs original file in Class this.setStats(); } // convert every pixel to an ascii character (ratio does not seem correct) public void convertToAscii() { BufferedImage img = null; PrintWriter asciiPrt = null; FileWriter asciiWrt = null; try { File file = new File(this.asciiFile); Files.deleteIfExists(file.toPath()); } catch (IOException e) { System.out.println("Delete File error: " + e); } try { asciiPrt = new PrintWriter(asciiWrt = new FileWriter(this.asciiFile, true)); } catch (IOException e) { System.out.println("ASCII out file create error: " + e); } try { img = ImageIO.read(new File(this.inFile)); } catch (IOException e) { } for (int i = 0; i < img.getHeight(); i++) { if (i % 2 != 0) { for (int j = 0; j < img.getWidth(); j++) { Color col = new Color(img.getRGB(j, i)); double pixVal = (((col.getRed() * 0.30) + (col.getBlue() * 0.59) + (col .getGreen() * 0.11))); try { asciiPrt.print(asciiChar(pixVal)); asciiPrt.print(asciiChar(pixVal)); asciiPrt.flush(); asciiWrt.flush(); } catch (Exception ex) { } } try { asciiPrt.println(""); asciiPrt.flush(); asciiWrt.flush(); } catch (Exception ex) { } } } } // conversion table, there may be better out there ie https://www.billmongan.com/Ursinus-CS173-Fall2020/Labs/ASCIIArt public String asciiChar(double g) { String str = " "; if (g >= 240) { str = " "; } else if (g >= 210) { str = "."; } else if (g >= 190) { str = "*"; } else if (g >= 170) { str = "+"; } else if (g >= 120) { str = "^"; } else if (g >= 110) { str = "&"; } else if (g >= 80) { str = "8"; } else if (g >= 60) { str = "#"; } else { str = "@"; } return str; } // tester/driver public static void main(String[] args) throws IOException { Pics giannis = new Pics("giannis", "png"); //giannis.greyscale(); //giannis.redscale(); //giannis.greenscale(); //giannis.bluescale(); giannis.printStats("Original"); giannis.resize(33); giannis.printStats("Scaled"); giannis.convertToAscii(); } } Pics.main(null); . Original: 1138463 1200x675 images/giannis.png Scaled: 195187 396x223 images/tmp/giannis.png .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/10/02/Arrays-Images.html",
@@ -254,7 +265,7 @@
- ,"post23": {
+ ,"post24": {
"title": "Fibonacci",
"content": "// Mort's Code for Fibonacci Class import java.util.ArrayList; import java.util.HashMap; import java.util.stream.Stream; /* Objective will require changing to abstract class with one or more abstract methods below */ public class Fibo { String name; // name or title of method int size; // nth sequence int hashID; // counter for hashIDs in hash map ArrayList<Long> list; // captures current Fibonacci sequence HashMap<Integer, Object> hash; // captures each sequence leading to final result /* Zero parameter constructor uses Telescoping technique to allow setting of the required value nth @param: none */ public Fibo() { this(10); // telescope to avoid code duplication, using default as 20 } /* Construct the nth fibonacci number @param: nth number, the value is constrained to 92 because of overflow in a long */ public Fibo(int nth) { this.size = nth; this.list = new ArrayList<>(); this.hashID = 0; this.hash = new HashMap<>(); //initialize fibonacci and time mvc this.init(); } /* This Method should be "abstract" Leave method as protected, as it is only authorized to extender of the class Make new class that extends and defines init() Inside references within this class would change from this to super Repeat process using for, while, recursion */ protected void init() { this.name = "Stream"; Stream.iterate(new long[]{0, 1}, f -> new long[]{f[1], f[0] + f[1]}) .limit(this.size) .forEach(f -> this.setData(f[0]) ); } /* Number is added to fibonacci sequence, current state of "list" is added to hash for hashID "num" */ public void setData(long num) { list.add(num); hash.put(this.hashID++, list.clone()); } /* Custom Getter to return last element in fibonacci sequence */ public long getNth() { return list.get(this.size - 1); } /* Custom Getter to return last fibonacci sequence in HashMap */ public Object getNthSeq(int i) { return hash.get(i); } /* Console/Terminal supported print method */ public void print() { System.out.println("Init method = " + this.name); System.out.println("fibonacci Number " + this.size + " = " + this.getNth()); System.out.println("fibonacci List = " + this.list); System.out.println("fibonacci Hashmap = " + this.hash); for (int i=0 ; i<this.size; i++ ) { System.out.println("fibonacci Sequence " + (i+1) + " = " + this.getNthSeq(i)); } } /* Tester class method. If this becomes abstract you will not be able to test it directly ... Change this method to call "main" class of each of the extended classes */ static public void main(String[] args) { Fibo fib = new Fibo(); fib.print(); } } Fibo.main(null); . Init method = Stream fibonacci Number 10 = 34 fibonacci List = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] fibonacci Hashmap = {0=[0], 1=[0, 1], 2=[0, 1, 1], 3=[0, 1, 1, 2], 4=[0, 1, 1, 2, 3], 5=[0, 1, 1, 2, 3, 5], 6=[0, 1, 1, 2, 3, 5, 8], 7=[0, 1, 1, 2, 3, 5, 8, 13], 8=[0, 1, 1, 2, 3, 5, 8, 13, 21], 9=[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]} fibonacci Sequence 1 = [0] fibonacci Sequence 2 = [0, 1] fibonacci Sequence 3 = [0, 1, 1] fibonacci Sequence 4 = [0, 1, 1, 2] fibonacci Sequence 5 = [0, 1, 1, 2, 3] fibonacci Sequence 6 = [0, 1, 1, 2, 3, 5] fibonacci Sequence 7 = [0, 1, 1, 2, 3, 5, 8] fibonacci Sequence 8 = [0, 1, 1, 2, 3, 5, 8, 13] fibonacci Sequence 9 = [0, 1, 1, 2, 3, 5, 8, 13, 21] fibonacci Sequence 10 = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] . Fibonacci While Loop . public class FiboWhile extends Fibo { public FiboWhile() { this(10); // telescope to avoid code duplication, using default } public FiboWhile(int nth) { this.size = nth; this.list = new ArrayList<>(); this.hashID = 0; this.hash = new HashMap<>(); //initialize fibonacci and time mvc this.init(); } static public void main(String[] args) { FiboWhile wFib = new FiboWhile(); wFib.print(); } // Custom init using while loop instead protected void init() { this.name = "While Loop"; int i = 0; // new long array with only 0 long[] f = new long[] {0,1}; //while i is less than the length desired while (i < this.size) { // sets data first, then adds to f this.setData(f[0]); f = new long[] {f[1], f[0] + f[1]}; // adds to counter i++; } } } FiboWhile.main(null) . Init method = While Loop fibonacci Number 10 = 34 fibonacci List = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] fibonacci Hashmap = {0=[0], 1=[0, 1], 2=[0, 1, 1], 3=[0, 1, 1, 2], 4=[0, 1, 1, 2, 3], 5=[0, 1, 1, 2, 3, 5], 6=[0, 1, 1, 2, 3, 5, 8], 7=[0, 1, 1, 2, 3, 5, 8, 13], 8=[0, 1, 1, 2, 3, 5, 8, 13, 21], 9=[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]} fibonacci Sequence 1 = [0] fibonacci Sequence 2 = [0, 1] fibonacci Sequence 3 = [0, 1, 1] fibonacci Sequence 4 = [0, 1, 1, 2] fibonacci Sequence 5 = [0, 1, 1, 2, 3] fibonacci Sequence 6 = [0, 1, 1, 2, 3, 5] fibonacci Sequence 7 = [0, 1, 1, 2, 3, 5, 8] fibonacci Sequence 8 = [0, 1, 1, 2, 3, 5, 8, 13] fibonacci Sequence 9 = [0, 1, 1, 2, 3, 5, 8, 13, 21] fibonacci Sequence 10 = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] . Fibonacci Recursion Loop . public class FiboRecur extends Fibo { public FiboRecur() { this(10); // telescope to avoid code duplication, using default } public FiboRecur(int nth) { this.size = nth; this.list = new ArrayList<>(); this.hashID = 0; this.hash = new HashMap<>(); //initialize fibonacci and time mvc this.init(); } static public void main(String[] args) { FiboRecur rFib = new FiboRecur(); rFib.print(); } // Recursion function, using int i as a counter protected void recur(long[] f, int i) { // Sets data using beginning value this.setData(f[0]); // Cretes new long f = new long[]{f[1], f[0] + f[1]}; // Adds to counter i++; if (i < this.size) { // Recusion continues if size limit has not been reached this.recur(f, i); } } // Custom init using recursion loop instead protected void init() { this.name = "Recursion"; // Uses int i as a counter for recusion, also creates initial long[] int i = 0; long[] f = new long[] {0,1}; // input long and counter i into recursion function this.recur(f, i); } } FiboRecur.main(null) . Init method = Recursion fibonacci Number 10 = 34 fibonacci List = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] fibonacci Hashmap = {0=[0], 1=[0, 1], 2=[0, 1, 1], 3=[0, 1, 1, 2], 4=[0, 1, 1, 2, 3], 5=[0, 1, 1, 2, 3, 5], 6=[0, 1, 1, 2, 3, 5, 8], 7=[0, 1, 1, 2, 3, 5, 8, 13], 8=[0, 1, 1, 2, 3, 5, 8, 13, 21], 9=[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]} fibonacci Sequence 1 = [0] fibonacci Sequence 2 = [0, 1] fibonacci Sequence 3 = [0, 1, 1] fibonacci Sequence 4 = [0, 1, 1, 2] fibonacci Sequence 5 = [0, 1, 1, 2, 3] fibonacci Sequence 6 = [0, 1, 1, 2, 3, 5] fibonacci Sequence 7 = [0, 1, 1, 2, 3, 5, 8] fibonacci Sequence 8 = [0, 1, 1, 2, 3, 5, 8, 13] fibonacci Sequence 9 = [0, 1, 1, 2, 3, 5, 8, 13, 21] fibonacci Sequence 10 = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] . Fibonacci For Loop . public class FiboFor extends Fibo { public FiboFor() { this(10); // telescope to avoid code duplication, using default } public FiboFor(int nth) { this.size = nth; this.list = new ArrayList<>(); this.hashID = 0; this.hash = new HashMap<>(); //initialize fibonacci and time mvc this.init(); } static public void main(String[] args) { FiboRecur rFib = new FiboRecur(); rFib.print(); } // Custom init using for loop instead protected void init() { this.name = "For loop"; // creates initial long[] long[] f = new long[] {0,1}; // iterates through until reaches desired length for (int i = 0; i < this.size; i++) { // sets data, then updates f this.setData(f[0]); f = new long[] {f[1], f[0] + f[1]}; } } } FiboFor.main(null) . Init method = Recursion fibonacci Number 10 = 34 fibonacci List = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] fibonacci Hashmap = {0=[0], 1=[0, 1], 2=[0, 1, 1], 3=[0, 1, 1, 2], 4=[0, 1, 1, 2, 3], 5=[0, 1, 1, 2, 3, 5], 6=[0, 1, 1, 2, 3, 5, 8], 7=[0, 1, 1, 2, 3, 5, 8, 13], 8=[0, 1, 1, 2, 3, 5, 8, 13, 21], 9=[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]} fibonacci Sequence 1 = [0] fibonacci Sequence 2 = [0, 1] fibonacci Sequence 3 = [0, 1, 1] fibonacci Sequence 4 = [0, 1, 1, 2] fibonacci Sequence 5 = [0, 1, 1, 2, 3] fibonacci Sequence 6 = [0, 1, 1, 2, 3, 5] fibonacci Sequence 7 = [0, 1, 1, 2, 3, 5, 8] fibonacci Sequence 8 = [0, 1, 1, 2, 3, 5, 8, 13] fibonacci Sequence 9 = [0, 1, 1, 2, 3, 5, 8, 13, 21] fibonacci Sequence 10 = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/09/25/fibonacci.html",
@@ -265,7 +276,7 @@
- ,"post24": {
+ ,"post25": {
"title": "AP CSA 2022 FRQ",
"content": "The Book class is used to store information about a book. A partial Book class definition is shown. . You will write a class Textbook, which is a subclass of Book. A Textbook has an edition number, which is a positive integer used to identify different versions of the book. The getBookInfo method, when called on a Textbook, returns a string that also includes the edition information, as shown in the example. Information about the book title and price must be maintained in the Book class. Information about the edition must be maintained in the Textbook class. The Textbook class contains an additional method, canSubstituteFor, which returns true if a Textbook is a valid substitute for another Textbook and returns false otherwise. The current Textbook is a valid substitute for the Textbook referenced by the parameter of the canSubstituteFor method if the two Textbook objects have the same title and if the edition of the current Textbook is greater than or equal to the edition of the parameter. . public class Textbook extends Book //Define class called textbook //Since we are using a super class we need to extend book { private int edition; public Textbook(String t, double p, int e) //Constructor called Textbook passes through parameters for title, price, and edition //Each parameter has a different primative that need to be listed before hand { super(t, p); //This helps to take care for both the title and the price this.edition = e; } public int getEdition() //By creating this public int, we can have the computer return our book title name { return edition; } public String getBookInfo() { return super.getBookInfo() + "-" + edition; //This returns the title of the book, along with both the price and the edition } public boolean canSubstituteFor(Textbook other) //canSubstituteFor means that if two books have the same title, it will access the edition number and if the current textbook edition is greater than or equal to the edition of the parameter { return getTitle().equals(other.getTitle()) && this.edition >= other.getEdition(); } } . | public class Textbook extends book cannot find symbol symbol: class book | return super.getBookInfo() + "-" + edition; non-static variable super cannot be referenced from a static context | return super.getBookInfo() + "-" + edition; cannot find symbol symbol: method getBookInfo() | return getTitle().equals(other.getTitle()) && this.edition >= other.getEdition(); cannot find symbol symbol: method getTitle() | return getTitle().equals(other.getTitle()) && this.edition >= other.getEdition(); cannot find symbol symbol: method getTitle() .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/09/19/FRQ-2.html",
@@ -276,7 +287,7 @@
- ,"post25": {
+ ,"post26": {
"title": "Java Iteration",
"content": "class playerLoop { // The area between class definition and the 1st method is where we keep data for object in Java String [][] players; /** * Constructor initializes a 2D array of s */ public playerLoop() { //Storing Data in 2D arrays players = new String[][]{ //Player 0 { " o__", "/| ", "/ > o" }, //player 1 { " o__", "/| ", "/ > o" }, //player 2 { " o__", "/| ", "/ > o" }, //player 3 { " o__", "/| ", "/ > o" }, //player 4 { " o__", "/| ", "/ > o" }, }; } /** * Loop and print s in array * ... repeat until you reach zero ... */ public void printPoem() { //begin the poem System.out.println(); System.out.println("Player Shooting Soccer Ball Poem in Java Loop"); System.out.println(""); // players (non-primitive) defined in constructor knows its length int playerCount = players.length; for (int i = playerCount; i >= 1; i--) //loops through 2D array length backwards { //this print statement shows current count of players // concatenation (+) of the loop variable and string to form a countdown message System.out.println(i + " players shooting the ball..."); //how many separate parts are there in a player player? int partCount = players[0].length; for (int row = 0; row < partCount; row++) { //cycles through "cells" of 2d array /*cycles through columns to print each player part by part, will eventually print entire column*/ for (int col = 0; col < playerCount; col++) { // prints specific part of the player from the column System.out.print(players[col][row] + " "); //this is new line between separate parts } //this new line gives separation between stanza of poem System.out.println(); } //countdown for poem, decrementing playerCount variable by 1 System.out.println("One missed and got benched"); playerCount -= 1; } //out of all the loops, prints finishing messages System.out.println("No more players shooting in the field"); System.out.println(""); System.out.println(" THE END "); } /** * A Java Driver/Test method that is the entry point for execution */ public static void main(String[] args) { new playerLoop().printPoem(); //a new player list and output in one step } } playerLoop.main(null); . Player Shooting Soccer Ball Poem in Java Loop 5 players shooting the ball... o__ o__ o__ o__ o__ /| /| /| /| /| / > o / > o / > o / > o / > o One missed and got benched 4 players shooting the ball... o__ o__ o__ o__ /| /| /| /| / > o / > o / > o / > o One missed and got benched 3 players shooting the ball... o__ o__ o__ /| /| /| / > o / > o / > o One missed and got benched 2 players shooting the ball... o__ o__ /| /| / > o / > o One missed and got benched 1 players shooting the ball... o__ /| / > o One missed and got benched No more players shooting in the field THE END .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/09/15/java-iteration.html",
@@ -287,7 +298,7 @@
- ,"post26": {
+ ,"post27": {
"title": "Human Day/Psychology Video Notes",
"content": "Takeaways From Video . All successful people find ways to keep themselves under a good/calm state of mind in order to be the most effective in a work setting | Many people think that making mistakes and not succeeding at first is bad. In reality, if you ask any successful person about failure, they will respond by saying that in order to succeed in life you must taste the defeat of failure | . | She also stated, that it is very important for people to reflect on the many different gifts we are given in life Having a home, supportful parents, and access to clean food and water are some of the many examples that we need to be thankful for in life In order to show our gratitude, we must take time atleast 5 mins a day in order to reflect on what we are thankful for each day cuz tommorow is never guaranteed | . | . | In addition, she also spoke about how we should make sure to let go of harships or fights that may have happened in the past with friends or family She said this because at the end of the day, many of these fights are trivial and if something bad happens to anyone you will always bound up feeling regret for not letting go and apologizing/taking their apology My Gratitude List . | . | Having good family and friends | Access to food, water, and shelter | Opportunities to pursue my passions | Ability to travel with my family to many different countries around the world My Future Goals . | To be the best version of myself in all aspects of life School, friends, family member, and athlete | . | Make sure to reflect on my wrongdoings and thnk about what I can do in the future to avoid these mistakes for reoccurring | .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/markdown/2022/09/11/Psychology-and-the-Good-Life-Summarization.html",
@@ -298,7 +309,7 @@
- ,"post27": {
+ ,"post28": {
"title": "If Statement Notes",
"content": "A conditional statement lets us choose which statement will be executed next • Therefore they are sometimes called selection statements • Conditional statements give us the power to make basic decisions • The Java conditional statements are the: – if statement – if-else statement – switch statement . # Boolean Notes | The Boolean logical operators are : | , & , ^ , ! , || , && , == , != . | Java supplies a primitive data type called Boolean, instances of which can take the value true or false only, and have the default value false. | The major use of Boolean facilities is to implement the expressions which control if decisions and while loops. | . boolean isSoccerFan = true;//If you set a variable along with the word "boolean" to true, //this allows for the if statements to print the correct statements if(isSoccerFan){ System.out.println("Watches 1 Soccer Game Every Weekend"); } else { System.out.println("Watches 0 Soccer Games"); } . Watches 1 Soccer Game Every Weekend . int weight = 200; //Weights Are Rounded to Nearest 10(in pounds) between 130-250lbs if(weight==130){ System.out.println("Your Are Very Light"); } else if(weight==140){ System.out.println("Your Are Quite Light"); } else if(weight==150){ System.out.println("Your Are A Little Bit On The Lighter Side"); } else if(weight==160){ System.out.println("You Are At A Good Weight"); } else if(weight==170){ System.out.println("You Are At A Good Weight"); } else if(weight==180){ System.out.println("You Are At A Strong Weight"); } else if(weight==190){ System.out.println("You Are Very Close To Obese"); } else if(weight==200){ System.out.println("You Are Just Obese"); } else if(weight==210){ System.out.println("You Are Slightly Obese"); } else if(weight==220){ System.out.println("You Are Nearly Moderately Obese"); } else if(weight==230){ System.out.println("You Are Moderately Obese"); } else if(weight==240){ System.out.println("You Are Nearly Very Obese"); } else if(weight==250){ System.out.println("You Are Very Obese"); } . You Are Just Obese . Switch Statement Notes . A switch statement allows a variable to be tested for equality against a list of values. | Each value is called a case, and the variable being switched on is checked for each case. | The variable used in a switch statement can only be integers, convirtable integers (byte, short, char), strings and enums. | You can have any number of case statements within a switch. | End of each statement is followed with a comparable value and a colon. | The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal. | When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. | When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. | . int weight = 200; //Weights Are Rounded to Nearest 10(in pounds) between 130-250lbs. Intended for indivduals between the height of 5'8 to 5'11 switch(weight){ case 130: System.out.println("You are Very Light"); break; case 140: System.out.println("Your Are Very Light"); break; case 150: System.out.println("Your Are A Little Bit On The Lighter Side"); break; case 160: System.out.println("You Are At A Good Weight"); break; case 170: System.out.println("You Are At A Good Weight"); break; case 180: System.out.println("You Are At A Strong Weight"); break; case 190: System.out.println("You Are Very Close To Obese"); break; case 200: System.out.println("You Are Just Obese"); break; case 210: System.out.println("You Are Slightly Obese"); break; case 220: System.out.println("You Are Nearly Moderately Obese"); break; case 230: System.out.println("You Are Moderately Obese"); break; case 240: System.out.println("You Are Nearly Very Obese"); break; case 250: System.out.println("You Are Very Obese"); break; default: System.out.println("Invalid Input") break; } . You Are Just Obese . DeMorgan's Law Notes . DeMorgan’s laws were developed by Augustus De Morgan in the 1800s. | They show how to handle the negation of a complex conditional, which is a conditional statement with more than one condition joined by an and (&&) or or (||), such as (x < 3) && (y > 2). | Applying DeMorgan’s Laws to !(x < 3 && y > 2) yields !(x < 3) || !(y > 2) which means that this complex conditional will be true when (x >= 3 || y <= 2). | The negation modifies each conditional as shown below. < becomes >= | "> becomes <=" | == becomes != | <= becomes > | ">= becomes <" | != becomes == | . | not (a and b) is the same as (not a) or (not b). In Java this is written as !(a && b) == !a || !b | not (a or b) is the same as (not a) and (not b). In Java this is written as !(a || b) == !a && !b | . public class DeMorgansLawExample { public static boolean exVarOne = true; public static boolean exVarTwo = false; public static void main(String[] args) { // The two boolean expressions below are equal if (!(exVarOne && exVarTwo)) { System.out.println("The boolean expression is true"); } else { System.out.println("The boolean expression is false"); } if (!(exVarOne || exVarTwo)) { System.out.println("The boolean expression is true"); } else { System.out.println("The boolean expression is false"); } } } DeMorgansLawExample.main(null) . The boolean expression is true The boolean expression is false .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/09/11/if-else-examples-lesson.html",
@@ -309,7 +320,7 @@
- ,"post28": {
+ ,"post29": {
"title": "Week 2 - Java Menu Colors",
"content": "Screenshot . .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/markdown/2022/09/06/colors-javamenu.html",
@@ -320,7 +331,7 @@
- ,"post29": {
+ ,"post30": {
"title": "Units 5-16 Code.org Week 2",
"content": "Lesson 6 . Subclasses can be derived by entending a superclassing and using its attributes and behaviors. Syntax error is when your code doesn’t follow the correct formatting which results in all the code not running. Logic error is when the code ends up running but it doesn’t do what the user expects because of the logic behind it. . Lesson 9 . Painter plus extends the painter class, so when the MyNeighbrhood has access to all the public void variables within the painter plus.java file. . Lesson 11 . In this multiple choice question, the user is struggling to figure out the logic error they are reciving in their code. They are trying to make their character go one way but the character keeps going in the wrong direction, therefore by using the getDirection feature, the user can figure out where their code may be going wrong and therefore change their code to make sure that it completes the logic they were going for. . Lesson 13 . The PatternPainter class extends the PainterPlus class and the PainterPlus class extends the Painter class, so the when the PatternPainter is initialized in the MyNeighborhood.java file it can also access all the functions from the Painter and PainterPlus classes. .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/markdown/2022/09/06/Code.org-Snippets.html",
@@ -331,7 +342,7 @@
- ,"post30": {
+ ,"post31": {
"title": "Java Menu Week 2",
"content": "import java.net.http.*; import java.util.Scanner; . import java.util.Scanner; import java.lang.Math; public class Menu { public final String DEFAULT = " u001B[0m"; public final String[][] COLORS = { {"Default",DEFAULT}, {"Red", " u001B[31m"}, {"Green", " u001B[32m"}, {"Yellow", " u001B[33m"}, {"Blue", " u001B[34m"}, {"Purple", " u001B[35m"}, {"Cyan", " u001B[36m"}, {"White", " u001B[37m"}, {"Reset"," u001B[0m"}, {"Liverpool"," 033[1;91m"}, {"Tottenham"," 033[0;107m"}, {"Real"," 033[0;95m"}, {"Bayern"," 033[0;101m"}, {"Dortmund", " 033[0;93m"}, }; public final int NAME = 0; public final int ANSI = 1; public Menu() { Scanner sc = new Scanner(System.in); this.print(); boolean quit = false; while (!quit) { try { int choice = sc.nextInt(); System.out.print("" + choice + ": "); quit = this.action(choice); } catch (Exception e) { sc.nextLine(); System.out.println(e + ": Not a number, try again."); } } sc.close(); } private void print() { System.out.println("- n"); System.out.println("Soccer Info"); System.out.println("- n"); System.out.println("1 - Premier League Scorers"); System.out.println("2 - La Liga Scorers"); System.out.println("3 - Champions Scorers "); System.out.println("4 - Bundesliga Scorers"); System.out.println("5 - Serie A Scorers"); System.out.println("6 - Goals Against Calculator"); System.out.println("7 - Shooting Percentage Calculator"); System.out.println("0 - Quit"); System.out.println("- n"); } private boolean action(int selection) { boolean quit = false; switch (selection) { case 0: System.out.print("Program Exiting..."); quit = true; break; case 1: System.out.println(COLORS[4][ANSI] + "Premier League Top Scorers" + COLORS[8][ANSI]); System.out.println(COLORS[9][ANSI] + " t Mohamed Salah" + COLORS[8][ANSI]); System.out.println(" t" + COLORS[10][ANSI] + "Son" + COLORS[8][ANSI]); System.out.println(COLORS[1][ANSI] + " t Cristiano Ronaldo" + COLORS[8][ANSI]); System.out.println(" t" + COLORS[10][ANSI] + "Harry Kane" + COLORS[8][ANSI]); System.out.println(COLORS[9][ANSI] + " t Sadio Mane" + COLORS[8][ANSI]); break; case 2: System.out.println(COLORS[1][ANSI] + "La Liga Top Scorers" + COLORS[8][ANSI]); System.out.println(COLORS[11][ANSI] + " t Karim Benzema" + COLORS[8][ANSI]); System.out.println(" t Iago Aspas"); System.out.println(" t Raul de Tomas"); System.out.println(COLORS[11][ANSI] + " t Vinicius" + COLORS[8][ANSI]); System.out.println(" t Juanmi"); // for(int i = 0; i < COLORS.length; i++) // System.out.print(COLORS[i][ANSI] + COLORS[i][NAME]); break; case 3: System.out.println(COLORS[6][ANSI] + "Champions League Top Scorers" + COLORS[8][ANSI]); System.out.println(COLORS[11][ANSI] + " t Karim Benzema" + COLORS[8][ANSI]); System.out.println(" t u001B[37m" + COLORS[12][ANSI] + "Robert Lewangoalski" + COLORS[8][ANSI]); System.out.println(" t Sébastien Haller"); System.out.println(COLORS[9][ANSI] + " t Mohamed Salah" + COLORS[8][ANSI]); System.out.println(" t Christopher Nkunku"); // for (int i = 0; i < 20; i++) { // int random = (int) (Math.random() * COLORS.length); // try { // Thread.sleep(100); // } catch (Exception e) { // System.out.println(e); // } // System.out.print(COLORS[random][ANSI] + "#"); // } break; case 4: System.out.println(COLORS[5][ANSI] + "Bundesliga" + COLORS[8][ANSI]); System.out.println(" t u001B[37m" + COLORS[12][ANSI] + "Robert Lewangoalski" + COLORS[8][ANSI]); System.out.println(" t Patrick Schick"); System.out.println(" t 033[0;93m" + COLORS[13][ANSI] + "Erling Haaland" + COLORS[8][ANSI]); System.out.println(" t Anothny Modeste"); System.out.println(" t Christopher Nkunku"); break; case 5: System.out.println(COLORS[2][ANSI] + "Serie A" + COLORS[8][ANSI]); System.out.println(" t Ciro Immobile"); System.out.println(" t Dušan Vlahović"); System.out.println(" t Lautaro Martínez"); System.out.println(" t Tammy Abraham"); System.out.println(" t Giovanni Simeone"); break; case 6: Scanner myObj = new Scanner(System.in); System.out.println("Enter Goals Against and Games Played:"); int GoalsAgainst = myObj.nextInt(); double GamesPlayed = myObj.nextDouble(); myObj.close(); System.out.println("Goals Against Average: " + GoalsAgainst/GamesPlayed); case 7: Scanner newObj = new Scanner(System.in); System.out.println("Enter Goals Scored and Shots Taken:"); int GoalsScored = newObj.nextInt(); double ShotsTaken = newObj.nextDouble(); newObj.close(); System.out.println("Shooting Percentage: " + GoalsScored/ShotsTaken); default: System.out.print("Unexpected choice, try again."); } System.out.println(DEFAULT); return quit; } static public void main(String[] args) { new Menu(); } } Menu.main(null); . - Soccer Info - 1 - Premier League Scorers 2 - La Liga Scorers 3 - Champions Scorers 4 - Bundesliga Scorers 5 - Serie A Scorers 6 - Goals Against Calculator 7 - Shooting Percentage Calculator 0 - Quit - 4 4: Bundesliga Robert Lewangoalski Patrick Schick Erling Haaland Anothny Modeste Christopher Nkunku 5 5: Serie A Ciro Immobile Dušan Vlahović Lautaro Martínez Tammy Abraham Giovanni Simeone 1 1: Premier League Top Scorers Mohamed Salah Son Cristiano Ronaldo Harry Kane Sadio Mane 2 2: La Liga Top Scorers Karim Benzema Iago Aspas Raul de Tomas Vinicius Juanmi 3 3: Champions League Top Scorers Karim Benzema Robert Lewangoalski Sébastien Haller Mohamed Salah Christopher Nkunku 6 6: Enter Goals Against and Games Played: 10 2 Goals Against Average: 5.0 Enter Goals Scored and Shots Taken: 7 0 Shooting Percentage: Infinity Unexpected choice, try again. 0 0: Program Exiting... .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/09/05/week2menu.html",
@@ -342,7 +353,7 @@
- ,"post31": {
+ ,"post32": {
"title": "Triple Double Calculator",
"content": "//A triple-double is achieved when a player has double-digit stats (at least 10) in all the categories(points, assists, rebounds). public class BasketballStatsTripleDouble { ArrayList<Integer> points; ArrayList<Integer> assists; ArrayList<Integer> rebounds; int games; public BasketballStatsTripleDouble() { this.points = new ArrayList<>(); this.enterPoints(); this.assists = new ArrayList<>(); this.enterAssists(); this.rebounds = new ArrayList<>(); this.enterRebounds(); } private void enterPoints() { Scanner input; while (true) { input = new Scanner(System.in); System.out.print("Enter a Integer, 0 to exit: "); try { int pointsScored = input.nextInt(); System.out.println(pointsScored); this.points.add(pointsScored); } catch (Exception e) { System.out.println("Not an Integer (form like 9), " + e); } input.close(); } } private void enterAssists() { Scanner input; while (true) { input = new Scanner(System.in); System.out.print("Enter a Integer, 0 to exit: "); try { int assistsTallied = input.nextInt(); System.out.println(assistsTallied); this.assists.add(assistsTallied); } catch (Exception e) { System.out.println("Not an Integer (form like 9), " + e); } input.close(); } } private void enterRebounds() { Scanner input; while (true) { input = new Scanner(System.in); System.out.print("Enter Number of Rebounds, 0 to exit: "); try { int reboundsTallied = input.nextInt(); System.out.println(reboundsTallied); this.rebounds.add(reboundsTallied); } catch (Exception e) { System.out.println("Not A Valid Number (form like 9), " + e); } input.close(); } } private void enterGames() { Scanner input; input = new Scanner(System.in); System.out.print("Enter a Integer, 0 to exit: "); try { int games = input.nextInt(); System.out.println(games); } catch (Exception e) { System.out.println("Not an Integer (form like 9), " + e); } input.close(); this.games = games; } public int getNumberOfTripleDoubles() { int numberOfTripleDoubles = 0; for (int x=0; x<this.games; x++) { int p = this.points.get(x); int a = this.assists.get(x); int r = this.rebounds.get(x); if (tripleDouble(p,a,r)==true) { System.out.println ("In game" + (x+1) + "you achieved a triple double"); numberOfTripleDoubles++; } } return (numberOfTripleDoubles); } private boolean tripleDouble(int points, int assists, int rebounds) { if(points >= 10 && assists >= 10 && rebounds >= 10) { return true; } return false; } public static void main(String[] args) { BasketballStatsTripleDouble stats = new BasketballStatsTripleDouble(); System.out.println("Number of Triple Doubles " + String.format("%.2f", stats.getNumberOfTripleDoubles())); } } BasketballStatsTripleDouble.main(null); . Enter a Integer, 0 to exit: 10 Enter a Integer, 0 to exit: 10 Enter a Integer, 0 to exit: 10 Enter a Integer, 0 to exit: 0 Enter a Integer, 0 to exit: 12 Enter a Integer, 0 to exit: 1 Enter a Integer, 0 to exit: 2 Enter a Integer, 0 to exit: 3 Enter a Integer, 0 to exit: 24 Enter a Integer, 0 to exit: 0 Enter a Integer, 0 to exit: .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/08/29/tripledoubles.html",
@@ -353,7 +364,7 @@
- ,"post32": {
+ ,"post33": {
"title": "Bash Notebook",
"content": "python --version python2 --version conda --version javac --version java --version jupyter --version jupyter kernelspec list . Python 3.9.12 Python 2.7.16 conda 4.14.0 javac 18.0.2 openjdk 18.0.2 2022-07-19 OpenJDK Runtime Environment Homebrew (build 18.0.2+0) OpenJDK 64-Bit Server VM Homebrew (build 18.0.2+0, mixed mode, sharing) Selected Jupyter core packages... IPython : 8.2.0 ipykernel : 6.9.1 ipywidgets : 7.6.5 jupyter_client : 6.1.12 jupyter_core : 4.9.2 jupyter_server : 1.13.5 jupyterlab : 3.3.2 nbclient : 0.5.13 nbconvert : 6.4.4 nbformat : 5.3.0 notebook : 6.4.8 qtconsole : 5.3.0 traitlets : 5.1.1 Available kernels: bash /Users/mfcbpranav/Library/Jupyter/kernels/bash java /Users/mfcbpranav/Library/Jupyter/kernels/java javascript /Users/mfcbpranav/Library/Jupyter/kernels/javascript python3 /Users/mfcbpranav/opt/anaconda3/share/jupyter/kernels/python3 .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/08/29/Bash-Test.html",
@@ -364,7 +375,7 @@
- ,"post33": {
+ ,"post34": {
"title": "Ap Test Planner",
"content": "Plan . Must Follow along class weekly requirements | Will make sure to watch collegboard videos | Will do the code.org assignments weekly to make sure that I am ahead | Daily CB videos | Organize jupyter based on units w/ key code segments Practice AP MCs and FRQs, especially near April . | Collegeboard work and practice | As AP Test date gets closer I will: | Take practice tests to determine strong and weak concepts | Review old material and search for new resources | Take practice MCs | Take practice FRQs | Take full lenght, sit down, timed AP exams | .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/08/29/AP-Test-Planner.html",
@@ -375,7 +386,7 @@
- ,"post34": {
+ ,"post35": {
"title": "Title",
"content": "",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/08/23/New-Java-Hack.html",
@@ -386,7 +397,7 @@
- ,"post35": {
+ ,"post36": {
"title": "Title",
"content": "print("hello world") . hello world .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/08/21/python-hello-world.html",
@@ -397,7 +408,7 @@
- ,"post36": {
+ ,"post37": {
"title": "TT 1.0.0 Tools and Equipment",
"content": "Hacks . Issue . Part 1 Fastpages . Python Jupyter Notebook | [Java Jupyter Notebook]https://github.com/PranavP04/OfficialTri1PranavCSA/2022/08/21/Java-Jupyter-Notebook.html) . | Github Insights for FastPages | Github Insights for CSA Project | . Part 2 Java Project . . Spring Portfolio Commit | . Issue .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/markdown/2022/08/21/Tools.html",
@@ -408,7 +419,7 @@
- ,"post37": {
+ ,"post38": {
"title": "Title",
"content": "print("hello world") . hello world .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/2022/08/21/Python-Jupyter-Notebook.html",
@@ -419,7 +430,7 @@
- ,"post38": {
+ ,"post39": {
"title": "Introducing fastpages",
"content": ". We are very pleased to announce the immediate availability of fastpages. fastpages is a platform which allows you to create and host a blog for free, with no ads and many useful features, such as: . Create posts containing code, outputs of code (which can be interactive), formatted text, etc directly from Jupyter Notebooks; for instance see this great example post from Scott Hawley. Notebook posts support features such as: Interactive visualizations made with Altair remain interactive. | Hide or show cell input and output. | Collapsable code cells that are either open or closed by default. | Define the Title, Summary and other metadata via a special markdown cells | Ability to add links to Colab and GitHub automatically. | . | Create posts, including formatting and images, directly from Microsoft Word documents. | Create and edit Markdown posts entirely online using GitHub's built-in markdown editor. | Embed Twitter cards and YouTube videos. | Categorization of blog posts by user-supplied tags for discoverability. | ... and much more | . fastpages relies on Github pages for hosting, and Github Actions to automate the creation of your blog. The setup takes around three minutes, and does not require any technical knowledge or expertise. Due to built-in automation of fastpages, you don't have to fuss with conversion scripts. All you have to do is save your Jupyter notebook, Word document or markdown file into a specified directory and the rest happens automatically. Infact, this blog post is written in a Jupyter notebook, which you can see with the "View on GitHub" link above. . fast.ai have previously released a similar project called fast_template, which is even easier to set up, but does not support automatic creation of posts from Microsoft Word or Jupyter notebooks, including many of the features outlined above. . Because fastpages is more flexible and extensible, we recommend using it where possible. fast_template may be a better option for getting folks blogging who have no technical expertise at all, and will only be creating posts using Github's integrated online editor. . Setting Up Fastpages . The setup process of fastpages is automated with GitHub Actions, too! Upon creating a repo from the fastpages template, a pull request will automatically be opened (after ~ 30 seconds) configuring your blog so it can start working. The automated pull request will greet you with instructions like this: . . All you have to do is follow these instructions (in the PR you receive) and your new blogging site will be up and running! . Jupyter Notebooks & Fastpages . In this post, we will cover special features that fastpages provides for Jupyter notebooks. You can also write your blog posts with Word documents or markdown in fastpages, which contain many, but not all the same features. . Options via FrontMatter . The first cell in your Jupyter Notebook or markdown blog post contains front matter. Front matter is metadata that can turn on/off options in your Notebook. It is formatted like this: . # Title > Awesome summary - toc:true- branch: master - badges: true - comments: true - author: Hamel Husain & Jeremy Howard - categories: [fastpages, jupyter] . All of the above settings are enabled in this post, so you can see what they look like! . the summary field (preceeded by >) will be displayed under your title, and will also be used by social media to display as the description of your page. | toc: setting this to true will automatically generate a table of contents | badges: setting this to true will display Google Colab and GitHub links on your blog post. | comments: setting this to true will enable comments. See these instructions for more details. | author this will display the authors names. | categories will allow your post to be categorized on a "Tags" page, where readers can browse your post by categories. | . Markdown front matter is formatted similarly to notebooks. The differences between the two can be viewed on the fastpages README. . Code Folding . put a #collapse-hide flag at the top of any cell if you want to hide that cell by default, but give the reader the option to show it: . import pandas as pd import altair as alt . . put a #collapse-show flag at the top of any cell if you want to show that cell by default, but give the reader the option to hide it: . cars = 'https://vega.github.io/vega-datasets/data/cars.json' movies = 'https://vega.github.io/vega-datasets/data/movies.json' sp500 = 'https://vega.github.io/vega-datasets/data/sp500.csv' stocks = 'https://vega.github.io/vega-datasets/data/stocks.csv' flights = 'https://vega.github.io/vega-datasets/data/flights-5k.json' . . If you want to completely hide cells (not just collapse them), read these instructions. . Interactive Charts With Altair . Interactive visualizations made with Altair remain interactive! . We leave this below cell unhidden so you can enjoy a preview of syntax highlighting in fastpages, which uses the Dracula theme. . label = alt.selection_single( encodings=['x'], # limit selection to x-axis value on='mouseover', # select on mouseover events nearest=True, # select data point nearest the cursor empty='none' # empty selection includes no data points ) # define our base line chart of stock prices base = alt.Chart().mark_line().encode( alt.X('date:T'), alt.Y('price:Q', scale=alt.Scale(type='log')), alt.Color('symbol:N') ) alt.layer( base, # base line chart # add a rule mark to serve as a guide line alt.Chart().mark_rule(color='#aaa').encode( x='date:T' ).transform_filter(label), # add circle marks for selected time points, hide unselected points base.mark_circle().encode( opacity=alt.condition(label, alt.value(1), alt.value(0)) ).add_selection(label), # add white stroked text to provide a legible background for labels base.mark_text(align='left', dx=5, dy=-5, stroke='white', strokeWidth=2).encode( text='price:Q' ).transform_filter(label), # add text labels for stock prices base.mark_text(align='left', dx=5, dy=-5).encode( text='price:Q' ).transform_filter(label), data=stocks ).properties( width=500, height=400 ) . Data Tables . You can display tables per the usual way in your blog: . df[['Title', 'Worldwide_Gross', 'Production_Budget', 'IMDB_Rating']].head() . Title Worldwide_Gross Production_Budget IMDB_Rating . 0 The Land Girls | 146083.0 | 8000000.0 | 6.1 | . 1 First Love, Last Rites | 10876.0 | 300000.0 | 6.9 | . 2 I Married a Strange Person | 203134.0 | 250000.0 | 6.8 | . 3 Let's Talk About Sex | 373615.0 | 300000.0 | NaN | . 4 Slam | 1087521.0 | 1000000.0 | 3.4 | . Other Features . GitHub Flavored Emojis . Typing I give this post two :+1:! will render this: . I give this post two :+1:! . Images w/Captions . You can include markdown images with captions like this: . ![](https://www.fast.ai/images/fastai_paper/show_batch.png "Credit: https://www.fast.ai/2020/02/13/fastai-A-Layered-API-for-Deep-Learning/") . . Of course, the caption is optional. . Tweetcards . Typing > twitter: https://twitter.com/jakevdp/status/1204765621767901185?s=20 will render this: Altair 4.0 is released! https://t.co/PCyrIOTcvvTry it with: pip install -U altairThe full list of changes is at https://t.co/roXmzcsT58 ...read on for some highlights. pic.twitter.com/vWJ0ZveKbZ . — Jake VanderPlas (@jakevdp) December 11, 2019 . Youtube Videos . Typing > youtube: https://youtu.be/XfoYk_Z5AkI will render this: . Boxes / Callouts . Typing > Warning: There will be no second warning! will render this: . Warning: There will be no second warning! . Typing > Important: Pay attention! It's important. will render this: . Important: Pay attention! It’s important. . Typing > Tip: This is my tip. will render this: . Tip: This is my tip. . Typing > Note: Take note of this. will render this: . Note: Take note of this. . Typing > Note: A doc link to [an example website: fast.ai](https://www.fast.ai/) should also work fine. will render in the docs: . Note: A doc link to an example website: fast.ai should also work fine. . More Examples . This tutorial contains more examples of what you can do with notebooks. . How fastpages Converts Notebooks to Blog Posts . fastpages uses nbdev to power the conversion process of Jupyter Notebooks to blog posts. When you save a notebook into the /_notebooks folder of your repository, GitHub Actions applies nbdev against those notebooks automatically. The same process occurs when you save Word documents or markdown files into the _word or _posts directory, respectively. . We will discuss how GitHub Actions work in a follow up blog post. . Resources & Next Steps . We highly encourage you to start blogging with fastpages! Some resources that may be helpful: . fastpages repo - this is where you can go to create your own fastpages blog! | Fastai forums - nbdev & blogging category. You can ask questions about fastpages here, as well as suggest new features. | nbdev: this project powers the conversion of Jupyter notebooks to blog posts. | . If you end up writing a blog post using fastpages, please let us know on Twitter: @jeremyphoward, @HamelHusain. .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/fastpages/jupyter/2020/02/21/introducing-fastpages.html",
@@ -430,7 +441,7 @@
- ,"post39": {
+ ,"post40": {
"title": "Fastpages Notebook Blog Post",
"content": "About . This notebook is a demonstration of some of capabilities of fastpages with notebooks. . With fastpages you can save your jupyter notebooks into the _notebooks folder at the root of your repository, and they will be automatically be converted to Jekyll compliant blog posts! . Front Matter . The first cell in your Jupyter Notebook or markdown blog post contains front matter. Front matter is metadata that can turn on/off options in your Notebook. It is formatted like this: . # "My Title" > "Awesome summary" - toc:true- branch: master - badges: true - comments: true - author: Hamel Husain & Jeremy Howard - categories: [fastpages, jupyter] . Setting toc: true will automatically generate a table of contents | Setting badges: true will automatically include GitHub and Google Colab links to your notebook. | Setting comments: true will enable commenting on your blog post, powered by utterances. | . The title and description need to be enclosed in double quotes only if they include special characters such as a colon. More details and options for front matter can be viewed on the front matter section of the README. . Markdown Shortcuts . A #hide comment at the top of any code cell will hide both the input and output of that cell in your blog post. . A #hide_input comment at the top of any code cell will only hide the input of that cell. . The comment #hide_input was used to hide the code that produced this. . put a #collapse-hide flag at the top of any cell if you want to hide that cell by default, but give the reader the option to show it: . import pandas as pd import altair as alt . . put a #collapse-show flag at the top of any cell if you want to show that cell by default, but give the reader the option to hide it: . cars = 'https://vega.github.io/vega-datasets/data/cars.json' movies = 'https://vega.github.io/vega-datasets/data/movies.json' sp500 = 'https://vega.github.io/vega-datasets/data/sp500.csv' stocks = 'https://vega.github.io/vega-datasets/data/stocks.csv' flights = 'https://vega.github.io/vega-datasets/data/flights-5k.json' . . place a #collapse-output flag at the top of any cell if you want to put the output under a collapsable element that is closed by default, but give the reader the option to open it: . print('The comment #collapse-output was used to collapse the output of this cell by default but you can expand it.') . The comment #collapse-output was used to collapse the output of this cell by default but you can expand it. . . Interactive Charts With Altair . Charts made with Altair remain interactive. Example charts taken from this repo, specifically this notebook. . Example 1: DropDown . # use specific hard-wired values as the initial selected values selection = alt.selection_single( name='Select', fields=['Major_Genre', 'MPAA_Rating'], init={'Major_Genre': 'Drama', 'MPAA_Rating': 'R'}, bind={'Major_Genre': alt.binding_select(options=genres), 'MPAA_Rating': alt.binding_radio(options=mpaa)} ) # scatter plot, modify opacity based on selection alt.Chart(df).mark_circle().add_selection( selection ).encode( x='Rotten_Tomatoes_Rating:Q', y='IMDB_Rating:Q', tooltip='Title:N', opacity=alt.condition(selection, alt.value(0.75), alt.value(0.05)) ) . Example 2: Tooltips . alt.Chart(df).mark_circle().add_selection( alt.selection_interval(bind='scales', encodings=['x']) ).encode( alt.X('Rotten_Tomatoes_Rating', type='quantitative'), alt.Y('IMDB_Rating', type='quantitative', axis=alt.Axis(minExtent=30)), # y=alt.Y('IMDB_Rating:Q', ), # use min extent to stabilize axis title placement tooltip=['Title:N', 'Release_Date:N', 'IMDB_Rating:Q', 'Rotten_Tomatoes_Rating:Q'] ).properties( width=500, height=400 ) . Example 3: More Tooltips . label = alt.selection_single( encodings=['x'], # limit selection to x-axis value on='mouseover', # select on mouseover events nearest=True, # select data point nearest the cursor empty='none' # empty selection includes no data points ) # define our base line chart of stock prices base = alt.Chart().mark_line().encode( alt.X('date:T'), alt.Y('price:Q', scale=alt.Scale(type='log')), alt.Color('symbol:N') ) alt.layer( base, # base line chart # add a rule mark to serve as a guide line alt.Chart().mark_rule(color='#aaa').encode( x='date:T' ).transform_filter(label), # add circle marks for selected time points, hide unselected points base.mark_circle().encode( opacity=alt.condition(label, alt.value(1), alt.value(0)) ).add_selection(label), # add white stroked text to provide a legible background for labels base.mark_text(align='left', dx=5, dy=-5, stroke='white', strokeWidth=2).encode( text='price:Q' ).transform_filter(label), # add text labels for stock prices base.mark_text(align='left', dx=5, dy=-5).encode( text='price:Q' ).transform_filter(label), data=stocks ).properties( width=500, height=400 ) . Data Tables . You can display tables per the usual way in your blog: . df[['Title', 'Worldwide_Gross', 'Production_Budget', 'Distributor', 'MPAA_Rating', 'IMDB_Rating', 'Rotten_Tomatoes_Rating']].head() . Title Worldwide_Gross Production_Budget Distributor MPAA_Rating IMDB_Rating Rotten_Tomatoes_Rating . 0 The Land Girls | 146083.0 | 8000000.0 | Gramercy | R | 6.1 | NaN | . 1 First Love, Last Rites | 10876.0 | 300000.0 | Strand | R | 6.9 | NaN | . 2 I Married a Strange Person | 203134.0 | 250000.0 | Lionsgate | None | 6.8 | NaN | . 3 Let's Talk About Sex | 373615.0 | 300000.0 | Fine Line | None | NaN | 13.0 | . 4 Slam | 1087521.0 | 1000000.0 | Trimark | R | 3.4 | 62.0 | . Images . Local Images . You can reference local images and they will be copied and rendered on your blog automatically. You can include these with the following markdown syntax: . ![](my_icons/fastai_logo.png) . . Remote Images . Remote images can be included with the following markdown syntax: . ![](https://image.flaticon.com/icons/svg/36/36686.svg) . . Animated Gifs . Animated Gifs work, too! . ![](https://upload.wikimedia.org/wikipedia/commons/7/71/ChessPawnSpecialMoves.gif) . . Captions . You can include captions with markdown images like this: . ![](https://www.fast.ai/images/fastai_paper/show_batch.png "Credit: https://www.fast.ai/2020/02/13/fastai-A-Layered-API-for-Deep-Learning/") . . Other Elements . GitHub Flavored Emojis . Typing I give this post two :+1:! will render this: . I give this post two :+1:! . Tweetcards . Typing > twitter: https://twitter.com/jakevdp/status/1204765621767901185?s=20 will render this: Altair 4.0 is released! https://t.co/PCyrIOTcvvTry it with: pip install -U altairThe full list of changes is at https://t.co/roXmzcsT58 ...read on for some highlights. pic.twitter.com/vWJ0ZveKbZ . — Jake VanderPlas (@jakevdp) December 11, 2019 . Youtube Videos . Typing > youtube: https://youtu.be/XfoYk_Z5AkI will render this: . Boxes / Callouts . Typing > Warning: There will be no second warning! will render this: . Warning: There will be no second warning! . Typing > Important: Pay attention! It's important. will render this: . Important: Pay attention! It’s important. . Typing > Tip: This is my tip. will render this: . Tip: This is my tip. . Typing > Note: Take note of this. will render this: . Note: Take note of this. . Typing > Note: A doc link to [an example website: fast.ai](https://www.fast.ai/) should also work fine. will render in the docs: . Note: A doc link to an example website: fast.ai should also work fine. . Footnotes . You can have footnotes in notebooks, however the syntax is different compared to markdown documents. This guide provides more detail about this syntax, which looks like this: . For example, here is a footnote {% fn 1 %}. And another {% fn 2 %} {{ 'This is the footnote.' | fndetail: 1 }} {{ 'This is the other footnote. You can even have a [link](www.github.com)!' | fndetail: 2 }} . For example, here is a footnote 1. . And another 2 . 1. This is the footnote.↩ . 2. This is the other footnote. You can even have a link!↩ .",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/jupyter/2020/02/20/test.html",
@@ -441,7 +452,7 @@
- ,"post40": {
+ ,"post41": {
"title": "An Example Markdown Post",
"content": "Example Markdown Post . Basic setup . Jekyll requires blog post files to be named according to the following format: . YEAR-MONTH-DAY-filename.md . Where YEAR is a four-digit number, MONTH and DAY are both two-digit numbers, and filename is whatever file name you choose, to remind yourself what this post is about. .md is the file extension for markdown files. . The first line of the file should start with a single hash character, then a space, then your title. This is how you create a “level 1 heading” in markdown. Then you can create level 2, 3, etc headings as you wish but repeating the hash character, such as you see in the line ## File names above. . Basic formatting . You can use italics, bold, code font text, and create links. Here’s a footnote 1. Here’s a horizontal rule: . . Lists . Here’s a list: . item 1 | item 2 | . And a numbered list: . item 1 | item 2 | Boxes and stuff . This is a quotation . . You can include alert boxes …and… . . You can include info boxes Images . . Code . You can format text and code per usual . General preformatted text: . # Do a thing do_thing() . Python code and output: . # Prints '2' print(1+1) . 2 . Formatting text as shell commands: . echo "hello world" ./some_script.sh --option "value" wget https://example.com/cat_photo1.png . Formatting text as YAML: . key: value - another_key: "another value" . Tables . Column 1 Column 2 . A thing | Another thing | . Tweetcards . Altair 4.0 is released! https://t.co/PCyrIOTcvvTry it with: pip install -U altairThe full list of changes is at https://t.co/roXmzcsT58 ...read on for some highlights. pic.twitter.com/vWJ0ZveKbZ . — Jake VanderPlas (@jakevdp) December 11, 2019 Footnotes . This is the footnote. ↩ . |",
"url": "https://pranavp04.github.io/OfficialTri1PranavCSA/markdown/2020/01/14/test-markdown-post.html",
diff --git a/feed.xml b/feed.xml
index ebeb2e5..ea91457 100755
--- a/feed.xml
+++ b/feed.xml
@@ -1 +1 @@
-Jekyll2023-04-27T11:42:48-05:00https://pranavp04.github.io/OfficialTri1PranavCSA/feed.xmlfastpagesAn easy to use blogging platform with support for Jupyter Notebooks.Pranav IJave Kernel Examples2023-04-26T00:00:00-05:002023-04-26T00:00:00-05:00https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/26/PranavPrimitiveJupyterPageJava Notebook2023-04-26T00:00:00-05:002023-04-26T00:00:00-05:00https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/26/Java-Jupyter-NotebookJava ArrayList2023-04-26T00:00:00-05:002023-04-26T00:00:00-05:00https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/26/Java-ArrayListHack 12023-04-26T00:00:00-05:002023-04-26T00:00:00-05:00https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/26/HW-RohangroupTitle2023-04-23T00:00:00-05:002023-04-23T00:00:00-05:00https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/23/Test
\ No newline at end of file
+Jekyll2023-04-28T11:25:45-05:00https://pranavp04.github.io/OfficialTri1PranavCSA/feed.xmlfastpagesAn easy to use blogging platform with support for Jupyter Notebooks.Classes FRQ2023-04-28T00:00:00-05:002023-04-28T00:00:00-05:00https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/28/FRQ'sJava ArrayList2023-04-27T00:00:00-05:002023-04-27T00:00:00-05:00https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/27/Java-ArrayListJava Notebook2023-04-27T00:00:00-05:002023-04-27T00:00:00-05:00https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/27/Java-Jupyter-NotebookPranav IJave Kernel Examples2023-04-27T00:00:00-05:002023-04-27T00:00:00-05:00https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/27/PranavPrimitiveJupyterPageHack 12023-04-26T00:00:00-05:002023-04-26T00:00:00-05:00https://pranavp04.github.io/OfficialTri1PranavCSA/2023/04/26/HW-Rohangroup
\ No newline at end of file
diff --git a/index.html b/index.html
index 6bc5977..8339971 100755
--- a/index.html
+++ b/index.html
@@ -27,20 +27,25 @@