<?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 Isaacwilhite on Medium]]></title>
        <description><![CDATA[Stories by Isaacwilhite on Medium]]></description>
        <link>https://medium.com/@isaacwilhite987?source=rss-61a59c5ecf95------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gBPOfVIw0QIDVwNA</url>
            <title>Stories by Isaacwilhite on Medium</title>
            <link>https://medium.com/@isaacwilhite987?source=rss-61a59c5ecf95------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:12:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@isaacwilhite987/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[Multi-Chat Rooms for Flask SQL Alchemy with Socketio]]></title>
            <link>https://medium.com/@isaacwilhite987/multi-chat-rooms-for-flask-sql-alchemy-with-socketio-d2d3e9f565f0?source=rss-61a59c5ecf95------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2d3e9f565f0</guid>
            <category><![CDATA[websocket-server]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Isaacwilhite]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 05:37:15 GMT</pubDate>
            <atom:updated>2023-12-21T05:37:15.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpOkjnjoOkKoSAwyhTm8Ng.jpeg" /></figure><p>In the realm of modern web development, real-time communication has transformed how we interact online. Instant messaging applications, which enable users to exchange messages without noticeable delays, are at the forefront of this revolution. In this blog, we’ll embark on a journey to create an instant chat application that not only facilitates real-time communication but also offers the flexibility of creating multiple chat rooms — a feature that amplifies its utility in various contexts, from virtual classrooms to online support systems.</p><p>To bring this project to life, we will harness the power of several cutting-edge technologies. On the front end, we’ll utilize React, a popular JavaScript library for building user interfaces with efficiency and elegance. For the backend, we’ll lean on Flask, a lightweight and versatile web framework written in Python, known for its simplicity and scalability. Managing our data will be SQLAlchemy, a powerful ORM (Object-Relational Mapping) tool for Python, which will simplify database operations. And the real magic happens with Socket.IO, a JavaScript library that enables real-time, bidirectional, and event-based communication between web clients and servers.</p><p>Throughout this blog, I’ll guide you through every step of the process — from setting up your development environment to deploying a fully functional chat application. Whether you’re a seasoned developer or just starting, this tutorial is designed to provide a comprehensive understanding of integrating these technologies seamlessly.</p><p>So, let’s dive in and start building an instant chat application that stands out with its capability to create multiple chat rooms, offering an engaging and interactive experience for users.</p><h3>Backend:</h3><p>First you’ll want to build your data base with some models. I have two separate models for users and admins. In the following example users can only message admins and vice versa. Once you have you’re users and their relationships set up, you’ll want to then create a message model and a chat room model. Those will be set up like so:</p><pre>class Message(db.Model, SerializerMixin):<br>    __tablename__ = &#39;messages&#39;<br><br>    id = db.Column(db.Integer, primary_key=True)<br>    content = db.Column(db.Text, nullable=False)<br>    user_id = db.Column(db.Integer, db.ForeignKey(&#39;users.id&#39;), nullable=False)<br>    admin_id = db.Column(db.Integer, db.ForeignKey(&#39;admins.id&#39;), nullable=False)<br>    sender_type = db.Column(db.String)<br>    timestamp = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)<br>    chatroom_id = db.Column(db.Integer, db.ForeignKey(&#39;chatrooms.id&#39;), nullable=False)<br><br>    user = db.relationship(&quot;User&quot;, back_populates=&quot;messages&quot;)<br>    admin = db.relationship(&quot;Admin&quot;, back_populates=&quot;messages&quot;)<br><br>    # serialization rules<br><br>class ChatRoom(db.Model, SerializerMixin):<br>    __tablename__ = &#39;chatrooms&#39;<br><br>    id = db.Column(db.Integer, primary_key=True)<br>    user_id = db.Column(db.Integer, db.ForeignKey(&#39;users.id&#39;), nullable=False)<br>    admin_id = db.Column(db.Integer, db.ForeignKey(&#39;admins.id&#39;), nullable=False)<br><br>    messages = db.relationship(&#39;Message&#39;, cascade=&#39;all, delete-orphan&#39;, back_populates=&#39;chatroom&#39;)<br>    user = db.relationship(&quot;User&quot;, back_populates=&quot;chatroom&quot;)<br>    admin = db.relationship(&quot;Admin&quot;, back_populates=&quot;chatroom&quot;)<br><br>    # serialization rules</pre><p>Here, you’ll create the proper columns necessary for your application and configure the relationships, so that one ChatRoom can have many messages as well as one user and one admin . If you don’t care who sent the message, then the user_id and admin_id in the Message model aren’t required. I wanted to know who sent the message, and incorporated it into my send logic.</p><p>Now it’s time to move onto the backend api endpoints and app setup. First you’ll want to have flask-socketio installed:</p><pre>pip install flask-socketio</pre><p>Then, you’ll need to configure your app. First, let’s instantiate SocketIO with app, add all of the correct imports, and end the file to sense when the script runs, to start the socket server and run the flask instance of app:</p><pre>from flask_socketio import SocketIO<br><br>socketio = SocketIO(app) <br># This is assuming your app is already correctly configured for flask<br><br># Other code will go here<br><br>if __name__ == &#39;__main__&#39;:<br>    socketio.run(app, port=5555, debug=True)</pre><p>How about we finally get into the good stuff? Let’s finally build an endpoint to create a chat room from a logged in user with an admin. I am using jwt_extended for my authorization, so you will see some snippets of that library in my code. Furthermore, we also need an endpoint to get all of the messages for that specific chat room:</p><pre>class CreateChatRoom(Resource):<br>    @jwt_required()<br>    def post(self):<br>        user_id = get_jwt_identity()<br>        admin_id = request.json.get(&#39;admin_id&#39;)<br><br>        chat_room = ChatRoom(user_id=user_id, admin_id=admin_id)<br>        db.session.add(chat_room)<br>        db.session.commit()<br>        return {&quot;chat_room_id&quot;: chat_room.id}, 201<br><br>class MessagesByChatRoomId(Resource):<br>    @jwt_required()<br>    def get(self, chat_room_id):<br>        user_id = get_jwt_identity()<br>        chat_room = ChatRoom.query.filter_by(id=chat_room_id).first()<br><br>        if not chat_room or (chat_room.user_id != user_id and chat_room.admin_id != user_id):<br>            return {&quot;message&quot;: &quot;Chat room not found or access denied&quot;}, 404<br><br>        messages = Message.query.filter_by(chatroom_id=chat_room_id).all()<br><br>        # response<br>        messages_data = [<br>            {<br>                &#39;id&#39;: message.id,<br>                &#39;content&#39;: message.content,<br>                &#39;user_id&#39;: message.user_id,<br>                &#39;admin_id&#39;: message.admin_id,<br>                &#39;sender_type&#39;: message.sender_type<br>            } for message in messages<br>        ]<br>        return messages_data<br><br>api.add_resource(CreateChatRoom, &#39;/chat_room&#39;)<br>api.add_resource(MessagesByChatRoomId, &#39;/chat_room/&lt;int:chat_room_id&gt;/messages&#39;)</pre><p>The code above provides the proper logic for us to be able to create some sort of logic in the front end to create a chat room when a user completes an action like clicks on a button. So when we want to create a POST fetch request to the backend we can use the /chat_room api and the chat room will successfully persist to the data base. Same thing goes for the GET fetch request we will fire when inside of a room to get the messages for the room.</p><p>However, were missing something… We need to add the socketio.on functionality for the server to send/receive messages and know if a user is in a room or not.</p><p>You’ll want to utilize the @socketio.on() decorator provided by flask-socketio to render the messages sent/received and if someone joins the room:</p><pre>from flask_socketio import emit, join_room<br><br>@socketio.on(&#39;send_message&#39;)<br>def handle_send_message(data):<br>    token = request.args.get(&#39;token&#39;)<br>    user_id = decode_jwt(token)<br>    chat_room_id = data[&#39;chat_room_id&#39;]<br>    message_content = data[&#39;message&#39;]<br>    sender_type = data[&#39;sender_type&#39;]<br>    admin_id = data.get(&#39;admin_id&#39;)<br><br>    chat_room = ChatRoom.query.get(chat_room_id)<br>    if chat_room:<br>        new_message = Message(content=message_content, user_id=user_id, sender_type=sender_type, admin_id=admin_id, chatroom_id=chat_room_id, timestamp=datetime.utcnow())<br>        db.session.add(new_message)<br>        db.session.commit()<br><br>        print(new_message)<br>        new_message_id = new_message.id<br>        emit(&#39;new_message&#39;, {&#39;id&#39;: new_message_id, &#39;content&#39;: message_content, &quot;sender_type&quot;: sender_type}, room=data[&#39;chat_room_id&#39;])<br>        print(message_content)<br><br>@socketio.on(&#39;join_room&#39;)<br>def on_join(data):<br>    room = data[&#39;chat_room_id&#39;]<br>    join_room(room)<br>    emit(&#39;room_notification&#39;, {&#39;message&#39;: &#39;A new user has joined.&#39;}, room=room)</pre><p>So first, we created the send_message attribute to be used in the frontend to pass the data. To process the data user_id, chat_room_id, message_content, sender_type, and admin_id are extracted from data . Then, a new Message object is created with the extracted data and the current timestamp. Next, we emit an event new_message back to the clients in the specified chat room. The data sent includes the new message’s ID, content, and sender type. The room argument specifies that the message should only be sent to clients connected to the given chat room.</p><p>Within the join_room decorator we use a flask-socketio attribute called join_room . This will activate the socket server when a user joins the room.</p><h3>Frontend:</h3><p>Before we start coding let’s install the proper npm package:</p><pre>npm install socket.io-client</pre><p>Now in your react component where you wish to create the chat room, you’ll need some sort of logic for the script to know when to create the chat room. However, I will go over the how with you. First, we will need to create the POST fetch request to our backend, then handle it when clicked on a button or however your application is designed:</p><pre>const onCreateChatRoom = async (adminId) =&gt; {<br>      const token = localStorage.getItem(&#39;jwt_token&#39;); // Retrieve the stored token<br>      // again using jwt tokens<br>      try {<br>        const response = await fetch(&#39;http://localhost:5555/chat_room&#39;, {<br>          method: &#39;POST&#39;,<br>          headers: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            &#39;Authorization&#39;: `Bearer ${token}`<br>          },<br>          body: JSON.stringify({ admin_id: adminId }),<br>        });<br>    <br>        if (!response.ok) {<br>          handleError(`HTTP error! Status: ${response.status}`);<br>        }<br>    <br>        const chatRoom = await response.json();<br>        navigate(`/chat/${chatRoom.chat_room_id}`, { state: { adminId: adminId }})<br>      } catch (error) {<br>        handleError(`Failed to create chat room: ${error}`);<br>      }<br>    };<br>return (<br>  &lt;div&gt;<br>    &lt;button onClick={() =&gt; onCreateChatRoom(admin.id)}&gt;Message&lt;/button&gt;<br>  &lt;/div&gt;</pre><p>Now this will create a chat room in the backend when we click on a button corresponding to a specific admin (you can customize that logic for your application) and navigate us to our chat room component where we can then handle the socket server.</p><p>In the chat room component we will need to import io from socket.io-client and useRef, useEffect, useState from react in order to handle our socket listeners:</p><pre>import React, { useState, useEffect, useRef } from &#39;react&#39;;<br>import io from &#39;socket.io-client&#39;;<br><br>const [messages, setMessages] = useState([]);<br>const [messageInput, setMessageInput] = useState(&#39;&#39;)<br>const socketRef = useRef(null)<br><br>useEffect(() =&gt; {<br>    // Initialize the socket inside useEffect<br>    socketRef.current = io(&#39;http://localhost:5555&#39;, {<br>      query: { token: localStorage.getItem(&#39;jwt_token&#39;) },<br>      transports: [&#39;websocket&#39;] // Force WebSocket transport<br>    });<br><br>    // Function to set up socket event listeners<br>    const setupSocketListeners = () =&gt; {<br>      socketRef.current.on(&#39;new_message&#39;, (newMessageData) =&gt; {<br>        const newMessage = newMessageData.message ? { content: newMessageData.message } : newMessageData;<br>        setMessages(prevMessages =&gt; [...prevMessages, newMessage]);<br>    });<br>    }<br><br>    if (chatRoomId) {<br>      // Emit event to join the room<br>      socketRef.current.emit(&#39;join_room&#39;, { chat_room_id: chatRoomId });<br><br>      setupSocketListeners();<br><br>      const fetchMessages = async () =&gt; {<br>        try {<br>          const response = await fetch(`http://localhost:5555/chat_room/${chatRoomId}/messages`, {<br>            method: &#39;GET&#39;,<br>            headers: {<br>              &#39;Content-Type&#39;: &#39;application/json&#39;,<br>              &#39;Authorization&#39;: `Bearer ${localStorage.getItem(&#39;jwt_token&#39;)}`<br>            },<br>          });<br>          if (!response.ok) {<br>            handleError(&#39;Network response was not okay!&#39;);<br>          }<br>          const messages = await response.json();<br>          setMessages(messages);<br>        } catch (error) {<br>          handleError(`Error fetching messages: ${error}`);<br>        }<br>      };<br><br>      fetchMessages();<br>    }<br><br>    return () =&gt; {<br>      socketRef.current.off(&#39;new_message&#39;);<br>      socketRef.current.emit(&#39;leave_room&#39;, { chat_room_id: chatRoomId });<br>      socketRef.current.disconnect();<br>    };<br>  }, [chatRoomId]) </pre><p>Here the useEffect is used to establish a WebSocket connection to the server when the component mounts or when the chatRoomId changes. Then, we initialize a Socket.IO client connection to the server running on localhost at port 5555. Next, we set up our socket event listener for the new_message event. When a new message is received from the server, it updates the messages state with this new message, displaying it in the UI. We then have to emit an event to join a specific chat room based on chatRoomId. We fetch the initial messages when joing the room so that they are properly rendered in the UI. Finally, the return statement in useEffect is a cleanup function that runs when the component unmounts. It turns off the new_message event listener, emits a &#39;leave_room&#39; event, and disconnects the socket.</p><pre>const sendMessage = () =&gt; {<br>    if (messageInput.trim()) {<br>        // Emitting the message event with necessary data<br>        socketRef.current.emit(&#39;send_message&#39;, { <br>        chat_room_id: chatRoomId, <br>        message: messageInput,<br>        admin_id: adminId,<br>        sender_type: chatUser.userType<br>      });<br>      setMessageInput(&#39;&#39;);<br>    }<br>  };<br><br>  const renderMessage = (msg) =&gt; {<br>    const isSentByCurrentUser = msg.sender_type === chatUser.userType<br>    console.log(msg.sender_type, chatUser.userType)<br>    const messageClass = isSentByCurrentUser ? &#39;sent&#39; : &#39;received&#39;;<br><br>    return (<br>        &lt;div key={msg.id} className={`message ${messageClass}`}&gt;<br>            &lt;p&gt;{msg.content}&lt;/p&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>return (<br>    &lt;div&gt;<br>      &lt;div&gt;<br>          {messages.map(renderMessage)}<br>      &lt;/div&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        value={messageInput}<br>        onChange={(e) =&gt; setMessageInput(e.target.value)}<br>      /&gt;<br>      &lt;button onClick={sendMessage}&gt;Send&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>This sendMessage function emits a send_message event to the server when a user sends a message. It includes details like the chat_room_id, the message content, admin_id, and the sender&#39;s type. The renderMessage function renders individual messages. It checks who sent the message to apply different styling for messages sent by the current user versus others. Again, customize the CSS how you’d like. However, if you have followed these steps with your applications spin on it, you should end up with something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*IPvNYKDkxe8nDT2z-weviQ.gif" /></figure><p>As we wrap up our journey in creating a multi-room instant chat application, it’s evident that the integration of Socket.IO, React, Flask, and SQLAlchemy offers a powerful combination for real-time web applications. Through this tutorial, we’ve seen how these technologies work harmoniously to enable seamless, real-time communication across multiple chat rooms, providing an engaging and interactive user experience.</p><p>The process involved setting up a robust backend with Flask and SQLAlchemy, establishing real-time capabilities with Socket.IO, and designing a responsive front-end with React. Each technology played a pivotal role: Flask and SQLAlchemy for handling server-side logic and data persistence, Socket.IO for real-time bidirectional communication, and React for building a dynamic and responsive user interface.</p><p>This project not only demonstrates the technical feasibility of such an application but also opens doors to numerous possibilities for customization and enhancement. Whether it’s adding features like user authentication, message encryption, or even scaling the application for larger audiences, the foundational knowledge you’ve gained here sets the stage for further exploration and innovation.</p><p>Thank you for following along with this tutorial. I hope it has been enlightening and inspiring as you continue to explore the vast landscape of web development and real-time applications. I encourage you to experiment with this project, perhaps by integrating additional features or optimizing its performance.</p><p>Happy coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2d3e9f565f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Docker for Efficient Websocket Communication with Flask]]></title>
            <link>https://medium.com/@isaacwilhite987/leveraging-docker-for-efficient-websocket-communication-with-flask-4cddd6aede48?source=rss-61a59c5ecf95------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cddd6aede48</guid>
            <dc:creator><![CDATA[Isaacwilhite]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 15:53:30 GMT</pubDate>
            <atom:updated>2023-12-01T19:32:56.197Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Turn your Python Script into a &#39;Real&#39; Program with Docker" src="https://cdn-images-1.medium.com/proxy/1*iHCpSEpd1JIrr9ahQ50ASA.png" /><figcaption><a href="https://cdn-images-1.medium.com/max/2560/1*iHCpSEpd1JIrr9ahQ50ASA.png">https://cdn-images-1.medium.com/max/2560/1*iHCpSEpd1JIrr9ahQ50ASA.png</a></figcaption></figure><p>Pre-requisites:</p><ul><li>install Docker Desktop and create an account</li><li>install Docker extension in VS code</li></ul><p>Let’s explore the powerful combination of Docker and Flask, focusing on integrating websockets into a Dockerized Flask application. Websockets offer a two-way communication channel between the client and server, making real-time updates and interactive features a breeze. Let’s dive into the steps of setting up Docker with Flask and incorporating websockets for a seamless and scalable application.</p><p>Step 1: Dockerizing Your Flask App Docker simplifies the deployment process, ensuring consistency across different environments. Start by creating a Dockerfile in your Flask project directory:</p><pre>DockerfileCopy code# Use an official Python runtime as a parent imageFROM python:3.8-# Use an official Python runtime as a parent image<br>FROM python:3.8-slim<br><br># Set the working directory in the container<br>WORKDIR /app<br><br># Copy the current directory contents into the container at /app<br>COPY . /app<br><br># Install any needed packages specified in requirements.txt<br>RUN pip install --no-cache-dir -r requirements.txt<br><br># Make port 5000 available to the world outside this container<br>EXPOSE 5000<br><br># Define environment variable<br>ENV NAME World<br><br># Run app.py when the container launches<br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p>This Dockerfile sets up a basic Python environment, copies your Flask app code into the container, installs dependencies, and exposes port 5000 for communication.</p><p>Step 2: Setting Up Flask with Websockets Now, let’s enhance our Flask app to include websockets. Install the Flask-SocketIO extension:</p><pre>pip install flask-socketio</pre><p>Update your app.py file to include socketio:</p><pre>from flask import Flask, render_template<br>from flask_socketio import SocketIO<br><br>app = Flask(__name__)<br>socketio = SocketIO(app)<br>@app.route(&#39;/&#39;)<br>def index():<br>    return render_template(&#39;index.html&#39;)<br>@socketio.on(&#39;message&#39;)<br>def handle_message(msg):<br>    print(&#39;Received message: &#39; + msg)<br>    socketio.emit(&#39;message&#39;, msg)<br>if __name__ == &#39;__main__&#39;:<br>    socketio.run(app)</pre><p>This modification introduces a simple websocket event handler. When a message is received, it’s printed, and the server broadcasts the message to all connected clients.</p><p>Step 3: Docker Compose for Easy Management To further streamline development, create a docker-compose.yml file:</p><pre>version: &#39;3&#39;<br>services:<br>  web:<br>    build: .<br>    ports:<br>      - &quot;5000:5000&quot;<br>    depends_on:<br>      - backend<br><br>  backend:<br>    build: ./path/to/backend  # Specify the path to your backend code<br>    ports:<br>      - &quot;5001:5001&quot; </pre><p>This file defines a service named ‘web’ based on the current directory’s Dockerfile. It also maps port 5001 on the host to port 5001 on the container.</p><p>web: This is your frontend or client service. It depends on the backend service and exposes port 5000.</p><p>backend: This is your backend server. It exposes port 5001, and the frontend service depends on it.</p><p>Step 4: Run Your Dockerized Flask App Build and run your Dockerized Flask app with the following commands:</p><pre>docker-compose build<br>docker-compose up</pre><p>Visit http://localhost:5000 in your browser, and you should see your Flask app running.</p><p>Step 5: Adding Websockets to Your Frontend Now, update your frontend (HTML and JavaScript) to establish a websocket connection and send/receive messages. Include the Socket.IO client library in your HTML file:</p><pre>&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js&quot;&gt;&lt;/script&gt;</pre><p>Then, in your JavaScript:</p><pre>const socket = io(&#39;http://localhost:5000&#39;);<br><br>socket.on(&#39;message&#39;, (msg) =&gt; {<br>    console.log(&#39;Received message: &#39; + msg);<br>});<br>function sendMessage() {<br>    const message = document.getElementById(&#39;message&#39;).value;<br>    socket.emit(&#39;message&#39;, message);<br>}</pre><p>This JavaScript code establishes a connection to the Flask server and listens for ‘message’ events. The sendMessage function sends a message to the server.</p><p>Congratulations! You’ve successfully Dockerized your Flask app and integrated websockets for real-time communication. This setup is scalable and can handle multiple concurrent connections, making it suitable for a wide range of interactive applications. Cheers to another year of streamlined development with Docker and Flask!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cddd6aede48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Efficiency: A Guide to Concurrency in Python]]></title>
            <link>https://medium.com/@isaacwilhite987/unlocking-efficiency-a-guide-to-concurrency-in-python-ce84ca1b6c13?source=rss-61a59c5ecf95------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce84ca1b6c13</guid>
            <dc:creator><![CDATA[Isaacwilhite]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 04:32:46 GMT</pubDate>
            <atom:updated>2023-11-16T17:12:07.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2J9ARL3-cGCv2ijZ.png" /><figcaption><a href="https://miro.medium.com/v2/resize:fit:1400/1*8m4Y8N6oHd8pflSKRO7yJw.png">https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fmedium.com%2F%40bobbymistery%2Fexploring-concurrency-in-python-asyncio-multithreading-and-multiprocessing-511d974eaed0&amp;psig=AOvVaw301AYu_O6olUdqGLn46PWH&amp;ust=1699935833428000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBIQjRxqFwoTCMie8c2QwIIDFQAAAAAdAAAAABAF</a></figcaption></figure><p>As our applications become more complex and data-intensive, the need to perform multiple tasks simultaneously becomes paramount. Concurrency is the key to achieving this, allowing us to execute tasks concurrently, enhancing performance, and making our applications more responsive. Here I will be discussing exactly this, different ways you can leverage concurrency in your python application.</p><p>Concurrency is the ability of a program to handle multiple tasks concurrently. In Python, this can be achieved through parallelism, where tasks are executed in parallel on multiple processors, or through concurrency, where tasks are interleaved in a single processor.</p><p>Python’s Global Interpreter Lock can limit true parallelism, especially in multi-core systems. However, Python provides several libraries and modules to implement concurrency effectively, including threading, multiprocessing, and asynchronous programming.</p><h3>Threading:</h3><p>In Python, one way to achieve concurrency is through threads. Threads are individual units of a process that can run independently, allowing different parts of the program to execute concurrently. Python’s threading module provides a way to work with threads. It allows you to create and manage threads easily. Threads in Python are lightweight, meaning they are relatively inexpensive to create and don&#39;t consume a significant amount of system resources.</p><p>example:</p><pre>import threading<br>import time<br><br>def print_numbers():<br>    for i in range(5):<br>        time.sleep(1)<br>        print(i)<br><br>def print_letters():<br>    for letter in &#39;ABCDE&#39;:<br>        time.sleep(1)<br>        print(letter)<br><br># Create threads<br>thread_numbers = threading.Thread(target=print_numbers)<br>thread_letters = threading.Thread(target=print_letters)<br><br># Start threads<br>thread_numbers.start()<br>thread_letters.start()<br><br># Wait for both threads to finish<br>thread_numbers.join()<br>thread_letters.join()</pre><p>In this example, thread_numbers and thread_letters are instances of the Thread class from the threading module. These threads execute the print_numbers and print_letters functions concurrently.</p><h3>Multiprocessing:</h3><p>Multiprocessing is a programming paradigm that involves the execution of multiple processes concurrently. In Python, the multiprocessing module provides a framework for creating and managing multiple processes. Unlike threads, processes run in independent memory spaces, allowing them to execute truly concurrently and take full advantage of multi-core systems.</p><p>example:</p><pre>from multiprocessing import Process<br><br>def print_numbers():<br>    for i in range(5):<br>        time.sleep(1)<br>        print(i)<br><br>def print_letters():<br>    for letter in &#39;ABCDE&#39;:<br>        time.sleep(1)<br>        print(letter)<br><br># Create processes<br>process_numbers = Process(target=print_numbers)<br>process_letters = Process(target=print_letters)<br><br># Start processes<br>process_numbers.start()<br>process_letters.start()<br><br># Wait for both processes to finish<br>process_numbers.join()<br>process_letters.join()</pre><p>Here, print_numbers and print_letters run in separate processes, providing true parallelism.</p><h3>Asyncio:</h3><p>Asynchronous programming is a powerful approach to concurrency, particularly useful for I/O-bound tasks. Asynchronous programming is a paradigm that enables non-blocking execution of code, allowing a program to perform other tasks while waiting for certain operations to complete. Python’s asyncio module provides a framework for writing asynchronous code using the async and await keywords.</p><p>example:</p><pre>import asyncio<br><br>async def print_numbers():<br>    for i in range(5):<br>        await asyncio.sleep(1)<br>        print(i)<br><br>async def print_letters():<br>    for letter in &#39;ABCDE&#39;:<br>        await asyncio.sleep(1)<br>        print(letter)<br><br># Create event loop<br>loop = asyncio.get_event_loop()<br><br># Schedule tasks<br>tasks = [print_numbers(), print_letters()]<br><br># Run tasks concurrently<br>loop.run_until_complete(asyncio.gather(*tasks))<br><br># Close the loop<br>loop.close()</pre><p>Here, print_numbers and print_letters are asynchronous tasks running concurrently.</p><h3>Choosing the Right Approach:</h3><p>The choice between threading, multiprocessing, and asynchronous programming depends on the nature of your tasks. Use threading for I/O-bound tasks where threads can wait for external resources. Use multiprocessing for CPU-bound tasks that can be parallelized. Asynchronous programming is suitable for I/O-bound tasks where tasks can yield control to the event loop.</p><p>Concurrency in Python opens up new horizons for building efficient and responsive applications. Whether you choose threading, multiprocessing, or asynchronous programming depends on your specific use case. Understanding the nature of your tasks, considering the GIL, and using appropriate synchronization mechanisms are key factors in successful concurrent programming.</p><p>As you venture into the world of concurrency, experiment with different approaches, and be mindful of potential pitfalls. Python’s rich ecosystem of libraries and the vibrant community make it an excellent choice for diving into the exciting realm of concurrent programming. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce84ca1b6c13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing React Performance: useMemo and useCallback]]></title>
            <link>https://medium.com/@isaacwilhite987/optimizing-react-performance-usememo-and-usecallback-30fce45dec2e?source=rss-61a59c5ecf95------2</link>
            <guid isPermaLink="false">https://medium.com/p/30fce45dec2e</guid>
            <dc:creator><![CDATA[Isaacwilhite]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 20:18:54 GMT</pubDate>
            <atom:updated>2023-10-20T18:44:48.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*A3KBlJy3Iz7nXiRomC8oVw.jpeg" /><figcaption>“<a href="https://www.michalsons.com/wp-content/uploads/2016/05/call-15924_640-e1561728325244.jpg">https://www.michalsons.com/wp-content/uploads/2016/05/call-15924_640-e1561728325244.jpg</a>”</figcaption></figure><p>When thinking of a React application, there are a numerous amount of components, functions, variables, and other things that can quickly create a significant amount of stress on your machine. Stress eventually turns into run time and efficiency delays. Luckily for us, React has a few hooks that allow us to ease some of the computing stress. Two of those easy to use hooks are useMemo and useCallback.</p><p>Before we dive deeper into the functionality of these two hooks there’s a very important term that needs to be addressed. This term is called memoization. Memoization is an optimization technique for accelerating computer programs by caching the results of heavy function calls and returning them when similar inputs are encountered repeatedly. In other words, memoization ensures that a method doesn’t run for the same inputs more than once by keeping a record of the results for the given inputs.</p><h3><strong>useMemo:</strong></h3><p>The useMemo hook memoizes the <strong>result</strong> of a function and re-computes it only if one of the dependencies in the dependency array changes. The purpose of useMemo is to optimize performance by preventing unnecessary calculations.</p><p>Here’s a breakdown of how useMemo works:</p><pre>const memoizedValue = useMemo(() =&gt; computeExpensiveValue(a, b), [a, b]);</pre><p>The first argument to useMemo is a function that performs some computation, and the second argument is an array of dependencies. The result of the function is cached, and it will only be recalculated if one of the dependencies changes.</p><p><strong>Caching the Result:</strong></p><ul><li>When the component renders, useMemo executes the provided function.</li><li>It then compares the current values of the dependencies with the previous values.</li></ul><p><strong>Recomputing Only if Dependencies Change:</strong></p><ul><li>If the values of the dependencies have not changed since the last render, useMemo returns the cached result without re-executing the function.</li><li>If any of the dependencies have changed, the function is re-executed, and the new result is cached.</li></ul><p><strong>Use Case:</strong></p><ul><li>As you can see useMemo is often used to memoize the result of expensive calculations, preventing them from being recalculated on every render.</li><li>It’s useful when dealing with computationally intensive operations, like complex data transformations or rendering logic.</li></ul><p>I’ll provide you with a whole component example so you can get a better feel on how it looks:</p><pre>import { useMemo } from &#39;react&#39;;<br><br>const MemoizedComponent = () =&gt; {<br>  const memoizedValue = useMemo(() =&gt; {<br>    // Expensive computation based on some props or state<br>    return computeExpensiveValue(propA, propB);<br>  }, [propA, propB]);<br><br>  return &lt;div&gt;{memoizedValue}&lt;/div&gt;;<br>};<br><br>export default MemoizedComponent;</pre><p>In this example, computeExpensiveValue is only called when propA or probB change. If neither of these dependencies changes, the previously calculated result is reused.</p><p>In summary, useMemo in React is a powerful tool for optimizing performance by memoizing the results of expensive computations. It helps avoid unnecessary calculations and can lead to more efficient rendering in components.</p><h3>useCallback:</h3><p>Now useCallback and useMemo are related concepts in React, but they serve slightly different purposes. useCallback is specifically designed for memoizing functions. It memoizes a callback function and returns a memoized version of that function. The primary use case is to prevent unnecessary re-creations of callback functions, especially when they are used as dependencies for other hooks (like useEffect).</p><p>So how does useCallback work with memoization? Here’s some examples:</p><p><strong>Preventing Function Re-Creation:</strong></p><pre>const memoizedCallback = useCallback(() =&gt; {<br>  // callback logic<br>}, [/* dependencies */]);</pre><p>Similar to useMemo, the useCallback hook memoizes the provided callback function. If the dependencies specified in the dependency array remain unchanged, the same memoized callback function instance is returned on subsequent renders. If the dependencies change, a new callback function is created.</p><p><strong>Use in Dependency Arrays:</strong></p><pre>useEffect(() =&gt; {<br>  // effect logic<br>  memoizedCallback(); // No need to include memoizedCallback in the dependencies array if it&#39;s memoized with useCallback<br>}, [someDependency, memoizedCallback]);\</pre><p>When using useCallback with other hooks like useEffect, it helps prevent unnecessary re-executions of the effect when the component re-renders. The memoized callback is used in the effect&#39;s dependency array without causing the effect to re-run unnecessarily.</p><p><strong>Optimizing Child Components:</strong></p><pre>const ParentComponent = () =&gt; {<br>  const handleButtonClick = useCallback(() =&gt; {<br>    // callback logic<br>  }, [/* dependencies */]);<br><br>  return &lt;ChildComponent onClick={handleButtonClick} /&gt;;<br>};</pre><p>When passing callback functions as props to child components, useCallback helps optimize performance by preventing unnecessary re-renders of the child components if the parent component re-renders.</p><p>In closing, useCallback is a specific hook for memoizing callback functions, and it&#39;s particularly useful when these functions are used as dependencies in other hooks. It helps optimize performance by preventing unnecessary re-creations of functions, reducing the chance of triggering unnecessary re-renders in child components or re-executions of effects.</p><p>Memoization, embodied in tools like useCallback, useMemo, and other memoization techniques, can serve as a valuable ally in your journey to becoming a proficient React developer. By incorporating these powerful hooks into your toolkit, you gain more control over the render flow and enhance the overall efficiency of your code.</p><p>The combination of thoughtful memoization practices, such as using useCallback, enables you to optimize performance by strategically caching and reusing functions. This, in turn, minimizes unnecessary re-renders and ensures that your application runs smoothly, especially in scenarios where computational resources are critical.</p><p>As you harness the capabilities of these memoization techniques, you empower yourself to create React components that not only meet the requirements of your application but also perform optimally. This optimization becomes increasingly significant as your applications grow in complexity, allowing you to manage state changes, handle callbacks, and orchestrate the rendering process with finesse.</p><p>In essence, embracing memoization, along with tools like useCallback, is a key step toward unlocking your full potential as a React developer. It not only streamlines your code but also positions you to tackle more intricate challenges, providing a solid foundation for the scalable and efficient React applications you aspire to build.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30fce45dec2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Data Types Explained: Unleash Their Power in Your Code (Pt. 1)]]></title>
            <link>https://medium.com/@isaacwilhite987/javascript-data-types-explained-unleash-their-power-in-your-code-pt-1-338e4d1be38c?source=rss-61a59c5ecf95------2</link>
            <guid isPermaLink="false">https://medium.com/p/338e4d1be38c</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Isaacwilhite]]></dc:creator>
            <pubDate>Fri, 29 Sep 2023 15:41:15 GMT</pubDate>
            <atom:updated>2023-09-29T15:41:15.939Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUMdLi0Oa98YqcYnl47slg.jpeg" /><figcaption><a href="https://cdn.pixabay.com/photo/2016/11/19/14/00/code-1839406_1280.jpg">https://cdn.pixabay.com/photo/2016/11/19/14/00/code-1839406_1280.jpg</a></figcaption></figure><p>Have you ever felt lost in the labyrinth of coding? Fear not, for JavaScript offers you eight essential guiding stars on your journey. These guiding stars, known as data types, are your key to unlocking the world of JavaScript with confidence and finesse.</p><p>I’m going to briefly breakdown the first four of eight data types for you, so that you can have a better understanding of what they are, and how they can be used in your code!</p><h3><strong>1. Strings</strong></h3><p>Strings are very, very important. They can hold ANY series of characters in your code. Strings can be any text contained inside single or double quotes.</p><p>For example, let’s say you want to create a variable that has your name stored to it. We might write something like:</p><pre>const myName = &#39;Isaac&#39;</pre><p>So now whenever we wish to put our name back into our code, we can call on the <em>myName</em> variable and <em>Isaac</em> will result.</p><p>You can also add multiple strings together, to form different results:</p><pre>const greeting = &#39;Hi my name is&#39;<br>const myName = &#39;Isaac&#39;<br>let greetingWithName = greeting + &#39; &#39; + myName + &#39;!&#39;<br>// &#39;Hi my name is Isaac!&#39;</pre><p>As you can see this is a very basic way to add strings together, but can come in very handy when building anything in JavaScript.</p><p>Strings are incredibly versatile and play a crucial role in many JavaScript applications, from simple text manipulation to more complex tasks like handling user input, generating dynamic content for web pages, and interacting with APIs. Understanding how to work with strings is a fundamental skill for JavaScript developers.</p><h3>2. Number</h3><p>In JavaScript, the number data type is used to represent numeric values, both integers and floating-point numbers.</p><p>What I mean by that is that, JavaScript numbers can represent both integers (whole numbers) and floating-point numbers (numbers with a decimal point).</p><p>Integers can be equal to any whole number within an infinite range. Examples could be <strong>50, 100, -3000, </strong>or even <strong>0.</strong></p><p>Floating-point numbers can be equal to any number, no matter the decimal or positivity. These are numbers that can be 100% accurate. The numbers <strong>0.0097</strong>, -<strong>31.4</strong>, and <strong>10000.0002</strong> are all great examples of floating-point numbers.</p><p>JavaScript also provides various arithmetic operators for performing numeric operations, including addition (+), subtraction (-), multiplication (*), division (/), and modulus (%) for finding the remainder of a division. These operations are very useful for many algorithms and functions you will surely be creating on your road to becoming a software engineer.</p><p>Example:</p><pre>let x = 10;<br>let y = 3;<br>let sum = x + y;      // 13<br>let difference = x - y; // 7<br>let product = x * y;   // 30<br>let quotient = x / y;  // 3.333...<br>let remainder = x % y; // 1</pre><p>Understanding the number data type is crucial for performing mathematical operations, working with numeric data, and writing code that involves calculations. Developers should ALWAYS be aware of potential pitfalls related to precision when dealing with floating-point numbers.</p><h3>3. BigInt</h3><p>The BigInt data type is used to represent arbitrarily large integers. It was introduced in ECMAScript 2020 (ES11) to address the limitations of the standard Number data type, which is constrained by the JavaScript engine&#39;s maximum safe integer value.</p><p>With the value of the max safe integer constant being 9007199254740991 (9,007,199,254,740,991 or nine quadrillion), BigInt is primarily used for scenarios where you need to work with extremely large integers, such as cryptographic operations, large-scale calculations, or when dealing with numbers that exceed the safe integer limit of Number<em>.</em></p><p>In order to use BigInt<em>,</em> you need to<em> </em>append the ’<em>n</em>’ suffix to an integer literal or by using the BigInt constructor:</p><pre>let bigIntLiteral = 1234567890123456789012345678901234567890n;<br>let bigIntFromConstructor = BigInt(&quot;1234567890123456789012345678901234567890&quot;);</pre><p>In summary, the BigInt data type in JavaScript is a valuable addition for handling arbitrarily large integers, addressing the limitations of the standard Number type. It&#39;s especially useful in scenarios where precision and the handling of large integer values are critical.</p><h3>4. Boolean</h3><p>the Boolean data type represents a binary value, which can have one of two results: ‘true’ or ‘false’. Booleans are fundamental in programming as they are used for making decisions and controlling the flow of code execution through conditional statements and expressions.</p><p>Booleans can be used in three different types of statements: conditional, logical, and function return values.</p><ul><li>Conditional Statements: Booleans determine which branch of code to execute based on whether a condition is true or false. For example:</li></ul><pre>if (userIsLoggedIn === true) {<br>    // Perform actions for a logged-in user<br>} else {<br>    // Perform actions for a guest user<br>}</pre><ul><li>Logical Operations: Booleans can be combined using logical operators like &amp;&amp; (AND), || (OR), and ! (NOT) to create complex conditions.</li></ul><pre>let isWeekend = true;<br>let hasTimeOff = true;<br>if (isWeekend &amp;&amp; hasTimeOff) {<br>    // Enjoy your weekend!<br>}</pre><ul><li>Function Return Values: Functions can return Boolean values to indicate the success or failure of an operation. For example:</li></ul><pre>function isEven(number) {<br>    return number % 2 === 0;<br>}</pre><p>In JavaScript, values that are not explicitly true or false can still be used in Boolean contexts. Values that evaluate to true are considered &quot;truthy,&quot; and values that evaluate to false are considered &quot;falsy.&quot;</p><pre>if (0) {<br>    // This code won&#39;t execute because 0 is falsy<br>}<br><br>if (&quot;Hello&quot;) {<br>    // This code will execute because &quot;Hello&quot; is truthy<br>}</pre><p>Booleans are fundamental for controlling program flow and making decisions in JavaScript. Understanding how to work with Booleans and how they interact with other data types is essential for writing effective and reliable code.</p><p>Understanding JavaScript’s data types is fundamental for any aspiring developer. Mastering these data types is your ticket to becoming a JavaScript pro. In our next post, we’ll delve deeper into the next four equally important data types in JavaScript, expanding your knowledge and empowering you to tackle even more complex programming challenges.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=338e4d1be38c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>