<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Joseph Lee on Medium]]></title>
        <description><![CDATA[Stories by Joseph Lee on Medium]]></description>
        <link>https://medium.com/@joeylee08?source=rss-bd73868e3155------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*wA7H-VCbcSO3Dmm1</url>
            <title>Stories by Joseph Lee on Medium</title>
            <link>https://medium.com/@joeylee08?source=rss-bd73868e3155------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:07:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joeylee08/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Transcending Syntax: Languages vs Concepts in Coding]]></title>
            <link>https://medium.com/@joeylee08/transcending-syntax-programming-languages-vs-concepts-ccc79944b59c?source=rss-bd73868e3155------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccc79944b59c</guid>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Joseph Lee]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 18:33:35 GMT</pubDate>
            <atom:updated>2024-01-29T12:20:10.954Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*SrzHM0mJq--WCp_evEDy_w.png" /></figure><p>In the sixties, there were two related literary movements called Structuralism and Deconstruction. Structuralism explored the idea of words and language being a manmade system of signs and symbols tied to specific abstract concepts. Deconstruction took this one step further and suggested that these words or symbols can only hold value within a complex network of mutual deferred meaning: a word can only be understood in terms of its relationship to other words, and no meaning can exist independently of that system. Which makes sense. What is a cat? It’s an animal. What is an animal? It’s a mammal with four legs. What is a mammal? Warm blooded. What is warm? What is blood? What is is? You struggle so hard to communicate what a cat is using language, all you can do is point to a cat and grunt.</p><p>The idea that kicked all of this off was that words are separate from the concepts they represent. Now to apply this pretentious knowledge to programming. Many beginning programmers often ask questions like, ‘Which programming language should I learn?’ or ‘Is Javascript harder than Python?’ First of all, the answers to those questions are ‘Python’ and ‘yes’. Secondly, what they are failing to understand is that a programming language is simply a specific syntax for generally ubiquitous concepts. Although this becomes more clear with time, a lot of programming concepts exist beyond the boundaries of one language, and each language simply has its own slightly different syntactical implementation of that programming concept.</p><p>We are not only learning programming syntax, we are using our chosen programming language to learn programming concepts.</p><p>Here’s the difference.</p><p><strong>Programming Syntax:</strong></p><pre>//javascript<br><br>const myArray = [1, 2, 3]<br>myArray.push(4)</pre><pre>#python<br><br>my_list = [1, 2, 3]<br>my_list.append(4)</pre><p><strong>Programming Concept: Add an element to a collection of ordered, indexed elements.</strong></p><p>Here’s another example:</p><p><strong>Programming Syntax:</strong></p><pre>//javascript<br><br>const myObject = {<br>  &#39;name&#39;: &#39;Joseph&#39;,<br>  &#39;height&#39;: &#39;6.2 feet&#39;,<br>  &#39;likes&#39;: [&#39;pizza&#39;, &#39;dogs&#39;, &#39;coffee&#39;, &#39;music&#39;]<br>}<br><br>const myKeys = Object.keys(myObject)<br><br>//python<br><br>my_dictionary = {<br>  &#39;name&#39;: &#39;Joseph&#39;,<br>  &#39;height&#39;: &#39;6.2 feet&#39;,<br>  &#39;likes&#39;: [&#39;pizza&#39;, &#39;dogs&#39;, &#39;coffee&#39;, &#39;music&#39;]<br>}<br><br>my_keys = my_dictionary.keys()</pre><p><strong>Programming Concept: Create a collection of key-value pairs, where each key is associated with a corresponding value. Then use a method to obtain a collection of the keys only.</strong></p><p>Going back to our first example, the programming concept of a collection of sequenced and indexed data is called different things depending on the language. Javascript calls it an array and Python calls it a list, but they both mean the same thing.</p><p>The concepts of adding an item to the end of the collection and generally manipulating these collections are also present in both of these languages. Both languages use for loops, while loops, strings, lists, dictionaries, callback functions, recursion, object oriented and class based instantiation, and much more.</p><p>Remember, the important thing is not to memorize specific syntax, but to become familiar with the programming concepts behind it. Once you adopt this mindset, then you will not only become more appreciative of the beauty and universality of programming, you will likely feel more empowered and ready to learn any new programming language that comes your way, because you would simply be adjusting your syntactic framework for concepts you have already been using.</p><p>Let’s take a famous coding challenge problem, Two Sum.</p><p>Question: Given an array of integers and a target integer, return indices of the two numbers in the array such that they add up to target.</p><pre>//javascript<br><br>function twoSum(nums, target){<br>  return<br>}<br><br>twoSum([1, 2, 3, 4], 6) // [2, 4]</pre><pre>#python<br><br>def two_sum(nums, target):<br>    pass<br><br>twoSum([1, 2, 3, 4], 6) // [2, 4]</pre><p>You are asking, should I solve this in Javascript or Python? Both? Which one first? Well, the answer is neither! We are going to pseudo code this problem in old fashioned people-speak. Yes, if you aren’t familiar with what psuedo coding is, it is basically using words to write out the steps you would take to solve a problem. So let’s go ahead and write out the steps we need to take, in plain English, to solve this Two Sum problem.</p><p>Note: There is definitely the nested-loop version of the solution that checks through every possible combination. Today we are going to implement a slightly more slick version of the solution.</p><pre>1. Sort the given collection of numbers nums in ascending order.<br><br>2. Create two variables to represent collection indexes. We can call them <br>   i and j. We set i to 0 and set j to the last index of the collection.<br><br>3. Create a while loop that continues while (i &lt; j).<br><br>4. Inside the while loop, if nums[i] + nums[j] equals target, then return <br>   a collection of [i, j] as the result.<br><br>5. Else, if the sum of nums[i] and nums[j] does not equal the target, <br>   check if that sum is either greater than or less than the target.<br><br>6. If the sum is greater than the target, decrement j by 1.<br><br>7. If the sum is less than the target, increment i by 1.<br><br>8. The loop will continue moving inward towards the center of the <br>   collection until the target sum is found.</pre><p>We just ran through a coding problem without using any programming syntax. We simply understood the abstract processes needed to accomplish our tasks.</p><p>Try it out for yourself, in any programming language.</p><p><a href="https://leetcode.com/problems/two-sum/">https://leetcode.com/problems/two-sum/</a></p><p>Remember, don’t feel intimidated by the idea of having to learn new technologies. Learn one well, and trust that you will pick things up when you need. Don’t spread yourself too thin and try to learn too many new languages at once. Focus on obtaining proficiency in one language, and use that language to learn and practice a variety of programming concepts.</p><p>They always say that your second programming language is easier to pick up, or maybe the first is the worst. From my experience, that is absolutely true. Once you understand all the basic, important programming concepts, learning a new language is simply about memorizing the specific syntax.</p><p>Just pick a popular language and use it as your gateway into programming. The path will become more visible as you walk it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccc79944b59c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code Challenges: Train Your Brain]]></title>
            <link>https://medium.com/@joeylee08/code-challenges-train-your-brain-387b9f8cbb8e?source=rss-bd73868e3155------2</link>
            <guid isPermaLink="false">https://medium.com/p/387b9f8cbb8e</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joseph Lee]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 19:31:06 GMT</pubDate>
            <atom:updated>2024-01-29T12:24:37.378Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LxQrps3gVt0SQmItmQOlvQ.png" /></figure><p>Code challenges are the unsung heroes of your coding education and job search. While you most likely won’t be solving programming puzzles throughout your professional day, code challenges are still important to your growth as a programmer. As a software developer, you most likely won’t need to solve: ‘n’ prisoners are standing in a circle… which one of them yells at his wife? That said, code challenges are a fantastic way to sharpen your problem solving skills and achieve mastery of programming syntax.</p><p>So, this blog will address some common code challenges and present a 5 step problem-solving schema that can be applied to many areas of your programming life.</p><p>Step 1: Identify the Problem.<br>Step 2: Identify your Input(s).<br>Step 3: Determine your Output(s).<br>Step 4: Pseudocode, Pseudocode, Pseudocode<br>Step 5: Identify Potential Edge Cases<br>Step 6: Ready, Set, Code!</p><p><strong>So, let’s try applying this question to a simple Javascript problem.</strong></p><p><strong>Question #1: Given an array of numbers, return the sum of all numbers in that array.</strong></p><ol><li>Identify the Problem. We are asked to return the sum of an array.</li></ol><pre>function arraySum(array) {<br>  let result = 0;<br>  return result<br>}</pre><p>2. Identify your Input(s). In this case we have an array.</p><p>3. Identify your Output(s). In this case it will be a single integer.</p><p>4. Pseudocode, Pseudocode, Pseudocode.</p><p>Pseudocoding is an important and often underutilized problem-solving technique. Pseudocoding is basically a way of writing out your steps in plain English. It provides a roadmap or logical framework for addressing each step of your algorithm.</p><pre>1. The result will be a single number, so create a variable of a number<br>   type and initialize that value to zero.<br><br>2. We need a loop to access each subsequent item in the array.<br><br>3. Increase our result sum by each iterated value.<br><br>4. Return the result.</pre><p>5. Identify Potential Edge Cases. What if we are passed an object instead of an array? What if we are passed a string? You should be mindful of potential edge cases and implement handling in your code, accordingly.</p><p>6. Ready, Set, Code!</p><pre>function arraySum(array) {<br>  let result = 0;<br>  for (let num in array) {<br>    result += num;<br>  }<br>  return result;<br>}<br><br>arraySum([1, 2, 3, 4, 5]) // 15</pre><p><strong>While there are fancy and slick methods like </strong>.reduce()<strong> that will perform this function for you, it is always good to understand how these work under the hood.</strong></p><p>Now, let’s try a slightly more complex problem.</p><p><strong>Question #2: Given a string, determine if that string is a palindrome.</strong></p><p><em>Note: A palindrome is not some kind of elephant. A palindrome is a word that is spelled the same forwards and backwards.</em></p><ol><li>Identify the Problem.</li></ol><pre>function isPalindrome(string) {<br>  return<br>}</pre><p>2. Identify your input(s). The input will be string type. Therefore we will need to implement the appropriate string methods in order to properly manipulate our data.</p><p>3. Identify your output(s). We are asked to determine if a given string is or is not a palindrome. Ergo, our return value will be either true or false.</p><p>4. Pseudocode, Pseudocode, Pseudocode</p><pre>1. Split the string into an array of individual characters.<br><br>2. Create an empty string to store the reversed string.<br><br>3. Iterate backwards through the array of characters and append each item<br>   to the front of the empty result string. This has to be done in reverse <br>   so that our test string will be a reversed version of the original.<br><br>4. Join the array of characters back into a now-reversed string.<br><br>5. Test for equality between the original and the new, reversed string.<br><br>6. Return true or false depending on the equality check.</pre><p>5. Identify potential edge cases. Do we need to account for capital letters? What about spaces? You can implement methods like .toLowerCase() to rule out capitalization discrepancies, and leverage regular expressions to filter out whitespaces.</p><p><strong>Ready to code this out? Here we go!</strong></p><pre>function isPalindrome(string) {<br>  let result = &quot;&quot;;<br><br>  let split = string.split(&quot;&quot;);<br><br>  for (let i = split.length - 1; i &gt;= 0; i--) {<br>    result += split[i]<br>  }<br><br>  return result === string;<br>}</pre><p><em>One final note: All algorithms have a time and complexity value that determines how efficiently it runs and how much space it requires. You should always aim to make your algorithm as simple and efficient as possible. Complicated algorithms that operate on large amounts of data and use multiple, sometimes nested, iterators will have a higher time and space complexity value than basic functions that accept and return simple values without much looping involved. This system for measuring time and space complexity is called Big O Notation. You can read more about it here:</em></p><p><a href="https://www.freecodecamp.org/news/learn-big-o-notation/">https://www.freecodecamp.org/news/learn-big-o-notation/</a></p><p>This was a basic look at a systematic framework for solving coding challenges. While most developers do not do many coding challenges in their day to day professional life, code challenges are a fantastic way to stretch your problem solving skills, deepen your understanding of programming concepts, and expand your current skill set.</p><p><strong>Here are a few additional resources where you can explore this topic further and get your hands dirty with some coding challenges.</strong></p><p><a href="https://leetcode.com/">https://leetcode.com/</a></p><p><a href="https://www.hackerrank.com/">https://www.hackerrank.com/</a></p><p><a href="https://www.codewars.com/">https://www.codewars.com/</a></p><p>The aforementioned problem-solving schema can also be applied to other areas of your programming life. Having a solid game plan for tackling problems will play a major role in how effectively you write your code. Good luck, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=387b9f8cbb8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Relational Mapping: From Python to SQL and Back]]></title>
            <link>https://medium.com/@joeylee08/object-relational-mapping-from-python-to-sql-and-back-cd629eca0060?source=rss-bd73868e3155------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd629eca0060</guid>
            <category><![CDATA[object-relational-mapping]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Joseph Lee]]></dc:creator>
            <pubDate>Wed, 08 Nov 2023 07:31:42 GMT</pubDate>
            <atom:updated>2024-01-23T19:48:46.075Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CERiRc8tNSKiYZ1J7e-Xbw.png" /></figure><p>As an up-and-coming programmer, you may have heard others discussing ORMs. Apart from being a fancy-sounding acronym that makes the user feel smart, what exactly is an ORM? ORM stands for ‘object relational mapping’, which basically the process of taking data from a Python object [aka class instance] and<strong> converting it into a table row format to be stored inside a SQL database.</strong></p><p>Conversely, ORM is also used to query table data from a SQL database and <strong>convert it into an object instance to be used in Python code.</strong></p><p>Does this sound intimidating? Lucky for us, it is not! While Python objects and SQL table rows may look completely different at first glance, they both follow a similar schema for storing data.</p><p>Let’s walk through an example together. This will require some pre-existing knowledge about how OOP and classes work. If you need to review this information, <a href="https://dev.to/ogwurujohnson/creating-and-instantiating-a-simple-class-in-python-79b">here is a fantastic blog post</a> on the topic.</p><p>Okay. Ready to dive into our example?</p><p>Great!</p><p>Say we have a Python class called Pet. All objects instantiated from the Pet class will possess a pre-defined set of attributes. For the sake of our example, let’s say that every Pet instance will have the attributes name, species, age, weight, and favorite_food. We can use our Python class to create [instantiate] several different pets and assign them unique values for each of these attributes.</p><pre>class Pet:<br>    def __init__(self, name, species, age, weight_in_kg, favorite_food):<br>        self.name = name<br>        self.species = species<br>        self.age = age<br>        self.weight_in_kg = weight_in_kg<br>        self.favorite_food = favorite_food<br><br>pet_1 = Pet(&#39;Pocket&#39;, &#39;dog&#39;, 3, 22.5, &#39;Kibbles &amp; Bits&#39;)<br>pet_2 = Pet(&#39;Mittens&#39;, &#39;cat&#39;, 7, 8.0, &#39;Fancy Feast: Salmon Edition&#39;)<br>pet_3 = Pet(&#39;Mrs. Birdy III&#39;, &#39;bird&#39;, 22, 0.5, &#39;Froot Loops&#39;)</pre><p>If you were to print() each of these objects as a dictionary using vars(), you would see the following data structures:</p><pre>#pet_1<br>{<br>    &#39;name&#39;: &#39;Pocket&#39;,<br>    &#39;species&#39;: &#39;dog&#39;,<br>    &#39;age&#39;: 3,<br>    &#39;weight_in_kg&#39;: 22.5,<br>    &#39;favorite_food&#39;: &#39;Kibbles &amp; Bits&#39;<br>}<br><br>#pet_2<br>{<br>    &#39;name&#39;: &#39;Mittens&#39;,<br>    &#39;species&#39;: &#39;cat&#39;,<br>    &#39;age&#39;: 7,<br>    &#39;weight_in_kg&#39;: 8.0,<br>    &#39;favorite_food&#39;: &#39;Fancy Feast: Salmon Edition&#39;<br>}<br><br>#pet_3<br>{<br>    &#39;name&#39;: &#39;Mrs. Birdy III&#39;,<br>    &#39;species&#39;: &#39;bird&#39;,<br>    &#39;age&#39;: 22,<br>    &#39;weight_in_kg&#39;: 0.5,<br>    &#39;favorite_food&#39;: &#39;Froot Loops&#39;<br>}</pre><p>If we were to take this same data and display it as a SQL table, the table name would be ‘pets’, and the rows would look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*Z1QZmDgcSyd9cwkPNcAy7w.png" /></figure><p>Pretty intuitive, right? The table name would correspond to the class name [lowercased and pluralized], the column names would correspond to the attribute names of each Pet instance, and the value in each cell would correspond to the values of each attribute.</p><p>Okay. Now here comes the tricky part. In order to successfully map a Python object to a SQL table, we need to:</p><ol><li>Import a special library that allows our Python code to connect to a SQL database.</li><li>Use these library methods to create SQL queries, populate them with our object data, and query the database.</li></ol><p><em>These special methods will also be used later to retrieve table data from a SQL database and instantiate Python objects from that data.</em></p><p><strong>Step One: Import the library. For the sake of our example, we will be using SQLite3.</strong></p><pre>import sqlite3<br><br>#sqlite3 has a connect() method which accepts a .db file as a destination<br>CONN = sqlite3.connect(&#39;our_database.db&#39;)<br><br>#once we establish our connection and assign it to CONN, we create a CURSOR<br>CURSOR = CONN.cursor() <br><br>#this CURSOR object contains all the methods we will need for our ORM tasks</pre><p><strong>Step Two: Create class methods in our </strong>Pet<strong> class that will allow us to create and drop tables in </strong>our_database.db<strong>, the destination we established by passing as a string argument to our </strong>sqlite3.connect()<strong> method.</strong></p><p><em>Note: If you need to </em><a href="https://pynative.com/python-class-method/"><em>brush up on class methods</em></a><em>, feel free to take a moment to do so. This next step also requires some knowledge about </em><a href="https://www.tutorialspoint.com/sqlite/index.htm"><em>constructing SQL queries</em></a><em>. Take as much time as you need to become comfortable with the syntax.</em></p><pre>class Pet:<br>    def __init__(self, name, species, age, weight_in_kg, favorite_food, id_=None):<br>        self.name = name<br>        self.species = species<br>        self.age = age<br>        self.weight_in_kg = weight_in_kg<br>        self.favorite_food = favorite_food<br>        self.id_ = id_<br>        #id_ is initially set to None, but will automatically be assigned<br>        #by the database once the object is persisted to a table<br>    <br>    @classmethod <br>    def create_table(cls):<br>        #use the triple quotes &quot;&quot;&quot; syntax to construct a SQL query<br>        sql = &quot;&quot;&quot;<br>            CREATE TABLE IF NOT EXISTS pets (<br>            id INTEGER PRIMARY KEY,<br>            name TEXT,<br>            species TEXT,<br>            age INTEGER,<br>            weight_in_kg REAL,<br>            favorite_food TEXT)<br>        &quot;&quot;&quot;<br>        #call CURSOR.execute and pass in our SQL query<br>        CURSOR.execute(sql)<br>        #finally, fire off the database request<br>        CONN.commit()<br><br>    @classmethod<br>    def drop_table(cls):<br>        #construct another SQL query to drop tables<br>        sql = &quot;&quot;&quot;   <br>            DROP TABLE IF EXISTS pets;<br>        &quot;&quot;&quot;<br>        CURSOR.execute(sql)<br>        CONN.commit() </pre><p>Great! Now our our_database.db should have a new, empty table called ‘pets’, with the column names set to name, species, age, weight, and favorite_food. You can call these class methods by running Pet.create_table() and Pet.drop_table().</p><p><strong>Step Three: Define some additional class and instance methods in our </strong>Pet<strong> class. These will be used to instantiate classes and save them to our database.</strong></p><p>Class methods will be called directly by our Pet class. Instance methods will be called by our instances, <strong>not</strong> by the Pet class.</p><pre>class Pet:<br>    #THE __init__ FUNCTION GOES HERE...<br><br>    #THE CREATE AND DROP CLASS METHODS GO HERE...<br><br>    #our save() method will be called on an instance to create a SQL query<br>    def save(self):<br><br>        #construct a SQL query that references the database column names<br>        sql = &quot;&quot;&quot;<br>            INSERT INTO pets (name, species, age, weight_in_kg, favorite_food)<br>            VALUES (?, ?, ?, ?, ?)<br>        &quot;&quot;&quot;<br><br>        #CURSOR.execute() will execute our SQL query with the desired values<br>        CURSOR.execute(sql, (self.name, self.species, self.age, self.weight_in_kg, self.favorite_food))<br>        <br>        #this will fire off the SQL query using CONN.commit()<br>        CONN.commit()<br>        <br>        #we assign our database generated id to our instance<br>        self.id = CURSOR.lastrowid<br>    <br>    #class method create() will instantiate an object and save() it to our database<br>    @classmethod<br>    def create(cls, name, species, age, weight_in_kg, favorite_food):<br><br>        #we then call the cls constructor [Pet] and pass in those values<br>        new_instance = cls(name, species, age, weight_in_kg, favorite_food)<br><br>        #our instance method save() is what actually will query the database<br>        new_instance.save()<br><br>        #we return the created object so it can be used elsewhere in our code<br>        return new_instance</pre><p><strong>Now let’s put this into action!</strong></p><pre>#instantiate some new Pet instances using our create() class method<br>pet_1 = Pet.create(&#39;Pocket&#39;, &#39;dog&#39;, 3, 22.5, &#39;Kibbles &amp; Bits&#39;)<br>pet_2 = Pet.create(&#39;Mittens&#39;, &#39;cat&#39;, 7, 8.0, &#39;Fancy Feast: Salmon Edition&#39;)<br>pet_3 = Pet.create(&#39;Mrs. Birdy III&#39;, &#39;bird&#39;, 22, 0.5, &#39;Froot Loops&#39;)<br><br>#Pet.create() will create the a new instance AND call save() on it</pre><p>Our newly populated SQL database should look exactly like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*Z1QZmDgcSyd9cwkPNcAy7w.png" /></figure><p>Okely dokely. We now have rows in our SQL database. So, how do we convert that data back into objects?</p><p><strong>Step Four: Create additional class methods that fetch table rows using a SQL </strong>SELECT<strong> query and instantiate objects from that row data.</strong></p><pre>class Pet:<br>    #THE __init__ FUNCTION GOES HERE...<br><br>    #THE CREATE AND DROP CLASS METHODS GO HERE...<br><br>    #THE save() AND create() CLASS METHODS GO HERE...<br><br>    #this method will create and populate an object from our table data<br>    @classmethod<br>    def create_from_db(cls, table_row):<br>        <br>        #table_row is a tuple containing the values from each queried row, which we pass to our constructor<br>        new_instance = cls(table_row[1], table_row[2], table_row[3], table_row[4], table_row[5], table_row[6])<br><br>        #table_row[0] is the newly generated &#39;id&#39; attribute we must assign<br>        new_instance.id = table_row[0]<br><br>        #now we can return the newly instantiated object<br>        return new_instance <br><br>    #this method will fetch table data from our SQL database<br>    @classmethod<br>    def get_table_rows(cls):<br>        <br>        #format a SQL query that will fetch table rows<br>        sql = &quot;&quot;&quot;    <br>            SELECT * FROM cats<br>        &quot;&quot;&quot;<br><br>        #fetchall() returns queried rows as a collection of tuples<br>        table_rows = CURSOR.execute(sql).fetchall()<br><br>        #use our create_from_db() method to create objects and return a list comprehension<br>        return [cls.create_from_db(row) for row in table_rows]</pre><p>Here is what our final code looks like, without comments:</p><pre>class Pet:<br>    def __init__(self, name, species, age, weight_in_kg, favorite_food):<br>        self.name = name<br>        self.species = species<br>        self.age = age<br>        self.weight_in_kg = weight_in_kg<br>        self.favorite_food = favorite_food<br><br>    @classmethod <br>    def create_table(cls):<br>        sql = &quot;&quot;&quot;<br>            CREATE TABLE IF NOT EXISTS pets (<br>            id INTEGER PRIMARY KEY,<br>            name TEXT,<br>            species TEXT,<br>            age INTEGER,<br>            weight_in_kg REAL,<br>            favorite_food TEXT)<br>        &quot;&quot;&quot;<br>        CURSOR.execute(sql)<br>        CONN.commit()<br><br>    @classmethod<br>    def drop_table(cls):<br>        sql = &quot;&quot;&quot;   <br>            DROP TABLE IF EXISTS pets;<br>        &quot;&quot;&quot;<br>        CURSOR.execute(sql)<br>        CONN.commit()<br><br>    def save(self):<br>        sql = &quot;&quot;&quot;<br>            INSERT INTO pets (name, species, age, weight_in_kg, favorite_food)<br>            VALUES (?, ?, ?, ?, ?)<br>        &quot;&quot;&quot;<br>        CURSOR.execute(sql, (self.name, self.species, self.age, self.weight_in_kg, self.favorite_food))<br>        CONN.commit()<br>        <br>        self.id = CURSOR.lastrowid<br>    <br>    @classmethod<br>    def create(cls, name, species, age, weight_in_kg, favorite_food):<br>        new_instance = cls(name, species, age, weight_in_kg, favorite_food)<br>        new_instance.save()<br><br>        return new_instance<br><br>    @classmethod<br>    def create_from_db(cls, table_row):<br>        new_instance = cls(table_row[1], table_row[2], table_row[3], table_row[4], table_row[5], table_row[6])<br>        new_instance.id = table_row[0]<br><br>        return new_instance <br><br>    @classmethod<br>    def get_table_rows(cls):<br>        sql = &quot;&quot;&quot;    <br>            SELECT * FROM cats<br>        &quot;&quot;&quot;<br>        table_rows = CURSOR.execute(sql).fetchall()<br><br>        return [cls.create_from_db(row) for row in table_rows]</pre><p>Okay. So now, you know how to use basic ORM methods to create SQL tables, use Python objects to populate SQL queries and save them to the database, and instantiate new Python objects from fetched table rows.</p><p>That was quite a bit of information. Congratulate yourself for getting this far. Maybe go treat yourself to a chicken fried steak. With scrambled eggs and hash browns. All smothered in a copious amount of artery-clogging, cardiac-arrest-inducing sausage gravy. Mmm.</p><p><strong>But wait, there’s more!</strong></p><p>Using this same schema, you can create additional Python instance methods that will UPDATE and DELETE data from our SQL table. And the power of ORMs is not just limited to basic CRUD operations. You can essentially use your Python code to create and execute any kind of SQL query using the CONN and CURSOR objects. You can SELECT table rows by id, name, age, or any other relevant column values that exist. You can implement JOIN and WHERE parameters to make your SQL queries as specific and intricate as you need. The sky is the limit!</p><p><strong>Now get out there and use your programming skills to make the world a better place [or at least keep it from becoming worse].</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd629eca0060" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LocalStorage 101: Persisting Browser Data on the Client]]></title>
            <link>https://medium.com/@joeylee08/localstorage-101-persisting-browser-data-on-the-client-694cea0981b3?source=rss-bd73868e3155------2</link>
            <guid isPermaLink="false">https://medium.com/p/694cea0981b3</guid>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Joseph Lee]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 06:17:44 GMT</pubDate>
            <atom:updated>2024-01-09T18:02:41.348Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_Aeq2y3pCvBd77OID3am1Q.jpeg" /></figure><p>Imagine that you are developing a website or app in which certain elements depend on a specific but changing state or variable. Say you have a table or div that only displays when displayItem is set to true, and although you want it to be hidden by default, once it becomes visible, you want it to remain visible until the user actively chooses to toggle it, regardless of whether the browser refreshes or the user briefly visits another page.</p><p>Or maybe you are programming a game and you want temporary game data [like a user’s score or the current level] to persist even if the user visits another page, closes the browser window, or accidentally his the refresh button, all without making costly network requests and cluttering your database with extraneous information.</p><p>A more relevant example would be concerning ‘like’ buttons on social media. You want a ‘liked’ comment to display some indication of user interaction on that specific individual’s UI, but you do not want to send a PATCH request to the database and inadvertently update the UI of every single user in your network.</p><p>This is where localStorage comes in handy. localStorage is a global browser object that allows data to be stored in key:value pairs that can be set and recalled at will, much like a plain-old Javascript object. The values set in localStorage do not get cleared upon browser refresh, or even if you log out and close the browser window.</p><p>There are six methods that can be used with LocalStorage:</p><p>setItem(key, value)<br>getItem(key)<br>removeItem(key)<br>clear()<br>key(index)<br>length</p><pre>localStorage.setItem(&#39;name&#39;, &#39;Bobby Hill&#39;) //sets &#39;name&#39; to &#39;Bobby Hill&#39;<br><br>localStorage.getItem(&#39;name&#39;) // &#39;Bobby Hill&#39;<br><br>localStorage.removeItem(&#39;name&#39;) //removes the value of the &#39;name&#39; key<br><br>localStorage.clear() //clears all stored data<br><br>localStorage.key(&#39;0&#39;) //returns the key at index 0 <br><br>localStorage.length //returns the number of stored items</pre><p>For the most part, you can use localStorage just like you would a plain-old Javascript object.</p><pre>//set and retrieve values using dot and bracket notation<br>localStorage.greeting = &#39;Hello, frens!&#39;<br>localStorage[name] = &#39;Chunky the Chimken&#39;<br>localStorage[&#39;age&#39;] = &#39;49 dog years&#39;<br><br>//localStorage automatically stores all keys and values as strings.<br>//More on that later.</pre><p>You can loop over items stored in localStorage.</p><pre>//loop over items using a for... in loop<br>for (let prop in localStorage) {<br>  console.log(prop, localStorage[prop])<br>}<br><br>//the above code would display ALL properties and methods, like getItem <br>//and setItem... the proper way would be to do this:<br><br>for (let prop in localStorage) {<br>  if (!localStorage.hasOwnProperty(prop)) continue <br>  console.log(prop, localStorage[prop])<br>}<br><br>//you can even loop over items using a for loop<br>for (let i = 0; i &lt; localStorage.length; i++) {<br>  let prop = localStorage.key(i)<br>  console.log(`The value of ${prop} is ${localStorage[prop]}!`<br>}</pre><p>You can also use Object.keys() to return a collection of stored keys.</p><pre>const myKeys = Object.keys(localStorage)</pre><p>Isn’t this fantastic? localStorage is particularly helpful because:</p><ol><li>Items stored in localStorage do not need to interact with the server. In addition, data stored in localStorage can’t be manipulated by server-side code.</li><li>A localStorage object is locally tied to a specific domain / origin. One domain’s localStorage cannot be accessed by a remote user.</li><li>Because data stored in localStorage is specific to a particular domain / origin, it can be accessed from different browser windows or tabs from the same origin.</li><li>Data will persist even after a page refresh, browser restart, and even an OS reboot.</li><li>When using a library like React.js, you can set and access data from anywhere in your component tree without worrying about information flow and ‘prop drilling’.</li></ol><p>We did mention that there were caveats to using localStorage. The main one is that although localStorage is used to store all data types, <strong>items must be stored as strings</strong>. There is an easy way around this, though.</p><p>You can store and retrieve objects using JSON.stringify() and JSON.parse().</p><pre>const myDoggo = {<br>  name: &#39;Pocket&#39;,<br>  age: 5,<br>  likes: [&#39;walks&#39;, &#39;rawhide bones&#39;, &#39;sleeping in my human bed&#39;],<br>  dislikes: [&#39;cats&#39;, &#39;baths&#39;, &#39;existential dread&#39;]<br>}<br><br>localStorage.setItem(&#39;doggyData&#39;, JSON.stringify(myDoggo))<br><br>const retrieved = JSON.parse(localStorage.getItem(&#39;doggyData&#39;))</pre><p>One last thing. Whenever a localStorage object is updated, there will be a storage event that triggers with a storage event object. Users can assign an event handler to window.onstorage.</p><p>The storage event object has the following properties:</p><p>key<br>oldValue<br>newValue<br>url<br>storageArea</p><pre>window.onstorage = (event) =&gt; {<br>  console.log(event.key) //returns the modified key<br>  console.log(event.oldValue) //returns the old value of a modified key<br>  console.log(event.newValue) //returns the new value of a modified key<br>  console.log(event.url) //the url of the document where the change occurred<br>  console.log(event.storageArea) //the localStorage object itself<br>}<br><br>//e.key will return null if the clear() method is called <br>//e.oldValue will return null if a new key is added<br>//e.newValue will return null if a key was removed</pre><p>Note: The storage event will trigger on every browser window tied to a particular origin, <strong>except the window where the event occurred</strong>. This functionality exists mainly to allow different browser windows with the same origin to share data.</p><p>In addition, there is another browser object called sessionStorage which has the same properties and methods as localStorage. The main difference is that while data stored in sessionStorage does survive page refreshes, sessionStorage data is local to a specific browser tab and does not persist data across tabs. In addition, sessionStorage data is cleared once the current tab is closed.</p><p>I hope this was an informative look into localStorage and how it can be used to persist data locally across page refreshes and browser reboots. I challenge you to find creative and useful ways to implement this tool into your own code. Have a wonderful day.</p><p>***</p><p><em>References and additional documentation: </em><br><a href="https://javascript.info/data-storage">https://javascript.info/data-storage</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=694cea0981b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using .map() .filter() and .reduce() in Javascript]]></title>
            <link>https://medium.com/@joeylee08/using-map-filter-and-reduce-in-javascript-da4b33199a03?source=rss-bd73868e3155------2</link>
            <guid isPermaLink="false">https://medium.com/p/da4b33199a03</guid>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joseph Lee]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 08:36:38 GMT</pubDate>
            <atom:updated>2024-01-29T12:36:52.149Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using .map() .filter() and .reduce() in Javascript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0x4JKaisZXKPcOZ_YqAuKw.jpeg" /></figure><p>Today we will be discussing the built-in array methods .map() .filter() and .reduce(). These methods are classified as higher-order functions, meaning that they are methods that <strong>take another function as a parameter</strong>.</p><p>Because they are array methods, you implement each function by calling it on a created instance of an array and passing in a callback function.</p><p>Usage:</p><pre>let myArray = [1, 2, 3];<br><br>let mapped = myArray.map(callback);<br>let filtered = myArray.filter(callback);<br>let reduced = myArray.reduce(callback);</pre><p>These methods are <strong>iterative</strong> by nature, meaning that they will iterate over each item in the given array and execute the callback on each value.</p><h3>.map()</h3><p>The first of our three methods .map() is called on an array and passed a callback function as a parameter. Our .map() method will iterate over each item in the given array and call the callback function with three arguments passed in: the current array element, the element’s index, and the target array itself. The callback will then perform an operation and populate a new array with the values returned from each iteration of the callback. The .map() function then returns the new array.</p><p>Here is an example using an anonymous arrow function.</p><pre>//targetArr.map((element, [index], [array] =&gt; {})<br><br>let myArray = [1, 2, 3];<br><br>let mapped = myArray.map((item, [index], [array]) =&gt; item + 1); // [2, 3, 4]</pre><p>With each iteration, the .map() method is passing the current array item, that item’s index, and the original target array into the callback function. The item and index variables take on the value of each subsequent array item and it’s index as the .map() method iterates through the array. In most cases, the index and array arguments are not used, but they can be useful if the callback needs to keep track of and use each item’s index as .map() iterates through the array. Once iteration is complete, our .map() method returns a new array with all the values ‘mapped’ into new ones as dictated by the callback function.</p><p><strong>Remember that unless you are using arrow function syntax with an implicit return, your callback needs to </strong>return<strong> a new value to be included in the new array.</strong></p><h3>.filter()</h3><p>Our next method, .filter() iterates over a given array, executes a callback function for each item, and populates a new array only containing the array values which, when passed into the callback, either returned true or a value that is considered by Javascript to be truthy.</p><p>Here is an example using an anonymous arrow function.</p><pre>//targetArr.filter((element, [index], [array] =&gt; {})<br><br>let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];<br><br>let filtered = myArray.filter((element, [index], [array]) =&gt; item % 2 === 0); // [2, 4, 6, 8, 10]</pre><p>Like with our .map() method, .filter() iterates over an array and passes each element into the given callback function, one after the other. It then returns a new array populated only by the values which returned true or a truthy value when passed into the callback.</p><h3>.reduce()</h3><p>Our final method is the trickiest of the three to master, but is equally useful. The .reduce() method iterates over an array and returns a single value. Unlike .map() and .filter() however, .reduce() accepts an additional optional argument: an initial accumulator value. The callback accepts the arguments acc, curr, index, andarray.</p><p>Here is an example using an anonymous arrow function.</p><pre>//targetArr.reduce((acc, curr, [index], [array] =&gt; {}, [accumulator])<br><br>let myArray = [1, 2, 3, 4, 5];<br><br>let reduced = myArray.reduce((acc, curr, [index], [array]) =&gt; acc + curr, 0); // 15</pre><p><strong>The argument </strong>curr<strong> corresponds to the current array element being iterated over.</strong></p><p><strong>If an </strong>accumulator<strong> value is specified, then </strong>acc<strong> will take on that value for the first iteration. If not specified, then </strong>acc<strong> will take on the value of the first array </strong>element<strong> and </strong>curr<strong> will start as the second.</strong></p><p>Here is what is happening. For the first iteration, the .reduce() method grabs the the accumulator value 0 along with the first element of the array, passing them into the callback as the values acc and curr. While any operation can be performed, our particular callback in this example adds acc and curr together and returns a single value 3. For the next iteration, our accumulated return value 3 will then be assigned to variable acc, and variable curr will take on the next [third] value waiting in our array, which in this case is another 3. The callback function will then run again with 3 and 3, returning 6. This accumulated value 6 will then be assigned to variable acc and variable curr will take on the next [fourth] value in the array, which is 4. The callback function runs with 6 and 4 and returns 10. This accumulated value 10 is then assigned to variable acc while variable curr takes on the next [and final] value in the array, which is 5. The callback function finally returns 15 and iteration is complete.</p><p><strong>Please note that the </strong>acc<strong>, </strong>curr<strong>, and </strong>accumulator<strong> values do not necessarily have to be numbers. The </strong>.reduce<strong>() method’s callback can accept any kind of data type as arguments to perform operations on. For example, we can pass in an empty object </strong>{}<strong> as our </strong>accumulator<strong>, then iterate through an array of objects, use the spread operator to ‘accumulate’ each object’s </strong>key<strong> </strong>:<strong> </strong>value<strong> pairs to that empty </strong>{}<strong> object, then finally return that object.</strong></p><p><strong>As long as the callback can accept two values and return a new, accumulated value to be used in the next iteration, the </strong>.reduce()<strong> method will work.</strong></p><p>The .reduce() method is a tricky one, so don’t be discouraged if it takes some time to fully understand.</p><h3>Combining / Chaining</h3><p>These three methods can be combined and chained in unique and creative ways. I personally find these methods versatile, elegant, and just plain fun to use. Here are a few examples of how this can be done. Don’t worry if some of these seem a little complicated, at first. With a little time and practice, I guarantee that you will learn to love these methods.</p><ol><li>Take an array of names and filter out names longer than 5 characters, then map that array of names into an array of objects, each containing a key:value pair of a name and its length.</li></ol><pre>let names = [&#39;Billy&#39;, &#39;Charlotte&#39;, &#39;Randy&#39;, &#39;Bob&#39;, &#39;Rebecca&#39;, &#39;Vladimir&#39;];<br><br>let result = names<br>      .filter(personName =&gt; personName.length &lt;= 5)<br>      .map(shortName =&gt; ({name: shortName, length: shortName.length}));<br><br>/*<br> [ { name: &#39;Billy&#39;, length: 5 },<br>   { name: &#39;Randy&#39;, length: 5 },<br>   { name: &#39;Bob&#39;, length: 3 } ]<br>*/</pre><p>2. Take an array of person objects, filter out individuals with ages greater than 100, map the result into an array of only their ages, and then add all of those ages together.</p><pre>let people = [<br>  {name: &#39;John&#39;, age: 32},<br>  {name: &#39;Robert&#39;, age: 65},<br>  {name: &#39;Jean Claude&#39;, age: 112},<br>  {name: &#39;Brianna&#39;, age: 23},<br>  {name: &#39;Norma&#39;, age: 101},<br>];<br><br>let result = people<br>      .filter(personObj =&gt; personObj.age &lt; 100)<br>      .map(personObj =&gt; personObj.age)<br>      .reduce((a, b) =&gt; a + b); <br><br>// 120</pre><p>Of course, the above example could have been done using only .filter()and reduce().</p><pre>let people = [<br>  {name: &#39;John&#39;, age: 32},<br>  {name: &#39;Robert&#39;, age: 65},<br>  {name: &#39;Jean Claude&#39;, age: 112},<br>  {name: &#39;Brianna&#39;, age: 23},<br>  {name: &#39;Norma&#39;, age: 101},<br>];<br><br>let result = people<br>      .filter(personObj =&gt; personObj.age &lt; 100)<br>      .reduce((a, b) =&gt; a + b.age, 0); <br><br>// 120</pre><p>3. Take an array of animal objects, filter out any non-bird animals, and then map those to an array of just the bird names.</p><pre>let animals = [<br>  {name: &#39;Robin&#39;, isBird: true},<br>  {name: &#39;Tiger&#39;, isBird: false},<br>  {name: &#39;Penguin&#39;, isBird: true},<br>  {name: &#39;Eagle&#39;, isBird: true},<br>  {name: &#39;Giraffe&#39;, isBird: false},<br>];<br><br>let birds = animals<br>      .filter(animalObj =&gt; animalObj.isBird)<br>      .map(birdObj =&gt; birdObj.name);<br><br>// [&#39;Robin&#39;, &#39;Penguin&#39;, &#39;Eagle&#39;]</pre><p>I hope this has been an informative exploration of the array methods .map() .filter() and .reduce(). This article has only begun to scratch the surface of what these powerful methods are capable of. Keep practicing, and I wish you the best of luck on your coding journey!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da4b33199a03" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>