Giter Club home page Giter Club logo

apcsa-pages's Introduction

https://dolphinalt.github.io/APCSA-Pages/

Chirpy Jekyll Theme

A minimal, responsive and feature-rich Jekyll theme for technical writing.

Gem Version  CI  Codacy Badge  GitHub license  996.icu

Live Demo →

Devices Mockup

Features

Click to view features

  • Dark / Light Theme Mode
  • Localized UI language
  • Pinned Posts on Home Page
  • Hierarchical Categories
  • Trending Tags
  • Table of Contents
  • Last Modified Date
  • Syntax Highlighting
  • Mathematical Expressions
  • Mermaid Diagrams & Flowcharts
  • Dark / Light Mode Images
  • Embed Videos
  • Disqus / Utterances / Giscus Comments
  • Built-in Search
  • Atom Feeds
  • Google Analytics
  • SEO & Performance Optimization

Documentation

To explore usage, development, and upgrade guide of the project, please refer to the Wiki.

Contributing

Contributions (Issues/PRs/Discussions) are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated. For details, see the "Contributing Guidelines".

Credits

This theme is mainly built with Jekyll ecosystem, Bootstrap, Font Awesome and some other wonderful tools. The avatar and favicon design come from Clipart Max.

Many thanks to the contributors who participated in the development and to the folks who reported bugs or shared ideas.

Last but not least, thanks to JetBrains for providing the Open Source License.

Sponsoring

If you'd like to sponsor this project, the following options are available.

Ko-fi  Wechat Pay  Alipay

License

This work is published under MIT License.

apcsa-pages's People

Contributors

cotes2020 avatar dolphinalt avatar zakkemble avatar joshjohanning avatar v4vong avatar dependabot-preview[bot] avatar griceturrble avatar mattpopovich avatar nichtshsu avatar sillebille avatar ruzickap avatar penekhun avatar brootware avatar mreddx avatar mpavelka avatar fwolfst avatar ryantg avatar periecle avatar genericmadscientist avatar onevzz avatar paulovitorweb avatar nshidqi avatar mikeytroo avatar michaeltan9999 avatar matybuild avatar martinp7r avatar marnick39 avatar kendaleiv avatar renardjojo avatar sorindex avatar

Stargazers

 avatar

Watchers

 avatar

apcsa-pages's Issues

2015 FRQ to PBL Associations and Reflection

Review Ticket

FRQ 1: Arrays and Array Lists

The original FRQ wanted us to loop through an array and calculate values and analytical data. In my PBL project, I still used the ideas relating to the arrays and array lists, however, it wasn't the same. As seen in the following code chunk, I iterate through a list to find specific values that are important to our algorithm and backend processing. In addition, while not quite a 2D array, the usage of a hashmap can also be seen, showing the methods of storing data under different entry dates with each stock ticker and its number of shares/price predicted.

            // Extract Attributes from JSON
            Map<String, Object> attributeMap = new HashMap<>();
            String[] stocks = {"AAPL", "AMZN", "COST", "GOOGL", "LMT", "META", "MSFT", "NOC", "TSLA", "UNH", "WMT"};

            for (Map.Entry<String,Object> entry : stat_map.entrySet())  {
                // Add all attributes other than "date" and "id" to the "attribute_map"
                if (!entry.getKey().equals("date") && !entry.getKey().equals("id")) {
                    // Handle each stock case
                    for (String stock : stocks) {
                        if (entry.getKey().equals(stock)) {
                            // String shares=String.valueOf(entry.getValue());
                            attributeMap.put(entry.getKey(), entry.getValue()); // Add stock attribute
                            break;
                        }
                    }
                    if (entry.getKey().equals("Balance")) {
                        // String shares=String.valueOf(entry.getValue());
                        attributeMap.put(entry.getKey(), entry.getValue()); // Add stock attribute
                        break;
                    }
                }
            }

FRQ 2: Classes

Almost all of my work on our PBL project was done with classes, especially the stock info classes. As seen in the following code segment, there is the usage of a Stock public class, along with multiple methods, such as the Stock setter method, as well as the getTotalCost and getTotalShares methods which both rely on the manipulation and analysis of data in order to return their values. You can also see an init function for the initialization of testing/initial prediction data for the database.

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Convert(attributeName ="stock", converter = JsonType.class)
public class Stock {

    // automatic unique identifier for Person record
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    // name, share cost, roles are key attributes to login and authentication
    @NotEmpty
    @Column(unique=true)
    private String name;

    @DateTimeFormat(pattern = "yyyy-MM-dd") //should probably change to time to be more accurate
    private Date time;

    @NotEmpty
    private Double cost;
    @NotEmpty
    private Integer shares;

    // Are we selling or buying the stock?
    // @NotEmpty
    // private String operation;

    @JdbcTypeCode(SqlTypes.JSON)
    @Column(columnDefinition = "jsonb")
    private Map<String,Map<String, Object>> stats = new HashMap<>(); 

    // Essentially, we record who buys the stock (id), what stock they bought (name), cost of the share (cost), amount of the shares (shares), time of the transaction (time), and whether it was bought or sold (operation)
    public Stock(String name, Double cost, Integer shares, String operation, Date time) {
        this.name = name;
        this.cost = cost;
        this.shares = shares;
        this.time = time;
        // this.operation = operation;
    }

    // A custom getter to return cost of a transaction
    public double getTotalCost() {
        if (this.cost != null && this.shares != null) {
            return cost*(float)shares;
        }
        return -1;
    }

    // A custom getter to update total number of shares owned
    public double getTotalShares() {
        if (this.name != null && this.shares != null) {
            // this is placeholder for now, we should get existing shares and subtract
            return cost*(float)shares;
        }
        return -1;
    }

    // Initialize static test data 
    public static Stock[] init() {

        // basics of class construction
        Stock s1 = new Stock();
        s1.setName("AAPL");
        s1.setCost(188.91);
        s1.setShares(15);
        Date d;
        try {
            d = new SimpleDateFormat("MM-dd-yyyy").parse("02-06-2024");
            s1.setTime(d);
        } catch (ParseException e) {
            System.out.println("Date parse exception ======================");
            e.printStackTrace();
        }
        // p1.setOperation("buy"); <-- we can set this on frontend and adjust shares to + or -. If shares is 0 we assume update

        // Array definition and data initialization
        Stock stocks[] = {s1};
        return(stocks);
    }

    public static void main(String[] args) {
        // obtain Person from initializer
        Stock stocks[] = init();

        // iterate using "enhanced for loop"
        for( Stock stock : stocks) {
            System.out.println(stock);  // print object
        }
    }

}

FRQ 3: 2D Arrays/Sparse Arrays

Again, there weren't too many instances of using a 2D array in my side of the project, as when working with a database, dictionaries and hashmaps will do the trick much more efficiently. With that being said, refer to the following code segment, where I am creating a new hashmap called attributeMap containing the date of the entry as well as the value of each stock attribute that the user decides to purchase. This could be easily adapted into a 2D array, however, as seen in the code segment comments, it would be much MUCH more complicated.

            // Extract Attributes from JSON
            /* 2D array mockup for issue:
             * [[id, appl, amzn, cost, google, lmt, meta, msft, noc, tsla, unh, wmt]]
             * example:
             * [[1, 0, 1, 23, 0, 0, 0, 1, 2, 3, 4, 5], [2, 0, 1, 23, 0, 0, 0, 1, 2, 3, 4, 5], [3, 0, 1, 23, 0, 0, 0, 1, 2, 3, 4, 5]]
             * Now when getting the info, its MUCH harder to tell what I'm trying to get, as well as having to mess with the actual accessing of data being a nightmare, as not always will the UIDs be in perfect numerical order like this (e.g. if a user deletes their account)
            * /
            Map<String, Object> attributeMap = new HashMap<>();
            String[] stocks = {"AAPL", "AMZN", "COST", "GOOGL", "LMT", "META", "MSFT", "NOC", "TSLA", "UNH", "WMT"};

            for (Map.Entry<String,Object> entry : stat_map.entrySet())  {
                // Add all attributes other than "date" and "id" to the "attribute_map"
                if (!entry.getKey().equals("date") && !entry.getKey().equals("id")) {
                    // Handle each stock case
                    for (String stock : stocks) {
                        if (entry.getKey().equals(stock)) {
                            // String shares=String.valueOf(entry.getValue());
                            attributeMap.put(entry.getKey(), entry.getValue()); // Add stock attribute
                            break;
                        }
                    }
                    if (entry.getKey().equals("Balance")) {
                        // String shares=String.valueOf(entry.getValue());
                        attributeMap.put(entry.getKey(), entry.getValue()); // Add stock attribute
                        break;
                    }
                }
            }

FRQ 4: Interfaces

The last FRQ was about Java interfaces, and this was used quite a bit in our person and stock API. As I worked mostly on the stock API, the code segments will focus on that. As can be seen in the following code segment, this is an interface that extends the JPARepository class, defining multiple extremely useful functions that can be used when implementing the StockJpaRepository class, such as finding a stock by its name (findByName), ordering the stocks (findAllByOrderByNameAsc();), as well as a specifically implemented method helping us to find specific stocks by its registered admin email and password (findByEmailAndPassword).

public interface StockJpaRepository extends JpaRepository<Stock, Long> {
    Stock findByName(String name);

    List<Stock> findAllByOrderByNameAsc();

    // JPA query, findBy does JPA magic with "Name", "Containing", "Or", "Email", "IgnoreCase"
    List<Stock> findByNameContainingIgnoreCaseOrEmailContainingIgnoreCase(String name, String email);

    /* Custom JPA query articles, there are articles that show custom SQL as well
       https://springframework.guru/spring-data-jpa-query/
       https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods
    */
    Stock findByEmailAndPassword(String email, String password);

    // Custom JPA query
    @Query(
            value = "SELECT * FROM Person p WHERE p.name LIKE ?1 or p.email LIKE ?1",
            nativeQuery = true)
    List<Stock> findByLikeTermNative(String term);
    /*
      https://www.baeldung.com/spring-data-jpa-query
    */
}

Overall reflection

  • FRQ 1: This was probably the 2nd easiest FRQ on the test, as all it had to do was figure out how to add up values in an array. After solving part A, I could easily extrapolate it out to the remainder of the parts for an easy solution. The only part that required a bit more thinking was the last, section C. Taking a look at my code segments, you can see how I was able to use the knowledge of iteration through the lists in order to apply it over to the 2015 FRQ!

  • FRQ 2: This was also a pretty easy FRQ, as all it required me to do was implement a rudimentary version of the game "Wordle" which I have created before. The only challenge with this one was the sequence in which the if statements were ordered in. Had I not been careful and arbitrarily ordered the if statements, some conditions would have been triggered before others, and thus, mess up the output of the code. Additionally, the usage of classes in my PBL helped me get a solid understanding of the underlying code structure, saving me valuable time, as I don't have to think too hard about the pre-existing code and can jump straight into the ideation and implementation.

  • FRQ 3: This was the most difficult FRQ, yet it still wasn't too confusing to do. The FRQ just required a little critical thinking on how exactly to implement the deletion of a column while still preserving the value, and the solution to this was just to move the value over to an adjacent column. The challenge with this FRQ was figuring out how exactly to present the data to the reader of my blog. (how to implement extra methods to display data) While I didn't directly work with 2D arrays in my PBL, the knowledge of what would have happened in the case of using a 2D array helped me, as I was able to develop a clear mental image of 2D arrays and how to process it.

  • FRQ 4: This was the easiest FRQ by far, as it was just a checker to see if a number was between two other numbers. Add on the fact that I worked closely with interfaces through our PBL project, this FRQ was a breeze, and I had no trouble with it whatsoever!

This whole activity with the FRQs and reflection really helped me to see how exactly I am preparing for the AP exam! Its really reassuring knowing that for the FRQs I have been practicing them through my PBL, and I can see the results when doing the 2015 practice FRQ!

Project: Fearless

Fearless

Description: An app designed to detect allergens in restaurant menus, aiming to reduce the amount of allergic emergencies. Submitted for Congressional App Award 2023

Github Repo: privatized due to competition guidelines
Demo code video link: https://youtu.be/-_76Z--lpKU?t=116

Fearless (1)

2015 Practice Exam MCQ

image

Debrief

This test went much smoother for me, and you can see that in my score jumping from a 22 to a 31. This directly correlated with me working much more with the Javascript backend and studying the AP modules. Continuing to do this, I expect my score to continue to go up!
In addition, I can target the specific parts of the AP material that I have the weakest performance on, and taking a look at my skills and performance section, I know that I need to work on units 2, 7, 9, and 10.
image
I also was not entirely sure about my time management during that test. I did not time myself, so I didn't know if I spent too much or too little time on each question. next time, I will be sure to time my test and make sure that I am using the full testing period to have my answers.
As stated last time, one of my big weaknesses was trying to do everything in my head. This time, I took a sheet of paper and wrote out my thinking on it. This made it much easier for me to keep track of and process the information from the question, saving me from a lot of wrong answers. It also allowed me to go back and properly check my work based on the work I did for each question.

Corrections

Q3

image
What I did wrong: I assumed that the parent class (A) would take precedence over the subclass (B) and therefore would run the show function from the parent class
Why the answer is correct: The object was created of type B due to the new B(); clause. Therefore, the method in class B will be called, printing "B"

Q24

image
What I did wrong: I didn't understand this question at all, so I just guessed.
Why the answer is correct: Every code segment has a public void one with different arguments than the ones shown in the original code. This is allowed to compile. However, if you have a duplicate method name with duplicate arguments, we run into a compilation error.

Q27

image
What I did wrong: I misunderstood the code, not realizing that it would literally swap the elements with each other, rather than just move it to the front.
Why the answer is correct: When running the code on pass 1, we swap 6 with 1 giving us {1, 3, 2, 5, 4, 6}. On pass 2, we swap 3 with 2, giving us {1, 2, 3, 5, 4, 6}. On pass 3, we swap 5 with 4 giving us {1, 2, 3, 4, 5, 6}

Q29

image
What I did wrong: The value of 1 is only returned if num is a single-digit number, therefore it will not always be returned. I misunderstood the code here.
Why the answer is correct: The code will recursively call the function while using integer division, stripping the num until it has one digit. the resultant return values will be the number of digits in the decimal representation of num.

Q34

image
What I did wrong: I autopiloted towards having to subtract one from the size of an array without carefully looking through the for loop in the code.
Why the answer is correct: The code uses a less than, not a less than or equal to statement, to determine whether or not to get the value of a list. Therefore, there is no reason to subtract one, and subtracting one from the size of the arraylist will only result in skipping the last element.

Q35

image
What I did wrong: I skipped the while loop line, missing the (start <= end) conditional. Thus, I thought the code would automatically skip ahead to the return -1 if the value was not mid.
Why the answer is correct: The code will loop through until the (start <= end) conditional has been met. The first time it runs through, (target > data[mid]) is true, therefore start is set to 5. The second time it runs through, (target = data[mid]) is met. Because mid is now set to 5, the binary search will return a value of 5.

Q38

image
What I did wrong: I did not understand what the code was doing here so I guessed E.
Why the answer is correct: The answer choice C is correct because the recursive method starts at the end of the array numbers by setting numVals to numbers.length and checks to see if this element is the same as v, which is equal to the actual parameter val. If it is, it sets k to 1. The method recursively calls mystery, decrementing numVals by 1 each time. Once, numVals is equal to 1 the method checks to see if element 0 is equal to v and then the recursion is complete and k is returned. In each iteration, k will either be 1 or 0, based on whether the element is equal to v or not. The sum of all the values of k will be the return value of the original call to mystery.

Q39

image
What I did wrong: I wasn't well versed in the Java coding language enough, and thus, did not know that it was valid to use the students.set(k, "alex") clause.
Why the answer is correct: The first loop in the code segment prints out each student while then setting each value of set students to "Alex". The second time the list is printed out, every string within it is "Alex" and thus, will print out all alexes.

Key Indicators

P1, Ethan Zhao

  Score, Grader Verification Runtime Extras Key Indicators: Blog, GitHub File(s) and Key Commits
SASS hacks 0.99/1.00 Raunak Runtime None Committing the lesson and it's hacks
jQuery hacks 0.95/1 Theo Runtime None Committing the lesson and it's hacks
Thymeleaf hacks None, no lesson None, no lesson None, no lesson None, no lesson
SQL, HashMap hacks 0.8/1.0 Haseeb Runtime None Building the lesson pages with the hacks included
JWT hacks 0.9/1.0 Kevin Du Runtime None Uploading the lesson and it's hacks, Diagram for JWT, JWT hacks issue
CORS, dotEnv, Exploits hacks 1.0/1.0 Our Lesson Runtime Creating a fake phishing website - I created a fake phishing site in order to show how important it is to watch the links that you click on. It served as a great way to add interaction into the lessons and engage the class before we started our talk. Creation of fake phishing link, Creation of lessons was sent as text over discord and commited by David
CB Quiz 1.81/2.00 - 31/39 Issue of missed questions N/A N/A
Totals Median Score: 0.95 Number complete: 6 Extra effort count: 1 Key commit count: 7

Review

Fibonacci!

I created the whole of the Fibonacci frontend and backend.

At first, I thought this part of the project would be pretty easy, as it was just creating algorithms to generate a fibonacci list. However, as I progressed, I realized that I needed to learn a lot of things I previously didn't know about Java. For example streams:

Streams learning

public class FibonacciStream extends Fibonacci {
    public ArrayList<Integer> FibonacciStream(int nth) {
        return Stream.iterate(new int[]{1, 1}, fib -> new int[]{fib[1], fib[0] + fib[1]})
                .limit(nth)
                .map(fib -> fib[0])
                .collect(Collectors.toCollection(ArrayList::new));
    }
}

Before this project, I would not be able to tell you what this code did. However, now I can explain the whole thing. We are returning an ArrayList of length nth, where we generate the ArrayList with two integers in the 0 and 1 slots. These will be initialized as 1 and 1. We then generate new items in the list by creating additional ArrayLists that combine the elements of the previous list by adding them with each other. At the end, we collect all the arrays together into one big ArrayList, returning it to the API.

Inheritence within fibo

Here's the fibonacci parent class

package com.nighthawk.spring_portfolio.mvc.fib;
import java.util.ArrayList;

public class Fibonacci {
    public String toStringArr(ArrayList fib) {
        int n = fib.size();
        String array = "";
        for (int i = 0; i < n; i++) {
             array = array + fib.get(i) + " ";
        }
        return array;
    }
}

and an example of one of the individual methods, inheriting the toStringArr abstraction method

package com.nighthawk.spring_portfolio.mvc.fib.fiboAlgorithms;

import java.util.ArrayList;

import com.nighthawk.spring_portfolio.mvc.fib.Fibonacci;

public class FibonacciWhile extends Fibonacci {
    public ArrayList<Integer> FibonacciWhile(int nth) {
        ArrayList<Integer> fib = new ArrayList<>();
        int i=0;
        while (i<nth) {
            if (i == 0) {
                fib.add(1);
            } else if (i == 1) {
                fib.add(1);
            } else {
                fib.add(fib.get(i - 2) + fib.get(i - 1));
            }
            i++;
        }

        return fib;
    }
}

Request API objects

The Fibonacci request controller

package com.nighthawk.spring_portfolio.mvc.fib;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@NoArgsConstructor
@AllArgsConstructor
@ToString
@Data
public class FibRequest {
    private int length;
}

The Fibonacci API controller

package com.nighthawk.spring_portfolio.mvc.fib;

import java.util.ArrayList;

import org.json.simple.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.nighthawk.spring_portfolio.mvc.fib.fiboAlgorithms.FibonacciFor;
import com.nighthawk.spring_portfolio.mvc.fib.fiboAlgorithms.FibonacciRecursive;
import com.nighthawk.spring_portfolio.mvc.fib.fiboAlgorithms.FibonacciStream;
import com.nighthawk.spring_portfolio.mvc.fib.fiboAlgorithms.FibonacciWhile;

@RestController
@RequestMapping("/api/fib")
public class FibonacciApiController {
    private JSONObject body; // last run result
    private HttpStatus status; // last run status
    String last_run = null; // last run day of month

    @GetMapping("/fibFor")
    public ResponseEntity<ArrayList<Integer>> getFibonacciFor(@RequestBody FibRequest request) {
        int startTime = (int)System.currentTimeMillis();

        int length = request.getLength();
        FibonacciFor fibonacciFor = new FibonacciFor();
        ArrayList<Integer> fibonacciSeries = fibonacciFor.FibonacciFor(length);
        System.out.println(fibonacciFor.toStringArr(fibonacciSeries));
        int endTime = (int)System.currentTimeMillis();
        int elapsedTime = endTime - startTime;
        fibonacciSeries.add(elapsedTime);

        return new ResponseEntity<>(fibonacciSeries, HttpStatus.OK);
    }

    @GetMapping("/fibRecursive")
    public ResponseEntity<ArrayList<Integer>> getFibonacciRecursive(@RequestBody FibRequest request) {
        int startTime = (int)System.currentTimeMillis();

        int length = request.getLength();
        FibonacciRecursive fibonacciRecursive = new FibonacciRecursive();
        ArrayList<Integer> fibonacciSeries = fibonacciRecursive.FibonacciRecursive(0, length);
        System.out.println(fibonacciRecursive.toStringArr(fibonacciSeries));
        int endTime = (int)System.currentTimeMillis();
        int elapsedTime = endTime - startTime;
        fibonacciSeries.add(elapsedTime);

        return new ResponseEntity<>(fibonacciSeries, HttpStatus.OK);
    }

    @GetMapping("/fibStream")
    public ResponseEntity<ArrayList<Integer>> getFibonacciStream(@RequestBody FibRequest request) {
        int startTime = (int)System.currentTimeMillis();

        int length = request.getLength();
        FibonacciStream fibonacciStream = new FibonacciStream();
        ArrayList<Integer> fibonacciSeries = fibonacciStream.FibonacciStream(length);
        System.out.println(fibonacciStream.toStringArr(fibonacciSeries));
        int endTime = (int)System.currentTimeMillis();
        int elapsedTime = endTime - startTime;
        fibonacciSeries.add(elapsedTime);

        return new ResponseEntity<>(fibonacciSeries, HttpStatus.OK);
    }

    @GetMapping("/fibWhile")
    public ResponseEntity<ArrayList<Integer>> getFibonacciWhile(@RequestBody FibRequest request) {
        int startTime = (int)System.currentTimeMillis();

        int length = request.getLength();
        FibonacciWhile fibonacciWhile = new FibonacciWhile();
        ArrayList<Integer> fibonacciSeries = fibonacciWhile.FibonacciWhile(length);
        System.out.println(fibonacciWhile.toStringArr(fibonacciSeries));
        int endTime = (int)System.currentTimeMillis();
        int elapsedTime = endTime - startTime;
        fibonacciSeries.add(elapsedTime);

        return new ResponseEntity<>(fibonacciSeries, HttpStatus.OK);
    }
}

Sorting!

I worked on selection sort for the sorting. I only worked on one sort due to me doing the other half of the project completely by my self. Using the animation methods Alex wrote, I built my selection sort around it. This project allowed me to gain a deeper understanding of the innerworkings of Selection sort, allowing me to understand this sorting algorithm and allow for future application into my projects. In addition, this entire project helped me to gain a much deeper understanding of Java and will definitely prepare me well for the AP test!

package com.nighthawk.spring_portfolio.mvc.sorting.SortingAlgorithms;

import java.util.ArrayList;
import java.util.HashMap;

import com.nighthawk.spring_portfolio.mvc.sorting.SortingAnimationGenerator;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@NoArgsConstructor
@AllArgsConstructor
@ToString
@Data
public class SelectionSort extends SortingAnimationGenerator {
	private ArrayList<HashMap<String, ArrayList<Integer>>> animations;
	public boolean sorted = false;

	public SelectionSort(int length, ArrayList<Integer> array) {
		super(length, array);
		animations = new ArrayList<>();
		long start = System.nanoTime();
		addAnimationEntry(new ArrayList<>(arr), -1, -1);
		this.SelectionSortAnimation();
		addAnimationEntry(new ArrayList<>(arr), -1, -1);
		long end = System.nanoTime();
		Integer elapsedTime = (int) (end - start);
		HashMap<String, ArrayList<Integer>> animationTime = new HashMap<>();
		ArrayList<Integer> timeValue = new ArrayList<>();
		HashMap<String, ArrayList<Integer>> animationSwaps = new HashMap<>();
		ArrayList<Integer> swapsValue = new ArrayList<>();
		swapsValue.add(this.swaps);
		animationSwaps.put("swaps", swapsValue);
		animations.add(animationSwaps);
		timeValue.add(elapsedTime);
		animationTime.put("time", timeValue);
		animations.add(animationTime);
	}

	public void addAnimationEntry(ArrayList<Integer> sortedArr, int num, int move) {
		HashMap<String, ArrayList<Integer>> animationEntry = new HashMap<>();
		ArrayList<Integer> integer = new ArrayList<>();
		animationEntry.put("arr", new ArrayList<>(sortedArr));
		integer.add(num);
		integer.add(move);
		animationEntry.put("int", integer);
		animations.add(animationEntry);
		this.swaps++;
	}

	public ArrayList<HashMap<String, ArrayList<Integer>>> getAnimations() {
		return animations;
	}

	public void SelectionSortAnimation() {
		if (!sorted) {
			selection();
		}
	}

	public void selection() {
		int n = arr.size();
		int i, j, temp;
		boolean swapped;

		for (i=0; i < n - 1; i++) {
			swapped = false;
			int min_idx = i;
			for (j = 0; j < n - i - 1; j++) {
				if (arr.get(j) > arr.get(min_idx)) {
					min_idx = j;
				}
				temp = arr.get(min_idx);
				arr.set(min_idx, arr.get(i));
				arr.set(i, temp);
			}

			if (!swapped) {
				addAnimationEntry(arr, i, j + 1);
				break;
			}
		}
		sorted = true;
	}
}

Request controller:

package com.nighthawk.spring_portfolio.mvc.sorting;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.ArrayList;

@NoArgsConstructor
@AllArgsConstructor
@ToString
@Data
public class SelectionRequest {
    private int length;
    private ArrayList<Integer> array;
}

API controller

@PostMapping("/selection")
    public ResponseEntity<ArrayList<HashMap<String, ArrayList<Integer>>>> getHeapAnimations(@RequestBody SelectionRequest request) {
        int length = request.getLength();
        ArrayList<Integer> array = request.getArray();
        SelectionSort selectionSort = new SelectionSort(length, array);
        System.out.println(selectionSort.toStringArr());
        return new ResponseEntity<>(selectionSort.getAnimations(), HttpStatus.OK);
    }

JWT Implementation proof

Postman:
Screen Shot 2023-12-25 at 12 28 23 AM

JPA repo:
Screen Shot 2023-12-25 at 12 33 24 AM

code for JWT:

package com.nighthawk.spring_portfolio.mvc.jwt;

import java.io.IOException;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
// import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.nighthawk.spring_portfolio.mvc.dolphin.DolphinDetailsService;

import io.jsonwebtoken.ExpiredJwtException;

@Component
public class JwtRequestFilter extends OncePerRequestFilter {

	@Autowired
	private DolphinDetailsService dolphinDetailsService;

	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

		final Cookie[] cookies = request.getCookies();
		String username = null;
		String jwtToken = null;
		// Try to get cookie with name jwt
		if ((cookies == null) || (cookies.length == 0)) {
			logger.warn("No cookies");
		} else {
			for (Cookie cookie: cookies) {
				if (cookie.getName().equals("jwt")) {
					jwtToken = cookie.getValue();
				}
			}
			if (jwtToken == null) {
				logger.warn("No jwt cookie");
			} else {
				try {
					// Get username from the token if jwt cookie exists
					username = jwtTokenUtil.getUsernameFromToken(jwtToken);
				} catch (IllegalArgumentException e) {
					System.out.println("Unable to get JWT Token");
				} catch (ExpiredJwtException e) {
					System.out.println("JWT Token has expired");
				} catch (Exception e) {
					System.out.println("An error occurred");
				}
			}
		}
		// If no cookies have name jwt return warning

		// Once we get the token validate it.
		if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

			UserDetails userDetails = this.dolphinDetailsService.loadUserByUsername(username);

			// if token is valid configure Spring Security to manually set
			// authentication
			if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {

				UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
				usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
				// After setting the Authentication in the context, we specify
				// that the current user is authenticated. So it passes the
				// Spring Security Configurations successfully.
				SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
			}
		}
		chain.doFilter(request, response);
	}
}

Weekly Plan 2

Todo


  • Brainstorm mini project to cover the JS hacks presented on teacher site
    • JS API: Utilize external API to print motivational quotes at the top of the page.
    • JS Input: Utilized input boxes and adding new elements onto the document.
      • Do something extra, have the program detect whenever a new table row is completed, then add on a new row with comment boxes. Scan the new row for completion
    • JS Output using jQuery: Implement a dataTable embed using jQuery, allow for column sorting, multiple pages, and searching
    • JS Storage using localStorage: Use the localStorage feature in modern browsers to store persistent user data for the user
      • Auto-generate the existing user data from JSON stored in localStorage
    • Project would simulate the old CSP project we created last year. Just more lightweight and implemented into the blog
  • Record video timelapse showing collaboration on project
  • Utilizing technology such as live share to facilitate group collaboration and peer programming
  • Stylize the todo list using CSS

Bugs


  • localStorage would not properly store user data
    • fixed, bad semicolon.
  • Bad starting index for table
    • fixed, stored index_count in localStorage
  • jQuery dataTable would not render properly, adds additional "No data in table" row in table even when data is present
    • Table structure was bad, new rows were being added to <thead> element instead of <tbody>. Locating this element fixed the issue.
  • Todo list would not render properly on Github pages, Jekyll rendering is bad
    • The todo list had JS comments in the code which commented out the rest of the program. Comment was removed in order for program to work as everything in the script tag was interpreted as one line

FRQ mini lab issue

FRQ

I got a 9/9 on the lab, so I didn't have anything to correct. Thus, I created these graphics to show my thinking and how I arrived at my answer:

For part A:

Screen Shot 2023-09-20 at 10 20 12 AM

For part B:

Screen Shot 2023-09-20 at 10 25 36 AM

Overall Plan for CSA AI Project Final Sprint

Overall Plan for CSA AI Project Final Sprint

To Dos (Total 31 Scrum Points) - (31/31)

  • RDS - (18)
    • RDS blog - (3)
    • Create example RDS mini project (because RDS connection with the main project is unfeasible). - (9)
    • Create template RDS project for future teams to use (6)
  • Frontend Development/connection with backend - (7)
  • Backend leaderboard database help - (3)
  • Python LSTM (3)
    • Data collection (2)
    • Debugging (1)

Goals

  • Create a RDS project template for future years to use
  • Create a RDS blog that allows people to adapt their projects to use RDS
  • Get at least 1 team to try and switch their project to use RDS

Visual Timeline

CSA-AI Final Sprint

Detailed Timeline Table

Date Task
05/20 RDS Work
05/21 RDS Work, Python API call to YFinance
05/22 RDS Work, Debug errors
05/23 ****RDS Blog should be done, Dev Ops integration
05/24 RDS Work, Sync up with others
05/25 ****Python LSTM DONE
05/26 RDS Work
05/27 ****RDS Demo project should be done
05/28 RDS Work, Frontend Connections
05/29 ****RDS template project should be done
05/30 Frontend Connections, Backend Database help
05/31 Frontend Connections, Backend Database help
06/01 Debugging/Testing
06/02 Debugging/Testing
06/03 Debugging/Testing
06/04 Final Project Demo
06/05 No CSA this day
06/06 No CSA this day

Work to show:

05/27 Review:

  • RDS Blog
  • RDS Example Project

Pre N@TM Review

  • CSA-AI project
  • Template RDS Project

N@TM

  • RDS Example Project
  • Main CSA AI Project

Student Lessons

Screen Shot 2023-11-03 at 8 59 11 AM

Created almost the entire lesson myself (The lesson plan itself, all the hacks, presentation were only time not done completely by myself). Spent multiple hours studying college board material, converting it into my own lesson.

AP Computer Science A 2014 Practice MCQ

Screen Shot 2023-11-06 at 8 50 21 AM

  • Integer division won't return a float! Remember type casting

Screen Shot 2023-11-06 at 8 56 59 AM

  • Case I would initialize with default parameters, so case I would also work.

Screen Shot 2023-11-06 at 9 03 59 AM

  • The code is printing k instead of arr[k] be careful!

Screen Shot 2023-11-06 at 9 06 05 AM

  • Case II would return an index out of bounds error so it doesn't work properly

Screen Shot 2023-11-06 at 9 06 05 AM

  • I didn't fully understand the question. It's asking for inserting the element right after the previous one, meaning we need to insert it at the array position. that the previous element was at +1

Screen Shot 2023-11-06 at 9 11 48 AM

  • The loop "feeds" itself, I can explain more in words

Screen Shot 2023-11-06 at 9 15 06 AM

  • Study Boolean laws more! Apply De Morgan’s Law

Screen Shot 2023-11-06 at 9 16 34 AM

  • Again, this is a type casting issue. The types in the array are strictly Book, so the method will not work.

Screen Shot 2023-11-06 at 9 18 00 AM

  • Computational error on my end. Just write it out on paper next time

Screen Shot 2023-11-06 at 9 19 40 AM

  • We go down the ROWS first (as collumns), and then go down the COLLUMNS (as rows)

Screen Shot 2023-11-06 at 9 20 54 AM

  • Knowing the dimensions of a box would natrually let you know wether or not it fits. Thus, Case I works.

Screen Shot 2023-11-06 at 9 22 46 AM

  • Again a computational error. The code segmenet will print out 25 elements divisiable by 4. The one I selected only prints out 25 elements. Be careful!

Screen Shot 2023-11-06 at 9 23 46 AM

  • Computational error. Just use paper pleasee!!!

Screen Shot 2023-11-06 at 9 25 37 AM

  • Again, use paper to write it out

Screen Shot 2023-11-06 at 9 27 10 AM

  • Boolean laws. If one of the two is true, the loop continues. K never changes, so the 2nd conditional is always true.

Screen Shot 2023-11-06 at 9 28 56 AM

  • Computational Error, write out!!

Screen Shot 2023-11-06 at 9 30 50 AM

  • Review boolean laws!

Screen Shot 2023-11-06 at 9 31 32 AM

  • Write out on paper

Debugging Event

screen capture HashMap or other data Object

Screen Shot 2024-03-07 at 9 19 37 AM

screen capture capturing break point and Data

Screen Shot 2024-03-07 at 9 25 10 AM

Changes reflected in frontend

Screen Shot 2024-03-08 at 9 12 38 AM

N@TM: Tri 2 reflection

Testing data:

Throughout our N@TM, we were hard at work collecting testing data for our future customers and players of the stock AI game.
image
As can be seen by the image above, there were many people who came and tried their luck with predicting the outcomes of stocks 2 months into the future. When N@TM rolls around again, our they will be competing against our AI to see how accurate they are!

Feedback:

We got a lot of feedback on our project, and from a lot of extremely knowledgeable people! Many students came up to us and pointed out some small details, such as the lack of styling on our prediction page and the uneasiness of the signup page, all features which we hope to fix. The definite highlight of the evening though was our talk with Anthony's dad Professor Bazhenov. Here is a picture you can see of me explaining our project to him!
image
Here is another image of our team talking to some interested students!
image
And another one with Mr. Mortensen!
image

Reflection

Glow:

  • VERY good presentation, and I think we impressed a lot of people!
  • I was supprised how smoothly our project ran, even though we were split very thin amongst 2 periods only meeting twice a week
  • A lot of people were intrigued with our LSTM model, but....

Grows:

  • Not very many "layman" people were engaged, as they didn't really understand what was going on behind the flying numbers and letters of the LSTM model.
  • This was compounded by the fact that there was a lack of appealing styling on the front page
  • Our model was a bit slow/inaccurate, but this was expected and we are already well on our way to fixing it!

A lot of other projects were showcased, and the one that caught my eye the most was the Mario game. Especially after learning about the company like scenario that was put into place by Mr. Mortensen in his CSSE class, I was extremely impressed by just how smoothly and well put together the whole project was!
image

Quick Quiz

Ethan Zhao (3.55)

Show JWT sign up or login process (split browser between inspect and the normal way, cookie with login page) (0.9)

Screen Shot 2024-01-30 at 8 48 34 AM

Explain a POJO change (0.9)

A POJO stands for Plain Old Java Object, and is a generic class that can be adapted to different use cases. A POJO change is changing the generic POJO into its specific use case

Image showing a POJO:
Screen Shot 2024-01-30 at 8 55 02 AM

Show a docker update process (0.9)

Screen Shot 2024-01-30 at 9 27 36 AM

Show API access code on a redirect to 403 (0.85)

Screen Shot 2024-01-30 at 9 28 49 AM
Screen Shot 2024-01-30 at 9 30 32 AM

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.