<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: TJ Stifter</title>
    <description>The latest articles on DEV Community by TJ Stifter (@tstifjr).</description>
    <link>https://dev.to/tstifjr</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1108220%2Fe7839700-e2af-4027-96cc-adf5efaf6dbb.png</url>
      <title>DEV Community: TJ Stifter</title>
      <link>https://dev.to/tstifjr</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/tstifjr"/>
    <language>en</language>
    <item>
      <title>Refactoring your code: Looking for Patterns</title>
      <dc:creator>TJ Stifter</dc:creator>
      <pubDate>Wed, 30 Aug 2023 22:54:46 +0000</pubDate>
      <link>https://dev.to/tstifjr/refactoring-your-code-looking-for-patterns-37en</link>
      <guid>https://dev.to/tstifjr/refactoring-your-code-looking-for-patterns-37en</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Writing good clean code is a difficult skill to pick up and no one should feel expected to be great at it starting off.  It's is something you acquire through practice of writing a lot of code.  Refactoring is the process of restructuring code, while not changing its original functionality. The goal of refactoring is to improve internal code by making many small changes without altering the code's external behavior.  It is important to practice refactoring and be diligent in looking for places to improve your code because it both helps you as you write and build your app as well as helps other developers who end up looking at your code.  Let's talk a bit about how to go about refactoring your code.&lt;/p&gt;

&lt;p&gt;Refactoring code to a new developer can seem incredibly overwhelming at first.  It can be a struggle just to find a correct way to get your code to functionally work, and looking for ways to improve its efficiency or readability is just asking for a new developer to break their code.  However, it is important to review your code on a regular basis looking for opportunities to refactor.  First, cleaning up your code helps both you and others who may have to go over your code at a later date.  Second, refactoring your code provides you an opportunity to reduce further complications by compartmentalizing code that can include making reusable pieces.  Let's go over a strategy and some examples to help with practicing refactoring.&lt;/p&gt;

&lt;h2&gt;
  
  
  Looking For Patterns
&lt;/h2&gt;

&lt;p&gt;Identifying patterns in your code is a great place to implement refactoring and can allow you to think about your code in a more compartmental way.  We often repeat use of codes snippets throughout our code, and no one is expected to find every single repeat and devise a way to write some compartmentalized code to replace it.  However, when blocks of code become larger and are all centered around a specific task that is then repeated somewhere else, the pattern becomes clear and finding a way to refactor that code makes everything much easier in the long run.  Below is a simple example using React, without much content, but the concept provides a good example for looking to refactor your code.  When writing out Components in React, we write our JSX to provide the structure for the component that is rendered.  Depending on the complexity of your component, that return line of JSX can get rather large and complex very quickly.  Here is just a simple example where a certain block of tags in JSX is repeated in our components return line.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return(

  &amp;lt;div&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;&amp;lt;/p&amp;gt;
      &amp;lt;p&amp;gt;&amp;lt;/p&amp;gt;
      &amp;lt;span&amp;gt;&amp;lt;/span&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;h2&amp;gt;&amp;lt;/h2&amp;gt;
    &amp;lt;div&amp;gt;
    &amp;lt;p&amp;gt;&amp;lt;/p&amp;gt;
      &amp;lt;p&amp;gt;&amp;lt;/p&amp;gt;
      &amp;lt;span&amp;gt;&amp;lt;/span&amp;gt;
    &amp;lt;/div&amp;gt;
  &amp;lt;/div&amp;gt;

)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can refactor this to improve both the readability of what our main components returns, and to create a new component that contains a piece of repetitive code, which we can implement in our main component.  With our code factored out this way, we could also use this refactored piece in an entirely different component that may wish to utilize the same structure and content.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return(
  &amp;lt;div&amp;gt;
    &amp;lt;MyCard /&amp;gt;
    &amp;lt;h2&amp;gt;&amp;lt;/h2&amp;gt;
    &amp;lt;MyCard /&amp;gt;
  &amp;lt;/div&amp;gt;
)

function MyCard () {
  return (
    &amp;lt;div&amp;gt;
    &amp;lt;p&amp;gt;&amp;lt;/p&amp;gt;
      &amp;lt;p&amp;gt;&amp;lt;/p&amp;gt;
      &amp;lt;span&amp;gt;&amp;lt;/span&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For another exmaple, let's look at another commonly used piece of code wiritten in javascript, a patch request.  Depending on the complexity of your app, you may be sending multiple patch requests to your backend from different components, for different pieces of data, and to different places on your backend.  You may think because the information, or the route, or the object being changed is different you would need to write out the patch request each time in each place you needed it.  By using refactoring and noticing the patterns in the patch requests, we can instead write a single general patch function that can then be called upon multiple times and provided the relevant information as arguments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//patch request to our database
const update = {'username' : newUsername}
fetch (`/users/${user.id}`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(update),
}).then(r =&amp;gt; {
    if (r.ok) {
        r.json().then(user =&amp;gt; {
            setUser({...user, 'username' : user.username})
        })
    }
    else {
        r.json().then(data =&amp;gt; console.log(data))
    }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can start by identifying the unique pieces of information to each patch.  Once we know these &lt;code&gt;item&lt;/code&gt;,&lt;code&gt;update&lt;/code&gt;,and &lt;code&gt;url&lt;/code&gt;, we can assign variables in their place and then to implement the patch, call the function &lt;code&gt;patchItem(item, update, url)&lt;/code&gt; passing in those arguments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const patchItem = (item, update, url) =&amp;gt; {
    fetch(url, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(update),
    }).then(r =&amp;gt; {
        if (r.ok) {
            r.json().then(data =&amp;gt; {
                const keys = Object.keys(data)
                keys.forEach(key =&amp;gt; item[key] = data[key])
            })
        }
        else {
            r.json().then(data =&amp;gt; console.log(data))
        }
    })
    return item
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;An important thing to note here, is that sometimes when refactoring your code, you may have to solve for different cases.  In the example above for a patch request, because I cannot be sure how many attributes were modified; therefore, I need to properly handle the response object by looking through each of the keys and updating each one, rather than only updating the username in the first example.  While not meant to be a perfect example, the above shows how to go about thinking of ways to refactor your code to a higher level of abstraction so that it can be used in multiple places.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Refactoring code is an important skill to have, but it is not one that comes easy and takes a lot of practice and experience from both writing your own code as well as reading others code.  It can be useful try to identify patterns and blocks of code functionality that are either the same or very similar as places to implement refactoring.  Some times it can be easier to look for the unique pieces of code in a code block to understand the key elements that need to be generalized so the code can be used in additional places.  Finally, while refactoring can be intimidating to new coders who may feel overwhelmed or anxious about breaking code they got to function correctly, refactoring provides you a great chance to gain a better understanding of what the code does and why.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Flask: An Intro to using Session in server-client communication</title>
      <dc:creator>TJ Stifter</dc:creator>
      <pubDate>Tue, 08 Aug 2023 16:08:55 +0000</pubDate>
      <link>https://dev.to/tstifjr/flask-an-intro-to-using-session-in-server-client-communication-4nd8</link>
      <guid>https://dev.to/tstifjr/flask-an-intro-to-using-session-in-server-client-communication-4nd8</guid>
      <description>&lt;h3&gt;
  
  
  What is Session?
&lt;/h3&gt;

&lt;p&gt;A session is a means for storing information related to a user, across different requests, as they interact with a web app.  In Flask, we import session from Flask, which is a data object, and this session object works similar to a dictionary, except that it can also keep track of modifications.&lt;/p&gt;

&lt;p&gt;There are two types of sessions commonly used in web development, client-side and sever-side.  Client-side are stored client-side in browser cookies, and server-side sessions are stored server-side; however, a session identifier is typically then created and stored in browser cookies. &lt;/p&gt;

&lt;p&gt;Some benefits to using sessions are speed and ability to scale; however, sessions are limited in their size (cookies typically no more than 4kb),and session data is cryptographically-signed upon being stored as cookies, but they are not encrypted. As a result, sessions should not be used to store sensitive information like passwords or personal information.&lt;/p&gt;

&lt;p&gt;Session is a great way to keep a user logged into your site through refreshes or over time.  Sessions can also be used to keep track of lists or items if you are say shopping and grabbing multiple items from different page loads.&lt;/p&gt;

&lt;h3&gt;
  
  
  Implementation in your Flask App
&lt;/h3&gt;

&lt;p&gt;Implementing session in your flask application is not very difficult; however, there are a number of ways to add additional functionality and control how your server application utilizes session.  For configuration, the first step is to import session from Flask.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import session
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;br&gt;
  Then, you simply need to call on the session object within any functions that needs to access the session data.  Typically, this can be done in the same manner that we would access information in a dictionary.  One of the most common uses of session for flask applications is to check whether current session data exists.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route('/')
def index():
   if 'username' in session:
      username = session['username']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This can be done to help direct what pages a browser has access to based on whether a current session exists.  Another common application of session involves logging in a user or creating a new user.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route('/login', methods = ['GET', 'POST'])
def login():
   if request.method == 'POST':
      session['username'] = request.form['username']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This session is called upon during the POST method and updates or sets a key in the session object to the data received from the POST request.  Another important aspect is being able to delete session data, which typically occurs upon a user logging out.  This can be done a few different ways, but the important points to remember is that the to remove the values for the session keys that need to be deleted.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sesssion['username'] = None #example A
session.pop('username', None) #example B
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lastly, let's touch on updating the session data.  Most of the time, the session object is capable of automatically tracking and accounting for changes to the session.  However, modifications to mutable data structures such as lists are not accounted for automatically, and instead must be accounted for by setting the modified attribute of session &lt;code&gt;session.modified = True&lt;/code&gt; to True.  A common occurence of this would be when storing a bunch of items in a cart say for online shopping.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cart_item = {'pencil': '10', 'eraser': '5', 'marker': '20'}
if 'cart_item' in session:
    session['cart_item']['marker'] = '35'
    session.modified = True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Session and the secret key
&lt;/h3&gt;

&lt;p&gt;An important part of session is that there is some data being provided and stored on the client-side that represents information which we do not want the client to be able to modify.  Therefore, a secret key is used to cryptographically-sign the cookies used for storing the session data.  We do this to ensure if the client tries to manipulate data within the session ID, we want it to be rejected by the server.  In other words, anyone has the permission to view the contents in the cookie but they can’t modify it unless they have the secret key .  Therefore, as best practice one wants to create a random somewhat complicated key, and there are a number of options for generating a secure random key.  One common way is to use your operating system, which has ways has ways to generate pretty random stuff based on a random cryptographic generator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ python -c 'import os; print(os.urandom(16))'
b'\r6CZO\x03\xdd&amp;lt;\x8c\x1f\xf4\xf44\x15\xe5\xd6'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code implemented merely sets the &lt;code&gt;.secret_key&lt;/code&gt; property of app using a method &lt;code&gt;.urandom&lt;/code&gt; that will generate a random byte string the size of the argument.  This randomly generated key can then be stored in your app, should be set during setup or even as part of the configuration as shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.secret_key = b'\r6CZO\x03\xdd&amp;lt;\x8c\x1f\xf4\xf44\x15\xe5\xd6' #Ex.A
app.config['SECRET_KEY']= b'\r6CZO\x03\xdd&amp;lt;\x8c\x1f\xf4\xf44\x15\xe5\xd6' #Ex. B
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;The session object is essentially a dictionary for storing relevant information about a current user from the client-side in order to maintain knowledge about that user over the length of the connection and that includes multiple requests between the client and server. They are important because they allow the application to maintain state across multiple requests, without needing authentication information from the user with each request. This helps to build better applications that are interactive and responsive to user input.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Sql Alchemy : using session.query()</title>
      <dc:creator>TJ Stifter</dc:creator>
      <pubDate>Tue, 25 Jul 2023 16:06:12 +0000</pubDate>
      <link>https://dev.to/tstifjr/sql-alchemy-using-sessionquery-3clp</link>
      <guid>https://dev.to/tstifjr/sql-alchemy-using-sessionquery-3clp</guid>
      <description>&lt;h3&gt;
  
  
  Introduction
&lt;/h3&gt;

&lt;p&gt;SqlAlchemy provides developers with a tool that gives the full power and flexibility of SQL.  One particularly useful tool is &lt;code&gt;session.query&lt;/code&gt;, but first let's quickly refresh on some terminology we use when referencing data in or database.  A &lt;strong&gt;table&lt;/strong&gt; refers to the structure in the database(db) pertaining to a particular class and is the means for storing instances of a class and their attributes. A &lt;strong&gt;record&lt;/strong&gt; refers to one row of the table and is also representative of one instance of the class the table is for. Finally, the table's &lt;strong&gt;column&lt;/strong&gt;'s represent attributes for the class the table is for, wherein each record has its own column entry pertaining to attributes for that class instance.&lt;/p&gt;

&lt;p&gt;In addition, to interact with the database, we create a session object to form a connection between our code and our database.  We use &lt;strong&gt;sessionmaker&lt;/strong&gt; to define our Session class &lt;code&gt;Session = sessionmaker(bind=engine)&lt;/code&gt;, and then create an instance of that Session() by &lt;code&gt;session = Session()&lt;/code&gt;.  This allows us to then reference &lt;code&gt;session&lt;/code&gt; throughout our application to manipulate data in our database.&lt;/p&gt;

&lt;h3&gt;
  
  
  Using session.query
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;session.query&lt;/code&gt; serves as our template for writing sql statements to communicate with our database.  Let's first breakdown a common sqlalchemy query statement that looks like this &lt;code&gt;query=session.query(Band)&lt;/code&gt;.  Here we are storing our query in the &lt;code&gt;query&lt;/code&gt; variable, &lt;code&gt;session.query&lt;/code&gt; acts as our mechanism for querying our database, and, &lt;code&gt;(Band)&lt;/code&gt; defines the class that we want to access.  Together they essentially allow sqlalchemy to construct sql statements for us to send to our db. As can be seen in Ex. 1, when we print the query, we get the actual sql statement that we would use to retrieve the data we want.  Printing the actual query you construct with &lt;code&gt;session.query&lt;/code&gt; can be a quick way to gain some understanding of what is goin on under the hood.&lt;br&gt;&lt;br&gt;
Ex. 1 &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--5qdYmw8e--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/schclz2lnwzz5999zcxo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5qdYmw8e--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/schclz2lnwzz5999zcxo.png" alt="session.query with print(query)" width="765" height="903"&gt;&lt;/a&gt;&lt;br&gt;
Next, to access the actual data from our query we use the &lt;code&gt;.all()&lt;/code&gt; method on our query.  A sidenote, the &lt;code&gt;.all()&lt;/code&gt; method returns a list of Band instances since our query(Band) grabs the whole record (e.g. row of each band).  We can also write our queries, to grab certain attributes (e.g. columns) from our database.  As shown in Ex. 2, we can &lt;code&gt;query(Band.name, Band.website)&lt;/code&gt; to only grab the columns for name and website of our Band records.&lt;br&gt;&lt;br&gt;
Ex. 2 &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--9XKDtCl7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oy34e7j92a8mpohjnl0q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--9XKDtCl7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oy34e7j92a8mpohjnl0q.png" alt="query multiple columns" width="765" height="811"&gt;&lt;/a&gt;&lt;br&gt;
This example also shows that when grabbing multiple different pieces in our query, we get a list of tuples where each tuple references a individual record, and each element of the tuple is info we wanted to grab from that record.  &lt;/p&gt;

&lt;p&gt;Finally, there are some additional methods such as &lt;code&gt;.first()&lt;/code&gt;, &lt;code&gt;.one()&lt;/code&gt;, and &lt;code&gt;.scalar()&lt;/code&gt;.  Each of these is applicable in certain cases where we only want a single record or element.  There are also many other methods that can be called on a query that will not be touched on here, but more info can be found at &lt;a href="https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_orm_using_query.htm"&gt;www.tutorialspoint.com/sqlalchemy/sqlalchemy_orm_using_query&lt;/a&gt; or &lt;a href="https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_orm_returning_list_and_scalars.htm"&gt;www.tutorialspoint.com/sqlalchemy/sqlalchemy_orm_returning_list_and_scalars&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  using filter() to grab certain records
&lt;/h3&gt;

&lt;p&gt;Now that we can use query to grab data from our tables, it would be helpful to have some way to further select portions of our data as needed.  This can be done by applying a .filter() method to our query.  Then in our .filter() we supply our criteria for how to limit the query.  Ex. 3a and 3b provides a common example when we want to find a particular record within our table.&lt;br&gt;
Ex. 3a &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZgrAEK39--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/esysoh0qdsey85p9h2qj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZgrAEK39--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/esysoh0qdsey85p9h2qj.png" alt="filter for single record a" width="596" height="21"&gt;&lt;/a&gt;  Ex. 3b &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ndOo0m-I--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m08ypfx4gjpy2kqaeu0v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ndOo0m-I--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m08ypfx4gjpy2kqaeu0v.png" alt="filter for single record b" width="720" height="73"&gt;&lt;/a&gt;&lt;br&gt;
In Ex. 3a, query is being made as part of an instance method within the Musician class, so we use self.id to select our Musician.  Ex. 3b simply shows how that would like if the Musician we wanted had an id = 5.&lt;br&gt;&lt;br&gt;
Ex. 4 show another use of filter to grab a subset of records.  The query includes both the Band instance, and the is_looking attribute to show that only bands where &lt;code&gt;is_looking == True&lt;/code&gt; were grabbed.&lt;br&gt;&lt;br&gt;
Ex. 4 &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--HlqfCAOf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ih3rcs99z5g39t2610d3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--HlqfCAOf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ih3rcs99z5g39t2610d3.png" alt="query.filter for subset of data" width="770" height="760"&gt;&lt;/a&gt; In ex 5, we show how the filter can take multiple criteria to further narrow our query.  The query grabs auditions whose &lt;code&gt;is_accepted attribute == False&lt;/code&gt; and that have a musician who's id is less than or equal to 10.&lt;br&gt;&lt;br&gt;
Ex. 5 &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ERq7Oaxn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/28u03hca31ngw431t1sd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ERq7Oaxn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/28u03hca31ngw431t1sd.png" alt="filter using multiple criteria" width="756" height="212"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  using func.count() and group_by()
&lt;/h3&gt;

&lt;p&gt;Sql also provides a number of sql functions that can be used as part of our query to further enhance how we can interact with data in our database.  There are a number of different functions e.g. (max, min, mode, sum, count, etc...), and here we will focus on count in combination with the group_by() method as a way to analyze the data in our db.  &lt;/p&gt;

&lt;p&gt;In ex. 6, we are returning a list of tuples, that include both the skill level and number of musicians at that skill level in our db.&lt;br&gt;
Ex. 6&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--jzFJWPs4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/81bx4hkf185s8coh8kqp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--jzFJWPs4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/81bx4hkf185s8coh8kqp.png" alt="query using count" width="760" height="100"&gt;&lt;/a&gt; Let's go through the code and see what's going on here.  First, the &lt;code&gt;query()&lt;/code&gt; establishes the two pieces of info we are goin to have in our list.  The first is straightforward, the skill_level attribute (column); however, the second is much more complex.  &lt;code&gt;func.count&lt;/code&gt; refers to the sql function, and it will simply count what it is given, here the id's of musicians.  The &lt;code&gt;.label('skill_count')&lt;/code&gt; is a descriptive method that allows as to assign a label/variable for the count so that we can then access this data (e.g. maybe sort by the count).  Before we talk about the last part of the code, let's see what happens when we query using &lt;code&gt;session.query(Musician.skill_level, func.count(Musician.id).label('skill_count'))&lt;/code&gt;.  &lt;/p&gt;

&lt;p&gt;In Ex. 7, we see the result, it only gives us one skill level 2, and one count 101 (this is the total # of musicians in our db).&lt;br&gt;
Ex. 7 &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mNeSyTL2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p1mcvm9xdclumshawvrz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mNeSyTL2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p1mcvm9xdclumshawvrz.png" alt="query using count without group by" width="758" height="93"&gt;&lt;/a&gt; This query provides some good context because what happens is it grabs the first musician record's skill_level, which is 2, and then pairs with our count, which counts every individual's musician id.  The problem is we don't want to count all the id's at once, and pair it with the first skill_level we pull from the db.  This is why &lt;code&gt;.group_by()&lt;/code&gt; is included in our query.  This method groups all the records we grab based on &lt;code&gt;Musician.skill_level&lt;/code&gt;, so that in this example we have five groups (1, 2, 3, 4 ,5).  It then works in tandem with our &lt;code&gt;func.count&lt;/code&gt; to then count the &lt;code&gt;Musician.id&lt;/code&gt; for each musician that resides in our different groups.  This provides the ability to analyze the data in our db using the tools of sqlAlchemy.&lt;/p&gt;

&lt;h3&gt;
  
  
  Using Join in query
&lt;/h3&gt;

&lt;p&gt;Another useful method is &lt;code&gt;.join()&lt;/code&gt; because it allows us access data from more than one table, especially when there exists a relationship between these tables.  Ex. 8 shows what happens when we try to query two different tables, we get a SAWarning about a cartesian product between our two tables.  While not provided in the example, the resulting list essentially returns a cross product between our tables, which means it creates an entry for each pair of (Band, Audition).  In other words, if we have 40 Bands, and 55  Auditions, our resulting list will have 2200 entries, Yikes!!. &lt;br&gt;
Ex. 8 &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0A0isYvo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vvbpxty7naj310oqp98s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0A0isYvo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vvbpxty7naj310oqp98s.png" alt="query two tables with warning" width="767" height="322"&gt;&lt;/a&gt; This is why the warning also tells us to apply join conditions.  The combination of tables needs to be given instructions on how to associate the records from each table with one another.  If there is a foreign key between the tables, than join will be able recognize this relationship.  As can be see in Ex. 9, we can return a list of (Band,Audition) pairs where the &lt;code&gt;band.id == Audition.band_id&lt;/code&gt;. Because we query both Band and Audition, we get back 55 entries, each representing a different Audition and the Band for that Audition. &lt;br&gt;
Ex. 9 &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--wE_Hsig1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/52ozdfoe3fpbhqtqk93e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--wE_Hsig1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/52ozdfoe3fpbhqtqk93e.png" alt="query with join, two Classes" width="765" height="535"&gt;&lt;/a&gt; Ex. 10, provides a different list where we grab the only the Bands that have and audition associated with them.  In both these cases, the &lt;code&gt;.join()&lt;/code&gt; method acts similarly to using &lt;code&gt;.filter(Band.id == Audition.band_id)&lt;/code&gt;, as can be seen by comparing Ex. 11 to Ex. 10, but allows us to do so without having to right out the explicit association because our models were designed having a relationship. &lt;br&gt;
Ex. 10 &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--OH8hDlyr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vvp5d4icd7uejqf7ceur.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OH8hDlyr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vvp5d4icd7uejqf7ceur.png" alt="query with join" width="774" height="485"&gt;&lt;/a&gt; Ex. 11 &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0PZP2XRF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b8v9242dymnnen87317w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0PZP2XRF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b8v9242dymnnen87317w.png" alt="query with filter equivalent of join" width="769" height="506"&gt;&lt;/a&gt; However, if there are more than one or no foreign keys, using an explicit from as shown below is a better choice. &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--xOL-qT0K--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/um9y7l17ccsijw0fzv0t.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--xOL-qT0K--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/um9y7l17ccsijw0fzv0t.png" alt="join forms table" width="800" height="153"&gt;&lt;/a&gt; From &lt;a href="https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_orm_working_with_joins.htm"&gt;tutorialspoint.com/sqlalchemy/sqlalchemy_orm_working_with_joins&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;sqlAlchemy provides developers with a set of tools to inquire, manipulate, and even analyze the data in our database.  &lt;code&gt;session.query&lt;/code&gt; provides a quicker means for execution of sql statements, that allows to develop more complex sql statements in a readable manner.  It can be especially beneficial when chaining multiple query methods together along with sql functions in order to provide results of analysis about the data in the database.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Different Conditional Rendering techniques and approaches.</title>
      <dc:creator>TJ Stifter</dc:creator>
      <pubDate>Wed, 05 Jul 2023 18:13:17 +0000</pubDate>
      <link>https://dev.to/tstifjr/different-conditional-rendering-techniques-and-approaches-n2d</link>
      <guid>https://dev.to/tstifjr/different-conditional-rendering-techniques-and-approaches-n2d</guid>
      <description>&lt;h3&gt;
  
  
  Introduction
&lt;/h3&gt;

&lt;p&gt;In React, we create components to render the behavior we want.  Further, like Javascript we can implement conditions to provide logic and control how and when we want to render our components.  These conditionals work the same way as in Javascript, and the power behind React, using state, updating, and re-rendering the UI allows us to improve our applications feel and interactivity.&lt;/p&gt;

&lt;h4&gt;
  
  
  Inline JSX or not
&lt;/h4&gt;

&lt;p&gt;The first thing to be aware of is that the code you write for conditional rendering can written either within the function itself, or can be written inline as part of the JSX return statement.  Using the traditional if...else syntax requires writing the code in the component function itself and not the JSX.  This can be performed both by setting different JSX return for the conditional, or by defining a variable conditionally with the desired html element and then providing that variable to the JSX return.  There are also a number of different inline operations which use conditionals within the JSX return line.&lt;/p&gt;

&lt;h4&gt;
  
  
  conditional statement with &amp;amp;&amp;amp; operator
&lt;/h4&gt;

&lt;p&gt;Conditional Rendering is setup primarily using if statements; however, there are a number of ways to implement this functionality depending on how you want to control the rendering.  One simple implementation is using if with the logical &amp;amp;&amp;amp; operation.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--adcHLrnl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o2hicdosv78ck2mrl6z2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--adcHLrnl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o2hicdosv78ck2mrl6z2.png" alt="example of conditional statement with logical &amp;amp;&amp;amp; operator" width="547" height="271"&gt;&lt;/a&gt;&lt;br&gt;
This conditional setup uses javascript logic where &lt;em&gt;true &amp;amp;&amp;amp; expression&lt;/em&gt; evaluates to the expression and &lt;code&gt;false &amp;amp;&amp;amp; expression&lt;/code&gt; evaluates to false.  Therefore, we can easily render an element only when a certain condition is met (e.g. evaluates to true.&lt;/p&gt;

&lt;h4&gt;
  
  
  if...else with Ternary
&lt;/h4&gt;

&lt;p&gt;Another common approach to conditional rendering utilizes if...else logic and commonly includes using the Ternary operator &lt;code&gt;condition ? true : false&lt;/code&gt;.  The benefit of using the ternary operator is that can be done inline and provided as part of the return in our component.  This makes for quick implementation and readable code.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--xCVqfJqj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2b1bdvdhmlko611ox4tj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--xCVqfJqj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2b1bdvdhmlko611ox4tj.png" alt="Example of ternary operator" width="487" height="213"&gt;&lt;/a&gt;&lt;br&gt;
The ternary operator approach is most useful in instances where you want to render one thing or another based on some conditional evaluation.  Additionally, the more traditional if...else statement could be used; however, this logic cannot be used inline in the return of a component, and therefore requires one to conditionally set html elements to variables within the if and else clauses to achieve the same result.&lt;/p&gt;

&lt;h4&gt;
  
  
  using Null to hide component
&lt;/h4&gt;

&lt;p&gt;There is another approach to conditional rendering that involves telling the component itself to rendering nothing or hide itself based on a certain condition.  This can be done by through the use of props by writing a conditional statement in the component function to evaluate if a value of the prop meets a condition and then tell the component not to render.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--XuDscgPe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/70d85bq741tasmku84qi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--XuDscgPe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/70d85bq741tasmku84qi.png" alt="example of using conditional with Null to hide component" width="313" height="220"&gt;&lt;/a&gt;&lt;br&gt;
Although not used often, this approach can be useful for when you want to hide a component or stop its rendering after its parent has rendered it.  &lt;/p&gt;

&lt;h4&gt;
  
  
  Conclusion
&lt;/h4&gt;

&lt;p&gt;Conditional Rendering is a powerful tool in React for creating engaging applications, and is therefore used in nearly all applications.  Being capable of using a plethora of different conditional logic statements to perform conditional rendering helps us code in better and more readable ways that our tailored to each specific instance.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Building an algorithm to generate random # Array (practice with recursion)</title>
      <dc:creator>TJ Stifter</dc:creator>
      <pubDate>Tue, 27 Jun 2023 18:06:38 +0000</pubDate>
      <link>https://dev.to/tstifjr/building-an-algorithm-to-generate-random-array-practice-with-recursion-3778</link>
      <guid>https://dev.to/tstifjr/building-an-algorithm-to-generate-random-array-practice-with-recursion-3778</guid>
      <description>&lt;h4&gt;
  
  
  Intro
&lt;/h4&gt;

&lt;p&gt;I recently decided to test a proof of concept that included designing a board of n X n squares (example 10X10), where each row as well as each column is assigned a number from 0 to n, and also restricted to only using each number once for each row and column. &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZUhb2ii1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ld82ah2mj9rmu2zmb008.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZUhb2ii1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ld82ah2mj9rmu2zmb008.png" alt="Squares board concept" width="626" height="289"&gt;&lt;/a&gt; My goal was to design a function creating an array of n elements, and built so that each element was assigned a unique number randomly.  This required me to solve the specific problem of how to randomly assign a unique number for an array of n length from (0 to n).  The solution requires a few things to be true:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;every number from 0 to n must be generated.&lt;/li&gt;
&lt;li&gt;no two numbers can be the same.&lt;/li&gt;
&lt;li&gt;the numbers should be randomly assigned within the array.&lt;/li&gt;
&lt;/ol&gt;

&lt;h6&gt;
  
  
  RNG with comparison function for unique Assignment
&lt;/h6&gt;

&lt;p&gt;My first solution was to assign each element in the array sequentially with a random number.  This required the function to make sure that every number was randomly generated and only appeared once in the output array.  The code includes randomly generating a number from 0 to n and pushing it to the output array for n elements.  &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2ONyyBvb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sgc0oof9pjm310g63amq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2ONyyBvb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sgc0oof9pjm310g63amq.png" alt="random assign over array with comparisons" width="555" height="445"&gt;&lt;/a&gt; The solution included a comparison function to be called each time a new random number was going to be assigned to the output array.  This comparison function would then check the new random number against all current numbers in the output array and regenerate the random number if the comparison was true.  This process does use a bit of recursion; however, this was more for flavor since a simple for loop could have worked just as well.&lt;/p&gt;

&lt;p&gt;A second solution would be to do something similar to the above but to instead have each unique number accounted for and then to randomly place them within the array.  I believe the code would follow similar logic where you are assigning numbers in turn from 0 to n to different index positions randomly and comparing to never assign the same index twice.&lt;/p&gt;

&lt;h6&gt;
  
  
  Recursive Approach using unique Pools:
&lt;/h6&gt;

&lt;p&gt;A third solution I explored used recursion as the primary tool.  In this function, I defined two pools of numbers (0 to n), with one for index and one for value, picked one value randomly from each pool, which would assign a random number to a random index for the output array.  Then, in order to fill out the remaining indexes with the remaining numbers, I used recursion to call my function within itself, but modifying the arguments passed in order to reduce the pools number of values by one for each recursive call. &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--p1GNFiS1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gjdapbpq1uuozh7veclb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--p1GNFiS1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gjdapbpq1uuozh7veclb.png" alt="recursive solution based on shrinking pools" width="518" height="384"&gt;&lt;/a&gt;  The function is includes initializing three arrays based on the desired lengths including an index array having n elements from 0 to n, an element array having n elements from 0 to n, and an output array having n elements that are empty.  The first two arrays serve as the pools, from which we randomly draw a number that tells us which value to put in which index of the output array. After, which the elements selected randomly from the pools are then removed as options, and the function is then called recursively passing in the current output array, and the reduced pool arrays.  This sequence of operations is performed until the output array has been fully filled and permits the unique assignment of each number 0 to n to a unique index of 0 to n.&lt;/p&gt;

&lt;p&gt;The results of these two approaches showed how vary different solutions can be used to solve the same problem.  Furthermore, I decided to log the execution time of each approach, and I found the differences to be quite interesting.  I may possibly look into why the results turned out as such in another post. &lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--WZt_o0q7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pkkla593fvgbpobsni38.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--WZt_o0q7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pkkla593fvgbpobsni38.png" alt="Execution Time Testing of solutions" width="219" height="71"&gt;&lt;/a&gt;  &lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
